From b2a0e3075922b49374da9e5fa5ebdda1ef2408f6 Mon Sep 17 00:00:00 2001 From: Christian Frankenberg Date: Sun, 29 Nov 2026 07:29:19 -0800 Subject: [PATCH 1/3] Pin tested bibtexparser 2.1 and document incremental sync --- README.md | 33 +++++++++++++-------------------- requirements.txt | 2 +- 2 files changed, 14 insertions(+), 21 deletions(-) diff --git a/README.md b/README.md index 85b7da8..ed27216 100644 --- a/README.md +++ b/README.md @@ -6,36 +6,29 @@ https://rsfralab.github.io/ This site can generate new publication entries directly from ORCID and Crossref. -### One-time setup - -- Install Python dependencies: `pip install requests bibtexparser` - ### Sync new publications +Install the repository's Python dependencies: + ``` -python scripts/orcid_sync.py --orcid YOUR-ORCID-ID --full +python -m pip install -r requirements.txt ``` -This will: - -- Read your ORCID works -- Pull metadata from Crossref using DOIs -- Rebuild publications/publications.bib from ORCID -- Optionally create QMD files under publications/ (unless --no-qmd) +The weekly **ORCID Sync** action adds previously unseen DOIs from ORCID and +Crossref without rewriting existing citations or publication pages. To preview +it on GitHub, choose **Actions → ORCID Sync → Run workflow** and leave +**Preview changes without committing or publishing** checked. -### ORCID-only workflow - -Use ORCID as the single source of truth and regenerate the BibTeX each time: +To run the same publication update locally: ``` -python scripts/orcid_sync.py --orcid YOUR-ORCID-ID --full +python scripts/orcid_sync.py --orcid YOUR-ORCID-ID --no-qmd +python scripts/parsePubs.py --include-preprints --preserve-existing ``` -To skip QMD creation: - -``` -python scripts/orcid_sync.py --orcid YOUR-ORCID-ID --full --no-qmd -``` +Pass `--dry-run` to the first command to inspect candidate records without +appending to the bibliography. Do not use `--full` on the site's curated +bibliography: that option rebuilds it from ORCID. ### Preprints diff --git a/requirements.txt b/requirements.txt index 236769a..15f2898 100644 --- a/requirements.txt +++ b/requirements.txt @@ -1,2 +1,2 @@ -bibtexparser +bibtexparser==2.1.0 requests From 9a195336ac6967e23d6fb8127c7398527f12ad8a Mon Sep 17 00:00:00 2001 From: Christian Frankenberg Date: Sun, 29 Nov 2026 07:29:46 -0800 Subject: [PATCH 2/3] Migrate publication scripts to BibTeX 2 and protect curated entries --- scripts/bibtex_io.py | 49 +++++++++++++++++ scripts/merge_bib.py | 32 ++++++----- scripts/orcid_sync.py | 94 ++++++++++++++++---------------- scripts/parsePubs.py | 40 ++++++++------ scripts/test_publication_sync.py | 90 ++++++++++++++++++++++++++++++ 5 files changed, 227 insertions(+), 78 deletions(-) create mode 100644 scripts/bibtex_io.py create mode 100644 scripts/test_publication_sync.py diff --git a/scripts/bibtex_io.py b/scripts/bibtex_io.py new file mode 100644 index 0000000..af0fb6f --- /dev/null +++ b/scripts/bibtex_io.py @@ -0,0 +1,49 @@ +"""Shared BibTeX 2.x input/output for the publication scripts.""" + +from pathlib import Path + +import bibtexparser +from bibtexparser.library import Library +from bibtexparser.model import DuplicateBlockKeyBlock, Entry, Field, String + + +def read_entries(path: Path) -> list[dict]: + # The existing bibliography contains legacy duplicate citation IDs. + # Preserve all records, as v1 did, so the generator can still dedupe by DOI. + library = bibtexparser.parse_file(str(path)) + strings = [block for block in library.blocks if isinstance(block, String)] + entries = [] + for block in library.blocks: + if isinstance(block, Entry): + entries.append(block) + elif isinstance(block, DuplicateBlockKeyBlock) and isinstance(block.previous_block, Entry): + parsed = bibtexparser.parse_string(block.raw, library=Library(strings)) + if not parsed.failed_blocks and len(parsed.entries) == 1: + entries.append(parsed.entries[0]) + continue + raise ValueError(f"Could not recover duplicate key {block.key} in {path}") + elif block in library.failed_blocks: + raise ValueError(f"Could not parse BibTeX in {path} (line {block.start_line + 1})") + return [ + { + **{ + field.key.lower(): "\n".join(line.lstrip() for line in str(field.value).split("\n")) + for field in entry.fields + }, + "ENTRYTYPE": entry.entry_type.lower(), + "ID": entry.key, + } + for entry in entries + ] + + +def write_entries(entries: list[dict]) -> str: + library = Library([ + Entry( + entry_type=entry["ENTRYTYPE"], + key=entry["ID"], + fields=[Field(key, value) for key, value in entry.items() if key not in {"ID", "ENTRYTYPE"}], + ) + for entry in entries + ]) + return bibtexparser.write_string(library) diff --git a/scripts/merge_bib.py b/scripts/merge_bib.py index 6e603b1..2bf55dc 100644 --- a/scripts/merge_bib.py +++ b/scripts/merge_bib.py @@ -1,9 +1,7 @@ import argparse from pathlib import Path -import bibtexparser -from bibtexparser.bibdatabase import BibDatabase -from bibtexparser.bwriter import BibTexWriter +from bibtex_io import read_entries, write_entries def entry_key(entry: dict) -> str: @@ -18,8 +16,7 @@ def entry_key(entry: dict) -> str: def load_bib(path: Path) -> list: if not path.exists(): return [] - with path.open("r", encoding="utf-8") as f: - return bibtexparser.load(f).entries + return read_entries(path) def main() -> None: @@ -35,17 +32,26 @@ def main() -> None: if key not in merged: merged[key] = entry - db = BibDatabase() - db.entries = list(merged.values()) - - writer = BibTexWriter() - writer.order_entries_by = None + entries = [] + reserved = {entry["ID"] for entry in merged.values()} + used = set() + for entry in merged.values(): + base = entry["ID"] + key = base + index = 2 + while key in used: + key = f"{base}-{index}" + index += 1 + while key in reserved: + key = f"{base}-{index}" + index += 1 + used.add(key) + entries.append({**entry, "ID": key}) out_path = Path(args.out) out_path.parent.mkdir(parents=True, exist_ok=True) - with out_path.open("w", encoding="utf-8") as f: - f.write(writer.write(db)) + out_path.write_text(write_entries(entries), encoding="utf-8") - print(f"Wrote {len(db.entries)} entries to {out_path}.") + print(f"Wrote {len(entries)} entries to {out_path}.") if __name__ == "__main__": diff --git a/scripts/orcid_sync.py b/scripts/orcid_sync.py index 9a2a285..a5dfec0 100644 --- a/scripts/orcid_sync.py +++ b/scripts/orcid_sync.py @@ -2,20 +2,15 @@ import html import os import re -from collections import defaultdict +import sys from pathlib import Path from typing import Optional import requests +from requests.adapters import HTTPAdapter +from urllib3.util.retry import Retry -try: - import bibtexparser - from bibtexparser.bibdatabase import BibDatabase - from bibtexparser.bwriter import BibTexWriter -except Exception: # pragma: no cover - bibtexparser = None - BibDatabase = None - BibTexWriter = None +from bibtex_io import read_entries, write_entries ORCID_API = "https://pub.orcid.org/v3.0" CROSSREF_API = "https://api.crossref.org/works" @@ -44,26 +39,13 @@ def load_existing_dois(publications_dir: Path) -> set: continue for line in content.splitlines(): if line.lower().startswith("doi:"): - doi = line.split(":", 1)[1].strip().strip('"') + doi = line.split(":", 1)[1].strip().strip("\"'") if doi: dois.add(doi.lower()) break return dois -def load_bib_dois(bib_path: Optional[Path]) -> set: - if not bib_path or not bib_path.exists() or bibtexparser is None: - return set() - with bib_path.open("r", encoding="utf-8") as f: - bib_database = bibtexparser.load(f) - dois = set() - for entry in bib_database.entries: - doi = entry.get("doi", "") - if doi: - dois.add(doi.lower()) - return dois - - def get_orcid_works(orcid: str) -> dict: headers = {"Accept": "application/vnd.orcid+json"} response = requests.get(f"{ORCID_API}/{orcid}/works", headers=headers, timeout=30) @@ -87,9 +69,12 @@ def extract_dois(works: dict) -> dict: def fetch_crossref(doi: str) -> dict: - response = requests.get(f"{CROSSREF_API}/{doi}", timeout=30) - response.raise_for_status() - return response.json().get("message", {}) + retries = Retry(total=3, backoff_factor=1, status_forcelist=(429, 500, 502, 503, 504)) + with requests.Session() as session: + session.mount("https://", HTTPAdapter(max_retries=retries)) + response = session.get(f"{CROSSREF_API}/{doi}", timeout=30) + response.raise_for_status() + return response.json().get("message", {}) def fetch_unpaywall(doi: str, email: str) -> dict: @@ -99,7 +84,7 @@ def fetch_unpaywall(doi: str, email: str) -> dict: def build_record(message: dict, doi: str, orcid_type: str = "") -> dict: - title = (message.get("title") or [""])[0] + title = strip_jats((message.get("title") or [""])[0]) container = (message.get("container-title") or [""])[0] issued = message.get("issued", {}).get("date-parts", [[""]])[0] year = issued[0] if issued else "" @@ -126,6 +111,9 @@ def build_record(message: dict, doi: str, orcid_type: str = "") -> dict: "author_bib": author_bib, "type": "article", "year": year, + "volume": message.get("volume"), + "number": message.get("issue"), + "pages": message.get("page"), "publication": container, "doi": doi, "materials": "", @@ -182,7 +170,7 @@ def write_qmd(path: Path, record: dict) -> None: def build_bib_entry(record: dict) -> dict: entry_id = Path(record.get("_filename", "")).stem - return { + entry = { "ENTRYTYPE": "article", "ID": entry_id, "title": record.get("title", ""), @@ -193,6 +181,10 @@ def build_bib_entry(record: dict) -> dict: "abstract": record.get("abstract", ""), "orcid_type": record.get("orcid_type", ""), } + for field in ("volume", "number", "pages", "materials"): + if record.get(field): + entry[field] = str(record[field]) + return entry def main() -> None: @@ -225,18 +217,20 @@ def main() -> None: if not args.orcid: raise SystemExit("Missing ORCID iD. Pass --orcid or set ORCID_ID.") - if not args.no_bib and bibtexparser is None: - raise SystemExit("Missing dependency: bibtexparser. Install with 'pip install bibtexparser'.") - publications_dir = Path(args.publications_dir) pdf_dir = Path(args.pdf_dir) bib_path = None if args.no_bib else Path(args.bib_file) publications_dir.mkdir(parents=True, exist_ok=True) existing_dois = set() + used_ids = set() if not args.full: existing_dois = load_existing_dois(publications_dir) - existing_dois |= load_bib_dois(bib_path) + used_ids.update(qmd.stem.lower() for qmd in publications_dir.rglob("*.qmd")) + if bib_path and bib_path.exists(): + entries = read_entries(bib_path) + existing_dois.update(e["doi"].strip().lower() for e in entries if e.get("doi")) + used_ids.update(slugify(e["ID"]) or "publication" for e in entries) works = get_orcid_works(args.orcid) doi_map = extract_dois(works) @@ -246,10 +240,23 @@ def main() -> None: continue try: message = fetch_crossref(doi) - except Exception: + except requests.HTTPError as exc: + if exc.response is None or exc.response.status_code != 404: + raise + print(f"Skipping DOI {doi}: not indexed by Crossref.", file=sys.stderr) + continue + if not message.get("title"): + print(f"Skipping DOI {doi}: no title in Crossref metadata.", file=sys.stderr) continue record = build_record(message, doi, orcid_type) - filename = choose_filename(record) + base = Path(choose_filename(record)).stem + key = base + index = 2 + while key in used_ids: + key = f"{base}-{index}" + index += 1 + used_ids.add(key) + filename = f"{key}.qmd" record["_filename"] = filename materials = resolve_materials(record, args.materials_template, args.unpaywall_email) @@ -278,22 +285,15 @@ def main() -> None: print(f"Total new records: {len(new_records)}") return - if not args.no_bib and bib_path is not None: + if bib_path is not None and (new_records or args.full): bib_path.parent.mkdir(parents=True, exist_ok=True) + additions = write_entries([build_bib_entry(record) for record in new_records]) if not args.full and bib_path.exists(): - with bib_path.open("r", encoding="utf-8") as f: - bib_database = bibtexparser.load(f) + # Keep existing entries, comments, and formatting byte-for-byte. + with bib_path.open("a", encoding="utf-8", newline="") as f: + f.write("\n\n" + additions) else: - bib_database = BibDatabase() - bib_database.entries = [] - - for record in new_records: - bib_database.entries.append(build_bib_entry(record)) - - writer = BibTexWriter() - writer.order_entries_by = None - with bib_path.open("w", encoding="utf-8") as f: - f.write(writer.write(bib_database)) + bib_path.write_text(additions, encoding="utf-8") if not args.no_qmd: for record in new_records: diff --git a/scripts/parsePubs.py b/scripts/parsePubs.py index bc836e3..4b7e884 100644 --- a/scripts/parsePubs.py +++ b/scripts/parsePubs.py @@ -2,7 +2,7 @@ import re from pathlib import Path -import bibtexparser +from bibtex_io import read_entries def slugify(value: str) -> str: @@ -201,6 +201,11 @@ def main() -> None: action="store_true", help="Include preprints in the publications list (default is to skip).", ) + parser.add_argument( + "--preserve-existing", + action="store_true", + help="Only create missing QMD files; do not overwrite or delete existing pages.", + ) args = parser.parse_args() bib_path = Path(args.bib) @@ -210,15 +215,13 @@ def main() -> None: if args.include_preprints: preprints_dir.mkdir(parents=True, exist_ok=True) - with bib_path.open("r", encoding="utf-8") as bibtex_file: - bib_database = bibtexparser.load(bibtex_file) + entries = read_entries(bib_path) - all_ids = [] generated_ids = [] generated_preprint_ids = [] supplements_by_base = {} - for entry in bib_database.entries: + for entry in entries: doi = (entry.get("doi") or "").lower() if is_supplement(entry) and doi: base = base_doi_from_supplement(doi) @@ -245,7 +248,7 @@ def type_rank(entry: dict) -> int: best_by_doi = {} non_doi_entries = [] - for entry in bib_database.entries: + for entry in entries: doi = (entry.get("doi") or "").lower() if doi: current = best_by_doi.get(doi) @@ -258,7 +261,6 @@ def type_rank(entry: dict) -> int: for entry in selected_entries: entry_id = sanitize_id(entry.get("ID", "")) - all_ids.append(entry_id) if is_conference_abstract(entry): continue @@ -275,9 +277,10 @@ def type_rank(entry: dict) -> int: generated_ids.append(entry_id) out_path = out_dir / f"{entry_id}.qmd" - doi = (entry.get("doi") or "").lower() + if args.preserve_existing and out_path.exists(): + continue - # out_path assigned above based on preprint status + doi = (entry.get("doi") or "").lower() supplement_link = "" if doi: @@ -304,17 +307,18 @@ def type_rank(entry: dict) -> int: write_qmd(out_path, qmd_entry) - for qmd in out_dir.glob("*.qmd"): - if qmd.stem not in set(generated_ids): - qmd.unlink() + if not args.preserve_existing: + for qmd in out_dir.glob("*.qmd"): + if qmd.stem not in set(generated_ids): + qmd.unlink() - if args.include_preprints: - for qmd in preprints_dir.glob("*.qmd"): - if qmd.stem not in set(generated_preprint_ids): + if args.include_preprints: + for qmd in preprints_dir.glob("*.qmd"): + if qmd.stem not in set(generated_preprint_ids): + qmd.unlink() + elif preprints_dir.exists(): + for qmd in preprints_dir.glob("*.qmd"): qmd.unlink() - elif preprints_dir.exists(): - for qmd in preprints_dir.glob("*.qmd"): - qmd.unlink() print(f"Wrote {len(generated_ids)} QMD files to {out_dir}.") if args.include_preprints: diff --git a/scripts/test_publication_sync.py b/scripts/test_publication_sync.py new file mode 100644 index 0000000..4c110db --- /dev/null +++ b/scripts/test_publication_sync.py @@ -0,0 +1,90 @@ +import sys +import tempfile +import unittest +from pathlib import Path +from unittest.mock import patch + +import orcid_sync +import parsePubs +from bibtex_io import read_entries + + +PREPRINT = "10.5194/egusphere-2026-2572" +ARTICLE = "10.5194/amt-19-7815-2026" + + +def publication(doi, work_type): + return {"work-summary": [{ + "type": work_type, + "external-ids": {"external-id": [{"external-id-type": "doi", "external-id-value": doi}]}, + }]} + + +class PublicationSyncTest(unittest.TestCase): + def test_incremental_sync_preserves_curated_files_and_is_idempotent(self): + with tempfile.TemporaryDirectory() as tmp: + root = Path(tmp) + bib = root / "publications.bib" + preprints = root / "preprints" + preprints.mkdir() + bib.write_text( + '% Curated bibliography\n' + '@article{plewa2026a, doi={' + PREPRINT + '}, orcid_type={preprint}}\n' + '@article{plewa2026amt, doi={' + ARTICLE + '}, volume={19}, ' + 'number={22}, pages={7815--7833}}\n', + encoding="utf-8", + ) + original_bib = bib.read_bytes() + article_page = root / "plewa2026amt.qmd" + preprint_page = preprints / "plewa2026a.qmd" + manual_page = root / "manual.qmd" + for page in (article_page, preprint_page, manual_page): + page.write_text("Hand-edited page\n", encoding="utf-8") + + doi = "10.1234/new" + works = {"group": [ + publication(PREPRINT, "preprint"), + publication(ARTICLE, "journal-article"), + publication(doi, "journal-article"), + ]} + metadata = { + "title": ["A test citation"], + "author": [{"family": "Plewa", "given": "Thomas"}], + "issued": {"date-parts": [[2026]]}, + "container-title": ["Test journal"], + "volume": "12", "issue": "4", "page": "1-5", + } + args = ["orcid_sync", "--orcid", "test", "--bib-file", str(bib), + "--publications-dir", str(root), "--no-qmd", "--unpaywall-email", ""] + with patch.object(orcid_sync, "get_orcid_works", return_value=works), \ + patch.object(orcid_sync, "fetch_crossref", return_value=metadata) as fetch, \ + patch.object(sys, "argv", args): + orcid_sync.main() + first_bib = bib.read_bytes() + orcid_sync.main() + fetch.assert_called_once_with(doi) + self.assertTrue(first_bib.startswith(original_bib)) + self.assertEqual(bib.read_bytes(), first_bib) + original_preprint, original_article, added = read_entries(bib) + self.assertEqual(original_preprint["doi"], PREPRINT) + self.assertEqual((original_article["volume"], original_article["number"], + original_article["pages"]), ("19", "22", "7815--7833")) + self.assertEqual((added["ID"], added["doi"], added["volume"]), ("plewa2026a-2", doi, "12")) + + with patch.object(sys, "argv", ["parsePubs", "--bib", str(bib), "--out-dir", str(root), + "--preprints-dir", str(preprints), + "--include-preprints", "--preserve-existing"]): + parsePubs.main() + self.assertTrue((root / "plewa2026a-2.qmd").exists()) + for page in (article_page, preprint_page, manual_page): + self.assertEqual(page.read_text(encoding="utf-8"), "Hand-edited page\n") + + def test_legacy_duplicate_ids_keep_both_entries(self): + with tempfile.TemporaryDirectory() as tmp: + bib = Path(tmp) / "duplicates.bib" + bib.write_text("@article{k, title={First}}\n@article{k, title={Second}}\n", encoding="utf-8") + self.assertEqual([e["title"] for e in read_entries(bib)], ["First", "Second"]) + + +if __name__ == "__main__": + unittest.main() From 71fac7d3bdf96da236258bbddab230377f0d4bad Mon Sep 17 00:00:00 2001 From: Christian Frankenberg Date: Sun, 29 Nov 2026 07:30:08 -0800 Subject: [PATCH 3/3] Make ORCID sync additive and deploy the updated commit --- .github/workflows/orcid-sync.yml | 42 +++++++++++++++++++++++++++----- .github/workflows/publish.yml | 7 ++++++ 2 files changed, 43 insertions(+), 6 deletions(-) diff --git a/.github/workflows/orcid-sync.yml b/.github/workflows/orcid-sync.yml index fa9c88d..8ccc0a3 100644 --- a/.github/workflows/orcid-sync.yml +++ b/.github/workflows/orcid-sync.yml @@ -2,16 +2,27 @@ name: ORCID Sync on: schedule: - - cron: "0 3 * * 0" + - cron: "17 3 * * 0" workflow_dispatch: + inputs: + dry_run: + description: Preview changes without committing or publishing + type: boolean + default: true + +concurrency: + group: orcid-sync-${{ github.ref }} + cancel-in-progress: false jobs: sync: + if: ${{ github.ref_name == github.event.repository.default_branch || (github.event_name == 'workflow_dispatch' && inputs.dry_run) }} runs-on: ubuntu-latest permissions: contents: write outputs: changed: ${{ steps.commit.outputs.changed }} + sha: ${{ steps.commit.outputs.sha }} steps: - name: Checkout uses: actions/checkout@v4 @@ -24,6 +35,9 @@ jobs: - name: Install dependencies run: python -m pip install --upgrade pip && pip install -r requirements.txt + - name: Test publication sync + run: python -m unittest discover -s scripts + - name: Sync ORCID env: ORCID_ID: "0000-0002-0546-5857" @@ -33,24 +47,38 @@ jobs: --orcid "$ORCID_ID" \ --bib-file publications/publications.bib \ --publications-dir publications \ - --full + --no-qmd - - name: Regenerate QMD files + - name: Generate missing publication pages run: | + if git diff --quiet -- publications/publications.bib; then + echo "No new bibliography entries." + exit 0 + fi python scripts/parsePubs.py \ --bib publications/publications.bib \ --out-dir publications \ - --include-preprints + --include-preprints \ + --preserve-existing + + - name: Preview changes + if: ${{ github.event_name == 'workflow_dispatch' && inputs.dry_run }} + run: | + git status --short -- publications + git diff --stat -- publications + git diff -- publications/publications.bib | grep -E '^\+([[:space:]]*doi[[:space:]]|@)' || true - name: Commit changes + if: ${{ github.event_name != 'workflow_dispatch' || !inputs.dry_run }} id: commit run: | - if git status --porcelain | grep -q .; then + if [ -n "$(git status --porcelain -- publications)" ]; then git config user.name "github-actions[bot]" git config user.email "github-actions[bot]@users.noreply.github.com" - git add publications/publications.bib publications publications/preprints + git add -- publications git commit -m "chore: sync ORCID publications" git push + echo "sha=$(git rev-parse HEAD)" >> "$GITHUB_OUTPUT" echo "changed=true" >> "$GITHUB_OUTPUT" else echo "No changes to commit." @@ -63,3 +91,5 @@ jobs: permissions: contents: write uses: ./.github/workflows/publish.yml + with: + source_ref: ${{ needs.sync.outputs.sha }} diff --git a/.github/workflows/publish.yml b/.github/workflows/publish.yml index 7373641..717ed0e 100644 --- a/.github/workflows/publish.yml +++ b/.github/workflows/publish.yml @@ -1,6 +1,11 @@ on: workflow_dispatch: workflow_call: + inputs: + source_ref: + description: Commit to publish + type: string + required: false push: branches: main @@ -14,6 +19,8 @@ jobs: steps: - name: Check out repository uses: actions/checkout@v4 + with: + ref: ${{ inputs.source_ref || github.sha }} - name: Set up Quarto uses: quarto-dev/quarto-actions/setup@v2