{html.escape(candidate.title)}
{html.escape(candidate.abstract[:380] + ('...' if len(candidate.abstract) > 380 else '')) if candidate.abstract else 'No abstract snippet available from Crossref metadata.'}
{html.escape(candidate.doi_url)}#!/usr/bin/env python3
"""
Segment manuscript text, search strict Nature/CNS-family citation candidates, and export a
reference-manager file. By default the script writes one inspectable `.ris` file.
Optional review artifacts can still be generated, but they are opt-in.
"""
from __future__ import annotations
import argparse
import csv
import hashlib
import html
import json
import re
import sys
import time
from dataclasses import dataclass, field
from pathlib import Path
from typing import Any, Callable
from urllib.parse import quote, urlencode
from urllib.request import Request, urlopen
import defusedxml.ElementTree as ET
xml_escape = lambda data: data.replace("&", "&").replace("<", "<").replace(">", ">")
quoteattr = lambda data: '"%s"' % xml_escape(data).replace('"', """)
CROSSREF_API = "https://api.crossref.org/works"
PUBMED_EFETCH = "https://eutils.ncbi.nlm.nih.gov/entrez/eutils/efetch.fcgi"
USER_AGENT = "codex-nature-citation/1.0 (mailto:unknown@example.com)"
EXPORT_FORMAT_CHOICES = ("enw", "ris", "zotero-rdf", "rdf")
DEFAULT_EXPORT_FORMAT = "ris"
ZOTERO_RDF_NS = {
"rdf": "http://www.w3.org/1999/02/22-rdf-syntax-ns#",
"z": "http://www.zotero.org/namespaces/export#",
"dcterms": "http://purl.org/dc/terms/",
"bib": "http://purl.org/net/biblio#",
"foaf": "http://xmlns.com/foaf/0.1/",
"dc": "http://purl.org/dc/elements/1.1/",
"prism": "http://prismstandard.org/namespaces/1.2/basic/",
}
NATURE_EXACT = {
"Nature",
# Research titles verified against the publisher's research-journals directory.
"Nature Aging",
"Nature Astronomy",
"Nature Biomedical Engineering",
"Nature Catalysis",
"Nature Chemical Engineering",
"Nature Cities",
"Nature Health",
"Nature Mechanical Engineering",
"Nature Mental Health",
"Nature Sensors",
"Nature Sustainability",
"Nature Synthesis",
"Nature Water",
"Nature Biotechnology",
"Nature Cancer",
"Nature Cardiovascular Research",
"Nature Cell Biology",
"Nature Chemical Biology",
"Nature Chemistry",
"Nature Climate Change",
"Nature Communications",
"Nature Computational Science",
"Nature Ecology & Evolution",
"Nature Electronics",
"Nature Energy",
"Nature Food",
"Nature Genetics",
"Nature Geoscience",
"Nature Human Behaviour",
"Nature Immunology",
"Nature Machine Intelligence",
"Nature Materials",
"Nature Medicine",
"Nature Metabolism",
"Nature Methods",
"Nature Microbiology",
"Nature Nanotechnology",
"Nature Neuroscience",
"Nature Photonics",
"Nature Physics",
"Nature Plants",
"Nature Protocols",
"Nature Reviews Cancer",
"Nature Reviews Cardiology",
"Nature Reviews Chemistry",
"Nature Reviews Clinical Oncology",
"Nature Reviews Drug Discovery",
"Nature Reviews Earth & Environment",
"Nature Reviews Endocrinology",
"Nature Reviews Gastroenterology & Hepatology",
"Nature Reviews Genetics",
"Nature Reviews Immunology",
"Nature Reviews Materials",
"Nature Reviews Microbiology",
"Nature Reviews Molecular Cell Biology",
"Nature Reviews Nephrology",
"Nature Reviews Neurology",
"Nature Reviews Neuroscience",
"Nature Reviews Physics",
"Nature Reviews Psychology",
"Nature Reviews Rheumatology",
"Nature Structural & Molecular Biology",
"Scientific Reports",
}
# Explicit names from the publisher's npj Series directory, checked 2026-10-16.
# https://www.nature.com/nature-portfolio/about-journals/npj-series
NPJ_EXACT = set(json.loads((Path(__file__).resolve().parents[1] / "data" / "npj-journals.json").read_text(encoding="utf-8")))
SCIENCE_EXACT = {
"Science",
"Science Advances",
"Science Immunology",
"Science Robotics",
"Science Signaling",
"Science Translational Medicine",
}
CELL_EXACT = {
"Cell",
"Cancer Cell",
"Cell Chemical Biology",
"Cell Genomics",
"Cell Host & Microbe",
"Cell Metabolism",
"Cell Reports",
"Cell Reports Medicine",
"Cell Reports Methods",
"Cell Reports Physical Science",
"Cell Stem Cell",
"Cell Systems",
"Chem",
"Current Biology",
"Developmental Cell",
"Immunity",
"Joule",
"Med",
"Molecular Cell",
"Neuron",
"One Earth",
"Patterns",
"Structure",
"The Innovation",
}
CELL_TRENDS_EXACT = {
"Trends in Biochemical Sciences",
"Trends in Biotechnology",
"Trends in Cancer",
"Trends in Cell Biology",
"Trends in Chemistry",
"Trends in Cognitive Sciences",
"Trends in Ecology & Evolution",
"Trends in Endocrinology & Metabolism",
"Trends in Genetics",
"Trends in Immunology",
"Trends in Microbiology",
"Trends in Molecular Medicine",
"Trends in Neurosciences",
"Trends in Parasitology",
"Trends in Pharmacological Sciences",
"Trends in Plant Science",
}
FLAGSHIP = {"Nature", "Science", "Cell"}
@dataclass
class Segment:
id: str
text: str
search_query: str
order: int
def as_dict(self) -> dict[str, Any]:
return {
"id": self.id,
"order": self.order,
"text": self.text,
"search_query": self.search_query,
}
@dataclass
class Candidate:
title: str
journal: str
family: str
year: str
y1: str
doi: str
url: str
volume: str
issue: str
start_page: str
end_page: str
issn: str
authors: list[str]
abstract: str
type: str
score: float
source_query: str
pmid: str = ""
source_catalog: str = "Crossref"
author_warnings: list[str] = field(default_factory=list)
@property
def doi_url(self) -> str:
return f"https://doi.org/{self.doi}" if self.doi else self.url
@property
def key(self) -> str:
if self.doi:
return self.doi.lower()
return f"{self.title.lower()}|{self.journal.lower()}"
@property
def first_author(self) -> str:
if not self.authors:
return "Unknown author"
return self.authors[0].split(",", 1)[0]
@property
def citation_marker(self) -> str:
if self.year:
return f"({self.first_author} et al., {self.year})"
return f"({self.first_author} et al.)"
@property
def page_range(self) -> str:
if self.start_page and self.end_page:
return f"{self.start_page}-{self.end_page}"
return self.start_page
@property
def identifier_url(self) -> str:
return self.doi_url or self.url
@property
def article_resource(self) -> str:
if self.identifier_url:
return self.identifier_url
return f"urn:candidate:{stable_hash(self.key or self.title or 'candidate')}"
@property
def journal_resource(self) -> str:
return build_journal_resource(self)
@property
def zotero_citation_key(self) -> str:
return build_zotero_citation_key(self)
def as_dict(self) -> dict[str, Any]:
return {
"title": self.title,
"journal": self.journal,
"family": self.family,
"year": self.year,
"doi": self.doi,
"pmid": self.pmid,
"url": self.url,
"doi_url": self.doi_url,
"volume": self.volume,
"issue": self.issue,
"start_page": self.start_page,
"end_page": self.end_page,
"issn": self.issn,
"authors": self.authors,
"abstract": self.abstract,
"type": self.type,
"score": self.score,
"source_query": self.source_query,
"source_catalog": self.source_catalog,
"author_metadata_status": "complete" if not self.author_warnings else "incomplete",
"author_warnings": self.author_warnings,
"citation_marker": self.citation_marker,
"support_grade": "metadata-only candidate",
"screening_note": "Inspect abstract/publisher page before citing this paper as support.",
"enw_record": build_enw_record(self),
"ris_record": build_ris_record(self),
"journal_resource": self.journal_resource,
"zotero_rdf_article": build_zotero_rdf_article(self),
"zotero_rdf_journal": build_zotero_rdf_journal(self),
}
def normalize_title(title: str) -> str:
return re.sub(r"\s+", " ", title or "").strip()
def stable_hash(value: str) -> str:
return hashlib.sha256(value.encode("utf-8")).hexdigest()[:12]
def slugify(value: str) -> str:
slug = re.sub(r"[^a-z0-9]+", "-", (value or "").lower()).strip("-")
return slug or "item"
def normalize_export_format(value: str | None) -> str:
if not value:
return DEFAULT_EXPORT_FORMAT
if value == "rdf":
return "zotero-rdf"
return value
def infer_export_format(output_path: Path | None) -> str:
if output_path is None:
return DEFAULT_EXPORT_FORMAT
suffix = output_path.suffix.lower()
if suffix == ".ris":
return "ris"
if suffix == ".rdf":
return "zotero-rdf"
if suffix == ".enw":
return "enw"
return DEFAULT_EXPORT_FORMAT
def export_filename(export_format: str, base: str = "references") -> str:
if export_format == "ris":
return f"{base}.ris"
if export_format == "zotero-rdf":
return f"{base}.rdf"
return f"{base}.enw"
def slug_from_text(text: str, max_words: int = 6) -> str:
"""Derive a filename slug from the first meaningful words of manuscript text."""
text = clean_text(text)
text = re.sub(r"\[[^\]]+\]|\([A-Za-z]+ et al\.,? \d{4}\)", " ", text)
words = re.findall(r"[A-Za-z0-9]+|[一-鿿]+", text)
stopwords = {
"the", "a", "an", "and", "or", "of", "to", "in", "for", "by", "with", "on", "at",
"from", "is", "are", "was", "were", "be", "been", "being", "that", "this", "these",
"those", "it", "its", "can", "may", "could", "not", "but", "as", "if", "into",
}
content = [w for w in words if w.lower() not in stopwords]
slug = "-".join(w.lower() for w in content[:max_words])
return slug or "references"
def export_label(export_format: str) -> str:
if export_format == "ris":
return "RIS"
if export_format == "zotero-rdf":
return "Zotero RDF"
return "ENW"
def make_partial_path(path: Path) -> Path:
return path.with_name(f"{path.stem}.partial{path.suffix}")
def retry_with_backoff(action: Callable[[], Any], max_retries: int, base_delay: float = 0.5) -> Any:
last_error: Exception | None = None
retries = max(0, max_retries)
for attempt in range(retries + 1):
try:
return action()
except Exception as exc: # noqa: BLE001
last_error = exc
if attempt >= retries:
break
time.sleep(base_delay * (2 ** attempt))
if last_error is not None:
raise last_error
raise RuntimeError("retry_with_backoff() exited without returning or raising")
def resolve_batch_size(segment_count: int, args: argparse.Namespace) -> int:
if getattr(args, "batch_size", 0) and args.batch_size > 0:
return max(1, args.batch_size)
if segment_count > 10:
return 10
return 0
def chunk_segments(segments: list[Segment], batch_size: int) -> list[list[Segment]]:
if not segments:
return []
if batch_size <= 0 or batch_size >= len(segments):
return [segments]
return [segments[idx : idx + batch_size] for idx in range(0, len(segments), batch_size)]
def limit_segments(segments: list[Segment], max_segments: int) -> tuple[list[Segment], int]:
if max_segments and max_segments > 0 and len(segments) > max_segments:
return segments[:max_segments], len(segments) - max_segments
return segments, 0
def zotero_date_value(item: Candidate) -> str:
if item.y1:
return item.y1.replace("/", "-")
return item.year
def split_author_parts(name: str) -> tuple[str, str]:
if name.endswith(","):
return name[:-1].replace(",,", ",").strip(), ""
if "," in name:
family, given = name.split(",", 1)
return family.strip(), given.strip()
parts = [part for part in name.split() if part]
if not parts:
return "", ""
if len(parts) == 1:
return parts[0], ""
return parts[-1], " ".join(parts[:-1])
def build_journal_resource(item: Candidate) -> str:
parts: list[str] = []
if item.issn:
parts.append(f"issn:{slugify(item.issn)}")
elif item.journal:
parts.append(f"title:{slugify(item.journal)}")
else:
parts.append(f"record:{stable_hash(item.key or item.title or 'journal')}")
if item.volume:
parts.append(f"vol:{slugify(item.volume)}")
if item.issue:
parts.append(f"issue:{slugify(item.issue)}")
return "urn:" + ":".join(parts)
def build_zotero_citation_key(item: Candidate) -> str:
first_author = slugify(item.first_author)
title_words = re.findall(r"[A-Za-z0-9]+", item.title)[:3]
title_part = "".join(word.capitalize() for word in title_words) or "Item"
year = item.year or "n.d."
return f"{first_author}{title_part}{year}"
def journal_family(journal: str) -> str | None:
journal = normalize_title(journal)
if not journal:
return None
if journal in NATURE_EXACT or journal in NPJ_EXACT:
return "Nature Portfolio"
if journal in SCIENCE_EXACT:
return "Science family"
if journal in CELL_EXACT or journal in CELL_TRENDS_EXACT:
return "Cell Press"
return None
def in_scope(journal: str, scope: str) -> bool:
journal = normalize_title(journal)
if not journal:
return False
if scope == "flagship":
return journal in FLAGSHIP
family = journal_family(journal)
if scope == "nature":
return family == "Nature Portfolio"
if scope == "science":
return family == "Science family"
if scope == "cell":
return family == "Cell Press"
return family in {"Nature Portfolio", "Science family", "Cell Press"}
def first(values: list[Any] | None, default: str = "") -> str:
if not values:
return default
value = values[0]
if isinstance(value, str):
return value
return default
def date_parts(item: dict[str, Any]) -> list[int]:
for key in ("published-print", "published-online", "published", "issued"):
parts = (item.get(key) or {}).get("date-parts")
if not (parts and parts[0]):
continue
# Crossref uses [[null]] for an unknown date; keep only the leading integer fields.
clean: list[int] = []
for value in parts[0]:
if not isinstance(value, int) or isinstance(value, bool):
break
clean.append(value)
if clean:
return clean
return []
def year_from_item(item: dict[str, Any]) -> str:
parts = date_parts(item)
return str(parts[0]) if parts else ""
def y1_from_item(item: dict[str, Any]) -> str:
parts = date_parts(item)
if not parts:
return ""
year = f"{parts[0]:04d}"
month = f"{parts[1]:02d}" if len(parts) > 1 else "01"
day = f"{parts[2]:02d}" if len(parts) > 2 else "01"
return f"{year}/{month}/{day}"
def endnote_corporate_author(name: str) -> str:
"""Return an EndNote-safe corporate author name.
EndNote requires a trailing comma to prevent a corporate name from being
inverted. Embedded commas are doubled so they remain part of the name.
"""
normalized = clean_text(name).rstrip(",").strip()
if not normalized:
return ""
return f"{normalized.replace(',', ',,')},"
def author_name(author: dict[str, Any]) -> str:
family = clean_text(str(author.get("family") or ""))
given = clean_text(str(author.get("given") or ""))
suffix = clean_text(str(author.get("suffix") or ""))
literal = clean_text(str(author.get("name") or ""))
if literal and not family and not given:
return endnote_corporate_author(literal)
if family and given:
parts = [family, given]
if suffix:
parts.append(suffix)
return ", ".join(parts)
return family or given or literal
def crossref_author_warnings(raw_authors: list[dict[str, Any]], authors: list[str]) -> list[str]:
warnings: list[str] = []
if not raw_authors or not authors:
return ["No structured author list was supplied by the metadata source."]
for index, author in enumerate(raw_authors, 1):
family = clean_text(str(author.get("family") or ""))
given = clean_text(str(author.get("given") or ""))
literal = clean_text(str(author.get("name") or ""))
if literal and not family and not given:
continue
if not family or not given:
warnings.append(
f"Author {index} lacks a {'family name' if not family else 'given name or initials'} in structured metadata."
)
return warnings
def pages(item: dict[str, Any]) -> tuple[str, str]:
page = item.get("page", "") or item.get("article-number", "")
if not page:
return "", ""
if "-" in page:
start, end = page.split("-", 1)
return start.strip(), end.strip()
return page.strip(), ""
def clean_text(text: str) -> str:
text = re.sub(r"<[^>]+>", " ", text or "")
text = re.sub(r"\s+", " ", text)
return text.strip()
def ris_escape(text: str) -> str:
return clean_text(text).replace("\n", " ").replace("\r", " ")
def split_sentences(text: str) -> list[str]:
text = re.sub(r"\s+", " ", text.strip())
if not text:
return []
pattern = r"(?<=[.!?。!?])\s+|(?<=[。!?])"
return [part.strip() for part in re.split(pattern, text) if part.strip()]
def looks_like_heading(text: str) -> bool:
stripped = text.strip()
if len(stripped) > 90:
return False
if stripped.endswith((".", "。", "!", "!", "?", "?")):
return False
words = stripped.split()
if 0 < len(words) <= 8 and not any(char in stripped for char in ",;,;"):
return True
return False
def query_from_segment(text: str, max_words: int = 26) -> str:
text = clean_text(text)
text = re.sub(r"\[[^\]]+\]|\([A-Za-z]+ et al\.,? \d{4}\)", " ", text)
words = re.findall(r"[A-Za-z0-9α-ωΑ-Ωβγδκλμνπρστυφχψω\-]+|[\u4e00-\u9fff]+", text)
if not words:
return text[:240]
return " ".join(words[:max_words])
def fallback_queries_from_segment(text: str) -> list[str]:
words = re.findall(r"[A-Za-z0-9α-ωΑ-Ωβγδκλμνπρστυφχψω\-]+|[\u4e00-\u9fff]+", clean_text(text))
if not words:
return []
stopwords = {
"the", "a", "an", "and", "or", "of", "to", "in", "for", "by", "with", "on", "at", "from",
"reveals", "reveal", "revealed", "promote", "promotes", "promoted", "promoting",
"suppress", "suppresses", "suppressing", "show", "shows", "showed", "indicate", "indicates",
"indicated", "identify", "identifies", "identified", "can", "may", "could", "is", "are",
"was", "were", "be", "been", "being", "that", "this", "these", "those",
}
content = [word for word in words if word.lower() not in stopwords]
candidates: list[str] = []
if len(content) >= 3:
candidates.append(" ".join(content[:12]))
if len(content) >= 5:
candidates.append(" ".join(content[:8]))
deduped: list[str] = []
seen: set[str] = set()
for candidate in candidates:
normalized = candidate.lower().strip()
if normalized and normalized not in seen:
seen.add(normalized)
deduped.append(candidate)
return deduped
def segment_text(text: str, max_chars: int = 700) -> list[Segment]:
normalized = text.replace("\r\n", "\n").replace("\r", "\n").strip()
if not normalized:
return []
paragraphs = [part.strip() for part in re.split(r"\n\s*\n+", normalized) if part.strip()]
raw_segments: list[str] = []
for paragraph in paragraphs:
if looks_like_heading(paragraph):
continue
sentences = split_sentences(paragraph)
if len(sentences) > 1:
raw_segments.extend(sentences)
elif len(paragraph) <= max_chars:
raw_segments.append(re.sub(r"\s+", " ", paragraph))
else:
raw_segments.extend(sentences)
segments: list[Segment] = []
for idx, segment in enumerate(raw_segments, 1):
cleaned = clean_text(segment)
if len(cleaned) < 10:
continue
segments.append(
Segment(
id=f"S{len(segments) + 1:03d}",
text=cleaned,
search_query=query_from_segment(cleaned),
order=len(segments) + 1,
)
)
return segments
def candidate_from_crossref(item: dict[str, Any], source_query: str) -> Candidate | None:
journal = first(item.get("container-title"))
if not journal:
return None
family = journal_family(journal) or ""
start, end = pages(item)
raw_authors = item.get("author", [])
authors = [author_name(author) for author in raw_authors]
authors = [author for author in authors if author]
return Candidate(
title=clean_text(first(item.get("title"))),
journal=normalize_title(journal),
family=family,
year=year_from_item(item),
y1=y1_from_item(item),
doi=item.get("DOI", ""),
url=item.get("URL", ""),
volume=item.get("volume", ""),
issue=item.get("issue", ""),
start_page=start,
end_page=end,
issn=first(item.get("ISSN")),
authors=authors,
abstract=clean_text(item.get("abstract", "")),
type=item.get("type", ""),
score=float(item.get("score", 0.0) or 0.0),
source_query=source_query,
source_catalog="Crossref",
author_warnings=crossref_author_warnings(raw_authors, authors),
)
def crossref_headers(mailto: str | None = None) -> dict[str, str]:
return {"User-Agent": USER_AGENT if not mailto else f"codex-nature-citation/1.0 (mailto:{mailto})"}
def fetch_crossref(query: str, rows: int, mailto: str | None = None, from_year: int | None = None, to_year: int | None = None, retries: int = 2) -> list[dict[str, Any]]:
filters = ["type:journal-article"]
if from_year is not None:
filters.append(f"from-pub-date:{from_year}-01-01")
if to_year is not None:
filters.append(f"until-pub-date:{to_year}-12-31")
params = {
"query.bibliographic": query,
"rows": str(rows),
"select": "DOI,title,container-title,published,published-print,published-online,issued,author,volume,issue,page,article-number,ISSN,URL,abstract,type,score",
"filter": ",".join(filters),
"sort": "relevance",
"order": "desc",
}
if mailto:
params["mailto"] = mailto
url = f"{CROSSREF_API}?{urlencode(params)}"
req = Request(url, headers=crossref_headers(mailto))
last_exc: Exception | None = None
for attempt in range(1, retries + 2):
try:
with urlopen(req, timeout=30) as response:
payload = json.loads(response.read().decode("utf-8"))
return payload.get("message", {}).get("items", [])
except Exception as exc: # noqa: BLE001
last_exc = exc
if attempt <= retries:
time.sleep(min(2 ** attempt, 8))
raise last_exc # type: ignore[misc]
def fetch_crossref_doi(doi: str, mailto: str | None = None) -> dict[str, Any]:
url = f"{CROSSREF_API}/{quote(doi.strip(), safe='')}"
if mailto:
url = f"{url}?{urlencode({'mailto': mailto})}"
req = Request(url, headers=crossref_headers(mailto))
with urlopen(req, timeout=30) as response:
payload = json.loads(response.read().decode("utf-8"))
return payload.get("message", {})
MONTHS = {
"jan": 1,
"feb": 2,
"mar": 3,
"apr": 4,
"may": 5,
"jun": 6,
"jul": 7,
"aug": 8,
"sep": 9,
"oct": 10,
"nov": 11,
"dec": 12,
}
def xml_text(element: ET.Element | None) -> str:
if element is None:
return ""
return clean_text("".join(element.itertext()))
def pubmed_date(article: ET.Element) -> tuple[str, str]:
date_node = article.find("MedlineCitation/Article/Journal/JournalIssue/PubDate")
if date_node is None:
date_node = article.find("MedlineCitation/Article/ArticleDate")
year = xml_text(date_node.find("Year")) if date_node is not None else ""
if not year and date_node is not None:
match = re.search(r"\b(18|19|20|21)\d{2}\b", xml_text(date_node.find("MedlineDate")))
year = match.group(0) if match else ""
if not year:
return "", ""
month_text = xml_text(date_node.find("Month")) if date_node is not None else ""
if month_text.isdigit():
month = max(1, min(12, int(month_text)))
else:
month = MONTHS.get(month_text[:3].lower(), 1)
day_text = xml_text(date_node.find("Day")) if date_node is not None else ""
day = max(1, min(31, int(day_text))) if day_text.isdigit() else 1
return year, f"{int(year):04d}/{month:02d}/{day:02d}"
def split_page_text(page: str) -> tuple[str, str]:
page = clean_text(page)
if not page:
return "", ""
if "-" in page:
start, end = page.split("-", 1)
return start.strip(), end.strip()
return page, ""
def pubmed_authors(article: ET.Element) -> tuple[list[str], list[str]]:
authors: list[str] = []
warnings: list[str] = []
author_nodes = article.findall("MedlineCitation/Article/AuthorList/Author")
if not author_nodes:
return [], ["No structured author list was supplied by PubMed."]
for index, author in enumerate(author_nodes, 1):
collective = xml_text(author.find("CollectiveName"))
if collective:
authors.append(endnote_corporate_author(collective))
continue
family = xml_text(author.find("LastName"))
given = xml_text(author.find("ForeName")) or xml_text(author.find("Initials"))
suffix = xml_text(author.find("Suffix"))
if family and given:
name_parts = [family, given]
if suffix:
name_parts.append(suffix)
authors.append(", ".join(name_parts))
continue
incomplete = family or given
if incomplete:
authors.append(incomplete)
warnings.append(
f"Author {index} lacks a {'family name' if not family else 'given name or initials'} in PubMed metadata."
)
if not authors and not warnings:
warnings.append("No usable authors were found in PubMed metadata.")
return authors, warnings
def candidate_from_pubmed(article: ET.Element) -> Candidate | None:
article_node = article.find("MedlineCitation/Article")
if article_node is None:
return None
pmid = xml_text(article.find("MedlineCitation/PMID"))
journal = xml_text(article_node.find("Journal/Title")) or xml_text(
article.find("MedlineCitation/MedlineJournalInfo/MedlineTA")
)
title = xml_text(article_node.find("ArticleTitle"))
if not title or not journal:
return None
year, y1 = pubmed_date(article)
start_page, end_page = split_page_text(xml_text(article_node.find("Pagination/MedlinePgn")))
doi = ""
for identifier in article.findall("PubmedData/ArticleIdList/ArticleId"):
if identifier.attrib.get("IdType", "").lower() == "doi":
doi = xml_text(identifier)
break
if not doi:
for identifier in article_node.findall("ELocationID"):
if identifier.attrib.get("EIdType", "").lower() == "doi":
doi = xml_text(identifier)
break
authors, warnings = pubmed_authors(article)
abstract = " ".join(
xml_text(node) for node in article_node.findall("Abstract/AbstractText") if xml_text(node)
)
return Candidate(
title=title,
journal=normalize_title(journal),
family=journal_family(journal) or "",
year=year,
y1=y1,
doi=doi,
url=f"https://pubmed.ncbi.nlm.nih.gov/{pmid}/" if pmid else "",
volume=xml_text(article_node.find("Journal/JournalIssue/Volume")),
issue=xml_text(article_node.find("Journal/JournalIssue/Issue")),
start_page=start_page,
end_page=end_page,
issn=xml_text(article_node.find("Journal/ISSN")),
authors=authors,
abstract=abstract,
type=xml_text(article_node.find("PublicationTypeList/PublicationType")) or "journal-article",
score=0.0,
source_query=f"pmid:{pmid}",
pmid=pmid,
source_catalog="PubMed",
author_warnings=warnings,
)
def fetch_pubmed(pmids: list[str], email: str | None = None) -> list[ET.Element]:
params = {
"db": "pubmed",
"id": ",".join(pmids),
"retmode": "xml",
"tool": "nature-citation",
}
if email:
params["email"] = email
request = Request(
f"{PUBMED_EFETCH}?{urlencode(params)}",
headers={"User-Agent": USER_AGENT if not email else f"codex-nature-citation/1.0 (mailto:{email})"},
)
with urlopen(request, timeout=45) as response:
root = ET.fromstring(response.read())
return list(root.findall("PubmedArticle"))
def dedupe(candidates: list[Candidate]) -> list[Candidate]:
output: list[Candidate] = []
positions: dict[str, int] = {}
for candidate in candidates:
if not candidate.key:
continue
if candidate.key not in positions:
positions[candidate.key] = len(output)
output.append(candidate)
continue
existing_index = positions[candidate.key]
existing = output[existing_index]
existing_quality = (not existing.author_warnings, len(existing.authors), bool(existing.doi))
candidate_quality = (not candidate.author_warnings, len(candidate.authors), bool(candidate.doi))
if candidate_quality > existing_quality:
output[existing_index] = candidate
return output
def author_integrity_issues(candidates: list[Candidate]) -> list[str]:
issues: list[str] = []
for candidate in candidates:
identifier = candidate.doi or (f"PMID {candidate.pmid}" if candidate.pmid else candidate.title)
candidate_issues = list(candidate.author_warnings)
if not candidate.authors and not candidate_issues:
candidate_issues.append("No authors are present.")
for index, author in enumerate(candidate.authors, 1):
if "," not in author and not any(issue.startswith(f"Author {index} ") for issue in candidate_issues):
candidate_issues.append(
f"Author {index} is not encoded as a complete personal name or an EndNote corporate author."
)
for issue in candidate_issues:
issues.append(f"{identifier}: {issue}")
return issues
def validate_author_integrity(candidates: list[Candidate], allow_incomplete: bool = False) -> None:
issues = author_integrity_issues(candidates)
if not issues or allow_incomplete:
return
preview = "\n".join(f" - {issue}" for issue in issues[:12])
remainder = f"\n - ... and {len(issues) - 12} more issue(s)" if len(issues) > 12 else ""
raise ValueError(
"Author metadata integrity check failed. Export was stopped so surname-only, missing, or "
"otherwise incomplete author data is not presented as EndNote-ready. Refetch the affected "
"records with --pmid/--pmid-file or verify them against the publisher record. Use "
"--allow-incomplete-authors only when the limitation is intentional.\n"
f"{preview}{remainder}"
)
def build_ris_record(item: Candidate) -> str:
lines: list[str] = []
lines.append("TY - JOUR")
if item.title:
lines.append(f"TI - {ris_escape(item.title)}")
for author in item.authors:
lines.append(f"AU - {ris_escape(author)}")
if item.journal:
lines.append(f"T2 - {ris_escape(item.journal)}")
lines.append(f"JO - {ris_escape(item.journal)}")
if item.year:
lines.append(f"PY - {ris_escape(item.year)}")
if item.y1:
lines.append(f"Y1 - {ris_escape(item.y1)}")
if item.volume:
lines.append(f"VL - {ris_escape(item.volume)}")
if item.issue:
lines.append(f"IS - {ris_escape(item.issue)}")
if item.start_page:
lines.append(f"SP - {ris_escape(item.start_page)}")
if item.end_page:
lines.append(f"EP - {ris_escape(item.end_page)}")
if item.doi:
lines.append(f"DO - {ris_escape(item.doi)}")
if item.pmid:
lines.append(f"AN - PMID:{ris_escape(item.pmid)}")
if item.doi_url:
lines.append(f"UR - {ris_escape(item.doi_url)}")
if item.issn:
lines.append(f"SN - {ris_escape(item.issn)}")
for warning in item.author_warnings:
lines.append(f"N1 - Author metadata warning: {ris_escape(warning)}")
lines.append("N1 - Metadata-only candidate. Inspect abstract or publisher page before citing as support.")
lines.append("ER -")
return "\n".join(lines)
def write_ris(candidates: list[Candidate], path: Path, allow_incomplete_authors: bool = False) -> None:
validate_author_integrity(candidates, allow_incomplete=allow_incomplete_authors)
lines: list[str] = []
for item in candidates:
lines.append(build_ris_record(item))
lines.append("")
path.write_text("\n".join(lines), encoding="utf-8")
def build_enw_record(item: Candidate) -> str:
lines: list[str] = []
lines.append("%0 Journal Article")
if item.title:
lines.append(f"%T {ris_escape(item.title)}")
for author in item.authors:
lines.append(f"%A {ris_escape(author)}")
if item.journal:
lines.append(f"%J {ris_escape(item.journal)}")
if item.volume:
lines.append(f"%V {ris_escape(item.volume)}")
if item.issue:
lines.append(f"%N {ris_escape(item.issue)}")
if item.start_page and item.end_page:
lines.append(f"%P {ris_escape(item.start_page)}-{ris_escape(item.end_page)}")
elif item.start_page:
lines.append(f"%P {ris_escape(item.start_page)}")
if item.year:
lines.append(f"%D {ris_escape(item.year)}")
if item.issn:
lines.append(f"%@ {ris_escape(item.issn)}")
if item.doi:
lines.append(f"%R {ris_escape(item.doi)}")
if item.pmid:
lines.append(f"%M PMID:{ris_escape(item.pmid)}")
if item.doi_url:
lines.append(f"%U {ris_escape(item.doi_url)}")
return "\n".join(lines)
def write_enw(candidates: list[Candidate], path: Path, allow_incomplete_authors: bool = False) -> None:
validate_author_integrity(candidates, allow_incomplete=allow_incomplete_authors)
lines: list[str] = []
for item in candidates:
lines.append(build_enw_record(item))
lines.append("")
path.write_text("\n".join(lines), encoding="utf-8")
def build_zotero_rdf_article(item: Candidate) -> str:
lines: list[str] = [f' {html.escape(candidate.abstract[:380] + ('...' if len(candidate.abstract) > 380 else '')) if candidate.abstract else 'No abstract snippet available from Crossref metadata.'}{html.escape(candidate.title)}
No in-scope candidate was found for this segment.
') cards.append( f"""{html.escape(segment.text)}
{html.escape(entry["suggested_insert_text"] or "No candidate")}
Scholar-style browsing for strict Nature/CNS-family candidates. Filter by year, compare related hits, choose the references you actually want, then download them as RIS, ENW, or Zotero RDF.