paper-tex-corpus / scripts /build_dataset.py
kadubon's picture
Explain corpus purpose and research themes
5f94652 verified
Raw
History Blame Contribute Delete
54.8 kB
from __future__ import annotations
import argparse
import csv
import io
import json
import os
import re
import shutil
import subprocess
import sys
import urllib.request
import zipfile
from collections import defaultdict
from datetime import date
from difflib import SequenceMatcher
from pathlib import Path, PurePosixPath
from typing import Any
import pyarrow as pa
import pyarrow.parquet as pq
from common import (
Archive,
TexEntry,
archive_stem_title,
brace_balance,
canonical_json,
clean_tex_label,
content_size_category,
extract_braced_command,
extract_document_body,
find_secret_patterns,
find_unsafe_tex_references,
make_chunks,
mime_type_for,
normalize_title,
sha256_bytes,
sha256_file,
write_text_lf,
)
DEFAULT_CATALOG_URL = "https://kadubon.github.io/github.io/research-catalog.json"
REPO_ID = "kadubon/paper-tex-corpus"
VERSION = "1.0.0"
SENTINEL = ".paper-tex-corpus-build"
PAPERS_SCHEMA = pa.schema(
[
("paper_id", pa.string()),
("doi", pa.string()),
("title", pa.string()),
("authors", pa.list_(pa.string())),
("date_published", pa.string()),
("abstract", pa.string()),
("keywords", pa.list_(pa.string())),
("language", pa.string()),
("genre", pa.string()),
("canonical_url", pa.string()),
("works_url", pa.string()),
("tex_source", pa.large_string()),
("archive_path", pa.string()),
("archive_sha256", pa.string()),
("tex_entry", pa.string()),
("tex_sha256", pa.string()),
("source_archive_paths", pa.list_(pa.string())),
("source_archive_sha256s", pa.list_(pa.string())),
("source_tex_entries", pa.list_(pa.string())),
("source_tex_sha256s", pa.list_(pa.string())),
("mapping_status", pa.string()),
("content_status", pa.string()),
("quality_flags", pa.list_(pa.string())),
]
)
ARCHIVE_ONLY_SCHEMA = pa.schema(
[
("record_id", pa.string()),
("title", pa.string()),
("authors", pa.list_(pa.string())),
("date_raw", pa.string()),
("language", pa.string()),
("tex_source", pa.large_string()),
("archive_path", pa.string()),
("archive_sha256", pa.string()),
("tex_entry", pa.string()),
("tex_sha256", pa.string()),
("mapping_status", pa.string()),
("candidate_dois", pa.list_(pa.string())),
("content_status", pa.string()),
("duplicate_of_archive", pa.string()),
("quality_flags", pa.list_(pa.string())),
]
)
CHUNKS_SCHEMA = pa.schema(
[
("chunk_id", pa.string()),
("paper_id", pa.string()),
("doi", pa.string()),
("title", pa.string()),
("partition", pa.string()),
("source_id", pa.string()),
("source_archive_path", pa.string()),
("tex_entry", pa.string()),
("section_path", pa.list_(pa.string())),
("section_title", pa.string()),
("chunk_index", pa.int32()),
("char_start", pa.int64()),
("char_end", pa.int64()),
("chunk_tex", pa.large_string()),
("chunk_text", pa.large_string()),
("char_count", pa.int32()),
("quality_flags", pa.list_(pa.string())),
]
)
ENTRY_SCHEMA = pa.struct(
[
("path", pa.string()),
("size", pa.int64()),
("compressed_size", pa.int64()),
("crc32", pa.string()),
("sha256", pa.string()),
("media_type", pa.string()),
("is_tex", pa.bool_()),
]
)
ARCHIVES_SCHEMA = pa.schema(
[
("archive_id", pa.string()),
("archive_path", pa.string()),
("archive_filename", pa.string()),
("archive_size", pa.int64()),
("archive_sha256", pa.string()),
("mapped_dois", pa.list_(pa.string())),
("candidate_dois", pa.list_(pa.string())),
("mapping_status", pa.string()),
("mapping_method", pa.string()),
("mapping_score", pa.float64()),
("content_status", pa.string()),
("primary_tex_entry", pa.string()),
("primary_tex_sha256", pa.string()),
("duplicate_of_archive", pa.string()),
("entries", pa.list_(ENTRY_SCHEMA)),
("quality_flags", pa.list_(pa.string())),
]
)
def parse_args() -> argparse.Namespace:
parser = argparse.ArgumentParser(
description="Build the Hugging Face-optimized K. Takahashi TeX corpus."
)
parser.add_argument("--source", type=Path, required=True)
parser.add_argument("--output", type=Path, required=True)
catalog = parser.add_mutually_exclusive_group()
catalog.add_argument("--catalog-file", type=Path)
catalog.add_argument("--catalog-url", default=DEFAULT_CATALOG_URL)
parser.add_argument(
"--manual-mappings",
type=Path,
default=Path(__file__).resolve().parents[1]
/ "config"
/ "manual_mappings.json",
)
return parser.parse_args()
def ensure_safe_workspace(source: Path, output: Path) -> tuple[Path, Path]:
source = source.resolve()
output = output.resolve()
if not source.is_dir():
raise SystemExit(f"Source directory does not exist: {source}")
if output == source or output in source.parents or source in output.parents:
raise SystemExit("Source and output must be separate, non-nested directories.")
output.mkdir(parents=True, exist_ok=True)
sentinel = output / SENTINEL
if not sentinel.exists():
if any(output.iterdir()):
raise SystemExit(
f"Refusing to build into non-empty directory without {SENTINEL}: {output}"
)
write_text_lf(sentinel, "This sentinel marks a generated paper-tex-corpus workspace.\n")
for generated in ("data", "raw"):
target = output / generated
if target.exists():
shutil.rmtree(target)
for generated_file in (
"metadata/research-catalog.json",
"metadata/catalog-crosswalk.csv",
"metadata/source-state.json",
"checksums.sha256",
"build-report.json",
"README.md",
"LICENSE",
"CITATION.cff",
):
target = output / generated_file
if target.exists():
target.unlink()
return source, output
def git_output(source: Path, *args: str) -> str:
result = subprocess.run(
["git", "-C", str(source), *args],
check=True,
text=True,
encoding="utf-8",
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
)
return result.stdout.strip()
def source_state(source: Path) -> dict[str, Any]:
status = git_output(source, "status", "--porcelain")
if status:
raise SystemExit("Source repository is dirty; refusing a non-reproducible build.")
return {
"source_repository": git_output(source, "remote", "get-url", "origin"),
"source_commit": git_output(source, "rev-parse", "HEAD"),
"source_commit_date": git_output(
source, "show", "-s", "--format=%cI", "HEAD"
),
"source_branch": git_output(source, "branch", "--show-current"),
}
def load_catalog(args: argparse.Namespace) -> tuple[dict[str, Any], str]:
if args.catalog_file:
raw = args.catalog_file.read_bytes()
origin = str(args.catalog_file.resolve())
else:
with urllib.request.urlopen(args.catalog_url, timeout=60) as response:
raw = response.read()
origin = args.catalog_url
catalog = json.loads(raw.decode("utf-8"))
if catalog.get("record_count") != len(catalog.get("records", [])):
raise SystemExit("Catalog record_count does not match records length.")
return catalog, origin
def tex_entry_from_bytes(
path: str,
raw: bytes,
compressed_size: int,
crc: int,
) -> TexEntry:
flags: list[str] = []
try:
text = raw.decode("utf-8")
except UnicodeDecodeError:
text = raw.decode("utf-8", errors="replace")
flags.append("utf8_decode_replacement")
title_raw = extract_braced_command(text, "title")
author_raw = extract_braced_command(text, "author")
date_raw = extract_braced_command(text, "date")
stripped = text.strip()
if len(stripped) <= 2 or not re.search(r"\\begin\s*\{document\}", text):
content_status = "invalid_source"
else:
content_status = "valid"
if not title_raw:
flags.append("missing_title_command")
if not author_raw:
flags.append("missing_author_command")
if not re.search(r"\\begin\s*\{abstract\}", text):
flags.append("missing_abstract_environment")
balance = brace_balance(text)
if balance:
flags.append(f"brace_imbalance:{balance}")
if re.search(r"\\(?:immediate\s*)?\\write18", text):
flags.append("shell_escape_command")
unsafe_references = find_unsafe_tex_references(text)
if unsafe_references:
flags.append("unsafe_external_path_reference")
secret_hits = find_secret_patterns(text)
if secret_hits:
flags.extend(f"secret_pattern:{name}" for name in secret_hits)
return TexEntry(
path=path,
size=len(raw),
compressed_size=compressed_size,
crc32=f"{crc:08x}",
sha256=sha256_bytes(raw),
text=text,
title_raw=title_raw,
title_clean=clean_tex_label(title_raw),
author_raw=author_raw,
author_clean=clean_tex_label(author_raw),
date_raw=clean_tex_label(date_raw),
doi_candidates=sorted(
{
match.group(0).rstrip(".,;)")
for match in DOI_RE.finditer(text)
}
),
content_status=content_status,
quality_flags=sorted(set(flags)),
)
DOI_RE = re.compile(r"10\.\d{4,9}/[-._;()/:A-Z0-9]+", re.IGNORECASE)
def choose_primary_tex(filename: str, tex_entries: list[TexEntry]) -> int | None:
if not tex_entries:
return None
stem_norm = normalize_title(archive_stem_title(filename))
ranked: list[tuple[float, int, int]] = []
for index, entry in enumerate(tex_entries):
title_norm = normalize_title(entry.title_clean or Path(entry.path).stem)
title_score = SequenceMatcher(None, stem_norm, title_norm).ratio()
path_score = SequenceMatcher(
None, stem_norm, normalize_title(Path(entry.path).stem)
).ratio()
validity = 1 if entry.content_status == "valid" else 0
ranked.append((validity * 10 + max(title_score, path_score), entry.size, index))
return max(ranked)[2]
def scan_archives(source: Path, output: Path) -> list[Archive]:
archives: list[Archive] = []
raw_dir = output / "raw"
raw_dir.mkdir(parents=True, exist_ok=True)
for source_zip in sorted(source.glob("*.zip"), key=lambda item: item.name.lower()):
destination = raw_dir / source_zip.name
shutil.copyfile(source_zip, destination)
archive_hash = sha256_file(source_zip)
if sha256_file(destination) != archive_hash:
raise SystemExit(f"Raw copy hash mismatch: {source_zip.name}")
entries: list[dict[str, Any]] = []
tex_entries: list[TexEntry] = []
archive_flags: list[str] = []
try:
with zipfile.ZipFile(source_zip) as archive:
bad_member = archive.testzip()
if bad_member:
raise SystemExit(
f"CRC failure in {source_zip.name}: {bad_member}"
)
for info in archive.infolist():
member = PurePosixPath(info.filename.replace("\\", "/"))
if (
member.is_absolute()
or ".." in member.parts
or re.match(r"^[A-Za-z]:", info.filename)
):
raise SystemExit(
f"Unsafe ZIP member path in {source_zip.name}: {info.filename}"
)
if info.is_dir():
continue
raw = archive.read(info)
entry = {
"path": info.filename,
"size": len(raw),
"compressed_size": info.compress_size,
"crc32": f"{info.CRC:08x}",
"sha256": sha256_bytes(raw),
"media_type": mime_type_for(info.filename),
"is_tex": Path(info.filename).suffix.lower() == ".tex",
}
entries.append(entry)
if entry["is_tex"]:
tex_entries.append(
tex_entry_from_bytes(
info.filename,
raw,
info.compress_size,
info.CRC,
)
)
except zipfile.BadZipFile as error:
raise SystemExit(f"Broken ZIP {source_zip.name}: {error}") from error
primary_index = choose_primary_tex(source_zip.name, tex_entries)
if len(tex_entries) > 1:
archive_flags.append("multiple_tex_entries")
if not tex_entries:
archive_flags.append("missing_tex_entry")
if any(
flag.startswith("secret_pattern:")
for tex in tex_entries
for flag in tex.quality_flags
):
raise SystemExit(f"Secret-like pattern found in {source_zip.name}")
archives.append(
Archive(
filename=source_zip.name,
source_path=source_zip,
raw_path=f"raw/{source_zip.name}",
size=source_zip.stat().st_size,
sha256=archive_hash,
entries=entries,
tex_entries=tex_entries,
primary_tex_index=primary_index,
quality_flags=sorted(set(archive_flags)),
)
)
return archives
def title_candidates(archive: Archive) -> list[str]:
values = [archive_stem_title(archive.filename)]
if archive.primary_tex:
values.extend(
[
archive.primary_tex.title_clean,
clean_tex_label(Path(archive.primary_tex.path).stem),
]
)
return [value for value in values if normalize_title(value)]
def title_score(archive: Archive, catalog_title: str) -> float:
target = normalize_title(catalog_title)
scores: list[float] = []
for candidate in title_candidates(archive):
value = normalize_title(candidate)
score = SequenceMatcher(None, value, target).ratio()
if (
min(len(value), len(target)) >= 20
and (value in target or target in value)
):
length_ratio = min(len(value), len(target)) / max(len(value), len(target))
score = max(score, min(1.0, length_ratio + 0.12))
scores.append(score)
return max(scores, default=0.0)
def apply_mappings(
archives: list[Archive],
papers: list[dict[str, Any]],
manual_path: Path,
) -> None:
by_doi = {paper["doi"].lower(): paper for paper in papers}
mapping_config = json.loads(manual_path.read_text(encoding="utf-8"))
manual = mapping_config["mappings"]
forced_archive_only = mapping_config.get("archive_only", {})
for archive in archives:
if archive.filename not in forced_archive_only:
continue
decision = forced_archive_only[archive.filename]
archive.mapping_method = "explicit_archive_only"
archive.mapping_status = "archive_only"
archive.mapping_score = 0.0
external_doi = (decision.get("external_doi") or "").lower()
archive.quality_flags.append(
f"external_record_not_in_catalog:{external_doi}"
if external_doi
else "no_verified_external_record"
)
archive.quality_flags = sorted(set(archive.quality_flags))
for archive in archives:
if archive.filename not in manual:
continue
dois = [doi.lower() for doi in manual[archive.filename]]
missing = [doi for doi in dois if doi not in by_doi]
if missing:
raise SystemExit(
f"Manual mapping references missing catalog DOI(s): {missing}"
)
archive.mapped_dois = dois
archive.mapping_method = "manual_evidence"
archive.mapping_score = max(
title_score(archive, by_doi[doi]["title"]) for doi in dois
)
archive.mapping_status = "matched"
normalized_title_to_dois: dict[str, list[str]] = defaultdict(list)
for paper in papers:
normalized_title_to_dois[normalize_title(paper["title"])].append(
paper["doi"].lower()
)
for archive in archives:
if (
archive.mapped_dois
or archive.mapping_method == "explicit_archive_only"
or not archive.primary_tex
):
continue
candidate_norms = {
normalize_title(candidate) for candidate in title_candidates(archive)
}
exact_dois = sorted(
{
doi
for norm in candidate_norms
for doi in normalized_title_to_dois.get(norm, [])
}
)
if len(exact_dois) == 1:
archive.mapped_dois = exact_dois
archive.mapping_method = "exact_normalized_title"
archive.mapping_score = 1.0
archive.mapping_status = "matched"
continue
body_front = archive.primary_tex.text
bibliography = re.search(
r"\\begin\s*\{thebibliography\}|\\bibliography\s*\{",
body_front,
)
if bibliography:
body_front = body_front[: bibliography.start()]
body_front = body_front[:40_000]
front_dois = {
match.group(0).rstrip(".,;)").lower()
for match in DOI_RE.finditer(body_front)
}
intersection = sorted(front_dois.intersection(by_doi))
if len(intersection) == 1:
doi = intersection[0]
score = title_score(archive, by_doi[doi]["title"])
if score >= 0.92:
archive.mapped_dois = [doi]
archive.mapping_method = "doi_in_source"
archive.mapping_score = score
archive.mapping_status = "matched"
continue
scores = sorted(
(
(title_score(archive, paper["title"]), paper["doi"].lower())
for paper in papers
),
reverse=True,
)
best_score, best_doi = scores[0]
second_score = scores[1][0]
archive.mapping_score = best_score
archive.candidate_dois = [best_doi]
if best_score >= 0.84 and best_score - second_score >= 0.06:
archive.mapped_dois = [best_doi]
archive.mapping_method = "strong_unique_title"
archive.mapping_status = "matched"
elif best_score >= 0.70:
archive.mapping_method = "ambiguous_title_candidate"
archive.mapping_status = "ambiguous"
else:
archive.mapping_method = "unresolved"
archive.mapping_status = "archive_only"
duplicate_groups: dict[str, list[Archive]] = defaultdict(list)
for archive in archives:
if archive.primary_tex:
duplicate_groups[archive.primary_tex.sha256].append(archive)
for group in duplicate_groups.values():
if len(group) < 2:
continue
representative = sorted(
group,
key=lambda archive: (
0 if archive.mapped_dois else 1,
1 if re.search(r"\(\d+\)\.zip$", archive.filename) else 0,
archive.filename.lower(),
),
)[0]
for duplicate in group:
if duplicate is representative:
continue
duplicate.duplicate_of_archive = representative.raw_path
if not duplicate.mapped_dois and representative.mapped_dois:
duplicate.mapped_dois = list(representative.mapped_dois)
duplicate.mapping_method = "exact_content_duplicate"
duplicate.mapping_score = representative.mapping_score
duplicate.mapping_status = "matched"
def author_list(author_clean: str) -> list[str]:
if not author_clean:
return []
if "takahashi" in author_clean.lower():
return ["K. Takahashi"]
return [author_clean]
def build_rows(
archives: list[Archive],
papers: list[dict[str, Any]],
) -> tuple[
list[dict[str, Any]],
list[dict[str, Any]],
list[dict[str, Any]],
list[dict[str, Any]],
]:
archives_by_doi: dict[str, list[Archive]] = defaultdict(list)
ambiguous_by_doi: dict[str, list[Archive]] = defaultdict(list)
for archive in archives:
for doi in archive.mapped_dois:
archives_by_doi[doi].append(archive)
if archive.mapping_status == "ambiguous":
for doi in archive.candidate_dois:
ambiguous_by_doi[doi].append(archive)
paper_rows: list[dict[str, Any]] = []
catalog_by_doi = {paper["doi"].lower(): paper for paper in papers}
for paper in papers:
doi = paper["doi"].lower()
sources = sorted(
archives_by_doi.get(doi, []),
key=lambda archive: (
1 if archive.content_status != "valid" else 0,
1 if archive.duplicate_of_archive else 0,
1 if re.search(r"\(\d+\)\.zip$", archive.filename) else 0,
-archive.mapping_score,
archive.filename.lower(),
),
)
usable = [
archive
for archive in sources
if archive.primary_tex
and archive.primary_tex.content_status == "valid"
and not archive.duplicate_of_archive
]
primary = usable[0] if usable else (sources[0] if sources else None)
primary_tex = primary.primary_tex if primary else None
flags = {
flag
for source in sources
for flag in [
*source.quality_flags,
*(source.primary_tex.quality_flags if source.primary_tex else []),
]
}
if len(usable) > 1:
flags.add("multiple_source_manuscripts")
if not sources:
flags.add("metadata_only")
if not sources and ambiguous_by_doi.get(doi):
mapping_status = "ambiguous"
flags.add("ambiguous_source_candidate")
elif not sources:
mapping_status = "metadata_only"
elif len(usable) > 1:
mapping_status = "multi_source"
else:
mapping_status = primary.mapping_method
if not sources:
content_status = "metadata_only"
elif usable:
content_status = "valid"
else:
content_status = "invalid_source"
paper_rows.append(
{
"paper_id": doi,
"doi": doi,
"title": paper["title"],
"authors": list(paper.get("authors") or []),
"date_published": paper.get("date_published") or "",
"abstract": paper.get("abstract") or "",
"keywords": list(paper.get("keywords") or []),
"language": paper.get("language") or "en",
"genre": paper.get("genre") or "",
"canonical_url": paper.get("canonical_url")
or paper.get("doi_url")
or "",
"works_url": paper.get("local_record_url") or paper.get("id") or "",
"tex_source": primary_tex.text if primary_tex else "",
"archive_path": primary.raw_path if primary else "",
"archive_sha256": primary.sha256 if primary else "",
"tex_entry": primary_tex.path if primary_tex else "",
"tex_sha256": primary_tex.sha256 if primary_tex else "",
"source_archive_paths": [source.raw_path for source in sources],
"source_archive_sha256s": [source.sha256 for source in sources],
"source_tex_entries": [
source.primary_tex.path if source.primary_tex else ""
for source in sources
],
"source_tex_sha256s": [
source.primary_tex.sha256 if source.primary_tex else ""
for source in sources
],
"mapping_status": mapping_status,
"content_status": content_status,
"quality_flags": sorted(flags),
}
)
archive_only_rows: list[dict[str, Any]] = []
for archive in archives:
if archive.mapped_dois:
continue
tex = archive.primary_tex
flags = set(archive.quality_flags)
if tex:
flags.update(tex.quality_flags)
archive_only_rows.append(
{
"record_id": f"archive:{archive.sha256}",
"title": (
tex.title_clean
if tex and tex.title_clean
else archive_stem_title(archive.filename)
),
"authors": author_list(tex.author_clean if tex else ""),
"date_raw": tex.date_raw if tex else "",
"language": "en",
"tex_source": tex.text if tex else "",
"archive_path": archive.raw_path,
"archive_sha256": archive.sha256,
"tex_entry": tex.path if tex else "",
"tex_sha256": tex.sha256 if tex else "",
"mapping_status": archive.mapping_status,
"candidate_dois": archive.candidate_dois,
"content_status": archive.content_status,
"duplicate_of_archive": archive.duplicate_of_archive,
"quality_flags": sorted(flags),
}
)
chunk_rows: list[dict[str, Any]] = []
seen_tex_hashes: set[str] = set()
for archive in archives:
tex = archive.primary_tex
if (
tex is None
or tex.content_status != "valid"
or tex.sha256 in seen_tex_hashes
):
continue
seen_tex_hashes.add(tex.sha256)
doi = archive.mapped_dois[0] if archive.mapped_dois else ""
if doi:
paper = catalog_by_doi[doi]
paper_id = doi
title = paper["title"]
partition = "papers"
else:
paper_id = f"archive:{archive.sha256}"
title = tex.title_clean or archive_stem_title(archive.filename)
partition = "archive_only"
body = extract_document_body(tex.text)
for index, chunk in enumerate(make_chunks(body)):
chunk_hash = sha256_bytes(
(
tex.sha256
+ "\0"
+ str(index)
+ "\0"
+ chunk["chunk_tex"]
).encode("utf-8")
)
flags = sorted(
set(archive.quality_flags)
| set(tex.quality_flags)
| set(chunk["quality_flags"])
)
chunk_rows.append(
{
"chunk_id": f"chunk:{chunk_hash}",
"paper_id": paper_id,
"doi": doi,
"title": title,
"partition": partition,
"source_id": f"sha256:{tex.sha256}",
"source_archive_path": archive.raw_path,
"tex_entry": tex.path,
"section_path": chunk["section_path"],
"section_title": chunk["section_title"],
"chunk_index": index,
"char_start": chunk["char_start"],
"char_end": chunk["char_end"],
"chunk_tex": chunk["chunk_tex"],
"chunk_text": chunk["chunk_text"],
"char_count": len(chunk["chunk_tex"]),
"quality_flags": flags,
}
)
archive_rows: list[dict[str, Any]] = []
for archive in archives:
primary = archive.primary_tex
flags = set(archive.quality_flags)
if primary:
flags.update(primary.quality_flags)
archive_rows.append(
{
"archive_id": f"sha256:{archive.sha256}",
"archive_path": archive.raw_path,
"archive_filename": archive.filename,
"archive_size": archive.size,
"archive_sha256": archive.sha256,
"mapped_dois": archive.mapped_dois,
"candidate_dois": archive.candidate_dois,
"mapping_status": archive.mapping_status,
"mapping_method": archive.mapping_method,
"mapping_score": archive.mapping_score,
"content_status": archive.content_status,
"primary_tex_entry": primary.path if primary else "",
"primary_tex_sha256": primary.sha256 if primary else "",
"duplicate_of_archive": archive.duplicate_of_archive,
"entries": archive.entries,
"quality_flags": sorted(flags),
}
)
return paper_rows, archive_only_rows, chunk_rows, archive_rows
def write_parquet(
output: Path,
config: str,
rows: list[dict[str, Any]],
schema: pa.Schema,
row_group_size: int,
) -> Path:
target = output / "data" / config / "train-00000-of-00001.parquet"
target.parent.mkdir(parents=True, exist_ok=True)
table = pa.Table.from_pylist(rows, schema=schema)
pq.write_table(
table,
target,
compression="zstd",
compression_level=9,
use_dictionary=True,
row_group_size=row_group_size,
write_page_index=True,
data_page_version="2.0",
version="2.6",
)
return target
def write_crosswalk(output: Path, archives: list[Archive]) -> None:
target = output / "metadata" / "catalog-crosswalk.csv"
target.parent.mkdir(parents=True, exist_ok=True)
buffer = io.StringIO(newline="")
writer = csv.DictWriter(
buffer,
fieldnames=[
"archive_filename",
"archive_sha256",
"mapped_dois",
"candidate_dois",
"mapping_status",
"mapping_method",
"mapping_score",
"content_status",
"primary_tex_entry",
"primary_tex_sha256",
"duplicate_of_archive",
"quality_flags",
],
lineterminator="\n",
)
writer.writeheader()
for archive in archives:
primary = archive.primary_tex
flags = sorted(
set(archive.quality_flags)
| set(primary.quality_flags if primary else [])
)
writer.writerow(
{
"archive_filename": archive.filename,
"archive_sha256": archive.sha256,
"mapped_dois": "|".join(archive.mapped_dois),
"candidate_dois": "|".join(archive.candidate_dois),
"mapping_status": archive.mapping_status,
"mapping_method": archive.mapping_method,
"mapping_score": f"{archive.mapping_score:.6f}",
"content_status": archive.content_status,
"primary_tex_entry": primary.path if primary else "",
"primary_tex_sha256": primary.sha256 if primary else "",
"duplicate_of_archive": archive.duplicate_of_archive,
"quality_flags": "|".join(flags),
}
)
write_text_lf(target, buffer.getvalue())
def license_text() -> str:
return """Creative Commons Attribution 4.0 International (CC BY 4.0)
SPDX-License-Identifier: CC-BY-4.0
This work is licensed under the Creative Commons Attribution 4.0 International License.
To view a copy of this license, visit:
https://creativecommons.org/licenses/by/4.0/
or:
https://creativecommons.org/licenses/by/4.0/legalcode
NO WARRANTY; LIMITATION OF LIABILITY.
This material is provided "as is", without warranty of any kind. The author shall not
be liable for any damages or other liability arising from, out of, or in connection
with the material or the use or other dealings in the material.
"""
def citation_text(source_date: str) -> str:
release_date = source_date[:10]
year = release_date[:4]
return f"""cff-version: 1.2.0
message: "If you use this dataset, please cite the corpus and the individual paper DOI(s)."
title: "K. Takahashi Paper TeX Corpus"
type: dataset
authors:
- family-names: "Takahashi"
given-names: "K."
orcid: "https://orcid.org/0009-0004-4273-3365"
version: "{VERSION}"
date-released: "{release_date}"
license: CC-BY-4.0
repository-code: "https://huggingface.co/datasets/{REPO_ID}"
url: "https://huggingface.co/datasets/{REPO_ID}"
preferred-citation:
type: dataset
authors:
- family-names: "Takahashi"
given-names: "K."
orcid: "https://orcid.org/0009-0004-4273-3365"
title: "K. Takahashi Paper TeX Corpus"
year: {year}
version: "{VERSION}"
url: "https://huggingface.co/datasets/{REPO_ID}"
"""
def readme_text(report: dict[str, Any]) -> str:
counts = report["counts"]
size_category = content_size_category(
counts["papers"]
+ counts["archive_only"]
+ counts["chunks"]
+ counts["archives"]
)
return f"""---
pretty_name: "K. Takahashi Paper TeX Corpus"
short_description: "A provenance-rich TeX corpus of K. Takahashi's research papers, with DOI metadata, section-aware RAG chunks, original ZIP archives, and checksums."
license: cc-by-4.0
language:
- en
task_categories:
- text-retrieval
- document-question-answering
- text-generation
tags:
- latex
- tex
- scientific-papers
- research-corpus
- mathematics
- artificial-intelligence
- rag
- provenance
- reproducible-research
size_categories:
- {size_category}
configs:
- config_name: papers
default: true
data_files:
- split: train
path: data/papers/train-*.parquet
- config_name: archive_only
data_files:
- split: train
path: data/archive_only/train-*.parquet
- config_name: chunks
data_files:
- split: train
path: data/chunks/train-*.parquet
- config_name: archives
data_files:
- split: train
path: data/archives/train-*.parquet
---
# K. Takahashi Paper TeX Corpus
This dataset publishes K. Takahashi's TeX research corpus in four complementary views:
canonical DOI records, uncatalogued archive records, section-aware retrieval chunks, and
an inventory of the original source ZIPs. The unmodified ZIP files are available under
`raw/`, while all viewer-facing data is provided directly as Parquet.
## What this dataset is for
The purpose of this dataset is to make a collection of scholarly TeX sources usable as a
**searchable, citable, and auditable research corpus**. A directory of ZIP files preserves
the manuscripts, but it is difficult to search across papers, connect a passage to its DOI,
or determine which file and version produced a result. This dataset adds those missing
layers without replacing the original sources:
- a **bibliographic layer** links each catalogued work to its DOI, title, abstract,
publication date, keywords, and canonical URL;
- a **source layer** preserves the full TeX text and byte-identical source ZIP so that a
result can be inspected in its original context;
- a **retrieval layer** supplies section-aware chunks that retain TeX mathematics and
avoid splitting structural environments where possible; and
- a **provenance layer** records checksums, archive members, mappings, duplicate
relationships, and quality flags so that downstream results can be traced and rebuilt.
The intended outcome is not merely easier downloading. It is a reproducible path from
**finding a relevant passage**, to **identifying the paper and DOI**, to **checking the
underlying TeX source and archive**. This is useful when answers, search results, or corpus
statistics need evidence that can be followed back to a specific scholarly document.
## Research content overview
The papers form a connected, theory-oriented research program on how autonomous and
self-modifying intelligent systems can remain viable, interpretable, governable, and
physically grounded when no infallible external evaluator is available. The corpus asks
how claims about intelligence, safety, autonomy, value, persistence, or improvement can
be stated in operational terms and checked using finite observations, explicit
assumptions, resource constraints, and reproducible evidence.
Major, overlapping research strands include:
- **Self-organizing and self-improving intelligence.** Early and continuing papers study
computational autopoiesis, active inference, collective adaptive intelligence,
teleogenesis, and architectures that can revise their own models or organization while
preserving specified viability or value constraints.
- **Observable-only and "no-meta" assurance.** A large part of the corpus examines agents
that cannot rely on a trusted meta-judge. It develops audit gates, proof- or
evidence-carrying claims, typed contracts, replayable records, provenance rules,
fail-closed controls, and institutional mechanisms for deciding what can be supported
from observable data.
- **Persistence, semantics, observation, and memory.** Papers analyze how identity,
meaning, values, and predictive organization behave under coarse-graining,
self-modification, finite context, partial logging, ontology drift, and non-Markovian
memory. Related work studies semantic phase transitions and limits on stable
representation.
- **Physical and thermodynamic constraints.** The research treats computation and agency
as processes embedded in open physical systems. Topics include free-energy and
entropy-production principles, exergy and resource accounting, energy-memory-compute
trade-offs, stochastic thermodynamics, and physically explicit boundaries and ledgers.
- **Mathematical structures for comparison and dynamics.** The corpus uses category
theory, information geometry, optimal transport and Hellinger--Kantorovich/Bures
geometry, gradient flows, dynamical systems, control theory, information theory, and
causal inference to compare models and describe change across scales.
- **AI systems, scaling, and multi-agent operation.** Applied theoretical papers address
LLM routing, inference reuse, memory telemetry, long-running agents, training
bottlenecks, silent data corruption, compute and I/O limits, multi-agent coordination,
and the conditions under which distributed inference or verification is beneficial.
- **Governance, welfare, and human--AI coexistence.** Other papers connect the technical
framework to rights, consent, non-coercive assistance, public claim certification,
institutional accountability, work and welfare, benevolent propagation, and
human--AI or organizational systems.
Across the collection, the emphasis shifts from broad architectures and axiomatic
proposals for self-organizing intelligence toward increasingly operational frameworks
based on measurable interfaces, causal identification, uncertainty sets, runtime
monitoring, physical accounting, and machine-checkable certificates. This is a thematic
guide, not a claim that every paper uses all of these concepts or that the proposed
theories have been empirically validated. The authoritative description of each work is
its catalog title, abstract, keywords, and linked DOI record.
## Dataset snapshot
| Item | Count |
|---|---:|
| Canonical scholarly records (`papers`) | {counts["papers"]} |
| Uncatalogued or unresolved records (`archive_only`) | {counts["archive_only"]} |
| Retrieval chunks (`chunks`) | {counts["chunks"]} |
| Original ZIP archives (`archives`) | {counts["archives"]} |
| TeX entries inside ZIPs | {counts["tex_entries"]} |
| Non-TeX auxiliary entries | {counts["auxiliary_entries"]} |
| Invalid primary TeX sources | {counts["invalid_sources"]} |
| Exact duplicate primary TeX archives | {counts["duplicate_archives"]} |
Source snapshot:
- TeX archive commit: `{report["source"]["source_commit"]}`
- Research catalog state: `{report["catalog"]["source_state_date"]}`
- Dataset release: `v{VERSION}`
## Which config should I start with?
All configs have one `train` split representing the complete corpus; `train` does not mean
that the records have been assigned to a machine-learning training partition.
| If you want to... | Start with | What one row represents |
|---|---|---|
| browse papers, join metadata by DOI, or retrieve a complete manuscript | `papers` | one canonical catalog record |
| build search, RAG, ranking, or embedding experiments | `chunks` | one section-aware TeX/text fragment |
| verify files, hashes, members, mappings, or preservation state | `archives` | one original ZIP archive |
| include older, supplementary, derivative, or unresolved sources | `archive_only` | one non-catalogued source record |
For most document-level analysis, begin with `papers`. For retrieval systems, begin with
`chunks` and use its paper/document identifier and DOI fields to join back to `papers`.
Use `archives` when exact source provenance matters. Add `archive_only` only when coverage
beyond the current publication catalog is required.
## Configs
### `papers` (default)
One row per canonical scholarly DOI in the machine-readable publication catalog. Catalog
metadata is authoritative. Source fields are empty when no TeX source can be established
without guessing. A DOI can point to multiple component source manuscripts; the primary
source is kept in the singular fields and every source is listed in the `source_*` arrays.
### `archive_only`
ZIPs that are not safely attributable to a current catalog DOI. These include older
versions, supplements, derivative manuscripts, and unresolved title candidates. No DOI
is inferred for these rows.
### `chunks`
Deterministic, section-aware chunks built from unique valid primary TeX sources. Chunking
targets about 4,000 characters, allows up to 6,000 characters, and reuses up to 400
characters of complete trailing blocks. The pipeline does not split equation, theorem,
proof, or verbatim environments. `char_start` and `char_end` refer to the comment-stripped
document body. Both the original TeX fragment and a conservative readable projection are
included.
### `archives`
One row per original ZIP. It records SHA-256 checksums, member metadata, DOI mappings,
duplicate relationships, and quality flags. The `raw/*.zip` files are byte-for-byte copies
of the source backup.
## Quick use
```python
from datasets import load_dataset
papers = load_dataset("{REPO_ID}", "papers", split="train")
chunks = load_dataset("{REPO_ID}", "chunks", split="train")
print(papers[0]["title"], papers[0]["doi"])
print(chunks[0]["section_title"], chunks[0]["chunk_text"][:500])
```
DuckDB can query the Parquet files directly:
```sql
SELECT doi, title, mapping_status
FROM read_parquet(
'https://huggingface.co/datasets/{REPO_ID}/resolve/main/data/papers/train-00000-of-00001.parquet'
)
LIMIT 10;
```
## Provenance and mapping
Bibliographic metadata comes from the publication index and its
[`research-catalog.json`](https://kadubon.github.io/github.io/research-catalog.json).
Mappings use, in order, explicit evidence recorded in `config/manual_mappings.json`, a
unique DOI in the manuscript front matter, exact normalized titles, or a strong unique
title match. Similarity-only candidates below the acceptance threshold remain
`ambiguous` or `archive_only`. The complete decision record is
`metadata/catalog-crosswalk.csv`.
`metadata/source-state.json`, `build-report.json`, and `checksums.sha256` make the release
auditable. `scripts/build_dataset.py` regenerates all Parquet files and raw copies;
`scripts/validate_dataset.py` performs structural, checksum, security-pattern,
cross-config, PyArrow, DuckDB, and optional 🤗 Datasets checks. `CITATION.cff` provides
machine-readable corpus citation metadata.
## Practical use cases
### Citation-grounded search and RAG
Index `chunk_text` for readable retrieval or `chunk_tex` when exact TeX syntax matters.
After retrieval, carry the DOI, paper/document identifier, section path, and position into
the application response. A user or evaluator can then open the corresponding `papers`
row, inspect the complete `tex_source`, and follow `canonical_url` to the publication.
This structure supports citation-grounded systems, but the dataset does not itself verify
that a generated answer is entailed by a retrieved chunk.
### Math- and TeX-aware retrieval research
The corpus retains equations in TeX instead of replacing them with MathML or a normalized
formula language. It can therefore support experiments on tokenization, lexical and
semantic retrieval, reranking, chunking, or representation learning for documents in
which mathematical notation and document structure are important. Results may depend on
author-specific macros and conservative TeX-to-text conversion, so comparisons should
report the fields and preprocessing used.
### Corpus analysis and reproducible preprocessing
The `papers` view supports document-level analyses using publication metadata and complete
source text. The `chunks` view supports passage-level analyses while preserving section
context. Because source and generated artifacts have SHA-256 identifiers and the build
scripts are included, researchers can describe an input snapshot precisely and compare
alternative extraction, parsing, deduplication, or chunking pipelines.
### Archival and provenance work
The `archives` config and `raw/` directory can be used to check whether a derived record
matches an original package, inspect auxiliary files, study source-package composition,
or reconstruct the corpus. Invalid, duplicated, multi-manuscript, ambiguous, and
catalogue-external cases are represented explicitly rather than removed, which allows
users to define and report their own inclusion policy.
### Training and tool development
Under CC BY 4.0 attribution, the corpus can be used as input for model pretraining,
fine-tuning, parser development, LaTeX tooling, or other preprocessing research. Users
should create their own task-specific splits and evaluation criteria, prevent unintended
train/test overlap caused by related or duplicate manuscripts, and retain paper-level
attribution where outputs expose source content.
## What this dataset does not provide
- It is not an evaluation benchmark, answer key, or set of verified ground-truth answers.
- It does not certify the scientific correctness, novelty, or current validity of a paper.
- It does not include embeddings, a vector database, a retrieval service, or a trained
model.
- It does not normalize equations or convert them to MathML.
- It does not guarantee that general-purpose TeX parsers can expand every author macro.
- It does not define a train/validation/test split; each config's `train` split is the
complete released view.
## Limitations
- Inclusion does not certify the scientific correctness of a manuscript.
- TeX-to-text conversion is conservative and may retain formatting commands.
- No MathML conversion or equation normalization is included in v1.
- A small number of source packages are invalid, duplicated, multi-manuscript, or not
attributable to a current DOI; these states are explicit rather than silently repaired.
- Public author contact information and ORCID values present in the source are retained.
- The corpus records source provenance, not whether any particular writing tool or
assistance process was used.
## License and citation
The dataset and included source materials are released under
[CC BY 4.0](https://creativecommons.org/licenses/by/4.0/). Attribute K. Takahashi,
cite this dataset, and cite each paper's DOI when using individual works.
Suggested BibTeX:
```bibtex
@dataset{{takahashi_paper_tex_corpus_{report["catalog"]["source_state_date"][:4]},
author = {{Takahashi, K.}},
title = {{K. Takahashi Paper TeX Corpus}},
year = {{{report["catalog"]["source_state_date"][:4]}}},
version = {{{VERSION}}},
publisher = {{Hugging Face}},
url = {{https://huggingface.co/datasets/{REPO_ID}}}
}}
```
Canonical publication records and paper-specific citation links are available at
<https://kadubon.github.io/github.io/works.html>.
"""
def write_checksums(output: Path) -> None:
excluded_parts = {".git", ".venv", "__pycache__", ".pytest_cache"}
excluded_names = {
"checksums.sha256",
"publish-report.json",
SENTINEL,
}
rows: list[str] = []
for path in sorted(
(item for item in output.rglob("*") if item.is_file()),
key=lambda item: item.relative_to(output).as_posix(),
):
relative = path.relative_to(output)
if any(part in excluded_parts for part in relative.parts):
continue
if relative.name in excluded_names:
continue
rows.append(f"{sha256_file(path)} {relative.as_posix()}")
write_text_lf(output / "checksums.sha256", "\n".join(rows) + "\n")
def main() -> None:
args = parse_args()
source, output = ensure_safe_workspace(args.source, args.output)
state = source_state(source)
catalog, catalog_origin = load_catalog(args)
scholarly = [
record
for record in catalog["records"]
if record.get("record_type") == "scholarly_article"
]
if len(scholarly) != 227:
raise SystemExit(
f"Expected 227 scholarly records, found {len(scholarly)}."
)
archives = scan_archives(source, output)
if len(archives) != 250:
raise SystemExit(f"Expected 250 ZIP archives, found {len(archives)}.")
apply_mappings(archives, scholarly, args.manual_mappings.resolve())
paper_rows, archive_only_rows, chunk_rows, archive_rows = build_rows(
archives, scholarly
)
write_parquet(output, "papers", paper_rows, PAPERS_SCHEMA, row_group_size=8)
write_parquet(
output,
"archive_only",
archive_only_rows,
ARCHIVE_ONLY_SCHEMA,
row_group_size=16,
)
write_parquet(output, "chunks", chunk_rows, CHUNKS_SCHEMA, row_group_size=128)
write_parquet(
output, "archives", archive_rows, ARCHIVES_SCHEMA, row_group_size=32
)
metadata_dir = output / "metadata"
metadata_dir.mkdir(parents=True, exist_ok=True)
write_text_lf(
metadata_dir / "research-catalog.json",
canonical_json(catalog),
)
write_crosswalk(output, archives)
source_record = {
**state,
"catalog_origin": catalog_origin,
"catalog_sha256": sha256_bytes(
canonical_json(catalog).encode("utf-8")
),
"catalog_source_state_date": catalog.get("source_state_date"),
"build_version": VERSION,
}
write_text_lf(
metadata_dir / "source-state.json",
canonical_json(source_record),
)
tex_entries = [tex for archive in archives for tex in archive.tex_entries]
tex_hash_counts: dict[str, int] = defaultdict(int)
for tex in tex_entries:
tex_hash_counts[tex.sha256] += 1
auxiliary_entries = [
entry
for archive in archives
for entry in archive.entries
if not entry["is_tex"]
]
report = {
"schema_version": "1.0",
"dataset_id": REPO_ID,
"version": VERSION,
"generated_at": (
f"{catalog.get('source_state_date')}T00:00:00+09:00"
if catalog.get("source_state_date")
else state["source_commit_date"]
),
"source": state,
"catalog": {
"origin": catalog_origin,
"source_state_date": catalog.get("source_state_date"),
"record_count": len(catalog["records"]),
"scholarly_record_count": len(scholarly),
"sha256": source_record["catalog_sha256"],
},
"counts": {
"papers": len(paper_rows),
"archive_only": len(archive_only_rows),
"chunks": len(chunk_rows),
"archives": len(archive_rows),
"tex_entries": len(tex_entries),
"auxiliary_entries": len(auxiliary_entries),
"invalid_sources": sum(
archive.content_status == "invalid_source" for archive in archives
),
"duplicate_archives": sum(
bool(archive.duplicate_of_archive) for archive in archives
),
"duplicate_tex_groups": sum(
count > 1 for count in tex_hash_counts.values()
),
"matched_archives": sum(
bool(archive.mapped_dois) for archive in archives
),
"ambiguous_archives": sum(
archive.mapping_status == "ambiguous" for archive in archives
),
"metadata_only_papers": sum(
row["content_status"] == "metadata_only" for row in paper_rows
),
},
"bytes": {
"raw_zip_total": sum(archive.size for archive in archives),
"tex_uncompressed_total": sum(tex.size for tex in tex_entries),
},
"mapping_methods": {
method: sum(archive.mapping_method == method for archive in archives)
for method in sorted({archive.mapping_method for archive in archives})
},
"quality": {
"secret_pattern_hits": 0,
"unsafe_zip_paths": 0,
"broken_zip_archives": 0,
"utf8_replacement_entries": sum(
"utf8_decode_replacement" in tex.quality_flags
for tex in tex_entries
),
},
}
write_text_lf(output / "build-report.json", canonical_json(report))
write_text_lf(output / "LICENSE", license_text())
write_text_lf(
output / "CITATION.cff",
citation_text(
catalog.get("source_state_date")
or state["source_commit_date"]
or date.today().isoformat()
),
)
write_text_lf(output / "README.md", readme_text(report))
write_checksums(output)
print(canonical_json(report), end="")
if __name__ == "__main__":
main()