Download scripts/publish.py from khb2439/capstone-design-by-task: direct link, hf CLI and curl.
- Browser
- Download file 8.43 kB
-
https://huggingface.co/datasets/khb2439/capstone-design-by-task/resolve/main/scripts/publish.py
- Command line
-
hf download hf://datasets/khb2439/capstone-design-by-task/scripts/publish.py
-
curl -L -o publish.py https://huggingface.co/datasets/khb2439/capstone-design-by-task/resolve/main/scripts/publish.py
8.43 kB
| """Publish the three-task dataset and verify remote metadata without raw-data audits. | |
| Uses the local Hugging Face login. Never embeds credentials in the repository. | |
| State and download cache are kept outside the published dataset directory. | |
| """ | |
| import argparse | |
| import json | |
| from datetime import datetime, timezone | |
| from pathlib import Path | |
| import pandas as pd | |
| import pyarrow.parquet as pq | |
| from huggingface_hub import HfApi, CommitOperationAdd, hf_hub_download | |
| from huggingface_hub.errors import RepositoryNotFoundError | |
| def save(path, value): | |
| path.parent.mkdir(parents=True,exist_ok=True) | |
| path.write_text(json.dumps(value,ensure_ascii=False,indent=2)+'\n',encoding='utf-8') | |
| def read(path): | |
| return json.loads(path.read_text(encoding='utf-8')) | |
| def inventory(root): | |
| return {p.relative_to(root).as_posix():p.stat().st_size for p in root.rglob('*') | |
| if p.is_file() and p.relative_to(root).parts[0] in {'tasks','reports','scripts','README.md','STATUS.json'} | |
| and '.cache' not in p.parts and '__pycache__' not in p.parts | |
| and p.suffix not in {'.pyc','.tmp'} | |
| and p.name!='publish_receipt.json'} | |
| def publish(root, repo_id, state_path, verify_dir): | |
| root=root.resolve() | |
| labels=read(root/'reports/task_labels.json') | |
| summary=read(root/'reports/summary.json') | |
| assert labels['instruction_language']=='en' | |
| assert len(labels['tasks'])==3 and summary['total_episodes']==189 | |
| api=HfApi() | |
| identity=api.whoami() | |
| if identity['name']!=repo_id.split('/')[0]: | |
| raise RuntimeError('The active Hugging Face account does not match the destination owner.') | |
| expected=inventory(root) | |
| state=read(state_path) if state_path.exists() else {} | |
| if state and (state.get('repo_id')!=repo_id or state.get('local_root')!=str(root)): | |
| raise RuntimeError('Publish state belongs to another dataset or destination.') | |
| try: | |
| remote=api.dataset_info(repo_id) | |
| except RepositoryNotFoundError: | |
| api.create_repo(repo_id,repo_type='dataset',private=False,exist_ok=False) | |
| remote=api.dataset_info(repo_id) | |
| state={'repo_id':repo_id,'local_root':str(root),'created_repo':True, | |
| 'initial_revision':remote.sha} | |
| save(state_path,state) | |
| else: | |
| if not state.get('created_repo'): | |
| raise RuntimeError('Destination already exists without this publication state; refusing to replace it.') | |
| if remote.private: | |
| raise RuntimeError('Existing destination is private; refusing an implicit visibility change.') | |
| if not state.get('content_revision'): | |
| if remote.sha!=state['initial_revision']: | |
| raise RuntimeError('Remote head changed since repository creation.') | |
| print(json.dumps({'phase':'uploading','files':len(expected),'bytes':sum(expected.values())}),flush=True) | |
| state['content_inventory']=expected | |
| save(state_path,state) | |
| commit=api.upload_folder(repo_id=repo_id,repo_type='dataset',folder_path=root, | |
| allow_patterns=list(expected), | |
| ignore_patterns=['**/.cache/**','**/__pycache__/**','**/*.pyc','reports/publish_receipt.json'], | |
| parent_commit=remote.sha, | |
| commit_message='Publish three LeRobot v3 task datasets with English instructions') | |
| state['content_revision']=commit.oid | |
| save(state_path,state) | |
| revision=state['content_revision'] | |
| expected=state['content_inventory'] | |
| print(json.dumps({'phase':'verifying_public_files_and_task_metadata','revision':revision}),flush=True) | |
| public_api=HfApi(token=False) | |
| published=public_api.dataset_info(repo_id,revision=revision,files_metadata=True) | |
| assert published.private is False | |
| remote_files={s.rfilename:s.size for s in published.siblings} | |
| missing=sorted(set(expected)-set(remote_files)) | |
| if missing:raise RuntimeError(f'Missing uploaded files: {missing}') | |
| # File size checks only, not content hash comparisons. | |
| mismatches=[name for name,size in expected.items() if remote_files[name]!=size] | |
| if mismatches:raise RuntimeError(f'Uploaded file-size mismatch: {mismatches}') | |
| verified=[] | |
| for group in summary['datasets']: | |
| instruction=labels['tasks'][group['task_slug']]['instruction_en'] | |
| downloaded={} | |
| for file in ['meta/tasks.parquet','meta/info.json','meta/episodes/chunk-000/file-000.parquet']: | |
| downloaded[file]=Path(hf_hub_download(repo_id=repo_id,repo_type='dataset',revision=revision, | |
| filename=f'{group["root"]}/{file}',token=False,cache_dir=str(verify_dir))) | |
| tasks=pd.read_parquet(downloaded['meta/tasks.parquet']) | |
| assert tasks.index.tolist()==[instruction] and tasks['task_index'].tolist()==[0] | |
| info=read(downloaded['meta/info.json']) | |
| assert info['total_episodes']==group['episodes'] and info['total_frames']==group['frames'] | |
| episodes=pq.read_table(downloaded['meta/episodes/chunk-000/file-000.parquet'], | |
| columns=['episode_index','tasks','length']).to_pylist() | |
| assert len(episodes)==group['episodes'] | |
| assert sum(e['length'] for e in episodes)==group['frames'] | |
| assert all(e['tasks']==[instruction] for e in episodes) | |
| assert [e['episode_index'] for e in episodes]==list(range(group['episodes'])) | |
| verified.append({'task_slug':group['task_slug'],'episodes':group['episodes'], | |
| 'frames':group['frames'],'english_instruction':instruction}) | |
| receipt={'repo_id':repo_id,'url':f'https://huggingface.co/datasets/{repo_id}', | |
| 'verified_content_revision':revision,'public':True, | |
| 'published_at_utc':datetime.now(timezone.utc).isoformat(), | |
| 'uploaded_content_files':len(expected),'uploaded_content_bytes':sum(expected.values()), | |
| 'remote_file_inventory_and_sizes':'passed','public_metadata_download':'passed', | |
| 'verified_tasks':verified,'total_episodes':189,'total_frames':129160, | |
| 'source_revision':labels['source_revision'], | |
| 'verification_scope':'Remote file inventory, file sizes, and task/episode metadata only. No checksum audit or exhaustive raw-data/video validation.'} | |
| if (root/'reports/publish_receipt.json').exists(): | |
| previous=read(root/'reports/publish_receipt.json') | |
| if previous.get('verified_content_revision')==revision: | |
| receipt=previous | |
| save(root/'reports/publish_receipt.json',receipt) | |
| status=read(root/'STATUS.json') | |
| status.update({'publication_status':'published','repo_id':repo_id,'visibility':'public', | |
| 'verified_content_revision':revision}) | |
| save(root/'STATUS.json',status) | |
| if not state.get('final_revision'): | |
| final=api.create_commit(repo_id=repo_id,repo_type='dataset',parent_commit=revision, | |
| operations=[CommitOperationAdd(path_in_repo='STATUS.json',path_or_fileobj=root/'STATUS.json'), | |
| CommitOperationAdd(path_in_repo='reports/publish_receipt.json',path_or_fileobj=root/'reports/publish_receipt.json')], | |
| commit_message='Record publication verification and public dataset status') | |
| state['final_revision']=final.oid | |
| save(state_path,state) | |
| final_info=public_api.dataset_info(repo_id,revision=state['final_revision'],files_metadata=True) | |
| final_files={s.rfilename:s.size for s in final_info.siblings} | |
| final_expected={**inventory(root),'reports/publish_receipt.json':(root/'reports/publish_receipt.json').stat().st_size} | |
| assert final_info.private is False | |
| assert all(final_files.get(name)==size for name,size in final_expected.items()) | |
| state['verification']='passed' | |
| save(state_path,state) | |
| print(json.dumps({'phase':'complete','url':receipt['url'],'revision':state['final_revision'], | |
| 'public':True,'verified_files':len(final_expected),'episodes':189},indent=2),flush=True) | |
| if __name__=='__main__': | |
| parser=argparse.ArgumentParser(description=__doc__) | |
| parser.add_argument('--root',type=Path,default=Path(__file__).resolve().parents[1]) | |
| parser.add_argument('--repo-id',default='khb2439/capstone-design-by-task') | |
| parser.add_argument('--state',type=Path,default=Path('work/hf_publish_state.json')) | |
| parser.add_argument('--verify-dir',type=Path,default=Path('work/hf_publish_verify')) | |
| args=parser.parse_args() | |
| publish(args.root,args.repo_id,args.state,args.verify_dir) | |