File size: 5,664 Bytes
47652a2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""Manifest-validated Hugging Face upload with SDK-managed concurrency and resume."""
import argparse
from concurrent.futures import ThreadPoolExecutor
import json
import logging
import os
from pathlib import Path

from filelock import FileLock
from huggingface_hub import HfApi
from huggingface_hub.errors import RepositoryNotFoundError
from convert_dataset import sha256, save_json


def main():
    p = argparse.ArgumentParser(description=__doc__)
    p.add_argument('--folder', type=Path, required=True)
    p.add_argument('--repo-id', default='leeibo/TraceSpatial-Trace')
    p.add_argument('--workers', type=int, default=4, help='Checksum workers; also upload workers when --legacy-workers is used')
    p.add_argument('--execute', action='store_true', help='Without this flag, only validate and show upload plan')
    p.add_argument('--legacy-workers', action='store_true', help='Use resumable upload_large_folder for explicit worker control (deprecated upstream)')
    args = p.parse_args()
    if args.workers < 1: p.error('--workers must be positive')
    root = args.folder.resolve()
    manifest_path = root/'manifest.json'
    if not manifest_path.is_file(): p.error('Conversion manifest.json missing; finish conversion first')
    manifest = json.loads(manifest_path.read_text(encoding='utf-8'))
    if not manifest.get('complete'): p.error('Conversion not complete')
    (root/'.state').mkdir(exist_ok=True)
    logging.basicConfig(level=logging.INFO, format='%(asctime)s %(message)s',
                        handlers=[logging.StreamHandler(), logging.FileHandler(root/'.state'/'upload.log', encoding='utf-8')])
    with FileLock(root/'.state'/'upload.lock', timeout=0), FileLock(root/'.state'/'convert.lock', timeout=0):
        def validate(item):
            path = (root/item['path']).resolve()
            if root not in path.parents or not path.is_file():
                raise RuntimeError(f'Invalid/missing shard path: {item["path"]}')
            if path.stat().st_size != item['bytes'] or sha256(path) != item['sha256']:
                raise RuntimeError(f'Shard checksum mismatch: {item["path"]}')
        with ThreadPoolExecutor(max_workers=args.workers) as pool:
            list(pool.map(validate, manifest['files']))
        tracked = {x['path'] for x in manifest['files']}
        actual = {f.relative_to(root).as_posix() for f in root.glob('data/**/*.parquet')}
        if tracked != actual:
            raise RuntimeError('Untracked or missing data shards; use a clean output directory')
        if not (root/'README.md').is_file(): raise RuntimeError('README.md missing')
        ancillary = [p.relative_to(root).as_posix() for pattern in ('scripts/*.py','scripts/*.md','scripts/*.txt','scripts/*.yml','assets/*') for p in root.glob(pattern) if p.is_file()]
        allow = sorted(tracked) + ['README.md','manifest.json'] + ancillary
        logging.info('Plan: %s files, %.3f GiB in data shards, %s QA rows -> %s',len(allow),sum(f['bytes'] for f in manifest['files'])/1024**3,manifest['qa_rows'],args.repo_id)
        if not args.execute:
            logging.info('Dry run complete; add --execute to upload. No network writes performed.')
            return
        # Bind SDK resume cache to one destination. Never print or embed the token.
        binding = root/'.state'/'upload-target.json'
        target = {'repo_id':args.repo_id, 'repo_type':'dataset'}
        if binding.exists() and json.loads(binding.read_text(encoding='utf-8')) != target:
            raise RuntimeError('This folder upload cache belongs to another repo; use a fresh staging folder')
        api = HfApi()
        logging.info('Authenticated as %s',api.whoami()['name'])
        try:
            info = api.dataset_info(args.repo_id)
            logging.info('Existing repository visibility: %s', 'private' if info.private else 'public')
        except RepositoryNotFoundError:
            api.create_repo(args.repo_id, repo_type='dataset', private=True, exist_ok=True)
        save_json(binding,target)
        if args.legacy_workers:
            # Explicitly requested compatibility mode; no concurrent committing processes.
            api.upload_large_folder(repo_id=args.repo_id, repo_type='dataset', folder_path=root,
                                    num_workers=args.workers, allow_patterns=allow, print_report_every=30)
        else:
            from huggingface_hub.utils._runtime import is_xet_available
            if not is_xet_available():
                raise RuntimeError("Install hf-xet from requirements.txt for resumable multi-commit upload")
            # Current SDK: internally concurrent, resumable, automatically splits commits.
            api.upload_folder(repo_id=args.repo_id, repo_type='dataset', folder_path=root,
                              allow_patterns=allow, commit_message='Publish TraceSpatial RGB and QA Parquet release')
        remote = {f.path:f for f in api.list_repo_tree(args.repo_id,repo_type='dataset',recursive=True) if hasattr(f,'size')}
        for item in manifest['files']:
            f = remote.get(item['path'])
            if f is None or f.size != item['bytes']:
                raise RuntimeError(f'Remote size mismatch: {item["path"]}')
            lfs = getattr(f,'lfs',None)
            remote_sha = getattr(lfs,'sha256',None)
            if remote_sha and remote_sha != item['sha256']:
                raise RuntimeError(f'Remote SHA-256 mismatch: {item["path"]}')
        logging.info('Upload verified: https://huggingface.co/datasets/%s',args.repo_id)


if __name__ == '__main__':
    main()