prithivMLmods commited on
Commit
b808114
·
verified ·
1 Parent(s): 98db794

update app

Browse files
Files changed (1) hide show
  1. app.py +194 -14
app.py CHANGED
@@ -8,6 +8,7 @@ from threading import Thread
8
  from pathlib import Path
9
  from io import BytesIO
10
  from typing import Optional, Tuple, Dict, Any, Iterable
 
11
 
12
  import gradio as gr
13
  import spaces
@@ -17,6 +18,7 @@ from PIL import Image
17
  import cv2
18
  import requests
19
  import fitz
 
20
 
21
  from transformers import (
22
  Qwen3VLMoeForConditionalGeneration,
@@ -28,9 +30,6 @@ from transformers.image_utils import load_image
28
  from gradio.themes import Soft
29
  from gradio.themes.utils import colors, fonts, sizes
30
 
31
- # --- Theme and CSS Definition ---
32
-
33
- # Define the new OrangeRed color palette
34
  colors.orange_red = colors.Color(
35
  name="orange_red",
36
  c50="#FFF0E5",
@@ -38,7 +37,7 @@ colors.orange_red = colors.Color(
38
  c200="#FFC299",
39
  c300="#FFA366",
40
  c400="#FF8533",
41
- c500="#FF4500", # OrangeRed base color
42
  c600="#E63E00",
43
  c700="#CC3700",
44
  c800="#B33000",
@@ -97,7 +96,6 @@ class OrangeRedTheme(Soft):
97
  block_label_background_fill="*primary_200",
98
  )
99
 
100
- # Instantiate the new theme
101
  orange_red_theme = OrangeRedTheme()
102
 
103
  css = """
@@ -251,6 +249,74 @@ def navigate_pdf_page(direction: str, state: Dict[str, Any]):
251
  page_info_html = f'<div style="text-align:center;">Page {new_index + 1} / {total_pages}</div>'
252
  return image_preview, state, page_info_html
253
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
254
  @spaces.GPU
255
  def generate_image(text: str, image: Image.Image, max_new_tokens: int = 1024, temperature: float = 0.6, top_p: float = 0.9, top_k: int = 50, repetition_penalty: float = 1.2):
256
  if image is None:
@@ -370,6 +436,65 @@ def generate_gif(text: str, gif_path: str, max_new_tokens: int = 1024, temperatu
370
  time.sleep(0.01)
371
  yield buffer, buffer
372
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
373
  image_examples = [["Perform OCR on the image...", "examples/images/1.jpg"],
374
  ["Caption the image. Describe the safety measures shown in the image. Conclude whether the situation is (safe or unsafe)...", "examples/images/2.jpg"],
375
  ["Solve the problem...", "examples/images/3.png"]]
@@ -381,6 +506,11 @@ gif_examples = [["Describe this GIF.", "examples/gifs/1.gif"],
381
  ["Describe this GIF.", "examples/gifs/2.gif"]]
382
  caption_examples = [["examples/captions/1.JPG"],
383
  ["examples/captions/2.jpeg"], ["examples/captions/3.jpeg"]]
 
 
 
 
 
384
 
385
  with gr.Blocks(theme=orange_red_theme, css=css) as demo:
386
  pdf_state = gr.State(value=get_initial_pdf_state())
@@ -394,11 +524,17 @@ with gr.Blocks(theme=orange_red_theme, css=css) as demo:
394
  image_submit = gr.Button("Submit", variant="primary")
395
  gr.Examples(examples=image_examples, inputs=[image_query, image_upload])
396
 
397
- with gr.TabItem("Video Inference"):
398
- video_query = gr.Textbox(label="Query Input", placeholder="Enter your query here...")
399
- video_upload = gr.Video(label="Upload Video(≤30s)", height=290)
400
- video_submit = gr.Button("Submit", variant="primary")
401
- gr.Examples(examples=video_examples, inputs=[video_query, video_upload])
 
 
 
 
 
 
402
 
403
  with gr.TabItem("PDF Inference"):
404
  with gr.Row():
@@ -424,6 +560,12 @@ with gr.Blocks(theme=orange_red_theme, css=css) as demo:
424
  caption_image_upload = gr.Image(type="pil", label="Image to Caption", height=290)
425
  caption_submit = gr.Button("Generate Caption", variant="primary")
426
  gr.Examples(examples=caption_examples, inputs=[caption_image_upload])
 
 
 
 
 
 
427
 
428
  with gr.Accordion("Advanced options", open=False):
429
  max_new_tokens = gr.Slider(label="Max new tokens", minimum=1, maximum=MAX_MAX_NEW_TOKENS, step=1, value=DEFAULT_MAX_NEW_TOKENS)
@@ -434,12 +576,22 @@ with gr.Blocks(theme=orange_red_theme, css=css) as demo:
434
 
435
  with gr.Column(scale=3):
436
  gr.Markdown("## Output", elem_id="output-title")
437
- output = gr.Textbox(label="Raw Output Stream", interactive=False, lines=14, show_copy_button=True)
438
- with gr.Accordion("(Result.md)", open=False):
439
- markdown_output = gr.Markdown(label="(Result.Md)", latex_delimiters=[
440
  {"left": "$$", "right": "$$", "display": True},
441
  {"left": "$", "right": "$", "display": False}
442
- ])
 
 
 
 
 
 
 
 
 
 
 
443
 
444
  image_submit.click(fn=generate_image,
445
  inputs=[image_query, image_upload, max_new_tokens, temperature, top_p, top_k, repetition_penalty],
@@ -456,6 +608,34 @@ with gr.Blocks(theme=orange_red_theme, css=css) as demo:
456
  caption_submit.click(fn=generate_caption,
457
  inputs=[caption_image_upload, max_new_tokens, temperature, top_p, top_k, repetition_penalty],
458
  outputs=[output, markdown_output])
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
459
 
460
  pdf_upload.change(fn=load_and_preview_pdf, inputs=[pdf_upload], outputs=[pdf_preview_img, pdf_state, page_info])
461
  prev_page_btn.click(fn=lambda s: navigate_pdf_page("prev", s), inputs=[pdf_state], outputs=[pdf_preview_img, pdf_state, page_info])
 
8
  from pathlib import Path
9
  from io import BytesIO
10
  from typing import Optional, Tuple, Dict, Any, Iterable
11
+ import re
12
 
13
  import gradio as gr
14
  import spaces
 
18
  import cv2
19
  import requests
20
  import fitz
21
+ import supervision as sv
22
 
23
  from transformers import (
24
  Qwen3VLMoeForConditionalGeneration,
 
30
  from gradio.themes import Soft
31
  from gradio.themes.utils import colors, fonts, sizes
32
 
 
 
 
33
  colors.orange_red = colors.Color(
34
  name="orange_red",
35
  c50="#FFF0E5",
 
37
  c200="#FFC299",
38
  c300="#FFA366",
39
  c400="#FF8533",
40
+ c500="#FF4500",
41
  c600="#E63E00",
42
  c700="#CC3700",
43
  c800="#B33000",
 
96
  block_label_background_fill="*primary_200",
97
  )
98
 
 
99
  orange_red_theme = OrangeRedTheme()
100
 
101
  css = """
 
249
  page_info_html = f'<div style="text-align:center;">Page {new_index + 1} / {total_pages}</div>'
250
  return image_preview, state, page_info_html
251
 
252
+ def draw_boxes_on_image(image: Image.Image, text_output: str, object_name: str) -> Tuple[Image.Image, str]:
253
+ try:
254
+ # Extract the JSON part of the text output
255
+ match = re.search(r'\[\s*\[.*?\]\s*\]', text_output, re.DOTALL)
256
+ if not match:
257
+ return image, f"Could not find coordinates in the model output: {text_output}"
258
+
259
+ boxes_str = match.group(0)
260
+ boxes = json.loads(boxes_str)
261
+
262
+ if not boxes or not isinstance(boxes[0], list):
263
+ return image, f"No valid boxes found in parsed data: {boxes}"
264
+
265
+ width, height = image.size
266
+ np_image = np.array(image.convert("RGB"))
267
+
268
+ # Denormalize coordinates
269
+ xyxy = []
270
+ for box in boxes:
271
+ x1, y1, x2, y2 = box
272
+ xyxy.append([x1 * width, y1 * height, x2 * width, y2 * height])
273
+
274
+ detections = sv.Detections(xyxy=np.array(xyxy))
275
+
276
+ bounding_box_annotator = sv.BoxAnnotator(thickness=2)
277
+ label_annotator = sv.LabelAnnotator(text_thickness=1, text_scale=0.5)
278
+
279
+ labels = [f"{object_name} #{i+1}" for i in range(len(detections))]
280
+
281
+ annotated_image = bounding_box_annotator.annotate(scene=np_image.copy(), detections=detections)
282
+ annotated_image = label_annotator.annotate(scene=annotated_image, detections=detections, labels=labels)
283
+
284
+ return Image.fromarray(annotated_image), text_output
285
+ except (json.JSONDecodeError, IndexError, TypeError) as e:
286
+ return image, f"Failed to parse or draw boxes. Error: {e}\nModel Output:\n{text_output}"
287
+
288
+ def draw_points_on_image(image: Image.Image, text_output: str) -> Tuple[Image.Image, str]:
289
+ try:
290
+ match = re.search(r'\[\s*\[.*?\]\s*\]', text_output, re.DOTALL)
291
+ if not match:
292
+ return image, f"Could not find coordinates in the model output: {text_output}"
293
+
294
+ points_str = match.group(0)
295
+ points = json.loads(points_str)
296
+
297
+ if not points or not isinstance(points[0], list):
298
+ return image, f"No valid points found in parsed data: {points}"
299
+
300
+ width, height = image.size
301
+ np_image = np.array(image.convert("RGB"))
302
+
303
+ # Denormalize coordinates
304
+ xy = []
305
+ for point in points:
306
+ x, y = point
307
+ xy.append([x * width, y * height])
308
+
309
+ points_array = np.array(xy).reshape(1, -1, 2)
310
+ key_points = sv.KeyPoints(xy=points_array)
311
+
312
+ point_annotator = sv.VertexAnnotator(radius=5, color=sv.Color.RED)
313
+ annotated_image = point_annotator.annotate(scene=np_image.copy(), key_points=key_points)
314
+
315
+ return Image.fromarray(annotated_image), text_output
316
+ except (json.JSONDecodeError, IndexError, TypeError) as e:
317
+ return image, f"Failed to parse or draw points. Error: {e}\nModel Output:\n{text_output}"
318
+
319
+
320
  @spaces.GPU
321
  def generate_image(text: str, image: Image.Image, max_new_tokens: int = 1024, temperature: float = 0.6, top_p: float = 0.9, top_k: int = 50, repetition_penalty: float = 1.2):
322
  if image is None:
 
436
  time.sleep(0.01)
437
  yield buffer, buffer
438
 
439
+ @spaces.GPU
440
+ def generate_object_detection(image: Image.Image, text: str, max_new_tokens: int = 256, temperature: float = 0.6, top_p: float = 0.9, top_k: int = 50, repetition_penalty: float = 1.2):
441
+ if image is None:
442
+ yield image, "Please upload an image."
443
+ return
444
+ if not text:
445
+ yield image, "Please enter the object name to detect."
446
+ return
447
+
448
+ prompt = (
449
+ f"You are an expert object detection model. Your task is to find all instances of '{text}' in the image. "
450
+ "You must respond ONLY with a JSON list of bounding boxes. Each bounding box must be in the format "
451
+ "[x_min, y_min, x_max, y_max], where the coordinates are normalized to be between 0 and 1. "
452
+ "Do not provide any other text, explanation, or preamble. For example: [[0.1, 0.2, 0.3, 0.4], [0.5, 0.6, 0.7, 0.8]]"
453
+ )
454
+
455
+ messages = [{"role": "user", "content": [{"type": "image"}, {"type": "text", "text": prompt}]}]
456
+ prompt_full = processor_q3vl.apply_chat_template(messages, tokenize=False, add_generation_prompt=True)
457
+ inputs = processor_q3vl(text=[prompt_full], images=[image], return_tensors="pt", padding=True).to(device)
458
+
459
+ # This task is not streamed because we need the full output to parse and draw boxes
460
+ outputs = model_q3vl.generate(**inputs, max_new_tokens=max_new_tokens, do_sample=False)
461
+ response_text = processor_q3vl.decode(outputs[0], skip_special_tokens=True).strip()
462
+
463
+ # Extract only the user-facing part of the response
464
+ final_text = response_text.split('<|im_end|>')[-1].strip() if '<|im_end|>' in response_text else response_text
465
+
466
+ annotated_image, raw_output = draw_boxes_on_image(image, final_text, text)
467
+ yield annotated_image, raw_output
468
+
469
+ @spaces.GPU
470
+ def generate_point_detection(image: Image.Image, text: str, max_new_tokens: int = 256, temperature: float = 0.6, top_p: float = 0.9, top_k: int = 50, repetition_penalty: float = 1.2):
471
+ if image is None:
472
+ yield image, "Please upload an image."
473
+ return
474
+ if not text:
475
+ yield image, "Please enter the object/point name to detect."
476
+ return
477
+
478
+ prompt = (
479
+ f"You are an expert point detection model. Your task is to find the specific location of '{text}' in the image. "
480
+ "You must respond ONLY with a JSON list containing a single coordinate pair. The coordinate must be in the format "
481
+ "[[x, y]], where the coordinates are normalized to be between 0 and 1. "
482
+ "Do not provide any other text, explanation, or preamble. For example: [[0.45, 0.67]]"
483
+ )
484
+
485
+ messages = [{"role": "user", "content": [{"type": "image"}, {"type": "text", "text": prompt}]}]
486
+ prompt_full = processor_q3vl.apply_chat_template(messages, tokenize=False, add_generation_prompt=True)
487
+ inputs = processor_q3vl(text=[prompt_full], images=[image], return_tensors="pt", padding=True).to(device)
488
+
489
+ outputs = model_q3vl.generate(**inputs, max_new_tokens=max_new_tokens, do_sample=False)
490
+ response_text = processor_q3vl.decode(outputs[0], skip_special_tokens=True).strip()
491
+
492
+ final_text = response_text.split('<|im_end|>')[-1].strip() if '<|im_end|>' in response_text else response_text
493
+
494
+ annotated_image, raw_output = draw_points_on_image(image, final_text)
495
+ yield annotated_image, raw_output
496
+
497
+
498
  image_examples = [["Perform OCR on the image...", "examples/images/1.jpg"],
499
  ["Caption the image. Describe the safety measures shown in the image. Conclude whether the situation is (safe or unsafe)...", "examples/images/2.jpg"],
500
  ["Solve the problem...", "examples/images/3.png"]]
 
506
  ["Describe this GIF.", "examples/gifs/2.gif"]]
507
  caption_examples = [["examples/captions/1.JPG"],
508
  ["examples/captions/2.jpeg"], ["examples/captions/3.jpeg"]]
509
+ object_detection_examples = [["a cat", "examples/detection/cat_dog.jpg"],
510
+ ["the person in the red shirt", "examples/detection/people.jpg"]]
511
+ point_detection_examples = [["the dog's nose", "examples/detection/cat_dog.jpg"],
512
+ ["the clock on the wall", "examples/detection/room.jpg"]]
513
+
514
 
515
  with gr.Blocks(theme=orange_red_theme, css=css) as demo:
516
  pdf_state = gr.State(value=get_initial_pdf_state())
 
524
  image_submit = gr.Button("Submit", variant="primary")
525
  gr.Examples(examples=image_examples, inputs=[image_query, image_upload])
526
 
527
+ with gr.TabItem("Object Detection"):
528
+ obj_det_query = gr.Textbox(label="Object to Detect", placeholder="e.g., 'a car', 'the dog'")
529
+ obj_det_upload = gr.Image(type="pil", label="Upload Image", height=290)
530
+ obj_det_submit = gr.Button("Detect Objects", variant="primary")
531
+ gr.Examples(examples=object_detection_examples, inputs=[obj_det_query, obj_det_upload])
532
+
533
+ with gr.TabItem("Point Detection"):
534
+ point_det_query = gr.Textbox(label="Point to Detect", placeholder="e.g., 'the cat's left eye'")
535
+ point_det_upload = gr.Image(type="pil", label="Upload Image", height=290)
536
+ point_det_submit = gr.Button("Detect Point", variant="primary")
537
+ gr.Examples(examples=point_detection_examples, inputs=[point_det_query, point_det_upload])
538
 
539
  with gr.TabItem("PDF Inference"):
540
  with gr.Row():
 
560
  caption_image_upload = gr.Image(type="pil", label="Image to Caption", height=290)
561
  caption_submit = gr.Button("Generate Caption", variant="primary")
562
  gr.Examples(examples=caption_examples, inputs=[caption_image_upload])
563
+
564
+ with gr.TabItem("Video Inference"):
565
+ video_query = gr.Textbox(label="Query Input", placeholder="Enter your query here...")
566
+ video_upload = gr.Video(label="Upload Video(≤30s)", height=290)
567
+ video_submit = gr.Button("Submit", variant="primary")
568
+ gr.Examples(examples=video_examples, inputs=[video_query, video_upload])
569
 
570
  with gr.Accordion("Advanced options", open=False):
571
  max_new_tokens = gr.Slider(label="Max new tokens", minimum=1, maximum=MAX_MAX_NEW_TOKENS, step=1, value=DEFAULT_MAX_NEW_TOKENS)
 
576
 
577
  with gr.Column(scale=3):
578
  gr.Markdown("## Output", elem_id="output-title")
579
+ output = gr.Textbox(label="Raw Output Stream", interactive=False, lines=14, show_copy_button=True, visible=True)
580
+ markdown_output = gr.Markdown(label="(Result.Md)", latex_delimiters=[
 
581
  {"left": "$$", "right": "$$", "display": True},
582
  {"left": "$", "right": "$", "display": False}
583
+ ], visible=True)
584
+ annotated_image_output = gr.Image(label="Annotated Image", visible=False)
585
+ raw_detection_output = gr.Textbox(label="Raw Detection Output", interactive=False, lines=4, show_copy_button=True, visible=False)
586
+
587
+ def switch_output_visibility(tab_name):
588
+ is_detection = tab_name in ["Object Detection", "Point Detection"]
589
+ return {
590
+ output: gr.update(visible=not is_detection),
591
+ markdown_output: gr.update(visible=not is_detection),
592
+ annotated_image_output: gr.update(visible=is_detection),
593
+ raw_detection_output: gr.update(visible=is_detection),
594
+ }
595
 
596
  image_submit.click(fn=generate_image,
597
  inputs=[image_query, image_upload, max_new_tokens, temperature, top_p, top_k, repetition_penalty],
 
608
  caption_submit.click(fn=generate_caption,
609
  inputs=[caption_image_upload, max_new_tokens, temperature, top_p, top_k, repetition_penalty],
610
  outputs=[output, markdown_output])
611
+
612
+ obj_det_submit.click(
613
+ fn=lambda: {
614
+ annotated_image_output: gr.update(visible=True),
615
+ raw_detection_output: gr.update(visible=True),
616
+ output: gr.update(visible=False),
617
+ markdown_output: gr.update(visible=False)
618
+ },
619
+ outputs=[annotated_image_output, raw_detection_output, output, markdown_output]
620
+ ).then(
621
+ fn=generate_object_detection,
622
+ inputs=[obj_det_upload, obj_det_query, max_new_tokens, temperature, top_p, top_k, repetition_penalty],
623
+ outputs=[annotated_image_output, raw_detection_output]
624
+ )
625
+
626
+ point_det_submit.click(
627
+ fn=lambda: {
628
+ annotated_image_output: gr.update(visible=True),
629
+ raw_detection_output: gr.update(visible=True),
630
+ output: gr.update(visible=False),
631
+ markdown_output: gr.update(visible=False)
632
+ },
633
+ outputs=[annotated_image_output, raw_detection_output, output, markdown_output]
634
+ ).then(
635
+ fn=generate_point_detection,
636
+ inputs=[point_det_upload, point_det_query, max_new_tokens, temperature, top_p, top_k, repetition_penalty],
637
+ outputs=[annotated_image_output, raw_detection_output]
638
+ )
639
 
640
  pdf_upload.change(fn=load_and_preview_pdf, inputs=[pdf_upload], outputs=[pdf_preview_img, pdf_state, page_info])
641
  prev_page_btn.click(fn=lambda s: navigate_pdf_page("prev", s), inputs=[pdf_state], outputs=[pdf_preview_img, pdf_state, page_info])