#!/usr/bin/env python3 """Clean an inventoried Kanripo snapshot without modifying raw files.""" import argparse from collections import Counter, defaultdict from contextlib import ExitStack import csv from datetime import datetime, timezone import hashlib import json from pathlib import Path import re from kanripo_profile import dump RULES = { 'dynasty': 'Exclude catalog dynasty 清/淸; unknown remains explicitly unknown', 'selection': 'Completed non-Qing catalog entries, inventoried KR_ID_digits[letter].txt only', 'management': 'Remove metadata/comment lines, pb/md/PB, pilcrow, fold/image tags, Org delimiters; keep link labels and heading text', 'body': 'Keep historical annotations, parentheses, slashes, missing characters, original glyphs and whitespace', 'unknown': 'Hold files with unresolved management syntax; never guess deletion ranges', 'unit': 'One source text file per record; no concatenation, deduplication, split or tokenize', } FLAGS = re.MULTILINE LINE = r'[^\r\n]*(?:\r?\n|$)' PATTERNS = [ ('metadata_lines', re.compile(r'^[ \t]*#+\+[A-Za-z][A-Za-z0-9_-]*' + LINE, FLAGS), ''), ('mode_lines', re.compile(r'^[ \t]*#+[ \t]*-\*-'+ LINE, FLAGS), ''), # A section title can be prefixed by an editorial Roman-numeral marker. ('roman_heading_prefix', re.compile(r'^[ \t]*#+[ \t]*[ivxlcdm]+#(?=<)', FLAGS | re.I), ''), ('comment_lines', re.compile(r'^[ \t]*#+[ \t]*[A-Za-z]' + LINE, FLAGS), ''), ('legacy_page_comments', re.compile(r'^[ \t]*%[ \t]*BR\d+(?:\.\d+)*[a-z]?[^\r\n]*(?:\r?\n|$)', FLAGS), ''), ('page_markers', re.compile(r'<(?:pb|md)(?::|[ \t]+)[^<>\r\n]*>', re.I), ''), ('fold_markers', re.compile(r'<折[ \t]+t="\d+"[ \t]*/>'), ''), ('image_markers', re.compile(r'\r\n]*>', re.I), ''), ('org_heading_prefix', re.compile(r'^\*+[ \t]+', FLAGS), ''), # Require a link type: [[...]] can also be nested character descriptions. ('org_labelled_links', re.compile(r'\[\[[A-Za-z][A-Za-z0-9_-]*:[^\[\]]{0,2000}\]\[([^\[\]]{0,2000})\]\]'), r'\1'), ('non_ascii_directive_prefix', re.compile(r'^[ \t]*#+\+(?=[\u3400-\u9fff])', FLAGS), ''), ('hash_heading_marks', re.compile(r'^[ \t]*#+|#+[ \t]*(?=\r?$)', FLAGS), ''), ('percent_page_prefix', re.compile(r'^[ \t]*%(?=¶?[ \t]*\r?$)', FLAGS), ''), ('pilcrow', re.compile('¶'), ''), ] RESIDUAL = re.compile(r'<(?:pb|md|img)(?=[:\s>])|<折\s|\[\[[A-Za-z][A-Za-z0-9_-]*:|^\s*#\+|^%[ \t]*BR\d', re.M | re.I) def sha(data): return hashlib.sha256(data).hexdigest() def clean(original): counts = Counter() text = original if text.startswith('\ufeff'): text = text[1:] counts['initial_bom'] = 1 for name, pattern, replacement in PATTERNS: text, n = pattern.subn(replacement, text) if n: counts[name] += n issues = [] for match in RESIDUAL.finditer(text): if len(issues) < 8: issues.append(text[max(0, match.start()-35):match.end()+100]) return text, counts, issues def load_inputs(root, audit): audit_manifest = json.loads((audit / 'manifest.json').read_text()) if not audit_manifest['complete']: raise ValueError('incomplete inventory') data = (root / 'metadata/manifest.csv').read_bytes() if sha(data) != audit_manifest['source_manifest_sha256']: raise ValueError('source manifest changed since inventory') rows = list(csv.DictReader(data.decode('utf-8-sig').splitlines())) catalog = {r['id']: r for r in rows} if len(catalog) != len(rows): raise ValueError('duplicate catalog IDs') inventory_data = (audit / 'files.jsonl').read_bytes() files = [json.loads(line) for line in inventory_data.decode('utf-8').splitlines()] if len(files) != len({r['raw_path'] for r in files}): raise ValueError('duplicate inventory paths') expected = {r['id'] for r in rows if r['status'] == 'complete' and r['dynasty'] not in {'清', '淸'}} report = json.loads((audit / 'report.json').read_text()) if not {r['id'] for r in files} <= expected or len(files) != report['totals']['body_files']: raise ValueError('inventory work coverage mismatch') return catalog, files, data, inventory_data def source_path(root, row): path = root / row['raw_path'] rid = row['id'] if (not re.fullmatch(r'KR[1-6][a-z]\d{4}', rid) or not re.fullmatch(re.escape(rid) + r'_\d+[a-z]?\.txt', path.name) or path.parent != root / 'raw' / rid or path.is_symlink() or path.parent.is_symlink() or not path.resolve().is_relative_to(root / 'raw')): raise ValueError(f'unsafe source path: {path}') return path def build(root, audit, output): root, audit, output = root.resolve(), audit.resolve(), output.resolve() catalog, files, metadata, inventory = load_inputs(root, audit) if root.is_relative_to(output) or output.is_relative_to(root / 'raw') or output == audit: raise ValueError('unsafe output directory') output.mkdir(parents=True, exist_ok=False) manifest = {'complete': False, 'started': datetime.now(timezone.utc).isoformat(), 'root': str(root), 'audit': str(audit), 'rules': RULES, 'source_manifest_sha256': sha(metadata), 'inventory_sha256': sha(inventory), 'script_sha256': sha(Path(__file__).read_bytes())} dump(output / 'manifest.json', manifest) totals, removed, dynasties = Counter(), Counter(), Counter() exact = defaultdict(list) selected_works, review_works = set(), set() sample_counts = Counter() with ExitStack() as stack: out = {name: stack.enter_context((output / (name + '.jsonl')).open('w', encoding='utf-8')) for name in ['documents', 'excluded', 'edits', 'review', 'preview', 'files']} def emit(name, obj): out[name].write(json.dumps(obj, ensure_ascii=False) + '\n') body_works = {entry['id'] for entry in files} 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: emit('excluded', dict(id=row['id'], dynasty=row['dynasty'], label=row['label'], reasons=reasons)) totals['excluded_catalog_works'] += 1 for i, entry in enumerate(files): rid = entry['id'] row = catalog[rid] if row['status'] != 'complete' or row['dynasty'] in {'清', '淸'}: raise ValueError(f'ineligible inventory entry: {rid}') data = source_path(root, entry).read_bytes() if sha(data) != entry['raw_sha256']: raise ValueError(f'raw input changed: {entry["raw_path"]}') original = data.decode('utf-8') text, counts, issues = clean(original) totals['input_files'] += 1 totals['original_chars'] += len(original) removed.update(counts) file_id = 'kanripo/' + rid + '/' + Path(entry['raw_path']).name base = dict(id=file_id, source='kanripo', work_id=rid, label=row['label'], dynasty=row['dynasty'], dynasty_raw=row['dynasty_raw'], classification_source=row['classification_source'], raw_path=entry['raw_path'], raw_sha256=entry['raw_sha256']) audit_row = dict(base, original_chars=len(original), clean_chars=len(text), removed=counts, clean_sha256=sha(text.encode('utf-8'))) if issues: status = 'review' emit('review', dict(audit_row, issues=issues)) review_works.add(rid) elif not text.strip(): status = 'empty' else: status = 'included' header = re.findall(r'^#+\+([^\r\n]+)', original, re.M) emit('documents', dict(base, text=text, clean_sha256=audit_row['clean_sha256'], chars=len(text), original_header=header)) exact[audit_row['clean_sha256']].append(file_id) selected_works.add(rid) totals['clean_chars'] += len(text) dynasties[row['dynasty']] += len(text) audit_row['status'] = status emit('files', audit_row) totals[status + '_files'] += 1 if counts: emit('edits', audit_row) for feature in counts: if sample_counts[feature] < 2: emit('preview', dict(id=file_id, feature=feature, before=original[:2500], after=text[:2500])) sample_counts[feature] += 1 if (i+1) % 10000 == 0: print(f'processed {i+1}/{len(files)}', flush=True) duplicates = [dict(sha256=key, ids=ids) for key, ids in exact.items() if len(ids) > 1] with (output / 'duplicates.jsonl').open('w', encoding='utf-8') as f: for group in duplicates: f.write(json.dumps(group, ensure_ascii=False) + '\n') totals['included_works'] = len(selected_works) totals['review_works'] = len(review_works) totals['duplicate_groups'] = len(duplicates) if sha((root / 'metadata/manifest.csv').read_bytes()) != sha(metadata): raise ValueError('source manifest changed during build') dump(output / 'report.json', dict(totals=totals, removed=removed, chars_by_dynasty=dynasties)) manifest.update(complete=True, finished=datetime.now(timezone.utc).isoformat(), output_hashes={p.name: sha(p.read_bytes()) for p in output.glob('*.jsonl') if p.name != 'documents.jsonl'}) dump(output / 'manifest.json', manifest) print(json.dumps(totals, ensure_ascii=False), flush=True) if __name__ == '__main__': p = argparse.ArgumentParser(description=__doc__) p.add_argument('--root', type=Path, default=Path('kanripo')) p.add_argument('--audit', type=Path, default=Path('kanripo/preprocessed-v1/inspection-002')) p.add_argument('--output', type=Path, required=True) a = p.parse_args() build(a.root, a.audit, a.output)