fffiloni commited on
Commit
5b4ff2c
·
verified ·
1 Parent(s): 5d4a1f3

feat: add advanced AniDoc controls in Gradio UI with documented settings for tracking, seed, sketch processing, and noise

Browse files
Files changed (1) hide show
  1. gradio_app.py +229 -82
gradio_app.py CHANGED
@@ -281,14 +281,23 @@ def load_control_images(control_path: str, width: int, height: int):
281
  return [img.resize((width, height)) for img in control_images]
282
 
283
 
284
- def build_sketch_condition(control_images, detector, width: int, height: int):
 
 
 
 
 
 
285
  controlnet_images = []
286
 
287
  for img in control_images:
288
  sketch = np.array(img)
289
  sketch = detector(sketch, coarse=False)
290
  sketch = np.repeat(sketch[:, :, np.newaxis], 3, axis=2)
291
- sketch = (sketch > 200).astype(np.uint8) * 255
 
 
 
292
  sketch = Image.fromarray(sketch).resize((width, height))
293
  controlnet_images.append(sketch)
294
 
@@ -301,7 +310,7 @@ def build_sketch_condition(control_images, detector, width: int, height: int):
301
  return controlnet_images, controlnet_sketch_condition
302
 
303
 
304
- def build_controlnet_condition(
305
  ref_image_pil,
306
  controlnet_images,
307
  controlnet_sketch_condition,
@@ -312,6 +321,10 @@ def build_controlnet_condition(
312
  height: int,
313
  num_frames: int,
314
  max_points: int,
 
 
 
 
315
  ):
316
  with torch.no_grad():
317
  ref_img_value = T.ToTensor()(ref_image_pil).to(DEVICE, dtype=torch.float16)
@@ -351,85 +364,102 @@ def build_controlnet_condition(
351
 
352
  conditional_pixel_values = ref_img_value.unsqueeze(0).unsqueeze(0)
353
  conditional_pixel_values = (conditional_pixel_values - 0.5) / 0.5
354
-
355
  point_map_with_ref = torch.cat([point_map, conditional_pixel_values], dim=2)
356
 
357
- video_for_tracker = (controlnet_sketch_condition * 0.5 + 0.5) * 255.0
358
- queries = np.insert(points1, 0, 0, axis=1)
359
- queries = torch.from_numpy(queries).to(DEVICE, torch.float32).unsqueeze(0)
360
-
361
- if queries.shape[1] == 0:
362
- tracked_mask1 = np.zeros((height, width), dtype=np.uint8)
363
- tracked_mask2 = np.zeros((num_frames, height, width), dtype=np.uint8)
364
- else:
365
- pred_tracks, pred_visibility = tracker(
366
- video_for_tracker.to(dtype=torch.float32),
367
- queries=queries,
368
- grid_size=8,
369
- grid_query_frame=0,
370
- backward_tracking=False,
371
  )
 
372
 
373
- pred_tracks_sampled, pred_visibility_sampled, points0_sampled = (
374
- sample_trajectories_with_ref(
375
- pred_tracks.cpu(),
376
- pred_visibility.cpu(),
377
- torch.from_numpy(points0).unsqueeze(0).cpu(),
378
- max_points=max_points,
379
- motion_threshold=1,
380
- vis_threshold=3,
381
- )
382
- )
383
 
384
- if pred_tracks_sampled is None:
385
  tracked_mask1 = np.zeros((height, width), dtype=np.uint8)
386
  tracked_mask2 = np.zeros((num_frames, height, width), dtype=np.uint8)
387
  else:
388
- pred_tracks_sampled = pred_tracks_sampled.squeeze(0).cpu().numpy()
389
- pred_visibility_sampled = pred_visibility_sampled.squeeze(0).cpu().numpy()
390
- points0_sampled = points0_sampled.squeeze(0).cpu().numpy()
391
-
392
- for frame_idx in range(num_frames):
393
- pred_tracks_sampled[frame_idx] = safe_round(
394
- pred_tracks_sampled[frame_idx],
395
- current_img.shape,
 
 
 
 
 
 
 
 
396
  )
 
397
 
398
- points0_sampled = safe_round(points0_sampled, current_img.shape)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
399
 
400
- tracked_mask1, tracked_mask2 = generate_point_map_frames(
401
- size=current_img.shape,
402
- coords0=points0_sampled,
403
- coords1=pred_tracks_sampled,
404
- visibility=pred_visibility_sampled,
405
- )
 
 
 
 
 
 
 
 
406
 
407
- tracked_point_map1 = (
408
- torch.from_numpy(tracked_mask1)
409
- .unsqueeze(0)
410
- .unsqueeze(0)
411
- .repeat(1, num_frames, 1, 1, 1)
412
- .to(DEVICE, dtype=torch.float16)
413
- )
414
- tracked_point_map2 = (
415
- torch.from_numpy(tracked_mask2)
416
- .unsqueeze(0)
417
- .unsqueeze(2)
418
- .to(DEVICE, dtype=torch.float16)
419
- )
420
- tracked_point_map = torch.cat([tracked_point_map1, tracked_point_map2], dim=2)
421
 
422
- conditional_pixel_values_repeat = conditional_pixel_values.repeat(
423
- 1, num_frames, 1, 1, 1
424
- )
425
- point_map_with_ref = torch.cat(
426
- [tracked_point_map, conditional_pixel_values_repeat], dim=2
427
- )
428
  controlnet_condition = torch.cat(
429
- [controlnet_sketch_condition, point_map_with_ref], dim=2
430
  )
431
-
432
- return controlnet_condition
433
 
434
 
435
  def run_anidoc(
@@ -442,6 +472,12 @@ def run_anidoc(
442
  num_frames: int = DEFAULT_NUM_FRAMES,
443
  seed: int = DEFAULT_SEED,
444
  max_points: int = DEFAULT_MAX_POINTS,
 
 
 
 
 
 
445
  ):
446
  pipe = models["pipe"]
447
  detector = models["detector"]
@@ -459,9 +495,10 @@ def run_anidoc(
459
  detector=detector,
460
  width=width,
461
  height=height,
 
462
  )
463
 
464
- controlnet_condition = build_controlnet_condition(
465
  ref_image_pil=ref_image_pil,
466
  controlnet_images=controlnet_images,
467
  controlnet_sketch_condition=controlnet_sketch_condition,
@@ -472,6 +509,10 @@ def run_anidoc(
472
  height=height,
473
  num_frames=num_frames,
474
  max_points=max_points,
 
 
 
 
475
  )
476
 
477
  input_fps = DEFAULT_FPS
@@ -494,7 +535,7 @@ def run_anidoc(
494
  decode_chunk_size=DEFAULT_DECODE_CHUNK_SIZE,
495
  motion_bucket_id=DEFAULT_MOTION_BUCKET_ID,
496
  fps=input_fps,
497
- noise_aug_strength=DEFAULT_NOISE_AUG,
498
  generator=generator,
499
  ).frames[0]
500
 
@@ -505,7 +546,6 @@ def run_anidoc(
505
 
506
  out_file = support_dir + ".mp4"
507
 
508
- # Keep the original helper for auxiliary outputs if needed.
509
  export_gif_side_by_side_complete_ablation(
510
  ref_image_pil,
511
  controlnet_images,
@@ -515,8 +555,9 @@ def run_anidoc(
515
  6,
516
  )
517
 
518
- # Final video returned to Gradio: written directly from generated frames
519
- final_output_path = os.path.join(support_dir, f"{ref_base_name}_{control_base_name}_final.mp4")
 
520
  final_output_path = write_video_frames_to_mp4(
521
  video_frames=video_frames,
522
  output_path=final_output_path,
@@ -536,7 +577,18 @@ def run_anidoc(
536
  # -----------------------------------------------------------------------------
537
 
538
  @spaces.GPU()
539
- def generate(control_sequence, ref_image, progress=gr.Progress(track_tqdm=True)):
 
 
 
 
 
 
 
 
 
 
 
540
  del progress
541
 
542
  if not control_sequence:
@@ -547,6 +599,9 @@ def generate(control_sequence, ref_image, progress=gr.Progress(track_tqdm=True))
547
  models = None
548
  output_dir = f"results_{uuid.uuid4()}"
549
 
 
 
 
550
  try:
551
  models = load_runtime_models()
552
 
@@ -558,8 +613,14 @@ def generate(control_sequence, ref_image, progress=gr.Progress(track_tqdm=True))
558
  width=DEFAULT_WIDTH,
559
  height=DEFAULT_HEIGHT,
560
  num_frames=DEFAULT_NUM_FRAMES,
561
- seed=DEFAULT_SEED,
562
- max_points=DEFAULT_MAX_POINTS,
 
 
 
 
 
 
563
  )
564
  return output_path
565
 
@@ -581,6 +642,10 @@ div#col-container {
581
  margin: 0 auto;
582
  max-width: 982px;
583
  }
 
 
 
 
584
  """
585
 
586
  with gr.Blocks(css=CSS) as demo:
@@ -617,24 +682,106 @@ with gr.Blocks(css=CSS) as demo:
617
  with gr.Column():
618
  control_sequence = gr.Video(label="Control Sequence", format="mp4")
619
  ref_image = gr.Image(label="Reference Image", type="filepath")
620
- submit_btn = gr.Button("Submit")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
621
 
622
  with gr.Column():
623
  video_result = gr.Video(label="Result")
624
 
625
  gr.Examples(
626
  examples=[
627
- ["data_test/sample1.mp4", "custom_examples/sample1.png"],
628
- ["data_test/sample2.mp4", "custom_examples/sample2.png"],
629
- ["data_test/sample3.mp4", "custom_examples/sample3.png"],
630
- ["data_test/sample4.mp4", "custom_examples/sample4.png"],
 
 
 
 
 
 
 
 
 
 
 
631
  ],
632
- inputs=[control_sequence, ref_image],
633
  )
634
 
 
 
 
 
 
 
 
 
635
  submit_btn.click(
636
  fn=generate,
637
- inputs=[control_sequence, ref_image],
 
 
 
 
 
 
 
 
 
 
638
  outputs=[video_result],
639
  api_visibility="private",
640
  )
 
281
  return [img.resize((width, height)) for img in control_images]
282
 
283
 
284
+ def build_sketch_condition(
285
+ control_images,
286
+ detector,
287
+ width: int,
288
+ height: int,
289
+ quantize_sketch: bool,
290
+ ):
291
  controlnet_images = []
292
 
293
  for img in control_images:
294
  sketch = np.array(img)
295
  sketch = detector(sketch, coarse=False)
296
  sketch = np.repeat(sketch[:, :, np.newaxis], 3, axis=2)
297
+
298
+ if quantize_sketch:
299
+ sketch = (sketch > 200).astype(np.uint8) * 255
300
+
301
  sketch = Image.fromarray(sketch).resize((width, height))
302
  controlnet_images.append(sketch)
303
 
 
310
  return controlnet_images, controlnet_sketch_condition
311
 
312
 
313
+ def build_matching_or_tracking_condition(
314
  ref_image_pil,
315
  controlnet_images,
316
  controlnet_sketch_condition,
 
321
  height: int,
322
  num_frames: int,
323
  max_points: int,
324
+ use_tracking: bool,
325
+ tracker_grid_size: int,
326
+ tracker_backward_tracking: bool,
327
+ repeat_matching: bool,
328
  ):
329
  with torch.no_grad():
330
  ref_img_value = T.ToTensor()(ref_image_pil).to(DEVICE, dtype=torch.float16)
 
364
 
365
  conditional_pixel_values = ref_img_value.unsqueeze(0).unsqueeze(0)
366
  conditional_pixel_values = (conditional_pixel_values - 0.5) / 0.5
 
367
  point_map_with_ref = torch.cat([point_map, conditional_pixel_values], dim=2)
368
 
369
+ if repeat_matching:
370
+ matching_controlnet_image = point_map_with_ref.repeat(1, num_frames, 1, 1, 1)
371
+ controlnet_condition = torch.cat(
372
+ [controlnet_sketch_condition, matching_controlnet_image], dim=2
 
 
 
 
 
 
 
 
 
 
373
  )
374
+ return controlnet_condition
375
 
376
+ if use_tracking:
377
+ video_for_tracker = (controlnet_sketch_condition * 0.5 + 0.5) * 255.0
378
+ queries = np.insert(points1, 0, 0, axis=1)
379
+ queries = torch.from_numpy(queries).to(DEVICE, torch.float32).unsqueeze(0)
 
 
 
 
 
 
380
 
381
+ if queries.shape[1] == 0:
382
  tracked_mask1 = np.zeros((height, width), dtype=np.uint8)
383
  tracked_mask2 = np.zeros((num_frames, height, width), dtype=np.uint8)
384
  else:
385
+ pred_tracks, pred_visibility = tracker(
386
+ video_for_tracker.to(dtype=torch.float32),
387
+ queries=queries,
388
+ grid_size=tracker_grid_size,
389
+ grid_query_frame=0,
390
+ backward_tracking=tracker_backward_tracking,
391
+ )
392
+
393
+ pred_tracks_sampled, pred_visibility_sampled, points0_sampled = (
394
+ sample_trajectories_with_ref(
395
+ pred_tracks.cpu(),
396
+ pred_visibility.cpu(),
397
+ torch.from_numpy(points0).unsqueeze(0).cpu(),
398
+ max_points=max_points,
399
+ motion_threshold=1,
400
+ vis_threshold=3,
401
  )
402
+ )
403
 
404
+ if pred_tracks_sampled is None:
405
+ tracked_mask1 = np.zeros((height, width), dtype=np.uint8)
406
+ tracked_mask2 = np.zeros((num_frames, height, width), dtype=np.uint8)
407
+ else:
408
+ pred_tracks_sampled = pred_tracks_sampled.squeeze(0).cpu().numpy()
409
+ pred_visibility_sampled = pred_visibility_sampled.squeeze(0).cpu().numpy()
410
+ points0_sampled = points0_sampled.squeeze(0).cpu().numpy()
411
+
412
+ for frame_idx in range(num_frames):
413
+ pred_tracks_sampled[frame_idx] = safe_round(
414
+ pred_tracks_sampled[frame_idx],
415
+ current_img.shape,
416
+ )
417
+
418
+ points0_sampled = safe_round(points0_sampled, current_img.shape)
419
+
420
+ tracked_mask1, tracked_mask2 = generate_point_map_frames(
421
+ size=current_img.shape,
422
+ coords0=points0_sampled,
423
+ coords1=pred_tracks_sampled,
424
+ visibility=pred_visibility_sampled,
425
+ )
426
 
427
+ tracked_point_map1 = (
428
+ torch.from_numpy(tracked_mask1)
429
+ .unsqueeze(0)
430
+ .unsqueeze(0)
431
+ .repeat(1, num_frames, 1, 1, 1)
432
+ .to(DEVICE, dtype=torch.float16)
433
+ )
434
+ tracked_point_map2 = (
435
+ torch.from_numpy(tracked_mask2)
436
+ .unsqueeze(0)
437
+ .unsqueeze(2)
438
+ .to(DEVICE, dtype=torch.float16)
439
+ )
440
+ tracked_point_map = torch.cat([tracked_point_map1, tracked_point_map2], dim=2)
441
 
442
+ conditional_pixel_values_repeat = conditional_pixel_values.repeat(
443
+ 1, num_frames, 1, 1, 1
444
+ )
445
+ point_map_with_ref = torch.cat(
446
+ [tracked_point_map, conditional_pixel_values_repeat], dim=2
447
+ )
448
+ controlnet_condition = torch.cat(
449
+ [controlnet_sketch_condition, point_map_with_ref], dim=2
450
+ )
451
+ return controlnet_condition
 
 
 
 
452
 
453
+ original_shape = list(point_map_with_ref.shape)
454
+ new_shape = original_shape.copy()
455
+ new_shape[1] = num_frames - 1
456
+
457
+ zero_tensor = torch.zeros(new_shape).to(DEVICE, dtype=torch.float16)
458
+ matching_controlnet_image = torch.cat((point_map_with_ref, zero_tensor), dim=1)
459
  controlnet_condition = torch.cat(
460
+ [controlnet_sketch_condition, matching_controlnet_image], dim=2
461
  )
462
+ return controlnet_condition
 
463
 
464
 
465
  def run_anidoc(
 
472
  num_frames: int = DEFAULT_NUM_FRAMES,
473
  seed: int = DEFAULT_SEED,
474
  max_points: int = DEFAULT_MAX_POINTS,
475
+ noise_aug: float = DEFAULT_NOISE_AUG,
476
+ use_tracking: bool = True,
477
+ repeat_matching: bool = False,
478
+ quantize_sketch: bool = True,
479
+ tracker_grid_size: int = 8,
480
+ tracker_backward_tracking: bool = False,
481
  ):
482
  pipe = models["pipe"]
483
  detector = models["detector"]
 
495
  detector=detector,
496
  width=width,
497
  height=height,
498
+ quantize_sketch=quantize_sketch,
499
  )
500
 
501
+ controlnet_condition = build_matching_or_tracking_condition(
502
  ref_image_pil=ref_image_pil,
503
  controlnet_images=controlnet_images,
504
  controlnet_sketch_condition=controlnet_sketch_condition,
 
509
  height=height,
510
  num_frames=num_frames,
511
  max_points=max_points,
512
+ use_tracking=use_tracking,
513
+ tracker_grid_size=tracker_grid_size,
514
+ tracker_backward_tracking=tracker_backward_tracking,
515
+ repeat_matching=repeat_matching,
516
  )
517
 
518
  input_fps = DEFAULT_FPS
 
535
  decode_chunk_size=DEFAULT_DECODE_CHUNK_SIZE,
536
  motion_bucket_id=DEFAULT_MOTION_BUCKET_ID,
537
  fps=input_fps,
538
+ noise_aug_strength=noise_aug,
539
  generator=generator,
540
  ).frames[0]
541
 
 
546
 
547
  out_file = support_dir + ".mp4"
548
 
 
549
  export_gif_side_by_side_complete_ablation(
550
  ref_image_pil,
551
  controlnet_images,
 
555
  6,
556
  )
557
 
558
+ final_output_path = os.path.join(
559
+ support_dir, f"{ref_base_name}_{control_base_name}_final.mp4"
560
+ )
561
  final_output_path = write_video_frames_to_mp4(
562
  video_frames=video_frames,
563
  output_path=final_output_path,
 
577
  # -----------------------------------------------------------------------------
578
 
579
  @spaces.GPU()
580
+ def generate(
581
+ control_sequence,
582
+ ref_image,
583
+ seed,
584
+ max_points,
585
+ mode,
586
+ noise_aug,
587
+ quantize_sketch,
588
+ tracker_grid_size,
589
+ tracker_backward_tracking,
590
+ progress=gr.Progress(track_tqdm=True),
591
+ ):
592
  del progress
593
 
594
  if not control_sequence:
 
599
  models = None
600
  output_dir = f"results_{uuid.uuid4()}"
601
 
602
+ use_tracking = mode == "Tracking"
603
+ repeat_matching = mode == "Repeat matching"
604
+
605
  try:
606
  models = load_runtime_models()
607
 
 
613
  width=DEFAULT_WIDTH,
614
  height=DEFAULT_HEIGHT,
615
  num_frames=DEFAULT_NUM_FRAMES,
616
+ seed=int(seed),
617
+ max_points=int(max_points),
618
+ noise_aug=float(noise_aug),
619
+ use_tracking=use_tracking,
620
+ repeat_matching=repeat_matching,
621
+ quantize_sketch=bool(quantize_sketch),
622
+ tracker_grid_size=int(tracker_grid_size),
623
+ tracker_backward_tracking=bool(tracker_backward_tracking),
624
  )
625
  return output_path
626
 
 
642
  margin: 0 auto;
643
  max-width: 982px;
644
  }
645
+ .small-note {
646
+ font-size: 0.92em;
647
+ opacity: 0.9;
648
+ }
649
  """
650
 
651
  with gr.Blocks(css=CSS) as demo:
 
682
  with gr.Column():
683
  control_sequence = gr.Video(label="Control Sequence", format="mp4")
684
  ref_image = gr.Image(label="Reference Image", type="filepath")
685
+ submit_btn = gr.Button("Submit", variant="primary")
686
+
687
+ with gr.Accordion("Advanced settings", open=False):
688
+ seed = gr.Number(
689
+ value=DEFAULT_SEED,
690
+ precision=0,
691
+ label="Seed",
692
+ info="Use the same seed to reproduce a similar result with the same inputs and settings.",
693
+ )
694
+
695
+ max_points = gr.Slider(
696
+ minimum=5,
697
+ maximum=30,
698
+ value=DEFAULT_MAX_POINTS,
699
+ step=1,
700
+ label="Tracking points",
701
+ info="Maximum number of motion points kept for correspondence tracking. More points can improve motion guidance but may add instability or compute cost.",
702
+ )
703
+
704
+ mode = gr.Radio(
705
+ choices=["Tracking", "Matching only", "Repeat matching"],
706
+ value="Tracking",
707
+ label="Motion guidance mode",
708
+ info="Tracking usually gives the best temporal consistency. Matching only is simpler. Repeat matching reuses the same matching signal across frames.",
709
+ )
710
+
711
+ noise_aug = gr.Slider(
712
+ minimum=0.0,
713
+ maximum=0.10,
714
+ value=DEFAULT_NOISE_AUG,
715
+ step=0.01,
716
+ label="Noise augmentation",
717
+ info="Controls how much noise is added before generation. Small changes can affect stylization and stability.",
718
+ )
719
+
720
+ quantize_sketch = gr.Checkbox(
721
+ value=True,
722
+ label="Quantize extracted sketch",
723
+ info="Turns the extracted line art into a stronger black-and-white sketch. Usually helps keep lines cleaner and more stable.",
724
+ )
725
+
726
+ tracker_grid_size = gr.Slider(
727
+ minimum=4,
728
+ maximum=16,
729
+ value=8,
730
+ step=1,
731
+ label="Tracker grid size",
732
+ info="Controls the density of the tracking grid. Smaller values can track more densely but may cost more computation.",
733
+ )
734
+
735
+ tracker_backward_tracking = gr.Checkbox(
736
+ value=False,
737
+ label="Backward tracking",
738
+ info="Tracks points in both directions instead of only forward. Can sometimes improve difficult motion, but may be slower.",
739
+ )
740
 
741
  with gr.Column():
742
  video_result = gr.Video(label="Result")
743
 
744
  gr.Examples(
745
  examples=[
746
+ ["data_test/sample1.mp4", "custom_examples/sample1.png", DEFAULT_SEED, 10, "Tracking", 0.02, True, 8, False],
747
+ ["data_test/sample2.mp4", "custom_examples/sample2.png", DEFAULT_SEED, 10, "Tracking", 0.02, True, 8, False],
748
+ ["data_test/sample3.mp4", "custom_examples/sample3.png", DEFAULT_SEED, 10, "Tracking", 0.02, True, 8, False],
749
+ ["data_test/sample4.mp4", "custom_examples/sample4.png", DEFAULT_SEED, 10, "Tracking", 0.02, True, 8, False],
750
+ ],
751
+ inputs=[
752
+ control_sequence,
753
+ ref_image,
754
+ seed,
755
+ max_points,
756
+ mode,
757
+ noise_aug,
758
+ quantize_sketch,
759
+ tracker_grid_size,
760
+ tracker_backward_tracking,
761
  ],
 
762
  )
763
 
764
+ gr.Markdown(
765
+ '<div class="small-note">'
766
+ "<b>Tips:</b> Tracking mode is the best default choice. "
767
+ "If the result feels too unstable, try lowering Tracking points or disabling Backward tracking. "
768
+ "If the sketch looks too soft, keep sketch quantization enabled."
769
+ "</div>"
770
+ )
771
+
772
  submit_btn.click(
773
  fn=generate,
774
+ inputs=[
775
+ control_sequence,
776
+ ref_image,
777
+ seed,
778
+ max_points,
779
+ mode,
780
+ noise_aug,
781
+ quantize_sketch,
782
+ tracker_grid_size,
783
+ tracker_backward_tracking,
784
+ ],
785
  outputs=[video_result],
786
  api_visibility="private",
787
  )