prithivMLmods commited on
Commit
a138236
·
verified ·
1 Parent(s): 63030e5

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +139 -160
app.py CHANGED
@@ -3,7 +3,6 @@ import random
3
  import uuid
4
  import json
5
  import time
6
- import re
7
  from threading import Thread
8
 
9
  import gradio as gr
@@ -12,7 +11,8 @@ import torch
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,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
- torch_dtype=torch.float16 # Corrected from 'dtype' to 'torch_dtype'
54
  ).to(device).eval()
55
 
56
 
@@ -129,7 +129,7 @@ def generate_video(text: str, video_path: str,
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)
@@ -153,126 +153,107 @@ def generate_video(text: str, video_path: str,
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
 
 
 
 
 
 
276
 
277
  css = """
278
  .submit-btn { background-color: #2980b9 !important; color: white !important; }
@@ -280,74 +261,72 @@ css = """
280
  .canvas-output { border: 2px solid #4682B4; border-radius: 10px; padding: 20px; }
281
  """
282
 
283
- with gr.Blocks(css=css) as demo:
 
284
  gr.Markdown("# **[Multimodal VLM Thinking with Qwen3-VL](https://huggingface.co/Qwen/Qwen3-VL-30B-A3B-Instruct)**")
285
-
286
- with gr.Tabs():
287
- with gr.TabItem("Image Inference"):
288
- with gr.Row():
289
- with gr.Column():
290
  image_query = gr.Textbox(label="Query Input", placeholder="Enter your query here...")
291
  image_upload = gr.Image(type="pil", label="Image", height=290)
292
  image_submit = gr.Button("Submit", elem_classes="submit-btn")
293
- #gr.Examples(examples=image_examples, inputs=[image_query, image_upload])
294
- with gr.Column():
295
- with gr.Column(elem_classes="canvas-output"):
296
- gr.Markdown("## Output")
297
- output_img, markdown_output_img = gr.Textbox(label="Raw Output Stream", interactive=False, lines=15, show_copy_button=True), gr.Markdown(label="(Result.Md)")
298
-
299
- with gr.TabItem("Video Inference"):
300
- with gr.Row():
301
- with gr.Column():
302
  video_query = gr.Textbox(label="Query Input", placeholder="Enter your query here...")
303
  video_upload = gr.Video(label="Video", height=290)
304
  video_submit = gr.Button("Submit", elem_classes="submit-btn")
305
- #gr.Examples(examples=video_examples, inputs=[video_query, video_upload])
306
- with gr.Column():
307
- with gr.Column(elem_classes="canvas-output"):
308
- gr.Markdown("## Output")
309
- output_vid, markdown_output_vid = gr.Textbox(label="Raw Output Stream", interactive=False, lines=15, show_copy_button=True), gr.Markdown(label="(Result.Md)")
310
-
311
- with gr.TabItem("Object Detection & Pointing"):
312
- with gr.Row():
313
- with gr.Column(scale=1):
314
- detection_image_input = gr.Image(label="Upload an image", type="pil", height=400)
315
- detection_task_type = gr.Radio(choices=["Object Detection", "Point Detection"], label="Task Type", value="Object Detection")
316
- detection_prompt_input = gr.Textbox(label="Object to Detect/Point", placeholder="e.g., 'car', 'the person's face'")
317
- detection_submit_btn = gr.Button(value="🚀 Find Objects", variant="primary")
318
- with gr.Column(scale=1):
319
- detection_output_image = gr.Image(type="pil", label="Result", height=400)
320
- detection_output_textbox = gr.Textbox(label="Model Raw Output (Coordinates)", lines=10, show_copy_button=True)
321
- #gr.Examples(examples=detection_examples, inputs=[detection_image_input, detection_task_type, detection_prompt_input])
322
-
323
- with gr.Accordion("Advanced options", open=False):
324
- max_new_tokens = gr.Slider(label="Max new tokens", minimum=1, maximum=MAX_MAX_NEW_TOKENS, step=1, value=DEFAULT_MAX_NEW_TOKENS)
325
- temperature = gr.Slider(label="Temperature", minimum=0.1, maximum=4.0, step=0.1, value=0.6)
326
- top_p = gr.Slider(label="Top-p (nucleus sampling)", minimum=0.05, maximum=1.0, step=0.05, value=0.9)
327
- top_k = gr.Slider(label="Top-k", minimum=1, maximum=1000, step=1, value=50)
328
- repetition_penalty = gr.Slider(label="Repetition penalty", minimum=1.0, maximum=2.0, step=0.05, value=1.2)
329
-
330
- gr.Markdown("---")
331
- gr.Markdown("**Model Info 💻** | [Report Bug](https://huggingface.co/spaces/prithivMLmods/Multimodal-VLM-Thinking/discussions)")
332
- 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.")
333
- gr.Markdown("> ⚠️ Note: Video inference performance can vary depending on the complexity and length of the video.")
334
-
335
- # Event Handlers
 
 
336
  image_submit.click(
337
  fn=generate_image,
338
  inputs=[image_query, image_upload, max_new_tokens, temperature, top_p, top_k, repetition_penalty],
339
- outputs=[output_img, markdown_output_img]
340
  )
341
  video_submit.click(
342
  fn=generate_video,
343
  inputs=[video_query, video_upload, max_new_tokens, temperature, top_p, top_k, repetition_penalty],
344
- outputs=[output_vid, markdown_output_vid]
345
  )
346
- detection_submit_btn.click(
347
- fn=generate_detection_and_pointing,
348
- inputs=[detection_image_input, detection_prompt_input, detection_task_type],
349
- outputs=[detection_output_image, detection_output_textbox]
350
  )
351
 
352
  if __name__ == "__main__":
353
- demo.queue(max_size=50).launch(mcp_server=True, ssr_mode=False, show_error=True)
 
3
  import uuid
4
  import json
5
  import time
 
6
  from threading import Thread
7
 
8
  import gradio as gr
 
11
  import numpy as np
12
  from PIL import Image
13
  import cv2
14
+ import requests
15
+ import supervision as sv # Added for object detection visualization
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
54
  ).to(device).eval()
55
 
56
 
 
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)
 
153
  time.sleep(0.01)
154
  yield buffer, buffer
155
 
156
+ # --- Object Detection Functions ---
 
 
 
 
 
 
157
 
158
+ def create_annotated_image(image: Image.Image, json_data_string: str):
159
+ """Parses JSON from model and draws bounding boxes on the image."""
160
  try:
161
+ # Clean up the string to get pure JSON from markdown code blocks
162
+ if "```json" in json_data_string:
163
+ json_str = json_data_string.split("```json")[1].split("```").strip()
164
+ else:
165
+ json_str = json_data_string
166
 
167
+ bbox_data = json.loads(json_str)
168
+ if not isinstance(bbox_data, list):
169
+ bbox_data = [bbox_data]
170
+
171
+ except (json.JSONDecodeError, IndexError):
172
+ # If parsing fails, return the original image and an error message
173
+ return image, f"Failed to parse JSON from model output:\n{json_data_string}"
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
174
 
 
 
 
 
 
175
  annotated_image = np.array(image.convert("RGB"))
176
+ boxes = []
177
+ labels = []
 
 
 
 
 
 
 
178
 
179
+ for item in bbox_data:
180
+ if "box_2d" in item and "label" in item:
181
+ boxes.append(item["box_2d"])
182
+ labels.append(str(item["label"]))
183
+
184
+ if not boxes:
185
+ return image, "No bounding boxes with labels found in the model's output."
186
+
187
+ # Create supervision Detections object from the parsed data
188
+ detections = sv.Detections(xyxy=np.array(boxes))
189
+
190
+ # Create annotators
191
+ bounding_box_annotator = sv.BoxAnnotator(color_lookup=sv.ColorLookup.INDEX)
192
+ label_annotator = sv.LabelAnnotator(color_lookup=sv.ColorLookup.INDEX)
193
+
194
+ # Annotate the image
195
+ annotated_image = bounding_box_annotator.annotate(
196
+ scene=annotated_image, detections=detections
197
+ )
198
+ annotated_image = label_annotator.annotate(
199
+ scene=annotated_image, detections=detections, labels=labels
200
+ )
201
 
202
+ return Image.fromarray(annotated_image), json.dumps(bbox_data, indent=2)
 
 
 
203
 
204
+ @spaces.GPU
205
+ def generate_detection(image: Image.Image, prompt: str):
206
+ """
207
+ Generates object detections using the Qwen3-VL model.
208
+ """
209
+ if image is None:
210
+ return None, "Please upload an image first."
211
+
212
+ # A detailed prompt to guide the model for object detection
213
+ detection_prompt = f"""
214
+ This is an object detection task. Analyze the image to identify all instances of '{prompt}'.
215
+ Respond ONLY with a JSON array where each object is a dictionary with two keys:
216
+ 1. "label": The name of the object found (e.g., "{prompt}").
217
+ 2. "box_2d": The bounding box coordinates as a list of four numbers [x_min, y_min, x_max, y_max].
218
+ Do not include any other text or explanations outside of the final JSON code block.
219
+ """
220
+
221
+ messages = [{"role": "user", "content": [{"type": "image"}, {"type": "text", "text": detection_prompt}]}]
222
  prompt_full = processor_q3vl.apply_chat_template(messages, tokenize=False, add_generation_prompt=True)
 
 
 
 
 
 
 
223
 
224
+ inputs = processor_q3vl(
225
+ text=[prompt_full], images=[image], return_tensors="pt", padding=True
226
+ ).to(device)
 
 
 
 
 
 
 
 
 
 
 
 
 
227
 
228
+ # Generate a static response (no streaming) for easier JSON parsing
229
+ generated_ids = model_q3vl.generate(**inputs, max_new_tokens=2048)
230
+ generated_ids_trimmed = generated_ids[:, inputs.input_ids.shape:]
231
+ response_text = processor_q3vl.batch_decode(generated_ids_trimmed, skip_special_tokens=True)
232
 
233
+ # Create annotated image from the model's response
234
+ annotated_image, formatted_json = create_annotated_image(image, response_text)
 
 
 
235
 
236
+ return annotated_image, formatted_json
 
 
 
237
 
238
+ # --- Gradio UI ---
 
 
239
 
240
+ # Define examples for image and video inference
241
+ image_examples = [
242
+ ["Describe the safety measures in the image. Conclude (Safe / Unsafe)..", "examples/5.jpg"],
243
+ ["Convert this page to doc [markdown] precisely.", "examples/3.png"],
244
+ ["Explain the creativity in the image.", "examples/6.jpg"],
245
+ ]
246
 
247
+ video_examples = [
248
+ ["Explain the video in detail.", "examples/2.mp4"],
249
+ ["Explain the ad in detail.", "examples/1.mp4"]
250
+ ]
251
 
252
+ detection_examples = [
253
+ ["examples/detection_1.jpg", "person"],
254
+ ["examples/detection_2.jpg", "car"],
255
+ ["examples/detection_3.jpg", "cat"],
256
+ ]
257
 
258
  css = """
259
  .submit-btn { background-color: #2980b9 !important; color: white !important; }
 
261
  .canvas-output { border: 2px solid #4682B4; border-radius: 10px; padding: 20px; }
262
  """
263
 
264
+ # Create the Gradio Interface
265
+ with gr.Blocks(css=css, theme="bethecloud/storj_theme") as demo:
266
  gr.Markdown("# **[Multimodal VLM Thinking with Qwen3-VL](https://huggingface.co/Qwen/Qwen3-VL-30B-A3B-Instruct)**")
267
+ with gr.Row():
268
+ with gr.Column():
269
+ with gr.Tabs():
270
+ # Tab 1: Image Inference
271
+ with gr.TabItem("Image Inference"):
272
  image_query = gr.Textbox(label="Query Input", placeholder="Enter your query here...")
273
  image_upload = gr.Image(type="pil", label="Image", height=290)
274
  image_submit = gr.Button("Submit", elem_classes="submit-btn")
275
+ gr.Examples(examples=image_examples, inputs=[image_query, image_upload])
276
+
277
+ # Tab 2: Video Inference
278
+ with gr.TabItem("Video Inference"):
 
 
 
 
 
279
  video_query = gr.Textbox(label="Query Input", placeholder="Enter your query here...")
280
  video_upload = gr.Video(label="Video", height=290)
281
  video_submit = gr.Button("Submit", elem_classes="submit-btn")
282
+ gr.Examples(examples=video_examples, inputs=[video_query, video_upload])
283
+
284
+ # Tab 3: Object Detection
285
+ with gr.TabItem("Object Detection & Pointing"):
286
+ detection_image_upload = gr.Image(type="pil", label="Image to Analyze", height=290)
287
+ detection_query = gr.Textbox(label="Object to Detect", placeholder="e.g., car, person, cat...")
288
+ detection_submit = gr.Button("Detect Objects", elem_classes="submit-btn")
289
+ gr.Examples(examples=detection_examples, inputs=[detection_image_upload, detection_query])
290
+
291
+
292
+ with gr.Accordion("Advanced options", open=False):
293
+ max_new_tokens = gr.Slider(label="Max new tokens", minimum=1, maximum=MAX_MAX_NEW_TOKENS, step=1, value=DEFAULT_MAX_NEW_TOKENS)
294
+ temperature = gr.Slider(label="Temperature", minimum=0.1, maximum=4.0, step=0.1, value=0.6)
295
+ top_p = gr.Slider(label="Top-p (nucleus sampling)", minimum=0.05, maximum=1.0, step=0.05, value=0.9)
296
+ top_k = gr.Slider(label="Top-k", minimum=1, maximum=1000, step=1, value=50)
297
+ repetition_penalty = gr.Slider(label="Repetition penalty", minimum=1.0, maximum=2.0, step=0.05, value=1.2)
298
+
299
+ with gr.Column():
300
+ with gr.Column(elem_classes="canvas-output"):
301
+ gr.Markdown("## Output")
302
+ # Outputs for Image/Video Inference
303
+ output_stream = gr.Textbox(label="Raw Output Stream", interactive=False, lines=5, show_copy_button=True)
304
+ markdown_output = gr.Markdown(label="Formatted Output (Result.md)")
305
+
306
+ # Outputs for Object Detection
307
+ annotated_image = gr.Image(type="pil", label="Annotated Image")
308
+ json_output = gr.JSON(label="Detection JSON Output")
309
+
310
+ gr.Markdown("**Model Info 💻** | [Report Bug](https://huggingface.co/spaces/prithivMLmods/Multimodal-VLM-Thinking/discussions)")
311
+ 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 like visual question answering, video analysis, and object detection.")
312
+ gr.Markdown("> ⚠️ Note: Performance can vary depending on the complexity of the input.")
313
+
314
+ # Wire up the events
315
  image_submit.click(
316
  fn=generate_image,
317
  inputs=[image_query, image_upload, max_new_tokens, temperature, top_p, top_k, repetition_penalty],
318
+ outputs=[output_stream, markdown_output]
319
  )
320
  video_submit.click(
321
  fn=generate_video,
322
  inputs=[video_query, video_upload, max_new_tokens, temperature, top_p, top_k, repetition_penalty],
323
+ outputs=[output_stream, markdown_output]
324
  )
325
+ detection_submit.click(
326
+ fn=generate_detection,
327
+ inputs=[detection_image_upload, detection_query],
328
+ outputs=[annotated_image, json_output]
329
  )
330
 
331
  if __name__ == "__main__":
332
+ demo.queue(max_size=50).launch(share=True, ssr_mode=False, show_error=True)