diff --git a/src/cli/prisma.py b/src/cli/prisma.py index aad8385..84ea3f7 100644 --- a/src/cli/prisma.py +++ b/src/cli/prisma.py @@ -412,15 +412,19 @@ def dedup_cmd( hold: bool = typer.Option(True, "--hold/--no-hold"), ) -> None: """Tag DOI, PMID, and title duplicates. Near-matches stay untagged.""" - from prisma.dedup import mark_duplicates + from prisma.dedup import cluster, load_records, mark_duplicates from zot.db import Db - def _go() -> int: + def _go(): with Db(str(db)) as zdb: - return mark_duplicates(zdb) + tagged = mark_duplicates(zdb) + borderline = cluster(load_records(zdb)).borderline + return tagged, borderline - tagged = _hold(_go, hold=hold) + tagged, borderline = _hold(_go, hold=hold) typer.echo(f" tagged: {tagged}") + for left, right in borderline: + typer.echo(f" borderline: {left.key} {left.title} | {right.key} {right.title}") search_app = typer.Typer(no_args_is_help=True) diff --git a/src/lead/ledger/claims.py b/src/lead/ledger/claims.py index d5df5e3..1ff6d1a 100644 --- a/src/lead/ledger/claims.py +++ b/src/lead/ledger/claims.py @@ -9,6 +9,7 @@ recording the same extraction again inserts nothing. from __future__ import annotations import hashlib +import re from collections.abc import Mapping, Sequence from typing import TYPE_CHECKING @@ -37,6 +38,7 @@ _DOWNGRADE_LABELS = { "risk_of_bias": "risk of bias", "publication_bias": "publication bias", } +_INTERVAL = re.compile(r"\s*(?:,|to)\s*", re.IGNORECASE) def grade(design: str, downgrades: Sequence[str]) -> str: @@ -56,6 +58,26 @@ def _target_id(project: str, extraction: Mapping[str, str]) -> str: return extraction.get("target_id") or extraction.get("outcome_target_id") or "" +def _number(value: str) -> float | None: + text = value.strip() + if not text: + return None + try: + return float(text) + except ValueError: + return None + + +def _interval(value: str) -> tuple[float | None, float | None]: + text = value.strip() + if not text: + return None, None + parts = _INTERVAL.split(text, maxsplit=1) + if len(parts) != 2: + return None, None + return _number(parts[0]), _number(parts[1]) + + def _downgrades(extraction: Mapping[str, str]) -> tuple[str, ...]: labels: list[str] = [] for field in _DOWNGRADE_FIELDS: @@ -110,11 +132,26 @@ def claims_from_extraction( ) if part ) + measured = _number(extraction.get("effect_value", "")) + if measured is not None: + claim["effect_value"] = measured + low, high = _interval(extraction.get("effect_ci", "")) + if low is not None: + claim["effect_ci_low"] = low + if high is not None: + claim["effect_ci_high"] = high + if "subject" not in claim: + subject = ( + extraction.get("factor_definition", "").strip() + or extraction.get("statement", "").strip() + ) + if subject: + claim["subject"] = subject return (claim,) def precursor_catalog(con: duckdb.DuckDBPyConnection) -> list[Mapping[str, object]]: - """One row per target: precursor lead time, grain, certainty, and any limit.""" + """One row per precursor claim, plus that target's first limit claim.""" rows = con.execute( """ SELECT id, kind, target_id, lead_time, grain, certainty @@ -122,27 +159,21 @@ def precursor_catalog(con: duckdb.DuckDBPyConnection) -> list[Mapping[str, objec ORDER BY target_id, id """ ).fetchall() - grouped: dict[str, dict[str, object]] = {} + limits: dict[str, str] = {} + precursors: list[dict[str, object]] = [] for claim_id, kind, target_id, lead_time, grain, certainty in rows: - entry = grouped.setdefault( - target_id, - { - "target_id": target_id, - "lead_time": "", - "grain": "", - "certainty": "", - "limit_claim_id": None, - "_precursor": False, - }, - ) - if kind == "precursor" and not entry["_precursor"]: - entry["lead_time"] = lead_time or "" - entry["grain"] = grain or "" - entry["certainty"] = certainty or "" - entry["_precursor"] = True - if kind == "limit" and entry["limit_claim_id"] is None: - entry["limit_claim_id"] = claim_id + if kind == "limit" and target_id not in limits: + limits[target_id] = claim_id + elif kind == "precursor": + precursors.append( + { + "target_id": target_id, + "lead_time": lead_time or "", + "grain": grain or "", + "certainty": certainty or "", + } + ) return [ - {key: value for key, value in entry.items() if key != "_precursor"} - for entry in grouped.values() + {**entry, "limit_claim_id": limits.get(str(entry["target_id"]))} + for entry in precursors ] diff --git a/src/lead/ledger/export.py b/src/lead/ledger/export.py index 0a40d09..86aa7fc 100644 --- a/src/lead/ledger/export.py +++ b/src/lead/ledger/export.py @@ -1,17 +1,22 @@ """Export one Zotero project's review rows into the evidence ledger. -Anchors tagged ``module:prisma`` are not records. Claims are not written -here. A second export of the same item key and extraction version inserts -nothing, because that pair is in the content hash. +Anchors tagged ``module:prisma`` are not records. An included extraction +also appends one claim from the note fields. A second export of the same +item key and extraction version inserts nothing, because that pair is in +the content hash. """ from __future__ import annotations import hashlib +import html +import json import re from typing import TYPE_CHECKING +from lead.ledger.claims import claims_from_extraction from lead.ledger.store import append +from lead.targets import by_id if TYPE_CHECKING: import duckdb @@ -19,7 +24,9 @@ if TYPE_CHECKING: from zot.db import Db _DECISIONS = frozenset({"include", "exclude", "uncertain"}) -_TARGET = re.compile(r"target_id:\s*(\S+)") +_PRE = re.compile(r"
(.*?)", re.DOTALL) +_TAG = re.compile(r"<[^>]+>") +_FIELD = re.compile(r"(? str: @@ -54,6 +61,32 @@ def _note_body(zdb: Db, item_id: int) -> str: return "\n".join(row[0] or "" for row in rows) +def _fields_from_note(body: str) -> dict[str, str]: + """JSON inside ``
`` wins. A plain line must not capture a tag."""
+ match = _PRE.search(body)
+ if match:
+ try:
+ payload = json.loads(html.unescape(match.group(1)).strip())
+ except json.JSONDecodeError:
+ payload = None
+ if isinstance(payload, dict):
+ return {
+ str(key): "" if value is None else str(value)
+ for key, value in payload.items()
+ }
+ text = _TAG.sub(" ", html.unescape(body))
+ found: dict[str, str] = {}
+ for key, value in _FIELD.findall(text):
+ if value.startswith(("<", "&")):
+ continue
+ found.setdefault(key, value)
+ return found
+
+
+def _target(fields: dict[str, str]) -> str:
+ return (fields.get("outcome_target_id") or fields.get("target_id") or "").strip()
+
+
def export_project(
zdb: Db,
con: duckdb.DuckDBPyConnection,
@@ -62,10 +95,20 @@ def export_project(
extraction_version: str,
actor: str,
) -> dict[str, int]:
- """Insert source, decision, and extraction rows. Returns how many landed."""
+ """Insert source, decision, and extraction rows.
+
+ A note that names a known target also appends one claim. The returned
+ counts are the three review tables.
+ """
inserted = {"source": 0, "decision": 0, "extraction": 0}
for item_id, key in _project_items(zdb, project):
tags = zdb.get_tags(item_id)
+ included = "stage:4-included" in tags
+ body = _note_body(zdb, item_id) if included else ""
+ fields = _fields_from_note(body) if included else {}
+ target = _target(fields)
+ if target:
+ by_id(target)
databases = sorted(
tag.removeprefix("found-in:") for tag in tags if tag.startswith("found-in:")
)
@@ -118,9 +161,8 @@ def export_project(
if append(con, "decision", row):
inserted["decision"] += 1
- if "stage:4-included" not in tags:
+ if not included:
continue
- body = _note_body(zdb, item_id)
extraction: dict[str, object] = {
"project": project,
"zotero_key": key,
@@ -129,9 +171,16 @@ def export_project(
"actor": actor,
"content_hash": _hash("extraction", key, extraction_version, project),
}
- found = _TARGET.search(body)
- if found:
- extraction["target_id"] = found.group(1)
+ if target:
+ extraction["target_id"] = target
if append(con, "extraction", extraction):
inserted["extraction"] += 1
+ if target:
+ claim_fields = dict(fields)
+ claim_fields["zotero_key"] = key
+ claim_fields["extraction_version"] = extraction_version
+ claim = claims_from_extraction(claim_fields, project=project, actor=actor)[
+ 0
+ ]
+ append(con, "claim", dict(claim))
return inserted
diff --git a/src/prisma/search/base.py b/src/prisma/search/base.py
index c57d609..f5db393 100644
--- a/src/prisma/search/base.py
+++ b/src/prisma/search/base.py
@@ -101,44 +101,55 @@ def seed_recall(retrieved: set[str], seeds: set[str]) -> float:
return len(retrieved & seeds) / len(seeds)
-def record(con, result: SearchResult, *, actor: str) -> bool:
- """Append one search row. The same export on a later day is a new row."""
+def record(con, result: SearchResult, *, actor: str, project: str = "") -> bool:
+ """Append one search row. The same export on a later day is a new row.
+
+ A nonempty ``project`` is stored and hashed, so two projects on the
+ same day stay two rows and a search logged today clears ``due``.
+ """
log = result.log
- raw = "\n".join(
- [
- log.database,
- log.interface,
- log.searched_on,
- log.query,
- log.filters,
- str(log.hit_count),
- log.export_sha256,
- actor,
- ]
- )
- return append(
- con,
- "search",
- {
- "database": log.database,
- "interface": log.interface,
- "searched_on": log.searched_on,
- "query": log.query,
- "filters": log.filters,
- "hit_count": log.hit_count,
- "export_sha256": log.export_sha256,
- "content_hash": hashlib.sha256(raw.encode()).hexdigest(),
- "actor": actor,
- },
- )
+ parts = [
+ log.database,
+ log.interface,
+ log.searched_on,
+ log.query,
+ log.filters,
+ str(log.hit_count),
+ log.export_sha256,
+ actor,
+ ]
+ if project:
+ parts.append(project)
+ row: dict[str, object] = {
+ "database": log.database,
+ "interface": log.interface,
+ "searched_on": log.searched_on,
+ "query": log.query,
+ "filters": log.filters,
+ "hit_count": log.hit_count,
+ "export_sha256": log.export_sha256,
+ "content_hash": hashlib.sha256("\n".join(parts).encode()).hexdigest(),
+ "actor": actor,
+ }
+ if project:
+ row["project"] = project
+ return append(con, "search", row)
def import_hits(zdb: Db, project: str, result: SearchResult) -> int:
- """Create one Zotero item per new DOI. Return how many were new."""
+ """Create one Zotero item per new DOI. Return how many were new.
+
+ A DOI already in the library is not inserted again. The existing item
+ gains this project's tag and this database's ``found-in`` tag.
+ """
inserted = 0
for hit in result.hits:
- if hit.doi and _doi_exists(zdb, hit.doi):
- continue
+ if hit.doi:
+ existing = _doi_item_id(zdb, hit.doi)
+ if existing is not None:
+ zdb.tag_item(existing, f"project:{project}")
+ zdb.tag_item(existing, f"found-in:{hit.database}")
+ continue
item_id = zdb.create_item(TYPE_MAP["journalArticle"])
fields = {"title": hit.title, "DOI": hit.doi, "PMID": hit.pmid}
if hit.year is not None:
@@ -153,10 +164,10 @@ def import_hits(zdb: Db, project: str, result: SearchResult) -> int:
return inserted
-def _doi_exists(zdb: Db, doi: str) -> bool:
+def _doi_item_id(zdb: Db, doi: str) -> int | None:
row = zdb.con.execute(
"""
- SELECT 1
+ SELECT id.itemID
FROM itemData id
JOIN itemDataValues idv ON id.valueID = idv.valueID
WHERE id.fieldID = ? AND lower(idv.value) = lower(?)
@@ -164,4 +175,6 @@ def _doi_exists(zdb: Db, doi: str) -> bool:
""",
(FIELD_MAP["DOI"], doi.strip()),
).fetchone()
- return row is not None
+ if row is None:
+ return None
+ return int(row[0])
diff --git a/src/prisma/search/due.py b/src/prisma/search/due.py
index 6ae4b31..800bd74 100644
--- a/src/prisma/search/due.py
+++ b/src/prisma/search/due.py
@@ -1,10 +1,12 @@
"""Whether a project's searches are due. This does not run a search.
-Dates are ``YYYY-MM-DD`` strings, compared as text. Nightly means the
-latest ``searched_on`` for the project is missing or earlier than today.
-The other reasons are a contradiction of moderate or high certainty, a
-strand-5 event on a target this project has a claim about, and a CMS
-source dated after that latest search.
+Dates are compared by the ``YYYY-MM-DD`` prefix, so an ISO timestamp and a
+date on the same day are the same day. Nightly means the latest
+``searched_on`` for the project is missing or earlier than today.
+Contradiction and exogenous fire only when their day is after that latest
+search. A project with no search row reports nightly only. CMS matches
+when ``cms`` is one comma-separated database token and the source day is
+after that latest search.
"""
from __future__ import annotations
@@ -29,26 +31,32 @@ def _latest(con: duckdb.DuckDBPyConnection, project: str) -> str | None:
return str(row[0])
-def _contradiction(con: duckdb.DuckDBPyConnection, project: str) -> bool:
- row = con.execute(
+def _day(value: object) -> str:
+ if value is None:
+ return ""
+ return str(value)[:10]
+
+
+def _contradiction(con: duckdb.DuckDBPyConnection, project: str, latest: str) -> bool:
+ rows = con.execute(
"""
- SELECT 1
+ SELECT f.created_at
FROM lead_evidence.finding AS f
JOIN lead_evidence.claim AS c ON c.id = f.claim_id
WHERE c.project = ?
AND f.relation = 'contradicts'
AND c.certainty IN ('moderate', 'high')
- LIMIT 1
""",
[project],
- ).fetchone()
- return row is not None
+ ).fetchall()
+ latest_day = _day(latest)
+ return any(_day(created_at) > latest_day for (created_at,) in rows)
-def _exogenous(con: duckdb.DuckDBPyConnection, project: str) -> bool:
- row = con.execute(
+def _exogenous(con: duckdb.DuckDBPyConnection, project: str, latest: str) -> bool:
+ rows = con.execute(
"""
- SELECT 1
+ SELECT e.event_on
FROM lead_evidence.exogenous AS e
WHERE EXISTS (
SELECT 1
@@ -56,37 +64,41 @@ def _exogenous(con: duckdb.DuckDBPyConnection, project: str) -> bool:
WHERE c.project = ?
AND c.target_id = e.target_id
)
- LIMIT 1
""",
[project],
- ).fetchone()
- return row is not None
+ ).fetchall()
+ latest_day = _day(latest)
+ return any(_day(event_on) > latest_day for (event_on,) in rows)
def _cms(con: duckdb.DuckDBPyConnection, project: str, latest: str) -> bool:
- row = con.execute(
+ rows = con.execute(
"""
- SELECT 1
+ SELECT database, created_at
FROM lead_evidence.source
WHERE project = ?
- AND database = 'cms'
- AND created_at > ?
- LIMIT 1
""",
- [project, latest],
- ).fetchone()
- return row is not None
+ [project],
+ ).fetchall()
+ latest_day = _day(latest)
+ for database, created_at in rows:
+ tokens = [
+ part.strip() for part in str(database or "").split(",") if part.strip()
+ ]
+ if "cms" in tokens and _day(created_at) > latest_day:
+ return True
+ return False
def due(con: duckdb.DuckDBPyConnection, *, project: str, now: str) -> tuple[str, ...]:
"""Reasons a search should run, in a fixed order."""
reasons: list[str] = []
latest = _latest(con, project)
- if latest is None or latest < now:
+ if latest is None or _day(latest) < _day(now):
reasons.append("nightly")
- if _contradiction(con, project):
+ if latest is not None and _contradiction(con, project, latest):
reasons.append("contradiction")
- if _exogenous(con, project):
+ if latest is not None and _exogenous(con, project, latest):
reasons.append("exogenous")
if latest is not None and _cms(con, project, latest):
reasons.append("cms")
diff --git a/tests/lead/test_ledger_claims.py b/tests/lead/test_ledger_claims.py
index aecbb42..b1a4b75 100644
--- a/tests/lead/test_ledger_claims.py
+++ b/tests/lead/test_ledger_claims.py
@@ -100,6 +100,82 @@ def test_same_extraction_inserts_one_claim_and_the_catalog_reads_it(tmp_path):
con.close()
+def test_claim_keeps_effect_value_interval_and_subject():
+ claim = claims_from_extraction(
+ {
+ "target_id": "Q.ACR",
+ "effect_measure": "OR",
+ "effect_value": "1.2",
+ "effect_ci": "1.1, 1.4",
+ "factor_definition": "frailty status",
+ "design": "cohort",
+ },
+ project="lead-limits",
+ actor="tester",
+ )[0]
+ assert claim["effect_measure"] == "OR"
+ assert claim["effect_value"] == 1.2
+ assert claim["effect_ci_low"] == 1.1
+ assert claim["effect_ci_high"] == 1.4
+ assert claim["subject"] == "frailty status"
+
+ stated = claims_from_extraction(
+ {
+ "target_id": "Q.ACR",
+ "effect_ci": "1.1 to 1.4",
+ "statement": "care changes the status",
+ },
+ project="lead-limits",
+ actor="tester",
+ )[0]
+ assert stated["effect_ci_low"] == 1.1
+ assert stated["effect_ci_high"] == 1.4
+ assert stated["subject"] == "care changes the status"
+
+
+def test_catalog_lists_each_precursor_claim(tmp_path):
+ first = claims_from_extraction(
+ {
+ "zotero_key": "ABCD2345",
+ "extraction_version": "v1",
+ "outcome_target_id": "Q.ACR",
+ "grain": "beneficiary",
+ "lead_time": "12 months",
+ "design": "cohort",
+ },
+ project="lead-precursors",
+ actor="tester",
+ )[0]
+ second = claims_from_extraction(
+ {
+ "zotero_key": "IJKM2345",
+ "extraction_version": "v1",
+ "outcome_target_id": "Q.ACR",
+ "grain": "beneficiary",
+ "lead_time": "6 months",
+ "design": "cohort",
+ },
+ project="lead-precursors",
+ actor="tester",
+ )[0]
+ limit = claims_from_extraction(
+ {"target_id": "Q.ACR", "grain": "ACO", "zotero_key": "EFGH5678"},
+ project="lead-limits",
+ actor="tester",
+ )[0]
+ con = open_ledger(str(tmp_path / "ledger.duckdb"))
+ try:
+ assert append(con, "claim", first) is True
+ assert append(con, "claim", second) is True
+ assert append(con, "claim", limit) is True
+ rows = [item for item in precursor_catalog(con) if item["target_id"] == "Q.ACR"]
+ assert len(rows) == 2
+ assert {row["lead_time"] for row in rows} == {"12 months", "6 months"}
+ assert {row["limit_claim_id"] for row in rows} == {limit["content_hash"]}
+ finally:
+ con.close()
+
+
def test_unknown_target_raises_key_error():
with pytest.raises(KeyError):
claims_from_extraction(
diff --git a/tests/lead/test_ledger_export.py b/tests/lead/test_ledger_export.py
index 4f3647b..04be6bf 100644
--- a/tests/lead/test_ledger_export.py
+++ b/tests/lead/test_ledger_export.py
@@ -2,11 +2,13 @@
from __future__ import annotations
+import pytest
from typer.testing import CliRunner
from cli import app
from lead.ledger.export import export_project
from lead.ledger.store import open_ledger
+from prisma.ingest import apply_extraction
from zot.db import TYPE_MAP, Db
from zot.schema import create_db
@@ -97,3 +99,136 @@ def test_export_is_idempotent_until_the_extraction_version_changes(tmp_path):
def test_ledger_export_command_is_registered():
result = runner.invoke(app, ["lead", "ledger", "export", "--help"])
assert result.exit_code == 0
+
+
+def test_html_extraction_note_stores_the_target_and_a_claim(tmp_path):
+ zpath = str(tmp_path / "z.sqlite")
+ con = create_db(zpath)
+ con.close()
+ with Db(zpath) as zdb:
+ item_id = zdb.create_item(TYPE_MAP["journalArticle"], key="ABCD2345")
+ zdb.set_fields(item_id, {"title": "All-cause readmission"})
+ zdb.tag_item(item_id, "stage:4-included")
+ apply_extraction(
+ zdb,
+ item_id,
+ "lead-precursors",
+ {
+ "outcome_target_id": "Q.ACR",
+ "effect_measure": "OR",
+ "effect_value": "1.2",
+ "effect_ci": "1.1, 1.4",
+ "factor_definition": "frailty",
+ "design": "cohort",
+ },
+ )
+ zdb.commit()
+ ledger = open_ledger(str(tmp_path / "ledger.duckdb"))
+ try:
+ export_project(
+ zdb,
+ ledger,
+ "lead-precursors",
+ extraction_version="v1",
+ actor="tester",
+ )
+ target = ledger.execute(
+ "select target_id from lead_evidence.extraction"
+ ).fetchone()[0]
+ assert target == "Q.ACR"
+ row = ledger.execute(
+ """
+ select effect_value, effect_ci_low, effect_ci_high, subject
+ from lead_evidence.claim
+ """
+ ).fetchone()
+ assert row == (1.2, 1.1, 1.4, "frailty")
+ finally:
+ ledger.close()
+
+
+def test_html_target_label_is_not_stored_as_a_tag(tmp_path):
+ zpath = str(tmp_path / "z.sqlite")
+ con = create_db(zpath)
+ con.close()
+ with Db(zpath) as zdb:
+ item_id = zdb.create_item(TYPE_MAP["journalArticle"], key="ABCD2345")
+ zdb.tag_item(item_id, "project:lead-precursors")
+ zdb.tag_item(item_id, "stage:4-included")
+ zdb.add_note(item_id, "