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sequential x2 refiners on videos.zip with temporal chunking."""
|
| 3 |
+
|
| 4 |
+
from __future__ import annotations
|
| 5 |
+
|
| 6 |
+
import argparse
|
| 7 |
+
import json
|
| 8 |
+
import os
|
| 9 |
+
import subprocess
|
| 10 |
+
import sys
|
| 11 |
+
import time
|
| 12 |
+
from pathlib import Path
|
| 13 |
+
|
| 14 |
+
from ltx_core.loader import LTXV_LORA_COMFY_RENAMING_MAP, LoraPathStrengthAndSDOps
|
| 15 |
+
from ltx_pipelines.utils.helpers import cleanup_memory
|
| 16 |
+
from ltx_pipelines.utils.media_io import get_videostream_metadata
|
| 17 |
+
from ltx_pipelines.utils.types import OffloadMode
|
| 18 |
+
from ltx_pipelines.video_refiner_upscale import (
|
| 19 |
+
VideoRefinerUpscalePipeline,
|
| 20 |
+
_parse_quantization,
|
| 21 |
+
_snap_frames_to_8k1,
|
| 22 |
+
)
|
| 23 |
+
|
| 24 |
+
ROOT = Path(__file__).resolve().parents[2]
|
| 25 |
+
if str(ROOT) not in sys.path:
|
| 26 |
+
sys.path.insert(0, str(ROOT))
|
| 27 |
+
|
| 28 |
+
from experiments.ltx2_repro.run_video_zip_two_refiners import (
|
| 29 |
+
OUTPUTS_DIR,
|
| 30 |
+
append_manifest,
|
| 31 |
+
extract_videos,
|
| 32 |
+
load_config,
|
| 33 |
+
rel,
|
| 34 |
+
)
|
| 35 |
+
|
| 36 |
+
|
| 37 |
+
CHUNKS_DIR = OUTPUTS_DIR / "chunks"
|
| 38 |
+
|
| 39 |
+
|
| 40 |
+
def chunk_spans(total_frames: int, chunk_frames: int) -> list[tuple[int, int]]:
|
| 41 |
+
spans: list[tuple[int, int]] = []
|
| 42 |
+
start = 0
|
| 43 |
+
while start < total_frames:
|
| 44 |
+
remaining = total_frames - start
|
| 45 |
+
if remaining < 9:
|
| 46 |
+
break
|
| 47 |
+
frames = _snap_frames_to_8k1(min(chunk_frames, remaining))
|
| 48 |
+
if frames < 1:
|
| 49 |
+
break
|
| 50 |
+
spans.append((start, frames))
|
| 51 |
+
start += frames
|
| 52 |
+
return spans
|
| 53 |
+
|
| 54 |
+
|
| 55 |
+
def concat_videos(inputs: list[Path], output_path: Path, fps: float) -> int:
|
| 56 |
+
cmd = [
|
| 57 |
+
sys.executable,
|
| 58 |
+
str(Path(__file__).with_name("concat_video_chunks.py")),
|
| 59 |
+
"--output",
|
| 60 |
+
str(output_path),
|
| 61 |
+
"--fps",
|
| 62 |
+
str(fps),
|
| 63 |
+
*(str(p) for p in inputs),
|
| 64 |
+
]
|
| 65 |
+
proc = subprocess.run(cmd, cwd=ROOT, text=True, capture_output=True)
|
| 66 |
+
if proc.returncode != 0:
|
| 67 |
+
raise RuntimeError(f"Video chunk concatenation failed: {proc.stderr.strip() or proc.stdout.strip()}")
|
| 68 |
+
return int(json.loads(proc.stdout.strip().splitlines()[-1])["frames"])
|
| 69 |
+
|
| 70 |
+
|
| 71 |
+
def is_valid_video(path: Path) -> bool:
|
| 72 |
+
if not path.exists() or path.stat().st_size < 1024:
|
| 73 |
+
return False
|
| 74 |
+
try:
|
| 75 |
+
return get_videostream_metadata(str(path)).frames > 0
|
| 76 |
+
except Exception:
|
| 77 |
+
return False
|
| 78 |
+
|
| 79 |
+
|
| 80 |
+
def build_pipeline(cfg: dict) -> VideoRefinerUpscalePipeline:
|
| 81 |
+
model_paths = cfg["model_paths"]
|
| 82 |
+
checkpoint_path = str(ROOT / model_paths["full_checkpoint"])
|
| 83 |
+
return VideoRefinerUpscalePipeline(
|
| 84 |
+
checkpoint_path=checkpoint_path,
|
| 85 |
+
distilled_lora=LoraPathStrengthAndSDOps(
|
| 86 |
+
path=str(ROOT / model_paths["distilled_lora"]),
|
| 87 |
+
strength=0.8,
|
| 88 |
+
sd_ops=LTXV_LORA_COMFY_RENAMING_MAP,
|
| 89 |
+
),
|
| 90 |
+
spatial_upsampler_path=str(ROOT / model_paths["spatial_upsampler"]),
|
| 91 |
+
gemma_root=str(ROOT / model_paths["gemma_root"]),
|
| 92 |
+
quantization=_parse_quantization("none", checkpoint_path),
|
| 93 |
+
offload_mode=OffloadMode.CPU,
|
| 94 |
+
)
|
| 95 |
+
|
| 96 |
+
|
| 97 |
+
def run_refiner_call(
|
| 98 |
+
*,
|
| 99 |
+
pipeline: VideoRefinerUpscalePipeline,
|
| 100 |
+
transformer: object,
|
| 101 |
+
input_video: Path,
|
| 102 |
+
output_video: Path,
|
| 103 |
+
run_id: str,
|
| 104 |
+
start_frame: int,
|
| 105 |
+
frames: int,
|
| 106 |
+
max_batch_size: int,
|
| 107 |
+
) -> dict:
|
| 108 |
+
os.environ["LTX2_BENCHMARK_RUN_ID"] = run_id
|
| 109 |
+
t0 = time.perf_counter()
|
| 110 |
+
try:
|
| 111 |
+
input_shape, output_shape = pipeline(
|
| 112 |
+
input_video=str(input_video),
|
| 113 |
+
output_path=str(output_video),
|
| 114 |
+
prompt="high quality video, sharp details",
|
| 115 |
+
seed=10,
|
| 116 |
+
start_frame=start_frame,
|
| 117 |
+
max_frames=frames,
|
| 118 |
+
max_batch_size=max_batch_size,
|
| 119 |
+
transformer=transformer,
|
| 120 |
+
)
|
| 121 |
+
status = "success" if output_video.exists() else "failed"
|
| 122 |
+
record = {
|
| 123 |
+
"run_id": run_id,
|
| 124 |
+
"status": status,
|
| 125 |
+
"wall_seconds": time.perf_counter() - t0,
|
| 126 |
+
"input_video": rel(input_video),
|
| 127 |
+
"output_video": rel(output_video),
|
| 128 |
+
"start_frame": start_frame,
|
| 129 |
+
"frames": frames,
|
| 130 |
+
"input_shape": {
|
| 131 |
+
"width": input_shape.width,
|
| 132 |
+
"height": input_shape.height,
|
| 133 |
+
"frames": input_shape.frames,
|
| 134 |
+
"fps": input_shape.fps,
|
| 135 |
+
},
|
| 136 |
+
"output_shape": {
|
| 137 |
+
"width": output_shape.width,
|
| 138 |
+
"height": output_shape.height,
|
| 139 |
+
"frames": output_shape.frames,
|
| 140 |
+
"fps": output_shape.fps,
|
| 141 |
+
},
|
| 142 |
+
}
|
| 143 |
+
except Exception as exc:
|
| 144 |
+
record = {
|
| 145 |
+
"run_id": run_id,
|
| 146 |
+
"status": "failed",
|
| 147 |
+
"wall_seconds": time.perf_counter() - t0,
|
| 148 |
+
"input_video": rel(input_video),
|
| 149 |
+
"output_video": rel(output_video),
|
| 150 |
+
"start_frame": start_frame,
|
| 151 |
+
"frames": frames,
|
| 152 |
+
"error": repr(exc),
|
| 153 |
+
}
|
| 154 |
+
finally:
|
| 155 |
+
cleanup_memory()
|
| 156 |
+
append_manifest(record)
|
| 157 |
+
return record
|
| 158 |
+
|
| 159 |
+
|
| 160 |
+
def process_video(
|
| 161 |
+
*,
|
| 162 |
+
index: int,
|
| 163 |
+
source: Path,
|
| 164 |
+
cfg: dict,
|
| 165 |
+
chunk_frames: int,
|
| 166 |
+
skip_existing: bool,
|
| 167 |
+
) -> None:
|
| 168 |
+
stem = source.stem
|
| 169 |
+
pass1_final = OUTPUTS_DIR / "pass1_x2" / f"{stem}_x2.mp4"
|
| 170 |
+
pass2_final = OUTPUTS_DIR / "pass2_x4" / f"{stem}_x4.mp4"
|
| 171 |
+
if skip_existing and is_valid_video(pass2_final):
|
| 172 |
+
append_manifest(
|
| 173 |
+
{
|
| 174 |
+
"video_index": index,
|
| 175 |
+
"source_video": rel(source),
|
| 176 |
+
"pass1_output": rel(pass1_final),
|
| 177 |
+
"pass2_output": rel(pass2_final),
|
| 178 |
+
"status": "skipped_existing",
|
| 179 |
+
"mode": "chunked",
|
| 180 |
+
}
|
| 181 |
+
)
|
| 182 |
+
return
|
| 183 |
+
|
| 184 |
+
metadata = get_videostream_metadata(str(source))
|
| 185 |
+
spans = chunk_spans(metadata.frames, chunk_frames)
|
| 186 |
+
if not spans:
|
| 187 |
+
raise ValueError(f"No usable chunk spans for {source}")
|
| 188 |
+
|
| 189 |
+
pass1_dir = CHUNKS_DIR / "pass1_x2" / stem
|
| 190 |
+
pass2_dir = CHUNKS_DIR / "pass2_x4" / stem
|
| 191 |
+
pass1_dir.mkdir(parents=True, exist_ok=True)
|
| 192 |
+
pass2_dir.mkdir(parents=True, exist_ok=True)
|
| 193 |
+
pass1_chunks = [pass1_dir / f"{stem}_chunk{i:04d}_x2.mp4" for i in range(len(spans))]
|
| 194 |
+
pass2_chunks = [pass2_dir / f"{stem}_chunk{i:04d}_x4.mp4" for i in range(len(spans))]
|
| 195 |
+
|
| 196 |
+
append_manifest(
|
| 197 |
+
{
|
| 198 |
+
"video_index": index,
|
| 199 |
+
"source_video": rel(source),
|
| 200 |
+
"status": "started",
|
| 201 |
+
"mode": "chunked",
|
| 202 |
+
"chunk_frames": chunk_frames,
|
| 203 |
+
"chunks": len(spans),
|
| 204 |
+
"source_shape": {
|
| 205 |
+
"width": metadata.width,
|
| 206 |
+
"height": metadata.height,
|
| 207 |
+
"frames": metadata.frames,
|
| 208 |
+
"fps": metadata.fps,
|
| 209 |
+
},
|
| 210 |
+
}
|
| 211 |
+
)
|
| 212 |
+
|
| 213 |
+
needs_refine = not skip_existing or any(not is_valid_video(p) for p in [*pass1_chunks, *pass2_chunks])
|
| 214 |
+
if needs_refine:
|
| 215 |
+
os.environ["LTX2_BENCHMARK_PIPELINE"] = "videos_zip_two_refiners_chunked"
|
| 216 |
+
os.environ["LTX2_BENCHMARK_JSONL"] = str(OUTPUTS_DIR / "metrics" / "dit_metrics_chunked.jsonl")
|
| 217 |
+
pipeline = build_pipeline(cfg)
|
| 218 |
+
max_batch_size = int(cfg.get("max_batch_size", 1))
|
| 219 |
+
|
| 220 |
+
with pipeline.stage.model_context() as transformer:
|
| 221 |
+
for chunk_index, (start, frames) in enumerate(spans):
|
| 222 |
+
pass1_chunk = pass1_chunks[chunk_index]
|
| 223 |
+
pass2_chunk = pass2_chunks[chunk_index]
|
| 224 |
+
if not (skip_existing and is_valid_video(pass1_chunk)):
|
| 225 |
+
record = run_refiner_call(
|
| 226 |
+
pipeline=pipeline,
|
| 227 |
+
transformer=transformer,
|
| 228 |
+
input_video=source,
|
| 229 |
+
output_video=pass1_chunk,
|
| 230 |
+
run_id=f"{stem}_chunk{chunk_index:04d}_pass1_x2",
|
| 231 |
+
start_frame=start,
|
| 232 |
+
frames=frames,
|
| 233 |
+
max_batch_size=max_batch_size,
|
| 234 |
+
)
|
| 235 |
+
if record["status"] != "success":
|
| 236 |
+
raise RuntimeError(f"{record['run_id']} failed: {record.get('error')}")
|
| 237 |
+
|
| 238 |
+
if not (skip_existing and is_valid_video(pass2_chunk)):
|
| 239 |
+
record = run_refiner_call(
|
| 240 |
+
pipeline=pipeline,
|
| 241 |
+
transformer=transformer,
|
| 242 |
+
input_video=pass1_chunk,
|
| 243 |
+
output_video=pass2_chunk,
|
| 244 |
+
run_id=f"{stem}_chunk{chunk_index:04d}_pass2_x4",
|
| 245 |
+
start_frame=0,
|
| 246 |
+
frames=frames,
|
| 247 |
+
max_batch_size=max_batch_size,
|
| 248 |
+
)
|
| 249 |
+
if record["status"] != "success":
|
| 250 |
+
raise RuntimeError(f"{record['run_id']} failed: {record.get('error')}")
|
| 251 |
+
|
| 252 |
+
pass1_count = concat_videos(pass1_chunks, pass1_final, metadata.fps)
|
| 253 |
+
pass2_count = concat_videos(pass2_chunks, pass2_final, metadata.fps)
|
| 254 |
+
append_manifest(
|
| 255 |
+
{
|
| 256 |
+
"video_index": index,
|
| 257 |
+
"source_video": rel(source),
|
| 258 |
+
"pass1_output": rel(pass1_final),
|
| 259 |
+
"pass2_output": rel(pass2_final),
|
| 260 |
+
"status": "success",
|
| 261 |
+
"mode": "chunked",
|
| 262 |
+
"chunk_frames": chunk_frames,
|
| 263 |
+
"chunks": len(spans),
|
| 264 |
+
"pass1_frames": pass1_count,
|
| 265 |
+
"pass2_frames": pass2_count,
|
| 266 |
+
}
|
| 267 |
+
)
|
| 268 |
+
|
| 269 |
+
|
| 270 |
+
def main() -> None:
|
| 271 |
+
parser = argparse.ArgumentParser()
|
| 272 |
+
parser.add_argument("--index", type=int, help="Process one extracted video index.")
|
| 273 |
+
parser.add_argument("--start-index", type=int, default=0)
|
| 274 |
+
parser.add_argument("--end-index", type=int)
|
| 275 |
+
parser.add_argument("--chunk-frames", type=int, default=65)
|
| 276 |
+
parser.add_argument("--skip-existing", action="store_true")
|
| 277 |
+
parser.add_argument("--continue-on-error", action="store_true")
|
| 278 |
+
args = parser.parse_args()
|
| 279 |
+
|
| 280 |
+
chunk_frames = _snap_frames_to_8k1(args.chunk_frames)
|
| 281 |
+
if chunk_frames != args.chunk_frames:
|
| 282 |
+
print(f"Adjusted chunk_frames from {args.chunk_frames} to {chunk_frames}")
|
| 283 |
+
|
| 284 |
+
cfg = load_config()
|
| 285 |
+
videos = extract_videos()
|
| 286 |
+
if args.index is not None:
|
| 287 |
+
selected = [(args.index, videos[args.index])]
|
| 288 |
+
else:
|
| 289 |
+
end = len(videos) - 1 if args.end_index is None else args.end_index
|
| 290 |
+
selected = list(enumerate(videos))[args.start_index : end + 1]
|
| 291 |
+
|
| 292 |
+
for index, source in selected:
|
| 293 |
+
try:
|
| 294 |
+
process_video(
|
| 295 |
+
index=index,
|
| 296 |
+
source=source,
|
| 297 |
+
cfg=cfg,
|
| 298 |
+
chunk_frames=chunk_frames,
|
| 299 |
+
skip_existing=args.skip_existing,
|
| 300 |
+
)
|
| 301 |
+
except Exception as exc:
|
| 302 |
+
append_manifest(
|
| 303 |
+
{
|
| 304 |
+
"video_index": index,
|
| 305 |
+
"source_video": rel(source),
|
| 306 |
+
"status": "failed_or_incomplete",
|
| 307 |
+
"mode": "chunked",
|
| 308 |
+
"error": repr(exc),
|
| 309 |
+
}
|
| 310 |
+
)
|
| 311 |
+
if not args.continue_on_error:
|
| 312 |
+
raise
|
| 313 |
+
|
| 314 |
+
|
| 315 |
+
if __name__ == "__main__":
|
| 316 |
+
main()
|