Spaces:
Sleeping
Sleeping
File size: 6,551 Bytes
f7a075a 4e73e35 eb46107 f7a075a 2dd0857 eb46107 f7a075a 0a004be f7a075a 7c0b56e eb46107 7c0b56e f7a075a abfc73c eb46107 abfc73c 7c0b56e eb46107 f7a075a eb46107 f7a075a eb46107 f7a075a 0a004be f7a075a 7c0b56e f7a075a eb46107 0a004be eb46107 4e73e35 eb46107 4e73e35 0a004be 7c0b56e 0a004be 9c67a05 7c0b56e eb46107 0a004be eb46107 4e73e35 eb46107 897f884 f7a075a eb46107 897f884 f7a075a eb46107 f7a075a eb46107 7c0b56e eb46107 7c0b56e eb46107 7c0b56e eb46107 7c0b56e f7a075a 2dd0857 7c0b56e eb46107 0a004be eb46107 7c0b56e eb46107 f7a075a 7c0b56e f7a075a eb46107 be8f1e2 f7a075a eb46107 0a004be 7c0b56e 0a004be 7c0b56e eb46107 7c0b56e 0a004be eb46107 f7a075a 7c0b56e f7a075a 7c0b56e f7a075a eb46107 be8f1e2 eb46107 7c0b56e eb46107 7c0b56e eb46107 7c0b56e eb46107 7c0b56e eb46107 7c0b56e eb46107 7c0b56e eb46107 f7a075a eb46107 be8f1e2 eb46107 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 | import os
import uuid
import shutil
import traceback
import json
import gradio as gr
from fastapi import FastAPI, File, UploadFile
from fastapi.responses import JSONResponse, FileResponse
from fastapi.middleware.cors import CORSMiddleware
from visualization import process_wireframe
from CodingModule import HTMLGenerator
# -----------------------------------------------------------------------------
# FASTAPI BACKEND
# -----------------------------------------------------------------------------
api = FastAPI()
api.add_middleware(
CORSMiddleware,
allow_origins=["*"],
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"],
)
TEMP_DIR = "./temp"
OUTPUT_DIR = "./output"
os.makedirs(TEMP_DIR, exist_ok=True)
os.makedirs(OUTPUT_DIR, exist_ok=True)
@api.get("/")
def health_check():
return {"status": "ok"}
@api.post("/process-wireframe")
async def process_wireframe_api(image: UploadFile = File(...)):
"""
Firebase / Programmatic endpoint
Returns JSON + HTML content directly.
"""
file_id = str(uuid.uuid4())
temp_path = os.path.join(TEMP_DIR, f"{file_id}_{image.filename}")
try:
with open(temp_path, "wb") as f:
shutil.copyfileobj(image.file, f)
results = process_wireframe(
image_path=temp_path,
save_json=True,
save_html=False,
show_visualization=False
)
if not results or not results.get('normalized_elements'):
return JSONResponse(
status_code=400,
content={"error": "No elements detected"}
)
json_path = results.get("json_path")
# Load JSON content
json_content = None
if json_path and os.path.exists(json_path):
with open(json_path, "r") as f:
json_content = json.load(f)
# Generate styled HTML
html_path = None
try:
html_generator = HTMLGenerator(json_path)
html_filename = f"{file_id}_styled.html"
html_path = os.path.join(OUTPUT_DIR, html_filename)
html_generator.generate_html(html_path)
except:
html_path = results.get("html_path")
html_content = None
if html_path and os.path.exists(html_path):
with open(html_path, "r", encoding="utf-8") as f:
html_content = f.read()
elements = (
results.get("normalized_elements")
or json_content.get("normalized_elements")
or json_content.get("elements")
or []
)
return {
"success": True,
"json_data": json_content,
"html_content": html_content,
"total_elements": len(elements),
"normalized_elements": elements
}
except Exception as e:
traceback.print_exc()
return JSONResponse(status_code=500, content={"error": str(e)})
finally:
if os.path.exists(temp_path):
os.remove(temp_path)
@api.get("/view-html/{filename}")
async def serve_output_file(filename: str):
"""
Serve stored HTML/JSON files.
"""
file_path = os.path.join(OUTPUT_DIR, filename)
if not os.path.exists(file_path):
return JSONResponse(status_code=404, content={"error": "File not found"})
if filename.endswith(".html"):
return FileResponse(file_path, media_type="text/html")
elif filename.endswith(".json"):
return FileResponse(file_path, media_type="application/json")
return FileResponse(file_path)
# -----------------------------------------------------------------------------
# GRADIO UI LOGIC
# -----------------------------------------------------------------------------
def gradio_process(image):
if image is None:
return "Please upload an image", None, None
file_id = str(uuid.uuid4())
temp_path = os.path.join(TEMP_DIR, f"{file_id}.png")
try:
image.save(temp_path)
except Exception as e:
return f"Error saving: {str(e)}", None, None
try:
results = process_wireframe(
image_path=temp_path,
save_json=True,
save_html=False,
show_visualization=False
)
if not results.get("normalized_elements"):
return "No elements detected", None, None
json_path = results["json_path"]
# Generate styled HTML
try:
html_generator = HTMLGenerator(json_path)
html_filename = f"{file_id}_styled.html"
html_path = os.path.join(OUTPUT_DIR, html_filename)
html_generator.generate_html(html_path)
except:
traceback.print_exc()
html_path = results.get("html_path")
num = len(results["normalized_elements"])
status = f"Detected {num} elements\n"
status += f"JSON: {os.path.basename(json_path)}\n"
status += f"HTML: {os.path.basename(html_path)}"
return status, json_path, html_path
except Exception as e:
traceback.print_exc()
return f"Error: {str(e)}", None, None
finally:
if os.path.exists(temp_path):
os.remove(temp_path)
# -----------------------------------------------------------------------------
# GRADIO UI (updated for Gradio 6 compliance)
# -----------------------------------------------------------------------------
with gr.Blocks(title="Wireframe Layout Normalizer") as demo:
gr.Markdown("# Wireframe Layout Normalizer")
gr.Markdown("Upload a wireframe image to extract and normalize UI layout elements.")
with gr.Row():
with gr.Column():
image_input = gr.Image(type="pil", label="Upload Wireframe Image")
process_btn = gr.Button("Process Wireframe")
with gr.Column():
status_output = gr.Textbox(label="Status")
json_output = gr.File(label="JSON Output")
html_output = gr.File(label="HTML Preview")
process_btn.click(
fn=gradio_process,
inputs=image_input,
outputs=[status_output, json_output, html_output],
)
# -----------------------------------------------------------------------------
# FINAL APP MOUNT (fixes reload + /new spam)
# -----------------------------------------------------------------------------
app = gr.mount_gradio_app(
api,
demo,
path="/gradio",
theme=gr.themes.Soft()
)
if __name__ == "__main__":
import uvicorn
uvicorn.run(app, host="0.0.0.0", port=7860)
|