File size: 6,146 Bytes
ce83ac1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
#!/usr/bin/env python3
"""Apply verified source URLs and source-video clip intervals."""
from __future__ import annotations

import argparse
from collections import Counter
import csv
from datetime import datetime, timezone
import hashlib
import json
from pathlib import Path
import shutil

import pyarrow as pa
import pyarrow.parquet as pq


def write_csv(path, rows, fields):
    with path.open('w', encoding='utf-8-sig', newline='') as stream:
        writer = csv.DictWriter(stream, fieldnames=fields)
        writer.writeheader()
        for row in rows:
            writer.writerow({k: json.dumps(v, ensure_ascii=False, sort_keys=True)
                             if isinstance(v, (list, dict)) else v for k, v in row.items()})


def main():
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument('--release-root', type=Path, required=True)
    args = parser.parse_args()
    root = args.release_root.resolve()
    public = root / 'huggingface'
    sources = json.loads((public / 'reference_sources.json').read_text())
    stamp = datetime.now(timezone.utc).strftime('%Y%m%dT%H%M%SZ')
    backup = root / 'private/reference_source_recovery' / ('before_apply_' + stamp)
    plans = []
    changed_ids = set()
    for split in ('all', 'train'):
        for task in ('i2v', 'v2v'):
            folder = public / split / task
            path = folder / ('data-00000-of-00001.parquet' if split == 'all'
                             else 'train-00000-of-00001.parquet')
            table = pq.read_table(path)
            before = table.to_pylist()
            after = [dict(row) for row in before]
            for old, new in zip(before, after):
                source = sources.get(new['task_id'])
                if not source:
                    continue
                url = source['reference_url']
                if old['reference_url'] and old['reference_url'] != url:
                    raise ValueError('Conflicting existing locator: ' + new['task_id'])
                new['reference_url'] = url
                updated_fields = {'reference_url'}
                if 'keyclip_start_s' in source or 'keyclip_end_s' in source:
                    if new['task'] != 'v2v':
                        raise ValueError('Clip timestamps are only valid for V2V: ' + new['task_id'])
                    start = source.get('keyclip_start_s')
                    end = source.get('keyclip_end_s')
                    if start is None or end is None or float(start) < 0 or float(start) >= float(end):
                        raise ValueError('Invalid source clip interval: ' + new['task_id'])
                    new['keyclip_start_s'] = float(start)
                    new['keyclip_end_s'] = float(end)
                    updated_fields.update({'keyclip_start_s', 'keyclip_end_s'})
                assert {k: v for k, v in old.items() if k not in updated_fields} == {
                    k: v for k, v in new.items() if k not in updated_fields}
                changed_ids.add(new['task_id'])
            assert len(before) == len(after) == 693
            assert table.schema.names[-1] == 'qa'
            for row in after:
                for field in ('video_categories', 'subtypes', 'subjects', 'motion_types', 'events', 'qa'):
                    assert isinstance(row[field], list), (row['task_id'], field)
            plans.append((path, table.schema, after))
    assert changed_ids == set(sources)
    for task in ('i2v', 'v2v'):
        assert next(p[2] for p in plans if p[0].parent == public / 'all' / task) == next(
            p[2] for p in plans if p[0].parent == public / 'train' / task)
    issues_path = public / 'data_issues.csv'
    with issues_path.open(encoding='utf-8-sig', newline='') as stream:
        reader = csv.DictReader(stream)
        issue_fields = reader.fieldnames
        issues = [row for row in reader if not (
            row['issue'] == 'missing_reference_url' and row['task_id'] in sources)]
    for path, schema, rows in plans:
        for file in (path, path.parent / 'records.jsonl', path.parent / 'records.csv'):
            dest = backup / file.relative_to(public)
            dest.parent.mkdir(parents=True, exist_ok=True)
            shutil.copy2(file, dest)
        temp = path.with_suffix('.parquet.tmp')
        pq.write_table(pa.Table.from_pylist(rows, schema=schema), temp, compression='zstd')
        assert pq.read_table(temp).to_pylist() == rows
        temp.replace(path)
        (path.parent / 'records.jsonl').write_text(''.join(
            json.dumps(row, ensure_ascii=False, sort_keys=True) + '\n' for row in rows))
        write_csv(path.parent / 'records.csv', rows, schema.names)
    for name in ('data_issues.csv', 'manifest.json'):
        shutil.copy2(public / name, backup / name)
    write_csv(issues_path, issues, issue_fields)
    manifest_path = public / 'manifest.json'
    manifest = json.loads(manifest_path.read_text())
    manifest['warnings'] = dict(Counter(row['issue'] for row in issues))
    manifest['rows_with_warnings'] = len({row['task_id'] for row in issues})
    manifest['reference_sources_updated_at'] = datetime.now(timezone.utc).isoformat()
    for name in list(manifest['files']) + ['reference_sources.json', 'data_issues.csv']:
        file = public / name
        if file.is_file():
            data = file.read_bytes()
            manifest['files'][name] = {'bytes': len(data), 'sha256': hashlib.sha256(data).hexdigest()}
    manifest_path.write_text(json.dumps(manifest, indent=2) + '\n')
    report = {'source_locators_recovered': len(changed_ids), 'source_intervals_updated': sum(
                  'keyclip_start_s' in sources[task_id] for task_id in changed_ids),
              'remaining_issues': len(issues), 'all_train_identical': True,
              'non_reference_fields_unchanged': True,
              'backup': str(backup), 'changed_task_ids': sorted(changed_ids)}
    (backup.parent / ('apply_report_' + stamp + '.json')).write_text(json.dumps(report, indent=2) + '\n')
    print(json.dumps({k: v for k, v in report.items() if k != 'changed_task_ids'}), flush=True)


if __name__ == '__main__':
    main()