Spaces:
Runtime error
Runtime error
Upload 4 files
Browse files- README.md +75 -9
- app.py +275 -105
- create_test_image.py +67 -0
- requirements.txt +4 -1
README.md
CHANGED
|
@@ -1,6 +1,27 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
# OmniParser v2.0 API
|
| 2 |
|
| 3 |
-
This
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 4 |
|
| 5 |
## API Usage
|
| 6 |
|
|
@@ -9,7 +30,7 @@ You can use this API by sending a POST request with a file upload:
|
|
| 9 |
```python
|
| 10 |
import requests
|
| 11 |
|
| 12 |
-
# Replace with
|
| 13 |
OMNIPARSER_API_URL = "https://your-username-omniparser-api.hf.space/api/parse"
|
| 14 |
|
| 15 |
# Upload a file
|
|
@@ -20,16 +41,61 @@ response = requests.post(OMNIPARSER_API_URL, files=files)
|
|
| 20 |
|
| 21 |
# Get JSON result
|
| 22 |
result = response.json()
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 23 |
```
|
| 24 |
|
| 25 |
-
##
|
| 26 |
|
| 27 |
-
|
| 28 |
-
|
| 29 |
-
|
| 30 |
-
|
| 31 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 32 |
|
| 33 |
## Credits
|
| 34 |
|
| 35 |
-
This API uses Microsoft's OmniParser v2.0, which is a screen parsing tool for pure vision-based GUI agents. For more information, visit the [OmniParser GitHub repository](https://github.com/microsoft/OmniParser).
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
---
|
| 2 |
+
title: OmniParser v2.0 API
|
| 3 |
+
emoji: 🖼️
|
| 4 |
+
colorFrom: blue
|
| 5 |
+
colorTo: indigo
|
| 6 |
+
sdk: gradio
|
| 7 |
+
sdk_version: 4.0.0
|
| 8 |
+
app_file: app.py
|
| 9 |
+
pinned: false
|
| 10 |
+
---
|
| 11 |
+
|
| 12 |
+
Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference
|
| 13 |
+
|
| 14 |
# OmniParser v2.0 API
|
| 15 |
|
| 16 |
+
This is a public API endpoint for Microsoft's OmniParser v2.0, which can parse UI screenshots and return structured data.
|
| 17 |
+
|
| 18 |
+
## Features
|
| 19 |
+
|
| 20 |
+
- Parses UI screenshots into structured JSON data
|
| 21 |
+
- Identifies interactive elements (buttons, menus, icons, etc.)
|
| 22 |
+
- Provides captions describing the functionality of each element
|
| 23 |
+
- Returns visualization of detected elements
|
| 24 |
+
- Accessible via a simple REST API
|
| 25 |
|
| 26 |
## API Usage
|
| 27 |
|
|
|
|
| 30 |
```python
|
| 31 |
import requests
|
| 32 |
|
| 33 |
+
# Replace with your actual API URL after deployment
|
| 34 |
OMNIPARSER_API_URL = "https://your-username-omniparser-api.hf.space/api/parse"
|
| 35 |
|
| 36 |
# Upload a file
|
|
|
|
| 41 |
|
| 42 |
# Get JSON result
|
| 43 |
result = response.json()
|
| 44 |
+
|
| 45 |
+
# Access parsed elements
|
| 46 |
+
elements = result["elements"]
|
| 47 |
+
for element in elements:
|
| 48 |
+
print(f"Element {element['id']}: {element['text']} - {element['caption']}")
|
| 49 |
+
print(f"Coordinates: {element['coordinates']}")
|
| 50 |
+
print(f"Interactable: {element['is_interactable']}")
|
| 51 |
+
print(f"Confidence: {element['confidence']}")
|
| 52 |
+
print("---")
|
| 53 |
+
|
| 54 |
+
# Access visualization (base64 encoded image)
|
| 55 |
+
visualization_base64 = result["visualization"]
|
| 56 |
```
|
| 57 |
|
| 58 |
+
## Response Format
|
| 59 |
|
| 60 |
+
The API returns a JSON object with the following structure:
|
| 61 |
+
|
| 62 |
+
```json
|
| 63 |
+
{
|
| 64 |
+
"status": "success",
|
| 65 |
+
"elements": [
|
| 66 |
+
{
|
| 67 |
+
"id": 0,
|
| 68 |
+
"text": "Button 1",
|
| 69 |
+
"caption": "Click to submit form",
|
| 70 |
+
"coordinates": [0.1, 0.1, 0.3, 0.2],
|
| 71 |
+
"is_interactable": true,
|
| 72 |
+
"confidence": 0.95
|
| 73 |
+
},
|
| 74 |
+
{
|
| 75 |
+
"id": 1,
|
| 76 |
+
"text": "Menu",
|
| 77 |
+
"caption": "Navigation menu",
|
| 78 |
+
"coordinates": [0.4, 0.5, 0.6, 0.6],
|
| 79 |
+
"is_interactable": true,
|
| 80 |
+
"confidence": 0.87
|
| 81 |
+
}
|
| 82 |
+
],
|
| 83 |
+
"visualization": "base64_encoded_image_string"
|
| 84 |
+
}
|
| 85 |
+
```
|
| 86 |
+
|
| 87 |
+
## Deployment
|
| 88 |
+
|
| 89 |
+
This API is deployed on Hugging Face Spaces using Gradio. The deployment is free and provides a public URL that you can use in your applications.
|
| 90 |
|
| 91 |
## Credits
|
| 92 |
|
| 93 |
+
This API uses Microsoft's OmniParser v2.0, which is a screen parsing tool for pure vision-based GUI agents. For more information, visit the [OmniParser GitHub repository](https://github.com/microsoft/OmniParser).
|
| 94 |
+
|
| 95 |
+
## License
|
| 96 |
+
|
| 97 |
+
Please note that the OmniParser models have specific licenses:
|
| 98 |
+
- icon_detect model is under AGPL license
|
| 99 |
+
- icon_caption is under MIT license
|
| 100 |
+
|
| 101 |
+
Please refer to the LICENSE file in the folder of each model in the original repository.
|
app.py
CHANGED
|
@@ -5,51 +5,102 @@ import base64
|
|
| 5 |
import gradio as gr
|
| 6 |
import numpy as np
|
| 7 |
import torch
|
|
|
|
|
|
|
| 8 |
from PIL import Image
|
| 9 |
from huggingface_hub import hf_hub_download
|
| 10 |
from typing import Optional, Dict, Any, List, Union
|
| 11 |
|
| 12 |
-
#
|
| 13 |
-
|
| 14 |
-
|
| 15 |
-
|
| 16 |
-
|
| 17 |
-
|
| 18 |
-
|
| 19 |
-
|
| 20 |
-
|
| 21 |
-
|
| 22 |
-
|
| 23 |
-
|
| 24 |
-
|
| 25 |
-
|
| 26 |
-
|
| 27 |
-
|
| 28 |
-
|
| 29 |
-
|
| 30 |
-
repo_id="microsoft/OmniParser-v2.0",
|
| 31 |
-
filename=f"icon_caption/{f}",
|
| 32 |
-
local_dir="weights"
|
| 33 |
-
)
|
| 34 |
|
| 35 |
-
|
| 36 |
-
|
| 37 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 38 |
|
| 39 |
-
#
|
| 40 |
-
|
| 41 |
-
download_omniparser_files()
|
| 42 |
|
| 43 |
-
# Import OmniParser utilities
|
| 44 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 45 |
|
| 46 |
# Initialize models
|
| 47 |
device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
|
| 48 |
-
|
| 49 |
-
|
| 50 |
-
|
| 51 |
-
|
| 52 |
-
)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 53 |
|
| 54 |
def process_image(
|
| 55 |
image: Image.Image,
|
|
@@ -71,62 +122,96 @@ def process_image(
|
|
| 71 |
Returns:
|
| 72 |
Dictionary with parsed elements and visualization
|
| 73 |
"""
|
| 74 |
-
#
|
| 75 |
-
|
| 76 |
-
|
| 77 |
-
|
| 78 |
-
|
| 79 |
-
|
| 80 |
-
|
| 81 |
-
'text_padding': max(int(3 * box_overlay_ratio), 1),
|
| 82 |
-
'thickness': max(int(3 * box_overlay_ratio), 1),
|
| 83 |
-
}
|
| 84 |
-
|
| 85 |
-
# Run OCR to detect text
|
| 86 |
-
ocr_bbox_rslt, is_goal_filtered = check_ocr_box(
|
| 87 |
-
image,
|
| 88 |
-
display_img=False,
|
| 89 |
-
output_bb_format='xyxy',
|
| 90 |
-
goal_filtering=None,
|
| 91 |
-
easyocr_args={'paragraph': False, 'text_threshold': 0.9},
|
| 92 |
-
use_paddleocr=use_paddleocr
|
| 93 |
-
)
|
| 94 |
-
text, ocr_bbox = ocr_bbox_rslt
|
| 95 |
-
|
| 96 |
-
# Process image with OmniParser
|
| 97 |
-
dino_labled_img, label_coordinates, parsed_content_list = get_som_labeled_img(
|
| 98 |
-
image,
|
| 99 |
-
yolo_model,
|
| 100 |
-
BOX_TRESHOLD=box_threshold,
|
| 101 |
-
output_coord_in_ratio=True,
|
| 102 |
-
ocr_bbox=ocr_bbox,
|
| 103 |
-
draw_bbox_config=draw_bbox_config,
|
| 104 |
-
caption_model_processor=caption_model_processor,
|
| 105 |
-
ocr_text=text,
|
| 106 |
-
iou_threshold=iou_threshold,
|
| 107 |
-
imgsz=imgsz
|
| 108 |
-
)
|
| 109 |
-
|
| 110 |
-
# Convert base64 image to PIL Image
|
| 111 |
-
visualization = Image.open(io.BytesIO(base64.b64decode(dino_labled_img)))
|
| 112 |
-
|
| 113 |
-
# Create structured output
|
| 114 |
-
elements = []
|
| 115 |
-
for i, element in enumerate(parsed_content_list):
|
| 116 |
-
elements.append({
|
| 117 |
-
"id": i,
|
| 118 |
-
"text": element.get("text", ""),
|
| 119 |
-
"caption": element.get("caption", ""),
|
| 120 |
-
"coordinates": element.get("coordinates", []),
|
| 121 |
-
"is_interactable": element.get("is_interactable", False),
|
| 122 |
-
"confidence": element.get("confidence", 0.0)
|
| 123 |
-
})
|
| 124 |
|
| 125 |
-
|
| 126 |
-
|
| 127 |
-
|
| 128 |
-
|
| 129 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 130 |
|
| 131 |
# API endpoint function
|
| 132 |
def api_endpoint(image):
|
|
@@ -146,6 +231,14 @@ def api_endpoint(image):
|
|
| 146 |
# Process the image
|
| 147 |
result = process_image(image)
|
| 148 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 149 |
# Convert visualization to base64 for JSON response
|
| 150 |
buffered = io.BytesIO()
|
| 151 |
result["visualization"].save(buffered, format="PNG")
|
|
@@ -160,7 +253,33 @@ def api_endpoint(image):
|
|
| 160 |
|
| 161 |
return json.dumps(response)
|
| 162 |
except Exception as e:
|
| 163 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 164 |
|
| 165 |
# Create Gradio interface
|
| 166 |
with gr.Blocks() as demo:
|
|
@@ -169,6 +288,10 @@ with gr.Blocks() as demo:
|
|
| 169 |
|
| 170 |
Upload an image to parse UI elements and get structured data.
|
| 171 |
|
|
|
|
|
|
|
|
|
|
|
|
|
| 172 |
## API Usage
|
| 173 |
|
| 174 |
You can use this API by sending a POST request with a file upload to this URL.
|
|
@@ -176,7 +299,7 @@ with gr.Blocks() as demo:
|
|
| 176 |
```python
|
| 177 |
import requests
|
| 178 |
|
| 179 |
-
# Replace with your actual API URL
|
| 180 |
OMNIPARSER_API_URL = "https://your-username-omniparser-api.hf.space/api/parse"
|
| 181 |
|
| 182 |
# Upload a file
|
|
@@ -193,7 +316,47 @@ with gr.Blocks() as demo:
|
|
| 193 |
with gr.Row():
|
| 194 |
with gr.Column():
|
| 195 |
image_input = gr.Image(type='pil', label='Upload image')
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 196 |
submit_button = gr.Button(value='Parse Image', variant='primary')
|
|
|
|
|
|
|
|
|
|
| 197 |
|
| 198 |
with gr.Column():
|
| 199 |
json_output = gr.JSON(label='Parsed Elements (JSON)')
|
|
@@ -201,20 +364,27 @@ with gr.Blocks() as demo:
|
|
| 201 |
|
| 202 |
# Connect the interface
|
| 203 |
submit_button.click(
|
| 204 |
-
fn=
|
| 205 |
-
inputs=[image_input],
|
| 206 |
-
outputs=[json_output, image_output]
|
|
|
|
| 207 |
)
|
| 208 |
|
| 209 |
-
#
|
| 210 |
-
|
| 211 |
-
fn=
|
| 212 |
-
|
| 213 |
-
|
| 214 |
-
|
| 215 |
-
|
| 216 |
-
|
| 217 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 218 |
|
| 219 |
# Launch the app
|
| 220 |
-
demo.launch(
|
|
|
|
| 5 |
import gradio as gr
|
| 6 |
import numpy as np
|
| 7 |
import torch
|
| 8 |
+
import subprocess
|
| 9 |
+
import sys
|
| 10 |
from PIL import Image
|
| 11 |
from huggingface_hub import hf_hub_download
|
| 12 |
from typing import Optional, Dict, Any, List, Union
|
| 13 |
|
| 14 |
+
# Setup OmniParser repository and models
|
| 15 |
+
def setup_omniparser():
|
| 16 |
+
"""Clone OmniParser repository and download model weights"""
|
| 17 |
+
try:
|
| 18 |
+
# Check if OmniParser repository exists
|
| 19 |
+
if not os.path.exists("OmniParser"):
|
| 20 |
+
print("Cloning OmniParser repository...")
|
| 21 |
+
subprocess.run(["git", "clone", "https://github.com/microsoft/OmniParser.git"], check=True)
|
| 22 |
+
|
| 23 |
+
# Add OmniParser to Python path
|
| 24 |
+
omniparser_path = os.path.abspath("OmniParser")
|
| 25 |
+
if omniparser_path not in sys.path:
|
| 26 |
+
sys.path.append(omniparser_path)
|
| 27 |
+
print(f"Added {omniparser_path} to Python path")
|
| 28 |
+
|
| 29 |
+
# Create weights directory
|
| 30 |
+
os.makedirs("OmniParser/weights/icon_detect", exist_ok=True)
|
| 31 |
+
os.makedirs("OmniParser/weights/icon_caption_florence", exist_ok=True)
|
|
|
|
|
|
|
|
|
|
|
|
|
| 32 |
|
| 33 |
+
# Download model weights if they don't exist
|
| 34 |
+
if not os.path.exists("OmniParser/weights/icon_detect/model.pt") or not os.path.exists("OmniParser/weights/icon_caption_florence/model.safetensors"):
|
| 35 |
+
print("Downloading model weights...")
|
| 36 |
+
|
| 37 |
+
# Download detection model files
|
| 38 |
+
for f in ["train_args.yaml", "model.pt", "model.yaml"]:
|
| 39 |
+
hf_hub_download(
|
| 40 |
+
repo_id="microsoft/OmniParser-v2.0",
|
| 41 |
+
filename=f"icon_detect/{f}",
|
| 42 |
+
local_dir="OmniParser/weights"
|
| 43 |
+
)
|
| 44 |
+
|
| 45 |
+
# Download caption model files
|
| 46 |
+
for f in ["config.json", "generation_config.json", "model.safetensors"]:
|
| 47 |
+
hf_hub_download(
|
| 48 |
+
repo_id="microsoft/OmniParser-v2.0",
|
| 49 |
+
filename=f"icon_caption/{f}",
|
| 50 |
+
local_dir="OmniParser/weights"
|
| 51 |
+
)
|
| 52 |
+
|
| 53 |
+
# Rename the caption folder to match expected path
|
| 54 |
+
if os.path.exists("OmniParser/weights/icon_caption") and not os.path.exists("OmniParser/weights/icon_caption_florence"):
|
| 55 |
+
os.rename("OmniParser/weights/icon_caption", "OmniParser/weights/icon_caption_florence")
|
| 56 |
+
|
| 57 |
+
print("OmniParser setup completed successfully!")
|
| 58 |
+
return True
|
| 59 |
+
except Exception as e:
|
| 60 |
+
print(f"Error setting up OmniParser: {str(e)}")
|
| 61 |
+
return False
|
| 62 |
|
| 63 |
+
# Setup OmniParser
|
| 64 |
+
setup_success = setup_omniparser()
|
|
|
|
| 65 |
|
| 66 |
+
# Import OmniParser utilities
|
| 67 |
+
if setup_success:
|
| 68 |
+
try:
|
| 69 |
+
from OmniParser.util.utils import check_ocr_box, get_yolo_model, get_caption_model_processor, get_som_labeled_img
|
| 70 |
+
print("Successfully imported OmniParser utilities")
|
| 71 |
+
except ImportError as e:
|
| 72 |
+
print(f"Error importing OmniParser utilities: {str(e)}")
|
| 73 |
+
# Fallback to a simple error message
|
| 74 |
+
def error_message(*args, **kwargs):
|
| 75 |
+
return "Error: OmniParser utilities could not be imported. Please check the logs."
|
| 76 |
+
|
| 77 |
+
# Create dummy functions that return error messages
|
| 78 |
+
check_ocr_box = get_yolo_model = get_caption_model_processor = get_som_labeled_img = error_message
|
| 79 |
+
else:
|
| 80 |
+
print("Using dummy functions due to setup failure")
|
| 81 |
+
# Create dummy functions that return error messages
|
| 82 |
+
def error_message(*args, **kwargs):
|
| 83 |
+
return "Error: OmniParser setup failed. Please check the logs."
|
| 84 |
+
|
| 85 |
+
check_ocr_box = get_yolo_model = get_caption_model_processor = get_som_labeled_img = error_message
|
| 86 |
|
| 87 |
# Initialize models
|
| 88 |
device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
|
| 89 |
+
print(f"Using device: {device}")
|
| 90 |
+
|
| 91 |
+
# Initialize models with correct paths
|
| 92 |
+
try:
|
| 93 |
+
yolo_model = get_yolo_model(model_path='OmniParser/weights/icon_detect/model.pt')
|
| 94 |
+
caption_model_processor = get_caption_model_processor(
|
| 95 |
+
model_name="florence2",
|
| 96 |
+
model_name_or_path="OmniParser/weights/icon_caption_florence"
|
| 97 |
+
)
|
| 98 |
+
print("Models initialized successfully")
|
| 99 |
+
except Exception as e:
|
| 100 |
+
print(f"Error initializing models: {str(e)}")
|
| 101 |
+
# Create dummy models for graceful failure
|
| 102 |
+
yolo_model = None
|
| 103 |
+
caption_model_processor = None
|
| 104 |
|
| 105 |
def process_image(
|
| 106 |
image: Image.Image,
|
|
|
|
| 122 |
Returns:
|
| 123 |
Dictionary with parsed elements and visualization
|
| 124 |
"""
|
| 125 |
+
# Check if models are initialized
|
| 126 |
+
if yolo_model is None or caption_model_processor is None:
|
| 127 |
+
return {
|
| 128 |
+
"error": "Models not initialized properly. Please check the logs.",
|
| 129 |
+
"elements": [],
|
| 130 |
+
"visualization": image
|
| 131 |
+
}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 132 |
|
| 133 |
+
try:
|
| 134 |
+
# Calculate overlay ratio based on image size
|
| 135 |
+
box_overlay_ratio = image.size[0] / 3200
|
| 136 |
+
|
| 137 |
+
# Configure drawing parameters
|
| 138 |
+
draw_bbox_config = {
|
| 139 |
+
'text_scale': 0.8 * box_overlay_ratio,
|
| 140 |
+
'text_thickness': max(int(2 * box_overlay_ratio), 1),
|
| 141 |
+
'text_padding': max(int(3 * box_overlay_ratio), 1),
|
| 142 |
+
'thickness': max(int(3 * box_overlay_ratio), 1),
|
| 143 |
+
}
|
| 144 |
+
|
| 145 |
+
# Run OCR to detect text
|
| 146 |
+
ocr_bbox_rslt, is_goal_filtered = check_ocr_box(
|
| 147 |
+
image,
|
| 148 |
+
display_img=False,
|
| 149 |
+
output_bb_format='xyxy',
|
| 150 |
+
goal_filtering=None,
|
| 151 |
+
easyocr_args={'paragraph': False, 'text_threshold': 0.9},
|
| 152 |
+
use_paddleocr=use_paddleocr
|
| 153 |
+
)
|
| 154 |
+
|
| 155 |
+
# Check if OCR returned an error message (string)
|
| 156 |
+
if isinstance(ocr_bbox_rslt, str):
|
| 157 |
+
return {
|
| 158 |
+
"error": ocr_bbox_rslt,
|
| 159 |
+
"elements": [],
|
| 160 |
+
"visualization": image
|
| 161 |
+
}
|
| 162 |
+
|
| 163 |
+
text, ocr_bbox = ocr_bbox_rslt
|
| 164 |
+
|
| 165 |
+
# Process image with OmniParser
|
| 166 |
+
dino_labled_img, label_coordinates, parsed_content_list = get_som_labeled_img(
|
| 167 |
+
image,
|
| 168 |
+
yolo_model,
|
| 169 |
+
BOX_TRESHOLD=box_threshold,
|
| 170 |
+
output_coord_in_ratio=True,
|
| 171 |
+
ocr_bbox=ocr_bbox,
|
| 172 |
+
draw_bbox_config=draw_bbox_config,
|
| 173 |
+
caption_model_processor=caption_model_processor,
|
| 174 |
+
ocr_text=text,
|
| 175 |
+
iou_threshold=iou_threshold,
|
| 176 |
+
imgsz=imgsz
|
| 177 |
+
)
|
| 178 |
+
|
| 179 |
+
# Check if get_som_labeled_img returned an error message (string)
|
| 180 |
+
if isinstance(dino_labled_img, str) and not dino_labled_img.startswith("data:"):
|
| 181 |
+
return {
|
| 182 |
+
"error": dino_labled_img,
|
| 183 |
+
"elements": [],
|
| 184 |
+
"visualization": image
|
| 185 |
+
}
|
| 186 |
+
|
| 187 |
+
# Convert base64 image to PIL Image
|
| 188 |
+
visualization = Image.open(io.BytesIO(base64.b64decode(dino_labled_img)))
|
| 189 |
+
|
| 190 |
+
# Create structured output
|
| 191 |
+
elements = []
|
| 192 |
+
for i, element in enumerate(parsed_content_list):
|
| 193 |
+
elements.append({
|
| 194 |
+
"id": i,
|
| 195 |
+
"text": element.get("text", ""),
|
| 196 |
+
"caption": element.get("caption", ""),
|
| 197 |
+
"coordinates": element.get("coordinates", []),
|
| 198 |
+
"is_interactable": element.get("is_interactable", False),
|
| 199 |
+
"confidence": element.get("confidence", 0.0)
|
| 200 |
+
})
|
| 201 |
+
|
| 202 |
+
# Return structured data and visualization
|
| 203 |
+
return {
|
| 204 |
+
"elements": elements,
|
| 205 |
+
"visualization": visualization
|
| 206 |
+
}
|
| 207 |
+
except Exception as e:
|
| 208 |
+
print(f"Error processing image: {str(e)}")
|
| 209 |
+
# Return error message and empty results
|
| 210 |
+
return {
|
| 211 |
+
"error": f"Error processing image: {str(e)}",
|
| 212 |
+
"elements": [],
|
| 213 |
+
"visualization": image
|
| 214 |
+
}
|
| 215 |
|
| 216 |
# API endpoint function
|
| 217 |
def api_endpoint(image):
|
|
|
|
| 231 |
# Process the image
|
| 232 |
result = process_image(image)
|
| 233 |
|
| 234 |
+
# Check if there was an error
|
| 235 |
+
if "error" in result:
|
| 236 |
+
return json.dumps({
|
| 237 |
+
"status": "error",
|
| 238 |
+
"error": result["error"],
|
| 239 |
+
"elements": []
|
| 240 |
+
})
|
| 241 |
+
|
| 242 |
# Convert visualization to base64 for JSON response
|
| 243 |
buffered = io.BytesIO()
|
| 244 |
result["visualization"].save(buffered, format="PNG")
|
|
|
|
| 253 |
|
| 254 |
return json.dumps(response)
|
| 255 |
except Exception as e:
|
| 256 |
+
print(f"API endpoint error: {str(e)}")
|
| 257 |
+
return json.dumps({
|
| 258 |
+
"status": "error",
|
| 259 |
+
"error": f"API processing error: {str(e)}",
|
| 260 |
+
"elements": []
|
| 261 |
+
})
|
| 262 |
+
|
| 263 |
+
# Function to handle UI submission
|
| 264 |
+
def handle_submission(image, box_threshold=0.05, iou_threshold=0.1, use_paddleocr=True, imgsz=640):
|
| 265 |
+
"""Handle UI submission and provide appropriate feedback"""
|
| 266 |
+
if image is None:
|
| 267 |
+
return {"error": "No image provided"}, None
|
| 268 |
+
|
| 269 |
+
# Process the image
|
| 270 |
+
result = process_image(
|
| 271 |
+
image,
|
| 272 |
+
box_threshold=box_threshold,
|
| 273 |
+
iou_threshold=iou_threshold,
|
| 274 |
+
use_paddleocr=use_paddleocr,
|
| 275 |
+
imgsz=imgsz
|
| 276 |
+
)
|
| 277 |
+
|
| 278 |
+
# Return the result
|
| 279 |
+
if "error" in result:
|
| 280 |
+
return {"error": result["error"]}, result.get("visualization", None)
|
| 281 |
+
else:
|
| 282 |
+
return {"elements": result["elements"]}, result["visualization"]
|
| 283 |
|
| 284 |
# Create Gradio interface
|
| 285 |
with gr.Blocks() as demo:
|
|
|
|
| 288 |
|
| 289 |
Upload an image to parse UI elements and get structured data.
|
| 290 |
|
| 291 |
+
## Quick Start
|
| 292 |
+
|
| 293 |
+
You can use the [test UI image](/file=static/test_ui.png) to try out the API, or upload your own UI screenshot.
|
| 294 |
+
|
| 295 |
## API Usage
|
| 296 |
|
| 297 |
You can use this API by sending a POST request with a file upload to this URL.
|
|
|
|
| 299 |
```python
|
| 300 |
import requests
|
| 301 |
|
| 302 |
+
# Replace with your actual API URL after deployment
|
| 303 |
OMNIPARSER_API_URL = "https://your-username-omniparser-api.hf.space/api/parse"
|
| 304 |
|
| 305 |
# Upload a file
|
|
|
|
| 316 |
with gr.Row():
|
| 317 |
with gr.Column():
|
| 318 |
image_input = gr.Image(type='pil', label='Upload image')
|
| 319 |
+
|
| 320 |
+
# Function to load test image
|
| 321 |
+
def load_test_image():
|
| 322 |
+
if os.path.exists("static/test_ui.png"):
|
| 323 |
+
return Image.open("static/test_ui.png")
|
| 324 |
+
return None
|
| 325 |
+
|
| 326 |
+
test_image_button = gr.Button(value='Load Test Image')
|
| 327 |
+
test_image_button.click(fn=load_test_image, inputs=[], outputs=[image_input])
|
| 328 |
+
|
| 329 |
+
with gr.Accordion("Advanced Options", open=False):
|
| 330 |
+
box_threshold = gr.Slider(
|
| 331 |
+
label='Box Threshold',
|
| 332 |
+
minimum=0.01,
|
| 333 |
+
maximum=1.0,
|
| 334 |
+
step=0.01,
|
| 335 |
+
value=0.05
|
| 336 |
+
)
|
| 337 |
+
iou_threshold = gr.Slider(
|
| 338 |
+
label='IOU Threshold',
|
| 339 |
+
minimum=0.01,
|
| 340 |
+
maximum=1.0,
|
| 341 |
+
step=0.01,
|
| 342 |
+
value=0.1
|
| 343 |
+
)
|
| 344 |
+
use_paddleocr = gr.Checkbox(
|
| 345 |
+
label='Use PaddleOCR',
|
| 346 |
+
value=True
|
| 347 |
+
)
|
| 348 |
+
imgsz = gr.Slider(
|
| 349 |
+
label='Icon Detect Image Size',
|
| 350 |
+
minimum=640,
|
| 351 |
+
maximum=1920,
|
| 352 |
+
step=32,
|
| 353 |
+
value=640
|
| 354 |
+
)
|
| 355 |
+
|
| 356 |
submit_button = gr.Button(value='Parse Image', variant='primary')
|
| 357 |
+
|
| 358 |
+
# Status message
|
| 359 |
+
status = gr.Markdown("Ready to parse images")
|
| 360 |
|
| 361 |
with gr.Column():
|
| 362 |
json_output = gr.JSON(label='Parsed Elements (JSON)')
|
|
|
|
| 364 |
|
| 365 |
# Connect the interface
|
| 366 |
submit_button.click(
|
| 367 |
+
fn=handle_submission,
|
| 368 |
+
inputs=[image_input, box_threshold, iou_threshold, use_paddleocr, imgsz],
|
| 369 |
+
outputs=[json_output, image_output],
|
| 370 |
+
api_name="parse" # This creates the /api/parse endpoint
|
| 371 |
)
|
| 372 |
|
| 373 |
+
# Update status on load
|
| 374 |
+
demo.load(
|
| 375 |
+
fn=lambda: f"OmniParser v2.0 API - Running on {'GPU' if torch.cuda.is_available() else 'CPU'}",
|
| 376 |
+
outputs=status
|
| 377 |
+
)
|
| 378 |
+
|
| 379 |
+
# Create test image if it doesn't exist
|
| 380 |
+
try:
|
| 381 |
+
if not os.path.exists("static/test_ui.png"):
|
| 382 |
+
print("Creating test UI image...")
|
| 383 |
+
from create_test_image import create_test_ui_image
|
| 384 |
+
test_image_path = create_test_ui_image()
|
| 385 |
+
print(f"Test image created at {test_image_path}")
|
| 386 |
+
except Exception as e:
|
| 387 |
+
print(f"Error creating test image: {str(e)}")
|
| 388 |
|
| 389 |
# Launch the app
|
| 390 |
+
demo.launch()
|
create_test_image.py
ADDED
|
@@ -0,0 +1,67 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from PIL import Image, ImageDraw, ImageFont
|
| 2 |
+
import os
|
| 3 |
+
|
| 4 |
+
def create_test_ui_image():
|
| 5 |
+
"""Create a simple test UI image with buttons and text"""
|
| 6 |
+
# Create a new image with white background
|
| 7 |
+
width, height = 800, 600
|
| 8 |
+
image = Image.new('RGB', (width, height), color='white')
|
| 9 |
+
draw = ImageDraw.Draw(image)
|
| 10 |
+
|
| 11 |
+
# Try to load a font, use default if not available
|
| 12 |
+
try:
|
| 13 |
+
font = ImageFont.truetype("arial.ttf", 20)
|
| 14 |
+
small_font = ImageFont.truetype("arial.ttf", 16)
|
| 15 |
+
except IOError:
|
| 16 |
+
font = ImageFont.load_default()
|
| 17 |
+
small_font = ImageFont.load_default()
|
| 18 |
+
|
| 19 |
+
# Draw a header
|
| 20 |
+
draw.rectangle([(0, 0), (width, 60)], fill='#4285F4')
|
| 21 |
+
draw.text((20, 15), "Test UI Application", fill='white', font=font)
|
| 22 |
+
|
| 23 |
+
# Draw a sidebar
|
| 24 |
+
draw.rectangle([(0, 60), (200, height)], fill='#F1F1F1')
|
| 25 |
+
|
| 26 |
+
# Draw menu items in sidebar
|
| 27 |
+
menu_items = ["Home", "Profile", "Settings", "Help", "Logout"]
|
| 28 |
+
for i, item in enumerate(menu_items):
|
| 29 |
+
y = 100 + i * 50
|
| 30 |
+
# Highlight one item
|
| 31 |
+
if item == "Settings":
|
| 32 |
+
draw.rectangle([(10, y-10), (190, y+30)], fill='#E1E1E1')
|
| 33 |
+
draw.text((20, y), item, fill='black', font=font)
|
| 34 |
+
|
| 35 |
+
# Draw main content area
|
| 36 |
+
draw.text((220, 80), "Welcome to the Test UI", fill='black', font=font)
|
| 37 |
+
|
| 38 |
+
# Draw a form
|
| 39 |
+
draw.text((220, 150), "Please enter your information:", fill='black', font=font)
|
| 40 |
+
|
| 41 |
+
# Draw form fields
|
| 42 |
+
fields = ["Name", "Email", "Phone"]
|
| 43 |
+
for i, field in enumerate(fields):
|
| 44 |
+
y = 200 + i * 60
|
| 45 |
+
draw.text((220, y), f"{field}:", fill='black', font=font)
|
| 46 |
+
draw.rectangle([(320, y-5), (700, y+25)], outline='black')
|
| 47 |
+
|
| 48 |
+
# Draw buttons
|
| 49 |
+
draw.rectangle([(220, 400), (320, 440)], fill='#4285F4')
|
| 50 |
+
draw.text((240, 410), "Submit", fill='white', font=font)
|
| 51 |
+
|
| 52 |
+
draw.rectangle([(340, 400), (440, 440)], fill='#9E9E9E')
|
| 53 |
+
draw.text((360, 410), "Cancel", fill='white', font=font)
|
| 54 |
+
|
| 55 |
+
# Draw a checkbox
|
| 56 |
+
draw.rectangle([(220, 470), (240, 490)], outline='black')
|
| 57 |
+
draw.text((250, 470), "Remember me", fill='black', font=small_font)
|
| 58 |
+
|
| 59 |
+
# Save the image
|
| 60 |
+
os.makedirs("static", exist_ok=True)
|
| 61 |
+
image_path = "static/test_ui.png"
|
| 62 |
+
image.save(image_path)
|
| 63 |
+
print(f"Test UI image created at {image_path}")
|
| 64 |
+
return image_path
|
| 65 |
+
|
| 66 |
+
if __name__ == "__main__":
|
| 67 |
+
create_test_ui_image()
|
requirements.txt
CHANGED
|
@@ -12,4 +12,7 @@ huggingface_hub>=0.16.0
|
|
| 12 |
peft>=0.4.0
|
| 13 |
bitsandbytes>=0.40.0
|
| 14 |
accelerate>=0.20.0
|
| 15 |
-
safetensors>=0.3.1
|
|
|
|
|
|
|
|
|
|
|
|
| 12 |
peft>=0.4.0
|
| 13 |
bitsandbytes>=0.40.0
|
| 14 |
accelerate>=0.20.0
|
| 15 |
+
safetensors>=0.3.1
|
| 16 |
+
gitpython>=3.1.0
|
| 17 |
+
ultralytics>=8.0.0
|
| 18 |
+
timm>=0.9.0
|