File size: 10,660 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
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
#!/usr/bin/env python3
"""Clean an inventoried Kanripo snapshot without modifying raw files."""
import argparse
from collections import Counter, defaultdict
from contextlib import ExitStack
import csv
from datetime import datetime, timezone
import hashlib
import json
from pathlib import Path
import re

from kanripo_profile import dump

RULES = {
    'dynasty': 'Exclude catalog dynasty 清/淸; unknown remains explicitly unknown',
    'selection': 'Completed non-Qing catalog entries, inventoried KR_ID_digits[letter].txt only',
    'management': 'Remove metadata/comment lines, pb/md/PB, pilcrow, fold/image tags, Org delimiters; keep link labels and heading text',
    'body': 'Keep historical annotations, parentheses, slashes, missing characters, original glyphs and whitespace',
    'unknown': 'Hold files with unresolved management syntax; never guess deletion ranges',
    'unit': 'One source text file per record; no concatenation, deduplication, split or tokenize',
}
FLAGS = re.MULTILINE
LINE = r'[^\r\n]*(?:\r?\n|$)'
PATTERNS = [
    ('metadata_lines', re.compile(r'^[ \t]*#+\+[A-Za-z][A-Za-z0-9_-]*' + LINE, FLAGS), ''),
    ('mode_lines', re.compile(r'^[ \t]*#+[ \t]*-\*-'+ LINE, FLAGS), ''),
    # A section title can be prefixed by an editorial Roman-numeral marker.
    ('roman_heading_prefix', re.compile(r'^[ \t]*#+[ \t]*[ivxlcdm]+#(?=<)', FLAGS | re.I), ''),
    ('comment_lines', re.compile(r'^[ \t]*#+[ \t]*[A-Za-z]' + LINE, FLAGS), ''),
    ('legacy_page_comments', re.compile(r'^[ \t]*%[ \t]*BR\d+(?:\.\d+)*[a-z]?[^\r\n]*(?:\r?\n|$)', FLAGS), ''),
    ('page_markers', re.compile(r'<(?:pb|md)(?::|[ \t]+)[^<>\r\n]*>', re.I), ''),
    ('fold_markers', re.compile(r'<折[ \t]+t="\d+"[ \t]*/>'), ''),
    ('image_markers', re.compile(r'<img:[^<>\r\n]*>', re.I), ''),
    ('org_heading_prefix', re.compile(r'^\*+[ \t]+', FLAGS), ''),
    # Require a link type: [[...]] can also be nested character descriptions.
    ('org_labelled_links', re.compile(r'\[\[[A-Za-z][A-Za-z0-9_-]*:[^\[\]]{0,2000}\]\[([^\[\]]{0,2000})\]\]'), r'\1'),
    ('non_ascii_directive_prefix', re.compile(r'^[ \t]*#+\+(?=[\u3400-\u9fff])', FLAGS), ''),
    ('hash_heading_marks', re.compile(r'^[ \t]*#+|#+[ \t]*(?=\r?$)', FLAGS), ''),
    ('percent_page_prefix', re.compile(r'^[ \t]*%(?=¶?[ \t]*\r?$)', FLAGS), ''),
    ('pilcrow', re.compile('¶'), ''),
]
RESIDUAL = re.compile(r'<(?:pb|md|img)(?=[:\s>])|<折\s|\[\[[A-Za-z][A-Za-z0-9_-]*:|^\s*#\+|^%[ \t]*BR\d', re.M | re.I)


def sha(data):
    return hashlib.sha256(data).hexdigest()


def clean(original):
    counts = Counter()
    text = original
    if text.startswith('\ufeff'):
        text = text[1:]
        counts['initial_bom'] = 1
    for name, pattern, replacement in PATTERNS:
        text, n = pattern.subn(replacement, text)
        if n:
            counts[name] += n
    issues = []
    for match in RESIDUAL.finditer(text):
        if len(issues) < 8:
            issues.append(text[max(0, match.start()-35):match.end()+100])
    return text, counts, issues


def load_inputs(root, audit):
    audit_manifest = json.loads((audit / 'manifest.json').read_text())
    if not audit_manifest['complete']:
        raise ValueError('incomplete inventory')
    data = (root / 'metadata/manifest.csv').read_bytes()
    if sha(data) != audit_manifest['source_manifest_sha256']:
        raise ValueError('source manifest changed since inventory')
    rows = list(csv.DictReader(data.decode('utf-8-sig').splitlines()))
    catalog = {r['id']: r for r in rows}
    if len(catalog) != len(rows):
        raise ValueError('duplicate catalog IDs')
    inventory_data = (audit / 'files.jsonl').read_bytes()
    files = [json.loads(line) for line in inventory_data.decode('utf-8').splitlines()]
    if len(files) != len({r['raw_path'] for r in files}):
        raise ValueError('duplicate inventory paths')
    expected = {r['id'] for r in rows if r['status'] == 'complete' and r['dynasty'] not in {'清', '淸'}}
    report = json.loads((audit / 'report.json').read_text())
    if not {r['id'] for r in files} <= expected or len(files) != report['totals']['body_files']:
        raise ValueError('inventory work coverage mismatch')
    return catalog, files, data, inventory_data


def source_path(root, row):
    path = root / row['raw_path']
    rid = row['id']
    if (not re.fullmatch(r'KR[1-6][a-z]\d{4}', rid)
            or not re.fullmatch(re.escape(rid) + r'_\d+[a-z]?\.txt', path.name)
            or path.parent != root / 'raw' / rid
            or path.is_symlink() or path.parent.is_symlink()
            or not path.resolve().is_relative_to(root / 'raw')):
        raise ValueError(f'unsafe source path: {path}')
    return path


def build(root, audit, output):
    root, audit, output = root.resolve(), audit.resolve(), output.resolve()
    catalog, files, metadata, inventory = load_inputs(root, audit)
    if root.is_relative_to(output) or output.is_relative_to(root / 'raw') or output == audit:
        raise ValueError('unsafe output directory')
    output.mkdir(parents=True, exist_ok=False)
    manifest = {'complete': False, 'started': datetime.now(timezone.utc).isoformat(),
                'root': str(root), 'audit': str(audit), 'rules': RULES,
                'source_manifest_sha256': sha(metadata), 'inventory_sha256': sha(inventory),
                'script_sha256': sha(Path(__file__).read_bytes())}
    dump(output / 'manifest.json', manifest)
    totals, removed, dynasties = Counter(), Counter(), Counter()
    exact = defaultdict(list)
    selected_works, review_works = set(), set()
    sample_counts = Counter()
    with ExitStack() as stack:
        out = {name: stack.enter_context((output / (name + '.jsonl')).open('w', encoding='utf-8'))
               for name in ['documents', 'excluded', 'edits', 'review', 'preview', 'files']}

        def emit(name, obj):
            out[name].write(json.dumps(obj, ensure_ascii=False) + '\n')

        body_works = {entry['id'] for entry in files}
        for row in catalog.values():
            reasons = []
            if row['dynasty'] in {'清', '淸'}:
                reasons.append('qing_user_excluded')
                totals['qing_catalog_works'] += 1
                if row['status'] == 'complete':
                    totals['qing_complete_works'] += 1
            if row['status'] != 'complete':
                reasons.append('download_not_complete')
                totals['incomplete_catalog_works'] += 1
            elif row['dynasty'] not in {'清', '淸'} and row['id'] not in body_works:
                reasons.append('no_body_files')
                totals['no_body_works'] += 1
            if reasons:
                emit('excluded', dict(id=row['id'], dynasty=row['dynasty'], label=row['label'], reasons=reasons))
                totals['excluded_catalog_works'] += 1

        for i, entry in enumerate(files):
            rid = entry['id']
            row = catalog[rid]
            if row['status'] != 'complete' or row['dynasty'] in {'清', '淸'}:
                raise ValueError(f'ineligible inventory entry: {rid}')
            data = source_path(root, entry).read_bytes()
            if sha(data) != entry['raw_sha256']:
                raise ValueError(f'raw input changed: {entry["raw_path"]}')
            original = data.decode('utf-8')
            text, counts, issues = clean(original)
            totals['input_files'] += 1
            totals['original_chars'] += len(original)
            removed.update(counts)
            file_id = 'kanripo/' + rid + '/' + Path(entry['raw_path']).name
            base = dict(id=file_id, source='kanripo', work_id=rid, label=row['label'],
                        dynasty=row['dynasty'], dynasty_raw=row['dynasty_raw'],
                        classification_source=row['classification_source'],
                        raw_path=entry['raw_path'], raw_sha256=entry['raw_sha256'])
            audit_row = dict(base, original_chars=len(original), clean_chars=len(text), removed=counts,
                             clean_sha256=sha(text.encode('utf-8')))
            if issues:
                status = 'review'
                emit('review', dict(audit_row, issues=issues))
                review_works.add(rid)
            elif not text.strip():
                status = 'empty'
            else:
                status = 'included'
                header = re.findall(r'^#+\+([^\r\n]+)', original, re.M)
                emit('documents', dict(base, text=text, clean_sha256=audit_row['clean_sha256'],
                                      chars=len(text), original_header=header))
                exact[audit_row['clean_sha256']].append(file_id)
                selected_works.add(rid)
                totals['clean_chars'] += len(text)
                dynasties[row['dynasty']] += len(text)
            audit_row['status'] = status
            emit('files', audit_row)
            totals[status + '_files'] += 1
            if counts:
                emit('edits', audit_row)
            for feature in counts:
                if sample_counts[feature] < 2:
                    emit('preview', dict(id=file_id, feature=feature, before=original[:2500], after=text[:2500]))
                    sample_counts[feature] += 1
            if (i+1) % 10000 == 0:
                print(f'processed {i+1}/{len(files)}', flush=True)
    duplicates = [dict(sha256=key, ids=ids) for key, ids in exact.items() if len(ids) > 1]
    with (output / 'duplicates.jsonl').open('w', encoding='utf-8') as f:
        for group in duplicates:
            f.write(json.dumps(group, ensure_ascii=False) + '\n')
    totals['included_works'] = len(selected_works)
    totals['review_works'] = len(review_works)
    totals['duplicate_groups'] = len(duplicates)
    if sha((root / 'metadata/manifest.csv').read_bytes()) != sha(metadata):
        raise ValueError('source manifest changed during build')
    dump(output / 'report.json', dict(totals=totals, removed=removed, chars_by_dynasty=dynasties))
    manifest.update(complete=True, finished=datetime.now(timezone.utc).isoformat(),
                    output_hashes={p.name: sha(p.read_bytes()) for p in output.glob('*.jsonl') if p.name != 'documents.jsonl'})
    dump(output / 'manifest.json', manifest)
    print(json.dumps(totals, ensure_ascii=False), flush=True)


if __name__ == '__main__':
    p = argparse.ArgumentParser(description=__doc__)
    p.add_argument('--root', type=Path, default=Path('kanripo'))
    p.add_argument('--audit', type=Path, default=Path('kanripo/preprocessed-v1/inspection-002'))
    p.add_argument('--output', type=Path, required=True)
    a = p.parse_args()
    build(a.root, a.audit, a.output)