File size: 14,594 Bytes
8a72e25
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9b8c36e
 
 
8a72e25
 
 
9b8c36e
8a72e25
 
 
 
 
 
 
 
9b8c36e
8a72e25
 
 
 
9b8c36e
8a72e25
 
 
 
 
 
 
9b8c36e
8a72e25
 
 
 
 
 
 
9b8c36e
8a72e25
 
 
 
9b8c36e
8a72e25
 
 
 
 
 
 
9b8c36e
 
8a72e25
 
 
9b8c36e
8a72e25
 
9b8c36e
8a72e25
 
 
9b8c36e
8a72e25
 
9b8c36e
8a72e25
9b8c36e
8a72e25
 
9b8c36e
8a72e25
 
 
9b8c36e
8a72e25
 
 
 
 
 
 
 
9b8c36e
8a72e25
 
 
9b8c36e
8a72e25
 
9b8c36e
8a72e25
 
 
9b8c36e
8a72e25
 
 
 
 
9b8c36e
8a72e25
 
 
 
9b8c36e
 
3c43b8a
8a72e25
 
9b8c36e
8a72e25
9b8c36e
 
3c43b8a
9b8c36e
 
3c43b8a
9b8c36e
 
 
 
 
 
 
 
 
 
 
3c43b8a
 
8a72e25
 
9b8c36e
8a72e25
 
9b8c36e
8a72e25
 
 
 
 
9b8c36e
8a72e25
 
 
 
 
 
9b8c36e
 
8a72e25
 
 
 
 
 
 
 
9b8c36e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8a72e25
 
9b8c36e
 
 
 
8a72e25
 
9b8c36e
8a72e25
 
 
 
 
9b8c36e
8a72e25
 
 
 
 
 
9b8c36e
 
8a72e25
9b8c36e
8a72e25
 
 
 
 
 
 
 
 
9b8c36e
8a72e25
 
9b8c36e
8a72e25
 
9b8c36e
 
 
8a72e25
9b8c36e
 
 
 
 
 
 
 
8a72e25
9b8c36e
8a72e25
 
 
 
 
 
 
 
 
 
 
 
9b8c36e
 
 
 
8a72e25
 
9b8c36e
 
8a72e25
 
9b8c36e
 
8a72e25
 
9b8c36e
 
 
 
8a72e25
 
9b8c36e
8a72e25
 
9b8c36e
8a72e25
 
 
 
9b8c36e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8a72e25
 
 
9b8c36e
 
 
 
 
 
 
 
8a72e25
 
9b8c36e
 
 
6053597
8a72e25
 
 
 
 
 
9b8c36e
 
 
8a72e25
 
 
 
 
 
 
 
 
 
 
 
 
 
9b8c36e
8a72e25
 
 
9b8c36e
 
 
8a72e25
9b8c36e
 
8a72e25
 
 
9b8c36e
8a72e25
 
 
 
 
9b8c36e
 
8a72e25
 
 
 
 
9b8c36e
 
8a72e25
a09418a
9b8c36e
8a72e25
 
 
 
 
 
9b8c36e
8a72e25
 
 
 
 
 
 
 
 
 
 
 
9b8c36e
8a72e25
 
9b8c36e
8a72e25
 
 
 
 
9b8c36e
8a72e25
 
 
 
 
 
 
 
 
 
9b8c36e
8a72e25
 
 
9b8c36e
8a72e25
6053597
8a72e25
 
 
9b8c36e
8a72e25
 
 
 
 
 
 
9b8c36e
8a72e25
 
9b8c36e
 
 
8a72e25
9b8c36e
 
 
 
 
8a72e25
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9b8c36e
 
 
 
 
 
 
8a72e25
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9b8c36e
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
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()