| |
| """Build val_N eval sample jsonl files. |
| |
| The output schema matches the saved val20/val100 artifacts: |
| {"id", "target_video", "control_video", "prompt"}. |
| |
| For reproducing the original val20/val100 split, use --metadata-val-csv with |
| one of the held-out real_train/metadata.val.csv files. The manifest sampling |
| mode is only a fallback for making a generic eval-like set and is not guaranteed |
| to be held out from a specific training run. |
| """ |
|
|
| from __future__ import annotations |
|
|
| import argparse |
| import csv |
| import json |
| import random |
| import re |
| from collections import defaultdict |
| from pathlib import Path |
| from typing import Any |
|
|
|
|
| DEFAULT_MANIFESTS = ( |
| "datas/ditto_face/manifest.json", |
| "datas/ditto_face2/manifest.json", |
| ) |
|
|
| DEFAULT_BUCKET_PREFIXES = ( |
| "global_freeform1", |
| "global_freeform1_filtered", |
| "global_freeform2", |
| "global_freeform2_filtered", |
| "global_freeform3", |
| "global_style1", |
| "global_style2", |
| ) |
|
|
|
|
| def read_json(path: Path) -> list[dict[str, Any]]: |
| data = json.loads(path.read_text(encoding="utf-8")) |
| if not isinstance(data, list): |
| raise TypeError(f"{path} must contain a JSON list") |
| return data |
|
|
|
|
| def read_metadata_val_csv(path: Path, count: int) -> list[dict[str, str]]: |
| rows: list[dict[str, str]] = [] |
| with path.open("r", encoding="utf-8", newline="") as handle: |
| reader = csv.DictReader(handle) |
| missing = {"video", "vace_video", "prompt"} - set(reader.fieldnames or []) |
| if missing: |
| raise ValueError(f"{path} missing required columns: {sorted(missing)}") |
| for row in reader: |
| rows.append( |
| { |
| "target_video": str(row["video"]), |
| "control_video": str(row["vace_video"]), |
| "prompt": str(row["prompt"]), |
| } |
| ) |
| if len(rows) >= count: |
| break |
| if len(rows) < count: |
| raise RuntimeError(f"{path} only has {len(rows)} rows, requested {count}") |
| return rows |
|
|
|
|
| def sanitize_flat_relpath(relpath: str) -> str: |
| parts = [re.sub(r"[^0-9A-Za-z._-]+", "_", piece) for piece in relpath.split("/")] |
| return "__".join(parts) |
|
|
|
|
| def bucket_root(bucket: str) -> str: |
| return bucket.split("/", 1)[0] |
|
|
|
|
| def category_from_relpath(relpath: str) -> str: |
| parts = Path(relpath).parts |
| return parts[1] if len(parts) >= 3 else "" |
|
|
|
|
| def video_path(dataset: str, side: str, relpath: str, materialized: str, path_style: str) -> str: |
| if path_style == "materialized" and materialized: |
| return materialized |
| return str(Path("datas") / dataset / side / sanitize_flat_relpath(relpath)) |
|
|
|
|
| def row_to_sample(row: dict[str, Any], dataset: str, path_style: str) -> dict[str, str] | None: |
| prompt = str(row.get("prompt", "") or "").strip() |
| low_rel = str(row.get("low_rel", "") or row.get("low_video_relpath", "") or "") |
| high_rel = str(row.get("high_rel", "") or row.get("high_video_relpath", "") or "") |
| if not prompt or not low_rel or not high_rel: |
| return None |
| return { |
| "target_video": video_path(dataset, "high", high_rel, str(row.get("high_materialized", "") or ""), path_style), |
| "control_video": video_path(dataset, "low", low_rel, str(row.get("low_materialized", "") or ""), path_style), |
| "prompt": prompt, |
| "_dataset": dataset, |
| "_bucket": bucket_root(str(row.get("target_bucket", "") or high_rel.split("/", 1)[0])), |
| "_category": category_from_relpath(high_rel), |
| "_dedupe_key": f"{dataset}\n{low_rel}\n{prompt}", |
| } |
|
|
|
|
| def collect_candidates( |
| repo_root: Path, |
| manifests: list[Path], |
| bucket_prefixes: tuple[str, ...], |
| path_style: str, |
| ) -> list[dict[str, str]]: |
| candidates = [] |
| seen = set() |
| for manifest in manifests: |
| path = manifest if manifest.is_absolute() else repo_root / manifest |
| dataset = path.parent.name |
| for row in read_json(path): |
| bucket = bucket_root(str(row.get("target_bucket", "") or "")) |
| if bucket and bucket not in bucket_prefixes: |
| continue |
| sample = row_to_sample(row, dataset, path_style) |
| if sample is None: |
| continue |
| key = sample["_dedupe_key"] |
| if key in seen: |
| continue |
| seen.add(key) |
| candidates.append(sample) |
| return candidates |
|
|
|
|
| def stratified_sample(candidates: list[dict[str, str]], count: int, seed: int) -> list[dict[str, str]]: |
| rng = random.Random(seed) |
| buckets: dict[tuple[str, str, str], list[dict[str, str]]] = defaultdict(list) |
| for sample in candidates: |
| buckets[(sample["_dataset"], sample["_bucket"], sample["_category"])].append(sample) |
| for values in buckets.values(): |
| rng.shuffle(values) |
|
|
| queues = list(buckets.values()) |
| rng.shuffle(queues) |
| selected = [] |
| while queues and len(selected) < count: |
| next_queues = [] |
| for queue in queues: |
| if len(selected) >= count: |
| break |
| if queue: |
| selected.append(queue.pop()) |
| if queue: |
| next_queues.append(queue) |
| queues = next_queues |
| rng.shuffle(queues) |
| if len(selected) < count: |
| raise RuntimeError(f"only selected {len(selected)} samples from {len(candidates)} candidates") |
| return selected[:count] |
|
|
|
|
| def write_samples(path: Path, samples: list[dict[str, str]]) -> None: |
| path.parent.mkdir(parents=True, exist_ok=True) |
| with path.open("w", encoding="utf-8") as handle: |
| for index, sample in enumerate(samples): |
| row = { |
| "id": f"val_{index:04d}", |
| "target_video": sample["target_video"], |
| "control_video": sample["control_video"], |
| "prompt": sample["prompt"], |
| } |
| handle.write(json.dumps(row, ensure_ascii=False) + "\n") |
|
|
|
|
| def main() -> None: |
| parser = argparse.ArgumentParser() |
| parser.add_argument("--repo-root", type=Path, default=Path.cwd()) |
| parser.add_argument("--manifest", type=Path, action="append", default=[]) |
| parser.add_argument( |
| "--metadata-val-csv", |
| type=Path, |
| default=None, |
| help="Held-out real_train/metadata.val.csv. Use this to reproduce val20/val100 logic.", |
| ) |
| parser.add_argument("--output", type=Path, required=True) |
| parser.add_argument("--count", type=int, default=1000) |
| parser.add_argument("--seed", type=int, default=20260511) |
| parser.add_argument("--path-style", choices=("flat", "materialized"), default="flat") |
| parser.add_argument("--bucket-prefix", action="append", default=[]) |
| args = parser.parse_args() |
|
|
| if args.metadata_val_csv is not None: |
| metadata_path = args.metadata_val_csv if args.metadata_val_csv.is_absolute() else args.repo_root / args.metadata_val_csv |
| selected = read_metadata_val_csv(metadata_path, args.count) |
| print(f"source={metadata_path}") |
| print("mode=metadata.val.csv prefix") |
| else: |
| manifests = args.manifest or [Path(p) for p in DEFAULT_MANIFESTS] |
| bucket_prefixes = tuple(args.bucket_prefix or DEFAULT_BUCKET_PREFIXES) |
| candidates = collect_candidates(args.repo_root, manifests, bucket_prefixes, args.path_style) |
| selected = stratified_sample(candidates, args.count, args.seed) |
| print(f"candidates={len(candidates)}") |
| print(f"path_style={args.path_style}, seed={args.seed}") |
| write_samples(args.output, selected) |
| print(f"selected={len(selected)} -> {args.output}") |
|
|
|
|
| if __name__ == "__main__": |
| main() |
|
|