Netrava commited on
Commit
91c1dbf
·
verified ·
1 Parent(s): a664674

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +150 -0
app.py ADDED
@@ -0,0 +1,150 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # app.py
2
+ # Final, definitive version.
3
+
4
+ import os
5
+ import torch
6
+ import gradio as gr
7
+ import numpy as np
8
+ from PIL import Image
9
+ import json
10
+
11
+ from huggingface_hub import hf_hub_download
12
+ from ultralytics import YOLO
13
+ from transformers import AutoProcessor, AutoModelForCausalLM, set_seed
14
+ from paddleocr import PaddleOCR
15
+ import supervision as sv
16
+ import warnings
17
+
18
+ warnings.filterwarnings("ignore")
19
+
20
+ # --- Global Configuration ---
21
+ REPO_ID = "microsoft/OmniParser-v2.0"
22
+ DETECTION_MODEL_FILENAME = "icon_detect/model.pt"
23
+ CAPTION_MODEL_SUBFOLDER = "icon_caption"
24
+ DEVICE = "cuda" if torch.cuda.is_available() else "cpu"
25
+ print(f"INFO: Using device: {DEVICE}")
26
+ set_seed(42)
27
+
28
+ # --- Model Loading ---
29
+ def load_detection_model():
30
+ print("INFO: Loading detection model...")
31
+ try:
32
+ model_path = hf_hub_download(repo_id=REPO_ID, filename=DETECTION_MODEL_FILENAME)
33
+ model = YOLO(model_path)
34
+ print("INFO: Detection model loaded successfully.")
35
+ return model
36
+ except Exception as e:
37
+ print(f"ERROR: Failed to load detection model: {e}")
38
+ return None
39
+
40
+ def load_caption_model():
41
+ print("INFO: Loading captioning model...")
42
+ try:
43
+ model = AutoModelForCausalLM.from_pretrained(
44
+ REPO_ID, subfolder=CAPTION_MODEL_SUBFOLDER, torch_dtype=torch.float32,
45
+ trust_remote_code=True, attn_implementation="eager"
46
+ ).to(DEVICE)
47
+ processor = AutoProcessor.from_pretrained(
48
+ REPO_ID, subfolder=CAPTION_MODEL_SUBFOLDER, trust_remote_code=True
49
+ )
50
+ print("INFO: Captioning model loaded successfully.")
51
+ return model, processor
52
+ except Exception as e:
53
+ print(f"ERROR: Failed to load captioning model: {e}")
54
+ return None, None
55
+
56
+ def load_ocr_model():
57
+ print("INFO: Loading OCR model...")
58
+ try:
59
+ ocr_model = PaddleOCR(use_angle_cls=True, lang='en', use_gpu=(DEVICE == "cuda"), show_log=False)
60
+ print("INFO: OCR model loaded successfully.")
61
+ return ocr_model
62
+ except Exception as e:
63
+ print(f"ERROR: Failed to load OCR model: {e}")
64
+ return None
65
+
66
+ detection_model = load_detection_model()
67
+ caption_model, caption_processor = load_caption_model()
68
+ ocr_model = load_ocr_model()
69
+
70
+ # --- Inference Pipeline ---
71
+ def run_captioning(image, text, model, processor):
72
+ prompt = f"<OD> <ref> {text} </ref>"
73
+ inputs = processor(text=prompt, images=image, return_tensors="pt").to(DEVICE)
74
+ generated_ids = model.generate(
75
+ input_ids=inputs["input_ids"], pixel_values=inputs["pixel_values"],
76
+ max_new_tokens=1024, num_beams=3, do_sample=False
77
+ )
78
+ generated_text = processor.batch_decode(generated_ids, skip_special_tokens=False)
79
+ parsed_text = processor.post_process_generation(generated_text, task="<OD>", image_size=image.size)
80
+ final_caption_list = parsed_text.get('<OD>', {}).get('labels', [])
81
+ return final_caption_list[0] if final_caption_list else "No description available"
82
+
83
+ def is_box_contained(outer_box, inner_box):
84
+ return (outer_box[0] <= inner_box[0] and outer_box[1] <= inner_box[1] and
85
+ outer_box[2] >= inner_box[2] and outer_box[3] >= inner_box[3])
86
+
87
+ def predict(input_image: Image.Image):
88
+ if not all([detection_model, caption_model, ocr_model]):
89
+ error_messages = []
90
+ if not detection_model: error_messages.append("Detection model failed.")
91
+ if not caption_model: error_messages.append("Captioning model failed.")
92
+ if not ocr_model: error_messages.append("OCR model failed.")
93
+ return {"error": " ".join(error_messages) + " Check container logs."}
94
+
95
+ image_np = np.array(input_image.convert("RGB"))
96
+
97
+ ocr_results = ocr_model.ocr(image_np, cls=True)[0]
98
+ ocr_texts = []
99
+ if ocr_results:
100
+ for line in ocr_results:
101
+ points, (text, conf) = line
102
+ x_coords = [p[0] for p in points]
103
+ y_coords = [p[1] for p in points]
104
+ ocr_texts.append({"box": [min(x_coords), min(y_coords), max(x_coords), max(y_coords)], "text": text, "conf": conf})
105
+
106
+ detection_results = detection_model(image_np, verbose=False)[0]
107
+ detections = sv.Detections.from_ultralytics(detection_results)
108
+
109
+ parsed_elements = []
110
+ element_id_counter = 0
111
+
112
+ for i in range(len(detections)):
113
+ box = detections.xyxy[i].astype(int)
114
+ confidence = detections.confidence[i]
115
+ class_name = detection_model.model.names[detections.class_id[i]]
116
+
117
+ cropped_image = input_image.crop(tuple(box))
118
+ caption = run_captioning(cropped_image, f"Describe this UI element.", caption_model, caption_processor)
119
+
120
+ contained_text = " ".join([o["text"] for o in ocr_texts if is_box_contained(box.tolist(), o["box"])])
121
+
122
+ parsed_elements.append({
123
+ "id": element_id_counter, "box_2d": box.tolist(), "type": class_name,
124
+ "text": contained_text.strip(), "description": caption, "confidence": float(confidence)
125
+ })
126
+ element_id_counter += 1
127
+
128
+ for ocr in ocr_texts:
129
+ if not any(is_box_contained(el["box_2d"], ocr["box"]) for el in parsed_elements):
130
+ parsed_elements.append({
131
+ "id": element_id_counter, "box_2d": [int(p) for p in ocr["box"]], "type": "text_label",
132
+ "text": ocr["text"], "description": "A text label.", "confidence": float(ocr["conf"])
133
+ })
134
+ element_id_counter += 1
135
+
136
+ return {"parsed_elements": parsed_elements}
137
+
138
+ # --- Gradio Interface ---
139
+ with gr.Blocks(css="footer {display: none!important}") as demo:
140
+ gr.Markdown("# Microsoft OmniParser-v2 API Endpoint\nUpload a UI screenshot to get a parsed JSON output.")
141
+ with gr.Row():
142
+ image_input = gr.Image(type="pil", label="Input UI Screenshot")
143
+ json_output = gr.JSON(label="Parsed UI Elements")
144
+
145
+ submit_button = gr.Button("Parse UI", variant="primary")
146
+ submit_button.click(fn=predict, inputs=[image_input], outputs=[json_output], api_name="predict")
147
+
148
+ # The Dockerfile handles how this is run, but demo.launch() is standard.
149
+ if __name__ == '__main__':
150
+ demo.launch()