from __future__ import annotations import argparse from collections import Counter from dataclasses import asdict, dataclass import csv import json from pathlib import Path import re import sys from typing import Any DEFAULT_DATASET = "common-pile/project_gutenberg_filtered" YEAR_RE = re.compile(r"(? argparse.Namespace: parser = argparse.ArgumentParser( description=( "Join a Hugging Face Gutenberg text dataset against a local metadata CSV " "with publication years and emit local JSONL for Talkie context-extension training." ) ) parser.add_argument("--dataset", default=DEFAULT_DATASET) parser.add_argument("--config") parser.add_argument("--split", default="train") parser.add_argument("--metadata-csv", type=Path, required=True) parser.add_argument("--out", type=Path, default=Path("data/gutenberg_pre1931.jsonl")) parser.add_argument("--summary-out", type=Path, default=Path("data/gutenberg_pre1931.summary.json")) parser.add_argument("--tokenizer-dir", type=Path) parser.add_argument( "--include-summary", type=Path, help=( "Rebuild only the Gutenberg IDs listed in an existing summary, preserving " "that summary's book order. Useful when the JSONL was lost but the manifest remains." ), ) parser.add_argument( "--reuse-include-summary-token-counts", action="store_true", help=( "When rebuilding from --include-summary without --tokenizer-dir, copy per-book " "Talkie token counts from that summary instead of re-tokenizing." ), ) parser.add_argument("--id-column", default="id") parser.add_argument("--year-column", default="publication_year") parser.add_argument("--metadata-title-column", default="title") parser.add_argument("--metadata-author-column", default="author") parser.add_argument("--min-year", type=int, default=1500) parser.add_argument("--max-year", type=int, default=1930) parser.add_argument("--languages", nargs="+", default=["en"]) parser.add_argument("--rights-contains", default="public domain") parser.add_argument("--min-chars", type=int, default=100_000) parser.add_argument("--max-chars-per-book", type=int, default=0) parser.add_argument("--max-books", type=int, default=64) parser.add_argument("--target-talkie-tokens", type=int, default=2_000_000) parser.add_argument( "--append-existing", action="store_true", help=( "Append additional books to --out using --summary-out to avoid duplicate " "Gutenberg IDs. The target token count is interpreted as the desired " "combined total." ), ) parser.add_argument( "--exclude-summary", type=Path, action="append", default=[], help="Skip Gutenberg IDs listed in an existing summary JSON. May be supplied more than once.", ) parser.add_argument("--strip-gutenberg-boilerplate", action=argparse.BooleanOptionalAction, default=True) parser.add_argument("--trust-remote-code", action=argparse.BooleanOptionalAction, default=False) return parser.parse_args() def import_datasets(): try: from datasets import load_dataset except ImportError as error: raise SystemExit( "Missing dependency: install with `uv sync --extra data` or " "`python -m pip install datasets pyarrow`." ) from error return load_dataset def load_tokenizer(path: Path | None): if path is None: return None try: from transformers import AutoTokenizer except ImportError as error: raise SystemExit("Missing dependency: transformers is required for --tokenizer-dir.") from error tokenizer = AutoTokenizer.from_pretrained(path, trust_remote_code=True) tokenizer.model_max_length = sys.maxsize return tokenizer def scalar(value: Any) -> str: if value is None: return "" return value if isinstance(value, str) else str(value) def row_metadata(row: dict[str, Any]) -> dict[str, Any]: metadata = row.get("metadata") return metadata if isinstance(metadata, dict) else {} def row_value(row: dict[str, Any], key: str, metadata_key: str | None = None) -> Any: value = row.get(key) if value not in (None, ""): return value return row_metadata(row).get(metadata_key or key) def normalize_id(value: Any) -> str: text = scalar(value).strip() if text.upper().startswith("PG"): text = text[2:] return text def parse_year(value: Any) -> int | None: text = scalar(value) match = YEAR_RE.search(text) return int(match.group(1)) if match else None def sniff_columns(fieldnames: list[str], requested: dict[str, str]) -> dict[str, str]: lowered = {name.lower(): name for name in fieldnames} aliases = { "id": ["id", "gutenberg_id", "ebook_id", "book_id", "pg_id", "gutenbergid"], "publication_year": ["publication_year", "year", "issued_date", "issued", "published", "publication_date"], "title": ["title", "book_title"], "author": ["author", "creator", "authors"], } result = {} for key, requested_name in requested.items(): if requested_name in fieldnames: result[key] = requested_name continue for alias in aliases[key]: if alias in lowered: result[key] = lowered[alias] break else: raise ValueError( f"could not find {key!r} column. Requested {requested_name!r}; " f"available columns: {fieldnames}" ) return result def load_year_metadata(args: argparse.Namespace) -> tuple[dict[str, dict[str, Any]], dict[str, str]]: with args.metadata_csv.open("r", encoding="utf-8-sig", errors="replace", newline="") as handle: reader = csv.DictReader(handle) if reader.fieldnames is None: raise ValueError(f"metadata CSV has no header: {args.metadata_csv}") columns = sniff_columns( reader.fieldnames, { "id": args.id_column, "publication_year": args.year_column, "title": args.metadata_title_column, "author": args.metadata_author_column, }, ) metadata: dict[str, dict[str, Any]] = {} for row in reader: book_id = normalize_id(row.get(columns["id"])) year = parse_year(row.get(columns["publication_year"])) if not book_id or year is None: continue metadata[book_id] = { "publication_year": year, "title": scalar(row.get(columns["title"])), "author": scalar(row.get(columns["author"])), } return metadata, columns def load_include_manifest(path: Path | None) -> tuple[list[str], dict[str, dict[str, Any]]]: if path is None: return [], {} summary = json.loads(path.read_text(encoding="utf-8")) seen: set[str] = set() include_order: list[str] = [] include_manifest: dict[str, dict[str, Any]] = {} for item in summary.get("books", []): book_id = normalize_id(item.get("gutenberg_id")) if book_id and book_id not in seen: seen.add(book_id) include_order.append(book_id) include_manifest[book_id] = item if not include_order: raise ValueError(f"--include-summary has no usable book IDs: {path}") return include_order, include_manifest def clean_text(text: str, strip_boilerplate: bool) -> str: text = text.replace("\r\n", "\n").replace("\r", "\n") if strip_boilerplate: for pattern in BOILERPLATE_PATTERNS: text = pattern.sub("\n", text) return text.strip() def row_ok(row: dict[str, Any], args: argparse.Namespace, metadata: dict[str, Any]) -> bool: if row_value(row, "language") not in set(args.languages): return False rights = scalar(row_value(row, "rights", "license")) if args.rights_contains and args.rights_contains.lower() not in rights.lower(): return False year = metadata["publication_year"] return args.min_year <= year <= args.max_year def main() -> None: args = parse_args() load_dataset = import_datasets() tokenizer = load_tokenizer(args.tokenizer_dir) year_metadata, columns = load_year_metadata(args) if not year_metadata: raise ValueError(f"no usable rows found in metadata CSV: {args.metadata_csv}") include_order, include_manifest = load_include_manifest(args.include_summary) include_ids = set(include_order) if include_order and args.append_existing: raise ValueError("--include-summary cannot be combined with --append-existing") if args.reuse_include_summary_token_counts and not include_order: raise ValueError("--reuse-include-summary-token-counts requires --include-summary") load_kwargs = { "split": args.split, "streaming": True, "trust_remote_code": args.trust_remote_code, } if args.config: dataset = load_dataset(args.dataset, args.config, **load_kwargs) else: dataset = load_dataset(args.dataset, **load_kwargs) args.out.parent.mkdir(parents=True, exist_ok=True) args.summary_out.parent.mkdir(parents=True, exist_ok=True) counters: Counter[str] = Counter() summaries: list[BookSummary] = [] included_lines: dict[str, str] = {} included_summaries: dict[str, BookSummary] = {} total_talkie_tokens = 0 existing_ids: set[str] = set() existing_counts: dict[str, int] | None = None for summary_path in args.exclude_summary: excluded_summary = json.loads(summary_path.read_text(encoding="utf-8")) existing_ids.update( normalize_id(item.get("gutenberg_id")) for item in excluded_summary.get("books", []) if item.get("gutenberg_id") is not None ) if args.append_existing: if not args.out.exists(): raise FileNotFoundError(f"--append-existing requires existing --out: {args.out}") if not args.summary_out.exists(): raise FileNotFoundError( f"--append-existing requires existing --summary-out: {args.summary_out}" ) existing_summary = json.loads(args.summary_out.read_text(encoding="utf-8")) existing_counts = dict(existing_summary.get("counts") or {}) summaries = [BookSummary(**item) for item in existing_summary.get("books", [])] existing_ids.update(item.gutenberg_id for item in summaries) total_talkie_tokens = int( existing_summary.get("total_talkie_tokens") or sum(item.talkie_tokens or 0 for item in summaries) ) output_mode = "a" if args.append_existing else "w" with args.out.open(output_mode, encoding="utf-8") as out_handle: for row in dataset: counters["seen"] += 1 book_id = normalize_id(row.get("id")) if include_ids and book_id not in include_ids: counters["skip_not_in_include_summary"] += 1 continue if include_ids and book_id in included_lines: counters["skip_existing"] += 1 continue if book_id in existing_ids: counters["skip_existing"] += 1 continue meta = year_metadata.get(book_id) if meta is None: counters["skip_missing_year_metadata"] += 1 continue if not row_ok(row, args, meta): counters["skip_filter"] += 1 continue source_text = scalar(row.get("text")) text = clean_text(source_text, args.strip_gutenberg_boilerplate) if len(text) < args.min_chars: counters["skip_short"] += 1 continue if args.max_chars_per_book > 0: text = text[: args.max_chars_per_book] talkie_tokens = None if tokenizer is not None: talkie_tokens = len(tokenizer.encode(text, add_special_tokens=False)) total_talkie_tokens += talkie_tokens elif args.reuse_include_summary_token_counts: manifest_tokens = include_manifest[book_id].get("talkie_tokens") if manifest_tokens is not None: talkie_tokens = int(manifest_tokens) total_talkie_tokens += talkie_tokens summary = BookSummary( gutenberg_id=book_id, title=scalar(row_value(row, "title")), author=scalar(row_value(row, "author")), publication_year=int(meta["publication_year"]), metadata_title=scalar(meta.get("title")), metadata_author=scalar(meta.get("author")), language=scalar(row_value(row, "language")), rights=scalar(row_value(row, "rights", "license")), release_date=scalar(row_value(row, "release_date", "added") or row.get("added")), source_chars=len(source_text), chars=len(text), talkie_tokens=talkie_tokens, ) line = json.dumps({"text": text, "meta": asdict(summary)}, ensure_ascii=False) if include_ids: included_lines[book_id] = line included_summaries[book_id] = summary else: summaries.append(summary) out_handle.write(line + "\n") counters["written"] += 1 print( json.dumps( { "written": counters["written"], "seen": counters["seen"], "id": book_id, "publication_year": summary.publication_year, "talkie_tokens": talkie_tokens, "title": summary.title[:120], }, ensure_ascii=False, sort_keys=True, ), flush=True, ) if include_ids and len(included_lines) == len(include_order): break if args.max_books and counters["written"] >= args.max_books: break if not include_ids: if args.target_talkie_tokens and total_talkie_tokens >= args.target_talkie_tokens: break if include_ids: missing = [book_id for book_id in include_order if book_id not in included_lines] if missing: preview = ", ".join(missing[:20]) raise RuntimeError( f"missing {len(missing)} IDs from --include-summary while rebuilding {args.out}: " f"{preview}" ) summaries = [included_summaries[book_id] for book_id in include_order] for book_id in include_order: out_handle.write(included_lines[book_id] + "\n") summary_obj = { "dataset": args.dataset, "config": args.config, "split": args.split, "metadata_csv": str(args.metadata_csv), "metadata_columns": columns, "filters": { "languages": args.languages, "min_year": args.min_year, "max_year": args.max_year, "rights_contains": args.rights_contains, "min_chars": args.min_chars, "strip_gutenberg_boilerplate": args.strip_gutenberg_boilerplate, }, "counts": dict(counters), "existing_counts": existing_counts, "total_talkie_tokens": total_talkie_tokens if tokenizer is not None or args.reuse_include_summary_token_counts else None, "books": [asdict(item) for item in summaries], } args.summary_out.write_text( json.dumps(summary_obj, ensure_ascii=False, indent=2, sort_keys=True) + "\n", encoding="utf-8", ) print(f"wrote {args.out}", file=sys.stderr) print(f"wrote {args.summary_out}", file=sys.stderr) if __name__ == "__main__": main()