#!/usr/bin/env python3 """Build manifests for the six val20/val100 edit-result folders.""" from __future__ import annotations import argparse from collections import defaultdict import json from pathlib import Path from typing import Any METHODS = ("wan_only", "ditto_global", "full", "text", "vace_hint", "vace_context") def read_jsonl(path: Path) -> list[dict]: rows: list[dict] = [] with path.open("r", encoding="utf-8") as handle: for line in handle: text = line.strip() if text: rows.append(json.loads(text)) return rows def load_source_maps(paths: list[Path], repo_root: Path) -> tuple[dict[str, Path], dict[str, Path]]: """Load optional source maps keyed by sample_id and by original path/basename.""" by_id: dict[str, Path] = {} by_key: dict[str, Path] = {} for path in paths: path = path if path.is_absolute() else repo_root / path rows = read_jsonl(path) for row in rows: video = ( row.get("path") or row.get("video") or row.get("source_video") or row.get("source_path") or row.get("control_video") ) if not video: continue video_path = Path(str(video)) if not video_path.is_absolute(): video_path = repo_root / video_path for key_name in ("sample_id", "id"): if row.get(key_name) is not None: by_id[str(row[key_name])] = video_path for key_name in ("old_path", "old_video", "control_video", "source_video"): if row.get(key_name) is not None: key = str(row[key_name]) by_key[key] = video_path by_key[Path(key).name] = video_path by_key[video_path.name] = video_path return by_id, by_key def dataset_name_from_path(path: str) -> str: parts = Path(path).parts for index, part in enumerate(parts): if part == "datas" and index + 1 < len(parts): return parts[index + 1] return "" def target_bucket_from_path(path: str) -> str: stem = Path(path).stem if "__" in stem: return stem.split("__", 1)[0] if "/" in path: parts = Path(path).parts if "high" in parts: index = parts.index("high") if index + 1 < len(parts): return parts[index + 1] return "" def edit_index_from_path(path: str) -> str: stem = Path(path).stem if "_" not in stem: return "" tail = stem.rsplit("_", 1)[-1] return tail if tail.isdigit() else "" def load_dataset_manifests(paths: list[Path], repo_root: Path) -> dict[tuple[str, str, str], list[dict[str, Any]]]: by_dataset_bucket_prompt: dict[tuple[str, str, str], list[dict[str, Any]]] = defaultdict(list) for path in paths: path = path if path.is_absolute() else repo_root / path if not path.exists(): continue dataset = path.parent.name rows = json.loads(path.read_text(encoding="utf-8")) for row in rows: bucket = str(row.get("target_bucket", "")) prompt = str(row.get("prompt", "")) if dataset and bucket and prompt: by_dataset_bucket_prompt[(dataset, bucket, prompt)].append(row) return by_dataset_bucket_prompt def resolve_source_video( repo_root: Path, sample_id: str, raw_path: str, target_path: str, prompt: str, source_roots: list[Path], source_by_id: dict[str, Path], source_by_key: dict[str, Path], dataset_rows: dict[tuple[str, str, str], list[dict[str, Any]]], ) -> Path: if sample_id in source_by_id: return source_by_id[sample_id] if raw_path in source_by_key: return source_by_key[raw_path] raw_name = Path(raw_path).name if raw_name in source_by_key: return source_by_key[raw_name] dataset = dataset_name_from_path(target_path) or dataset_name_from_path(raw_path) bucket = target_bucket_from_path(target_path) rows = dataset_rows.get((dataset, bucket, prompt), []) if rows: edit_index = edit_index_from_path(target_path) if edit_index: indexed_rows = [ row for row in rows if Path(str(row.get("high_materialized") or row.get("high_video_path") or row.get("high_rel") or "")).stem.endswith( f"_{edit_index}" ) ] if len(indexed_rows) == 1: rows = indexed_rows if len(rows) == 1: manifest_source = rows[0].get("low_materialized") or rows[0].get("low_video_path") if manifest_source: source_from_manifest = Path(str(manifest_source)) if not source_from_manifest.is_absolute(): source_from_manifest = repo_root / source_from_manifest return source_from_manifest source_video = Path(raw_path) if not source_video.is_absolute(): source_video = repo_root / source_video if source_video.exists(): return source_video # Some machines only have downloaded/evaluated outputs, not the original # absolute data tree. Let callers provide roots that contain source mp4s. for root in source_roots: root = root if root.is_absolute() else repo_root / root candidate = root / source_video.name if candidate.exists(): return candidate for root in source_roots: root = root if root.is_absolute() else repo_root / root if not root.exists(): continue matches = list(root.rglob(source_video.name)) if matches: return matches[0] return source_video def build_split( repo_root: Path, split: str, samples_path: Path, outputs_root: Path, output_path: Path, source_roots: list[Path], source_by_id: dict[str, Path], source_by_key: dict[str, Path], dataset_rows: dict[tuple[str, str, str], list[dict[str, Any]]], ) -> None: samples = read_jsonl(samples_path) output_path.parent.mkdir(parents=True, exist_ok=True) count = 0 missing_sources: set[str] = set() missing_edits: list[str] = [] with output_path.open("w", encoding="utf-8") as handle: for sample in samples: sample_id = str(sample["id"]) source_video = resolve_source_video( repo_root, sample_id, str(sample["control_video"]), str(sample.get("target_video", "")), str(sample["prompt"]), source_roots, source_by_id, source_by_key, dataset_rows, ) if not source_video.exists(): missing_sources.add(str(source_video)) for method in METHODS: edited_video = outputs_root / method / f"{sample_id}.mp4" if not edited_video.exists(): missing_edits.append(str(edited_video)) row = { "split": split, "sample_id": sample_id, "method": method, "instruction": sample["prompt"], "source_video": str(source_video), "edited_video": str(edited_video), "source_prompt": sample.get("source_prompt", ""), "target_prompt": sample.get("target_prompt", sample["prompt"]), } handle.write(json.dumps(row, ensure_ascii=False) + "\n") count += 1 print(f"{split}: wrote {count} rows -> {output_path}") if missing_sources: print(f"{split}: warning missing source videos: {len(missing_sources)} unique paths") for path in sorted(missing_sources)[:20]: print(f" missing source: {path}") if missing_edits: print(f"{split}: warning missing edited videos: {len(missing_edits)} rows") for path in missing_edits[:20]: print(f" missing edited: {path}") def main() -> None: parser = argparse.ArgumentParser() parser.add_argument("--repo-root", type=Path, default=Path.cwd()) parser.add_argument("--output-dir", type=Path, default=Path("out/edit_model_face_stage1/traditional_eval_manifests")) parser.add_argument( "--source-root", type=Path, action="append", default=[], help="Optional directory to search for original source mp4s by basename when eval_samples control_video is missing.", ) parser.add_argument( "--source-map", type=Path, action="append", default=[], help=( "Optional JSONL map. Each row may contain sample_id/id and path/video/source_video/source_path. " "It can also contain old_path/old_video/control_video to map old names to current hashed paths." ), ) parser.add_argument( "--dataset-manifest", type=Path, action="append", default=[], help="Dataset manifest.json used to map eval_samples target_video/prompt back to hash low_materialized paths.", ) args = parser.parse_args() repo_root = args.repo_root.resolve() base = repo_root / "out/edit_model_face_stage1" output_dir = args.output_dir if args.output_dir.is_absolute() else repo_root / args.output_dir source_by_id, source_by_key = load_source_maps(args.source_map, repo_root) dataset_manifest_paths = args.dataset_manifest or [ Path("datas/ditto_face/manifest.json"), Path("datas/ditto_face2/manifest.json"), ] dataset_rows = load_dataset_manifests(dataset_manifest_paths, repo_root) jobs = [ ( "val20", base / "eval_samples/val_20.jsonl", base / "eval_outputs", output_dir / "val20.jsonl", ), ( "val100", base / "eval_samples/val_100.jsonl", base / "eval_outputs_val100", output_dir / "val100.jsonl", ), ] for split, samples_path, outputs_root, output_path in jobs: if not samples_path.exists(): raise FileNotFoundError(samples_path) build_split( repo_root, split, samples_path, outputs_root, output_path, args.source_root, source_by_id, source_by_key, dataset_rows, ) if __name__ == "__main__": main()