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
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
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
#!/usr/bin/env python3
"""Inspect and preview minhon retain_candidate pages without changing sources.

All edit offsets are Unicode character offsets in the decoded original text
(before line-ending/whitespace normalization), not UTF-8 byte offsets.
"""
from __future__ import annotations

import argparse
from collections import Counter, defaultdict
import csv
from dataclasses import dataclass, field
from datetime import datetime, timezone
import hashlib
import json
from pathlib import Path
import re
import sys

ROOT = Path(__file__).resolve().parents[1]
DEFAULT_RULES = Path(__file__).with_name('minhon_preprocess_rules.json')
KANA = re.compile(r'[ぁ-ゖァ-ヺーゝゞヽヾ々〱〲〳〴〵\s・・]+\Z')
BASE_CHAR = re.compile(r'[\u3400-\u9fff\uf900-\ufaff\U00020000-\U000323afぁ-ゖァ-ヺ々〻〆〇〱〲〳〴〵\ufe00-\ufe0f\U000e0100-\U000e01ef]')
TAG_HEAD = re.compile(r'([^::\n《》]{1,40})[::]')
RETURN_MARK = re.compile(r'_[レ一二三上中下甲乙丙]+')
OKURI_MARK = re.compile(r' ̄([ァ-ヺー]+)')


def sha256(data: bytes) -> str:
    return hashlib.sha256(data).hexdigest()


def dump_line(handle, value):
    handle.write(json.dumps(value, ensure_ascii=False) + '\n')


@dataclass
class Result:
    text: str
    edits: list = field(default_factory=list)
    issues: list = field(default_factory=list)
    features: Counter = field(default_factory=Counter)
    normalization: dict = field(default_factory=dict)


class Cleaner:
    def __init__(self, rules):
        self.rules = rules
        self.admin_patterns = [re.compile(p) for p in rules['admin_line_patterns']]
        self.opens = {'《': '》', '(': ')', '(': ')', **rules['editorial_brackets'],
                      **rules.get('legacy_editorial_brackets', {})}
        self.closes = set(self.opens.values())

    def clean(self, original: str) -> Result:
        result = Result('')

        def issue(kind, start, end, **extra):
            result.issues.append(dict(kind=kind, start=start, end=end, **extra))
            result.features[kind] += 1

        def edit(kind, start, end, replacement):
            result.edits.append(dict(kind=kind, start=start, end=end,
                                     before=original[start:end], after=replacement))
            result.features[kind] += 1

        def matching(start, limit):
            opening = original[start]
            aggressive_round = opening in '((' and self.rules.get('round_brackets_policy') == 'drop_all'
            aggressive_note = (opening in self.rules['editorial_brackets'] or
                               opening in self.rules.get('legacy_editorial_brackets', {})) and self.rules.get('legacy_editorial_policy') == 'drop'
            if aggressive_round or aggressive_note:
                # Annotation contents may themselves contain broken markup.
                # Balance only the delimiter family that will be discarded.
                starts = '((' if aggressive_round else opening
                ends = '))' if aggressive_round else self.opens[opening]
                level = 1
                for pos in range(start + 1, limit):
                    if original[pos] in starts:
                        level += 1
                    elif original[pos] in ends:
                        level -= 1
                        if level == 0:
                            return pos
                return None
            stack = [original[start]]
            for pos in range(start + 1, limit):
                char = original[pos]
                if char in self.opens:
                    stack.append(char)
                    if len(stack) > 64:
                        return None
                elif char in self.closes:
                    if not stack:
                        return None
                    expected = self.opens[stack[-1]]
                    if char != expected and not (stack[-1] in '((' and char in '))'):
                        return None
                    stack.pop()
                    if not stack:
                        return pos
            return None

        def split_parts(start, end):
            parts, current = [], start
            pos = start
            while pos < end:
                if original[pos] in self.opens:
                    close = matching(pos, end)
                    if close is None:
                        return None
                    pos = close + 1
                    continue
                if original[pos] in '||':
                    parts.append((current, pos))
                    current = pos + 1
                pos += 1
            parts.append((current, end))
            return parts

        def ruby_at(pos, limit):
            close = matching(pos, limit)
            if close is None:
                return None
            content = original[pos + 1:close]
            if content.strip() and KANA.fullmatch(content):
                return close
            return None

        def parse(start, end, depth=0):
            if depth > 64:
                issue('nesting_limit', start, end)
                return original[start:end]
            out, pos = [], start
            while pos < end:
                char = original[pos]
                if char in self.opens:
                    close = matching(pos, end)
                    if close is None:
                        # Preserve the entire remainder: never reinterpret nested
                        # spans inside a broken outer annotation as ordinary text.
                        issue('unclosed_or_mismatched_bracket', pos, end)
                        out.append(original[pos:end])
                        break
                    stop = close + 1
                    if char in self.rules['editorial_brackets']:
                        edit('editorial_note', pos, stop, '')
                    elif char in self.rules.get('legacy_editorial_brackets', {}):
                        edit('legacy_editorial_note', pos, stop, '')
                        if self.rules.get('legacy_editorial_policy', 'review') != 'drop':
                            issue('legacy_note_requires_review', pos, stop)
                    elif char in '((':
                        if self.rules.get('round_brackets_policy') == 'drop_all':
                            edit('round_bracket_contents', pos, stop, '')
                            if self.opens[char] != original[close]:
                                result.features['mixed_round_brackets'] += 1
                        elif pos > 0 and BASE_CHAR.fullmatch(original[pos-1]) and ruby_at(pos, end) == close:
                            edit('parenthetical_ruby', pos, stop, '')
                            if self.opens[char] != original[close]:
                                result.features['mixed_round_brackets'] += 1
                        else:
                            out.append(original[pos:stop])
                            issue('non_ruby_parentheses', pos, stop)
                    else:
                        header = TAG_HEAD.match(original, pos + 1, close)
                        name = header[1].strip() if header else ''
                        action = self.rules['tags'].get(name)
                        parts = ([(header.end(), close)] if action in ('unwrap', 'drop')
                                 else split_parts(header.end(), close)) if header else None
                        valid = parts is not None
                        if action == 'ruby':
                            valid = valid and len(parts) in (2, 3)
                        elif action in ('first', 'correction'):
                            valid = valid and len(parts) == 2
                        elif action in ('unwrap', 'drop'):
                            valid = valid and len(parts) == 1
                        elif action == 'join':
                            valid = valid and len(parts) >= 1
                        else:
                            valid = False
                        if not valid:
                            out.append(original[pos:stop])
                            issue('unknown_or_invalid_tag', pos, stop, tag=name)
                        else:
                            # Nested changes are summarized by the outer edit;
                            # features still record the nested notation types.
                            saved = len(result.edits)
                            selected = ([] if action == 'drop' else parts if action in ('join', 'unwrap')
                                        else [parts[-1] if action == 'correction' else parts[0]])
                            replacement = ''.join(parse(a, b, depth + 1) for a, b in selected)
                            del result.edits[saved:]
                            out.append(replacement)
                            edit('tag:' + name, pos, stop, replacement)
                    pos = stop
                    continue
                # Ruby-base delimiters are removed only when a ruby actually follows.
                if char in '||/':
                    candidate = pos + 1
                    while candidate < end and BASE_CHAR.fullmatch(original[candidate]):
                        candidate += 1
                    bracket_end = (matching(candidate, end) if self.rules.get('round_brackets_policy') == 'drop_all'
                                   else ruby_at(candidate, end)) if candidate < end and original[candidate] in '((' else None
                    if candidate > pos + 1 and bracket_end is not None:
                        edit('ruby_base_marker', pos, pos + 1, '')
                        pos += 1
                        continue
                    issue('unresolved_separator', pos, pos + 1)
                match = RETURN_MARK.match(original, pos, end)
                if match:
                    edit('return_mark', pos, match.end(), '')
                    pos = match.end()
                    continue
                match = OKURI_MARK.match(original, pos, end)
                if match:
                    out.append(match[1])
                    edit('okurigana_marker', pos, match.end(), match[1])
                    pos = match.end()
                    continue
                if char in self.closes:
                    issue('unmatched_closing_bracket', pos, pos + 1)
                elif char in '_ ̄':
                    issue('unresolved_kanbun_marker', pos, pos + 1)
                out.append(char)
                pos += 1
            return ''.join(out)

        # Administrative removal is intentionally limited to explicit whole lines.
        # The era-audit offsets are NFKC offsets and cannot be applied to this source.
        pieces, cursor = [], 0
        for match in re.finditer(r'[^\r\n]+', original):
            if any(pattern.fullmatch(match[0]) for pattern in self.admin_patterns):
                pieces.append(parse(cursor, match.start()))
                edit('administrative_line', match.start(), match.end(), '')
                cursor = match.end()
        pieces.append(parse(cursor, len(original)))
        text = ''.join(pieces)
        before_normalization = text
        missing_removed_in_normalization = 0
        if self.rules.get('missing_character_policy') == 'drop':
            missing_removed_in_normalization = text.count('□')
            text = text.replace('□', '')
            if original.count('□'):
                # Includes squares already removed inside annotations as well.
                result.features['missing_characters_removed'] += original.count('□')
        text = text.removeprefix('\ufeff').replace('\r\n', '\n').replace('\r', '\n')
        controls = re.findall(r'[\x00-\x08\x0b\x0c\x0e-\x1f\x7f]', text)
        text = re.sub(r'[\x00-\x08\x0b\x0c\x0e-\x1f\x7f]', '', text)
        # Spaces can represent deliberate omissions (闕字); line breaks and
        # indentation reflect the source. Do not trim or collapse this layout.
        # Entirely whitespace-only pages have no model text, and are counted.
        if not text.strip():
            text = ''
        result.text = text
        result.normalization = dict(changed=text != before_normalization,
                                    chars_before=len(before_normalization), chars_after=len(text),
                                    control_characters_removed=len(controls),
                                    missing_characters_removed=missing_removed_in_normalization)
        if controls:
            result.features['control_characters'] += len(controls)
        raw_len = len(re.sub(r'\s', '', original))
        clean_len = len(re.sub(r'\s', '', text))
        if raw_len >= self.rules['min_chars_for_removal_review'] and 1 - clean_len / raw_len > self.rules['max_removal_ratio']:
            issue('high_removal_ratio', 0, len(original))
        missing = text.count('□')
        if missing:
            result.features['missing_characters'] += missing
        if missing >= self.rules['min_missing_for_review'] and missing / max(1, clean_len) > self.rules['max_missing_ratio']:
            issue('high_missing_ratio', 0, len(original))
        if not text.strip():
            result.features['empty_after_cleaning'] += 1
        result.edits.sort(key=lambda item: item['start'])
        return result


def candidate_pages(audit: Path, source_root: Path):
    """CSV allowlist only; never walk view symlinks or translations."""
    documents = {}
    with (audit / 'documents.csv').open(encoding='utf-8-sig', newline='') as handle:
        for row in csv.DictReader(handle):
            if row['decision'] != 'retain_candidate':
                continue
            key = '/'.join(filter(None, (row['version'], row['project'], row['id'])))
            documents[key] = row
    seen = set()
    with (audit / 'pages.csv').open(encoding='utf-8-sig', newline='') as handle:
        for row in csv.DictReader(handle):
            if row['document_decision'] != 'retain_candidate':
                continue
            # The audit contains absolute source paths. Map their logical v1/v3
            # suffix into the selected source root so the dataset is portable.
            parts = Path(row['source_path']).parts
            indexes = [i for i, part in enumerate(parts) if part == 'honkoku-data']
            if not indexes:
                raise ValueError('source_path lacks honkoku-data: ' + row['source_path'])
            rel = Path(*parts[indexes[-1] + 1:])
            if '..' in rel.parts or 'translations' in rel.parts or rel.suffix != '.txt':
                raise ValueError('unsafe or non-body path: ' + str(rel))
            doc_parts = 2 if rel.parts[0] == 'v1' else 3 if rel.parts[0] == 'v3' else 0
            if not doc_parts or len(rel.parts) <= doc_parts:
                raise ValueError('invalid page path: ' + str(rel))
            doc_key = Path(*rel.parts[:doc_parts]).as_posix()
            if doc_key not in documents:
                raise ValueError('page missing retained document: ' + str(rel))
            if rel.as_posix() in seen:
                raise ValueError('repeated source page: ' + str(rel))
            seen.add(rel.as_posix())
            path = source_root / rel
            path.resolve().relative_to(source_root.resolve())
            doc = documents[doc_key]
            yield path, dict(id=rel.as_posix(), document_id=doc_key,
                             source_path=rel.as_posix(), page=rel.relative_to(Path(doc_key)).as_posix(),
                             version=doc['version'], project=doc['project'], title=doc['title'],
                             era_bucket=doc['era_bucket'])


def scan(args):
    rule_bytes = args.rules.read_bytes()
    rules = json.loads(rule_bytes)
    cleaner = Cleaner(rules)
    # Refuse output directories that exist: a partial/older run is never overwritten.
    args.output.mkdir(parents=True, exist_ok=False)
    manifest = dict(command=args.command, state='running',
                    created_at=datetime.now(timezone.utc).isoformat(),
                    rules=rules, rules_sha256=sha256(rule_bytes),
                    script_sha256=sha256(Path(__file__).read_bytes()),
                    audit=str(args.audit.resolve()), source_root=str(args.source_root.resolve()),
                    input_hashes={name: sha256((args.audit / name).read_bytes()) for name in ('documents.csv', 'pages.csv')},
                    limit=args.limit, offset_unit='decoded_original_unicode_characters',
                    notes=['No training, split, tokenization or corpus merging.',
                           'Candidate status is not proof of original date.',
                           'Duplicates are reported, not removed.',
                           'Only build emits clean_pages.jsonl; inspect/sample emit reports and previews.',
                           'No document concatenation until page ordering and gaps are verified.'])
    manifest_path = args.output / 'manifest.json'
    manifest_path.write_text(json.dumps(manifest, ensure_ascii=False, indent=2) + '\n')
    counts, feature_pages, feature_hits = Counter(), Counter(), Counter()
    projects = defaultdict(Counter)
    tags = Counter()
    samples = Counter()
    docs, nonempty_docs, clean_docs = set(), set(), set()
    hashes, duplicate_groups = {}, {}
    preview_ids = set()
    max_chars = 0
    with (args.output / 'preview.jsonl').open('w') as previews, (args.output / 'review.jsonl').open('w') as reviews, (args.output / 'edits.jsonl').open('w') as edits, (args.output / 'empty_pages.jsonl').open('w') as empty_pages:
        clean_handle = (args.output / 'clean_pages.jsonl').open('w') if args.command == 'build' else None
        try:
            for index, (path, meta) in enumerate(candidate_pages(args.audit, args.source_root), 1):
                if args.limit and index > args.limit:
                    break
                counts['candidate_pages'] += 1
                docs.add(meta['document_id'])
                project = meta['version'] + '/' + meta['project']
                projects[project]['pages'] += 1
                try:
                    data = path.read_bytes()
                    raw = data.decode('utf-8')
                except (OSError, UnicodeError) as error:
                    counts['read_errors'] += 1
                    dump_line(reviews, dict(**meta, status='error', error=str(error)))
                    continue
                result = cleaner.clean(raw)
                status = 'empty' if not result.text.strip() else 'review' if result.issues else 'clean'
                counts[status + '_pages'] += 1
                counts['raw_characters'] += len(raw)
                if not raw.removeprefix('\ufeff').strip():
                    counts['raw_empty_pages'] += 1
                elif status == 'empty':
                    counts['removed_to_empty_pages'] += 1
                counts['clean_characters'] += len(result.text)
                counts[status + '_page_characters'] += len(result.text)
                if status != 'empty':
                    nonempty_docs.add(meta['document_id'])
                if status == 'clean':
                    clean_docs.add(meta['document_id'])
                counts['non_whitespace_clean_characters'] += len(re.sub(r'\s', '', result.text))
                counts['clean_bytes'] += len(result.text.encode('utf-8'))
                counts['edits'] += len(result.edits)
                counts['missing_characters'] += result.text.count('□')
                counts['raw_missing_characters'] += raw.count('□')
                counts['missing_characters_removed'] += raw.count('□') - result.text.count('□')
                projects[project]['raw_characters'] += len(raw)
                projects[project]['clean_characters'] += len(result.text)
                projects[project][status + '_pages'] += 1
                max_chars = max(max_chars, len(result.text))
                feature_hits.update(result.features)
                feature_pages.update(result.features.keys())
                for match in re.finditer(r'《([^::\n《》]{1,40})[::]', raw):
                    tags[match[1]] += 1
                record = dict(**meta, source_sha256=sha256(data),
                              clean_sha256=sha256(result.text.encode('utf-8')),
                              rules_version=rules['version'], status=status,
                              text=result.text, raw_characters=len(raw), clean_characters=len(result.text),
                              features=dict(result.features), issues=result.issues,
                              normalization=result.normalization)
                if status != 'empty':
                    digest = record['clean_sha256']
                    member = dict(id=meta['id'], document_id=meta['document_id'], status=status)
                    if digest in hashes:
                        duplicate_groups.setdefault(digest, [hashes[digest]]).append(member)
                        counts['exact_duplicate_extra_pages'] += 1
                    else:
                        hashes[digest] = member
                if result.issues:
                    dump_line(reviews, {k: v for k, v in record.items() if k != 'text'})
                if status == 'empty':
                    dump_line(empty_pages, {k: v for k, v in record.items() if k != 'text'})
                if result.edits or result.normalization['changed']:
                    dump_line(edits, dict(id=meta['id'], source_sha256=record['source_sha256'],
                                         edits=result.edits, normalization=result.normalization))
                reasons = [feature for feature in sorted(result.features) if samples[feature] < rules['sample_per_feature']]
                if reasons or index <= 8:
                    if meta['id'] not in preview_ids:
                        dump_line(previews, dict(**record, raw_text=raw, sample_reasons=reasons,
                                                edits=result.edits))
                        preview_ids.add(meta['id'])
                        counts['preview_pages'] += 1
                    samples.update(reasons)
                if clean_handle and status == 'clean':
                    dump_line(clean_handle, record)
                if index % 25000 == 0:
                    print(f'{index:,} pages inspected', file=sys.stderr, flush=True)
        finally:
            if clean_handle:
                clean_handle.close()
    with (args.output / 'duplicates.jsonl').open('w') as handle:
        for digest, members in sorted(duplicate_groups.items()):
            dump_line(handle, dict(clean_sha256=digest, members=members,
                                   cross_document=len({m['document_id'] for m in members}) > 1))
    report = dict(counts=dict(counts), documents=len(docs),
                  documents_with_nonempty_pages=len(nonempty_docs),
                  documents_with_clean_pages=len(clean_docs),
                  documents_without_nonempty_pages=len(docs - nonempty_docs),
                  max_clean_page_characters=max_chars,
                  exact_duplicate_groups=len(duplicate_groups),
                  feature_page_counts=dict(feature_pages.most_common()),
                  feature_occurrences=dict(feature_hits.most_common()),
                  tag_occurrences=dict(tags.most_common()),
                  projects={key: dict(value) for key, value in sorted(projects.items())})
    (args.output / 'report.json').write_text(json.dumps(report, ensure_ascii=False, indent=2) + '\n')
    manifest.update(state='complete', completed_at=datetime.now(timezone.utc).isoformat())
    manifest_path.write_text(json.dumps(manifest, ensure_ascii=False, indent=2) + '\n')
    print(json.dumps(dict(output=str(args.output), counts=dict(counts), documents=len(docs)), ensure_ascii=False))


def main():
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument('command', choices=('inspect', 'sample', 'build'))
    parser.add_argument('--audit', type=Path, default=ROOT / 'minhon/era-audit/output-v2')
    parser.add_argument('--source-root', type=Path, default=ROOT / 'minhon/honkoku-data')
    parser.add_argument('--rules', type=Path, default=DEFAULT_RULES)
    parser.add_argument('--output', type=Path, required=True)
    parser.add_argument('--limit', type=int, default=0, help='0: all candidates; positive: first N pages')
    args = parser.parse_args()
    if args.limit < 0:
        parser.error('--limit must be non-negative')
    scan(args)


if __name__ == '__main__':
    main()