multimodalart HF Staff commited on
Commit
e2b49c1
·
verified ·
1 Parent(s): 9007f4e

feat: Enable MCP

Browse files

Hello! This is an automated PR adding MCP compatibility to your AI App 🤖.

![image.png](https://cdn-uploads.huggingface.co/production/uploads/624bebf604abc7ebb01789af/HQQK38I_MDXLDMYDYBq8H.png)This PR introduces two improvements:
1. Adds docstrings to the functions in the app file that are directly connected to the Gradio UI, for the downstream LLM to use.
2. Enables the Model-Compute-Platform by adding `mcp_server=True` to the `.launch()` call.

No other logic has been changed. Please review and merge if it looks good!Learn more about MCP compatibility in Spaces here: https://huggingface.co/changelog/add-compatible-spaces-to-your-mcp-tools

Files changed (1) hide show
  1. app.py +58 -244
app.py CHANGED
@@ -51,6 +51,17 @@ def add_contour(img, mask, color=(1., 1., 1.)):
51
 
52
  @spaces.GPU(duration=120)
53
  def generate_masks(image, mask_list, mask_raw_list):
 
 
 
 
 
 
 
 
 
 
 
54
  image['image'] = image['background'].convert('RGB')
55
  # del image['background'], image['composite']
56
  assert len(image['layers']) == 1, f"Expected 1 layer, got {len(image['layers'])}"
@@ -77,6 +88,17 @@ def generate_masks(image, mask_list, mask_raw_list):
77
 
78
  @spaces.GPU(duration=120)
79
  def generate_masks_video(image, mask_list_video, mask_raw_list_video):
 
 
 
 
 
 
 
 
 
 
 
80
  image['image'] = image['background'].convert('RGB')
81
  # del image['background'], image['composite']
82
  assert len(image['layers']) == 1, f"Expected 1 layer, got {len(image['layers'])}"
@@ -104,6 +126,18 @@ def generate_masks_video(image, mask_list_video, mask_raw_list_video):
104
 
105
  @spaces.GPU(duration=120)
106
  def describe(image, mode, query, masks):
 
 
 
 
 
 
 
 
 
 
 
 
107
  # Create an image object from the uploaded image
108
  # print(image.keys())
109
 
@@ -194,6 +228,15 @@ def describe(image, mode, query, masks):
194
 
195
 
196
  def load_first_frame(video_path):
 
 
 
 
 
 
 
 
 
197
  cap = cv2.VideoCapture(video_path)
198
  ret, frame = cap.read()
199
  cap.release()
@@ -205,6 +248,20 @@ def load_first_frame(video_path):
205
 
206
  @spaces.GPU(duration=120)
207
  def describe_video(video_path, mode, query, annotated_frame, masks, mask_list_video):
 
 
 
 
 
 
 
 
 
 
 
 
 
 
208
  # Create a temporary directory to save extracted video frames
209
  cap = cv2.VideoCapture(video_path)
210
 
@@ -294,247 +351,4 @@ def describe_video(video_path, mode, query, annotated_frame, masks, mask_list_vi
294
  mask_image = Image.fromarray((mask_np[:,:,np.newaxis] * np.array(annotated_frame['image'])).astype(np.uint8))
295
  mask_list_video.append((mask_image, f"<object{len(mask_list_video)}>"))
296
  text = ""
297
- yield frame_img, text, mask_list_video, mask_list_video
298
-
299
- for token in get_model_output(
300
- video_tensor,
301
- query,
302
- model=model,
303
- tokenizer=tokenizer,
304
- masks=masks,
305
- mask_ids=mask_ids,
306
- modal='video',
307
- streaming=True,
308
- ):
309
- text += token
310
- yield gr.update(), text, gr.update(), gr.update()
311
-
312
-
313
- @spaces.GPU(duration=120)
314
- def apply_sam(image, input_points):
315
- inputs = sam_processor(image, input_points=input_points, return_tensors="pt").to(device)
316
-
317
- with torch.no_grad():
318
- outputs = sam_model(**inputs)
319
-
320
- masks = sam_processor.image_processor.post_process_masks(outputs.pred_masks.cpu(), inputs["original_sizes"].cpu(), inputs["reshaped_input_sizes"].cpu())[0][0]
321
- scores = outputs.iou_scores[0, 0]
322
-
323
- mask_selection_index = scores.argmax()
324
-
325
- mask_np = masks[mask_selection_index].numpy()
326
-
327
- return mask_np
328
-
329
-
330
- def clear_masks():
331
- return [], [], []
332
-
333
-
334
- if __name__ == "__main__":
335
- parser = argparse.ArgumentParser(description="VideoRefer gradio demo")
336
- parser.add_argument("--model-path", type=str, default="DAMO-NLP-SG/VideoRefer-VideoLLaMA3-7B", help="Path to the model checkpoint")
337
- parser.add_argument("--prompt-mode", type=str, default="focal_prompt", help="Prompt mode")
338
- parser.add_argument("--conv-mode", type=str, default="v1", help="Conversation mode")
339
- parser.add_argument("--temperature", type=float, default=0.2, help="Sampling temperature")
340
- parser.add_argument("--top_p", type=float, default=0.5, help="Top-p for sampling")
341
-
342
- args_cli = parser.parse_args()
343
-
344
- with gr.Blocks(theme=gr.themes.Soft(primary_hue="amber")) as demo:
345
-
346
- mask_list = gr.State([])
347
- mask_raw_list = gr.State([])
348
- mask_list_video = gr.State([])
349
- mask_raw_list_video = gr.State([])
350
-
351
-
352
- HEADER = ("""
353
- <div>
354
- <h1>VideoRefer X VideoLLaMA3 Demo</h1>
355
- <h5 style="margin: 0;">Feel free to click on anything that grabs your interest!</h5>
356
- <h5 style="margin: 0;">If this demo please you, please give us a star ⭐ on Github or 💖 on this space.</h5>
357
- </div>
358
- </div>
359
- <div style="display: flex; justify-content: left; margin-top: 10px;">
360
- <a href="https://arxiv.org/pdf/2501.00599"><img src="https://img.shields.io/badge/Arxiv-2501.00599-ECA8A7" style="margin-right: 5px;"></a>
361
- <a href="https://github.com/DAMO-NLP-SG/VideoRefer"><img src='https://img.shields.io/badge/Github-VideoRefer-F7C97E' style="margin-right: 5px;"></a>
362
- <a href="https://github.com/DAMO-NLP-SG/VideoLLaMA3"><img src='https://img.shields.io/badge/Github-VideoLLaMA3-9DC3E6' style="margin-right: 5px;"></a>
363
- </div>
364
- """)
365
-
366
- with gr.Row():
367
- with gr.Column():
368
- gr.HTML(HEADER)
369
-
370
-
371
- image_tips = """
372
- ### 💡 Tips:
373
-
374
- 🧸 Upload an image, and you can use the drawing tool✍️ to highlight the areas you're interested in.
375
-
376
- 🔖 For single-object caption mode, simply select the area and click the 'Generate Caption' button to receive a caption for the object.
377
-
378
- 🔔 In QA mode, you can generate multiple masks by clicking the 'Generate Mask' button multiple times. Afterward, use the corresponding object id to ask questions.
379
-
380
- 📌 Click the button 'Clear Masks' to clear the current generated masks.
381
-
382
- """
383
-
384
- video_tips = """
385
- ### 💡 Tips:
386
- ⚠️ For video mode, we only support masking on the first frame in this demo.
387
-
388
- 🧸 Upload an video, and you can use the drawing tool✍️ to highlight the areas you're interested in the first frame.
389
-
390
- 🔖 For single-object caption mode, simply select the area and click the 'Generate Caption' button to receive a caption for the object.
391
-
392
- 🔔 In QA mode, you can generate multiple masks by clicking the 'Generate Mask' button multiple times. Afterward, use the corresponding object id to ask questions.
393
-
394
- 📌 Click the button 'Clear Masks' to clear the current generated masks.
395
-
396
- """
397
-
398
-
399
- with gr.TabItem("Image"):
400
- with gr.Row():
401
- with gr.Column():
402
- image_input = gr.ImageEditor(
403
- label="Image",
404
- type="pil",
405
- sources=['upload'],
406
- brush=gr.Brush(colors=["#ED7D31"], color_mode="fixed", default_size=10),
407
- eraser=True,
408
- layers=False,
409
- transforms=[],
410
- height=300,
411
- )
412
- generate_mask_btn = gr.Button("1️⃣ Generate Mask", visible=False, variant="primary")
413
- mode = gr.Radio(label="Mode", choices=["Caption", "QA"], value="Caption")
414
- query = gr.Textbox(label="Question", value="What is the relationship between <region0> and <region1>?", interactive=True, visible=False)
415
-
416
- submit_btn = gr.Button("Generate Caption", variant="primary")
417
- submit_btn1 = gr.Button("2️⃣ Generate Answer", variant="primary", visible=False)
418
- gr.Examples([f"./demo/images/{i+1}.jpg" for i in range(8)], inputs=image_input, label="Examples")
419
-
420
- with gr.Column():
421
- mask_output = gr.Gallery(label="Referred Masks", object_fit='scale-down', visible=False)
422
- output_image = gr.Image(label="Image with Mask", visible=True, height=400)
423
- description = gr.Textbox(label="Output", visible=True)
424
-
425
- clear_masks_btn = gr.Button("Clear Masks", variant="secondary", visible=False)
426
- gr.Markdown(image_tips)
427
-
428
- with gr.TabItem("Video"):
429
- with gr.Row():
430
- with gr.Column():
431
- video_input = gr.Video(label="Video")
432
- # load_btn = gr.Button("🖼️ Load First Frame", variant="secondary")
433
- first_frame = gr.ImageEditor(
434
- label="Annotate First Frame",
435
- type="pil",
436
- sources=['upload'],
437
- brush=gr.Brush(colors=["#ED7D31"], color_mode="fixed", default_size=10),
438
- eraser=True,
439
- layers=False,
440
- transforms=[],
441
- height=300,
442
- )
443
- generate_mask_btn_video = gr.Button("1️⃣ Generate Mask", visible=False, variant="primary")
444
- gr.Examples([f"./demo/videos/{i+1}.mp4" for i in range(4)], inputs=video_input, label="Examples")
445
-
446
- with gr.Column():
447
- mode_video = gr.Radio(label="Mode", choices=["Caption", "QA"], value="Caption")
448
- mask_output_video = gr.Gallery(label="Referred Masks", object_fit='scale-down')
449
-
450
- query_video = gr.Textbox(label="Question", value="What is the relationship between <object0> and <object1>?", interactive=True, visible=False)
451
-
452
- submit_btn_video = gr.Button("Generate Caption", variant="primary")
453
- submit_btn_video1 = gr.Button("2️⃣ Generate Answer", variant="primary", visible=False)
454
- description_video = gr.Textbox(label="Output", visible=True)
455
-
456
- clear_masks_btn_video = gr.Button("Clear Masks", variant="secondary")
457
-
458
- gr.Markdown(video_tips)
459
-
460
-
461
- def toggle_query_and_generate_button(mode):
462
- query_visible = mode == "QA"
463
- caption_visible = mode == "Caption"
464
- return gr.update(visible=query_visible), gr.update(visible=query_visible), gr.update(visible=query_visible), gr.update(visible=query_visible), gr.update(visible=query_visible), gr.update(visible=caption_visible), gr.update(visible=caption_visible), [], "", [], [],[],[]
465
-
466
- video_input.change(load_first_frame, inputs=video_input, outputs=first_frame)
467
-
468
- mode.change(toggle_query_and_generate_button, inputs=mode, outputs=[query, generate_mask_btn, clear_masks_btn, submit_btn1, mask_output, output_image, submit_btn, mask_output, description, mask_list, mask_raw_list, mask_list_video, mask_raw_list_video])
469
-
470
- def toggle_query_and_generate_button_video(mode):
471
- query_visible = mode == "QA"
472
- caption_visible = mode == "Caption"
473
- return gr.update(visible=query_visible), gr.update(visible=query_visible), gr.update(visible=query_visible), gr.update(visible=caption_visible), [], [], [], [], []
474
-
475
-
476
- mode_video.change(toggle_query_and_generate_button_video, inputs=mode_video, outputs=[query_video, generate_mask_btn_video, submit_btn_video1, submit_btn_video, mask_output_video, mask_list, mask_raw_list, mask_list_video, mask_raw_list_video])
477
-
478
- submit_btn.click(
479
- fn=describe,
480
- inputs=[image_input, mode, query, mask_raw_list],
481
- outputs=[output_image, description, image_input],
482
- api_name="describe"
483
- )
484
-
485
- submit_btn1.click(
486
- fn=describe,
487
- inputs=[image_input, mode, query, mask_raw_list],
488
- outputs=[output_image, description, image_input],
489
- api_name="describe"
490
- )
491
-
492
- generate_mask_btn.click(
493
- fn=generate_masks,
494
- inputs=[image_input, mask_list, mask_raw_list],
495
- outputs=[mask_output, image_input, mask_list, mask_raw_list]
496
- )
497
-
498
- generate_mask_btn_video.click(
499
- fn=generate_masks_video,
500
- inputs=[first_frame, mask_list_video, mask_raw_list_video],
501
- outputs=[mask_output_video, first_frame, mask_list_video, mask_raw_list_video]
502
- )
503
-
504
- clear_masks_btn.click(
505
- fn=clear_masks,
506
- outputs=[mask_output, mask_list, mask_raw_list]
507
- )
508
-
509
- clear_masks_btn_video.click(
510
- fn=clear_masks,
511
- outputs=[mask_output_video, mask_list_video, mask_raw_list_video]
512
- )
513
-
514
- submit_btn_video.click(
515
- fn=describe_video,
516
- inputs=[video_input, mode_video, query_video, first_frame, mask_raw_list_video, mask_list_video],
517
- outputs=[first_frame, description_video, mask_output_video, mask_list_video],
518
- api_name="describe_video"
519
- )
520
-
521
- submit_btn_video1.click(
522
- fn=describe_video,
523
- inputs=[video_input, mode_video, query_video, first_frame, mask_raw_list_video, mask_list_video],
524
- outputs=[first_frame, description_video, mask_output_video, mask_list_video],
525
- api_name="describe_video"
526
- )
527
-
528
-
529
-
530
- device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
531
- sam_model = SamModel.from_pretrained("facebook/sam-vit-huge").to(device)
532
- sam_processor = SamProcessor.from_pretrained("facebook/sam-vit-huge")
533
-
534
- disable_torch_init()
535
-
536
-
537
- model, processor, tokenizer = model_init(args_cli.model_path)
538
-
539
-
540
- demo.launch()
 
51
 
52
  @spaces.GPU(duration=120)
53
  def generate_masks(image, mask_list, mask_raw_list):
54
+ """
55
+ Generate masks from user-drawn annotations on an image.
56
+
57
+ Args:
58
+ image: Dictionary containing the image editor state with background and layers
59
+ mask_list: List of generated mask images with labels
60
+ mask_raw_list: List of raw numpy arrays of masks
61
+
62
+ Returns:
63
+ Tuple containing updated mask_list, image editor state, mask_list, and mask_raw_list
64
+ """
65
  image['image'] = image['background'].convert('RGB')
66
  # del image['background'], image['composite']
67
  assert len(image['layers']) == 1, f"Expected 1 layer, got {len(image['layers'])}"
 
88
 
89
  @spaces.GPU(duration=120)
90
  def generate_masks_video(image, mask_list_video, mask_raw_list_video):
91
+ """
92
+ Generate masks from user-drawn annotations on a video frame.
93
+
94
+ Args:
95
+ image: Dictionary containing the image editor state with background and layers
96
+ mask_list_video: List of generated mask images with labels for video
97
+ mask_raw_list_video: List of raw numpy arrays of masks for video
98
+
99
+ Returns:
100
+ Tuple containing updated mask_list_video, image editor state, mask_list_video, and mask_raw_list_video
101
+ """
102
  image['image'] = image['background'].convert('RGB')
103
  # del image['background'], image['composite']
104
  assert len(image['layers']) == 1, f"Expected 1 layer, got {len(image['layers'])}"
 
126
 
127
  @spaces.GPU(duration=120)
128
  def describe(image, mode, query, masks):
129
+ """
130
+ Generate descriptions or answer questions about regions in an image.
131
+
132
+ Args:
133
+ image: Dictionary containing the image editor state
134
+ mode: Either "Caption" or "QA" mode
135
+ query: Question to ask about the image (used in QA mode)
136
+ masks: List of mask arrays for the regions
137
+
138
+ Returns:
139
+ Generator yielding image with contours, generated text, and updated image state
140
+ """
141
  # Create an image object from the uploaded image
142
  # print(image.keys())
143
 
 
228
 
229
 
230
  def load_first_frame(video_path):
231
+ """
232
+ Load and return the first frame of a video.
233
+
234
+ Args:
235
+ video_path: Path to the video file
236
+
237
+ Returns:
238
+ PIL Image of the first frame
239
+ """
240
  cap = cv2.VideoCapture(video_path)
241
  ret, frame = cap.read()
242
  cap.release()
 
248
 
249
  @spaces.GPU(duration=120)
250
  def describe_video(video_path, mode, query, annotated_frame, masks, mask_list_video):
251
+ """
252
+ Generate descriptions or answer questions about regions in a video.
253
+
254
+ Args:
255
+ video_path: Path to the video file
256
+ mode: Either "Caption" or "QA" mode
257
+ query: Question to ask about the video (used in QA mode)
258
+ annotated_frame: Dictionary containing the annotated first frame
259
+ masks: List of mask arrays for the regions
260
+ mask_list_video: List of mask images with labels
261
+
262
+ Returns:
263
+ Generator yielding frame image, generated text, and updated mask lists
264
+ """
265
  # Create a temporary directory to save extracted video frames
266
  cap = cv2.VideoCapture(video_path)
267
 
 
351
  mask_image = Image.fromarray((mask_np[:,:,np.newaxis] * np.array(annotated_frame['image'])).astype(np.uint8))
352
  mask_list_video.append((mask_image, f"<object{len(mask_list_video)}>"))
353
  text = ""
354
+ yield frame_img, text, mask_list_video, mask_list_video