johnbridges commited on
Commit
a576c9d
·
verified ·
1 Parent(s): a727012

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +161 -128
app.py CHANGED
@@ -1,10 +1,7 @@
1
- import subprocess
2
- subprocess.run('pip install flash-attn --no-build-isolation', env={'FLASH_ATTENTION_SKIP_CUDA_BUILD': "TRUE"}, shell=True)
3
-
4
  import gradio as gr
5
  import json
6
  import os
7
- from typing import Any, List
8
  import spaces
9
 
10
  from PIL import Image, ImageDraw
@@ -12,104 +9,161 @@ import requests
12
  from transformers import AutoModelForImageTextToText, AutoProcessor
13
  from transformers.models.qwen2_vl.image_processing_qwen2_vl import smart_resize
14
  import torch
15
- import re
 
16
 
17
  # --- Configuration ---
18
  MODEL_ID = "Hcompany/Holo1-7B"
19
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
20
  # --- Model and Processor Loading (Load once) ---
21
- print(f"Loading model and processor for {MODEL_ID}...")
22
  model = None
23
  processor = None
24
  model_loaded = False
25
  load_error_message = ""
26
 
27
  try:
 
28
  model = AutoModelForImageTextToText.from_pretrained(
29
  MODEL_ID,
30
- torch_dtype=torch.bfloat16,
31
- trust_remote_code=True
32
- ).to("cuda")
33
  processor = AutoProcessor.from_pretrained(MODEL_ID, trust_remote_code=True)
34
  model_loaded = True
35
  print("Model and processor loaded successfully.")
36
  except Exception as e:
37
- load_error_message = f"Error loading model/processor: {e}\n" \
38
- "This might be due to network issues, an incorrect model ID, or missing dependencies (like flash_attention_2 if enabled by default in some config).\n" \
39
- "Ensure you have a stable internet connection and the necessary libraries installed."
 
 
40
  print(load_error_message)
 
41
 
42
- # --- Helper functions from the model card (or adapted) ---
43
-
44
- def get_localization_prompt(pil_image: Image.Image, instruction: str) -> List[dict[str, Any]]:
45
- """
46
- Prepares the prompt structure for the Holo1 model for localization tasks.
47
- The `pil_image` argument here is primarily for semantic completeness in the prompt structure,
48
- as the actual image tensor is handled by the processor later.
49
- """
50
- guidelines: str = "Localize an element on the GUI image according to my instructions and output a click position as Click(x, y) with x num pixels from the left edge and y num pixels from the top edge."
51
-
52
  return [
53
  {
54
  "role": "user",
55
  "content": [
56
- {
57
- "type": "image",
58
- "image": pil_image,
59
- },
60
- {"type": "text", "text": f"{guidelines}\n{instruction}"},
61
  ],
62
  }
63
  ]
64
 
65
- @spaces.GPU(duration=20)
66
  def run_inference_localization(
67
- messages_for_template: List[dict[str, Any]],
68
  pil_image_for_processing: Image.Image
69
  ) -> str:
70
- model.to("cuda")
71
- torch.cuda.set_device(0)
72
  """
73
- Runs inference using the Holo1 model.
74
- - messages_for_template: The prompt structure, potentially including the PIL image object
75
- (which apply_chat_template converts to an image tag).
76
- - pil_image_for_processing: The actual PIL image to be processed into tensors.
77
  """
78
- # 1. Apply chat template to messages. This will create the text part of the prompt,
79
- # including image tags if the image was part of `messages_for_template`.
80
- text_prompt = processor.apply_chat_template(
81
- messages_for_template,
82
- tokenize=False,
83
- add_generation_prompt=True
84
- )
85
 
86
- # 2. Process text and image together to get model inputs
87
- inputs = processor(
88
- text=[text_prompt],
89
- images=[pil_image_for_processing], # Provide the actual image data here
90
- padding=True,
91
- return_tensors="pt",
92
- )
93
- inputs = inputs.to(model.device)
94
-
95
- # 3. Generate response
96
- # Using do_sample=False for more deterministic output, as in the model card's structured output example
97
- generated_ids = model.generate(**inputs, max_new_tokens=128, do_sample=False)
98
-
99
- # 4. Trim input_ids from generated_ids to get only the generated part
100
- generated_ids_trimmed = [
101
- out_ids[len(in_ids):] for in_ids, out_ids in zip(inputs.input_ids, generated_ids)
102
- ]
103
-
104
- # 5. Decode the generated tokens
105
- decoded_output = processor.batch_decode(
106
- generated_ids_trimmed,
107
- skip_special_tokens=True,
108
- clean_up_tokenization_spaces=False
109
- )
110
-
111
- return decoded_output[0] if decoded_output else ""
112
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
113
 
114
  # --- Gradio processing function ---
115
  def predict_click_location(input_pil_image: Image.Image, instruction: str):
@@ -120,68 +174,52 @@ def predict_click_location(input_pil_image: Image.Image, instruction: str):
120
  if not instruction or instruction.strip() == "":
121
  return "No instruction provided. Please type an instruction.", input_pil_image.copy().convert("RGB")
122
 
123
- # 1. Prepare image: Resize according to model's image processor's expected properties
124
- # This ensures predicted coordinates match the (resized) image dimensions.
125
- image_proc_config = processor.image_processor
126
  try:
 
127
  resized_height, resized_width = smart_resize(
128
  input_pil_image.height,
129
  input_pil_image.width,
130
- factor=image_proc_config.patch_size * image_proc_config.merge_size,
131
- min_pixels=image_proc_config.min_pixels,
132
- max_pixels=image_proc_config.max_pixels,
133
  )
134
- # Using LANCZOS for resampling as it's generally good for downscaling.
135
- # The model card used `resample=None`, which might imply nearest or default.
136
- # For visual quality in the demo, LANCZOS is reasonable.
137
  resized_image = input_pil_image.resize(
138
- size=(resized_width, resized_height),
139
- resample=Image.Resampling.LANCZOS # type: ignore
140
  )
141
  except Exception as e:
142
  print(f"Error resizing image: {e}")
 
143
  return f"Error resizing image: {e}", input_pil_image.copy().convert("RGB")
144
 
145
- # 2. Create the prompt using the resized image (for correct image tagging context) and instruction
146
  messages = get_localization_prompt(resized_image, instruction)
147
 
148
- # 3. Run inference
149
- # Pass `messages` (which includes the image object for template processing)
150
- # and `resized_image` (for actual tensor conversion).
151
  try:
152
  coordinates_str = run_inference_localization(messages, resized_image)
153
  except Exception as e:
154
- print(f"Error during model inference: {e}")
155
  return f"Error during model inference: {e}", resized_image.copy().convert("RGB")
156
 
157
- # 4. Parse coordinates and draw on the image
158
- output_image_with_click = resized_image.copy().convert("RGB") # Ensure it's RGB for drawing
159
- parsed_coords = None
160
-
161
- # Expected format from the model: "Click(x, y)"
162
  match = re.search(r"Click\((\d+),\s*(\d+)\)", coordinates_str)
163
  if match:
164
  try:
165
  x = int(match.group(1))
166
  y = int(match.group(2))
167
- parsed_coords = (x, y)
168
-
169
  draw = ImageDraw.Draw(output_image_with_click)
170
- # Make the marker somewhat responsive to image size, but not too small/large
171
- radius = max(5, min(resized_width // 100, resized_height // 100, 15))
172
-
173
- # Define the bounding box for the ellipse (circle)
174
  bbox = (x - radius, y - radius, x + radius, y + radius)
175
- draw.ellipse(bbox, outline="red", width=max(2, radius // 4)) # Draw a red circle
176
  print(f"Predicted and drawn click at: ({x}, {y}) on resized image ({resized_width}x{resized_height})")
177
- except ValueError:
178
- print(f"Could not parse integers from coordinates: {coordinates_str}")
179
- # Keep original coordinates_str, output_image_with_click will be the resized image without a mark
180
  except Exception as e:
181
  print(f"Error drawing on image: {e}")
 
182
  else:
183
  print(f"Could not parse 'Click(x, y)' from model output: {coordinates_str}")
184
-
185
  return coordinates_str, output_image_with_click
186
 
187
  # --- Load Example Data ---
@@ -192,32 +230,19 @@ try:
192
  example_image = Image.open(requests.get(example_image_url, stream=True).raw)
193
  except Exception as e:
194
  print(f"Could not load example image from URL: {e}")
195
- # Create a placeholder image if loading fails, so Gradio example still works
196
  try:
197
  example_image = Image.new("RGB", (200, 150), color="lightgray")
198
  draw = ImageDraw.Draw(example_image)
199
  draw.text((10, 10), "Example image\nfailed to load", fill="black")
200
- except: # If PIL itself is an issue (unlikely here but good for robustness)
201
- pass
202
-
203
 
204
- # --- Gradio Interface Definition ---
205
- title = "Holo1-7B: Action VLM Localization Demo"
206
- description = """
207
- This demo showcases **Holo1-7B**, an Action Vision-Language Model developed by HCompany, fine-tuned from Qwen/Qwen2.5-VL-7B-Instruct.
208
- It's designed to interact with web interfaces like a human user. Here, we demonstrate its UI localization capability.
209
-
210
- **How to use:**
211
- 1. Upload an image (e.g., a screenshot of a UI, like the calendar example).
212
- 2. Provide a textual instruction (e.g., "Select July 14th as the check-out date").
213
- 3. The model will predict the click coordinates in the format `Click(x, y)`.
214
- 4. The predicted click point will be marked with a red circle on the (resized) image.
215
-
216
- The model processes a resized version of your input image. Coordinates are relative to this resized image.
217
- """
218
  article = f"""
219
  <p style='text-align: center'>
220
- Model: <a href='https://huggingface.co/{MODEL_ID}' target='_blank'>{MODEL_ID}</a> by HCompany |
221
  Paper: <a href='https://cdn.prod.website-files.com/67e2dbd9acff0c50d4c8a80c/683ec8095b353e8b38317f80_h_tech_report_v1.pdf' target='_blank'>HCompany Tech Report</a> |
222
  Blog: <a href='https://www.hcompany.ai/surfer-h' target='_blank'>Surfer-H Blog Post</a>
223
  </p>
@@ -227,26 +252,33 @@ if not model_loaded:
227
  with gr.Blocks() as demo:
228
  gr.Markdown(f"# <center>⚠️ Error: Model Failed to Load ⚠️</center>")
229
  gr.Markdown(f"<center>{load_error_message}</center>")
230
- gr.Markdown("<center>Please check the console output for more details. Reloading the space might help if it's a temporary issue.</center>")
231
  else:
232
  with gr.Blocks(theme=gr.themes.Soft()) as demo:
233
  gr.Markdown(f"<h1 style='text-align: center;'>{title}</h1>")
234
- # gr.Markdown(description)
235
 
236
  with gr.Row():
237
  with gr.Column(scale=1):
238
  input_image_component = gr.Image(type="pil", label="Input UI Image", height=400)
239
  instruction_component = gr.Textbox(
240
- label="Instruction",
241
  placeholder="e.g., Click the 'Login' button",
242
  info="Type the action you want the model to localize on the image."
243
  )
244
  submit_button = gr.Button("Localize Click", variant="primary")
245
-
246
  with gr.Column(scale=1):
247
- output_coords_component = gr.Textbox(label="Predicted Coordinates (Format: Click(x,y))", interactive=False)
248
- output_image_component = gr.Image(type="pil", label="Image with Predicted Click Point", height=400, interactive=False)
249
-
 
 
 
 
 
 
 
 
250
  if example_image:
251
  gr.Examples(
252
  examples=[[example_image, example_instruction]],
@@ -255,7 +287,7 @@ else:
255
  fn=predict_click_location,
256
  cache_examples="lazy",
257
  )
258
-
259
  gr.Markdown(article)
260
 
261
  submit_button.click(
@@ -265,4 +297,5 @@ else:
265
  )
266
 
267
  if __name__ == "__main__":
268
- demo.launch(debug=True)
 
 
 
 
 
1
  import gradio as gr
2
  import json
3
  import os
4
+ from typing import Any, List, Dict
5
  import spaces
6
 
7
  from PIL import Image, ImageDraw
 
9
  from transformers import AutoModelForImageTextToText, AutoProcessor
10
  from transformers.models.qwen2_vl.image_processing_qwen2_vl import smart_resize
11
  import torch
12
+ import re
13
+ import traceback
14
 
15
  # --- Configuration ---
16
  MODEL_ID = "Hcompany/Holo1-7B"
17
 
18
+ # --- Helpers (robust across different transformers versions) ---
19
+
20
+ def pick_device() -> str:
21
+ # Force CPU per request
22
+ return "cpu"
23
+
24
+ def apply_chat_template_compat(processor, messages: List[Dict[str, Any]]) -> str:
25
+ """
26
+ Works whether apply_chat_template lives on the processor or tokenizer,
27
+ or not at all (falls back to naive text join of 'text' contents).
28
+ """
29
+ tok = getattr(processor, "tokenizer", None)
30
+ if hasattr(processor, "apply_chat_template"):
31
+ return processor.apply_chat_template(messages, tokenize=False, add_generation_prompt=True)
32
+ if tok is not None and hasattr(tok, "apply_chat_template"):
33
+ return tok.apply_chat_template(messages, tokenize=False, add_generation_prompt=True)
34
+ # Fallback: concatenate visible text segments
35
+ texts = []
36
+ for m in messages:
37
+ for c in m.get("content", []):
38
+ if isinstance(c, dict) and c.get("type") == "text":
39
+ texts.append(c.get("text", ""))
40
+ return "\n".join(texts)
41
+
42
+ def batch_decode_compat(processor, token_id_batches, **kw):
43
+ tok = getattr(processor, "tokenizer", None)
44
+ if tok is not None and hasattr(tok, "batch_decode"):
45
+ return tok.batch_decode(token_id_batches, **kw)
46
+ if hasattr(processor, "batch_decode"):
47
+ return processor.batch_decode(token_id_batches, **kw)
48
+ raise AttributeError("No batch_decode available on processor or tokenizer.")
49
+
50
+ def get_image_proc_params(processor) -> Dict[str, int]:
51
+ """
52
+ Safely access image processor params with defaults that work for Qwen2-VL family.
53
+ """
54
+ ip = getattr(processor, "image_processor", None)
55
+ return {
56
+ "patch_size": getattr(ip, "patch_size", 14),
57
+ "merge_size": getattr(ip, "merge_size", 1),
58
+ "min_pixels": getattr(ip, "min_pixels", 256 * 256),
59
+ "max_pixels": getattr(ip, "max_pixels", 1280 * 1280),
60
+ }
61
+
62
+ def trim_generated(generated_ids, inputs):
63
+ """
64
+ Trim prompt tokens from generated tokens when input_ids exist.
65
+ """
66
+ in_ids = getattr(inputs, "input_ids", None)
67
+ if in_ids is None and isinstance(inputs, dict):
68
+ in_ids = inputs.get("input_ids", None)
69
+ if in_ids is None:
70
+ return [out_ids for out_ids in generated_ids]
71
+ return [out_ids[len(in_seq):] for in_seq, out_ids in zip(in_ids, generated_ids)]
72
+
73
  # --- Model and Processor Loading (Load once) ---
74
+ print(f"Loading model and processor for {MODEL_ID} (CPU only)...")
75
  model = None
76
  processor = None
77
  model_loaded = False
78
  load_error_message = ""
79
 
80
  try:
81
+ # CPU-friendly dtype; bf16 on CPU is spotty, so prefer float32
82
  model = AutoModelForImageTextToText.from_pretrained(
83
  MODEL_ID,
84
+ torch_dtype=torch.float32,
85
+ trust_remote_code=True
86
+ ).to(pick_device())
87
  processor = AutoProcessor.from_pretrained(MODEL_ID, trust_remote_code=True)
88
  model_loaded = True
89
  print("Model and processor loaded successfully.")
90
  except Exception as e:
91
+ load_error_message = (
92
+ f"Error loading model/processor: {e}\n"
93
+ "This might be due to network issues, an incorrect model ID, or incompatible library versions.\n"
94
+ "Check the full traceback in the Space logs."
95
+ )
96
  print(load_error_message)
97
+ traceback.print_exc()
98
 
99
+ # --- Prompt builder ---
100
+ def get_localization_prompt(pil_image: Image.Image, instruction: str) -> List[dict]:
101
+ guidelines: str = (
102
+ "Localize an element on the GUI image according to my instructions and "
103
+ "output a click position as Click(x, y) with x num pixels from the left edge "
104
+ "and y num pixels from the top edge."
105
+ )
 
 
 
106
  return [
107
  {
108
  "role": "user",
109
  "content": [
110
+ {"type": "image", "image": pil_image},
111
+ {"type": "text", "text": f"{guidelines}\n{instruction}"}
 
 
 
112
  ],
113
  }
114
  ]
115
 
116
+ # --- Inference (CPU) ---
117
  def run_inference_localization(
118
+ messages_for_template: List[dict[str, Any]],
119
  pil_image_for_processing: Image.Image
120
  ) -> str:
 
 
121
  """
122
+ CPU inference; robust to processor/tokenizer differences and logs full traceback on failure.
 
 
 
123
  """
124
+ try:
125
+ model.to(pick_device())
 
 
 
 
 
126
 
127
+ # 1) Build prompt text via robust helper
128
+ text_prompt = apply_chat_template_compat(processor, messages_for_template)
129
+
130
+ # 2) Prepare inputs (text + image)
131
+ inputs = processor(
132
+ text=[text_prompt],
133
+ images=[pil_image_for_processing],
134
+ padding=True,
135
+ return_tensors="pt",
136
+ )
137
+
138
+ # Move tensor inputs to the same device as model (CPU)
139
+ if isinstance(inputs, dict):
140
+ for k, v in list(inputs.items()):
141
+ if hasattr(v, "to"):
142
+ inputs[k] = v.to(model.device)
143
+
144
+ # 3) Generate (deterministic)
145
+ generated_ids = model.generate(
146
+ **inputs,
147
+ max_new_tokens=128,
148
+ do_sample=False,
149
+ )
 
 
 
150
 
151
+ # 4) Trim prompt tokens if possible
152
+ generated_ids_trimmed = trim_generated(generated_ids, inputs)
153
+
154
+ # 5) Decode via robust helper
155
+ decoded_output = batch_decode_compat(
156
+ processor,
157
+ generated_ids_trimmed,
158
+ skip_special_tokens=True,
159
+ clean_up_tokenization_spaces=False
160
+ )
161
+
162
+ return decoded_output[0] if decoded_output else ""
163
+ except Exception as e:
164
+ print(f"Error during model inference: {e}")
165
+ traceback.print_exc()
166
+ raise
167
 
168
  # --- Gradio processing function ---
169
  def predict_click_location(input_pil_image: Image.Image, instruction: str):
 
174
  if not instruction or instruction.strip() == "":
175
  return "No instruction provided. Please type an instruction.", input_pil_image.copy().convert("RGB")
176
 
177
+ # 1) Resize according to image processor params (safe defaults if missing)
 
 
178
  try:
179
+ ip = get_image_proc_params(processor)
180
  resized_height, resized_width = smart_resize(
181
  input_pil_image.height,
182
  input_pil_image.width,
183
+ factor=ip["patch_size"] * ip["merge_size"],
184
+ min_pixels=ip["min_pixels"],
185
+ max_pixels=ip["max_pixels"],
186
  )
 
 
 
187
  resized_image = input_pil_image.resize(
188
+ size=(resized_width, resized_height),
189
+ resample=Image.Resampling.LANCZOS
190
  )
191
  except Exception as e:
192
  print(f"Error resizing image: {e}")
193
+ traceback.print_exc()
194
  return f"Error resizing image: {e}", input_pil_image.copy().convert("RGB")
195
 
196
+ # 2) Build messages with image + instruction
197
  messages = get_localization_prompt(resized_image, instruction)
198
 
199
+ # 3) Run inference
 
 
200
  try:
201
  coordinates_str = run_inference_localization(messages, resized_image)
202
  except Exception as e:
 
203
  return f"Error during model inference: {e}", resized_image.copy().convert("RGB")
204
 
205
+ # 4) Parse coordinates and draw marker
206
+ output_image_with_click = resized_image.copy().convert("RGB")
 
 
 
207
  match = re.search(r"Click\((\d+),\s*(\d+)\)", coordinates_str)
208
  if match:
209
  try:
210
  x = int(match.group(1))
211
  y = int(match.group(2))
 
 
212
  draw = ImageDraw.Draw(output_image_with_click)
213
+ radius = max(5, min(resized_width // 100, resized_height // 100, 15))
 
 
 
214
  bbox = (x - radius, y - radius, x + radius, y + radius)
215
+ draw.ellipse(bbox, outline="red", width=max(2, radius // 4))
216
  print(f"Predicted and drawn click at: ({x}, {y}) on resized image ({resized_width}x{resized_height})")
 
 
 
217
  except Exception as e:
218
  print(f"Error drawing on image: {e}")
219
+ traceback.print_exc()
220
  else:
221
  print(f"Could not parse 'Click(x, y)' from model output: {coordinates_str}")
222
+
223
  return coordinates_str, output_image_with_click
224
 
225
  # --- Load Example Data ---
 
230
  example_image = Image.open(requests.get(example_image_url, stream=True).raw)
231
  except Exception as e:
232
  print(f"Could not load example image from URL: {e}")
233
+ traceback.print_exc()
234
  try:
235
  example_image = Image.new("RGB", (200, 150), color="lightgray")
236
  draw = ImageDraw.Draw(example_image)
237
  draw.text((10, 10), "Example image\nfailed to load", fill="black")
238
+ except Exception:
239
+ pass
 
240
 
241
+ # --- Gradio UI ---
242
+ title = "Holo1-7B: Action VLM Localization Demo (CPU)"
 
 
 
 
 
 
 
 
 
 
 
 
243
  article = f"""
244
  <p style='text-align: center'>
245
+ Model: <a href='https://huggingface.co/{MODEL_ID}' target='_blank'>{MODEL_ID}</a> by HCompany |
246
  Paper: <a href='https://cdn.prod.website-files.com/67e2dbd9acff0c50d4c8a80c/683ec8095b353e8b38317f80_h_tech_report_v1.pdf' target='_blank'>HCompany Tech Report</a> |
247
  Blog: <a href='https://www.hcompany.ai/surfer-h' target='_blank'>Surfer-H Blog Post</a>
248
  </p>
 
252
  with gr.Blocks() as demo:
253
  gr.Markdown(f"# <center>⚠️ Error: Model Failed to Load ⚠️</center>")
254
  gr.Markdown(f"<center>{load_error_message}</center>")
255
+ gr.Markdown("<center>See Space logs for the full traceback.</center>")
256
  else:
257
  with gr.Blocks(theme=gr.themes.Soft()) as demo:
258
  gr.Markdown(f"<h1 style='text-align: center;'>{title}</h1>")
 
259
 
260
  with gr.Row():
261
  with gr.Column(scale=1):
262
  input_image_component = gr.Image(type="pil", label="Input UI Image", height=400)
263
  instruction_component = gr.Textbox(
264
+ label="Instruction",
265
  placeholder="e.g., Click the 'Login' button",
266
  info="Type the action you want the model to localize on the image."
267
  )
268
  submit_button = gr.Button("Localize Click", variant="primary")
269
+
270
  with gr.Column(scale=1):
271
+ output_coords_component = gr.Textbox(
272
+ label="Predicted Coordinates (Format: Click(x, y))",
273
+ interactive=False
274
+ )
275
+ output_image_component = gr.Image(
276
+ type="pil",
277
+ label="Image with Predicted Click Point",
278
+ height=400,
279
+ interactive=False
280
+ )
281
+
282
  if example_image:
283
  gr.Examples(
284
  examples=[[example_image, example_instruction]],
 
287
  fn=predict_click_location,
288
  cache_examples="lazy",
289
  )
290
+
291
  gr.Markdown(article)
292
 
293
  submit_button.click(
 
297
  )
298
 
299
  if __name__ == "__main__":
300
+ # CPU Spaces can be slow; keep debug True for logs
301
+ demo.launch(debug=True)