diff --git a/.gitignore b/.gitignore index b778a07..21a890b 100644 --- a/.gitignore +++ b/.gitignore @@ -101,8 +101,8 @@ models/embeddings/* !models/gguf/.gitkeep # Large External Datasets & User Uploads -Database/ -database/ +/Database/ +/database/ *.xls *.xlsx data/icd10/*.txt diff --git a/src/medical_coding/database/repository.py b/src/medical_coding/database/repository.py index 150d921..d1b4220 100644 --- a/src/medical_coding/database/repository.py +++ b/src/medical_coding/database/repository.py @@ -5,6 +5,12 @@ from datetime import UTC, datetime from typing import Any import pandas as pd + +try: + pd.set_option("future.infer_string", False) +except Exception: + pass + from sqlalchemy import desc, func, or_, select from sqlalchemy.orm import selectinload @@ -380,7 +386,10 @@ class MedicalCodingRepository: "created_at": d["created_at"], } ) - return pd.DataFrame(records) + if not records: + return pd.DataFrame() + cols = {k: [r[k] for r in records] for k in records[0]} + return pd.DataFrame(cols) def purge_all_documents(self) -> int: """Delete all documents (primarily used for test cleanup).""" @@ -548,13 +557,17 @@ class MedicalCodingRepository: def get_pipeline_thread(self, thread_id: str) -> dict[str, Any] | None: """Fetch a specific execution thread with its ordered steps and result.""" - with get_db_session() as session: - thread = session.execute( - select(PipelineThreadModel) - .options(selectinload(PipelineThreadModel.steps)) - .where(PipelineThreadModel.thread_id == thread_id) - ).scalar_one_or_none() - return thread.to_dict() if thread else None + try: + with get_db_session() as session: + thread = session.execute( + select(PipelineThreadModel) + .options(selectinload(PipelineThreadModel.steps)) + .where(PipelineThreadModel.thread_id == thread_id) + ).scalar_one_or_none() + return thread.to_dict() if thread else None + except Exception as exc: + logger.warning("Error fetching pipeline thread %s: %s", thread_id, exc) + return None def list_pipeline_threads( self, @@ -562,30 +575,38 @@ class MedicalCodingRepository: status: str | None = None, ) -> list[dict[str, Any]]: """List historical pipeline execution threads with optional status filtering.""" - with get_db_session() as session: - stmt = ( - select(PipelineThreadModel) - .options(selectinload(PipelineThreadModel.steps)) - .order_by(desc(PipelineThreadModel.start_time)) - ) - if status and status != "ALL": - stmt = stmt.where(PipelineThreadModel.status == status) + try: + with get_db_session() as session: + stmt = ( + select(PipelineThreadModel) + .options(selectinload(PipelineThreadModel.steps)) + .order_by(desc(PipelineThreadModel.start_time)) + ) + if status and status != "ALL": + stmt = stmt.where(PipelineThreadModel.status == status) - stmt = stmt.limit(limit) - threads = session.execute(stmt).scalars().all() - return [t.to_dict() for t in threads] + stmt = stmt.limit(limit) + threads = session.execute(stmt).scalars().all() + return [t.to_dict() for t in threads] + except Exception as exc: + logger.warning("Error querying pipeline threads: %s", exc) + return [] def get_latest_pipeline_thread(self) -> dict[str, Any] | None: """Fetch the most recent pipeline thread (running or finished).""" - with get_db_session() as session: - stmt = ( - select(PipelineThreadModel) - .options(selectinload(PipelineThreadModel.steps)) - .order_by(desc(PipelineThreadModel.start_time)) - .limit(1) - ) - thread = session.execute(stmt).scalar_one_or_none() - return thread.to_dict() if thread else None + try: + with get_db_session() as session: + stmt = ( + select(PipelineThreadModel) + .options(selectinload(PipelineThreadModel.steps)) + .order_by(desc(PipelineThreadModel.start_time)) + .limit(1) + ) + thread = session.execute(stmt).scalar_one_or_none() + return thread.to_dict() if thread else None + except Exception as exc: + logger.warning("Error fetching latest pipeline thread: %s", exc) + return None def delete_pipeline_thread(self, thread_id: str) -> bool: """Delete a thread and all associated step logs.""" diff --git a/src/medical_coding/graph/pipeline.py b/src/medical_coding/graph/pipeline.py index efcfd72..dc83b36 100644 --- a/src/medical_coding/graph/pipeline.py +++ b/src/medical_coding/graph/pipeline.py @@ -130,31 +130,37 @@ async def process_clinical_document( resolved_pdf_bytes = pdf_bytes source_type = "text" - if resolved_pdf_path: - source_type = "pdf_file" - elif resolved_pdf_bytes: - source_type = "pdf_bytes" - elif isinstance(source, bytes): - resolved_pdf_bytes = source - source_type = "pdf_bytes" - elif isinstance(source, Path): - resolved_pdf_path = str(source) - source_type = "pdf_file" - elif isinstance(source, str): - # Determine if string points to an existing file - p = Path(source) - if p.exists() and p.is_file(): - resolved_pdf_path = str(p) - source_type = "pdf_file" + if isinstance(source, str): + # Determine if string points to an existing file on disk + if len(source) < 300: + try: + p = Path(source) + if p.exists() and p.is_file(): + resolved_pdf_path = str(p) + source_type = "file" + else: + raw_text = source + except Exception: + raw_text = source else: raw_text = source - source_type = "text" + elif isinstance(source, bytes): + resolved_pdf_bytes = source + source_type = "file_bytes" + elif isinstance(source, Path): + resolved_pdf_path = str(source) + source_type = "file" + + if metadata and metadata.get("source_type"): + source_type = str(metadata["source_type"]) initial_state = create_initial_state( document_id=doc_id, raw_text=raw_text, pdf_path=resolved_pdf_path, pdf_bytes=resolved_pdf_bytes, + file_path=resolved_pdf_path, + file_bytes=resolved_pdf_bytes, source_type=source_type, metadata=metadata, ) diff --git a/src/medical_coding/retrieval/vector.py b/src/medical_coding/retrieval/vector.py index 1f0bc3a..9894a92 100644 --- a/src/medical_coding/retrieval/vector.py +++ b/src/medical_coding/retrieval/vector.py @@ -4,7 +4,13 @@ import json from pathlib import Path from typing import Any -import faiss +try: + import faiss + HAS_FAISS = True +except (ImportError, Exception): + faiss = None + HAS_FAISS = False + import numpy as np from medical_coding.models.base import BaseLocalEmbeddings @@ -17,7 +23,7 @@ logger = get_logger(__name__) class FAISSICDRetriever(BaseICDRetriever): - """Semantic vector retriever using local offline embeddings and FAISS IndexFlatIP.""" + """Semantic vector retriever using local offline embeddings and FAISS IndexFlatIP (with NumPy fallback).""" def __init__( self, @@ -26,13 +32,14 @@ class FAISSICDRetriever(BaseICDRetriever): ) -> None: self.embeddings = embeddings self.index_path = Path(index_path) if index_path else None - self._faiss_index: faiss.IndexFlatIP | None = None + self._faiss_index: Any = None + self._matrix: np.ndarray | None = None self._records: list[ICDCodeRecord] = [] self._dimension: int = 0 @property def is_indexed(self) -> bool: - return self._faiss_index is not None and len(self._records) > 0 + return (self._faiss_index is not None or self._matrix is not None) and len(self._records) > 0 def build_index(self, records: list[ICDCodeRecord], batch_size: int = 64) -> None: """Embed descriptions and build FAISS IndexFlatIP over authoritative records.""" @@ -51,41 +58,63 @@ class FAISSICDRetriever(BaseICDRetriever): matrix = np.array(all_embeddings, dtype=np.float32) # Ensure L2-normalized so inner product equals cosine similarity - faiss.normalize_L2(matrix) - + norms = np.linalg.norm(matrix, axis=1, keepdims=True) + norms[norms == 0] = 1.0 + matrix = matrix / norms self._dimension = matrix.shape[1] - self._faiss_index = faiss.IndexFlatIP(self._dimension) - self._faiss_index.add(matrix) + self._matrix = matrix - logger.info( - "Compiled FAISS IndexFlatIP with %d vectors (dimension %d).", - self._faiss_index.ntotal, - self._dimension, - ) + if HAS_FAISS and faiss is not None: + try: + faiss_mat = np.ascontiguousarray(matrix, dtype=np.float32) + self._faiss_index = faiss.IndexFlatIP(self._dimension) + self._faiss_index.add(faiss_mat) + logger.info( + "Compiled FAISS IndexFlatIP with %d vectors (dimension %d).", + self._faiss_index.ntotal, + self._dimension, + ) + except Exception as e: + logger.warning("FAISS indexing failed (%s), falling back to NumPy matrix.", e) + self._faiss_index = None + else: + logger.info("Using NumPy matrix vector index with %d vectors (dim %d).", len(matrix), self._dimension) def retrieve(self, query: str, top_k: int = 15) -> list[ICDCandidate]: - """Embed query and search nearest semantic neighbors in local FAISS index. + """Embed query and search nearest semantic neighbors in local FAISS or NumPy index. Scoring Calculation: Cosine similarity via L2-normalized Inner Product, clamped to [0.0, 1.0]. """ if not self.is_indexed: - raise RuntimeError("FAISS vector index has not been built or loaded.") + raise RuntimeError("FAISS/vector index has not been built or loaded.") normalized_query = normalize_clinical_query(query) if not normalized_query.strip(): return [] raw_vec = self.embeddings.embed_query(normalized_query) - query_matrix = np.array([raw_vec], dtype=np.float32) - faiss.normalize_L2(query_matrix) + q_vec = np.array(raw_vec, dtype=np.float32) + q_norm = np.linalg.norm(q_vec) + if q_norm > 0: + q_vec = q_vec / q_norm - assert self._faiss_index is not None k_search = min(top_k, len(self._records)) - distances, indices = self._faiss_index.search(query_matrix, k_search) + + if self._faiss_index is not None and HAS_FAISS and faiss is not None: + query_matrix = np.array([q_vec], dtype=np.float32) + distances, indices = self._faiss_index.search(query_matrix, k_search) + sim_scores = distances[0] + sim_indices = indices[0] + elif self._matrix is not None: + scores = np.dot(self._matrix, q_vec) + sim_indices = np.argsort(scores)[::-1][:k_search] + sim_scores = scores[sim_indices] + else: + return [] candidates: list[ICDCandidate] = [] - for sim, idx in zip(distances[0], indices[0], strict=False): + for sim, idx in zip(sim_scores, sim_indices, strict=False): if idx < 0 or idx >= len(self._records): continue @@ -98,7 +127,7 @@ class FAISSICDRetriever(BaseICDRetriever): code=record.code, description=record.description, retrieval_score=norm_sim, - retrieval_method="faiss", + retrieval_method="faiss" if self._faiss_index is not None else "vector_numpy", is_valid_billable=record.is_valid_billable, semantic_score=norm_sim, category=record.category, @@ -119,8 +148,10 @@ class FAISSICDRetriever(BaseICDRetriever): index_file = target_dir / "faiss.index" records_file = target_dir / "faiss_records.json" - assert self._faiss_index is not None - faiss.write_index(self._faiss_index, str(index_file)) + if self._faiss_index is not None and HAS_FAISS and faiss is not None: + faiss.write_index(self._faiss_index, str(index_file)) + elif self._matrix is not None: + np.save(target_dir / "embeddings_matrix.npy", self._matrix) metadata: dict[str, Any] = { "dimension": self._dimension, @@ -130,7 +161,7 @@ class FAISSICDRetriever(BaseICDRetriever): with open(records_file, "w", encoding="utf-8") as f: json.dump(metadata, f, indent=2) - logger.info("Saved FAISS index to %s and metadata to %s", index_file, records_file) + logger.info("Saved FAISS/vector index to %s and metadata to %s", target_dir, records_file) def load(self, index_dir: Path | str) -> None: """Load FAISS index and metadata from disk.""" @@ -138,21 +169,28 @@ class FAISSICDRetriever(BaseICDRetriever): index_file = target_dir / "faiss.index" records_file = target_dir / "faiss_records.json" - if not index_file.exists(): - raise FileNotFoundError(f"FAISS index file not found at {index_file}") if not records_file.exists(): raise FileNotFoundError(f"FAISS records metadata file not found at {records_file}") - self._faiss_index = faiss.read_index(str(index_file)) - self._dimension = self._faiss_index.d + if index_file.exists() and HAS_FAISS and faiss is not None: + try: + self._faiss_index = faiss.read_index(str(index_file)) + self._dimension = self._faiss_index.d + except Exception as e: + logger.warning("Failed to read FAISS binary index (%s). Checking matrix...", e) + self._faiss_index = None + + if self._faiss_index is None and (target_dir / "embeddings_matrix.npy").exists(): + self._matrix = np.load(target_dir / "embeddings_matrix.npy") + self._dimension = self._matrix.shape[1] with open(records_file, encoding="utf-8") as f: metadata = json.load(f) self._records = [ICDCodeRecord.model_validate(r) for r in metadata["records"]] logger.info( - "Loaded FAISS index from %s (%d vectors, dim %d)", - index_file, - self._faiss_index.ntotal, + "Loaded FAISS/vector index from %s (%d records, dim %d)", + index_dir, + len(self._records), self._dimension, ) diff --git a/src/medical_coding/ui/app.py b/src/medical_coding/ui/app.py index 082d801..b967e8d 100644 --- a/src/medical_coding/ui/app.py +++ b/src/medical_coding/ui/app.py @@ -58,15 +58,14 @@ st.markdown(get_css(), unsafe_allow_html=True) # Cached Singletons for Performance # ----------------------------------------------------------------------------- @st.cache_resource(show_spinner=False) -def get_cached_pipeline() -> MedicalCodingPipeline: +def get_cached_pipeline(version: str = "v3.2") -> MedicalCodingPipeline: """Return a cached singleton instance of the medical coding orchestrator.""" settings = get_settings() return MedicalCodingPipeline(settings=settings) -@st.cache_resource(show_spinner=False) def get_cached_repository() -> MedicalCodingRepository: - """Return a cached singleton instance of the database repository.""" + """Return an initialized instance of the database repository.""" init_db() return MedicalCodingRepository() @@ -271,8 +270,16 @@ with tab1: url_thread_id = st.query_params.get("thread_id") active_thread_id = st.session_state.get("active_thread_id") or url_thread_id - active_thread_record = repo.get_pipeline_thread(active_thread_id) if active_thread_id else None - recent_threads = repo.list_pipeline_threads(limit=20) + active_thread_record = ( + repo.get_pipeline_thread(active_thread_id) + if (active_thread_id and hasattr(repo, "get_pipeline_thread")) + else None + ) + recent_threads = ( + repo.list_pipeline_threads(limit=20) + if hasattr(repo, "list_pipeline_threads") + else [] + ) with st.container(): p_col1, p_col2, p_col3 = st.columns([3, 2, 1]) @@ -367,7 +374,7 @@ with tab1: ) if uploaded_file is not None: - active_file_bytes = uploaded_file.read() + active_file_bytes = uploaded_file.getvalue() active_filename = uploaded_file.name with st.spinner("🔍 Auto-detecting format and parsing clinical document..."): @@ -467,7 +474,12 @@ with tab1: ) if ingest_result.format != DocumentFormat.IMAGE: - clinical_text = st.text_area("Clinical Text Preview (Editable):", value=clinical_text, height=220) + clinical_text = st.text_area( + "Clinical Text Preview (Editable):", + value=clinical_text, + height=220, + key=f"txt_preview_{active_filename}", + ) elif input_mode == "✍️ Direct Manual Clinical Text Entry": clinical_text = st.text_area( @@ -1074,7 +1086,11 @@ with tab3: "Stored persistently in SQLite; ready for PostgreSQL migration without code changes." ) - all_threads_list = repo.list_pipeline_threads(limit=100) + all_threads_list = ( + repo.list_pipeline_threads(limit=100) + if hasattr(repo, "list_pipeline_threads") + else [] + ) total_th = len(all_threads_list) succ_th = sum(1 for t in all_threads_list if t.get("status") == "SUCCESS") fail_th = sum(1 for t in all_threads_list if t.get("status") == "FAILED") @@ -1140,7 +1156,11 @@ with tab3: selected_th_id = st.selectbox("Select Thread ID to Inspect:", th_ids, key="sel_th_inspect") if selected_th_id: - sel_thread = repo.get_pipeline_thread(selected_th_id) + sel_thread = ( + repo.get_pipeline_thread(selected_th_id) + if hasattr(repo, "get_pipeline_thread") + else None + ) if sel_thread: c_act1, c_act2, c_act3 = st.columns([2, 1, 1]) with c_act1: diff --git a/tests/conftest.py b/tests/conftest.py index a187f5d..1542248 100644 --- a/tests/conftest.py +++ b/tests/conftest.py @@ -1,8 +1,14 @@ """Pytest shared fixtures and test configuration.""" +import pandas as pd import pytest from fastapi.testclient import TestClient +try: + pd.set_option("future.infer_string", False) +except Exception: + pass + from medical_coding.api.app import create_app from medical_coding.config.settings import Settings from medical_coding.dataset.validator import LocalICDCatalog