File size: 4,899 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
from pathlib import Path
import sys,time
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,hashlib,collections,datetime,sqlite3,re
def now():return datetime.datetime.now(datetime.timezone.utc).isoformat()
def main():
 while not (RUN/'reports/final-filter-complete.json').exists():
  if 'Traceback' in (RUN/'logs/final-filter.log').read_text():raise RuntimeError('final filter failed')
  time.sleep(10)
 m=j.loads((RUN/'reports/manifest.pending.json').read_bytes())
 con=sqlite3.connect(f'file:{RUN/"documents.sqlite"}?mode=ro',uri=True)
 statuses=collections.Counter();kept={};activeq=0
 for doc,raw in con.execute('SELECT doc,record FROM docs'):
  d=j.loads(raw);statuses[d['disposition']]+=1
  if d['disposition']=='kept_strict_final':kept[doc]=d
  else:activeq+=1
 assert len(kept)+activeq==149159
 assert len(kept)==m['counts']['documents']
 seen=set();stats=collections.Counter();sources=collections.defaultdict(collections.Counter);boundaries=collections.Counter()
 current=None;parts=[];end=idx=0;h=None
 def finish():
  if current:
   body=''.join(parts);doc=current['document_id']
   assert end==current['cleaned_body_chars'] and len(body.encode())==current['cleaned_body_bytes']
   assert h.hexdigest()==current['cleaned_text_sha256']==kept[doc]['cleaned_text_sha256']
   assert '\ufffd' not in body and '\x00' not in body
   stats['documents']+=1;stats['body_bytes']+=len(body.encode());sources[current['source_repo']]['documents']+=1
 for f in m['files']:
  path=RUN/'books.ready'/Path(f['path']).name;fh=hashlib.sha256();n=tokens=0
  with path.open('rb') as inp:
   for raw in inp:
    fh.update(raw);row=j.loads(raw.decode('utf-8',errors='strict'));meta=row['meta'];doc=meta['document_id'];text=row['text']
    assert raw.endswith(b'\n') and set(row)=={'id','language','meta','text'} and row['language']=='en'
    assert doc in kept and meta['source_repo'] not in ['common-pile/doab_filtered','common-pile/library_of_congress_filtered','common-pile/pre_1929_books_filtered']
    if current is None or doc!=current['document_id']:
     finish();assert doc not in seen;seen.add(doc);current=meta;parts=[];end=idx=0;h=hashlib.sha256()
    assert meta['slice_index']==idx and meta['body_char_start']==end
    assert row['id']==f"books_en_{doc.removeprefix('books_')}_{idx:05d}"
    assert 0<meta['token_count']<=7680
    b=text[meta['prefix_chars']:len(text)-meta['suffix_chars'] if meta['suffix_chars'] else len(text)]
    assert len(b)==meta['body_char_end']-end
    h.update(b.encode());parts.append(b);end=meta['body_char_end'];idx+=1
    if end<current['cleaned_body_chars']:
     if b.endswith('\n\n'):boundaries['paragraph']+=1
     elif b.endswith('\n'):boundaries['line']+=1
     elif b[-1:].isspace():boundaries['whitespace']+=1
     else:boundaries['hard_character']+=1
    stats['slices']+=1;stats['tokens']+=meta['token_count'];stats['text_bytes']+=len(text.encode())
    sources[meta['source_repo']]['slices']+=1;sources[meta['source_repo']]['tokens']+=meta['token_count']
    n+=1;tokens+=meta['token_count']
  assert n==f['slices'] and tokens==f['tokens'] and path.stat().st_size==f['bytes'] and fh.hexdigest()==f['sha256']
 finish()
 assert set(kept)==seen
 for k in ['documents','slices','tokens','body_bytes','text_bytes']:assert stats[k]==m['counts'][k],(k,stats[k],m['counts'][k])
 assert not boundaries['hard_character']
 # Same-object held-out observations after global final gate.
 audit=j.loads((RUN/'samples/final-audit.json').read_bytes())
 decisions=[]
 for i,x in enumerate(audit['records']):
  d=j.loads(con.execute('SELECT record FROM docs WHERE doc=?',(x['document_id'],)).fetchone()[0])
  decisions.append({'sample_index':i,'document_id':x['document_id'],'title':x['title'],'repo':x['repo'],
                    'final_disposition':d['disposition'],'final_quarantine_reasons':d['quarantine_reasons']})
 # Long books reviewed as excerpts, not full content or third-party legal accuracy.
 out={'checked_at':now(),'passed':True,'counts':dict(stats),'source_counts':dict(sources),
      'boundaries':dict(boundaries),'active_dispositions':dict(statuses),
      'source_held_records':657150,'prior_records_reconciled':806309,
      'zero_U_FFFD_in_retained_body':True,'unique_ids_and_full_body_reconstruction':True,
      'all_file_hashes_verified':True,'same_final_holdout':decisions,
      'independent_overall_quality_acceptance_claimed':False,
      'scope':'All candidates technically checked; after failed holdout, global categories excluded; remaining same-object excerpts are not a fresh independent pass.'}
 (RUN/'reports/final-release-validation.json').write_bytes(j.dumps(out,option=j.OPT_INDENT_2))
 print(j.dumps({k:v for k,v in out.items() if k!='same_final_holdout'},option=j.OPT_INDENT_2).decode(),flush=True)
if __name__=='__main__':main()