File size: 8,199 Bytes
7a088d4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
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
#!/usr/bin/env python3
"""Render a completed inspection's JSON reports into a bounded Markdown review."""
import argparse
from collections import Counter
import json
from pathlib import Path


def render(folder, source_root):
    manifest = json.loads((folder / 'manifest.json').read_text())
    if manifest['state'] != 'complete':
        raise ValueError('Inspection is not complete')
    report = json.loads((folder / 'report.json').read_text())
    counts = report['counts']
    lines = ['# minhon 前処理の調査結果', '',
             'retain_candidateを対象にした暫定規則での集計。原文は変更していない。',
             'cleanは現在の規則で警告が出なかった意味で、年代・翻刻精度の保証ではない。',
             ('採用本文をclean_pages.jsonlに出力済み。要確認・空ページは別一覧。訓練・他データセットとの結合は未実施。'
              if manifest['command'] == 'build' else
              '全件の学習用本文出力、訓練、他データセットとの結合は未実施。'), '',
             '| 項目 | 件数 |', '| --- | ---: |',
             f"| 資料 | {report['documents']:,} |"]
    labels = {'candidate_pages': '対象ページ', 'clean_pages': '警告なし',
              'review_pages': '要確認(非空)', 'empty_pages': '処理後空',
              'raw_empty_pages': '元から空・空白のみ',
              'removed_to_empty_pages': '記法・注記の除去で空になったページ',
              'read_errors': '読み取り失敗', 'raw_characters': '原文の文字数(記号・空白含む)',
              'clean_characters': '処理後の文字数(空・要確認ページを含む)',
              'clean_characters_clean_only': '警告なしページの文字数',
              'non_whitespace_clean_characters': '処理後の非空白文字数(要確認含む)',
              'raw_missing_characters': '原文中の欠字記号□',
              'missing_characters_removed': '削除した欠字記号□(注記内を含む)',
              'missing_characters': '処理後に残る欠字記号□',
              'exact_duplicate_extra_pages': '完全一致の余剰ページ数(未削除)'}
    for key, label in labels.items():
        if key == 'clean_characters_clean_only':
            lines.append(f"| {label} | {counts.get('clean_page_characters', 0):,} |")
            continue
        lines.append(f'| {label} | {counts.get(key, 0):,} |')
    references = manifest['rules'].get('references', [])
    if references:
        lines.extend(['', '## 公式資料を踏まえた規則', '',
                      '- [特殊記法](https://www.wiki.honkoku.org/doku.php?id=howto_markup)',
                      '- [標準翻刻ガイドライン](https://www.wiki.honkoku.org/doku.php?id=guidelines)', '',
                      '非空本文の空白(闕字)・改行・字下げは保存する。ルビはユーザー指定で削除し、送り仮名は残す。',
                      '入力翻刻には既に字体の変更が含まれうる。既存の表記を保存し、原本の字形を推定復元しない。'])
        if manifest['rules'].get('round_brackets_policy') == 'drop_all':
            lines.extend(['', 'ユーザー指定の積極削除規則により、丸括弧(全角・半角)と【…】・〖…〗は中身ごと削除する。',
                          '括弧内が原本の文言である可能性も承知した本文抽出方針で、括弧の成立年代を断定した規則ではない。',
                          '欠字□は削除して前後を連結する。原文の復元や推測補完は行わず、削除数を記録する。',
                          '003で付けていた旧注記の確認フラグは解除。未閉鎖括弧と未知タグは引き続き要確認。'])
        else:
            lines.extend(['', '公式に出力時削除とされている注記は〖…〗。【…】の暫定削除には確認フラグを付ける。'])
    lines.extend(['', '## 記法・警告のあるページ', '', '| 種別 | ページ数 |', '| --- | ---: |'])
    for key, value in report['feature_page_counts'].items():
        lines.append(f'| {key} | {value:,} |')
    lines.extend(['', '## 出現したタグ', '', '| タグ | 出現数 |', '| --- | ---: |'])
    for key, value in report['tag_occurrences'].items():
        lines.append(f'| {key.replace(chr(124), chr(65372))} | {value:,} |')
    # Preview real changes and preserve full page text in preview.jsonl.
    lines.extend(['', '## 変換例', '', '長いページは最初の変更箇所付近を抜粋。全文と変更位置はpreview.jsonlに記録。'])
    shown = set()
    with (folder / 'preview.jsonl').open() as handle:
        for line in handle:
            record = json.loads(line)
            kinds = {edit['kind'] for edit in record['edits']} - shown
            if not kinds:
                continue
            selected = next(edit for edit in record['edits'] if edit['kind'] in kinds)
            start, end = selected['start'], selected['end']
            before = record['raw_text'][max(0, start-35):min(len(record['raw_text']), end+35)]
            lines.extend(['', f"### {record['id']} — {selected['kind']}", '',
                          '変換対象と周辺:', '', '```text', before[:600], '```', '',
                          '対象部分の変換後:', '', '```text', selected['after'][:600] or '(削除)', '```'])
            shown.add(selected['kind'])
    lines.extend(['', '## 要確認例', '', '警告の種類・タグごとに最大2例。括弧の破損や未知記法の中身を確認する。'])
    issue_samples = Counter()
    with (folder / 'review.jsonl').open() as handle:
        for line in handle:
            record = json.loads(line)
            selected = []
            for issue in record.get('issues', []):
                key = (issue['kind'], issue.get('tag', ''))
                if issue_samples[key] < 2:
                    issue_samples[key] += 1
                    selected.append(issue)
            if not selected:
                continue
            raw = (source_root / record['source_path']).read_text(encoding='utf-8')
            for issue in selected:
                start, end = issue['start'], issue['end']
                excerpt = raw[max(0, start-50):min(len(raw), min(end, start+350)+50)]
                lines.extend(['', f"### {record['id']} — {issue['kind']} {issue.get('tag', '')}", '',
                              '```text', excerpt, '```'])
    duplicate_groups = cross_document = 0
    with (folder / 'duplicates.jsonl').open() as handle:
        for line in handle:
            record = json.loads(line)
            duplicate_groups += 1
            cross_document += bool(record['cross_document'])
    lines.extend(['', '## 重複と次の判断', '',
                  f'完全一致は{duplicate_groups:,}群。そのうち資料をまたぐ群は{cross_document:,}群。重複は削除していない。',
                  '', '1. 未知タグの処理を決める。',
                  '2. 括弧の破損を含むページの扱いを決める。',
                  '3. 高い削除率のサンプルを確認する。',
                  ('4. 採用本文は出力済み。資料連結・他コーパスとの重複整理は後工程。'
                   if manifest['command'] == 'build' else
                   '4. ルール確定後に全件変換する。資料連結・他コーパスとの重複整理は後工程。'), ''])
    destination = folder / 'REPORT.md'
    if destination.exists():
        raise FileExistsError(destination)
    destination.write_text('\n'.join(lines))
    print(destination)


if __name__ == '__main__':
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument('inspection', type=Path)
    parser.add_argument('--source-root', type=Path,
                        default=Path(__file__).resolve().parents[1] / 'minhon/honkoku-data')
    args = parser.parse_args()
    render(args.inspection, args.source_root)