fix(pipeline): resolve repo attribute error, fix txt file upload crash, and ensure dual-mode vector retrieval

This commit is contained in:
Abhinav Gupta
2026-10-03 11:37:28 +05:30
parent 240d14e6f6
commit c6c0cf477c
6 changed files with 178 additions and 87 deletions
+2 -2
View File
@@ -101,8 +101,8 @@ models/embeddings/*
!models/gguf/.gitkeep !models/gguf/.gitkeep
# Large External Datasets & User Uploads # Large External Datasets & User Uploads
Database/ /Database/
database/ /database/
*.xls *.xls
*.xlsx *.xlsx
data/icd10/*.txt data/icd10/*.txt
+22 -1
View File
@@ -5,6 +5,12 @@ from datetime import UTC, datetime
from typing import Any from typing import Any
import pandas as pd import pandas as pd
try:
pd.set_option("future.infer_string", False)
except Exception:
pass
from sqlalchemy import desc, func, or_, select from sqlalchemy import desc, func, or_, select
from sqlalchemy.orm import selectinload from sqlalchemy.orm import selectinload
@@ -380,7 +386,10 @@ class MedicalCodingRepository:
"created_at": d["created_at"], "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: def purge_all_documents(self) -> int:
"""Delete all documents (primarily used for test cleanup).""" """Delete all documents (primarily used for test cleanup)."""
@@ -548,6 +557,7 @@ class MedicalCodingRepository:
def get_pipeline_thread(self, thread_id: str) -> dict[str, Any] | None: def get_pipeline_thread(self, thread_id: str) -> dict[str, Any] | None:
"""Fetch a specific execution thread with its ordered steps and result.""" """Fetch a specific execution thread with its ordered steps and result."""
try:
with get_db_session() as session: with get_db_session() as session:
thread = session.execute( thread = session.execute(
select(PipelineThreadModel) select(PipelineThreadModel)
@@ -555,6 +565,9 @@ class MedicalCodingRepository:
.where(PipelineThreadModel.thread_id == thread_id) .where(PipelineThreadModel.thread_id == thread_id)
).scalar_one_or_none() ).scalar_one_or_none()
return thread.to_dict() if thread else 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( def list_pipeline_threads(
self, self,
@@ -562,6 +575,7 @@ class MedicalCodingRepository:
status: str | None = None, status: str | None = None,
) -> list[dict[str, Any]]: ) -> list[dict[str, Any]]:
"""List historical pipeline execution threads with optional status filtering.""" """List historical pipeline execution threads with optional status filtering."""
try:
with get_db_session() as session: with get_db_session() as session:
stmt = ( stmt = (
select(PipelineThreadModel) select(PipelineThreadModel)
@@ -574,9 +588,13 @@ class MedicalCodingRepository:
stmt = stmt.limit(limit) stmt = stmt.limit(limit)
threads = session.execute(stmt).scalars().all() threads = session.execute(stmt).scalars().all()
return [t.to_dict() for t in threads] 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: def get_latest_pipeline_thread(self) -> dict[str, Any] | None:
"""Fetch the most recent pipeline thread (running or finished).""" """Fetch the most recent pipeline thread (running or finished)."""
try:
with get_db_session() as session: with get_db_session() as session:
stmt = ( stmt = (
select(PipelineThreadModel) select(PipelineThreadModel)
@@ -586,6 +604,9 @@ class MedicalCodingRepository:
) )
thread = session.execute(stmt).scalar_one_or_none() thread = session.execute(stmt).scalar_one_or_none()
return thread.to_dict() if thread else 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: def delete_pipeline_thread(self, thread_id: str) -> bool:
"""Delete a thread and all associated step logs.""" """Delete a thread and all associated step logs."""
+20 -14
View File
@@ -130,31 +130,37 @@ async def process_clinical_document(
resolved_pdf_bytes = pdf_bytes resolved_pdf_bytes = pdf_bytes
source_type = "text" source_type = "text"
if resolved_pdf_path: if isinstance(source, str):
source_type = "pdf_file" # Determine if string points to an existing file on disk
elif resolved_pdf_bytes: if len(source) < 300:
source_type = "pdf_bytes" try:
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) p = Path(source)
if p.exists() and p.is_file(): if p.exists() and p.is_file():
resolved_pdf_path = str(p) resolved_pdf_path = str(p)
source_type = "pdf_file" source_type = "file"
else: else:
raw_text = source raw_text = source
source_type = "text" except Exception:
raw_text = source
else:
raw_text = source
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( initial_state = create_initial_state(
document_id=doc_id, document_id=doc_id,
raw_text=raw_text, raw_text=raw_text,
pdf_path=resolved_pdf_path, pdf_path=resolved_pdf_path,
pdf_bytes=resolved_pdf_bytes, pdf_bytes=resolved_pdf_bytes,
file_path=resolved_pdf_path,
file_bytes=resolved_pdf_bytes,
source_type=source_type, source_type=source_type,
metadata=metadata, metadata=metadata,
) )
+59 -21
View File
@@ -4,7 +4,13 @@ import json
from pathlib import Path from pathlib import Path
from typing import Any from typing import Any
try:
import faiss import faiss
HAS_FAISS = True
except (ImportError, Exception):
faiss = None
HAS_FAISS = False
import numpy as np import numpy as np
from medical_coding.models.base import BaseLocalEmbeddings from medical_coding.models.base import BaseLocalEmbeddings
@@ -17,7 +23,7 @@ logger = get_logger(__name__)
class FAISSICDRetriever(BaseICDRetriever): 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__( def __init__(
self, self,
@@ -26,13 +32,14 @@ class FAISSICDRetriever(BaseICDRetriever):
) -> None: ) -> None:
self.embeddings = embeddings self.embeddings = embeddings
self.index_path = Path(index_path) if index_path else None 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._records: list[ICDCodeRecord] = []
self._dimension: int = 0 self._dimension: int = 0
@property @property
def is_indexed(self) -> bool: 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: def build_index(self, records: list[ICDCodeRecord], batch_size: int = 64) -> None:
"""Embed descriptions and build FAISS IndexFlatIP over authoritative records.""" """Embed descriptions and build FAISS IndexFlatIP over authoritative records."""
@@ -51,41 +58,63 @@ class FAISSICDRetriever(BaseICDRetriever):
matrix = np.array(all_embeddings, dtype=np.float32) matrix = np.array(all_embeddings, dtype=np.float32)
# Ensure L2-normalized so inner product equals cosine similarity # 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._dimension = matrix.shape[1]
self._faiss_index = faiss.IndexFlatIP(self._dimension) self._matrix = matrix
self._faiss_index.add(matrix)
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( logger.info(
"Compiled FAISS IndexFlatIP with %d vectors (dimension %d).", "Compiled FAISS IndexFlatIP with %d vectors (dimension %d).",
self._faiss_index.ntotal, self._faiss_index.ntotal,
self._dimension, 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]: 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: Scoring Calculation:
Cosine similarity via L2-normalized Inner Product, clamped to [0.0, 1.0]. Cosine similarity via L2-normalized Inner Product, clamped to [0.0, 1.0].
""" """
if not self.is_indexed: 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) normalized_query = normalize_clinical_query(query)
if not normalized_query.strip(): if not normalized_query.strip():
return [] return []
raw_vec = self.embeddings.embed_query(normalized_query) raw_vec = self.embeddings.embed_query(normalized_query)
query_matrix = np.array([raw_vec], dtype=np.float32) q_vec = np.array(raw_vec, dtype=np.float32)
faiss.normalize_L2(query_matrix) 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)) k_search = min(top_k, len(self._records))
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) 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] = [] 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): if idx < 0 or idx >= len(self._records):
continue continue
@@ -98,7 +127,7 @@ class FAISSICDRetriever(BaseICDRetriever):
code=record.code, code=record.code,
description=record.description, description=record.description,
retrieval_score=norm_sim, 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, is_valid_billable=record.is_valid_billable,
semantic_score=norm_sim, semantic_score=norm_sim,
category=record.category, category=record.category,
@@ -119,8 +148,10 @@ class FAISSICDRetriever(BaseICDRetriever):
index_file = target_dir / "faiss.index" index_file = target_dir / "faiss.index"
records_file = target_dir / "faiss_records.json" records_file = target_dir / "faiss_records.json"
assert self._faiss_index is not None if self._faiss_index is not None and HAS_FAISS and faiss is not None:
faiss.write_index(self._faiss_index, str(index_file)) 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] = { metadata: dict[str, Any] = {
"dimension": self._dimension, "dimension": self._dimension,
@@ -130,7 +161,7 @@ class FAISSICDRetriever(BaseICDRetriever):
with open(records_file, "w", encoding="utf-8") as f: with open(records_file, "w", encoding="utf-8") as f:
json.dump(metadata, f, indent=2) 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: def load(self, index_dir: Path | str) -> None:
"""Load FAISS index and metadata from disk.""" """Load FAISS index and metadata from disk."""
@@ -138,21 +169,28 @@ class FAISSICDRetriever(BaseICDRetriever):
index_file = target_dir / "faiss.index" index_file = target_dir / "faiss.index"
records_file = target_dir / "faiss_records.json" 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(): if not records_file.exists():
raise FileNotFoundError(f"FAISS records metadata file not found at {records_file}") raise FileNotFoundError(f"FAISS records metadata file not found at {records_file}")
if index_file.exists() and HAS_FAISS and faiss is not None:
try:
self._faiss_index = faiss.read_index(str(index_file)) self._faiss_index = faiss.read_index(str(index_file))
self._dimension = self._faiss_index.d 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: with open(records_file, encoding="utf-8") as f:
metadata = json.load(f) metadata = json.load(f)
self._records = [ICDCodeRecord.model_validate(r) for r in metadata["records"]] self._records = [ICDCodeRecord.model_validate(r) for r in metadata["records"]]
logger.info( logger.info(
"Loaded FAISS index from %s (%d vectors, dim %d)", "Loaded FAISS/vector index from %s (%d records, dim %d)",
index_file, index_dir,
self._faiss_index.ntotal, len(self._records),
self._dimension, self._dimension,
) )
+29 -9
View File
@@ -58,15 +58,14 @@ st.markdown(get_css(), unsafe_allow_html=True)
# Cached Singletons for Performance # Cached Singletons for Performance
# ----------------------------------------------------------------------------- # -----------------------------------------------------------------------------
@st.cache_resource(show_spinner=False) @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.""" """Return a cached singleton instance of the medical coding orchestrator."""
settings = get_settings() settings = get_settings()
return MedicalCodingPipeline(settings=settings) return MedicalCodingPipeline(settings=settings)
@st.cache_resource(show_spinner=False)
def get_cached_repository() -> MedicalCodingRepository: def get_cached_repository() -> MedicalCodingRepository:
"""Return a cached singleton instance of the database repository.""" """Return an initialized instance of the database repository."""
init_db() init_db()
return MedicalCodingRepository() return MedicalCodingRepository()
@@ -271,8 +270,16 @@ with tab1:
url_thread_id = st.query_params.get("thread_id") 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_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 active_thread_record = (
recent_threads = repo.list_pipeline_threads(limit=20) 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(): with st.container():
p_col1, p_col2, p_col3 = st.columns([3, 2, 1]) p_col1, p_col2, p_col3 = st.columns([3, 2, 1])
@@ -367,7 +374,7 @@ with tab1:
) )
if uploaded_file is not None: if uploaded_file is not None:
active_file_bytes = uploaded_file.read() active_file_bytes = uploaded_file.getvalue()
active_filename = uploaded_file.name active_filename = uploaded_file.name
with st.spinner("🔍 Auto-detecting format and parsing clinical document..."): with st.spinner("🔍 Auto-detecting format and parsing clinical document..."):
@@ -467,7 +474,12 @@ with tab1:
) )
if ingest_result.format != DocumentFormat.IMAGE: 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": elif input_mode == "✍️ Direct Manual Clinical Text Entry":
clinical_text = st.text_area( clinical_text = st.text_area(
@@ -1074,7 +1086,11 @@ with tab3:
"Stored persistently in SQLite; ready for PostgreSQL migration without code changes." "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) total_th = len(all_threads_list)
succ_th = sum(1 for t in all_threads_list if t.get("status") == "SUCCESS") 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") 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") selected_th_id = st.selectbox("Select Thread ID to Inspect:", th_ids, key="sel_th_inspect")
if selected_th_id: 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: if sel_thread:
c_act1, c_act2, c_act3 = st.columns([2, 1, 1]) c_act1, c_act2, c_act3 = st.columns([2, 1, 1])
with c_act1: with c_act1:
+6
View File
@@ -1,8 +1,14 @@
"""Pytest shared fixtures and test configuration.""" """Pytest shared fixtures and test configuration."""
import pandas as pd
import pytest import pytest
from fastapi.testclient import TestClient 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.api.app import create_app
from medical_coding.config.settings import Settings from medical_coding.config.settings import Settings
from medical_coding.dataset.validator import LocalICDCatalog from medical_coding.dataset.validator import LocalICDCatalog