File size: 1,732 Bytes
ca3d57d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
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
#!/usr/bin/env python3
"""Restore text Parquet assets to their original relative paths, checking hashes."""
import argparse
import hashlib
from pathlib import Path, PurePosixPath
import pyarrow.parquet as pq


def main():
    p = argparse.ArgumentParser()
    p.add_argument("--dataset-root", type=Path, required=True)
    p.add_argument("--output", type=Path, required=True)
    args = p.parse_args()
    count = 0
    for base in ["level1/text", "level1/audio"]:
        for parquet in sorted((args.dataset_root / base).rglob("*.parquet")):
            for batch in pq.ParquetFile(parquet).iter_batches(batch_size=4096):
                for row in batch.to_pylist():
                    rel = PurePosixPath(row["original_relpath"])
                    if rel.is_absolute() or ".." in rel.parts:
                        raise ValueError("Unsafe relative path")
                    raw = row["text"].encode("utf-8")
                    assert hashlib.sha256(raw).hexdigest() == row["sha256"]
                    out = args.output / str(rel)
                    # Refuse writing outside the requested output tree through symlinks.
                    if not out.resolve().is_relative_to(args.output.resolve()):
                        raise ValueError("Output path escapes root")
                    out.parent.mkdir(parents=True, exist_ok=True)
                    if out.exists():
                        if out.read_bytes() != raw:
                            raise FileExistsError(out)
                    else:
                        with out.open("xb") as f:
                            f.write(raw)
                    count += 1
    print(f"Restored and verified {count} text files")


if __name__ == "__main__":
    main()