Datasets:
File size: 7,997 Bytes
00b8e9c | 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 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 | 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 0<m['token_count']<=7680 and '\ufffd' not in d['text']
if n%1000==0:assert len(TOK.encode(d['text'],add_special_tokens=False).ids)==m['token_count'];recount+=1
n+=1;ts+=m['token_count']
assert h.hexdigest()==f['sha256'] and n==f['slices'] and ts==f['tokens']
return {'path':f['path'],'passed':True,'token_recounts':recount}
class Writer:
def __init__(self):self.files=[];self.f=None
def open(self):
self.path=RUN/'books.ready'/f'books_en_{len(self.files):05d}.jsonl'
self.f=self.path.open('wb');self.size=self.n=self.ts=0;self.h=hashlib.sha256()
def close(self):
if self.f is None:return
self.f.close();self.files.append({'path':'books/'+self.path.name,'bytes':self.size,'sha256':self.h.hexdigest(),'slices':self.n,'tokens':self.ts});self.f=None
def add(self,b,t):
if self.f and self.size+len(b)>200_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()
|