Netrava commited on
Commit
9a2e595
·
verified ·
1 Parent(s): 0ef105d

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +179 -106
app.py CHANGED
@@ -1,112 +1,185 @@
1
- from typing import Optional
2
- import spaces
3
- import gradio as gr
4
- import numpy as np
5
- import torch
6
- from PIL import Image
7
- import io
8
-
9
 
10
- import base64, os
11
- from util.utils import check_ocr_box, get_yolo_model, get_caption_model_processor, get_som_labeled_img
12
  import torch
 
 
13
  from PIL import Image
14
-
15
- from huggingface_hub import snapshot_download
16
-
17
- # Define repository and local directory
18
- repo_id = "microsoft/OmniParser-v2.0" # HF repo
19
- local_dir = "weights" # Target local directory
20
-
21
- # Download the entire repository
22
- snapshot_download(repo_id=repo_id, local_dir=local_dir)
23
-
24
- print(f"Repository downloaded to: {local_dir}")
25
-
26
-
27
- yolo_model = get_yolo_model(model_path='weights/icon_detect/model.pt')
28
- caption_model_processor = get_caption_model_processor(model_name="florence2", model_name_or_path="weights/icon_caption")
29
- # caption_model_processor = get_caption_model_processor(model_name="blip2", model_name_or_path="weights/icon_caption_blip2")
30
-
31
- MARKDOWN = """
32
- # OmniParser V2 for Pure Vision Based General GUI Agent 🔥
33
- <div>
34
- <a href="https://arxiv.org/pdf/2408.00203">
35
- <img src="https://img.shields.io/badge/arXiv-2408.00203-b31b1b.svg" alt="Arxiv" style="display:inline-block;">
36
- </a>
37
- </div>
38
-
39
- OmniParser is a screen parsing tool to convert general GUI screen to structured elements.
40
- """
41
-
42
- DEVICE = torch.device('cuda')
43
-
44
- @spaces.GPU
45
- @torch.inference_mode()
46
- # @torch.autocast(device_type="cuda", dtype=torch.bfloat16)
47
- def process(
48
- image_input,
49
- box_threshold,
50
- iou_threshold,
51
- use_paddleocr,
52
- imgsz
53
- ) -> Optional[Image.Image]:
54
-
55
- # image_save_path = 'imgs/saved_image_demo.png'
56
- # image_input.save(image_save_path)
57
- # image = Image.open(image_save_path)
58
- box_overlay_ratio = image_input.size[0] / 3200
59
- draw_bbox_config = {
60
- 'text_scale': 0.8 * box_overlay_ratio,
61
- 'text_thickness': max(int(2 * box_overlay_ratio), 1),
62
- 'text_padding': max(int(3 * box_overlay_ratio), 1),
63
- 'thickness': max(int(3 * box_overlay_ratio), 1),
64
- }
65
- # import pdb; pdb.set_trace()
66
-
67
- ocr_bbox_rslt, is_goal_filtered = check_ocr_box(image_input, display_img = False, output_bb_format='xyxy', goal_filtering=None, easyocr_args={'paragraph': False, 'text_threshold':0.9}, use_paddleocr=use_paddleocr)
68
- text, ocr_bbox = ocr_bbox_rslt
69
- dino_labled_img, label_coordinates, parsed_content_list = get_som_labeled_img(image_input, yolo_model, BOX_TRESHOLD = box_threshold, output_coord_in_ratio=True, ocr_bbox=ocr_bbox,draw_bbox_config=draw_bbox_config, caption_model_processor=caption_model_processor, ocr_text=text,iou_threshold=iou_threshold, imgsz=imgsz,)
70
- image = Image.open(io.BytesIO(base64.b64decode(dino_labled_img)))
71
- print('finish processing')
72
- parsed_content_list = '\n'.join([f'icon {i}: ' + str(v) for i,v in enumerate(parsed_content_list)])
73
- # parsed_content_list = str(parsed_content_list)
74
- return image, str(parsed_content_list)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
75
 
76
  with gr.Blocks() as demo:
77
- gr.Markdown(MARKDOWN)
78
  with gr.Row():
79
- with gr.Column():
80
- image_input_component = gr.Image(
81
- type='pil', label='Upload image')
82
- # set the threshold for removing the bounding boxes with low confidence, default is 0.05
83
- box_threshold_component = gr.Slider(
84
- label='Box Threshold', minimum=0.01, maximum=1.0, step=0.01, value=0.05)
85
- # set the threshold for removing the bounding boxes with large overlap, default is 0.1
86
- iou_threshold_component = gr.Slider(
87
- label='IOU Threshold', minimum=0.01, maximum=1.0, step=0.01, value=0.1)
88
- use_paddleocr_component = gr.Checkbox(
89
- label='Use PaddleOCR', value=True)
90
- imgsz_component = gr.Slider(
91
- label='Icon Detect Image Size', minimum=640, maximum=1920, step=32, value=640)
92
- submit_button_component = gr.Button(
93
- value='Submit', variant='primary')
94
- with gr.Column():
95
- image_output_component = gr.Image(type='pil', label='Image Output')
96
- text_output_component = gr.Textbox(label='Parsed screen elements', placeholder='Text Output')
97
-
98
- submit_button_component.click(
99
- fn=process,
100
- inputs=[
101
- image_input_component,
102
- box_threshold_component,
103
- iou_threshold_component,
104
- use_paddleocr_component,
105
- imgsz_component
106
- ],
107
- outputs=[image_output_component, text_output_component]
108
- )
109
-
110
- # demo.launch(debug=False, show_error=True, share=True)
111
- # demo.launch(share=True, server_port=7861, server_name='0.0.0.0')
112
- demo.queue().launch(share=False)
 
1
+ # app.py
2
+ # FINAL CORRECTED VERSION - Self-Contained
3
+ # This version includes all necessary functions and fixes the model loading error.
 
 
 
 
 
4
 
5
+ import os
 
6
  import torch
7
+ import gradio as gr
8
+ import numpy as np
9
  from PIL import Image
10
+ import json
11
+ from io import BytesIO
12
+
13
+ # Hugging Face Hub utilities for downloading model files
14
+ from huggingface_hub import hf_hub_download
15
+
16
+ # Core libraries for the models
17
+ from ultralytics import YOLO
18
+ from transformers import AutoProcessor, AutoModelForCausalLM, set_seed
19
+ from paddleocr import PaddleOCR
20
+
21
+ # Computer vision utilities
22
+ import supervision as sv
23
+
24
+ # Suppress unnecessary warnings for a cleaner log
25
+ import warnings
26
+ warnings.filterwarnings("ignore")
27
+
28
+ # --- Global Configuration ---
29
+ REPO_ID = "microsoft/OmniParser-v2.0"
30
+ DETECTION_MODEL_FILENAME = "weights/detection/model.pt" # Correct path in the original repo
31
+ CAPTION_MODEL_PATH = "weights/icon_caption"
32
+ DEVICE = "cuda" if torch.cuda.is_available() else "cpu"
33
+ # This specific revision of the Florence-2 model code is known to work on CPU.
34
+ FLORENCE_REVISION = "e149e62e3c88b64e42138e12b9a04683b5d1e26e"
35
+
36
+ print(f"INFO: Using device: {DEVICE}")
37
+ set_seed(42)
38
+
39
+ # =====================================================================================
40
+ # PART 2: AUTOMATED MODEL LOADING FROM THE HUB
41
+ # =====================================================================================
42
+
43
+ def load_detection_model():
44
+ print("INFO: Loading detection model...")
45
+ try:
46
+ # Note: The original repo structure might use a local path 'weights/detection/model.pt'
47
+ # hf_hub_download ensures it's available.
48
+ model_path = hf_hub_download(repo_id=REPO_ID, filename=DETECTION_MODEL_FILENAME)
49
+ model = YOLO(model_path)
50
+ print("INFO: Detection model loaded successfully.")
51
+ return model
52
+ except Exception as e:
53
+ print(f"ERROR: Failed to load detection model: {e}")
54
+ return None
55
+
56
+ def load_caption_model():
57
+ print("INFO: Loading captioning model...")
58
+ try:
59
+ # The caption model is based on Florence-2, but the fine-tuned weights are in the OmniParser repo.
60
+ # We load the weights from the subfolder but pin the *remote code* to a specific stable revision.
61
+ model = AutoModelForCausalLM.from_pretrained(
62
+ os.path.join(REPO_ID, CAPTION_MODEL_PATH), # Load from subfolder
63
+ torch_dtype=torch.float32,
64
+ trust_remote_code=True,
65
+ revision=FLORENCE_REVISION # Pin the remote code to the stable version
66
+ ).to(DEVICE)
67
+
68
+ processor = AutoProcessor.from_pretrained(
69
+ os.path.join(REPO_ID, CAPTION_MODEL_PATH), # Load from subfolder
70
+ trust_remote_code=True,
71
+ revision=FLORENCE_REVISION # Pin the remote code to the stable version
72
+ )
73
+ print("INFO: Captioning model loaded successfully.")
74
+ return model, processor
75
+ except Exception as e:
76
+ # This fallback is crucial for debugging
77
+ print(f"ERROR: Failed to load captioning model from primary path. Attempting fallback.")
78
+ try:
79
+ # Fallback to the main repo ID if the subfolder path fails
80
+ model = AutoModelForCausalLM.from_pretrained(
81
+ "microsoft/Florence-2-base-ft",
82
+ torch_dtype=torch.float32,
83
+ trust_remote_code=True,
84
+ revision=FLORENCE_REVISION
85
+ ).to(DEVICE)
86
+ processor = AutoProcessor.from_pretrained(
87
+ "microsoft/Florence-2-base-ft",
88
+ trust_remote_code=True,
89
+ revision=FLORENCE_REVISION
90
+ )
91
+ print("INFO: Captioning model loaded successfully via fallback.")
92
+ return model, processor
93
+ except Exception as fallback_e:
94
+ print(f"ERROR: Fallback also failed. Main error: {e}, Fallback error: {fallback_e}")
95
+ return None, None
96
+
97
+
98
+ def load_ocr_model():
99
+ print("INFO: Loading OCR model...")
100
+ try:
101
+ ocr_model = PaddleOCR(use_angle_cls=True, lang='en', use_gpu=(DEVICE == "cuda"), show_log=False)
102
+ print("INFO: OCR model loaded successfully.")
103
+ return ocr_model
104
+ except Exception as e:
105
+ print(f"ERROR: Failed to load OCR model: {e}")
106
+ return None
107
+
108
+ # --- Initialize Models at Application Startup ---
109
+ detection_model = load_detection_model()
110
+ caption_model, caption_processor = load_caption_model()
111
+ ocr_model = load_ocr_model()
112
+
113
+ # =====================================================================================
114
+ # PART 3: HELPER AND PREDICTION FUNCTIONS
115
+ # =====================================================================================
116
+
117
+ def run_captioning(image, text, model, processor):
118
+ prompt = f"<OD> <ref> {text} </ref>"
119
+ inputs = processor(text=prompt, images=image, return_tensors="pt").to(DEVICE)
120
+ generated_ids = model.generate(
121
+ input_ids=inputs["input_ids"],
122
+ pixel_values=inputs["pixel_values"],
123
+ max_new_tokens=1024,
124
+ num_beams=3,
125
+ do_sample=False
126
+ )
127
+ generated_text = processor.batch_decode(generated_ids, skip_special_tokens=False)
128
+ parsed_text = processor.post_process_generation(generated_text, task="<OD>", image_size=image.size)
129
+ final_caption_list = parsed_text.get('<OD>', {}).get('labels', [])
130
+ return final_caption_list[0] if final_caption_list else "No description available"
131
+
132
+ def predict_func(input_image: Image.Image):
133
+ if not all([detection_model, caption_model, ocr_model]):
134
+ # UI Error Message
135
+ return {"error": "A model failed to load. Please check the container logs for details."}
136
+
137
+ image_np = np.array(input_image.convert("RGB"))
138
+
139
+ # OCR
140
+ ocr_results = ocr_model.ocr(image_np, cls=True)[0]
141
+ ocr_texts = []
142
+ if ocr_results:
143
+ for line in ocr_results:
144
+ points, (text, conf) = line
145
+ x_coords = [p[0] for p in points]
146
+ y_coords = [p[1] for p in points]
147
+ ocr_texts.append({"box": [min(x_coords), min(y_coords), max(x_coords), max(y_coords)], "text": text})
148
+
149
+ # Object Detection
150
+ detection_results = detection_model(image_np, verbose=False)[0]
151
+ detections = sv.Detections.from_ultralytics(detection_results)
152
+
153
+ # Process and combine
154
+ parsed_elements = []
155
+ for i in range(len(detections)):
156
+ box = detections.xyxy[i].astype(int)
157
+ class_name = detection_model.model.names[detections.class_id[i]]
158
+
159
+ cropped_image = input_image.crop(tuple(box))
160
+ caption = run_captioning(cropped_image, f"Describe this UI element.", caption_model, caption_processor)
161
+
162
+ contained_text = " ".join([o["text"] for o in ocr_texts if (box[0] < o["box"][0] and box[1] < o["box"][1] and box[2] > o["box"][2] and box[3] > o["box"][3])])
163
+
164
+ parsed_elements.append({
165
+ "box_2d": box.tolist(), "class": class_name,
166
+ "ocr_text": contained_text.strip(), "description": caption
167
+ })
168
+
169
+ return {"parsed_elements": parsed_elements}
170
+
171
+ # =====================================================================================
172
+ # PART 4: GRADIO INTERFACE
173
+ # =====================================================================================
174
 
175
  with gr.Blocks() as demo:
176
+ gr.Markdown("# Microsoft OmniParser-v2 API Endpoint")
177
  with gr.Row():
178
+ image_input = gr.Image(type="pil", label="Input UI Screenshot")
179
+ json_output = gr.JSON(label="Parsed UI Elements")
180
+
181
+ submit_button = gr.Button("Parse UI", variant="primary")
182
+ submit_button.click(fn=predict_func, inputs=[image_input], outputs=[json_output], api_name="predict")
183
+
184
+ if __name__ == "__main__":
185
+ demo.launch()