#!/usr/bin/env python3 """Convert pinned Crossref citations of DataCite DOIs to validated COMET insert records.""" from __future__ import annotations import argparse from collections import Counter from datetime import datetime, timezone import gzip import hashlib import io import json from pathlib import Path import re import shutil import fastjsonschema import pyarrow.parquet as pq import rfc8785 import xxhash SOURCE_REPO = "cometadata/crossref-datacite-citations" SOURCE_REVISION = "65642a869543640f2965bcf9a7652f49fe88ef93" SOURCE_CONFIG = "all" PIPELINE_MANIFEST = "metadata/pipeline-manifest.json" PIPELINE_MANIFEST_SHA256 = "9a68b2e5189e2a627d5cd33bca7e17f6cfb7c5b0d39dc4cbe4c05897ce1dda76" SCHEMA_REVISION = "abd6a9acd3fc70d25f703ea5be3c0fc62e0b6a61" SCHEMA_SHA256 = "8a46a45770572b68261aa4045641006e22d56cc652ae3ec9242718a091ff7c28" METHOD = "crossref-datacite-citations" SCHEMA_PATH = Path(__file__).parent / "provenance/enrichment_input_schema.json" DOI_NAME = re.compile(r"\A10\.[0-9]+(?:\.[0-9]+)*/.+\Z") # Rust's char::is_control is general category Cc, which is exactly these code points. CONTROL = re.compile(r"[\x00-\x1f\x7f-\x9f]") VALUE_SCHEMA = { "$schema": "http://json-schema.org/draft-07/schema#", "type": "object", "required": ["relatedIdentifier", "relatedIdentifierType", "relationType"], "additionalProperties": False, "properties": { "relatedIdentifier": {"type": "string", "pattern": r"^10\.[0-9]+(?:\.[0-9]+)*/.+$"}, "relatedIdentifierType": {"const": "DOI"}, "relationType": {"const": "IsCitedBy"}, }, } def is_valid_doi_name(value: str) -> bool: """Port of comet-enrich identifiers::is_valid_doi_name at SCHEMA_REVISION.""" # str.strip also removes U+001C to U+001F, which Rust's trim keeps. # Both reject them as control characters, so the predicates agree. return value.strip() == value and not CONTROL.search(value) and DOI_NAME.match(value) is not None def require_doi(value, role: str) -> str: if not (isinstance(value, str) and is_valid_doi_name(value) and value == value.lower()): raise ValueError(f"Invalid or non-lowercase {role} DOI: {value!r}") return value def content_key(doi: str, value: dict, method: str = METHOD) -> str: return xxhash.xxh3_128_hexdigest( rfc8785.dumps([method, doi, "relatedIdentifiers", "insert", value]) ) def sha256(path: Path) -> str: with path.open("rb") as stream: return hashlib.file_digest(stream, "sha256").hexdigest() def gzip_text(path: Path): # Fixed gzip header for reproducible data bytes. return io.TextIOWrapper( gzip.GzipFile(filename=str(path), mode="wb", compresslevel=6, mtime=0), encoding="utf-8", newline="\n", ) class ShardWriter: """Numbered gzip JSONL shards of rows_per_shard records under data/.""" def __init__(self, output: Path, rows_per_shard: int): self.output = output self.rows_per_shard = rows_per_shard self.files = [] self.stream = None self.path = None self.rows = 0 def write(self, line: str): if self.stream is None or self.rows == self.rows_per_shard: self.close() self.path = self.output / "data" / f"part_{len(self.files):04d}.jsonl.gz" self.stream = gzip_text(self.path) self.rows = 0 self.stream.write(line) self.rows += 1 def close(self): if self.stream is not None: self.stream.close() self.stream = None self.files.append({"path": str(self.path.relative_to(self.output)), "rows": self.rows, "bytes": self.path.stat().st_size, "sha256": sha256(self.path)}) def pinned_source(source_dir: Path) -> tuple[dict, list[dict]]: """Check the pipeline manifest, then every config file it lists, before any read.""" manifest_path = source_dir / PIPELINE_MANIFEST if sha256(manifest_path) != PIPELINE_MANIFEST_SHA256: raise ValueError(f"{manifest_path} is not the manifest at revision {SOURCE_REVISION}") pipeline = json.loads(manifest_path.read_text()) inputs = [] for name in pipeline["config_files"][SOURCE_CONFIG]: path = source_dir / name expected = pipeline["files"][name] size, digest = path.stat().st_size, sha256(path) if size != expected["size"] or digest != expected["sha256"]: raise ValueError(f"{path} does not match its size and SHA-256 in the pipeline manifest") inputs.append({"path": name, "rows": pq.ParquetFile(path).metadata.num_rows, "bytes": size, "sha256": digest}) return pipeline, inputs def main(): parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("--source-dir", type=Path, required=True, help="Local download of the pinned source revision, holding metadata/ and data/all/") parser.add_argument("--output-dir", type=Path, required=True) parser.add_argument("--rows-per-shard", type=int, default=250000) parser.add_argument("--source-id", default="", help="Project DOI written to every sourceId; empty until one is registered") args = parser.parse_args() if args.source_id and not (is_valid_doi_name(args.source_id) and args.source_id == args.source_id.lower()): parser.error(f"--source-id must be a lowercase DOI name, got {args.source_id!r}") if sha256(SCHEMA_PATH) != SCHEMA_SHA256: raise ValueError(f"{SCHEMA_PATH} is not the enrichment schema at {SCHEMA_REVISION}") pipeline, inputs = pinned_source(args.source_dir) output = args.output_dir data = output / "data" data.mkdir(parents=True, exist_ok=True) if any(data.iterdir()): raise ValueError("Output data directory is not empty") (output / "provenance").mkdir(exist_ok=True) validate_enrichment = fastjsonschema.compile(json.loads(SCHEMA_PATH.read_text())) validate_value = fastjsonschema.compile(VALUE_SCHEMA) (output / "provenance/related_identifier_subset_schema.json").write_text( json.dumps(VALUE_SCHEMA, indent=2) + "\n") shutil.copyfile(args.source_dir / PIPELINE_MANIFEST, output / "provenance/source_pipeline_manifest.json") counts = Counter() by_provenance = Counter() seen_keys = set() cited_dois = set() enriched_dois = set() writer = ShardWriter(output, args.rows_per_shard) examples = [] for item in inputs: parquet = pq.ParquetFile(args.source_dir / item["path"]) # Only the citing DOI and its strongest provenance are needed, so the # per-match reference metadata is never decoded. columns = ["doi", "citation_count", "reference_count", "cited_by.list.element.doi", "cited_by.list.element.provenance"] for batch in parquet.iter_batches(batch_size=1000, columns=columns): for row in batch.to_pylist(): counts["source_rows"] += 1 doi = require_doi(row["doi"], "cited") cited_dois.add(doi) if row["citation_count"] != len(row["cited_by"]): raise ValueError(f"{doi}: citation_count {row['citation_count']} " f"!= {len(row['cited_by'])} cited_by entries") counts["source_citing_entries"] += len(row["cited_by"]) counts["source_reference_matches"] += row["reference_count"] for citing in row["cited_by"]: value = {"relatedIdentifier": require_doi(citing["doi"], "citing"), "relatedIdentifierType": "DOI", "relationType": "IsCitedBy"} validate_value(value) key = content_key(doi, value) key_bytes = bytes.fromhex(key) # The value is a pure function of the pair, so a repeated # key means the source repeated a pair. if key_bytes in seen_keys: raise ValueError(f"Repeated citation pair: {doi} cited by {citing['doi']}") seen_keys.add(key_bytes) record = {"doi": doi, "action": "insert", "field": "relatedIdentifiers", "enrichedValue": value, "sourceId": args.source_id, "contentKey": key} validate_enrichment(record) writer.write(json.dumps(record, ensure_ascii=False, separators=(",", ":")) + "\n") counts["enrichments"] += 1 by_provenance[citing["provenance"]] += 1 counts["enrichments_to_arxiv_dois"] += doi.startswith("10.48550/") enriched_dois.add(doi) if len(examples) < 4: examples.append(record) print(json.dumps({"source_file": item["path"], "source_rows": counts["source_rows"], "enrichments": counts["enrichments"]}), flush=True) writer.close() counts["unique_cited_dois"] = len(cited_dois) counts["unique_enriched_dois"] = len(enriched_dois) assert counts["enrichments"] == counts["source_citing_entries"] published = pipeline["counts"] assert counts["source_rows"] == published["all"]["works"] assert counts["source_citing_entries"] == published["all"]["citations"] assert counts["source_reference_matches"] == published["all"]["references"] manifest = { "created_at": datetime.now(timezone.utc).isoformat(), "method": {"name": METHOD, "version": "1.0.0"}, "source_id": args.source_id, "source": {"repo": SOURCE_REPO, "revision": SOURCE_REVISION, "config": SOURCE_CONFIG, "split": "train", "snapshot_id": pipeline["snapshot_id"], "extractor_version": pipeline["extractor_version"], "pipeline_manifest_sha256": PIPELINE_MANIFEST_SHA256}, "enrichment_schema": {"repo": "cometadata/comet-enrich", "revision": SCHEMA_REVISION, "path": "configs/enrichment_input_schema.json", "sha256": SCHEMA_SHA256}, "content_key": {"algorithm": "xxh3-128", "canonicalization": "RFC 8785 JCS", "input": "[method, doi, field, action, enrichedValue]"}, "counts": dict(sorted(counts.items())) | { "enrichments_by_source_provenance": dict(sorted(by_provenance.items())), }, "validation": {"enrichment_schema_failures": 0, "related_identifier_schema_failures": 0}, "input_files": inputs, "data_files": writer.files, } (output / "manifest.json").write_text(json.dumps(manifest, indent=2) + "\n") (output / "provenance/examples.json").write_text( json.dumps(examples, indent=2, ensure_ascii=False) + "\n") print(json.dumps(manifest["counts"], indent=2), flush=True) if __name__ == "__main__": main()