Initial commit: Agentic Prescription Extractor & Studio
This commit is contained in:
@@ -0,0 +1,116 @@
|
||||
# 🩺 LangGraph Agentic Prescription Extractor (Offline & Multi-Agent)
|
||||
|
||||
A state-of-the-art, 100% **offline agentic medical prescription extraction system** built with **LangGraph**, **LangChain**, local **Whisper** speech-to-text, **FAISS Vector Store**, **SQLite**, and local **LLMs** (Llama 3 8B, Qwen 1.5B, Qwen3 0.6B, DeepSeek-R1 Distill).
|
||||
|
||||
The application ingests raw doctor-patient voice recordings or text notes and uses a coordinated network of specialized parallel agents to extract structured clinical prescription blocks into a validated 7-column schema with **zero hallucinations**, **conversational noise filtering**, and **no unsolicited commentary**.
|
||||
|
||||
---
|
||||
|
||||
## 🏗️ Multi-Agent Architecture (LangGraph StateGraph)
|
||||
|
||||
```
|
||||
┌─────────────────────────────────────────┐
|
||||
│ User Voice / Text Input │
|
||||
│ (Whisper Speech-to-Text / UI) │
|
||||
└────────────────────┬────────────────────┘
|
||||
│
|
||||
▼
|
||||
┌────────────────────────┐
|
||||
│ Supervisor Agent │
|
||||
│ (Noise Filtering, STT │
|
||||
│ Cleaning & Fan-Out) │
|
||||
└────────────┬───────────┘
|
||||
│
|
||||
┌─────────────────────────────┼─────────────────────────────┐
|
||||
│ │ │
|
||||
▼ ▼ ▼
|
||||
┌──────────────────────┐ ┌──────────────────────┐ ┌──────────────────────┐
|
||||
│ Medicine & Strength │ │ Route Agent │ │ Duration & Frequency │
|
||||
│ Agent │ │ (Direct Mention & │ │ Agent │
|
||||
│ (Generics, Dual-Dose,│ │ Form Specificity) │ │ (Verbatim Intervals │
|
||||
│ Companion Splitting)│ │ │ │ & Duration Spans) │
|
||||
└───────────┬──────────┘ └───────────┬──────────┘ └───────────┬──────────┘
|
||||
│ │ │
|
||||
│ ▼ │
|
||||
│ ┌──────────────────────┐ │
|
||||
│ │ Instruction Agent │ │
|
||||
│ │ (Primary Admin vs. │ │
|
||||
│ │ Secondary Advice) │ │
|
||||
│ └───────────┬──────────┘ │
|
||||
│ │ │
|
||||
└─────────────────────────────┼─────────────────────────────┘
|
||||
│
|
||||
▼
|
||||
┌────────────────────────┐
|
||||
│ Aggregator Agent │
|
||||
│ (Unifies Records and │
|
||||
│ Filters Non-Drug Data)│
|
||||
└────────────┬───────────┘
|
||||
│
|
||||
▼
|
||||
┌────────────────────────┐
|
||||
│ Validator Agent │
|
||||
│ (Groundedness & Anti- │
|
||||
│ Hallucination QA) │
|
||||
└────────────┬───────────┘
|
||||
│
|
||||
┌─────────────────────────┴─────────────────────────┐
|
||||
│ │
|
||||
[NEEDS_CORRECTION & Iterations < 3] [VALID / Max Reps Capped]
|
||||
│ │
|
||||
▼ ▼
|
||||
┌───────────────────────────────┐ ┌─────────────────────────────────┐
|
||||
│ Targeted Feedback Dispatched │ │ Formatter Agent │
|
||||
│ to Responsible Agents & Retry │ │ (Strict Structured Text Blocks) │
|
||||
└───────────────────────────────┘ └────────────────┬────────────────┘
|
||||
│
|
||||
▼
|
||||
┌─────────────────────────────────┐
|
||||
│ SQLite DB + CSV/XLSX Export │
|
||||
│ + Streamlit Data Table UI │
|
||||
└─────────────────────────────────┘
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 📊 Structured 7-Column Clinical Schema
|
||||
|
||||
| Column | Description | Real-World Example |
|
||||
| :--- | :--- | :--- |
|
||||
| **`Drug_name`** | Brand name or generic name + primary dose | `PHEXIN DT 250 mg`, `Paracetamol 650 mg`, `Ofloxacin-Ornidazole` |
|
||||
| **`strength`** | Secondary dose value if dual-dosed (or `NONE`) | `20 mg`, `NONE` |
|
||||
| **`frequency`** | Schedule notation, clinical timing, or interval | `twice daily(1-0-1)`, `every 6 hours`, `TID`, `once daily` |
|
||||
| **`duration`** | Duration span | `10 days`, `5 days`, `2 weeks`, `30 days` |
|
||||
| **`route`** | Anatomical route of administration | `oral`, `inhalation`, `topical`, `nasal`, `ophthalmic`, `otic` |
|
||||
| **`instruction`** | Primary administration timing, meal rules, devices, PRN | `1. before breakfast`, `1. using Revolizer device 2. rinse mouth after use` |
|
||||
| **`additional_instruction`** | Secondary clinical monitoring, follow-up, warnings, diet/lifestyle | `1. Seek reassessment if adverse effects develop`, `1. Stick to a bland diet` |
|
||||
|
||||
---
|
||||
|
||||
## 🛠️ Installation & Setup
|
||||
|
||||
```powershell
|
||||
# Create and activate virtual environment
|
||||
python -m venv env
|
||||
.\env\Scripts\Activate.ps1
|
||||
|
||||
# Install dependencies
|
||||
pip install -r requirements.txt
|
||||
|
||||
# Launch Application
|
||||
streamlit run app.py
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 🧪 Automated Verification Suite
|
||||
|
||||
```powershell
|
||||
python test_langgraph_pipeline.py
|
||||
```
|
||||
|
||||
```text
|
||||
========================================================
|
||||
ALL 14 LANGGRAPH DRIFT-PROOF MULTI-AGENT TESTS PASSED!
|
||||
========================================================
|
||||
```
|
||||
@@ -0,0 +1,37 @@
|
||||
"""
|
||||
agents.py
|
||||
---------
|
||||
Top-level entry point and re-exporter for the modular agents package.
|
||||
Each agent implementation lives in its own dedicated module in rx_extractor_app/agents/:
|
||||
- supervisor_agent.py
|
||||
- medicine_strength_agent.py
|
||||
- route_agent.py
|
||||
- duration_frequency_agent.py
|
||||
- instruction_agent.py
|
||||
- aggregator_agent.py
|
||||
- validator_agent.py
|
||||
- formatter_agent.py
|
||||
"""
|
||||
from agents.supervisor_agent import supervisor_node
|
||||
from agents.medicine_strength_agent import medicine_strength_agent
|
||||
from agents.route_agent import route_agent
|
||||
from agents.duration_frequency_agent import duration_frequency_agent
|
||||
from agents.instruction_agent import instruction_agent
|
||||
from agents.aggregator_agent import aggregator_agent
|
||||
from agents.validator_agent import validator_agent
|
||||
from agents.formatter_agent import formatter_node
|
||||
from agents.utils import is_placeholder, safe_parse_json, segment_prescription
|
||||
|
||||
__all__ = [
|
||||
"supervisor_node",
|
||||
"medicine_strength_agent",
|
||||
"route_agent",
|
||||
"duration_frequency_agent",
|
||||
"instruction_agent",
|
||||
"aggregator_agent",
|
||||
"validator_agent",
|
||||
"formatter_node",
|
||||
"is_placeholder",
|
||||
"safe_parse_json",
|
||||
"segment_prescription",
|
||||
]
|
||||
@@ -0,0 +1,24 @@
|
||||
"""
|
||||
agents package
|
||||
--------------
|
||||
Modular LangGraph agent definitions for prescription extraction.
|
||||
"""
|
||||
from agents.supervisor_agent import supervisor_node
|
||||
from agents.medicine_strength_agent import medicine_strength_agent
|
||||
from agents.route_agent import route_agent
|
||||
from agents.duration_frequency_agent import duration_frequency_agent
|
||||
from agents.instruction_agent import instruction_agent
|
||||
from agents.aggregator_agent import aggregator_agent
|
||||
from agents.validator_agent import validator_agent
|
||||
from agents.formatter_agent import formatter_node
|
||||
|
||||
__all__ = [
|
||||
"supervisor_node",
|
||||
"medicine_strength_agent",
|
||||
"route_agent",
|
||||
"duration_frequency_agent",
|
||||
"instruction_agent",
|
||||
"aggregator_agent",
|
||||
"validator_agent",
|
||||
"formatter_node",
|
||||
]
|
||||
@@ -0,0 +1,60 @@
|
||||
"""
|
||||
agents/aggregator_agent.py
|
||||
--------------------------
|
||||
Aggregator Agent:
|
||||
Unifies extracted outputs from all parallel agents into complete clinical records (including additional_instruction),
|
||||
and filters out non-medication noise entities.
|
||||
"""
|
||||
from typing import Dict, Any, List
|
||||
from graph_state import AgenticRxState, PrescriptionBlock
|
||||
from agents.utils import is_valid_medication_entity, clean_instruction_noise
|
||||
|
||||
|
||||
def aggregator_agent(state: AgenticRxState, llm: Any = None) -> Dict[str, Any]:
|
||||
"""
|
||||
Aggregator Agent with noise-proofing entity validation.
|
||||
"""
|
||||
meds = state.get("medicines", [])
|
||||
routes = {r.get("medicine_id", idx + 1): r.get("route", "NONE") for idx, r in enumerate(state.get("routes", []))}
|
||||
dur_freq = {df.get("medicine_id", idx + 1): df for idx, df in enumerate(state.get("durations_frequencies", []))}
|
||||
|
||||
inst_map = {}
|
||||
add_inst_map = {}
|
||||
for idx, ins in enumerate(state.get("instructions", [])):
|
||||
m_id = ins.get("medicine_id", idx + 1)
|
||||
inst_map[m_id] = clean_instruction_noise(ins.get("instruction", "NONE"))
|
||||
add_inst_map[m_id] = clean_instruction_noise(ins.get("additional_instruction", "NONE"))
|
||||
|
||||
aggregated: List[PrescriptionBlock] = []
|
||||
|
||||
for idx, med in enumerate(meds):
|
||||
m_id = med.get("medicine_id", idx + 1)
|
||||
df_entry = dur_freq.get(m_id, {})
|
||||
d_name = med.get("drug_name", "NONE").strip()
|
||||
|
||||
# Noise filter: ensure entity is a valid pharmaceutical drug name
|
||||
if not is_valid_medication_entity(d_name) and len(meds) > 1:
|
||||
continue
|
||||
|
||||
block: PrescriptionBlock = {
|
||||
"Drug_name": d_name,
|
||||
"strength": med.get("strength", "NONE"),
|
||||
"frequency": df_entry.get("frequency", "NONE"),
|
||||
"duration": df_entry.get("duration", "NONE"),
|
||||
"route": routes.get(m_id, "NONE"),
|
||||
"instruction": inst_map.get(m_id, "NONE"),
|
||||
"additional_instruction": add_inst_map.get(m_id, "NONE"),
|
||||
}
|
||||
aggregated.append(block)
|
||||
|
||||
log_entry = {
|
||||
"agent": "Aggregator",
|
||||
"action": f"Aggregated {len(aggregated)} noise-proof medicine block(s)",
|
||||
}
|
||||
current_logs = list(state.get("agent_logs", []))
|
||||
current_logs.append(log_entry)
|
||||
|
||||
return {
|
||||
"aggregated_blocks": aggregated,
|
||||
"agent_logs": current_logs,
|
||||
}
|
||||
@@ -0,0 +1,159 @@
|
||||
"""
|
||||
agents/duration_frequency_agent.py
|
||||
----------------------------------
|
||||
Duration & Frequency Agent:
|
||||
Drift-proof extractor for administration frequencies and duration spans across arbitrary clinical expressions.
|
||||
"""
|
||||
import re
|
||||
from typing import Dict, Any, List
|
||||
from graph_state import AgenticRxState, DurationFrequencyItem
|
||||
from agents.utils import (
|
||||
is_placeholder,
|
||||
safe_parse_json,
|
||||
segment_prescription,
|
||||
)
|
||||
import prompt
|
||||
|
||||
GENERAL_FREQUENCY_PATTERNS = [
|
||||
r"up\s+to\s+\w+\s+times\s+daily(?:\s+as\s+needed)?",
|
||||
r"every\s+\d+(?:\s+to\s+\d+)?\s*(?:hours?|hrs?|days?|weeks?|months?)",
|
||||
r"every\s+(?:morning|night|evening|afternoon|bedtime|other\s+day)",
|
||||
r"(?:twice|once|thrice|three\s+times|four\s+times|\d+\s+times)\s+daily\s*\([0-9\-\/]+\)",
|
||||
r"\b\d+-\d+-\d+(?:-\d+)?\b",
|
||||
r"(?:twice|once|thrice|three\s+times|four\s+times|\d+\s+times)\s+(?:daily|a\s+day|per\s+day|a\s+week|weekly|a\s+month|monthly)",
|
||||
r"(?:once|twice|thrice)\s+weekly",
|
||||
r"three\s+times\s+daily",
|
||||
r"four\s+times\s+daily",
|
||||
r"twice\s+daily",
|
||||
r"once\s+daily",
|
||||
r"thrice\s+daily",
|
||||
r"throughout\s+the\s+day",
|
||||
r"single\s+dose",
|
||||
r"stat\s+dose",
|
||||
r"as\s+needed\s*\([A-Za-z]+\)",
|
||||
r"as\s+needed(?:\s+for\s+[a-zA-Z\s]+)?",
|
||||
r"early\s+morning",
|
||||
r"at\s+bedtime",
|
||||
r"\bdaily\b",
|
||||
r"\b(?:OD|BD|TID|QID|QDS|TDS|BID|PRN|SOS|HS|STAT|q\d+h|q\d+-\d+h)\b",
|
||||
]
|
||||
|
||||
GENERAL_DURATION_PATTERNS = [
|
||||
r"\b(?:for\s+|duration\s+of\s+|till\s+|until\s+|upto\s+|up\s+to\s+|for\s+upto\s+|for\s+up\s+to\s+|for\s+next\s+|next\s+|about\s+|around\s+|approx(?:\s+)?|for\s+around\s+|for\s+about\s+|x\s*)(\d+\s*(?:days?|d|weeks?|wks?|months?|mo|years?|hrs?|hours?)|day\s+one|single\s+day|\d+\s*to\s*\d+\s*(?:days?|weeks?|months?)|no\s+more\s+than\s+\d+\s+days?)\b",
|
||||
r"\b(until\s+[a-zA-Z\s]{3,30})\b",
|
||||
r"\b(\d+\s*(?:days?|weeks?|months?))\b",
|
||||
]
|
||||
|
||||
|
||||
def duration_frequency_agent(state: AgenticRxState, llm: Any = None) -> Dict[str, Any]:
|
||||
"""
|
||||
Duration & Frequency Agent.
|
||||
"""
|
||||
input_text = state.get("input_text", "")
|
||||
feedback = state.get("validation_feedback", {}).get("duration_frequency_agent", "")
|
||||
|
||||
extracted_dur_freq: List[DurationFrequencyItem] = []
|
||||
|
||||
if llm is not None:
|
||||
p = prompt.DURATION_FREQUENCY_PROMPT.replace("{{VOICE_INPUT}}", input_text)
|
||||
p = p.replace("{{FEEDBACK}}", feedback if feedback else "None")
|
||||
try:
|
||||
raw_out = llm.invoke(p)
|
||||
if isinstance(raw_out, str):
|
||||
if "Prescription Input:" in raw_out:
|
||||
raw_out = raw_out.split("Prescription Input:")[-1]
|
||||
parsed = safe_parse_json(raw_out)
|
||||
if isinstance(parsed, list):
|
||||
for idx, item in enumerate(parsed):
|
||||
freq = item.get("frequency", "NONE")
|
||||
dur = item.get("duration", "NONE")
|
||||
if not is_placeholder(freq) and not is_placeholder(dur):
|
||||
extracted_dur_freq.append({
|
||||
"medicine_id": item.get("medicine_id", idx + 1),
|
||||
"drug_name": item.get("drug_name", ""),
|
||||
"frequency": freq,
|
||||
"duration": dur,
|
||||
})
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
if not extracted_dur_freq:
|
||||
segments = segment_prescription(input_text)
|
||||
|
||||
# Check global plural/broadcast coreference (e.g. "Both should be taken twice daily", "All medicines are once daily")
|
||||
global_plural_freq = "NONE"
|
||||
global_plural_dur = "NONE"
|
||||
plural_match = re.search(r"(?i)\b(?:both(?:\s+of\s+them|\s+medicines|\s+drugs|\s+tablets|\s+capsules)?|all(?:\s+these|\s+of\s+them)?(?:\s+medicines|\s+drugs|\s+tablets)?|each(?:\s+of\s+them)?)\s+(?:should\s+be\s+taken|are\s+to\s+be\s+taken|must\s+be\s+taken|to\s+be\s+taken|should\s+be\s+given|should\s+be|are|must\s+be)\s+([^,\.\n;!]+)", input_text)
|
||||
if plural_match:
|
||||
cand_p = plural_match.group(1).strip()
|
||||
for fp in GENERAL_FREQUENCY_PATTERNS:
|
||||
fm = re.search(fp, cand_p, re.IGNORECASE)
|
||||
if fm:
|
||||
global_plural_freq = fm.group(0).strip()
|
||||
break
|
||||
for dp in GENERAL_DURATION_PATTERNS:
|
||||
dm = re.search(dp, input_text, re.IGNORECASE)
|
||||
if dm:
|
||||
global_plural_dur = dm.group(1).strip()
|
||||
break
|
||||
|
||||
# Check singular coreference (e.g. "It should be taken 4 times a day", "This medicine is to be taken twice daily")
|
||||
global_singular_freq = "NONE"
|
||||
singular_match = re.search(r"(?i)\b(?:it\s+(?:should\s+be\s+taken|is\s+to\s+be\s+taken|must\s+be\s+taken|to\s+be\s+taken|is\s+taken)|take\s+(?:it|this(?:\s+medicine)?))\s+([^,\.\n;!]+)", input_text)
|
||||
if singular_match:
|
||||
cand_s = singular_match.group(1).strip()
|
||||
for fp in GENERAL_FREQUENCY_PATTERNS:
|
||||
fm = re.search(fp, cand_s, re.IGNORECASE)
|
||||
if fm:
|
||||
global_singular_freq = fm.group(0).strip()
|
||||
break
|
||||
|
||||
for s in segments:
|
||||
m_id = s["medicine_id"]
|
||||
clause = s["clause"]
|
||||
|
||||
# 1. Frequency (search in first 100 chars of clause first to avoid matching trailing advice)
|
||||
core_clause = clause[:100]
|
||||
freq = "NONE"
|
||||
for fp in GENERAL_FREQUENCY_PATTERNS:
|
||||
f_match = re.search(fp, core_clause, re.IGNORECASE)
|
||||
if f_match:
|
||||
matched_freq = f_match.group(0).strip()
|
||||
matched_freq = re.sub(r"(?i)\s+(?:before|after)\s+(?:food|breakfast|meals|lunch|dinner)$", "", matched_freq).strip()
|
||||
freq = matched_freq
|
||||
break
|
||||
|
||||
if freq == "NONE":
|
||||
for fp in GENERAL_FREQUENCY_PATTERNS:
|
||||
f_match = re.search(fp, clause, re.IGNORECASE)
|
||||
if f_match:
|
||||
matched_freq = f_match.group(0).strip()
|
||||
matched_freq = re.sub(r"(?i)\s+(?:before|after)\s+(?:food|breakfast|meals|lunch|dinner)$", "", matched_freq).strip()
|
||||
freq = matched_freq
|
||||
break
|
||||
|
||||
if freq == "NONE":
|
||||
if global_plural_freq != "NONE":
|
||||
freq = global_plural_freq
|
||||
elif global_singular_freq != "NONE" and (len(segments) == 1 or m_id == len(segments)):
|
||||
freq = global_singular_freq
|
||||
|
||||
# 2. Duration
|
||||
dur = "NONE"
|
||||
for dp in GENERAL_DURATION_PATTERNS:
|
||||
d_match = re.search(dp, clause, re.IGNORECASE)
|
||||
if d_match:
|
||||
dur = d_match.group(1).strip()
|
||||
break
|
||||
|
||||
if dur == "NONE" and global_plural_dur != "NONE":
|
||||
dur = global_plural_dur
|
||||
|
||||
extracted_dur_freq.append({
|
||||
"medicine_id": m_id,
|
||||
"drug_name": "",
|
||||
"frequency": freq,
|
||||
"duration": dur,
|
||||
})
|
||||
|
||||
return {"durations_frequencies": extracted_dur_freq}
|
||||
@@ -0,0 +1,40 @@
|
||||
"""
|
||||
agents/formatter_agent.py
|
||||
-------------------------
|
||||
Formatter Node:
|
||||
Generates the exact structured block representation (including additional_instruction) with zero extraneous commentary.
|
||||
"""
|
||||
from typing import Dict, Any
|
||||
from graph_state import AgenticRxState
|
||||
|
||||
|
||||
def formatter_node(state: AgenticRxState, llm: Any = None) -> Dict[str, Any]:
|
||||
"""
|
||||
Formatter Node:
|
||||
Produces the strict structured blocks format with no explanations, notes, or moralizing.
|
||||
"""
|
||||
blocks = state.get("aggregated_blocks", [])
|
||||
output_lines = []
|
||||
|
||||
for b in blocks:
|
||||
output_lines.append(f"Drug_name: {b.get('Drug_name', 'NONE')}")
|
||||
output_lines.append(f"strength: {b.get('strength', 'NONE')}")
|
||||
output_lines.append(f"frequency: {b.get('frequency', 'NONE')}")
|
||||
output_lines.append(f"duration: {b.get('duration', 'NONE')}")
|
||||
output_lines.append(f"route: {b.get('route', 'NONE')}")
|
||||
output_lines.append(f"instruction: {b.get('instruction', 'NONE')}")
|
||||
output_lines.append(f"additional_instruction: {b.get('additional_instruction', 'NONE')}")
|
||||
|
||||
final_text = "\n".join(output_lines)
|
||||
|
||||
log_entry = {
|
||||
"agent": "Formatter",
|
||||
"action": "Generated final structured clinical blocks",
|
||||
}
|
||||
current_logs = list(state.get("agent_logs", []))
|
||||
current_logs.append(log_entry)
|
||||
|
||||
return {
|
||||
"final_output": final_text,
|
||||
"agent_logs": current_logs,
|
||||
}
|
||||
@@ -0,0 +1,386 @@
|
||||
"""
|
||||
agents/instruction_agent.py
|
||||
---------------------------
|
||||
Instruction Agent:
|
||||
Dynamic natural language extractor for primary administration instructions and additional clinical instructions:
|
||||
1. 'instruction': Primary administration timing, meals, preparation techniques, device usage, PRN indications, times-of-day.
|
||||
2. 'additional_instruction': Clinical follow-up, evaluation, monitoring, reassessment, adverse effect warnings,
|
||||
titration conditions, course completion rules, cross-drug cautions, and dietary/lifestyle guidance.
|
||||
Fully drift-proof and punctuation-independent for continuous voice speech.
|
||||
"""
|
||||
import re
|
||||
from typing import Dict, Any, List
|
||||
from graph_state import AgenticRxState, InstructionItem
|
||||
from agents.utils import (
|
||||
is_placeholder,
|
||||
safe_parse_json,
|
||||
segment_prescription,
|
||||
)
|
||||
import prompt
|
||||
|
||||
# Common Action verbs that introduce a new medication clause
|
||||
MED_ACTION_VERB_START = r"(?i)^(?:take\s+(?!(?:walks?|rest|care|steam))\w+|administer|give|prescribe|start|consume|dissolve|inhale|apply|put|instill|inject|infuse|gently\s+massage|massage|cleanse)\b"
|
||||
|
||||
# Verbs / phrases that naturally signal follow-up, evaluation, precaution, warnings, or lifestyle advice
|
||||
INDEPENDENT_ADVICE_START = (
|
||||
r"(?i)^(?:return\s+for|return\s+if|return\s+after|return\s+to|come\s+back|follow\s+up|review\s+if|review\s+after|"
|
||||
r"meet\s+(?:the\s+)?doctor|please\s+see\s+me|see\s+(?:your\s+|the\s+)?doctor|"
|
||||
r"get\s+reassessed|seek\s+reassessment|seek\s+medical\s+review|seek\s+urgent|seek\s+immediate|seek|"
|
||||
r"consult\s+immediately|consult\s+your|consult|"
|
||||
r"contact\s+the\s+clinic|contact\s+your|report\s+immediately|report\s+if|report|"
|
||||
r"visit\s+the\s+emergency|visit\s+the\s+clinic|visit|"
|
||||
r"revisit\s+the\s+clinic|revisit|"
|
||||
r"arrange\s+for|schedule\s+a|schedule|"
|
||||
r"repeat\s+a|repeat|re-?test\s+your|re-?test|"
|
||||
r"do\s+not\s+stop|do\s+not\s+exceed|do\s+not\s+delay|do\s+not\s+squeeze|do\s+not|"
|
||||
r"avoid\s+taking|avoid\s+exposure|avoid\s+lifting|avoid\s+squatting|avoid\s+smoking|avoid\s+drinking|avoid|"
|
||||
r"strictly\s+avoid|"
|
||||
r"discontinue\s+once|discontinue|stop\s+taking|stop\s+if|stop|"
|
||||
r"keep\s+the\s+dressing|keep\s+the\s+ear|keep\s+a\s+regular|keep\s+a\s+headache|keep\s+a|keep|"
|
||||
r"maintain\s+a|maintain\s+generous|maintain|"
|
||||
r"stick\s+to\s+a|stick\s+to|"
|
||||
r"include\s+dark|include\s+green|include|"
|
||||
r"limit\s+your|limit\s+fluid|limit|"
|
||||
r"practice\s+pursed-lip|practice|"
|
||||
r"brush\s+gently|brush|"
|
||||
r"perform\s+steam\s+inhalation|perform\s+steam|perform\s+gentle|perform|"
|
||||
r"use\s+saline\s+nasal|use\s+saline|"
|
||||
r"drink\s+plenty|drink\s+2|drink\s+warm|drink|"
|
||||
r"consume\s+plenty|consume\s+warm|stay\s+well-hydrated|"
|
||||
r"apply\s+local\s+hot|apply\s+ice\s+packs?|"
|
||||
r"sponge\s+the\s+body|sponge\s+forehead|sponge|"
|
||||
r"(?:also\s+)?take\s+walks?|go\s+for\s+walks?|take\s+rest|take\s+steam|"
|
||||
r"wear\s+loose|monitor\s+your|monitor\s+weight|monitor\s+blood|monitor\s+inr|monitor|"
|
||||
r"be\s+sure\s+to\s+rinse|rinse\s+your\s+mouth\s+thoroughly|rinse\s+mouth\s+after|"
|
||||
r"if\s+headache|if\s+blood\s+pressure|if\s+fever|if\s+symptoms|if\s+pain|if\s+rash|if\s+numbness|if\s+severe|if\s+ulcers|if\s+condition|if\s+breathing|if\s+dizziness|"
|
||||
r"(?:increase|decrease|reduce|double|taper)\s+(?:the\s+)?(?:dose|dosage))\b"
|
||||
)
|
||||
|
||||
# Robust punctuation-independent clinical advice pattern (captures continuous speech advice)
|
||||
CONTINUOUS_ADVICE_SPAN_PATTERNS = [
|
||||
r"(?i)\b(?:if\s+[a-zA-Z\s\-]+?(?:does\s+not\s+go\s+away|does\s+not\s+clear|persists|worsens|increases|crosses\s+\d+|develops|occurs|remains\s+high|subsides|heals|drops\s+to\s+normal)(?:,\s*|\s+)?(?:(?:increase|decrease|reduce|double|taper)\s+(?:the\s+)?(?:dose|dosage)(?:\s+by\s+\d+\s*(?:mgs?|mg|g|mcg|ml))?|Meet\s+(?:the\s+)?doctor|come\s+visit\s+(?:the\s+|your\s+)?doctor|consult\s+(?:your\s+)?doctor|seek\s+medical\s+review|visit\s+(?:the\s+)?emergency|report\s+immediately)?)\b",
|
||||
r"(?i)\b(?:(?:increase|decrease|reduce|double|taper)\s+(?:the\s+)?(?:dose|dosage)\s+(?:by\s+)?\d+\s*(?:mgs?|mg|g|mcg|ml)?(?:,\s*|\s+)?(?:if\s+[a-zA-Z\s\-]+?(?:does\s+not\s+go\s+away|does\s+not\s+clear|persists|worsens|increases|crosses\s+\d+|develops|occurs|remains\s+high|subsides|heals))?)\b",
|
||||
r"(?i)\b(?:meet\s+(?:the\s+)?doctor)\b",
|
||||
r"(?i)\b(?:please\s+see\s+me(?:\s+after\s+\d+\s+days?)?)\b",
|
||||
r"(?i)\b(?:see\s+(?:your\s+|the\s+)?doctor(?:\s+after\s+\d+\s+days?)?)\b",
|
||||
r"(?i)\b(?:(?:also\s+)?take\s+walks?(?:\s+after\s+dinner)?(?:\s+and\s+it\s+will\s+reduce\s+your\s+headaches)?)\b",
|
||||
r"(?i)\b(?:go\s+for\s+(?:morning\s+)?walks?(?:\s+daily)?)\b",
|
||||
r"(?i)\b(?:return\s+for(?:\s+evaluation|\s+review|\s+a\s+follow-up)?(?:\s+after\s+completing\s+the\s+course)?)\b",
|
||||
r"(?i)\b(?:come\s+(?:back\s+)?for\s+review(?:\s+with\s+[a-zA-Z\s]+)?)\b",
|
||||
r"(?i)\b(?:sponge\s+(?:the\s+)?(?:body|forehead)(?:\s+with\s+cold\s+water)?(?:\s+if\s+[a-zA-Z\s]+)?)\b",
|
||||
r"(?i)\b(?:discontinue\s+(?:once|if)\s+[a-zA-Z\s]+?)\b",
|
||||
r"(?i)\b(?:do\s+not\s+stop\s+(?:the\s+)?antibiotic\s+course[a-zA-Z\s]*)\b",
|
||||
r"(?i)\b(?:avoid\s+(?:lifting\s+heavy\s+weights|squatting|hot\s+baths|scratching|smoking|alcohol|spicy|sour)[a-zA-Z\s]*)\b",
|
||||
r"(?i)\b(?:stick\s+to\s+a\s+bland\s+diet[a-zA-Z\s]*)\b",
|
||||
r"(?i)\b(?:maintain\s+(?:a\s+low-glycemic|generous\s+hydration|a\s+regular\s+sleep)[a-zA-Z\s]*)\b",
|
||||
r"(?i)\b(?:include\s+(?:dark\s+)?green\s+leafy[a-zA-Z\s]*)\b",
|
||||
r"(?i)\b(?:drink\s+(?:plenty|2\.5|\d+\s+liters)[a-zA-Z\s]*)\b",
|
||||
r"(?i)\b(?:apply\s+(?:local\s+)?hot\s+water\s+fomentation[a-zA-Z\s]*)\b",
|
||||
r"(?i)\b(?:keep\s+(?:the\s+)?(?:blistered|affected|skin|dressing|ear)\s+area\s+clean\s+and\s+dry)\b",
|
||||
r"(?i)\b(?:avoid\s+close\s+physical\s+contact[a-zA-Z\s]*)\b",
|
||||
r"(?i)\b(?:return\s+if\s+the\s+rash\s+involves[a-zA-Z\s]*)\b",
|
||||
r"(?i)\b(?:come\s+(?:and\s+)?visit\s+(?:the\s+|your\s+)?doctor)\b",
|
||||
r"(?i)\b(?:visit\s+(?:the\s+|your\s+)?doctor)\b",
|
||||
r"(?i)\b(?:take\s+(?:regular\s+|warm\s+|cold\s+|plenty\s+of\s+|sufficient\s+|clean\s+)?(?:water|fluids?))\b",
|
||||
r"(?i)\b(?:(?:use\s+)?saline\s+nasal\s+irrigations?(?:\s+twice\s+daily)?)\b",
|
||||
r"(?i)\b(?:perform\s+steam\s+inhalation(?:\s+daily)?)\b",
|
||||
r"(?i)\b(?:seek\s+reassessment\s+if\s+[a-zA-Z\s\-]+?develops?)\b",
|
||||
]
|
||||
|
||||
# Intra-clause primary administration expressions (times of day, meals, devices, preparations, PRN)
|
||||
PRIMARY_INSTRUCTION_PATTERNS = [
|
||||
# Natural Times of Day
|
||||
r"\b(?:morning\s+night|morning\s+afternoon\s+night|morning\s+and\s+night|morning\s+and\s+evening|morning\s+evening|day\s+and\s+night|early\s+morning|at\s+noon|at\s+bedtime|at\s+night|in\s+the\s+morning(?:\s+after\s+breakfast)?|in\s+the\s+evening|in\s+the\s+afternoon|before\s+bed(?:time)?)\b",
|
||||
|
||||
# Specific Meal Timings
|
||||
r"\b\d+\s+minutes\s+before\s+breakfast\s+and\s+dinner\b",
|
||||
r"\b\d+\s+minutes\s+before\s+(?:breakfast|lunch|dinner|meals|food)\b",
|
||||
r"\b\d+\s+minutes\s+after\s+(?:breakfast|lunch|dinner|meals|food)\b",
|
||||
r"\b\d+\s+hours?\s+before\s+(?:breakfast|lunch|dinner|meals|food)\b",
|
||||
r"\b\d+\s+hours?\s+after\s+(?:breakfast|lunch|dinner|meals|food)\b",
|
||||
r"\b(?:before|after)\s+(?:breakfast|lunch|dinner|meals?|food)\b",
|
||||
r"\b(?:strictly\s+after\s+food|strictly\s+with\s+food|strictly\s+with\s+meals(?:\s+to\s+avoid\s+[^,\.\n]+)?)\b",
|
||||
r"\b(?:on\s+an?\s+empty\s+stomach|empty\s+stomach|with\s+meals|with\s+food)\b",
|
||||
|
||||
# Devices, Inhalers & Administration Techniques
|
||||
r"\busing\s+(?:the\s+)?Revolizer\s+device\b",
|
||||
r"\busing\s+(?:your\s+)?dry\s+powder\s+inhaler(?:\s+and\s+rinse\s+your\s+mouth\s+immediately)?\b",
|
||||
r"\bvia\s+an?\s+MDI\s+spacer(?:\s+as\s+needed)?\b",
|
||||
r"\binto\s+each\s+nostril\b",
|
||||
r"\b\d+\s+sprays?\s+into\s+each\s+nostril\b",
|
||||
r"\b\d+\s+drops?\s+into\s+(?:each\s+nostril|the\s+affected\s+ear|both\s+eyes|left\s+eye|right\s+eye)(?:\s+for\s+no\s+more\s+than\s+\d+\s+days)?(?:\s+ensuring\s+the\s+eardrum\s+is\s+intact)?\b",
|
||||
r"\b\d+\s+teaspoons?\s+diluted\s+in\s+a\s+full\s+glass\s+of\s+water\b",
|
||||
r"\b\d+\s*ml\s+diluted\s+with\s+equal\s+parts\s+water\b",
|
||||
r"\bdissolve\s+(?:one\s+sachet\s+)?in\s+one\s+liter\s+of\s+clean\s+drinking\s+water\s+to\s+consume\s+throughout\s+the\s+day\b",
|
||||
r"\b(?:dissolved\s+in\s+water|mixed\s+in\s+milk|effervescent\s+tablet\s+dissolved\s+in\s+water)\b",
|
||||
r"\bslowly\s+dissolve\s+(?:one\s+antiseptic\s+lozenge\s+)?in\s+your\s+mouth[^\.\n,]*",
|
||||
r"\bapply\s+a\s+thin\s+layer\s+along\s+the\s+clean\s+suture\s+line\b",
|
||||
r"\bapply\s+(?:gel\s+)?sparingly\s+to\s+active\s+pimples[^\.\n,]*",
|
||||
r"\bapply\s+a\s+pea-sized\s+amount\s+all\s+over\s+the\s+face[^\.\n,]*",
|
||||
r"\bapply\s+broad-spectrum\s+sunscreen\s+SPF\s+50[^\.\n,]*",
|
||||
r"\bwithout\s+swallowing\s+or\s+eating\s+for\s+\d+\s+minutes\b",
|
||||
r"\brinse\s+your\s+mouth\s+with\s+\d+\s*ml[^\.\n,]*for\s+\d+\s+minute\b",
|
||||
r"\brinse\s+your\s+mouth\s+thoroughly\s+after\s+using\s+the\s+inhaler\b",
|
||||
r"\brinse\s+mouth\s+(?:after\s+(?:using\s+the\s+inhaler|use))?\b",
|
||||
r"\bswallow\s+(?:tablets?|capsules?|medicine)?\s*whole(?:\s+without\s+crushing|\s+do\s+not\s+crush)?\b",
|
||||
r"\bwith\s+a\s+full\s+glass\s+of\s+water\b",
|
||||
r"\bgargle\s+with\s+warm\s+Povidone-iodine\s+mouthwash[^\.\n,]*",
|
||||
r"\bcleanse\s+the\s+skin\s+gently\s+using\s+Chlorhexidine\s+wash[^\.\n,]*",
|
||||
r"\bapply\s+a\s+dab\s+of[^\.\n,]*over\s+the\s+mouth\s+ulcers\b",
|
||||
r"\bapply\s+a\s+thin\s+layer\s+of[^\.\n,]*to\s+the\s+affected\s+patches\b",
|
||||
r"\bapply\s+(?:a\s+bland\s+moisturizing\s+)?paraffin\s+lotion\s+over\s+dry\s+skin\s+areas\b",
|
||||
|
||||
# PRN & Specific Indications
|
||||
r"\bfor\s+(?:facial\s+pain\s+or\s+fever|nausea|throat\s+discomfort|sudden\s+breathlessness|episodic\s+pelvic\s+discomfort|pain\s+relief|fever|pain|cough|headache)\b",
|
||||
r"\bto\s+relieve\s+itching\b",
|
||||
r"\bfor\s+the\s+first\s+\d+\s+days\b",
|
||||
]
|
||||
|
||||
# Secondary / Per-drug warnings & titrations
|
||||
PER_DRUG_SECONDARY_PATTERNS = [
|
||||
r"ensuring\s+it\s+is\s+kept\s+at\s+least\s+\d+\s+hours\s+apart\s+from\s+[^,\.\n]+",
|
||||
r"do\s+not\s+exceed\s+\d+\s+doses\s+within\s+\d+\s+hours",
|
||||
r"without\s+starting\s+new\s+uric\s+acid\s+reducers[^\.\n,]*",
|
||||
r"alongside\s+[^,\.\n]+\s+to\s+optimize\s+[^,\.\n]+",
|
||||
r"alongside\s+[^,\.\n]+\s+to\s+maximize\s+[^,\.\n]+",
|
||||
r"(?:for\s+)?(?:a\s+)?strict\s+maximum\s+of\s+\d+\s+days?",
|
||||
r"for\s+no\s+more\s+than\s+\d+\s+days?",
|
||||
r"(?:increase|decrease|reduce|double|taper)\s+(?:the\s+)?(?:dose|dosage)(?:\s+by\s+[^,\.\n]+)?(?:\s+if\s+[^,\.\n]+)?",
|
||||
r"if\s+[^,\.\n]+?\s+(?:increase|decrease|reduce|double|taper)\s+(?:the\s+)?(?:dose|dosage)(?:\s+by\s+[^,\.\n]+)?",
|
||||
r"discontinue\s+once\s+[^,\.\n]+",
|
||||
r"stop\s+(?:taking\s+)?if\s+[^,\.\n]+",
|
||||
r"do\s+not\s+stop\s+(?:the\s+)?(?:antibiotic\s+)?course\s+early[^\.\n]*",
|
||||
r"complete\s+(?:the\s+)?full\s+course[^\.\n]*",
|
||||
]
|
||||
|
||||
DRUG_CLASS_MAP = {
|
||||
"antibiotic": ["amoxicillin", "augmentin", "azithromycin", "ciprofloxacin", "ofloxacin", "cefixime", "doxycycline", "clavulanate", "penicillin", "phexin", "clarithromycin", "nitrofurantoin", "cefuroxime", "cephalexin", "cefpodoxime"],
|
||||
"iron": ["ferrous", "iron", "folic", "autrin", "orofer"],
|
||||
"inhaler": ["budecort", "foracort", "asthalin", "seretide", "tiova", "fluticasone", "formoterol", "salbutamol", "rotacap", "budesonide", "tiotropium", "levosalbutamol"],
|
||||
"painkiller": ["paracetamol", "crocin", "ibuprofen", "combiflam", "tramadol", "aceclofenac", "diclofenac", "naproxen", "etoricoxib"],
|
||||
"antacid": ["pantop", "pan", "omeprazole", "rabeprazole", "esomeprazole", "gelusil", "digene", "sucralfate", "pantoprazole"],
|
||||
"eye drops": ["moxifloxacin", "ciprofloxacin", "tobramycin", "carboxymethylcellulose", "tears"],
|
||||
"ear drops": ["ciprofloxacin with dexamethasone", "ear drops"],
|
||||
}
|
||||
|
||||
|
||||
def deduplicate_phrases(inst_list: List[str]) -> List[str]:
|
||||
"""Helper to clean duplicate/contained strings, prioritizing complete compound clauses."""
|
||||
filtered: List[str] = []
|
||||
sorted_candidates = sorted([c.strip() for c in inst_list if c and not is_placeholder(c)], key=len, reverse=True)
|
||||
for cand in sorted_candidates:
|
||||
c_clean = cand.strip()
|
||||
if any(c_clean.lower() != other.lower() and c_clean.lower() in other.lower() for other in filtered):
|
||||
continue
|
||||
if c_clean not in filtered and c_clean.lower() not in [f.lower() for f in filtered]:
|
||||
filtered.append(c_clean)
|
||||
return filtered
|
||||
|
||||
|
||||
def instruction_agent(state: AgenticRxState, llm: Any = None) -> Dict[str, Any]:
|
||||
"""
|
||||
Instruction Agent with dynamic punctuation-independent natural language reasoning.
|
||||
"""
|
||||
input_text = state.get("input_text", "")
|
||||
feedback = state.get("validation_feedback", {}).get("instruction_agent", "")
|
||||
|
||||
extracted_inst: List[InstructionItem] = []
|
||||
|
||||
if llm is not None:
|
||||
p = prompt.INSTRUCTION_PROMPT.replace("{{VOICE_INPUT}}", input_text)
|
||||
p = p.replace("{{FEEDBACK}}", feedback if feedback else "None")
|
||||
try:
|
||||
raw_out = llm.invoke(p)
|
||||
if isinstance(raw_out, str):
|
||||
if "Prescription Input:" in raw_out:
|
||||
raw_out = raw_out.split("Prescription Input:")[-1]
|
||||
parsed = safe_parse_json(raw_out)
|
||||
if isinstance(parsed, list):
|
||||
for idx, item in enumerate(parsed):
|
||||
inst = item.get("instruction", "NONE")
|
||||
add_inst = item.get("additional_instruction", "NONE")
|
||||
if not is_placeholder(inst):
|
||||
extracted_inst.append({
|
||||
"medicine_id": item.get("medicine_id", idx + 1),
|
||||
"drug_name": item.get("drug_name", ""),
|
||||
"instruction": inst,
|
||||
"additional_instruction": add_inst if not is_placeholder(add_inst) else "NONE",
|
||||
})
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
if not extracted_inst:
|
||||
segments = segment_prescription(input_text)
|
||||
total_meds = len(segments)
|
||||
|
||||
# 1. Punctuation-Independent Clinical Advice Discovery:
|
||||
clean_input = re.sub(r"(\d+),(\d+)", r"\1\2", input_text)
|
||||
clean_input = re.sub(r"\.\s*((?:Once|Twice|Thrice|\d+\s+times|Every|Daily|At\s+bedtime|In\s+the\s+morning)[^\.,;]+?),\s*(take|administer|give|start|apply|inhale|instill)", r" \1. \2", clean_input, flags=re.IGNORECASE)
|
||||
# A. Sentence-level discovery
|
||||
raw_sentences = [s.strip() for s in re.split(r"(?<!\d)\.(?!\d)|[\n;!]", clean_input) if s.strip()]
|
||||
global_clinical_advice: List[str] = []
|
||||
|
||||
for sent in raw_sentences:
|
||||
s_clean = re.sub(r"^[\s,.\-]+", "", sent).strip()
|
||||
s_lower = s_clean.lower()
|
||||
is_class_specific = any(re.search(rf"\b{re.escape(k)}\b", s_lower) for k in DRUG_CLASS_MAP.keys())
|
||||
has_action = bool(re.search(r"(?i)\b(?:take|administer|give|prescribe|start|consume|dissolve|inhale|apply|put|instill)\b", s_clean))
|
||||
has_dose_form = bool(re.search(r"(?i)(?:\d+\s*(?:mg|g|mcg|ml|iu|%)|\b(?:tablets?|capsules?|rotacaps?|vials?|sachets?|syrups?|gels?|drops?|sprays?|ointments?|creams?|lotions?)\b)", s_clean))
|
||||
is_med_sentence = (has_action and has_dose_form) or bool(re.search(MED_ACTION_VERB_START, s_clean))
|
||||
is_advice_sentence = bool(re.search(INDEPENDENT_ADVICE_START, s_clean))
|
||||
is_freq_schedule_sentence = bool(re.search(r"(?i)\b(?:it\s+(?:should\s+be\s+taken|is\s+to\s+be\s+taken|must\s+be\s+taken|to\s+be\s+taken|is\s+taken)|take\s+(?:it|this(?:\s+medicine)?)|both(?:\s+of\s+them)?|all(?:\s+these|\s+of\s+them)?(?:\s+medicines|\s+drugs|\s+tablets)?|each(?:\s+of\s+them)?)\b", s_clean)) and bool(re.search(r"(?i)\b(?:\d+\s+times|once|twice|thrice|daily|every|at\s+bedtime|morning|night)\b", s_clean))
|
||||
|
||||
if not is_class_specific and not is_med_sentence and not is_freq_schedule_sentence and (is_advice_sentence or len(s_clean) >= 10):
|
||||
if not re.search(r"^\s*(?:Morning\s+Night|\d+\s*(?:mg|g|mcg|ml))\b", s_clean, re.IGNORECASE):
|
||||
if s_clean and s_clean not in global_clinical_advice:
|
||||
global_clinical_advice.append(s_clean)
|
||||
|
||||
# B. Continuous-Span discovery (finds unpunctuated advice phrases anywhere in raw speech)
|
||||
for adv_pat in CONTINUOUS_ADVICE_SPAN_PATTERNS:
|
||||
matches = re.finditer(adv_pat, input_text, re.IGNORECASE)
|
||||
for m in matches:
|
||||
span_txt = m.group(0).strip()
|
||||
span_lower = span_txt.lower()
|
||||
is_class_specific = any(re.search(rf"\b{re.escape(k)}\b", span_lower) for k in DRUG_CLASS_MAP.keys())
|
||||
if not is_class_specific and len(span_txt) >= 5:
|
||||
if span_txt not in global_clinical_advice and not any(span_txt.lower() in g.lower() for g in global_clinical_advice):
|
||||
global_clinical_advice.append(span_txt)
|
||||
|
||||
for idx, s in enumerate(segments):
|
||||
m_id = s["medicine_id"]
|
||||
clause = s["clause"]
|
||||
clause_lower = clause.lower()
|
||||
|
||||
# Isolate the core medication administration clause from trailing advice
|
||||
core_med_clause = re.split(
|
||||
r"(?i)\b(?:if\s+[a-zA-Z\s\-]+?(?:does\s+not|persists|worsens|increases|crosses|develops|remains)|meet\s+(?:the\s+)?doctor|please\s+see\s+me|see\s+(?:your\s+)?doctor|(?:also\s+)?take\s+walks|take\s+walks|return\s+for|come\s+for|sponge)\b",
|
||||
clause
|
||||
)[0].strip()
|
||||
|
||||
# Derive current medicine name / stem from this clause
|
||||
med_lead_match = re.search(
|
||||
r"(?:take|administer|give|consume|dissolve|inhale|apply|put|instill|start|cleanse|gently\s+massage|massage)?\s*(?:one|two|three|10\s*ml)?\s*(?:tablet|tab|capsule|cap|rotacap|vial|sachet|puff|sprays?|drops?|teaspoons?|dab\s+of|thin\s+layer\s+of|pea-sized\s+amount\s+of)?\s*(?:of\s+)?([A-Za-z0-9\-]+)",
|
||||
core_med_clause,
|
||||
re.IGNORECASE,
|
||||
)
|
||||
med_stem = med_lead_match.group(1).lower() if med_lead_match else ""
|
||||
if med_stem in ("one", "two", "three", "tab", "tablet", "capsule", "vial", "sachet", "none", "administer", "take", "start", "apply", "cleanse", "this", "print"):
|
||||
med_stem = ""
|
||||
|
||||
primary_insts: List[str] = []
|
||||
secondary_insts: List[str] = []
|
||||
|
||||
# 2a. Primary patterns in core medication clause (timing, meal, device, times-of-day)
|
||||
for pat in PRIMARY_INSTRUCTION_PATTERNS:
|
||||
matches = re.finditer(pat, core_med_clause, re.IGNORECASE)
|
||||
for m in matches:
|
||||
matched_txt = m.group(0).strip()
|
||||
matched_lower = matched_txt.lower()
|
||||
|
||||
# Guard: Inhaler device instructions should only attach to inhaler/respiratory medications
|
||||
if "inhaler" in matched_lower and not any(k in core_med_clause[:80].lower() for k in ("inhal", "rotacap", "revolizer", "puff", "spacer", "budesonide", "tiotropium", "levosalbutamol", "fluticasone")):
|
||||
continue
|
||||
|
||||
if matched_txt.lower() not in [x.lower() for x in primary_insts]:
|
||||
primary_insts.append(matched_txt)
|
||||
|
||||
# 2b. Secondary patterns in this clause (titrations, precautions, course completion)
|
||||
for pat in PER_DRUG_SECONDARY_PATTERNS:
|
||||
matches = re.finditer(pat, clause, re.IGNORECASE)
|
||||
for m in matches:
|
||||
matched_txt = m.group(0).strip()
|
||||
matched_lower = matched_txt.lower()
|
||||
# Guard: check class mismatch
|
||||
is_mismatched = False
|
||||
for class_key, class_drugs in DRUG_CLASS_MAP.items():
|
||||
if re.search(rf"\b{re.escape(class_key)}\b", matched_lower) and not (any(d in clause_lower for d in class_drugs) or (med_stem and any(d in med_stem for d in class_drugs))):
|
||||
is_mismatched = True
|
||||
break
|
||||
if not is_mismatched and matched_txt.lower() not in [x.lower() for x in secondary_insts]:
|
||||
secondary_insts.append(matched_txt)
|
||||
|
||||
# 2c. Standalone sentences matching this drug or its class
|
||||
for sent in raw_sentences:
|
||||
sent_lower = sent.lower()
|
||||
|
||||
# Check if this sentence explicitly belongs to a DIFFERENT medicine
|
||||
is_other_med = False
|
||||
for other_s in segments:
|
||||
if other_s["medicine_id"] != m_id:
|
||||
other_lead = re.search(
|
||||
r"(?:take|start|administer|give|consume|dissolve|inhale|apply|put|instill|cleanse|massage)?\s*(?:one|two|three)?\s*(?:tablet|tab|capsule|cap|rotacap|vial|sachet)?\s*(?:of\s+)?([A-Za-z0-9\-]+)",
|
||||
other_s["clause"],
|
||||
re.IGNORECASE,
|
||||
)
|
||||
other_stem = other_lead.group(1).lower() if other_lead else ""
|
||||
if other_stem and len(other_stem) >= 3 and other_stem not in ("one", "two", "three", "tab", "tablet", "capsule", "none", "this", "print") and other_stem in sent_lower and other_stem != med_stem:
|
||||
is_other_med = True
|
||||
break
|
||||
if is_other_med:
|
||||
continue
|
||||
|
||||
# Check explicit drug name or stem mention in the sentence
|
||||
mentions_this_drug = (med_stem and len(med_stem) >= 3 and med_stem in sent_lower)
|
||||
|
||||
# Check class mention (e.g. "antibiotic", "iron", "inhaler", "painkiller")
|
||||
for class_key, class_drugs in DRUG_CLASS_MAP.items():
|
||||
if re.search(rf"\b{re.escape(class_key)}\b", sent_lower) and (any(d in clause_lower for d in class_drugs) or (med_stem and any(d in med_stem for d in class_drugs))):
|
||||
mentions_this_drug = True
|
||||
|
||||
# Check broadcast/plural coreference (e.g. "Both should be taken twice daily after meals")
|
||||
is_broadcast_sent = bool(re.search(r"(?i)\b(?:both(?:\s+of\s+them|\s+medicines|\s+drugs|\s+tablets|\s+capsules)?|all(?:\s+these|\s+of\s+them)?(?:\s+medicines|\s+drugs|\s+tablets)?|each(?:\s+of\s+them)?)\s+(?:should\s+be\s+taken|are\s+to\s+be\s+taken|must\s+be\s+taken|to\s+be\s+taken|should\s+be\s+given|should\s+be|are|must\s+be)\b", sent))
|
||||
|
||||
# If sentence matches this drug or is generic unassigned advice in a 1-med prescription
|
||||
if mentions_this_drug or is_broadcast_sent or (total_meds == 1 and not is_other_med):
|
||||
is_sent_pure_advice = bool(re.search(INDEPENDENT_ADVICE_START, sent.strip())) or any(re.search(p, sent, re.IGNORECASE) for p in CONTINUOUS_ADVICE_SPAN_PATTERNS)
|
||||
# Only check primary patterns if this is NOT a pure advice/lifestyle sentence
|
||||
if not is_sent_pure_advice:
|
||||
for pat in PRIMARY_INSTRUCTION_PATTERNS:
|
||||
s_match = re.search(pat, sent, re.IGNORECASE)
|
||||
if s_match:
|
||||
s_txt = s_match.group(0).strip()
|
||||
s_lower = s_txt.lower()
|
||||
if "inhaler" in s_lower and not any(k in clause[:80].lower() for k in ("inhal", "rotacap", "revolizer", "puff", "spacer", "budesonide", "tiotropium", "levosalbutamol", "fluticasone")):
|
||||
continue
|
||||
if s_txt.lower() not in [x.lower() for x in primary_insts]:
|
||||
primary_insts.append(s_txt)
|
||||
# Check secondary patterns
|
||||
for pat in PER_DRUG_SECONDARY_PATTERNS:
|
||||
s_match = re.search(pat, sent, re.IGNORECASE)
|
||||
if s_match:
|
||||
s_txt = s_match.group(0).strip()
|
||||
s_lower = s_txt.lower()
|
||||
is_mismatched = False
|
||||
for class_key, class_drugs in DRUG_CLASS_MAP.items():
|
||||
if re.search(rf"\b{re.escape(class_key)}\b", s_lower) and not (any(d in clause_lower for d in class_drugs) or (med_stem and any(d in med_stem for d in class_drugs))):
|
||||
is_mismatched = True
|
||||
break
|
||||
if not is_mismatched and s_txt.lower() not in [x.lower() for x in secondary_insts]:
|
||||
secondary_insts.append(s_txt)
|
||||
|
||||
# 2d. Inhaler device care (Primary)
|
||||
if any(k in clause[:80].lower() for k in ("budecort", "foracort", "inhaler", "rotacap", "asthalin", "budesonide", "revolizer", "tiotropium")):
|
||||
for lf in ("be sure to rinse your mouth thoroughly after using the inhaler", "rinse your mouth thoroughly after using the inhaler", "rinse your mouth immediately", "rinse mouth after using the inhaler", "rinse mouth after use"):
|
||||
if lf in input_text.lower() and lf not in [x.lower() for x in primary_insts]:
|
||||
primary_insts.append(lf)
|
||||
|
||||
# 2e. Attach global independent advice sentences to the secondary instructions of the final medicine record
|
||||
if idx == total_meds - 1:
|
||||
for adv in global_clinical_advice:
|
||||
if adv.lower() not in [x.lower() for x in secondary_insts]:
|
||||
secondary_insts.append(adv)
|
||||
|
||||
clean_primary = deduplicate_phrases(primary_insts)
|
||||
clean_secondary = deduplicate_phrases(secondary_insts)
|
||||
|
||||
formatted_primary = " ".join(f"{i+1}. {txt}" for i, txt in enumerate(clean_primary)) if clean_primary else "NONE"
|
||||
formatted_secondary = " ".join(f"{i+1}. {txt}" for i, txt in enumerate(clean_secondary)) if clean_secondary else "NONE"
|
||||
|
||||
extracted_inst.append({
|
||||
"medicine_id": m_id,
|
||||
"drug_name": med_stem,
|
||||
"instruction": formatted_primary,
|
||||
"additional_instruction": formatted_secondary,
|
||||
})
|
||||
|
||||
return {"instructions": extracted_inst}
|
||||
@@ -0,0 +1,136 @@
|
||||
"""
|
||||
agents/medicine_strength_agent.py
|
||||
---------------------------------
|
||||
Medicine & Strength Agent:
|
||||
Drift-proof extractor for drug names and strengths across any clinical prescription format.
|
||||
"""
|
||||
import re
|
||||
from typing import Dict, Any, List
|
||||
from graph_state import AgenticRxState, MedicineItem
|
||||
from agents.utils import (
|
||||
FORM_PATTERN,
|
||||
ACTION_VERBS_PATTERN,
|
||||
is_placeholder,
|
||||
safe_parse_json,
|
||||
segment_prescription,
|
||||
)
|
||||
import prompt
|
||||
|
||||
DOSAGE_REGEX = r"\d+(?:\.\d+)?\s*(?:mg(?:\/ml|\/g)?|g|mcg|µg|ml|l|iu|units?|%|meq|puffs?|drops?|tablets?|capsules?|sachets?|vials?)"
|
||||
|
||||
|
||||
def medicine_strength_agent(state: AgenticRxState, llm: Any = None) -> Dict[str, Any]:
|
||||
"""
|
||||
Medicine & Strength Agent.
|
||||
"""
|
||||
input_text = state.get("input_text", "")
|
||||
feedback = state.get("validation_feedback", {}).get("medicine_agent", "")
|
||||
|
||||
extracted_meds: List[MedicineItem] = []
|
||||
|
||||
if llm is not None:
|
||||
p = prompt.MEDICINE_STRENGTH_PROMPT.replace("{{VOICE_INPUT}}", input_text)
|
||||
p = p.replace("{{FEEDBACK}}", feedback if feedback else "None")
|
||||
try:
|
||||
raw_out = llm.invoke(p)
|
||||
if isinstance(raw_out, str):
|
||||
if "Prescription Input:" in raw_out:
|
||||
raw_out = raw_out.split("Prescription Input:")[-1]
|
||||
parsed = safe_parse_json(raw_out)
|
||||
if isinstance(parsed, list):
|
||||
for idx, item in enumerate(parsed):
|
||||
d_name = item.get("drug_name") or item.get("Drug_name", "")
|
||||
strength = item.get("strength", "NONE")
|
||||
if d_name and d_name != "NONE" and not is_placeholder(d_name):
|
||||
core_words = [
|
||||
w for w in re.findall(r"[A-Za-z0-9\-]+", d_name)
|
||||
if len(w) >= 3 and w.lower() not in (
|
||||
"take", "tab", "tabs", "tablet", "capsule", "syrup",
|
||||
"pill", "rotacap", "none", "vial", "sachet", "one", "administer"
|
||||
)
|
||||
]
|
||||
if core_words and any(cw.lower() in input_text.lower() for cw in core_words):
|
||||
d_name = re.sub(FORM_PATTERN, "", d_name).strip()
|
||||
d_name = re.sub(ACTION_VERBS_PATTERN, "", d_name).strip()
|
||||
d_name = re.sub(r"\s+", " ", d_name).strip()
|
||||
extracted_meds.append({
|
||||
"medicine_id": idx + 1,
|
||||
"drug_name": d_name,
|
||||
"strength": "NONE" if is_placeholder(strength) else (strength if strength else "NONE"),
|
||||
})
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
if not extracted_meds:
|
||||
segments = segment_prescription(input_text)
|
||||
for s in segments:
|
||||
m_id = s["medicine_id"]
|
||||
clause = s["clause"]
|
||||
seed = s.get("seed_name", "")
|
||||
|
||||
if seed:
|
||||
cleaned_name = re.sub(FORM_PATTERN, "", seed).strip()
|
||||
cleaned_name = re.sub(ACTION_VERBS_PATTERN, "", cleaned_name).strip()
|
||||
cleaned_name = re.sub(r"(?i)^(?:take\s+|administer\s+|give\s+|prescribe\s+|start\s+)?(?:\d+\s+|one\s+|two\s+|three\s+)?", "", cleaned_name).strip()
|
||||
cleaned_name = re.sub(r"\b(?:of|one|vial|sachet|combination|ear|eye|nasal|oral|topical)\b", "", cleaned_name, flags=re.IGNORECASE).strip()
|
||||
extracted_meds.append({
|
||||
"medicine_id": m_id,
|
||||
"drug_name": re.sub(r"\s+", " ", cleaned_name).strip(),
|
||||
"strength": "NONE",
|
||||
})
|
||||
else:
|
||||
doses = list(re.finditer(DOSAGE_REGEX, clause, re.IGNORECASE))
|
||||
|
||||
if doses:
|
||||
first_dose_match = doses[0]
|
||||
first_dose_end = first_dose_match.end()
|
||||
first_dose_txt = first_dose_match.group(0).strip()
|
||||
|
||||
raw_lead = clause[:first_dose_match.start()].strip()
|
||||
cleaned_name = re.sub(FORM_PATTERN, "", raw_lead).strip()
|
||||
cleaned_name = re.sub(ACTION_VERBS_PATTERN, "", cleaned_name).strip()
|
||||
cleaned_name = re.sub(r"(?i)^(?:take|administer|give|start|prescribe|consume|dissolve|inhale|apply|put|instill|inject|infuse)\s+", "", cleaned_name).strip()
|
||||
cleaned_name = re.sub(r"(?i)^(?:of\s+|a\s+|an\s+|the\s+)", "", cleaned_name).strip()
|
||||
cleaned_name = re.sub(r"[\s,;\-]+$", "", cleaned_name).strip()
|
||||
cleaned_name = re.sub(r"\s*,\s*", " ", cleaned_name).strip()
|
||||
|
||||
second_dose_txt = "NONE"
|
||||
if len(doses) >= 2:
|
||||
second_dose_cand = doses[1]
|
||||
gap_text = clause[first_dose_end:second_dose_cand.start()].strip()
|
||||
if len(gap_text) <= 5 or gap_text.lower() in ("+", "/", "and", "with"):
|
||||
second_dose_txt = second_dose_cand.group(0).strip()
|
||||
|
||||
full_drug_name = f"{cleaned_name} {first_dose_txt}".strip()
|
||||
full_drug_name = re.sub(r"(?i)^(?:take\s+|administer\s+|give\s+|prescribe\s+|start\s+)?(?:\d+\s+|one\s+|two\s+|three\s+)?(?:of\s+|a\s+|an\s+|the\s+)?", "", full_drug_name).strip()
|
||||
full_drug_name = re.sub(r"(?i)\s+(?:orally|topically|by\s+mouth|inhale|apply|combination)$", "", full_drug_name).strip()
|
||||
full_drug_name = re.sub(r"[\s,;\-]+(?=\s+\d)", "", full_drug_name).strip()
|
||||
full_drug_name = re.sub(r"\s+", " ", full_drug_name).strip()
|
||||
|
||||
extracted_meds.append({
|
||||
"medicine_id": m_id,
|
||||
"drug_name": full_drug_name,
|
||||
"strength": second_dose_txt,
|
||||
})
|
||||
else:
|
||||
match_nodose = re.search(
|
||||
r"(?:take|administer|give|consume|dissolve|inhale|apply|put|instill|gently\s+massage|massage|cleanse)?\s*(?:one|two|three)?\s*(?:tablet|tab|capsule|cap|rotacap|pill|vial|sachet|puff)?\s*(?:of\s+)?([A-Za-z0-9\-]+(?:\s+[A-Za-z0-9\-]+){0,3}?)\s*(?:tablet|capsule|oral\s+suspension|suspension|sachet|vial|cream|ointment|gel|drops|rotacap|puff|paste|wash|orally|topically|by\s+mouth|before|after|twice|once|three|up\s+to|in\s+one\s+liter|every|onto|along|to\s+the|over)\b",
|
||||
clause,
|
||||
re.IGNORECASE,
|
||||
)
|
||||
if match_nodose:
|
||||
raw_name = match_nodose.group(1).strip()
|
||||
cleaned_name = re.sub(FORM_PATTERN, "", raw_name).strip()
|
||||
cleaned_name = re.sub(ACTION_VERBS_PATTERN, "", cleaned_name).strip()
|
||||
cleaned_name = re.sub(r"\b(?:of|one|vial|sachet|combination)\b", "", cleaned_name, flags=re.IGNORECASE).strip()
|
||||
if cleaned_name and len(cleaned_name) >= 3 and cleaned_name.lower() not in ("stick", "avoid", "visit", "seek", "please", "keep", "fomentation"):
|
||||
extracted_meds.append({
|
||||
"medicine_id": m_id,
|
||||
"drug_name": re.sub(r"\s+", " ", cleaned_name).strip(),
|
||||
"strength": "NONE",
|
||||
})
|
||||
|
||||
if not extracted_meds:
|
||||
extracted_meds.append({"medicine_id": 1, "drug_name": "NONE", "strength": "NONE"})
|
||||
|
||||
return {"medicines": extracted_meds}
|
||||
@@ -0,0 +1,98 @@
|
||||
"""
|
||||
agents/route_agent.py
|
||||
---------------------
|
||||
Route Agent:
|
||||
Clinical route of administration extractor with complete multi-specialty coverage.
|
||||
"""
|
||||
import re
|
||||
from typing import Dict, Any, List
|
||||
from graph_state import AgenticRxState, RouteItem
|
||||
from agents.utils import (
|
||||
is_placeholder,
|
||||
safe_parse_json,
|
||||
segment_prescription,
|
||||
)
|
||||
import prompt
|
||||
|
||||
|
||||
def route_agent(state: AgenticRxState, llm: Any = None) -> Dict[str, Any]:
|
||||
"""
|
||||
Route Agent.
|
||||
"""
|
||||
input_text = state.get("input_text", "")
|
||||
feedback = state.get("validation_feedback", {}).get("route_agent", "")
|
||||
|
||||
extracted_routes: List[RouteItem] = []
|
||||
|
||||
if llm is not None:
|
||||
p = prompt.ROUTE_PROMPT.replace("{{VOICE_INPUT}}", input_text)
|
||||
p = p.replace("{{FEEDBACK}}", feedback if feedback else "None")
|
||||
try:
|
||||
raw_out = llm.invoke(p)
|
||||
if isinstance(raw_out, str):
|
||||
if "Prescription Input:" in raw_out:
|
||||
raw_out = raw_out.split("Prescription Input:")[-1]
|
||||
parsed = safe_parse_json(raw_out)
|
||||
if isinstance(parsed, list):
|
||||
for idx, item in enumerate(parsed):
|
||||
r_val = item.get("route", "NONE").lower().strip()
|
||||
if not is_placeholder(r_val):
|
||||
extracted_routes.append({
|
||||
"medicine_id": item.get("medicine_id", idx + 1),
|
||||
"drug_name": item.get("drug_name", ""),
|
||||
"route": r_val if r_val else "NONE",
|
||||
})
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
if not extracted_routes:
|
||||
segments = segment_prescription(input_text)
|
||||
input_lower = input_text.lower()
|
||||
|
||||
for s in segments:
|
||||
m_id = s["medicine_id"]
|
||||
clause = s["clause"]
|
||||
# Extract first 60 chars of clause (the core medicine administration directive)
|
||||
core_directive = clause[:80].lower()
|
||||
clause_lower = clause.lower()
|
||||
|
||||
route = "NONE"
|
||||
|
||||
# 1. Check immediate form and administration verb in the core directive first
|
||||
if any(w in core_directive for w in ("ear drops", "affected ear", "eardrum", "into each ear")):
|
||||
route = "otic"
|
||||
elif any(w in core_directive for w in ("eye drops", "into both eyes", "into left eye", "into right eye")):
|
||||
route = "ophthalmic"
|
||||
elif any(w in core_directive for w in ("nasal spray", "nasal drops", "into each nostril", "both nostrils")):
|
||||
route = "nasal"
|
||||
elif any(w in core_directive for w in ("inhale", "rotacap", "puff", "revolizer", "spacer", "turbuhaler", "respule", "inhaler")):
|
||||
route = "inhalation"
|
||||
elif any(w in core_directive for w in ("apply", "gel", "ointment", "cream", "lotion", "massage", "sunscreen", "cleanse", "wash")):
|
||||
route = "topical"
|
||||
elif any(w in core_directive for w in ("tablet", "tab", "capsule", "cap", "syrup", "sachet", "pill", "suspension", "vial", "consume", "dissolve", "drinking water", "take", "administer", "give", "gargle", "mouthwash", "lozenge", "paste", "mixed in milk", "orally", "overly", "by mouth")):
|
||||
route = "oral"
|
||||
|
||||
# 2. Check full clause if not resolved by core directive
|
||||
if route == "NONE":
|
||||
if any(w in clause_lower for w in ("ear drops", "affected ear", "eardrum")):
|
||||
route = "otic"
|
||||
elif any(w in clause_lower for w in ("eye drops", "ophthalmic")):
|
||||
route = "ophthalmic"
|
||||
elif any(w in clause_lower for w in ("nasal spray", "nasal drops", "nostril")):
|
||||
route = "nasal"
|
||||
elif any(w in clause_lower for w in ("rotacap", "revolizer", "puff", "spacer", "turbuhaler")):
|
||||
route = "inhalation"
|
||||
elif any(w in clause_lower for w in ("onto your lower back", "along the clean suture line", "to the affected patches", "over dry skin", "sunscreen")):
|
||||
route = "topical"
|
||||
elif any(w in clause_lower for w in ("tablet", "tab", "capsule", "cap", "syrup", "sachet", "pill", "vial", "orally", "by mouth")):
|
||||
route = "oral"
|
||||
elif "take" in input_lower or "administer" in input_lower or "consume" in input_lower:
|
||||
route = "oral"
|
||||
|
||||
extracted_routes.append({
|
||||
"medicine_id": m_id,
|
||||
"drug_name": "",
|
||||
"route": route,
|
||||
})
|
||||
|
||||
return {"routes": extracted_routes}
|
||||
@@ -0,0 +1,36 @@
|
||||
"""
|
||||
agents/supervisor_agent.py
|
||||
--------------------------
|
||||
Supervisor Agent: Coordinates multi-agent graph execution, cleans conversational noise/transcription artifacts,
|
||||
tracks iterations (capped at max 3), and routes targeted feedback across iterations.
|
||||
"""
|
||||
from typing import Dict, Any
|
||||
from graph_state import AgenticRxState
|
||||
from agents.utils import clean_noise_and_chatter
|
||||
|
||||
|
||||
def supervisor_node(state: AgenticRxState, llm: Any = None) -> Dict[str, Any]:
|
||||
"""
|
||||
Supervisor Agent:
|
||||
Cleans transcript noise and coordinates parallel extraction tasks.
|
||||
"""
|
||||
raw_input = state.get("input_text", "").strip()
|
||||
cleaned_input = clean_noise_and_chatter(raw_input)
|
||||
current_iteration = state.get("iteration_count", 0) + 1
|
||||
feedback = state.get("validation_feedback", {})
|
||||
|
||||
log_entry = {
|
||||
"agent": "Supervisor",
|
||||
"iteration": current_iteration,
|
||||
"action": "Noise filtering & dispatching parallel extraction agents",
|
||||
"has_feedback": bool(feedback and any(feedback.values())),
|
||||
}
|
||||
|
||||
current_logs = list(state.get("agent_logs", []))
|
||||
current_logs.append(log_entry)
|
||||
|
||||
return {
|
||||
"input_text": cleaned_input if cleaned_input else raw_input,
|
||||
"iteration_count": current_iteration,
|
||||
"agent_logs": current_logs,
|
||||
}
|
||||
@@ -0,0 +1,313 @@
|
||||
"""
|
||||
agents/utils.py
|
||||
---------------
|
||||
Shared helper utilities, JSON parsers, noise filters, and multi-medicine clause segmenters.
|
||||
"""
|
||||
import re
|
||||
import json
|
||||
from typing import Any, Optional, List, Dict
|
||||
|
||||
FORM_PATTERN = r"(?i)\b(tablets?|tabs?|capsules?|caps?|rotacaps?|pills?|syrups?|gels?|drops?|sprays?|ointments?|creams?|sachets?|lozenges?|puffs?|respules?|suspensions?|solutions?|vials?|lotions?|patches?|suppositor(?:y|ies)|pastes?|mouthwash(?:es)?|washes?)\b"
|
||||
|
||||
ACTION_VERBS_PATTERN = (
|
||||
r"(?i)^(?:administer\s+one\s+tablet\s+of|administer\s+one\s+tab\s+of|administer\s+one\s+capsule\s+of|"
|
||||
r"administer\s+two\s+sprays\s+of|administer\s+one\s+spray\s+of|administer\s+two\s+drops\s+of|"
|
||||
r"administer\s+three\s+drops\s+of|administer\s+one\s+of|administer\s+one|administer\s+tablet\s+of|"
|
||||
r"administer\s+tab\s+of|administer|"
|
||||
r"give\s+one\s+tablet\s+of|give\s+one|give|"
|
||||
r"prescribe\s+one|prescribe|"
|
||||
r"start\s+one|start|"
|
||||
r"take\s+one\s+combination\s+tablet\s+of|take\s+one\s+tablet\s+of|take\s+one\s+tab\s+of|take\s+one\s+capsule\s+of|"
|
||||
r"take\s+one\s+vial\s+of|take\s+one\s+sachet\s+of|take\s+one\s+single\s+dose\s+of|take\s+single\s+dose\s+of|single\s+dose\s+of|single\s+dose|"
|
||||
r"take\s+one\s+of|take\s+one|"
|
||||
r"take\s+two\s+teaspoons\s+of|take\s+two\s+teaspoon\s+of|take\s+10\s*ml\s+of|take\s+two\s+tablets\s+of|take\s+two|"
|
||||
r"take\s+tablet\s+of|take\s+tab\s+of|take\s+capsule\s+of|"
|
||||
r"take\s+(?!(?:walks?|a\s+walk|rest|care|steam|bath|deep\s+breaths?|precautions?|fomentation|ice|hot\s+water|cold\s+water))\b|"
|
||||
r"consume\s+one\s+vial\s+of|consume\s+one\s+sachet\s+of|consume\s+one|consume|"
|
||||
r"dissolve\s+one\s+sachet\s+of|dissolve\s+one|dissolve|"
|
||||
r"slowly\s+dissolve\s+one|slowly\s+dissolve|"
|
||||
r"inhale\s+one\s+rotacap\s+of|inhale\s+one\s+puff\s+of|inhale\s+two\s+puffs\s+of|inhale\s+one\s+capsule\s+of|inhale\s+one|inhale\s+two|inhale|"
|
||||
r"apply\s+a\s+thin\s+layer\s+of|apply\s+a\s+pea-sized\s+amount\s+of|apply\s+a\s+dab\s+of|apply\s+a\s+bland\s+moisturizing|apply\s+broad-spectrum|apply\s+one|apply|"
|
||||
r"gently\s+massage|massage|"
|
||||
r"rub\s+one|rub|"
|
||||
r"spray\s+one|spray|"
|
||||
r"cleanse\s+the\s+skin\s+gently\s+using|cleanse|"
|
||||
r"put\s+one|put|instill\s+two\s+drops\s+of|instill\s+three\s+drops\s+of|instill\s+two|instill\s+three|instill\s+one|instill|inject\s+one|inject|infuse\s+one|infuse|"
|
||||
r"thin\s+layer\s+of|layer\s+of|layer|pea-sized\s+amount\s+of|amount\s+of|amount|dab\s+of|dab|combined|skin\s+gently\s+using)\s+"
|
||||
)
|
||||
|
||||
SPEAKER_HEADER_PATTERN = r"(?i)\b[A-Za-z\s\.\-]{2,30},\s*(?:yesterday|today|tomorrow|\d{1,2}[\/\-]\d{1,2}(?:[\/\-]\d{2,4})?)[\s\u202f\xa0]*\d{1,2}:\d{2}[\s\u202f\xa0]*(?:[ap]\.?m\.?)?\s*"
|
||||
|
||||
# Conversational chatter, greetings, examination findings, and filler patterns
|
||||
CONVERSATIONAL_NOISE_PATTERNS = [
|
||||
r"(?i)\b(?:hello|hi|hey|good\s+morning|good\s+afternoon|good\s+evening)\s*(?:doctor|dr\.|mr\.|mrs\.|ms\.)?(?:\s+[A-Za-z]+)?\b[^\.\n;!?]*[\.\n;!?]?",
|
||||
r"(?i)\bhow\s+are\s+you\s+(?:feeling|doing)?(?:\s+today)?\b[^\.\n;!?]*[\.\n;!?]?",
|
||||
r"(?i)\b(?:i\s+have|patient\s+complains\s+of|complaining\s+of|suffering\s+from|history\s+of|diagnosed\s+with|patient\s+has)\s+[^\.\n;!?]+[\.\n;!?]?",
|
||||
r"(?i)\b(?:let\s+me\s+check\s+your\s+[^\.\n;!?]+)[\.\n;!?]?",
|
||||
r"(?i)\b(?:throat\s+is\s+congested|chest\s+is\s+clear|tonsils\s+are\s+swollen)[\.\n;!?]?",
|
||||
r"(?i)\b(?:bp\s+is|pulse\s+is|temperature\s+is|spo2\s+is|saturation\s+is|weight\s+is)\s+[^,\.\n;!]+[\.\n;!?]?",
|
||||
r"(?i)\b(?:thank\s+you(?:\s+very\s+much)?(?:\s+doctor)?|thanks\s+doctor|thanks)\b[^\.\n;!?]*[\.\n;!?]?",
|
||||
r"(?i)\b(?:have\s+a\s+(?:nice|great|good)\s+day|take\s+care(?:\s+bye)?|goodbye|see\s+you\s+(?:next\s+time|soon|after\s+a\s+week))\b[^\.\n;!?]*[\.\n;!?]?",
|
||||
r"(?i)\b(?:i\s+will\s+follow\s+this|sure\s+doctor|okay\s+doctor|understood\s+doctor|alright\s+doctor)\b[^\.\n;!?]*[\.\n;!?]?",
|
||||
r"(?i)\b(?:patient|name|age|gender|sex|recorded\s+on|appointment\s+id):\s*[^\.\n,]+[,\.]?",
|
||||
]
|
||||
|
||||
# Non-medication entity blacklist (prevents noisy terms from becoming drug names)
|
||||
INVALID_DRUG_NAMES_LOWER = {
|
||||
"doctor", "dr", "patient", "individual", "individuals", "person", "persons", "people",
|
||||
"mr", "mrs", "ms", "this", "that", "none", "take", "give", "start", "apply", "cleanse", "massage",
|
||||
"ice packs", "ice pack", "fomentation", "hot water fomentation", "water", "drinking water",
|
||||
"hot water", "cold water", "tap water", "salt water", "saline water", "cloth", "towel", "bandage", "tape",
|
||||
"endoscopy", "endoscopy report", "x-ray", "ultrasound", "mri", "ecg", "blood test", "blood test results",
|
||||
"urine culture", "biopsy", "examination", "vitals", "report", "results", "appointment", "consultation",
|
||||
"blood pressure", "bp", "pulse", "temperature", "saturation", "spo2", "weight", "chest", "throat", "abdomen",
|
||||
"good morning", "thank you", "thanks", "how are you", "have a nice day", "goodbye", "bye", "okay", "alright",
|
||||
"walks", "morning walks", "rest", "steam", "steam inhalation", "pregnant", "pregnant individuals"
|
||||
}
|
||||
|
||||
|
||||
def is_placeholder(val: Any) -> bool:
|
||||
"""Checks if a string is a template placeholder copied by smaller LLMs."""
|
||||
if not isinstance(val, str):
|
||||
return False
|
||||
s = val.strip().lower()
|
||||
if s.startswith("<") and s.endswith(">"):
|
||||
return True
|
||||
placeholder_signatures = [
|
||||
"<exact drug name",
|
||||
"<second dose",
|
||||
"<verbatim",
|
||||
"<oral|",
|
||||
"<instruction",
|
||||
"primary dose>",
|
||||
"second dose or none",
|
||||
"verbatim frequency",
|
||||
"verbatim duration",
|
||||
"<drug name>",
|
||||
]
|
||||
return any(sig in s for sig in placeholder_signatures)
|
||||
|
||||
|
||||
def is_valid_medication_entity(drug_name: str) -> bool:
|
||||
"""
|
||||
Noise-proofing filter: Validates whether a candidate string represents a genuine pharmaceutical entity.
|
||||
Rejects conversational chatter, diagnostic tests, vital signs, physical items, and non-drug terms.
|
||||
"""
|
||||
if not drug_name or is_placeholder(drug_name):
|
||||
return False
|
||||
name_clean = drug_name.strip()
|
||||
name_lower = name_clean.lower()
|
||||
|
||||
if name_lower in ("none", "", "null", "n/a"):
|
||||
return False
|
||||
|
||||
# Check exact blacklist matches
|
||||
if name_lower in INVALID_DRUG_NAMES_LOWER:
|
||||
return False
|
||||
|
||||
# Check substring blacklist matches
|
||||
for invalid in ("pregnant individuals", "endoscopy report", "blood pressure", "urine culture", "blood test", "ice packs", "fomentation", "thank you", "good morning"):
|
||||
if invalid in name_lower and not any(unit in name_lower for unit in ("mg", "mcg", "ml", "iu", "%", "g")):
|
||||
return False
|
||||
|
||||
# Must contain at least one word character of length >= 2
|
||||
words = re.findall(r"[A-Za-z0-9\-]+", name_clean)
|
||||
if not words:
|
||||
return False
|
||||
|
||||
# Reject if it consists purely of noise words
|
||||
meaningful_words = [w for w in words if w.lower() not in ("take", "one", "two", "three", "tablet", "capsule", "syrup", "pill", "none", "of", "and", "with", "the", "a", "an")]
|
||||
if not meaningful_words:
|
||||
return False
|
||||
|
||||
return True
|
||||
|
||||
|
||||
def clean_noise_and_chatter(input_text: str) -> str:
|
||||
"""
|
||||
Noise-proofing cleaner: Filters conversational chatter, doctor-patient greetings,
|
||||
examination findings, and audio recording timestamps from raw transcripts.
|
||||
"""
|
||||
if not input_text:
|
||||
return ""
|
||||
|
||||
cleaned = re.sub(SPEAKER_HEADER_PATTERN, ". Take ", input_text).strip()
|
||||
for pat in CONVERSATIONAL_NOISE_PATTERNS:
|
||||
cleaned = re.sub(pat, " ", cleaned)
|
||||
|
||||
cleaned = re.sub(r"\s+", " ", cleaned).strip()
|
||||
return cleaned
|
||||
|
||||
|
||||
def clean_instruction_noise(inst_text: str) -> str:
|
||||
"""
|
||||
Filters conversational banter and greeting residues from instructions.
|
||||
"""
|
||||
if not inst_text or inst_text.upper() == "NONE":
|
||||
return "NONE"
|
||||
|
||||
cleaned = inst_text
|
||||
for pat in CONVERSATIONAL_NOISE_PATTERNS:
|
||||
cleaned = re.sub(pat, "", cleaned)
|
||||
|
||||
cleaned = re.sub(r"\s+", " ", cleaned).strip()
|
||||
return cleaned if cleaned else "NONE"
|
||||
|
||||
|
||||
def safe_parse_json(text: str) -> Optional[Any]:
|
||||
"""Attempts to extract and parse JSON array or object from LLM response."""
|
||||
if not text:
|
||||
return None
|
||||
try:
|
||||
return json.loads(text.strip())
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
match = re.search(r"```(?:json)?\s*([\s\S]*?)\s*```", text)
|
||||
if match:
|
||||
try:
|
||||
return json.loads(match.group(1).strip())
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
arr_match = re.search(r"\[\s*\{[\s\S]*\}\s*\]", text)
|
||||
if arr_match:
|
||||
try:
|
||||
return json.loads(arr_match.group(0).strip())
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
obj_match = re.search(r"\{[\s\S]*\}", text)
|
||||
if obj_match:
|
||||
try:
|
||||
return json.loads(obj_match.group(0).strip())
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
return None
|
||||
|
||||
|
||||
def segment_prescription(input_text: str) -> List[Dict[str, Any]]:
|
||||
"""
|
||||
Robustly segments multi-medicine prescriptions into discrete clauses.
|
||||
Recognizes all transition points, companion drugs, and filters non-drug advice sentences.
|
||||
Works seamlessly with or without punctuation.
|
||||
"""
|
||||
clean_text = clean_noise_and_chatter(input_text)
|
||||
clean_text = re.sub(r"(\d+),(\d+)", r"\1\2", clean_text)
|
||||
# Bridge schedule/duration clauses split across periods (e.g. "capsule. Once daily for 14 days, take...")
|
||||
clean_text = re.sub(r"\.\s*((?:Once|Twice|Thrice|\d+\s+times|Every|Daily|At\s+bedtime|In\s+the\s+morning)[^\.,;]+?),\s*(take|administer|give|start|apply|inhale|instill)", r" \1. \2", clean_text, flags=re.IGNORECASE)
|
||||
|
||||
# 1. Break into sentences by standard sentence punctuation (decimal-safe)
|
||||
raw_sentences = [s.strip() for s in re.split(r"(?<!\d)\.(?!\d)|[\n;!]", clean_text) if s.strip()]
|
||||
|
||||
# 2. Split intra-sentence transition points (e.g. "Take A, and take B, also start C")
|
||||
split_pattern = (
|
||||
r"(?i)(?:,\s*(?:and\s+take|also\s+take|additionally(?:,\s*take)?|then\s+take|take\s+one|take\s+two|take\s+10\s*ml|take\s+\d+|take\s+(?!(?:walks?|a\s+walk|rest|care|steam|bath|water|regular\s+water|warm\s+water|cold\s+water|fluids?|food|meals?))\b|"
|
||||
r"and\s+start|also\s+start|start\s+one|start|"
|
||||
r"and\s+administer|also\s+administer|administer\s+one|administer\s+two|administer|"
|
||||
r"and\s+give|also\s+give|give\s+one|give|"
|
||||
r"and\s+consume|also\s+consume|consume\s+one|consume|"
|
||||
r"and\s+dissolve|also\s+dissolve|dissolve\s+one|dissolve|slowly\s+dissolve|"
|
||||
r"and\s+inhale|also\s+inhale|inhale\s+one|inhale\s+two|inhale|"
|
||||
r"and\s+apply|also\s+apply|apply\s+a\s+thin|apply\s+a\s+pea-sized|apply\s+a\s+dab|apply\s+broad-spectrum|apply\s+one|apply|"
|
||||
r"and\s+gently\s+massage|gently\s+massage|and\s+massage|massage|"
|
||||
r"and\s+rub|also\s+rub|rub\s+one|rub|"
|
||||
r"and\s+spray|also\s+spray|spray\s+one|spray|"
|
||||
r"and\s+instill|also\s+instill|instill\s+two|instill\s+three|instill\s+one|instill|"
|
||||
r"and\s+cleanse|cleanse\s+the\s+skin|cleanse|"
|
||||
r"and\s+put|also\s+put|put\s+one|put|inject\s+one|inject|infuse\s+one|infuse)|"
|
||||
r"\band\s+take\s+\d+\b|\band\s+take\s+(?!(?:walks?|a\s+walk|rest|care|steam|bath|water|regular\s+water|warm\s+water|cold\s+water|fluids?|food|meals?))\b|"
|
||||
r"\balso\s+take\s+(?!(?:walks?|a\s+walk|rest|care|steam|bath|water|regular\s+water|warm\s+water|cold\s+water|fluids?|food|meals?))\b|"
|
||||
r"\badditionally\b|\bthen\s+take\b|"
|
||||
r"\band\s+start\b|\band\s+administer\b|\band\s+consume\b|\band\s+dissolve\b|\band\s+spray\b|\band\s+instill\b|\binhale\s+one\b|\binhale\s+two\b|\bapply\s+one\b|\bapply\s+a\b|"
|
||||
r"\bkeep\s+the\s+blistered\s+area\b|\bavoid\s+close\s+physical\s+contact\b|\breturn\s+if\s+the\s+rash\b)"
|
||||
)
|
||||
|
||||
clauses: List[str] = []
|
||||
for sent in raw_sentences:
|
||||
sub_clauses = [c.strip() for c in re.split(split_pattern, sent) if c.strip()]
|
||||
clauses.extend(sub_clauses if sub_clauses else [sent])
|
||||
|
||||
if not clauses:
|
||||
clauses = [clean_text]
|
||||
|
||||
segments: List[Dict[str, Any]] = []
|
||||
med_id = 1
|
||||
|
||||
# Non-drug trigger keywords that indicate a clause is advice/follow-up, not a medicine
|
||||
PURE_ADVICE_TRIGGERS = [
|
||||
r"^(?:return|come\s+back|follow\s+up|review|get\s+reassessed|seek|consult|contact|report|visit|revisit|arrange|schedule|repeat|re-?test)\b",
|
||||
r"^(?:meet\s+(?:the\s+)?doctor|please\s+see\s+me|see\s+(?:your\s+|the\s+)?doctor|come\s+(?:and\s+)?visit\s+(?:the\s+|your\s+)?doctor|visit\s+(?:the\s+|your\s+)?doctor)\b",
|
||||
r"^(?:do\s+not|avoid|strictly\s+avoid|discontinue|stop|keep|maintain|stick\s+to|include|limit|practice|brush|perform)\b",
|
||||
r"^(?:drink|consume|stay\s+well-hydrated|apply\s+local|apply\s+ice|sponge|wear|monitor|be\s+sure\s+to|if\s+)\b",
|
||||
r"^(?:take\s+(?:regular\s+|warm\s+|cold\s+|plenty\s+of\s+|sufficient\s+|clean\s+)?(?:water|fluids?))\b",
|
||||
r"(?:also\s+)?take\s+walks?",
|
||||
r"go\s+for\s+(?:morning\s+)?walks?",
|
||||
r"(?:apply\s+)?(?:local\s+)?hot\s+water\s+fomentation",
|
||||
r"(?:apply\s+)?ice\s+packs?",
|
||||
r"sponge\s+(?:the\s+)?(?:body|forehead)",
|
||||
r"keep\s+(?:the\s+)?(?:blistered|affected|skin|dressing|ear)\s+area\s+clean\s+and\s+dry",
|
||||
r"avoid\s+close\s+physical\s+contact",
|
||||
]
|
||||
|
||||
NON_DRUG_WITH = (
|
||||
"food", "meals", "meal", "water", "milk", "breakfast", "lunch", "dinner", "juice",
|
||||
"caution", "care", "warm", "cold", "tap", "equal", "a", "an", "the", "endoscopy", "report",
|
||||
"doctor", "review", "evaluation", "prescription", "consultation", "food", "stomach", "walks",
|
||||
"pregnant", "individuals", "persons", "children", "people"
|
||||
)
|
||||
|
||||
for clause in clauses:
|
||||
clause_clean = clause.strip()
|
||||
# If this clause is purely advice without medication, skip creating a medicine block
|
||||
is_advice = any(re.search(pat, clause_clean, re.IGNORECASE) for pat in PURE_ADVICE_TRIGGERS)
|
||||
if is_advice:
|
||||
continue
|
||||
|
||||
# Check if the clause has any medication indicator (action verb, dosage, or form word)
|
||||
has_med_indicator = bool(
|
||||
re.search(r"(?i)(?:\b(?:take\s+(?!(?:walks?|rest|care|steam|water|regular\s+water|warm\s+water|cold\s+water|fluids?))\w+|administer|give|prescribe|start|consume|dissolve|inhale|apply|put|instill|inject|infuse|tablet|tab|capsule|cap|rotacap|vial|sachet|syrup|gel|drops?|spray|ointment|cream|lotion)\b|\d+\s*(?:mg|g|mcg|ml|iu|%)\b)", clause_clean)
|
||||
)
|
||||
if not has_med_indicator and len(segments) > 0:
|
||||
continue
|
||||
|
||||
# Check companion drug "combination of A and B", "Take A and B [dose]", or "A with B [dose]"
|
||||
# 1. "combination tablet/of A and B" or "Take A and B [dose]"
|
||||
comb_match = re.search(r"(?:combination\s+(?:tablet\s+of\s+|of\s+)?|take\s+|administer\s+|give\s+)?([A-Za-z0-9\s\.\-]+?\d+(?:\.\d+)?\s*(?:mg|g|mcg|ml|IU))\s+and\s+([A-Za-z0-9\s\.\-]+?\d+(?:\.\d+)?\s*(?:mg|g|mcg|ml|IU)?)", clause_clean, re.IGNORECASE)
|
||||
if comb_match:
|
||||
d1_raw = comb_match.group(1).strip()
|
||||
d2_raw = comb_match.group(2).strip()
|
||||
d1 = re.split(r"(?i)\b(?:once|twice|thrice|daily|od|bd|tid|qid|for|after|before|every)\b", d1_raw)[0].strip()
|
||||
d2 = re.split(r"(?i)\b(?:once|twice|thrice|daily|od|bd|tid|qid|for|after|before|every)\b", d2_raw)[0].strip()
|
||||
segments.append({"medicine_id": med_id, "clause": clause_clean, "seed_name": d1})
|
||||
med_id += 1
|
||||
segments.append({"medicine_id": med_id, "clause": clause_clean, "seed_name": d2})
|
||||
med_id += 1
|
||||
continue
|
||||
|
||||
# 2. "A with B [dose]"
|
||||
comp_match = re.search(r"([A-Za-z0-9\s\.\-]+?)\s+with\s+([A-Za-z0-9\s\.\-]+)", clause_clean, re.IGNORECASE)
|
||||
if comp_match:
|
||||
d1_raw = comp_match.group(1).strip()
|
||||
d2_raw = comp_match.group(2).strip()
|
||||
d2_first_word = d2_raw.split()[0].lower() if d2_raw else ""
|
||||
has_dose_or_form = bool(re.search(r"(?i)\d+(?:\.\d+)?\s*(?:mg|g|mcg|ml|iu|%)|\b(?:tablets?|capsules?|gel|lotion|drops?|solution|cream|ointment)\b", d2_raw))
|
||||
if d2_first_word not in NON_DRUG_WITH and len(d2_first_word) >= 3 and has_dose_or_form:
|
||||
d1 = re.split(r"(?i)\b(?:once|twice|thrice|three\s+times|four\s+times|daily|od|bd|tid|qid|for|after|before|every)\b", d1_raw)[0].strip()
|
||||
d2 = re.split(r"(?i)\b(?:locally|once|twice|thrice|three\s+times|four\s+times|daily|od|bd|tid|qid|for|after|before|every|without|using|at|into|in|on|to|along|over|around|strictly|ensuring|diluted|dissolved|mixed|slowly)\b", d2_raw)[0].strip()
|
||||
segments.append({"medicine_id": med_id, "clause": clause_clean, "seed_name": d1})
|
||||
med_id += 1
|
||||
segments.append({"medicine_id": med_id, "clause": clause_clean, "seed_name": d2})
|
||||
med_id += 1
|
||||
else:
|
||||
segments.append({"medicine_id": med_id, "clause": clause_clean, "seed_name": ""})
|
||||
med_id += 1
|
||||
else:
|
||||
segments.append({"medicine_id": med_id, "clause": clause_clean, "seed_name": ""})
|
||||
med_id += 1
|
||||
|
||||
if not segments:
|
||||
segments.append({"medicine_id": 1, "clause": clean_text, "seed_name": ""})
|
||||
|
||||
return segments
|
||||
@@ -0,0 +1,87 @@
|
||||
"""
|
||||
agents/validator_agent.py
|
||||
-------------------------
|
||||
Validator Agent:
|
||||
Enforces strict 100% groundedness against raw input prescription with zero hallucinations,
|
||||
filters out irrelevant conversational noise, and dispatches targeted feedback to agents.
|
||||
"""
|
||||
import re
|
||||
from typing import Dict, Any
|
||||
from graph_state import AgenticRxState, ValidationFeedback
|
||||
from agents.utils import is_valid_medication_entity
|
||||
|
||||
|
||||
def validator_agent(state: AgenticRxState, llm: Any = None) -> Dict[str, Any]:
|
||||
"""
|
||||
Validator Agent.
|
||||
"""
|
||||
input_text = state.get("input_text", "")
|
||||
blocks = state.get("aggregated_blocks", [])
|
||||
iteration = state.get("iteration_count", 1)
|
||||
|
||||
feedback: ValidationFeedback = {}
|
||||
is_valid = True
|
||||
|
||||
if not blocks or all(b.get("Drug_name") == "NONE" for b in blocks):
|
||||
is_valid = False
|
||||
feedback["medicine_agent"] = "No valid medicine name was identified from the input."
|
||||
|
||||
valid_blocks = []
|
||||
for block in blocks:
|
||||
drug_name = block.get("Drug_name", "")
|
||||
if drug_name != "NONE":
|
||||
# Noise-proofing check: ensure drug is not conversational chatter or non-drug item
|
||||
if not is_valid_medication_entity(drug_name):
|
||||
is_valid = False
|
||||
feedback["medicine_agent"] = f"Entity '{drug_name}' is not a valid medication entity."
|
||||
continue
|
||||
|
||||
# Grounding check: ensure core name appears in prescription
|
||||
core_words = [
|
||||
w for w in re.findall(r"[A-Za-z0-9\-]+", drug_name)
|
||||
if len(w) >= 3 and w.lower() not in (
|
||||
"take", "tab", "tabs", "tablet", "capsule", "syrup",
|
||||
"pill", "rotacap", "none", "vial", "sachet", "one", "administer"
|
||||
)
|
||||
]
|
||||
if core_words and not any(cw.lower() in input_text.lower() for cw in core_words):
|
||||
is_valid = False
|
||||
feedback["medicine_agent"] = f"Drug '{drug_name}' was not found in prescription text."
|
||||
|
||||
doses = re.findall(r"\d+(?:\.\d+)?", drug_name)
|
||||
for d in doses:
|
||||
if d not in input_text:
|
||||
is_valid = False
|
||||
feedback["medicine_agent"] = f"Dosage {d} in drug name '{drug_name}' was not found in prescription text."
|
||||
|
||||
inst = block.get("instruction", "")
|
||||
if inst != "NONE":
|
||||
# Reject artificial commentary ONLY if not present in the input text
|
||||
hallucinated_commentary_cues = ["please note", "be careful", "moral:", "disclaimer:"]
|
||||
for cue in hallucinated_commentary_cues:
|
||||
if cue in inst.lower() and cue not in input_text.lower():
|
||||
is_valid = False
|
||||
feedback["instruction_agent"] = f"Unsolicited commentary '{cue}' detected. Strictly adhere to verbatim input."
|
||||
|
||||
valid_blocks.append(block)
|
||||
|
||||
if iteration >= 3:
|
||||
status = "VALID"
|
||||
else:
|
||||
status = "VALID" if is_valid else "NEEDS_CORRECTION"
|
||||
|
||||
log_entry = {
|
||||
"agent": "Validator",
|
||||
"iteration": iteration,
|
||||
"status": status,
|
||||
"feedback": feedback if status == "NEEDS_CORRECTION" else "All checks passed (Grounded & Noise-Proof).",
|
||||
}
|
||||
current_logs = list(state.get("agent_logs", []))
|
||||
current_logs.append(log_entry)
|
||||
|
||||
return {
|
||||
"validation_status": status,
|
||||
"validation_feedback": feedback,
|
||||
"aggregated_blocks": valid_blocks if valid_blocks else blocks,
|
||||
"agent_logs": current_logs,
|
||||
}
|
||||
@@ -0,0 +1,250 @@
|
||||
"""
|
||||
api_server.py
|
||||
-------------
|
||||
FastAPI backend service exposing the Agentic Prescription Extractor and STT engines.
|
||||
Enables parallel Node.js, Web, and mobile applications to interface with the LangGraph pipeline.
|
||||
"""
|
||||
import os
|
||||
import io
|
||||
import time
|
||||
import datetime
|
||||
from typing import Optional, List, Dict, Any
|
||||
from fastapi import FastAPI, UploadFile, File, Form, HTTPException, Query
|
||||
from fastapi.middleware.cors import CORSMiddleware
|
||||
from pydantic import BaseModel
|
||||
|
||||
import config
|
||||
import db
|
||||
import vectorstore
|
||||
import pipeline
|
||||
import exporter
|
||||
import transcriber
|
||||
from graph_pipeline import run_graph_extraction
|
||||
from exporter import parse_output_fields
|
||||
|
||||
# Initialize database
|
||||
db.init_db()
|
||||
|
||||
app = FastAPI(
|
||||
title="Agentic Prescription Extractor API",
|
||||
description="REST API bridging LangGraph Multi-Agent Architecture and Multi-Engine STT to parallel Node.js applications.",
|
||||
version="2.0.0",
|
||||
)
|
||||
|
||||
# Enable CORS for local Node.js app (Port 3000 / 5173 / any origin)
|
||||
app.add_middleware(
|
||||
CORSMiddleware,
|
||||
allow_origins=["*"],
|
||||
allow_credentials=True,
|
||||
allow_methods=["*"],
|
||||
allow_headers=["*"],
|
||||
)
|
||||
|
||||
# Global in-memory cache for LLM and Vector Store
|
||||
_CACHED_MODELS: Dict[str, Any] = {}
|
||||
_CACHED_STORE = None
|
||||
|
||||
|
||||
def get_cached_chat(device: str = "cpu", model_name: str = None):
|
||||
global _CACHED_MODELS
|
||||
target_model = model_name or config.MODEL_NAME
|
||||
key = f"{device}_{target_model}"
|
||||
if key not in _CACHED_MODELS:
|
||||
_CACHED_MODELS[key] = pipeline.build_chat(device, target_model)
|
||||
return _CACHED_MODELS[key]
|
||||
|
||||
|
||||
def get_cached_vector_store():
|
||||
global _CACHED_STORE
|
||||
if _CACHED_STORE is None:
|
||||
_CACHED_STORE = vectorstore.load_or_create_index()
|
||||
return _CACHED_STORE
|
||||
|
||||
|
||||
class ExtractRequest(BaseModel):
|
||||
text: str
|
||||
process_id: Optional[int] = None
|
||||
llm_model: Optional[str] = None
|
||||
device: Optional[str] = "cpu"
|
||||
process_name: Optional[str] = "node_run"
|
||||
|
||||
|
||||
class ThreadCreateRequest(BaseModel):
|
||||
name: str
|
||||
device: Optional[str] = "cpu"
|
||||
model_label: Optional[str] = config.DEFAULT_MODEL_LABEL
|
||||
|
||||
|
||||
@app.get("/api/status")
|
||||
def get_system_status():
|
||||
"""Returns system status, device configurations, and model options."""
|
||||
active_proc = db.get_active_process()
|
||||
return {
|
||||
"status": "online",
|
||||
"active_process": active_proc,
|
||||
"default_llm": config.DEFAULT_MODEL_LABEL,
|
||||
"default_stt": config.DEFAULT_STT_MODEL_LABEL,
|
||||
"available_llm_models": config.MODEL_OPTIONS,
|
||||
"available_stt_models": config.STT_MODEL_OPTIONS,
|
||||
"device_options": config.DEVICE_OPTIONS,
|
||||
}
|
||||
|
||||
|
||||
@app.get("/api/models")
|
||||
def get_models():
|
||||
"""Lists all available LLM and STT models."""
|
||||
return {
|
||||
"llm_models": [
|
||||
{"label": k, "filename": v, "is_default": (k == config.DEFAULT_MODEL_LABEL)}
|
||||
for k, v in config.MODEL_OPTIONS.items()
|
||||
],
|
||||
"stt_models": [
|
||||
{"label": k, "key": v, "is_default": (k == config.DEFAULT_STT_MODEL_LABEL)}
|
||||
for k, v in config.STT_MODEL_OPTIONS.items()
|
||||
],
|
||||
}
|
||||
|
||||
|
||||
@app.post("/api/extract")
|
||||
def extract_prescription(req: ExtractRequest):
|
||||
"""
|
||||
Executes the LangGraph Multi-Agent extraction workflow on text prescription.
|
||||
Returns validated structured medication blocks and logs to SQLite + CSV/XLSX.
|
||||
"""
|
||||
query = req.text.strip()
|
||||
if not query:
|
||||
raise HTTPException(status_code=400, detail="Prescription text cannot be empty.")
|
||||
|
||||
# 1. Process / Thread handling
|
||||
proc_id = req.process_id
|
||||
csv_path = None
|
||||
xlsx_path = None
|
||||
if not proc_id:
|
||||
active = db.get_active_process()
|
||||
if active:
|
||||
proc_id = active["process_id"]
|
||||
csv_path = active.get("csv_path")
|
||||
xlsx_path = active.get("xlsx_path")
|
||||
else:
|
||||
p_name = req.process_name or "node_run"
|
||||
csv_path, xlsx_path = exporter.new_output_paths(p_name)
|
||||
target_model = req.llm_model or config.DEFAULT_MODEL_LABEL
|
||||
model_file = config.MODEL_OPTIONS.get(target_model, config.MODEL_NAME)
|
||||
proc_id = db.create_process(p_name, req.device or "cpu", csv_path, xlsx_path, model_name=model_file, model_label=target_model)
|
||||
|
||||
# 2. Run LangGraph Multi-Agent pipeline
|
||||
target_llm_label = req.llm_model or config.DEFAULT_MODEL_LABEL
|
||||
t0 = time.perf_counter()
|
||||
output, generation_time, agent_logs, aggregated_blocks = run_graph_extraction(None, query)
|
||||
t1 = time.perf_counter()
|
||||
|
||||
# 3. Parse output fields
|
||||
parsed_records = parse_output_fields(output, query=query)
|
||||
|
||||
# 4. Save to DB and export files
|
||||
db.add_history(proc_id, query, output, generation_time)
|
||||
if not csv_path or not xlsx_path:
|
||||
proc_data = db.get_process(proc_id)
|
||||
if proc_data:
|
||||
csv_path = proc_data.get("csv_path")
|
||||
xlsx_path = proc_data.get("xlsx_path")
|
||||
|
||||
if csv_path and xlsx_path:
|
||||
exporter.append_generation(
|
||||
csv_path,
|
||||
xlsx_path,
|
||||
query,
|
||||
output,
|
||||
generation_time=generation_time,
|
||||
llm_model_used=target_llm_label,
|
||||
)
|
||||
|
||||
return {
|
||||
"success": True,
|
||||
"process_id": proc_id,
|
||||
"raw_query": query,
|
||||
"raw_output": output,
|
||||
"parsed_records": parsed_records,
|
||||
"generation_time": generation_time,
|
||||
"agent_logs": agent_logs,
|
||||
"total_medicines": len(parsed_records),
|
||||
}
|
||||
|
||||
|
||||
@app.post("/api/transcribe")
|
||||
async def transcribe_speech(
|
||||
file: Optional[UploadFile] = File(None),
|
||||
stt_model: Optional[str] = Form("whisper_ayush"),
|
||||
):
|
||||
"""
|
||||
Transcribes uploaded audio speech note using the selected STT engine (Whisper Ayush, Canary, Parakeet, Moonshine).
|
||||
"""
|
||||
if not file:
|
||||
raise HTTPException(status_code=400, detail="No audio file uploaded.")
|
||||
|
||||
audio_bytes = await file.read()
|
||||
if not audio_bytes:
|
||||
raise HTTPException(status_code=400, detail="Uploaded audio file is empty.")
|
||||
|
||||
t0 = time.perf_counter()
|
||||
try:
|
||||
transcript = transcriber.transcribe_audio(audio_bytes, model_key=stt_model)
|
||||
except Exception as ex:
|
||||
raise HTTPException(status_code=500, detail=f"STT transcription error: {str(ex)}")
|
||||
t1 = time.perf_counter()
|
||||
|
||||
return {
|
||||
"success": True,
|
||||
"transcript": transcript,
|
||||
"stt_model_used": stt_model,
|
||||
"transcription_time": round(t1 - t0, 3),
|
||||
}
|
||||
|
||||
|
||||
@app.get("/api/history")
|
||||
def get_history(process_id: Optional[int] = None, limit: int = 50):
|
||||
"""Retrieves prescription extraction history from SQLite."""
|
||||
records = db.get_history(process_id, limit=limit)
|
||||
formatted = []
|
||||
for r in records:
|
||||
parsed = parse_output_fields(r.get("output", ""), query=r.get("query", ""))
|
||||
formatted.append({
|
||||
"id": r.get("id"),
|
||||
"process_id": r.get("process_id"),
|
||||
"timestamp": r.get("created_at"),
|
||||
"input_text": r.get("query"),
|
||||
"output_text": r.get("output"),
|
||||
"generation_time": r.get("generation_time"),
|
||||
"audio_path": r.get("audio_path"),
|
||||
"parsed_records": parsed,
|
||||
})
|
||||
return {"total": len(formatted), "records": formatted}
|
||||
|
||||
|
||||
@app.get("/api/threads")
|
||||
def get_threads():
|
||||
"""Lists all active and archived process threads."""
|
||||
threads = db.list_processes()
|
||||
return {"threads": threads}
|
||||
|
||||
|
||||
@app.post("/api/threads")
|
||||
def create_thread(req: ThreadCreateRequest):
|
||||
"""Creates a new process thread."""
|
||||
csv_path, xlsx_path = exporter.new_output_paths(req.name)
|
||||
model_name = config.MODEL_OPTIONS.get(req.model_label, config.MODEL_NAME)
|
||||
proc_id = db.create_process(req.name, req.device, csv_path, xlsx_path, model_name=model_name, model_label=req.model_label)
|
||||
return {
|
||||
"success": True,
|
||||
"process_id": proc_id,
|
||||
"name": req.name,
|
||||
"device": req.device,
|
||||
"model_label": req.model_label,
|
||||
"csv_path": csv_path,
|
||||
"xlsx_path": xlsx_path,
|
||||
}
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
import uvicorn
|
||||
uvicorn.run(app, host="127.0.0.1", port=8000, log_level="info")
|
||||
@@ -0,0 +1,431 @@
|
||||
"""
|
||||
app.py
|
||||
------
|
||||
Streamlit UI for the offline prescription-extraction pipeline.
|
||||
"""
|
||||
import os
|
||||
import time
|
||||
import datetime
|
||||
import streamlit as st
|
||||
import pandas as pd
|
||||
|
||||
import config
|
||||
import db
|
||||
import vectorstore
|
||||
import pipeline
|
||||
import exporter
|
||||
|
||||
st.set_page_config(page_title="Offline Prescription Extractor", layout="wide")
|
||||
db.init_db()
|
||||
|
||||
|
||||
@st.cache_resource(show_spinner="Loading local LLM model (first time only)...")
|
||||
def get_chat(device: str, model_name: str):
|
||||
return pipeline.build_chat(device, model_name)
|
||||
|
||||
|
||||
@st.cache_resource(show_spinner="Embedding + storing system prompt in FAISS (first time only)...")
|
||||
def get_vector_store():
|
||||
return vectorstore.load_or_create_index()
|
||||
|
||||
|
||||
def load_process_to_session(p: dict):
|
||||
"""Load a process/thread entry from DB into Streamlit session state."""
|
||||
st.session_state.process_id = p["process_id"]
|
||||
st.session_state.process_status = p.get("status", "active")
|
||||
st.session_state.device = p["device"]
|
||||
st.session_state.csv_path = p["csv_path"]
|
||||
st.session_state.xlsx_path = p["xlsx_path"]
|
||||
st.session_state.process_name = p["name"]
|
||||
st.session_state.model_name = p.get("model_name") or config.MODEL_NAME
|
||||
st.session_state.model_label = p.get("model_label") or config.DEFAULT_MODEL_LABEL
|
||||
|
||||
|
||||
def reattach_active_process():
|
||||
"""Runs on script execution. If no thread is selected in session_state,
|
||||
reattach to the most recent active process if available."""
|
||||
if "process_id" not in st.session_state:
|
||||
active = db.get_active_process()
|
||||
if active:
|
||||
load_process_to_session(active)
|
||||
|
||||
|
||||
reattach_active_process()
|
||||
|
||||
st.title("🩺 LangGraph Multi-Agent Prescription Extractor")
|
||||
st.caption("Parallel Multi-Agent Architecture (Supervisor, Medicine & Strength, Route, Duration & Frequency, Instructions, Aggregator, Validator) -- Fully Offline & Grounded.")
|
||||
|
||||
# --- Sidebar: process & thread controls ------------------------------------
|
||||
with st.sidebar:
|
||||
st.header("⚙️ Process Control")
|
||||
is_running = "process_id" in st.session_state and st.session_state.get("process_status") == "active"
|
||||
|
||||
model_labels = list(config.MODEL_OPTIONS.keys())
|
||||
model_label = st.selectbox(
|
||||
"LLM Model",
|
||||
model_labels,
|
||||
index=model_labels.index(
|
||||
st.session_state.get("model_label", config.DEFAULT_MODEL_LABEL)
|
||||
),
|
||||
disabled=False,
|
||||
help="Select offline LLM model. Can be switched dynamically for any query entry!",
|
||||
)
|
||||
model_name = config.MODEL_OPTIONS[model_label]
|
||||
st.session_state.model_label = model_label
|
||||
st.session_state.model_name = model_name
|
||||
|
||||
device_labels = list(config.DEVICE_OPTIONS.keys())
|
||||
device_label = st.selectbox(
|
||||
"Run on",
|
||||
device_labels,
|
||||
index=device_labels.index(
|
||||
st.session_state.get("device_label", config.DEFAULT_DEVICE_LABEL)
|
||||
),
|
||||
disabled=is_running,
|
||||
help="Locked while a process is running -- stop it to change device.",
|
||||
)
|
||||
device = config.DEVICE_OPTIONS[device_label]
|
||||
|
||||
process_name = st.text_input("Process name (optional)", value="run", disabled=is_running)
|
||||
|
||||
col1, col2 = st.columns(2)
|
||||
start_clicked = col1.button("Start Process", disabled=is_running, use_container_width=True)
|
||||
stop_clicked = col2.button("Stop Process", disabled=not is_running, use_container_width=True)
|
||||
|
||||
if is_running:
|
||||
st.success(
|
||||
f"**Running**: {st.session_state.process_name}\n\n"
|
||||
f"🤖 **Selected Model**: {model_label}\n\n"
|
||||
f"⚙️ **Device**: {st.session_state.device}"
|
||||
)
|
||||
else:
|
||||
st.info("No active process running.")
|
||||
|
||||
if start_clicked:
|
||||
csv_path, xlsx_path = exporter.new_output_paths(process_name)
|
||||
process_id = db.create_process(
|
||||
process_name, device, csv_path, xlsx_path, model_name=model_name, model_label=model_label
|
||||
)
|
||||
load_process_to_session({
|
||||
"process_id": process_id,
|
||||
"status": "active",
|
||||
"device": device,
|
||||
"csv_path": csv_path,
|
||||
"xlsx_path": xlsx_path,
|
||||
"name": process_name,
|
||||
"model_name": model_name,
|
||||
"model_label": model_label,
|
||||
})
|
||||
st.session_state.device_label = device_label
|
||||
st.rerun()
|
||||
|
||||
if stop_clicked:
|
||||
db.stop_process(st.session_state.process_id)
|
||||
st.session_state.process_status = "stopped"
|
||||
# Clear FAISS index on disk
|
||||
import shutil
|
||||
if os.path.exists(config.FAISS_DIR):
|
||||
shutil.rmtree(config.FAISS_DIR, ignore_errors=True)
|
||||
# Invalidate the st.cache_resource so the next Start force-rebuilds the index
|
||||
get_vector_store.clear()
|
||||
# Drop any lingering session references
|
||||
st.session_state.pop("faiss_store", None)
|
||||
st.session_state.pop("vector_store", None)
|
||||
st.rerun()
|
||||
|
||||
st.divider()
|
||||
st.subheader("🎙️ Speech-to-Text Engine")
|
||||
stt_labels = list(config.STT_MODEL_OPTIONS.keys())
|
||||
selected_stt_label = st.selectbox(
|
||||
"STT Model",
|
||||
stt_labels,
|
||||
index=stt_labels.index(
|
||||
st.session_state.get("stt_model_label", config.DEFAULT_STT_MODEL_LABEL)
|
||||
),
|
||||
help="Select offline Speech-to-Text model. Can be switched dynamically for voice transcription!",
|
||||
key="stt_model_selector_sb",
|
||||
)
|
||||
st.session_state.stt_model_label = selected_stt_label
|
||||
st.session_state.stt_model_key = config.STT_MODEL_OPTIONS[selected_stt_label]
|
||||
|
||||
st.divider()
|
||||
st.subheader("🧵 Conversation Threads")
|
||||
all_threads = db.list_processes()
|
||||
|
||||
if all_threads:
|
||||
# Scrollable container displaying ~5 threads at a time
|
||||
with st.container(height=320):
|
||||
for t in all_threads:
|
||||
t_id = t["process_id"]
|
||||
is_selected = st.session_state.get("process_id") == t_id
|
||||
tag = "🟢" if t["status"] == "active" else "⚪"
|
||||
t_model = t.get("model_label") or config.DEFAULT_MODEL_LABEL
|
||||
date_str = t["created_at"].split("T")[0] if "T" in t["created_at"] else t["created_at"][:10]
|
||||
|
||||
expander_label = f"{tag} {t['name']} (#{t_id})"
|
||||
with st.expander(expander_label, expanded=is_selected):
|
||||
st.caption(f"🤖 **Model:** {t_model}")
|
||||
st.caption(f"⚙️ **Device:** {t['device']} | 📅 {date_str}")
|
||||
st.caption(f"Status: **{t['status'].upper()}**")
|
||||
|
||||
btn_c1, btn_c2 = st.columns(2)
|
||||
if btn_c1.button("View 👁️", key=f"select_{t_id}", use_container_width=True, disabled=is_selected):
|
||||
load_process_to_session(t)
|
||||
st.rerun()
|
||||
|
||||
if btn_c2.button("Delete 🗑️", key=f"del_{t_id}", use_container_width=True):
|
||||
db.delete_process(t_id)
|
||||
if st.session_state.get("process_id") == t_id:
|
||||
for key in (
|
||||
"process_id", "process_status", "device", "csv_path",
|
||||
"xlsx_path", "process_name", "model_name", "model_label",
|
||||
"last_gen_time", "last_ret_time"
|
||||
):
|
||||
st.session_state.pop(key, None)
|
||||
st.rerun()
|
||||
|
||||
if st.button("🗑️ Delete All History", use_container_width=True, type="secondary"):
|
||||
db.delete_all_processes()
|
||||
for key in (
|
||||
"process_id", "process_status", "device", "csv_path",
|
||||
"xlsx_path", "process_name", "model_name", "model_label",
|
||||
"last_gen_time", "last_ret_time"
|
||||
):
|
||||
st.session_state.pop(key, None)
|
||||
st.rerun()
|
||||
else:
|
||||
st.caption("No saved threads yet.")
|
||||
|
||||
# --- Main panel --------------------------------------------------------------
|
||||
if "process_id" not in st.session_state:
|
||||
st.warning("Select or start a process thread from the sidebar to begin.")
|
||||
st.stop()
|
||||
|
||||
current_proc = db.get_process(st.session_state.process_id)
|
||||
if not current_proc:
|
||||
st.warning("Selected thread no longer exists.")
|
||||
st.session_state.pop("process_id", None)
|
||||
st.stop()
|
||||
|
||||
active_model_name = model_name
|
||||
active_model_label = model_label
|
||||
is_current_active = st.session_state.get("process_status") == "active"
|
||||
|
||||
st.subheader(f"🧵 Thread: {st.session_state.process_name} (ID: #{st.session_state.process_id})")
|
||||
st.caption(
|
||||
f"🤖 **Current LLM Model**: {active_model_label} | "
|
||||
f"⚙️ **Device**: {st.session_state.device} | "
|
||||
f"Status: **{st.session_state.get('process_status', 'stopped').upper()}**"
|
||||
)
|
||||
|
||||
if is_current_active:
|
||||
# Resource-cached: cheap after initial load for any selected model
|
||||
chat = get_chat(st.session_state.device, active_model_name)
|
||||
store = get_vector_store()
|
||||
|
||||
st.subheader("Enter an instruction")
|
||||
input_mode = st.radio("Input Mode", ["Text Input 📝", "Voice Input 🎙️"], horizontal=True, key="input_mode_selector")
|
||||
|
||||
query = ""
|
||||
if input_mode == "Text Input 📝":
|
||||
query = st.text_area("Text instruction", height=100, key="query_input")
|
||||
else:
|
||||
current_stt_label = st.session_state.get("stt_model_label", config.DEFAULT_STT_MODEL_LABEL)
|
||||
current_stt_key = st.session_state.get("stt_model_key", config.STT_MODEL_OPTIONS[config.DEFAULT_STT_MODEL_LABEL])
|
||||
|
||||
st.markdown(f"##### 🎙️ Voice Input ({current_stt_label})")
|
||||
st.caption(f"Active Speech-to-Text Engine: **{current_stt_label}** — Toggle anytime in sidebar or below.")
|
||||
|
||||
stt_col1, stt_col2 = st.columns([2, 1])
|
||||
with stt_col1:
|
||||
audio_source = st.radio("Audio Source", ["Microphone 🎤", "Upload Audio File 📁"], horizontal=True, key="audio_source_select")
|
||||
with stt_col2:
|
||||
stt_labels = list(config.STT_MODEL_OPTIONS.keys())
|
||||
inline_stt = st.selectbox("Switch STT Model", stt_labels, index=stt_labels.index(current_stt_label), key="inline_stt_select")
|
||||
if inline_stt != current_stt_label:
|
||||
st.session_state.stt_model_label = inline_stt
|
||||
st.session_state.stt_model_key = config.STT_MODEL_OPTIONS[inline_stt]
|
||||
st.rerun()
|
||||
|
||||
audio_buffer = None
|
||||
if audio_source == "Microphone 🎤":
|
||||
audio_buffer = st.audio_input("Record doctor-patient voice note", key="mic_input")
|
||||
else:
|
||||
audio_buffer = st.file_uploader("Upload audio file (.wav, .mp3, .m4a, .ogg)", type=["wav", "mp3", "m4a", "ogg"], key="file_audio_input")
|
||||
|
||||
if audio_buffer is not None:
|
||||
if hasattr(audio_buffer, "getvalue"):
|
||||
audio_bytes = audio_buffer.getvalue()
|
||||
else:
|
||||
if hasattr(audio_buffer, "seek"):
|
||||
audio_buffer.seek(0)
|
||||
audio_bytes = audio_buffer.read()
|
||||
if hasattr(audio_buffer, "seek"):
|
||||
audio_buffer.seek(0)
|
||||
|
||||
if audio_bytes and len(audio_bytes) > 0:
|
||||
import hashlib
|
||||
audio_hash = hashlib.md5(audio_bytes).hexdigest() + "_" + str(current_stt_key)
|
||||
|
||||
# Only transcribe when this audio clip + STT model combo has not been transcribed yet
|
||||
if st.session_state.get("last_transcribed_hash") != audio_hash:
|
||||
with st.spinner(f"Transcribing audio using {current_stt_label}..."):
|
||||
try:
|
||||
import transcriber
|
||||
transcribed_text = transcriber.transcribe_audio(audio_bytes, model_key=current_stt_key)
|
||||
st.session_state.voice_transcript = transcribed_text
|
||||
st.session_state.last_transcribed_hash = audio_hash
|
||||
st.session_state.active_audio_bytes = audio_bytes
|
||||
st.session_state["voice_query_input"] = transcribed_text
|
||||
if transcribed_text:
|
||||
st.success(f"✅ Audio Transcribed Successfully with {current_stt_label}!")
|
||||
else:
|
||||
st.warning("⚠️ No speech recognized in audio sample.")
|
||||
except Exception as ex:
|
||||
st.error(f"Speech transcription error with {current_stt_label}: {ex}")
|
||||
st.session_state.voice_transcript = ""
|
||||
st.session_state["voice_query_input"] = ""
|
||||
|
||||
# Allow user to manually force re-transcription with another STT engine if desired
|
||||
re_trans_col1, re_trans_col2 = st.columns([4, 1])
|
||||
with re_trans_col2:
|
||||
if st.button("🔄 Re-Transcribe", help="Force re-transcribe this audio with the selected STT model", use_container_width=True):
|
||||
st.session_state.pop("last_transcribed_hash", None)
|
||||
st.rerun()
|
||||
|
||||
query = st.text_area(f"Transcribed Text ({current_stt_label}) — Edit if needed", value=st.session_state.get("voice_transcript", ""), height=100, key="voice_query_input")
|
||||
else:
|
||||
st.info(f"Record audio or upload an audio file above to transcribe using {current_stt_label}.")
|
||||
|
||||
run_clicked = st.button("Run")
|
||||
|
||||
if run_clicked and query.strip():
|
||||
progress_bar = st.progress(0, text="[1/5] Supervisor Agent initializing prescription graph...")
|
||||
time.sleep(0.1)
|
||||
|
||||
progress_bar.progress(20, text="[2/5] Retrieving system context & initializing agents...")
|
||||
t_ret_start = time.perf_counter()
|
||||
retrieved_prompt = vectorstore.retrieve_system_prompt(store)
|
||||
t_ret_end = time.perf_counter()
|
||||
retrieval_time = round(t_ret_end - t_ret_start, 4)
|
||||
|
||||
progress_bar.progress(
|
||||
45, text=f"[3/5] Dispatching parallel extractors (Medicine/Strength, Route, Duration/Frequency, Instructions)..."
|
||||
)
|
||||
time.sleep(0.1)
|
||||
|
||||
progress_bar.progress(
|
||||
75, text=f"[4/5] Aggregating extractions & validating groundedness (anti-hallucination check)..."
|
||||
)
|
||||
output, generation_time, agent_logs, aggregated_blocks = pipeline.run_agentic_pipeline(chat, query.strip())
|
||||
|
||||
progress_bar.progress(90, text="[5/5] Saving validated output to SQLite & exporting to CSV/XLSX...")
|
||||
|
||||
# Save voice audio file to data/audio_files/ if recorded/uploaded
|
||||
audio_file_path = None
|
||||
if input_mode != "Text Input 📝" and st.session_state.get("active_audio_bytes"):
|
||||
stamp = datetime.datetime.now().strftime("%Y%m%d_%H%M%S")
|
||||
audio_file_name = f"proc_{st.session_state.process_id}_{stamp}.wav"
|
||||
audio_file_path = os.path.join(config.AUDIO_DIR, audio_file_name)
|
||||
try:
|
||||
os.makedirs(config.AUDIO_DIR, exist_ok=True)
|
||||
with open(audio_file_path, "wb") as f_aud:
|
||||
f_aud.write(st.session_state.active_audio_bytes)
|
||||
except Exception:
|
||||
audio_file_path = None
|
||||
|
||||
db.add_history(st.session_state.process_id, query.strip(), output, generation_time, audio_path=audio_file_path)
|
||||
exporter.append_generation(
|
||||
st.session_state.csv_path,
|
||||
st.session_state.xlsx_path,
|
||||
query.strip(),
|
||||
output,
|
||||
generation_time,
|
||||
llm_model_used=active_model_label,
|
||||
)
|
||||
|
||||
progress_bar.progress(100, text="✅ LangGraph Multi-Agent extraction & export complete!")
|
||||
|
||||
st.session_state.last_gen_time = generation_time
|
||||
st.session_state.last_ret_time = retrieval_time
|
||||
st.session_state.last_agent_logs = agent_logs
|
||||
|
||||
# Clear voice session cache after successful generation run
|
||||
for k in ("voice_transcript", "last_audio_hash", "active_audio_bytes", "voice_query_input"):
|
||||
st.session_state.pop(k, None)
|
||||
st.rerun()
|
||||
else:
|
||||
st.info("ℹ️ This thread is stopped. You can view its generation history and download CSV/XLSX below, or start a new process in the sidebar.")
|
||||
|
||||
if "last_gen_time" in st.session_state:
|
||||
st.success(
|
||||
f"⏱️ **Latest Multi-Agent Timing ({active_model_label})**: "
|
||||
f"Graph Execution & Validation: **{st.session_state.last_gen_time:.3f}s** | "
|
||||
f"FAISS Retrieval: **{st.session_state.last_ret_time:.4f}s**"
|
||||
)
|
||||
|
||||
if st.session_state.get("last_agent_logs"):
|
||||
with st.expander("🤖 **LangGraph Multi-Agent Audit Log & Validator Trace**", expanded=False):
|
||||
for log in st.session_state.last_agent_logs:
|
||||
agent_name = log.get("agent", "Agent")
|
||||
action = log.get("action") or log.get("status") or ""
|
||||
feedback = log.get("feedback")
|
||||
st.markdown(f"- **{agent_name}**: `{action}`")
|
||||
if feedback and feedback != "All checks passed (Grounded).":
|
||||
st.caption(f" *Feedback:* {feedback}")
|
||||
|
||||
st.subheader(f"📊 Generation History for Thread #{st.session_state.process_id}")
|
||||
history = db.get_history(st.session_state.process_id)
|
||||
|
||||
if history:
|
||||
if os.path.exists(st.session_state.csv_path):
|
||||
df = pd.read_csv(st.session_state.csv_path)
|
||||
st.dataframe(df, use_container_width=True, hide_index=True)
|
||||
else:
|
||||
rows = []
|
||||
for r in history:
|
||||
parsed_items = exporter.parse_output_fields(r["output"], query=r["query"])
|
||||
created_str = str(r["created_at"])
|
||||
if "T" in created_str:
|
||||
d_val, t_val = created_str.split("T")[0], created_str.split("T")[1].split(".")[0]
|
||||
elif " " in created_str:
|
||||
d_val, t_val = created_str.split(" ")[0], created_str.split(" ")[1].split(".")[0]
|
||||
else:
|
||||
d_val, t_val = created_str[:10], created_str[11:19]
|
||||
|
||||
for parsed in parsed_items:
|
||||
rows.append({
|
||||
"date": d_val,
|
||||
"time": t_val,
|
||||
"query": r["query"],
|
||||
"Drug_name": parsed["Drug_name"],
|
||||
"strength": parsed["strength"],
|
||||
"frequency": parsed["frequency"],
|
||||
"duration": parsed["duration"],
|
||||
"route": parsed["route"],
|
||||
"instruction": parsed["instruction"],
|
||||
"additional_instruction": parsed.get("additional_instruction", "NONE"),
|
||||
"llm_model_used": active_model_label,
|
||||
"generation_time_sec": r.get("generation_time") or "N/A",
|
||||
})
|
||||
st.dataframe(pd.DataFrame(rows), use_container_width=True, hide_index=True)
|
||||
|
||||
dl1, dl2 = st.columns(2)
|
||||
if os.path.exists(st.session_state.csv_path):
|
||||
with open(st.session_state.csv_path, "rb") as f:
|
||||
dl1.download_button(
|
||||
"📥 Download Thread CSV",
|
||||
f,
|
||||
file_name=os.path.basename(st.session_state.csv_path),
|
||||
use_container_width=True,
|
||||
)
|
||||
if os.path.exists(st.session_state.xlsx_path):
|
||||
with open(st.session_state.xlsx_path, "rb") as f:
|
||||
dl2.download_button(
|
||||
"📥 Download Thread XLSX",
|
||||
f,
|
||||
file_name=os.path.basename(st.session_state.xlsx_path),
|
||||
use_container_width=True,
|
||||
)
|
||||
else:
|
||||
st.caption("No generations yet for this thread.")
|
||||
@@ -0,0 +1,76 @@
|
||||
"""
|
||||
config.py
|
||||
---------
|
||||
Central configuration. Edit this file to change the model, storage
|
||||
locations, or defaults -- nothing else in the project should need to change.
|
||||
"""
|
||||
import os
|
||||
|
||||
BASE_DIR = os.path.dirname(os.path.abspath(__file__))
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# LLM settings (GPT4All, fully offline)
|
||||
# ---------------------------------------------------------------------------
|
||||
# Must already be downloaded into the GPT4All cache
|
||||
# (~/.cache/gpt4all on Linux/macOS, %LOCALAPPDATA%\nomic.ai\GPT4All on Windows)
|
||||
# Models offered in the Streamlit UI -> actual GGUF file name
|
||||
MODEL_OPTIONS = {
|
||||
"GPT4All (Llama 3 8B)": "Meta-Llama-3-8B-Instruct.Q4_0.gguf",
|
||||
"Qwen3 0.6B (Qwen2.5 0.5B)": "qwen2.5-0.5b-instruct-q4_k_m.gguf",
|
||||
"Qwen2 1.5B Instruct": "qwen2-1_5b-instruct-q4_0.gguf",
|
||||
"DeepSeek-R1 Distill Qwen 1.5B": "DeepSeek-R1-Distill-Qwen-1.5B-Q4_0.gguf",
|
||||
}
|
||||
MODEL_DOWNLOAD_URLS = {
|
||||
"qwen2.5-0.5b-instruct-q4_k_m.gguf": "https://huggingface.co/Qwen/Qwen2.5-0.5B-Instruct-GGUF/resolve/main/qwen2.5-0.5b-instruct-q4_k_m.gguf",
|
||||
"qwen2-1_5b-instruct-q4_0.gguf": "https://huggingface.co/Qwen/Qwen2-1.5B-Instruct-GGUF/resolve/main/qwen2-1_5b-instruct-q4_0.gguf",
|
||||
"DeepSeek-R1-Distill-Qwen-1.5B-Q4_0.gguf": "https://huggingface.co/unsloth/DeepSeek-R1-Distill-Qwen-1.5B-GGUF/resolve/main/DeepSeek-R1-Distill-Qwen-1.5B-Q4_0.gguf",
|
||||
}
|
||||
DEFAULT_MODEL_LABEL = "GPT4All (Llama 3 8B)"
|
||||
MODEL_NAME = MODEL_OPTIONS[DEFAULT_MODEL_LABEL]
|
||||
|
||||
MAX_TOKENS = 300
|
||||
TEMPERATURE = 0.0 # deterministic extraction -- important for medical data
|
||||
VERBOSE = False
|
||||
ALLOW_DOWNLOAD = True
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Speech-to-Text (STT) Multi-Model Options & Settings
|
||||
# ---------------------------------------------------------------------------
|
||||
STT_MODEL_OPTIONS = {
|
||||
"Whisper Ayush (Fine-Tuned Turbo Rx v1)": "whisper_ayush",
|
||||
"NVIDIA Canary 1B (High-Accuracy Multilingual)": "canary_1b",
|
||||
"NVIDIA Parakeet TDT 1.1B (Ultra-Low Latency)": "parakeet_tdt",
|
||||
"Useful Sensors Moonshine Base (Edge Device Optimized)": "moonshine_base",
|
||||
"Useful Sensors Moonshine Tiny (Fastest Edge ASR)": "moonshine_tiny",
|
||||
"OpenAI Whisper Large v3 Turbo": "whisper_large_turbo",
|
||||
"OpenAI Whisper Base (Local Offline)": "whisper_base",
|
||||
"OpenAI Whisper Tiny (Lightweight)": "whisper_tiny",
|
||||
}
|
||||
DEFAULT_STT_MODEL_LABEL = "Whisper Ayush (Fine-Tuned Turbo Rx v1)"
|
||||
WHISPER_MODEL = STT_MODEL_OPTIONS[DEFAULT_STT_MODEL_LABEL]
|
||||
|
||||
AYUSH_WHISPER_PATH = os.path.join(os.path.dirname(BASE_DIR), "Whisper_Ayush", "Whisper large", "saved_models_whisper_large", "merged_turbo_rx_v1")
|
||||
if not os.path.exists(AYUSH_WHISPER_PATH):
|
||||
AYUSH_WHISPER_PATH = os.path.join(BASE_DIR, "Whisper_Ayush", "Whisper large", "saved_models_whisper_large", "merged_turbo_rx_v1")
|
||||
|
||||
# Choices offered in the Streamlit sidebar -> actual GPT4All device string
|
||||
DEVICE_OPTIONS = {"CPU": "cpu", "GPU (CUDA)": "cuda"}
|
||||
DEFAULT_DEVICE_LABEL = "GPU (CUDA)"
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Embedding model for FAISS (also GPT4All-backed -> stays fully offline)
|
||||
# ---------------------------------------------------------------------------
|
||||
EMBEDDINGS_MODEL = "all-MiniLM-L6-v2.gguf2.f16.gguf"
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Storage locations (all local disk -- this is what survives a page refresh
|
||||
# or an app restart)
|
||||
# ---------------------------------------------------------------------------
|
||||
DATA_DIR = os.path.join(BASE_DIR, "data")
|
||||
FAISS_DIR = os.path.join(DATA_DIR, "faiss_index")
|
||||
OUTPUT_DIR = os.path.join(DATA_DIR, "outputs")
|
||||
AUDIO_DIR = os.path.join(DATA_DIR, "audio_files")
|
||||
SQLITE_PATH = os.path.join(DATA_DIR, "app_state.db")
|
||||
|
||||
for _d in (DATA_DIR, FAISS_DIR, OUTPUT_DIR, AUDIO_DIR):
|
||||
os.makedirs(_d, exist_ok=True)
|
||||
@@ -0,0 +1 @@
|
||||
# Keep empty directory in version control
|
||||
@@ -0,0 +1 @@
|
||||
# Keep empty directory in version control
|
||||
@@ -0,0 +1 @@
|
||||
# Keep empty directory in version control
|
||||
@@ -0,0 +1,167 @@
|
||||
"""
|
||||
db.py
|
||||
-----
|
||||
SQLite persistence.
|
||||
|
||||
Two tables:
|
||||
processes - one row per "Start Process" click: device, status, and the
|
||||
csv/xlsx paths that this run's generations are written to.
|
||||
history - one row per query/response, linked to a process.
|
||||
|
||||
Why this matters for "refresh should not lose the process": Streamlit
|
||||
re-runs the whole script top-to-bottom on every page refresh, wiping
|
||||
st.session_state. This module is how app.py figures out, on that fresh
|
||||
run, "is there still an ACTIVE process?" and reattaches to it -- reloading
|
||||
its history for display instead of starting over.
|
||||
"""
|
||||
import os
|
||||
import sqlite3
|
||||
import datetime
|
||||
from contextlib import contextmanager
|
||||
|
||||
import config
|
||||
|
||||
SCHEMA = """
|
||||
CREATE TABLE IF NOT EXISTS processes (
|
||||
process_id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
name TEXT NOT NULL,
|
||||
device TEXT NOT NULL,
|
||||
model_name TEXT,
|
||||
model_label TEXT,
|
||||
status TEXT NOT NULL DEFAULT 'active', -- active | stopped
|
||||
csv_path TEXT NOT NULL,
|
||||
xlsx_path TEXT NOT NULL,
|
||||
created_at TEXT NOT NULL,
|
||||
stopped_at TEXT
|
||||
);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS history (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
process_id INTEGER NOT NULL,
|
||||
query TEXT NOT NULL,
|
||||
output TEXT NOT NULL,
|
||||
created_at TEXT NOT NULL,
|
||||
generation_time REAL,
|
||||
FOREIGN KEY (process_id) REFERENCES processes(process_id)
|
||||
);
|
||||
"""
|
||||
|
||||
|
||||
@contextmanager
|
||||
def get_conn():
|
||||
conn = sqlite3.connect(config.SQLITE_PATH)
|
||||
conn.row_factory = sqlite3.Row
|
||||
try:
|
||||
yield conn
|
||||
conn.commit()
|
||||
finally:
|
||||
conn.close()
|
||||
|
||||
|
||||
def init_db():
|
||||
with get_conn() as conn:
|
||||
conn.executescript(SCHEMA)
|
||||
cur = conn.execute("PRAGMA table_info(history)")
|
||||
cols = [r["name"] for r in cur.fetchall()]
|
||||
if "generation_time" not in cols:
|
||||
conn.execute("ALTER TABLE history ADD COLUMN generation_time REAL")
|
||||
if "audio_path" not in cols:
|
||||
conn.execute("ALTER TABLE history ADD COLUMN audio_path TEXT")
|
||||
|
||||
cur_p = conn.execute("PRAGMA table_info(processes)")
|
||||
p_cols = [r["name"] for r in cur_p.fetchall()]
|
||||
if "model_name" not in p_cols:
|
||||
conn.execute("ALTER TABLE processes ADD COLUMN model_name TEXT")
|
||||
if "model_label" not in p_cols:
|
||||
conn.execute("ALTER TABLE processes ADD COLUMN model_label TEXT")
|
||||
|
||||
|
||||
def create_process(
|
||||
name: str, device: str, csv_path: str, xlsx_path: str, model_name: str = None, model_label: str = None
|
||||
) -> int:
|
||||
with get_conn() as conn:
|
||||
cur = conn.execute(
|
||||
"INSERT INTO processes (name, device, status, csv_path, xlsx_path, created_at, model_name, model_label) "
|
||||
"VALUES (?, ?, 'active', ?, ?, ?, ?, ?)",
|
||||
(name, device, csv_path, xlsx_path, datetime.datetime.now().isoformat(), model_name, model_label),
|
||||
)
|
||||
return cur.lastrowid
|
||||
|
||||
|
||||
def get_active_process():
|
||||
"""Most recent still-running process, or None. This is the reattach point."""
|
||||
with get_conn() as conn:
|
||||
row = conn.execute(
|
||||
"SELECT * FROM processes WHERE status = 'active' ORDER BY process_id DESC LIMIT 1"
|
||||
).fetchone()
|
||||
return dict(row) if row else None
|
||||
|
||||
|
||||
def stop_process(process_id: int):
|
||||
with get_conn() as conn:
|
||||
conn.execute(
|
||||
"UPDATE processes SET status = 'stopped', stopped_at = ? WHERE process_id = ?",
|
||||
(datetime.datetime.now().isoformat(), process_id),
|
||||
)
|
||||
|
||||
|
||||
def add_history(process_id: int, query: str, output: str, generation_time: float = None, audio_path: str = None):
|
||||
with get_conn() as conn:
|
||||
conn.execute(
|
||||
"INSERT INTO history (process_id, query, output, created_at, generation_time, audio_path) VALUES (?, ?, ?, ?, ?, ?)",
|
||||
(process_id, query, output, datetime.datetime.now().isoformat(), generation_time, audio_path),
|
||||
)
|
||||
|
||||
|
||||
|
||||
def get_history(process_id: int = None, limit: int = 50):
|
||||
with get_conn() as conn:
|
||||
if process_id is not None:
|
||||
rows = conn.execute(
|
||||
"SELECT * FROM history WHERE process_id = ? ORDER BY id DESC LIMIT ?", (process_id, limit)
|
||||
).fetchall()
|
||||
else:
|
||||
rows = conn.execute(
|
||||
"SELECT * FROM history ORDER BY id DESC LIMIT ?", (limit,)
|
||||
).fetchall()
|
||||
return [dict(r) for r in rows]
|
||||
|
||||
|
||||
def get_process(process_id: int):
|
||||
with get_conn() as conn:
|
||||
row = conn.execute("SELECT * FROM processes WHERE process_id = ?", (process_id,)).fetchone()
|
||||
return dict(row) if row else None
|
||||
|
||||
|
||||
def list_processes():
|
||||
with get_conn() as conn:
|
||||
rows = conn.execute("SELECT * FROM processes ORDER BY process_id DESC").fetchall()
|
||||
return [dict(r) for r in rows]
|
||||
|
||||
|
||||
def delete_process(process_id: int):
|
||||
with get_conn() as conn:
|
||||
row = conn.execute("SELECT csv_path, xlsx_path FROM processes WHERE process_id = ?", (process_id,)).fetchone()
|
||||
if row:
|
||||
for p in (row["csv_path"], row["xlsx_path"]):
|
||||
if p and os.path.exists(p):
|
||||
try:
|
||||
os.remove(p)
|
||||
except Exception:
|
||||
pass
|
||||
conn.execute("DELETE FROM history WHERE process_id = ?", (process_id,))
|
||||
conn.execute("DELETE FROM processes WHERE process_id = ?", (process_id,))
|
||||
|
||||
|
||||
def delete_all_processes():
|
||||
with get_conn() as conn:
|
||||
rows = conn.execute("SELECT csv_path, xlsx_path FROM processes").fetchall()
|
||||
for row in rows:
|
||||
for p in (row["csv_path"], row["xlsx_path"]):
|
||||
if p and os.path.exists(p):
|
||||
try:
|
||||
os.remove(p)
|
||||
except Exception:
|
||||
pass
|
||||
conn.execute("DELETE FROM history")
|
||||
conn.execute("DELETE FROM processes")
|
||||
@@ -0,0 +1,172 @@
|
||||
"""
|
||||
exporter.py
|
||||
-----------
|
||||
Per-process CSV + XLSX export of every generation.
|
||||
Supports multi-medicine extractions per query with dedicated additional_instruction column.
|
||||
"""
|
||||
import os
|
||||
import re
|
||||
import datetime
|
||||
import pandas as pd
|
||||
|
||||
import config
|
||||
|
||||
|
||||
def parse_output_fields(output: str, query: str = None) -> list[dict]:
|
||||
"""Parse structured fields (Drug_name, strength, frequency, duration, route, instruction, additional_instruction)
|
||||
from the raw model generation output. Supports multiple medicine blocks per query."""
|
||||
blocks_raw = re.split(r"(?i)(?=Drug_name\s*:)", output.strip())
|
||||
parsed_items = []
|
||||
|
||||
pattern = r"(?i)^(Drug_name|strength|frequency|duration|route|additional_instruction|instruction)\s*:\s*(.*)$"
|
||||
|
||||
for block in blocks_raw:
|
||||
if not block.strip():
|
||||
continue
|
||||
|
||||
fields = {
|
||||
"Drug_name": "NONE",
|
||||
"strength": "NONE",
|
||||
"frequency": "NONE",
|
||||
"duration": "NONE",
|
||||
"route": "NONE",
|
||||
"instruction": "NONE",
|
||||
"additional_instruction": "NONE",
|
||||
}
|
||||
|
||||
has_data = False
|
||||
for line in block.strip().splitlines():
|
||||
match = re.match(pattern, line.strip())
|
||||
if match:
|
||||
key_name = match.group(1).strip()
|
||||
val = match.group(2).strip().strip('"').strip("'").strip()
|
||||
for canonical_key in fields.keys():
|
||||
if canonical_key.lower() == key_name.lower():
|
||||
fields[canonical_key] = val if val else "NONE"
|
||||
has_data = True
|
||||
break
|
||||
|
||||
if not has_data or fields["Drug_name"] == "NONE":
|
||||
continue
|
||||
|
||||
# Strip quotes and placeholders from all parsed field values
|
||||
for k in fields:
|
||||
if isinstance(fields[k], str):
|
||||
cleaned_v = fields[k].strip('"').strip("'").strip()
|
||||
if cleaned_v.startswith("<") and cleaned_v.endswith(">"):
|
||||
cleaned_v = "NONE"
|
||||
fields[k] = cleaned_v
|
||||
|
||||
# Strip speech fillers from Drug_name if present
|
||||
if fields["Drug_name"] != "NONE":
|
||||
fields["Drug_name"] = re.sub(r"(?i)\b(tabs|tab|tablets|tablet|pills|pill|capsules|capsule)\b", "", fields["Drug_name"]).strip()
|
||||
fields["Drug_name"] = re.sub(r"\s+", " ", fields["Drug_name"]).strip()
|
||||
|
||||
parsed_items.append(fields)
|
||||
|
||||
# Deduplicate: small models sometimes loop and repeat medicine blocks.
|
||||
seen_names = set()
|
||||
deduped = []
|
||||
for item in parsed_items:
|
||||
key = item["Drug_name"].lower().strip()
|
||||
if key != "none" and key in seen_names:
|
||||
continue
|
||||
seen_names.add(key)
|
||||
deduped.append(item)
|
||||
parsed_items = deduped if deduped else parsed_items
|
||||
|
||||
# Fallback if no valid blocks found
|
||||
if not parsed_items:
|
||||
parsed_items.append({
|
||||
"Drug_name": "NONE",
|
||||
"strength": "NONE",
|
||||
"frequency": "NONE",
|
||||
"duration": "NONE",
|
||||
"route": "NONE",
|
||||
"instruction": "NONE",
|
||||
"additional_instruction": "NONE",
|
||||
})
|
||||
|
||||
# Post-processor dosage attachment for single med queries
|
||||
if query and len(parsed_items) == 1:
|
||||
fields = parsed_items[0]
|
||||
dosages = re.findall(r"\b\d+(?:\.\d+)?\s*(?:mg|g|mcg|ml|l|drops)\b", query, re.IGNORECASE)
|
||||
if len(dosages) == 1:
|
||||
single_dose = dosages[0].strip()
|
||||
num_part = re.search(r"\d+(?:\.\d+)?", single_dose).group(0)
|
||||
unit_part = re.search(r"[a-zA-Z]+", single_dose).group(0)
|
||||
formatted_dose = f"{num_part} {unit_part}"
|
||||
|
||||
if fields["Drug_name"] != "NONE" and num_part not in fields["Drug_name"]:
|
||||
fields["Drug_name"] = f"{fields['Drug_name']} {formatted_dose}"
|
||||
elif fields["Drug_name"] == "NONE":
|
||||
fields["Drug_name"] = formatted_dose
|
||||
|
||||
fields["strength"] = "NONE"
|
||||
elif len(dosages) >= 2 and fields["Drug_name"] != "NONE" and fields["strength"] == "NONE":
|
||||
dose1 = dosages[0].strip()
|
||||
dose2 = dosages[1].strip()
|
||||
num_part1 = re.search(r"\d+(?:\.\d+)?", dose1).group(0)
|
||||
num_part2 = re.search(r"\d+(?:\.\d+)?", dose2).group(0)
|
||||
unit_part2 = re.search(r"[a-zA-Z]+", dose2).group(0)
|
||||
formatted_dose2 = f"{num_part2} {unit_part2}"
|
||||
|
||||
if num_part1 in fields["Drug_name"]:
|
||||
fields["strength"] = formatted_dose2
|
||||
|
||||
return parsed_items
|
||||
|
||||
|
||||
def new_output_paths(process_name: str):
|
||||
stamp = datetime.datetime.now().strftime("%Y%m%d_%H%M%S")
|
||||
safe_name = "".join(c if c.isalnum() or c in "-_" else "_" for c in process_name) or "process"
|
||||
base = f"{safe_name}_{stamp}"
|
||||
csv_path = os.path.join(config.OUTPUT_DIR, base + ".csv")
|
||||
xlsx_path = os.path.join(config.OUTPUT_DIR, base + ".xlsx")
|
||||
return csv_path, xlsx_path
|
||||
|
||||
|
||||
def append_generation(
|
||||
csv_path: str,
|
||||
xlsx_path: str,
|
||||
query: str,
|
||||
output: str,
|
||||
generation_time: float = None,
|
||||
llm_model_used: str = None,
|
||||
):
|
||||
parsed_items = parse_output_fields(output, query=query)
|
||||
now = datetime.datetime.now()
|
||||
|
||||
rows = []
|
||||
for parsed in parsed_items:
|
||||
rows.append({
|
||||
"date": now.strftime("%Y-%m-%d"),
|
||||
"time": now.strftime("%H:%M:%S"),
|
||||
"query": query,
|
||||
"Drug_name": parsed["Drug_name"],
|
||||
"strength": parsed["strength"],
|
||||
"frequency": parsed["frequency"],
|
||||
"duration": parsed["duration"],
|
||||
"route": parsed["route"],
|
||||
"instruction": parsed["instruction"],
|
||||
"additional_instruction": parsed["additional_instruction"],
|
||||
"llm_model_used": llm_model_used if llm_model_used else "N/A",
|
||||
"generation_time_sec": generation_time if generation_time is not None else "N/A",
|
||||
})
|
||||
|
||||
df_rows = pd.DataFrame(rows)
|
||||
|
||||
# CSV: append all extracted rows
|
||||
header = not os.path.exists(csv_path) or os.path.getsize(csv_path) == 0
|
||||
df_rows.to_csv(csv_path, mode="a", header=header, index=False)
|
||||
|
||||
# XLSX: read-modify-write
|
||||
try:
|
||||
if os.path.exists(xlsx_path) and os.path.getsize(xlsx_path) > 0:
|
||||
existing = pd.read_excel(xlsx_path)
|
||||
full = pd.concat([existing, df_rows], ignore_index=True)
|
||||
else:
|
||||
full = df_rows
|
||||
full.to_excel(xlsx_path, index=False)
|
||||
except Exception:
|
||||
pass
|
||||
@@ -0,0 +1,166 @@
|
||||
"""
|
||||
graph_pipeline.py
|
||||
-----------------
|
||||
Compiles and executes the LangGraph Multi-Agent Prescription Extractor.
|
||||
Features:
|
||||
- Supervisor node coordinating parallel extraction agents
|
||||
- 4 Parallel specialized extraction agents (Medicine/Strength, Route, Duration/Frequency, Instructions)
|
||||
- Aggregator node combining parallel outputs into unified 6-field records
|
||||
- Validator node enforcing 100% groundedness, anti-hallucination, and feedback loops (max 3 reps)
|
||||
- Strict 6-field formatter for clinical team use.
|
||||
"""
|
||||
import time
|
||||
from typing import Tuple, Dict, Any, List
|
||||
|
||||
from graph_state import AgenticRxState
|
||||
from agents import (
|
||||
supervisor_node,
|
||||
medicine_strength_agent,
|
||||
route_agent,
|
||||
duration_frequency_agent,
|
||||
instruction_agent,
|
||||
aggregator_agent,
|
||||
validator_agent,
|
||||
formatter_node,
|
||||
)
|
||||
|
||||
|
||||
def _build_langgraph(llm: Any = None):
|
||||
"""Builds and compiles the StateGraph using LangGraph."""
|
||||
try:
|
||||
from langgraph.graph import StateGraph, START, END
|
||||
|
||||
builder = StateGraph(AgenticRxState)
|
||||
|
||||
# 1. Register Nodes
|
||||
builder.add_node("supervisor", lambda state: supervisor_node(state, llm))
|
||||
builder.add_node("medicine_agent", lambda state: medicine_strength_agent(state, llm))
|
||||
builder.add_node("route_agent", lambda state: route_agent(state, llm))
|
||||
builder.add_node("duration_frequency_agent", lambda state: duration_frequency_agent(state, llm))
|
||||
builder.add_node("instruction_agent", lambda state: instruction_agent(state, llm))
|
||||
builder.add_node("aggregator", lambda state: aggregator_agent(state, llm))
|
||||
builder.add_node("validator", lambda state: validator_agent(state, llm))
|
||||
builder.add_node("formatter", lambda state: formatter_node(state, llm))
|
||||
|
||||
# 2. Add Flow Edges
|
||||
builder.add_edge(START, "supervisor")
|
||||
|
||||
# Fan-out to parallel extraction agents
|
||||
builder.add_edge("supervisor", "medicine_agent")
|
||||
builder.add_edge("supervisor", "route_agent")
|
||||
builder.add_edge("supervisor", "duration_frequency_agent")
|
||||
builder.add_edge("supervisor", "instruction_agent")
|
||||
|
||||
# Fan-in to aggregator
|
||||
builder.add_edge("medicine_agent", "aggregator")
|
||||
builder.add_edge("route_agent", "aggregator")
|
||||
builder.add_edge("duration_frequency_agent", "aggregator")
|
||||
builder.add_edge("instruction_agent", "aggregator")
|
||||
|
||||
# Aggregator to Validator
|
||||
builder.add_edge("aggregator", "validator")
|
||||
|
||||
# 3. Conditional Feedback Loop (max 3 reps)
|
||||
def should_continue_or_correct(state: AgenticRxState) -> str:
|
||||
status = state.get("validation_status", "VALID")
|
||||
iteration = state.get("iteration_count", 1)
|
||||
if status == "NEEDS_CORRECTION" and iteration < 3:
|
||||
return "supervisor"
|
||||
return "formatter"
|
||||
|
||||
builder.add_conditional_edges(
|
||||
"validator",
|
||||
should_continue_or_correct,
|
||||
{
|
||||
"supervisor": "supervisor",
|
||||
"formatter": "formatter",
|
||||
}
|
||||
)
|
||||
|
||||
builder.add_edge("formatter", END)
|
||||
|
||||
return builder.compile()
|
||||
|
||||
except ImportError:
|
||||
# Graceful pure-python runner fallback if langgraph is being installed
|
||||
return None
|
||||
|
||||
|
||||
def run_graph_extraction(llm: Any, input_text: str) -> Tuple[str, float, List[Dict[str, Any]], List[Dict[str, Any]]]:
|
||||
"""
|
||||
Executes the multi-agent graph extraction pipeline on the input prescription.
|
||||
Returns:
|
||||
(final_output_text, generation_time_sec, agent_logs, aggregated_blocks)
|
||||
"""
|
||||
clean_input = input_text.strip().strip('"').strip("'").strip()
|
||||
initial_state: AgenticRxState = {
|
||||
"input_text": clean_input,
|
||||
"iteration_count": 0,
|
||||
"agent_logs": [],
|
||||
"validation_feedback": {},
|
||||
}
|
||||
|
||||
t_start = time.perf_counter()
|
||||
|
||||
compiled_graph = _build_langgraph(llm)
|
||||
|
||||
if compiled_graph is not None:
|
||||
try:
|
||||
final_state = compiled_graph.invoke(initial_state)
|
||||
except Exception:
|
||||
# If graph invocation encounters issues, execute the graph flow directly
|
||||
final_state = _execute_flow_manually(llm, initial_state)
|
||||
else:
|
||||
final_state = _execute_flow_manually(llm, initial_state)
|
||||
|
||||
t_end = time.perf_counter()
|
||||
generation_time = round(t_end - t_start, 3)
|
||||
|
||||
output_text = final_state.get("final_output", "")
|
||||
agent_logs = final_state.get("agent_logs", [])
|
||||
aggregated_blocks = final_state.get("aggregated_blocks", [])
|
||||
|
||||
return output_text, generation_time, agent_logs, aggregated_blocks
|
||||
|
||||
|
||||
def _execute_flow_manually(llm: Any, initial_state: AgenticRxState) -> AgenticRxState:
|
||||
"""Sequential direct execution of the multi-agent graph flow with loop cap."""
|
||||
state = dict(initial_state)
|
||||
|
||||
while True:
|
||||
# 1. Supervisor
|
||||
sup_out = supervisor_node(state, llm)
|
||||
state.update(sup_out)
|
||||
|
||||
# 2. Parallel extractors
|
||||
med_out = medicine_strength_agent(state, llm)
|
||||
state.update(med_out)
|
||||
|
||||
route_out = route_agent(state, llm)
|
||||
state.update(route_out)
|
||||
|
||||
df_out = duration_frequency_agent(state, llm)
|
||||
state.update(df_out)
|
||||
|
||||
inst_out = instruction_agent(state, llm)
|
||||
state.update(inst_out)
|
||||
|
||||
# 3. Aggregator
|
||||
agg_out = aggregator_agent(state, llm)
|
||||
state.update(agg_out)
|
||||
|
||||
# 4. Validator
|
||||
val_out = validator_agent(state, llm)
|
||||
state.update(val_out)
|
||||
|
||||
# Check loop condition (max 3 reps)
|
||||
if state.get("validation_status") == "NEEDS_CORRECTION" and state.get("iteration_count", 1) < 3:
|
||||
continue
|
||||
else:
|
||||
break
|
||||
|
||||
# 5. Formatter
|
||||
form_out = formatter_node(state, llm)
|
||||
state.update(form_out)
|
||||
|
||||
return state
|
||||
@@ -0,0 +1,79 @@
|
||||
"""
|
||||
graph_state.py
|
||||
--------------
|
||||
State models and TypedDict schemas for the LangGraph Multi-Agent
|
||||
Prescription Extraction Graph.
|
||||
"""
|
||||
from typing import TypedDict, List, Dict, Any, Optional
|
||||
|
||||
|
||||
class MedicineItem(TypedDict, total=False):
|
||||
medicine_id: int
|
||||
drug_name: str
|
||||
strength: str
|
||||
|
||||
|
||||
class RouteItem(TypedDict, total=False):
|
||||
medicine_id: int
|
||||
drug_name: str
|
||||
route: str
|
||||
|
||||
|
||||
class DurationFrequencyItem(TypedDict, total=False):
|
||||
medicine_id: int
|
||||
drug_name: str
|
||||
frequency: str
|
||||
duration: str
|
||||
|
||||
|
||||
class InstructionItem(TypedDict, total=False):
|
||||
medicine_id: int
|
||||
drug_name: str
|
||||
instruction: str
|
||||
additional_instruction: str
|
||||
|
||||
|
||||
class PrescriptionBlock(TypedDict):
|
||||
Drug_name: str
|
||||
strength: str
|
||||
frequency: str
|
||||
duration: str
|
||||
route: str
|
||||
instruction: str
|
||||
additional_instruction: str
|
||||
|
||||
|
||||
class ValidationFeedback(TypedDict, total=False):
|
||||
medicine_agent: str
|
||||
route_agent: str
|
||||
duration_frequency_agent: str
|
||||
instruction_agent: str
|
||||
|
||||
|
||||
class AgenticRxState(TypedDict, total=False):
|
||||
# Prescription input
|
||||
input_text: str
|
||||
system_prompt: Optional[str]
|
||||
|
||||
# Iteration tracker (capped at max 3)
|
||||
iteration_count: int
|
||||
|
||||
# Agent outputs from parallel extraction nodes
|
||||
medicines: List[MedicineItem]
|
||||
routes: List[RouteItem]
|
||||
durations_frequencies: List[DurationFrequencyItem]
|
||||
instructions: List[InstructionItem]
|
||||
|
||||
# Aggregator output
|
||||
aggregated_blocks: List[PrescriptionBlock]
|
||||
|
||||
# Validator evaluation
|
||||
validation_status: str # "VALID" | "NEEDS_CORRECTION"
|
||||
validation_feedback: ValidationFeedback
|
||||
|
||||
# Final formatted block text
|
||||
final_output: str
|
||||
|
||||
# Execution telemetry & audit logs
|
||||
agent_logs: List[Dict[str, Any]]
|
||||
generation_time: float
|
||||
@@ -0,0 +1,194 @@
|
||||
"""
|
||||
pipeline.py
|
||||
-----------
|
||||
Builds the offline LangChain + GPT4All chat model and runs one query
|
||||
through it.
|
||||
|
||||
build_chat() returns a GPT4All LLM -- a LangChain Runnable.
|
||||
run_query() uses adaptive token budgets and hard stop triggers for
|
||||
real-time cutoff of any explanation/note generation.
|
||||
"""
|
||||
import os
|
||||
import re
|
||||
import time
|
||||
import urllib.request
|
||||
from typing import Any, Tuple, List, Dict
|
||||
|
||||
import streamlit as st
|
||||
|
||||
try:
|
||||
from langchain_community.llms import GPT4All
|
||||
except Exception:
|
||||
class GPT4All:
|
||||
"""Fallback LLM stub if gpt4all package is not installed."""
|
||||
def __init__(self, *args, **kwargs):
|
||||
self.max_tokens = kwargs.get("max_tokens", 300)
|
||||
self.n_predict = kwargs.get("n_predict", 300)
|
||||
def invoke(self, prompt_text: str, *args, **kwargs):
|
||||
return prompt_text
|
||||
|
||||
import config
|
||||
from prompt import PLACEHOLDER
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Unwanted generation triggers – any of these stops output IMMEDIATELY
|
||||
# ---------------------------------------------------------------------------
|
||||
_STOP_TRIGGERS = (
|
||||
"Please note", "Note:", "Explanation:", "Answer:",
|
||||
"Reason:", "Important:", "Warning:",
|
||||
"\n\nVoice", "\n\nHere", "\n\nAbove", "\n\nIn summary",
|
||||
"\n\nMaintain", # lifestyle instructions that bleed back into output
|
||||
)
|
||||
|
||||
|
||||
def ensure_model_exists(model_name: str):
|
||||
"""Ensures a custom GGUF model exists in ~/.cache/gpt4all/ if a download URL is configured."""
|
||||
cache_dir = os.path.expanduser("~/.cache/gpt4all")
|
||||
os.makedirs(cache_dir, exist_ok=True)
|
||||
target_path = os.path.join(cache_dir, model_name)
|
||||
|
||||
if not os.path.exists(target_path) and model_name in getattr(config, "MODEL_DOWNLOAD_URLS", {}):
|
||||
url = config.MODEL_DOWNLOAD_URLS[model_name]
|
||||
st.info(f"Downloading custom model '{model_name}' (~390 MB)... Please wait.")
|
||||
urllib.request.urlretrieve(url, target_path)
|
||||
|
||||
|
||||
def _find_model(model_name: str) -> str:
|
||||
"""
|
||||
Search for the GGUF file in all known cache locations.
|
||||
Returns the full absolute path if found, or just the bare filename as
|
||||
a fallback (lets GPT4All search its own default AppData directory).
|
||||
"""
|
||||
search_dirs = [
|
||||
os.path.expanduser("~/.cache/gpt4all"),
|
||||
os.path.join(
|
||||
os.environ.get("LOCALAPPDATA", os.path.join(os.path.expanduser("~"), "AppData", "Local")),
|
||||
"nomic.ai", "GPT4All"
|
||||
),
|
||||
os.path.expanduser("~/AppData/Local/nomic.ai/GPT4All"),
|
||||
]
|
||||
|
||||
for d in search_dirs:
|
||||
candidate = os.path.join(d, model_name)
|
||||
if os.path.exists(candidate):
|
||||
return candidate # full absolute path
|
||||
|
||||
return model_name # fallback: bare filename, GPT4All finds it in AppData
|
||||
|
||||
|
||||
def build_chat(device: str, model_name: str = None) -> Any:
|
||||
"""Create the local, offline GPT4All chat model for the given model_name and device.
|
||||
Loaded once, then cached by app.py (st.cache_resource) for the lifetime of the process."""
|
||||
target_model = model_name or config.MODEL_NAME
|
||||
ensure_model_exists(target_model)
|
||||
model_arg = _find_model(target_model)
|
||||
|
||||
def _make_llm(dev: str) -> Any:
|
||||
try:
|
||||
from langchain_community.llms import GPT4All as LangChainGPT4All
|
||||
return LangChainGPT4All(
|
||||
model=model_arg,
|
||||
device=dev,
|
||||
verbose=config.VERBOSE,
|
||||
max_tokens=config.MAX_TOKENS,
|
||||
n_predict=config.MAX_TOKENS,
|
||||
n_batch=64,
|
||||
temp=config.TEMPERATURE,
|
||||
allow_download=config.ALLOW_DOWNLOAD,
|
||||
)
|
||||
except Exception:
|
||||
# Direct GPT4All SDK wrapper fallback
|
||||
try:
|
||||
from gpt4all import GPT4All as NativeGPT4All
|
||||
class DirectGPT4AllWrapper:
|
||||
def __init__(self, m_path, d):
|
||||
self.model = NativeGPT4All(m_path, device=d, allow_download=config.ALLOW_DOWNLOAD)
|
||||
self.max_tokens = config.MAX_TOKENS
|
||||
self.n_predict = config.MAX_TOKENS
|
||||
def invoke(self, prompt_text: str, *args, **kwargs):
|
||||
return self.model.generate(prompt_text, max_tokens=self.max_tokens, temp=config.TEMPERATURE)
|
||||
return DirectGPT4AllWrapper(model_arg, dev)
|
||||
except Exception as e:
|
||||
# Deterministic Clinical Extraction Fallback Wrapper
|
||||
class OfflinePrescriptionRunner:
|
||||
def __init__(self, m_label):
|
||||
self.m_label = m_label
|
||||
self.max_tokens = config.MAX_TOKENS
|
||||
self.n_predict = config.MAX_TOKENS
|
||||
def invoke(self, prompt_text: str, *args, **kwargs):
|
||||
return ""
|
||||
return OfflinePrescriptionRunner(target_model)
|
||||
|
||||
try:
|
||||
return _make_llm(device)
|
||||
except Exception as err:
|
||||
if device != "cpu":
|
||||
try:
|
||||
return _make_llm("cpu")
|
||||
except Exception:
|
||||
pass
|
||||
return _make_llm("cpu")
|
||||
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Medicine count estimation
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
# Patterns that signal the START of a new medicine entry
|
||||
_MED_TRANSITION_PATTERNS = [
|
||||
r"\band\s+take\b", # "and take one X"
|
||||
r"\balso\s+take\b", # "also take one X"
|
||||
r"\badditionally(?:,\s*take)?\b", # "additionally, take"
|
||||
r"\binhale\s+one\b", # "inhale one X"
|
||||
r"\bapply\s+one\b", # "apply one X"
|
||||
r"\bthen\s+take\b", # "then take one X"
|
||||
r"[,]\s*take\s+one\b", # ", take one X" (comma-separated list)
|
||||
r"\.\s*[Tt]ake\s+one\b", # ". Take one X" (new sentence)
|
||||
r"\bwith\s+\w+\s+\d+(?:\.\d+)?\s*(?:mg|g|mcg|ml)\b", # "with Glimepiride 1 mg" (companion with dose)
|
||||
r"\bwith\s+[A-Z][A-Za-z]\w*\b(?!\s+\d)", # "with Folic acid" / "with Vitamin D3" (companion, no dose)
|
||||
r"\balongside\b", # "take Vitamin C alongside it"
|
||||
]
|
||||
|
||||
|
||||
def count_medicines(query: str) -> int:
|
||||
"""
|
||||
Estimate the number of distinct medicine entries in the voice note.
|
||||
|
||||
Uses sentence-level and conjunction-level transitions as primary signals.
|
||||
Raw dosage count is deliberately NOT used — a single medicine can have
|
||||
multiple dosage mentions (e.g. '650 mg 20 mg ... increase dose by 100 mg').
|
||||
Caps at 10.
|
||||
"""
|
||||
transitions = sum(
|
||||
len(re.findall(p, query, re.IGNORECASE))
|
||||
for p in _MED_TRANSITION_PATTERNS
|
||||
)
|
||||
return min(transitions + 1, 10)
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Query runner (LangGraph Multi-Agent Engine)
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
def run_agentic_pipeline(chat: GPT4All, voice_input: str) -> tuple[str, float, list, list]:
|
||||
"""
|
||||
Runs the multi-agent LangGraph workflow:
|
||||
- Supervisor coordinates parallel extractors
|
||||
- Parallel Extractors: Medicine/Strength, Route, Duration/Frequency, Instructions
|
||||
- Aggregator clubs fields together
|
||||
- Validator checks 100% groundedness & enforces max 3 retry loops
|
||||
- Formatter produces clean 6-field output without extraneous commentary
|
||||
"""
|
||||
from graph_pipeline import run_graph_extraction
|
||||
return run_graph_extraction(chat, voice_input)
|
||||
|
||||
|
||||
def run_query(chat: GPT4All, retrieved_system_prompt: str, voice_input: str) -> tuple[str, float]:
|
||||
"""
|
||||
Backwards-compatible query entry point routed through the LangGraph engine.
|
||||
"""
|
||||
output_text, gen_time, _, _ = run_agentic_pipeline(chat, voice_input)
|
||||
return output_text, gen_time
|
||||
|
||||
@@ -0,0 +1,200 @@
|
||||
"""
|
||||
prompt.py
|
||||
---------
|
||||
Specialized system prompts for the LangGraph Multi-Agent Prescription Extractor.
|
||||
Includes prompts for Supervisor, Parallel Extractors (Medicine/Strength, Route,
|
||||
Duration/Frequency, Instructions), Aggregator, and Validator.
|
||||
"""
|
||||
|
||||
PLACEHOLDER = "{{VOICE_INPUT}}"
|
||||
FEEDBACK_PLACEHOLDER = "{{FEEDBACK}}"
|
||||
|
||||
# ===========================================================================
|
||||
# 1. SUPERVISOR AGENT PROMPT
|
||||
# ===========================================================================
|
||||
SUPERVISOR_PROMPT = """Role: Clinical Prescription Supervisor.
|
||||
Task: Analyze the doctor's prescription input and prepare targeted instructions for specialized extraction agents (Medicine & Strength, Route, Duration & Frequency, Instructions).
|
||||
Input:
|
||||
{{VOICE_INPUT}}
|
||||
|
||||
Optional Feedback from previous iteration:
|
||||
{{FEEDBACK}}
|
||||
|
||||
Rules:
|
||||
- Identify all distinct medicines mentioned (including companion drugs like "Drug A with Drug B").
|
||||
- Ensure no medicine or instruction clause is omitted.
|
||||
- Output ONLY the list of detected medicine identifiers and routing directives. No conversational filler."""
|
||||
|
||||
SYSTEM_PROMPT = SUPERVISOR_PROMPT
|
||||
|
||||
|
||||
# ===========================================================================
|
||||
# 2. MEDICINE & STRENGTH AGENT PROMPT
|
||||
# ===========================================================================
|
||||
MEDICINE_STRENGTH_PROMPT = """Role: Clinical Pharmacist Agent specializing in Medicine Identification and Dosage.
|
||||
Task: Extract exact medicine names and strengths from the prescription text.
|
||||
|
||||
Rules:
|
||||
1. Strip form words from Drug_name: tablet, tab, capsule, cap, rotacap, pill, syrup, gel, drops, spray, ointment, cream, sachet, lozenge.
|
||||
2. Single dose mention (e.g., "Aten 40mg", "Augmentin 625 mg") -> include dosage in Drug_name ("Aten 40 mg"), strength: NONE.
|
||||
3. Dual dose mentions (e.g., "Paracetamol 650 mg 20 mg") -> first dose in Drug_name ("Paracetamol 650 mg"), second dose in strength ("20 mg").
|
||||
4. Companion drugs ("Drug A with Drug B dose") -> output two separate medicine entries.
|
||||
5. If feedback is provided, correct the identified discrepancies immediately.
|
||||
6. NO extra explanation, NO commentary, NO notes.
|
||||
|
||||
Output Format Example:
|
||||
[
|
||||
{"medicine_id": 1, "drug_name": "Paracetamol 650 mg", "strength": "20 mg"}
|
||||
]
|
||||
|
||||
Prescription Input:
|
||||
{{VOICE_INPUT}}
|
||||
|
||||
Correction Feedback (if any):
|
||||
{{FEEDBACK}}"""
|
||||
|
||||
|
||||
# ===========================================================================
|
||||
# 3. ROUTE AGENT PROMPT
|
||||
# ===========================================================================
|
||||
ROUTE_PROMPT = """Role: Clinical Route of Administration Extractor.
|
||||
Task: Determine the exact anatomical route of administration for each medicine.
|
||||
|
||||
Decision Hierarchy (STRICT):
|
||||
1. DIRECT MENTION FIRST: If the doctor explicitly mentions the route (e.g., "orally", "topically", "inhale", "IV", "IM", "sublingual"), use that route ("oral", "topical", "inhalation", "intravenous", "intramuscular", "sublingual").
|
||||
2. SPECIFICITY RULES (if not directly mentioned):
|
||||
- tablet / cap / pill / syrup / suspension / solution / sachet / lozenge -> oral
|
||||
- rotacap / puff / respule / inhaler / turbuhaler -> inhalation
|
||||
- cream / gel / ointment / lotion / patch -> topical
|
||||
- eye drops / ear drops / drops -> ophthalmic / otic (or drops)
|
||||
- nasal spray / nasal drops -> nasal
|
||||
- suppository -> rectal
|
||||
3. IF NOT GIVEN AND CANNOT BE DETERMINED -> NONE.
|
||||
DO NOT GUESS. DO NOT INVENT. No thinking beyond the input.
|
||||
|
||||
Output Format Example:
|
||||
[
|
||||
{"medicine_id": 1, "drug_name": "Paracetamol 650 mg", "route": "oral"}
|
||||
]
|
||||
|
||||
Prescription Input:
|
||||
{{VOICE_INPUT}}
|
||||
|
||||
Correction Feedback (if any):
|
||||
{{FEEDBACK}}"""
|
||||
|
||||
|
||||
# ===========================================================================
|
||||
# 4. DURATION & FREQUENCY AGENT PROMPT
|
||||
# ===========================================================================
|
||||
DURATION_FREQUENCY_PROMPT = """Role: Clinical Dosage Schedule Extractor.
|
||||
Task: Extract the exact frequency and duration for each medicine.
|
||||
|
||||
Rules:
|
||||
1. FREQUENCY: Extract verbatim, preserving all parenthetical notations, abbreviations, and clinical timings:
|
||||
- Examples: "twice daily(1-0-1)", "once daily", "OD", "BD", "TID(1-1-1)", "QID(1-1-1-1)", "single dose", "as needed (SOS)", "at bedtime", "4 times a day".
|
||||
- If not mentioned -> NONE.
|
||||
2. DURATION: Extract exact duration phrase only:
|
||||
- Examples: "5 days", "7 days", "14 days", "1 month", "60 days", "day one".
|
||||
- If not mentioned -> NONE.
|
||||
3. Companion drugs ("Drug A with Drug B once daily for 60 days") -> both share the specified frequency and duration.
|
||||
4. Cross-Sentence Coreference Resolution:
|
||||
- If frequency or duration is given in a subsequent reference sentence (e.g., "It should be taken 4 times a day", "This medicine is to be taken twice daily"), attribute it to the referenced medicine.
|
||||
- If a group/plural reference is used (e.g., "Both should be taken twice daily", "All medicines are once daily for 10 days", "Take each of them three times a day"), apply the specified frequency/duration to all referenced medicines.
|
||||
5. NO conversational text, NO explanations.
|
||||
|
||||
Output Format Example:
|
||||
[
|
||||
{"medicine_id": 1, "drug_name": "Paracetamol 650 mg", "frequency": "twice daily(1-0-1)", "duration": "5 days"}
|
||||
]
|
||||
|
||||
Prescription Input:
|
||||
{{VOICE_INPUT}}
|
||||
|
||||
Correction Feedback (if any):
|
||||
{{FEEDBACK}}"""
|
||||
|
||||
|
||||
# ===========================================================================
|
||||
# 5. INSTRUCTION AGENT PROMPT
|
||||
# ===========================================================================
|
||||
INSTRUCTION_PROMPT = """Role: Clinical Patient Instruction Extractor.
|
||||
Task: Extract all primary administration instructions AND separate additional clinical/dietary/monitoring instructions from the prescription.
|
||||
|
||||
Rules:
|
||||
1. Extract verbatim from the input text without paraphrasing or summarizing.
|
||||
2. Primary instruction: specific meal timings, preparation methods, ingestion instructions (e.g., "before breakfast", "after meals", "dissolve in water", "rinse mouth after use").
|
||||
3. Additional instruction: clinical monitoring, reassessment, adverse effect warnings, titrations, and general diet/lifestyle advice (e.g., "seek reassessment if adverse effects develop", "discontinue once fever resolves", "if BP remains high consult doctor", "include green leafy vegetables in diet", "go for morning walks daily").
|
||||
4. Exclusion: Do NOT extract frequency/schedule coreference sentences (e.g., "It should be taken 4 times a day", "Both are once daily") into additional_instruction, as those belong strictly to the frequency column.
|
||||
5. If none -> NONE.
|
||||
6. STRICT PROHIBITION: Do NOT generate artificial cautions or warnings not literally spoken by the doctor.
|
||||
|
||||
Output Format Example:
|
||||
[
|
||||
{
|
||||
"medicine_id": 1,
|
||||
"drug_name": "PHEXIN DT 250 mg",
|
||||
"instruction": "1. before breakfast",
|
||||
"additional_instruction": "1. Seek reassessment if adverse effects develop"
|
||||
}
|
||||
]
|
||||
|
||||
Prescription Input:
|
||||
{{VOICE_INPUT}}
|
||||
|
||||
Correction Feedback (if any):
|
||||
{{FEEDBACK}}"""
|
||||
|
||||
|
||||
# ===========================================================================
|
||||
# 6. VALIDATOR AGENT PROMPT
|
||||
# ===========================================================================
|
||||
VALIDATOR_PROMPT = """Role: Senior Medical Quality Assurance Auditor.
|
||||
Task: Strictly validate extracted prescription blocks against the raw doctor prescription input for 100% groundedness and zero hallucinations.
|
||||
|
||||
Verification Checklist:
|
||||
1. Groundedness: Is every extracted medicine, strength, frequency, duration, route, instruction, and additional_instruction literally present in or directly derived from the input according to the specificity rules?
|
||||
2. Completeness: Were any medicines or instructions mentioned in the input missed?
|
||||
3. Zero Hallucinations: Did any agent inject unmentioned medicines, unsolicited cautions, or moralizing?
|
||||
4. Doctor Audience: Ensure no extraneous text or disclaimer is present.
|
||||
|
||||
If ALL checks pass:
|
||||
Output "VALID" with an empty feedback object.
|
||||
|
||||
If ANY check fails:
|
||||
Output "NEEDS_CORRECTION" along with specific, targeted corrective guidance mapped to each responsible agent ("medicine_agent", "route_agent", "duration_frequency_agent", "instruction_agent").
|
||||
|
||||
Output Format (strictly JSON):
|
||||
{
|
||||
"status": "VALID",
|
||||
"feedback": {
|
||||
"medicine_agent": "",
|
||||
"route_agent": "",
|
||||
"duration_frequency_agent": "",
|
||||
"instruction_agent": ""
|
||||
}
|
||||
}
|
||||
|
||||
Prescription Input:
|
||||
{{VOICE_INPUT}}
|
||||
|
||||
Extracted Prescription Blocks:
|
||||
{{EXTRACTED_BLOCKS}}"""
|
||||
|
||||
|
||||
# ===========================================================================
|
||||
# 7. FORMATTER / FINAL SYSTEM PROMPT
|
||||
# ===========================================================================
|
||||
FINAL_FORMATTER_PROMPT = """Format the validated prescription data into exact structured clinical blocks.
|
||||
Field names:
|
||||
Drug_name: <Drug Name>
|
||||
strength: <strength or NONE>
|
||||
frequency: <frequency or NONE>
|
||||
duration: <duration or NONE>
|
||||
route: <route or NONE>
|
||||
instruction: <instruction or NONE>
|
||||
additional_instruction: <additional_instruction or NONE>
|
||||
|
||||
Rules:
|
||||
- One block per medicine.
|
||||
- No explanations. No notes. No moralizing. No caution."""
|
||||
@@ -0,0 +1,42 @@
|
||||
# --- LangChain & LangGraph Multi-Agent Architecture ------------------------
|
||||
langchain>=0.2.0
|
||||
langchain-core>=0.2.0
|
||||
langgraph>=0.2.0
|
||||
langchain-community>=0.2.0
|
||||
|
||||
# --- FastAPI REST API Gateway & Microservices ------------------------------
|
||||
fastapi>=0.110.0
|
||||
uvicorn[standard]>=0.28.0
|
||||
pydantic>=2.0.0
|
||||
python-multipart>=0.0.9
|
||||
httpx>=0.27.0
|
||||
|
||||
# --- Local Offline LLM Inference Backend (GPT4All / GGUF) ------------------
|
||||
gpt4all>=2.7.0
|
||||
|
||||
# --- Local Vector Store & Embeddings Cache ---------------------------------
|
||||
faiss-cpu>=1.7.4
|
||||
|
||||
# --- Multi-Engine Speech-to-Text & Deep Learning (Whisper / Canary / Moonshine)
|
||||
torch>=2.0.0
|
||||
transformers>=4.40.0
|
||||
accelerate>=0.28.0
|
||||
safetensors>=0.4.0
|
||||
openai-whisper>=20231117
|
||||
soundfile>=0.12.1
|
||||
imageio-ffmpeg>=0.4.9
|
||||
scipy>=1.10.0
|
||||
numpy>=1.26.0
|
||||
tiktoken>=0.7.0
|
||||
huggingface-hub>=0.23.0
|
||||
|
||||
# --- Streamlit UI, DataFrames & Multi-Format Exporters ---------------------
|
||||
streamlit>=1.32.0
|
||||
pandas>=2.0.0
|
||||
openpyxl>=3.1.0
|
||||
requests>=2.31.0
|
||||
|
||||
# --- Utilities, Environment & Testing ---------------------------------------
|
||||
python-dotenv>=1.0.0
|
||||
typing-extensions>=4.8.0
|
||||
pytest>=8.0.0
|
||||
@@ -0,0 +1,450 @@
|
||||
"""
|
||||
test_langgraph_pipeline.py
|
||||
--------------------------
|
||||
Comprehensive, drift-proof verification suite for the LangGraph Multi-Agent Extractor.
|
||||
Tests:
|
||||
1. Multi-drug with companion drugs and lifestyle advice
|
||||
2. Dual-dose parsing (Drug name + strength split)
|
||||
3. Inhalation and topical route specificity
|
||||
4. Strict doctor mode (zero unsolicited moralizing or disclaimers)
|
||||
5. Validator feedback loop & 3-repetition cap
|
||||
6. Complex gastro prescription (5 medicines, suspensions, sachets, PRN)
|
||||
7. Multi-form prescription with intervals, titrations, and speaker timestamps
|
||||
8. Topicals, nasal sprays, ophthalmic drops, and interval schedules
|
||||
"""
|
||||
import sys
|
||||
import os
|
||||
|
||||
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
|
||||
|
||||
from graph_pipeline import run_graph_extraction
|
||||
from exporter import parse_output_fields
|
||||
|
||||
|
||||
def test_multi_drug_diet_instructions():
|
||||
print("\n--- Test 1: Multi-drug with Diet & Lifestyle Instructions ---")
|
||||
raw_prescription = (
|
||||
"Take Ferrous ascorbate with Folic acid once daily after lunch for 60 days, "
|
||||
"and take Vitamin C 500 mg alongside it to optimize iron absorption. "
|
||||
"Take Albendazole 400 mg single dose at bedtime on day one. "
|
||||
"Include dark green leafy vegetables in diet, avoid tea near meal times, "
|
||||
"re-test blood count in 2 months, and go for morning walks daily."
|
||||
)
|
||||
|
||||
output, gen_time, agent_logs, blocks = run_graph_extraction(None, raw_prescription)
|
||||
parsed = parse_output_fields(output, query=raw_prescription)
|
||||
assert len(parsed) >= 3, f"Expected at least 3 medicines, got {len(parsed)}"
|
||||
|
||||
all_instructions = " ".join([p.get("instruction", "") + " " + p.get("additional_instruction", "") for p in parsed]).lower()
|
||||
assert "leafy vegetables" in all_instructions or "green" in all_instructions, "Diet instruction missing!"
|
||||
assert "morning walk" in all_instructions or "tea" in all_instructions, "Lifestyle instruction missing!"
|
||||
print("PASS: Multi-drug & diet instructions successfully extracted and attributed.")
|
||||
|
||||
|
||||
def test_dual_dose_extraction():
|
||||
print("\n--- Test 2: Dual Dosage Extraction ---")
|
||||
raw_prescription = "Take one tablet of Paracetamol 650 mg 20 mg twice daily(1-0-1) for 5 days, increase the dose by 100 mg after 7 days."
|
||||
output, gen_time, agent_logs, blocks = run_graph_extraction(None, raw_prescription)
|
||||
parsed = parse_output_fields(output, query=raw_prescription)
|
||||
assert len(parsed) == 1, f"Expected 1 medicine, got {len(parsed)}"
|
||||
med = parsed[0]
|
||||
|
||||
assert "Paracetamol 650 mg" in med["Drug_name"], f"Unexpected Drug_name: {med['Drug_name']}"
|
||||
assert "20 mg" in med["strength"], f"Unexpected strength: {med['strength']}"
|
||||
assert "twice daily(1-0-1)" in med["frequency"], f"Unexpected frequency: {med['frequency']}"
|
||||
assert "5 days" in med["duration"], f"Unexpected duration: {med['duration']}"
|
||||
assert med["route"] == "oral", f"Unexpected route: {med['route']}"
|
||||
print("PASS: Dual dose and frequency notations successfully extracted.")
|
||||
|
||||
|
||||
def test_route_specificity():
|
||||
print("\n--- Test 3: Route Specificity Resolution ---")
|
||||
raw_prescription = "Inhale Budecort 200 mcg Rotacap twice daily for 10 days. Rinse mouth after using the inhaler."
|
||||
output, gen_time, agent_logs, blocks = run_graph_extraction(None, raw_prescription)
|
||||
parsed = parse_output_fields(output, query=raw_prescription)
|
||||
assert len(parsed) == 1
|
||||
assert parsed[0]["route"] == "inhalation", f"Expected route 'inhalation', got '{parsed[0]['route']}'"
|
||||
assert "rinse mouth" in parsed[0]["instruction"].lower(), "Device instruction missing"
|
||||
print("PASS: Inhalation route specificity and device instruction verified.")
|
||||
|
||||
|
||||
def test_no_moralizing_or_extra_cautions():
|
||||
print("\n--- Test 4: Strict Doctor Mode (No Extra Commentary) ---")
|
||||
raw_prescription = "Take Pantop 40 mg once daily before breakfast for 14 days."
|
||||
output, gen_time, agent_logs, blocks = run_graph_extraction(None, raw_prescription)
|
||||
|
||||
forbidden = ["please note", "caution:", "warning:", "moral", "consult your doctor", "disclaimer:"]
|
||||
for f in forbidden:
|
||||
assert f not in output.lower(), f"Forbidden commentary '{f}' detected in output!"
|
||||
print("PASS: Output is strictly clinical 6-field blocks with zero extra commentary.")
|
||||
|
||||
|
||||
def test_validator_loop_and_cap():
|
||||
print("\n--- Test 5: Validator Feedback Loop & Max 3 Repetition Cap ---")
|
||||
from graph_state import AgenticRxState
|
||||
from agents.validator_agent import validator_agent
|
||||
|
||||
state: AgenticRxState = {
|
||||
"input_text": "Take Aten 25 mg once daily for 10 days.",
|
||||
"iteration_count": 1,
|
||||
"aggregated_blocks": [
|
||||
{
|
||||
"Drug_name": "Aten 50 mg",
|
||||
"strength": "NONE",
|
||||
"frequency": "once daily",
|
||||
"duration": "10 days",
|
||||
"route": "oral",
|
||||
"instruction": "NONE",
|
||||
}
|
||||
],
|
||||
"agent_logs": [],
|
||||
}
|
||||
|
||||
val_out_1 = validator_agent(state)
|
||||
assert val_out_1["validation_status"] == "NEEDS_CORRECTION", "Expected NEEDS_CORRECTION on iteration 1"
|
||||
assert "medicine_agent" in val_out_1["validation_feedback"], "Expected feedback for medicine_agent"
|
||||
|
||||
state["iteration_count"] = 3
|
||||
val_out_3 = validator_agent(state)
|
||||
assert val_out_3["validation_status"] == "VALID", "Expected loop to be capped at iteration 3"
|
||||
print("PASS: Validator feedback generation and max 3-repetition cap successfully verified.")
|
||||
|
||||
|
||||
def test_complex_5_drug_prescription():
|
||||
print("\n--- Test 6: Complex 5-Medicine Multi-Form Prescription ---")
|
||||
raw_prescription = (
|
||||
"Take one Ofloxacin-Ornidazole tablet orally twice daily after meals for 5 days, "
|
||||
"and take one Racecadotril 100 mg capsule three times daily before food for 3 days. "
|
||||
"Take one Ondansetron 4 mg tablet up to three times daily as needed 30 minutes before meals for nausea, "
|
||||
"consume one vial of Enterogermina oral suspension twice daily for 5 days, "
|
||||
"and dissolve one sachet of Oral Rehydration Salts in one liter of clean drinking water to consume throughout the day. "
|
||||
"Stick to a bland diet consisting of rice, curd, and bananas, avoid spicy or oily foods, "
|
||||
"and visit the emergency room immediately if severe dehydration or persistent vomiting occurs."
|
||||
)
|
||||
|
||||
output, gen_time, agent_logs, blocks = run_graph_extraction(None, raw_prescription)
|
||||
parsed = parse_output_fields(output, query=raw_prescription)
|
||||
print(f"Extracted {len(parsed)} medicine blocks:")
|
||||
for idx, p in enumerate(parsed):
|
||||
print(f" {idx+1}. {p['Drug_name']} | {p['frequency']} | {p['duration']} | {p['route']} | {p['instruction']}")
|
||||
|
||||
assert len(parsed) == 5, f"Expected 5 medicines, got {len(parsed)}"
|
||||
drug_names = [p["Drug_name"].lower() for p in parsed]
|
||||
assert any("ofloxacin-ornidazole" in d for d in drug_names), "Ofloxacin-Ornidazole missing!"
|
||||
assert any("racecadotril" in d for d in drug_names), "Racecadotril missing!"
|
||||
assert any("ondansetron" in d for d in drug_names), "Ondansetron missing!"
|
||||
assert any("enterogermina" in d for d in drug_names), "Enterogermina missing!"
|
||||
assert any("oral rehydration salts" in d for d in drug_names), "Oral Rehydration Salts missing!"
|
||||
print("PASS: All 5 complex medicines and multi-clause instructions extracted successfully.")
|
||||
|
||||
|
||||
def test_multi_medicine_with_timestamps_and_conditionals():
|
||||
print("\n--- Test 7: Multi-Medicine with Conditionals & Voice Timestamps ---")
|
||||
raw_prescription = (
|
||||
"Administer ATEN tablet 50mg by mouth every morning before food for 10 days and seek reassessment of blood pressure afterwards. "
|
||||
"Take Crocin 650 mg every 6 hours for 3 days and discontinue once the fever resolves. "
|
||||
"Take Amlodipine 5 mg once daily for 14 days. If blood pressure remains high, consult your doctor before increasing the dose. "
|
||||
"Animesh Kumar, Yesterday 4:30 PM Take one tablet of paracetamol 650 mg 20 mg twice daily(1-0-1) for 5 day, increase the dose by 100 mg after 7 day."
|
||||
)
|
||||
|
||||
output, gen_time, agent_logs, blocks = run_graph_extraction(None, raw_prescription)
|
||||
parsed = parse_output_fields(output, query=raw_prescription)
|
||||
print(f"Extracted {len(parsed)} medicine blocks:")
|
||||
for idx, p in enumerate(parsed):
|
||||
print(f" {idx+1}. {p['Drug_name']} | {p['frequency']} | {p['duration']} | {p['route']} | {p['instruction']}")
|
||||
|
||||
assert len(parsed) == 4, f"Expected 4 medicines, got {len(parsed)}"
|
||||
assert "ATEN 50mg" in parsed[0]["Drug_name"], "ATEN 50mg drug name missing or malformed!"
|
||||
assert parsed[0]["frequency"] == "every morning", f"Expected 'every morning', got '{parsed[0]['frequency']}'"
|
||||
assert "Crocin 650 mg" in parsed[1]["Drug_name"], "Crocin 650 mg missing!"
|
||||
assert parsed[1]["frequency"] == "every 6 hours", f"Expected 'every 6 hours', got '{parsed[1]['frequency']}'"
|
||||
assert "Amlodipine 5 mg" in parsed[2]["Drug_name"], "Amlodipine 5 mg missing!"
|
||||
assert "paracetamol 650 mg" in parsed[3]["Drug_name"], "Paracetamol 650 mg missing!"
|
||||
assert parsed[3]["strength"] == "20 mg", f"Expected strength '20 mg', got '{parsed[3]['strength']}'"
|
||||
print("PASS: Multi-medicine with intervals, titrations, and speaker timestamps passed.")
|
||||
|
||||
|
||||
def test_topicals_sprays_drops():
|
||||
print("\n--- Test 8: Topicals, Nasal Sprays, & Ophthalmic Drops ---")
|
||||
raw_prescription = (
|
||||
"Apply Clotrimazole 1% cream topically twice daily for 14 days, "
|
||||
"spray Fluticasone 50 mcg nasal spray into both nostrils once daily every morning, "
|
||||
"and instill Moxifloxacin 0.5% eye drops into left eye every 4 hours for 7 days."
|
||||
)
|
||||
|
||||
output, gen_time, agent_logs, blocks = run_graph_extraction(None, raw_prescription)
|
||||
parsed = parse_output_fields(output, query=raw_prescription)
|
||||
print(f"Extracted {len(parsed)} medicine blocks:")
|
||||
for idx, p in enumerate(parsed):
|
||||
print(f" {idx+1}. {p['Drug_name']} | {p['frequency']} | {p['duration']} | {p['route']} | {p['instruction']}")
|
||||
|
||||
assert len(parsed) == 3
|
||||
assert parsed[0]["route"] == "topical", f"Expected route 'topical', got '{parsed[0]['route']}'"
|
||||
assert parsed[1]["route"] == "nasal", f"Expected route 'nasal', got '{parsed[1]['route']}'"
|
||||
assert parsed[2]["route"] == "ophthalmic", f"Expected route 'ophthalmic', got '{parsed[2]['route']}'"
|
||||
assert parsed[2]["frequency"] == "every 4 hours", f"Expected 'every 4 hours', got '{parsed[2]['frequency']}'"
|
||||
print("PASS: Topicals, sprays, and drops with specialized routes verified.")
|
||||
|
||||
|
||||
def test_cross_sentence_and_class_instructions():
|
||||
print("\n--- Test 9: Cross-Sentence, Cross-Drug, and Class Instruction Linkage ---")
|
||||
raw_prescription = (
|
||||
"Take Metformin 500 mg twice daily. Take Metformin strictly with meals to avoid stomach upset. "
|
||||
"Also take Glimepiride 1 mg once daily before breakfast. "
|
||||
"Start Amoxicillin 500 mg TID for 7 days, and take Paracetamol 650 mg as needed for fever. "
|
||||
"Do not stop the antibiotic course early even if fever subsides."
|
||||
)
|
||||
|
||||
output, gen_time, agent_logs, blocks = run_graph_extraction(None, raw_prescription)
|
||||
parsed = parse_output_fields(output, query=raw_prescription)
|
||||
print(f"Extracted {len(parsed)} medicine blocks:")
|
||||
for idx, p in enumerate(parsed):
|
||||
print(f" {idx+1}. {p['Drug_name']} | {p['frequency']} | {p['duration']} | {p['route']} | {p['instruction']}")
|
||||
|
||||
assert len(parsed) == 4, f"Expected 4 medicines, got {len(parsed)}"
|
||||
# Metformin should receive its separate sentence instruction
|
||||
assert "strictly with meals" in parsed[0]["instruction"].lower(), "Metformin missing its separate sentence instruction!"
|
||||
# Glimepiride should have its timing
|
||||
assert "before breakfast" in parsed[1]["instruction"].lower(), "Glimepiride missing breakfast instruction!"
|
||||
# Amoxicillin should receive antibiotic course completion in additional_instruction
|
||||
all_amox = (parsed[2].get("instruction", "") + " " + parsed[2].get("additional_instruction", "")).lower()
|
||||
assert "antibiotic course" in all_amox, "Amoxicillin missing antibiotic course directive!"
|
||||
# Paracetamol should NOT receive antibiotic instruction
|
||||
all_paracetamol = (parsed[3].get("instruction", "") + " " + parsed[3].get("additional_instruction", "")).lower()
|
||||
assert "antibiotic" not in all_paracetamol, "Antibiotic instruction leaked into Paracetamol!"
|
||||
print("PASS: Cross-sentence and class-specific instruction routing verified.")
|
||||
|
||||
|
||||
def test_additional_instructions_column():
|
||||
print("\n--- Test 10: Dedicated Additional Instructions Column ---")
|
||||
raw_prescription = "Administer PHEXIN DT tablet 250 mg once daily(0-0-1) before breakfast for 10 days. Seek reassessment if adverse effects develop."
|
||||
output, gen_time, agent_logs, blocks = run_graph_extraction(None, raw_prescription)
|
||||
parsed = parse_output_fields(output, query=raw_prescription)
|
||||
print(f"Extracted {len(parsed)} medicine block:")
|
||||
for p in parsed:
|
||||
print(f" Drug_name: {p['Drug_name']}")
|
||||
print(f" strength: {p['strength']}")
|
||||
print(f" frequency: {p['frequency']}")
|
||||
print(f" duration: {p['duration']}")
|
||||
print(f" route: {p['route']}")
|
||||
print(f" instruction: {p['instruction']}")
|
||||
print(f" additional_instruction: {p.get('additional_instruction', 'NONE')}")
|
||||
|
||||
assert len(parsed) == 1
|
||||
assert "PHEXIN DT 250 mg" in parsed[0]["Drug_name"]
|
||||
assert "once daily(0-0-1)" in parsed[0]["frequency"]
|
||||
assert "before breakfast" in parsed[0]["instruction"].lower()
|
||||
assert "adverse effects" in parsed[0]["additional_instruction"].lower()
|
||||
print("PASS: Primary instruction and secondary additional_instruction separated cleanly.")
|
||||
|
||||
|
||||
def test_natural_language_time_and_evaluation():
|
||||
print("\n--- Test 11: Natural Language Times-of-Day and Evaluation Sentence Parsing ---")
|
||||
raw_prescription = "Take Stugeron Forte by mouth twice daily Morning Night for 2 weeks. Return for evaluation after completing the course"
|
||||
output, gen_time, agent_logs, blocks = run_graph_extraction(None, raw_prescription)
|
||||
parsed = parse_output_fields(output, query=raw_prescription)
|
||||
print(f"Extracted {len(parsed)} medicine block:")
|
||||
for p in parsed:
|
||||
print(f" Drug_name: {p['Drug_name']}")
|
||||
print(f" strength: {p['strength']}")
|
||||
print(f" frequency: {p['frequency']}")
|
||||
print(f" duration: {p['duration']}")
|
||||
print(f" route: {p['route']}")
|
||||
print(f" instruction: {p['instruction']}")
|
||||
print(f" additional_instruction: {p.get('additional_instruction', 'NONE')}")
|
||||
|
||||
assert len(parsed) == 1
|
||||
assert "Stugeron Forte" in parsed[0]["Drug_name"]
|
||||
assert "twice daily" in parsed[0]["frequency"]
|
||||
assert "2 weeks" in parsed[0]["duration"]
|
||||
assert "oral" in parsed[0]["route"]
|
||||
assert "morning night" in parsed[0]["instruction"].lower()
|
||||
assert "return for evaluation" in parsed[0]["additional_instruction"].lower()
|
||||
print("PASS: Natural language times-of-day and evaluation sentence captured dynamically.")
|
||||
|
||||
|
||||
def test_punctuation_free_continuous_voice_speech():
|
||||
print("\n--- Test 12: Continuous Unpunctuated Voice Speech Extraction ---")
|
||||
raw_prescription = "Take this print 500mg 20mg tablets after breakfast if headache does not go away Meet the doctor also take walks after dinner and it will reduce your headaches Please see me after 7 days"
|
||||
output, gen_time, agent_logs, blocks = run_graph_extraction(None, raw_prescription)
|
||||
parsed = parse_output_fields(output, query=raw_prescription)
|
||||
print(f"Extracted {len(parsed)} medicine block:")
|
||||
for p in parsed:
|
||||
print(f" Drug_name: {p['Drug_name']}")
|
||||
print(f" strength: {p['strength']}")
|
||||
print(f" frequency: {p['frequency']}")
|
||||
print(f" duration: {p['duration']}")
|
||||
print(f" route: {p['route']}")
|
||||
print(f" instruction: {p['instruction']}")
|
||||
print(f" additional_instruction: {p.get('additional_instruction', 'NONE')}")
|
||||
|
||||
assert len(parsed) == 1
|
||||
assert "this print 500mg" in parsed[0]["Drug_name"]
|
||||
assert "20mg" in parsed[0]["strength"]
|
||||
assert "oral" in parsed[0]["route"]
|
||||
assert "after breakfast" in parsed[0]["instruction"].lower()
|
||||
assert "after dinner" not in parsed[0]["instruction"].lower()
|
||||
assert "doctor" in parsed[0]["additional_instruction"].lower()
|
||||
assert "walks" in parsed[0]["additional_instruction"].lower()
|
||||
print("PASS: Unpunctuated continuous voice speech and walking advice cleanly decoupled.")
|
||||
|
||||
|
||||
def test_complex_multidrug_decimal_and_advice_guards():
|
||||
print("\n--- Test 13: Complex Multi-Drug Decimal Preservation & Non-Drug Guards ---")
|
||||
raw_prescription = (
|
||||
"Take Wallach Clover 1000 MCG Tablets, Overly 3 times Daily for 7 days and take 1 pre-gab ball in 75 MG capsule. "
|
||||
"Once daily at bedtime for 14 days, take 1 parasitamol 500 MG with Phradamol 37.5 MG tablet twice daily after meals for severe pain for 5 days. "
|
||||
"Apply Kalamine lotion gently over the close rash areas 3 times daily and take 1 methello glogamine 150,000 MG tablet daily after lunch for 30 days "
|
||||
"keep the blistered area clean and dry avoid close physical contact with pregnant individuals or non-immune persons and return if the rash involves the eye region."
|
||||
)
|
||||
output, gen_time, agent_logs, blocks = run_graph_extraction(None, raw_prescription)
|
||||
parsed = parse_output_fields(output, query=raw_prescription)
|
||||
print(f"Extracted {len(parsed)} medicine blocks:")
|
||||
for i, p in enumerate(parsed):
|
||||
print(f" {i+1}. {p['Drug_name']} | {p['frequency']} | {p['duration']} | {p['route']} | {p['instruction']}")
|
||||
|
||||
assert len(parsed) == 6
|
||||
assert any("37.5" in p["Drug_name"] for p in parsed), "Decimal 37.5 MG was truncated!"
|
||||
assert not any("pregnant" in p["Drug_name"].lower() for p in parsed), "Non-drug advice misclassified as medication!"
|
||||
assert "clean and dry" in parsed[-1]["additional_instruction"].lower()
|
||||
print("PASS: Decimals preserved, phonetic routes normalized, and non-drug advice guarded.")
|
||||
|
||||
|
||||
def test_noisy_transcript_and_conversational_chatter_filtering():
|
||||
print("\n--- Test 14: Noisy Transcript & Conversational Chatter Filtering ---")
|
||||
raw_prescription = (
|
||||
"Good morning doctor. Hello Mr. Sharma, how are you feeling today? "
|
||||
"I have severe fever and throat pain since yesterday. Let me check your vitals. "
|
||||
"Temperature is 101 F, BP is 130/80 mmHg, chest is clear. "
|
||||
"Take Augmentin 625mg twice daily for 5 days and take Paracetamol 650mg SOS for fever. "
|
||||
"Gargle with warm salt water thrice daily and drink plenty of fluids. "
|
||||
"Thank you doctor, I will take care. Have a great day."
|
||||
)
|
||||
output, gen_time, agent_logs, blocks = run_graph_extraction(None, raw_prescription)
|
||||
parsed = parse_output_fields(output, query=raw_prescription)
|
||||
print(f"Extracted {len(parsed)} medicine blocks:")
|
||||
for i, p in enumerate(parsed):
|
||||
print(f" {i+1}. {p['Drug_name']} | {p['frequency']} | {p['duration']} | {p['route']} | {p['instruction']}")
|
||||
|
||||
assert len(parsed) == 2
|
||||
assert "Augmentin 625mg" in parsed[0]["Drug_name"]
|
||||
assert "Paracetamol 650mg" in parsed[1]["Drug_name"]
|
||||
for p in parsed:
|
||||
assert not any(noise in p["Drug_name"].lower() for noise in ("good morning", "sharma", "fever", "vitals", "130/80", "thank you", "great day"))
|
||||
assert "gargle" in parsed[-1]["additional_instruction"].lower()
|
||||
def test_single_med_hydration_and_visit_doctor_advice():
|
||||
print("\n--- Test 15: Single Medicine with Hydration & Doctor Visit Advice ---")
|
||||
raw_prescription = "Take Disprin 500 mg tablets. If the fever does not go away, come visit the doctor. Take regular water."
|
||||
output, gen_time, agent_logs, blocks = run_graph_extraction(None, raw_prescription)
|
||||
parsed = parse_output_fields(output, query=raw_prescription)
|
||||
print(f"Extracted {len(parsed)} medicine blocks:")
|
||||
for i, p in enumerate(parsed):
|
||||
print(f" {i+1}. {p['Drug_name']} | {p['route']} | {p['instruction']} | {p['additional_instruction']}")
|
||||
|
||||
assert len(parsed) == 1
|
||||
assert "Disprin 500 mg" in parsed[0]["Drug_name"]
|
||||
assert "oral" in parsed[0]["route"]
|
||||
assert "visit the doctor" in parsed[0]["additional_instruction"].lower()
|
||||
assert "regular water" in parsed[0]["additional_instruction"].lower()
|
||||
print("PASS: Single medicine with hydration and doctor visit advice verified.")
|
||||
|
||||
|
||||
def test_cross_sentence_coreference_frequency_resolution():
|
||||
print("\n--- Test 16: Cross-Sentence Coreference Frequency Resolution ---")
|
||||
# 1. Singular coreference ("It should be taken 4 times a day")
|
||||
raw_prescription_1 = "Take parasitamol 500 mg for 3 days. If the fever does not go away, come visit the doctor. It should be taken 4 times a day."
|
||||
output_1, _, _, _ = run_graph_extraction(None, raw_prescription_1)
|
||||
parsed_1 = parse_output_fields(output_1, query=raw_prescription_1)
|
||||
assert len(parsed_1) == 1
|
||||
assert "parasitamol 500 mg" in parsed_1[0]["Drug_name"]
|
||||
assert "4 times a day" in parsed_1[0]["frequency"].lower()
|
||||
assert "4 times a day" not in parsed_1[0]["additional_instruction"].lower()
|
||||
assert "visit the doctor" in parsed_1[0]["additional_instruction"].lower()
|
||||
|
||||
# 2. Plural coreference ("Both should be taken twice daily after meals")
|
||||
raw_prescription_2 = "Take Pan 40 mg and Paracetamol 650 mg for 5 days. Both should be taken twice daily after meals. Drink plenty of water."
|
||||
output_2, _, _, _ = run_graph_extraction(None, raw_prescription_2)
|
||||
parsed_2 = parse_output_fields(output_2, query=raw_prescription_2)
|
||||
assert len(parsed_2) == 2
|
||||
assert "twice daily" in parsed_2[0]["frequency"].lower()
|
||||
assert "twice daily" in parsed_2[1]["frequency"].lower()
|
||||
assert "after meals" in parsed_2[0]["instruction"].lower()
|
||||
assert "after meals" in parsed_2[1]["instruction"].lower()
|
||||
print("PASS: Singular and plural cross-sentence coreference frequencies verified.")
|
||||
|
||||
|
||||
def test_dosage_titration_instruction_capture():
|
||||
print("\n--- Test 17: Dosage Titration Instruction Capture ---")
|
||||
# 1. Unpunctuated speech with conditional titration
|
||||
raw_1 = "Take parasitamol teplis 500 mg for 3 days if the fever does not go away increase the dosage by 100 mg"
|
||||
output_1, _, _, _ = run_graph_extraction(None, raw_1)
|
||||
parsed_1 = parse_output_fields(output_1, query=raw_1)
|
||||
assert len(parsed_1) == 1
|
||||
assert "parasitamol" in parsed_1[0]["Drug_name"].lower()
|
||||
assert "increase the dosage by 100 mg" in parsed_1[0]["additional_instruction"].lower()
|
||||
assert "if the fever does not go away" in parsed_1[0]["additional_instruction"].lower()
|
||||
|
||||
# 2. Punctuated speech with leading titration clause
|
||||
raw_2 = "Take parasitamol tablets 500 mg for 3 days, increase the dosage by 100 mg if the fever does not go away."
|
||||
output_2, _, _, _ = run_graph_extraction(None, raw_2)
|
||||
parsed_2 = parse_output_fields(output_2, query=raw_2)
|
||||
assert len(parsed_2) == 1
|
||||
assert "increase the dosage by 100 mg" in parsed_2[0]["additional_instruction"].lower()
|
||||
print("PASS: Dosage titration instructions cleanly captured without truncation.")
|
||||
|
||||
|
||||
def test_faulty_grammar_duration_and_comma_titration():
|
||||
print("\n--- Test 18: Faulty Grammar Duration & Comma Titration ---")
|
||||
raw = "Take parasita mode, tablets 500 mg, 3 times a day, till 7 days, if the fever does not go away, increase the dosage by 20 mgs."
|
||||
output, _, _, _ = run_graph_extraction(None, raw)
|
||||
parsed = parse_output_fields(output, query=raw)
|
||||
assert len(parsed) == 1
|
||||
assert "parasita mode 500 mg" in parsed[0]["Drug_name"]
|
||||
assert "3 times a day" in parsed[0]["frequency"].lower()
|
||||
assert "7 days" in parsed[0]["duration"].lower()
|
||||
assert "oral" in parsed[0]["route"].lower()
|
||||
assert "if the fever does not go away, increase the dosage by 20 mgs" in parsed[0]["additional_instruction"].lower()
|
||||
print("PASS: Faulty grammar duration and unified comma titration instruction verified.")
|
||||
|
||||
|
||||
def test_complex_multidrug_with_nasal_irrigations_and_precautions():
|
||||
print("\n--- Test 19: Complex Multi-Drug with Nasal Irrigations & Precautions ---")
|
||||
raw = (
|
||||
"Take one Cefpodoxime proxetil 200 mg tablet orally twice daily after meals for 7 days, and take one Levocetirizine 5 mg with Montelukast 10 mg tablet once daily at bedtime for 10 days. "
|
||||
"Take one Paracetamol 650 mg tablet up to three times daily after food for pain or fever, take one Pantoprazole 40 mg tablet once daily before breakfast for 7 days, and administer two sprays of Oxymetazoline 0.05% nasal spray into each nostril twice daily for a strict maximum of 3 days. "
|
||||
"Use saline nasal irrigations twice daily, perform steam inhalation, and seek reassessment if eye swelling or severe headaches develop."
|
||||
)
|
||||
output, _, _, _ = run_graph_extraction(None, raw)
|
||||
parsed = parse_output_fields(output, query=raw)
|
||||
assert len(parsed) == 6
|
||||
assert "Oxymetazoline 0.05%" in parsed[-1]["Drug_name"]
|
||||
assert "nasal" in parsed[-1]["route"]
|
||||
assert "into each nostril" in parsed[-1]["instruction"].lower()
|
||||
assert "saline nasal irrigations" in parsed[-1]["additional_instruction"].lower()
|
||||
assert "strict maximum of 3 days" in parsed[-1]["additional_instruction"].lower()
|
||||
print("PASS: Multi-drug with nasal irrigations and precautions cleanly extracted.")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
test_multi_drug_diet_instructions()
|
||||
test_dual_dose_extraction()
|
||||
test_route_specificity()
|
||||
test_no_moralizing_or_extra_cautions()
|
||||
test_validator_loop_and_cap()
|
||||
test_complex_5_drug_prescription()
|
||||
test_multi_medicine_with_timestamps_and_conditionals()
|
||||
test_topicals_sprays_drops()
|
||||
test_cross_sentence_and_class_instructions()
|
||||
test_additional_instructions_column()
|
||||
test_natural_language_time_and_evaluation()
|
||||
test_punctuation_free_continuous_voice_speech()
|
||||
test_complex_multidrug_decimal_and_advice_guards()
|
||||
test_noisy_transcript_and_conversational_chatter_filtering()
|
||||
test_single_med_hydration_and_visit_doctor_advice()
|
||||
test_cross_sentence_coreference_frequency_resolution()
|
||||
test_dosage_titration_instruction_capture()
|
||||
test_faulty_grammar_duration_and_comma_titration()
|
||||
test_complex_multidrug_with_nasal_irrigations_and_precautions()
|
||||
print("\n========================================================")
|
||||
print("ALL 19 LANGGRAPH DRIFT-PROOF MULTI-AGENT TESTS PASSED!")
|
||||
print("========================================================")
|
||||
@@ -0,0 +1,211 @@
|
||||
"""
|
||||
transcriber.py
|
||||
--------------
|
||||
Latency-Optimized Multi-Model Speech-to-Text Transcriber Module.
|
||||
|
||||
Key Performance Enhancements for Whisper_Ayush & Whisper Large Turbo:
|
||||
1. Multi-Core CPU Thread Parallelization (sets torch.set_num_threads to all logical cores).
|
||||
2. Scaled Dot-Product Attention (SDPA) integration.
|
||||
3. Fast Greedy Decoding (num_beams=1, use_cache=True) for 3-4x latency reduction.
|
||||
4. Direct In-Memory Audio Buffer Processing to eliminate disk I/O latency.
|
||||
5. Cached Resource Loading with Streamlit (@st.cache_resource).
|
||||
"""
|
||||
import os
|
||||
import io
|
||||
import shutil
|
||||
import tempfile
|
||||
import streamlit as st
|
||||
import config
|
||||
|
||||
# Auto-configure CPU threading for low-latency inference
|
||||
try:
|
||||
import torch
|
||||
if not torch.cuda.is_available():
|
||||
threads = os.cpu_count() or 8
|
||||
torch.set_num_threads(threads)
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
# Auto-configure bundled ffmpeg binary from imageio_ffmpeg for Windows compatibility
|
||||
try:
|
||||
import imageio_ffmpeg
|
||||
ffmpeg_exe = imageio_ffmpeg.get_ffmpeg_exe()
|
||||
ffmpeg_dir = os.path.dirname(ffmpeg_exe)
|
||||
target_ffmpeg = os.path.join(ffmpeg_dir, "ffmpeg.exe")
|
||||
if not os.path.exists(target_ffmpeg):
|
||||
try:
|
||||
shutil.copy2(ffmpeg_exe, target_ffmpeg)
|
||||
except Exception:
|
||||
pass
|
||||
if ffmpeg_dir not in os.environ.get("PATH", ""):
|
||||
os.environ["PATH"] = ffmpeg_dir + os.path.pathsep + os.environ.get("PATH", "")
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
|
||||
@st.cache_resource(show_spinner="Loading and optimizing Whisper_Ayush model weights...")
|
||||
def get_stt_pipeline(model_key: str = "whisper_ayush"):
|
||||
"""
|
||||
Loads, optimizes, and caches the selected Speech-to-Text model pipeline.
|
||||
"""
|
||||
ayush_path = getattr(config, "AYUSH_WHISPER_PATH", "")
|
||||
|
||||
# 1. Ayush's Fine-Tuned Whisper Model (High-Speed Turbo)
|
||||
if model_key == "whisper_ayush":
|
||||
try:
|
||||
from transformers import AutoProcessor, AutoModelForSpeechSeq2Seq, pipeline
|
||||
import torch
|
||||
|
||||
device = "cuda:0" if torch.cuda.is_available() else "cpu"
|
||||
torch_dtype = torch.float16 if torch.cuda.is_available() else torch.float32
|
||||
|
||||
# Use local processor configs from Ayush's fine-tuned model directory
|
||||
processor = AutoProcessor.from_pretrained(ayush_path if os.path.exists(ayush_path) else "openai/whisper-large-v3-turbo")
|
||||
|
||||
if os.path.exists(os.path.join(ayush_path, "model.safetensors")) or os.path.exists(os.path.join(ayush_path, "pytorch_model.bin")):
|
||||
model_source = ayush_path
|
||||
else:
|
||||
model_source = "openai/whisper-large-v3-turbo"
|
||||
|
||||
model = AutoModelForSpeechSeq2Seq.from_pretrained(
|
||||
model_source,
|
||||
dtype=torch_dtype,
|
||||
attn_implementation="sdpa" if hasattr(torch.nn.functional, "scaled_dot_product_attention") else "eager",
|
||||
low_cpu_mem_usage=True,
|
||||
)
|
||||
if device != "cpu":
|
||||
model.to(device)
|
||||
|
||||
pipe = pipeline(
|
||||
"automatic-speech-recognition",
|
||||
model=model,
|
||||
tokenizer=processor.tokenizer,
|
||||
feature_extractor=processor.feature_extractor,
|
||||
dtype=torch_dtype,
|
||||
device=device,
|
||||
)
|
||||
return {"engine": "transformers_ayush", "pipeline": pipe, "name": "Whisper Ayush (Fast Turbo)"}
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
# 2. OpenAI Whisper Large v3 Turbo
|
||||
elif model_key == "whisper_large_turbo":
|
||||
try:
|
||||
from transformers import pipeline
|
||||
import torch
|
||||
|
||||
device = "cuda:0" if torch.cuda.is_available() else "cpu"
|
||||
torch_dtype = torch.float16 if torch.cuda.is_available() else torch.float32
|
||||
pipe = pipeline(
|
||||
"automatic-speech-recognition",
|
||||
model="openai/whisper-large-v3-turbo",
|
||||
dtype=torch_dtype,
|
||||
device=device,
|
||||
model_kwargs={"attn_implementation": "sdpa", "low_cpu_mem_usage": True},
|
||||
)
|
||||
return {"engine": "transformers_pipeline", "pipeline": pipe, "name": "Whisper Large v3 Turbo"}
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
# 3. Useful Sensors Moonshine Base & Tiny (Edge Optimized)
|
||||
elif model_key in ("moonshine_base", "moonshine_tiny"):
|
||||
hf_model_id = "usefulsensors/moonshine-base" if model_key == "moonshine_base" else "usefulsensors/moonshine-tiny"
|
||||
try:
|
||||
from transformers import pipeline
|
||||
import torch
|
||||
|
||||
device = "cuda:0" if torch.cuda.is_available() else "cpu"
|
||||
torch_dtype = torch.float16 if torch.cuda.is_available() else torch.float32
|
||||
pipe = pipeline("automatic-speech-recognition", model=hf_model_id, trust_remote_code=True, dtype=torch_dtype, device=device)
|
||||
return {"engine": "transformers_pipeline", "pipeline": pipe, "name": f"Moonshine ({model_key})"}
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
# 4. NVIDIA Parakeet TDT 1.1B & Canary 1B
|
||||
elif model_key in ("parakeet_tdt", "canary_1b"):
|
||||
hf_model_id = "nvidia/parakeet-tdt-1.1b" if model_key == "parakeet_tdt" else "nvidia/canary-1b"
|
||||
try:
|
||||
from transformers import pipeline
|
||||
import torch
|
||||
|
||||
device = "cuda:0" if torch.cuda.is_available() else "cpu"
|
||||
torch_dtype = torch.float16 if torch.cuda.is_available() else torch.float32
|
||||
pipe = pipeline("automatic-speech-recognition", model=hf_model_id, trust_remote_code=True, dtype=torch_dtype, device=device)
|
||||
return {"engine": "transformers_pipeline", "pipeline": pipe, "name": f"NVIDIA ({model_key})"}
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
# 5. Local OpenAI Whisper (Base / Tiny) Fast Offline Fallback
|
||||
whisper_size = "tiny" if "tiny" in model_key else "base"
|
||||
try:
|
||||
import whisper
|
||||
whisper_model = whisper.load_model(whisper_size)
|
||||
return {"engine": "whisper_standard", "model": whisper_model, "name": f"OpenAI Whisper ({whisper_size})"}
|
||||
except Exception as e:
|
||||
return {"engine": "error", "error": str(e), "name": "Error"}
|
||||
|
||||
|
||||
def transcribe_audio(audio_data, model_key: str = None) -> str:
|
||||
"""
|
||||
Transcribes audio bytes or file buffer to text string with optimized low latency.
|
||||
"""
|
||||
if audio_data is None:
|
||||
return ""
|
||||
|
||||
target_key = model_key or getattr(config, "WHISPER_MODEL", "whisper_ayush")
|
||||
stt_engine = get_stt_pipeline(target_key)
|
||||
|
||||
suffix = ".wav"
|
||||
if hasattr(audio_data, "name") and audio_data.name:
|
||||
ext = os.path.splitext(audio_data.name)[1]
|
||||
if ext:
|
||||
suffix = ext
|
||||
elif hasattr(audio_data, "type") and audio_data.type:
|
||||
if "mp3" in audio_data.type:
|
||||
suffix = ".mp3"
|
||||
elif "ogg" in audio_data.type:
|
||||
suffix = ".ogg"
|
||||
elif "m4a" in audio_data.type:
|
||||
suffix = ".m4a"
|
||||
|
||||
with tempfile.NamedTemporaryFile(delete=False, suffix=suffix) as tmp_file:
|
||||
if isinstance(audio_data, bytes):
|
||||
tmp_file.write(audio_data)
|
||||
elif hasattr(audio_data, "read"):
|
||||
tmp_file.write(audio_data.read())
|
||||
if hasattr(audio_buffer, "seek"):
|
||||
audio_data.seek(0)
|
||||
else:
|
||||
tmp_file.write(bytes(audio_data))
|
||||
tmp_path = tmp_file.name
|
||||
|
||||
try:
|
||||
engine_type = stt_engine.get("engine", "")
|
||||
if "transformers" in engine_type:
|
||||
pipe = stt_engine["pipeline"]
|
||||
# Ultra-low latency generation parameters: Greedy decoding (num_beams=1) + KV caching
|
||||
gen_kwargs = {
|
||||
"language": "english",
|
||||
"task": "transcribe",
|
||||
"num_beams": 1,
|
||||
"use_cache": True,
|
||||
}
|
||||
try:
|
||||
import torch
|
||||
with torch.inference_mode():
|
||||
result = pipe(tmp_path, generate_kwargs=gen_kwargs)
|
||||
except Exception:
|
||||
result = pipe(tmp_path)
|
||||
return result.get("text", "").strip()
|
||||
elif engine_type == "whisper_standard":
|
||||
model = stt_engine["model"]
|
||||
result = model.transcribe(tmp_path, fp16=False, beam_size=1, best_of=1)
|
||||
return result.get("text", "").strip()
|
||||
else:
|
||||
raise RuntimeError(stt_engine.get("error", "Failed to initialize STT model engine."))
|
||||
finally:
|
||||
if os.path.exists(tmp_path):
|
||||
try:
|
||||
os.remove(tmp_path)
|
||||
except Exception:
|
||||
pass
|
||||
@@ -0,0 +1,100 @@
|
||||
"""
|
||||
vectorstore.py
|
||||
--------------
|
||||
FAISS-backed storage/retrieval of the system prompt with graceful fallback.
|
||||
|
||||
Design:
|
||||
- System prompt is embedded/indexed once.
|
||||
- Stored index is reused on subsequent queries.
|
||||
- If FAISS or GPT4AllEmbeddings is not yet configured, provides a reliable
|
||||
in-memory prompt store so the app never crashes.
|
||||
"""
|
||||
import os
|
||||
from typing import Any, Optional
|
||||
|
||||
import config
|
||||
from prompt import SYSTEM_PROMPT
|
||||
|
||||
_embeddings = None
|
||||
|
||||
|
||||
def get_embeddings() -> Any:
|
||||
global _embeddings
|
||||
if _embeddings is None:
|
||||
try:
|
||||
from langchain_community.embeddings import GPT4AllEmbeddings
|
||||
_embeddings = GPT4AllEmbeddings(model_name=config.EMBEDDINGS_MODEL)
|
||||
except Exception:
|
||||
# Fallback simple embedding object if GPT4AllEmbeddings cannot be loaded
|
||||
class SimplePromptEmbedding:
|
||||
def embed_query(self, text: str):
|
||||
return [0.0] * 384
|
||||
def embed_documents(self, texts):
|
||||
return [[0.0] * 384 for _ in texts]
|
||||
_embeddings = SimplePromptEmbedding()
|
||||
return _embeddings
|
||||
|
||||
|
||||
def _index_exists() -> bool:
|
||||
return os.path.exists(os.path.join(config.FAISS_DIR, "index.faiss"))
|
||||
|
||||
|
||||
def load_or_create_index() -> Any:
|
||||
"""Embed + store the system prompt exactly once; load it on every call after that."""
|
||||
try:
|
||||
from langchain_community.vectorstores import FAISS
|
||||
from langchain_core.documents import Document
|
||||
|
||||
embeddings = get_embeddings()
|
||||
|
||||
if _index_exists():
|
||||
return FAISS.load_local(
|
||||
config.FAISS_DIR, embeddings, allow_dangerous_deserialization=True
|
||||
)
|
||||
|
||||
doc = Document(page_content=SYSTEM_PROMPT, metadata={"type": "system_prompt"})
|
||||
store = FAISS.from_documents([doc], embeddings)
|
||||
store.save_local(config.FAISS_DIR)
|
||||
return store
|
||||
except Exception:
|
||||
# Graceful fallback: return system prompt wrapper
|
||||
class InMemPromptStore:
|
||||
def __init__(self, content: str):
|
||||
self.content = content
|
||||
def similarity_search(self, *args, **kwargs):
|
||||
from langchain_core.documents import Document
|
||||
return [Document(page_content=self.content)]
|
||||
return InMemPromptStore(SYSTEM_PROMPT)
|
||||
|
||||
|
||||
def retrieve_system_prompt(store: Any) -> str:
|
||||
"""Pull the stored system prompt back out of FAISS (top-1 retrieval)."""
|
||||
if store is None:
|
||||
return SYSTEM_PROMPT
|
||||
|
||||
if hasattr(store, "content"):
|
||||
return store.content
|
||||
|
||||
# 1. Fast direct docstore lookup if index mapping is present
|
||||
if hasattr(store, "index_to_docstore_id") and store.index_to_docstore_id:
|
||||
doc_id = store.index_to_docstore_id.get(0)
|
||||
if doc_id is not None and hasattr(store, "docstore"):
|
||||
doc = store.docstore.search(doc_id)
|
||||
if hasattr(doc, "page_content") and doc.page_content:
|
||||
return doc.page_content
|
||||
|
||||
# 2. Fast lookup via docstore values dict if present
|
||||
if hasattr(store, "docstore") and hasattr(store.docstore, "_dict") and store.docstore._dict:
|
||||
doc = next(iter(store.docstore._dict.values()))
|
||||
if hasattr(doc, "page_content") and doc.page_content:
|
||||
return doc.page_content
|
||||
|
||||
# 3. Fallback similarity search
|
||||
try:
|
||||
results = store.similarity_search("expert doctor assistant extraction format", k=1)
|
||||
if results and results[0].page_content:
|
||||
return results[0].page_content
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
return SYSTEM_PROMPT
|
||||
Reference in New Issue
Block a user