import os import re import json import time import uuid import glob import psutil import hashlib from collections import OrderedDict import faiss import gradio as gr from datetime import datetime from sentence_transformers import SentenceTransformer from transformers import pipeline os.makedirs("runtime_logs", exist_ok=True) os.makedirs("runtime_cache", exist_ok=True) REQUEST_LOG_PATH = "runtime_logs/request_logs.jsonl" ERROR_LOG_PATH = "runtime_logs/error_logs.jsonl" RETRIEVAL_CACHE_SIZE = int(os.getenv("RETRIEVAL_CACHE_SIZE", "256")) GENERATION_CACHE_SIZE = int(os.getenv("GENERATION_CACHE_SIZE", "128")) # IMPORTANT: default off because retry makes Phi-4 much slower on Hugging Face CPU ENABLE_REPAIR_RETRY = os.getenv("ENABLE_REPAIR_RETRY", "0") == "1" RETRIEVAL_CACHE = OrderedDict() GENERATION_CACHE = OrderedDict() PIPELINE_METRICS = { "retrieval_cache_hits": 0, "retrieval_cache_misses": 0, "generation_cache_hits": 0, "generation_cache_misses": 0, "repair_attempts": 0, } def make_cache_key(*parts): payload = json.dumps(parts, sort_keys=True, default=str) return hashlib.sha256(payload.encode("utf-8")).hexdigest() def lru_get(cache, key): if key not in cache: return None value = cache.pop(key) cache[key] = value return value def lru_set(cache, key, value, max_size): if key in cache: cache.pop(key) cache[key] = value while len(cache) > max_size: cache.popitem(last=False) def append_jsonl(path, record): with open(path, "a", encoding="utf-8") as f: f.write(json.dumps(record) + "\n") def get_system_snapshot(): process = psutil.Process(os.getpid()) return { "cpu_percent": psutil.cpu_percent(interval=0.1), "memory_mb": round(process.memory_info().rss / (1024 * 1024), 2) } def chunk_text(text, chunk_size=450, overlap=75): text = text.strip() if not text: return [] chunks = [] start = 0 while start < len(text): end = min(start + chunk_size, len(text)) chunks.append(text[start:end]) if end == len(text): break start += chunk_size - overlap return chunks def validate_input(transcript): if transcript is None or not transcript.strip(): return False, "Empty transcript provided." lowered = transcript.lower() blocked_patterns = [ "ignore previous instructions", "reveal system prompt", "show api key", "print environment variables", "bypass safety" ] for pat in blocked_patterns: if pat in lowered: return False, "Transcript blocked by input validation." return True, "" def apply_output_filter(text): if text is None: return "" redactions = [ r"api[_ -]?key\s*[:=]\s*\S+", r"secret\s*[:=]\s*\S+", r"token\s*[:=]\s*\S+" ] cleaned = text for pat in redactions: cleaned = re.sub(pat, "[REDACTED]", cleaned, flags=re.IGNORECASE) return cleaned.strip() def load_documents(): docs = [] for path in glob.glob("data/knowledge_base/*.txt"): text = "" try: with open(path, "r", encoding="utf-8", errors="ignore") as f: text = f.read().strip() except UnicodeDecodeError: with open(path, "r", encoding="latin-1", errors="ignore") as f: text = f.read().strip() except Exception as exc: print(f"Skipping file due to read error: {path} | {exc}") continue if text: docs.append({ "source": path, "text": text }) print(f"Loaded documents: {len(docs)}") return docs documents = load_documents() embed_model = SentenceTransformer("sentence-transformers/all-MiniLM-L6-v2") generator = pipeline( "text-generation", model="microsoft/Phi-4-mini-instruct", device_map="auto", torch_dtype="auto" ) all_chunks = [] metadata = [] for doc in documents: chunks = chunk_text(doc["text"], chunk_size=450, overlap=75) for i, chunk in enumerate(chunks): all_chunks.append(chunk) metadata.append({ "source": doc["source"], "chunk_id": i, "text": chunk }) if all_chunks: embeddings = embed_model.encode( all_chunks, convert_to_numpy=True, normalize_embeddings=True ).astype("float32") dimension = embeddings.shape[1] index = faiss.IndexFlatIP(dimension) index.add(embeddings) print(f"Chunks created: {len(all_chunks)}") print("FAISS index built successfully") else: index = None print("No knowledge base chunks found. Retrieval will be skipped.") def retrieve_context(query, top_k=2): if index is None or not metadata: return [] cache_key = make_cache_key("retrieve_context", query, top_k) cached = lru_get(RETRIEVAL_CACHE, cache_key) if cached is not None: PIPELINE_METRICS["retrieval_cache_hits"] += 1 return [item.copy() for item in cached] PIPELINE_METRICS["retrieval_cache_misses"] += 1 query_embedding = embed_model.encode( [query], convert_to_numpy=True, normalize_embeddings=True ).astype("float32") k = min(top_k, len(metadata)) scores, indices = index.search(query_embedding, k) results = [] for score, idx in zip(scores[0], indices[0]): if idx != -1: item = metadata[idx].copy() item["score"] = float(score) results.append(item) lru_set(RETRIEVAL_CACHE, cache_key, [item.copy() for item in results], RETRIEVAL_CACHE_SIZE) return results def build_prompt(transcript, retrieved_chunks): context_text = "\n\n".join( [f"Source: {c['source']}\n{c['text'][:700]}" for c in retrieved_chunks] ) if not context_text.strip(): context_text = "No supporting context retrieved." prompt = f""" Convert the doctor-patient conversation into a structured SOAP note for a gastroenterology visit. Rules: - Use the transcript as the main source of truth. - Use retrieved context only as supporting information. - Do not repeat the transcript. - Do not output instructions. - Keep the answer concise. - If a detail is missing, write "Not stated". - Return only the final structured SOAP note. Transcript: {transcript} Retrieved context: {context_text} Required output format: SOAP NOTE Subjective: - Chief complaint: - History of present illness: - Associated symptoms: - Relevant negatives: Objective: - Exam findings: - Diagnostic information: Assessment: - Most likely diagnosis: - Differential diagnosis: Plan: - Medications: - Tests/Workup: - Lifestyle recommendations: - Follow-up / return precautions: ICD SUGGESTIONS: - ICD-10: CLINICAL REASONING: - """.strip() return prompt def clean_generated_text(text): if not text: return "" text = text.strip() if "SOAP NOTE" in text: text = text[text.index("SOAP NOTE"):].strip() stop_markers = [ "\nTranscript:", "\nRetrieved context:", "\nRetrieved Context:", "\nDoctor:", "\nPatient:" ] positions = [text.find(marker) for marker in stop_markers if marker in text] if positions: text = text[:min(positions)].strip() return text.strip() def looks_incomplete_note(text): if not text or not text.strip(): return True required_sections = [ "SOAP NOTE", "Subjective:", "Objective:", "Assessment:", "Plan:", "ICD SUGGESTIONS:" ] return any(section not in text for section in required_sections) def generate_llm_output(prompt, max_new_tokens=350): def _run_generation(prompt_text, token_limit=max_new_tokens): messages = [ { "role": "system", "content": ( "You are a careful gastroenterology clinical documentation assistant. " "Return only a concise structured SOAP note with ICD suggestions. " "Do not repeat the transcript. " "Do not repeat instructions." ) }, { "role": "user", "content": prompt_text } ] formatted_prompt = generator.tokenizer.apply_chat_template( messages, tokenize=False, add_generation_prompt=True ) result = generator( formatted_prompt, max_new_tokens=token_limit, do_sample=False, return_full_text=False, pad_token_id=generator.tokenizer.eos_token_id ) text = result[0]["generated_text"].strip() return clean_generated_text(text) cache_key = make_cache_key("generate_llm_output", prompt, max_new_tokens) cached = lru_get(GENERATION_CACHE, cache_key) if cached is not None: PIPELINE_METRICS["generation_cache_hits"] += 1 return apply_output_filter(cached) PIPELINE_METRICS["generation_cache_misses"] += 1 text = _run_generation(prompt, token_limit=max_new_tokens) if ENABLE_REPAIR_RETRY and looks_incomplete_note(text): PIPELINE_METRICS["repair_attempts"] += 1 repair_prompt = ( prompt + "\n\nRewrite the answer once more. Keep it concise. " + "Do not repeat the transcript. Fill all SOAP sections." ) repaired = _run_generation(repair_prompt, token_limit=350) if repaired and not looks_incomplete_note(repaired): text = repaired lru_set(GENERATION_CACHE, cache_key, text, GENERATION_CACHE_SIZE) return apply_output_filter(text) def run_app(transcript): request_id = str(uuid.uuid4()) started = time.time() append_jsonl(REQUEST_LOG_PATH, { "request_id": request_id, "timestamp": datetime.utcnow().isoformat(), "status": "started", "transcript_chars": len(transcript or "") }) is_valid, validation_message = validate_input(transcript) if not is_valid: system_snapshot = get_system_snapshot() append_jsonl(ERROR_LOG_PATH, { "request_id": request_id, "timestamp": datetime.utcnow().isoformat(), "error": validation_message }) append_jsonl(REQUEST_LOG_PATH, { "request_id": request_id, "timestamp": datetime.utcnow().isoformat(), "status": "blocked", "latency_seconds": round(time.time() - started, 3), "transcript_chars": len(transcript or ""), "retrieved_chunk_count": 0, "cpu_percent": system_snapshot["cpu_percent"], "memory_mb": system_snapshot["memory_mb"] }) return validation_message, "", "", f"Request ID: {request_id}\nStatus: blocked" try: retrieved = retrieve_context(transcript, top_k=2) prompt = build_prompt(transcript, retrieved) response = generate_llm_output(prompt, max_new_tokens=350) retrieved_text = "" sources = set() for i, item in enumerate(retrieved, start=1): sources.add(os.path.basename(item["source"])) retrieved_text += ( f"Chunk {i}\n" f"Source: {item['source']}\n" f"Score: {item['score']:.3f}\n" f"{item['text']}\n\n" f"{'-' * 60}\n\n" ) if not retrieved_text: retrieved_text = "No context retrieved." source_text = "Top Retrieved Sources:\n" if sources: for s in sorted(sources): source_text += f"- {s}\n" else: source_text += "- None\n" latency = round(time.time() - started, 3) system_snapshot = get_system_snapshot() append_jsonl(REQUEST_LOG_PATH, { "request_id": request_id, "timestamp": datetime.utcnow().isoformat(), "status": "completed", "latency_seconds": latency, "transcript_chars": len(transcript or ""), "retrieved_chunk_count": len(retrieved), "cpu_percent": system_snapshot["cpu_percent"], "memory_mb": system_snapshot["memory_mb"] }) metrics_text = ( f"Request ID: {request_id}\n" f"Status: completed\n" f"Latency (s): {latency}\n" f"Retrieved Chunks: {len(retrieved)}\n" f"Retrieval Cache Hits: {PIPELINE_METRICS['retrieval_cache_hits']}\n" f"Generation Cache Hits: {PIPELINE_METRICS['generation_cache_hits']}\n" f"Repair Attempts: {PIPELINE_METRICS['repair_attempts']}\n" f"CPU %: {system_snapshot['cpu_percent']}\n" f"Memory (MB): {system_snapshot['memory_mb']}" ) return response, retrieved_text, source_text, metrics_text except Exception as e: latency = round(time.time() - started, 3) system_snapshot = get_system_snapshot() append_jsonl(ERROR_LOG_PATH, { "request_id": request_id, "timestamp": datetime.utcnow().isoformat(), "error": str(e) }) append_jsonl(REQUEST_LOG_PATH, { "request_id": request_id, "timestamp": datetime.utcnow().isoformat(), "status": "failed", "latency_seconds": latency, "transcript_chars": len(transcript or ""), "retrieved_chunk_count": 0, "cpu_percent": system_snapshot["cpu_percent"], "memory_mb": system_snapshot["memory_mb"] }) return ( "System failed safely while processing the transcript.", "", "", f"Request ID: {request_id}\nStatus: failed\nError: {str(e)}" ) demo = gr.Interface( fn=run_app, inputs=gr.Textbox( lines=18, label="Doctor-Patient Transcript", placeholder="Paste the full doctor-patient transcript here..." ), outputs=[ gr.Textbox(lines=20, label="SOAP + ICD Output"), gr.Textbox(lines=12, label="Retrieved Context"), gr.Textbox(lines=4, label="Top Retrieved Sources"), gr.Textbox(lines=8, label="Runtime Metrics") ], title="NexScribe - Hosted Deploy & Test Demo", description="Hosted NexScribe demo with retrieval, SOAP note generation, request monitoring, and runtime observability." ) demo.launch()