prithivMLmods commited on
Commit
c203efc
·
verified ·
1 Parent(s): c3486a1

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +164 -40
app.py CHANGED
@@ -3,7 +3,7 @@ import random
3
  import uuid
4
  import json
5
  import time
6
- import asyncio
7
  from threading import Thread
8
 
9
  import gradio as gr
@@ -12,7 +12,7 @@ import torch
12
  import numpy as np
13
  from PIL import Image
14
  import cv2
15
- import requests
16
 
17
  from transformers import (
18
  Qwen3VLMoeForConditionalGeneration,
@@ -50,7 +50,7 @@ processor_q3vl = AutoProcessor.from_pretrained(MODEL_ID_Q3VL, trust_remote_code=
50
  model_q3vl = Qwen3VLMoeForConditionalGeneration.from_pretrained(
51
  MODEL_ID_Q3VL,
52
  trust_remote_code=True,
53
- dtype=torch.float16
54
  ).to(device).eval()
55
 
56
 
@@ -93,7 +93,6 @@ def generate_image(text: str, image: Image.Image,
93
  messages = [{"role": "user", "content": [{"type": "image"}, {"type": "text", "text": text}]}]
94
  prompt_full = processor_q3vl.apply_chat_template(messages, tokenize=False, add_generation_prompt=True)
95
 
96
- # FIX: Removed truncation=True and max_length to prevent the ValueError
97
  inputs = processor_q3vl(
98
  text=[prompt_full], images=[image], return_tensors="pt", padding=True
99
  ).to(device)
@@ -129,14 +128,12 @@ def generate_video(text: str, video_path: str,
129
 
130
  messages = [{"role": "user", "content": [{"type": "text", "text": text}]}]
131
  images_for_processor = []
132
- # Add an <|image|> placeholder for each frame in the message
133
  for frame, timestamp in frames_with_ts:
134
- messages[0]["content"].insert(0, {"type": "image"}) # Insert at beginning to match common patterns
135
  images_for_processor.append(frame)
136
 
137
  prompt_full = processor_q3vl.apply_chat_template(messages, tokenize=False, add_generation_prompt=True)
138
 
139
- # FIX: Removed truncation=True and max_length to prevent the ValueError
140
  inputs = processor_q3vl(
141
  text=[prompt_full], images=images_for_processor, return_tensors="pt", padding=True
142
  ).to(device)
@@ -156,71 +153,198 @@ def generate_video(text: str, video_path: str,
156
  time.sleep(0.01)
157
  yield buffer, buffer
158
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
159
 
160
- # Define examples for image and video inference
161
  image_examples = [
162
- ["Describe the safety measures in the image. Conclude (Safe / Unsafe)..", "images/5.jpg"],
163
- ["Convert this page to doc [markdown] precisely.", "images/3.png"],
164
- ["Convert this page to doc [markdown] precisely.", "images/4.png"],
165
- ["Explain the creativity in the image.", "images/6.jpg"],
166
- ["Convert this page to doc [markdown] precisely.", "images/1.png"],
167
- ["Convert chart to OTSL.", "images/2.png"]
168
  ]
169
 
170
  video_examples = [
171
- ["Explain the video in detail.", "videos/2.mp4"],
172
- ["Explain the ad in detail.", "videos/1.mp4"]
173
  ]
174
 
 
 
 
 
 
 
175
  css = """
176
  .submit-btn { background-color: #2980b9 !important; color: white !important; }
177
  .submit-btn:hover { background-color: #3498db !important; }
178
  .canvas-output { border: 2px solid #4682B4; border-radius: 10px; padding: 20px; }
179
  """
180
 
181
- # Create the Gradio Interface
182
  with gr.Blocks(css=css, theme="bethecloud/storj_theme") as demo:
183
  gr.Markdown("# **[Multimodal VLM Thinking with Qwen3-VL](https://huggingface.co/Qwen/Qwen3-VL-30B-A3B-Instruct)**")
184
- with gr.Row():
185
- with gr.Column():
186
- with gr.Tabs():
187
- with gr.TabItem("Image Inference"):
 
188
  image_query = gr.Textbox(label="Query Input", placeholder="Enter your query here...")
189
  image_upload = gr.Image(type="pil", label="Image", height=290)
190
  image_submit = gr.Button("Submit", elem_classes="submit-btn")
191
  gr.Examples(examples=image_examples, inputs=[image_query, image_upload])
192
- with gr.TabItem("Video Inference"):
 
 
 
 
 
 
 
193
  video_query = gr.Textbox(label="Query Input", placeholder="Enter your query here...")
194
  video_upload = gr.Video(label="Video", height=290)
195
  video_submit = gr.Button("Submit", elem_classes="submit-btn")
196
  gr.Examples(examples=video_examples, inputs=[video_query, video_upload])
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
197
 
198
- with gr.Accordion("Advanced options", open=False):
199
- max_new_tokens = gr.Slider(label="Max new tokens", minimum=1, maximum=MAX_MAX_NEW_TOKENS, step=1, value=DEFAULT_MAX_NEW_TOKENS)
200
- temperature = gr.Slider(label="Temperature", minimum=0.1, maximum=4.0, step=0.1, value=0.6)
201
- top_p = gr.Slider(label="Top-p (nucleus sampling)", minimum=0.05, maximum=1.0, step=0.05, value=0.9)
202
- top_k = gr.Slider(label="Top-k", minimum=1, maximum=1000, step=1, value=50)
203
- repetition_penalty = gr.Slider(label="Repetition penalty", minimum=1.0, maximum=2.0, step=0.05, value=1.2)
204
-
205
- with gr.Column():
206
- with gr.Column(elem_classes="canvas-output"):
207
- gr.Markdown("## Output")
208
- output = gr.Textbox(label="Raw Output Stream", interactive=False, lines=5, show_copy_button=True)
209
- with gr.Accordion("(Result.md)", open=False):
210
- markdown_output = gr.Markdown(label="(Result.Md)")
211
- gr.Markdown("**Model Info 💻** | [Report Bug](https://huggingface.co/spaces/prithivMLmods/Multimodal-VLM-Thinking/discussions)")
212
- gr.Markdown("> Using **[Qwen/Qwen3-VL-30B-A3B-Instruct](https://huggingface.co/Qwen/Qwen3-VL-30B-A3B-Instruct)**, a powerful and versatile vision-language model. It excels at understanding and processing both text and visual information, making it suitable for a wide range of multimodal tasks. The model demonstrates strong performance in areas like visual question answering, image captioning, and video analysis.")
213
- gr.Markdown("> ⚠️ Note: Video inference performance can vary depending on the complexity and length of the video.")
214
 
 
215
  image_submit.click(
216
  fn=generate_image,
217
  inputs=[image_query, image_upload, max_new_tokens, temperature, top_p, top_k, repetition_penalty],
218
- outputs=[output, markdown_output]
219
  )
220
  video_submit.click(
221
  fn=generate_video,
222
  inputs=[video_query, video_upload, max_new_tokens, temperature, top_p, top_k, repetition_penalty],
223
- outputs=[output, markdown_output]
 
 
 
 
 
224
  )
225
 
226
  if __name__ == "__main__":
 
3
  import uuid
4
  import json
5
  import time
6
+ import re
7
  from threading import Thread
8
 
9
  import gradio as gr
 
12
  import numpy as np
13
  from PIL import Image
14
  import cv2
15
+ import supervision as sv
16
 
17
  from transformers import (
18
  Qwen3VLMoeForConditionalGeneration,
 
50
  model_q3vl = Qwen3VLMoeForConditionalGeneration.from_pretrained(
51
  MODEL_ID_Q3VL,
52
  trust_remote_code=True,
53
+ torch_dtype=torch.float16 # Corrected from 'dtype' to 'torch_dtype'
54
  ).to(device).eval()
55
 
56
 
 
93
  messages = [{"role": "user", "content": [{"type": "image"}, {"type": "text", "text": text}]}]
94
  prompt_full = processor_q3vl.apply_chat_template(messages, tokenize=False, add_generation_prompt=True)
95
 
 
96
  inputs = processor_q3vl(
97
  text=[prompt_full], images=[image], return_tensors="pt", padding=True
98
  ).to(device)
 
128
 
129
  messages = [{"role": "user", "content": [{"type": "text", "text": text}]}]
130
  images_for_processor = []
 
131
  for frame, timestamp in frames_with_ts:
132
+ messages[0]["content"].insert(0, {"type": "image"})
133
  images_for_processor.append(frame)
134
 
135
  prompt_full = processor_q3vl.apply_chat_template(messages, tokenize=False, add_generation_prompt=True)
136
 
 
137
  inputs = processor_q3vl(
138
  text=[prompt_full], images=images_for_processor, return_tensors="pt", padding=True
139
  ).to(device)
 
153
  time.sleep(0.01)
154
  yield buffer, buffer
155
 
156
+ # --- Object Detection & Pointing Functions ---
157
+
158
+ def parse_model_output_for_coords(text_output, task_type):
159
+ """Parses text to find normalized coordinates using regex and json."""
160
+ match = re.search(r'\[\[.*?\]\]', text_output)
161
+ if not match:
162
+ return []
163
+
164
+ try:
165
+ coords_str = match.group(0)
166
+ coords = json.loads(coords_str)
167
+
168
+ if not isinstance(coords, list): return []
169
+ if task_type == "Object Detection":
170
+ return [c for c in coords if isinstance(c, list) and len(c) == 4 and all(isinstance(n, (int, float)) for n in c)]
171
+ elif task_type == "Point Detection":
172
+ return [c for c in coords if isinstance(c, list) and len(c) == 2 and all(isinstance(n, (int, float)) for n in c)]
173
+ return []
174
+ except (json.JSONDecodeError, TypeError):
175
+ return []
176
+
177
+ def create_annotated_image_from_normalized(image, bboxes_normalized, object_name="Object"):
178
+ """Draws bounding boxes on an image from normalized coordinates."""
179
+ if not bboxes_normalized: return image
180
+
181
+ original_width, original_height = image.size
182
+ annotated_image = np.array(image.convert("RGB"))
183
+
184
+ bboxes_absolute = []
185
+ for bbox in bboxes_normalized:
186
+ x_min, y_min, x_max, y_max = bbox
187
+ bboxes_absolute.append([
188
+ int(x_min * original_width), int(y_min * original_height),
189
+ int(x_max * original_width), int(y_max * original_height)
190
+ ])
191
+
192
+ detections = sv.Detections(xyxy=np.array(bboxes_absolute, dtype=np.float32))
193
+ bounding_box_annotator = sv.BoxAnnotator(thickness=2)
194
+ label_annotator = sv.LabelAnnotator(text_thickness=1, text_scale=0.5)
195
+ labels = [f"{object_name} #{i+1}" for i in range(len(detections))]
196
+
197
+ annotated_image = bounding_box_annotator.annotate(scene=annotated_image, detections=detections)
198
+ annotated_image = label_annotator.annotate(scene=annotated_image, detections=detections, labels=labels)
199
+
200
+ return Image.fromarray(annotated_image)
201
+
202
+ def create_point_annotated_image_from_normalized(image, points_normalized):
203
+ """Draws points on an image from normalized coordinates."""
204
+ if not points_normalized: return image
205
+
206
+ original_width, original_height = image.size
207
+ annotated_image = np.array(image.convert("RGB"))
208
+
209
+ points_absolute = [[int(p[0] * original_width), int(p[1] * original_height)] for p in points_normalized]
210
+
211
+ points_array = np.array(points_absolute).reshape(1, -1, 2)
212
+ key_points = sv.KeyPoints(xy=points_array)
213
+ vertex_annotator = sv.VertexAnnotator(radius=5, color=sv.Color.RED)
214
+ annotated_image = vertex_annotator.annotate(scene=annotated_image, key_points=key_points)
215
+
216
+ return Image.fromarray(annotated_image)
217
+
218
+ @spaces.GPU
219
+ def generate_detection_and_pointing(image: Image.Image, prompt: str, task_type: str):
220
+ """Main function for the detection/pointing tab."""
221
+ if image is None: raise gr.Error("Please upload an image.")
222
+ if not prompt or not prompt.strip(): raise gr.Error("Please enter a prompt describing the object.")
223
+
224
+ if task_type == "Object Detection":
225
+ instruction = f"You are a helpful detection assistant. Find all instances of '{prompt}' in the image. Provide their bounding box coordinates in the format [[x_min, y_min, x_max, y_max]]. The coordinates must be normalized between 0 and 1. Only output the list of coordinates."
226
+ else: # Point Detection
227
+ instruction = f"You are a helpful detection assistant. Find the center point of all instances of '{prompt}' in the image. Provide their coordinates in the format [[x, y]]. The coordinates must be normalized between 0 and 1. Only output the list of coordinates."
228
+
229
+ messages = [{"role": "user", "content": [{"type": "image"}, {"type": "text", "text": instruction}]}]
230
+ prompt_full = processor_q3vl.apply_chat_template(messages, tokenize=False, add_generation_prompt=True)
231
+ inputs = processor_q3vl(text=[prompt_full], images=[image], return_tensors="pt", padding=True).to(device)
232
+
233
+ output_ids = model_q3vl.generate(**inputs, max_new_tokens=128, do_sample=False)
234
+ response_text = processor_q3vl.batch_decode(output_ids, skip_special_tokens=True)[0]
235
+
236
+ parts = response_text.split("ASSISTANT:")
237
+ response_text = parts[-1].strip() if len(parts) > 1 else response_text.split("<|im_end|>")[-1].strip()
238
+
239
+ coords = parse_model_output_for_coords(response_text, task_type)
240
+
241
+ annotated_image = image
242
+ if coords:
243
+ try:
244
+ if task_type == "Object Detection":
245
+ annotated_image = create_annotated_image_from_normalized(image, coords, prompt)
246
+ else:
247
+ annotated_image = create_point_annotated_image_from_normalized(image, coords)
248
+ except Exception as e:
249
+ response_text += f"\n\n[Error] Failed to draw annotations. Details: {e}"
250
+ annotated_image = image
251
+ else:
252
+ response_text += "\n\n[Info] Could not find or parse coordinates from model output. No annotations were drawn."
253
+
254
+ return annotated_image, response_text
255
+
256
+ # --- Gradio UI ---
257
 
 
258
  image_examples = [
259
+ ["Describe the safety measures in the image. Conclude (Safe / Unsafe)..", "https://huggingface.co/spaces/prithivMLmods/Multimodal-VLM-Thinking/resolve/main/images/5.jpg"],
260
+ ["Convert this page to doc [markdown] precisely.", "https://huggingface.co/spaces/prithivMLmods/Multimodal-VLM-Thinking/resolve/main/images/3.png"],
261
+ ["Explain the creativity in the image.", "https://huggingface.co/spaces/prithivMLmods/Multimodal-VLM-Thinking/resolve/main/images/6.jpg"],
 
 
 
262
  ]
263
 
264
  video_examples = [
265
+ ["Explain the video in detail.", "https://huggingface.co/spaces/prithivMLmods/Multimodal-VLM-Thinking/resolve/main/videos/2.mp4"],
266
+ ["Explain the ad in detail.", "https://huggingface.co/spaces/prithivMLmods/Multimodal-VLM-Thinking/resolve/main/videos/1.mp4"]
267
  ]
268
 
269
+ detection_examples = [
270
+ ["https://huggingface.co/spaces/prithivMLmods/Multimodal-VLM-Thinking/resolve/main/images/6.jpg", "Object Detection", "the person"],
271
+ ["https://huggingface.co/spaces/prithivMLmods/Multimodal-VLM-Thinking/resolve/main/images/5.jpg", "Point Detection", "the fire extinguisher"],
272
+ ]
273
+
274
+
275
  css = """
276
  .submit-btn { background-color: #2980b9 !important; color: white !important; }
277
  .submit-btn:hover { background-color: #3498db !important; }
278
  .canvas-output { border: 2px solid #4682B4; border-radius: 10px; padding: 20px; }
279
  """
280
 
 
281
  with gr.Blocks(css=css, theme="bethecloud/storj_theme") as demo:
282
  gr.Markdown("# **[Multimodal VLM Thinking with Qwen3-VL](https://huggingface.co/Qwen/Qwen3-VL-30B-A3B-Instruct)**")
283
+
284
+ with gr.Tabs():
285
+ with gr.TabItem("Image Inference"):
286
+ with gr.Row():
287
+ with gr.Column():
288
  image_query = gr.Textbox(label="Query Input", placeholder="Enter your query here...")
289
  image_upload = gr.Image(type="pil", label="Image", height=290)
290
  image_submit = gr.Button("Submit", elem_classes="submit-btn")
291
  gr.Examples(examples=image_examples, inputs=[image_query, image_upload])
292
+ with gr.Column():
293
+ with gr.Column(elem_classes="canvas-output"):
294
+ gr.Markdown("## Output")
295
+ output_img, markdown_output_img = gr.Textbox(label="Raw Output Stream", interactive=False, lines=15, show_copy_button=True), gr.Markdown(label="(Result.Md)")
296
+
297
+ with gr.TabItem("Video Inference"):
298
+ with gr.Row():
299
+ with gr.Column():
300
  video_query = gr.Textbox(label="Query Input", placeholder="Enter your query here...")
301
  video_upload = gr.Video(label="Video", height=290)
302
  video_submit = gr.Button("Submit", elem_classes="submit-btn")
303
  gr.Examples(examples=video_examples, inputs=[video_query, video_upload])
304
+ with gr.Column():
305
+ with gr.Column(elem_classes="canvas-output"):
306
+ gr.Markdown("## Output")
307
+ output_vid, markdown_output_vid = gr.Textbox(label="Raw Output Stream", interactive=False, lines=15, show_copy_button=True), gr.Markdown(label="(Result.Md)")
308
+
309
+ with gr.TabItem("Object Detection & Pointing"):
310
+ with gr.Row():
311
+ with gr.Column(scale=1):
312
+ detection_image_input = gr.Image(label="Upload an image", type="pil", height=400)
313
+ detection_task_type = gr.Radio(choices=["Object Detection", "Point Detection"], label="Task Type", value="Object Detection")
314
+ detection_prompt_input = gr.Textbox(label="Object to Detect/Point", placeholder="e.g., 'car', 'the person's face'")
315
+ detection_submit_btn = gr.Button(value="🚀 Find Objects", variant="primary")
316
+ with gr.Column(scale=1):
317
+ detection_output_image = gr.Image(type="pil", label="Result", height=400)
318
+ detection_output_textbox = gr.Textbox(label="Model Raw Output (Coordinates)", lines=10, show_copy_button=True)
319
+ gr.Examples(examples=detection_examples, inputs=[detection_image_input, detection_task_type, detection_prompt_input])
320
 
321
+ with gr.Accordion("Advanced options", open=False):
322
+ max_new_tokens = gr.Slider(label="Max new tokens", minimum=1, maximum=MAX_MAX_NEW_TOKENS, step=1, value=DEFAULT_MAX_NEW_TOKENS)
323
+ temperature = gr.Slider(label="Temperature", minimum=0.1, maximum=4.0, step=0.1, value=0.6)
324
+ top_p = gr.Slider(label="Top-p (nucleus sampling)", minimum=0.05, maximum=1.0, step=0.05, value=0.9)
325
+ top_k = gr.Slider(label="Top-k", minimum=1, maximum=1000, step=1, value=50)
326
+ repetition_penalty = gr.Slider(label="Repetition penalty", minimum=1.0, maximum=2.0, step=0.05, value=1.2)
327
+
328
+ gr.Markdown("---")
329
+ gr.Markdown("**Model Info 💻** | [Report Bug](https://huggingface.co/spaces/prithivMLmods/Multimodal-VLM-Thinking/discussions)")
330
+ gr.Markdown("> Using **[Qwen/Qwen3-VL-30B-A3B-Instruct](https://huggingface.co/Qwen/Qwen3-VL-30B-A3B-Instruct)**, a powerful and versatile vision-language model. It excels at understanding and processing both text and visual information, making it suitable for a wide range of multimodal tasks.")
331
+ gr.Markdown("> ⚠️ Note: Video inference performance can vary depending on the complexity and length of the video.")
 
 
 
 
 
332
 
333
+ # Event Handlers
334
  image_submit.click(
335
  fn=generate_image,
336
  inputs=[image_query, image_upload, max_new_tokens, temperature, top_p, top_k, repetition_penalty],
337
+ outputs=[output_img, markdown_output_img]
338
  )
339
  video_submit.click(
340
  fn=generate_video,
341
  inputs=[video_query, video_upload, max_new_tokens, temperature, top_p, top_k, repetition_penalty],
342
+ outputs=[output_vid, markdown_output_vid]
343
+ )
344
+ detection_submit_btn.click(
345
+ fn=generate_detection_and_pointing,
346
+ inputs=[detection_image_input, detection_prompt_input, detection_task_type],
347
+ outputs=[detection_output_image, detection_output_textbox]
348
  )
349
 
350
  if __name__ == "__main__":