makeitfr commited on
Commit
709fba5
Β·
verified Β·
1 Parent(s): d88dfd3

Upload app_hf_spaces.py with huggingface_hub

Browse files
Files changed (1) hide show
  1. app_hf_spaces.py +151 -0
app_hf_spaces.py ADDED
@@ -0,0 +1,151 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """
3
+ Hugging Face Spaces optimized app with Gradio UI
4
+ Initializes models on startup, provides both UI and API
5
+ """
6
+
7
+ import os
8
+ import gc
9
+ import json
10
+ from pathlib import Path
11
+ import gradio as gr
12
+ import numpy as np
13
+ from PIL import Image
14
+ import cv2
15
+
16
+ # Configure OmniParser
17
+ os.environ["OMP_NUM_THREADS"] = "4"
18
+
19
+ from config import get_omniparser_config
20
+ from ui_element_analyzer import UIElementAnalyzer
21
+
22
+ # Global analyzer (initialized once)
23
+ analyzer = None
24
+
25
+ def initialize_models():
26
+ """Initialize OmniParser models on startup"""
27
+ global analyzer
28
+ print("[INIT] Loading OmniParser models...")
29
+ config = get_omniparser_config()
30
+ analyzer = UIElementAnalyzer(config)
31
+ print("[INIT] Models loaded successfully")
32
+ gc.collect()
33
+
34
+ def analyze_ui_image(image: Image.Image) -> tuple:
35
+ """
36
+ Analyze UI screenshot and return results
37
+
38
+ Args:
39
+ image: PIL Image of UI screenshot
40
+
41
+ Returns:
42
+ (visualization_image, json_str, csv_str, status_str)
43
+ """
44
+ if analyzer is None:
45
+ return None, "", "", "❌ Models not initialized. Please refresh page."
46
+
47
+ try:
48
+ print("[PROCESSING] Analyzing image...")
49
+
50
+ # Convert PIL to numpy
51
+ img_np = np.array(image)
52
+ if len(img_np.shape) == 2:
53
+ img_np = cv2.cvtColor(img_np, cv2.COLOR_GRAY2BGR)
54
+
55
+ # Analyze
56
+ results = analyzer.analyze(img_np)
57
+
58
+ # Load visualization
59
+ viz_path = results.get("visualization_path")
60
+ if viz_path and Path(viz_path).exists():
61
+ viz_image = Image.open(viz_path)
62
+ else:
63
+ viz_image = image
64
+
65
+ # Format JSON
66
+ coords = results.get("coordinates", [])
67
+ json_str = json.dumps(coords, indent=2)
68
+
69
+ # Format CSV
70
+ csv_lines = ["element_id,x,y,confidence,ocr_text"]
71
+ for elem in coords:
72
+ csv_lines.append(
73
+ f"{elem['element_id']},{elem['x']},{elem['y']},"
74
+ f"{elem['confidence']},{elem['ocr_text']}"
75
+ )
76
+ csv_str = "\n".join(csv_lines)
77
+
78
+ status = f"βœ… Detected {len(coords)} UI elements"
79
+
80
+ return viz_image, json_str, csv_str, status
81
+
82
+ except Exception as e:
83
+ print(f"[ERROR] {str(e)}")
84
+ return image, "", "", f"❌ Error: {str(e)}"
85
+
86
+
87
+ # Initialize on startup
88
+ print("[HF SPACES] Starting application...")
89
+ initialize_models()
90
+
91
+ # Create Gradio interface
92
+ with gr.Blocks(title="OmniParser UI Detector", theme=gr.themes.Soft()) as demo:
93
+ gr.Markdown("# 🎯 OmniParser UI Element Detector")
94
+ gr.Markdown("Upload a UI screenshot to detect and locate all UI elements (buttons, text, icons, etc.)")
95
+
96
+ with gr.Row():
97
+ with gr.Column(scale=1):
98
+ gr.Markdown("### πŸ“€ Upload Image")
99
+ image_input = gr.Image(type="pil", label="UI Screenshot")
100
+ analyze_btn = gr.Button("πŸ” Analyze", variant="primary", size="lg")
101
+
102
+ with gr.Column(scale=1):
103
+ gr.Markdown("### πŸ“Š Results")
104
+ viz_output = gr.Image(label="Detection Visualization")
105
+ status_output = gr.Textbox(label="Status", interactive=False)
106
+
107
+ with gr.Row():
108
+ with gr.Column():
109
+ gr.Markdown("### πŸ“‹ Coordinates (JSON)")
110
+ json_output = gr.Textbox(
111
+ label="JSON Output",
112
+ lines=10,
113
+ max_lines=30,
114
+ interactive=False
115
+ )
116
+
117
+ with gr.Row():
118
+ with gr.Column():
119
+ gr.Markdown("### πŸ“ˆ Coordinates (CSV)")
120
+ csv_output = gr.Textbox(
121
+ label="CSV Output",
122
+ lines=10,
123
+ max_lines=30,
124
+ interactive=False
125
+ )
126
+
127
+ # Set click handler
128
+ analyze_btn.click(
129
+ analyze_ui_image,
130
+ inputs=[image_input],
131
+ outputs=[viz_output, json_output, csv_output, status_output]
132
+ )
133
+
134
+ gr.Markdown("""
135
+ ### ℹ️ How it works:
136
+ 1. **Upload** a screenshot of any UI/app
137
+ 2. **Click** "Analyze" button
138
+ 3. **View** detected elements with coordinates
139
+ 4. **Export** results as JSON or CSV
140
+
141
+ Detects: Buttons, text fields, icons, dropdowns, etc.
142
+ """)
143
+
144
+ if __name__ == "__main__":
145
+ print("[LAUNCH] Starting Gradio server on port 7860...")
146
+ demo.launch(
147
+ server_name="0.0.0.0",
148
+ server_port=7860,
149
+ share=False,
150
+ show_error=True
151
+ )