File size: 8,239 Bytes
0469e08
 
 
 
 
ff98ab7
0469e08
 
 
 
 
 
aeda90f
3bd6fba
 
0469e08
 
d31c2af
0469e08
 
 
 
2c8e1ad
 
 
aeda90f
2c8e1ad
 
aeda90f
2c8e1ad
 
aeda90f
2c8e1ad
 
 
 
32056ff
3b0c073
3bd6fba
22ed136
 
 
32056ff
22ed136
3b0c073
b75ba06
0469e08
 
 
 
 
 
 
 
 
 
 
 
 
3bd6fba
0469e08
 
 
 
2bd9b5e
0469e08
 
 
3bd6fba
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5cbd5b0
5028d04
0469e08
3bd6fba
 
0469e08
 
 
 
 
 
 
 
 
 
 
b226556
22ed136
 
0469e08
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5028d04
0469e08
2bd9b5e
5028d04
5a458ea
2bd9b5e
 
5028d04
 
0469e08
 
5028d04
0469e08
 
3bd6fba
2bd9b5e
3bd6fba
5028d04
 
3bd6fba
782714c
 
3bd6fba
5028d04
 
5a458ea
ea2b32e
 
 
 
 
 
 
 
 
 
 
 
5a458ea
 
0469e08
3bd6fba
0469e08
 
 
 
 
 
 
 
 
 
 
5a458ea
0469e08
68a6103
818194d
5a458ea
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0469e08
 
 
 
 
 
5a458ea
5028d04
0469e08
5a458ea
0469e08
5a458ea
 
 
0469e08
 
5a458ea
0469e08
5a458ea
0469e08
5a458ea
0469e08
 
 
3bd6fba
0469e08
5a458ea
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
import base64
import json
from datetime import datetime
import gradio as gr
import torch
import spaces
from PIL import Image, ImageDraw
from qwen_vl_utils import process_vision_info
from transformers import Qwen2VLForConditionalGeneration, AutoProcessor
import ast
import os
import numpy as np
from huggingface_hub import hf_hub_download, list_repo_files
import boto3
from botocore.exceptions import NoCredentialsError

# Define constants
DESCRIPTION = "[ShowUI Demo](https://huggingface.co/showlab/ShowUI-2B)"
_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."
MIN_PIXELS = 256 * 28 * 28
MAX_PIXELS = 1344 * 28 * 28

# Specify the model repository and destination folder
model_repo = "showlab/ShowUI-2B"
destination_folder = "./showui-2b"

# Ensure the destination folder exists
os.makedirs(destination_folder, exist_ok=True)

# List all files in the repository
files = list_repo_files(repo_id=model_repo)

# Download each file to the destination folder
for file in files:
    file_path = hf_hub_download(repo_id=model_repo, filename=file, local_dir=destination_folder)
    print(f"Downloaded {file} to {file_path}")

model = Qwen2VLForConditionalGeneration.from_pretrained(
    destination_folder,
    torch_dtype=torch.bfloat16,
    device_map="cpu",
)

# Load the processor
processor = AutoProcessor.from_pretrained("Qwen/Qwen2-VL-2B-Instruct", min_pixels=MIN_PIXELS, max_pixels=MAX_PIXELS)

# Helper functions
def draw_point(image_input, point=None, radius=5):
    """Draw a point on the image."""
    if isinstance(image_input, str):
        image = Image.open(image_input)
    else:
        image = Image.fromarray(np.uint8(image_input))

    if point:
        x, y = point[0] * image.width, point[1] * image.height
        ImageDraw.Draw(image).ellipse((x - radius, y - radius, x + radius, y + radius), fill='red')
    return image

def array_to_image_path(image_array, session_id):
    """Save the uploaded image and return its path."""
    if image_array is None:
        raise ValueError("No image provided. Please upload an image before submitting.")
    img = Image.fromarray(np.uint8(image_array))
    filename = f"{session_id}.png"
    img.save(filename)
    return os.path.abspath(filename)

def upload_to_s3(file_name, bucket, object_name=None):
    """Upload a file to an S3 bucket."""
    if object_name is None:
        object_name = file_name

    s3 = boto3.client('s3')

    try:
        s3.upload_file(file_name, bucket, object_name)
        return True
    except FileNotFoundError:
        return False
    except NoCredentialsError:
        return False

@spaces.GPU
def run_showui(image, query, session_id):
    """Main function for inference."""
    image_path = array_to_image_path(image, session_id)
    
    messages = [
        {
            "role": "user",
            "content": [
                {"type": "text", "text": _SYSTEM},
                {"type": "image", "image": image_path, "min_pixels": MIN_PIXELS, "max_pixels": MAX_PIXELS},
                {"type": "text", "text": query}
            ],
        }
    ]

    global model
    model = model.to("cuda")
    
    text = processor.apply_chat_template(messages, tokenize=False, add_generation_prompt=True)
    image_inputs, video_inputs = process_vision_info(messages)
    inputs = processor(
        text=[text],
        images=image_inputs,
        videos=video_inputs,
        padding=True,
        return_tensors="pt"
    )
    inputs = inputs.to("cuda")

    generated_ids = model.generate(**inputs, max_new_tokens=128)
    generated_ids_trimmed = [
        out_ids[len(in_ids):] for in_ids, out_ids in zip(inputs.input_ids, generated_ids)
    ]
    output_text = processor.batch_decode(
        generated_ids_trimmed, skip_special_tokens=True, clean_up_tokenization_spaces=False
    )[0]

    click_xy = ast.literal_eval(output_text)
    result_image = draw_point(image_path, click_xy, radius=10)
    return result_image, str(click_xy), image_path

def save_and_upload_data(image_path, query, session_id, is_example_image, votes=None):
    """Save the data to a JSON file and upload to S3."""
    if is_example_image == "True":  # Updated to handle string values from Dropdown
        return

    votes = votes or {"upvotes": 0, "downvotes": 0}
    data = {
        "image_path": image_path,
        "query": query,
        "votes": votes,
        "timestamp": datetime.now().isoformat()
    }
    
    local_file_name = f"{session_id}.json"
    
    with open(local_file_name, "w") as f:
        json.dump(data, f)
    
    upload_to_s3(local_file_name, 'altair.storage', object_name=f"ootb/{local_file_name}")
    upload_to_s3(image_path, 'altair.storage', object_name=f"ootb/{os.path.basename(image_path)}")

    return data

# Examples with the `is_example` flag
examples = [
    ["./examples/app_store.png", "Download Kindle.", True],
    ["./examples/ios_setting.png", "Turn off Do not disturb.", True],
    ["./examples/apple_music.png", "Star to favorite.", True],
    ["./examples/map.png", "Boston.", True],
    ["./examples/wallet.png", "Scan a QR code.", True],
    ["./examples/word.png", "More shapes.", True],
    ["./examples/web_shopping.png", "Proceed to checkout.", True],
    ["./examples/web_forum.png", "Post my comment.", True],
    ["./examples/safari_google.png", "Click on search bar.", True],
]

def build_demo():
    with gr.Blocks() as demo:
        state_image_path = gr.State(value=None)
        state_session_id = gr.State(value=None)

        with gr.Row():
            with gr.Column(scale=3):
                imagebox = gr.Image(type="numpy", label="Input Screenshot")
                textbox = gr.Textbox(
                    show_label=True,
                    placeholder="Enter a query (e.g., 'Click Nahant')",
                    label="Query",
                )
                submit_btn = gr.Button(value="Submit", variant="primary")

                # Examples component
                gr.Examples(
                    examples=[[e[0], e[1]] for e in examples],
                    inputs=[imagebox, textbox],
                    outputs=[textbox],  # Only update the query textbox
                    examples_per_page=3,
                )

                # Add a hidden dropdown to pass the `is_example` flag
                is_example_dropdown = gr.Dropdown(
                    choices=["True", "False"],
                    value="False",
                    visible=False,
                    label="Is Example Image",
                )

                def set_is_example(query):
                    # Find the example and return its `is_example` flag
                    for _, example_query, is_example in examples:
                        if query.strip() == example_query.strip():
                            return str(is_example)  # Return as string for Dropdown compatibility
                    return "False"

                textbox.change(
                    set_is_example,
                    inputs=[textbox],
                    outputs=[is_example_dropdown],
                )

            with gr.Column(scale=8):
                output_img = gr.Image(type="pil", label="Output Image")
                output_coords = gr.Textbox(label="Clickable Coordinates")

                with gr.Row(equal_height=True):
                    clear_btn = gr.Button(value="🗑️ Clear", interactive=True)

            # Submit button logic
            submit_btn.click(
                lambda image, query, is_example: on_submit(image, query, is_example),
                inputs=[imagebox, textbox, is_example_dropdown],
                outputs=[output_img, output_coords, state_image_path, state_session_id],
            )

            # Clear button logic
            clear_btn.click(
                lambda: (None, None, None, None),
                inputs=None,
                outputs=[imagebox, textbox, output_img, output_coords, state_image_path, state_session_id],
            )

    return demo

if __name__ == "__main__":
    demo = build_demo()
    demo.launch()