forked from Lightricks/LTX-2
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathlt1.py
More file actions
5858 lines (5271 loc) · 267 KB
/
lt1.py
File metadata and controls
5858 lines (5271 loc) · 267 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""
LTX-2 Video Generation UI (lt1.py)
Gradio-based web interface for LTX-2 video generation with:
- Two-stage pipeline (low-res + hi-res refinement)
- Joint audio-video generation
- Image conditioning (I2V)
- LoRA support
- Memory optimization (offload, FP8, block swap)
- Prompt enhancement with Gemma
"""
import os
import sys
import signal
# Try to use local patched gradio from modules/ if available (allows jobs to continue after browser disconnect)
_modules_path = os.path.join(os.path.dirname(os.path.abspath(__file__)), "modules")
if os.path.exists(_modules_path):
sys.path.insert(0, _modules_path)
import gradio as gr
from gradio import themes
from gradio.themes.utils import colors
import time
import random
import subprocess
import re
from typing import Generator, List, Tuple, Optional, Dict
import threading
import json
from PIL import Image
from pathlib import Path
import tempfile
import shutil
# Global state
stop_event = threading.Event()
current_process = None
current_output_filename = None
# Defaults configuration
UI_CONFIGS_DIR = "ui_configs"
LT1_DEFAULTS_FILE = os.path.join(UI_CONFIGS_DIR, "lt1_defaults.json")
# =============================================================================
# Progress Parsing
# =============================================================================
def parse_ltx_progress_line(line: str) -> Optional[str]:
"""Parse LTX-2 generation progress output."""
line = line.strip()
# LTX-specific progress messages
if ">>> Loading text encoder" in line:
return "Loading text encoder..."
if ">>> Enhancing prompt" in line:
return "Enhancing prompt with Gemma..."
if ">>> Encoding prompts" in line:
return "Encoding text prompts..."
# One-stage pipeline
if ">>> One-stage: Loading" in line:
return "One-stage: Loading models..."
if ">>> One-stage: Generating" in line:
return "One-stage: Generating at full resolution..."
if ">>> One-stage completed" in line:
match = re.search(r'(\d+\.?\d*)s', line)
if match:
return f"One-stage completed ({match.group(1)}s)"
# Refine-only pipeline
if ">>> Refine-only mode" in line:
return "Refine-only: Loading input video..."
if ">>> Input video encoded" in line:
match = re.search(r'(\d+\.?\d*)s', line)
if match:
return f"Video encoded ({match.group(1)}s)"
# Two-stage pipeline
if ">>> Stage 1: Loading" in line:
return "Stage 1: Loading models..."
if ">>> Stage 1: Generating" in line:
return "Stage 1: Low-res generation..."
if ">>> Stage 1 completed" in line:
match = re.search(r'(\d+\.?\d*)s', line)
if match:
return f"Stage 1 completed ({match.group(1)}s)"
if ">>> Upsampling" in line:
return "Upsampling latents (2x)..."
if ">>> Stage 2: Loading" in line:
return "Stage 2: Loading refined model..."
if ">>> Stage 2: Refining" in line:
return "Stage 2: Hi-res refinement..."
if ">>> Stage 2 completed" in line:
match = re.search(r'(\d+\.?\d*)s', line)
if match:
return f"Stage 2 completed ({match.group(1)}s)"
# Stage 3 progress
if ">>> Stage 3: Loading" in line:
return "Stage 3: Loading transformer..."
if ">>> Stage 3: Refining" in line:
return "Stage 3: Final refinement..."
if ">>> Stage 3 completed" in line:
match = re.search(r'(\d+\.?\d*)s', line)
if match:
return f"Stage 3 completed ({match.group(1)}s)"
if ">>> Linear mode: skipping upsampling" in line:
return "Linear mode: same resolution..."
if ">>> Decoding video" in line:
return "Decoding video from latents..."
if ">>> Decoding audio" in line:
return "Decoding audio..."
if ">>> Encoding video" in line:
return "Encoding video to MP4..."
# AV Extension mode
if "AV Extension Mode" in line:
return "AV Extension: Starting..."
if "[AV Extension] Video mask" in line:
return "AV Extension: Creating video mask..."
if "[AV Extension] Audio mask" in line:
return "AV Extension: Creating audio mask..."
if ">>> Running masked denoising" in line:
return "AV Extension: Masked denoising..."
if ">>> Creating extended latent" in line:
return "AV Extension: Creating extended latent space..."
if ">>> Extracting audio from input" in line:
return "AV Extension: Extracting audio..."
if ">>> Encoding video to latent" in line:
return "AV Extension: Encoding video to latent..."
if ">>> Done!" in line:
return "Generation complete!"
if ">>> Total generation time" in line:
match = re.search(r'(\d+\.?\d*)s', line)
if match:
return f"Total time: {match.group(1)}s"
# TQDM progress bar parsing
match = re.search(r'(\d+)%\|.*?\|\s*(\d+)/(\d+)\s*\[.*?<([\d:]+)', line)
if match:
percent = match.group(1)
current = match.group(2)
total = match.group(3)
eta = match.group(4)
return f"Denoising: {percent}% ({current}/{total}) ETA: {eta}"
return None
# =============================================================================
# LoRA Discovery
# =============================================================================
def get_ltx_lora_options(lora_folder: str = "lora") -> List[str]:
"""
Discover LTX LoRAs in the specified folder.
Returns ['None'] + list of .safetensors files.
"""
if not os.path.exists(lora_folder):
return ["None"]
lora_items = []
for item in os.listdir(lora_folder):
if item.endswith(".safetensors"):
lora_items.append(item)
lora_items.sort(key=str.lower)
return ["None"] + lora_items
def refresh_lora_dropdown(lora_folder: str):
"""Refresh LoRA dropdown choices."""
new_choices = get_ltx_lora_options(lora_folder)
return gr.update(choices=new_choices, value="None")
# =============================================================================
# Validation
# =============================================================================
def validate_num_frames(num_frames: int) -> Optional[str]:
"""Validate num_frames is in 8*K + 1 format."""
if (num_frames - 1) % 8 != 0:
valid_examples = [8*k + 1 for k in range(1, 20)]
return f"Error: num_frames must be 8*K + 1 (e.g., {', '.join(map(str, valid_examples[:5]))}...)"
return None
def validate_resolution(width: int, height: int) -> Optional[str]:
"""Validate resolution is divisible by 64."""
if width % 64 != 0 or height % 64 != 0:
return f"Error: width ({width}) and height ({height}) must be divisible by 64"
return None
def validate_model_paths(checkpoint_path: str, spatial_upsampler_path: str,
distilled_lora_path: str, gemma_root: str,
is_one_stage: bool = False,
is_refine_only: bool = False) -> Optional[str]:
"""Validate all required model paths exist."""
# Core paths required for all pipelines
paths = [
("LTX Checkpoint", checkpoint_path),
("Gemma Root", gemma_root),
]
# Two-stage specific paths (spatial upsampler always needed for two-stage)
if not is_one_stage and not is_refine_only:
paths.extend([
("Spatial Upsampler", spatial_upsampler_path),
("Distilled LoRA", distilled_lora_path),
])
# Refine-only: distilled LoRA is optional, but validate if provided
if is_refine_only:
# Only validate distilled LoRA if path is provided
if distilled_lora_path and distilled_lora_path.strip():
paths.append(("Distilled LoRA", distilled_lora_path))
for name, path in paths:
if not path or not path.strip():
return f"Error: {name} path is required"
if not os.path.exists(path):
return f"Error: {name} not found: {path}"
return None
# =============================================================================
# Image Dimension Helpers
# =============================================================================
def update_image_dimensions(image_path):
"""Update original dimensions when image is uploaded."""
if image_path is None:
return "", gr.update(), gr.update()
try:
img = Image.open(image_path)
w, h = img.size
original_dims_str = f"{w}x{h}"
# Calculate dimensions snapped to nearest multiple of 32 while maintaining aspect ratio
new_w = round(w / 32) * 32
new_h = round(h / 32) * 32
new_w = max(32, new_w)
new_h = max(32, new_h)
return original_dims_str, gr.update(value=new_w), gr.update(value=new_h)
except Exception as e:
print(f"Error reading image dimensions: {e}")
return "", gr.update(), gr.update()
def update_resolution_from_scale(scale, original_dims):
"""Update dimensions based on scale percentage (divisible by 64)."""
if not original_dims:
return gr.update(), gr.update()
try:
scale = float(scale) if scale is not None else 100.0
if scale <= 0:
scale = 100.0
orig_w, orig_h = map(int, original_dims.split('x'))
scale_factor = scale / 100.0
# Calculate and round to the nearest multiple of 64
new_w = round((orig_w * scale_factor) / 64) * 64
new_h = round((orig_h * scale_factor) / 64) * 64
# Ensure minimum size (must be multiple of 64)
new_w = max(64, new_w)
new_h = max(64, new_h)
return gr.update(value=new_w), gr.update(value=new_h)
except Exception as e:
print(f"Error updating from scale: {e}")
return gr.update(), gr.update()
def calculate_width_from_height(height, original_dims):
"""Calculate width based on height maintaining aspect ratio (divisible by 64)."""
if not original_dims or height is None:
return gr.update()
try:
height = int(height)
if height <= 0:
return gr.update()
height = (height // 64) * 64
height = max(64, height)
orig_w, orig_h = map(int, original_dims.split('x'))
if orig_h == 0:
return gr.update()
aspect_ratio = orig_w / orig_h
new_width = round((height * aspect_ratio) / 64) * 64
return gr.update(value=max(64, new_width))
except Exception as e:
print(f"Error calculating width: {e}")
return gr.update()
def calculate_height_from_width(width, original_dims):
"""Calculate height based on width maintaining aspect ratio (divisible by 64)."""
if not original_dims or width is None:
return gr.update()
try:
width = int(width)
if width <= 0:
return gr.update()
width = (width // 64) * 64
width = max(64, width)
orig_w, orig_h = map(int, original_dims.split('x'))
if orig_w == 0:
return gr.update()
aspect_ratio = orig_w / orig_h
new_height = round((width / aspect_ratio) / 64) * 64
return gr.update(value=max(64, new_height))
except Exception as e:
print(f"Error calculating height: {e}")
return gr.update()
def get_video_info(video_path: str) -> dict:
"""Get video information using PyAV."""
try:
import av
with av.open(video_path) as container:
# Get first video stream
video_stream = container.streams.video[0]
width = video_stream.width
height = video_stream.height
# Calculate FPS from average_rate or guessed_rate
if video_stream.average_rate:
fps = float(video_stream.average_rate)
elif video_stream.guessed_rate:
fps = float(video_stream.guessed_rate)
else:
fps = 30.0 # fallback
# Calculate duration
if video_stream.duration and video_stream.time_base:
duration = float(video_stream.duration * video_stream.time_base)
elif container.duration:
duration = container.duration / av.time_base
else:
duration = 0
total_frames = int(video_stream.frames) if video_stream.frames else int(duration * fps)
return {
'width': width,
'height': height,
'fps': fps,
'total_frames': total_frames,
'duration': duration
}
except Exception as e:
print(f"Error extracting video info: {e}")
return {}
def update_depth_control_status(video_path: str, image_path: str) -> str:
"""Get status info for depth control video or image."""
if video_path and os.path.exists(video_path):
info = get_video_info(video_path)
if info:
w = info.get("width", 0)
h = info.get("height", 0)
fps = info.get("fps", 0)
frames = info.get("total_frames", 0)
return f"Video: {w}x{h} | {fps:.2f} FPS | {frames} frames"
return "Video: Unable to read info"
elif image_path and os.path.exists(image_path):
try:
img = Image.open(image_path)
w, h = img.size
return f"Image: {w}x{h} | N/A FPS | 1 frame"
except Exception:
return "Image: Unable to read info"
return "No depth map loaded"
def update_video_dimensions(video_path):
"""Update dimensions and frame count when video is uploaded."""
if video_path is None:
return "", gr.update(), gr.update(), gr.update(), gr.update()
try:
info = get_video_info(video_path)
if info:
w, h = info.get("width", 0), info.get("height", 0)
if w and h:
original_dims_str = f"{w}x{h}"
# Snap to nearest multiple of 32
new_w = round(w / 32) * 32
new_h = round(h / 32) * 32
new_w = max(32, new_w)
new_h = max(32, new_h)
# Calculate frame count (snap to 8*K+1 format)
if info.get("total_frames"):
num_frames = info["total_frames"]
elif info.get("duration") and info.get("fps"):
num_frames = int(info["duration"] * info["fps"])
else:
num_frames = 121
# Snap to nearest 8*K+1
k = max(1, round((num_frames - 1) / 8))
num_frames = 8 * k + 1
fps = info.get("fps", 24)
return original_dims_str, gr.update(value=new_w), gr.update(value=new_h), gr.update(value=num_frames), gr.update(value=int(fps))
except Exception as e:
print(f"Error reading video dimensions: {e}")
return "", gr.update(), gr.update(), gr.update(), gr.update()
def extract_video_metadata(video_path: str) -> dict:
"""Extract metadata from video file using PyAV."""
try:
import av
with av.open(video_path) as container:
# Get comment metadata from container
comment = container.metadata.get('comment', '{}')
return json.loads(comment)
except Exception as e:
print(f"Metadata extraction failed: {str(e)}")
return {}
def add_metadata_to_video(video_path: str, parameters: dict) -> None:
"""Add generation parameters to video metadata using ffmpeg."""
# Convert parameters to JSON string
params_json = json.dumps(parameters, indent=2)
# Temporary output path
temp_path = video_path.replace(".mp4", "_temp.mp4")
# FFmpeg command to add metadata without re-encoding
cmd = [
'ffmpeg',
'-i', video_path,
'-metadata', f'comment={params_json}',
'-codec', 'copy',
temp_path
]
try:
# Execute FFmpeg command
subprocess.run(cmd, check=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
# Replace original file with the metadata-enhanced version
os.replace(temp_path, video_path)
except subprocess.CalledProcessError as e:
print(f"Failed to add metadata: {e.stderr.decode()}")
if os.path.exists(temp_path):
os.remove(temp_path)
except Exception as e:
print(f"Error: {str(e)}")
def extract_first_frame(video_path: str, output_dir: str = "outputs") -> Optional[str]:
"""Extract the first frame from a video file."""
try:
import av
os.makedirs(output_dir, exist_ok=True)
with av.open(video_path) as container:
stream = container.streams.video[0]
for frame in container.decode(stream):
# Convert to PIL Image and save
img = frame.to_image()
# Save with unique name based on source video
base_name = os.path.splitext(os.path.basename(video_path))[0]
output_path = os.path.join(output_dir, f"{base_name}_frame0.png")
img.save(output_path)
return output_path
except Exception as e:
print(f"Error extracting first frame: {e}")
return None
def extract_video_details(video_path: str) -> Tuple[dict, str, Optional[str]]:
"""Extract metadata, video information, and first frame."""
metadata = extract_video_metadata(video_path)
video_details = get_video_info(video_path)
# Combine metadata with video details
for key, value in video_details.items():
if key not in metadata:
metadata[key] = value
# Extract first frame
first_frame_path = extract_first_frame(video_path)
# Return metadata, status message, and first frame path
return metadata, "Video details extracted successfully", first_frame_path
# =============================================================================
# GIMM-VFI Frame Interpolation
# =============================================================================
def _gimm_set_seed(seed=None):
"""Set random seed for reproducibility (inlined from GIMM-VFI)."""
import random
import numpy as np
import torch
if seed is None:
seed = random.getrandbits(32)
random.seed(seed)
np.random.seed(seed)
torch.manual_seed(seed)
torch.cuda.manual_seed_all(seed)
return seed
class _GIMMInputPadder:
"""Pads images such that dimensions are divisible by divisor (inlined from GIMM-VFI)."""
def __init__(self, dims, divisor=16):
import torch.nn.functional as F
self.F = F
self.ht, self.wd = dims[-2:]
pad_ht = (((self.ht // divisor) + 1) * divisor - self.ht) % divisor
pad_wd = (((self.wd // divisor) + 1) * divisor - self.wd) % divisor
self._pad = [
pad_wd // 2,
pad_wd - pad_wd // 2,
pad_ht // 2,
pad_ht - pad_ht // 2,
]
def pad(self, *inputs):
if len(inputs) == 1:
return self.F.pad(inputs[0], self._pad, mode="replicate")
else:
return [self.F.pad(x, self._pad, mode="replicate") for x in inputs]
def unpad(self, *inputs):
if len(inputs) == 1:
return self._unpad(inputs[0])
else:
return [self._unpad(x) for x in inputs]
def _unpad(self, x):
ht, wd = x.shape[-2:]
c = [self._pad[2], ht - self._pad[3], self._pad[0], wd - self._pad[1]]
return x[..., c[0] : c[1], c[2] : c[3]]
# Model variant configurations
GIMM_MODELS = {
"GIMM-VFI-R (RAFT)": {
"type": "gimm",
"config": "GIMM-VFI/configs/gimmvfi/gimmvfi_r_arb.yaml",
"checkpoint": "GIMM-VFI/pretrained_ckpt/gimmvfi_r_arb.pt",
},
"GIMM-VFI-R-P (RAFT+Perceptual)": {
"type": "gimm",
"config": "GIMM-VFI/configs/gimmvfi/gimmvfi_r_arb.yaml",
"checkpoint": "GIMM-VFI/pretrained_ckpt/gimmvfi_r_arb_lpips.pt",
},
"GIMM-VFI-F (FlowFormer)": {
"type": "gimm",
"config": "GIMM-VFI/configs/gimmvfi/gimmvfi_f_arb.yaml",
"checkpoint": "GIMM-VFI/pretrained_ckpt/gimmvfi_f_arb.pt",
},
"GIMM-VFI-F-P (FlowFormer+Perceptual)": {
"type": "gimm",
"config": "GIMM-VFI/configs/gimmvfi/gimmvfi_f_arb.yaml",
"checkpoint": "GIMM-VFI/pretrained_ckpt/gimmvfi_f_arb_lpips.pt",
},
"BiM-VFI (Bidirectional Motion)": {
"type": "bim",
"checkpoint": "GIMM-VFI/pretrained_ckpt/bim_vfi.pth",
},
}
# Upscaler model configurations
UPSCALER_MODELS = {
"Real-ESRGAN x2": {
"type": "esrgan",
"scale": 2,
"checkpoint": "GIMM-VFI/pretrained_ckpt/RealESRGAN_x2plus.pth",
},
"Real-ESRGAN x4": {
"type": "esrgan",
"scale": 4,
"checkpoint": "GIMM-VFI/pretrained_ckpt/RealESRGAN_x4plus.pth",
},
"SwinIR x4": {
"type": "swinir",
"scale": 4,
"checkpoint": "GIMM-VFI/pretrained_ckpt/003_realSR_BSRGAN_DFOWMFC_s64w8_SwinIR-L_x4_GAN.pth",
},
"BasicVSR++ x4 (Temporal)": {
"type": "basicvsr",
"scale": 4,
"checkpoint": "GIMM-VFI/pretrained_ckpt/basicvsr_plusplus_reds4.pth",
"hf_repo": "maybleMyers/interpolate",
"hf_filename": "basicvsr_plusplus_reds4.pth",
},
}
# Global cache for GIMM-VFI model
_gimm_model_cache = {"model": None, "variant": None}
# Global cache for BiM-VFI model
_bim_model_cache = {"model": None, "variant": None}
def _load_gimm_model(model_variant: str, checkpoint_path: str = "", config_path: str = ""):
"""Load GIMM-VFI model with caching."""
import torch
# Get paths
script_dir = os.path.dirname(os.path.abspath(__file__))
gimm_dir = os.path.join(script_dir, "GIMM-VFI")
gimm_src_path = os.path.join(gimm_dir, "src")
# Add GIMM-VFI to path
if gimm_src_path not in sys.path:
sys.path.insert(0, gimm_src_path)
from models import create_model
from utils.setup import single_setup
# Use defaults if not specified
model_info = GIMM_MODELS.get(model_variant, GIMM_MODELS["GIMM-VFI-R-P (RAFT+Perceptual)"])
config_file = config_path if config_path else model_info["config"]
ckpt_file = checkpoint_path if checkpoint_path else model_info["checkpoint"]
# Check if already loaded
cache_key = f"{model_variant}:{ckpt_file}"
if _gimm_model_cache["model"] is not None and _gimm_model_cache["variant"] == cache_key:
return _gimm_model_cache["model"]
# Clear old model from GPU
if _gimm_model_cache["model"] is not None:
del _gimm_model_cache["model"]
_gimm_model_cache["model"] = None
torch.cuda.empty_cache()
# Setup config via argparse.Namespace (required by GIMM-VFI single_setup)
# Use absolute path for config file
import argparse
abs_config_file = os.path.join(script_dir, config_file) if not os.path.isabs(config_file) else config_file
args = argparse.Namespace(
eval=True,
resume=False,
seed=0,
model_config=abs_config_file,
)
config = single_setup(args, extra_args=[])
# Create model - need to change to GIMM-VFI dir because RAFT uses relative paths
original_cwd = os.getcwd()
try:
os.chdir(gimm_dir)
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
model, _ = create_model(config.arch)
model = model.to(device)
finally:
os.chdir(original_cwd)
# Load checkpoint (use absolute path)
abs_ckpt_file = os.path.join(script_dir, ckpt_file) if not os.path.isabs(ckpt_file) else ckpt_file
if os.path.exists(abs_ckpt_file):
ckpt = torch.load(abs_ckpt_file, map_location="cpu")
model.load_state_dict(ckpt["state_dict"], strict=True)
else:
raise FileNotFoundError(f"Checkpoint not found: {abs_ckpt_file}")
model.eval()
# Cache the model
_gimm_model_cache["model"] = model
_gimm_model_cache["variant"] = cache_key
return model
def _load_bim_model(checkpoint_path: str = ""):
"""Load BiM-VFI model with caching."""
import torch
script_dir = os.path.dirname(os.path.abspath(__file__))
gimm_dir = os.path.join(script_dir, "GIMM-VFI")
# Add GIMM-VFI to path so bim_vfi can be imported as a package
if gimm_dir not in sys.path:
sys.path.insert(0, gimm_dir)
from bim_vfi import BiMVFI
# Use default checkpoint if not specified
default_ckpt = "GIMM-VFI/pretrained_ckpt/bim_vfi.pth"
ckpt_file = checkpoint_path if checkpoint_path else default_ckpt
# Check if already loaded
cache_key = f"bim:{ckpt_file}"
if _bim_model_cache["model"] is not None and _bim_model_cache["variant"] == cache_key:
return _bim_model_cache["model"]
# Clear old model from GPU
if _bim_model_cache["model"] is not None:
del _bim_model_cache["model"]
_bim_model_cache["model"] = None
torch.cuda.empty_cache()
# Create model
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
model = BiMVFI(pyr_level=3, feat_channels=32)
model = model.to(device)
# Load checkpoint (use absolute path)
abs_ckpt_file = os.path.join(script_dir, ckpt_file) if not os.path.isabs(ckpt_file) else ckpt_file
if os.path.exists(abs_ckpt_file):
ckpt = torch.load(abs_ckpt_file, map_location="cpu", weights_only=False)
# Support "model", "state_dict" keys or direct state dict
if "model" in ckpt:
state_dict = ckpt["model"]
elif "state_dict" in ckpt:
state_dict = ckpt["state_dict"]
else:
state_dict = ckpt
model.load_state_dict(state_dict, strict=True)
else:
raise FileNotFoundError(f"BiM-VFI checkpoint not found: {abs_ckpt_file}")
model.eval()
# Cache the model
_bim_model_cache["model"] = model
_bim_model_cache["variant"] = cache_key
return model
def _extract_video_frames(video_path: str, output_dir: str) -> Tuple[List[str], float]:
"""Extract frames from video using ffmpeg. Returns frame paths and FPS."""
os.makedirs(output_dir, exist_ok=True)
# Get video FPS
probe_cmd = [
"ffprobe", "-v", "error", "-select_streams", "v:0",
"-show_entries", "stream=r_frame_rate",
"-of", "default=noprint_wrappers=1:nokey=1", video_path
]
result = subprocess.run(probe_cmd, capture_output=True, text=True)
fps_str = result.stdout.strip()
if "/" in fps_str:
num, den = fps_str.split("/")
fps = float(num) / float(den)
else:
fps = float(fps_str) if fps_str else 24.0
# Extract frames
extract_cmd = [
"ffmpeg", "-y", "-i", video_path,
"-qscale:v", "2",
os.path.join(output_dir, "%05d.png")
]
subprocess.run(extract_cmd, capture_output=True)
# Get sorted frame paths
frame_paths = sorted(Path(output_dir).glob("*.png"))
return [str(p) for p in frame_paths], fps
def _frames_to_video(frame_dir: str, output_path: str, fps: float, audio_source: str = None):
"""Reassemble frames into video using ffmpeg, optionally adding audio."""
if audio_source:
# Create video without audio first
temp_video = output_path + ".temp.mp4"
cmd = [
"ffmpeg", "-y",
"-framerate", str(fps),
"-i", os.path.join(frame_dir, "%05d.png"),
"-c:v", "libx264",
"-pix_fmt", "yuv420p",
"-crf", "18",
temp_video
]
subprocess.run(cmd, capture_output=True)
# Mux audio from source (stretch/compress to match new duration)
# Get durations
probe_cmd = ["ffprobe", "-v", "error", "-show_entries", "format=duration",
"-of", "default=noprint_wrappers=1:nokey=1", temp_video]
result = subprocess.run(probe_cmd, capture_output=True, text=True)
new_duration = float(result.stdout.strip()) if result.stdout.strip() else 0
probe_cmd = ["ffprobe", "-v", "error", "-show_entries", "format=duration",
"-of", "default=noprint_wrappers=1:nokey=1", audio_source]
result = subprocess.run(probe_cmd, capture_output=True, text=True)
orig_duration = float(result.stdout.strip()) if result.stdout.strip() else 0
if orig_duration > 0 and new_duration > 0:
# Calculate tempo adjustment for audio to match video duration
tempo = orig_duration / new_duration
# atempo filter only accepts 0.5 to 2.0, chain multiple if needed
atempo_filters = []
t = tempo
while t > 2.0:
atempo_filters.append("atempo=2.0")
t /= 2.0
while t < 0.5:
atempo_filters.append("atempo=0.5")
t *= 2.0
atempo_filters.append(f"atempo={t}")
atempo_chain = ",".join(atempo_filters)
cmd = [
"ffmpeg", "-y",
"-i", temp_video,
"-i", audio_source,
"-c:v", "copy",
"-af", atempo_chain,
"-map", "0:v:0",
"-map", "1:a:0?",
"-shortest",
output_path
]
else:
# Just copy audio without tempo adjustment
cmd = [
"ffmpeg", "-y",
"-i", temp_video,
"-i", audio_source,
"-c:v", "copy",
"-c:a", "aac",
"-map", "0:v:0",
"-map", "1:a:0?",
"-shortest",
output_path
]
subprocess.run(cmd, capture_output=True)
# Clean up temp file
try:
os.remove(temp_video)
except:
pass
else:
cmd = [
"ffmpeg", "-y",
"-framerate", str(fps),
"-i", os.path.join(frame_dir, "%05d.png"),
"-c:v", "libx264",
"-pix_fmt", "yuv420p",
"-crf", "18",
output_path
]
subprocess.run(cmd, capture_output=True)
def interpolate_video_gimm(
input_video: str,
model_variant: str,
checkpoint_path: str,
config_path: str,
interp_factor: int,
ds_scale: float,
output_fps_override: float,
raft_iters: int,
seed: int,
) -> Generator[Tuple[Optional[str], str, float], None, None]:
"""
Interpolate video frames using GIMM-VFI.
Yields: (output_video_path, status_text, progress_fraction)
"""
import torch
import numpy as np
import cv2
import gc
if not input_video:
yield None, "Error: No input video provided", 0.0
return
_gimm_set_seed(seed)
# Create temp directories
temp_dir = tempfile.mkdtemp(prefix="gimm_interp_")
input_frames_dir = os.path.join(temp_dir, "input_frames")
output_frames_dir = os.path.join(temp_dir, "output_frames")
os.makedirs(input_frames_dir, exist_ok=True)
os.makedirs(output_frames_dir, exist_ok=True)
try:
# Extract frames
yield None, "Extracting video frames...", 0.05
frame_paths, original_fps = _extract_video_frames(input_video, input_frames_dir)
if len(frame_paths) < 2:
yield None, "Error: Video must have at least 2 frames", 0.0
return
yield None, f"Extracted {len(frame_paths)} frames at {original_fps:.2f} FPS", 0.1
# Load model
yield None, f"Loading {model_variant}...", 0.15
model = _load_gimm_model(model_variant, checkpoint_path, config_path)
device = next(model.parameters()).device
yield None, "Model loaded, starting interpolation...", 0.2
# Process frame pairs
N = interp_factor # Number of output frames per input pair (including endpoints)
total_pairs = len(frame_paths) - 1
output_frame_idx = 0
def load_image(img_path):
from PIL import Image
img = Image.open(img_path)
raw_img = np.array(img.convert("RGB"))
img_tensor = torch.from_numpy(raw_img.copy()).permute(2, 0, 1) / 255.0
return img_tensor.to(torch.float).unsqueeze(0)
for pair_idx in range(total_pairs):
progress = 0.2 + (pair_idx / total_pairs) * 0.7
yield None, f"Interpolating pair {pair_idx + 1}/{total_pairs}...", progress
# Load frame pair
I0 = load_image(frame_paths[pair_idx]).to(device)
I2 = load_image(frame_paths[pair_idx + 1]).to(device)
# Pad to divisible by 32
padder = _GIMMInputPadder(I0.shape, 32)
I0_pad, I2_pad = padder.pad(I0, I2)
# Create batch
xs = torch.cat((I0_pad.unsqueeze(2), I2_pad.unsqueeze(2)), dim=2)
batch_size = xs.shape[0]
s_shape = xs.shape[-2:]
# Save first frame (only for first pair)
if pair_idx == 0:
frame_np = (I0[0].cpu().numpy().transpose(1, 2, 0) * 255.0).astype(np.uint8)
frame_bgr = cv2.cvtColor(frame_np, cv2.COLOR_RGB2BGR)
cv2.imwrite(os.path.join(output_frames_dir, f"{output_frame_idx:05d}.png"), frame_bgr)
output_frame_idx += 1
# Generate intermediate frames
with torch.no_grad():
coord_inputs = [
(
model.sample_coord_input(
batch_size,
s_shape,
[1 / N * i],
device=xs.device,
upsample_ratio=ds_scale,
),
None,
)
for i in range(1, N)
]
timesteps = [
i * 1 / N * torch.ones(batch_size).to(xs.device).to(torch.float)
for i in range(1, N)
]
outputs = model(xs, coord_inputs, t=timesteps, ds_factor=ds_scale)
out_frames = [padder.unpad(im) for im in outputs["imgt_pred"]]
# Save interpolated frames
for frame_tensor in out_frames:
frame_np = (frame_tensor[0].cpu().numpy().transpose(1, 2, 0) * 255.0)
frame_np = np.clip(frame_np, 0, 255).astype(np.uint8)
frame_bgr = cv2.cvtColor(frame_np, cv2.COLOR_RGB2BGR)
cv2.imwrite(os.path.join(output_frames_dir, f"{output_frame_idx:05d}.png"), frame_bgr)
output_frame_idx += 1
# Save second frame of pair
frame_np = (padder.unpad(I2_pad)[0].cpu().numpy().transpose(1, 2, 0) * 255.0).astype(np.uint8)
frame_bgr = cv2.cvtColor(frame_np, cv2.COLOR_RGB2BGR)
cv2.imwrite(os.path.join(output_frames_dir, f"{output_frame_idx:05d}.png"), frame_bgr)
output_frame_idx += 1
# Clear CUDA cache periodically
if pair_idx % 10 == 0:
torch.cuda.empty_cache()
# Reassemble video
yield None, "Encoding output video...", 0.92
# Calculate output FPS
output_fps = output_fps_override if output_fps_override > 0 else original_fps * N
# Create output path
output_dir = "outputs"
os.makedirs(output_dir, exist_ok=True)
output_filename = f"interpolated_{int(time.time())}.mp4"
output_path = os.path.join(output_dir, output_filename)
_frames_to_video(output_frames_dir, output_path, output_fps, audio_source=input_video)
# Offload model and clear VRAM before final yield
if _gimm_model_cache["model"] is not None:
_gimm_model_cache["model"].cpu()
del _gimm_model_cache["model"]
_gimm_model_cache["model"] = None
_gimm_model_cache["variant"] = None