classical-ja-pretrain / code /scripts /kanripo_verify_clean.py
kuramot6f's picture
Initial release (history squashed)
7a088d4
Raw History Blame Contribute Delete
6.88 kB
#!/usr/bin/env python3
"""Re-read every serialized Kanripo record and verify it against raw sources."""
import argparse
from collections import Counter, defaultdict
import hashlib
import json
from pathlib import Path
from kanripo_clean import RULES, RESIDUAL, clean, load_inputs, sha, source_path
from kanripo_profile import dump
def records(path):
with path.open(encoding='utf-8') as f:
for line in f:
yield json.loads(line)
def file_hash(path):
h = hashlib.sha256()
with path.open('rb') as f:
for block in iter(lambda: f.read(1024*1024), b''):
h.update(block)
return h.hexdigest()
def check(condition, message):
if not condition:
raise ValueError(message)
def verify(output):
output = output.resolve()
manifest = json.loads((output / 'manifest.json').read_text())
check(manifest['complete'], 'incomplete build')
check(manifest['rules'] == RULES, 'rules changed')
check(manifest['script_sha256'] == file_hash(Path(__file__).with_name('kanripo_clean.py')), 'implementation changed')
root, audit = Path(manifest['root']), Path(manifest['audit'])
catalog, inventory, metadata, inventory_data = load_inputs(root, audit)
check(sha(metadata) == manifest['source_manifest_sha256'], 'metadata mismatch')
check(sha(inventory_data) == manifest['inventory_sha256'], 'inventory changed')
for name, digest in manifest['output_hashes'].items():
check(file_hash(output / name) == digest, f'output changed: {name}')
file_rows = list(records(output / 'files.jsonl'))
check(len(file_rows) == len(inventory), 'file coverage mismatch')
docs = iter(records(output / 'documents.jsonl'))
review = {r['id']: r for r in records(output / 'review.jsonl')}
edits = {r['id']: r for r in records(output / 'edits.jsonl')}
totals, removed, dynasties = Counter(), Counter(), Counter()
exact = defaultdict(list)
works, review_works = set(), set()
for i, (entry, f) in enumerate(zip(inventory, file_rows)):
rid = entry['id']
check(f['raw_path'] == entry['raw_path'], 'file order/coverage mismatch')
row = catalog[rid]
check(row['status'] == 'complete' and row['dynasty'] not in {'清', '淸'}, 'ineligible work')
raw = source_path(root, entry).read_bytes()
check(sha(raw) == entry['raw_sha256'] == f['raw_sha256'], 'raw hash mismatch')
original = raw.decode('utf-8')
text, counts, issues = clean(original)
digest = sha(text.encode('utf-8'))
expected_status = 'review' if issues else ('included' if text.strip() else 'empty')
check(f['status'] == expected_status, 'status mismatch')
check(f['original_chars'] == len(original) and f['clean_chars'] == len(text), 'length mismatch')
check(f['removed'] == counts and f['clean_sha256'] == digest, 'edit audit mismatch')
check((f['id'] in edits) == bool(counts), 'edit coverage mismatch')
if counts:
check(edits[f['id']] == f, 'edit record mismatch')
totals['input_files'] += 1
totals['original_chars'] += len(original)
totals[expected_status + '_files'] += 1
removed.update(counts)
if issues:
check(f['id'] in review and review[f['id']]['issues'] == issues, 'review mismatch')
review_works.add(rid)
elif expected_status == 'included':
doc = next(docs, None)
check(doc is not None and doc['id'] == f['id'], 'document order/coverage mismatch')
check(doc['text'] == text and doc['chars'] == len(text) and doc['clean_sha256'] == digest, 'serialized text mismatch')
for key in ['raw_path', 'raw_sha256', 'dynasty', 'label', 'source', 'work_id', 'classification_source', 'dynasty_raw']:
check(doc[key] == f[key], 'document provenance mismatch')
check(not RESIDUAL.search(doc['text']) and '¶' not in doc['text'], 'management syntax survived')
exact[digest].append(doc['id'])
works.add(rid)
totals['clean_chars'] += len(text)
dynasties[row['dynasty']] += len(text)
if (i+1) % 10000 == 0:
print(f'verified {i+1}/{len(inventory)}', flush=True)
check(next(docs, None) is None, 'extra documents')
check(set(review) == {r['id'] for r in file_rows if r['status'] == 'review'}, 'review coverage')
check(set(edits) == {r['id'] for r in file_rows if r['removed']}, 'edits coverage')
body_works = {r['id'] for r in inventory}
expected_excluded = {}
for row in catalog.values():
reasons = []
if row['dynasty'] in {'清', '淸'}:
reasons.append('qing_user_excluded')
totals['qing_catalog_works'] += 1
if row['status'] == 'complete':
totals['qing_complete_works'] += 1
if row['status'] != 'complete':
reasons.append('download_not_complete')
totals['incomplete_catalog_works'] += 1
elif row['dynasty'] not in {'清', '淸'} and row['id'] not in body_works:
reasons.append('no_body_files')
totals['no_body_works'] += 1
if reasons:
expected_excluded[row['id']] = reasons
exclusions = list(records(output / 'excluded.jsonl'))
check(len(exclusions) == len(expected_excluded), 'exclusion coverage')
check({r['id']: r['reasons'] for r in exclusions} == expected_excluded, 'exclusion reasons')
totals['excluded_catalog_works'] = len(exclusions)
expected_duplicates = [dict(sha256=h, ids=ids) for h, ids in exact.items() if len(ids) > 1]
check(list(records(output / 'duplicates.jsonl')) == expected_duplicates, 'duplicate group mismatch')
totals.update(included_works=len(works), review_works=len(review_works), duplicate_groups=len(expected_duplicates))
report = json.loads((output / 'report.json').read_text())
check(totals == Counter(report['totals']), 'total mismatch')
check(removed == Counter(report['removed']), 'removal count mismatch')
check(dynasties == Counter(report['chars_by_dynasty']), 'dynasty character counts mismatch')
result = dict(verified=True, verified_files=len(inventory), included_files=totals['included_files'],
clean_chars=totals['clean_chars'], documents_sha256=file_hash(output / 'documents.jsonl'),
checks=['raw hashes', 'full serialized text and provenance', 'Qing exclusion and file coverage',
'management marker absence', 'review and empty statuses', 'totals and duplicates'])
dump(output / 'verification.json', result)
print(json.dumps(result, ensure_ascii=False), flush=True)
return result
if __name__ == '__main__':
p = argparse.ArgumentParser(description=__doc__)
p.add_argument('output', type=Path)
a = p.parse_args()
verify(a.output)