| """Build a current PubMed metadata Parquet file from NCBI's XML distribution. |
| |
| The input directory is expected to contain the two directories mirrored from NCBI:: |
| |
| pubmed/ |
| baseline/pubmed26n0001.xml.gz ... |
| updatefiles/pubmed26n1335.xml.gz ... |
| |
| The baseline is a snapshot. Update files contain new, revised, and deleted records. |
| This script indexes the last update event for every PMID, writes unchanged baseline |
| records, and then writes only the final live version from the updates. The result has |
| one row per current PMID without needing to hold the corpus in memory. |
| |
| Example:: |
| |
| uv run --group dev python scripts/pubmed_xml_to_parquet.py \ |
| --input-root /mnt/data/pubmed_corpus/pubmed \ |
| --output /mnt/data/pubmed_corpus/papers.parquet |
| """ |
|
|
| from __future__ import annotations |
|
|
| import argparse |
| import concurrent.futures |
| import contextlib |
| import gzip |
| import hashlib |
| import os |
| import re |
| import sqlite3 |
| import tempfile |
| from collections import deque |
| from collections.abc import Callable, Iterable, Iterator, Sequence |
| from dataclasses import dataclass |
| from pathlib import Path |
| from typing import Any |
| from xml.etree import ElementTree as ET |
|
|
| import pyarrow as pa |
| import pyarrow.parquet as pq |
| from tqdm.auto import tqdm |
|
|
| DEFAULT_INPUT_ROOT = Path("/mnt/data/pubmed_corpus/pubmed") |
| DEFAULT_WORKERS = min(8, os.process_cpu_count() or 1) |
| FILE_RE = re.compile(r"^pubmed(?P<release>\d{2})n(?P<sequence>\d{4})\.xml\.gz$") |
| YEAR_RE = re.compile(r"(?<!\d)(1[5-9]\d{2}|20\d{2}|2100)(?!\d)") |
| WHITESPACE_RE = re.compile(r"\s+") |
| ORCID_URL_RE = re.compile(r"^https?://orcid\.org/", re.IGNORECASE) |
| SQLITE_QUERY_CHUNK = 900 |
|
|
| MONTHS = { |
| "jan": 1, |
| "feb": 2, |
| "mar": 3, |
| "apr": 4, |
| "may": 5, |
| "jun": 6, |
| "jul": 7, |
| "aug": 8, |
| "sep": 9, |
| "oct": 10, |
| "nov": 11, |
| "dec": 12, |
| } |
|
|
| AUTHOR_TYPE = pa.struct([ |
| pa.field("display_name", pa.string(), nullable=False), |
| pa.field("last_name", pa.string()), |
| pa.field("fore_name", pa.string()), |
| pa.field("initials", pa.string()), |
| pa.field("suffix", pa.string()), |
| pa.field("collective_name", pa.string()), |
| pa.field("orcid", pa.string()), |
| pa.field("affiliations", pa.list_(pa.string())), |
| pa.field("valid", pa.bool_(), nullable=False), |
| pa.field("equal_contrib", pa.bool_()), |
| ]) |
|
|
| PARQUET_SCHEMA = pa.schema([ |
| pa.field("pmid", pa.string(), nullable=False), |
| pa.field("pmcid", pa.string()), |
| pa.field("doi", pa.string()), |
| pa.field("title", pa.string()), |
| pa.field("abstract", pa.string()), |
| pa.field("journal", pa.string()), |
| pa.field("year", pa.int64()), |
| pa.field("issn", pa.string()), |
| pa.field("eissn", pa.string()), |
| pa.field("issn_linking", pa.string()), |
| pa.field("journal_abbrev", pa.string()), |
| pa.field("nlm_unique_id", pa.string()), |
| pa.field("country", pa.string()), |
| pa.field("volume", pa.string()), |
| pa.field("issue", pa.string()), |
| pa.field("pages", pa.string()), |
| pa.field("publication_date", pa.string()), |
| pa.field("date_completed", pa.string()), |
| pa.field("date_revised", pa.string()), |
| pa.field("citation_status", pa.string()), |
| pa.field("publication_status", pa.string()), |
| pa.field("pub_model", pa.string()), |
| pa.field("vernacular_title", pa.string()), |
| pa.field("authors", pa.list_(AUTHOR_TYPE)), |
| pa.field("publication_types", pa.list_(pa.string())), |
| pa.field("languages", pa.list_(pa.string())), |
| pa.field("mesh_terms", pa.list_(pa.string())), |
| pa.field("mesh_major_topics", pa.list_(pa.string())), |
| pa.field("keywords", pa.list_(pa.string())), |
| pa.field("article_ids", pa.list_(pa.string())), |
| ]) |
|
|
| Record = dict[str, Any] |
|
|
|
|
| @dataclass(frozen=True) |
| class DistributionFile: |
| path: Path |
| release: int |
| sequence: int |
|
|
|
|
| @dataclass |
| class ParsedFile: |
| table: pa.Table |
| event_count: int |
|
|
|
|
| def _local_name(tag: str) -> str: |
| """Return an XML local name, including for embedded namespaced content.""" |
| return tag.rsplit("}", 1)[-1] |
|
|
|
|
| def _element_text(element: ET.Element | None) -> str | None: |
| """Extract mixed XML content and normalize formatting whitespace.""" |
| if element is None: |
| return None |
| text = WHITESPACE_RE.sub(" ", "".join(element.itertext())).strip() |
| return text or None |
|
|
|
|
| def _text_at(parent: ET.Element | None, path: str) -> str | None: |
| return _element_text(parent.find(path)) if parent is not None else None |
|
|
|
|
| def _texts_at(parent: ET.Element | None, path: str) -> list[str]: |
| if parent is None: |
| return [] |
| return [text for element in parent.findall(path) if (text := _element_text(element)) is not None] |
|
|
|
|
| def _unique(values: Iterable[str]) -> list[str]: |
| return list(dict.fromkeys(value for value in values if value)) |
|
|
|
|
| def _abstract(parent: ET.Element | None) -> str | None: |
| if parent is None: |
| return None |
| sections: list[str] = [] |
| for element in parent.findall("Abstract/AbstractText"): |
| text = _element_text(element) |
| if text is None: |
| continue |
| label = WHITESPACE_RE.sub(" ", element.attrib.get("Label", "")).strip() |
| sections.append(f"{label}: {text}" if label else text) |
| return "\n".join(sections) or None |
|
|
|
|
| def _authors(parent: ET.Element | None, paths: Sequence[str]) -> list[Record]: |
| if parent is None: |
| return [] |
|
|
| authors: list[Record] = [] |
| for path in paths: |
| for author in parent.findall(path): |
| collective_name = _text_at(author, "CollectiveName") |
| last_name = _text_at(author, "LastName") |
| fore_name = _text_at(author, "ForeName") |
| initials = _text_at(author, "Initials") |
| suffix = _text_at(author, "Suffix") |
| if collective_name: |
| display_name = collective_name |
| else: |
| display_name = " ".join( |
| part |
| for part in ( |
| fore_name, |
| last_name, |
| suffix, |
| ) |
| if part |
| ) |
|
|
| orcid: str | None = None |
| for identifier in author.findall("Identifier"): |
| if identifier.attrib.get("Source", "").casefold() != "orcid": |
| continue |
| if value := _element_text(identifier): |
| orcid = orcid or ORCID_URL_RE.sub("", value) |
|
|
| equal_contrib_attribute = author.attrib.get("EqualContrib") |
| authors.append({ |
| "display_name": display_name, |
| "last_name": last_name, |
| "fore_name": fore_name, |
| "initials": initials, |
| "suffix": suffix, |
| "collective_name": collective_name, |
| "orcid": orcid, |
| "affiliations": _unique(_texts_at(author, "AffiliationInfo/Affiliation")), |
| "valid": author.attrib.get("ValidYN", "Y") == "Y", |
| "equal_contrib": (equal_contrib_attribute == "Y" if equal_contrib_attribute is not None else None), |
| }) |
|
|
| return authors |
|
|
|
|
| def _article_ids(*parents: ET.Element | None) -> tuple[dict[str, list[str]], list[str]]: |
| by_type: dict[str, list[str]] = {} |
| flattened: list[str] = [] |
| for parent in parents: |
| if parent is None: |
| continue |
| for element in parent.findall("ArticleIdList/ArticleId"): |
| value = _element_text(element) |
| if value is None: |
| continue |
| id_type = element.attrib.get("IdType", "unknown").casefold() |
| values = by_type.setdefault(id_type, []) |
| if value not in values: |
| values.append(value) |
| flattened.append(f"{id_type}:{value}") |
| return by_type, _unique(flattened) |
|
|
|
|
| def _date_parts(parent: ET.Element | None) -> tuple[int | None, str | None]: |
| if parent is None: |
| return None, None |
|
|
| year_text = _text_at(parent, "Year") |
| medline_date = _text_at(parent, "MedlineDate") |
| year: int | None = None |
| if year_text and year_text.isdigit(): |
| year = int(year_text) |
| elif medline_date and (match := YEAR_RE.search(medline_date)): |
| year = int(match.group(1)) |
|
|
| if year is None: |
| return None, medline_date |
|
|
| month_text = _text_at(parent, "Month") |
| day_text = _text_at(parent, "Day") |
| month: int | None = None |
| if month_text: |
| if month_text.isdigit() and 1 <= int(month_text) <= 12: |
| month = int(month_text) |
| else: |
| month = MONTHS.get(month_text[:3].casefold()) |
|
|
| if month is None: |
| return year, str(year) |
| if day_text and day_text.isdigit() and 1 <= int(day_text) <= 31: |
| return year, f"{year:04d}-{month:02d}-{int(day_text):02d}" |
| return year, f"{year:04d}-{month:02d}" |
|
|
|
|
| def _simple_date(parent: ET.Element | None) -> str | None: |
| _, value = _date_parts(parent) |
| return value |
|
|
|
|
| def _publication_date( |
| article: ET.Element | None, |
| pubmed_data: ET.Element | None, |
| *, |
| book: ET.Element | None = None, |
| ) -> tuple[int | None, str | None]: |
| candidates: list[ET.Element | None] = [] |
| if article is not None: |
| candidates.extend([ |
| article.find("Journal/JournalIssue/PubDate"), |
| article.find("ArticleDate"), |
| ]) |
| if book is not None: |
| candidates.append(book.find("PubDate")) |
| if pubmed_data is not None: |
| history = pubmed_data.find("History") |
| if history is not None: |
| by_status = {date.attrib.get("PubStatus"): date for date in history.findall("PubMedPubDate")} |
| candidates.extend(by_status.get(status) for status in ("ppublish", "epublish", "pubmed", "entrez")) |
|
|
| for candidate in candidates: |
| year, value = _date_parts(candidate) |
| if year is not None: |
| return year, value |
| return None, None |
|
|
|
|
| def _journal_issns(journal: ET.Element | None) -> tuple[str | None, str | None]: |
| if journal is None: |
| return None, None |
| print_issn: str | None = None |
| electronic_issn: str | None = None |
| for element in journal.findall("ISSN"): |
| value = _element_text(element) |
| if value is None: |
| continue |
| issn_type = element.attrib.get("IssnType", "").casefold() |
| if issn_type == "electronic": |
| electronic_issn = electronic_issn or value |
| elif issn_type == "print": |
| print_issn = print_issn or value |
| return print_issn, electronic_issn |
|
|
|
|
| def _mesh(citation: ET.Element | None) -> tuple[list[str], list[str]]: |
| if citation is None: |
| return [], [] |
| terms: list[str] = [] |
| major_topics: list[str] = [] |
| for heading in citation.findall("MeshHeadingList/MeshHeading"): |
| descriptor = heading.find("DescriptorName") |
| descriptor_text = _element_text(descriptor) |
| if descriptor_text is None: |
| continue |
| terms.append(descriptor_text) |
| if descriptor is not None and descriptor.attrib.get("MajorTopicYN") == "Y": |
| major_topics.append(descriptor_text) |
| for qualifier in heading.findall("QualifierName"): |
| qualifier_text = _element_text(qualifier) |
| if qualifier_text and qualifier.attrib.get("MajorTopicYN") == "Y": |
| major_topics.append(f"{descriptor_text}/{qualifier_text}") |
| return _unique(terms), _unique(major_topics) |
|
|
|
|
| def _parse_journal_article(element: ET.Element) -> Record: |
| citation = element.find("MedlineCitation") |
| if citation is None: |
| raise ValueError("PubmedArticle has no MedlineCitation") |
| article = citation.find("Article") |
| pubmed_data = element.find("PubmedData") |
| journal = article.find("Journal") if article is not None else None |
| journal_info = citation.find("MedlineJournalInfo") |
|
|
| pmid = _text_at(citation, "PMID") |
| if pmid is None: |
| raise ValueError("PubmedArticle has no PMID") |
|
|
| ids, flattened_ids = _article_ids(pubmed_data) |
| if article is not None: |
| for e_location in article.findall("ELocationID"): |
| if e_location.attrib.get("EIdType", "").casefold() != "doi": |
| continue |
| if value := _element_text(e_location): |
| ids.setdefault("doi", []).append(value) |
| flattened_ids.append(f"doi:{value}") |
|
|
| print_issn, electronic_issn = _journal_issns(journal) |
| year, publication_date = _publication_date(article, pubmed_data) |
| authors = _authors(article, ("AuthorList/Author",)) |
| mesh_terms, mesh_major_topics = _mesh(citation) |
|
|
| return { |
| "pmid": pmid, |
| "pmcid": (ids.get("pmc") or ids.get("pmcid") or [None])[0], |
| "doi": (ids.get("doi") or [None])[0], |
| "title": _text_at(article, "ArticleTitle"), |
| "abstract": _abstract(article), |
| "journal": _text_at(journal, "Title"), |
| "year": year, |
| "issn": print_issn, |
| "eissn": electronic_issn, |
| "issn_linking": _text_at(journal_info, "ISSNLinking"), |
| "journal_abbrev": _text_at(journal, "ISOAbbreviation"), |
| "nlm_unique_id": _text_at(journal_info, "NlmUniqueID"), |
| "country": _text_at(journal_info, "Country"), |
| "volume": _text_at(journal, "JournalIssue/Volume"), |
| "issue": _text_at(journal, "JournalIssue/Issue"), |
| "pages": _text_at(article, "Pagination/MedlinePgn"), |
| "publication_date": publication_date, |
| "date_completed": _simple_date(citation.find("DateCompleted")), |
| "date_revised": _simple_date(citation.find("DateRevised")), |
| "citation_status": citation.attrib.get("Status"), |
| "publication_status": _text_at(pubmed_data, "PublicationStatus"), |
| "pub_model": article.attrib.get("PubModel") if article is not None else None, |
| "vernacular_title": _text_at(article, "VernacularTitle"), |
| "authors": authors, |
| "publication_types": _texts_at(article, "PublicationTypeList/PublicationType"), |
| "languages": _texts_at(article, "Language"), |
| "mesh_terms": mesh_terms, |
| "mesh_major_topics": mesh_major_topics, |
| "keywords": _unique(_texts_at(citation, "KeywordList/Keyword")), |
| "article_ids": _unique(flattened_ids), |
| } |
|
|
|
|
| def _parse_book_article(element: ET.Element) -> Record: |
| document = element.find("BookDocument") |
| if document is None: |
| raise ValueError("PubmedBookArticle has no BookDocument") |
| book_data = element.find("PubmedBookData") |
| book = document.find("Book") |
|
|
| pmid = _text_at(document, "PMID") |
| if pmid is None: |
| raise ValueError("PubmedBookArticle has no PMID") |
|
|
| ids, flattened_ids = _article_ids(document, book_data) |
| year, publication_date = _publication_date(None, book_data, book=book) |
| authors = _authors( |
| document, |
| ( |
| "AuthorList/Author", |
| "Book/AuthorList/Author", |
| ), |
| ) |
|
|
| return { |
| "pmid": pmid, |
| "pmcid": (ids.get("pmc") or ids.get("pmcid") or [None])[0], |
| "doi": (ids.get("doi") or [None])[0], |
| "title": _text_at(document, "ArticleTitle") or _text_at(book, "BookTitle"), |
| "abstract": _abstract(document), |
| "journal": _text_at(book, "BookTitle"), |
| "year": year, |
| "issn": None, |
| "eissn": None, |
| "issn_linking": None, |
| "journal_abbrev": None, |
| "nlm_unique_id": None, |
| "country": _text_at(book, "Publisher/PublisherLocation"), |
| "volume": _text_at(book, "Volume"), |
| "issue": None, |
| "pages": _text_at(document, "Pagination/MedlinePgn"), |
| "publication_date": publication_date, |
| "date_completed": None, |
| "date_revised": _simple_date(document.find("DateRevised")), |
| "citation_status": "Book", |
| "publication_status": _text_at(book_data, "PublicationStatus"), |
| "pub_model": None, |
| "vernacular_title": _text_at(document, "VernacularTitle"), |
| "authors": authors, |
| "publication_types": _texts_at(document, "PublicationType"), |
| "languages": _texts_at(document, "Language"), |
| "mesh_terms": [], |
| "mesh_major_topics": [], |
| "keywords": _unique(_texts_at(document, "KeywordList/Keyword")), |
| "article_ids": flattened_ids, |
| } |
|
|
|
|
| def _parse_record(element: ET.Element) -> Record: |
| if _local_name(element.tag) == "PubmedBookArticle": |
| return _parse_book_article(element) |
| return _parse_journal_article(element) |
|
|
|
|
| def _record_pmid(element: ET.Element) -> str: |
| citation = element.find("MedlineCitation") |
| document = element.find("BookDocument") |
| pmid = _text_at(citation, "PMID") or _text_at(document, "PMID") |
| if pmid is None: |
| raise ValueError(f"{_local_name(element.tag)} has no PMID") |
| return pmid |
|
|
|
|
| def _expected_md5(path: Path) -> str: |
| sidecar = path.with_name(f"{path.name}.md5") |
| try: |
| contents = sidecar.read_text().strip() |
| except FileNotFoundError as exc: |
| raise ValueError(f"Missing checksum sidecar: {sidecar}") from exc |
| match = re.search(r"\b([0-9a-fA-F]{32})\b", contents) |
| if match is None: |
| raise ValueError(f"Invalid MD5 sidecar: {sidecar}") |
| return match.group(1).casefold() |
|
|
|
|
| def _verify_md5(path: Path) -> None: |
| expected = _expected_md5(path) |
| with path.open("rb") as file: |
| actual = hashlib.file_digest(file, "md5").hexdigest() |
| if actual != expected: |
| raise ValueError(f"MD5 mismatch for {path}: expected {expected}, got {actual}") |
|
|
|
|
| def _iter_events( |
| path: Path, |
| *, |
| parse_records: bool, |
| verify_md5: bool, |
| ) -> Iterator[tuple[str, Record | None, bool]]: |
| if verify_md5: |
| _verify_md5(path) |
|
|
| with gzip.open(path, "rb") as file: |
| context = ET.iterparse(file, events=("start", "end")) |
| try: |
| _, root = next(context) |
| except StopIteration as exc: |
| raise ValueError(f"Empty XML file: {path}") from exc |
|
|
| for event, element in context: |
| if event != "end": |
| continue |
| tag = _local_name(element.tag) |
| if tag in {"PubmedArticle", "PubmedBookArticle"}: |
| record = _parse_record(element) if parse_records else None |
| pmid = record["pmid"] if record is not None else _record_pmid(element) |
| yield pmid, record, False |
| root.clear() |
| elif tag in {"DeleteCitation", "DeleteDocument"}: |
| for pmid_element in element.findall("PMID"): |
| if pmid := _element_text(pmid_element): |
| yield pmid, None, True |
| root.clear() |
|
|
|
|
| def _event_key(file_index: int, event_index: int) -> int: |
| return (file_index << 32) | event_index |
|
|
|
|
| def _index_update_file(task: tuple[int, Path, bool]) -> list[tuple[int, int, int]]: |
| file_index, path, verify_md5 = task |
| indexed: list[tuple[int, int, int]] = [] |
| for event_index, (pmid, _, deleted) in enumerate( |
| _iter_events(path, parse_records=False, verify_md5=verify_md5), |
| start=1, |
| ): |
| indexed.append((int(pmid), _event_key(file_index, event_index), int(deleted))) |
| return indexed |
|
|
|
|
| def _query_changed_pmids(connection: sqlite3.Connection, pmids: Sequence[int]) -> set[int]: |
| changed: set[int] = set() |
| for offset in range(0, len(pmids), SQLITE_QUERY_CHUNK): |
| chunk = pmids[offset : offset + SQLITE_QUERY_CHUNK] |
| placeholders = ",".join("?" for _ in chunk) |
| rows = connection.execute(f"SELECT pmid FROM latest_updates WHERE pmid IN ({placeholders})", chunk) |
| changed.update(row[0] for row in rows) |
| return changed |
|
|
|
|
| def _query_latest_events(connection: sqlite3.Connection, pmids: Sequence[int]) -> dict[int, int]: |
| latest: dict[int, int] = {} |
| for offset in range(0, len(pmids), SQLITE_QUERY_CHUNK): |
| chunk = pmids[offset : offset + SQLITE_QUERY_CHUNK] |
| placeholders = ",".join("?" for _ in chunk) |
| rows = connection.execute( |
| f"SELECT pmid, event_key FROM latest_updates WHERE pmid IN ({placeholders})", |
| chunk, |
| ) |
| latest.update(rows) |
| return latest |
|
|
|
|
| def _read_only_connection(path: Path) -> sqlite3.Connection: |
| connection = sqlite3.connect(path) |
| connection.execute("PRAGMA query_only = ON") |
| return connection |
|
|
|
|
| def _parse_baseline_file(task: tuple[Path, Path | None, bool]) -> ParsedFile: |
| path, state_db, verify_md5 = task |
| events = list(_iter_events(path, parse_records=True, verify_md5=verify_md5)) |
| records = [record for _, record, _ in events if record is not None] |
| if state_db is not None and records: |
| connection = _read_only_connection(state_db) |
| try: |
| changed = _query_changed_pmids(connection, [int(record["pmid"]) for record in records]) |
| finally: |
| connection.close() |
| records = [record for record in records if int(record["pmid"]) not in changed] |
| return ParsedFile(table=pa.Table.from_pylist(records, schema=PARQUET_SCHEMA), event_count=len(events)) |
|
|
|
|
| def _parse_update_file(task: tuple[int, Path, Path]) -> ParsedFile: |
| file_index, path, state_db = task |
| events = list(_iter_events(path, parse_records=True, verify_md5=False)) |
| connection = _read_only_connection(state_db) |
| try: |
| latest = _query_latest_events(connection, [int(pmid) for pmid, _, _ in events]) |
| finally: |
| connection.close() |
|
|
| records: list[Record] = [ |
| record |
| for event_index, (pmid, record, _) in enumerate(events, start=1) |
| if record is not None and latest.get(int(pmid)) == _event_key(file_index, event_index) |
| ] |
| return ParsedFile(table=pa.Table.from_pylist(records, schema=PARQUET_SCHEMA), event_count=len(events)) |
|
|
|
|
| def _ordered_process_map[Task, Result]( |
| function: Callable[[Task], Result], |
| tasks: Iterable[Task], |
| *, |
| workers: int, |
| ) -> Iterator[Result]: |
| if workers == 1: |
| yield from map(function, tasks) |
| return |
|
|
| task_iterator = iter(tasks) |
| with concurrent.futures.ProcessPoolExecutor(max_workers=workers) as executor: |
| pending: deque[concurrent.futures.Future[Result]] = deque() |
| for _ in range(workers): |
| try: |
| pending.append(executor.submit(function, next(task_iterator))) |
| except StopIteration: |
| break |
|
|
| while pending: |
| yield pending.popleft().result() |
| with contextlib.suppress(StopIteration): |
| pending.append(executor.submit(function, next(task_iterator))) |
|
|
|
|
| def _discover_files(directory: Path) -> list[DistributionFile]: |
| files: list[DistributionFile] = [] |
| for path in directory.glob("pubmed*n*.xml.gz"): |
| if match := FILE_RE.fullmatch(path.name): |
| files.append( |
| DistributionFile( |
| path=path, |
| release=int(match.group("release")), |
| sequence=int(match.group("sequence")), |
| ) |
| ) |
| return sorted(files, key=lambda item: (item.release, item.sequence)) |
|
|
|
|
| def _assert_contiguous(files: Sequence[DistributionFile], label: str) -> None: |
| for previous, current in zip(files, files[1:], strict=False): |
| if current.release != previous.release or current.sequence != previous.sequence + 1: |
| raise ValueError(f"{label} files are not contiguous between {previous.path.name} and {current.path.name}") |
|
|
|
|
| def discover_distribution( |
| input_root: Path, *, baseline_only: bool |
| ) -> tuple[list[DistributionFile], list[DistributionFile]]: |
| baseline = _discover_files(input_root / "baseline") |
| updates = [] if baseline_only else _discover_files(input_root / "updatefiles") |
| if not baseline: |
| raise ValueError(f"No PubMed baseline XML files found in {input_root / 'baseline'}") |
| if baseline[0].sequence != 1: |
| raise ValueError(f"The baseline starts at {baseline[0].path.name}, not sequence 0001") |
| _assert_contiguous(baseline, "Baseline") |
| _assert_contiguous(updates, "Update") |
|
|
| if updates: |
| expected_first_update = baseline[-1].sequence + 1 |
| if updates[0].release != baseline[-1].release or updates[0].sequence != expected_first_update: |
| raise ValueError( |
| f"Expected the first update after {baseline[-1].path.name} to have sequence " |
| f"{expected_first_update:04d}, found {updates[0].path.name}" |
| ) |
| return baseline, updates |
|
|
|
|
| def _build_update_index( |
| update_files: Sequence[DistributionFile], |
| state_db: Path, |
| *, |
| workers: int, |
| verify_md5: bool, |
| ) -> tuple[int, int, int]: |
| with sqlite3.connect(state_db) as connection: |
| connection.execute("PRAGMA journal_mode = OFF") |
| connection.execute("PRAGMA synchronous = OFF") |
| connection.execute( |
| """ |
| CREATE TABLE latest_updates ( |
| pmid INTEGER PRIMARY KEY, |
| event_key INTEGER NOT NULL, |
| deleted INTEGER NOT NULL |
| ) |
| """ |
| ) |
| tasks = ((index, item.path, verify_md5) for index, item in enumerate(update_files)) |
| total_events = 0 |
| results = _ordered_process_map(_index_update_file, tasks, workers=workers) |
| for indexed in tqdm(results, total=len(update_files), desc="Index updates", unit="file"): |
| total_events += len(indexed) |
| connection.executemany( |
| """ |
| INSERT INTO latest_updates (pmid, event_key, deleted) |
| VALUES (?, ?, ?) |
| ON CONFLICT(pmid) DO UPDATE SET |
| event_key = excluded.event_key, |
| deleted = excluded.deleted |
| WHERE excluded.event_key > latest_updates.event_key |
| """, |
| indexed, |
| ) |
| connection.commit() |
| counts = connection.execute("SELECT count(), coalesce(sum(deleted), 0) FROM latest_updates").fetchone() |
| assert counts is not None |
| latest_events, latest_deletions = counts |
| return total_events, latest_events, latest_deletions |
|
|
|
|
| def _parquet_schema(baseline: Sequence[DistributionFile], updates: Sequence[DistributionFile]) -> pa.Schema: |
| metadata = { |
| b"source": b"NLM PubMed baseline and daily update XML", |
| b"pubmed_release": str(baseline[0].release).encode(), |
| b"baseline_first_file": baseline[0].path.name.encode(), |
| b"baseline_last_file": baseline[-1].path.name.encode(), |
| b"update_last_file": (updates[-1].path.name if updates else "").encode(), |
| } |
| return PARQUET_SCHEMA.with_metadata(metadata) |
|
|
|
|
| def build_parquet( |
| input_root: Path, |
| output: Path, |
| *, |
| workers: int = DEFAULT_WORKERS, |
| baseline_only: bool = False, |
| verify_md5: bool = True, |
| overwrite: bool = False, |
| compression_level: int = 3, |
| ) -> None: |
| """Build one Parquet file containing the final live version of each PMID.""" |
| if workers < 1: |
| raise ValueError("workers must be at least 1") |
| if output.exists() and not overwrite: |
| raise FileExistsError(f"Output exists; pass --overwrite to replace it: {output}") |
|
|
| baseline, updates = discover_distribution(input_root, baseline_only=baseline_only) |
| print( |
| f"Found {len(baseline):,} baseline files" |
| + (f" and {len(updates):,} update files" if updates else " (baseline only)") |
| ) |
| output.parent.mkdir(parents=True, exist_ok=True) |
| partial_output = output.with_name(f".{output.name}.partial") |
| if partial_output.exists(): |
| if not overwrite: |
| raise FileExistsError(f"Partial output exists; pass --overwrite to replace it: {partial_output}") |
| partial_output.unlink() |
|
|
| total_input_events = 0 |
| total_output_rows = 0 |
| update_event_count = 0 |
| latest_update_count = 0 |
| latest_deletion_count = 0 |
| try: |
| with tempfile.TemporaryDirectory(prefix="pubmed-parquet-", dir=output.parent) as temp_dir: |
| state_db = Path(temp_dir) / "latest_updates.sqlite3" |
| state_db_or_none: Path | None = None |
| if updates: |
| update_event_count, latest_update_count, latest_deletion_count = _build_update_index( |
| updates, |
| state_db, |
| workers=workers, |
| verify_md5=verify_md5, |
| ) |
| state_db_or_none = state_db |
|
|
| schema = _parquet_schema(baseline, updates) |
| with pq.ParquetWriter( |
| partial_output, |
| schema, |
| compression="zstd", |
| compression_level=compression_level, |
| use_dictionary=[ |
| "journal", |
| "year", |
| "country", |
| "citation_status", |
| "publication_status", |
| "pub_model", |
| ], |
| write_statistics=["pmid", "pmcid", "doi", "journal", "year"], |
| ) as writer: |
| baseline_tasks = ((item.path, state_db_or_none, verify_md5) for item in baseline) |
| baseline_results = _ordered_process_map(_parse_baseline_file, baseline_tasks, workers=workers) |
| for parsed in tqdm(baseline_results, total=len(baseline), desc="Write baseline", unit="file"): |
| total_input_events += parsed.event_count |
| if parsed.table.num_rows: |
| writer.write_table(parsed.table) |
| total_output_rows += parsed.table.num_rows |
|
|
| if updates: |
| update_tasks = ((index, item.path, state_db) for index, item in enumerate(updates)) |
| update_results = _ordered_process_map(_parse_update_file, update_tasks, workers=workers) |
| for parsed in tqdm(update_results, total=len(updates), desc="Write updates", unit="file"): |
| if parsed.table.num_rows: |
| writer.write_table(parsed.table) |
| total_output_rows += parsed.table.num_rows |
|
|
| partial_output.replace(output) |
| except BaseException: |
| partial_output.unlink(missing_ok=True) |
| raise |
|
|
| print(f"Wrote {total_output_rows:,} current PubMed records to {output}") |
| print(f"Read {total_input_events:,} baseline records") |
| if updates: |
| print( |
| f"Processed {update_event_count:,} update events affecting {latest_update_count:,} PMIDs " |
| f"({latest_deletion_count:,} deleted in their latest event)" |
| ) |
|
|
|
|
| def _parse_args() -> argparse.Namespace: |
| parser = argparse.ArgumentParser(description=__doc__) |
| parser.add_argument( |
| "--input-root", |
| type=Path, |
| default=DEFAULT_INPUT_ROOT, |
| help=f"Directory containing baseline/ and updatefiles/ (default: {DEFAULT_INPUT_ROOT})", |
| ) |
| parser.add_argument("--output", type=Path, required=True, help="Destination .parquet file") |
| parser.add_argument( |
| "--workers", type=int, default=DEFAULT_WORKERS, help=f"Parser processes (default: {DEFAULT_WORKERS})" |
| ) |
| parser.add_argument("--baseline-only", action="store_true", help="Ignore daily update files") |
| parser.add_argument("--skip-md5", action="store_true", help="Do not validate mirrored files against .md5 sidecars") |
| parser.add_argument("--overwrite", action="store_true", help="Atomically replace an existing output file") |
| parser.add_argument("--compression-level", type=int, default=3, help="Zstandard compression level (default: 3)") |
| return parser.parse_args() |
|
|
|
|
| def main() -> None: |
| args = _parse_args() |
| build_parquet( |
| args.input_root, |
| args.output, |
| workers=args.workers, |
| baseline_only=args.baseline_only, |
| verify_md5=not args.skip_md5, |
| overwrite=args.overwrite, |
| compression_level=args.compression_level, |
| ) |
|
|
|
|
| if __name__ == "__main__": |
| main() |
|
|