File size: 6,049 Bytes
88d648e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
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
#!/usr/bin/env python3
"""Resolve the annotation release against legally obtained local source waveforms.

No audio is downloaded. No source waveform is modified. All host-specific paths
are written only beneath --output-root, never into the annotation release.
"""
import argparse
import hashlib
import json
import os
from pathlib import Path
import shutil


def sha256(path):
    h = hashlib.sha256()
    with path.open('rb') as f:
        for block in iter(lambda: f.read(1024 * 1024), b''):
            h.update(block)
    return h.hexdigest()


def records(path):
    with path.open(encoding='utf-8') as f:
        for line in f:
            if line.strip():
                yield json.loads(line)


def main():
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument('--release-root', type=Path, default=Path(__file__).resolve().parents[1])
    parser.add_argument('--source-root', action='append', default=[], metavar='DATASET=PATH',
                        help='Repeat for audioset_strong, audiotime, tacos; root precedes catalog source_relative_path.')
    parser.add_argument('--output-root', type=Path, required=True)
    parser.add_argument('--include', nargs='+', choices=['temporal_init', 'sft', 'rl', 'benchmark'], default=['sft', 'rl', 'benchmark'])
    parser.add_argument('--mode', choices=['symlink', 'copy'], default='symlink')
    parser.add_argument('--verify-hashes', action='store_true', help='Check all available saved file SHA256 values; no decoding.')
    parser.add_argument('--dry-run', action='store_true', help='Resolve/check source files without writing output.')
    args = parser.parse_args()
    release = args.release_root.resolve()
    output = args.output_root.resolve()
    if output == release or release in output.parents:
        parser.error('--output-root must be outside the released repository')
    roots = {}
    for specification in args.source_root:
        name, sep, value = specification.partition('=')
        if not sep or name not in ('audioset_strong', 'audiotime', 'tacos'):
            parser.error('source roots must use audioset_strong=..., audiotime=..., tacos=...')
        roots[name] = Path(value).expanduser().resolve()
    selected = set(args.include)
    required = []
    missing = []
    bad = []
    verified = 0
    for r in records(release / 'audio/catalog.jsonl'):
        if not selected.intersection(r['used_by']):
            continue
        root = roots.get(r['source_dataset'])
        source = root / r['source_relative_path'] if root else None
        if source is None or not source.is_file():
            missing.append({'audio_id': r['audio_id'], 'dataset': r['source_dataset'],
                            'source_relative_path': r['source_relative_path']})
            continue
        if r.get('size_bytes') is not None and source.stat().st_size != r['size_bytes']:
            bad.append({'audio_id': r['audio_id'], 'error': 'size mismatch'})
        if args.verify_hashes and r.get('file_sha256'):
            verified += 1
            if sha256(source) != r['file_sha256']:
                bad.append({'audio_id': r['audio_id'], 'error': 'file SHA256 mismatch'})
        required.append((r, source))
    report = {'selected': sorted(selected), 'found_audio': len(required),
              'missing_audio': len(missing), 'invalid_audio': len(bad),
              'verified_file_hashes': verified, 'missing_examples': missing[:20], 'invalid_examples': bad[:20]}
    print(json.dumps(report, indent=2, ensure_ascii=False))
    if missing or bad:
        raise SystemExit('Audio validation failed; no dataset was materialized. Obtain the exact source exports listed in the catalog.')
    if args.dry_run:
        return
    output.mkdir(parents=True, exist_ok=True)
    for r, source in required:
        destination = output / r['path']
        destination.parent.mkdir(parents=True, exist_ok=True)
        if destination.is_symlink():
            if destination.resolve() == source.resolve():
                continue
            raise SystemExit(f'Refusing to overwrite mismatched symlink: {destination}')
        if destination.exists():
            if args.mode == 'copy' and destination.stat().st_size == source.stat().st_size and sha256(destination) == sha256(source):
                continue
            raise SystemExit(f'Refusing to overwrite existing file: {destination}')
        if args.mode == 'symlink':
            destination.symlink_to(source)
        else:
            shutil.copy2(source, destination)
    def rewrite(value):
        if isinstance(value, list):
            return [rewrite(x) for x in value]
        if isinstance(value, dict):
            return {k: rewrite(v) for k, v in value.items()}
        if isinstance(value, str) and value.startswith(('audio/audioset_strong/', 'audio/audiotime/', 'audio/tacos/')):
            return str(output / value)
        return value
    for split in sorted(selected):
        for p in (release / split).glob('*'):
            if not p.is_file():
                continue
            destination = output / split / p.name
            destination.parent.mkdir(parents=True, exist_ok=True)
            if p.suffix == '.jsonl':
                with destination.open('w', encoding='utf-8') as f:
                    for row in records(p):
                        f.write(json.dumps(rewrite(row), ensure_ascii=False, separators=(',', ':')) + '\n')
            elif p.suffix == '.json':
                destination.write_text(json.dumps(rewrite(json.loads(p.read_text())), ensure_ascii=False, indent=2) + '\n')
            else:
                shutil.copy2(p, destination)
    (output / 'audio').mkdir(exist_ok=True)
    shutil.copy2(release / 'audio/catalog.jsonl', output / 'audio/catalog.jsonl')
    for name in ['task_families.json']:
        shutil.copy2(release / name, output / name)
    (output / 'materialization_audit.json').write_text(json.dumps(report, indent=2) + '\n')
    print(f'Materialized datasets: {output}')


if __name__ == '__main__':
    main()