import os,sys,time os.environ['TOKENIZERS_PARALLELISM']='false' from pathlib import Path ROOT=Path('/mnt/data/yuxu/datax-open');RUN=ROOT/'books-clean-full-20261205' sys.path.insert(0,str(ROOT/'books-build-20261205/vendor')) import orjson as j,gzip,collections,hashlib,datetime,concurrent.futures,sqlite3,shutil from tokenizers import Tokenizer TOK=None def now():return datetime.datetime.now(datetime.timezone.utc).isoformat() def save(p,d):p.write_bytes(j.dumps(d,option=j.OPT_INDENT_2)) def check(f): global TOK if TOK is None:TOK=Tokenizer.from_file(str(ROOT/'books-recovery/metadata/tokenizer-qwen2/tokenizer.json')) n=ts=recount=0;h=hashlib.sha256() with (RUN/'books.ready'/Path(f['path']).name).open('rb') as inp: for raw in inp: h.update(raw);d=j.loads(raw.decode('utf-8'));m=d['meta'] assert raw.endswith(b'\n') and set(d)=={'id','language','meta','text'} and d['language']=='en' assert 0200_000_000:self.close() if self.f is None:self.open() self.f.write(b);self.h.update(b);self.size+=len(b);self.n+=1;self.ts+=t def main(): while not (RUN/'reports/build-complete.json').exists(): if 'Traceback' in (RUN/'logs/build.log').read_text():raise RuntimeError('builder failed') time.sleep(15) data=j.loads((RUN/'reports/build-complete.json').read_bytes());stages=data['stages'] assert not list((RUN/'books.ready').glob('*.jsonl')) assert shutil.disk_usage(ROOT).free>sum(s['jsonl_bytes'] for s in stages)+15*1024**3 writer=Writer();seen=set();counts=collections.Counter();licenses=collections.Counter();sources=collections.defaultdict(collections.Counter) bydoc=sqlite3.connect(RUN/'documents.sqlite');bydoc.execute('CREATE TABLE docs(doc TEXT PRIMARY KEY,record BLOB)') for s in stages: tag=s['stage'];cur=None;off=idx=nb=0;h=None;fh=hashlib.sha256() rems=collections.defaultdict(list) with gzip.open(RUN/'removals'/f'{tag}.jsonl.gz','rb') as inp: for raw in inp: x=j.loads(raw);assert hashlib.sha256(x['text'].encode()).hexdigest()==x['sha256'];rems[x['document_id']].append(x) docparts=[] def finish(): if cur: text=''.join(docparts) assert off==cur['cleaned_body_chars'] and nb==cur['cleaned_body_bytes'] and h.hexdigest()==cur['cleaned_text_sha256'] spans=sorted(rems.get(cur['document_id'],[]),key=lambda x:x['start']);oldpos=newpos=0;rebuild=[] for x in spans: assert x['start']>=oldpos;n=x['start']-oldpos;rebuild.extend((text[newpos:newpos+n],x['text'])) oldpos=x['end'];newpos+=n rebuild.append(text[newpos:]);original=''.join(rebuild) assert len(original)==cur['input_markdown_chars'] and hashlib.sha256(original.encode()).hexdigest()==cur['input_markdown_sha256'] with gzip.open(RUN/'staging'/f'{tag}.jsonl.gz','rb') as inp: for raw in inp: fh.update(raw);d=j.loads(raw);m=d['meta'];doc=m['document_id'];t=d['text'] if cur is None or doc!=cur['document_id']: finish();assert doc not in seen;seen.add(doc);cur=m;off=idx=nb=0;h=hashlib.sha256();docparts=[] counts['documents']+=1;counts['body_bytes']+=m['cleaned_body_bytes'];sources[m['source_repo']]['documents']+=1 sources[m['source_repo']]['body_bytes']+=m['cleaned_body_bytes'] assert m['slice_index']==idx and m['body_char_start']==off assert d['id']==f"books_en_{doc.removeprefix('books_')}_{idx:05d}" body=t[m['prefix_chars']:len(t)-m['suffix_chars'] if m['suffix_chars'] else len(t)] assert len(body)==m['body_char_end']-off b=body.encode();h.update(b);nb+=len(b);docparts.append(body);off=m['body_char_end'];idx+=1 assert '\ufffd' not in body writer.add(raw,m['token_count']);counts['slices']+=1;counts['tokens']+=m['token_count'];counts['text_bytes']+=len(t.encode()) counts['max_tokens']=max(counts['max_tokens'],m['token_count']);licenses[m['license']]+=1 sources[m['source_repo']]['slices']+=1;sources[m['source_repo']]['tokens']+=m['token_count'] finish();assert fh.hexdigest()==s['jsonl_sha256'] batch=[] with (RUN/'reports'/f'{tag}.documents.jsonl').open('rb') as inp: for raw in inp: x=j.loads(raw);batch.append((x['document_id'],raw)) if len(batch)>=1000:bydoc.executemany('INSERT INTO docs VALUES (?,?)',batch);bydoc.commit();batch=[] if batch:bydoc.executemany('INSERT INTO docs VALUES (?,?)',batch);bydoc.commit() print('PACKED',tag,dict(counts),flush=True) writer.close() assert counts['documents']==sum(s['kept_records'] for s in stages) and counts['tokens']==sum(s['tokens'] for s in stages) with concurrent.futures.ProcessPoolExecutor(12) as pool:checks=list(pool.map(check,writer.files)) full=j.loads((ROOT/'docs/books-manifest.json').read_bytes()) qby=collections.Counter();removed=collections.Counter() for s in stages:qby.update(s['quarantine_reasons']);removed.update(s['removal_rules']) totals={k:sum(s.get(k,0) for s in stages) for k in ['input_records','input_tokens','kept_records','changed_records','quarantined_records','quarantine_input_tokens','kept_input_tokens','removed_chars','removal_spans']} held=sum(x.get('quarantined_records',0) for x in data['index']['source_counts'].values()) heldt=sum(x.get('quarantine_input_tokens',0) for x in data['index']['source_counts'].values()) manifest={'release':'books-strict-clean-20261205','status':'strict_cleaned_pending_textual_review','created_at':now(), 'counts':dict(counts),'source_counts':dict(sources),'file_count':len(writer.files),'jsonl_bytes':sum(f['bytes'] for f in writer.files), 'files':writer.files,'language':['en'],'record_fields':['id','language','meta','text'],'format':'uncompressed UTF-8 JSONL', 'tokenizer':full['tokenizer'],'text_token_limit':7680,'context_target':8192, 'license_inventory_training_slices':dict(licenses),'prior_release':'books-full-markdown-20261205', 'input_records':806309,'input_tokens':26911243820,'source_held_records':held,'source_held_input_tokens':heldt, 'active_cleaning_totals':totals,'quarantine_reason_counts':dict(qby),'removed_span_rules':dict(removed), 'technical_validation':{'passed':True,'all_retained_bodies_hash_reconstructed':True,'all_retained_deletions_reversible':True, 'full_file_hash_schema_checks':True,'independent_token_recounts':sum(x['token_recounts'] for x in checks)}, 'quality_caveats':['Not lossless original publication and not a guarantee of zero semantic/OCR errors.', 'DOAB, Library of Congress and Pre-1929 held wholesale due unresolved systematic extraction risk, not proof all their books are bad.', 'All806309 prior source records have an auditable retained/quarantine disposition. Removed attribution preserved in metadata and sidecars.', 'No guessed OCR repair, generated replacement prose, or invented formulas. Exact long duplicate/repetition risk is isolated.', 'Preserved per-slice source-title wrappers; current title policy unchanged.', 'This manifest does not replace independent legal-rights clearance.']} save(RUN/'reports/manifest.pending.json',manifest) save(RUN/'reports/technical-validation.json',{'passed':True,'checked_at':now(),'files':checks}) save(RUN/'reports/package-complete.json',{'complete':True,'time':now(),'files':len(writer.files),'counts':dict(counts)}) print('PACKAGE COMPLETE',flush=True) if __name__=='__main__':main()