#!/usr/bin/env python3 """Read-only inventory of completed Kanripo snapshots, excluding Qing.""" import argparse from collections import Counter, defaultdict import csv import hashlib import json from pathlib import Path import re def dump(path, data): path.write_text(json.dumps(data, ensure_ascii=False, indent=2) + '\n', encoding='utf-8') def profile(root, output): root, output = Path(root).resolve(), Path(output).resolve() output.mkdir(parents=True, exist_ok=False) manifest_bytes = (root / 'metadata/manifest.csv').read_bytes() rows = list(csv.DictReader(manifest_bytes.decode('utf-8-sig').splitlines())) totals, extensions, features, periods = Counter(), Counter(), Counter(), Counter() examples = defaultdict(list) with (output / 'files.jsonl').open('w', encoding='utf-8') as inventory, \ (output / 'excluded.jsonl').open('w', encoding='utf-8') as excluded: for row in rows: rid = row['id'] if not re.fullmatch(r'KR[1-6][a-z]\d{4}', rid): raise ValueError(f'invalid ID: {rid}') reasons = [] if row['dynasty'] in {'清', '淸'}: reasons.append('qing_user_excluded') if row['status'] != 'complete': reasons.append('download_not_complete') if reasons: excluded.write(json.dumps(dict(row, reasons=reasons), ensure_ascii=False) + '\n') totals.update(reasons) continue totals['eligible_works'] += 1 periods[row['dynasty']] += 1 source = root / 'raw' / rid if not source.is_dir() or source.is_symlink(): raise ValueError(f'missing or linked work directory: {rid}') for path in sorted(source.rglob('*')): if path.is_symlink(): raise ValueError(f'unexpected symlink: {path}') if not path.is_file(): continue extensions[path.suffix] += 1 if not re.fullmatch(re.escape(rid) + r'_\d+[a-z]?\.txt', path.name): totals['non_body_files'] += 1 continue data = path.read_bytes() text = data.decode('utf-8-sig') rel = str(path.relative_to(root)) entry = {'id': rid, 'raw_path': rel, 'raw_sha256': hashlib.sha256(data).hexdigest(), 'bytes': len(data), 'chars': len(text), 'dynasty': row['dynasty']} inventory.write(json.dumps(entry, ensure_ascii=False) + '\n') totals['body_files'] += 1 totals['body_chars'] += len(text) found = Counter() for match in re.finditer(r'<[^<>\n]{1,200}>', text): tag = match.group() kind = 'tag:' + re.split(r'[:\s>]', tag[1:], maxsplit=1)[0] found[kind] += 1 if len(examples[kind]) < 8: examples[kind].append({'path': rel, 'text': tag}) for line in text.splitlines(): if re.match(r'^\s*(?:#|\*+\s|:|\[\[|\||\[fn:)', line): key = ('hash:' + line.strip().split(' ', 1)[0]) if line.lstrip().startswith('#') else 'structural_line' found[key] += 1 if len(examples[key]) < 8: examples[key].append({'path': rel, 'text': line[:350]}) for symbol in ['¶', '\u3000', '\ufffd', '□', '〓', '[[', ']]', '[fn:', '\t', '\x00']: if symbol in text: found['symbol:' + symbol] = text.count(symbol) features.update(found) dump(output / 'report.json', {'totals': totals, 'extensions': extensions, 'eligible_dynasties': periods, 'features': features, 'examples': examples}) dump(output / 'manifest.json', {'complete': True, 'root': str(root), 'source_manifest_sha256': hashlib.sha256(manifest_bytes).hexdigest(), 'script_sha256': hashlib.sha256(Path(__file__).read_bytes()).hexdigest(), 'body_selection': 'complete non-Qing catalog entries; KR_ID_digits[letter].txt only', 'scope': 'Read-only inventory; no raw changes or training output'}) print(json.dumps(totals, ensure_ascii=False), flush=True) if __name__ == '__main__': parser = argparse.ArgumentParser(description=__doc__) parser.add_argument('--root', type=Path, default=Path('kanripo')) parser.add_argument('--output', type=Path, required=True) args = parser.parse_args() profile(args.root, args.output)