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
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
#!/usr/bin/env python3
from __future__ import annotations

import argparse
import hashlib
import json
import random
import shutil
from pathlib import Path
from typing import Any

import pyarrow as pa
import pyarrow.parquet as pq


NEGATIVE_COUNT = 5
SOURCE_COLUMNS = ("query_id", "case_id", "raw_text", "parsed_text", "video")
OUTPUT_COLUMNS = ("text", "video", "hard_negative_texts", "hard_negative_videos")

HF_FEATURES = {
    "text": {"dtype": "string", "_type": "Value"},
    "video": {"dtype": "string", "_type": "Value"},
    "hard_negative_texts": {
        "feature": {"dtype": "string", "_type": "Value"},
        "length": -1,
        "_type": "List",
    },
    "hard_negative_videos": {
        "feature": {"dtype": "string", "_type": "Value"},
        "length": -1,
        "_type": "List",
    },
}

OUTPUT_SCHEMA = pa.schema(
    [
        pa.field("text", pa.string()),
        pa.field("video", pa.string()),
        pa.field("hard_negative_texts", pa.list_(pa.string())),
        pa.field("hard_negative_videos", pa.list_(pa.string())),
    ],
    metadata={
        b"huggingface": json.dumps(
            {"info": {"features": HF_FEATURES}}, separators=(",", ":")
        ).encode()
    },
)


def _write_json(path: Path, payload: Any) -> None:
    path.parent.mkdir(parents=True, exist_ok=True)
    path.write_text(
        json.dumps(payload, indent=2, ensure_ascii=False) + "\n", encoding="utf-8"
    )


def _source_files(source_dir: Path) -> list[tuple[str, Path]]:
    return sorted(
        (
            (path.parent.name, path)
            for path in source_dir.glob("*/train-*.parquet")
        ),
        key=lambda item: item[0],
    )


def _read_family(path: Path) -> list[dict[str, Any]]:
    table = pq.read_table(path)
    if tuple(table.column_names) != SOURCE_COLUMNS:
        raise ValueError(f"Unexpected source columns in {path}: {table.column_names}")
    return sorted(table.to_pylist(), key=lambda row: str(row["case_id"]))


def _sample_assignments(
    family_rows: dict[str, list[dict[str, Any]]],
    *,
    seed: int,
) -> dict[str, dict[str, list[str]]]:
    rng = random.Random(seed)
    assignments: dict[str, dict[str, list[str]]] = {}
    for family in sorted(family_rows):
        rows = sorted(family_rows[family], key=lambda row: str(row["case_id"]))
        family_assignments: dict[str, list[str]] = {}
        for row in rows:
            case_id = str(row["case_id"])
            candidates = [
                str(candidate["case_id"])
                for candidate in rows
                if str(candidate["case_id"]) != case_id
            ]
            family_assignments[case_id] = rng.sample(candidates, NEGATIVE_COUNT)
        assignments[family] = family_assignments
    return assignments


def _assignment_digest(assignments: dict[str, dict[str, list[str]]]) -> str:
    payload = [
        {
            "family": family,
            "case_id": case_id,
            "negative_case_ids": assignments[family][case_id],
        }
        for family in sorted(assignments)
        for case_id in sorted(assignments[family])
    ]
    return hashlib.sha256(
        json.dumps(payload, sort_keys=True, separators=(",", ":")).encode()
    ).hexdigest()


def _video_relpath(family: str, case_id: str) -> str:
    return f"videos/{family}/{case_id}.mp4"


def _update_video_digest(digest: Any, relpath: str, data: bytes) -> None:
    digest.update(relpath.encode())
    digest.update(b"\0")
    digest.update(data)
    digest.update(b"\n")


def _feature_yaml(indent: str = "  ") -> list[str]:
    return [
        f"{indent}- name: text",
        f"{indent}  dtype: string",
        f"{indent}- name: video",
        f"{indent}  dtype: string",
        f"{indent}- name: hard_negative_texts",
        f"{indent}  list: string",
        f"{indent}- name: hard_negative_videos",
        f"{indent}  list: string",
    ]


def _readme(
    *,
    repo_id: str,
    source_repo: str,
    seed: int,
    total_rows: int,
    metadata_size: int,
    video_size: int,
) -> str:
    total_size = metadata_size + video_size
    lines = [
        "---",
        "dataset_info:",
        "  features:",
        *_feature_yaml("  "),
        "  splits:",
        "  - name: train",
        f"    num_bytes: {total_size}",
        f"    num_examples: {total_rows}",
        f"  download_size: {total_size}",
        f"  dataset_size: {total_size}",
        "configs:",
        "- config_name: default",
        "  data_files:",
        "  - split: train",
        "    path: metadata.parquet",
        "---",
        "",
        "# Physics Bench Dynamics With Hard Negatives",
        "",
        f"Repository: `{repo_id}`",
        "",
        f"Source dataset: `{source_repo}`",
        "",
        "This repository uses a path-based VideoFolder-style layout for direct positive and hard-negative loading.",
        "",
        f"- rows: {total_rows}",
        "- metadata columns: `text`, `video`, `hard_negative_texts`, `hard_negative_videos`",
        "- positive text: query 1 (`__full__0`) from the source row",
        f"- hard negatives per row: {NEGATIVE_COUNT}",
        "- video paths: repository-relative `videos/<family>/<case_id>.mp4`",
        "- list alignment: `hard_negative_texts[i]` and `hard_negative_videos[i]` come from the same case",
        "- candidate pool: only the other 99 cases in the positive case's family",
        "",
        "## Reproducibility",
        "",
        f"- global seed: {seed}",
        "- traversal: family alphabetical order, then case_id order",
        f"- sampling: one `random.Random(seed)` stream for all {total_rows} rows",
        "- selection: `random.sample(sorted(other_99_case_ids), 5)`",
        "",
        "## Loading",
        "",
        "```python",
        "from pathlib import Path",
        "import pyarrow.parquet as pq",
        "from huggingface_hub import snapshot_download",
        "",
        f'root = Path(snapshot_download("{repo_id}", repo_type="dataset"))',
        'rows = pq.read_table(root / "metadata.parquet").to_pylist()',
        "row = rows[0]",
        'positive_video = root / row["video"]',
        'negative_videos = [root / path for path in row["hard_negative_videos"]]',
        "```",
        "",
        "The training metadata intentionally contains only the four requested columns. Case IDs and query IDs are retained in `source_metadata/sampling_manifest.json` for auditing.",
        "",
    ]
    return "\n".join(lines)


def _validate_output(
    *,
    out_dir: Path,
    metadata_rows: list[dict[str, Any]],
    family_rows: dict[str, list[dict[str, Any]]],
    expected_total_rows: int,
    source_video_hash: str,
) -> dict[str, Any]:
    errors: list[str] = []
    table = pq.read_table(out_dir / "metadata.parquet")
    if tuple(table.column_names) != OUTPUT_COLUMNS:
        errors.append(
            f"metadata columns are {table.column_names}, expected {OUTPUT_COLUMNS}"
        )
    written_rows = table.to_pylist()
    if len(written_rows) != expected_total_rows:
        errors.append(
            f"metadata has {len(written_rows)} rows, expected {expected_total_rows}"
        )
    if written_rows != metadata_rows:
        errors.append("metadata changed during parquet serialization")

    source_by_path: dict[str, dict[str, Any]] = {}
    for family, rows in family_rows.items():
        for row in rows:
            source_by_path[_video_relpath(family, str(row["case_id"]))] = row

    output_digest = hashlib.sha256()
    seen_positive_paths: set[str] = set()
    hard_negative_pairs = 0
    cross_family_count = 0
    self_negative_count = 0
    for row in written_rows:
        video = str(row["video"])
        source = source_by_path.get(video)
        if source is None:
            errors.append(f"positive video path is unknown: {video}")
            continue
        family = Path(video).parts[1]
        if video in seen_positive_paths:
            errors.append(f"duplicate positive video path: {video}")
        seen_positive_paths.add(video)
        if str(row["text"]) != str(source["raw_text"]):
            errors.append(f"positive text mismatch: {video}")
        neg_texts = list(row["hard_negative_texts"])
        neg_videos = [str(path) for path in row["hard_negative_videos"]]
        if len(neg_texts) != NEGATIVE_COUNT or len(neg_videos) != NEGATIVE_COUNT:
            errors.append(f"{video}: expected five hard negatives")
        if len(set(neg_videos)) != NEGATIVE_COUNT:
            errors.append(f"{video}: hard-negative videos are not unique")
        for neg_text, neg_video in zip(neg_texts, neg_videos):
            hard_negative_pairs += 1
            neg_source = source_by_path.get(neg_video)
            if neg_source is None:
                errors.append(f"{video}: unknown hard-negative path {neg_video}")
                continue
            if Path(neg_video).parts[1] != family:
                cross_family_count += 1
            if neg_video == video:
                self_negative_count += 1
            if str(neg_text) != str(neg_source["raw_text"]):
                errors.append(
                    f"{video}: hard-negative text/path mismatch for {neg_video}"
                )

    if cross_family_count:
        errors.append(f"found {cross_family_count} cross-family hard negatives")
    if self_negative_count:
        errors.append(f"found {self_negative_count} self hard negatives")

    missing_videos = []
    for relpath in sorted(source_by_path):
        path = out_dir / relpath
        if not path.is_file() or path.stat().st_size == 0:
            missing_videos.append(relpath)
            continue
        _update_video_digest(output_digest, relpath, path.read_bytes())
    output_video_hash = output_digest.hexdigest()
    if output_video_hash != source_video_hash:
        errors.append("video bytes changed while creating the VideoFolder")

    return {
        "passed": not errors,
        "errors": errors[:100],
        "metadata_rows": len(written_rows),
        "metadata_columns": table.column_names,
        "video_files": len(source_by_path) - len(missing_videos),
        "missing_videos": missing_videos[:100],
        "hard_negative_pairs": hard_negative_pairs,
        "cross_family_hard_negatives": cross_family_count,
        "self_hard_negatives": self_negative_count,
        "source_video_sha256": source_video_hash,
        "output_video_sha256": output_video_hash,
        "video_bytes_preserved": source_video_hash == output_video_hash,
    }


def build_dataset(
    *,
    source_dir: Path,
    out_dir: Path,
    repo_id: str,
    source_repo: str,
    seed: int,
    expected_rows_per_family: int,
    expected_total_rows: int,
) -> dict[str, Any]:
    source_files = _source_files(source_dir)
    if not source_files:
        raise FileNotFoundError(
            f"No source family parquet files found under {source_dir}"
        )
    family_rows = {
        family: _read_family(path) for family, path in source_files
    }
    bad_counts = {
        family: len(rows)
        for family, rows in family_rows.items()
        if len(rows) != expected_rows_per_family
    }
    if bad_counts:
        raise ValueError(
            f"Expected {expected_rows_per_family} rows per family: {bad_counts}"
        )
    if sum(map(len, family_rows.values())) != expected_total_rows:
        raise ValueError(f"Expected {expected_total_rows} rows in total")

    assignments = _sample_assignments(family_rows, seed=seed)
    repeated = _sample_assignments(family_rows, seed=seed)
    if assignments != repeated:
        raise AssertionError("Hard-negative sampling is not reproducible")

    if out_dir.exists():
        shutil.rmtree(out_dir)
    out_dir.mkdir(parents=True)

    metadata_rows: list[dict[str, Any]] = []
    manifest_rows: list[dict[str, Any]] = []
    source_video_digest = hashlib.sha256()
    video_size = 0
    for family in sorted(family_rows):
        rows = family_rows[family]
        by_case = {str(row["case_id"]): row for row in rows}
        for source_row in rows:
            case_id = str(source_row["case_id"])
            query_id = str(source_row["query_id"])
            if query_id != f"{case_id}__full__0":
                raise ValueError(
                    f"Source row is not the expected dynamics query 1: {query_id}"
                )
            relpath = _video_relpath(family, case_id)
            video_value = source_row["video"]
            video_bytes = bytes(video_value["bytes"])
            video_path = out_dir / relpath
            video_path.parent.mkdir(parents=True, exist_ok=True)
            video_path.write_bytes(video_bytes)
            video_size += len(video_bytes)
            _update_video_digest(source_video_digest, relpath, video_bytes)

            negative_case_ids = assignments[family][case_id]
            negative_rows = [by_case[negative_id] for negative_id in negative_case_ids]
            negative_paths = [
                _video_relpath(family, negative_id)
                for negative_id in negative_case_ids
            ]
            metadata_rows.append(
                {
                    "text": str(source_row["raw_text"]),
                    "video": relpath,
                    "hard_negative_texts": [
                        str(row["raw_text"]) for row in negative_rows
                    ],
                    "hard_negative_videos": negative_paths,
                }
            )
            manifest_rows.append(
                {
                    "family": family,
                    "case_id": case_id,
                    "query_id": query_id,
                    "video": relpath,
                    "negative_case_ids": negative_case_ids,
                    "negative_query_ids": [
                        str(row["query_id"]) for row in negative_rows
                    ],
                    "hard_negative_videos": negative_paths,
                }
            )

    metadata_path = out_dir / "metadata.parquet"
    table = pa.Table.from_pylist(metadata_rows, schema=OUTPUT_SCHEMA)
    pq.write_table(
        table,
        metadata_path,
        compression="snappy",
        row_group_size=100,
        write_page_index=True,
    )
    source_video_hash = source_video_digest.hexdigest()
    validation = _validate_output(
        out_dir=out_dir,
        metadata_rows=metadata_rows,
        family_rows=family_rows,
        expected_total_rows=expected_total_rows,
        source_video_hash=source_video_hash,
    )
    validation.update(
        {
            "repo_id": repo_id,
            "source_repo": source_repo,
            "seed": seed,
            "family_count": len(family_rows),
            "rows_per_family": {
                family: len(rows) for family, rows in family_rows.items()
            },
            "assignment_sha256": _assignment_digest(assignments),
            "second_pass_assignment_sha256": _assignment_digest(repeated),
            "reproducibility_verified": assignments == repeated,
            "single_rng_stream": True,
            "traversal_order": "family alphabetical, then case_id",
        }
    )
    _write_json(out_dir / "quality" / "validation.json", validation)
    _write_json(
        out_dir / "generation_manifest.json",
        {
            "repo_id": repo_id,
            "source_repo": source_repo,
            "seed": seed,
            "algorithm": (
                "one random.Random(seed) stream; sorted families; sorted "
                "case_id; random.sample(other_99, 5)"
            ),
            "family_count": len(family_rows),
            "total_rows": len(metadata_rows),
            "assignment_sha256": _assignment_digest(assignments),
        },
    )
    _write_json(
        out_dir / "source_metadata" / "sampling_manifest.json", manifest_rows
    )
    shutil.copy2(
        Path(__file__).resolve(),
        out_dir / "source_metadata" / "build_hf_hardneg_dataset.py",
    )
    (out_dir / ".gitattributes").write_text(
        "*.mp4 filter=lfs diff=lfs merge=lfs -text\n", encoding="utf-8"
    )
    (out_dir / "README.md").write_text(
        _readme(
            repo_id=repo_id,
            source_repo=source_repo,
            seed=seed,
            total_rows=len(metadata_rows),
            metadata_size=metadata_path.stat().st_size,
            video_size=video_size,
        ),
        encoding="utf-8",
    )
    if not validation["passed"]:
        raise ValueError(f"Validation failed: {validation['errors'][:10]}")
    return validation


def main() -> None:
    parser = argparse.ArgumentParser(
        description="Build path-based dynamics hard-negative VideoFolder data."
    )
    parser.add_argument("--source-dir", type=Path, required=True)
    parser.add_argument("--out-dir", type=Path, required=True)
    parser.add_argument(
        "--repo-id",
        default="gowitheflowlab/physics-bench-dynamics-w-hardnegs",
    )
    parser.add_argument(
        "--source-repo",
        default="gowitheflowlab/physics-bench-dynamics-train-1900",
    )
    parser.add_argument("--seed", type=int, default=42)
    parser.add_argument("--expected-rows-per-family", type=int, default=100)
    parser.add_argument("--expected-total-rows", type=int, default=1900)
    args = parser.parse_args()
    result = build_dataset(
        source_dir=args.source_dir.resolve(),
        out_dir=args.out_dir.resolve(),
        repo_id=args.repo_id,
        source_repo=args.source_repo,
        seed=args.seed,
        expected_rows_per_family=args.expected_rows_per_family,
        expected_total_rows=args.expected_total_rows,
    )
    print(json.dumps(result, indent=2, ensure_ascii=False))


if __name__ == "__main__":
    main()