Ouzhang commited on
Commit
ac9573f
·
verified ·
1 Parent(s): 51b0765

Add eval sample builder for valN

Browse files
Files changed (1) hide show
  1. benchmarks/edit/build_eval_samples.py +167 -0
benchmarks/edit/build_eval_samples.py ADDED
@@ -0,0 +1,167 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """Build val_N eval sample jsonl files from Ditto manifests.
3
+
4
+ The output schema matches the saved val20/val100 artifacts:
5
+ {"id", "target_video", "control_video", "prompt"}.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ import argparse
11
+ import json
12
+ import random
13
+ import re
14
+ from collections import defaultdict
15
+ from pathlib import Path
16
+ from typing import Any
17
+
18
+
19
+ DEFAULT_MANIFESTS = (
20
+ "datas/ditto_face/manifest.json",
21
+ "datas/ditto_face2/manifest.json",
22
+ )
23
+
24
+ DEFAULT_BUCKET_PREFIXES = (
25
+ "global_freeform1",
26
+ "global_freeform1_filtered",
27
+ "global_freeform2",
28
+ "global_freeform2_filtered",
29
+ "global_freeform3",
30
+ "global_style1",
31
+ "global_style2",
32
+ )
33
+
34
+
35
+ def read_json(path: Path) -> list[dict[str, Any]]:
36
+ data = json.loads(path.read_text(encoding="utf-8"))
37
+ if not isinstance(data, list):
38
+ raise TypeError(f"{path} must contain a JSON list")
39
+ return data
40
+
41
+
42
+ def sanitize_flat_relpath(relpath: str) -> str:
43
+ parts = [re.sub(r"[^0-9A-Za-z._-]+", "_", piece) for piece in relpath.split("/")]
44
+ return "__".join(parts)
45
+
46
+
47
+ def bucket_root(bucket: str) -> str:
48
+ return bucket.split("/", 1)[0]
49
+
50
+
51
+ def category_from_relpath(relpath: str) -> str:
52
+ parts = Path(relpath).parts
53
+ return parts[1] if len(parts) >= 3 else ""
54
+
55
+
56
+ def video_path(dataset: str, side: str, relpath: str, materialized: str, path_style: str) -> str:
57
+ if path_style == "materialized" and materialized:
58
+ return materialized
59
+ return str(Path("datas") / dataset / side / sanitize_flat_relpath(relpath))
60
+
61
+
62
+ def row_to_sample(row: dict[str, Any], dataset: str, path_style: str) -> dict[str, str] | None:
63
+ prompt = str(row.get("prompt", "") or "").strip()
64
+ low_rel = str(row.get("low_rel", "") or row.get("low_video_relpath", "") or "")
65
+ high_rel = str(row.get("high_rel", "") or row.get("high_video_relpath", "") or "")
66
+ if not prompt or not low_rel or not high_rel:
67
+ return None
68
+ return {
69
+ "target_video": video_path(dataset, "high", high_rel, str(row.get("high_materialized", "") or ""), path_style),
70
+ "control_video": video_path(dataset, "low", low_rel, str(row.get("low_materialized", "") or ""), path_style),
71
+ "prompt": prompt,
72
+ "_dataset": dataset,
73
+ "_bucket": bucket_root(str(row.get("target_bucket", "") or high_rel.split("/", 1)[0])),
74
+ "_category": category_from_relpath(high_rel),
75
+ "_dedupe_key": f"{dataset}\n{low_rel}\n{prompt}",
76
+ }
77
+
78
+
79
+ def collect_candidates(
80
+ repo_root: Path,
81
+ manifests: list[Path],
82
+ bucket_prefixes: tuple[str, ...],
83
+ path_style: str,
84
+ ) -> list[dict[str, str]]:
85
+ candidates = []
86
+ seen = set()
87
+ for manifest in manifests:
88
+ path = manifest if manifest.is_absolute() else repo_root / manifest
89
+ dataset = path.parent.name
90
+ for row in read_json(path):
91
+ bucket = bucket_root(str(row.get("target_bucket", "") or ""))
92
+ if bucket and bucket not in bucket_prefixes:
93
+ continue
94
+ sample = row_to_sample(row, dataset, path_style)
95
+ if sample is None:
96
+ continue
97
+ key = sample["_dedupe_key"]
98
+ if key in seen:
99
+ continue
100
+ seen.add(key)
101
+ candidates.append(sample)
102
+ return candidates
103
+
104
+
105
+ def stratified_sample(candidates: list[dict[str, str]], count: int, seed: int) -> list[dict[str, str]]:
106
+ rng = random.Random(seed)
107
+ buckets: dict[tuple[str, str, str], list[dict[str, str]]] = defaultdict(list)
108
+ for sample in candidates:
109
+ buckets[(sample["_dataset"], sample["_bucket"], sample["_category"])].append(sample)
110
+ for values in buckets.values():
111
+ rng.shuffle(values)
112
+
113
+ queues = list(buckets.values())
114
+ rng.shuffle(queues)
115
+ selected = []
116
+ while queues and len(selected) < count:
117
+ next_queues = []
118
+ for queue in queues:
119
+ if len(selected) >= count:
120
+ break
121
+ if queue:
122
+ selected.append(queue.pop())
123
+ if queue:
124
+ next_queues.append(queue)
125
+ queues = next_queues
126
+ rng.shuffle(queues)
127
+ if len(selected) < count:
128
+ raise RuntimeError(f"only selected {len(selected)} samples from {len(candidates)} candidates")
129
+ return selected[:count]
130
+
131
+
132
+ def write_samples(path: Path, samples: list[dict[str, str]]) -> None:
133
+ path.parent.mkdir(parents=True, exist_ok=True)
134
+ with path.open("w", encoding="utf-8") as handle:
135
+ for index, sample in enumerate(samples):
136
+ row = {
137
+ "id": f"val_{index:04d}",
138
+ "target_video": sample["target_video"],
139
+ "control_video": sample["control_video"],
140
+ "prompt": sample["prompt"],
141
+ }
142
+ handle.write(json.dumps(row, ensure_ascii=False) + "\n")
143
+
144
+
145
+ def main() -> None:
146
+ parser = argparse.ArgumentParser()
147
+ parser.add_argument("--repo-root", type=Path, default=Path.cwd())
148
+ parser.add_argument("--manifest", type=Path, action="append", default=[])
149
+ parser.add_argument("--output", type=Path, required=True)
150
+ parser.add_argument("--count", type=int, default=1000)
151
+ parser.add_argument("--seed", type=int, default=20260511)
152
+ parser.add_argument("--path-style", choices=("flat", "materialized"), default="flat")
153
+ parser.add_argument("--bucket-prefix", action="append", default=[])
154
+ args = parser.parse_args()
155
+
156
+ manifests = args.manifest or [Path(p) for p in DEFAULT_MANIFESTS]
157
+ bucket_prefixes = tuple(args.bucket_prefix or DEFAULT_BUCKET_PREFIXES)
158
+ candidates = collect_candidates(args.repo_root, manifests, bucket_prefixes, args.path_style)
159
+ selected = stratified_sample(candidates, args.count, args.seed)
160
+ write_samples(args.output, selected)
161
+ print(f"candidates={len(candidates)}")
162
+ print(f"selected={len(selected)} -> {args.output}")
163
+ print(f"path_style={args.path_style}, seed={args.seed}")
164
+
165
+
166
+ if __name__ == "__main__":
167
+ main()