Spaces:
Running
Running
Commit
·
ddb2dc9
1
Parent(s):
1cc14d1
update
Browse files- README.md +16 -7
- app.py +34 -55
- packages.txt +2 -0
- requirements.txt +1 -1
- screencoder/image_box_detection.py +2 -4
- screencoder/main.py +24 -24
- setup.sh +9 -0
README.md
CHANGED
@@ -1,14 +1,23 @@
|
|
1 |
---
|
2 |
title: ScreenCoder
|
3 |
-
emoji:
|
4 |
-
colorFrom:
|
5 |
-
colorTo:
|
6 |
sdk: gradio
|
7 |
-
sdk_version:
|
8 |
app_file: app.py
|
9 |
pinned: false
|
10 |
-
|
11 |
-
short_description: Private Space For ScreenCoder Demo
|
12 |
---
|
13 |
|
14 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
---
|
2 |
title: ScreenCoder
|
3 |
+
emoji: 🖼️
|
4 |
+
colorFrom: blue
|
5 |
+
colorTo: green
|
6 |
sdk: gradio
|
7 |
+
sdk_version: 4.29.0
|
8 |
app_file: app.py
|
9 |
pinned: false
|
10 |
+
post_install: "bash setup.sh"
|
|
|
11 |
---
|
12 |
|
13 |
+
# ScreenCoder: Screenshot to Code
|
14 |
+
|
15 |
+
This is a Hugging Face Space for ScreenCoder, a tool that converts screenshots into HTML code.
|
16 |
+
|
17 |
+
## How it works
|
18 |
+
|
19 |
+
1. **Upload a screenshot**: Provide an image of a user interface.
|
20 |
+
2. **Generate HTML**: The tool analyzes the image and generates the corresponding HTML and CSS code.
|
21 |
+
3. **Preview and Download**: You can preview the generated code live and download the complete package.
|
22 |
+
|
23 |
+
This application uses various computer vision and code generation techniques to achieve the conversion.
|
app.py
CHANGED
@@ -10,8 +10,10 @@ import shutil
|
|
10 |
import html
|
11 |
import base64
|
12 |
from bs4 import BeautifulSoup
|
|
|
13 |
|
14 |
# Predefined examples
|
|
|
15 |
examples_data = [
|
16 |
[
|
17 |
"screencoder/data/input/test1.png",
|
@@ -124,7 +126,9 @@ def process_and_generate(image_np, image_path_from_state, sidebar_prompt, header
|
|
124 |
if not run_id: # Handle potential errors from the generator
|
125 |
return "Generation failed.", f"Error: {html_content}", gr.update(visible=False), None
|
126 |
|
127 |
-
|
|
|
|
|
128 |
soup = BeautifulSoup(html_content, 'html.parser')
|
129 |
|
130 |
print(f"Processing HTML for run_id: {run_id}")
|
@@ -134,64 +138,34 @@ def process_and_generate(image_np, image_path_from_state, sidebar_prompt, header
|
|
134 |
original_src = img['src']
|
135 |
print(f"Processing image: {original_src}")
|
136 |
|
137 |
-
|
138 |
-
|
139 |
-
|
140 |
-
possible_paths = [
|
141 |
-
os.path.join(base_dir, 'screencoder', 'data', 'output', run_id, original_src),
|
142 |
-
os.path.join(base_dir, 'screencoder', 'data', 'output', run_id, 'cropped_images', original_src),
|
143 |
-
os.path.join(base_dir, 'screencoder', 'data', 'output', run_id, f'cropped_images_{run_id}', original_src),
|
144 |
-
os.path.join(base_dir, 'screencoder', 'data', 'output', run_id, os.path.basename(original_src)),
|
145 |
-
os.path.join(base_dir, 'screencoder', 'data', 'output', run_id, original_src.lstrip('./').lstrip('../')),
|
146 |
-
]
|
147 |
-
|
148 |
-
img_path = None
|
149 |
-
for path in possible_paths:
|
150 |
-
if os.path.exists(path):
|
151 |
-
img_path = path
|
152 |
-
print(f"Found image at: {path}")
|
153 |
-
break
|
154 |
-
|
155 |
-
if not img_path:
|
156 |
-
print(f"Could not find image: {original_src}")
|
157 |
-
# Try to convert to data URL as last resort
|
158 |
-
fallback_path = os.path.join(base_dir, 'screencoder', 'data', 'output', run_id, original_src)
|
159 |
-
data_url = image_to_data_url(fallback_path)
|
160 |
-
if data_url:
|
161 |
-
print(f"Converted to data URL: {original_src}")
|
162 |
-
img['src'] = data_url
|
163 |
-
else:
|
164 |
-
img['src'] = original_src
|
165 |
-
continue
|
166 |
|
167 |
-
|
168 |
-
|
169 |
-
print(f"Found image: {img_path}")
|
170 |
# Convert to base64 data URL for better iframe compatibility
|
171 |
-
data_url = image_to_data_url(img_path)
|
172 |
if data_url:
|
173 |
print(f"Converted to data URL: {original_src}")
|
174 |
img['src'] = data_url
|
175 |
else:
|
176 |
-
# Fallback to Gradio file path
|
177 |
-
img['src'] = f'/file={img_path}'
|
178 |
else:
|
179 |
-
print(f"Image not found: {img_path}")
|
180 |
-
|
181 |
-
|
182 |
-
print(f"Converted to data URL: {original_src}")
|
183 |
-
img['src'] = data_url
|
184 |
-
else:
|
185 |
-
img['src'] = original_src
|
186 |
|
187 |
html_content = str(soup)
|
188 |
|
189 |
-
output_dir =
|
190 |
-
packages_dir =
|
191 |
-
|
192 |
-
|
193 |
-
|
194 |
-
|
|
|
195 |
|
196 |
if is_temp_file:
|
197 |
os.unlink(final_image_path)
|
@@ -273,15 +247,20 @@ with gr.Blocks(head=TAILWIND_SCRIPT, theme=gr.themes.Soft(primary_hue="blue", se
|
|
273 |
download_button.click(None, download_button, None, js= \
|
274 |
"(url) => { const link = document.createElement('a'); link.href = url; link.download = ''; document.body.appendChild(link); link.click(); document.body.removeChild(link); }")
|
275 |
|
276 |
-
base_dir =
|
277 |
allowed_paths = [
|
278 |
-
|
279 |
-
|
280 |
-
|
281 |
-
os.path.join(base_dir, 'screencoder', 'data', 'packages')
|
282 |
]
|
283 |
|
284 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
285 |
for path in allowed_paths:
|
286 |
print(f" - {path}")
|
287 |
|
|
|
10 |
import html
|
11 |
import base64
|
12 |
from bs4 import BeautifulSoup
|
13 |
+
from pathlib import Path
|
14 |
|
15 |
# Predefined examples
|
16 |
+
# HF Spaces: Update paths to be relative to the app's root
|
17 |
examples_data = [
|
18 |
[
|
19 |
"screencoder/data/input/test1.png",
|
|
|
126 |
if not run_id: # Handle potential errors from the generator
|
127 |
return "Generation failed.", f"Error: {html_content}", gr.update(visible=False), None
|
128 |
|
129 |
+
# Rewrite image paths to be absolute for Gradio serving
|
130 |
+
# HF Spaces: Use Path objects for robust path handling
|
131 |
+
base_dir = Path(__file__).parent.resolve()
|
132 |
soup = BeautifulSoup(html_content, 'html.parser')
|
133 |
|
134 |
print(f"Processing HTML for run_id: {run_id}")
|
|
|
138 |
original_src = img['src']
|
139 |
print(f"Processing image: {original_src}")
|
140 |
|
141 |
+
# In HF Spaces, paths can be tricky. We'll rely on the fact
|
142 |
+
# that the image replacer creates a predictable structure.
|
143 |
+
img_path = base_dir / 'screencoder' / 'data' / 'output' / run_id / original_src
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
144 |
|
145 |
+
if img_path.exists():
|
146 |
+
print(f"Found image at: {img_path}")
|
|
|
147 |
# Convert to base64 data URL for better iframe compatibility
|
148 |
+
data_url = image_to_data_url(str(img_path))
|
149 |
if data_url:
|
150 |
print(f"Converted to data URL: {original_src}")
|
151 |
img['src'] = data_url
|
152 |
else:
|
153 |
+
# Fallback to Gradio file path (might not work in all Spaces configs)
|
154 |
+
img['src'] = f'/file={str(img_path)}'
|
155 |
else:
|
156 |
+
print(f"Image not found at expected path: {img_path}")
|
157 |
+
# Keep original path as fallback
|
158 |
+
img['src'] = original_src
|
|
|
|
|
|
|
|
|
159 |
|
160 |
html_content = str(soup)
|
161 |
|
162 |
+
output_dir = base_dir / 'screencoder' / 'data' / 'output' / run_id
|
163 |
+
packages_dir = base_dir / 'screencoder' / 'data' / 'packages'
|
164 |
+
packages_dir.mkdir(exist_ok=True)
|
165 |
+
|
166 |
+
shutil.make_archive(str(packages_dir / run_id), 'zip', str(output_dir))
|
167 |
+
package_path = packages_dir / f'{run_id}.zip'
|
168 |
+
package_url = f'/file={str(package_path)}'
|
169 |
|
170 |
if is_temp_file:
|
171 |
os.unlink(final_image_path)
|
|
|
247 |
download_button.click(None, download_button, None, js= \
|
248 |
"(url) => { const link = document.createElement('a'); link.href = url; link.download = ''; document.body.appendChild(link); link.click(); document.body.removeChild(link); }")
|
249 |
|
250 |
+
base_dir = Path(__file__).parent.resolve()
|
251 |
allowed_paths = [
|
252 |
+
str(base_dir),
|
253 |
+
str(base_dir / 'screencoder' / 'data' / 'output'),
|
254 |
+
str(base_dir / 'screencoder' / 'data' / 'packages')
|
|
|
255 |
]
|
256 |
|
257 |
+
# Add all example file paths to allowed_paths to ensure they are accessible
|
258 |
+
for example in examples_data:
|
259 |
+
example_path = Path(example[0]).parent
|
260 |
+
if str(example_path) not in allowed_paths:
|
261 |
+
allowed_paths.append(str(example_path))
|
262 |
+
|
263 |
+
print("Allowed paths for file serving:")
|
264 |
for path in allowed_paths:
|
265 |
print(f" - {path}")
|
266 |
|
packages.txt
ADDED
@@ -0,0 +1,2 @@
|
|
|
|
|
|
|
1 |
+
libvips-dev
|
2 |
+
libpangocairo-1.0-0
|
requirements.txt
CHANGED
@@ -1,4 +1,4 @@
|
|
1 |
-
gradio
|
2 |
Pillow>=10.0.0
|
3 |
beautifulsoup4>=4.12.0
|
4 |
volcengine-python-sdk[ark]>=1.0.0
|
|
|
1 |
+
gradio==4.29.0
|
2 |
Pillow>=10.0.0
|
3 |
beautifulsoup4>=4.12.0
|
4 |
volcengine-python-sdk[ark]>=1.0.0
|
screencoder/image_box_detection.py
CHANGED
@@ -117,10 +117,8 @@ def main():
|
|
117 |
|
118 |
# --- Dynamic Path Construction ---
|
119 |
base_dir = Path(__file__).parent.resolve()
|
120 |
-
|
121 |
-
|
122 |
-
tmp_dir = project_root / 'screencoder' / 'data' / 'tmp' / run_id
|
123 |
-
output_dir = project_root / 'screencoder' / 'data' / 'output' / run_id
|
124 |
|
125 |
html_path = output_dir / f"{run_id}_layout.html"
|
126 |
screenshot_path = tmp_dir / f"{run_id}.png"
|
|
|
117 |
|
118 |
# --- Dynamic Path Construction ---
|
119 |
base_dir = Path(__file__).parent.resolve()
|
120 |
+
tmp_dir = base_dir / 'data' / 'tmp' / run_id
|
121 |
+
output_dir = base_dir / 'data' / 'output' / run_id
|
|
|
|
|
122 |
|
123 |
html_path = output_dir / f"{run_id}_layout.html"
|
124 |
screenshot_path = tmp_dir / f"{run_id}.png"
|
screencoder/main.py
CHANGED
@@ -5,6 +5,7 @@ import json
|
|
5 |
import uuid
|
6 |
import shutil
|
7 |
from PIL import Image
|
|
|
8 |
|
9 |
# This function is now more robust, injecting the prompt into a temporary copy of the generator.
|
10 |
def inject_prompt_to_generator(prompt_text, temp_generator_path):
|
@@ -35,20 +36,21 @@ def inject_prompt_to_generator(prompt_text, temp_generator_path):
|
|
35 |
|
36 |
def run_script_with_run_id(script_name, run_id, instructions=None):
|
37 |
"""Executes a script with a specific run_id and optional instructions."""
|
38 |
-
|
39 |
-
|
40 |
-
|
|
|
41 |
# Handle scripts inside subdirectories like UIED/
|
42 |
-
script_path =
|
43 |
-
|
44 |
-
command = [
|
45 |
-
|
46 |
# Add instructions to the command if provided
|
47 |
-
if instructions and
|
48 |
instructions_json = json.dumps(instructions)
|
49 |
command.extend(["--instructions", instructions_json])
|
50 |
|
51 |
-
print(f"\n--- Running script: {
|
52 |
try:
|
53 |
# Pass the current environment variables to the subprocess
|
54 |
result = subprocess.run(command, check=True, capture_output=True, text=True, env=os.environ)
|
@@ -57,7 +59,7 @@ def run_script_with_run_id(script_name, run_id, instructions=None):
|
|
57 |
print("Error:")
|
58 |
print(result.stderr)
|
59 |
except subprocess.CalledProcessError as e:
|
60 |
-
print(f"Error executing {
|
61 |
print(e.stdout)
|
62 |
print(e.stderr)
|
63 |
raise # Re-raise the exception to stop the workflow if a script fails
|
@@ -73,15 +75,16 @@ def generate_html_for_demo(image_path, instructions):
|
|
73 |
run_id = str(uuid.uuid4())
|
74 |
print(f"--- Starting Screencoder workflow for run_id: {run_id} ---")
|
75 |
|
76 |
-
|
77 |
-
|
78 |
-
|
|
|
79 |
os.makedirs(tmp_dir, exist_ok=True)
|
80 |
os.makedirs(output_dir, exist_ok=True)
|
81 |
|
82 |
try:
|
83 |
# 1. Copy user-uploaded image to the temp input directory
|
84 |
-
new_image_path =
|
85 |
img = Image.open(image_path)
|
86 |
img.save(new_image_path, "PNG")
|
87 |
|
@@ -94,8 +97,8 @@ def generate_html_for_demo(image_path, instructions):
|
|
94 |
run_script_with_run_id("image_replacer.py", run_id)
|
95 |
|
96 |
# 3. Read the final generated HTML
|
97 |
-
final_html_path =
|
98 |
-
if
|
99 |
with open(final_html_path, 'r', encoding='utf-8') as f:
|
100 |
html_content = f.read()
|
101 |
print(f"Successfully generated HTML for run_id: {run_id}")
|
@@ -120,15 +123,12 @@ def generate_html_for_demo(image_path, instructions):
|
|
120 |
def main():
|
121 |
"""Main function to run the entire Screencoder workflow (legacy)."""
|
122 |
print("Starting the Screencoder full workflow (legacy)...")
|
123 |
-
# This main function is now considered legacy and
|
124 |
-
# It will continue to use the hardcoded paths.
|
125 |
run_id = "test1" # Hardcoded for legacy main
|
126 |
-
|
127 |
-
|
128 |
-
|
129 |
-
|
130 |
-
run_script_with_run_id("mapping.py", run_id)
|
131 |
-
run_script_with_run_id("image_replacer.py", run_id)
|
132 |
print("\nScreencoder workflow completed successfully!")
|
133 |
|
134 |
if __name__ == "__main__":
|
|
|
5 |
import uuid
|
6 |
import shutil
|
7 |
from PIL import Image
|
8 |
+
from pathlib import Path
|
9 |
|
10 |
# This function is now more robust, injecting the prompt into a temporary copy of the generator.
|
11 |
def inject_prompt_to_generator(prompt_text, temp_generator_path):
|
|
|
36 |
|
37 |
def run_script_with_run_id(script_name, run_id, instructions=None):
|
38 |
"""Executes a script with a specific run_id and optional instructions."""
|
39 |
+
# HF Spaces: Use absolute paths based on the script's location
|
40 |
+
screencoder_dir = Path(__file__).parent.resolve()
|
41 |
+
script_path = screencoder_dir / script_name
|
42 |
+
if not script_path.exists():
|
43 |
# Handle scripts inside subdirectories like UIED/
|
44 |
+
script_path = screencoder_dir / "UIED" / script_name
|
45 |
+
|
46 |
+
command = [sys.executable, str(script_path), "--run_id", run_id]
|
47 |
+
|
48 |
# Add instructions to the command if provided
|
49 |
+
if instructions and "html_generator.py" in str(script_path):
|
50 |
instructions_json = json.dumps(instructions)
|
51 |
command.extend(["--instructions", instructions_json])
|
52 |
|
53 |
+
print(f"\n--- Running script: {script_path.name} ---")
|
54 |
try:
|
55 |
# Pass the current environment variables to the subprocess
|
56 |
result = subprocess.run(command, check=True, capture_output=True, text=True, env=os.environ)
|
|
|
59 |
print("Error:")
|
60 |
print(result.stderr)
|
61 |
except subprocess.CalledProcessError as e:
|
62 |
+
print(f"Error executing {script_path.name}:")
|
63 |
print(e.stdout)
|
64 |
print(e.stderr)
|
65 |
raise # Re-raise the exception to stop the workflow if a script fails
|
|
|
75 |
run_id = str(uuid.uuid4())
|
76 |
print(f"--- Starting Screencoder workflow for run_id: {run_id} ---")
|
77 |
|
78 |
+
# HF Spaces: Use absolute paths and pathlib for robustness
|
79 |
+
base_dir = Path(__file__).parent.resolve()
|
80 |
+
tmp_dir = base_dir / 'data' / 'tmp' / run_id
|
81 |
+
output_dir = base_dir / 'data' / 'output' / run_id
|
82 |
os.makedirs(tmp_dir, exist_ok=True)
|
83 |
os.makedirs(output_dir, exist_ok=True)
|
84 |
|
85 |
try:
|
86 |
# 1. Copy user-uploaded image to the temp input directory
|
87 |
+
new_image_path = tmp_dir / f"{run_id}.png"
|
88 |
img = Image.open(image_path)
|
89 |
img.save(new_image_path, "PNG")
|
90 |
|
|
|
97 |
run_script_with_run_id("image_replacer.py", run_id)
|
98 |
|
99 |
# 3. Read the final generated HTML
|
100 |
+
final_html_path = output_dir / f"{run_id}_layout_final.html"
|
101 |
+
if final_html_path.exists():
|
102 |
with open(final_html_path, 'r', encoding='utf-8') as f:
|
103 |
html_content = f.read()
|
104 |
print(f"Successfully generated HTML for run_id: {run_id}")
|
|
|
123 |
def main():
|
124 |
"""Main function to run the entire Screencoder workflow (legacy)."""
|
125 |
print("Starting the Screencoder full workflow (legacy)...")
|
126 |
+
# This main function is now considered legacy and should not be used in HF Spaces.
|
|
|
127 |
run_id = "test1" # Hardcoded for legacy main
|
128 |
+
# Use a dummy image path for legacy run
|
129 |
+
dummy_image_path = Path(__file__).parent.resolve() / "data" / "input" / "test1.png"
|
130 |
+
instructions = {"main content": "Generate the HTML for this screenshot."}
|
131 |
+
generate_html_for_demo(str(dummy_image_path), instructions)
|
|
|
|
|
132 |
print("\nScreencoder workflow completed successfully!")
|
133 |
|
134 |
if __name__ == "__main__":
|
setup.sh
ADDED
@@ -0,0 +1,9 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
#!/bin/bash
|
2 |
+
|
3 |
+
# This script is executed after the 'pip install -r requirements.txt' and before the execution of the app.
|
4 |
+
|
5 |
+
# 1. Install playwright browsers
|
6 |
+
echo "Installing playwright browsers..."
|
7 |
+
python -m playwright install --with-deps
|
8 |
+
|
9 |
+
echo "Setup complete."
|