RAG-HPO 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
rag_hpo/__init__.py ADDED
File without changes
@@ -0,0 +1,108 @@
1
+ import re
2
+
3
+ import pandas as pd
4
+
5
+ from rag_hpo.constants import PHENO_ID
6
+ from rag_hpo.ontology import Ontology
7
+
8
+
9
+ class HPODataframeBuilder:
10
+ def __init__(self, ontology: Ontology):
11
+ self._ontology = ontology
12
+ self._pattern = re.compile(r"(.+?):(.+)")
13
+ self._clean_abnormality = re.compile(r"(?i)^Abnormality of(?: the)?\s*")
14
+
15
+ def build_hpo_dataframe(self, limit: int | None = None) -> pd.DataFrame:
16
+ """Builds the HPO dataframe."""
17
+ records = []
18
+ terms = (
19
+ list(self._ontology.terms())[:limit]
20
+ if limit
21
+ else list(self._ontology.terms())
22
+ )
23
+
24
+ for term in terms:
25
+ hp_id = term.id
26
+ label = term.name
27
+ definition = term.definition or ""
28
+ synonyms = [syn.description for syn in term.synonyms]
29
+
30
+ # ── ALT IDs ──
31
+ alt_ids = self._sort_by_numeric(list(term.alternate_ids))
32
+
33
+ # ── XREFS ──
34
+ snomedct, umls = [], []
35
+ for xr in term.xrefs:
36
+ txt = str(xr)
37
+ m = self._pattern.search(txt)
38
+ ent = m.group(1) if m else txt
39
+ pre, _, _ = ent.partition(":")
40
+ if pre.upper() == "UMLS":
41
+ umls.append(ent)
42
+ elif pre.upper().startswith("SNOMED"):
43
+ snomedct.append(ent)
44
+ snomedct = self._sort_by_numeric(snomedct)
45
+ umls = self._sort_by_numeric(umls)
46
+
47
+ # ── LINEAGE ──
48
+ paths = self._ontology.root_to_node_paths(hp_id) or [
49
+ [self._ontology.root_id(), hp_id]
50
+ ]
51
+ for path_ids in paths:
52
+ lineage_str = " -> ".join(
53
+ f"{self._ontology.get_label(i)} ({i})" for i in path_ids
54
+ )
55
+
56
+ # ── ORGAN SYSTEM ──
57
+ if PHENO_ID in path_ids:
58
+ idx = path_ids.index(PHENO_ID)
59
+ organ = (
60
+ self._ontology.get_label(path_ids[idx + 1]) or "Other"
61
+ if idx + 1 < len(path_ids)
62
+ else "Other"
63
+ )
64
+ else:
65
+ organ = "Other"
66
+ organ_system = self._clean_abnormality.sub("", organ).title()
67
+
68
+ # ── EMIT ROWS ──
69
+ for phrase in [label] + synonyms:
70
+ if not phrase:
71
+ continue
72
+ # **Only title-case** the phrase; do NOT strip anything from it
73
+ clean_phrase = phrase.title()
74
+
75
+ records.append(
76
+ {
77
+ "hp_id": hp_id,
78
+ "phrase": clean_phrase,
79
+ "organ_system": organ_system,
80
+ "lineage": lineage_str,
81
+ "definition": definition,
82
+ "alt_ids": ";".join(alt_ids),
83
+ "snomedct": ";".join(snomedct),
84
+ "umls": ";".join(umls),
85
+ }
86
+ )
87
+
88
+ return pd.DataFrame(
89
+ records,
90
+ columns=[
91
+ "hp_id",
92
+ "phrase",
93
+ "organ_system",
94
+ "lineage",
95
+ "definition",
96
+ "alt_ids",
97
+ "snomedct",
98
+ "umls",
99
+ ],
100
+ )
101
+
102
+ @staticmethod
103
+ def _sort_by_numeric(entries: list[str]) -> list[str]:
104
+ def key_fn(e: str):
105
+ digs = "".join(filter(str.isdigit, e))
106
+ return int(digs) if digs else float("inf")
107
+
108
+ return sorted(entries, key=key_fn)
rag_hpo/_version.py ADDED
@@ -0,0 +1,21 @@
1
+ # file generated by setuptools-scm
2
+ # don't change, don't track in version control
3
+
4
+ __all__ = ["__version__", "__version_tuple__", "version", "version_tuple"]
5
+
6
+ TYPE_CHECKING = False
7
+ if TYPE_CHECKING:
8
+ from typing import Tuple
9
+ from typing import Union
10
+
11
+ VERSION_TUPLE = Tuple[Union[int, str], ...]
12
+ else:
13
+ VERSION_TUPLE = object
14
+
15
+ version: str
16
+ __version__: str
17
+ __version_tuple__: VERSION_TUPLE
18
+ version_tuple: VERSION_TUPLE
19
+
20
+ __version__ = version = '0.1.0'
21
+ __version_tuple__ = version_tuple = (0, 1, 0)
@@ -0,0 +1,96 @@
1
+ import logging
2
+ import os
3
+ from pathlib import Path
4
+ from typing import Iterable
5
+
6
+ import pandas as pd
7
+
8
+ logger = logging.getLogger(__name__)
9
+
10
+
11
+ class CheckpointStore:
12
+ """
13
+ Pickle-based checkpoints for named pipeline stages, one file per stage.
14
+
15
+ State is a dict mapping stage key -> DataFrame or None, where None means
16
+ "stage not reached yet" and an empty DataFrame means "stage done, no rows".
17
+
18
+ The first key marks a run: if its file exists, the directory holds a run
19
+ that can be resumed.
20
+
21
+ With directory=None the store is disabled and every operation is a no-op,
22
+ so callers don't need to branch on whether checkpointing is on.
23
+ """
24
+
25
+ def __init__(self, directory: Path | str | None, keys: Iterable[str]):
26
+ self.directory = Path(directory) if directory is not None else None
27
+ self.keys = tuple(keys)
28
+ if not self.keys:
29
+ raise ValueError("keys must not be empty.")
30
+
31
+ @property
32
+ def enabled(self) -> bool:
33
+ """True if the directory holds a resumable run."""
34
+ return self.directory is not None
35
+
36
+ def path(self, key: str) -> Path | None:
37
+ """Return the path of the checkpoint file for the given key."""
38
+ if not self.enabled:
39
+ return None
40
+ return self.directory / f"{key}.pkl"
41
+
42
+ def exists(self) -> bool:
43
+ """True if the directory holds a resumable run."""
44
+ p = self.path(self.keys[0])
45
+ return p is not None and p.exists()
46
+
47
+ def existing(self) -> list[str]:
48
+ """File names of all checkpoints currently on disk."""
49
+ paths = (self.path(k) for k in self.keys)
50
+ return [p.name for p in paths if p is not None and p.exists()]
51
+
52
+ def empty_state(self) -> dict[str, pd.DataFrame | None]:
53
+ """Return a dict mapping stage key -> DataFrame or None."""
54
+ return {key: None for key in self.keys}
55
+
56
+ def load(self) -> dict[str, pd.DataFrame | None]:
57
+ """Load the checkpoint state."""
58
+ state = self.empty_state()
59
+ for key in self.keys:
60
+ p = self.path(key)
61
+ if p is not None and p.exists():
62
+ state[key] = pd.read_pickle(p)
63
+ logger.info("Loaded checkpoint '%s' (%d rows)", key, len(state[key]))
64
+ return state
65
+
66
+ def save(
67
+ self, state: dict[str, pd.DataFrame | None], keys: Iterable[str] | None = None
68
+ ):
69
+ """Atomically write the given stages (all by default). None entries are skipped."""
70
+ if not self.enabled:
71
+ return
72
+ self.directory.mkdir(parents=True, exist_ok=True)
73
+ for key in keys or self.keys:
74
+ df = state.get(key)
75
+ if df is None:
76
+ continue
77
+ p = self.path(key)
78
+ tmp = p.with_suffix(p.suffix + ".tmp")
79
+ try:
80
+ df.to_pickle(tmp)
81
+ os.replace(tmp, p) # atomic
82
+ logger.debug("Checkpointed '%s' (%d rows) -> %s", key, len(df), p)
83
+ except Exception:
84
+ logger.exception("Error saving checkpoint '%s'", key)
85
+ tmp.unlink(missing_ok=True)
86
+
87
+ def clear(self):
88
+ """Delete all checkpoint files (the directory itself is left in place)."""
89
+ for key in self.keys:
90
+ p = self.path(key)
91
+ if p is None:
92
+ continue
93
+ try:
94
+ p.unlink(missing_ok=True)
95
+ except OSError as e:
96
+ logger.warning("Error removing checkpoint %s: %s", p, e)
rag_hpo/constants.py ADDED
@@ -0,0 +1,21 @@
1
+ import re
2
+
3
+ PROMPTS = {
4
+ "system_message_I": 'You are a highly specialized clinical information extraction system. Your task is to identify *all* phenotypic mentions in a clinical note and categorize them into exactly one of: Abnormal, Normal, Family History, Other, or Suspected.\n\n**Instructions:**\n1. **Scan Every Sentence**: Extract every phrase that describes a phenotype—signs, symptoms, abnormal findings, test results, anatomical observations—or any diagnostic conjecture or history statement.\n2. **Assign One Category**:\n • **Abnormal**: Any *observed* finding deviating from healthy (disease signs, lab abnormalities, pathological conditions). *These will be sent on for HPO mapping.*\n • **Normal**: Explicit statements of normalcy.\n • **Family History**: Phenotypes in relatives.\n • **Other**: Personal medical history, risk factors, demographics, or any non‐finding statement (e.g., “history of HIV,” “smoker,” “height 5′10″”).\n • **Suspected**: Any mention of a possible or rule‐out diagnosis (e.g., “possible sciatica,” “rule out PE”).\n3. **Preserve Specificity**: Extract the phrasing exactly as written.\n4. **Output JSON Only**: Return `{ "phenotypes": [ { "phrase": ..., "category": ... }, … ] }`.\n\n**Post‐processing:** Immediately drop anything not labeled Abnormal before HPO mapping.',
5
+ "system_message_II": 'You are an expert clinical phenotype mapper. \nGiven one abnormal phenotype phrase and a list of candidate HPO terms, select exactly one best matching HPO term—and only from those candidates. Do not invent, hallucinate, or suggest any term not in the provided list. \n\nWhen you receive input, it will be a JSON object:\n{\n "phrase": "​…​",\n "category": "​…​",\n "original_sentence": "​…​",\n "candidates": [ {"term": "​…​", "id": "HP:…​"}, … ]\n}\n\nDecision steps:\n1. Leverage context: Use the original_sentence to capture nuance. \n2. Match specificity: Pick the candidate whose term description most precisely matches the phenotype. \n3. If two are equally good, choose the one with the highest semantic similarity score. \n4. If none fits well (similarity < 80 or no clear match), return null. \n\nOutput requirement:\nReturn exactly one JSON object, nothing else:\n\n {"hpo_id": "HP:0001234"}\n\nor\n\n {"hpo_id": null"}\n\n—no commentary, no extra keys, no surrounding text.',
6
+ "system_message_double_check": 'You are a clinical phenotype validator. Only KEEP phrases that describe abnormal phenotypic findings — these include patient symptoms, physical signs, timing of presentation, disease course, laboratory values, imaging findings, or treatment responses. DELETE any phrase that: a) Describes a normal finding or routine observation (e.g., "normal heart rate"), b) Is not a phenotype (e.g., administrative note, demographic detail), c) Is not specifically abnormal, or d) Is part of a potential diagnosis or discussion point (e.g., "possible pneumonia", "rule out lupus"). Respond strictly in JSON with two keys: "verdict" ("keep" or "delete") and "reason" (optional brief justification).',
7
+ }
8
+
9
+ ROOT_ID = "HP:0000001" # “All”
10
+ PHENO_ID = "HP:0000118" # “Phenotypic abnormality”
11
+ CLEAN_ABNORMALITY = re.compile(r"(?i)^Abnormality of(?: the)?\s*")
12
+
13
+ FLAG_FILE = "LLaMa-4-Scout.flag"
14
+ TEMP_FILES = {
15
+ "input": "temp_input.pkl",
16
+ "combined": "temp_combined_results.pkl",
17
+ "exact": "temp_exact_matches.pkl",
18
+ "non_exact": "temp_non_exact_matches.pkl",
19
+ "final": "temp_final_result.pkl",
20
+ "responses": "responses_backup.pkl",
21
+ }
File without changes