OmniParser / app.py
Netrava's picture
Update app.py
07c0eb0 verified
Raw History Blame Contribute Delete
3.23 kB
import sys
import os
import gradio as gr
from PIL import Image
import io
import base64
# This is correct and necessary.
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
# --- START OF INITIALIZATION (Based on official gradio_demo.py) ---
# 1. Import the correct, low-level functions directly from utils.
from util.utils import check_ocr_box, get_yolo_model, get_caption_model_processor, get_som_labeled_img
print("Initializing models... this may take a few minutes on first startup.")
# 2. Load the models into memory, just like the official demo.
# Note: The demo expects the 'weights' folder to be present.
yolo_model = get_yolo_model(model_path='weights/icon_detect/best.pt')
caption_model_processor = get_caption_model_processor(model_name="florence2", model_name_or_path="weights/icon_caption_florence")
print("βœ… Models initialized successfully.")
# --- END OF INITIALIZATION ---
def process_image(image_input):
"""
This function processes the uploaded image using the pre-loaded models.
It is a simplified version of the 'process' function in the official demo.
"""
if image_input is None:
return None, "Please upload an image."
print(f"Processing image of size: {image_input.size}")
# Default values from the demo
box_threshold = 0.05
iou_threshold = 0.1
imgsz = 640
try:
# 1. Perform OCR
(text, ocr_bbox), _ = check_ocr_box(image_input, display_img=False, output_bb_format='xyxy', use_paddleocr=True)
# 2. Perform main parsing by calling the utility function
dino_labeled_img_base64, 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,
caption_model_processor=caption_model_processor,
ocr_text=text,
iou_threshold=iou_threshold,
imgsz=imgsz
)
# 3. Decode the output image and format the text
output_image = Image.open(io.BytesIO(base64.b64decode(dino_labeled_img_base64)))
output_text = '\n'.join([str(v) for v in parsed_content_list])
print("βœ… Processing finished successfully.")
return output_image, output_text
except Exception as e:
import traceback
traceback.print_exc()
return None, f"An error occurred during processing: {e}"
# --- Create and Launch the Gradio Interface ---
with gr.Blocks() as demo:
gr.Markdown("# OmniParser Demo")
with gr.Row():
with gr.Column():
image_input_component = gr.Image(type='pil', label='Upload Image')
submit_button_component = gr.Button(value='Submit', variant='primary')
with gr.Column():
image_output_component = gr.Image(type='pil', label='Parsed Image')
text_output_component = gr.Textbox(label='Parsed Screen Elements', placeholder='Text Output')
submit_button_component.click(
fn=process_image,
inputs=[image_input_component],
outputs=[image_output_component, text_output_component]
)
demo.launch()
print("--- Gradio UI launched ---")