import os os.environ["TOKENIZERS_PARALLELISM"]="false" import sys from pathlib import Path ROOT=Path('/mnt/data/yuxu/datax-open');RUN=ROOT/'books-markdown-20261205';BUILD=ROOT/'books-build-20261205';REC=ROOT/'books-recovery' sys.path.insert(0,str(BUILD/'vendor'));sys.path.insert(0,str(BUILD/'scripts')) import orjson as j import build,format_markdown as fmt import collections,concurrent.futures,datetime,gzip,hashlib,json,re,sqlite3,shutil,fcntl DB=None ORPHAN=re.compile(r"(?m)^ {0,3}#{1,6} [^\n]+\n?\s*\Z") SENTENCE=re.compile(r'[.!?。!?](?:["”’\')\]]*)[ \t]+(?=[A-Z0-9"“‘(\[])') def now():return datetime.datetime.now(datetime.timezone.utc).isoformat() def boundary(text,start,cap): end=min(len(text),start+cap) if end==len(text):return end minimum=start+(end-start)//2;pick=None for sep in ('\n\n','\n'): k=text.rfind(sep,minimum,end) if k>=minimum:pick=k+len(sep);break if pick is None: matches=list(SENTENCE.finditer(text,minimum,end)) if matches:pick=matches[-1].end() if pick is None: for k in range(end-1,minimum-1,-1): if text[k].isspace():pick=k+1;break if pick is None:pick=end while pick>start: m=ORPHAN.search(text[start:pick]) if not m or m.start()<512:break pick=start+m.start() return pick def prepare(): dbpath=RUN/'kept.sqlite' if (RUN/'reports/index-ready.json').exists():return assert not dbpath.exists(),'partial index; inspect first' con=sqlite3.connect(dbpath) con.execute('CREATE TABLE kept (repo TEXT,file TEXT,line INTEGER,doc TEXT,meta BLOB,PRIMARY KEY(repo,file,line)) WITHOUT ROWID') batch=[];n=0 with (ROOT/'docs/books-dispositions.jsonl').open('rb') as inp: for raw in inp: d=j.loads(raw) if d.get('disposition')!='kept':continue batch.append((d['source_repo'],d['source_file'],d['source_line'],d['document_id'],j.dumps(d))) n+=1 if len(batch)>=2000:con.executemany('INSERT INTO kept VALUES(?,?,?,?,?)',batch);con.commit();batch=[] if batch:con.executemany('INSERT INTO kept VALUES(?,?,?,?,?)',batch);con.commit() assert n==806309 con.close() (RUN/'reports/index-ready.json').write_bytes(j.dumps({'documents':n,'created_at':now()})) def init(): global DB DB=sqlite3.connect(f'file:{RUN/"kept.sqlite"}?mode=ro',uri=True) build.initialize();build.boundary=boundary def base_meta(s,f,line,d,keep,raw,cleaned,edits): up=d.get('metadata',{});lic,url=build.license_info(up,s['repo']) assert lic==keep['license'] return {k:v for k,v in { 'document_id':keep['document_id'],'title':up.get('title') or 'Untitled', 'source_repo':s['repo'],'source_revision':s['revision'],'source_file':f['path'],'source_line':line, 'source_id':d.get('id'),'source_url':keep.get('source_url'),'authors':up.get('author'), 'license':lic,'license_url':url,'license_evidence':up.get('license'), 'license_verification':'upstream_metadata_not_independent_rights_clearance', 'upstream_metadata':up,'upstream_source':d.get('source'),'upstream_added':d.get('added'),'upstream_created':d.get('created'), 'raw_text_sha256':build.sha(raw.encode('utf-8')), 'pre_markdown_text_sha256':build.sha(cleaned.encode('utf-8')), 'cleaning':edits,'markdown_revision':fmt.VERSION, 'quality_revision':'books_full_source_fidelity_markdown_20261205', 'quality_status':'programmatically_formatted_not_independently_text_quality_accepted', 'boundary_revision':'paragraph_sentence_heading_20261205' }.items()} def work(job): index,s,f=job;tag=f'{index:03d}' report=RUN/'reports'/f'{tag}.json' if report.exists(): r=j.loads(report.read_bytes()) if r.get('complete'):return r keep={ln:j.loads(meta) for ln,meta in DB.execute('SELECT line,meta FROM kept WHERE repo=? AND file=?',(s['repo'],f['path']))} outpath=RUN/'staging'/f'{tag}.jsonl.gz' stat={'stage':tag,'repo':s['repo'],'source_file':f['path'],'documents':0,'changed_documents':0,'slices':0, 'tokens':0,'body_bytes':0,'text_bytes':0,'jsonl_bytes':0,'max_tokens':0,'edits':collections.Counter(), 'license_slices':collections.Counter(),'started_at':now()} ledger=RUN/'reports'/f'{tag}.documents.jsonl' events=RUN/'samples'/f'{tag}.samples.jsonl' selected=[];risk={};output_hash=hashlib.sha256() with gzip.open(REC/f['local_path'],'rt',encoding='utf-8',errors='strict') as inp, gzip.open(outpath.with_suffix('.part'),'wb',compresslevel=1) as out,ledger.open('wb') as lg: for lineno,line in enumerate(inp,1): if lineno not in keep:continue d=j.loads(line);k=keep.pop(lineno);raw=d['text'] cleaned,cedits=build.clean(raw,s['repo']) assert build.sha(raw.encode('utf-8'))==k['raw_text_sha256'] assert build.sha(cleaned.encode('utf-8'))==k['cleaned_text_sha256'] title=str(d.get('metadata',{}).get('title') or 'Untitled') converted,edits=fmt.transform(cleaned,title) assert bool(edits)==(converted!=cleaned),(s['repo'],lineno,'edit accounting') meta=base_meta(s,f,lineno,d,k,raw,cleaned,cedits) meta.update({'cleaned_text_sha256':build.sha(converted.encode('utf-8')), 'cleaned_body_chars':len(converted),'cleaned_body_bytes':len(converted.encode('utf-8')), 'markdown_changes':edits}) stat['documents']+=1;stat['changed_documents']+=bool(edits);stat['edits'].update(edits) stat['body_bytes']+=meta['cleaned_body_bytes'] slices=tokens=0 for sl in build.slices(converted,title): text=sl.pop('text');m={**meta,**sl} row={'id':f"books_en_{meta['document_id'].removeprefix('books_')}_{sl['slice_index']:05d}", 'language':'en','meta':m,'text':text} b=j.dumps(row)+b'\n';out.write(b);output_hash.update(b) stat['slices']+=1;stat['tokens']+=sl['token_count'];stat['text_bytes']+=len(text.encode('utf-8')) stat['jsonl_bytes']+=len(b);stat['max_tokens']=max(stat['max_tokens'],sl['token_count']) stat['license_slices'][meta['license']]+=1 slices+=1;tokens+=sl['token_count'] lg.write(j.dumps({'document_id':meta['document_id'],'source_repo':s['repo'],'source_file':f['path'], 'source_line':lineno,'pre_markdown_text_sha256':meta['pre_markdown_text_sha256'], 'cleaned_text_sha256':meta['cleaned_text_sha256'],'cleaned_body_bytes':meta['cleaned_body_bytes'], 'cleaned_body_chars':meta['cleaned_body_chars'],'markdown_changes':edits,'slices':slices,'tokens':tokens})+b'\n') if edits: # Deterministic hash-based sample; a separate per-rule sample catches uncommon transformations. score=build.sha(('markdown-audit-v1:'+meta['document_id']).encode()) candidate={'score':score,'document_id':meta['document_id'],'source_repo':s['repo'], 'source_file':f['path'],'source_line':lineno,'title':title,'edits':edits, 'before_chars':len(cleaned),'after_chars':len(converted)} selected.append(candidate);selected.sort(key=lambda x:x['score']);selected=selected[:3] for rule in edits: if rule not in risk or score