techdrizzdev commited on
Commit
18c16bc
·
verified ·
1 Parent(s): 6f74afa

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +214 -0
app.py ADDED
@@ -0,0 +1,214 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import base64
2
+ import json
3
+ from datetime import datetime
4
+ import torch
5
+ import spaces
6
+ from PIL import Image, ImageDraw
7
+ from qwen_vl_utils import process_vision_info
8
+ from transformers import Qwen2VLForConditionalGeneration, AutoProcessor, AutoModelForCausalLM, AutoTokenizer
9
+ from PIL import Image
10
+ import ast
11
+ import os
12
+ from datetime import datetime
13
+ import numpy as np
14
+ from huggingface_hub import hf_hub_download, list_repo_files
15
+ import gradio as gr
16
+ import time
17
+
18
+ # Define constants
19
+ _SYSTEM = "Based on the screenshot of the page, I give a text description and you give its corresponding location. The coordinate represents a clickable location [x, y] for an element, which is a relative coordinate on the screenshot, scaled from 0 to 1."
20
+ MIN_PIXELS = 256 * 28 * 28
21
+ MAX_PIXELS = 1344 * 28 * 28
22
+
23
+ # Specify the model repository and destination folder
24
+ model_repo = "showlab/ShowUI-2B"
25
+ destination_folder = "./showui-2b"
26
+
27
+ # Ensure the destination folder exists
28
+ os.makedirs(destination_folder, exist_ok=True)
29
+
30
+ # List all files in the repository
31
+ files = list_repo_files(repo_id=model_repo)
32
+
33
+ # Download each file to the destination folder
34
+ for file in files:
35
+ file_path = hf_hub_download(repo_id=model_repo, filename=file, local_dir=destination_folder)
36
+ print(f"Downloaded {file} to {file_path}")
37
+
38
+ model = Qwen2VLForConditionalGeneration.from_pretrained(
39
+ "./showui-2b",
40
+ # "showlab/ShowUI-2B",
41
+ torch_dtype=torch.bfloat16,
42
+ device_map="cuda",
43
+ )
44
+
45
+ # Load the processor
46
+ processor = AutoProcessor.from_pretrained("Qwen/Qwen2-VL-2B-Instruct", min_pixels=MIN_PIXELS, max_pixels=MAX_PIXELS)
47
+
48
+ model_moon = AutoModelForCausalLM.from_pretrained("vikhyatk/moondream2", revision="2025-01-09", trust_remote_code=True, device_map={"": "cuda"})
49
+
50
+
51
+ # Helper functions
52
+ def draw_point(image_input, point=None, radius=5):
53
+ """Draw a point on the image."""
54
+ if isinstance(image_input, str):
55
+ image = Image.open(image_input)
56
+ else:
57
+ image = Image.fromarray(np.uint8(image_input))
58
+
59
+ if point:
60
+ x, y = point[0] * image.width, point[1] * image.height
61
+ ImageDraw.Draw(image).ellipse((x - radius, y - radius, x + radius, y + radius), fill="red")
62
+ return image
63
+
64
+
65
+ def array_to_image_path(image_array):
66
+ """Save the uploaded image and return its path."""
67
+ if image_array is None:
68
+ raise ValueError("No image provided. Please upload an image before submitting.")
69
+ img = Image.fromarray(np.uint8(image_array))
70
+ timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
71
+ filename = f"image_{timestamp}.png"
72
+ img.save(filename)
73
+ return os.path.abspath(filename)
74
+
75
+
76
+ def infer_moon(img, query):
77
+ start = time.time()
78
+ image = Image.fromarray(np.uint8(img))
79
+ points = model_moon.point(image, query)["points"]
80
+ converted_data = [round(points[0]["x"], 2), round(points[0]["y"], 2)]
81
+ end = time.time()
82
+ total_time = end - start
83
+ return converted_data, f"{round(total_time, 2)} seconds"
84
+
85
+
86
+ def infer_showui(image_path, query):
87
+ start = time.time()
88
+ messages = [
89
+ {
90
+ "role": "user",
91
+ "content": [
92
+ {"type": "text", "text": _SYSTEM},
93
+ {"type": "image", "image": image_path, "min_pixels": MIN_PIXELS, "max_pixels": MAX_PIXELS},
94
+ {"type": "text", "text": query},
95
+ ],
96
+ }
97
+ ]
98
+
99
+ text = processor.apply_chat_template(messages, tokenize=False, add_generation_prompt=True)
100
+ image_inputs, video_inputs = process_vision_info(messages)
101
+ inputs = processor(text=[text], images=image_inputs, videos=video_inputs, padding=True, return_tensors="pt")
102
+ inputs = inputs.to("cuda")
103
+
104
+ # Generate output
105
+ generated_ids = model.generate(**inputs, max_new_tokens=128)
106
+ generated_ids_trimmed = [out_ids[len(in_ids) :] for in_ids, out_ids in zip(inputs.input_ids, generated_ids)]
107
+ output_text = processor.batch_decode(generated_ids_trimmed, skip_special_tokens=True, clean_up_tokenization_spaces=False)[0]
108
+
109
+ # Parse the output into coordinates
110
+ click_xy = ast.literal_eval(output_text)
111
+ end = time.time()
112
+ total_time = end - start
113
+ return click_xy, f"{round(total_time, 2)} seconds"
114
+
115
+
116
+ def run(image, query):
117
+ """Main function for inference."""
118
+ image_path = array_to_image_path(image)
119
+ moon, time_taken_moon = infer_moon(image, query)
120
+ showui, time_taken_showui = infer_showui(image_path, query)
121
+
122
+ # Draw the point on the image
123
+ result_image = draw_point(image_path, showui, radius=10)
124
+ result_moon_image = draw_point(image_path, moon, radius=10)
125
+ return result_image, time_taken_showui, result_moon_image, time_taken_moon
126
+
127
+
128
+ def build_demo():
129
+ with gr.Blocks(title="ShowUI Demo", theme=gr.themes.Default()) as demo:
130
+ # State to store the consistent image path
131
+ state_image_path = gr.State(value=None)
132
+
133
+ with gr.Row():
134
+ with gr.Column(scale=3):
135
+ # Input components
136
+ imagebox = gr.Image(type="numpy", label="Input Screenshot")
137
+ textbox = gr.Textbox(
138
+ show_label=True,
139
+ placeholder="Enter a query (e.g., 'Click Nahant')",
140
+ label="Query",
141
+ )
142
+ submit_btn = gr.Button(value="Submit", variant="primary")
143
+
144
+ # Placeholder examples
145
+ gr.Examples(
146
+ examples=[
147
+ ["./examples/app_store.png", "Download Kindle."],
148
+ ["./examples/ios_setting.png", "Turn off Do not disturb."],
149
+ ["./examples/image_13.png", "Tap on vehicle search."],
150
+ ["./examples/map.png", "Boston."],
151
+ ["./examples/wallet.png", "Scan a QR code."],
152
+ ["./examples/word.png", "More shapes."],
153
+ ["./examples/web_shopping.png", "Proceed to checkout."],
154
+ ["./examples/web_forum.png", "Post my comment."],
155
+ ["./examples/safari_google.png", "Click on search bar."],
156
+ ],
157
+ inputs=[imagebox, textbox],
158
+ examples_per_page=3,
159
+ )
160
+
161
+ with gr.Column(scale=8):
162
+ # Output components
163
+ output_img1 = gr.Image(type="pil", label="Show UI Output")
164
+ output_time1 = gr.Text(label="showui inference time")
165
+ output_img2 = gr.Image(type="pil", label="Moon dream Output")
166
+ output_time2 = gr.Text(label="moondream inference time")
167
+
168
+ # Add a note below the images to explain the red point
169
+ gr.HTML(
170
+ """
171
+ <p><strong>Note:</strong> The <span style="color: red;">red point</span> on the output images represents the predicted clickable coordinates.</p>
172
+ """
173
+ )
174
+
175
+ # Buttons for voting, flagging, regenerating, and clearing
176
+ with gr.Row(elem_id="action-buttons", equal_height=True):
177
+ regenerate_btn = gr.Button(value="🔄 Regenerate", variant="secondary")
178
+ clear_btn = gr.Button(value="🗑️ Clear", interactive=True) # Combined Clear button
179
+
180
+ # Define button actions
181
+ def on_submit(image, query):
182
+ """Handle the submit button click."""
183
+ if image is None:
184
+ raise ValueError("No image provided. Please upload an image before submitting.")
185
+
186
+ # Generate consistent image path and store it in the state
187
+ image_path = array_to_image_path(image)
188
+ return run(image, query) + (image_path,)
189
+
190
+ submit_btn.click(
191
+ on_submit,
192
+ [imagebox, textbox],
193
+ [output_img1, output_time1, output_img2, output_time2, state_image_path],
194
+ )
195
+
196
+ clear_btn.click(
197
+ lambda: (None, None, None, None, None),
198
+ inputs=None,
199
+ outputs=[imagebox, textbox, output_img1, output_img2, state_image_path], # Clear all outputs
200
+ queue=False,
201
+ )
202
+
203
+ regenerate_btn.click(
204
+ lambda image, query, state_image_path: run(image, query),
205
+ [imagebox, textbox, state_image_path],
206
+ [output_img1, output_time1, output_img2, output_time2],
207
+ )
208
+
209
+ return demo
210
+
211
+
212
+ if __name__ == "__main__":
213
+ demo = build_demo()
214
+ demo.queue(api_open=False).launch(server_name="0.0.0.0", server_port=7860, ssr_mode=False, debug=True, share=True)