Netrava commited on
Commit
07c0eb0
Β·
verified Β·
1 Parent(s): c95c023

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +73 -38
app.py CHANGED
@@ -1,56 +1,91 @@
1
  import sys
2
  import os
3
  import gradio as gr
4
- import json
5
- import torch
 
6
 
7
- # This part is correct and finds the project files.
8
  sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
9
 
10
- # --- START OF THE FINAL, VERIFIED INITIALIZATION ---
11
 
12
- # 1. Import the class and the CORRECTLY NAMED config dictionary and helper function.
13
- from util.omniparser import Omniparser
14
- from util.utils import MODEL_CONFIG, get_model_path # CORRECTED VARIABLE NAME
15
 
16
- print("Initializing...")
17
 
18
- # 2. Use the helper function to get the full model path/key.
19
- model_name_key = get_model_path("omniparser-v2-effnet")
20
- print(f"Resolved model name to key: {model_name_key}")
 
21
 
22
- # 3. Get the correct configuration dictionary from the MODEL_CONFIG constant.
23
- config = MODEL_CONFIG[model_name_key] # CORRECTED VARIABLE NAME
24
- print("βœ… Configuration dictionary loaded successfully.")
25
 
26
- # 4. Pass the CONFIG DICTIONARY to the class constructor.
27
- parser_instance = Omniparser(config)
28
- print("βœ… OmniParser model loaded successfully.")
29
 
30
- # --- END OF THE FINAL, VERIFIED INITIALIZATION ---
31
 
32
- def parse_document(input_file):
33
- if input_file is None: return "Please upload a document.", "{}"
34
- print(f"Processing file: {input_file.name}")
 
 
 
 
 
 
 
 
 
 
 
 
35
  try:
36
- # Use the instantiated parser
37
- result = parser_instance.parse(input_file.name)
38
- markdown_text = result[0].get("text", "Markdown not found.") if isinstance(result, list) and result else "Output format not as expected."
39
- return markdown_text, json.dumps(result, indent=2)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
40
  except Exception as e:
41
  import traceback
42
  traceback.print_exc()
43
- return f"An error occurred during parsing: {e}", f"Error: {e}"
44
-
45
- iface = gr.Interface(
46
- fn=parse_document,
47
- inputs=gr.File(label="Upload Document"),
48
- outputs=[
49
- gr.Markdown(label="Parsed Markdown Content"),
50
- gr.Code(label="Full JSON Output", language="json")
51
- ],
52
- title="Microsoft OmniParser Demo",
53
- description="This deployment is now fully functional."
54
- )
55
- iface.launch()
 
 
 
 
 
 
 
 
56
  print("--- Gradio UI launched ---")
 
1
  import sys
2
  import os
3
  import gradio as gr
4
+ from PIL import Image
5
+ import io
6
+ import base64
7
 
8
+ # This is correct and necessary.
9
  sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
10
 
11
+ # --- START OF INITIALIZATION (Based on official gradio_demo.py) ---
12
 
13
+ # 1. Import the correct, low-level functions directly from utils.
14
+ from util.utils import check_ocr_box, get_yolo_model, get_caption_model_processor, get_som_labeled_img
 
15
 
16
+ print("Initializing models... this may take a few minutes on first startup.")
17
 
18
+ # 2. Load the models into memory, just like the official demo.
19
+ # Note: The demo expects the 'weights' folder to be present.
20
+ yolo_model = get_yolo_model(model_path='weights/icon_detect/best.pt')
21
+ caption_model_processor = get_caption_model_processor(model_name="florence2", model_name_or_path="weights/icon_caption_florence")
22
 
23
+ print("βœ… Models initialized successfully.")
 
 
24
 
25
+ # --- END OF INITIALIZATION ---
 
 
26
 
 
27
 
28
+ def process_image(image_input):
29
+ """
30
+ This function processes the uploaded image using the pre-loaded models.
31
+ It is a simplified version of the 'process' function in the official demo.
32
+ """
33
+ if image_input is None:
34
+ return None, "Please upload an image."
35
+
36
+ print(f"Processing image of size: {image_input.size}")
37
+
38
+ # Default values from the demo
39
+ box_threshold = 0.05
40
+ iou_threshold = 0.1
41
+ imgsz = 640
42
+
43
  try:
44
+ # 1. Perform OCR
45
+ (text, ocr_bbox), _ = check_ocr_box(image_input, display_img=False, output_bb_format='xyxy', use_paddleocr=True)
46
+
47
+ # 2. Perform main parsing by calling the utility function
48
+ dino_labeled_img_base64, label_coordinates, parsed_content_list = get_som_labeled_img(
49
+ image_input,
50
+ yolo_model,
51
+ BOX_TRESHOLD=box_threshold,
52
+ output_coord_in_ratio=True,
53
+ ocr_bbox=ocr_bbox,
54
+ caption_model_processor=caption_model_processor,
55
+ ocr_text=text,
56
+ iou_threshold=iou_threshold,
57
+ imgsz=imgsz
58
+ )
59
+
60
+ # 3. Decode the output image and format the text
61
+ output_image = Image.open(io.BytesIO(base64.b64decode(dino_labeled_img_base64)))
62
+ output_text = '\n'.join([str(v) for v in parsed_content_list])
63
+
64
+ print("βœ… Processing finished successfully.")
65
+ return output_image, output_text
66
+
67
  except Exception as e:
68
  import traceback
69
  traceback.print_exc()
70
+ return None, f"An error occurred during processing: {e}"
71
+
72
+
73
+ # --- Create and Launch the Gradio Interface ---
74
+ with gr.Blocks() as demo:
75
+ gr.Markdown("# OmniParser Demo")
76
+ with gr.Row():
77
+ with gr.Column():
78
+ image_input_component = gr.Image(type='pil', label='Upload Image')
79
+ submit_button_component = gr.Button(value='Submit', variant='primary')
80
+ with gr.Column():
81
+ image_output_component = gr.Image(type='pil', label='Parsed Image')
82
+ text_output_component = gr.Textbox(label='Parsed Screen Elements', placeholder='Text Output')
83
+
84
+ submit_button_component.click(
85
+ fn=process_image,
86
+ inputs=[image_input_component],
87
+ outputs=[image_output_component, text_output_component]
88
+ )
89
+
90
+ demo.launch()
91
  print("--- Gradio UI launched ---")