Datasets:
Download code/scripts/minhon_verify_inspection.py from kuramot6f/classical-ja-pretrain: direct link, hf CLI and curl.
- Browser
- Download file 7.83 kB
-
https://huggingface.co/datasets/kuramot6f/classical-ja-pretrain/resolve/main/code/scripts/minhon_verify_inspection.py
- Command line
-
hf download hf://datasets/kuramot6f/classical-ja-pretrain/code/scripts/minhon_verify_inspection.py
-
curl -L -o minhon_verify_inspection.py https://huggingface.co/datasets/kuramot6f/classical-ja-pretrain/resolve/main/code/scripts/minhon_verify_inspection.py
7.83 kB
| #!/usr/bin/env python3 | |
| """Verify inspection counters, input hashes and all saved preview transformations.""" | |
| import argparse | |
| from collections import Counter | |
| import json | |
| from pathlib import Path | |
| from minhon_preprocess import Cleaner, sha256, candidate_pages | |
| def verify(folder): | |
| manifest = json.loads((folder / 'manifest.json').read_text()) | |
| report = json.loads((folder / 'report.json').read_text()) | |
| if manifest['state'] != 'complete': | |
| raise ValueError('Inspection not complete') | |
| for name, expected in manifest['input_hashes'].items(): | |
| if sha256((Path(manifest['audit']) / name).read_bytes()) != expected: | |
| raise ValueError('Audit input changed: ' + name) | |
| if sha256(Path(__file__).with_name('minhon_preprocess.py').read_bytes()) != manifest['script_sha256']: | |
| raise ValueError('Cleaner implementation changed since inspection') | |
| counts = report['counts'] | |
| if sum(counts.get(key, 0) for key in ('clean_pages', 'review_pages', 'empty_pages', 'read_errors')) != counts['candidate_pages']: | |
| raise ValueError('Page partition mismatch') | |
| if counts.get('raw_empty_pages', 0) + counts.get('removed_to_empty_pages', 0) != counts.get('empty_pages', 0): | |
| raise ValueError('Empty page partition mismatch') | |
| if sum(counts.get(key, 0) for key in ('clean_page_characters', 'review_page_characters', 'empty_page_characters')) != counts['clean_characters']: | |
| raise ValueError('Character partition mismatch') | |
| if manifest['rules'].get('missing_character_policy') == 'drop': | |
| if counts.get('missing_characters') != 0 or counts.get('raw_missing_characters') != counts.get('missing_characters_removed'): | |
| raise ValueError('Missing-character deletion mismatch') | |
| cleaner = Cleaner(manifest['rules']) | |
| verified = Counter() | |
| with (folder / 'preview.jsonl').open() as handle: | |
| for line in handle: | |
| record = json.loads(line) | |
| data = (Path(manifest['source_root']) / record['source_path']).read_bytes() | |
| if sha256(data) != record['source_sha256'] or data.decode('utf-8') != record['raw_text']: | |
| raise ValueError('Preview source changed: ' + record['id']) | |
| result = cleaner.clean(record['raw_text']) | |
| if result.text != record['text'] or result.edits != record['edits'] or result.issues != record['issues']: | |
| raise ValueError('Preview transformation mismatch: ' + record['id']) | |
| if sha256(result.text.encode('utf-8')) != record['clean_sha256']: | |
| raise ValueError('Preview output hash mismatch: ' + record['id']) | |
| # Independently replay every non-overlapping edit against original. | |
| cursor, chunks = 0, [] | |
| for edit in result.edits: | |
| if edit['start'] < cursor or record['raw_text'][edit['start']:edit['end']] != edit['before']: | |
| raise ValueError('Invalid edit range: ' + record['id']) | |
| chunks.extend([record['raw_text'][cursor:edit['start']], edit['after']]) | |
| cursor = edit['end'] | |
| chunks.append(record['raw_text'][cursor:]) | |
| if not result.normalization['changed'] and ''.join(chunks) != result.text: | |
| raise ValueError('Edit replay mismatch: ' + record['id']) | |
| verified['preview_pages'] += 1 | |
| with (folder / 'duplicates.jsonl').open() as handle: | |
| for line in handle: | |
| group = json.loads(line) | |
| if len(group['members']) < 2: | |
| raise ValueError('Singleton duplicate group') | |
| verified['duplicate_groups'] += 1 | |
| verified['duplicate_extra_pages'] += len(group['members']) - 1 | |
| if verified['preview_pages'] != counts['preview_pages']: | |
| raise ValueError('Preview count mismatch') | |
| if verified['duplicate_extra_pages'] != counts['exact_duplicate_extra_pages']: | |
| raise ValueError('Duplicate count mismatch') | |
| if verified['duplicate_groups'] != report['exact_duplicate_groups']: | |
| raise ValueError('Duplicate group count mismatch') | |
| checks = ['audit_input_hashes', 'cleaner_hash', 'page_partition', | |
| 'empty_page_partition', 'character_partition', | |
| 'preview_source_hashes', 'preview_reproduction', | |
| 'non_overlapping_edits', 'duplicate_counts'] | |
| if (folder / 'empty_pages.jsonl').exists(): | |
| empty_ids = set() | |
| with (folder / 'empty_pages.jsonl').open() as handle: | |
| for line in handle: | |
| record = json.loads(line) | |
| if record['status'] != 'empty' or record['id'] in empty_ids: | |
| raise ValueError('Invalid empty page record') | |
| empty_ids.add(record['id']) | |
| if len(empty_ids) != counts['empty_pages']: | |
| raise ValueError('Empty page listing count mismatch') | |
| verified['empty_pages'] = len(empty_ids) | |
| checks.append('empty_page_listing') | |
| if manifest['command'] == 'build': | |
| allowed = {meta['id'] for _, meta in candidate_pages(Path(manifest['audit']), Path(manifest['source_root']))} | |
| ids = set() | |
| with (folder / 'clean_pages.jsonl').open() as handle: | |
| for line in handle: | |
| record = json.loads(line) | |
| ident = record['id'] | |
| if ident not in allowed or ident in ids: | |
| raise ValueError('Unlisted or repeated output: ' + ident) | |
| ids.add(ident) | |
| if record['status'] != 'clean' or record['issues'] or not record['text'].strip(): | |
| raise ValueError('Unclean output: ' + ident) | |
| data = (Path(manifest['source_root']) / ident).read_bytes() | |
| if sha256(data) != record['source_sha256']: | |
| raise ValueError('Build source changed: ' + ident) | |
| result = cleaner.clean(data.decode('utf-8')) | |
| if result.issues or result.text != record['text']: | |
| raise ValueError('Build transformation mismatch: ' + ident) | |
| if record['clean_characters'] != len(record['text']) or sha256(record['text'].encode('utf-8')) != record['clean_sha256']: | |
| raise ValueError('Build text hash/length mismatch: ' + ident) | |
| if record['rules_version'] != manifest['rules']['version']: | |
| raise ValueError('Build rule version mismatch: ' + ident) | |
| verified['build_pages'] += 1 | |
| verified['build_characters'] += len(record['text']) | |
| if verified['build_pages'] % 25000 == 0: | |
| print(f"{verified['build_pages']:,} emitted pages verified", flush=True) | |
| if verified['build_pages'] != counts['clean_pages'] or verified['build_characters'] != counts['clean_page_characters']: | |
| raise ValueError('Build count mismatch') | |
| checks.extend(['build_allowlist', 'build_unique_ids', 'build_all_source_hashes', | |
| 'build_all_transformations', 'build_text_hashes', 'build_counts']) | |
| destination = folder / 'verification.json' | |
| if destination.exists(): | |
| raise FileExistsError(destination) | |
| payload = dict(status='passed', verified=dict(verified), | |
| checks=checks, | |
| scope=('All counters, saved previews, and every emitted clean page with its source.' | |
| if manifest['command'] == 'build' else | |
| 'All counters and saved previews; source hashes outside previews are not re-read.')) | |
| destination.write_text(json.dumps(payload, ensure_ascii=False, indent=2) + '\n') | |
| print(json.dumps(payload, ensure_ascii=False)) | |
| if __name__ == '__main__': | |
| parser = argparse.ArgumentParser(description=__doc__) | |
| parser.add_argument('inspection', type=Path) | |
| verify(parser.parse_args().inspection) | |