File size: 6,709 Bytes
9a1f607
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
129
130
131
132
133
134
135
136
137
138
139
"""Stage a checked export with the code and docs from this release. No upload."""
from __future__ import annotations

import argparse
import copy
import hashlib
import json
import os
from pathlib import Path
import re
import shutil
import subprocess
import sys
import time


RUNTIME = {'.cache', '__pycache__', '.git', '.venv', 'work'}


def read_json(path):
    return json.loads(path.read_text(encoding='utf-8'))


def write_json(path, value):
    path.parent.mkdir(parents=True, exist_ok=True)
    path.write_text(json.dumps(value, indent=2), encoding='utf-8')


def inventory(folder):
    folder = folder.resolve(strict=True)
    paths = sorted(
        p for p in folder.rglob('*') if p.is_file()
        and not (set(p.relative_to(folder).parts) & RUNTIME)
        and p.name not in {'release_inventory.json', 'upload_state.json'}
        and p.suffix != '.pyc'
    )
    entries = []
    started = last = time.monotonic()
    for index, path in enumerate(paths, 1):
        with path.open('rb') as handle:
            digest = hashlib.file_digest(handle, 'sha256').hexdigest()
        entries.append({'path': path.relative_to(folder).as_posix(), 'bytes': path.stat().st_size, 'sha256': digest})
        if time.monotonic() - last >= 20:
            print(json.dumps({'event': 'hash_progress', 'files': index, 'total': len(paths)}), flush=True)
            last = time.monotonic()
    result = {
        'status': 'prepared', 'algorithm': 'SHA256', 'files': entries,
        'file_count': len(entries), 'total_bytes': sum(i['bytes'] for i in entries),
        'total_GiB': sum(i['bytes'] for i in entries) / 2**30,
        'note': 'This inventory excludes itself and local runtime files.',
    }
    write_json(folder / 'release_inventory.json', result)
    print(json.dumps({'event': 'inventory_complete', 'files': len(entries), 'GiB': result['total_GiB'], 'seconds': round(time.monotonic()-started, 1)}), flush=True)


def prepare(args):
    source = args.compressed_dir.resolve(strict=True)
    assets = args.assets_dir.resolve(strict=True)
    dest = args.output_dir.resolve()
    for input_path in (source, assets):
        if dest == input_path or dest.is_relative_to(input_path) or input_path.is_relative_to(dest):
            raise ValueError('Use a separate output directory outside the input folders')
    if dest.exists():
        raise ValueError('Output directory already exists. Choose a new directory')
    if not re.fullmatch(r'[A-Za-z0-9_.-]+/[A-Za-z0-9_.-]+', args.repo_id):
        raise ValueError('Use username/dataset-name')
    manifest = read_json(source / 'manifest.json')
    report = read_json(source / 'validation.json')
    if manifest['status'] != 'complete' or report['status'] != 'passed':
        raise ValueError('Use a completed export with a passed validation report')
    dest.mkdir(parents=True)
    for path in assets.rglob('*'):
        relative = path.relative_to(assets)
        if not path.is_file() or set(relative.parts) & RUNTIME or path.suffix in {'.parquet', '.pyc'}:
            continue
        if path.name in {'manifest.json', 'validation.json', 'upload_plan.json', 'release_inventory.json', 'release_checks.json', 'upload_state.json'}:
            continue
        target = dest / relative
        target.parent.mkdir(parents=True, exist_ok=True)
        shutil.copy2(path, target)
    public_manifest = copy.deepcopy(manifest)
    public_manifest['source_folder'] = 'source SQLite databases (local path omitted)'
    write_json(dest / 'manifest.json', public_manifest)
    shutil.copy2(source / 'validation.json', dest / 'validation.json')
    count = 0
    counts = []
    for filename, database in manifest['databases'].items():
        for table, info in database['tables'].items():
            counts.append({'File': filename, 'Table': table, 'Rows': info['rows'], 'Columns': len(info['schema']) - 1, 'SizeBytes': database['source_identity']['bytes']})
            for part in info['parts']:
                relative = Path(Path(filename).stem) / table / part['part']
                src = (source / relative).resolve(strict=True)
                target = (dest / relative).resolve()
                if not src.is_relative_to(source) or not target.is_relative_to(dest):
                    raise ValueError('Invalid manifest part path')
                if src.stat().st_size != part['bytes']:
                    raise ValueError('Part size differs: ' + str(relative))
                target.parent.mkdir(parents=True, exist_ok=True)
                if args.copy_data:
                    shutil.copy2(src, target)
                else:
                    os.link(src, target)  # Requires both folders on one filesystem.
                count += 1
    if count != report['files']:
        raise ValueError('Part count differs from validation report')
    write_json(dest / 'metadata/source_counts.json', counts)
    plan = {
        'repo_id': args.repo_id, 'repo_type': 'dataset', 'public': True,
        'status': 'prepared_not_uploaded', 'parquet_files': count,
        'parquet_bytes': manifest['total_parquet_bytes'],
        'parquet_GiB': manifest['total_parquet_bytes'] / 2**30,
        'tables': report['tables'], 'rows': manifest['total_rows'],
        'original_databases_modified': False, 'code_included': True,
        'local_data_layout': 'copies' if args.copy_data else 'hard links to validated Parquet',
        'source_license': 'No explicit redistribution license supplied; no new license assigned',
    }
    write_json(dest / 'upload_plan.json', plan)
    subprocess.run([sys.executable, str(dest / 'code/prepare_hf_card.py'), '--repo-id', args.repo_id], check=True)
    write_json(dest / 'release_checks.json', {'status': 'not_run_for_this_new_package', 'note': 'Run the documented local validation before publishing this newly staged package.'})
    inventory(dest)
    print(json.dumps(plan, indent=2))


if __name__ == '__main__':
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument('--compressed-dir', type=Path)
    parser.add_argument('--assets-dir', type=Path, default=Path(__file__).resolve().parents[1])
    parser.add_argument('--output-dir', type=Path)
    parser.add_argument('--repo-id', default='alpha31476/spotify-metadata-parquet')
    parser.add_argument('--copy-data', action='store_true', help='Copy data instead of same-filesystem hard links')
    parser.add_argument('--inventory-only', type=Path)
    args = parser.parse_args()
    if args.inventory_only:
        inventory(args.inventory_only)
    elif not args.compressed_dir or not args.output_dir:
        parser.error('--compressed-dir and --output-dir are required for preparation')
    else:
        prepare(args)