Spaces:
Runtime error
Runtime error
File size: 5,635 Bytes
b9e2109 | 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 | import gradio as gr
from modules.element_processing import process_screenshot
from modules.element_detector import initialize_models
import asyncio
import io
import os
import base64
import numpy as np
from PIL import Image
# Initialize models on startup
async def init():
await initialize_models()
loop = asyncio.new_event_loop()
asyncio.set_event_loop(loop)
loop.run_until_complete(init())
# Create a mock background tasks class
class MockBackgroundTasks:
def add_task(self, *args, **kwargs):
pass
# Define interface for data URI processing
def process_image_data_uri(data_uri):
if not data_uri.startswith('data:image'):
return None, "Invalid data URI format"
try:
# Split the header and the base64 data
header, encoded = data_uri.split(",", 1)
image_data = base64.b64decode(encoded)
# Process the screenshot
background_tasks = MockBackgroundTasks()
elements, image_path = loop.run_until_complete(
process_screenshot(image_data, background_tasks)
)
# Format output
result_lines = []
for element in elements:
# Determine content based on element type
if element["type"] == "text":
content_value = element.get("text_content", "")
else:
content_value = element.get("object_label", "")
# Format the element string
element_str = (f"icon {element['code']}: {{"
f"'type': '{element['type']}', "
f"'centerX': {element['center_x']}, "
f"'centerY': {element['center_y']}, "
f"'content': '{content_value}'}}")
result_lines.append(element_str)
# Join all lines
result_string = "\n".join(result_lines)
# Load annotated image
annotated_img = None
if image_path and os.path.exists(image_path):
annotated_img = Image.open(image_path)
return annotated_img, result_string
except Exception as e:
return None, f"Error: {str(e)}"
# Also allow uploading an image directly
def process_image_upload(image):
if image is None:
return None, "No image provided"
try:
# Convert image to bytes
img_byte_arr = io.BytesIO()
image.save(img_byte_arr, format='PNG')
image_data = img_byte_arr.getvalue()
# Process the screenshot
background_tasks = MockBackgroundTasks()
elements, image_path = loop.run_until_complete(
process_screenshot(image_data, background_tasks)
)
# Format output
result_lines = []
for element in elements:
# Determine content based on element type
if element["type"] == "text":
content_value = element.get("text_content", "")
else:
content_value = element.get("object_label", "")
# Format the element string
element_str = (f"icon {element['code']}: {{"
f"'type': '{element['type']}', "
f"'centerX': {element['center_x']}, "
f"'centerY': {element['center_y']}, "
f"'content': '{content_value}'}}")
result_lines.append(element_str)
# Join all lines
result_string = "\n".join(result_lines)
# Load annotated image
annotated_img = None
if image_path and os.path.exists(image_path):
annotated_img = Image.open(image_path)
return annotated_img, result_string
except Exception as e:
return None, f"Error: {str(e)}"
# Create tabbed interface
with gr.Blocks(title="UI Element Detection") as demo:
gr.Markdown("# UI Element Detection")
gr.Markdown("Upload a screenshot or provide a data URI to detect UI elements with bounding boxes and text annotations")
with gr.Tabs():
with gr.TabItem("Upload Image"):
with gr.Row():
with gr.Column():
image_input = gr.Image(type="pil", label="Upload Screenshot")
upload_button = gr.Button("Process Image")
with gr.Column():
image_output = gr.Image(type="pil", label="Annotated Image")
text_output = gr.Textbox(label="Detected Elements", lines=10)
upload_button.click(
fn=process_image_upload,
inputs=image_input,
outputs=[image_output, text_output]
)
with gr.TabItem("Data URI"):
with gr.Row():
with gr.Column():
data_uri_input = gr.Textbox(label="Image Data URI", lines=5, placeholder="data:image/png;base64,...")
data_uri_button = gr.Button("Process Data URI")
with gr.Column():
data_uri_image_output = gr.Image(type="pil", label="Annotated Image")
data_uri_text_output = gr.Textbox(label="Detected Elements", lines=10)
data_uri_button.click(
fn=process_image_data_uri,
inputs=data_uri_input,
outputs=[data_uri_image_output, data_uri_text_output]
)
# Ensure annotated directory exists
os.makedirs("annotated", exist_ok=True)
# Launch the app
demo.launch(share=True, enable_api=True) |