Datasets:
Add files using upload-large-folder tool
Browse files- README.md +281 -0
- data/train-00000-of-00210.parquet +3 -0
- data/train-00001-of-00210.parquet +3 -0
- data/train-00002-of-00210.parquet +3 -0
- data/train-00003-of-00210.parquet +3 -0
- data/train-00004-of-00210.parquet +3 -0
- data/train-00005-of-00210.parquet +3 -0
- data/train-00006-of-00210.parquet +3 -0
- data/train-00007-of-00210.parquet +3 -0
- data/train-00008-of-00210.parquet +3 -0
- data/train-00009-of-00210.parquet +3 -0
- data/train-00010-of-00210.parquet +3 -0
- data/train-00011-of-00210.parquet +3 -0
- data/train-00012-of-00210.parquet +3 -0
- data/train-00013-of-00210.parquet +3 -0
- data/train-00014-of-00210.parquet +3 -0
- data/train-00015-of-00210.parquet +3 -0
- data/train-00016-of-00210.parquet +3 -0
- data/train-00017-of-00210.parquet +3 -0
- data/train-00018-of-00210.parquet +3 -0
- data/train-00019-of-00210.parquet +3 -0
- data/train-00020-of-00210.parquet +3 -0
- data/train-00021-of-00210.parquet +3 -0
- data/train-00022-of-00210.parquet +3 -0
- data/train-00023-of-00210.parquet +3 -0
- data/train-00024-of-00210.parquet +3 -0
- data/train-00025-of-00210.parquet +3 -0
- data/train-00026-of-00210.parquet +3 -0
- data/train-00027-of-00210.parquet +3 -0
- data/train-00028-of-00210.parquet +3 -0
- data/train-00029-of-00210.parquet +3 -0
- data/train-00030-of-00210.parquet +3 -0
- data/train-00031-of-00210.parquet +3 -0
- data/train-00032-of-00210.parquet +3 -0
- data/train-00033-of-00210.parquet +3 -0
- data/train-00034-of-00210.parquet +3 -0
- data/train-00035-of-00210.parquet +3 -0
- data/train-00036-of-00210.parquet +3 -0
- data/train-00037-of-00210.parquet +3 -0
- data/train-00038-of-00210.parquet +3 -0
- data/train-00039-of-00210.parquet +3 -0
- data/train-00040-of-00210.parquet +3 -0
- data/train-00041-of-00210.parquet +3 -0
- data/train-00042-of-00210.parquet +3 -0
- data/train-00043-of-00210.parquet +3 -0
- data/train-00044-of-00210.parquet +3 -0
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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
---
|
| 2 |
+
pretty_name: PubMed Metadata V2
|
| 3 |
+
license: other
|
| 4 |
+
language:
|
| 5 |
+
- multilingual
|
| 6 |
+
task_categories:
|
| 7 |
+
- text-retrieval
|
| 8 |
+
size_categories:
|
| 9 |
+
- 10M<n<100M
|
| 10 |
+
tags:
|
| 11 |
+
- pubmed
|
| 12 |
+
- pubmed-central
|
| 13 |
+
- biomedical
|
| 14 |
+
- scholarly-metadata
|
| 15 |
+
- open-access
|
| 16 |
+
dataset_info:
|
| 17 |
+
features:
|
| 18 |
+
- name: pmid
|
| 19 |
+
dtype: uint32
|
| 20 |
+
- name: pmcid
|
| 21 |
+
dtype: large_string
|
| 22 |
+
- name: doi
|
| 23 |
+
dtype: large_string
|
| 24 |
+
- name: title
|
| 25 |
+
dtype: large_string
|
| 26 |
+
- name: abstract
|
| 27 |
+
dtype: large_string
|
| 28 |
+
- name: journal
|
| 29 |
+
dtype: large_string
|
| 30 |
+
- name: year
|
| 31 |
+
dtype: uint16
|
| 32 |
+
- name: publication_month
|
| 33 |
+
dtype: uint8
|
| 34 |
+
- name: publication_day
|
| 35 |
+
dtype: uint8
|
| 36 |
+
- name: issn
|
| 37 |
+
dtype: large_string
|
| 38 |
+
- name: eissn
|
| 39 |
+
dtype: large_string
|
| 40 |
+
- name: is_oa
|
| 41 |
+
dtype: bool
|
| 42 |
+
- name: issn_linking
|
| 43 |
+
dtype: large_string
|
| 44 |
+
- name: journal_abbrev
|
| 45 |
+
dtype: large_string
|
| 46 |
+
- name: nlm_unique_id
|
| 47 |
+
dtype: large_string
|
| 48 |
+
- name: country
|
| 49 |
+
dtype: large_string
|
| 50 |
+
- name: volume
|
| 51 |
+
dtype: large_string
|
| 52 |
+
- name: issue
|
| 53 |
+
dtype: large_string
|
| 54 |
+
- name: pages
|
| 55 |
+
dtype: large_string
|
| 56 |
+
- name: date_completed
|
| 57 |
+
dtype: date32
|
| 58 |
+
- name: date_revised
|
| 59 |
+
dtype: date32
|
| 60 |
+
- name: citation_status
|
| 61 |
+
dtype: string
|
| 62 |
+
- name: publication_status
|
| 63 |
+
dtype: string
|
| 64 |
+
- name: pub_model
|
| 65 |
+
dtype: string
|
| 66 |
+
- name: vernacular_title
|
| 67 |
+
dtype: large_string
|
| 68 |
+
- name: authors
|
| 69 |
+
large_list:
|
| 70 |
+
- name: display_name
|
| 71 |
+
dtype: large_string
|
| 72 |
+
- name: last_name
|
| 73 |
+
dtype: large_string
|
| 74 |
+
- name: fore_name
|
| 75 |
+
dtype: large_string
|
| 76 |
+
- name: initials
|
| 77 |
+
dtype: large_string
|
| 78 |
+
- name: suffix
|
| 79 |
+
dtype: large_string
|
| 80 |
+
- name: collective_name
|
| 81 |
+
dtype: large_string
|
| 82 |
+
- name: orcid
|
| 83 |
+
dtype: large_string
|
| 84 |
+
- name: affiliations
|
| 85 |
+
large_list: large_string
|
| 86 |
+
- name: valid
|
| 87 |
+
dtype: bool
|
| 88 |
+
- name: equal_contrib
|
| 89 |
+
dtype: bool
|
| 90 |
+
- name: publication_types
|
| 91 |
+
large_list: large_string
|
| 92 |
+
- name: languages
|
| 93 |
+
large_list: large_string
|
| 94 |
+
- name: mesh_terms
|
| 95 |
+
large_list: large_string
|
| 96 |
+
- name: mesh_major_topics
|
| 97 |
+
large_list: large_string
|
| 98 |
+
- name: keywords
|
| 99 |
+
large_list: large_string
|
| 100 |
+
- name: article_ids
|
| 101 |
+
large_list: large_string
|
| 102 |
+
splits:
|
| 103 |
+
- name: train
|
| 104 |
+
num_examples: 41860640
|
| 105 |
+
configs:
|
| 106 |
+
- config_name: default
|
| 107 |
+
data_files:
|
| 108 |
+
- split: train
|
| 109 |
+
path: data/train-*
|
| 110 |
+
---
|
| 111 |
+
|
| 112 |
+
# PubMed Metadata V2
|
| 113 |
+
|
| 114 |
+
An updated, V1-schema-compatible Parquet snapshot of PubMed citation metadata,
|
| 115 |
+
augmented with PMC records that were not safely represented in PubMed's current
|
| 116 |
+
PMID-to-PMCID mapping.
|
| 117 |
+
|
| 118 |
+
The PubMed portion was built from the NLM PubMed 2026 annual baseline and daily
|
| 119 |
+
update XML files through `pubmed26n1592.xml.gz`. Updates are applied in numeric
|
| 120 |
+
order, revised records replace earlier versions, and citations whose latest event
|
| 121 |
+
is a deletion are omitted. The dataset was built on 2026-08-16.
|
| 122 |
+
|
| 123 |
+
The single `train` split contains **41,860,640 records**:
|
| 124 |
+
|
| 125 |
+
- 40,990,549 records have a unique, non-null PMID;
|
| 126 |
+
- 870,091 PMC-only records have a null PMID and are keyed by PMCID;
|
| 127 |
+
- 879,135 validated PMC records were added to the current PubMed snapshot; and
|
| 128 |
+
- 2,553 existing PMID rows were safely updated with their missing PMCID and
|
| 129 |
+
available metadata.
|
| 130 |
+
|
| 131 |
+
Compared with `haydn-jones/PubMed-Metadata`, V2 has 915,429 additional records and
|
| 132 |
+
retains the same 32 columns and logical Arrow types. Ambiguous identifier conflicts
|
| 133 |
+
were excluded rather than guessed. PMC matching and external metadata retrieval used
|
| 134 |
+
exact PMCID or DOI identifiers only; no title/author fuzzy matching was used.
|
| 135 |
+
|
| 136 |
+
## Usage
|
| 137 |
+
|
| 138 |
+
Streaming avoids downloading the entire dataset:
|
| 139 |
+
|
| 140 |
+
```python
|
| 141 |
+
from datasets import load_dataset
|
| 142 |
+
|
| 143 |
+
papers = load_dataset(
|
| 144 |
+
"haydn-jones/PubMed-Metadata-V2",
|
| 145 |
+
split="train",
|
| 146 |
+
streaming=True,
|
| 147 |
+
)
|
| 148 |
+
|
| 149 |
+
first_paper = next(iter(papers))
|
| 150 |
+
```
|
| 151 |
+
|
| 152 |
+
For a local memory-mapped dataset:
|
| 153 |
+
|
| 154 |
+
```python
|
| 155 |
+
from datasets import load_dataset
|
| 156 |
+
|
| 157 |
+
papers = load_dataset("haydn-jones/PubMed-Metadata-V2", split="train")
|
| 158 |
+
```
|
| 159 |
+
|
| 160 |
+
PMID remains unique whenever present. For a unique key across the whole dataset,
|
| 161 |
+
use the PMID when non-null and otherwise use the PMCID.
|
| 162 |
+
|
| 163 |
+
## Open-access flag
|
| 164 |
+
|
| 165 |
+
`is_oa` is a non-null operational full-text accessibility flag:
|
| 166 |
+
|
| 167 |
+
```text
|
| 168 |
+
pmcid is present
|
| 169 |
+
OR
|
| 170 |
+
(issn, eissn, or issn_linking matches a current DOAJ journal
|
| 171 |
+
AND publication year >= that journal's all-content open-license start year)
|
| 172 |
+
```
|
| 173 |
+
|
| 174 |
+
- 12,906,383 rows are marked `is_oa=true`.
|
| 175 |
+
- 12,338,603 rows have a PMCID; every one is marked `is_oa=true`.
|
| 176 |
+
- 567,780 rows are marked open through the date-aware DOAJ rule without a PMCID.
|
| 177 |
+
|
| 178 |
+
This flag indicates practical full-text accessibility. It does **not** assert that
|
| 179 |
+
an article has a permissive reuse license: PMC content has article-specific rights,
|
| 180 |
+
and users must check the applicable license before reuse.
|
| 181 |
+
|
| 182 |
+
## Columns
|
| 183 |
+
|
| 184 |
+
| Column | Type | Description |
|
| 185 |
+
|---|---|---|
|
| 186 |
+
| `pmid` | `uint32` | PubMed identifier; unique when present. Null for PMC-only records without a safely resolved PMID. |
|
| 187 |
+
| `pmcid` | string | PubMed Central identifier, when available. |
|
| 188 |
+
| `doi` | string | Digital Object Identifier, normalized to its identifier value. |
|
| 189 |
+
| `title` | string | Article or book-document title as plain text. |
|
| 190 |
+
| `abstract` | string | Abstract sections joined with newlines; section labels are retained. |
|
| 191 |
+
| `journal` | string | Full journal title. |
|
| 192 |
+
| `year` | `uint16` | Best available publication year. |
|
| 193 |
+
| `publication_month` | `uint8` | Explicit publication month, when available. |
|
| 194 |
+
| `publication_day` | `uint8` | Explicit publication day, when available. |
|
| 195 |
+
| `issn` | string | Print ISSN. |
|
| 196 |
+
| `eissn` | string | Electronic ISSN. |
|
| 197 |
+
| `is_oa` | boolean | PMCID-or-date-aware-DOAJ accessibility flag described above. |
|
| 198 |
+
| `issn_linking` | string | NLM linking ISSN used to associate journal formats and title histories. |
|
| 199 |
+
| `journal_abbrev` | string | NLM/ISO journal abbreviation. |
|
| 200 |
+
| `nlm_unique_id` | string | NLM Catalog identifier for the journal. |
|
| 201 |
+
| `country` | string | Journal publication country recorded by NLM. |
|
| 202 |
+
| `volume` | string | Journal volume; kept as text because values are not always numeric. |
|
| 203 |
+
| `issue` | string | Journal issue; kept as text because values are not always numeric. |
|
| 204 |
+
| `pages` | string | Pagination or electronic location text. |
|
| 205 |
+
| `date_completed` | date | Date NLM completed processing the citation. |
|
| 206 |
+
| `date_revised` | date | Most recent explicit revision date in the record. |
|
| 207 |
+
| `citation_status` | string | PubMed/Medline citation status. |
|
| 208 |
+
| `publication_status` | string | PubMed publication status such as `ppublish` or `epublish`. |
|
| 209 |
+
| `pub_model` | string | Print/electronic publication model. |
|
| 210 |
+
| `vernacular_title` | string | Title in the original language, when supplied separately. |
|
| 211 |
+
| `authors` | list of structs | Ordered authors, including names, ORCID, affiliations, validity, and equal-contribution metadata. |
|
| 212 |
+
| `publication_types` | list of strings | NLM publication-type labels. |
|
| 213 |
+
| `languages` | list of strings | PubMed language codes. |
|
| 214 |
+
| `mesh_terms` | list of strings | MeSH descriptor headings assigned to the citation. |
|
| 215 |
+
| `mesh_major_topics` | list of strings | MeSH descriptors or descriptor/qualifier combinations marked as major topics. |
|
| 216 |
+
| `keywords` | list of strings | Author, publisher, or indexing keywords. |
|
| 217 |
+
| `article_ids` | list of strings | Identifier values carried in the source record. |
|
| 218 |
+
|
| 219 |
+
Each element of `authors` has this structure:
|
| 220 |
+
|
| 221 |
+
```text
|
| 222 |
+
display_name: string
|
| 223 |
+
last_name: string
|
| 224 |
+
fore_name: string
|
| 225 |
+
initials: string
|
| 226 |
+
suffix: string
|
| 227 |
+
collective_name: string
|
| 228 |
+
orcid: string
|
| 229 |
+
affiliations: list[string]
|
| 230 |
+
valid: bool
|
| 231 |
+
equal_contrib: bool
|
| 232 |
+
```
|
| 233 |
+
|
| 234 |
+
## Reproduction
|
| 235 |
+
|
| 236 |
+
The PubMed XML parsing and cleaning scripts are included under `scripts/`. The DOAJ
|
| 237 |
+
journal CSV used for the date-aware OA flag is included under `sources/`.
|
| 238 |
+
|
| 239 |
+
Mirror the PubMed baseline and updates from NCBI, including checksum sidecars:
|
| 240 |
+
|
| 241 |
+
```bash
|
| 242 |
+
lftp -e "
|
| 243 |
+
set net:connection-limit 8;
|
| 244 |
+
mirror --parallel=8 --continue --use-pget-n=4 \
|
| 245 |
+
-I '*.xml.gz' -I '*.xml.gz.md5' \
|
| 246 |
+
/pubmed/baseline/ /path/to/pubmed/baseline/;
|
| 247 |
+
mirror --parallel=8 --continue --use-pget-n=4 \
|
| 248 |
+
-I '*.xml.gz' -I '*.xml.gz.md5' \
|
| 249 |
+
/pubmed/updatefiles/ /path/to/pubmed/updatefiles/;
|
| 250 |
+
quit
|
| 251 |
+
" https://ftp.ncbi.nlm.nih.gov
|
| 252 |
+
```
|
| 253 |
+
|
| 254 |
+
Build a current-state raw Parquet file:
|
| 255 |
+
|
| 256 |
+
```bash
|
| 257 |
+
uv run --with pyarrow --with tqdm python scripts/pubmed_xml_to_parquet.py \
|
| 258 |
+
--input-root /path/to/pubmed \
|
| 259 |
+
--output papers.parquet \
|
| 260 |
+
--workers 8
|
| 261 |
+
```
|
| 262 |
+
|
| 263 |
+
Produce the typed, DOAJ-enriched file:
|
| 264 |
+
|
| 265 |
+
```bash
|
| 266 |
+
uv run --with polars --with pyarrow python scripts/clean_pubmed_parquet.py \
|
| 267 |
+
papers.parquet papers_clean.parquet \
|
| 268 |
+
--doaj-csv sources/doaj_journalcsv_20260709_2320_utf8.csv
|
| 269 |
+
```
|
| 270 |
+
|
| 271 |
+
Both scripts write through a partial file and replace the destination atomically.
|
| 272 |
+
The XML builder validates the NLM MD5 sidecars by default.
|
| 273 |
+
|
| 274 |
+
## Sources and terms
|
| 275 |
+
|
| 276 |
+
- Citation metadata: [NLM PubMed baseline and daily update files](https://pubmed.ncbi.nlm.nih.gov/download/).
|
| 277 |
+
- PMC metadata: [PubMed Central Open Access bulk data](https://pmc.ncbi.nlm.nih.gov/tools/ftp/).
|
| 278 |
+
- OA journal metadata: [DOAJ Journal CSV](https://doaj.org/docs/journal-csv).
|
| 279 |
+
- DOAJ metadata terms: [DOAJ terms and conditions](https://doaj.org/terms/).
|
| 280 |
+
- Additional exact-identifier gap filling used NCBI ESummary, Europe PMC, OpenAlex,
|
| 281 |
+
and Crossref metadata.
|
data/train-00000-of-00210.parquet
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:866f8e154d43d302e950d792e9e72abb9193a65d0007fd9856df9f2feb9ae67a
|
| 3 |
+
size 27935538
|
data/train-00001-of-00210.parquet
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:9ea497d4a1068e5d2cc11686323916f7e639c351867889f9046ee7292738cc21
|
| 3 |
+
size 46623876
|
data/train-00002-of-00210.parquet
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:018996ff6451169c342c32bd04f962bfe0da1d48f1118aeefa77df7ab222af4b
|
| 3 |
+
size 43904224
|
data/train-00003-of-00210.parquet
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:d59640166eebfe7855082fdbb8d4ae6fedbd3c377e7d456bc41917796f2e487d
|
| 3 |
+
size 62967113
|
data/train-00004-of-00210.parquet
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:e4af56e06ec794735599d5167cc6c812f26198f861db1c58352526ce3ea6bd3c
|
| 3 |
+
size 49638807
|
data/train-00005-of-00210.parquet
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:c9ac00116798b6ba4cb1453f6b0659ade98393866f58be7f7598229ac41b0ce1
|
| 3 |
+
size 67510994
|
data/train-00006-of-00210.parquet
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:d796cb304a6ba8c104490516f05360857d3e6d6eddb4105ba6a36522b0b6c3d1
|
| 3 |
+
size 62352905
|
data/train-00007-of-00210.parquet
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:999cc5a3c321ceaab2d401d45302de59dbe5651a419852f9de52855a3d193904
|
| 3 |
+
size 60850009
|
data/train-00008-of-00210.parquet
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:5dbab1c10f128a84cf7215e94b567626e9226c2bb03506a065e9d43a0fbe354f
|
| 3 |
+
size 51821746
|
data/train-00009-of-00210.parquet
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:4424d5f7e9237e356cfbfdac2e5a355e01630e7527bcc2ea02b46b85e5db32b8
|
| 3 |
+
size 44834522
|
data/train-00010-of-00210.parquet
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:3be23f922785178804ef5f380f8b1bb345bbc7918335b03cc910f7d12d205a6b
|
| 3 |
+
size 59711503
|
data/train-00011-of-00210.parquet
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:2e516a076b4f2583e152abb12e0aeef4f9341f7f6b15ada84b0e47fb7c0ed1a3
|
| 3 |
+
size 66966669
|
data/train-00012-of-00210.parquet
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:8646b9b94bc8013287c3af61bc9f4eaba6119c99def78f52f2e0d5c2ed8d06b7
|
| 3 |
+
size 55741717
|
data/train-00013-of-00210.parquet
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:9dbd7cd460db8cceca173cf6ad99c2b25592fc04b8fa1b25939a11d9f094bd13
|
| 3 |
+
size 43525945
|
data/train-00014-of-00210.parquet
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:2136c4c3b540e41f7c40cdc148ca8bed2e12de416a1b863f5c971358c8549d81
|
| 3 |
+
size 50783945
|
data/train-00015-of-00210.parquet
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:54395cc44ad07da4c728b6a32c3e325e511304cdab7bff2ea78cd3e488f90c80
|
| 3 |
+
size 49743987
|
data/train-00016-of-00210.parquet
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:cf7b2e44ad4ac9bd77b11e2e61a44c32c01c3c8743f8357d46019503264bef80
|
| 3 |
+
size 50539484
|
data/train-00017-of-00210.parquet
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:ccbc2df419f1b1ec86ff54f3e584472cf753207429e49e0a56984f83191eb702
|
| 3 |
+
size 63468580
|
data/train-00018-of-00210.parquet
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:2ca1d7ab96ba937787c93993ea7db81d99b9d6a7cbdaf2e7ed5421782cbfe8fb
|
| 3 |
+
size 47374252
|
data/train-00019-of-00210.parquet
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:2cb844cd95940f5f1ea6c7825b2ecd5334b5939d1c13ed0aff83b77f4514d96f
|
| 3 |
+
size 82080435
|
data/train-00020-of-00210.parquet
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:6046d9d657e986e856acf52181eca3020a3a4c57c1e4af143c10c4fc9e2033a3
|
| 3 |
+
size 73379015
|
data/train-00021-of-00210.parquet
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:3894d42439e2992688aec86a2fe1044845d4f0fcc1ba826f438db1a641a3859e
|
| 3 |
+
size 70267072
|
data/train-00022-of-00210.parquet
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:78c31885e7f8adb68b8adb9cde6c949931b8c8d92c82da41af27e7aa7a4e2722
|
| 3 |
+
size 43778256
|
data/train-00023-of-00210.parquet
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:711b31281370bb4d25820008d751c8ba8cfa5c6246568ff915ec10c3a703fce1
|
| 3 |
+
size 61530143
|
data/train-00024-of-00210.parquet
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:8888a28c942fcf054fcba7b6d07806db95733960ab3f23b373417cb681200c03
|
| 3 |
+
size 64821060
|
data/train-00025-of-00210.parquet
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:707bad7a8fe9427067b8fe32f83cc0e8f6ca28d38308452b83c07c94d0ee482e
|
| 3 |
+
size 49371703
|
data/train-00026-of-00210.parquet
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:86ba5f2890a3a5fb5ee25ce380e2d8568576f55bee8ec02680ab187b4a76dff6
|
| 3 |
+
size 63968778
|
data/train-00027-of-00210.parquet
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:80c24730f9bf29936e39f9c33892bd40922dddc5176a2da118e10001b66c36d3
|
| 3 |
+
size 38828286
|
data/train-00028-of-00210.parquet
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:e7affa9650a3f396326efcc9aabd8b64884e8c25046f0549ad52160e16e2e89c
|
| 3 |
+
size 63769918
|
data/train-00029-of-00210.parquet
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:79beb6acd02e771f55be954b6c789f54f8dd059fba34a0dc6af84dafda73476c
|
| 3 |
+
size 60207928
|
data/train-00030-of-00210.parquet
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:610a34840fb8244bd9ed4546ba929d71602125c9fdb5d6dac6afb9d4d4976eb4
|
| 3 |
+
size 55972178
|
data/train-00031-of-00210.parquet
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:c8156109ccaa74ea92e49bbf12fb0b5c4beb6f5a6ad2a22617f9c6b8b9fbbee1
|
| 3 |
+
size 63800231
|
data/train-00032-of-00210.parquet
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:0fcb85b8306bfcbb0ecbf03febd26693dad4ed5b546575327e44fc4ef5d30699
|
| 3 |
+
size 63322953
|
data/train-00033-of-00210.parquet
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:47eb6d96e622764d4502bbf9884d9e1557ba0fa7c6846748bef9ef5264aaca12
|
| 3 |
+
size 53050831
|
data/train-00034-of-00210.parquet
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:0772919787febd2c8e0a61f0cfe064415b58a7a0f1d923b0f44a6a8e326091f5
|
| 3 |
+
size 82622056
|
data/train-00035-of-00210.parquet
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:d17c115343cfa312d0866116605c98dd9c977cd78c6885245b312ca46c617bd7
|
| 3 |
+
size 66464741
|
data/train-00036-of-00210.parquet
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:05ace61943cadef4a1476e703c393791e59954ec13650cf64bd76f5141299eff
|
| 3 |
+
size 62260948
|
data/train-00037-of-00210.parquet
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:cbe1ef15f86f3dcae0119b20b8417494a511c115679bee4cbc9646cba4468a55
|
| 3 |
+
size 61694372
|
data/train-00038-of-00210.parquet
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:5aa351ac776593aac47e80b7811b9408e2ea01f00a196cdcd9cb4da40c9dd018
|
| 3 |
+
size 67415677
|
data/train-00039-of-00210.parquet
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:e2b0b84d7dfa74f92c35dff5064103cd7451a4d8c318e47a702120008c4b05b9
|
| 3 |
+
size 92999623
|
data/train-00040-of-00210.parquet
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:06b2a0c60a1561079e9d24321d82c1f2d0081d94f162b4bf801c85d9b8055fed
|
| 3 |
+
size 60971355
|
data/train-00041-of-00210.parquet
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:93a6927436f6c38457610df4f69ed74c129dbb82191e5d9874fdf3a9d96afebe
|
| 3 |
+
size 76476465
|
data/train-00042-of-00210.parquet
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:cae38c33a1cb71b0411675d53853fc523c233c5a798a436dda9bee543ef8bba3
|
| 3 |
+
size 88006811
|
data/train-00043-of-00210.parquet
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:f9220578679065ea2fccb31dd7e6c688e913542bf841c1aaa34352de45eccfce
|
| 3 |
+
size 71083310
|
data/train-00044-of-00210.parquet
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:147cde15b7e42aa4a1bccf69a9b7357904881189106b1c5a01f9f58b99425d2b
|
| 3 |
+
size 49601398
|
data/train-00045-of-00210.parquet
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:56feecc6c435fc0c999770966bd3ba8c10d5071ff9ae7562d21dbcd466b07b2c
|
| 3 |
+
size 60237327
|
data/train-00046-of-00210.parquet
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:6f73a24bc55daefad7fc63b2d0fed8d68b0c55ccc89215a3fce48e9883eaa7e9
|
| 3 |
+
size 72631487
|
scripts/clean_pubmed_parquet.py
ADDED
|
@@ -0,0 +1,174 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Rewrite PubMed metadata Parquet with compact, query-friendly scalar types."""
|
| 2 |
+
|
| 3 |
+
from __future__ import annotations
|
| 4 |
+
|
| 5 |
+
import argparse
|
| 6 |
+
import hashlib
|
| 7 |
+
import re
|
| 8 |
+
from datetime import datetime
|
| 9 |
+
from pathlib import Path
|
| 10 |
+
|
| 11 |
+
import polars as pl
|
| 12 |
+
import pyarrow.parquet as pq
|
| 13 |
+
|
| 14 |
+
CITATION_STATUS = pl.Enum(["In-Data-Review", "In-Process", "MEDLINE", "PubMed-not-MEDLINE", "Publisher"])
|
| 15 |
+
PUBLICATION_STATUS = pl.Enum(["aheadofprint", "epublish", "ppublish"])
|
| 16 |
+
PUB_MODEL = pl.Enum(["Electronic", "Electronic-Print", "Electronic-eCollection", "Print", "Print-Electronic"])
|
| 17 |
+
DOAJ_START_YEAR = "When did the journal start to publish all content using an open license?"
|
| 18 |
+
DOAJ_PRINT_ISSN = "Journal ISSN (print version)"
|
| 19 |
+
DOAJ_EISSN = "Journal EISSN (online version)"
|
| 20 |
+
DOAJ_COMPLIES = "Does the journal comply to DOAJ's definition of open access?"
|
| 21 |
+
|
| 22 |
+
|
| 23 |
+
def _parquet_metadata(path: Path) -> dict[str, str]:
|
| 24 |
+
metadata = pq.read_metadata(path).metadata or {}
|
| 25 |
+
return {key.decode(): value.decode() for key, value in metadata.items() if key != b"ARROW:schema"}
|
| 26 |
+
|
| 27 |
+
|
| 28 |
+
def _normalized_issn(column: str) -> pl.Expr:
|
| 29 |
+
return pl.col(column).cast(pl.String).str.to_uppercase().str.replace_all(r"[^0-9X]", "")
|
| 30 |
+
|
| 31 |
+
|
| 32 |
+
def _doaj_issn_start_years(path: Path) -> pl.DataFrame:
|
| 33 |
+
if not path.is_file():
|
| 34 |
+
raise FileNotFoundError(path)
|
| 35 |
+
|
| 36 |
+
journals = pl.read_csv(
|
| 37 |
+
path,
|
| 38 |
+
columns=[DOAJ_PRINT_ISSN, DOAJ_EISSN, DOAJ_START_YEAR, DOAJ_COMPLIES],
|
| 39 |
+
schema_overrides={
|
| 40 |
+
DOAJ_PRINT_ISSN: pl.String,
|
| 41 |
+
DOAJ_EISSN: pl.String,
|
| 42 |
+
DOAJ_START_YEAR: pl.String,
|
| 43 |
+
DOAJ_COMPLIES: pl.String,
|
| 44 |
+
},
|
| 45 |
+
null_values="",
|
| 46 |
+
).filter(pl.col(DOAJ_COMPLIES) == "Yes")
|
| 47 |
+
issns = pl.concat([
|
| 48 |
+
journals.select(pl.col(DOAJ_PRINT_ISSN).alias("issn"), pl.col(DOAJ_START_YEAR)),
|
| 49 |
+
journals.select(pl.col(DOAJ_EISSN).alias("issn"), pl.col(DOAJ_START_YEAR)),
|
| 50 |
+
]).with_columns(
|
| 51 |
+
_normalized_issn("issn").alias("issn"),
|
| 52 |
+
pl.col(DOAJ_START_YEAR).cast(pl.UInt16).alias("oa_start_year"),
|
| 53 |
+
)
|
| 54 |
+
return issns.filter(pl.col("issn").str.len_chars() == 8).group_by("issn").agg(pl.col("oa_start_year").min())
|
| 55 |
+
|
| 56 |
+
|
| 57 |
+
def _add_is_oa(source: pl.LazyFrame, doaj_csv_path: Path) -> pl.LazyFrame:
|
| 58 |
+
lookup = _doaj_issn_start_years(doaj_csv_path).lazy()
|
| 59 |
+
issn_columns = ["issn", "eissn", "issn_linking"]
|
| 60 |
+
source = source.with_columns(*(_normalized_issn(column).alias(f"__{column}") for column in issn_columns))
|
| 61 |
+
start_columns: list[str] = []
|
| 62 |
+
for column in issn_columns:
|
| 63 |
+
key = f"__{column}"
|
| 64 |
+
start = f"__{column}_oa_start_year"
|
| 65 |
+
start_columns.append(start)
|
| 66 |
+
source = source.join(
|
| 67 |
+
lookup.rename({"issn": key, "oa_start_year": start}),
|
| 68 |
+
on=key,
|
| 69 |
+
how="left",
|
| 70 |
+
)
|
| 71 |
+
|
| 72 |
+
return source.with_columns(pl.min_horizontal(start_columns).alias("__oa_start_year")).with_columns(
|
| 73 |
+
(pl.col("pmcid").is_not_null() | (pl.col("year") >= pl.col("__oa_start_year")).fill_null(False)).alias("is_oa")
|
| 74 |
+
)
|
| 75 |
+
|
| 76 |
+
|
| 77 |
+
def _doaj_metadata(path: Path, lookup_rows: int) -> dict[str, str]:
|
| 78 |
+
with path.open("rb") as handle:
|
| 79 |
+
checksum = hashlib.file_digest(handle, "sha256").hexdigest()
|
| 80 |
+
date_match = re.search(r"doaj_journalcsv_(\d{8})", path.name)
|
| 81 |
+
snapshot_date = datetime.strptime(date_match.group(1), "%Y%m%d").date().isoformat() if date_match else "unknown"
|
| 82 |
+
return {
|
| 83 |
+
"doaj_source": "https://doaj.org/csv",
|
| 84 |
+
"doaj_snapshot_date": snapshot_date,
|
| 85 |
+
"doaj_csv_sha256": checksum,
|
| 86 |
+
"doaj_unique_issns": str(lookup_rows),
|
| 87 |
+
"is_oa_definition": (
|
| 88 |
+
"true when PMCID is present, or when issn, eissn, or issn_linking matches a current DOAJ journal "
|
| 89 |
+
"and publication year is at least the journal's all-content open-license start year; this indicates "
|
| 90 |
+
"practical full-text accessibility, not necessarily a permissive reuse license"
|
| 91 |
+
),
|
| 92 |
+
}
|
| 93 |
+
|
| 94 |
+
|
| 95 |
+
def clean_pubmed_parquet(
|
| 96 |
+
input_path: Path,
|
| 97 |
+
output_path: Path,
|
| 98 |
+
*,
|
| 99 |
+
doaj_csv_path: Path | None = None,
|
| 100 |
+
overwrite: bool = False,
|
| 101 |
+
) -> None:
|
| 102 |
+
"""Stream ``input_path`` into an atomically replaced, typed Parquet file."""
|
| 103 |
+
if not input_path.is_file():
|
| 104 |
+
raise FileNotFoundError(input_path)
|
| 105 |
+
if output_path.exists() and not overwrite:
|
| 106 |
+
raise FileExistsError(f"Output already exists: {output_path}; pass --overwrite to replace it")
|
| 107 |
+
|
| 108 |
+
partial_path = output_path.with_name(f".{output_path.name}.partial")
|
| 109 |
+
if partial_path.exists():
|
| 110 |
+
raise FileExistsError(f"Refusing to overwrite existing partial output: {partial_path}")
|
| 111 |
+
|
| 112 |
+
source = pl.scan_parquet(input_path)
|
| 113 |
+
source_columns = source.collect_schema().names()
|
| 114 |
+
if "publication_date" not in source_columns:
|
| 115 |
+
raise ValueError("Input is missing required publication_date column")
|
| 116 |
+
|
| 117 |
+
output_columns = (
|
| 118 |
+
source_columns[:7]
|
| 119 |
+
+ ["publication_month", "publication_day"]
|
| 120 |
+
+ [column for column in source_columns[7:] if column != "publication_date"]
|
| 121 |
+
)
|
| 122 |
+
if doaj_csv_path is not None:
|
| 123 |
+
source = _add_is_oa(source, doaj_csv_path)
|
| 124 |
+
output_columns.insert(output_columns.index("eissn") + 1, "is_oa")
|
| 125 |
+
typed = source.with_columns(
|
| 126 |
+
pl.col("pmid").cast(pl.UInt32),
|
| 127 |
+
pl.col("year").cast(pl.UInt16),
|
| 128 |
+
pl.col("publication_date").str.slice(5, 2).cast(pl.UInt8, strict=False).alias("publication_month"),
|
| 129 |
+
pl.col("publication_date").str.slice(8, 2).cast(pl.UInt8, strict=False).alias("publication_day"),
|
| 130 |
+
pl.col("date_completed").str.to_date("%Y-%m-%d", strict=True),
|
| 131 |
+
pl.col("date_revised").str.to_date("%Y-%m-%d", strict=True),
|
| 132 |
+
pl.col("citation_status").cast(CITATION_STATUS),
|
| 133 |
+
pl.col("publication_status").cast(PUBLICATION_STATUS),
|
| 134 |
+
pl.col("pub_model").cast(PUB_MODEL),
|
| 135 |
+
).select(output_columns)
|
| 136 |
+
|
| 137 |
+
metadata = _parquet_metadata(input_path)
|
| 138 |
+
metadata["transform"] = (
|
| 139 |
+
"pmid=uint32; year=uint16; publication_date split into uint8 month/day; "
|
| 140 |
+
"completion/revision dates=date32; bounded statuses=enum"
|
| 141 |
+
)
|
| 142 |
+
if doaj_csv_path is not None:
|
| 143 |
+
metadata.update(_doaj_metadata(doaj_csv_path, _doaj_issn_start_years(doaj_csv_path).height))
|
| 144 |
+
output_path.parent.mkdir(parents=True, exist_ok=True)
|
| 145 |
+
try:
|
| 146 |
+
typed.sink_parquet(
|
| 147 |
+
partial_path,
|
| 148 |
+
compression="zstd",
|
| 149 |
+
compression_level=3,
|
| 150 |
+
statistics=True,
|
| 151 |
+
row_group_size=100_000,
|
| 152 |
+
data_page_size=1024 * 1024,
|
| 153 |
+
maintain_order=True,
|
| 154 |
+
sync_on_close="data",
|
| 155 |
+
metadata=metadata,
|
| 156 |
+
)
|
| 157 |
+
partial_path.replace(output_path)
|
| 158 |
+
except BaseException:
|
| 159 |
+
partial_path.unlink(missing_ok=True)
|
| 160 |
+
raise
|
| 161 |
+
|
| 162 |
+
|
| 163 |
+
def main() -> None:
|
| 164 |
+
parser = argparse.ArgumentParser(description=__doc__)
|
| 165 |
+
parser.add_argument("input", type=Path, help="Source PubMed Parquet")
|
| 166 |
+
parser.add_argument("output", type=Path, help="Destination clean Parquet")
|
| 167 |
+
parser.add_argument("--doaj-csv", type=Path, help="DOAJ journal CSV used to derive is_oa")
|
| 168 |
+
parser.add_argument("--overwrite", action="store_true", help="Atomically replace an existing output")
|
| 169 |
+
args = parser.parse_args()
|
| 170 |
+
clean_pubmed_parquet(args.input, args.output, doaj_csv_path=args.doaj_csv, overwrite=args.overwrite)
|
| 171 |
+
|
| 172 |
+
|
| 173 |
+
if __name__ == "__main__":
|
| 174 |
+
main()
|
scripts/pubmed_xml_to_parquet.py
ADDED
|
@@ -0,0 +1,838 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Build a current PubMed metadata Parquet file from NCBI's XML distribution.
|
| 2 |
+
|
| 3 |
+
The input directory is expected to contain the two directories mirrored from NCBI::
|
| 4 |
+
|
| 5 |
+
pubmed/
|
| 6 |
+
baseline/pubmed26n0001.xml.gz ...
|
| 7 |
+
updatefiles/pubmed26n1335.xml.gz ...
|
| 8 |
+
|
| 9 |
+
The baseline is a snapshot. Update files contain new, revised, and deleted records.
|
| 10 |
+
This script indexes the last update event for every PMID, writes unchanged baseline
|
| 11 |
+
records, and then writes only the final live version from the updates. The result has
|
| 12 |
+
one row per current PMID without needing to hold the corpus in memory.
|
| 13 |
+
|
| 14 |
+
Example::
|
| 15 |
+
|
| 16 |
+
uv run --group dev python scripts/pubmed_xml_to_parquet.py \
|
| 17 |
+
--input-root /mnt/data/pubmed_corpus/pubmed \
|
| 18 |
+
--output /mnt/data/pubmed_corpus/papers.parquet
|
| 19 |
+
"""
|
| 20 |
+
|
| 21 |
+
from __future__ import annotations
|
| 22 |
+
|
| 23 |
+
import argparse
|
| 24 |
+
import concurrent.futures
|
| 25 |
+
import contextlib
|
| 26 |
+
import gzip
|
| 27 |
+
import hashlib
|
| 28 |
+
import os
|
| 29 |
+
import re
|
| 30 |
+
import sqlite3
|
| 31 |
+
import tempfile
|
| 32 |
+
from collections import deque
|
| 33 |
+
from collections.abc import Callable, Iterable, Iterator, Sequence
|
| 34 |
+
from dataclasses import dataclass
|
| 35 |
+
from pathlib import Path
|
| 36 |
+
from typing import Any
|
| 37 |
+
from xml.etree import ElementTree as ET
|
| 38 |
+
|
| 39 |
+
import pyarrow as pa
|
| 40 |
+
import pyarrow.parquet as pq
|
| 41 |
+
from tqdm.auto import tqdm
|
| 42 |
+
|
| 43 |
+
DEFAULT_INPUT_ROOT = Path("/mnt/data/pubmed_corpus/pubmed")
|
| 44 |
+
DEFAULT_WORKERS = min(8, os.process_cpu_count() or 1)
|
| 45 |
+
FILE_RE = re.compile(r"^pubmed(?P<release>\d{2})n(?P<sequence>\d{4})\.xml\.gz$")
|
| 46 |
+
YEAR_RE = re.compile(r"(?<!\d)(1[5-9]\d{2}|20\d{2}|2100)(?!\d)")
|
| 47 |
+
WHITESPACE_RE = re.compile(r"\s+")
|
| 48 |
+
ORCID_URL_RE = re.compile(r"^https?://orcid\.org/", re.IGNORECASE)
|
| 49 |
+
SQLITE_QUERY_CHUNK = 900
|
| 50 |
+
|
| 51 |
+
MONTHS = {
|
| 52 |
+
"jan": 1,
|
| 53 |
+
"feb": 2,
|
| 54 |
+
"mar": 3,
|
| 55 |
+
"apr": 4,
|
| 56 |
+
"may": 5,
|
| 57 |
+
"jun": 6,
|
| 58 |
+
"jul": 7,
|
| 59 |
+
"aug": 8,
|
| 60 |
+
"sep": 9,
|
| 61 |
+
"oct": 10,
|
| 62 |
+
"nov": 11,
|
| 63 |
+
"dec": 12,
|
| 64 |
+
}
|
| 65 |
+
|
| 66 |
+
AUTHOR_TYPE = pa.struct([
|
| 67 |
+
pa.field("display_name", pa.string(), nullable=False),
|
| 68 |
+
pa.field("last_name", pa.string()),
|
| 69 |
+
pa.field("fore_name", pa.string()),
|
| 70 |
+
pa.field("initials", pa.string()),
|
| 71 |
+
pa.field("suffix", pa.string()),
|
| 72 |
+
pa.field("collective_name", pa.string()),
|
| 73 |
+
pa.field("orcid", pa.string()),
|
| 74 |
+
pa.field("affiliations", pa.list_(pa.string())),
|
| 75 |
+
pa.field("valid", pa.bool_(), nullable=False),
|
| 76 |
+
pa.field("equal_contrib", pa.bool_()),
|
| 77 |
+
])
|
| 78 |
+
|
| 79 |
+
PARQUET_SCHEMA = pa.schema([
|
| 80 |
+
pa.field("pmid", pa.string(), nullable=False),
|
| 81 |
+
pa.field("pmcid", pa.string()),
|
| 82 |
+
pa.field("doi", pa.string()),
|
| 83 |
+
pa.field("title", pa.string()),
|
| 84 |
+
pa.field("abstract", pa.string()),
|
| 85 |
+
pa.field("journal", pa.string()),
|
| 86 |
+
pa.field("year", pa.int64()),
|
| 87 |
+
pa.field("issn", pa.string()),
|
| 88 |
+
pa.field("eissn", pa.string()),
|
| 89 |
+
pa.field("issn_linking", pa.string()),
|
| 90 |
+
pa.field("journal_abbrev", pa.string()),
|
| 91 |
+
pa.field("nlm_unique_id", pa.string()),
|
| 92 |
+
pa.field("country", pa.string()),
|
| 93 |
+
pa.field("volume", pa.string()),
|
| 94 |
+
pa.field("issue", pa.string()),
|
| 95 |
+
pa.field("pages", pa.string()),
|
| 96 |
+
pa.field("publication_date", pa.string()),
|
| 97 |
+
pa.field("date_completed", pa.string()),
|
| 98 |
+
pa.field("date_revised", pa.string()),
|
| 99 |
+
pa.field("citation_status", pa.string()),
|
| 100 |
+
pa.field("publication_status", pa.string()),
|
| 101 |
+
pa.field("pub_model", pa.string()),
|
| 102 |
+
pa.field("vernacular_title", pa.string()),
|
| 103 |
+
pa.field("authors", pa.list_(AUTHOR_TYPE)),
|
| 104 |
+
pa.field("publication_types", pa.list_(pa.string())),
|
| 105 |
+
pa.field("languages", pa.list_(pa.string())),
|
| 106 |
+
pa.field("mesh_terms", pa.list_(pa.string())),
|
| 107 |
+
pa.field("mesh_major_topics", pa.list_(pa.string())),
|
| 108 |
+
pa.field("keywords", pa.list_(pa.string())),
|
| 109 |
+
pa.field("article_ids", pa.list_(pa.string())),
|
| 110 |
+
])
|
| 111 |
+
|
| 112 |
+
Record = dict[str, Any]
|
| 113 |
+
|
| 114 |
+
|
| 115 |
+
@dataclass(frozen=True)
|
| 116 |
+
class DistributionFile:
|
| 117 |
+
path: Path
|
| 118 |
+
release: int
|
| 119 |
+
sequence: int
|
| 120 |
+
|
| 121 |
+
|
| 122 |
+
@dataclass
|
| 123 |
+
class ParsedFile:
|
| 124 |
+
table: pa.Table
|
| 125 |
+
event_count: int
|
| 126 |
+
|
| 127 |
+
|
| 128 |
+
def _local_name(tag: str) -> str:
|
| 129 |
+
"""Return an XML local name, including for embedded namespaced content."""
|
| 130 |
+
return tag.rsplit("}", 1)[-1]
|
| 131 |
+
|
| 132 |
+
|
| 133 |
+
def _element_text(element: ET.Element | None) -> str | None:
|
| 134 |
+
"""Extract mixed XML content and normalize formatting whitespace."""
|
| 135 |
+
if element is None:
|
| 136 |
+
return None
|
| 137 |
+
text = WHITESPACE_RE.sub(" ", "".join(element.itertext())).strip()
|
| 138 |
+
return text or None
|
| 139 |
+
|
| 140 |
+
|
| 141 |
+
def _text_at(parent: ET.Element | None, path: str) -> str | None:
|
| 142 |
+
return _element_text(parent.find(path)) if parent is not None else None
|
| 143 |
+
|
| 144 |
+
|
| 145 |
+
def _texts_at(parent: ET.Element | None, path: str) -> list[str]:
|
| 146 |
+
if parent is None:
|
| 147 |
+
return []
|
| 148 |
+
return [text for element in parent.findall(path) if (text := _element_text(element)) is not None]
|
| 149 |
+
|
| 150 |
+
|
| 151 |
+
def _unique(values: Iterable[str]) -> list[str]:
|
| 152 |
+
return list(dict.fromkeys(value for value in values if value))
|
| 153 |
+
|
| 154 |
+
|
| 155 |
+
def _abstract(parent: ET.Element | None) -> str | None:
|
| 156 |
+
if parent is None:
|
| 157 |
+
return None
|
| 158 |
+
sections: list[str] = []
|
| 159 |
+
for element in parent.findall("Abstract/AbstractText"):
|
| 160 |
+
text = _element_text(element)
|
| 161 |
+
if text is None:
|
| 162 |
+
continue
|
| 163 |
+
label = WHITESPACE_RE.sub(" ", element.attrib.get("Label", "")).strip()
|
| 164 |
+
sections.append(f"{label}: {text}" if label else text)
|
| 165 |
+
return "\n".join(sections) or None
|
| 166 |
+
|
| 167 |
+
|
| 168 |
+
def _authors(parent: ET.Element | None, paths: Sequence[str]) -> list[Record]:
|
| 169 |
+
if parent is None:
|
| 170 |
+
return []
|
| 171 |
+
|
| 172 |
+
authors: list[Record] = []
|
| 173 |
+
for path in paths:
|
| 174 |
+
for author in parent.findall(path):
|
| 175 |
+
collective_name = _text_at(author, "CollectiveName")
|
| 176 |
+
last_name = _text_at(author, "LastName")
|
| 177 |
+
fore_name = _text_at(author, "ForeName")
|
| 178 |
+
initials = _text_at(author, "Initials")
|
| 179 |
+
suffix = _text_at(author, "Suffix")
|
| 180 |
+
if collective_name:
|
| 181 |
+
display_name = collective_name
|
| 182 |
+
else:
|
| 183 |
+
display_name = " ".join(
|
| 184 |
+
part
|
| 185 |
+
for part in (
|
| 186 |
+
fore_name,
|
| 187 |
+
last_name,
|
| 188 |
+
suffix,
|
| 189 |
+
)
|
| 190 |
+
if part
|
| 191 |
+
)
|
| 192 |
+
|
| 193 |
+
orcid: str | None = None
|
| 194 |
+
for identifier in author.findall("Identifier"):
|
| 195 |
+
if identifier.attrib.get("Source", "").casefold() != "orcid":
|
| 196 |
+
continue
|
| 197 |
+
if value := _element_text(identifier):
|
| 198 |
+
orcid = orcid or ORCID_URL_RE.sub("", value)
|
| 199 |
+
|
| 200 |
+
equal_contrib_attribute = author.attrib.get("EqualContrib")
|
| 201 |
+
authors.append({
|
| 202 |
+
"display_name": display_name,
|
| 203 |
+
"last_name": last_name,
|
| 204 |
+
"fore_name": fore_name,
|
| 205 |
+
"initials": initials,
|
| 206 |
+
"suffix": suffix,
|
| 207 |
+
"collective_name": collective_name,
|
| 208 |
+
"orcid": orcid,
|
| 209 |
+
"affiliations": _unique(_texts_at(author, "AffiliationInfo/Affiliation")),
|
| 210 |
+
"valid": author.attrib.get("ValidYN", "Y") == "Y",
|
| 211 |
+
"equal_contrib": (equal_contrib_attribute == "Y" if equal_contrib_attribute is not None else None),
|
| 212 |
+
})
|
| 213 |
+
|
| 214 |
+
return authors
|
| 215 |
+
|
| 216 |
+
|
| 217 |
+
def _article_ids(*parents: ET.Element | None) -> tuple[dict[str, list[str]], list[str]]:
|
| 218 |
+
by_type: dict[str, list[str]] = {}
|
| 219 |
+
flattened: list[str] = []
|
| 220 |
+
for parent in parents:
|
| 221 |
+
if parent is None:
|
| 222 |
+
continue
|
| 223 |
+
for element in parent.findall("ArticleIdList/ArticleId"):
|
| 224 |
+
value = _element_text(element)
|
| 225 |
+
if value is None:
|
| 226 |
+
continue
|
| 227 |
+
id_type = element.attrib.get("IdType", "unknown").casefold()
|
| 228 |
+
values = by_type.setdefault(id_type, [])
|
| 229 |
+
if value not in values:
|
| 230 |
+
values.append(value)
|
| 231 |
+
flattened.append(f"{id_type}:{value}")
|
| 232 |
+
return by_type, _unique(flattened)
|
| 233 |
+
|
| 234 |
+
|
| 235 |
+
def _date_parts(parent: ET.Element | None) -> tuple[int | None, str | None]:
|
| 236 |
+
if parent is None:
|
| 237 |
+
return None, None
|
| 238 |
+
|
| 239 |
+
year_text = _text_at(parent, "Year")
|
| 240 |
+
medline_date = _text_at(parent, "MedlineDate")
|
| 241 |
+
year: int | None = None
|
| 242 |
+
if year_text and year_text.isdigit():
|
| 243 |
+
year = int(year_text)
|
| 244 |
+
elif medline_date and (match := YEAR_RE.search(medline_date)):
|
| 245 |
+
year = int(match.group(1))
|
| 246 |
+
|
| 247 |
+
if year is None:
|
| 248 |
+
return None, medline_date
|
| 249 |
+
|
| 250 |
+
month_text = _text_at(parent, "Month")
|
| 251 |
+
day_text = _text_at(parent, "Day")
|
| 252 |
+
month: int | None = None
|
| 253 |
+
if month_text:
|
| 254 |
+
if month_text.isdigit() and 1 <= int(month_text) <= 12:
|
| 255 |
+
month = int(month_text)
|
| 256 |
+
else:
|
| 257 |
+
month = MONTHS.get(month_text[:3].casefold())
|
| 258 |
+
|
| 259 |
+
if month is None:
|
| 260 |
+
return year, str(year)
|
| 261 |
+
if day_text and day_text.isdigit() and 1 <= int(day_text) <= 31:
|
| 262 |
+
return year, f"{year:04d}-{month:02d}-{int(day_text):02d}"
|
| 263 |
+
return year, f"{year:04d}-{month:02d}"
|
| 264 |
+
|
| 265 |
+
|
| 266 |
+
def _simple_date(parent: ET.Element | None) -> str | None:
|
| 267 |
+
_, value = _date_parts(parent)
|
| 268 |
+
return value
|
| 269 |
+
|
| 270 |
+
|
| 271 |
+
def _publication_date(
|
| 272 |
+
article: ET.Element | None,
|
| 273 |
+
pubmed_data: ET.Element | None,
|
| 274 |
+
*,
|
| 275 |
+
book: ET.Element | None = None,
|
| 276 |
+
) -> tuple[int | None, str | None]:
|
| 277 |
+
candidates: list[ET.Element | None] = []
|
| 278 |
+
if article is not None:
|
| 279 |
+
candidates.extend([
|
| 280 |
+
article.find("Journal/JournalIssue/PubDate"),
|
| 281 |
+
article.find("ArticleDate"),
|
| 282 |
+
])
|
| 283 |
+
if book is not None:
|
| 284 |
+
candidates.append(book.find("PubDate"))
|
| 285 |
+
if pubmed_data is not None:
|
| 286 |
+
history = pubmed_data.find("History")
|
| 287 |
+
if history is not None:
|
| 288 |
+
by_status = {date.attrib.get("PubStatus"): date for date in history.findall("PubMedPubDate")}
|
| 289 |
+
candidates.extend(by_status.get(status) for status in ("ppublish", "epublish", "pubmed", "entrez"))
|
| 290 |
+
|
| 291 |
+
for candidate in candidates:
|
| 292 |
+
year, value = _date_parts(candidate)
|
| 293 |
+
if year is not None:
|
| 294 |
+
return year, value
|
| 295 |
+
return None, None
|
| 296 |
+
|
| 297 |
+
|
| 298 |
+
def _journal_issns(journal: ET.Element | None) -> tuple[str | None, str | None]:
|
| 299 |
+
if journal is None:
|
| 300 |
+
return None, None
|
| 301 |
+
print_issn: str | None = None
|
| 302 |
+
electronic_issn: str | None = None
|
| 303 |
+
for element in journal.findall("ISSN"):
|
| 304 |
+
value = _element_text(element)
|
| 305 |
+
if value is None:
|
| 306 |
+
continue
|
| 307 |
+
issn_type = element.attrib.get("IssnType", "").casefold()
|
| 308 |
+
if issn_type == "electronic":
|
| 309 |
+
electronic_issn = electronic_issn or value
|
| 310 |
+
elif issn_type == "print":
|
| 311 |
+
print_issn = print_issn or value
|
| 312 |
+
return print_issn, electronic_issn
|
| 313 |
+
|
| 314 |
+
|
| 315 |
+
def _mesh(citation: ET.Element | None) -> tuple[list[str], list[str]]:
|
| 316 |
+
if citation is None:
|
| 317 |
+
return [], []
|
| 318 |
+
terms: list[str] = []
|
| 319 |
+
major_topics: list[str] = []
|
| 320 |
+
for heading in citation.findall("MeshHeadingList/MeshHeading"):
|
| 321 |
+
descriptor = heading.find("DescriptorName")
|
| 322 |
+
descriptor_text = _element_text(descriptor)
|
| 323 |
+
if descriptor_text is None:
|
| 324 |
+
continue
|
| 325 |
+
terms.append(descriptor_text)
|
| 326 |
+
if descriptor is not None and descriptor.attrib.get("MajorTopicYN") == "Y":
|
| 327 |
+
major_topics.append(descriptor_text)
|
| 328 |
+
for qualifier in heading.findall("QualifierName"):
|
| 329 |
+
qualifier_text = _element_text(qualifier)
|
| 330 |
+
if qualifier_text and qualifier.attrib.get("MajorTopicYN") == "Y":
|
| 331 |
+
major_topics.append(f"{descriptor_text}/{qualifier_text}")
|
| 332 |
+
return _unique(terms), _unique(major_topics)
|
| 333 |
+
|
| 334 |
+
|
| 335 |
+
def _parse_journal_article(element: ET.Element) -> Record:
|
| 336 |
+
citation = element.find("MedlineCitation")
|
| 337 |
+
if citation is None:
|
| 338 |
+
raise ValueError("PubmedArticle has no MedlineCitation")
|
| 339 |
+
article = citation.find("Article")
|
| 340 |
+
pubmed_data = element.find("PubmedData")
|
| 341 |
+
journal = article.find("Journal") if article is not None else None
|
| 342 |
+
journal_info = citation.find("MedlineJournalInfo")
|
| 343 |
+
|
| 344 |
+
pmid = _text_at(citation, "PMID")
|
| 345 |
+
if pmid is None:
|
| 346 |
+
raise ValueError("PubmedArticle has no PMID")
|
| 347 |
+
|
| 348 |
+
ids, flattened_ids = _article_ids(pubmed_data)
|
| 349 |
+
if article is not None:
|
| 350 |
+
for e_location in article.findall("ELocationID"):
|
| 351 |
+
if e_location.attrib.get("EIdType", "").casefold() != "doi":
|
| 352 |
+
continue
|
| 353 |
+
if value := _element_text(e_location):
|
| 354 |
+
ids.setdefault("doi", []).append(value)
|
| 355 |
+
flattened_ids.append(f"doi:{value}")
|
| 356 |
+
|
| 357 |
+
print_issn, electronic_issn = _journal_issns(journal)
|
| 358 |
+
year, publication_date = _publication_date(article, pubmed_data)
|
| 359 |
+
authors = _authors(article, ("AuthorList/Author",))
|
| 360 |
+
mesh_terms, mesh_major_topics = _mesh(citation)
|
| 361 |
+
|
| 362 |
+
return {
|
| 363 |
+
"pmid": pmid,
|
| 364 |
+
"pmcid": (ids.get("pmc") or ids.get("pmcid") or [None])[0],
|
| 365 |
+
"doi": (ids.get("doi") or [None])[0],
|
| 366 |
+
"title": _text_at(article, "ArticleTitle"),
|
| 367 |
+
"abstract": _abstract(article),
|
| 368 |
+
"journal": _text_at(journal, "Title"),
|
| 369 |
+
"year": year,
|
| 370 |
+
"issn": print_issn,
|
| 371 |
+
"eissn": electronic_issn,
|
| 372 |
+
"issn_linking": _text_at(journal_info, "ISSNLinking"),
|
| 373 |
+
"journal_abbrev": _text_at(journal, "ISOAbbreviation"),
|
| 374 |
+
"nlm_unique_id": _text_at(journal_info, "NlmUniqueID"),
|
| 375 |
+
"country": _text_at(journal_info, "Country"),
|
| 376 |
+
"volume": _text_at(journal, "JournalIssue/Volume"),
|
| 377 |
+
"issue": _text_at(journal, "JournalIssue/Issue"),
|
| 378 |
+
"pages": _text_at(article, "Pagination/MedlinePgn"),
|
| 379 |
+
"publication_date": publication_date,
|
| 380 |
+
"date_completed": _simple_date(citation.find("DateCompleted")),
|
| 381 |
+
"date_revised": _simple_date(citation.find("DateRevised")),
|
| 382 |
+
"citation_status": citation.attrib.get("Status"),
|
| 383 |
+
"publication_status": _text_at(pubmed_data, "PublicationStatus"),
|
| 384 |
+
"pub_model": article.attrib.get("PubModel") if article is not None else None,
|
| 385 |
+
"vernacular_title": _text_at(article, "VernacularTitle"),
|
| 386 |
+
"authors": authors,
|
| 387 |
+
"publication_types": _texts_at(article, "PublicationTypeList/PublicationType"),
|
| 388 |
+
"languages": _texts_at(article, "Language"),
|
| 389 |
+
"mesh_terms": mesh_terms,
|
| 390 |
+
"mesh_major_topics": mesh_major_topics,
|
| 391 |
+
"keywords": _unique(_texts_at(citation, "KeywordList/Keyword")),
|
| 392 |
+
"article_ids": _unique(flattened_ids),
|
| 393 |
+
}
|
| 394 |
+
|
| 395 |
+
|
| 396 |
+
def _parse_book_article(element: ET.Element) -> Record:
|
| 397 |
+
document = element.find("BookDocument")
|
| 398 |
+
if document is None:
|
| 399 |
+
raise ValueError("PubmedBookArticle has no BookDocument")
|
| 400 |
+
book_data = element.find("PubmedBookData")
|
| 401 |
+
book = document.find("Book")
|
| 402 |
+
|
| 403 |
+
pmid = _text_at(document, "PMID")
|
| 404 |
+
if pmid is None:
|
| 405 |
+
raise ValueError("PubmedBookArticle has no PMID")
|
| 406 |
+
|
| 407 |
+
ids, flattened_ids = _article_ids(document, book_data)
|
| 408 |
+
year, publication_date = _publication_date(None, book_data, book=book)
|
| 409 |
+
authors = _authors(
|
| 410 |
+
document,
|
| 411 |
+
(
|
| 412 |
+
"AuthorList/Author",
|
| 413 |
+
"Book/AuthorList/Author",
|
| 414 |
+
),
|
| 415 |
+
)
|
| 416 |
+
|
| 417 |
+
return {
|
| 418 |
+
"pmid": pmid,
|
| 419 |
+
"pmcid": (ids.get("pmc") or ids.get("pmcid") or [None])[0],
|
| 420 |
+
"doi": (ids.get("doi") or [None])[0],
|
| 421 |
+
"title": _text_at(document, "ArticleTitle") or _text_at(book, "BookTitle"),
|
| 422 |
+
"abstract": _abstract(document),
|
| 423 |
+
"journal": _text_at(book, "BookTitle"),
|
| 424 |
+
"year": year,
|
| 425 |
+
"issn": None,
|
| 426 |
+
"eissn": None,
|
| 427 |
+
"issn_linking": None,
|
| 428 |
+
"journal_abbrev": None,
|
| 429 |
+
"nlm_unique_id": None,
|
| 430 |
+
"country": _text_at(book, "Publisher/PublisherLocation"),
|
| 431 |
+
"volume": _text_at(book, "Volume"),
|
| 432 |
+
"issue": None,
|
| 433 |
+
"pages": _text_at(document, "Pagination/MedlinePgn"),
|
| 434 |
+
"publication_date": publication_date,
|
| 435 |
+
"date_completed": None,
|
| 436 |
+
"date_revised": _simple_date(document.find("DateRevised")),
|
| 437 |
+
"citation_status": "Book",
|
| 438 |
+
"publication_status": _text_at(book_data, "PublicationStatus"),
|
| 439 |
+
"pub_model": None,
|
| 440 |
+
"vernacular_title": _text_at(document, "VernacularTitle"),
|
| 441 |
+
"authors": authors,
|
| 442 |
+
"publication_types": _texts_at(document, "PublicationType"),
|
| 443 |
+
"languages": _texts_at(document, "Language"),
|
| 444 |
+
"mesh_terms": [],
|
| 445 |
+
"mesh_major_topics": [],
|
| 446 |
+
"keywords": _unique(_texts_at(document, "KeywordList/Keyword")),
|
| 447 |
+
"article_ids": flattened_ids,
|
| 448 |
+
}
|
| 449 |
+
|
| 450 |
+
|
| 451 |
+
def _parse_record(element: ET.Element) -> Record:
|
| 452 |
+
if _local_name(element.tag) == "PubmedBookArticle":
|
| 453 |
+
return _parse_book_article(element)
|
| 454 |
+
return _parse_journal_article(element)
|
| 455 |
+
|
| 456 |
+
|
| 457 |
+
def _record_pmid(element: ET.Element) -> str:
|
| 458 |
+
citation = element.find("MedlineCitation")
|
| 459 |
+
document = element.find("BookDocument")
|
| 460 |
+
pmid = _text_at(citation, "PMID") or _text_at(document, "PMID")
|
| 461 |
+
if pmid is None:
|
| 462 |
+
raise ValueError(f"{_local_name(element.tag)} has no PMID")
|
| 463 |
+
return pmid
|
| 464 |
+
|
| 465 |
+
|
| 466 |
+
def _expected_md5(path: Path) -> str:
|
| 467 |
+
sidecar = path.with_name(f"{path.name}.md5")
|
| 468 |
+
try:
|
| 469 |
+
contents = sidecar.read_text().strip()
|
| 470 |
+
except FileNotFoundError as exc:
|
| 471 |
+
raise ValueError(f"Missing checksum sidecar: {sidecar}") from exc
|
| 472 |
+
match = re.search(r"\b([0-9a-fA-F]{32})\b", contents)
|
| 473 |
+
if match is None:
|
| 474 |
+
raise ValueError(f"Invalid MD5 sidecar: {sidecar}")
|
| 475 |
+
return match.group(1).casefold()
|
| 476 |
+
|
| 477 |
+
|
| 478 |
+
def _verify_md5(path: Path) -> None:
|
| 479 |
+
expected = _expected_md5(path)
|
| 480 |
+
with path.open("rb") as file:
|
| 481 |
+
actual = hashlib.file_digest(file, "md5").hexdigest()
|
| 482 |
+
if actual != expected:
|
| 483 |
+
raise ValueError(f"MD5 mismatch for {path}: expected {expected}, got {actual}")
|
| 484 |
+
|
| 485 |
+
|
| 486 |
+
def _iter_events(
|
| 487 |
+
path: Path,
|
| 488 |
+
*,
|
| 489 |
+
parse_records: bool,
|
| 490 |
+
verify_md5: bool,
|
| 491 |
+
) -> Iterator[tuple[str, Record | None, bool]]:
|
| 492 |
+
if verify_md5:
|
| 493 |
+
_verify_md5(path)
|
| 494 |
+
|
| 495 |
+
with gzip.open(path, "rb") as file:
|
| 496 |
+
context = ET.iterparse(file, events=("start", "end"))
|
| 497 |
+
try:
|
| 498 |
+
_, root = next(context)
|
| 499 |
+
except StopIteration as exc:
|
| 500 |
+
raise ValueError(f"Empty XML file: {path}") from exc
|
| 501 |
+
|
| 502 |
+
for event, element in context:
|
| 503 |
+
if event != "end":
|
| 504 |
+
continue
|
| 505 |
+
tag = _local_name(element.tag)
|
| 506 |
+
if tag in {"PubmedArticle", "PubmedBookArticle"}:
|
| 507 |
+
record = _parse_record(element) if parse_records else None
|
| 508 |
+
pmid = record["pmid"] if record is not None else _record_pmid(element)
|
| 509 |
+
yield pmid, record, False
|
| 510 |
+
root.clear()
|
| 511 |
+
elif tag in {"DeleteCitation", "DeleteDocument"}:
|
| 512 |
+
for pmid_element in element.findall("PMID"):
|
| 513 |
+
if pmid := _element_text(pmid_element):
|
| 514 |
+
yield pmid, None, True
|
| 515 |
+
root.clear()
|
| 516 |
+
|
| 517 |
+
|
| 518 |
+
def _event_key(file_index: int, event_index: int) -> int:
|
| 519 |
+
return (file_index << 32) | event_index
|
| 520 |
+
|
| 521 |
+
|
| 522 |
+
def _index_update_file(task: tuple[int, Path, bool]) -> list[tuple[int, int, int]]:
|
| 523 |
+
file_index, path, verify_md5 = task
|
| 524 |
+
indexed: list[tuple[int, int, int]] = []
|
| 525 |
+
for event_index, (pmid, _, deleted) in enumerate(
|
| 526 |
+
_iter_events(path, parse_records=False, verify_md5=verify_md5),
|
| 527 |
+
start=1,
|
| 528 |
+
):
|
| 529 |
+
indexed.append((int(pmid), _event_key(file_index, event_index), int(deleted)))
|
| 530 |
+
return indexed
|
| 531 |
+
|
| 532 |
+
|
| 533 |
+
def _query_changed_pmids(connection: sqlite3.Connection, pmids: Sequence[int]) -> set[int]:
|
| 534 |
+
changed: set[int] = set()
|
| 535 |
+
for offset in range(0, len(pmids), SQLITE_QUERY_CHUNK):
|
| 536 |
+
chunk = pmids[offset : offset + SQLITE_QUERY_CHUNK]
|
| 537 |
+
placeholders = ",".join("?" for _ in chunk)
|
| 538 |
+
rows = connection.execute(f"SELECT pmid FROM latest_updates WHERE pmid IN ({placeholders})", chunk)
|
| 539 |
+
changed.update(row[0] for row in rows)
|
| 540 |
+
return changed
|
| 541 |
+
|
| 542 |
+
|
| 543 |
+
def _query_latest_events(connection: sqlite3.Connection, pmids: Sequence[int]) -> dict[int, int]:
|
| 544 |
+
latest: dict[int, int] = {}
|
| 545 |
+
for offset in range(0, len(pmids), SQLITE_QUERY_CHUNK):
|
| 546 |
+
chunk = pmids[offset : offset + SQLITE_QUERY_CHUNK]
|
| 547 |
+
placeholders = ",".join("?" for _ in chunk)
|
| 548 |
+
rows = connection.execute(
|
| 549 |
+
f"SELECT pmid, event_key FROM latest_updates WHERE pmid IN ({placeholders})",
|
| 550 |
+
chunk,
|
| 551 |
+
)
|
| 552 |
+
latest.update(rows)
|
| 553 |
+
return latest
|
| 554 |
+
|
| 555 |
+
|
| 556 |
+
def _read_only_connection(path: Path) -> sqlite3.Connection:
|
| 557 |
+
connection = sqlite3.connect(path)
|
| 558 |
+
connection.execute("PRAGMA query_only = ON")
|
| 559 |
+
return connection
|
| 560 |
+
|
| 561 |
+
|
| 562 |
+
def _parse_baseline_file(task: tuple[Path, Path | None, bool]) -> ParsedFile:
|
| 563 |
+
path, state_db, verify_md5 = task
|
| 564 |
+
events = list(_iter_events(path, parse_records=True, verify_md5=verify_md5))
|
| 565 |
+
records = [record for _, record, _ in events if record is not None]
|
| 566 |
+
if state_db is not None and records:
|
| 567 |
+
connection = _read_only_connection(state_db)
|
| 568 |
+
try:
|
| 569 |
+
changed = _query_changed_pmids(connection, [int(record["pmid"]) for record in records])
|
| 570 |
+
finally:
|
| 571 |
+
connection.close()
|
| 572 |
+
records = [record for record in records if int(record["pmid"]) not in changed]
|
| 573 |
+
return ParsedFile(table=pa.Table.from_pylist(records, schema=PARQUET_SCHEMA), event_count=len(events))
|
| 574 |
+
|
| 575 |
+
|
| 576 |
+
def _parse_update_file(task: tuple[int, Path, Path]) -> ParsedFile:
|
| 577 |
+
file_index, path, state_db = task
|
| 578 |
+
events = list(_iter_events(path, parse_records=True, verify_md5=False))
|
| 579 |
+
connection = _read_only_connection(state_db)
|
| 580 |
+
try:
|
| 581 |
+
latest = _query_latest_events(connection, [int(pmid) for pmid, _, _ in events])
|
| 582 |
+
finally:
|
| 583 |
+
connection.close()
|
| 584 |
+
|
| 585 |
+
records: list[Record] = [
|
| 586 |
+
record
|
| 587 |
+
for event_index, (pmid, record, _) in enumerate(events, start=1)
|
| 588 |
+
if record is not None and latest.get(int(pmid)) == _event_key(file_index, event_index)
|
| 589 |
+
]
|
| 590 |
+
return ParsedFile(table=pa.Table.from_pylist(records, schema=PARQUET_SCHEMA), event_count=len(events))
|
| 591 |
+
|
| 592 |
+
|
| 593 |
+
def _ordered_process_map[Task, Result](
|
| 594 |
+
function: Callable[[Task], Result],
|
| 595 |
+
tasks: Iterable[Task],
|
| 596 |
+
*,
|
| 597 |
+
workers: int,
|
| 598 |
+
) -> Iterator[Result]:
|
| 599 |
+
if workers == 1:
|
| 600 |
+
yield from map(function, tasks)
|
| 601 |
+
return
|
| 602 |
+
|
| 603 |
+
task_iterator = iter(tasks)
|
| 604 |
+
with concurrent.futures.ProcessPoolExecutor(max_workers=workers) as executor:
|
| 605 |
+
pending: deque[concurrent.futures.Future[Result]] = deque()
|
| 606 |
+
for _ in range(workers):
|
| 607 |
+
try:
|
| 608 |
+
pending.append(executor.submit(function, next(task_iterator)))
|
| 609 |
+
except StopIteration:
|
| 610 |
+
break
|
| 611 |
+
|
| 612 |
+
while pending:
|
| 613 |
+
yield pending.popleft().result()
|
| 614 |
+
with contextlib.suppress(StopIteration):
|
| 615 |
+
pending.append(executor.submit(function, next(task_iterator)))
|
| 616 |
+
|
| 617 |
+
|
| 618 |
+
def _discover_files(directory: Path) -> list[DistributionFile]:
|
| 619 |
+
files: list[DistributionFile] = []
|
| 620 |
+
for path in directory.glob("pubmed*n*.xml.gz"):
|
| 621 |
+
if match := FILE_RE.fullmatch(path.name):
|
| 622 |
+
files.append(
|
| 623 |
+
DistributionFile(
|
| 624 |
+
path=path,
|
| 625 |
+
release=int(match.group("release")),
|
| 626 |
+
sequence=int(match.group("sequence")),
|
| 627 |
+
)
|
| 628 |
+
)
|
| 629 |
+
return sorted(files, key=lambda item: (item.release, item.sequence))
|
| 630 |
+
|
| 631 |
+
|
| 632 |
+
def _assert_contiguous(files: Sequence[DistributionFile], label: str) -> None:
|
| 633 |
+
for previous, current in zip(files, files[1:], strict=False):
|
| 634 |
+
if current.release != previous.release or current.sequence != previous.sequence + 1:
|
| 635 |
+
raise ValueError(f"{label} files are not contiguous between {previous.path.name} and {current.path.name}")
|
| 636 |
+
|
| 637 |
+
|
| 638 |
+
def discover_distribution(
|
| 639 |
+
input_root: Path, *, baseline_only: bool
|
| 640 |
+
) -> tuple[list[DistributionFile], list[DistributionFile]]:
|
| 641 |
+
baseline = _discover_files(input_root / "baseline")
|
| 642 |
+
updates = [] if baseline_only else _discover_files(input_root / "updatefiles")
|
| 643 |
+
if not baseline:
|
| 644 |
+
raise ValueError(f"No PubMed baseline XML files found in {input_root / 'baseline'}")
|
| 645 |
+
if baseline[0].sequence != 1:
|
| 646 |
+
raise ValueError(f"The baseline starts at {baseline[0].path.name}, not sequence 0001")
|
| 647 |
+
_assert_contiguous(baseline, "Baseline")
|
| 648 |
+
_assert_contiguous(updates, "Update")
|
| 649 |
+
|
| 650 |
+
if updates:
|
| 651 |
+
expected_first_update = baseline[-1].sequence + 1
|
| 652 |
+
if updates[0].release != baseline[-1].release or updates[0].sequence != expected_first_update:
|
| 653 |
+
raise ValueError(
|
| 654 |
+
f"Expected the first update after {baseline[-1].path.name} to have sequence "
|
| 655 |
+
f"{expected_first_update:04d}, found {updates[0].path.name}"
|
| 656 |
+
)
|
| 657 |
+
return baseline, updates
|
| 658 |
+
|
| 659 |
+
|
| 660 |
+
def _build_update_index(
|
| 661 |
+
update_files: Sequence[DistributionFile],
|
| 662 |
+
state_db: Path,
|
| 663 |
+
*,
|
| 664 |
+
workers: int,
|
| 665 |
+
verify_md5: bool,
|
| 666 |
+
) -> tuple[int, int, int]:
|
| 667 |
+
with sqlite3.connect(state_db) as connection:
|
| 668 |
+
connection.execute("PRAGMA journal_mode = OFF")
|
| 669 |
+
connection.execute("PRAGMA synchronous = OFF")
|
| 670 |
+
connection.execute(
|
| 671 |
+
"""
|
| 672 |
+
CREATE TABLE latest_updates (
|
| 673 |
+
pmid INTEGER PRIMARY KEY,
|
| 674 |
+
event_key INTEGER NOT NULL,
|
| 675 |
+
deleted INTEGER NOT NULL
|
| 676 |
+
)
|
| 677 |
+
"""
|
| 678 |
+
)
|
| 679 |
+
tasks = ((index, item.path, verify_md5) for index, item in enumerate(update_files))
|
| 680 |
+
total_events = 0
|
| 681 |
+
results = _ordered_process_map(_index_update_file, tasks, workers=workers)
|
| 682 |
+
for indexed in tqdm(results, total=len(update_files), desc="Index updates", unit="file"):
|
| 683 |
+
total_events += len(indexed)
|
| 684 |
+
connection.executemany(
|
| 685 |
+
"""
|
| 686 |
+
INSERT INTO latest_updates (pmid, event_key, deleted)
|
| 687 |
+
VALUES (?, ?, ?)
|
| 688 |
+
ON CONFLICT(pmid) DO UPDATE SET
|
| 689 |
+
event_key = excluded.event_key,
|
| 690 |
+
deleted = excluded.deleted
|
| 691 |
+
WHERE excluded.event_key > latest_updates.event_key
|
| 692 |
+
""",
|
| 693 |
+
indexed,
|
| 694 |
+
)
|
| 695 |
+
connection.commit()
|
| 696 |
+
counts = connection.execute("SELECT count(), coalesce(sum(deleted), 0) FROM latest_updates").fetchone()
|
| 697 |
+
assert counts is not None
|
| 698 |
+
latest_events, latest_deletions = counts
|
| 699 |
+
return total_events, latest_events, latest_deletions
|
| 700 |
+
|
| 701 |
+
|
| 702 |
+
def _parquet_schema(baseline: Sequence[DistributionFile], updates: Sequence[DistributionFile]) -> pa.Schema:
|
| 703 |
+
metadata = {
|
| 704 |
+
b"source": b"NLM PubMed baseline and daily update XML",
|
| 705 |
+
b"pubmed_release": str(baseline[0].release).encode(),
|
| 706 |
+
b"baseline_first_file": baseline[0].path.name.encode(),
|
| 707 |
+
b"baseline_last_file": baseline[-1].path.name.encode(),
|
| 708 |
+
b"update_last_file": (updates[-1].path.name if updates else "").encode(),
|
| 709 |
+
}
|
| 710 |
+
return PARQUET_SCHEMA.with_metadata(metadata)
|
| 711 |
+
|
| 712 |
+
|
| 713 |
+
def build_parquet(
|
| 714 |
+
input_root: Path,
|
| 715 |
+
output: Path,
|
| 716 |
+
*,
|
| 717 |
+
workers: int = DEFAULT_WORKERS,
|
| 718 |
+
baseline_only: bool = False,
|
| 719 |
+
verify_md5: bool = True,
|
| 720 |
+
overwrite: bool = False,
|
| 721 |
+
compression_level: int = 3,
|
| 722 |
+
) -> None:
|
| 723 |
+
"""Build one Parquet file containing the final live version of each PMID."""
|
| 724 |
+
if workers < 1:
|
| 725 |
+
raise ValueError("workers must be at least 1")
|
| 726 |
+
if output.exists() and not overwrite:
|
| 727 |
+
raise FileExistsError(f"Output exists; pass --overwrite to replace it: {output}")
|
| 728 |
+
|
| 729 |
+
baseline, updates = discover_distribution(input_root, baseline_only=baseline_only)
|
| 730 |
+
print(
|
| 731 |
+
f"Found {len(baseline):,} baseline files"
|
| 732 |
+
+ (f" and {len(updates):,} update files" if updates else " (baseline only)")
|
| 733 |
+
)
|
| 734 |
+
output.parent.mkdir(parents=True, exist_ok=True)
|
| 735 |
+
partial_output = output.with_name(f".{output.name}.partial")
|
| 736 |
+
if partial_output.exists():
|
| 737 |
+
if not overwrite:
|
| 738 |
+
raise FileExistsError(f"Partial output exists; pass --overwrite to replace it: {partial_output}")
|
| 739 |
+
partial_output.unlink()
|
| 740 |
+
|
| 741 |
+
total_input_events = 0
|
| 742 |
+
total_output_rows = 0
|
| 743 |
+
update_event_count = 0
|
| 744 |
+
latest_update_count = 0
|
| 745 |
+
latest_deletion_count = 0
|
| 746 |
+
try:
|
| 747 |
+
with tempfile.TemporaryDirectory(prefix="pubmed-parquet-", dir=output.parent) as temp_dir:
|
| 748 |
+
state_db = Path(temp_dir) / "latest_updates.sqlite3"
|
| 749 |
+
state_db_or_none: Path | None = None
|
| 750 |
+
if updates:
|
| 751 |
+
update_event_count, latest_update_count, latest_deletion_count = _build_update_index(
|
| 752 |
+
updates,
|
| 753 |
+
state_db,
|
| 754 |
+
workers=workers,
|
| 755 |
+
verify_md5=verify_md5,
|
| 756 |
+
)
|
| 757 |
+
state_db_or_none = state_db
|
| 758 |
+
|
| 759 |
+
schema = _parquet_schema(baseline, updates)
|
| 760 |
+
with pq.ParquetWriter(
|
| 761 |
+
partial_output,
|
| 762 |
+
schema,
|
| 763 |
+
compression="zstd",
|
| 764 |
+
compression_level=compression_level,
|
| 765 |
+
use_dictionary=[
|
| 766 |
+
"journal",
|
| 767 |
+
"year",
|
| 768 |
+
"country",
|
| 769 |
+
"citation_status",
|
| 770 |
+
"publication_status",
|
| 771 |
+
"pub_model",
|
| 772 |
+
],
|
| 773 |
+
write_statistics=["pmid", "pmcid", "doi", "journal", "year"],
|
| 774 |
+
) as writer:
|
| 775 |
+
baseline_tasks = ((item.path, state_db_or_none, verify_md5) for item in baseline)
|
| 776 |
+
baseline_results = _ordered_process_map(_parse_baseline_file, baseline_tasks, workers=workers)
|
| 777 |
+
for parsed in tqdm(baseline_results, total=len(baseline), desc="Write baseline", unit="file"):
|
| 778 |
+
total_input_events += parsed.event_count
|
| 779 |
+
if parsed.table.num_rows:
|
| 780 |
+
writer.write_table(parsed.table)
|
| 781 |
+
total_output_rows += parsed.table.num_rows
|
| 782 |
+
|
| 783 |
+
if updates:
|
| 784 |
+
update_tasks = ((index, item.path, state_db) for index, item in enumerate(updates))
|
| 785 |
+
update_results = _ordered_process_map(_parse_update_file, update_tasks, workers=workers)
|
| 786 |
+
for parsed in tqdm(update_results, total=len(updates), desc="Write updates", unit="file"):
|
| 787 |
+
if parsed.table.num_rows:
|
| 788 |
+
writer.write_table(parsed.table)
|
| 789 |
+
total_output_rows += parsed.table.num_rows
|
| 790 |
+
|
| 791 |
+
partial_output.replace(output)
|
| 792 |
+
except BaseException:
|
| 793 |
+
partial_output.unlink(missing_ok=True)
|
| 794 |
+
raise
|
| 795 |
+
|
| 796 |
+
print(f"Wrote {total_output_rows:,} current PubMed records to {output}")
|
| 797 |
+
print(f"Read {total_input_events:,} baseline records")
|
| 798 |
+
if updates:
|
| 799 |
+
print(
|
| 800 |
+
f"Processed {update_event_count:,} update events affecting {latest_update_count:,} PMIDs "
|
| 801 |
+
f"({latest_deletion_count:,} deleted in their latest event)"
|
| 802 |
+
)
|
| 803 |
+
|
| 804 |
+
|
| 805 |
+
def _parse_args() -> argparse.Namespace:
|
| 806 |
+
parser = argparse.ArgumentParser(description=__doc__)
|
| 807 |
+
parser.add_argument(
|
| 808 |
+
"--input-root",
|
| 809 |
+
type=Path,
|
| 810 |
+
default=DEFAULT_INPUT_ROOT,
|
| 811 |
+
help=f"Directory containing baseline/ and updatefiles/ (default: {DEFAULT_INPUT_ROOT})",
|
| 812 |
+
)
|
| 813 |
+
parser.add_argument("--output", type=Path, required=True, help="Destination .parquet file")
|
| 814 |
+
parser.add_argument(
|
| 815 |
+
"--workers", type=int, default=DEFAULT_WORKERS, help=f"Parser processes (default: {DEFAULT_WORKERS})"
|
| 816 |
+
)
|
| 817 |
+
parser.add_argument("--baseline-only", action="store_true", help="Ignore daily update files")
|
| 818 |
+
parser.add_argument("--skip-md5", action="store_true", help="Do not validate mirrored files against .md5 sidecars")
|
| 819 |
+
parser.add_argument("--overwrite", action="store_true", help="Atomically replace an existing output file")
|
| 820 |
+
parser.add_argument("--compression-level", type=int, default=3, help="Zstandard compression level (default: 3)")
|
| 821 |
+
return parser.parse_args()
|
| 822 |
+
|
| 823 |
+
|
| 824 |
+
def main() -> None:
|
| 825 |
+
args = _parse_args()
|
| 826 |
+
build_parquet(
|
| 827 |
+
args.input_root,
|
| 828 |
+
args.output,
|
| 829 |
+
workers=args.workers,
|
| 830 |
+
baseline_only=args.baseline_only,
|
| 831 |
+
verify_md5=not args.skip_md5,
|
| 832 |
+
overwrite=args.overwrite,
|
| 833 |
+
compression_level=args.compression_level,
|
| 834 |
+
)
|
| 835 |
+
|
| 836 |
+
|
| 837 |
+
if __name__ == "__main__":
|
| 838 |
+
main()
|