gaoyu1314 commited on
Commit
54d34a5
·
verified ·
1 Parent(s): 25bf480

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +45 -41
app.py CHANGED
@@ -1,39 +1,48 @@
1
  from typing import Optional
2
-
3
  import gradio as gr
4
  import numpy as np
5
  import torch
6
  from PIL import Image
7
  import io
 
 
8
  import base64, os
9
  from util.utils import check_ocr_box, get_yolo_model, get_caption_model_processor, get_som_labeled_img
10
  import torch
11
  from PIL import Image
12
- import ast
13
 
14
- # 定义模型路径,使用相对路径,并使用 os.path.join 确保跨平台兼容性
15
- MODEL_DIR = 'weights'
16
- YOLO_MODEL_PATH = os.path.join(MODEL_DIR, 'icon_detect', 'model.pt')
17
- CAPTION_MODEL_PATH = os.path.join(MODEL_DIR, 'icon_caption')
18
- # BLIP2_CAPTION_MODEL_PATH = os.path.join(MODEL_DIR, 'icon_caption_blip2') # 如果使用 BLIP2 模型
 
 
 
 
 
 
19
 
20
  yolo_model = get_yolo_model(model_path='weights/icon_detect/model.pt')
21
- caption_model_processor = get_caption_model_processor(model_name="florence2", model_name_or_path=CAPTION_MODEL_PATH)
22
  # caption_model_processor = get_caption_model_processor(model_name="blip2", model_name_or_path="weights/icon_caption_blip2")
23
 
24
  MARKDOWN = """
25
- # OmniParser for Pure Vision Based General GUI Agent嘻嘻 🔥
26
  <div>
27
  <a href="https://arxiv.org/pdf/2408.00203">
28
  <img src="https://img.shields.io/badge/arXiv-2408.00203-b31b1b.svg" alt="Arxiv" style="display:inline-block;">
29
  </a>
30
  </div>
31
-
32
  OmniParser is a screen parsing tool to convert general GUI screen to structured elements.
33
  """
34
 
35
  DEVICE = torch.device('cuda')
36
 
 
 
 
37
  def process(
38
  image_input,
39
  box_threshold,
@@ -42,52 +51,45 @@ def process(
42
  imgsz
43
  ) -> Optional[Image.Image]:
44
 
45
- image_save_path = 'imgs/saved_image_demo.png'
46
- image_input.save(image_save_path)
47
- image = Image.open(image_save_path)
48
- box_overlay_ratio = image.size[0] / 3200
49
  draw_bbox_config = {
50
  'text_scale': 0.8 * box_overlay_ratio,
51
  'text_thickness': max(int(2 * box_overlay_ratio), 1),
52
  'text_padding': max(int(3 * box_overlay_ratio), 1),
53
  'thickness': max(int(3 * box_overlay_ratio), 1),
54
  }
 
55
 
56
- ocr_bbox_rslt, is_goal_filtered = check_ocr_box(image_save_path, display_img = False, output_bb_format='xyxy', goal_filtering=None, easyocr_args={'paragraph': False, 'text_threshold':0.9}, use_paddleocr=use_paddleocr)
57
- text, ocr_bbox_input = ocr_bbox_rslt
58
-
59
- # Correctly handle ocr_bbox and ocr_text
60
- if ocr_bbox_input is None or not ocr_bbox_input:
61
- ocr_bbox = []
62
- ocr_text = []
63
- else:
64
- ocr_bbox = []
65
- for box_str in ocr_bbox_input:
66
- try:
67
- # 使用 eval(),但要非常小心!
68
- box = eval(box_str) # 转换为元组
69
- ocr_bbox.append(box)
70
- except (SyntaxError, NameError, TypeError, ValueError):
71
- print(f"警告:无法解析边界框字符串:{box_str}") # 打印警告信息,但继续处理其他框
72
- continue # 跳过错误的框
73
- ocr_text = text # 使用 check_ocr_box 返回的 text
74
-
75
- dino_labled_img, label_coordinates, parsed_content_list = get_som_labeled_img(image_save_path, 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=ocr_text, iou_threshold=iou_threshold, imgsz=imgsz)
76
  image = Image.open(io.BytesIO(base64.b64decode(dino_labled_img)))
77
  print('finish processing')
78
  parsed_content_list = '\n'.join([f'icon {i}: ' + str(v) for i,v in enumerate(parsed_content_list)])
 
79
  return image, str(parsed_content_list)
80
 
81
  with gr.Blocks() as demo:
82
  gr.Markdown(MARKDOWN)
83
  with gr.Row():
84
  with gr.Column():
85
- image_input_component = gr.Image(type='pil', label='Upload image')
86
- box_threshold_component = gr.Slider(label='Box Threshold', minimum=0.01, maximum=1.0, step=0.01, value=0.05)
87
- iou_threshold_component = gr.Slider(label='IOU Threshold', minimum=0.01, maximum=1.0, step=0.01, value=0.1)
88
- use_paddleocr_component = gr.Checkbox(label='Use PaddleOCR', value=True)
89
- imgsz_component = gr.Slider(label='Icon Detect Image Size', minimum=640, maximum=1920, step=32, value=640)
90
- submit_button_component = gr.Button(value='Submit', variant='primary')
 
 
 
 
 
 
 
 
91
  with gr.Column():
92
  image_output_component = gr.Image(type='pil', label='Image Output')
93
  text_output_component = gr.Textbox(label='Parsed screen elements', placeholder='Text Output')
@@ -104,4 +106,6 @@ with gr.Blocks() as demo:
104
  outputs=[image_output_component, text_output_component]
105
  )
106
 
107
- demo.launch(share=True, server_port=7861, server_name='0.0.0.0')
 
 
 
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
  OmniParser is a screen parsing tool to convert general GUI screen to structured elements.
39
  """
40
 
41
  DEVICE = torch.device('cuda')
42
 
43
+ @spaces.GPU
44
+ @torch.inference_mode()
45
+ # @torch.autocast(device_type="cuda", dtype=torch.bfloat16)
46
  def process(
47
  image_input,
48
  box_threshold,
 
51
  imgsz
52
  ) -> Optional[Image.Image]:
53
 
54
+ # image_save_path = 'imgs/saved_image_demo.png'
55
+ # image_input.save(image_save_path)
56
+ # image = Image.open(image_save_path)
57
+ box_overlay_ratio = image_input.size[0] / 3200
58
  draw_bbox_config = {
59
  'text_scale': 0.8 * box_overlay_ratio,
60
  'text_thickness': max(int(2 * box_overlay_ratio), 1),
61
  'text_padding': max(int(3 * box_overlay_ratio), 1),
62
  'thickness': max(int(3 * box_overlay_ratio), 1),
63
  }
64
+ # import pdb; pdb.set_trace()
65
 
66
+ 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)
67
+ text, ocr_bbox = ocr_bbox_rslt
68
+ 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,)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
69
  image = Image.open(io.BytesIO(base64.b64decode(dino_labled_img)))
70
  print('finish processing')
71
  parsed_content_list = '\n'.join([f'icon {i}: ' + str(v) for i,v in enumerate(parsed_content_list)])
72
+ # parsed_content_list = str(parsed_content_list)
73
  return image, str(parsed_content_list)
74
 
75
  with gr.Blocks() as demo:
76
  gr.Markdown(MARKDOWN)
77
  with gr.Row():
78
  with gr.Column():
79
+ image_input_component = gr.Image(
80
+ type='pil', label='Upload image')
81
+ # set the threshold for removing the bounding boxes with low confidence, default is 0.05
82
+ box_threshold_component = gr.Slider(
83
+ label='Box Threshold', minimum=0.01, maximum=1.0, step=0.01, value=0.05)
84
+ # set the threshold for removing the bounding boxes with large overlap, default is 0.1
85
+ iou_threshold_component = gr.Slider(
86
+ label='IOU Threshold', minimum=0.01, maximum=1.0, step=0.01, value=0.1)
87
+ use_paddleocr_component = gr.Checkbox(
88
+ label='Use PaddleOCR', value=True)
89
+ imgsz_component = gr.Slider(
90
+ label='Icon Detect Image Size', minimum=640, maximum=1920, step=32, value=640)
91
+ submit_button_component = gr.Button(
92
+ value='Submit', variant='primary')
93
  with gr.Column():
94
  image_output_component = gr.Image(type='pil', label='Image Output')
95
  text_output_component = gr.Textbox(label='Parsed screen elements', placeholder='Text Output')
 
106
  outputs=[image_output_component, text_output_component]
107
  )
108
 
109
+ # demo.launch(debug=False, show_error=True, share=True)
110
+ # demo.launch(share=True, server_port=7861, server_name='0.0.0.0')
111
+ demo.queue().launch(share=False)