From 8f7140cd5e2e059c5d2654bb83885bf0c67e8e23 Mon Sep 17 00:00:00 2001 From: Abhinav Gupta Date: Thu, 15 Oct 2026 14:22:40 +0530 Subject: [PATCH] fix(ui): resolve AttributeError on dict pages in render_pdf_page_inspector and eliminate circular import --- src/medical_coding/retrieval/tokenizer.py | 390 +------------------ src/medical_coding/ui/components.py | 26 +- src/medical_coding/utils/clinical_lexicon.py | 387 ++++++++++++++++++ src/medical_coding/utils/text.py | 2 +- tests/test_pdf_processing.py | 43 ++ 5 files changed, 457 insertions(+), 391 deletions(-) create mode 100644 src/medical_coding/utils/clinical_lexicon.py diff --git a/src/medical_coding/retrieval/tokenizer.py b/src/medical_coding/retrieval/tokenizer.py index 40ab347..0a95453 100644 --- a/src/medical_coding/retrieval/tokenizer.py +++ b/src/medical_coding/retrieval/tokenizer.py @@ -2,228 +2,11 @@ import re -# Standard clinical abbreviations mapped to expanded medical concepts -CLINICAL_ABBREVIATIONS: dict[str, str] = { - "hf": "heart failure", - "chf": "congestive heart failure", - "hfref": "heart failure reduced ejection fraction systolic", - "hfpef": "heart failure preserved ejection fraction diastolic", - "dm": "diabetes mellitus", - "t1dm": "type 1 diabetes mellitus", - "t2dm": "type 2 diabetes mellitus", - "htn": "hypertension", - "ckd": "chronic kidney disease", - "esrd": "end stage renal disease", - "copd": "chronic obstructive pulmonary disease", - "afib": "atrial fibrillation", - "af": "atrial fibrillation", - "cad": "coronary artery disease", - "mi": "myocardial infarction", - "ami": "acute myocardial infarction", - "stemi": "st elevation myocardial infarction", - "nstemi": "non st elevation myocardial infarction", - "aki": "acute kidney injury", - "arf": "acute renal failure", - "dvt": "deep vein thrombosis", - "pe": "pulmonary embolism", - "gerd": "gastroesophageal reflux disease", - "cva": "cerebrovascular accident stroke", - "tia": "transient ischemic attack", - "uti": "urinary tract infection", - "pna": "pneumonia", - "cap": "pneumonia", - "pud": "peptic ulcer disease", - "sob": "shortness of breath dyspnea", - "bph": "benign prostatic hyperplasia", - "osa": "obstructive sleep apnea", - "ra": "rheumatoid arthritis", - "oa": "osteoarthritis", - "dlbcl": "diffuse large b cell lymphoma", - "dka": "diabetic ketoacidosis", - "hiv": "human immunodeficiency virus", - "hbv": "hepatitis b virus viral hepatitis b", - "hcv": "hepatitis c virus viral hepatitis c", - "hav": "hepatitis a virus viral hepatitis a", - "ks": "kaposi sarcoma", - "acl": "anterior cruciate ligament", - "pcl": "posterior cruciate ligament", - "net": "neuroendocrine tumor carcinoid", - "fet": "frozen embryo transfer", - "dns": "deviated nasal septum", - "fess": "functional endoscopic sinus surgery sinus endoscopy", - "ith": "inferior turbinate hypertrophy", - "coli": "escherichia coli", - "pylori": "helicobacter pylori", - "choledocholithiasis": "calculus bile duct gallstone", - "mrsa": "methicillin resistant staphylococcus aureus", - "pbc": "primary biliary cholangitis", - "psc": "primary sclerosing cholangitis", - "poag": "primary open angle glaucoma", - "pah": "pulmonary arterial hypertension", - "phtn": "pulmonary hypertension", - "ehtn": "essential primary hypertension", - "crf": "chronic renal failure chronic kidney disease", - "cag": "coronary artery disease", - "ihd": "ischemic heart disease coronary artery disease", - "ashd": "atherosclerotic heart disease coronary artery disease", - "niddm": "type 2 diabetes mellitus", - "iddm": "type 1 diabetes mellitus", - "sle": "systemic lupus erythematosus", - "tb": "tuberculosis", - "uri": "upper respiratory tract infection", - "urti": "upper respiratory tract infection", - "lrti": "lower respiratory tract infection", - "ards": "acute respiratory distress syndrome", - "sbo": "small bowel obstruction", - "lbo": "large bowel obstruction", - "pvd": "peripheral vascular disease peripheral arterial disease", - "pad": "peripheral arterial disease peripheral vascular disease", - "ugib": "upper gastrointestinal bleeding", - "lgib": "lower gastrointestinal bleeding", - "hl": "hodgkin lymphoma", - "nhl": "non hodgkin lymphoma", - "all": "acute lymphoblastic leukemia", - "aml": "acute myeloid leukemia", - "cll": "chronic lymphocytic leukemia", - "cml": "chronic myeloid leukemia", - "mm": "multiple myeloma", - "nsclc": "non small cell lung cancer", - "sclc": "small cell lung cancer", - "rcc": "renal cell carcinoma", - "hcc": "hepatocellular carcinoma", - "crc": "colorectal cancer", - "itp": "immune thrombocytopenic purpura", - "sah": "subarachnoid hemorrhage", - "sdh": "subdural hematoma", - "edh": "epidural hematoma", - "ich": "intracerebral hemorrhage", -} - -# Non-informative general words (keeping critical medical distinctions: acute, chronic, type, 1, 2, without, etc.) -GENERAL_STOPWORDS: set[str] = { - "a", - "about", - "above", - "after", - "again", - "against", - "all", - "am", - "an", - "and", - "any", - "are", - "as", - "at", - "be", - "because", - "been", - "before", - "being", - "below", - "between", - "both", - "but", - "by", - "could", - "did", - "do", - "does", - "doing", - "down", - "during", - "each", - "for", - "from", - "further", - "had", - "has", - "have", - "having", - "he", - "her", - "here", - "hers", - "herself", - "him", - "himself", - "his", - "how", - "i", - "if", - "in", - "into", - "is", - "it", - "its", - "itself", - "me", - "more", - "most", - "my", - "myself", - "no", - "nor", - "not", - "of", - "off", - "on", - "once", - "only", - "or", - "other", - "ought", - "our", - "ours", - "ourselves", - "out", - "over", - "own", - "same", - "she", - "should", - "so", - "some", - "such", - "than", - "that", - "the", - "their", - "theirs", - "them", - "themselves", - "then", - "there", - "these", - "they", - "this", - "those", - "through", - "to", - "too", - "under", - "until", - "up", - "very", - "was", - "we", - "were", - "what", - "when", - "where", - "which", - "while", - "who", - "whom", - "why", - "with", - "would", - "you", - "your", - "yours", - "yourself", - "yourselves", -} +from medical_coding.utils.clinical_lexicon import ( + CLINICAL_ABBREVIATIONS, + CLINICAL_MORPHOLOGY, + GENERAL_STOPWORDS, +) def expand_medical_abbreviations(text: str) -> str: @@ -291,168 +74,7 @@ def normalize_clinical_query(text: str) -> str: return re.sub(r"\s+", " ", expanded) -CLINICAL_MORPHOLOGY: dict[str, list[str]] = { - "ureter": ["ureteric", "ureteral"], - "ureteric": ["ureter", "ureteral"], - "ureteral": ["ureter", "ureteric"], - "calculus": ["stone", "calculi", "stones", "cholelithiasis", "gallstone", "gallstones", "lithiasis", "nephrolithiasis"], - "calculi": ["calculus", "stone", "stones", "cholelithiasis", "gallstone", "gallstones"], - "stone": ["calculus", "calculi", "stones", "cholelithiasis", "gallstone", "gallstones"], - "stones": ["calculus", "calculi", "stone", "cholelithiasis", "gallstone", "gallstones"], - "renal": ["kidney", "renal", "nephropathy"], - "kidney": ["renal", "kidney", "nephropathy"], - "injury": ["failure", "injury"], - "failure": ["injury", "failure", "insufficiency"], - "infarction": ["infarct", "infarctions", "stemi", "nstemi", "ami", "attack"], - "attack": ["infarction", "mi"], - "gastric": ["stomach", "gastric"], - "stomach": ["gastric", "stomach"], - "cardiac": ["heart", "cardiac"], - "heart": ["cardiac", "heart"], - "pulmonary": ["lung", "pulmonary"], - "lung": ["pulmonary", "lung"], - "hepatic": ["liver", "hepatic"], - "liver": ["hepatic", "liver"], - "colonic": ["colon", "colonic"], - "colon": ["colonic", "colon"], - "appendiceal": ["appendix", "appendiceal"], - "appendix": ["appendiceal", "appendix"], - "splenic": ["spleen", "splenic"], - "spleen": ["splenic", "spleen"], - "cerebral": ["brain", "cerebral"], - "brain": ["cerebral", "brain"], - "ocular": ["eye", "ocular"], - "eye": ["ocular", "eye"], - "turbinate": ["turbinates", "nasal", "nose"], - "turbinates": ["turbinate", "nasal", "nose"], - "nasal": ["nose", "turbinate", "turbinates", "septum"], - "septum": ["nasal", "nose"], - "obstruction": ["blockage", "congestion", "disorder", "stricture", "stenosis"], - "choledocholithiasis": ["calculus", "bile", "duct", "gallstone", "gallstones", "cholelithiasis", "stone", "stones"], - "coli": ["escherichia", "infection", "bacteria", "bacteremia"], - "escherichia": ["coli", "infection", "bacteria", "bacteremia"], - "pylori": ["helicobacter", "gastritis", "infection", "bacteria"], - "helicobacter": ["pylori", "gastritis", "infection", "bacteria"], - "staphylococcus": ["staph", "aureus", "infection", "mrsa"], - "streptococcus": ["strep", "pneumoniae", "infection"], - "pneumonia": ["pneumonitis", "pna"], - "hypertension": ["htn", "high blood pressure"], - "diabetes": ["dm", "diabetic"], - "diabetic": ["diabetes", "dm"], - "colic": ["colicky"], - "chf": ["heart failure", "congestive heart failure"], - "pain": ["discomfort", "ache"], - "discomfort": ["pain", "ache"], - "ache": ["pain", "discomfort"], - "community": ["pneumonia"], - "dlbcl": ["lymphoma", "diffuse", "large"], - "lymphoma": ["dlbcl"], - "bronchitis": ["bronchial"], - "ckd": ["chronic", "kidney", "disease"], - "candida": ["candidiasis", "candidal"], - "candidiasis": ["candida", "candidal"], - "candidal": ["candida", "candidiasis"], - "sepsis": ["septic", "septicemia"], - "septic": ["sepsis", "septicemia"], - "septicemia": ["sepsis", "septic"], - "urinary": ["urogenital"], - "urogenital": ["urinary", "genital"], - "urosepsis": ["urinary", "sepsis"], - "hbv": ["hepatitis", "viral"], - "hepatitis": ["hbv", "hcv", "viral"], - "sarcoma": ["kaposi", "sarcomas", "malignant", "neoplasm", "cancer"], - "viral": ["virus", "hepatitis", "hiv"], - "virus": ["viral", "hepatitis", "hiv"], - "cancer": ["malignant", "neoplasm", "carcinoma"], - "carcinoma": ["cancer", "malignant", "neoplasm"], - "malignant": ["cancer", "carcinoma", "neoplasm", "metastasis", "metastatic", "metastases", "malignancy"], - "neoplasm": ["cancer", "carcinoma", "malignant", "metastasis", "metastatic", "metastases", "tumor", "tumour"], - "metastasis": ["metastatic", "metastases", "secondary", "malignant", "neoplasm"], - "metastases": ["metastasis", "metastatic", "secondary", "malignant", "neoplasm"], - "metastatic": ["metastasis", "metastases", "secondary", "malignant", "neoplasm"], - "secondary": ["metastasis", "metastases", "metastatic", "secondaries"], - "carcinoid": ["neuroendocrine", "net"], - "neuroendocrine": ["carcinoid", "net", "endocrine", "tumor", "neoplasm"], - "male": ["man", "men", "boy", "gentleman"], - "subsequent": ["follow-up", "followup", "subsequent", "routine healing"], - "pleural": ["pleura"], - "pleura": ["pleural"], - "malleolus": ["malleolar", "fibula", "fibular"], - "malleolar": ["malleolus", "fibula", "fibular"], - "fibula": ["malleolus", "malleolar", "fibular"], - "fibular": ["malleolus", "malleolar", "fibula"], - "tarsal": ["tarsus", "tarsals", "foot"], - "tarsals": ["tarsal", "foot"], - "metatarsal": ["metatarsals", "foot"], - "metatarsals": ["metatarsal", "foot"], - "foot": ["tarsal", "tarsals", "metatarsal", "metatarsals", "ankle"], - "ankle": ["deltoid", "calcaneofibular", "malleolus", "malleolar"], - "ligament": ["deltoid", "calcaneofibular", "sprain", "tear"], - "sprain": ["sprains", "injury", "ligament", "tear", "rupture"], - "sprains": ["sprain", "injury", "ligament", "tear", "rupture"], - "tear": ["tears", "rupture", "sprain", "sprains", "disruption", "injury"], - "tears": ["tear", "rupture", "sprain", "sprains", "disruption"], - "cruciate": ["acl", "pcl", "ligament"], - "sarcomas": ["sarcoma", "malignant", "neoplasm", "cancer"], - "pyelonephritis": ["pyelonephritic", "nephritis", "renal", "kidney"], - "nondisplaced": ["non-displaced"], - "displaced": ["displacement"], - "fracture": ["fractures"], - "fractures": ["fracture"], - "cholecystitis": ["gallbladder"], - "cholelithiasis": ["calculus", "gallbladder", "gallstone", "gallstones", "calculi"], - "gallstones": ["cholelithiasis", "calculus", "gallbladder", "gallstone", "stone"], - "gallstone": ["cholelithiasis", "calculus", "gallbladder", "gallstones", "stone"], - "gallbladder": ["cholecystitis", "cholelithiasis", "biliary"], - "myocardial": ["infarction", "nstemi", "stemi", "heart"], - "infarction": ["myocardial", "nstemi", "stemi"], - "nstemi": ["subendocardial", "myocardial", "infarction"], - "stemi": ["myocardial", "infarction"], - "subendocardial": ["nstemi", "infarction", "myocardial"], - "hyperlipidemia": ["hypercholesterolemia", "dyslipidemia", "lipids"], - "dyslipidemia": ["hyperlipidemia", "hypercholesterolemia", "lipids"], - "hypercholesterolemia": ["hyperlipidemia", "dyslipidemia", "cholesterol"], - "hypokalemia": ["potassium", "electrolyte"], - "hyperkalemia": ["potassium", "electrolyte"], - "hyponatremia": ["sodium", "electrolyte"], - "potassium": ["hypokalemia", "hyperkalemia"], - "sodium": ["hyponatremia"], - "anemia": ["iron", "deficiency", "blood"], - "appendicitis": ["appendix"], - "diverticulitis": ["diverticular", "colon", "diverticulosis"], - "diverticular": ["diverticulitis", "diverticulosis", "colon"], - "pancreatitis": ["pancreas", "pancreatic"], - "pancreas": ["pancreatitis", "pancreatic"], - "pancreatic": ["pancreas", "pancreatitis"], - "fibrillation": ["atrial", "afib"], - "atherosclerosis": ["coronary", "artery", "disease", "cad", "native", "atherosclerotic"], - "atherosclerotic": ["coronary", "cad", "atherosclerosis", "native", "artery"], - "coronary": ["cad", "atherosclerotic", "artery", "heart", "arteriosclerotic", "native"], - "cad": ["coronary", "artery", "disease", "atherosclerotic", "native"], - "stroke": ["cerebral", "infarction", "cva", "ischemic"], - "cva": ["stroke", "cerebral", "infarction"], - "syncope": ["collapse", "vasovagal", "fainting"], - "collapse": ["syncope", "vasovagal", "fainting"], - "cirrhosis": ["hepatic", "liver", "cirrhotic"], - "cirrhotic": ["cirrhosis", "liver", "hepatic"], - "delirium": ["encephalopathy", "acute", "confusional", "toxic", "metabolic"], - "encephalopathy": ["delirium", "acute", "metabolic", "toxic"], - "hypothyroidism": ["thyroid"], - "thyroid": ["hypothyroidism"], - "primary": ["essential", "idiopathic"], - "essential": ["primary", "idiopathic"], - "osteoarthritis": ["osteoarthrosis", "degenerative", "joint", "disease", "oa"], - "glaucoma": ["open-angle", "poag", "ocular"], - "cholangitis": ["biliary", "cirrhosis"], - "biliary": ["cholangitis", "gallbladder", "cholecystitis", "cholelithiasis"], - "pneumothorax": ["spontaneous", "collapsed", "lung"], - "aldosteronism": ["hyperaldosteronism", "conn"], - "hyperparathyroidism": ["parathyroid"], - "sclerosis": ["multiple", "sclerosis", "ppms"], - "infection": ["infectious", "infective"], - "thrombosis": ["thrombus", "thrombotic", "clot", "dvt"], - "embolism": ["embolus", "embolic", "pe"], -} + def expand_clinical_morphology(tokens: list[str]) -> list[str]: diff --git a/src/medical_coding/ui/components.py b/src/medical_coding/ui/components.py index 3cf42df..4b3f1e2 100644 --- a/src/medical_coding/ui/components.py +++ b/src/medical_coding/ui/components.py @@ -585,29 +585,43 @@ def render_pdf_page_inspector(pages: list[Any]) -> None: if not pages: return + def _get(obj: Any, key: str, default: Any = None) -> Any: + if isinstance(obj, dict): + return obj.get(key, default) + return getattr(obj, key, default) + + page_numbers = [_get(p, "page_number", idx + 1) for idx, p in enumerate(pages)] + with st.expander(f"📄 Ingested PDF Document Viewer ({len(pages)} Pages)", expanded=False): selected_page = st.selectbox( "Select Page to Inspect:", - options=[p.page_number for p in pages], + options=page_numbers, format_func=lambda x: f"Page {x} of {len(pages)}", ) - page_obj = next((p for p in pages if p.page_number == selected_page), pages[0]) + page_obj = next((p for p in pages if _get(p, "page_number") == selected_page), pages[0]) + + norm_text = str(_get(page_obj, "normalized_text", "") or "") + char_count = _get(page_obj, "char_count", len(norm_text)) + word_count = _get(page_obj, "word_count", len(norm_text.split())) + has_images = _get(page_obj, "has_images", False) c1, c2, c3 = st.columns(3) - c1.metric("Character Count", page_obj.char_count) - c2.metric("Word Count", page_obj.word_count) - c3.metric("Embedded Images", "Yes" if page_obj.has_images else "No") + c1.metric("Character Count", char_count) + c2.metric("Word Count", word_count) + c3.metric("Embedded Images", "Yes" if has_images else "No") + escaped_text = html.escape(norm_text) st.markdown( f"""
-
{page_obj.normalized_text}
+
{escaped_text}
""", unsafe_allow_html=True, ) + NODE_TITLES: dict[str, str] = { "validate_document": "Document Validation", "extract_text": "Multimodal Normalization", diff --git a/src/medical_coding/utils/clinical_lexicon.py b/src/medical_coding/utils/clinical_lexicon.py new file mode 100644 index 0000000..540a682 --- /dev/null +++ b/src/medical_coding/utils/clinical_lexicon.py @@ -0,0 +1,387 @@ +"""Clinical acronym dictionaries, medical stop words, and morphological synonym lexicons.""" + +# Standard clinical abbreviations mapped to expanded medical concepts +CLINICAL_ABBREVIATIONS: dict[str, str] = { + "hf": "heart failure", + "chf": "congestive heart failure", + "hfref": "heart failure reduced ejection fraction systolic", + "hfpef": "heart failure preserved ejection fraction diastolic", + "dm": "diabetes mellitus", + "t1dm": "type 1 diabetes mellitus", + "t2dm": "type 2 diabetes mellitus", + "htn": "hypertension", + "ckd": "chronic kidney disease", + "esrd": "end stage renal disease", + "copd": "chronic obstructive pulmonary disease", + "afib": "atrial fibrillation", + "af": "atrial fibrillation", + "cad": "coronary artery disease", + "mi": "myocardial infarction", + "ami": "acute myocardial infarction", + "stemi": "st elevation myocardial infarction", + "nstemi": "non st elevation myocardial infarction", + "aki": "acute kidney injury", + "arf": "acute renal failure", + "dvt": "deep vein thrombosis", + "pe": "pulmonary embolism", + "gerd": "gastroesophageal reflux disease", + "cva": "cerebrovascular accident stroke", + "tia": "transient ischemic attack", + "uti": "urinary tract infection", + "pna": "pneumonia", + "cap": "pneumonia", + "pud": "peptic ulcer disease", + "sob": "shortness of breath dyspnea", + "bph": "benign prostatic hyperplasia", + "osa": "obstructive sleep apnea", + "ra": "rheumatoid arthritis", + "oa": "osteoarthritis", + "dlbcl": "diffuse large b cell lymphoma", + "dka": "diabetic ketoacidosis", + "hiv": "human immunodeficiency virus", + "hbv": "hepatitis b virus viral hepatitis b", + "hcv": "hepatitis c virus viral hepatitis c", + "hav": "hepatitis a virus viral hepatitis a", + "ks": "kaposi sarcoma", + "acl": "anterior cruciate ligament", + "pcl": "posterior cruciate ligament", + "net": "neuroendocrine tumor carcinoid", + "fet": "frozen embryo transfer", + "dns": "deviated nasal septum", + "fess": "functional endoscopic sinus surgery sinus endoscopy", + "ith": "inferior turbinate hypertrophy", + "coli": "escherichia coli", + "pylori": "helicobacter pylori", + "choledocholithiasis": "calculus bile duct gallstone", + "mrsa": "methicillin resistant staphylococcus aureus", + "pbc": "primary biliary cholangitis", + "psc": "primary sclerosing cholangitis", + "poag": "primary open angle glaucoma", + "pah": "pulmonary arterial hypertension", + "phtn": "pulmonary hypertension", + "ehtn": "essential primary hypertension", + "crf": "chronic renal failure chronic kidney disease", + "cag": "coronary artery disease", + "ihd": "ischemic heart disease coronary artery disease", + "ashd": "atherosclerotic heart disease coronary artery disease", + "niddm": "type 2 diabetes mellitus", + "iddm": "type 1 diabetes mellitus", + "sle": "systemic lupus erythematosus", + "tb": "tuberculosis", + "uri": "upper respiratory tract infection", + "urti": "upper respiratory tract infection", + "lrti": "lower respiratory tract infection", + "ards": "acute respiratory distress syndrome", + "sbo": "small bowel obstruction", + "lbo": "large bowel obstruction", + "pvd": "peripheral vascular disease peripheral arterial disease", + "pad": "peripheral arterial disease peripheral vascular disease", + "ugib": "upper gastrointestinal bleeding", + "lgib": "lower gastrointestinal bleeding", + "hl": "hodgkin lymphoma", + "nhl": "non hodgkin lymphoma", + "all": "acute lymphoblastic leukemia", + "aml": "acute myeloid leukemia", + "cll": "chronic lymphocytic leukemia", + "cml": "chronic myeloid leukemia", + "mm": "multiple myeloma", + "nsclc": "non small cell lung cancer", + "sclc": "small cell lung cancer", + "rcc": "renal cell carcinoma", + "hcc": "hepatocellular carcinoma", + "crc": "colorectal cancer", + "itp": "immune thrombocytopenic purpura", + "sah": "subarachnoid hemorrhage", + "sdh": "subdural hematoma", + "edh": "epidural hematoma", + "ich": "intracerebral hemorrhage", +} + +# Non-informative general words (keeping critical medical distinctions: acute, chronic, type, 1, 2, without, etc.) +GENERAL_STOPWORDS: set[str] = { + "a", + "about", + "above", + "after", + "again", + "against", + "all", + "am", + "an", + "and", + "any", + "are", + "as", + "at", + "be", + "because", + "been", + "before", + "being", + "below", + "between", + "both", + "but", + "by", + "could", + "did", + "do", + "does", + "doing", + "down", + "during", + "each", + "for", + "from", + "further", + "had", + "has", + "have", + "having", + "he", + "her", + "here", + "hers", + "herself", + "him", + "himself", + "his", + "how", + "i", + "if", + "in", + "into", + "is", + "it", + "its", + "itself", + "me", + "more", + "most", + "my", + "myself", + "no", + "nor", + "not", + "of", + "off", + "on", + "once", + "only", + "or", + "other", + "ought", + "our", + "ours", + "ourselves", + "out", + "over", + "own", + "same", + "she", + "should", + "so", + "some", + "such", + "than", + "that", + "the", + "their", + "theirs", + "them", + "themselves", + "then", + "there", + "these", + "they", + "this", + "those", + "through", + "to", + "too", + "under", + "until", + "up", + "very", + "was", + "we", + "were", + "what", + "when", + "where", + "which", + "while", + "who", + "whom", + "why", + "with", + "would", + "you", + "your", + "yours", + "yourself", + "yourselves", +} + +CLINICAL_MORPHOLOGY: dict[str, list[str]] = { + "ureter": ["ureteric", "ureteral"], + "ureteric": ["ureter", "ureteral"], + "ureteral": ["ureter", "ureteric"], + "calculus": ["stone", "calculi", "stones", "cholelithiasis", "gallstone", "gallstones", "lithiasis", "nephrolithiasis"], + "calculi": ["calculus", "stone", "stones", "cholelithiasis", "gallstone", "gallstones"], + "stone": ["calculus", "calculi", "stones", "cholelithiasis", "gallstone", "gallstones"], + "stones": ["calculus", "calculi", "stone", "cholelithiasis", "gallstone", "gallstones"], + "renal": ["kidney", "renal", "nephropathy"], + "kidney": ["renal", "kidney", "nephropathy"], + "injury": ["failure", "injury"], + "failure": ["injury", "failure", "insufficiency"], + "infarction": ["infarct", "infarctions", "stemi", "nstemi", "ami", "attack"], + "attack": ["infarction", "mi"], + "gastric": ["stomach", "gastric"], + "stomach": ["gastric", "stomach"], + "cardiac": ["heart", "cardiac"], + "heart": ["cardiac", "heart"], + "pulmonary": ["lung", "pulmonary"], + "lung": ["pulmonary", "lung"], + "hepatic": ["liver", "hepatic"], + "liver": ["hepatic", "liver"], + "colonic": ["colon", "colonic"], + "colon": ["colonic", "colon"], + "appendiceal": ["appendix", "appendiceal"], + "appendix": ["appendiceal", "appendix"], + "splenic": ["spleen", "splenic"], + "spleen": ["splenic", "spleen"], + "cerebral": ["brain", "cerebral"], + "brain": ["cerebral", "brain"], + "ocular": ["eye", "ocular"], + "eye": ["ocular", "eye"], + "turbinate": ["turbinates", "nasal", "nose"], + "turbinates": ["turbinate", "nasal", "nose"], + "nasal": ["nose", "turbinate", "turbinates", "septum"], + "septum": ["nasal", "nose"], + "obstruction": ["blockage", "congestion", "disorder", "stricture", "stenosis"], + "choledocholithiasis": ["calculus", "bile", "duct", "gallstone", "gallstones", "cholelithiasis", "stone", "stones"], + "coli": ["escherichia", "infection", "bacteria", "bacteremia"], + "escherichia": ["coli", "infection", "bacteria", "bacteremia"], + "pylori": ["helicobacter", "gastritis", "infection", "bacteria"], + "helicobacter": ["pylori", "gastritis", "infection", "bacteria"], + "staphylococcus": ["staph", "aureus", "infection", "mrsa"], + "streptococcus": ["strep", "pneumoniae", "infection"], + "pneumonia": ["pneumonitis", "pna"], + "hypertension": ["htn", "high blood pressure"], + "diabetes": ["dm", "diabetic"], + "diabetic": ["diabetes", "dm"], + "colic": ["colicky"], + "chf": ["heart failure", "congestive heart failure"], + "pain": ["discomfort", "ache"], + "discomfort": ["pain", "ache"], + "ache": ["pain", "discomfort"], + "community": ["pneumonia"], + "dlbcl": ["lymphoma", "diffuse", "large"], + "lymphoma": ["dlbcl"], + "bronchitis": ["bronchial"], + "ckd": ["chronic", "kidney", "disease"], + "candida": ["candidiasis", "candidal"], + "candidiasis": ["candida", "candidal"], + "candidal": ["candida", "candidiasis"], + "sepsis": ["septic", "septicemia"], + "septic": ["sepsis", "septicemia"], + "septicemia": ["sepsis", "septic"], + "urinary": ["urogenital"], + "urogenital": ["urinary", "genital"], + "urosepsis": ["urinary", "sepsis"], + "hbv": ["hepatitis", "viral"], + "hepatitis": ["hbv", "hcv", "viral"], + "sarcoma": ["kaposi", "sarcomas", "malignant", "neoplasm", "cancer"], + "viral": ["virus", "hepatitis", "hiv"], + "virus": ["viral", "hepatitis", "hiv"], + "cancer": ["malignant", "neoplasm", "carcinoma"], + "carcinoma": ["cancer", "malignant", "neoplasm"], + "malignant": ["cancer", "carcinoma", "neoplasm", "metastasis", "metastatic", "metastases", "malignancy"], + "neoplasm": ["cancer", "carcinoma", "malignant", "metastasis", "metastatic", "metastases", "tumor", "tumour"], + "metastasis": ["metastatic", "metastases", "secondary", "malignant", "neoplasm"], + "metastases": ["metastasis", "metastatic", "secondary", "malignant", "neoplasm"], + "metastatic": ["metastasis", "metastases", "secondary", "malignant", "neoplasm"], + "secondary": ["metastasis", "metastases", "metastatic", "secondaries"], + "carcinoid": ["neuroendocrine", "net"], + "neuroendocrine": ["carcinoid", "net", "endocrine", "tumor", "neoplasm"], + "male": ["man", "men", "boy", "gentleman"], + "subsequent": ["follow-up", "followup", "subsequent", "routine healing"], + "pleural": ["pleura"], + "pleura": ["pleural"], + "malleolus": ["malleolar", "fibula", "fibular"], + "malleolar": ["malleolus", "fibula", "fibular"], + "fibula": ["malleolus", "malleolar", "fibular"], + "fibular": ["malleolus", "malleolar", "fibula"], + "tarsal": ["tarsus", "tarsals", "foot"], + "tarsals": ["tarsal", "foot"], + "metatarsal": ["metatarsals", "foot"], + "metatarsals": ["metatarsal", "foot"], + "foot": ["tarsal", "tarsals", "metatarsal", "metatarsals", "ankle"], + "ankle": ["deltoid", "calcaneofibular", "malleolus", "malleolar"], + "ligament": ["deltoid", "calcaneofibular", "sprain", "tear"], + "sprain": ["sprains", "injury", "ligament", "tear", "rupture"], + "sprains": ["sprain", "injury", "ligament", "tear", "rupture"], + "tear": ["tears", "rupture", "sprain", "sprains", "disruption", "injury"], + "tears": ["tear", "rupture", "sprain", "sprains", "disruption"], + "cruciate": ["acl", "pcl", "ligament"], + "sarcomas": ["sarcoma", "malignant", "neoplasm", "cancer"], + "pyelonephritis": ["pyelonephritic", "nephritis", "renal", "kidney"], + "nondisplaced": ["non-displaced"], + "displaced": ["displacement"], + "fracture": ["fractures"], + "fractures": ["fracture"], + "cholecystitis": ["gallbladder"], + "cholelithiasis": ["calculus", "gallbladder", "gallstone", "gallstones", "calculi"], + "gallstones": ["cholelithiasis", "calculus", "gallbladder", "gallstone", "stone"], + "gallstone": ["cholelithiasis", "calculus", "gallbladder", "gallstones", "stone"], + "gallbladder": ["cholecystitis", "cholelithiasis", "biliary"], + "myocardial": ["infarction", "nstemi", "stemi", "heart"], + "infarction": ["myocardial", "nstemi", "stemi"], + "nstemi": ["subendocardial", "myocardial", "infarction"], + "stemi": ["myocardial", "infarction"], + "subendocardial": ["nstemi", "infarction", "myocardial"], + "hyperlipidemia": ["hypercholesterolemia", "dyslipidemia", "lipids"], + "dyslipidemia": ["hyperlipidemia", "hypercholesterolemia", "lipids"], + "hypercholesterolemia": ["hyperlipidemia", "dyslipidemia", "cholesterol"], + "hypokalemia": ["potassium", "electrolyte"], + "hyperkalemia": ["potassium", "electrolyte"], + "hyponatremia": ["sodium", "electrolyte"], + "potassium": ["hypokalemia", "hyperkalemia"], + "sodium": ["hyponatremia"], + "anemia": ["iron", "deficiency", "blood"], + "appendicitis": ["appendix"], + "diverticulitis": ["diverticular", "colon", "diverticulosis"], + "diverticular": ["diverticulitis", "diverticulosis", "colon"], + "pancreatitis": ["pancreas", "pancreatic"], + "pancreas": ["pancreatitis", "pancreatic"], + "pancreatic": ["pancreas", "pancreatitis"], + "fibrillation": ["atrial", "afib"], + "atherosclerosis": ["coronary", "artery", "disease", "cad", "native", "atherosclerotic"], + "atherosclerotic": ["coronary", "cad", "atherosclerosis", "native", "artery"], + "coronary": ["cad", "atherosclerotic", "artery", "heart", "arteriosclerotic", "native"], + "cad": ["coronary", "artery", "disease", "atherosclerotic", "native"], + "stroke": ["cerebral", "infarction", "cva", "ischemic"], + "cva": ["stroke", "cerebral", "infarction"], + "syncope": ["collapse", "vasovagal", "fainting"], + "collapse": ["syncope", "vasovagal", "fainting"], + "cirrhosis": ["hepatic", "liver", "cirrhotic"], + "cirrhotic": ["cirrhosis", "liver", "hepatic"], + "delirium": ["encephalopathy", "acute", "confusional", "toxic", "metabolic"], + "encephalopathy": ["delirium", "acute", "metabolic", "toxic"], + "hypothyroidism": ["thyroid"], + "thyroid": ["hypothyroidism"], + "primary": ["essential", "idiopathic"], + "essential": ["primary", "idiopathic"], + "osteoarthritis": ["osteoarthrosis", "degenerative", "joint", "disease", "oa"], + "glaucoma": ["open-angle", "poag", "ocular"], + "cholangitis": ["biliary", "cirrhosis"], + "biliary": ["cholangitis", "gallbladder", "cholecystitis", "cholelithiasis"], + "pneumothorax": ["spontaneous", "collapsed", "lung"], + "aldosteronism": ["hyperaldosteronism", "conn"], + "hyperparathyroidism": ["parathyroid"], + "sclerosis": ["multiple", "sclerosis", "ppms"], + "infection": ["infectious", "infective"], + "thrombosis": ["thrombus", "thrombotic", "clot", "dvt"], + "embolism": ["embolus", "embolic", "pe"], +} diff --git a/src/medical_coding/utils/text.py b/src/medical_coding/utils/text.py index 60bb9d7..2d3ecd2 100644 --- a/src/medical_coding/utils/text.py +++ b/src/medical_coding/utils/text.py @@ -223,7 +223,7 @@ def extract_search_query_variations(raw_term: str, evidence: str = "") -> list[s _add(" ".join(core_words)) # 4. Morphological synonyms - from medical_coding.retrieval.tokenizer import CLINICAL_MORPHOLOGY + from medical_coding.utils.clinical_lexicon import CLINICAL_MORPHOLOGY syn_words: list[str] = [] has_syn = False for w in (core_words or words): diff --git a/tests/test_pdf_processing.py b/tests/test_pdf_processing.py index 445207b..5f409f4 100644 --- a/tests/test_pdf_processing.py +++ b/tests/test_pdf_processing.py @@ -330,3 +330,46 @@ async def test_throughput_benchmark_ten_documents() -> None: f"Total time = {batch_result.total_elapsed_ms:.2f} ms | " f"Throughput = {batch_result.throughput_docs_per_sec:.2f} docs/sec" ) + + +def test_render_pdf_page_inspector_handles_dicts_and_objects() -> None: + """Verify that render_pdf_page_inspector works seamlessly with both dict pages and object pages.""" + from medical_coding.ui.components import render_pdf_page_inspector + from medical_coding.pdf.models import ExtractedPage + + # 1. Test dict pages (as produced by IngestionResult / ParsedDocument) + dict_pages = [ + { + "page_number": 1, + "normalized_text": "Page 1 clinical text.", + "char_count": 21, + "word_count": 4, + "has_images": False, + }, + { + "page_number": 2, + "normalized_text": "Page 2 clinical text.", + "char_count": 21, + "word_count": 4, + "has_images": True, + }, + ] + # Must not raise AttributeError: 'dict' object has no attribute 'page_number' + render_pdf_page_inspector(dict_pages) + + # 2. Test object pages (ExtractedPage) + obj_pages = [ + ExtractedPage( + page_number=1, + raw_text="Raw text page 1", + normalized_text="Page 1 clinical text.", + char_count=21, + word_count=4, + has_images=False, + ) + ] + render_pdf_page_inspector(obj_pages) + + # 3. Empty list test + render_pdf_page_inspector([]) +