fix: close the part 1 review minors
This commit is contained in:
@@ -28,7 +28,13 @@ def ledger_status_cmd(
|
||||
con = open_ledger(db)
|
||||
try:
|
||||
for row in ledger_status(con):
|
||||
typer.echo(row.target_id)
|
||||
counts = row.claims_by_tier
|
||||
typer.echo(
|
||||
f"{row.target_id}\t{row.gaps}\t{row.last_run or ''}\t"
|
||||
f"{row.open_contradictions}\t{counts['rule']}\t"
|
||||
f"{counts['aggregate']}\t{counts['literature']}\t"
|
||||
f"{counts['synthetic']}"
|
||||
)
|
||||
finally:
|
||||
con.close()
|
||||
|
||||
|
||||
@@ -9,7 +9,7 @@ from dataclasses import dataclass
|
||||
@dataclass(frozen=True)
|
||||
class SeriesRow:
|
||||
series_id: str
|
||||
year: int
|
||||
year: int | None
|
||||
period: str
|
||||
value: float | None
|
||||
|
||||
@@ -33,7 +33,7 @@ def parse_observations(payload: Mapping[str, object]) -> tuple[SeriesRow, ...]:
|
||||
if not isinstance(item, Mapping):
|
||||
continue
|
||||
date = str(item.get("date") or "")
|
||||
year = int(date[:4]) if len(date) >= 4 and date[:4].isdigit() else 0
|
||||
year = int(date[:4]) if len(date) >= 4 and date[:4].isdigit() else None
|
||||
rows.append(
|
||||
SeriesRow(
|
||||
series_id=str(item.get("series_id") or ""),
|
||||
|
||||
@@ -14,7 +14,13 @@ def disagreements(a: Mapping[str, str], b: Mapping[str, str]) -> tuple[str, ...]
|
||||
|
||||
|
||||
def agreed_excludes(a: Mapping[str, str], b: Mapping[str, str]) -> tuple[str, ...]:
|
||||
"""Sorted ids both passes labeled exclude."""
|
||||
"""Sorted ids both passes labeled exclude.
|
||||
|
||||
Both passes must name the same ids. An id in only one pass raises
|
||||
``KeyError``, the same rule as :func:`disagreements`.
|
||||
"""
|
||||
if set(a) != set(b):
|
||||
raise KeyError(min(set(a) ^ set(b)))
|
||||
return tuple(
|
||||
sorted(
|
||||
item_id
|
||||
@@ -32,6 +38,15 @@ def advances(decision: str) -> bool:
|
||||
def audit_sample(
|
||||
ids: Sequence[str], *, rate: float = 0.10, seed: int
|
||||
) -> tuple[str, ...]:
|
||||
"""Sort the ids, then draw ``int(len * rate)`` of them with ``seed``."""
|
||||
"""Sort the ids, then draw ``int(len * rate)`` of them with ``seed``.
|
||||
|
||||
A positive rate on a nonempty list draws at least one id, so a list
|
||||
shorter than ten still gets a 10 percent audit. Rate 0 draws nothing.
|
||||
"""
|
||||
ordered = sorted(ids)
|
||||
return tuple(random.Random(seed).sample(ordered, int(len(ordered) * rate)))
|
||||
count = int(len(ordered) * rate)
|
||||
if ordered and rate > 0 and count == 0:
|
||||
count = 1
|
||||
if count == 0:
|
||||
return ()
|
||||
return tuple(random.Random(seed).sample(ordered, count))
|
||||
|
||||
@@ -13,6 +13,7 @@ from dataclasses import dataclass
|
||||
from difflib import SequenceMatcher
|
||||
|
||||
from zot.db import TYPE_MAP, Db
|
||||
from zot.fetch.select import normalise_doi
|
||||
|
||||
_YEAR = re.compile(r"(\d{4})")
|
||||
_SIMILAR = 0.85
|
||||
@@ -46,7 +47,7 @@ def normalize(title: str) -> str:
|
||||
|
||||
|
||||
def _doi_key(doi: str) -> str:
|
||||
return doi.strip().casefold().rstrip(".")
|
||||
return normalise_doi(doi).casefold().rstrip(".")
|
||||
|
||||
|
||||
def _title_key(rec: Record) -> tuple[str, int | None, str] | None:
|
||||
@@ -108,7 +109,7 @@ def cluster(records: Sequence[Record]) -> DedupResult:
|
||||
if not left_title:
|
||||
continue
|
||||
for right in singles[i + 1 :]:
|
||||
if left.year != right.year:
|
||||
if left.year is None or right.year is None or left.year != right.year:
|
||||
continue
|
||||
right_title = normalize(right.title)
|
||||
if not right_title:
|
||||
|
||||
@@ -9,6 +9,7 @@ from prisma.search.base import (
|
||||
SearchResult,
|
||||
bare_doi,
|
||||
finish,
|
||||
pmid_of,
|
||||
surname,
|
||||
year_of,
|
||||
)
|
||||
@@ -44,7 +45,9 @@ def parse_arxiv(payload: str, *, query: str, searched_on: str) -> SearchResult:
|
||||
title=_text(_child(entry, "title")),
|
||||
year=year_of(_text(_child(entry, "published"))),
|
||||
doi=bare_doi(doi),
|
||||
pmid="",
|
||||
pmid=pmid_of(
|
||||
_text(_child(entry, "pmid", _ARXIV)) or _text(_child(entry, "pmid"))
|
||||
),
|
||||
first_author=surname(name),
|
||||
database="arxiv",
|
||||
)
|
||||
|
||||
@@ -3,10 +3,15 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import hashlib
|
||||
import re
|
||||
from dataclasses import dataclass
|
||||
|
||||
from lead.ledger.store import append
|
||||
from zot.db import FIELD_MAP, TYPE_MAP, Db
|
||||
from zot.fetch.select import normalise_doi
|
||||
|
||||
_PMID_URL = re.compile(r"pubmed\.ncbi\.nlm\.nih\.gov/(\d+)", re.IGNORECASE)
|
||||
_PMID_PREFIX = re.compile(r"^pmid:\s*", re.IGNORECASE)
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
@@ -73,13 +78,29 @@ def surname(name: str) -> str:
|
||||
|
||||
|
||||
def bare_doi(value: str) -> str:
|
||||
"""Drop a ``doi.org`` or ``doi:`` prefix."""
|
||||
text = value.strip()
|
||||
lowered = text.casefold()
|
||||
for prefix in ("https://doi.org/", "http://doi.org/", "doi:"):
|
||||
if lowered.startswith(prefix):
|
||||
return text[len(prefix) :]
|
||||
return text
|
||||
"""Drop a ``doi.org``, ``dx.doi.org``, or ``doi:`` prefix.
|
||||
|
||||
A trailing period stays. Dedup strips that period itself.
|
||||
"""
|
||||
return normalise_doi(value)
|
||||
|
||||
|
||||
def pmid_of(value: object) -> str:
|
||||
"""Digits of a PMID, or empty when the field is not one.
|
||||
|
||||
A ``pmid:`` prefix and a PubMed URL are stripped. Any other text,
|
||||
including a DOI, is empty.
|
||||
"""
|
||||
if value is None:
|
||||
return ""
|
||||
text = str(value).strip()
|
||||
if not text:
|
||||
return ""
|
||||
url = _PMID_URL.search(text)
|
||||
if url:
|
||||
return url.group(1)
|
||||
text = _PMID_PREFIX.sub("", text).strip()
|
||||
return text if text.isdigit() else ""
|
||||
|
||||
|
||||
def year_of(value: object) -> int | None:
|
||||
@@ -165,16 +186,20 @@ def import_hits(zdb: Db, project: str, result: SearchResult) -> int:
|
||||
|
||||
|
||||
def _doi_item_id(zdb: Db, doi: str) -> int | None:
|
||||
row = zdb.con.execute(
|
||||
"""Match a DOI already stored as a URL, a ``doi:`` prefix, or bare text."""
|
||||
wanted = normalise_doi(doi).casefold().rstrip(".")
|
||||
if not wanted:
|
||||
return None
|
||||
rows = zdb.con.execute(
|
||||
"""
|
||||
SELECT id.itemID
|
||||
SELECT id.itemID, idv.value
|
||||
FROM itemData id
|
||||
JOIN itemDataValues idv ON id.valueID = idv.valueID
|
||||
WHERE id.fieldID = ? AND lower(idv.value) = lower(?)
|
||||
LIMIT 1
|
||||
WHERE id.fieldID = ?
|
||||
""",
|
||||
(FIELD_MAP["DOI"], doi.strip()),
|
||||
).fetchone()
|
||||
if row is None:
|
||||
return None
|
||||
return int(row[0])
|
||||
(FIELD_MAP["DOI"],),
|
||||
).fetchall()
|
||||
for item_id, value in rows:
|
||||
if normalise_doi(str(value)).casefold().rstrip(".") == wanted:
|
||||
return int(item_id)
|
||||
return None
|
||||
|
||||
@@ -4,7 +4,14 @@ from __future__ import annotations
|
||||
|
||||
import json
|
||||
|
||||
from prisma.search.base import SearchHit, SearchResult, bare_doi, finish, year_of
|
||||
from prisma.search.base import (
|
||||
SearchHit,
|
||||
SearchResult,
|
||||
bare_doi,
|
||||
finish,
|
||||
pmid_of,
|
||||
year_of,
|
||||
)
|
||||
|
||||
|
||||
def _title(row: dict) -> str:
|
||||
@@ -35,7 +42,7 @@ def parse_crossref(payload: str, *, query: str, searched_on: str) -> SearchResul
|
||||
title=_title(row),
|
||||
year=_year(row),
|
||||
doi=bare_doi(row.get("DOI") or ""),
|
||||
pmid="",
|
||||
pmid=pmid_of(row["pmid"] if "pmid" in row else row.get("PMID")),
|
||||
first_author=family,
|
||||
database="crossref",
|
||||
)
|
||||
|
||||
@@ -9,6 +9,7 @@ from prisma.search.base import (
|
||||
SearchResult,
|
||||
bare_doi,
|
||||
finish,
|
||||
pmid_of,
|
||||
surname,
|
||||
year_of,
|
||||
)
|
||||
@@ -23,12 +24,13 @@ def parse_openalex(payload: str, *, query: str, searched_on: str) -> SearchResul
|
||||
name = ""
|
||||
if authorships:
|
||||
name = ((authorships[0].get("author") or {}).get("display_name")) or ""
|
||||
ids = row.get("ids") if isinstance(row.get("ids"), dict) else {}
|
||||
hits.append(
|
||||
SearchHit(
|
||||
title=row.get("title") or "",
|
||||
year=year_of(row.get("publication_year")),
|
||||
doi=bare_doi(row.get("doi") or ""),
|
||||
pmid="",
|
||||
pmid=pmid_of(ids.get("pmid")),
|
||||
first_author=surname(name),
|
||||
database="openalex",
|
||||
)
|
||||
|
||||
@@ -29,7 +29,23 @@ def _doi(article: ET.Element) -> str:
|
||||
|
||||
|
||||
def parse_pubmed_xml(xml: str, *, query: str, searched_on: str) -> SearchResult:
|
||||
"""Read one PubmedArticleSet. Missing fields become empty or None."""
|
||||
"""Read one PubmedArticleSet. Missing fields become empty or None.
|
||||
|
||||
A blank payload has no hits. The log still records that payload's sha256.
|
||||
"""
|
||||
if not xml.strip():
|
||||
return SearchResult(
|
||||
hits=(),
|
||||
log=SearchLog(
|
||||
database="pubmed",
|
||||
interface="eutils",
|
||||
searched_on=searched_on,
|
||||
query=query,
|
||||
filters="",
|
||||
hit_count=0,
|
||||
export_sha256=hashlib.sha256(xml.encode()).hexdigest(),
|
||||
),
|
||||
)
|
||||
root = ET.fromstring(xml)
|
||||
hits: list[SearchHit] = []
|
||||
for article in root.iter("PubmedArticle"):
|
||||
|
||||
@@ -9,6 +9,7 @@ from prisma.search.base import (
|
||||
SearchResult,
|
||||
bare_doi,
|
||||
finish,
|
||||
pmid_of,
|
||||
surname,
|
||||
year_of,
|
||||
)
|
||||
@@ -23,13 +24,19 @@ def parse_semanticscholar(
|
||||
for row in rows:
|
||||
authors = row.get("authors") or []
|
||||
name = (authors[0].get("name") or "") if authors else ""
|
||||
doi = ((row.get("externalIds") or {}).get("DOI")) or ""
|
||||
external = row.get("externalIds") or {}
|
||||
doi = (external.get("DOI") if isinstance(external, dict) else "") or ""
|
||||
raw_pmid = None
|
||||
if isinstance(external, dict):
|
||||
raw_pmid = external.get("PubMed")
|
||||
if raw_pmid in (None, ""):
|
||||
raw_pmid = external.get("PMID")
|
||||
hits.append(
|
||||
SearchHit(
|
||||
title=row.get("title") or "",
|
||||
year=year_of(row.get("year")),
|
||||
doi=bare_doi(doi),
|
||||
pmid="",
|
||||
pmid=pmid_of(raw_pmid),
|
||||
first_author=surname(name),
|
||||
database="semanticscholar",
|
||||
)
|
||||
|
||||
@@ -16,6 +16,12 @@ def test_fred_dot_value_is_missing():
|
||||
assert rows[0].period == "2024-01-01"
|
||||
|
||||
|
||||
def test_fred_missing_date_has_no_year():
|
||||
rows = parse_observations({"observations": [{"date": "", "value": "1"}]})
|
||||
assert rows[0].year is None
|
||||
assert rows[0].value == 1.0
|
||||
|
||||
|
||||
def test_county_income_keeps_the_fips_text():
|
||||
rows = parse_county_income("fips,year,agi\n01001,2022,40000\n")
|
||||
assert rows == (CountyIncome(fips="01001", year=2022, agi=40000),)
|
||||
|
||||
@@ -219,3 +219,10 @@ def test_status_command_prints_every_target(tmp_path):
|
||||
result = runner.invoke(app, ["lead", "ledger", "status", "--db", str(path)])
|
||||
assert result.exit_code == 0
|
||||
assert "Q.ACR" in result.stdout
|
||||
|
||||
|
||||
def test_status_command_prints_gaps_runs_contradictions_and_tiers(tmp_path):
|
||||
path = tmp_path / "ledger.duckdb"
|
||||
result = runner.invoke(app, ["lead", "ledger", "status", "--db", str(path)])
|
||||
assert result.exit_code == 0
|
||||
assert "Q.ACR\t1\t\t0\t0\t0\t0\t0" in result.stdout
|
||||
|
||||
@@ -38,6 +38,18 @@ def test_agreed_excludes_are_ids_both_passes_exclude():
|
||||
assert agreed_excludes(a, b) == ("i2",)
|
||||
|
||||
|
||||
def test_agreed_excludes_require_the_same_ids():
|
||||
with pytest.raises(KeyError):
|
||||
agreed_excludes({"i1": "exclude"}, {"i1": "exclude", "i2": "exclude"})
|
||||
|
||||
|
||||
def test_audit_sample_draws_one_when_ten_percent_floors_to_zero():
|
||||
ids = [f"i{n}" for n in range(9)]
|
||||
drawn = audit_sample(ids, rate=0.10, seed=1)
|
||||
assert len(drawn) == 1
|
||||
assert drawn[0] in ids
|
||||
|
||||
|
||||
def test_uncertain_and_include_advance_exclude_does_not():
|
||||
assert advances("uncertain") is True
|
||||
assert advances("include") is True
|
||||
|
||||
@@ -79,6 +79,49 @@ def test_near_titles_stay_borderline_and_unmerged():
|
||||
assert result.borderline == ((first, second),)
|
||||
|
||||
|
||||
def test_doi_url_and_bare_doi_are_one_group():
|
||||
first = _rec(key="AAAAAAAA", doi="https://dx.doi.org/10.1000/ABC", title="One")
|
||||
second = _rec(key="BBBBBBBB", doi="10.1000/abc", title="Two")
|
||||
result = cluster([first, second])
|
||||
assert len(result.groups) == 1
|
||||
assert {rec.key for rec in result.groups[0]} == {"AAAAAAAA", "BBBBBBBB"}
|
||||
|
||||
|
||||
def test_undated_near_titles_are_not_borderline():
|
||||
first = _rec(
|
||||
key="AAAAAAAA",
|
||||
title="High needs frailty index",
|
||||
year=None,
|
||||
first_author="Kim",
|
||||
)
|
||||
second = _rec(
|
||||
key="BBBBBBBB",
|
||||
title="High-need frailty index",
|
||||
year=None,
|
||||
first_author="Lee",
|
||||
)
|
||||
result = cluster([first, second])
|
||||
assert len(result.groups) == 2
|
||||
assert result.borderline == ()
|
||||
|
||||
|
||||
def test_identical_undated_titles_with_the_same_author_merge():
|
||||
first = _rec(
|
||||
key="AAAAAAAA",
|
||||
title="High needs frailty index",
|
||||
year=None,
|
||||
first_author="Kim",
|
||||
)
|
||||
second = _rec(
|
||||
key="BBBBBBBB",
|
||||
title="High needs frailty index",
|
||||
year=None,
|
||||
first_author="Kim",
|
||||
)
|
||||
result = cluster([first, second])
|
||||
assert len(result.groups) == 1
|
||||
|
||||
|
||||
def test_dissimilar_titles_are_neither_merged_nor_borderline():
|
||||
first = _rec(key="AAAAAAAA", title="zzzz unique alpha", first_author="Kim")
|
||||
second = _rec(key="BBBBBBBB", title="qqqq other beta", first_author="Lee")
|
||||
|
||||
@@ -5,6 +5,7 @@ from __future__ import annotations
|
||||
import pytest
|
||||
|
||||
from prisma.search.arxiv import parse_arxiv
|
||||
from prisma.search.base import bare_doi
|
||||
from prisma.search.crossref import parse_crossref
|
||||
from prisma.search.europepmc import parse_europepmc
|
||||
from prisma.search.openalex import parse_openalex
|
||||
@@ -68,6 +69,60 @@ _SPARSE = [
|
||||
]
|
||||
|
||||
|
||||
def test_bare_doi_strips_a_dx_doi_org_prefix_and_keeps_a_trailing_period():
|
||||
assert bare_doi("https://dx.doi.org/10.1/ab") == "10.1/ab"
|
||||
assert bare_doi("https://dx.doi.org/10.1/ab.") == "10.1/ab."
|
||||
|
||||
|
||||
def test_openalex_reads_a_pubmed_url_pmid():
|
||||
payload = (
|
||||
'{"results":[{"title":"Report title","publication_year":2020,'
|
||||
'"doi":"https://doi.org/10.1/o","ids":{"pmid":'
|
||||
'"https://pubmed.ncbi.nlm.nih.gov/42"},'
|
||||
'"authorships":[{"author":{"display_name":"Ada Kim"}}]}]}'
|
||||
)
|
||||
hit = parse_openalex(payload, query="frailty", searched_on="2026-10-31").hits[0]
|
||||
assert hit.pmid == "42"
|
||||
|
||||
|
||||
def test_semanticscholar_reads_external_pubmed_id():
|
||||
payload = (
|
||||
'{"data":[{"title":"Report title","year":2020,'
|
||||
'"externalIds":{"DOI":"10.1/s","PubMed":"999"},'
|
||||
'"authors":[{"name":"Ada Kim"}]}]}'
|
||||
)
|
||||
hit = parse_semanticscholar(
|
||||
payload, query="frailty", searched_on="2026-10-31"
|
||||
).hits[0]
|
||||
assert hit.pmid == "999"
|
||||
|
||||
|
||||
def test_crossref_reads_a_pmid_field():
|
||||
payload = (
|
||||
'{"message":{"items":[{"title":["Report title"],"DOI":"10.1/c",'
|
||||
'"pmid":"12345","issued":{"date-parts":[[2020,1,2]]},'
|
||||
'"author":[{"family":"Kim","given":"Ada"}]}]}}'
|
||||
)
|
||||
hit = parse_crossref(payload, query="frailty", searched_on="2026-10-31").hits[0]
|
||||
assert hit.pmid == "12345"
|
||||
|
||||
|
||||
def test_arxiv_reads_a_pmid_element():
|
||||
payload = """\
|
||||
<feed xmlns="http://www.w3.org/2005/Atom" xmlns:arxiv="http://arxiv.org/schemas/atom">
|
||||
<entry>
|
||||
<title>Report title</title>
|
||||
<published>2020-01-02T00:00:00Z</published>
|
||||
<author><name>Ada Kim</name></author>
|
||||
<arxiv:doi>10.1/a</arxiv:doi>
|
||||
<arxiv:pmid>77</arxiv:pmid>
|
||||
</entry>
|
||||
</feed>
|
||||
"""
|
||||
hit = parse_arxiv(payload, query="frailty", searched_on="2026-10-31").hits[0]
|
||||
assert hit.pmid == "77"
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
("parser", "payload", "database", "doi", "year", "author"), _CASES
|
||||
)
|
||||
|
||||
@@ -109,6 +109,54 @@ def test_record_with_project_clears_due_and_keeps_projects_apart(tmp_path):
|
||||
con.close()
|
||||
|
||||
|
||||
def test_blank_pubmed_xml_has_no_hits():
|
||||
payload = " \n"
|
||||
result = parse_pubmed_xml(payload, query="frailty", searched_on="2026-10-31")
|
||||
assert result.hits == ()
|
||||
assert result.log.hit_count == 0
|
||||
assert result.log.database == "pubmed"
|
||||
assert result.log.interface == "eutils"
|
||||
assert result.log.export_sha256 == hashlib.sha256(payload.encode()).hexdigest()
|
||||
|
||||
|
||||
def test_import_hits_matches_a_doi_stored_as_a_dx_url(tmp_path):
|
||||
path = str(tmp_path / "z.sqlite")
|
||||
con = create_db(path)
|
||||
con.close()
|
||||
hit = SearchHit(
|
||||
title="Alpha frailty",
|
||||
year=2020,
|
||||
doi="10.1/alpha",
|
||||
pmid="111",
|
||||
first_author="Kim",
|
||||
database="openalex",
|
||||
)
|
||||
result = SearchResult(
|
||||
hits=(hit,),
|
||||
log=SearchLog(
|
||||
database="openalex",
|
||||
interface="openalex",
|
||||
searched_on="2026-10-31",
|
||||
query="frailty",
|
||||
filters="",
|
||||
hit_count=1,
|
||||
export_sha256="abc",
|
||||
),
|
||||
)
|
||||
with Db(path) as db:
|
||||
item_id = db.create_item(TYPE_MAP["journalArticle"])
|
||||
db.set_fields(
|
||||
item_id,
|
||||
{"title": "Alpha frailty", "DOI": "https://dx.doi.org/10.1/alpha"},
|
||||
)
|
||||
assert import_hits(db, "lead-limits", result) == 0
|
||||
articles = db.con.execute(
|
||||
"select count(*) from items where itemTypeID = ?",
|
||||
(TYPE_MAP["journalArticle"],),
|
||||
).fetchone()[0]
|
||||
assert articles == 1
|
||||
|
||||
|
||||
def test_import_hits_is_idempotent_on_doi(tmp_path):
|
||||
path = str(tmp_path / "z.sqlite")
|
||||
con = create_db(path)
|
||||
|
||||
Reference in New Issue
Block a user