Netrava commited on
Commit
fcc5f8d
·
verified ·
1 Parent(s): 31cb40d

Upload 6 files

Browse files
Files changed (6) hide show
  1. .gitattributes +34 -35
  2. README-HF.md +35 -0
  3. README.md +88 -12
  4. app.py +220 -0
  5. requirements.txt +15 -0
  6. test_api.py +70 -0
.gitattributes CHANGED
@@ -1,35 +1,34 @@
1
- *.7z filter=lfs diff=lfs merge=lfs -text
2
- *.arrow filter=lfs diff=lfs merge=lfs -text
3
- *.bin filter=lfs diff=lfs merge=lfs -text
4
- *.bz2 filter=lfs diff=lfs merge=lfs -text
5
- *.ckpt filter=lfs diff=lfs merge=lfs -text
6
- *.ftz filter=lfs diff=lfs merge=lfs -text
7
- *.gz filter=lfs diff=lfs merge=lfs -text
8
- *.h5 filter=lfs diff=lfs merge=lfs -text
9
- *.joblib filter=lfs diff=lfs merge=lfs -text
10
- *.lfs.* filter=lfs diff=lfs merge=lfs -text
11
- *.mlmodel filter=lfs diff=lfs merge=lfs -text
12
- *.model filter=lfs diff=lfs merge=lfs -text
13
- *.msgpack filter=lfs diff=lfs merge=lfs -text
14
- *.npy filter=lfs diff=lfs merge=lfs -text
15
- *.npz filter=lfs diff=lfs merge=lfs -text
16
- *.onnx filter=lfs diff=lfs merge=lfs -text
17
- *.ot filter=lfs diff=lfs merge=lfs -text
18
- *.parquet filter=lfs diff=lfs merge=lfs -text
19
- *.pb filter=lfs diff=lfs merge=lfs -text
20
- *.pickle filter=lfs diff=lfs merge=lfs -text
21
- *.pkl filter=lfs diff=lfs merge=lfs -text
22
- *.pt filter=lfs diff=lfs merge=lfs -text
23
- *.pth filter=lfs diff=lfs merge=lfs -text
24
- *.rar filter=lfs diff=lfs merge=lfs -text
25
- *.safetensors filter=lfs diff=lfs merge=lfs -text
26
- saved_model/**/* filter=lfs diff=lfs merge=lfs -text
27
- *.tar.* filter=lfs diff=lfs merge=lfs -text
28
- *.tar filter=lfs diff=lfs merge=lfs -text
29
- *.tflite filter=lfs diff=lfs merge=lfs -text
30
- *.tgz filter=lfs diff=lfs merge=lfs -text
31
- *.wasm filter=lfs diff=lfs merge=lfs -text
32
- *.xz filter=lfs diff=lfs merge=lfs -text
33
- *.zip filter=lfs diff=lfs merge=lfs -text
34
- *.zst filter=lfs diff=lfs merge=lfs -text
35
- *tfevents* filter=lfs diff=lfs merge=lfs -text
 
1
+ *.7z filter=lfs diff=lfs merge=lfs -text
2
+ *.arrow filter=lfs diff=lfs merge=lfs -text
3
+ *.bin filter=lfs diff=lfs merge=lfs -text
4
+ *.bz2 filter=lfs diff=lfs merge=lfs -text
5
+ *.ckpt filter=lfs diff=lfs merge=lfs -text
6
+ *.ftz filter=lfs diff=lfs merge=lfs -text
7
+ *.gz filter=lfs diff=lfs merge=lfs -text
8
+ *.h5 filter=lfs diff=lfs merge=lfs -text
9
+ *.joblib filter=lfs diff=lfs merge=lfs -text
10
+ *.lfs.* filter=lfs diff=lfs merge=lfs -text
11
+ *.mlmodel filter=lfs diff=lfs merge=lfs -text
12
+ *.model filter=lfs diff=lfs merge=lfs -text
13
+ *.msgpack filter=lfs diff=lfs merge=lfs -text
14
+ *.npy filter=lfs diff=lfs merge=lfs -text
15
+ *.npz filter=lfs diff=lfs merge=lfs -text
16
+ *.onnx filter=lfs diff=lfs merge=lfs -text
17
+ *.ot filter=lfs diff=lfs merge=lfs -text
18
+ *.parquet filter=lfs diff=lfs merge=lfs -text
19
+ *.pb filter=lfs diff=lfs merge=lfs -text
20
+ *.pickle filter=lfs diff=lfs merge=lfs -text
21
+ *.pkl filter=lfs diff=lfs merge=lfs -text
22
+ *.pt filter=lfs diff=lfs merge=lfs -text
23
+ *.pth filter=lfs diff=lfs merge=lfs -text
24
+ *.rar filter=lfs diff=lfs merge=lfs -text
25
+ *.safetensors filter=lfs diff=lfs merge=lfs -text
26
+ saved_model/**/* filter=lfs diff=lfs merge=lfs -text
27
+ *.tar.* filter=lfs diff=lfs merge=lfs -text
28
+ *.tflite filter=lfs diff=lfs merge=lfs -text
29
+ *.tgz filter=lfs diff=lfs merge=lfs -text
30
+ *.wasm filter=lfs diff=lfs merge=lfs -text
31
+ *.xz filter=lfs diff=lfs merge=lfs -text
32
+ *.zip filter=lfs diff=lfs merge=lfs -text
33
+ *.zst filter=lfs diff=lfs merge=lfs -text
34
+ *tfevents* filter=lfs diff=lfs merge=lfs -text
 
README-HF.md ADDED
@@ -0,0 +1,35 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # OmniParser v2.0 API
2
+
3
+ This Hugging Face Space provides a public API endpoint for Microsoft's OmniParser v2.0, which can parse UI screenshots and return structured data.
4
+
5
+ ## API Usage
6
+
7
+ You can use this API by sending a POST request with a file upload:
8
+
9
+ ```python
10
+ import requests
11
+
12
+ # Replace with the actual URL of this Space
13
+ OMNIPARSER_API_URL = "https://your-username-omniparser-api.hf.space/api/parse"
14
+
15
+ # Upload a file
16
+ files = {'image': open('screenshot.png', 'rb')}
17
+
18
+ # Send request
19
+ response = requests.post(OMNIPARSER_API_URL, files=files)
20
+
21
+ # Get JSON result
22
+ result = response.json()
23
+ ```
24
+
25
+ ## Features
26
+
27
+ - Parses UI screenshots into structured JSON data
28
+ - Identifies interactive elements (buttons, menus, icons, etc.)
29
+ - Provides captions describing the functionality of each element
30
+ - Returns visualization of detected elements
31
+ - Accessible via a simple REST API
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).
README.md CHANGED
@@ -1,12 +1,88 @@
1
- ---
2
- title: Omniparser Api
3
- emoji: 📚
4
- colorFrom: pink
5
- colorTo: red
6
- sdk: gradio
7
- sdk_version: 5.39.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
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # OmniParser v2.0 API
2
+
3
+ This is a public API endpoint for Microsoft's OmniParser v2.0, which can parse UI screenshots and return structured data.
4
+
5
+ ## Features
6
+
7
+ - Parses UI screenshots into structured JSON data
8
+ - Identifies interactive elements (buttons, menus, icons, etc.)
9
+ - Provides captions describing the functionality of each element
10
+ - Returns visualization of detected elements
11
+ - Accessible via a simple REST API
12
+
13
+ ## API Usage
14
+
15
+ You can use this API by sending a POST request with a file upload:
16
+
17
+ ```python
18
+ import requests
19
+
20
+ # Replace with your actual API URL after deployment
21
+ OMNIPARSER_API_URL = "https://your-username-omniparser-api.hf.space/api/parse"
22
+
23
+ # Upload a file
24
+ files = {'image': open('screenshot.png', 'rb')}
25
+
26
+ # Send request
27
+ response = requests.post(OMNIPARSER_API_URL, files=files)
28
+
29
+ # Get JSON result
30
+ result = response.json()
31
+
32
+ # Access parsed elements
33
+ elements = result["elements"]
34
+ for element in elements:
35
+ print(f"Element {element['id']}: {element['text']} - {element['caption']}")
36
+ print(f"Coordinates: {element['coordinates']}")
37
+ print(f"Interactable: {element['is_interactable']}")
38
+ print(f"Confidence: {element['confidence']}")
39
+ print("---")
40
+
41
+ # Access visualization (base64 encoded image)
42
+ visualization_base64 = result["visualization"]
43
+ ```
44
+
45
+ ## Response Format
46
+
47
+ The API returns a JSON object with the following structure:
48
+
49
+ ```json
50
+ {
51
+ "status": "success",
52
+ "elements": [
53
+ {
54
+ "id": 0,
55
+ "text": "Button 1",
56
+ "caption": "Click to submit form",
57
+ "coordinates": [0.1, 0.1, 0.3, 0.2],
58
+ "is_interactable": true,
59
+ "confidence": 0.95
60
+ },
61
+ {
62
+ "id": 1,
63
+ "text": "Menu",
64
+ "caption": "Navigation menu",
65
+ "coordinates": [0.4, 0.5, 0.6, 0.6],
66
+ "is_interactable": true,
67
+ "confidence": 0.87
68
+ }
69
+ ],
70
+ "visualization": "base64_encoded_image_string"
71
+ }
72
+ ```
73
+
74
+ ## Deployment
75
+
76
+ 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.
77
+
78
+ ## Credits
79
+
80
+ 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).
81
+
82
+ ## License
83
+
84
+ Please note that the OmniParser models have specific licenses:
85
+ - icon_detect model is under AGPL license
86
+ - icon_caption is under MIT license
87
+
88
+ Please refer to the LICENSE file in the folder of each model in the original repository.
app.py ADDED
@@ -0,0 +1,220 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import io
3
+ import json
4
+ 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
+ # Import OmniParser utilities
13
+ # These will be downloaded from the Hugging Face Hub
14
+ def download_omniparser_files():
15
+ """Download necessary OmniParser files from Hugging Face Hub"""
16
+ os.makedirs("weights/icon_detect", exist_ok=True)
17
+ os.makedirs("weights/icon_caption_florence", exist_ok=True)
18
+
19
+ # Download detection model files
20
+ for f in ["train_args.yaml", "model.pt", "model.yaml"]:
21
+ hf_hub_download(
22
+ repo_id="microsoft/OmniParser-v2.0",
23
+ filename=f"icon_detect/{f}",
24
+ local_dir="weights"
25
+ )
26
+
27
+ # Download caption model files
28
+ for f in ["config.json", "generation_config.json", "model.safetensors"]:
29
+ hf_hub_download(
30
+ repo_id="microsoft/OmniParser-v2.0",
31
+ filename=f"icon_caption/{f}",
32
+ local_dir="weights"
33
+ )
34
+
35
+ # Rename the caption folder to match expected path
36
+ if os.path.exists("weights/icon_caption") and not os.path.exists("weights/icon_caption_florence"):
37
+ os.rename("weights/icon_caption", "weights/icon_caption_florence")
38
+
39
+ # Download OmniParser files if they don't exist
40
+ if not os.path.exists("weights/icon_detect/model.pt") or not os.path.exists("weights/icon_caption_florence/model.safetensors"):
41
+ download_omniparser_files()
42
+
43
+ # Import OmniParser utilities after ensuring files are downloaded
44
+ from util.utils import check_ocr_box, get_yolo_model, get_caption_model_processor, get_som_labeled_img
45
+
46
+ # Initialize models
47
+ device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
48
+ yolo_model = get_yolo_model(model_path='weights/icon_detect/model.pt')
49
+ caption_model_processor = get_caption_model_processor(
50
+ model_name="florence2",
51
+ model_name_or_path="weights/icon_caption_florence"
52
+ )
53
+
54
+ def process_image(
55
+ image: Image.Image,
56
+ box_threshold: float = 0.05,
57
+ iou_threshold: float = 0.1,
58
+ use_paddleocr: bool = True,
59
+ imgsz: int = 640
60
+ ) -> Dict[str, Any]:
61
+ """
62
+ Process an image with OmniParser and return structured data
63
+
64
+ Args:
65
+ image: PIL Image to process
66
+ box_threshold: Threshold for bounding box confidence
67
+ iou_threshold: Threshold for IOU overlap
68
+ use_paddleocr: Whether to use PaddleOCR for text detection
69
+ imgsz: Image size for icon detection
70
+
71
+ Returns:
72
+ Dictionary with parsed elements and visualization
73
+ """
74
+ # Calculate overlay ratio based on image size
75
+ box_overlay_ratio = image.size[0] / 3200
76
+
77
+ # Configure drawing parameters
78
+ draw_bbox_config = {
79
+ 'text_scale': 0.8 * box_overlay_ratio,
80
+ 'text_thickness': max(int(2 * box_overlay_ratio), 1),
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
+ # Return structured data and visualization
126
+ return {
127
+ "elements": elements,
128
+ "visualization": visualization
129
+ }
130
+
131
+ # API endpoint function
132
+ def api_endpoint(image):
133
+ """
134
+ API endpoint that accepts an image and returns parsed elements
135
+
136
+ Args:
137
+ image: Uploaded image file
138
+
139
+ Returns:
140
+ JSON with parsed elements
141
+ """
142
+ if image is None:
143
+ return json.dumps({"error": "No image provided"})
144
+
145
+ try:
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")
152
+ img_str = base64.b64encode(buffered.getvalue()).decode()
153
+
154
+ # Create response
155
+ response = {
156
+ "status": "success",
157
+ "elements": result["elements"],
158
+ "visualization": img_str
159
+ }
160
+
161
+ return json.dumps(response)
162
+ except Exception as e:
163
+ return json.dumps({"error": str(e)})
164
+
165
+ # Create Gradio interface
166
+ with gr.Blocks() as demo:
167
+ gr.Markdown("""
168
+ # OmniParser v2.0 API
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.
175
+
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
183
+ files = {'image': open('screenshot.png', 'rb')}
184
+
185
+ # Send request
186
+ response = requests.post(OMNIPARSER_API_URL, files=files)
187
+
188
+ # Get JSON result
189
+ result = response.json()
190
+ ```
191
+ """)
192
+
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)')
200
+ image_output = gr.Image(type='pil', label='Visualization')
201
+
202
+ # Connect the interface
203
+ submit_button.click(
204
+ fn=process_image,
205
+ inputs=[image_input],
206
+ outputs=[json_output, image_output]
207
+ )
208
+
209
+ # Add API endpoint
210
+ gr.Interface(
211
+ fn=api_endpoint,
212
+ inputs=gr.Image(type='pil'),
213
+ outputs=gr.JSON(),
214
+ title="OmniParser API",
215
+ description="Upload an image to parse UI elements",
216
+ allow_flagging=False
217
+ ).launch(share=True)
218
+
219
+ # Launch the app
220
+ demo.launch(share=True)
requirements.txt ADDED
@@ -0,0 +1,15 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ gradio>=4.0.0
2
+ torch>=2.0.0
3
+ torchvision>=0.15.0
4
+ transformers>=4.30.0
5
+ pillow>=9.0.0
6
+ numpy>=1.24.0
7
+ easyocr>=1.7.0
8
+ paddleocr>=2.6.0
9
+ paddlepaddle>=2.4.0
10
+ opencv-python>=4.7.0
11
+ 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
test_api.py ADDED
@@ -0,0 +1,70 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import requests
2
+ import json
3
+ import base64
4
+ from PIL import Image
5
+ import io
6
+ import argparse
7
+
8
+ def test_omniparser_api(api_url, image_path):
9
+ """
10
+ Test the OmniParser API by sending an image and displaying the results
11
+
12
+ Args:
13
+ api_url: URL of the OmniParser API
14
+ image_path: Path to the image file to test
15
+ """
16
+ print(f"Testing OmniParser API at: {api_url}")
17
+ print(f"Using image: {image_path}")
18
+
19
+ # Upload the image file
20
+ files = {'image': open(image_path, 'rb')}
21
+
22
+ try:
23
+ # Send request to the API
24
+ response = requests.post(api_url, files=files)
25
+
26
+ # Check if the request was successful
27
+ if response.status_code == 200:
28
+ # Parse the JSON response
29
+ result = response.json()
30
+
31
+ if "error" in result:
32
+ print(f"Error: {result['error']}")
33
+ return
34
+
35
+ # Display the parsed elements
36
+ print("\nParsed Elements:")
37
+ print("---------------")
38
+
39
+ elements = result["elements"]
40
+ for element in elements:
41
+ print(f"Element {element['id']}:")
42
+ print(f" Text: {element['text']}")
43
+ print(f" Caption: {element['caption']}")
44
+ print(f" Coordinates: {element['coordinates']}")
45
+ print(f" Interactable: {element['is_interactable']}")
46
+ print(f" Confidence: {element['confidence']}")
47
+ print("---")
48
+
49
+ # Display the visualization
50
+ if "visualization" in result:
51
+ print("\nVisualization received. Saving to 'visualization.png'")
52
+ img_data = base64.b64decode(result["visualization"])
53
+ img = Image.open(io.BytesIO(img_data))
54
+ img.save("visualization.png")
55
+ print("Visualization saved to 'visualization.png'")
56
+
57
+ else:
58
+ print(f"Error: Request failed with status code {response.status_code}")
59
+ print(response.text)
60
+
61
+ except Exception as e:
62
+ print(f"Error: {str(e)}")
63
+
64
+ if __name__ == "__main__":
65
+ parser = argparse.ArgumentParser(description="Test the OmniParser API")
66
+ parser.add_argument("--api_url", type=str, required=True, help="URL of the OmniParser API")
67
+ parser.add_argument("--image_path", type=str, required=True, help="Path to the image file to test")
68
+
69
+ args = parser.parse_args()
70
+ test_omniparser_api(args.api_url, args.image_path)