xytpai's picture
Replace books with strict-cleaned quality-first subset; quarantine hard-to-repair source text
00b8e9c verified
Raw History Blame Contribute Delete
4.15 kB
import sys,os,time
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,extra_gate,package
import collections,hashlib,sqlite3,concurrent.futures,datetime,shutil
def main():
while not (RUN/'reports/package-complete.json').exists():time.sleep(10)
v1=RUN/'candidate-v1';v1.mkdir(exist_ok=True)
for p in ['reports/manifest.pending.json','reports/package-complete.json','reports/technical-validation.json','samples/audit.json','reports/audit-plan.json']:
shutil.copy2(RUN/p,v1/Path(p).name)
m=j.loads((RUN/'reports/manifest.pending.json').read_bytes());source=RUN/'books.v1'
assert not source.exists()
(RUN/'books.ready').rename(source);(RUN/'books.ready').mkdir()
con=sqlite3.connect(RUN/'documents.sqlite')
writer=package.Writer();counts=collections.Counter();sources=collections.defaultdict(collections.Counter);lic=collections.Counter();why=collections.Counter()
previous=None;records=[];text=[]
def finish():
nonlocal records,text
if not records:return
meta=records[0]['meta'];doc=meta['document_id'];body=''.join(text)
assert hashlib.sha256(body.encode()).hexdigest()==meta['cleaned_text_sha256']
row=j.loads(con.execute('SELECT record FROM docs WHERE doc=?',(doc,)).fetchone()[0])
reasons=extra_gate.reasons(body,str(meta['title']),meta['source_repo'])
if reasons:
why.update(reasons);row['quarantine_reasons']+=reasons;row['disposition']='quarantined_second_gate'
ledger.write(j.dumps({'document_id':doc,'reasons':reasons,'record':row})+b'\n')
else:
counts['documents']+=1;counts['body_bytes']+=meta['cleaned_body_bytes']
sources[meta['source_repo']]['documents']+=1;sources[meta['source_repo']]['body_bytes']+=meta['cleaned_body_bytes']
for d in records:
mt=d['meta'];mt['quality_status']='strict_cleaned_rule_screened';mt['strict_selection_revision']=extra_gate.REVISION
raw=j.dumps(d)+b'\n';writer.add(raw,mt['token_count'])
counts['slices']+=1;counts['tokens']+=mt['token_count'];counts['text_bytes']+=len(d['text'].encode())
counts['max_tokens']=max(counts['max_tokens'],mt['token_count'])
sources[mt['source_repo']]['slices']+=1;sources[mt['source_repo']]['tokens']+=mt['token_count'];lic[mt['license']]+=1
row['disposition']='kept_candidate_v2'
con.execute('UPDATE docs SET record=? WHERE doc=?',(j.dumps(row),doc))
records=[];text=[]
with (RUN/'quarantine/second-gate.jsonl').open('wb') as ledger:
for i,f in enumerate(m['files']):
p=source/Path(f['path']).name;h=hashlib.sha256()
with p.open('rb') as inp:
for raw in inp:
h.update(raw);d=j.loads(raw);mt=d['meta'];doc=mt['document_id']
if previous is not None and previous!=doc:finish()
previous=doc;records.append(d);t=d['text'];text.append(t[mt['prefix_chars']:len(t)-mt['suffix_chars'] if mt['suffix_chars'] else len(t)])
assert h.hexdigest()==f['sha256']
if writer.f:writer.f.flush();os.fsync(writer.f.fileno())
con.commit();p.unlink()
if i%20==0:print('FILTERED',i,'keptdocs',counts['documents'],flush=True)
finish()
writer.close();con.commit()
m['second_gate']={'revision':extra_gate.REVISION,'previous_candidate_counts':m['counts'],'reason_counts':dict(why)}
m['counts']=dict(counts);m['source_counts']=dict(sources);m['license_inventory_training_slices']=dict(lic)
m['files']=writer.files;m['file_count']=len(writer.files);m['jsonl_bytes']=sum(f['bytes'] for f in writer.files)
with concurrent.futures.ProcessPoolExecutor(12) as pool:checks=list(pool.map(package.check,writer.files))
m['technical_validation']['independent_token_recounts']=sum(x['token_recounts'] for x in checks)
package.save(RUN/'reports/manifest.pending.json',m)
package.save(RUN/'reports/technical-validation.json',{'passed':True,'time':package.now(),'files':checks})
package.save(RUN/'reports/refilter-complete.json',{'complete':True,'time':package.now(),'counts':dict(counts),'reason_counts':dict(why),
'files':len(writer.files),'jsonl_bytes':m['jsonl_bytes']})
print('REFILTER COMPLETE',dict(counts),flush=True)
if __name__=='__main__':main()