classical-ja-pretrain / code /scripts /minhon_select_bibliographic_dates.py
kuramot6f's picture
Initial release (history squashed)
7a088d4
Raw History Blame Contribute Delete
14 kB
"""Select dated minhon candidates with populated bibliographic date fields.
Uses existing metadata only. Copies source JSONL lines without text changes;
date-field presence does not establish a pre-1868 edition or manuscript.
"""
import argparse
from collections import Counter
import csv
from datetime import datetime, timezone
import hashlib
import json
from pathlib import Path
import re
import unicodedata
ROOT = Path(__file__).resolve().parents[1]
BUCKET = '江戸以前の年代記述あり'
def sha(path):
h = hashlib.sha256()
with path.open('rb') as f:
for block in iter(lambda: f.read(1024 * 1024), b''):
h.update(block)
return h.hexdigest()
def save(path, data):
path.write_text(json.dumps(data, ensure_ascii=False, indent=2) + '\n')
def flatten(value):
if isinstance(value, dict):
# IIIF language maps and older presentation API text values.
if '@value' in value:
return flatten(value['@value'])
return ' '.join(flatten(v) for v in value.values())
if isinstance(value, list):
return ' '.join(flatten(v) for v in value)
return '' if value is None else str(value)
def populated_date(value):
text = unicodedata.normalize('NFKC', flatten(value)).strip()
return bool(text) and text.lower() not in {
'9999', '0000', '0', '不明', '刊年不明', '出版年不明', '書写年不明',
'unknown', 'undated', 'n.d.', 'none', 'null', '-', '―', '?',
}
def date_field(label):
text = unicodedata.normalize('NFKC', flatten(label)).strip()
if re.search(r'災害|事件|撮影|登録|更新|公開|デジタル|digitiz|creat|updat|modif|register', text, re.I):
return False
return bool(re.fullmatch(
r'(?:Publication Date(?:\s*\([^)]*\))?|Date|DC\.date|DCTERMS\.issued|'
r'刊行年(?:月日)?|出版年(?:月日)?|書写年(?:月日)?|成立年(?:月日)?|年代|時代)',
text, re.I))
def write_csv(path, rows, fields):
with path.open('w', encoding='utf-8-sig', newline='') as f:
writer = csv.DictWriter(f, fieldnames=fields, extrasaction='ignore')
writer.writeheader()
writer.writerows(rows)
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument('--source', type=Path, default=ROOT / 'minhon/preprocessed-v1/build-002-dated')
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('--metadata', type=Path, default=ROOT / 'minhon/era-audit/external-metadata.jsonl')
parser.add_argument('--output', type=Path, required=True)
args = parser.parse_args()
source, audit, raw, out = (p.resolve() for p in (args.source, args.audit, args.source_root, args.output))
metadata_path = args.metadata.resolve()
input_paths = [source / n for n in ('clean_pages.jsonl', 'report.json', 'verification.json')]
input_paths += [audit / 'documents.csv', raw / 'v1/entries.csv', metadata_path, Path(__file__).resolve()]
info_paths = sorted((raw / 'v3').glob('*/info.tsv'))
input_paths += info_paths
hashes = {str(p): sha(p) for p in input_paths}
prior = json.loads((source / 'verification.json').read_text())
if prior['status'] != 'passed' or prior['output_sha256'] != hashes[str(source / 'clean_pages.jsonl')]:
raise ValueError('Source build verification/hash failed')
with (audit / 'documents.csv').open(encoding='utf-8-sig', newline='') as f:
docs = {}
for r in csv.DictReader(f):
if r['decision'] == 'retain_candidate' and r['era_bucket'] == BUCKET:
key = '/'.join(filter(None, (r['version'], r['project'], r['id'])))
if key in docs:
raise ValueError('Duplicate document ' + key)
docs[key] = r
local = {}
for p in info_paths:
with p.open(encoding='utf-8-sig', newline='') as f:
for r in csv.DictReader(f, delimiter='\t'):
key = (p.parent.name, r['id'])
if '/'.join(('v3', *key)) not in docs:
continue
if key in local:
raise ValueError('Duplicate local metadata ' + str(key))
local[key] = r
cache = {}
with metadata_path.open() as f:
for line in f:
r = json.loads(line)
cache[(r['kind'], r['key'])] = r
evidence = {key: [] for key in docs}
def add(key, kind, field, value, location, url='', fetched_at='', row_number=None, column=None):
if populated_date(value):
evidence[key].append(dict(document_id=key, source_kind=kind, field=field,
value=value, value_text=flatten(value), source=location, url=url,
fetched_at=fetched_at, row_number=row_number, column=column))
# Preserve duplicate headers and all matching rows instead of DictReader's
# last-column behavior. Only publication date counts, never disaster date.
with (raw / 'v1/entries.csv').open(encoding='utf-8-sig', newline='') as f:
reader = csv.reader(f)
headers = next(reader)
for row_number, values in enumerate(reader, 2):
key = 'v1/' + values[0]
if key not in docs:
continue
url = next((v for h, v in zip(headers, values) if h == '書誌URL'), '')
for column, (field, value) in enumerate(zip(headers, values), 1):
if field == '出版年(西暦年月日)':
add(key, 'v1_catalog', field, value, str(raw / 'v1/entries.csv'),
url, row_number=row_number, column=column)
for key, doc in docs.items():
if doc['version'] != 'v3':
continue
url = local.get((doc['project'], doc['id']), {}).get('manifestUrl', '')
record = cache.get(('manifest', url), {})
if record.get('ok'):
for index, item in enumerate(record['data'].get('metadata', [])):
if date_field(item.get('label')):
add(key, 'iiif_metadata', flatten(item['label']), item.get('value'),
str(metadata_path), url, record.get('fetched_at', ''), row_number=index)
for doi in filter(None, doc['dois'].split(';')):
record = cache.get(('doi', doi), {})
if record.get('ok'):
date = record['data'].get('publication_date', {})
# JaLC 9999 means an unknown publication year, not evidence.
year = date.get('publication_year') if isinstance(date, dict) else None
if populated_date(year):
add(key, 'doi_metadata', 'publication_date', date,
str(metadata_path), record.get('url', 'https://doi.org/' + doi),
record.get('fetched_at', ''))
allowed = {key for key, items in evidence.items() if items}
out.mkdir(parents=True, exist_ok=False)
manifest = dict(status='running', created_at=datetime.now(timezone.utc).isoformat(),
source_build=str(source), input_sha256=hashes,
selection=dict(decision='retain_candidate', era_bucket=BUCKET,
populated_bibliographic_date=True, metadata_scope='existing cache only'),
limitation='Date fields may contain approximate/range dates; original pre-1868 edition is not confirmed.',
text_transformation='none; original JSONL lines copied byte for byte')
save(out / 'manifest.json', manifest)
pages, chars = Counter(), Counter()
included, excluded = Counter(), Counter()
seen = set()
with (source / 'clean_pages.jsonl').open('rb') as src, (out / 'clean_pages.jsonl').open('wb') as dst:
for line in src:
p = json.loads(line)
key = p['document_id']
assert key in docs and p['era_bucket'] == BUCKET
assert p['id'] not in seen
seen.add(p['id'])
assert p['status'] == 'clean' and p['text'].strip()
assert len(p['text']) == p['clean_characters']
assert hashlib.sha256(p['text'].encode()).hexdigest() == p['clean_sha256']
pages[key] += 1
chars[key] += len(p['text'])
counts = included if key in allowed else excluded
counts['pages'] += 1
counts['characters'] += len(p['text'])
if key in allowed:
dst.write(line)
source_report = json.loads((source / 'report.json').read_text())['included']
assert len(seen) == source_report['pages']
assert len(pages) == source_report['documents']
assert sum(chars.values()) == source_report['characters']
included['documents'] = len(set(pages) & allowed)
excluded['documents'] = len(set(pages) - allowed)
document_rows = []
for key, doc in sorted(docs.items()):
document_rows.append(dict(document_id=key, title=doc['title'], version=doc['version'],
project=doc['project'], has_bibliographic_date=key in allowed,
included=key in allowed and pages[key] > 0,
reason=('included' if pages[key] else 'no_clean_pages') if key in allowed else 'no_populated_bibliographic_date',
clean_pages=pages[key], clean_characters=chars[key],
date_evidence_count=len(evidence[key]),
date_fields_json=json.dumps(evidence[key], ensure_ascii=False), source_path=doc['source_path']))
fields = list(document_rows[0])
write_csv(out / 'documents.csv', document_rows, fields)
write_csv(out / 'included_documents.csv', [r for r in document_rows if r['included']], fields)
write_csv(out / 'excluded_documents.csv', [r for r in document_rows if not r['included']], fields)
with (out / 'date_evidence.jsonl').open('w') as f:
for key in sorted(allowed):
for item in evidence[key]:
f.write(json.dumps(item, ensure_ascii=False) + '\n')
# Independently replay the source allowlist; verify exact order and bytes.
verified = Counter()
with (source / 'clean_pages.jsonl').open('rb') as src, (out / 'clean_pages.jsonl').open('rb') as dst:
for line in src:
p = json.loads(line)
if p['document_id'] in allowed:
assert next(dst) == line
verified['pages'] += 1
verified['characters'] += len(p['text'])
assert dst.read() == b''
assert verified['pages'] == included['pages'] and verified['characters'] == included['characters']
assert all(sha(Path(p)) == digest for p, digest in hashes.items())
report = dict(included=dict(included), excluded_from_source=dict(excluded),
audit_candidate_documents=len(docs), bibliographic_date_documents=len(allowed),
dated_documents_without_clean_pages=len(allowed - set(pages)),
bibliographic_date_documents_by_version=dict(Counter(docs[k]['version'] for k in allowed)),
included_documents_by_version=dict(Counter(docs[k]['version'] for k in allowed & set(pages))),
evidence_by_kind=dict(Counter(e['source_kind'] for k in allowed for e in evidence[k])),
source_counts=source_report)
save(out / 'report.json', report)
save(out / 'verification.json', dict(status='passed', verified_output=dict(verified),
checks=['source_verification_and_output_hash', 'unique_source_page_ids',
'all_source_clean_text_hashes', 'source_report_totals',
'output_exactly_matches_bibliographic_date_allowlist',
'all_selected_lines_byte_identical_in_source_order', 'input_hashes_unchanged'],
output_sha256=sha(out / 'clean_pages.jsonl')))
(out / 'README.md').write_text(f'''# minhon 書誌年代項目あり版
採用: {included['documents']:,}資料、{included['pages']:,}ページ、{included['characters']:,}文字(空白・改行を含む)。
本文: `clean_pages.jsonl` の `text` フィールド。
入力: `{source.relative_to(ROOT)}/clean_pages.jsonl`。
既存監査の残す候補・「江戸以前の年代記述あり」のうち、取得済み書誌に値の入った年代項目がある資料だけを選択。
v1は出版年欄、v3はIIIFのPublication Date・Date等とDOIのpublication_dateを使用。
災害年・撮影年・登録日時・本文中だけの年号・不明年コード9999は採用根拠にしません。
**書誌の年代項目がある資料の集合であり、江戸以前の成立・版・写本年代を確定した集合ではありません。**
幅のある推定年代や一般的なDate欄も含み、原表記と出典を根拠ファイルに残しています。
外部書誌の新規取得と原画像の年代確認は行っていません。未取得書誌は年代項目なしと区別できず、この版では不採用です。
- `included_documents.csv`: 本文を採用した資料と年代根拠。
- `excluded_documents.csv`: 対象候補の不採用理由。清掃済み本文のない資料も含みます。
- `documents.csv`: 全{len(docs):,}候補の判定。
- `date_evidence.jsonl`: 書誌年代の原値・項目名・出典・取得日時。
- `report.json`: 件数・文字数・出典別集計。
- `manifest.json`: 条件と入力ハッシュ。
- `verification.json`: 全出力行と入力の再照合結果。
本文は元JSONL行をバイト単位でコピーし、順序も保持。原文・既存成果物は保持しています。
原文 `minhon/honkoku-data` のライセンス表示はCC BY-SA 4.0。
学習・tokenize・他データとの統合は行っていません。
再実行: `python3 scripts/minhon_select_bibliographic_dates.py --output minhon/preprocessed-v1/build-next-bibdated`
''')
manifest['status'] = 'complete'
save(out / 'manifest.json', manifest)
print(json.dumps(report, ensure_ascii=False, indent=2))
if __name__ == '__main__':
main()