Download scripts/build_catalogue.py from fffiloni/SimReady-assets-explorer: direct link, hf CLI and curl.
- Browser
- Download file 6.41 kB
-
https://huggingface.co/spaces/fffiloni/SimReady-assets-explorer/resolve/main/scripts/build_catalogue.py
- Command line
-
hf download hf://spaces/fffiloni/SimReady-assets-explorer/scripts/build_catalogue.py
-
curl -L -o build_catalogue.py https://huggingface.co/spaces/fffiloni/SimReady-assets-explorer/resolve/main/scripts/build_catalogue.py
6.41 kB
| """Build the public catalogue without downloading model geometry. | |
| The NVIDIA media service supplies prepared web USD, thumbnails and motion clips. | |
| Original dataset URLs are immutable (commit-pinned). Media URLs are external | |
| dependencies; use --media-base with a separately mirrored compatible tree. | |
| """ | |
| import argparse, collections, concurrent.futures, datetime, hashlib, json, re, urllib.request | |
| from pathlib import Path | |
| ROOT=Path(__file__).resolve().parents[1] | |
| DEFAULT_BASE='https://nvidia-simready-central.hf.space/library_media/usdsearch-dev' | |
| def fetch_json(url): | |
| with urllib.request.urlopen(url, timeout=40) as response: return json.load(response) | |
| def humanize(name): | |
| name=re.sub(r'^sm_', '', name) | |
| name=re.sub(r'_[a-z]\d{2}(?:_\d+)?$', '', name) | |
| name=re.sub(r'([a-z])([A-Z])', r'\1 \2', name).replace('_',' ') | |
| return name[:1].upper()+name[1:] | |
| def apply_source_corrections(assets, corrections): | |
| applied=[] | |
| for asset in assets: | |
| correction=corrections.get('assets',{}).get(asset['id']) | |
| if not correction or correction['dataset']!=asset['dataset'] or correction['fromRevision']!=asset['revision']: | |
| continue | |
| old,new=correction['fromRevision'],correction['toRevision'] | |
| if not re.fullmatch('[a-f0-9]{40}',new): | |
| raise ValueError('Source correction must use an immutable commit.') | |
| for field in ('source','sourceFolder','download','image','imageFallback'): | |
| asset[field]=asset[field].replace('/'+old+'/', '/'+new+'/') | |
| asset['revision']=new | |
| applied.append({'id':asset['id'],**correction}) | |
| return applied | |
| def main(): | |
| parser=argparse.ArgumentParser();parser.add_argument('--manifest',type=Path);parser.add_argument('--media-base',default=DEFAULT_BASE);args=parser.parse_args() | |
| cache=ROOT/'.cache';cache.mkdir(exist_ok=True) | |
| if args.manifest: manifest=json.loads(args.manifest.read_text()) | |
| else: | |
| manifest=fetch_json(DEFAULT_BASE+'/manifest.json');(cache/'media-manifest.json').write_text(json.dumps(manifest)) | |
| repos=sorted({'/'.join(url.split('/')[4:6]) for url in manifest['assets']}) | |
| def repo_info(repo): | |
| file=cache/('repo-'+repo.replace('/','--')+'.json') | |
| try: | |
| value=json.loads(file.read_text()) if file.exists() else fetch_json('https://huggingface.co/api/datasets/'+repo) | |
| if not file.exists(): file.write_text(json.dumps(value)) | |
| card=value.get('cardData') or {} | |
| return repo,{'license':card.get('license'), 'sha':value.get('sha'),'gated':value.get('gated',False)} | |
| except Exception as error: return repo,{'license':None,'metadataError':str(error)} | |
| with concurrent.futures.ThreadPoolExecutor(max_workers=6) as pool: metadata=dict(pool.map(repo_info,repos)) | |
| featured=['Robotiq_2F_140','chair_office_fabric_manager_a01','lighting_taskLight_adjustableArmBench_a01','equipment_utility_cart_e01','food_produce_banana_m01','palletJack_lowProfile_a01','cooking_ldgl6924s','standardbots_thor'] | |
| assets=[];seen=set();duplicates=[] | |
| for source,entry in manifest['assets'].items(): | |
| repo='/'.join(source.split('/')[4:6]);revision,path=source.split('/blob/',1)[1].split('/',1) | |
| if (repo,path) in seen: duplicates.append(source);continue | |
| seen.add((repo,path));folder=path.split('/')[0] | |
| filename=path.rsplit('/',1)[-1];name=humanize(folder) | |
| media=args.media_base.rstrip('/')+'/'+entry['id']+'/' | |
| usd=entry.get('usd',{});files=usd.get('files',{});still=entry.get('still',{}).get('files',{}) | |
| motion=entry.get('rtxclip',{}).get('files',{}) | |
| rank=next((i for i,term in enumerate(featured) if term in path),None) | |
| thumbnail_path=path.rsplit('/',1)[0]+'/.thumbs/256x256/'+filename | |
| thumbnail_base=f'https://huggingface.co/datasets/{repo}/resolve/{revision}/'+thumbnail_path | |
| assets.append({'id':entry['id'],'name':name,'dataset':repo,'author':repo.split('/')[0],'folder':folder,'path':path,'revision':revision,'source':source,'sourceFolder':f'https://huggingface.co/datasets/{repo}/tree/{revision}/{folder}', 'download':source.replace('/blob/','/resolve/'), 'image':thumbnail_base+'_transparent.png','imageFallback':thumbnail_base+'_light.png','renderedPreview':media+still['poster'] if still.get('poster') else None,'model':media+files['asset'] if files.get('asset') else None,'compact':usd.get('compact'),'moving':entry.get('moving',0),'robot':bool(entry.get('robot')),'bytes':usd.get('wire',{}).get('tier1',usd.get('bytes',{}).get('tier1')),'video':media+motion['textured'] if motion.get('textured') else None,'license':metadata[repo].get('license'),'rank':rank}) | |
| assets.sort(key=lambda a:(a['rank'] if a['rank'] is not None else 100, hashlib.sha256(a['id'].encode()).hexdigest())) | |
| for a in assets: | |
| a.pop('rank') | |
| corrections=apply_source_corrections(assets,json.loads((ROOT/'tools/catalogue-corrections.json').read_text())) | |
| # Never infer absence from the repo API's truncated siblings list. | |
| # The browser tries native alpha, then light, then original at the pinned revision. | |
| try: | |
| collection=fetch_json('https://huggingface.co/api/collections/cfahlgren1/openusd-datasets');collection_repos=[item['id'] for item in collection['items'] if item['type']=='dataset'] | |
| except Exception: collection_repos=[] | |
| counts=collections.Counter(a['dataset'] for a in assets) | |
| report={'generatedAt':datetime.datetime.now(datetime.timezone.utc).isoformat(),'manifestGeneratedAt':manifest.get('generated_at'),'assetCount':len(assets),'datasetCount':len(counts),'articulated':sum(a['moving']>0 for a in assets),'withVideo':sum(bool(a['video']) for a in assets),'counts':dict(counts),'collectionNotInManifest':sorted(set(collection_repos)-set(repos)),'duplicatesRemoved':duplicates,'mediaBase':args.media_base,'coverage':'Prepared web assets listed by SimReady Central. Not a complete inventory of every USD file in each source repository.','externalMedia':True,'datasets':metadata} | |
| report['sourceCorrections']=corrections | |
| (ROOT/'public/catalogue.json').write_text(json.dumps({'meta':report,'assets':assets},separators=(',',':'))) | |
| (ROOT/'reports/catalogue.json').write_text(json.dumps(report,indent=2)) | |
| print(json.dumps({k:report[k] for k in ['assetCount','datasetCount','articulated','withVideo','collectionNotInManifest']},indent=2)) | |
| if __name__=='__main__':main() | |