import os, hashlib, json, re
from concurrent.futures import ThreadPoolExecutor
from pathlib import Path
import requests
rev='b08601e04326c79dfdd32d625aee71d232d685c3'
root=Path(os.environ.get('P11_SAE_DATA','p11-sae-data'));root.mkdir(parents=True,exist_ok=True)
names=['train-00000-of-00002.parquet','train-00001-of-00002.parquet','validation-00000-of-00001.parquet']
api=f'https://huggingface.co/api/datasets/Salesforce/wikitext/tree/{rev}/wikitext-103-raw-v1?expand=true'
response=requests.get(api,timeout=60);response.raise_for_status()
objects={row['path'].rsplit('/',1)[-1]:row['lfs']['oid'] for row in response.json() if 'lfs' in row}
manifest={}
for name in names:
 base=f'https://huggingface.co/datasets/Salesforce/wikitext/resolve/{rev}/wikitext-103-raw-v1/{name}'
 first=requests.get(base+'?download=true&chunk=probe',headers={'Range':'bytes=0-0'},timeout=60);first.raise_for_status()
 assert first.status_code==206
 total=int(first.headers['Content-Range'].split('/')[-1]);expected=objects[name]
 target=root/name;tmp=root/(name+'.part')
 chunk=8*1024*1024
 if target.exists() and target.stat().st_size==total and hashlib.sha256(target.read_bytes()).hexdigest()==expected:
  manifest[name]={'bytes':total,'sha256':expected};continue
 start_at=tmp.stat().st_size if tmp.exists() else 0
 assert start_at % chunk == 0 or start_at == total
 def fetch(start):
  end=min(total-1,start+chunk-1)
  r=requests.get(base+f'?download=true&chunk={start}',headers={'Range':f'bytes={start}-{end}'},timeout=120)
  r.raise_for_status(); assert r.status_code==206 and r.headers['Content-Range']==f'bytes {start}-{end}/{total}' and len(r.content)==end-start+1
  return r.content
 with tmp.open('ab') as f, ThreadPoolExecutor(max_workers=4) as pool:
  for start,block in zip(range(start_at,total,chunk),pool.map(fetch,range(start_at,total,chunk))):
   f.write(block);f.flush();print(name,start+len(block),'/',total,flush=True)
 digest=hashlib.sha256(tmp.read_bytes()).hexdigest();assert digest==expected,(digest,expected)
 tmp.replace(target);manifest[name]={'bytes':total,'sha256':digest}
root.joinpath('manifest.json').write_text(json.dumps({'repository':'Salesforce/wikitext','revision':rev,'files':manifest},indent=2),encoding='utf-8')
print('verificado',manifest,flush=True)
