#!/usr/bin/env python3 """Character-length distributions for the frozen dialogue extraction corpus.""" import argparse from collections import defaultdict import csv import json import math from pathlib import Path from extract_dialogues import ROOT, file_hash, iter_jsonl, ordered_segments, write_json def percentile(values, fraction): position = (len(values) - 1) * fraction lower = math.floor(position) upper = math.ceil(position) return round(values[lower] + (values[upper] - values[lower]) * (position - lower), 1) def summarize(rows): values = sorted(r['chars'] for r in rows) total = sum(values) edges = [1000, 3000, 6000, 10000, 20000, 50000, 100000, 200000, 500000, 1000000] bins = [] lower = 0 for upper in edges + [None]: matched = [n for n in values if n >= lower and (upper is None or n <= upper)] bins.append({'min_chars': lower, 'max_chars': upper, 'count': len(matched), 'percent': round(100 * len(matched) / len(values), 2), 'text_percent': round(100 * sum(matched) / total, 2) if total else 0}) if upper is not None: lower = upper + 1 return {'count': len(values), 'total_chars': total, 'min': values[0], 'mean': round(total / len(values), 1), **{f'p{int(p * 100):02d}': percentile(values, p) for p in (.25, .5, .75, .9, .95, .99)}, 'max': values[-1], 'bins': bins, 'thresholds': {str(threshold): { 'count_le': sum(n <= threshold for n in values), 'percent_le': round(100 * sum(n <= threshold for n in values) / len(values), 2), 'text_percent_le': round(100 * sum(n for n in values if n <= threshold) / total, 2) if total else 0} for threshold in (6000, 10000, 20000, 50000, 100000)}} def main(): parser = argparse.ArgumentParser(description=__doc__) parser.add_argument('--input', type=Path, default=ROOT / 'unified/pretrain-v1/build-003/pretrain.jsonl') parser.add_argument('--output', type=Path, required=True) args = parser.parse_args() args.output.mkdir(parents=True, exist_ok=False) works = defaultdict(list) records = defaultdict(list) for doc in iter_jsonl(args.input): if doc.get('source') not in ('minhon', 'wikisource'): continue work_id = doc.get('source_document_id') or doc['id'] thin = {k: doc.get(k) for k in ('id', 'source', 'unit_label', 'title')} thin.update(work_id=work_id, chars=len(doc['text'])) works[(doc['source'], work_id)].append(thin) records[doc['source']].append(thin) work_rows, segments = defaultdict(list), defaultdict(list) for (source, work_id), docs in works.items(): parts = ordered_segments(docs) work_rows[source].append({'id': work_id, 'title': docs[0]['title'], 'chars': sum(d['chars'] for d in docs), 'records': len(docs), 'segments': len(parts)}) for index, part in enumerate(parts): segments[source].append({'id': f'{work_id}#segment-{index + 1}', 'title': part[0]['title'], 'chars': sum(d['chars'] for d in part) + len(part) - 1, 'records': len(part), 'work_id': work_id}) report = {'input': str(args.input.resolve()), 'input_sha256': file_hash(args.input), 'unit': 'Unicode code points, including whitespace; not tokens', 'work_definition': 'source_document_id within source; editions remain separate', 'work_chars': 'sum of record lengths; no gap filling or implied concatenation', 'segment_definition': 'same ordered_segments policy as extract_dialogues.py; ' 'consecutive numeric minhon pages joined with one LF; ' 'Wikisource articles remain separate', 'percentile_method': 'linear interpolation at (n-1)*p', 'distributions': {}} for source in sorted(records): report['distributions'][source] = {} for unit, rows in [('record', records[source]), ('work', work_rows[source]), ('segment', segments[source])]: report['distributions'][source][unit] = summarize(rows) path = args.output / f'{source}.{unit}.csv' with open(path, 'w', newline='', encoding='utf-8') as f: writer = csv.DictWriter(f, fieldnames=list(rows[0])) writer.writeheader() writer.writerows(sorted(rows, key=lambda r: r['chars'], reverse=True)) write_json(args.output / 'report.json', report) compact = {source: {unit: {k: v for k, v in stats.items() if k != 'bins'} for unit, stats in units.items()} for source, units in report['distributions'].items()} print(json.dumps(compact, ensure_ascii=False, indent=2)) if __name__ == '__main__': main()