File size: 8,427 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
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
"""Create a new subset of a verified minhon build, excluding unknown-era docs.

This selects observed pre-1868 date mentions, not confirmed composition dates.
The original JSONL lines and all source artifacts are preserved.
"""
import argparse
import csv
import hashlib
import json
from collections import Counter
from datetime import datetime, timezone
from pathlib import Path

ROOT = Path(__file__).resolve().parents[1]
BUCKET = '江戸以前の年代記述あり'


def sha(path):
    h = hashlib.sha256()
    with path.open('rb') as f:
        for chunk in iter(lambda: f.read(1024 * 1024), b''):
            h.update(chunk)
    return h.hexdigest()


def save(path, data):
    path.write_text(json.dumps(data, ensure_ascii=False, indent=2) + '\n', encoding='utf-8')


def main():
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument('--source', type=Path, default=ROOT / 'minhon/preprocessed-v1/build-001')
    parser.add_argument('--audit', type=Path, default=ROOT / 'minhon/era-audit/output-v2')
    parser.add_argument('--output', type=Path, required=True)
    args = parser.parse_args()
    source, audit, out = args.source.resolve(), args.audit.resolve(), args.output.resolve()
    inputs = [source / n for n in ('clean_pages.jsonl', 'report.json', 'verification.json')]
    inputs += [audit / 'documents.csv', Path(__file__).resolve()]
    hashes = {str(p): sha(p) for p in inputs}
    if json.loads((source / 'verification.json').read_text())['status'] != 'passed':
        raise ValueError('Source build has not passed verification')
    with (audit / 'documents.csv').open(encoding='utf-8-sig', newline='') as f:
        rows = list(csv.DictReader(f))
    docs = {}
    for row in rows:
        if row['decision'] != 'retain_candidate':
            continue
        key = '/'.join(filter(None, (row['version'], row['project'], row['id'])))
        if key in docs:
            raise ValueError(f'Duplicate document: {key}')
        docs[key] = dict(row, document_id=key)
    allowed = {key for key, r in docs.items() if r['decision'] == 'retain_candidate'
               and r['era_bucket'] == BUCKET and r['old_date_observed'] == 'True'}
    out.mkdir(parents=True, exist_ok=False)
    manifest = {'status': 'running', 'created_at': datetime.now(timezone.utc).isoformat(),
                'source_build': str(source), 'audit': str(audit), 'input_sha256': hashes,
                'selection': {'decision': 'retain_candidate', 'era_bucket': BUCKET,
                              'old_date_observed': 'True'},
                'limitation': 'Date mentions only; original composition/publication dates are not confirmed.',
                'text_transformation': 'none; selected JSONL lines copied byte for byte'}
    save(out / 'manifest.json', manifest)
    pages, chars = Counter(), Counter()
    kept, removed = Counter(), Counter()
    ids = set()
    with (source / 'clean_pages.jsonl').open('rb') as src, (out / 'clean_pages.jsonl').open('wb') as dst:
        for line in src:
            page = json.loads(line)
            key = page['document_id']
            row = docs[key]
            if page['id'] in ids:
                raise ValueError(f'Duplicate page: {page["id"]}')
            ids.add(page['id'])
            assert row['decision'] == 'retain_candidate'
            assert row['era_bucket'] == page['era_bucket']
            assert page['status'] == 'clean' and page['text'].strip()
            assert len(page['text']) == page['clean_characters']
            assert hashlib.sha256(page['text'].encode('utf-8')).hexdigest() == page['clean_sha256']
            pages[key] += 1
            chars[key] += page['clean_characters']
            target = kept if key in allowed else removed
            target['pages'] += 1
            target['characters'] += page['clean_characters']
            if key in allowed:
                dst.write(line)
            else:
                assert row['era_bucket'] == '年代不明'
    source_report = json.loads((source / 'report.json').read_text())
    assert len(ids) == source_report['counts']['clean_pages']
    assert len(pages) == source_report['documents_with_clean_pages']
    assert sum(chars.values()) == source_report['counts']['clean_page_characters']
    for name, keys in [('included_documents', set(pages) & allowed),
                       ('excluded_documents', set(pages) - allowed)]:
        fields = ['document_id', 'title', 'decision', 'era_bucket', 'old_date_observed',
                  'clean_pages', 'clean_characters', 'source_path']
        with (out / f'{name}.csv').open('w', encoding='utf-8-sig', newline='') as f:
            writer = csv.DictWriter(f, fieldnames=fields, extrasaction='ignore')
            writer.writeheader()
            for key in sorted(keys):
                writer.writerow(dict(docs[key], clean_pages=pages[key], clean_characters=chars[key]))
    # Verify the entire output against a second, independent pass over the input.
    verified = Counter()
    with (source / 'clean_pages.jsonl').open('rb') as src, (out / 'clean_pages.jsonl').open('rb') as dst:
        for line in src:
            page = json.loads(line)
            if page['document_id'] in allowed:
                assert next(dst) == line
                verified['pages'] += 1
                verified['characters'] += len(page['text'])
        assert dst.read() == b''
    assert verified == kept
    assert all(sha(Path(p)) == digest for p, digest in hashes.items())
    kept['documents'] = len(set(pages) & allowed)
    removed['documents'] = len(set(pages) - allowed)
    report = {'included': dict(kept), 'excluded_unknown_era': dict(removed),
              'audit_eligible_documents': len(allowed), 'source_pages': len(ids),
              'source_documents': len(pages), 'source_characters': sum(chars.values())}
    save(out / 'report.json', report)
    save(out / 'verification.json', {'status': 'passed', 'verified_output': dict(verified),
         'checks': ['source_verification_passed', 'audit_retained_document_unique_ids',
                    'all_source_page_unique_ids', 'all_source_clean_text_hashes',
                    'all_source_counts', 'all_selected_lines_byte_identical',
                    'output_exactly_matches_allowlist', 'input_hashes_unchanged'],
         'output_sha256': sha(out / 'clean_pages.jsonl')})
    (out / 'README.md').write_text(f'''# minhon 年代不明除外版

元データ: `{source.relative_to(ROOT)}/clean_pages.jsonl`。
既存監査の `decision=retain_candidate`、`era_bucket={BUCKET}`、
`old_date_observed=True` の資料だけを採用。年代不明資料は除外しました。

`clean_pages.jsonl`: {kept['documents']:,}資料、{kept['pages']:,}ページ、
{kept['characters']:,}文字(空白・改行含む)。モデル入力には `text` フィールドを使います。
除外: {removed['documents']:,}資料、{removed['pages']:,}ページ、{removed['characters']:,}文字。

**年代の記述があることと、原資料の成立・書写・刊行年代が確定していることは異なります。**
本文中の過去の出来事の日付も既存判定に含まれます。この版は年代不明区分を外した候補集合です。
成立年・刊行年を厳密に保証するデータセットではありません。年代の新規調査・再判定はしていません。

本文・清掃規則・順序は元の採用行とバイト単位で同一です。原文と旧版は保持しています。
採用資料は `included_documents.csv`、除外資料は `excluded_documents.csv`、
判定条件と入力ハッシュは `manifest.json`、集計は `report.json` に保存しました。
全出力行を元データの許可対象と再照合し、`verification.json` に結果を保存しています。
元の前処理・原文照合は旧版の監査ファイルを参照してください。

原文: `minhon/honkoku-data`。原データREADMEのライセンス表示はCC BY-SA 4.0。
学習・tokenize・分割・結合・重複削除は未実施です。

再実行(未作成の出力先を指定):
```bash
python3 scripts/minhon_select_dated.py --output minhon/preprocessed-v1/build-next-dated
```
''', encoding='utf-8')
    manifest['status'] = 'complete'
    save(out / 'manifest.json', manifest)
    print(json.dumps(report, ensure_ascii=False, indent=2))


if __name__ == '__main__':
    main()