Upload 5 files
Browse files- README.md +24 -0
- app.py +457 -0
- cost_performance_tradeoffs.md +24 -0
- projected_system_costs.csv +5 -0
- requirements.txt +9 -0
README.md
ADDED
|
@@ -0,0 +1,24 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
---
|
| 2 |
+
title: NexScribe Deploy Test
|
| 3 |
+
emoji: π©Ί
|
| 4 |
+
colorFrom: blue
|
| 5 |
+
colorTo: indigo
|
| 6 |
+
sdk: gradio
|
| 7 |
+
sdk_version: 5.25.2
|
| 8 |
+
app_file: app.py
|
| 9 |
+
pinned: false
|
| 10 |
+
---
|
| 11 |
+
|
| 12 |
+
# NexScribe - Deploy & Test
|
| 13 |
+
|
| 14 |
+
This Space hosts the deployed NexScribe clinical documentation assistant.
|
| 15 |
+
|
| 16 |
+
Features:
|
| 17 |
+
- transcript-to-SOAP generation
|
| 18 |
+
- GI knowledge-base retrieval
|
| 19 |
+
- runtime monitoring and JSONL logging
|
| 20 |
+
- request tracing and observability metrics
|
| 21 |
+
- safe failure behavior for blocked or invalid input
|
| 22 |
+
|
| 23 |
+
Upload the GI knowledge-base `.txt` files into:
|
| 24 |
+
`data/knowledge_base/`
|
app.py
ADDED
|
@@ -0,0 +1,457 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
|
| 2 |
+
import os
|
| 3 |
+
import re
|
| 4 |
+
import json
|
| 5 |
+
import time
|
| 6 |
+
import uuid
|
| 7 |
+
import glob
|
| 8 |
+
import psutil
|
| 9 |
+
import hashlib
|
| 10 |
+
from collections import OrderedDict
|
| 11 |
+
import numpy as np
|
| 12 |
+
import faiss
|
| 13 |
+
import gradio as gr
|
| 14 |
+
from datetime import datetime
|
| 15 |
+
from sentence_transformers import SentenceTransformer
|
| 16 |
+
from transformers import pipeline
|
| 17 |
+
|
| 18 |
+
os.makedirs("runtime_logs", exist_ok=True)
|
| 19 |
+
os.makedirs("runtime_cache", exist_ok=True)
|
| 20 |
+
|
| 21 |
+
REQUEST_LOG_PATH = "runtime_logs/request_logs.jsonl"
|
| 22 |
+
ERROR_LOG_PATH = "runtime_logs/error_logs.jsonl"
|
| 23 |
+
|
| 24 |
+
RETRIEVAL_CACHE_SIZE = int(os.getenv("RETRIEVAL_CACHE_SIZE", "256"))
|
| 25 |
+
GENERATION_CACHE_SIZE = int(os.getenv("GENERATION_CACHE_SIZE", "128"))
|
| 26 |
+
ENABLE_REPAIR_RETRY = os.getenv("ENABLE_REPAIR_RETRY", "1") == "1"
|
| 27 |
+
|
| 28 |
+
RETRIEVAL_CACHE = OrderedDict()
|
| 29 |
+
GENERATION_CACHE = OrderedDict()
|
| 30 |
+
PIPELINE_METRICS = {
|
| 31 |
+
"retrieval_cache_hits": 0,
|
| 32 |
+
"retrieval_cache_misses": 0,
|
| 33 |
+
"generation_cache_hits": 0,
|
| 34 |
+
"generation_cache_misses": 0,
|
| 35 |
+
"repair_attempts": 0,
|
| 36 |
+
}
|
| 37 |
+
|
| 38 |
+
def make_cache_key(*parts):
|
| 39 |
+
payload = json.dumps(parts, sort_keys=True, default=str)
|
| 40 |
+
return hashlib.sha256(payload.encode("utf-8")).hexdigest()
|
| 41 |
+
|
| 42 |
+
def lru_get(cache, key):
|
| 43 |
+
if key not in cache:
|
| 44 |
+
return None
|
| 45 |
+
value = cache.pop(key)
|
| 46 |
+
cache[key] = value
|
| 47 |
+
return value
|
| 48 |
+
|
| 49 |
+
def lru_set(cache, key, value, max_size):
|
| 50 |
+
if key in cache:
|
| 51 |
+
cache.pop(key)
|
| 52 |
+
cache[key] = value
|
| 53 |
+
while len(cache) > max_size:
|
| 54 |
+
cache.popitem(last=False)
|
| 55 |
+
|
| 56 |
+
def append_jsonl(path, record):
|
| 57 |
+
with open(path, "a", encoding="utf-8") as f:
|
| 58 |
+
f.write(json.dumps(record) + "\n")
|
| 59 |
+
|
| 60 |
+
def get_system_snapshot():
|
| 61 |
+
process = psutil.Process(os.getpid())
|
| 62 |
+
return {
|
| 63 |
+
"cpu_percent": psutil.cpu_percent(interval=0.1),
|
| 64 |
+
"memory_mb": round(process.memory_info().rss / (1024 * 1024), 2)
|
| 65 |
+
}
|
| 66 |
+
|
| 67 |
+
def chunk_text(text, chunk_size=500, overlap=100):
|
| 68 |
+
text = text.strip()
|
| 69 |
+
if not text:
|
| 70 |
+
return []
|
| 71 |
+
chunks = []
|
| 72 |
+
start = 0
|
| 73 |
+
while start < len(text):
|
| 74 |
+
end = min(start + chunk_size, len(text))
|
| 75 |
+
chunks.append(text[start:end])
|
| 76 |
+
if end == len(text):
|
| 77 |
+
break
|
| 78 |
+
start += chunk_size - overlap
|
| 79 |
+
return chunks
|
| 80 |
+
|
| 81 |
+
def validate_input(transcript):
|
| 82 |
+
if transcript is None or not transcript.strip():
|
| 83 |
+
return False, "Empty transcript provided."
|
| 84 |
+
lowered = transcript.lower()
|
| 85 |
+
blocked_patterns = [
|
| 86 |
+
"ignore previous instructions",
|
| 87 |
+
"reveal system prompt",
|
| 88 |
+
"show api key",
|
| 89 |
+
"print environment variables",
|
| 90 |
+
"bypass safety"
|
| 91 |
+
]
|
| 92 |
+
for pat in blocked_patterns:
|
| 93 |
+
if pat in lowered:
|
| 94 |
+
return False, "Transcript blocked by input validation."
|
| 95 |
+
return True, ""
|
| 96 |
+
|
| 97 |
+
def apply_output_filter(text):
|
| 98 |
+
if text is None:
|
| 99 |
+
return ""
|
| 100 |
+
redactions = [
|
| 101 |
+
r"api[_ -]?key\s*[:=]\s*\S+",
|
| 102 |
+
r"secret\s*[:=]\s*\S+",
|
| 103 |
+
r"token\s*[:=]\s*\S+"
|
| 104 |
+
]
|
| 105 |
+
cleaned = text
|
| 106 |
+
for pat in redactions:
|
| 107 |
+
cleaned = re.sub(pat, "[REDACTED]", cleaned, flags=re.IGNORECASE)
|
| 108 |
+
return cleaned
|
| 109 |
+
|
| 110 |
+
def load_documents():
|
| 111 |
+
docs = []
|
| 112 |
+
for path in glob.glob("data/knowledge_base/*.txt"):
|
| 113 |
+
with open(path, "r", encoding="utf-8") as f:
|
| 114 |
+
docs.append({
|
| 115 |
+
"source": path,
|
| 116 |
+
"text": f.read()
|
| 117 |
+
})
|
| 118 |
+
return docs
|
| 119 |
+
|
| 120 |
+
documents = load_documents()
|
| 121 |
+
embed_model = SentenceTransformer("sentence-transformers/all-MiniLM-L6-v2")
|
| 122 |
+
|
| 123 |
+
model_kwargs = {}
|
| 124 |
+
if os.getenv("USE_4BIT", "0") == "1":
|
| 125 |
+
try:
|
| 126 |
+
from transformers import BitsAndBytesConfig
|
| 127 |
+
model_kwargs["quantization_config"] = BitsAndBytesConfig(
|
| 128 |
+
load_in_4bit=True,
|
| 129 |
+
bnb_4bit_quant_type="nf4",
|
| 130 |
+
bnb_4bit_compute_dtype="float16",
|
| 131 |
+
bnb_4bit_use_double_quant=True,
|
| 132 |
+
)
|
| 133 |
+
print("4-bit quantization enabled for model loading.")
|
| 134 |
+
except Exception as exc:
|
| 135 |
+
print("4-bit quantization requested but unavailable; using default model loading:", exc)
|
| 136 |
+
|
| 137 |
+
generator = pipeline(
|
| 138 |
+
"text-generation",
|
| 139 |
+
model="microsoft/Phi-4-mini-instruct",
|
| 140 |
+
device_map="auto",
|
| 141 |
+
model_kwargs=model_kwargs
|
| 142 |
+
)
|
| 143 |
+
|
| 144 |
+
all_chunks = []
|
| 145 |
+
metadata = []
|
| 146 |
+
|
| 147 |
+
for doc in documents:
|
| 148 |
+
chunks = chunk_text(doc["text"], chunk_size=500, overlap=100)
|
| 149 |
+
for i, chunk in enumerate(chunks):
|
| 150 |
+
all_chunks.append(chunk)
|
| 151 |
+
metadata.append({
|
| 152 |
+
"source": doc["source"],
|
| 153 |
+
"chunk_id": i,
|
| 154 |
+
"text": chunk
|
| 155 |
+
})
|
| 156 |
+
|
| 157 |
+
embeddings = embed_model.encode(
|
| 158 |
+
all_chunks,
|
| 159 |
+
convert_to_numpy=True,
|
| 160 |
+
normalize_embeddings=True
|
| 161 |
+
).astype("float32")
|
| 162 |
+
|
| 163 |
+
dimension = embeddings.shape[1]
|
| 164 |
+
index = faiss.IndexFlatIP(dimension)
|
| 165 |
+
index.add(embeddings)
|
| 166 |
+
|
| 167 |
+
def retrieve_context(query, top_k=3):
|
| 168 |
+
cache_key = make_cache_key("retrieve_context", query, top_k)
|
| 169 |
+
cached = lru_get(RETRIEVAL_CACHE, cache_key)
|
| 170 |
+
if cached is not None:
|
| 171 |
+
PIPELINE_METRICS["retrieval_cache_hits"] += 1
|
| 172 |
+
return [item.copy() for item in cached]
|
| 173 |
+
|
| 174 |
+
PIPELINE_METRICS["retrieval_cache_misses"] += 1
|
| 175 |
+
query_embedding = embed_model.encode(
|
| 176 |
+
[query],
|
| 177 |
+
convert_to_numpy=True,
|
| 178 |
+
normalize_embeddings=True
|
| 179 |
+
).astype("float32")
|
| 180 |
+
|
| 181 |
+
scores, indices = index.search(query_embedding, top_k)
|
| 182 |
+
results = []
|
| 183 |
+
|
| 184 |
+
for score, idx in zip(scores[0], indices[0]):
|
| 185 |
+
if idx != -1:
|
| 186 |
+
item = metadata[idx].copy()
|
| 187 |
+
item["score"] = float(score)
|
| 188 |
+
results.append(item)
|
| 189 |
+
|
| 190 |
+
lru_set(RETRIEVAL_CACHE, cache_key, [item.copy() for item in results], RETRIEVAL_CACHE_SIZE)
|
| 191 |
+
return results
|
| 192 |
+
|
| 193 |
+
def build_prompt(transcript, retrieved_chunks):
|
| 194 |
+
context_text = "\n\n".join(
|
| 195 |
+
[f"Source: {c['source']}\n{c['text']}" for c in retrieved_chunks]
|
| 196 |
+
)
|
| 197 |
+
|
| 198 |
+
prompt = f"""
|
| 199 |
+
Convert the following doctor-patient conversation into a structured SOAP note for a gastroenterology visit.
|
| 200 |
+
|
| 201 |
+
Use the transcript as the main source of truth.
|
| 202 |
+
Use the retrieved context only as supporting information.
|
| 203 |
+
Do not repeat the transcript verbatim.
|
| 204 |
+
Do not output instructions.
|
| 205 |
+
Return only the final structured answer.
|
| 206 |
+
|
| 207 |
+
Critical formatting rules:
|
| 208 |
+
- Every bullet must contain actual patient-specific content after the colon.
|
| 209 |
+
- Never leave a bullet blank.
|
| 210 |
+
- Never output placeholders such as "CODE - Diagnosis" or "2 to 4 concise clinical sentences".
|
| 211 |
+
- If a detail is missing, write "Not stated".
|
| 212 |
+
- Use concise clinical language.
|
| 213 |
+
|
| 214 |
+
Transcript:
|
| 215 |
+
{transcript}
|
| 216 |
+
|
| 217 |
+
Retrieved context:
|
| 218 |
+
{context_text}
|
| 219 |
+
|
| 220 |
+
Required output format:
|
| 221 |
+
|
| 222 |
+
SOAP NOTE
|
| 223 |
+
|
| 224 |
+
Subjective:
|
| 225 |
+
- Chief complaint: <fill with patient-specific content>
|
| 226 |
+
- History of present illness: <fill with patient-specific content>
|
| 227 |
+
- Associated symptoms: <fill with patient-specific content>
|
| 228 |
+
- Relevant negatives: <fill with patient-specific content>
|
| 229 |
+
- Medication/risk factors: <fill with patient-specific content>
|
| 230 |
+
|
| 231 |
+
Objective:
|
| 232 |
+
- Exam findings: <fill with patient-specific content or "Not provided" if not mentioned>
|
| 233 |
+
- Diagnostic information: <fill with patient-specific content or "Not provided" if not mentioned>
|
| 234 |
+
|
| 235 |
+
Assessment:
|
| 236 |
+
- Most likely diagnosis: <fill with patient-specific content>
|
| 237 |
+
- Differential diagnosis: <fill with patient-specific content>
|
| 238 |
+
|
| 239 |
+
Plan:
|
| 240 |
+
- Medications: <fill with patient-specific content>
|
| 241 |
+
- Tests/Workup: <fill with patient-specific content>
|
| 242 |
+
- Lifestyle recommendations: <fill with patient-specific content>
|
| 243 |
+
- Follow-up / return precautions: <fill with patient-specific content>
|
| 244 |
+
|
| 245 |
+
ICD SUGGESTIONS:
|
| 246 |
+
- <ICD code> - <diagnosis>
|
| 247 |
+
- <ICD code> - <diagnosis or Not stated>
|
| 248 |
+
|
| 249 |
+
CLINICAL REASONING:
|
| 250 |
+
- Write 2 to 4 concise clinical sentences based on the transcript and context.
|
| 251 |
+
""".strip()
|
| 252 |
+
|
| 253 |
+
return prompt
|
| 254 |
+
|
| 255 |
+
def looks_incomplete_note(text):
|
| 256 |
+
if not text or not text.strip():
|
| 257 |
+
return True
|
| 258 |
+
placeholder_patterns = [
|
| 259 |
+
"- Chief complaint:",
|
| 260 |
+
"- History of present illness:",
|
| 261 |
+
"- Associated symptoms:",
|
| 262 |
+
"- Relevant negatives:",
|
| 263 |
+
"- Medication/risk factors:",
|
| 264 |
+
"- Most likely diagnosis:",
|
| 265 |
+
"- Differential diagnosis:",
|
| 266 |
+
"- Medications:",
|
| 267 |
+
"- Tests/Workup:",
|
| 268 |
+
"- Lifestyle recommendations:",
|
| 269 |
+
"- Follow-up / return precautions:",
|
| 270 |
+
"- CODE - Diagnosis",
|
| 271 |
+
"- 2 to 4 concise clinical sentences"
|
| 272 |
+
]
|
| 273 |
+
return any(pattern in text for pattern in placeholder_patterns)
|
| 274 |
+
|
| 275 |
+
def generate_llm_output(prompt, max_new_tokens=450):
|
| 276 |
+
def _run_generation(prompt_text, token_limit=max_new_tokens):
|
| 277 |
+
messages = [
|
| 278 |
+
{
|
| 279 |
+
"role": "system",
|
| 280 |
+
"content": (
|
| 281 |
+
"You are a careful gastroenterology clinical documentation assistant. "
|
| 282 |
+
"Always return only a structured SOAP note with ICD suggestions. "
|
| 283 |
+
"Do not repeat the transcript. Do not repeat instructions. "
|
| 284 |
+
"Fill every section with patient-specific content. "
|
| 285 |
+
"If information is missing, say 'Not stated'."
|
| 286 |
+
)
|
| 287 |
+
},
|
| 288 |
+
{
|
| 289 |
+
"role": "user",
|
| 290 |
+
"content": prompt_text
|
| 291 |
+
}
|
| 292 |
+
]
|
| 293 |
+
|
| 294 |
+
formatted_prompt = generator.tokenizer.apply_chat_template(
|
| 295 |
+
messages,
|
| 296 |
+
tokenize=False,
|
| 297 |
+
add_generation_prompt=True
|
| 298 |
+
)
|
| 299 |
+
|
| 300 |
+
text = generator(
|
| 301 |
+
formatted_prompt,
|
| 302 |
+
max_new_tokens=token_limit,
|
| 303 |
+
do_sample=False,
|
| 304 |
+
return_full_text=False
|
| 305 |
+
)[0]["generated_text"].strip()
|
| 306 |
+
|
| 307 |
+
if "SOAP NOTE" in text:
|
| 308 |
+
text = text[text.index("SOAP NOTE"):].strip()
|
| 309 |
+
|
| 310 |
+
return text
|
| 311 |
+
|
| 312 |
+
cache_key = make_cache_key("generate_llm_output", prompt, max_new_tokens)
|
| 313 |
+
cached = lru_get(GENERATION_CACHE, cache_key)
|
| 314 |
+
if cached is not None:
|
| 315 |
+
PIPELINE_METRICS["generation_cache_hits"] += 1
|
| 316 |
+
return apply_output_filter(cached)
|
| 317 |
+
|
| 318 |
+
PIPELINE_METRICS["generation_cache_misses"] += 1
|
| 319 |
+
text = _run_generation(prompt)
|
| 320 |
+
|
| 321 |
+
if ENABLE_REPAIR_RETRY and looks_incomplete_note(text):
|
| 322 |
+
PIPELINE_METRICS["repair_attempts"] += 1
|
| 323 |
+
repair_prompt = (
|
| 324 |
+
prompt
|
| 325 |
+
+ "\n\nThe previous draft was incomplete because it left placeholders blank. "
|
| 326 |
+
+ "Rewrite the SOAP note now and replace every placeholder with actual patient-specific content. "
|
| 327 |
+
+ "Every bullet must contain text after the colon. "
|
| 328 |
+
+ "Do not output placeholder text such as 'CODE - Diagnosis' or '2 to 4 concise clinical sentences'."
|
| 329 |
+
)
|
| 330 |
+
repaired = _run_generation(repair_prompt, token_limit=max(max_new_tokens, 550))
|
| 331 |
+
if repaired and not looks_incomplete_note(repaired):
|
| 332 |
+
text = repaired
|
| 333 |
+
|
| 334 |
+
lru_set(GENERATION_CACHE, cache_key, text, GENERATION_CACHE_SIZE)
|
| 335 |
+
return apply_output_filter(text)
|
| 336 |
+
|
| 337 |
+
def run_app(transcript):
|
| 338 |
+
request_id = str(uuid.uuid4())
|
| 339 |
+
started = time.time()
|
| 340 |
+
|
| 341 |
+
append_jsonl(REQUEST_LOG_PATH, {
|
| 342 |
+
"request_id": request_id,
|
| 343 |
+
"timestamp": datetime.utcnow().isoformat(),
|
| 344 |
+
"status": "started",
|
| 345 |
+
"transcript_chars": len(transcript or "")
|
| 346 |
+
})
|
| 347 |
+
|
| 348 |
+
is_valid, validation_message = validate_input(transcript)
|
| 349 |
+
if not is_valid:
|
| 350 |
+
system_snapshot = get_system_snapshot()
|
| 351 |
+
append_jsonl(ERROR_LOG_PATH, {
|
| 352 |
+
"request_id": request_id,
|
| 353 |
+
"timestamp": datetime.utcnow().isoformat(),
|
| 354 |
+
"error": validation_message
|
| 355 |
+
})
|
| 356 |
+
append_jsonl(REQUEST_LOG_PATH, {
|
| 357 |
+
"request_id": request_id,
|
| 358 |
+
"timestamp": datetime.utcnow().isoformat(),
|
| 359 |
+
"status": "blocked",
|
| 360 |
+
"latency_seconds": round(time.time() - started, 3),
|
| 361 |
+
"transcript_chars": len(transcript or ""),
|
| 362 |
+
"retrieved_chunk_count": 0,
|
| 363 |
+
"cpu_percent": system_snapshot["cpu_percent"],
|
| 364 |
+
"memory_mb": system_snapshot["memory_mb"]
|
| 365 |
+
})
|
| 366 |
+
return validation_message, "", "", f"Request ID: {request_id}\nStatus: blocked"
|
| 367 |
+
|
| 368 |
+
try:
|
| 369 |
+
retrieved = retrieve_context(transcript, top_k=3)
|
| 370 |
+
prompt = build_prompt(transcript, retrieved)
|
| 371 |
+
response = generate_llm_output(prompt)
|
| 372 |
+
|
| 373 |
+
retrieved_text = ""
|
| 374 |
+
sources = set()
|
| 375 |
+
for i, item in enumerate(retrieved, start=1):
|
| 376 |
+
sources.add(os.path.basename(item["source"]))
|
| 377 |
+
retrieved_text += (
|
| 378 |
+
f"Chunk {i}\n"
|
| 379 |
+
f"Source: {item['source']}\n"
|
| 380 |
+
f"Score: {item['score']:.3f}\n"
|
| 381 |
+
f"{item['text']}\n\n"
|
| 382 |
+
f"{'-'*60}\n\n"
|
| 383 |
+
)
|
| 384 |
+
|
| 385 |
+
source_text = "Top Retrieved Sources:\n"
|
| 386 |
+
for s in sorted(sources):
|
| 387 |
+
source_text += f"- {s}\n"
|
| 388 |
+
|
| 389 |
+
latency = round(time.time() - started, 3)
|
| 390 |
+
system_snapshot = get_system_snapshot()
|
| 391 |
+
|
| 392 |
+
append_jsonl(REQUEST_LOG_PATH, {
|
| 393 |
+
"request_id": request_id,
|
| 394 |
+
"timestamp": datetime.utcnow().isoformat(),
|
| 395 |
+
"status": "completed",
|
| 396 |
+
"latency_seconds": latency,
|
| 397 |
+
"transcript_chars": len(transcript or ""),
|
| 398 |
+
"retrieved_chunk_count": len(retrieved),
|
| 399 |
+
"cpu_percent": system_snapshot["cpu_percent"],
|
| 400 |
+
"memory_mb": system_snapshot["memory_mb"]
|
| 401 |
+
})
|
| 402 |
+
|
| 403 |
+
metrics_text = (
|
| 404 |
+
f"Request ID: {request_id}\n"
|
| 405 |
+
f"Status: completed\n"
|
| 406 |
+
f"Latency (s): {latency}\n"
|
| 407 |
+
f"Retrieved Chunks: {len(retrieved)}\n"
|
| 408 |
+
f"Retrieval Cache Hits: {PIPELINE_METRICS['retrieval_cache_hits']}\n"
|
| 409 |
+
f"Generation Cache Hits: {PIPELINE_METRICS['generation_cache_hits']}\n"
|
| 410 |
+
f"Repair Attempts: {PIPELINE_METRICS['repair_attempts']}\n"
|
| 411 |
+
f"CPU %: {system_snapshot['cpu_percent']}\n"
|
| 412 |
+
f"Memory (MB): {system_snapshot['memory_mb']}"
|
| 413 |
+
)
|
| 414 |
+
|
| 415 |
+
return response, retrieved_text, source_text, metrics_text
|
| 416 |
+
|
| 417 |
+
except Exception as e:
|
| 418 |
+
latency = round(time.time() - started, 3)
|
| 419 |
+
system_snapshot = get_system_snapshot()
|
| 420 |
+
|
| 421 |
+
append_jsonl(ERROR_LOG_PATH, {
|
| 422 |
+
"request_id": request_id,
|
| 423 |
+
"timestamp": datetime.utcnow().isoformat(),
|
| 424 |
+
"error": str(e)
|
| 425 |
+
})
|
| 426 |
+
|
| 427 |
+
append_jsonl(REQUEST_LOG_PATH, {
|
| 428 |
+
"request_id": request_id,
|
| 429 |
+
"timestamp": datetime.utcnow().isoformat(),
|
| 430 |
+
"status": "failed",
|
| 431 |
+
"latency_seconds": latency,
|
| 432 |
+
"transcript_chars": len(transcript or ""),
|
| 433 |
+
"retrieved_chunk_count": 0,
|
| 434 |
+
"cpu_percent": system_snapshot["cpu_percent"],
|
| 435 |
+
"memory_mb": system_snapshot["memory_mb"]
|
| 436 |
+
})
|
| 437 |
+
|
| 438 |
+
return "System failed safely while processing the transcript.", "", "", f"Request ID: {request_id}\nStatus: failed\nError: {str(e)}"
|
| 439 |
+
|
| 440 |
+
demo = gr.Interface(
|
| 441 |
+
fn=run_app,
|
| 442 |
+
inputs=gr.Textbox(
|
| 443 |
+
lines=18,
|
| 444 |
+
label="Doctor-Patient Transcript",
|
| 445 |
+
placeholder="Paste the full doctor-patient transcript here..."
|
| 446 |
+
),
|
| 447 |
+
outputs=[
|
| 448 |
+
gr.Textbox(lines=20, label="SOAP + ICD Output"),
|
| 449 |
+
gr.Textbox(lines=12, label="Retrieved Context"),
|
| 450 |
+
gr.Textbox(lines=4, label="Top Retrieved Sources"),
|
| 451 |
+
gr.Textbox(lines=8, label="Runtime Metrics")
|
| 452 |
+
],
|
| 453 |
+
title="NexScribe - Hosted Deploy & Test Demo",
|
| 454 |
+
description="Hosted NexScribe demo with retrieval, SOAP note generation, request monitoring, and runtime observability."
|
| 455 |
+
)
|
| 456 |
+
|
| 457 |
+
demo.launch()
|
cost_performance_tradeoffs.md
ADDED
|
@@ -0,0 +1,24 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
Analyze and document cost-performance trade-offs and identify key scaling bottlenecks.
|
| 2 |
+
|
| 3 |
+
Cost-performance trade-offs:
|
| 4 |
+
- The current Hugging Face Space design avoids per-request API charges because Phi-4-mini-instruct runs inside the app runtime, but response quality and latency depend heavily on the selected HF hardware.
|
| 5 |
+
- CPU Basic has the lowest direct cost but is the most likely to produce slow cold starts, long generation latency, and poor concurrent-user performance.
|
| 6 |
+
- GPU hardware such as T4 or L4 increases monthly compute cost but reduces generation latency and improves user experience for a transcript-to-SOAP workflow.
|
| 7 |
+
- Caching repeated retrieval and generation outputs reduces duplicate embedding/model calls, which is especially useful during demos, testing, and repeated evaluation cases.
|
| 8 |
+
- The FrugalGPT-style strategy keeps the cheap path first: validate input, reuse cache, retrieve only the amount of context needed, generate once, and only spend extra tokens/compute on repair when the output is incomplete.
|
| 9 |
+
- Optional API fallback would add per-token cost but can improve reliability if the local HF model fails or times out. Under the current assumptions, projected GPT-5.4 mini API usage is shown in deployment_artifacts/projected_system_costs.csv.
|
| 10 |
+
- Optional 4-bit quantization can reduce memory pressure and make smaller GPU tiers more viable, but it may slightly reduce output quality and requires a compatible CUDA/bitsandbytes runtime.
|
| 11 |
+
|
| 12 |
+
Key scaling bottlenecks:
|
| 13 |
+
- Model generation is the primary bottleneck because each SOAP note requires hundreds of output tokens.
|
| 14 |
+
- Concurrent requests can saturate a single Space worker, especially on CPU or small GPU tiers.
|
| 15 |
+
- Cold starts are expensive because the embedding model, FAISS index, and LLM must load before requests are served.
|
| 16 |
+
- The current FAISS index is in-memory; this is fine for a small GI knowledge base but will need persistence/sharding if the document set grows significantly.
|
| 17 |
+
- Evaluation cells that call baseline and full-system generation repeatedly can be much slower than the production app path and should be skipped during deployment testing.
|
| 18 |
+
- Storage cost is currently negligible for small text knowledge-base files, but model artifacts and logs can grow if runtime logs are retained indefinitely.
|
| 19 |
+
|
| 20 |
+
Recommended deployment path:
|
| 21 |
+
- Use caching and repair retry by default.
|
| 22 |
+
- Use CPU only for low-traffic demos; use a T4/L4 Space for smoother interactive demos.
|
| 23 |
+
- Keep knowledge-base text files small and curated to minimize retrieval noise and prompt size.
|
| 24 |
+
- Use API fallback only for failed/incomplete generations or high-risk cases where quality is more important than cost.
|
projected_system_costs.csv
ADDED
|
@@ -0,0 +1,5 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
monthly_requests,optional_api_cost_gpt54_mini_usd,hf_cpu_basic_compute_usd,hf_cpu_upgrade_compute_usd,hf_t4_small_compute_usd,hf_l4_compute_usd,storage_usd
|
| 2 |
+
100,0.2548,0.0,21.9,292.0,584.0,0.0117
|
| 3 |
+
1000,2.5481,0.0,21.9,292.0,584.0,0.0117
|
| 4 |
+
10000,25.4812,0.0,21.9,292.0,584.0,0.0117
|
| 5 |
+
50000,127.4062,0.0,21.9,292.0,584.0,0.0117
|
requirements.txt
ADDED
|
@@ -0,0 +1,9 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
gradio
|
| 2 |
+
sentence-transformers
|
| 3 |
+
faiss-cpu
|
| 4 |
+
transformers
|
| 5 |
+
accelerate
|
| 6 |
+
numpy
|
| 7 |
+
pandas
|
| 8 |
+
psutil
|
| 9 |
+
torch
|