Spaces:
Paused
Paused
Commit ·
ddb2dc9
1
Parent(s): 1cc14d1
update
Browse filesFiles changed (7)
- README.md+16-7
- app.py+34-55
- packages.txtAdded+2
- requirements.txt+1-1
- screencoder/image_box_detection.py+2-4
- screencoder/main.py+24-24
- setup.shAdded+9
1234567891011121314---title: ScreenCoderemoji: 🏃colorFrom: purplecolorTo: pinksdk: gradiosdk_version: 5.38.0app_file: app.pypinned: falselicense: mitshort_description: Private Space For ScreenCoder Demo---Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference1234567891011121314151617181920212223---title: ScreenCoderemoji: 🖼️colorFrom: bluecolorTo: greensdk: gradiosdk_version: 4.29.0app_file: app.pypinned: falsepost_install: "bash setup.sh"---# ScreenCoder: Screenshot to CodeThis is a Hugging Face Space for ScreenCoder, a tool that converts screenshots into HTML code.## How it works1. **Upload a screenshot**: Provide an image of a user interface.2. **Generate HTML**: The tool analyzes the image and generates the corresponding HTML and CSS code.3. **Preview and Download**: You can preview the generated code live and download the complete package.This application uses various computer vision and code generation techniques to achieve the conversion.
9 unmodified lines1011121314151617106 unmodified lines1241251261271281291303 unmodified lines13413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619775 unmodified lines2732742752762772782792802812822832842852862879 unmodified linesimport htmlimport base64from bs4 import BeautifulSoup# Predefined examplesexamples_data = [["screencoder/data/input/test1.png",106 unmodified linesif not run_id: # Handle potential errors from the generatorreturn "Generation failed.", f"Error: {html_content}", gr.update(visible=False), Nonebase_dir = os.path.dirname(os.path.abspath(__file__))soup = BeautifulSoup(html_content, 'html.parser')print(f"Processing HTML for run_id: {run_id}")3 unmodified linesoriginal_src = img['src']print(f"Processing image: {original_src}")if original_src.startswith('/'):img_path = os.path.join(base_dir, original_src.lstrip('/'))else:possible_paths = [os.path.join(base_dir, 'screencoder', 'data', 'output', run_id, original_src),os.path.join(base_dir, 'screencoder', 'data', 'output', run_id, 'cropped_images', original_src),os.path.join(base_dir, 'screencoder', 'data', 'output', run_id, f'cropped_images_{run_id}', original_src),os.path.join(base_dir, 'screencoder', 'data', 'output', run_id, os.path.basename(original_src)),os.path.join(base_dir, 'screencoder', 'data', 'output', run_id, original_src.lstrip('./').lstrip('../')),]img_path = Nonefor path in possible_paths:if os.path.exists(path):img_path = pathprint(f"Found image at: {path}")breakif not img_path:print(f"Could not find image: {original_src}")# Try to convert to data URL as last resortfallback_path = os.path.join(base_dir, 'screencoder', 'data', 'output', run_id, original_src)data_url = image_to_data_url(fallback_path)if data_url:print(f"Converted to data URL: {original_src}")img['src'] = data_urlelse:img['src'] = original_srccontinue# Check if the image file actually existsif img_path and os.path.exists(img_path):print(f"Found image: {img_path}")# Convert to base64 data URL for better iframe compatibilitydata_url = image_to_data_url(img_path)if data_url:print(f"Converted to data URL: {original_src}")img['src'] = data_urlelse:# Fallback to Gradio file pathimg['src'] = f'/file={img_path}'else:print(f"Image not found: {img_path}")data_url = image_to_data_url(img_path)if data_url:print(f"Converted to data URL: {original_src}")img['src'] = data_urlelse:img['src'] = original_srchtml_content = str(soup)output_dir = os.path.join(base_dir, 'screencoder', 'data', 'output', run_id)packages_dir = os.path.join(base_dir, 'screencoder', 'data', 'packages')os.makedirs(packages_dir, exist_ok=True)shutil.make_archive(os.path.join(packages_dir, run_id), 'zip', output_dir)package_path = os.path.join(packages_dir, f'{run_id}.zip')package_url = f'/file={package_path}'if is_temp_file:os.unlink(final_image_path)75 unmodified linesdownload_button.click(None, download_button, None, js= \"(url) => { const link = document.createElement('a'); link.href = url; link.download = ''; document.body.appendChild(link); link.click(); document.body.removeChild(link); }")base_dir = os.path.dirname(os.path.abspath(__file__))allowed_paths = [os.path.join(base_dir),os.path.join(base_dir, 'screencoder', 'data'),os.path.join(base_dir, 'screencoder', 'data', 'output'),os.path.join(base_dir, 'screencoder', 'data', 'packages')]print(f"Allowed paths for file serving:")for path in allowed_paths:print(f" - {path}")9 unmodified lines10111213141516171819106 unmodified lines1261271281291301311321331343 unmodified lines13813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017175 unmodified lines2472482492502512522532542552562572582592602612622632642652669 unmodified linesimport htmlimport base64from bs4 import BeautifulSoupfrom pathlib import Path# Predefined examples# HF Spaces: Update paths to be relative to the app's rootexamples_data = [["screencoder/data/input/test1.png",106 unmodified linesif not run_id: # Handle potential errors from the generatorreturn "Generation failed.", f"Error: {html_content}", gr.update(visible=False), None# Rewrite image paths to be absolute for Gradio serving# HF Spaces: Use Path objects for robust path handlingbase_dir = Path(__file__).parent.resolve()soup = BeautifulSoup(html_content, 'html.parser')print(f"Processing HTML for run_id: {run_id}")3 unmodified linesoriginal_src = img['src']print(f"Processing image: {original_src}")# In HF Spaces, paths can be tricky. We'll rely on the fact# that the image replacer creates a predictable structure.img_path = base_dir / 'screencoder' / 'data' / 'output' / run_id / original_srcif img_path.exists():print(f"Found image at: {img_path}")# Convert to base64 data URL for better iframe compatibilitydata_url = image_to_data_url(str(img_path))if data_url:print(f"Converted to data URL: {original_src}")img['src'] = data_urlelse:# Fallback to Gradio file path (might not work in all Spaces configs)img['src'] = f'/file={str(img_path)}'else:print(f"Image not found at expected path: {img_path}")# Keep original path as fallbackimg['src'] = original_srchtml_content = str(soup)output_dir = base_dir / 'screencoder' / 'data' / 'output' / run_idpackages_dir = base_dir / 'screencoder' / 'data' / 'packages'packages_dir.mkdir(exist_ok=True)shutil.make_archive(str(packages_dir / run_id), 'zip', str(output_dir))package_path = packages_dir / f'{run_id}.zip'package_url = f'/file={str(package_path)}'if is_temp_file:os.unlink(final_image_path)75 unmodified linesdownload_button.click(None, download_button, None, js= \"(url) => { const link = document.createElement('a'); link.href = url; link.download = ''; document.body.appendChild(link); link.click(); document.body.removeChild(link); }")base_dir = Path(__file__).parent.resolve()allowed_paths = [str(base_dir),str(base_dir / 'screencoder' / 'data' / 'output'),str(base_dir / 'screencoder' / 'data' / 'packages')]# Add all example file paths to allowed_paths to ensure they are accessiblefor example in examples_data:example_path = Path(example[0]).parentif str(example_path) not in allowed_paths:allowed_paths.append(str(example_path))print("Allowed paths for file serving:")for path in allowed_paths:print(f" - {path}")
12libvips-devlibpangocairo-1.0-0 1234gradioPillow>=10.0.0beautifulsoup4>=4.12.0volcengine-python-sdk[ark]>=1.0.01234gradio==4.29.0Pillow>=10.0.0beautifulsoup4>=4.12.0volcengine-python-sdk[ark]>=1.0.0
116 unmodified lines117118119120121122123124125126116 unmodified lines# --- Dynamic Path Construction ---base_dir = Path(__file__).parent.resolve()# Go up one level to the project root to find the data directoryproject_root = base_dir.parenttmp_dir = project_root / 'screencoder' / 'data' / 'tmp' / run_idoutput_dir = project_root / 'screencoder' / 'data' / 'output' / run_idhtml_path = output_dir / f"{run_id}_layout.html"screenshot_path = tmp_dir / f"{run_id}.png"116 unmodified lines117118119120121122123124116 unmodified lines# --- Dynamic Path Construction ---base_dir = Path(__file__).parent.resolve()tmp_dir = base_dir / 'data' / 'tmp' / run_idoutput_dir = base_dir / 'data' / 'output' / run_idhtml_path = output_dir / f"{run_id}_layout.html"screenshot_path = tmp_dir / f"{run_id}.png"
4 unmodified lines567891024 unmodified lines35363738394041424344454647484950515253542 unmodified lines575859606162639 unmodified lines7374757677787980818283848586876 unmodified lines94959697989910010118 unmodified lines1201211221231241251261271281291301311321331344 unmodified linesimport uuidimport shutilfrom PIL import Image# This function is now more robust, injecting the prompt into a temporary copy of the generator.def inject_prompt_to_generator(prompt_text, temp_generator_path):24 unmodified linesdef run_script_with_run_id(script_name, run_id, instructions=None):"""Executes a script with a specific run_id and optional instructions."""screencoder_dir = os.path.dirname(os.path.abspath(__file__))script_path = os.path.join(screencoder_dir, script_name)if not os.path.exists(script_path):# Handle scripts inside subdirectories like UIED/script_path = os.path.join(screencoder_dir, "UIED", script_name)command = ["python", script_path, "--run_id", run_id]# Add instructions to the command if providedif instructions and script_name == "html_generator.py":instructions_json = json.dumps(instructions)command.extend(["--instructions", instructions_json])print(f"\n--- Running script: {script_name} ---")try:# Pass the current environment variables to the subprocessresult = subprocess.run(command, check=True, capture_output=True, text=True, env=os.environ)2 unmodified linesprint("Error:")print(result.stderr)except subprocess.CalledProcessError as e:print(f"Error executing {script_name}:")print(e.stdout)print(e.stderr)raise # Re-raise the exception to stop the workflow if a script fails9 unmodified linesrun_id = str(uuid.uuid4())print(f"--- Starting Screencoder workflow for run_id: {run_id} ---")base_dir = os.path.dirname(os.path.abspath(__file__))tmp_dir = os.path.join(base_dir, 'data', 'tmp', run_id)output_dir = os.path.join(base_dir, 'data', 'output', run_id)os.makedirs(tmp_dir, exist_ok=True)os.makedirs(output_dir, exist_ok=True)try:# 1. Copy user-uploaded image to the temp input directorynew_image_path = os.path.join(tmp_dir, f"{run_id}.png")img = Image.open(image_path)img.save(new_image_path, "PNG")6 unmodified linesrun_script_with_run_id("image_replacer.py", run_id)# 3. Read the final generated HTMLfinal_html_path = os.path.join(output_dir, f"{run_id}_layout_final.html")if os.path.exists(final_html_path):with open(final_html_path, 'r', encoding='utf-8') as f:html_content = f.read()print(f"Successfully generated HTML for run_id: {run_id}")18 unmodified linesdef main():"""Main function to run the entire Screencoder workflow (legacy)."""print("Starting the Screencoder full workflow (legacy)...")# This main function is now considered legacy and does not use dynamic run_ids.# It will continue to use the hardcoded paths.run_id = "test1" # Hardcoded for legacy mainrun_script_with_run_id("UIED/run_single.py", run_id)run_script_with_run_id("block_parsor.py", run_id)run_script_with_run_id("html_generator.py", run_id)run_script_with_run_id("image_box_detection.py", run_id)run_script_with_run_id("mapping.py", run_id)run_script_with_run_id("image_replacer.py", run_id)print("\nScreencoder workflow completed successfully!")if __name__ == "__main__":4 unmodified lines56789101124 unmodified lines3637383940414243444546474849505152535455562 unmodified lines596061626364659 unmodified lines757677787980818283848586878889906 unmodified lines97989910010110210310418 unmodified lines1231241251261271281291301311321331344 unmodified linesimport uuidimport shutilfrom PIL import Imagefrom pathlib import Path# This function is now more robust, injecting the prompt into a temporary copy of the generator.def inject_prompt_to_generator(prompt_text, temp_generator_path):24 unmodified linesdef run_script_with_run_id(script_name, run_id, instructions=None):"""Executes a script with a specific run_id and optional instructions."""# HF Spaces: Use absolute paths based on the script's locationscreencoder_dir = Path(__file__).parent.resolve()script_path = screencoder_dir / script_nameif not script_path.exists():# Handle scripts inside subdirectories like UIED/script_path = screencoder_dir / "UIED" / script_namecommand = [sys.executable, str(script_path), "--run_id", run_id]# Add instructions to the command if providedif instructions and "html_generator.py" in str(script_path):instructions_json = json.dumps(instructions)command.extend(["--instructions", instructions_json])print(f"\n--- Running script: {script_path.name} ---")try:# Pass the current environment variables to the subprocessresult = subprocess.run(command, check=True, capture_output=True, text=True, env=os.environ)2 unmodified linesprint("Error:")print(result.stderr)except subprocess.CalledProcessError as e:print(f"Error executing {script_path.name}:")print(e.stdout)print(e.stderr)raise # Re-raise the exception to stop the workflow if a script fails9 unmodified linesrun_id = str(uuid.uuid4())print(f"--- Starting Screencoder workflow for run_id: {run_id} ---")# HF Spaces: Use absolute paths and pathlib for robustnessbase_dir = Path(__file__).parent.resolve()tmp_dir = base_dir / 'data' / 'tmp' / run_idoutput_dir = base_dir / 'data' / 'output' / run_idos.makedirs(tmp_dir, exist_ok=True)os.makedirs(output_dir, exist_ok=True)try:# 1. Copy user-uploaded image to the temp input directorynew_image_path = tmp_dir / f"{run_id}.png"img = Image.open(image_path)img.save(new_image_path, "PNG")6 unmodified linesrun_script_with_run_id("image_replacer.py", run_id)# 3. Read the final generated HTMLfinal_html_path = output_dir / f"{run_id}_layout_final.html"if final_html_path.exists():with open(final_html_path, 'r', encoding='utf-8') as f:html_content = f.read()print(f"Successfully generated HTML for run_id: {run_id}")18 unmodified linesdef main():"""Main function to run the entire Screencoder workflow (legacy)."""print("Starting the Screencoder full workflow (legacy)...")# This main function is now considered legacy and should not be used in HF Spaces.run_id = "test1" # Hardcoded for legacy main# Use a dummy image path for legacy rundummy_image_path = Path(__file__).parent.resolve() / "data" / "input" / "test1.png"instructions = {"main content": "Generate the HTML for this screenshot."}generate_html_for_demo(str(dummy_image_path), instructions)print("\nScreencoder workflow completed successfully!")if __name__ == "__main__":
123456789#!/bin/bash
# This script is executed after the 'pip install -r requirements.txt' and before the execution of the app.
# 1. Install playwright browsersecho "Installing playwright browsers..."python -m playwright install --with-deps
echo "Setup complete." README.md+16-7
app.py+34-55
packages.txtAdded+2
requirements.txt+1-1
screencoder/image_box_detection.py+2-4
screencoder/main.py+24-24
setup.shAdded+9