File size: 4,348 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
#!/usr/bin/env python3
"""List NDL documents by original missing-character ratio with local links.

Reads a completed unified audit catalog and writes a Markdown table plus a CSV
for an arbitrary [min, max) missing-ratio band. Links point at the pre-clean
text (corpus/text/<PID>.txt) and at the post-clean line in build documents.
No corpus text is modified.
"""
import argparse
import collections
import csv
import json
from pathlib import Path


def ratio_band(value, bands):
    for label, low, high in bands:
        if low <= value < high:
            return label
    return 'other'


def main():
    p = argparse.ArgumentParser(description=__doc__)
    p.add_argument('--audit', type=Path, required=True)
    p.add_argument('--min', type=float, required=True, dest='low')
    p.add_argument('--max', type=float, required=True, dest='high')
    p.add_argument('--output', type=Path, required=True, help='Markdown output path')
    args = p.parse_args()

    audit = args.audit.resolve()
    out = args.output.resolve()
    root = Path(__file__).resolve().parents[1]

    rows = []
    with (audit / 'catalog.jsonl').open() as f:
        for line in f:
            r = json.loads(line)
            if r['source'] != 'ndl':
                continue
            q = r['quality']['original_quality']
            ratio = float(q['missing_ratio'])
            if not (args.low <= ratio < args.high):
                continue
            rows.append((r, q))
    rows.sort(key=lambda x: (-x[1]['missing_ratio'], x[0]['id']))
    if not rows:
        raise SystemExit('no documents in range')

    width = (args.high - args.low) / 5
    bands = []
    for i in range(5):
        low = args.low + i * width
        high = args.low + (i + 1) * width
        label = f'{low*100:.0f}-{high*100:.0f}%'
        bands.append((label, low, high))
    counts = collections.Counter(ratio_band(q['missing_ratio'], bands) for _, q in rows)

    out.parent.mkdir(parents=True, exist_ok=True)
    csv_path = out.with_suffix('.csv')
    with csv_path.open('w', newline='') as f:
        w = csv.writer(f)
        w.writerow(['id', 'title', 'missing_ratio', 'missing_count', 'nonspace_chars',
                    'text_path', 'text_line', 'document_path', 'document_line'])
        for r, q in rows:
            pid = r['id'].split('/')[1]
            w.writerow([r['id'], r['title'], f"{q['missing_ratio']:.6f}", q['missing_count'],
                        q['nonspace_chars'], f'corpus/text/{pid}.txt', 1,
                        r['text_ref']['path'], r['text_ref']['line']])

    total_chars = sum(q['nonspace_chars'] for _, q in rows)
    lines = [
        f"# NDL 欠字率 {args.low*100:.0f}–{args.high*100:.0f}% の資料一覧",
        '',
        f'- 対象: {len(rows)}資料(`{audit.name}/catalog.jsonl` の original missing_ratio 基準)',
        f'- 削除前の非空白文字合計: {total_chars:,}字',
        f'- 書名の種類: {len({r["title"] for r, _ in rows})}',
        f'- CSV: `{csv_path.name}`',
        '',
        '| 欠字率 | 件数 |',
        '|---|---:|',
    ]
    for label, low, high in reversed(bands):
        lines.append(f'| {label} | {counts[label]} |')
    lines.extend([
        f'| 合計 | {len(rows)} |',
        '',
        'リンク: `txt` は削除前テキスト、`Lxxxx` は削除後本文(documents.jsonl の行)。',
        '',
        '| # | ID | 書名 | 欠字率 | 欠字/字数 | 本文 | 後処理 |',
        '|---|---|---|---:|---:|---|---|',
    ])
    for n, (r, q) in enumerate(rows, 1):
        pid = r['id'].split('/')[1]
        title = r['title'].replace('|', '\\|')
        txt = f'[txt](vscode://file{root}/corpus/text/{pid}.txt:1)'
        doc = (f'[L{r["text_ref"]["line"]}](vscode://file{root}/'
               f'{r["text_ref"]["path"]}:{r["text_ref"]["line"]})')
        lines.append(f'| {n} | {r["id"]} | {title} | {q["missing_ratio"]*100:.1f}% | '
                     f'{q["missing_count"]}/{q["nonspace_chars"]} | {txt} | {doc} |')
    out.write_text('\n'.join(lines) + '\n')
    print(json.dumps(dict(documents=len(rows), chars=total_chars,
                          markdown=str(out), csv=str(csv_path),
                          bands={label: counts[label] for label, _, _ in bands}),
                     ensure_ascii=False))


if __name__ == '__main__':
    main()