Spaces:
Sleeping
Sleeping
Upload 12 files
Browse files- api/__init__.py +0 -0
- api/agent.py +367 -0
- api/auth.py +164 -0
- api/database.py +531 -0
- api/email_utils.py +139 -0
- api/main.py +1534 -0
- api/memory.py +92 -0
- api/rag.py +232 -0
- frontend/admin.html +534 -0
- frontend/chat.html +988 -0
- frontend/index.html +573 -0
- scripts/setup_and_run.py +63 -0
api/__init__.py
ADDED
|
File without changes
|
api/agent.py
ADDED
|
@@ -0,0 +1,367 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
AxonIQ Agentic AI β Direct Architecture (no tool-calling)
|
| 3 |
+
=============================================================
|
| 4 |
+
Architecture:
|
| 5 |
+
Every user message with symptom content is ALWAYS classified by Python directly.
|
| 6 |
+
The LLM NEVER calls tools β it only generates clinical prose.
|
| 7 |
+
|
| 8 |
+
Flow:
|
| 9 |
+
1. Greeting check β fast-path response (no LLM)
|
| 10 |
+
2. Python runs classifier + RAG directly
|
| 11 |
+
3. Results injected into LLM prompt as structured context
|
| 12 |
+
4. LLM generates ONLY the clinical conversation response
|
| 13 |
+
5. Response returned β guaranteed no JSON ever
|
| 14 |
+
"""
|
| 15 |
+
from __future__ import annotations
|
| 16 |
+
|
| 17 |
+
import json
|
| 18 |
+
import os
|
| 19 |
+
import re
|
| 20 |
+
from typing import Any, Dict, List
|
| 21 |
+
from loguru import logger
|
| 22 |
+
|
| 23 |
+
from langchain_ollama import ChatOllama
|
| 24 |
+
from langchain_huggingface import HuggingFaceEndpoint, ChatHuggingFace
|
| 25 |
+
from langchain_core.messages import HumanMessage as HM, AIMessage as AM, SystemMessage
|
| 26 |
+
|
| 27 |
+
# ββ LLM Setup βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 28 |
+
_HF_TOKEN = os.environ.get("HF_TOKEN", "")
|
| 29 |
+
_USE_HF = bool(_HF_TOKEN) and _HF_TOKEN not in ("", "none", "local")
|
| 30 |
+
LLM_MODEL = os.environ.get("HF_MODEL", "mistralai/Mistral-7B-Instruct-v0.3")
|
| 31 |
+
|
| 32 |
+
if _USE_HF:
|
| 33 |
+
logger.info("[AxonIQ] Using HuggingFace Inference API ({})", LLM_MODEL)
|
| 34 |
+
_hf_endpoint = HuggingFaceEndpoint(
|
| 35 |
+
repo_id=LLM_MODEL,
|
| 36 |
+
huggingfacehub_api_token=_HF_TOKEN,
|
| 37 |
+
temperature=0.1,
|
| 38 |
+
max_new_tokens=1024,
|
| 39 |
+
)
|
| 40 |
+
llm = ChatHuggingFace(llm=_hf_endpoint)
|
| 41 |
+
else:
|
| 42 |
+
logger.info("[AxonIQ] Using local Ollama (llama3.1:8b)")
|
| 43 |
+
llm = ChatOllama(model="llama3.1:8b", temperature=0.1, num_predict=1024)
|
| 44 |
+
|
| 45 |
+
# ββ System Prompt βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 46 |
+
SYSTEM_PROMPT = """You are AxonIQ, a clinical decision support AI specialising in Multiple Sclerosis (MS). Designed by Dr. Avasarala (MD PhD, University of Kentucky) and Dr. Kadambari (PhD, NIT Warangal).
|
| 47 |
+
|
| 48 |
+
YOUR ROLE:
|
| 49 |
+
- Conduct a structured clinical interview to gather neurological symptoms
|
| 50 |
+
- Use the CLASSIFIER RESULT and RAG CONTEXT provided to you to guide your response
|
| 51 |
+
- Ask focused follow-up questions to clarify key MS diagnostic anchors
|
| 52 |
+
- Never diagnose β you provide clinical decision support only
|
| 53 |
+
|
| 54 |
+
KEY MS ANCHOR SYMPTOMS to probe:
|
| 55 |
+
1. Visual: Monocular blurring/dimming, pain on eye movement, colour fading, double vision
|
| 56 |
+
2. Sensory: Electric shock down spine on neck bending (Lhermitte's), numbness/tingling, burning
|
| 57 |
+
3. Motor: Limb weakness, grip failure, foot drop, spasticity, tremor, gait unsteadiness
|
| 58 |
+
4. Brainstem: Diplopia, dizziness/vertigo, facial pain/numbness, swallowing difficulty
|
| 59 |
+
5. Autonomic: Bladder urgency, bowel dysfunction
|
| 60 |
+
6. Heat sensitivity (Uhthoff): Symptoms worse in heat, hot showers, exercise
|
| 61 |
+
7. Tight band around chest/trunk (MS Hug)
|
| 62 |
+
8. Prior episodes that resolved spontaneously (CIS pattern)
|
| 63 |
+
|
| 64 |
+
STANDARD MS WORKUP (recommend when MS suspected):
|
| 65 |
+
- MRI Orbits with/without contrast (optic nerve)
|
| 66 |
+
- MRI Brain and Spinal Cord with/without contrast
|
| 67 |
+
- Lumbar Puncture: oligoclonal bands (>2 exclusive to CSF), IgG index, kappa free light chains
|
| 68 |
+
- Serum assay for NMO and MOGAD
|
| 69 |
+
- Mimic screen: run tests to rule out other conditions
|
| 70 |
+
|
| 71 |
+
EMERGENCY FLAGS β respond immediately:
|
| 72 |
+
- Sudden face droop + arm weakness + slurred speech β Possible Stroke (call 999/911)
|
| 73 |
+
- Fever + neck stiffness + photophobia β Possible Meningitis (call 999/911)
|
| 74 |
+
- Thunderclap worst-ever headache β Possible Subarachnoid Haemorrhage (call 999/911)
|
| 75 |
+
- Ascending bilateral leg weakness β Possible GBS (call 999/911)
|
| 76 |
+
|
| 77 |
+
STRICT RULES β NEVER BREAK THESE:
|
| 78 |
+
- NEVER output JSON, tool calls, function calls, or code of any kind
|
| 79 |
+
- NEVER say "based on search results", "I searched", "the tool says", "classifier output"
|
| 80 |
+
- NEVER name other diseases (NMOSD, MOGAD, Lupus, Sarcoidosis, NMO, AQP4, MOG-IgG, Vasculitis) β say "we will test to rule out other conditions"
|
| 81 |
+
- NEVER repeat the same response or question twice
|
| 82 |
+
- NEVER end with "Would you like to know more?" or "Do you have any questions?"
|
| 83 |
+
- NEVER keep asking MS questions if patient has ONLY non-neurological symptoms (fever, cough, cold, nausea, stomach pain) β redirect to GP immediately
|
| 84 |
+
- MAXIMUM 5 follow-up questions β after 5 "no" answers with no MS features, conclude clearly
|
| 85 |
+
- Each response MUST move the conversation forward
|
| 86 |
+
- Ask only ONE follow-up question per response
|
| 87 |
+
- Respond ONLY in plain conversational English prose"""
|
| 88 |
+
|
| 89 |
+
# ββ Non-symptom fast-path βββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 90 |
+
_GREETINGS = {
|
| 91 |
+
"hi","hey","hello","hiya","howdy","greetings","sup","yo","hai",
|
| 92 |
+
"good morning","good afternoon","good evening","good night","good day",
|
| 93 |
+
"morning","afternoon","evening",
|
| 94 |
+
"ok","okay","k","kk","sure","alright","got it","understood","i see",
|
| 95 |
+
"noted","makes sense","that makes sense","i understand",
|
| 96 |
+
"oh i see","oh okay","oh ok","ah ok","ah i see","i get it",
|
| 97 |
+
"yes","yeah","yep","yup","yah","ye","yea","correct","exactly","right",
|
| 98 |
+
"absolutely","definitely","of course","certainly","indeed","true",
|
| 99 |
+
"that's right","thats right","that is right","sounds right",
|
| 100 |
+
"no","nope","nah","not really","not sure","i don't know","idk","hmm",
|
| 101 |
+
"not yet","maybe","possibly","i think so","i guess","i suppose",
|
| 102 |
+
"thanks","thank you","thank you so much","thanks a lot","thank u",
|
| 103 |
+
"ty","thnx","thx","many thanks","much appreciated","appreciate it",
|
| 104 |
+
"appreciate that","that's helpful","thats helpful","very helpful",
|
| 105 |
+
"that helped","that was helpful","that was very helpful",
|
| 106 |
+
"great","awesome","amazing","wonderful","excellent","fantastic","nice",
|
| 107 |
+
"good","very good","cool","perfect","brilliant","superb","impressive",
|
| 108 |
+
"wow","oh wow","that's great","thats great","that's amazing",
|
| 109 |
+
"that's good","thats good","good to know","interesting",
|
| 110 |
+
"please continue","go on","continue","go ahead","please go on",
|
| 111 |
+
"tell me more","and then","and","what else","ok go on","okay go on",
|
| 112 |
+
"bye","goodbye","good bye","see you","see ya","take care","later",
|
| 113 |
+
"talk later","ttyl","cya","have a good day","have a nice day",
|
| 114 |
+
"farewell","until next time",
|
| 115 |
+
"who are you","what are you","what is neurocheck","what's neurocheck",
|
| 116 |
+
"whats neurocheck","what can you do","how does this work",
|
| 117 |
+
"how do you work","what do you do","tell me about yourself",
|
| 118 |
+
"are you a doctor","are you an ai","are you real","are you human",
|
| 119 |
+
"what","huh","sorry","pardon","can you repeat","come again",
|
| 120 |
+
"i didn't understand","i don't understand","please repeat",
|
| 121 |
+
"say that again","what do you mean","what does that mean",
|
| 122 |
+
"hello ji","hi ji","namaste","namaskar","jai hind",
|
| 123 |
+
"haan","haan ji","nahi","theek hai","theek","bilkul","accha",
|
| 124 |
+
"thoda","shukriya","dhanyawad",
|
| 125 |
+
}
|
| 126 |
+
|
| 127 |
+
_GREETING_PATTERNS = [
|
| 128 |
+
r"^(hi|hey|hello|good[\s]\w+)[!. ]*$",
|
| 129 |
+
r"^(thanks?( you)?[\w ]*)$",
|
| 130 |
+
r"^(ok(ay)?|sure|alright|got it)[!. ]*$",
|
| 131 |
+
r"^(yes|no|yeah|nope|yep|nah)[!., ]*$",
|
| 132 |
+
r"^(that.s (helpful|great|good|amazing|clear))[!. ]*$",
|
| 133 |
+
r"^(how are you|how.s it going)[?!. ]*$",
|
| 134 |
+
r"^(can you help me|i need help)[?!. ]*$",
|
| 135 |
+
]
|
| 136 |
+
|
| 137 |
+
_CONTEXT_DEPENDENT = {
|
| 138 |
+
"yes","yeah","yep","yup","no","nope","nah","ok","okay","sure",
|
| 139 |
+
"alright","got it","understood","correct","exactly","right","true",
|
| 140 |
+
"not really","maybe","possibly","i think so","i guess","hmm","huh",
|
| 141 |
+
"what","go on","continue","please continue","go ahead","and","good",
|
| 142 |
+
"great","nice","cool","interesting","i see","oh i see","makes sense",
|
| 143 |
+
"noted","that's right","thats right","i don't know","idk","not sure",
|
| 144 |
+
}
|
| 145 |
+
|
| 146 |
+
def _is_greeting(text: str) -> bool:
|
| 147 |
+
cleaned = text.strip().lower().rstrip("!.,? ")
|
| 148 |
+
if cleaned in _GREETINGS:
|
| 149 |
+
return True
|
| 150 |
+
for pat in _GREETING_PATTERNS:
|
| 151 |
+
if re.match(pat, cleaned):
|
| 152 |
+
return True
|
| 153 |
+
return False
|
| 154 |
+
|
| 155 |
+
def _greeting_response(msg: str, is_first_turn: bool) -> str | None:
|
| 156 |
+
if any(x in msg for x in ["who are you","what are you","what is neurocheck",
|
| 157 |
+
"whats neurocheck","what can you do","tell me about",
|
| 158 |
+
"how does this work","how do you work","what do you do"]):
|
| 159 |
+
return (
|
| 160 |
+
"I'm AxonIQ, an AI-powered clinical decision support assistant "
|
| 161 |
+
"specialising in Multiple Sclerosis (MS) and related neurological conditions.\n\n"
|
| 162 |
+
"I was designed by Dr. Avasarala (MD PhD, University of Kentucky) and "
|
| 163 |
+
"Dr. Kadambari (PhD, NIT Warangal).\n\n"
|
| 164 |
+
"I can help you:\n"
|
| 165 |
+
"β’ Analyse neurological symptoms for MS-related patterns\n"
|
| 166 |
+
"β’ Identify red-flag emergency signs\n"
|
| 167 |
+
"β’ Recommend the appropriate clinical workup\n\n"
|
| 168 |
+
"Please describe your symptoms and I'll begin a structured clinical assessment."
|
| 169 |
+
)
|
| 170 |
+
if any(x in msg for x in ["are you a doctor","are you an ai","are you real","are you human","are you a robot"]):
|
| 171 |
+
return (
|
| 172 |
+
"I'm an AI assistant β not a doctor. I provide clinical decision support "
|
| 173 |
+
"to help identify patterns consistent with MS, but I cannot diagnose.\n\n"
|
| 174 |
+
"Could you tell me what symptoms you've been experiencing?"
|
| 175 |
+
)
|
| 176 |
+
if any(x in msg for x in ["can you help","i need help","help me","need some help"]):
|
| 177 |
+
return (
|
| 178 |
+
"Absolutely, I'm here to help. Please describe your neurological symptoms "
|
| 179 |
+
"in as much detail as you can β what you're feeling, where it is, when it "
|
| 180 |
+
"started, and whether it has happened before."
|
| 181 |
+
)
|
| 182 |
+
if any(x in msg for x in ["sorry","didn't understand","don't understand",
|
| 183 |
+
"what do you mean","can you repeat","say that again","pardon"]):
|
| 184 |
+
return (
|
| 185 |
+
"No problem! Let me know which part was unclear and I'll explain differently. "
|
| 186 |
+
"Or just describe your symptoms and I'll start a fresh assessment."
|
| 187 |
+
)
|
| 188 |
+
if any(x in msg for x in ["bye","goodbye","good bye","see you","take care","farewell","ttyl"]):
|
| 189 |
+
return "Take care! If your symptoms change or new ones develop, don't hesitate to return. Wishing you good health."
|
| 190 |
+
if any(x in msg for x in ["thank","thanks","ty","thnx","appreciate","helpful","that helped"]):
|
| 191 |
+
return "You're welcome! Is there anything else you'd like me to assess?"
|
| 192 |
+
if is_first_turn:
|
| 193 |
+
return (
|
| 194 |
+
"Hello! I'm AxonIQ, your MS clinical decision support assistant.\n\n"
|
| 195 |
+
"I'm here to help evaluate neurological symptoms that may be related to "
|
| 196 |
+
"Multiple Sclerosis. Could you describe what you've been experiencing? "
|
| 197 |
+
"Please include when it started, which part of the body is affected, "
|
| 198 |
+
"and whether it has happened before."
|
| 199 |
+
)
|
| 200 |
+
return None
|
| 201 |
+
|
| 202 |
+
|
| 203 |
+
# ββ Python-side classification and RAG βββββββββββββββββββββββββββββββββββββββ
|
| 204 |
+
def _run_classifier(text: str) -> dict:
|
| 205 |
+
"""Run the MS classifier directly in Python. Never fails β returns empty dict on error."""
|
| 206 |
+
try:
|
| 207 |
+
from api.main import classify as _classify
|
| 208 |
+
result = _classify(text)
|
| 209 |
+
return {
|
| 210 |
+
"tier": result.tier,
|
| 211 |
+
"tier_label": result.tier_label,
|
| 212 |
+
"action": result.action,
|
| 213 |
+
"features": [f.label for f in result.features],
|
| 214 |
+
"workup": result.workup[:5],
|
| 215 |
+
}
|
| 216 |
+
except Exception as e:
|
| 217 |
+
logger.warning("[agent] Classifier error: {}", e)
|
| 218 |
+
return {}
|
| 219 |
+
|
| 220 |
+
|
| 221 |
+
def _run_rag(text: str) -> str:
|
| 222 |
+
"""Query the RAG knowledge base. Returns empty string on error."""
|
| 223 |
+
try:
|
| 224 |
+
from api.rag import query as _query
|
| 225 |
+
results = _query(text, n_results=3)
|
| 226 |
+
chunks = [r["text"] for r in results if r.get("score", 0) > 0.3]
|
| 227 |
+
return "\n\n".join(chunks[:3])
|
| 228 |
+
except Exception as e:
|
| 229 |
+
logger.warning("[agent] RAG error: {}", e)
|
| 230 |
+
return ""
|
| 231 |
+
|
| 232 |
+
|
| 233 |
+
# ββ Build LLM prompt ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 234 |
+
def _build_context_block(cls: dict, rag: str) -> str:
|
| 235 |
+
"""Build a structured context block injected into the LLM prompt."""
|
| 236 |
+
parts = []
|
| 237 |
+
|
| 238 |
+
if cls:
|
| 239 |
+
tier = cls.get("tier", "LOW")
|
| 240 |
+
label = cls.get("tier_label", "")
|
| 241 |
+
action = cls.get("action", "")
|
| 242 |
+
feats = cls.get("features", [])
|
| 243 |
+
workup = cls.get("workup", [])
|
| 244 |
+
|
| 245 |
+
parts.append(f"CLASSIFIER RESULT:\n Risk tier: {tier} β {label}")
|
| 246 |
+
if feats:
|
| 247 |
+
parts.append(" Detected MS features: " + ", ".join(feats))
|
| 248 |
+
else:
|
| 249 |
+
parts.append(" Detected MS features: none identified yet")
|
| 250 |
+
if action:
|
| 251 |
+
parts.append(f" Recommended action: {action}")
|
| 252 |
+
if workup and tier not in ("LOW",):
|
| 253 |
+
parts.append(" Workup steps:\n" + "\n".join(f" - {w}" for w in workup))
|
| 254 |
+
|
| 255 |
+
if rag:
|
| 256 |
+
parts.append(f"CLINICAL KNOWLEDGE CONTEXT:\n{rag}")
|
| 257 |
+
|
| 258 |
+
if not parts:
|
| 259 |
+
return ""
|
| 260 |
+
|
| 261 |
+
return (
|
| 262 |
+
"\n\n--- CLINICAL DATA (use this to guide your response, do NOT quote it directly) ---\n"
|
| 263 |
+
+ "\n\n".join(parts)
|
| 264 |
+
+ "\n--- END CLINICAL DATA ---"
|
| 265 |
+
)
|
| 266 |
+
|
| 267 |
+
|
| 268 |
+
# ββ Main chat function ββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 269 |
+
def chat(session_id: str, user_message: str, history: List[Dict]) -> str:
|
| 270 |
+
"""
|
| 271 |
+
Process a user message and return the agent's clinical response.
|
| 272 |
+
Always returns clean prose β never JSON, never tool call text.
|
| 273 |
+
"""
|
| 274 |
+
human_turns = len([m for m in history if m["role"] == "human"])
|
| 275 |
+
is_first_turn = human_turns <= 1
|
| 276 |
+
msg = user_message.strip().lower().rstrip("!.,? ")
|
| 277 |
+
|
| 278 |
+
# ββ Fast-path: greetings ββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 279 |
+
if _is_greeting(user_message) and (is_first_turn or msg not in _CONTEXT_DEPENDENT):
|
| 280 |
+
response = _greeting_response(msg, is_first_turn)
|
| 281 |
+
if response:
|
| 282 |
+
return response
|
| 283 |
+
|
| 284 |
+
# ββ Step 1: Run classifier + RAG directly in Python βββββββββββββββββββββββ
|
| 285 |
+
# Accumulate all human messages for richer classification context
|
| 286 |
+
all_human_text = " ".join(
|
| 287 |
+
m["content"] for m in history if m["role"] == "human"
|
| 288 |
+
) + " " + user_message
|
| 289 |
+
|
| 290 |
+
cls_result = _run_classifier(all_human_text.strip())
|
| 291 |
+
rag_context = _run_rag(user_message)
|
| 292 |
+
|
| 293 |
+
# ββ Step 2: Build prompt with injected context ββββββββββββββββββββββββββββ
|
| 294 |
+
context_block = _build_context_block(cls_result, rag_context)
|
| 295 |
+
system_with_context = SYSTEM_PROMPT + context_block
|
| 296 |
+
|
| 297 |
+
# Rebuild conversation history for LLM
|
| 298 |
+
lc_messages = [SystemMessage(content=system_with_context)]
|
| 299 |
+
for m in history[:-1]:
|
| 300 |
+
if m["role"] == "human":
|
| 301 |
+
lc_messages.append(HM(content=m["content"]))
|
| 302 |
+
else:
|
| 303 |
+
lc_messages.append(AM(content=m["content"]))
|
| 304 |
+
lc_messages.append(HM(content=user_message))
|
| 305 |
+
|
| 306 |
+
# ββ Step 3: LLM generates ONLY prose βββββββββββββββββββββββββββββββββββββ
|
| 307 |
+
try:
|
| 308 |
+
response = llm.invoke(lc_messages)
|
| 309 |
+
content = response.content if hasattr(response, "content") else str(response)
|
| 310 |
+
except Exception as e:
|
| 311 |
+
logger.error("[agent] LLM error: {}", e)
|
| 312 |
+
return (
|
| 313 |
+
"I'm having trouble connecting to the AI service right now. "
|
| 314 |
+
"Please try again in a moment."
|
| 315 |
+
)
|
| 316 |
+
|
| 317 |
+
# ββ Step 4: Safety net β strip any JSON that slipped through βββββββββββββ
|
| 318 |
+
content = _strip_all_json(content)
|
| 319 |
+
content = content.strip()
|
| 320 |
+
|
| 321 |
+
if not content:
|
| 322 |
+
# LLM returned nothing useful β give a sensible fallback based on classifier
|
| 323 |
+
tier = cls_result.get("tier", "LOW")
|
| 324 |
+
if tier in ("HIGH", "CRITICAL_EMERGENCY", "MODERATE"):
|
| 325 |
+
feats = cls_result.get("features", [])
|
| 326 |
+
feat_str = ", ".join(feats) if feats else "the symptoms you described"
|
| 327 |
+
return (
|
| 328 |
+
f"Based on {feat_str}, there are features that warrant a neurological assessment. "
|
| 329 |
+
"Could you tell me more about when these symptoms first appeared and "
|
| 330 |
+
"whether you've had any similar episodes in the past?"
|
| 331 |
+
)
|
| 332 |
+
return (
|
| 333 |
+
"Thank you for sharing that. Could you tell me more about your symptoms β "
|
| 334 |
+
"when they started, which part of the body is affected, and whether "
|
| 335 |
+
"anything makes them better or worse?"
|
| 336 |
+
)
|
| 337 |
+
|
| 338 |
+
return content
|
| 339 |
+
|
| 340 |
+
|
| 341 |
+
def _strip_all_json(text: str) -> str:
|
| 342 |
+
"""
|
| 343 |
+
Aggressively remove any JSON or tool-call content from LLM output.
|
| 344 |
+
Handles all known HF Inference API formats.
|
| 345 |
+
"""
|
| 346 |
+
# Remove {"type": "function", ...} blocks
|
| 347 |
+
text = re.sub(
|
| 348 |
+
r'\{[^{}]*"type"\s*:\s*"function"[^{}]*(?:\{[^{}]*\}[^{}]*)?\}',
|
| 349 |
+
"", text, flags=re.DOTALL
|
| 350 |
+
)
|
| 351 |
+
# Remove any remaining {...} blocks that look like tool calls
|
| 352 |
+
text = re.sub(
|
| 353 |
+
r'\{[^{}]*"name"\s*:\s*"[a-z_]+"[^{}]*\}',
|
| 354 |
+
"", text, flags=re.DOTALL
|
| 355 |
+
)
|
| 356 |
+
# Remove [{"type": ...}] array wrappers
|
| 357 |
+
text = re.sub(
|
| 358 |
+
r'\[\s*\{[^[\]]*"(?:type|name)"[^[\]]*\}\s*\]',
|
| 359 |
+
"", text, flags=re.DOTALL
|
| 360 |
+
)
|
| 361 |
+
# Remove <tool_call>...</tool_call> XML style
|
| 362 |
+
text = re.sub(r'<tool_call>[\s\S]*?</tool_call>', "", text)
|
| 363 |
+
# Remove ```json ... ``` code blocks
|
| 364 |
+
text = re.sub(r'```(?:json)?[\s\S]*?```', "", text)
|
| 365 |
+
# Clean up extra blank lines left behind
|
| 366 |
+
text = re.sub(r'\n{3,}', '\n\n', text)
|
| 367 |
+
return text.strip()
|
api/auth.py
ADDED
|
@@ -0,0 +1,164 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
NeuroCheck β Authentication Layer
|
| 3 |
+
JWT-based stateless auth with bcrypt password hashing.
|
| 4 |
+
|
| 5 |
+
Endpoints added to main.py via include_router:
|
| 6 |
+
POST /auth/register β create account
|
| 7 |
+
POST /auth/login β returns access_token
|
| 8 |
+
GET /auth/me β returns current user info (requires Bearer token)
|
| 9 |
+
"""
|
| 10 |
+
from __future__ import annotations
|
| 11 |
+
import os
|
| 12 |
+
from datetime import datetime, timedelta, timezone
|
| 13 |
+
from typing import Optional
|
| 14 |
+
|
| 15 |
+
from fastapi import APIRouter, Depends, HTTPException, status
|
| 16 |
+
from fastapi.security import OAuth2PasswordBearer, OAuth2PasswordRequestForm
|
| 17 |
+
from jose import JWTError, jwt
|
| 18 |
+
import bcrypt as _bcrypt
|
| 19 |
+
from pydantic import BaseModel, Field
|
| 20 |
+
|
| 21 |
+
from api.database import (
|
| 22 |
+
create_user,
|
| 23 |
+
get_user_by_username,
|
| 24 |
+
get_user_by_email,
|
| 25 |
+
get_user_by_id,
|
| 26 |
+
init_db,
|
| 27 |
+
)
|
| 28 |
+
|
| 29 |
+
# ββ Config ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 30 |
+
SECRET_KEY = os.environ.get("JWT_SECRET", "neurocheck-dev-secret-change-in-production")
|
| 31 |
+
ALGORITHM = "HS256"
|
| 32 |
+
ACCESS_TOKEN_EXPIRE_MINUTES = int(os.environ.get("JWT_EXPIRE_MINUTES", "10080")) # 7 days
|
| 33 |
+
|
| 34 |
+
oauth2_scheme = OAuth2PasswordBearer(tokenUrl="/auth/login")
|
| 35 |
+
|
| 36 |
+
router = APIRouter(prefix="/auth", tags=["auth"])
|
| 37 |
+
|
| 38 |
+
# ββ Schemas βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 39 |
+
|
| 40 |
+
class RegisterRequest(BaseModel):
|
| 41 |
+
username: str = Field(..., min_length=3, max_length=40, pattern=r"^[a-zA-Z0-9_\-]+$")
|
| 42 |
+
email: str = Field(..., pattern=r'^[^@\s]+@[^@\s]+\.[^@\s]+$')
|
| 43 |
+
password: str = Field(..., min_length=6, max_length=128)
|
| 44 |
+
|
| 45 |
+
|
| 46 |
+
class LoginResponse(BaseModel):
|
| 47 |
+
access_token: str
|
| 48 |
+
token_type: str = "bearer"
|
| 49 |
+
user_id: int
|
| 50 |
+
username: str
|
| 51 |
+
|
| 52 |
+
|
| 53 |
+
class UserInfo(BaseModel):
|
| 54 |
+
user_id: int
|
| 55 |
+
username: str
|
| 56 |
+
email: str
|
| 57 |
+
created_at: str
|
| 58 |
+
is_admin: bool = False
|
| 59 |
+
|
| 60 |
+
|
| 61 |
+
# ββ Helpers βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 62 |
+
|
| 63 |
+
def hash_password(plain: str) -> str:
|
| 64 |
+
return _bcrypt.hashpw(plain.encode("utf-8"), _bcrypt.gensalt()).decode("utf-8")
|
| 65 |
+
|
| 66 |
+
|
| 67 |
+
def verify_password(plain: str, hashed: str) -> bool:
|
| 68 |
+
try:
|
| 69 |
+
return _bcrypt.checkpw(plain.encode("utf-8"), hashed.encode("utf-8"))
|
| 70 |
+
except Exception:
|
| 71 |
+
return False
|
| 72 |
+
|
| 73 |
+
|
| 74 |
+
def create_access_token(user_id: int, username: str) -> str:
|
| 75 |
+
expire = datetime.now(timezone.utc) + timedelta(minutes=ACCESS_TOKEN_EXPIRE_MINUTES)
|
| 76 |
+
payload = {"sub": str(user_id), "username": username, "exp": expire}
|
| 77 |
+
return jwt.encode(payload, SECRET_KEY, algorithm=ALGORITHM)
|
| 78 |
+
|
| 79 |
+
|
| 80 |
+
def decode_token(token: str) -> dict:
|
| 81 |
+
try:
|
| 82 |
+
return jwt.decode(token, SECRET_KEY, algorithms=[ALGORITHM])
|
| 83 |
+
except JWTError:
|
| 84 |
+
raise HTTPException(
|
| 85 |
+
status_code=status.HTTP_401_UNAUTHORIZED,
|
| 86 |
+
detail="Invalid or expired token",
|
| 87 |
+
headers={"WWW-Authenticate": "Bearer"},
|
| 88 |
+
)
|
| 89 |
+
|
| 90 |
+
|
| 91 |
+
# ββ Dependency: get current user from Bearer token ββββββββββββββββββββββββββββ
|
| 92 |
+
|
| 93 |
+
def get_current_user(token: str = Depends(oauth2_scheme)) -> dict:
|
| 94 |
+
"""FastAPI dependency β inject into any protected route."""
|
| 95 |
+
payload = decode_token(token)
|
| 96 |
+
user_id = int(payload.get("sub", 0))
|
| 97 |
+
user = get_user_by_id(user_id)
|
| 98 |
+
if not user:
|
| 99 |
+
raise HTTPException(status_code=401, detail="User not found")
|
| 100 |
+
return user
|
| 101 |
+
|
| 102 |
+
|
| 103 |
+
def get_optional_user(token: Optional[str] = Depends(oauth2_scheme)) -> Optional[dict]:
|
| 104 |
+
"""Like get_current_user but returns None instead of raising (for semi-public routes)."""
|
| 105 |
+
if not token:
|
| 106 |
+
return None
|
| 107 |
+
try:
|
| 108 |
+
return get_current_user(token)
|
| 109 |
+
except HTTPException:
|
| 110 |
+
return None
|
| 111 |
+
|
| 112 |
+
|
| 113 |
+
# ββ Routes ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 114 |
+
|
| 115 |
+
@router.post("/register", status_code=201)
|
| 116 |
+
async def register(req: RegisterRequest):
|
| 117 |
+
"""Create a new user account."""
|
| 118 |
+
init_db()
|
| 119 |
+
|
| 120 |
+
if get_user_by_username(req.username):
|
| 121 |
+
raise HTTPException(status_code=409, detail="Username already taken")
|
| 122 |
+
if get_user_by_email(req.email):
|
| 123 |
+
raise HTTPException(status_code=409, detail="Email already registered")
|
| 124 |
+
|
| 125 |
+
hashed = hash_password(req.password)
|
| 126 |
+
uid = create_user(req.username, req.email, hashed)
|
| 127 |
+
token = create_access_token(uid, req.username)
|
| 128 |
+
|
| 129 |
+
return LoginResponse(
|
| 130 |
+
access_token=token,
|
| 131 |
+
user_id=uid,
|
| 132 |
+
username=req.username,
|
| 133 |
+
)
|
| 134 |
+
|
| 135 |
+
|
| 136 |
+
@router.post("/login", response_model=LoginResponse)
|
| 137 |
+
async def login(form: OAuth2PasswordRequestForm = Depends()):
|
| 138 |
+
"""Authenticate and return JWT. Accepts username OR email in the username field."""
|
| 139 |
+
user = get_user_by_username(form.username) or get_user_by_email(form.username)
|
| 140 |
+
if not user or not verify_password(form.password, user["password_hash"]):
|
| 141 |
+
raise HTTPException(
|
| 142 |
+
status_code=status.HTTP_401_UNAUTHORIZED,
|
| 143 |
+
detail="Incorrect username/email or password",
|
| 144 |
+
headers={"WWW-Authenticate": "Bearer"},
|
| 145 |
+
)
|
| 146 |
+
|
| 147 |
+
token = create_access_token(user["id"], user["username"])
|
| 148 |
+
return LoginResponse(
|
| 149 |
+
access_token=token,
|
| 150 |
+
user_id=user["id"],
|
| 151 |
+
username=user["username"],
|
| 152 |
+
)
|
| 153 |
+
|
| 154 |
+
|
| 155 |
+
@router.get("/me", response_model=UserInfo)
|
| 156 |
+
async def me(current_user: dict = Depends(get_current_user)):
|
| 157 |
+
"""Return current user's profile info."""
|
| 158 |
+
return UserInfo(
|
| 159 |
+
user_id=current_user["id"],
|
| 160 |
+
username=current_user["username"],
|
| 161 |
+
email=current_user["email"],
|
| 162 |
+
created_at=current_user["created_at"],
|
| 163 |
+
is_admin=bool(current_user.get("is_admin", 0)),
|
| 164 |
+
)
|
api/database.py
ADDED
|
@@ -0,0 +1,531 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
NeuroCheck β Persistent Database Layer
|
| 3 |
+
SQLite-backed storage for users, chat sessions, and messages.
|
| 4 |
+
|
| 5 |
+
Tables:
|
| 6 |
+
users β registered accounts (id, username, email, hashed_password, created_at)
|
| 7 |
+
chat_sessions β per-user conversation sessions (id, user_id, title, created_at, updated_at)
|
| 8 |
+
messages β every message in a session (id, session_db_id, role, content, created_at)
|
| 9 |
+
"""
|
| 10 |
+
from __future__ import annotations
|
| 11 |
+
import sqlite3
|
| 12 |
+
import os
|
| 13 |
+
from datetime import datetime, timezone
|
| 14 |
+
from pathlib import Path
|
| 15 |
+
from contextlib import contextmanager
|
| 16 |
+
from typing import List, Dict, Any, Optional
|
| 17 |
+
|
| 18 |
+
# ββ DB path βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 19 |
+
DB_PATH = Path(os.environ.get("NEUROCHECK_DB", "/tmp/neurocheck.db"))
|
| 20 |
+
|
| 21 |
+
|
| 22 |
+
def _now() -> str:
|
| 23 |
+
return datetime.now(timezone.utc).isoformat()
|
| 24 |
+
|
| 25 |
+
|
| 26 |
+
@contextmanager
|
| 27 |
+
def get_conn():
|
| 28 |
+
"""Thread-safe SQLite connection with WAL mode for concurrency."""
|
| 29 |
+
conn = sqlite3.connect(str(DB_PATH), check_same_thread=False)
|
| 30 |
+
conn.row_factory = sqlite3.Row
|
| 31 |
+
conn.execute("PRAGMA journal_mode=WAL")
|
| 32 |
+
conn.execute("PRAGMA foreign_keys=ON")
|
| 33 |
+
try:
|
| 34 |
+
yield conn
|
| 35 |
+
conn.commit()
|
| 36 |
+
except Exception:
|
| 37 |
+
conn.rollback()
|
| 38 |
+
raise
|
| 39 |
+
finally:
|
| 40 |
+
conn.close()
|
| 41 |
+
|
| 42 |
+
|
| 43 |
+
# ββ Schema Init βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 44 |
+
|
| 45 |
+
def init_db() -> None:
|
| 46 |
+
"""Create all tables if they don't exist. Safe to call on every startup."""
|
| 47 |
+
# Ensure parent directory exists (important for /data/db/ on HuggingFace)
|
| 48 |
+
DB_PATH.parent.mkdir(parents=True, exist_ok=True)
|
| 49 |
+
|
| 50 |
+
with get_conn() as conn:
|
| 51 |
+
conn.executescript("""
|
| 52 |
+
CREATE TABLE IF NOT EXISTS users (
|
| 53 |
+
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
| 54 |
+
username TEXT NOT NULL UNIQUE COLLATE NOCASE,
|
| 55 |
+
email TEXT NOT NULL UNIQUE COLLATE NOCASE,
|
| 56 |
+
password_hash TEXT NOT NULL,
|
| 57 |
+
created_at TEXT NOT NULL,
|
| 58 |
+
is_admin INTEGER NOT NULL DEFAULT 0
|
| 59 |
+
);
|
| 60 |
+
-- Add is_admin column if upgrading from older schema
|
| 61 |
+
-- (safe to run multiple times β ALTER TABLE fails silently via Python)
|
| 62 |
+
|
| 63 |
+
CREATE TABLE IF NOT EXISTS chat_sessions (
|
| 64 |
+
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
| 65 |
+
session_uuid TEXT NOT NULL UNIQUE,
|
| 66 |
+
user_id INTEGER NOT NULL REFERENCES users(id),
|
| 67 |
+
title TEXT NOT NULL DEFAULT 'New Chat',
|
| 68 |
+
created_at TEXT NOT NULL,
|
| 69 |
+
updated_at TEXT NOT NULL,
|
| 70 |
+
deleted_at TEXT DEFAULT NULL,
|
| 71 |
+
ms_tier TEXT DEFAULT NULL,
|
| 72 |
+
ms_tier_label TEXT DEFAULT NULL,
|
| 73 |
+
ms_symptoms TEXT DEFAULT NULL,
|
| 74 |
+
ms_workup TEXT DEFAULT NULL,
|
| 75 |
+
ms_action TEXT DEFAULT NULL,
|
| 76 |
+
concluded_at TEXT DEFAULT NULL
|
| 77 |
+
);
|
| 78 |
+
|
| 79 |
+
CREATE TABLE IF NOT EXISTS messages (
|
| 80 |
+
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
| 81 |
+
session_uuid TEXT NOT NULL REFERENCES chat_sessions(session_uuid),
|
| 82 |
+
role TEXT NOT NULL CHECK(role IN ('human','assistant','system')),
|
| 83 |
+
content TEXT NOT NULL,
|
| 84 |
+
created_at TEXT NOT NULL
|
| 85 |
+
);
|
| 86 |
+
|
| 87 |
+
CREATE INDEX IF NOT EXISTS idx_sessions_user ON chat_sessions(user_id);
|
| 88 |
+
CREATE INDEX IF NOT EXISTS idx_messages_session ON messages(session_uuid);
|
| 89 |
+
|
| 90 |
+
CREATE TABLE IF NOT EXISTS password_reset_otps (
|
| 91 |
+
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
| 92 |
+
user_id INTEGER NOT NULL REFERENCES users(id),
|
| 93 |
+
email TEXT NOT NULL,
|
| 94 |
+
otp_hash TEXT NOT NULL,
|
| 95 |
+
expires_at TEXT NOT NULL,
|
| 96 |
+
used INTEGER NOT NULL DEFAULT 0,
|
| 97 |
+
created_at TEXT NOT NULL
|
| 98 |
+
);
|
| 99 |
+
|
| 100 |
+
CREATE TABLE IF NOT EXISTS user_logs (
|
| 101 |
+
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
| 102 |
+
user_id INTEGER REFERENCES users(id),
|
| 103 |
+
username TEXT,
|
| 104 |
+
action TEXT NOT NULL,
|
| 105 |
+
detail TEXT DEFAULT NULL,
|
| 106 |
+
ip_address TEXT DEFAULT NULL,
|
| 107 |
+
session_uuid TEXT DEFAULT NULL,
|
| 108 |
+
created_at TEXT NOT NULL
|
| 109 |
+
);
|
| 110 |
+
CREATE INDEX IF NOT EXISTS idx_logs_user ON user_logs(user_id);
|
| 111 |
+
CREATE INDEX IF NOT EXISTS idx_logs_time ON user_logs(created_at);
|
| 112 |
+
""")
|
| 113 |
+
|
| 114 |
+
# Auto-backup on every startup β keeps last 7 daily backups
|
| 115 |
+
_backup_db()
|
| 116 |
+
|
| 117 |
+
|
| 118 |
+
def _backup_db() -> None:
|
| 119 |
+
"""Copy the DB to /data/backups/ with a timestamp. Keep last 7 backups."""
|
| 120 |
+
import shutil, glob
|
| 121 |
+
backup_dir = DB_PATH.parent.parent / "backups"
|
| 122 |
+
try:
|
| 123 |
+
backup_dir.mkdir(parents=True, exist_ok=True)
|
| 124 |
+
if not DB_PATH.exists():
|
| 125 |
+
return
|
| 126 |
+
ts = datetime.now(timezone.utc).strftime("%Y%m%d")
|
| 127 |
+
dest = backup_dir / f"neurocheck_{ts}.db"
|
| 128 |
+
if not dest.exists(): # one backup per day max
|
| 129 |
+
shutil.copy2(str(DB_PATH), str(dest))
|
| 130 |
+
# Keep only last 7 backups
|
| 131 |
+
backups = sorted(glob.glob(str(backup_dir / "neurocheck_*.db")))
|
| 132 |
+
for old in backups[:-7]:
|
| 133 |
+
Path(old).unlink(missing_ok=True)
|
| 134 |
+
except Exception:
|
| 135 |
+
pass # never crash startup due to backup failure
|
| 136 |
+
|
| 137 |
+
|
| 138 |
+
# ββ User CRUD βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 139 |
+
|
| 140 |
+
def create_user(username: str, email: str, password_hash: str) -> int:
|
| 141 |
+
"""Insert a new user. Returns the new user's integer id."""
|
| 142 |
+
with get_conn() as conn:
|
| 143 |
+
cur = conn.execute(
|
| 144 |
+
"INSERT INTO users (username, email, password_hash, created_at) VALUES (?,?,?,?)",
|
| 145 |
+
(username.strip(), email.strip().lower(), password_hash, _now()),
|
| 146 |
+
)
|
| 147 |
+
return cur.lastrowid
|
| 148 |
+
|
| 149 |
+
|
| 150 |
+
def get_user_by_username(username: str) -> Optional[Dict[str, Any]]:
|
| 151 |
+
with get_conn() as conn:
|
| 152 |
+
row = conn.execute(
|
| 153 |
+
"SELECT * FROM users WHERE username = ? COLLATE NOCASE", (username,)
|
| 154 |
+
).fetchone()
|
| 155 |
+
return dict(row) if row else None
|
| 156 |
+
|
| 157 |
+
|
| 158 |
+
def get_user_by_email(email: str) -> Optional[Dict[str, Any]]:
|
| 159 |
+
with get_conn() as conn:
|
| 160 |
+
row = conn.execute(
|
| 161 |
+
"SELECT * FROM users WHERE email = ? COLLATE NOCASE", (email.strip().lower(),)
|
| 162 |
+
).fetchone()
|
| 163 |
+
return dict(row) if row else None
|
| 164 |
+
|
| 165 |
+
|
| 166 |
+
def get_user_by_id(user_id: int) -> Optional[Dict[str, Any]]:
|
| 167 |
+
with get_conn() as conn:
|
| 168 |
+
row = conn.execute("SELECT * FROM users WHERE id = ?", (user_id,)).fetchone()
|
| 169 |
+
return dict(row) if row else None
|
| 170 |
+
|
| 171 |
+
|
| 172 |
+
# ββ Session CRUD ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 173 |
+
|
| 174 |
+
def create_db_session(session_uuid: str, user_id: int, title: str = "New Chat") -> None:
|
| 175 |
+
"""Persist a new chat session linked to a user."""
|
| 176 |
+
now = _now()
|
| 177 |
+
with get_conn() as conn:
|
| 178 |
+
conn.execute(
|
| 179 |
+
"INSERT OR IGNORE INTO chat_sessions (session_uuid, user_id, title, created_at, updated_at) "
|
| 180 |
+
"VALUES (?,?,?,?,?)",
|
| 181 |
+
(session_uuid, user_id, title, now, now),
|
| 182 |
+
)
|
| 183 |
+
|
| 184 |
+
|
| 185 |
+
def get_user_sessions(user_id: int) -> List[Dict[str, Any]]:
|
| 186 |
+
"""Return all active (non-deleted) sessions for a user, newest first."""
|
| 187 |
+
with get_conn() as conn:
|
| 188 |
+
rows = conn.execute(
|
| 189 |
+
"SELECT * FROM chat_sessions WHERE user_id = ? AND deleted_at IS NULL ORDER BY updated_at DESC",
|
| 190 |
+
(user_id,),
|
| 191 |
+
).fetchall()
|
| 192 |
+
return [dict(r) for r in rows]
|
| 193 |
+
|
| 194 |
+
|
| 195 |
+
def update_session_title(session_uuid: str, title: str) -> None:
|
| 196 |
+
now = _now()
|
| 197 |
+
with get_conn() as conn:
|
| 198 |
+
conn.execute(
|
| 199 |
+
"UPDATE chat_sessions SET title=?, updated_at=? WHERE session_uuid=?",
|
| 200 |
+
(title[:80], now, session_uuid),
|
| 201 |
+
)
|
| 202 |
+
|
| 203 |
+
|
| 204 |
+
def touch_session(session_uuid: str) -> None:
|
| 205 |
+
"""Update the updated_at timestamp on a session."""
|
| 206 |
+
with get_conn() as conn:
|
| 207 |
+
conn.execute(
|
| 208 |
+
"UPDATE chat_sessions SET updated_at=? WHERE session_uuid=?",
|
| 209 |
+
(_now(), session_uuid),
|
| 210 |
+
)
|
| 211 |
+
|
| 212 |
+
|
| 213 |
+
def delete_db_session(session_uuid: str) -> None:
|
| 214 |
+
"""Soft-delete β marks session as deleted but NEVER removes data from disk."""
|
| 215 |
+
with get_conn() as conn:
|
| 216 |
+
conn.execute(
|
| 217 |
+
"UPDATE chat_sessions SET deleted_at=? WHERE session_uuid=?",
|
| 218 |
+
(_now(), session_uuid)
|
| 219 |
+
)
|
| 220 |
+
|
| 221 |
+
|
| 222 |
+
def get_session_owner(session_uuid: str) -> Optional[int]:
|
| 223 |
+
"""Return user_id that owns this session, or None."""
|
| 224 |
+
with get_conn() as conn:
|
| 225 |
+
row = conn.execute(
|
| 226 |
+
"SELECT user_id FROM chat_sessions WHERE session_uuid=?", (session_uuid,)
|
| 227 |
+
).fetchone()
|
| 228 |
+
return row["user_id"] if row else None
|
| 229 |
+
|
| 230 |
+
|
| 231 |
+
# ββ Message CRUD ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 232 |
+
|
| 233 |
+
def save_message(session_uuid: str, role: str, content: str) -> int:
|
| 234 |
+
"""Append a message to a session. Returns new message id."""
|
| 235 |
+
now = _now()
|
| 236 |
+
with get_conn() as conn:
|
| 237 |
+
cur = conn.execute(
|
| 238 |
+
"INSERT INTO messages (session_uuid, role, content, created_at) VALUES (?,?,?,?)",
|
| 239 |
+
(session_uuid, role, content, now),
|
| 240 |
+
)
|
| 241 |
+
# touch session updated_at
|
| 242 |
+
conn.execute(
|
| 243 |
+
"UPDATE chat_sessions SET updated_at=? WHERE session_uuid=?",
|
| 244 |
+
(now, session_uuid),
|
| 245 |
+
)
|
| 246 |
+
return cur.lastrowid
|
| 247 |
+
|
| 248 |
+
|
| 249 |
+
def get_messages(session_uuid: str) -> List[Dict[str, Any]]:
|
| 250 |
+
"""Return all messages for a session in chronological order."""
|
| 251 |
+
with get_conn() as conn:
|
| 252 |
+
rows = conn.execute(
|
| 253 |
+
"SELECT role, content, created_at FROM messages "
|
| 254 |
+
"WHERE session_uuid=? ORDER BY id ASC",
|
| 255 |
+
(session_uuid,),
|
| 256 |
+
).fetchall()
|
| 257 |
+
return [dict(r) for r in rows]
|
| 258 |
+
|
| 259 |
+
|
| 260 |
+
def get_message_count(session_uuid: str) -> int:
|
| 261 |
+
with get_conn() as conn:
|
| 262 |
+
row = conn.execute(
|
| 263 |
+
"SELECT COUNT(*) as n FROM messages WHERE session_uuid=?", (session_uuid,)
|
| 264 |
+
).fetchone()
|
| 265 |
+
return row["n"] if row else 0
|
| 266 |
+
|
| 267 |
+
|
| 268 |
+
# ββ Admin helpers βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 269 |
+
|
| 270 |
+
def migrate_add_admin_column() -> None:
|
| 271 |
+
"""Safe migration β adds is_admin and conclusion columns to existing databases."""
|
| 272 |
+
cols = [
|
| 273 |
+
"ALTER TABLE users ADD COLUMN is_admin INTEGER NOT NULL DEFAULT 0",
|
| 274 |
+
"ALTER TABLE chat_sessions ADD COLUMN ms_tier TEXT DEFAULT NULL",
|
| 275 |
+
"ALTER TABLE chat_sessions ADD COLUMN ms_tier_label TEXT DEFAULT NULL",
|
| 276 |
+
"ALTER TABLE chat_sessions ADD COLUMN ms_symptoms TEXT DEFAULT NULL",
|
| 277 |
+
"ALTER TABLE chat_sessions ADD COLUMN ms_workup TEXT DEFAULT NULL",
|
| 278 |
+
"ALTER TABLE chat_sessions ADD COLUMN ms_action TEXT DEFAULT NULL",
|
| 279 |
+
"ALTER TABLE chat_sessions ADD COLUMN concluded_at TEXT DEFAULT NULL",
|
| 280 |
+
]
|
| 281 |
+
for sql in cols:
|
| 282 |
+
try:
|
| 283 |
+
with get_conn() as conn:
|
| 284 |
+
conn.execute(sql)
|
| 285 |
+
except Exception:
|
| 286 |
+
pass # Column already exists β safe to ignore
|
| 287 |
+
|
| 288 |
+
|
| 289 |
+
def set_admin(username: str, is_admin: bool = True) -> bool:
|
| 290 |
+
"""Grant or revoke admin access for a user."""
|
| 291 |
+
with get_conn() as conn:
|
| 292 |
+
cur = conn.execute(
|
| 293 |
+
"UPDATE users SET is_admin=? WHERE username=? COLLATE NOCASE",
|
| 294 |
+
(1 if is_admin else 0, username)
|
| 295 |
+
)
|
| 296 |
+
return cur.rowcount > 0
|
| 297 |
+
|
| 298 |
+
|
| 299 |
+
def get_all_users_admin() -> list:
|
| 300 |
+
"""Return all users with session and message counts for admin panel."""
|
| 301 |
+
with get_conn() as conn:
|
| 302 |
+
rows = conn.execute("""
|
| 303 |
+
SELECT
|
| 304 |
+
u.id, u.username, u.email, u.created_at, u.is_admin,
|
| 305 |
+
COUNT(DISTINCT cs.id) AS session_count,
|
| 306 |
+
COUNT(DISTINCT m.id) AS message_count,
|
| 307 |
+
MAX(CASE WHEN cs.ms_tier='CRITICAL_EMERGENCY' THEN 5
|
| 308 |
+
WHEN cs.ms_tier='HIGH' THEN 4
|
| 309 |
+
WHEN cs.ms_tier='MODERATE' THEN 3
|
| 310 |
+
WHEN cs.ms_tier='WATCH' THEN 2
|
| 311 |
+
WHEN cs.ms_tier='LOW' THEN 1
|
| 312 |
+
ELSE 0 END) AS highest_risk_score,
|
| 313 |
+
(SELECT cs2.ms_tier FROM chat_sessions cs2
|
| 314 |
+
WHERE cs2.user_id=u.id AND cs2.ms_tier IS NOT NULL
|
| 315 |
+
ORDER BY cs2.concluded_at DESC LIMIT 1) AS latest_tier
|
| 316 |
+
FROM users u
|
| 317 |
+
LEFT JOIN chat_sessions cs ON cs.user_id = u.id AND cs.deleted_at IS NULL
|
| 318 |
+
LEFT JOIN messages m ON m.session_uuid = cs.session_uuid
|
| 319 |
+
GROUP BY u.id
|
| 320 |
+
ORDER BY u.created_at DESC
|
| 321 |
+
""").fetchall()
|
| 322 |
+
return [dict(r) for r in rows]
|
| 323 |
+
|
| 324 |
+
|
| 325 |
+
def get_all_sessions_admin() -> tuple:
|
| 326 |
+
"""Return total session and message counts across all users."""
|
| 327 |
+
with get_conn() as conn:
|
| 328 |
+
s = conn.execute("SELECT COUNT(*) FROM chat_sessions WHERE deleted_at IS NULL").fetchone()[0]
|
| 329 |
+
m = conn.execute("SELECT COUNT(*) FROM messages").fetchone()[0]
|
| 330 |
+
return s, m
|
| 331 |
+
|
| 332 |
+
|
| 333 |
+
def get_user_sessions_with_messages(user_id: int) -> list:
|
| 334 |
+
"""Return all sessions for a user including full message content and conclusion."""
|
| 335 |
+
import json as _json
|
| 336 |
+
with get_conn() as conn:
|
| 337 |
+
sessions = conn.execute(
|
| 338 |
+
"SELECT * FROM chat_sessions WHERE user_id=? AND deleted_at IS NULL ORDER BY created_at DESC",
|
| 339 |
+
(user_id,)
|
| 340 |
+
).fetchall()
|
| 341 |
+
result = []
|
| 342 |
+
for s in sessions:
|
| 343 |
+
s = dict(s)
|
| 344 |
+
msgs = conn.execute(
|
| 345 |
+
"SELECT role, content, created_at FROM messages WHERE session_uuid=? ORDER BY id ASC",
|
| 346 |
+
(s["session_uuid"],)
|
| 347 |
+
).fetchall()
|
| 348 |
+
s["messages"] = [dict(m) for m in msgs]
|
| 349 |
+
# Attach parsed conclusion
|
| 350 |
+
if s.get("ms_tier"):
|
| 351 |
+
s["conclusion"] = {
|
| 352 |
+
"tier": s["ms_tier"],
|
| 353 |
+
"tier_label": s["ms_tier_label"],
|
| 354 |
+
"symptoms": _json.loads(s.get("ms_symptoms") or "[]"),
|
| 355 |
+
"workup": _json.loads(s.get("ms_workup") or "[]"),
|
| 356 |
+
"action": s.get("ms_action", ""),
|
| 357 |
+
"concluded_at": s.get("concluded_at"),
|
| 358 |
+
}
|
| 359 |
+
else:
|
| 360 |
+
s["conclusion"] = None
|
| 361 |
+
result.append(s)
|
| 362 |
+
return result
|
| 363 |
+
|
| 364 |
+
|
| 365 |
+
def save_conclusion(session_uuid: str, tier: str, tier_label: str,
|
| 366 |
+
symptoms: list, workup: list, action: str) -> None:
|
| 367 |
+
"""Save the MS classification conclusion to the session record."""
|
| 368 |
+
import json as _json
|
| 369 |
+
now = _now()
|
| 370 |
+
with get_conn() as conn:
|
| 371 |
+
conn.execute("""
|
| 372 |
+
UPDATE chat_sessions
|
| 373 |
+
SET ms_tier=?, ms_tier_label=?, ms_symptoms=?, ms_workup=?,
|
| 374 |
+
ms_action=?, concluded_at=?, updated_at=?
|
| 375 |
+
WHERE session_uuid=?
|
| 376 |
+
""", (
|
| 377 |
+
tier,
|
| 378 |
+
tier_label,
|
| 379 |
+
_json.dumps(symptoms),
|
| 380 |
+
_json.dumps(workup),
|
| 381 |
+
action,
|
| 382 |
+
now,
|
| 383 |
+
now,
|
| 384 |
+
session_uuid,
|
| 385 |
+
))
|
| 386 |
+
|
| 387 |
+
|
| 388 |
+
def get_conclusion(session_uuid: str) -> dict | None:
|
| 389 |
+
"""Return the saved conclusion for a session, or None."""
|
| 390 |
+
import json as _json
|
| 391 |
+
with get_conn() as conn:
|
| 392 |
+
row = conn.execute(
|
| 393 |
+
"SELECT ms_tier, ms_tier_label, ms_symptoms, ms_workup, ms_action, concluded_at "
|
| 394 |
+
"FROM chat_sessions WHERE session_uuid=?",
|
| 395 |
+
(session_uuid,)
|
| 396 |
+
).fetchone()
|
| 397 |
+
if not row or not row["ms_tier"]:
|
| 398 |
+
return None
|
| 399 |
+
return {
|
| 400 |
+
"tier": row["ms_tier"],
|
| 401 |
+
"tier_label": row["ms_tier_label"],
|
| 402 |
+
"symptoms": _json.loads(row["ms_symptoms"] or "[]"),
|
| 403 |
+
"workup": _json.loads(row["ms_workup"] or "[]"),
|
| 404 |
+
"action": row["ms_action"],
|
| 405 |
+
"concluded_at": row["concluded_at"],
|
| 406 |
+
}
|
| 407 |
+
|
| 408 |
+
|
| 409 |
+
# ββ User Activity Logging βββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 410 |
+
|
| 411 |
+
def log_action(
|
| 412 |
+
action: str,
|
| 413 |
+
user_id: int | None = None,
|
| 414 |
+
username: str | None = None,
|
| 415 |
+
detail: str | None = None,
|
| 416 |
+
ip_address: str | None = None,
|
| 417 |
+
session_uuid: str | None = None,
|
| 418 |
+
) -> None:
|
| 419 |
+
"""Log a user action. Never raises β logging must not crash the app."""
|
| 420 |
+
try:
|
| 421 |
+
DB_PATH.parent.mkdir(parents=True, exist_ok=True)
|
| 422 |
+
with get_conn() as conn:
|
| 423 |
+
conn.execute(
|
| 424 |
+
"INSERT INTO user_logs (user_id, username, action, detail, ip_address, session_uuid, created_at) "
|
| 425 |
+
"VALUES (?,?,?,?,?,?,?)",
|
| 426 |
+
(user_id, username, action, detail, ip_address, session_uuid, _now()),
|
| 427 |
+
)
|
| 428 |
+
except Exception:
|
| 429 |
+
pass
|
| 430 |
+
|
| 431 |
+
|
| 432 |
+
def get_user_logs(user_id: int, limit: int = 200) -> list:
|
| 433 |
+
"""Return recent activity logs for a specific user."""
|
| 434 |
+
with get_conn() as conn:
|
| 435 |
+
rows = conn.execute(
|
| 436 |
+
"SELECT action, detail, ip_address, session_uuid, created_at "
|
| 437 |
+
"FROM user_logs WHERE user_id=? ORDER BY id DESC LIMIT ?",
|
| 438 |
+
(user_id, limit)
|
| 439 |
+
).fetchall()
|
| 440 |
+
return [dict(r) for r in rows]
|
| 441 |
+
|
| 442 |
+
|
| 443 |
+
def get_all_logs(limit: int = 500) -> list:
|
| 444 |
+
"""Return recent activity logs across all users (admin view)."""
|
| 445 |
+
with get_conn() as conn:
|
| 446 |
+
rows = conn.execute(
|
| 447 |
+
"SELECT ul.created_at, ul.username, ul.action, ul.detail, ul.ip_address, ul.session_uuid "
|
| 448 |
+
"FROM user_logs ul ORDER BY ul.id DESC LIMIT ?",
|
| 449 |
+
(limit,)
|
| 450 |
+
).fetchall()
|
| 451 |
+
return [dict(r) for r in rows]
|
| 452 |
+
|
| 453 |
+
|
| 454 |
+
def migrate_add_logs_table() -> None:
|
| 455 |
+
"""Safe migration β creates user_logs table if not exists."""
|
| 456 |
+
try:
|
| 457 |
+
with get_conn() as conn:
|
| 458 |
+
conn.execute("""
|
| 459 |
+
CREATE TABLE IF NOT EXISTS user_logs (
|
| 460 |
+
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
| 461 |
+
user_id INTEGER REFERENCES users(id),
|
| 462 |
+
username TEXT,
|
| 463 |
+
action TEXT NOT NULL,
|
| 464 |
+
detail TEXT DEFAULT NULL,
|
| 465 |
+
ip_address TEXT DEFAULT NULL,
|
| 466 |
+
session_uuid TEXT DEFAULT NULL,
|
| 467 |
+
created_at TEXT NOT NULL
|
| 468 |
+
)
|
| 469 |
+
""")
|
| 470 |
+
conn.execute("CREATE INDEX IF NOT EXISTS idx_logs_user ON user_logs(user_id)")
|
| 471 |
+
conn.execute("CREATE INDEX IF NOT EXISTS idx_logs_time ON user_logs(created_at)")
|
| 472 |
+
except Exception:
|
| 473 |
+
pass
|
| 474 |
+
|
| 475 |
+
|
| 476 |
+
# ββ Password Reset OTP ββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 477 |
+
|
| 478 |
+
def save_otp(user_id: int, email: str, otp_hash: str, expires_at: str) -> None:
|
| 479 |
+
"""Save a new OTP for password reset. Invalidates any previous OTPs."""
|
| 480 |
+
now = _now()
|
| 481 |
+
with get_conn() as conn:
|
| 482 |
+
# Invalidate old OTPs for this user
|
| 483 |
+
conn.execute("UPDATE password_reset_otps SET used=1 WHERE user_id=?", (user_id,))
|
| 484 |
+
conn.execute(
|
| 485 |
+
"INSERT INTO password_reset_otps (user_id, email, otp_hash, expires_at, used, created_at) "
|
| 486 |
+
"VALUES (?,?,?,?,0,?)",
|
| 487 |
+
(user_id, email, otp_hash, expires_at, now)
|
| 488 |
+
)
|
| 489 |
+
|
| 490 |
+
|
| 491 |
+
def get_valid_otp(email: str) -> dict | None:
|
| 492 |
+
"""Get the latest unused, unexpired OTP for an email."""
|
| 493 |
+
from datetime import datetime, timezone
|
| 494 |
+
now = datetime.now(timezone.utc).isoformat()
|
| 495 |
+
with get_conn() as conn:
|
| 496 |
+
row = conn.execute(
|
| 497 |
+
"SELECT * FROM password_reset_otps "
|
| 498 |
+
"WHERE email=? AND used=0 AND expires_at > ? "
|
| 499 |
+
"ORDER BY id DESC LIMIT 1",
|
| 500 |
+
(email.lower(), now)
|
| 501 |
+
).fetchone()
|
| 502 |
+
return dict(row) if row else None
|
| 503 |
+
|
| 504 |
+
|
| 505 |
+
def mark_otp_used(otp_id: int) -> None:
|
| 506 |
+
with get_conn() as conn:
|
| 507 |
+
conn.execute("UPDATE password_reset_otps SET used=1 WHERE id=?", (otp_id,))
|
| 508 |
+
|
| 509 |
+
|
| 510 |
+
def update_user_password(user_id: int, new_hash: str) -> None:
|
| 511 |
+
with get_conn() as conn:
|
| 512 |
+
conn.execute("UPDATE users SET password_hash=? WHERE id=?", (new_hash, user_id))
|
| 513 |
+
|
| 514 |
+
|
| 515 |
+
def migrate_add_otp_table() -> None:
|
| 516 |
+
"""Safe migration β adds OTP table to existing databases."""
|
| 517 |
+
try:
|
| 518 |
+
with get_conn() as conn:
|
| 519 |
+
conn.execute("""
|
| 520 |
+
CREATE TABLE IF NOT EXISTS password_reset_otps (
|
| 521 |
+
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
| 522 |
+
user_id INTEGER NOT NULL REFERENCES users(id),
|
| 523 |
+
email TEXT NOT NULL,
|
| 524 |
+
otp_hash TEXT NOT NULL,
|
| 525 |
+
expires_at TEXT NOT NULL,
|
| 526 |
+
used INTEGER NOT NULL DEFAULT 0,
|
| 527 |
+
created_at TEXT NOT NULL
|
| 528 |
+
)
|
| 529 |
+
""")
|
| 530 |
+
except Exception:
|
| 531 |
+
pass
|
api/email_utils.py
ADDED
|
@@ -0,0 +1,139 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
NeuroCheck β Email Utility
|
| 3 |
+
Sends OTP emails for password reset via SMTP.
|
| 4 |
+
|
| 5 |
+
Supported providers (set via environment variables):
|
| 6 |
+
|
| 7 |
+
Option A β Brevo (recommended, free 300 emails/day):
|
| 8 |
+
SMTP_EMAIL = your@email.com
|
| 9 |
+
SMTP_PASSWORD = your Brevo SMTP key
|
| 10 |
+
SMTP_HOST = smtp-relay.brevo.com
|
| 11 |
+
SMTP_PORT = 587
|
| 12 |
+
|
| 13 |
+
Option B β Gmail (requires App Password):
|
| 14 |
+
SMTP_EMAIL = yourname@gmail.com
|
| 15 |
+
SMTP_PASSWORD = 16-char app password
|
| 16 |
+
SMTP_HOST = smtp.gmail.com (default)
|
| 17 |
+
SMTP_PORT = 587 (default)
|
| 18 |
+
|
| 19 |
+
Option C β Any SMTP provider:
|
| 20 |
+
Set SMTP_HOST, SMTP_PORT, SMTP_EMAIL, SMTP_PASSWORD accordingly
|
| 21 |
+
|
| 22 |
+
If SMTP not configured: OTP is returned in API response (dev mode).
|
| 23 |
+
"""
|
| 24 |
+
from __future__ import annotations
|
| 25 |
+
import os
|
| 26 |
+
import smtplib
|
| 27 |
+
import random
|
| 28 |
+
import string
|
| 29 |
+
import hashlib
|
| 30 |
+
from datetime import datetime, timedelta, timezone
|
| 31 |
+
from email.mime.text import MIMEText
|
| 32 |
+
from email.mime.multipart import MIMEMultipart
|
| 33 |
+
from loguru import logger
|
| 34 |
+
|
| 35 |
+
SMTP_EMAIL = os.environ.get("SMTP_EMAIL", "")
|
| 36 |
+
SMTP_PASSWORD = os.environ.get("SMTP_PASSWORD", "")
|
| 37 |
+
SMTP_HOST = os.environ.get("SMTP_HOST", "smtp.gmail.com")
|
| 38 |
+
SMTP_PORT = int(os.environ.get("SMTP_PORT", "587"))
|
| 39 |
+
OTP_EXPIRY_MINUTES = 15
|
| 40 |
+
|
| 41 |
+
|
| 42 |
+
def generate_otp(length: int = 6) -> str:
|
| 43 |
+
"""Generate a 6-digit numeric OTP."""
|
| 44 |
+
return "".join(random.choices(string.digits, k=length))
|
| 45 |
+
|
| 46 |
+
|
| 47 |
+
def hash_otp(otp: str) -> str:
|
| 48 |
+
"""Hash the OTP before storing (SHA-256)."""
|
| 49 |
+
return hashlib.sha256(otp.encode()).hexdigest()
|
| 50 |
+
|
| 51 |
+
|
| 52 |
+
def verify_otp(plain_otp: str, stored_hash: str) -> bool:
|
| 53 |
+
"""Check if plain OTP matches stored hash."""
|
| 54 |
+
return hash_otp(plain_otp) == stored_hash
|
| 55 |
+
|
| 56 |
+
|
| 57 |
+
def otp_expiry() -> str:
|
| 58 |
+
"""Return UTC expiry timestamp (15 minutes from now)."""
|
| 59 |
+
return (datetime.now(timezone.utc) + timedelta(minutes=OTP_EXPIRY_MINUTES)).isoformat()
|
| 60 |
+
|
| 61 |
+
|
| 62 |
+
def send_otp_email(to_email: str, username: str, otp: str) -> bool:
|
| 63 |
+
"""
|
| 64 |
+
Send OTP email via Gmail SMTP.
|
| 65 |
+
Returns True on success, False on failure.
|
| 66 |
+
"""
|
| 67 |
+
if not SMTP_EMAIL or not SMTP_PASSWORD:
|
| 68 |
+
logger.warning("[Email] SMTP_EMAIL or SMTP_PASSWORD not set. Cannot send email.")
|
| 69 |
+
return False
|
| 70 |
+
|
| 71 |
+
subject = "NeuroCheck β Password Reset Code"
|
| 72 |
+
html_body = f"""
|
| 73 |
+
<div style="font-family:'Helvetica Neue',Arial,sans-serif;max-width:480px;margin:0 auto;padding:32px;">
|
| 74 |
+
<div style="background:#0B1F3A;border-radius:12px;padding:24px;text-align:center;margin-bottom:24px;">
|
| 75 |
+
<div style="background:#0A7B74;width:48px;height:48px;border-radius:10px;display:inline-flex;
|
| 76 |
+
align-items:center;justify-content:center;font-size:22px;font-weight:700;
|
| 77 |
+
color:#fff;font-family:serif;margin-bottom:12px;">NC</div>
|
| 78 |
+
<h1 style="color:#fff;font-size:20px;margin:0;font-family:'Georgia',serif;">NeuroCheck AI</h1>
|
| 79 |
+
<p style="color:#8FA8BF;font-size:13px;margin:4px 0 0;">MS Clinical Assistant</p>
|
| 80 |
+
</div>
|
| 81 |
+
|
| 82 |
+
<h2 style="color:#0B1F3A;font-size:18px;margin-bottom:8px;">Password Reset Request</h2>
|
| 83 |
+
<p style="color:#6B6056;font-size:14px;line-height:1.7;">
|
| 84 |
+
Hello <strong>{username}</strong>, we received a request to reset your NeuroCheck password.
|
| 85 |
+
Use the code below to proceed:
|
| 86 |
+
</p>
|
| 87 |
+
|
| 88 |
+
<div style="background:#F5F1EB;border:1px solid #DDD8CF;border-radius:12px;
|
| 89 |
+
padding:24px;text-align:center;margin:24px 0;">
|
| 90 |
+
<div style="font-size:36px;font-weight:700;letter-spacing:12px;color:#0B1F3A;
|
| 91 |
+
font-family:'Courier New',monospace;">{otp}</div>
|
| 92 |
+
<p style="color:#6B6056;font-size:12px;margin:10px 0 0;">
|
| 93 |
+
This code expires in <strong>{OTP_EXPIRY_MINUTES} minutes</strong>
|
| 94 |
+
</p>
|
| 95 |
+
</div>
|
| 96 |
+
|
| 97 |
+
<p style="color:#6B6056;font-size:13px;line-height:1.7;">
|
| 98 |
+
If you didn't request this, you can safely ignore this email.
|
| 99 |
+
Your password will not be changed.
|
| 100 |
+
</p>
|
| 101 |
+
|
| 102 |
+
<hr style="border:none;border-top:1px solid #DDD8CF;margin:24px 0;">
|
| 103 |
+
<p style="color:#B0A898;font-size:11px;text-align:center;">
|
| 104 |
+
NeuroCheck AI β MS Clinical Decision Support<br>
|
| 105 |
+
Built by Dr. Avasarala (UKY) & Dr. Kadambari (NITW)
|
| 106 |
+
</p>
|
| 107 |
+
</div>
|
| 108 |
+
"""
|
| 109 |
+
|
| 110 |
+
msg = MIMEMultipart("alternative")
|
| 111 |
+
msg["Subject"] = subject
|
| 112 |
+
msg["From"] = f"NeuroCheck AI <{SMTP_EMAIL}>"
|
| 113 |
+
msg["To"] = to_email
|
| 114 |
+
msg.attach(MIMEText(html_body, "html"))
|
| 115 |
+
|
| 116 |
+
try:
|
| 117 |
+
logger.info("[Email] Connecting to {}:{}", SMTP_HOST, SMTP_PORT)
|
| 118 |
+
with smtplib.SMTP(SMTP_HOST, SMTP_PORT, timeout=15) as server:
|
| 119 |
+
server.set_debuglevel(0)
|
| 120 |
+
server.ehlo()
|
| 121 |
+
server.starttls()
|
| 122 |
+
server.ehlo()
|
| 123 |
+
logger.info("[Email] Logging in as {}", SMTP_EMAIL)
|
| 124 |
+
server.login(SMTP_EMAIL, SMTP_PASSWORD)
|
| 125 |
+
server.sendmail(SMTP_EMAIL, to_email, msg.as_string())
|
| 126 |
+
logger.info("[Email] OTP sent successfully to {}", to_email)
|
| 127 |
+
return True
|
| 128 |
+
except smtplib.SMTPAuthenticationError as e:
|
| 129 |
+
logger.error("[Email] AUTH FAILED β wrong email/password or App Password not set. Error: {}", e)
|
| 130 |
+
return False
|
| 131 |
+
except smtplib.SMTPConnectError as e:
|
| 132 |
+
logger.error("[Email] CONNECTION FAILED to {}:{} β {}", SMTP_HOST, SMTP_PORT, e)
|
| 133 |
+
return False
|
| 134 |
+
except smtplib.SMTPException as e:
|
| 135 |
+
logger.error("[Email] SMTP error: {}", e)
|
| 136 |
+
return False
|
| 137 |
+
except Exception as e:
|
| 138 |
+
logger.error("[Email] Unexpected error sending to {}: {}", to_email, e)
|
| 139 |
+
return False
|
api/main.py
ADDED
|
@@ -0,0 +1,1534 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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ENCY β HIGH β MODERATE β WATCH β LOW
|
| 9 |
+
|
| 10 |
+
Validated: 150 cases Β· 15 internet sources Β· PMC 2024 Β· NINDS Β· MSAA
|
| 11 |
+
NHS Β· Mayo Β· StatPearls Β· Cureus Β· Frontiers Β· Merck Manual 2024
|
| 12 |
+
|
| 13 |
+
Domain Expert: Dr. Avasarala, MD PhD, UKY, Lexington KY USA
|
| 14 |
+
Lead AI Architect : Raghu Gangolu, NITW, Telangana India
|
| 15 |
+
Principal investigator : Dr. Kadambari, PhD, NITW, Telangana India
|
| 16 |
+
|
| 17 |
+
Clinical Decision Support Only β Not a diagnosis.
|
| 18 |
+
"""
|
| 19 |
+
from __future__ import annotations
|
| 20 |
+
import re, os
|
| 21 |
+
from typing import List, Dict, Optional
|
| 22 |
+
from contextlib import asynccontextmanager
|
| 23 |
+
|
| 24 |
+
import spacy
|
| 25 |
+
from negspacy.termsets import termset
|
| 26 |
+
from negspacy.negation import Negex # noqa: F401 β registers 'negex' factory
|
| 27 |
+
from fastapi import FastAPI, HTTPException, Request, Depends
|
| 28 |
+
from fastapi.middleware.cors import CORSMiddleware
|
| 29 |
+
from fastapi.staticfiles import StaticFiles
|
| 30 |
+
from fastapi.responses import FileResponse
|
| 31 |
+
from pydantic import BaseModel, Field
|
| 32 |
+
from loguru import logger
|
| 33 |
+
from slowapi import Limiter, _rate_limit_exceeded_handler
|
| 34 |
+
from slowapi.util import get_remote_address
|
| 35 |
+
from slowapi.errors import RateLimitExceeded
|
| 36 |
+
|
| 37 |
+
# ββ Rate limiter ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 38 |
+
limiter = Limiter(key_func=get_remote_address)
|
| 39 |
+
|
| 40 |
+
# ββ Global NLP pipeline (stored on app.state) βββββββββββββββββββββββββββββββββ
|
| 41 |
+
nlp = None
|
| 42 |
+
|
| 43 |
+
|
| 44 |
+
@asynccontextmanager
|
| 45 |
+
async def lifespan(app: FastAPI):
|
| 46 |
+
global nlp
|
| 47 |
+
model_path = os.environ.get("SPACY_MODEL", "en_model")
|
| 48 |
+
nlp = spacy.load(model_path)
|
| 49 |
+
ts = termset("en_clinical")
|
| 50 |
+
ts.add_patterns({
|
| 51 |
+
"preceding_negations": [
|
| 52 |
+
"negative for", "cleared of", "denies any", "no history of",
|
| 53 |
+
"do not have", "does not have", "no evidence of", "without",
|
| 54 |
+
"denies", "rules out", "not had", "not having", "never had",
|
| 55 |
+
"excluded", "has been excluded", "has not had",
|
| 56 |
+
],
|
| 57 |
+
"following_negations": [
|
| 58 |
+
"ruled out by", "ruled out", "is absent",
|
| 59 |
+
"is negative", "has been excluded",
|
| 60 |
+
],
|
| 61 |
+
"pseudo_negations": ["might not be", "not entirely sure", "not certain"],
|
| 62 |
+
})
|
| 63 |
+
nlp.add_pipe("negex", config={"ent_types": ["SYMPTOM"], "neg_termset": ts.get_patterns()})
|
| 64 |
+
app.state.nlp = nlp
|
| 65 |
+
logger.info("[AxonIQ] spaCy model loaded: {}", model_path)
|
| 66 |
+
|
| 67 |
+
# Init persistent database
|
| 68 |
+
from api.database import init_db, migrate_add_admin_column, set_admin, get_user_by_username, DB_PATH
|
| 69 |
+
init_db()
|
| 70 |
+
migrate_add_admin_column()
|
| 71 |
+
from api.database import migrate_add_logs_table, migrate_add_otp_table
|
| 72 |
+
migrate_add_logs_table()
|
| 73 |
+
migrate_add_otp_table()
|
| 74 |
+
# Log exact DB path so we can verify persistent storage is mounted
|
| 75 |
+
logger.info("[AxonIQ] SQLite database initialized at: {}", str(DB_PATH))
|
| 76 |
+
logger.info("[AxonIQ] DB exists on disk: {}", DB_PATH.exists())
|
| 77 |
+
logger.info("[AxonIQ] /data mounted: {}", __import__("pathlib").Path("/data").exists())
|
| 78 |
+
# Auto-grant admin to ADMIN_USERNAME env var if set
|
| 79 |
+
admin_user = os.environ.get("ADMIN_USERNAME", "")
|
| 80 |
+
if admin_user:
|
| 81 |
+
u = get_user_by_username(admin_user)
|
| 82 |
+
if u and not u.get("is_admin"):
|
| 83 |
+
set_admin(admin_user, True)
|
| 84 |
+
logger.info("[AxonIQ] Admin access granted to '{}'", admin_user)
|
| 85 |
+
|
| 86 |
+
# Build RAG knowledge base (runs once, persists to disk)
|
| 87 |
+
try:
|
| 88 |
+
from api.rag import build_knowledge_base
|
| 89 |
+
build_knowledge_base()
|
| 90 |
+
except Exception as e:
|
| 91 |
+
logger.warning("[RAG] Could not build knowledge base: {}", e)
|
| 92 |
+
|
| 93 |
+
yield
|
| 94 |
+
logger.info("[AxonIQ] Shutting down.")
|
| 95 |
+
|
| 96 |
+
|
| 97 |
+
app = FastAPI(
|
| 98 |
+
title="AxonIQ MS Classifier + Agentic AI",
|
| 99 |
+
version="9.0.0",
|
| 100 |
+
description=(
|
| 101 |
+
"MS Symptom Classifier + Agentic AI β 150-case validated. "
|
| 102 |
+
"Clinical decision support only. Not a diagnosis."
|
| 103 |
+
),
|
| 104 |
+
lifespan=lifespan,
|
| 105 |
+
)
|
| 106 |
+
|
| 107 |
+
app.state.limiter = limiter
|
| 108 |
+
app.add_exception_handler(RateLimitExceeded, _rate_limit_exceeded_handler)
|
| 109 |
+
|
| 110 |
+
app.add_middleware(
|
| 111 |
+
CORSMiddleware,
|
| 112 |
+
allow_origins=["*"],
|
| 113 |
+
allow_methods=["POST", "GET", "DELETE", "OPTIONS"],
|
| 114 |
+
allow_headers=["*"],
|
| 115 |
+
)
|
| 116 |
+
|
| 117 |
+
# ββ Auth router ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 118 |
+
from api.auth import router as auth_router
|
| 119 |
+
app.include_router(auth_router)
|
| 120 |
+
|
| 121 |
+
|
| 122 |
+
# ββ Pydantic schemas βββββββββββββββββββββββββββββββββββββββββββββββοΏ½οΏ½οΏ½ββββββββββ
|
| 123 |
+
class SymptomRequest(BaseModel):
|
| 124 |
+
text: str = Field(..., min_length=5, max_length=3000)
|
| 125 |
+
|
| 126 |
+
|
| 127 |
+
class ChatRequest(BaseModel):
|
| 128 |
+
message: str = Field(..., min_length=1, max_length=3000)
|
| 129 |
+
session_id: Optional[str] = None
|
| 130 |
+
user_id: Optional[int] = None # set server-side from JWT
|
| 131 |
+
|
| 132 |
+
|
| 133 |
+
class ChatResponse(BaseModel):
|
| 134 |
+
session_id: str
|
| 135 |
+
response: str
|
| 136 |
+
turn: int
|
| 137 |
+
|
| 138 |
+
|
| 139 |
+
class FeatureFound(BaseModel):
|
| 140 |
+
key: str
|
| 141 |
+
label: str
|
| 142 |
+
priority: str # "standard" | "low"
|
| 143 |
+
|
| 144 |
+
|
| 145 |
+
class ClassifyResponse(BaseModel):
|
| 146 |
+
tier: str
|
| 147 |
+
tier_label: str
|
| 148 |
+
tier_subtitle: str
|
| 149 |
+
action: str
|
| 150 |
+
workup: List[str]
|
| 151 |
+
features: List[FeatureFound]
|
| 152 |
+
temporal_notes: List[str]
|
| 153 |
+
disclaimer: str = (
|
| 154 |
+
"Clinical Decision Support Only β Not a diagnosis. "
|
| 155 |
+
"All outputs must be reviewed by a qualified clinician."
|
| 156 |
+
)
|
| 157 |
+
|
| 158 |
+
|
| 159 |
+
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 160 |
+
# EMERGENCY FLAGS (bypass scoring β fire immediately)
|
| 161 |
+
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 162 |
+
EMERGENCY_FLAGS: Dict[str, dict] = {
|
| 163 |
+
"stroke_suspected": {
|
| 164 |
+
"patterns": [r"(sudden|woke up).{0,20}(face droop|arm weak|slurred speech)"],
|
| 165 |
+
"label": "Possible Acute Stroke",
|
| 166 |
+
"action": "Call emergency services immediately (999 / 911). Do not wait β time is critical.",
|
| 167 |
+
},
|
| 168 |
+
"meningitis_suspected": {
|
| 169 |
+
"patterns": [
|
| 170 |
+
r"(fever|high temp).{0,30}(neck).{0,20}(stiff|rigid|pain)",
|
| 171 |
+
r"photophobia.{0,20}fever",
|
| 172 |
+
],
|
| 173 |
+
"label": "Possible Meningitis / Encephalitis",
|
| 174 |
+
"action": "Seek emergency care immediately. Meningitis is life-threatening.",
|
| 175 |
+
},
|
| 176 |
+
"hemorrhage_suspected": {
|
| 177 |
+
"patterns": [r"(sudden|worst).{0,20}(headache).{0,20}(life|ever|thunderclap)"],
|
| 178 |
+
"label": "Possible Subarachnoid Haemorrhage",
|
| 179 |
+
"action": "Call emergency services immediately. Thunderclap headache requires emergency evaluation.",
|
| 180 |
+
},
|
| 181 |
+
"gbs_suspected": {
|
| 182 |
+
"patterns": [
|
| 183 |
+
r"(both legs|feet).{0,30}(weak|paralyzed).{0,30}(moving up|spreading up|hands)",
|
| 184 |
+
r"ascending paralysis",
|
| 185 |
+
r"weakness.{0,30}(spreading|moving up).{0,20}(arm|hand)",
|
| 186 |
+
],
|
| 187 |
+
"label": "Possible Guillain-BarrΓ© Syndrome",
|
| 188 |
+
"action": "Seek emergency care immediately. Ascending weakness requires urgent neurological assessment.",
|
| 189 |
+
},
|
| 190 |
+
}
|
| 191 |
+
|
| 192 |
+
|
| 193 |
+
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 194 |
+
# ANCHOR FEATURES
|
| 195 |
+
# Any anchor hit β₯ 3 pts β HIGH regardless of total score
|
| 196 |
+
# Updated v8.1: added paroxysmal_ms, tonic_spasms_ms, tumefactive_ms,
|
| 197 |
+
# lhermittes_variant, sensory_idioms, limb_numbness
|
| 198 |
+
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 199 |
+
ANCHOR_FEATURES = {
|
| 200 |
+
# ββ Visual / optic ββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 201 |
+
"lhermittes_sign",
|
| 202 |
+
"lhermittes_variant",
|
| 203 |
+
"uhthoff_phenomenon",
|
| 204 |
+
"pain_on_eye_movement",
|
| 205 |
+
"monocular_vision_loss",
|
| 206 |
+
"ino_features",
|
| 207 |
+
"ms_hug",
|
| 208 |
+
"oscillopsia",
|
| 209 |
+
"bilateral_vision_loss",
|
| 210 |
+
"diplopia",
|
| 211 |
+
# ββ Brainstem / TN ββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 212 |
+
"paroxysmal_tn_young",
|
| 213 |
+
"area_postrema",
|
| 214 |
+
# ββ Spinal / sensory ββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 215 |
+
"sensory_idioms",
|
| 216 |
+
"limb_numbness",
|
| 217 |
+
# ββ Ocular / IIH overlap ββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 218 |
+
"optic_neuritis_idioms",
|
| 219 |
+
"obesity_disc_flag",
|
| 220 |
+
# ββ History / DIT βββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 221 |
+
"prior_cis_episode",
|
| 222 |
+
# ββ Vestibular βββββββββββββββββββββββββββββββββββββββββββββββββββββββοΏ½οΏ½ββββ
|
| 223 |
+
"vertigo_ms",
|
| 224 |
+
# ββ Paroxysmal / rare (v8.1) ββββββββββββββββββββββββββββββββββββββββββββββ
|
| 225 |
+
"paroxysmal_ms",
|
| 226 |
+
"tonic_spasms_ms",
|
| 227 |
+
"tumefactive_ms",
|
| 228 |
+
}
|
| 229 |
+
|
| 230 |
+
|
| 231 |
+
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 232 |
+
# TIER 1 + 2: SYMPTOM PATTERNS (3.0 pts each Γ severity multiplier)
|
| 233 |
+
# v8.1: 17 new categories added from 150-case internet testing
|
| 234 |
+
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 235 |
+
SYMPTOM_PATTERNS: Dict[str, List[tuple]] = {
|
| 236 |
+
|
| 237 |
+
# ββ ANCHOR: Lhermitte's sign ββββββββββββββββββββββββββββββββββββββββββββββ
|
| 238 |
+
"lhermittes_sign": [
|
| 239 |
+
(r"electric.{0,20}(shock|jolt|current|zap).{0,30}spine", "Lhermitte's sign β electric shock down spine"),
|
| 240 |
+
(r"(shock|jolt|current|zap).{0,30}(when|if|on).{0,20}(bend|bow|look|flex|tilt).{0,20}(neck|head|chin|down)", "Shock on neck bending"),
|
| 241 |
+
(r"(sharp|sudden).{0,20}(electric|zap|jolt|current).{0,20}(run|shoot|travel).{0,30}(spine|leg|back)", "Lhermitte-type electric sensation"),
|
| 242 |
+
(r"\blhermitte.{0,20}(sign|phenomenon|symptom)\b", "Lhermitte's sign (clinical)"),
|
| 243 |
+
],
|
| 244 |
+
|
| 245 |
+
# ββ ANCHOR: Lhermitte variant (cough/sneeze trigger) β v8.1 βββββββββββββ
|
| 246 |
+
"lhermittes_variant": [
|
| 247 |
+
(r"(shock|jolt|electric).{0,20}(cough|coughing|sneeze|sneezing|limb movement)", "Lhermitte variant β cough/sneeze trigger"),
|
| 248 |
+
(r"\blhermitte.{0,20}(cough|movement|limb|trigger|variant)\b", "Lhermitte variant trigger"),
|
| 249 |
+
],
|
| 250 |
+
|
| 251 |
+
# ββ ANCHOR: Uhthoff's phenomenon βββββββββββββββββββββββββββββββββββββββββ
|
| 252 |
+
# v8.1: must have visual OR gait/balance component to distinguish from
|
| 253 |
+
# generic heat sensitivity (LP category)
|
| 254 |
+
"uhthoff_phenomenon": [
|
| 255 |
+
(r"(vision|sight|see|eyesight).{0,30}(blur|worse|bad|dim|grey|gray|dark).{0,30}(hot|heat|shower|bath|exercise|warm|fever)", "Uhthoff's β vision worse in heat"),
|
| 256 |
+
(r"(hot|heat|shower|bath|exercise|warm|fever).{0,30}(vision|sight|see|eyesight).{0,30}(blur|worse|bad|dim)", "Uhthoff's β heat worsens vision"),
|
| 257 |
+
(r"(shimmer|shimmers|obscur).{0,40}(hot shower|warm shower|shower|bath|exercise|heat|fever)", "Uhthoff's β shimmer in heat"),
|
| 258 |
+
(r"worsening.{0,20}(vision|balance|weakness|gait).{0,30}(exercise|warm|heat|hot|fever)", "Uhthoff's β visual/gait worsening in heat"),
|
| 259 |
+
(r"\buhthoff.{0,20}(phenomenon|sign|syndrome)\b", "Uhthoff's phenomenon (clinical)"),
|
| 260 |
+
(r"heat intolerance.{0,40}(gait|walk|stumbl|fall|vision)", "Uhthoff's β heat intolerance with visual/gait"),
|
| 261 |
+
],
|
| 262 |
+
|
| 263 |
+
# ββ ANCHOR: Pain on eye movement βββββββββββββββββββββββββββββββββββββββββ
|
| 264 |
+
"pain_on_eye_movement": [
|
| 265 |
+
(r"pain.{0,30}(mov|look).{0,15}eye", "Pain on eye movement"),
|
| 266 |
+
(r"(move|moving|turning|side.to.side).{0,20}(eye|eyes).{0,30}(pain|hurt|ache|sore|throb)", "Moving eyes causes pain"),
|
| 267 |
+
(r"(exacerbated|worse|painful).{0,30}(looking up|side.to.side|look.{0,5}side)", "Pain exacerbated by eye movement"),
|
| 268 |
+
(r"pain.{0,20}(eye.{0,10}movement|moving the eye)", "Pain on eye movement"),
|
| 269 |
+
(r"retrobulbar.{0,15}pain", "Retrobulbar pain (ON)"),
|
| 270 |
+
(r"(discomfort|pain).{0,20}(left eye|right eye|eye).{0,20}(worse|made worse|exacerbated)", "Discomfort worse with eye movements"),
|
| 271 |
+
],
|
| 272 |
+
|
| 273 |
+
# ββ ANCHOR: Monocular vision loss βββββββββββββββββββββββββββββββββββββββββ
|
| 274 |
+
"monocular_vision_loss": [
|
| 275 |
+
(r"(one|left|right|l-eye|r-eye) eye.{0,30}(blur|vision|dim|loss|blind)", "Monocular vision loss"),
|
| 276 |
+
(r"blurring in one eye", "Blurring in one eye"),
|
| 277 |
+
(r"(left|right).{0,5}eye.{0,20}(dimm|blur|dull|fad|fog|dim|vision|loss)", "One eye dimming / blurring"),
|
| 278 |
+
(r"vision.{0,20}(painful|pain).{0,20}(monocular|one eye)", "Painful monocular vision loss"),
|
| 279 |
+
(r"(monocular).{0,20}(vision loss|blind|dim|blur|visual|impairment)", "Monocular vision loss (clinical)"),
|
| 280 |
+
(r"unilateral.{0,20}(visual|vision).{0,20}(impairment|loss|deficit|blurr|acuity)", "Unilateral visual impairment"),
|
| 281 |
+
(r"(optic neuritis|optic nerve).{0,30}(vision|visual|acuity|pain)", "Optic neuritis (clinical)"),
|
| 282 |
+
],
|
| 283 |
+
|
| 284 |
+
# ββ Dyschromatopsia βββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 285 |
+
"dyschromatopsia": [
|
| 286 |
+
(r"(red|colour|color).{0,20}(fad|wash|dim|dull|less|pale|grey|gray|wrong|off|not bright|desatur|less vivid)", "Dyschromatopsia β colour fading"),
|
| 287 |
+
(r"(grey|gray|greyed|greyed out|less vibrant).{0,20}(eye|vision|right|left)", "Vision greyed out / less vibrant"),
|
| 288 |
+
(r"red.green color loss", "Red-green colour loss"),
|
| 289 |
+
(r"(fading|faded).{0,15}(color|colour)", "Faded colours"),
|
| 290 |
+
(r"colors (look|appear|seem).{0,20}(dull|washed|faded|wrong|off|different)", "Colours appear wrong"),
|
| 291 |
+
],
|
| 292 |
+
|
| 293 |
+
# ββ ANCHOR: INO / eye movement disorder ββββββββββββββββββββββββββββββββββ
|
| 294 |
+
# v8.1: word-boundary fix prevents 'ino' matching in 'coordination'
|
| 295 |
+
# v8.1: added lateral gaze palsy / sixth nerve palsy patterns
|
| 296 |
+
"ino_features": [
|
| 297 |
+
(r"(eye|eyes).{0,20}(jiggle|wobble|bounce|shake|jump).{0,20}(look|gaze|side)", "INO β eyes jiggle on gaze"),
|
| 298 |
+
(r"\b(adduction lag|internuclear ophthalmoplegia|ophthalmoplegia)\b", "Internuclear ophthalmoplegia"),
|
| 299 |
+
(r"cannot.{0,20}move.{0,20}(eye|eyes).{0,20}(nose|toward|nasal)", "INO β eye cannot adduct"),
|
| 300 |
+
(r"(eye|eyes).{0,10}(crooked|jiggly|nystagmus|wiggling|oscillating)", "Jiggly / crooked eyes (INO/nystagmus)"),
|
| 301 |
+
(r"(lateral gaze palsy|sixth nerve palsy|6th nerve palsy)", "Sixth nerve / lateral gaze palsy"),
|
| 302 |
+
(r"(eye|eyes).{0,20}(cannot|can.{0,5}not).{0,20}(move outward|abduct|lateral)", "Eye cannot abduct"),
|
| 303 |
+
(r"abduction (deficit|palsy|weakness)", "Abduction deficit (6th nerve)"),
|
| 304 |
+
],
|
| 305 |
+
|
| 306 |
+
# ββ ANCHOR: Oscillopsia βββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 307 |
+
"oscillopsia": [
|
| 308 |
+
(r"(room|world|everything|objects|things).{0,30}(wiggl|wobbl|bounc|shak|oscillat|vibrat|jump)", "Oscillopsia β room appears to wiggle"),
|
| 309 |
+
(r"world.{0,20}(split|splits)", "World splits on gaze"),
|
| 310 |
+
(r"object.{0,15}jump.{0,15}(focus|see|gaze)", "Objects jump when focusing"),
|
| 311 |
+
(r"vision.{0,20}(jump|jumpy|jiggly|shimmer)", "Jumpy / shimmery vision"),
|
| 312 |
+
(r"\b(opsoclonus|oscillopsia)\b", "Oscillopsia / opsoclonus (clinical)"),
|
| 313 |
+
],
|
| 314 |
+
|
| 315 |
+
# ββ ANCHOR: MS Hug ββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 316 |
+
"ms_hug": [
|
| 317 |
+
(r"(tight|squeezing|pressure|band|belt|corset|grip).{0,30}(chest|torso|stomach|abdomen|waist|rib|midsection|trunk|middle)", "MS hug β tight band around trunk"),
|
| 318 |
+
(r"(banding|girdle).{0,20}(sensation|feeling|pain).{0,20}(chest|abdomen|trunk|waist)", "Girdle / banding sensation"),
|
| 319 |
+
],
|
| 320 |
+
|
| 321 |
+
# ββ ANCHOR: Bilateral vision loss (NMOSD) ββββββββββββββββββββββββββββββββ
|
| 322 |
+
"bilateral_vision_loss": [
|
| 323 |
+
(r"(bilateral|both eyes).{0,30}(vision loss|blind|blur|dim|black|loss of sight)", "Bilateral vision loss"),
|
| 324 |
+
(r"(vision loss|blind|blur|dim|black|loss of sight).{0,30}(bilateral|both eyes)", "Bilateral vision loss"),
|
| 325 |
+
(r"(nlp|no light perception)", "No light perception (NLP)"),
|
| 326 |
+
(r"(bottom half|top half|altitudinal).{0,20}(gone|lost|blind|vision)", "Altitudinal vision loss"),
|
| 327 |
+
(r"both eyes.{0,20}(painful|pain)", "Both eyes painful (ADEM / NMO flag)"),
|
| 328 |
+
(r"(simultaneous).{0,30}vision loss", "Simultaneous bilateral vision loss"),
|
| 329 |
+
],
|
| 330 |
+
|
| 331 |
+
# Post-viral vision (ADEM flag)
|
| 332 |
+
"post_viral_vision": [
|
| 333 |
+
(r"(flu|illness|viral|flu-like).{0,30}(both eyes|bilateral|eye|vision)", "Post-viral vision loss (ADEM flag)"),
|
| 334 |
+
(r"(flu.like illness|viral illness).{0,40}(eye|vision|painful)", "Post-viral eye involvement"),
|
| 335 |
+
],
|
| 336 |
+
|
| 337 |
+
# ββ ANCHOR: Diplopia ββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 338 |
+
"diplopia": [
|
| 339 |
+
(r"double vision", "Double vision (diplopia)"),
|
| 340 |
+
(r"seeing double", "Seeing double"),
|
| 341 |
+
(r"diplopia", "Diplopia (clinical)"),
|
| 342 |
+
(r"(seeing|see).{0,10}two", "Seeing two images"),
|
| 343 |
+
(r"world.{0,20}split.{0,20}(left|right|look)", "World splits on gaze"),
|
| 344 |
+
(r"(eyes.{0,20}crooked|jiggly eyes)", "Crooked / jiggly eyes"),
|
| 345 |
+
(r"(eyes? pointing|eye pointing).{0,20}(wrong direction|wrong way|deviation)", "Eye pointing wrong direction"),
|
| 346 |
+
(r"binocular.{0,15}(diplopia|vision)", "Binocular diplopia"),
|
| 347 |
+
],
|
| 348 |
+
|
| 349 |
+
# ββ ANCHOR: Paroxysmal TN / facial pain ββββββββββββββββββββββββββββββββββ
|
| 350 |
+
"paroxysmal_tn_young": [
|
| 351 |
+
(r"electric shocks? in (jaw|face)", "Electric shock in jaw / face (TN)"),
|
| 352 |
+
(r"severe face pain", "Severe face pain (TN)"),
|
| 353 |
+
(r"trigeminal neuralgia", "Trigeminal neuralgia"),
|
| 354 |
+
(r"facial shock", "Facial shock"),
|
| 355 |
+
(r"(facial|face).{0,20}(numb|numbness|pain.{0,15}young|electric|stab|shock)", "Facial numbness / pain"),
|
| 356 |
+
(r"(face|jaw).{0,15}pain.{0,20}(cold wind|trigger|touch|brush)", "Trigger-evoked face pain (TN)"),
|
| 357 |
+
(r"(sharp facial|facial).{0,10}(pain|shock)", "Sharp facial pain"),
|
| 358 |
+
(r"(v1|v2|trigeminal).{0,20}(pain|numb|symptom)", "V1/V2 trigeminal pain"),
|
| 359 |
+
(r"on and off.{0,20}facial pain", "Paroxysmal facial pain"),
|
| 360 |
+
(r"(severe facial|severe face).{0,10}(pain|ache)", "Severe facial pain"),
|
| 361 |
+
(r"(face|facial).{0,15}(weakness|numb|numbness)", "Facial weakness / numbness"),
|
| 362 |
+
(r"(face|jaw|cheek).{0,20}pain.{0,30}(light touch|touch|trigger|cold|wind|brush)", "Light-touch triggered facial pain (TN)"),
|
| 363 |
+
(r"stabbing.{0,20}(face|jaw|cheek|facial|character)", "Stabbing facial pain"),
|
| 364 |
+
],
|
| 365 |
+
|
| 366 |
+
# ββ ANCHOR: Area postrema (NMO) βββββββββββββββββββββββββββββββββββββββββββ
|
| 367 |
+
"area_postrema": [
|
| 368 |
+
(r"intractable hiccups", "Intractable hiccups (area postrema)"),
|
| 369 |
+
(r"uncontrollable vomiting", "Uncontrollable vomiting"),
|
| 370 |
+
(r"hiccups and vomiting", "Hiccups and vomiting (NMO sign)"),
|
| 371 |
+
(r"nausea and vomiting", "Nausea and vomiting"),
|
| 372 |
+
(r"\barea postrema\b", "Area postrema syndrome (NMO)"),
|
| 373 |
+
],
|
| 374 |
+
|
| 375 |
+
# ββ ANCHOR: Vertigo / vestibular MS ββββββββββββββββββββββββββββββββββββββ
|
| 376 |
+
"vertigo_ms": [
|
| 377 |
+
(r"(vertigo|dizziness|dizzy).{0,30}(fall|balance|walk|gait)", "Vertigo with falls / gait problems"),
|
| 378 |
+
(r"(constant|persistent|abrupt|sudden).{0,15}(vertigo|dizziness)", "Constant or sudden-onset vertigo"),
|
| 379 |
+
(r"(increasingly frequent falls|progressively.{0,15}fall|frequent falls)", "Increasingly frequent falls"),
|
| 380 |
+
(r"(lost all equilibrium|loss of equilibrium|lost equilibrium)", "Loss of equilibrium"),
|
| 381 |
+
(r"(lightheadedness|lightheaded|light.headed).{0,30}(dizziness|balance|standing)", "Lightheadedness with balance difficulty"),
|
| 382 |
+
],
|
| 383 |
+
|
| 384 |
+
# ββ ANCHOR: Optic neuritis idioms βββββββββββββββββββββββββββββββββββββββββ
|
| 385 |
+
"optic_neuritis_idioms": [
|
| 386 |
+
(r"(dirty water|smudge|foggy|foggy vision|fog).{0,20}(eye|vision|see)", "ON β foggy / smudged vision"),
|
| 387 |
+
(r"(looking through|vision like).{0,20}(dirty|foggy|cloudy|smeared|smudge|mist|haze)", "ON β dirty / foggy vision"),
|
| 388 |
+
(r"(scotoma|central blur|central blurr|central loss|central vision)", "Scotoma / central vision loss"),
|
| 389 |
+
(r"(eye soreness|eye sore|sore eye|soreness behind the eye|eye ache|ache behind the eye)", "Eye soreness (ON)"),
|
| 390 |
+
(r"pulling sensation.{0,20}(behind|eye)", "Pulling sensation behind the eye"),
|
| 391 |
+
(r"(vision|visual).{0,20}(deficit|dimming)", "Visual deficit / dimming"),
|
| 392 |
+
(r"(blurring|blur).{0,20}one eye", "Blurring in one eye (ON)"),
|
| 393 |
+
(r"transient obscur", "Transient obscurations"),
|
| 394 |
+
(r"(washed out|less vibrant|world.{0,10}dim)", "Washed-out / dim vision"),
|
| 395 |
+
(r"(optic neuritis|optic nerve)", "Optic neuritis (clinical)"),
|
| 396 |
+
(r"(visual acuity|visual impairment|visual field).{0,30}(decreas|loss|reduced|impair|defect)", "Visual acuity / field loss"),
|
| 397 |
+
(r"(blurry vision|blurred vision|blurring of vision)", "Blurred vision"),
|
| 398 |
+
(r"\b(afferent pupillary defect|relative afferent)\b", "Afferent pupillary defect (RAPD)"),
|
| 399 |
+
],
|
| 400 |
+
|
| 401 |
+
# ββ ANCHOR: IIH / obesity / disc swelling ββββββββββββββββββββββββββββββββ
|
| 402 |
+
"obesity_disc_flag": [
|
| 403 |
+
(r"(disc swelling|papilledema|disc edema|swelling.{0,20}eye|swelling.{0,20}optic)", "Disc swelling (papilledema)"),
|
| 404 |
+
(r"(bilateral disc|disc.{0,10}swelling)", "Bilateral disc swelling"),
|
| 405 |
+
(r"(eyes.{0,20}abnormal|abnormal.{0,20}eye)", "Abnormal eye exam finding"),
|
| 406 |
+
(r"(heavy legs|heavy leg|legs feel heavy|leg heaviness).{0,30}(walk|walking|clinic|stand)", "Heavy legs (spinal cord flag)"),
|
| 407 |
+
(r"(\d{3}\s*kg|obese|high bmi|overweight|obesity)", "Obesity marker (IIH / MS overlap)"),
|
| 408 |
+
],
|
| 409 |
+
|
| 410 |
+
# ββ ANCHOR: Prior CIS / DIT βββββββββββββββββββββββββββββββββββββββββββββββ
|
| 411 |
+
"prior_cis_episode": [
|
| 412 |
+
(r"(years?|months?) ago.{0,40}(numb|weak|vision|tingling|balance).{0,60}(better|resolved|went away|recovered)", "Prior resolved neurological episode"),
|
| 413 |
+
(r"(episode|attack|event).{0,20}(numb|weakness|vision|tingling).{0,20}(resolved|recovered|cleared)", "Prior episode resolved"),
|
| 414 |
+
(r"(transient|tingling|numbness|numb).{0,40}(lasted|for one week|for a week|weeks?).{0,30}(ago|years? ago|last)", "Transient episode β DIT marker"),
|
| 415 |
+
(r"history of optic neuritis", "History of optic neuritis (DIT)"),
|
| 416 |
+
(r"(previous|prior|history of).{0,30}(episode|attack|relapse|event|numbness|tingling|weakness|vision)", "Prior neurological episode"),
|
| 417 |
+
(r"(spontaneously resolved|resolved spontaneously|went away on its own|resolved on its own)", "Spontaneous resolution (CIS pattern)"),
|
| 418 |
+
(r"clinically isolated syndrome|first (episode|attack|event|relapse)", "Clinically isolated syndrome"),
|
| 419 |
+
(r"(tingling|numbness|numb).{0,40}(last monsoon|last year|years? ago|months? ago)", "Prior monsoon / seasonal episode (DIT)"),
|
| 420 |
+
(r"monsoon.{0,40}(resolved|better|went away|numb|tingle)", "Monsoon-triggered episode resolved"),
|
| 421 |
+
(r"(episode|attack).{0,50}(numb|weak|tingling|vision).{0,50}(resolved|went away|got better|cleared)", "Prior episode resolved (flexible)"),
|
| 422 |
+
],
|
| 423 |
+
|
| 424 |
+
# ββ Standard: Cerebellar ataxia βββββββββββββββββββββββββββββββββββββββββββ
|
| 425 |
+
"cerebellar_ataxia": [
|
| 426 |
+
(r"(clumsiness|clumsy|dropping keys|drops things|cerebellar)", "Cerebellar clumsiness"),
|
| 427 |
+
(r"(steady|steady myself|off balance|balance problems|poor balance)", "Balance problems (cerebellar)"),
|
| 428 |
+
(r"(seasick|feels seasick|nausea.{0,20}walk|dizzy.{0,20}walk)", "Seasick feeling (cerebellar)"),
|
| 429 |
+
(r"swallowing difficulty", "Swallowing difficulty (brainstem)"),
|
| 430 |
+
(r"\b(dysdiadochokinesia|ataxia|coordination deficit)\b", "Ataxia / coordination deficit"),
|
| 431 |
+
(r"(impaired balance|loss of balance|balance impair|vestibular)", "Impaired balance"),
|
| 432 |
+
(r"(equilibrium|lost.{0,10}equilibrium|lost.{0,10}balance)", "Loss of equilibrium"),
|
| 433 |
+
(r"(heel.to.shin|finger.to.nose|tandem gait)", "Cerebellar examination findings"),
|
| 434 |
+
],
|
| 435 |
+
|
| 436 |
+
# ββ Standard: Motor weakness / grip ββββββββββββββββββββββββββββββββββββββ
|
| 437 |
+
"motor_weakness_grip": [
|
| 438 |
+
(r"(weak|lose|loss of|give out|clumsy).{0,20}(grip|grasp|hand|power|oomph|button|zip)", "Weak grip / clumsy hands"),
|
| 439 |
+
(r"(drop|dropping).{0,20}(cup|keys|things|mug|bottle)", "Dropping objects"),
|
| 440 |
+
(r"(typing errors|typos|handwriting|script)|(buttoning trouble|loss of oomph)", "Fine motor deficit"),
|
| 441 |
+
(r"(hand|arm|upper extremity|upper limb).{0,20}(weakness|weak|paresis|paresthesia)", "Upper extremity weakness"),
|
| 442 |
+
(r"(decreased|reduced).{0,20}(dexterity|grip|coordination|finger)", "Decreased dexterity"),
|
| 443 |
+
(r"\b(tremor|tremors|intention tremor|action tremor)\b", "Tremor"),
|
| 444 |
+
(r"\b(hemiparesis|paraparesis|monoparesis|quadriparesis)\b", "Paresis / paralysis"),
|
| 445 |
+
(r"(hyperreflexia|babinski.{0,10}(sign|positive)|extensor plantar)", "Upper motor neuron signs"),
|
| 446 |
+
(r"left lower limb weakness|right lower limb weakness|lower limb weakness", "Lower limb weakness"),
|
| 447 |
+
],
|
| 448 |
+
|
| 449 |
+
# ββ Standard: Gait ataxia βββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 450 |
+
"gait_ataxia": [
|
| 451 |
+
(r"(drunk|drunken|boat|seasick|stagger|lurch|veer|unsteady|balance|fall|leaner).{0,30}(walk|walking|gait|stand|pivot|staircase|hallway)", "Gait ataxia / unsteady walk"),
|
| 452 |
+
(r"(occasional falls|fall|tripping|trips).{0,20}(walk|balance|gait)", "Falls (gait / balance)"),
|
| 453 |
+
(r"(stumbling gait|stumbl.{0,10}gait|stumbl.{0,10}walk)", "Stumbling gait"),
|
| 454 |
+
(r"(gait disturbance|gait disorder|gait impairment|difficulty.{0,10}walk|difficulty.{0,10}ambul)", "Gait disturbance (clinical)"),
|
| 455 |
+
(r"(tendency to fall|multiple falls|several falls|bad falls|frequent falls)", "Tendency to fall"),
|
| 456 |
+
(r"(ambulation|ambulating|ambulatory).{0,20}(difficult|impaired|problem)", "Ambulation difficulty"),
|
| 457 |
+
(r"(increasingly frequent falls|progressively.{0,15}fall)", "Increasingly frequent falls"),
|
| 458 |
+
(r"(ataxic gait|ataxic walking)", "Ataxic gait"),
|
| 459 |
+
],
|
| 460 |
+
|
| 461 |
+
# ββ Standard: Spasticity βββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 462 |
+
"spasticity": [
|
| 463 |
+
(r"(spring.loaded|springy|twitch|jump|stiff|rigid|locked|cramp|spasm|board|glued).{0,20}(leg|feet|foot|muscle|calf|knee|finger|hand)", "Spasticity / stiffness"),
|
| 464 |
+
(r"(locked muscles|stiff fingers|stiff knee)", "Locked / stiff muscles"),
|
| 465 |
+
(r"\b(spasticity|hyperreflexia|hyperreflexic|extensor plantar|babinski|clonus)\b", "Spasticity (clinical)"),
|
| 466 |
+
(r"(increased tone|increased reflexes|brisk reflexes)", "Increased tone / reflexes"),
|
| 467 |
+
(r"spastic (quadriparesis|paraparesis|hemiparesis)", "Spastic paresis"),
|
| 468 |
+
(r"(muscle spasm|muscle cramp).{0,20}(ms|neurological|multiple sclerosis)", "MS-related muscle spasm"),
|
| 469 |
+
],
|
| 470 |
+
|
| 471 |
+
# ββ Standard: Tremor (v8.1 β separated from motor_weakness_grip) ββββββββ
|
| 472 |
+
"tremor_standard": [
|
| 473 |
+
(r"(uncontrollable shaking|uncontrollable trembling|tremor).{0,20}(arm|leg|head|hand|body)", "Uncontrollable tremor"),
|
| 474 |
+
(r"\b(intention tremor|action tremor|cerebellar tremor)\b", "Intention / cerebellar tremor"),
|
| 475 |
+
],
|
| 476 |
+
|
| 477 |
+
# ββ Standard: Foot drop βββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 478 |
+
"foot_drop": [
|
| 479 |
+
(r"(foot|toe|toes|feet).{0,20}(drag|dragging|drop|dropping|scuff|scrape)", "Foot drop"),
|
| 480 |
+
(r"toe dragging", "Toe dragging"),
|
| 481 |
+
(r"(lift|lifting).{0,15}(knee|foot).{0,20}(clear|foot|toe|floor|step)", "Lifting knee to clear foot (foot drop)"),
|
| 482 |
+
(r"foot drop|drop foot", "Foot drop (clinical)"),
|
| 483 |
+
],
|
| 484 |
+
|
| 485 |
+
# ββ ANCHOR: Limb numbness / paresthesia βββββββββββββββββββββββββββββββββββ
|
| 486 |
+
"limb_numbness": [
|
| 487 |
+
(r"(arm|leg|hand|foot|feet|finger|fingertip|thigh|shin|back|scalp|neck|cheek|face|ankle).{0,30}(numb|numbness|tingling|pins and needles)", "Limb / body numbness or tingling"),
|
| 488 |
+
(r"(numbness|numb|tingling).{0,30}(fingertip|finger|hand|arm|leg|ankle)", "Fingertip / limb numbness"),
|
| 489 |
+
(r"(tingling in|numbness in|numb in).{0,20}(extremities|arm|leg|hand|foot|body|side|face|ankle)", "Tingling / numbness in extremities"),
|
| 490 |
+
(r"\b(hemibody|hemi.body|hemisensory)\b.{0,30}(paresthesia|numb|weak|sensory)", "Hemibody paresthesia (MS relapse)"),
|
| 491 |
+
(r"\b(paresthesia|paresthesias|dysesthesia)\b.{0,20}(sensory|numb|tingle|sensation|deficit)", "Clinical paresthesia"),
|
| 492 |
+
(r"(altered sensation|sensory deficit|sensory loss|hemisensory)", "Sensory deficit (clinical)"),
|
| 493 |
+
(r"(paresthesia|tingling|numbness).{0,30}(ascend|ascending|spread|spreading).{0,30}(leg|limb|trunk|umbilicus|body)", "Ascending paresthesia (myelitis)"),
|
| 494 |
+
(r"(right.sided|left.sided).{0,20}(weakness|numbness|numb|paresthesia)", "Hemisensory / hemibody symptoms"),
|
| 495 |
+
(r"glove.{0,10}stocking.{0,10}(pattern|numbness|paresthesia)", "Glove-and-stocking pattern"),
|
| 496 |
+
(r"(radiation|radiating).{0,20}(numb|numbness|tingling|pain).{0,20}(ankle|leg|arm|foot|thigh|shin)", "Radiating numbness / tingling"),
|
| 497 |
+
],
|
| 498 |
+
|
| 499 |
+
# ββ ANCHOR: Sensory idioms / dysesthesia βββββββββββββββββββββββββββββββββ
|
| 500 |
+
"sensory_idioms": [
|
| 501 |
+
(r"(cold|water|ice|frozen).{0,20}(trickle|trickling|running|poured|pack)", "Cold water / ice sensation"),
|
| 502 |
+
(r"(twice its size|swollen|puffy).{0,30}(looks normal|looks fine|perfectly normal)", "Phantom swelling (dysesthesia)"),
|
| 503 |
+
(r"(hand|arm|leg|foot).{0,20}feels.{0,20}(twice|swollen|puffy|bigger).{0,30}(normal|fine)", "Phantom swelling"),
|
| 504 |
+
(r"(dead|wooden|block|dead feeling|completely dead).{0,20}(arm|leg|patch|skin|left arm|right arm)", "Dead / wooden sensation"),
|
| 505 |
+
(r"(completely dead|dead feeling|deadness).{0,20}(arm|leg|hand|foot)", "Dead limb sensation"),
|
| 506 |
+
(r"(left arm|right arm|arm|leg).{0,30}(completely dead|dead|wooden|numb)", "Arm / leg feels dead"),
|
| 507 |
+
(r"(arm|leg).{0,20}(feels|feel|is|are).{0,10}(completely dead|dead|wooden)", "Limb feels dead"),
|
| 508 |
+
(r"(hot coals|stinging needles|bee sting|stinging).{0,20}(feet|foot|sole|face|skin|soles)", "Hot coals / stinging sensation"),
|
| 509 |
+
(r"(walking on hot coals|feel like hot coals|feels like hot coals)", "Walking on hot coals"),
|
| 510 |
+
(r"soles.{0,30}(hot coals|needles|stinging|burning|fire)", "Burning soles"),
|
| 511 |
+
(r"(sandpaper).{0,20}(skin|rubbing|touch|wound|on a wound)", "Allodynia β sandpaper sensation"),
|
| 512 |
+
(r"(light touch|cotton|shirt).{0,30}(sandpaper|stinging|hurts|pain|painful|wound)", "Allodynia β light touch painful"),
|
| 513 |
+
(r"(cell phone|vibration).{0,20}(hip|bone|deep)", "Internal vibration (pallanaesthesia)"),
|
| 514 |
+
(r"(gloves|socks).{0,30}(muffled|numb|thick)", "Glove-and-stocking numbness"),
|
| 515 |
+
(r"(sloshy|wet).{0,20}(shoes|feet)", "Sloshy / wet sensation"),
|
| 516 |
+
(r"(ants|ant|insect|bug).{0,20}(crawl|crawling|creeping).{0,20}(scalp|neck|skin|face|arm|leg)", "Formication (ants crawling)"),
|
| 517 |
+
(r"(palm.sized|patch).{0,40}(wooden|numb)", "Specific numb patch"),
|
| 518 |
+
(r"felt.{0,10}(wooden|completely numb)", "Felt wooden / numb"),
|
| 519 |
+
],
|
| 520 |
+
|
| 521 |
+
# ββ Standard: Proprioception loss βββββββββββββββββββββββββββββββββββββββββ
|
| 522 |
+
"proprioception_loss": [
|
| 523 |
+
(r"(lose|loses|lost|where).{0,20}(feet|track of|dark|look down)", "Proprioception loss"),
|
| 524 |
+
(r"(walk.{0,15}dark|dark.{0,15}walk).{0,30}(look down|feet|where)", "Proprioception loss in dark"),
|
| 525 |
+
(r"vibratory sense.{0,20}(loss|impaired|decreased|reduced)", "Vibratory sense loss"),
|
| 526 |
+
(r"(position sense|proprioception).{0,20}(impaired|loss|reduced)", "Proprioception impaired (clinical)"),
|
| 527 |
+
],
|
| 528 |
+
|
| 529 |
+
# ββ Standard: Autonomic / bladder / bowel ββββββββββββββββββββββββοΏ½οΏ½βββββββ
|
| 530 |
+
"autonomic_ms": [
|
| 531 |
+
(r"(urinary urgency|bladder urgency|urge to urinate|urgency urination|frequency urination)", "Urinary urgency"),
|
| 532 |
+
(r"(bowel|bladder).{0,20}(problem|control|urgency|incontinence|dysfunction)", "Bladder / bowel dysfunction"),
|
| 533 |
+
(r"(urinary|urinating).{0,20}(problem|urgency|frequent|difficult)", "Urinary dysfunction"),
|
| 534 |
+
(r"(incontinence|incontinent|nocturia|multiple voids|voiding)", "Incontinence / nocturia"),
|
| 535 |
+
(r"(incomplete bladder|bladder emptying|urinary bladder)", "Incomplete bladder emptying"),
|
| 536 |
+
(r"\b(neurogenic bladder|neurogenic bowel)\b", "Neurogenic bladder / bowel"),
|
| 537 |
+
(r"(constipation|bowel.{0,20}(control|incontinence|problem)).{0,20}(ms|neurological|multiple sclerosis)", "MS-related bowel dysfunction"),
|
| 538 |
+
(r"(fecal incontinence|bowel incontinence|bowel leakage)", "Fecal / bowel incontinence"),
|
| 539 |
+
],
|
| 540 |
+
|
| 541 |
+
# ββ Standard: Visual mimic flags βββββββββββββββββββββββββββββββββββββββββ
|
| 542 |
+
"visual_mimic_flags": [
|
| 543 |
+
(r"(floater|floaters|dark spot|black spot|spot.{0,15}moves|moving spot)", "Floaters / dark spot (retinal flag)"),
|
| 544 |
+
(r"(red.{0,10}eye|red.{0,10}painful eye|painful.{0,10}red eye)", "Red painful eye (mimic flag)"),
|
| 545 |
+
(r"(flickering lights|flicker.{0,15}light|scintillating).{0,30}(20 min|min|lasts|aura)", "Flickering lights β migraine aura flag"),
|
| 546 |
+
(r"(chronic|progressive).{0,20}(vision loss|visual loss).{0,30}(1 year|year|months?)", "Chronic progressive vision loss β tumour flag"),
|
| 547 |
+
],
|
| 548 |
+
|
| 549 |
+
# ββ Standard: Cognitive / brain fog ββββββββββββββββββββββββββββββββββββββ
|
| 550 |
+
"cognitive_ms": [
|
| 551 |
+
(r"(brain|mind).{0,15}(fog|cloudy|slow|blank|mush)", "Brain fog"),
|
| 552 |
+
(r"(memory|remember).{0,20}(loss|lapse|bad|poor|failing|forget)", "Memory lapses"),
|
| 553 |
+
(r"(cognitive|concentration|attention).{0,20}(impair|problem|difficult|decline|deficit)", "Cognitive impairment (clinical)"),
|
| 554 |
+
(r"impaired.{0,10}(memory|short.term memory|recall)", "Impaired memory"),
|
| 555 |
+
(r"(word.{0,10}finding|anomia|forget.{0,10}words|lose.{0,10}words)", "Word-finding difficulty"),
|
| 556 |
+
(r"(slow.{0,10}processing|processing speed|slow.{0,10}thinking|thinking.{0,10}slow)", "Slowed cognitive processing"),
|
| 557 |
+
],
|
| 558 |
+
|
| 559 |
+
# ββ Standard: Fatigue βββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 560 |
+
"fatigue_ms": [
|
| 561 |
+
(r"(severe|extreme|debilitating|significant|profound|marked).{0,20}(fatigue|exhaustion|tiredness)", "Severe MS fatigue"),
|
| 562 |
+
(r"(fatigue|exhaustion).{0,20}(ms|multiple sclerosis|relapse|symptom)", "MS-associated fatigue"),
|
| 563 |
+
(r"(chronic fatigue|persistent fatigue|overwhelming fatigue|constant fatigue)", "Chronic / persistent fatigue"),
|
| 564 |
+
],
|
| 565 |
+
|
| 566 |
+
# ββ Standard: Dysarthria / dysphagia βββββββββββββββββββββββββββββββββββββ
|
| 567 |
+
"dysarthria_dysphagia": [
|
| 568 |
+
(r"(slurred speech|dysarthria|speech.{0,15}(slur|difficult|impaired))", "Dysarthria (slurred speech)"),
|
| 569 |
+
(r"(swallowing.{0,20}(difficult|problem|impaired)|dysphagia|aspirat)", "Dysphagia / aspiration"),
|
| 570 |
+
(r"(tongue.{0,15}(slow|weak|impaired)|difficulty speaking)", "Tongue / speech difficulty"),
|
| 571 |
+
],
|
| 572 |
+
|
| 573 |
+
# ββ Standard: Dysphagia isolated (v8.1) ββββββββββββββββββββββββββββββββββ
|
| 574 |
+
"dysphagia_ms": [
|
| 575 |
+
(r"(swallowing.{0,20}(difficult|problem|impaired|trouble)|dysphagia)", "Swallowing difficulty"),
|
| 576 |
+
(r"(food.{0,20}stuck.{0,20}throat|choking.{0,20}(eat|drink|swallow))", "Food stuck / choking"),
|
| 577 |
+
(r"(coughing.{0,20}(eat|drink|swallow)|aspiration)", "Aspiration / coughing when eating"),
|
| 578 |
+
],
|
| 579 |
+
|
| 580 |
+
# ββ Standard: Pseudobulbar affect ββββββββββββββββββββββββββββββββββββββββ
|
| 581 |
+
"pseudobulbar_affect": [
|
| 582 |
+
(r"(laugh|laughing|cry|crying|weep).{0,30}(uncontrollable|random|no reason|inappropriate)", "Pseudobulbar affect (PBA)"),
|
| 583 |
+
(r"\b(pseudobulbar|emotional lability)\b.{0,20}", "Pseudobulbar affect / emotional lability"),
|
| 584 |
+
],
|
| 585 |
+
|
| 586 |
+
# ββ Standard: Nocturnal spasms ββββββββββββββββββββββββββββββββββββββββββββ
|
| 587 |
+
# Note: RLS intentionally omitted here β stays in sleep_disturbance_ms (LP)
|
| 588 |
+
"nocturnal_spasms": [
|
| 589 |
+
(r"(spasm|cramp|stiff|jerk|kick).{0,30}(night|sleep|bed|nocturnal|waking)", "Nocturnal spasms / kicks"),
|
| 590 |
+
(r"(night kick|night kicks)", "Night kicks"),
|
| 591 |
+
],
|
| 592 |
+
|
| 593 |
+
# ββ Standard: Thermal dysesthesia ββββββββββββββββββββββββββββββββοΏ½οΏ½βββββββ
|
| 594 |
+
"thermal_dysesthesia": [
|
| 595 |
+
(r"(feet|legs|foot|soles).{0,20}(burn|fire|hot|hot coals|stinging|needles)", "Burning / hot feet / legs"),
|
| 596 |
+
],
|
| 597 |
+
|
| 598 |
+
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 599 |
+
# NEW IN v8.1 β Paroxysmal / Rare / Internet-sourced categories
|
| 600 |
+
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 601 |
+
|
| 602 |
+
# ββ ANCHOR: Paroxysmal MS symptoms ββββββββββββββββββββββββββββββββββββββββ
|
| 603 |
+
# Source: PMC 2024, Frontiers in Neurology, StatPearls
|
| 604 |
+
"paroxysmal_ms": [
|
| 605 |
+
(r"(paroxysmal).{0,30}(dysarthria|ataxia|diplopia|hemiparesis|sensory|symptom)", "Paroxysmal MS symptom"),
|
| 606 |
+
(r"(episodic|stereotyped|brief.{0,10}recurring).{0,20}(motor|sensory|speech|movement|neurological)", "Stereotyped recurring neurological episodes"),
|
| 607 |
+
(r"(dystonic|dystonia).{0,20}(episode|attack|spasm).{0,20}(ms|sclerosis|neurological)", "Dystonic episode (paroxysmal MS)"),
|
| 608 |
+
(r"(paroxysmal dysarthria|paroxysmal ataxia|paroxysmal hemiparesis|paroxysmal sensory)", "Paroxysmal dysarthria / ataxia / hemiparesis"),
|
| 609 |
+
(r"(paroxysmal.{0,20}(symptom|episode|attack)).{0,20}(ms|sclerosis|demyelinating)", "Paroxysmal MS episode"),
|
| 610 |
+
(r"(paroxysmal dystonia|paroxysmal posturing).{0,20}(ms|first|initial|manifestation)", "Paroxysmal dystonia β MS first sign"),
|
| 611 |
+
],
|
| 612 |
+
|
| 613 |
+
# ββ ANCHOR: Tonic spasms ββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 614 |
+
# Source: Frontiers 2024, PubMed, Cureus
|
| 615 |
+
"tonic_spasms_ms": [
|
| 616 |
+
(r"(tonic spasm|painful tonic|tonic seizure).{0,20}(ms|multiple sclerosis|episodic|brief|posture|limb)", "Tonic spasms in MS"),
|
| 617 |
+
(r"(involuntary.{0,20}(flexion|extension|posturing|tonic).{0,20}(ms|episodic|brief))", "Involuntary tonic posturing"),
|
| 618 |
+
(r"(painful.{0,15}stereotyped.{0,15}(episode|spasm|attack)|stereotyped.{0,15}painful.{0,15}episode)", "Painful stereotyped episodes"),
|
| 619 |
+
],
|
| 620 |
+
|
| 621 |
+
# ββ ANCHOR: Tumefactive MS ββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 622 |
+
# Source: Frontiers 2024, ScienceDirect
|
| 623 |
+
"tumefactive_ms": [
|
| 624 |
+
(r"(tumefactive|large lesion|mass effect).{0,20}(ms|multiple sclerosis|demyelinating)", "Tumefactive MS"),
|
| 625 |
+
(r"(rapid.{0,15}deterioration|progressive.{0,15}deterioration).{0,20}(ms|lesion|neurological)", "Rapid neurological deterioration"),
|
| 626 |
+
(r"ring.{0,10}enhancement.{0,20}(ms|lesion|gadolinium|mri)", "Ring-enhancing lesion (tumefactive)"),
|
| 627 |
+
(r"tumefactive multiple sclerosis", "Tumefactive multiple sclerosis"),
|
| 628 |
+
],
|
| 629 |
+
|
| 630 |
+
# ββ Standard: Paroxysmal pruritis βββββββββββββββββββββββββββββββββββββββββ
|
| 631 |
+
# Source: PMC 2020 review, Cureus case report
|
| 632 |
+
"paroxysmal_pruritis": [
|
| 633 |
+
(r"(paroxysmal|intense|episodic|sudden).{0,15}(itch|itching|pruritis|pruritus)", "Paroxysmal itching"),
|
| 634 |
+
(r"(intense itching|severe itching).{0,20}(dermatome|ms|neurological|skin|no.{0,10}rash)", "Intense dermatome itching"),
|
| 635 |
+
(r"itch.{0,30}(ms|multiple sclerosis|dermatome|neurological|spinal cord)", "Neurological pruritis in MS"),
|
| 636 |
+
],
|
| 637 |
+
|
| 638 |
+
# ββ Standard: Transverse myelitis ββββββββββββββββββββββββββββββββββββββββ
|
| 639 |
+
# Source: NINDS, StatPearls
|
| 640 |
+
"transverse_myelitis": [
|
| 641 |
+
(r"(transverse myelitis|myelitis|spinal cord.{0,20}(inflam|lesion|demyelinating))", "Transverse / spinal cord myelitis"),
|
| 642 |
+
(r"(acute myelitis|subacute myelitis|partial myelitis)", "Acute / partial myelitis"),
|
| 643 |
+
],
|
| 644 |
+
|
| 645 |
+
# ββ Standard: Cerebellar variant βββββββββββββββββββββββββββββββββββββββββ
|
| 646 |
+
# Source: StatPearls, WebMD
|
| 647 |
+
"cerebellar_ms": [
|
| 648 |
+
(r"\b(cerebellar.{0,20}(ataxia|tremor|variant|ms|lesion))\b", "Cerebellar MS variant"),
|
| 649 |
+
(r"(charcot triad|intention tremor.{0,20}nystagmus|nystagmus.{0,20}intention tremor)", "Charcot triad (cerebellar MS)"),
|
| 650 |
+
],
|
| 651 |
+
|
| 652 |
+
# ββ Standard: Gustatory / taste disturbance βββββββββββββββββββββββββββββββ
|
| 653 |
+
# Source: StatPearls, PMC
|
| 654 |
+
"gustatory_ms": [
|
| 655 |
+
(r"(taste.{0,20}(hallucination|altered|distorted|loss|abnormal|changed))", "Taste hallucination / disturbance"),
|
| 656 |
+
(r"(dysgeusia|ageusia|gustatory.{0,15}(symptom|disturbance|hallucination))", "Dysgeusia / ageusia (clinical)"),
|
| 657 |
+
(r"(food.{0,15}(taste|tastes).{0,15}(different|wrong|strange|metallic|bland|off)).{0,20}(neurological|ms)", "Food tastes wrong / metallic"),
|
| 658 |
+
(r"(altered taste|taste disturbance).{0,20}(neurological|ms|sclerosis)", "Altered taste (MS context)"),
|
| 659 |
+
],
|
| 660 |
+
|
| 661 |
+
# ββ Standard: Euphoria / inappropriate affect βββββββββββββββββββββββββββββ
|
| 662 |
+
# Source: Merck Manual 2024
|
| 663 |
+
"euphoria_ms": [
|
| 664 |
+
(r"(euphoria|euphoric|inappropriate happiness|manic episode).{0,20}(ms|neurological|cerebral|brain)", "Euphoria in MS"),
|
| 665 |
+
(r"(apathy|poor judgment|inattention).{0,20}(ms|neurological|cerebral|cognitive)", "Apathy / poor judgment (MS)"),
|
| 666 |
+
],
|
| 667 |
+
|
| 668 |
+
# ββ Standard: Useless hand (Oppenheim) βββββββββββββββββββββββββββββββββββ
|
| 669 |
+
# Source: StatPearls 2024
|
| 670 |
+
"useless_hand_ms": [
|
| 671 |
+
(r"(useless hand|oppenheim|loss of.{0,10}function.{0,10}hand|hand.{0,10}useless).{0,20}(ms|neurological|demyelinating)", "Useless hand (Oppenheim sign)"),
|
| 672 |
+
(r"(difficulty.{0,20}(crossing road|pour|pouring|playing ball).{0,20}(ms|neurological|dexterity))", "Difficulty pouring / crossing road"),
|
| 673 |
+
(r"(sense of.{0,10}uselessness.{0,10}hand|hand.{0,10}function.{0,10}lost)", "Sense of hand uselessness"),
|
| 674 |
+
],
|
| 675 |
+
|
| 676 |
+
# ββ Standard: Seizures in MS βββββββββββββββββββββββββββββββββββββββββββββ
|
| 677 |
+
# Source: StatPearls, Frontiers, PubMed
|
| 678 |
+
"seizures_ms": [
|
| 679 |
+
(r"(seizure|epileptic).{0,30}(ms|multiple sclerosis|demyelinating)", "Seizures in MS"),
|
| 680 |
+
(r"(focal seizure|tonic.clonic|absence seizure).{0,20}(ms|neurological|brain lesion)", "Focal / generalised seizure in MS"),
|
| 681 |
+
(r"(epilepsy|epileptic).{0,20}(ms|multiple sclerosis)", "Epilepsy / MS comorbidity"),
|
| 682 |
+
],
|
| 683 |
+
|
| 684 |
+
# ββ Standard: Prodromal / RIS (2024 McDonald) ββββββββββββββββββββββββββββ
|
| 685 |
+
# Source: PMC 2024, McDonald criteria 2024
|
| 686 |
+
"prodromal_ms": [
|
| 687 |
+
(r"(radiologically isolated syndrome|\bris\b).{0,20}(ms|white matter|lesion)", "Radiologically isolated syndrome (RIS)"),
|
| 688 |
+
(r"(subclinical|asymptomatic).{0,20}(ms|lesion|demyelinating|white matter)", "Subclinical / asymptomatic MS lesions"),
|
| 689 |
+
(r"(prodromal.{0,20}ms|ms.{0,20}prodromal)", "Prodromal MS"),
|
| 690 |
+
],
|
| 691 |
+
|
| 692 |
+
# ββ Standard: Psychiatric first presentation ββββββββββββββββββββββββββββββ
|
| 693 |
+
# Source: Merck, Cureus
|
| 694 |
+
"psychiatric_ms": [
|
| 695 |
+
(r"(psychiatric.{0,20}(symptom|presentation|ms|first))", "Psychiatric first presentation of MS"),
|
| 696 |
+
(r"(mood disorder.{0,20}(ms|neurological|brain|lesion))", "Mood disorder with MS lesion"),
|
| 697 |
+
(r"(psychosis|mania|bipolar).{0,20}(ms|multiple sclerosis|demyelinating)", "Psychosis / mania in MS"),
|
| 698 |
+
],
|
| 699 |
+
|
| 700 |
+
# ββ Standard: Functional overlay on MS βββββββββββββββββββββββββββββββββββ
|
| 701 |
+
# Source: NHS, Frontiers
|
| 702 |
+
"functional_ms": [
|
| 703 |
+
(r"(functional neurological|functional overlay).{0,20}(ms|multiple sclerosis|confirmed)", "Functional overlay on MS"),
|
| 704 |
+
(r"(functional.{0,15}disorder|non.organic).{0,20}(ms|confirmed|comorbid)", "Functional neurological disorder comorbid MS"),
|
| 705 |
+
(r"functional overlay on.{0,15}(ms|multiple sclerosis|confirmed ms)", "Functional overlay on confirmed MS"),
|
| 706 |
+
],
|
| 707 |
+
}
|
| 708 |
+
|
| 709 |
+
|
| 710 |
+
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 711 |
+
# TIER 3: LOW-PRIORITY PATTERNS (1.0 pt each β fixed weight)
|
| 712 |
+
#
|
| 713 |
+
# These are recognised MS symptoms but non-specific and insufficient alone to
|
| 714 |
+
# independently trigger HIGH. They:
|
| 715 |
+
# β’ Add 1.0 pt each to combined score
|
| 716 |
+
# β’ LP-only β WATCH tier
|
| 717 |
+
# β’ LP + standard β can escalate WATCH β MODERATE
|
| 718 |
+
# β’ LP + anchor β HIGH (anchor override)
|
| 719 |
+
#
|
| 720 |
+
# To add a new low-priority category: add key + patterns here.
|
| 721 |
+
# No other code changes needed.
|
| 722 |
+
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 723 |
+
LOW_PRIORITY_PATTERNS: Dict[str, List[tuple]] = {
|
| 724 |
+
|
| 725 |
+
# LP-1: Heat sensitivity (non-visual)
|
| 726 |
+
# Distinct from Uhthoff's (which requires visual/gait component).
|
| 727 |
+
# Generalised heat intolerance, summer worsening β common MS soft sign.
|
| 728 |
+
"heat_sensitivity_general": [
|
| 729 |
+
(r"(heat|warm|hot).{0,30}(worsen|worse|trigger|tired|exhaust|weak|fatigue)", "Heat worsening general symptoms"),
|
| 730 |
+
(r"(feel worse|feel bad|symptoms worse).{0,20}(heat|warm|hot|summer|sauna)", "Symptoms worse in heat"),
|
| 731 |
+
(r"(cannot tolerate|intolerant to|sensitive to).{0,20}(heat|warm|hot|sun)", "Heat intolerance (general)"),
|
| 732 |
+
(r"(summer|hot weather|warm weather).{0,20}(worse|bad|difficult|relapse|trigger)", "Summer symptom worsening"),
|
| 733 |
+
],
|
| 734 |
+
|
| 735 |
+
# LP-2: Chronic pain (non-TN)
|
| 736 |
+
"chronic_pain_ms": [
|
| 737 |
+
(r"(chronic|persistent|constant|ongoing).{0,15}(pain|aching|burning|discomfort)", "Chronic pain"),
|
| 738 |
+
(r"(back pain|leg pain|arm pain|body pain|joint pain).{0,30}(ms|neurological|nerve|numb)", "MS-related pain"),
|
| 739 |
+
(r"(burning|aching).{0,20}(legs|arms|back|body|limbs).{0,30}(constant|chronic|always|persistent)", "Burning / aching extremities"),
|
| 740 |
+
(r"(central sensitiz|central sensitisation|neuropathic pain|allodynia).{0,20}", "Central sensitisation / neuropathic pain"),
|
| 741 |
+
(r"(pain.{0,15}unresponsive|pain.{0,15}not respond).{0,20}(paracetamol|ibuprofen|nsaid|analgesic)", "Pain unresponsive to analgesia"),
|
| 742 |
+
],
|
| 743 |
+
|
| 744 |
+
# LP-3: Sleep disturbance
|
| 745 |
+
"sleep_disturbance_ms": [
|
| 746 |
+
(r"(insomnia|cannot sleep|trouble sleeping|poor sleep|sleep disturbance)", "Insomnia / sleep disturbance"),
|
| 747 |
+
(r"(non.restorative sleep|unrefreshing sleep|wake.{0,10}unrefreshed|tired after sleep)", "Non-restorative sleep"),
|
| 748 |
+
(r"(periodic limb|limb movement).{0,20}(sleep|night|bed)", "Periodic limb movement in sleep"),
|
| 749 |
+
(r"(sleep.{0,15}(problem|issue|disorder)).{0,20}(ms|fatigue|spasm|pain)", "Sleep problem (MS context)"),
|
| 750 |
+
],
|
| 751 |
+
|
| 752 |
+
# LP-4: Sexual dysfunction
|
| 753 |
+
"sexual_dysfunction_ms": [
|
| 754 |
+
(r"(sexual dysfunction|sexual problem|sexual difficulty|sex.{0,10}problem)", "Sexual dysfunction"),
|
| 755 |
+
(r"(reduced libido|low libido|decreased libido|loss of libido|no desire)", "Reduced libido"),
|
| 756 |
+
(r"(erectile dysfunction|impotence|erection problem)", "Erectile dysfunction"),
|
| 757 |
+
(r"(genital.{0,15}(numb|numbness|tingle|sensation|sensory))", "Genital numbness / tingling"),
|
| 758 |
+
(r"(arousal.{0,15}(problem|difficult|reduced|impaired)|lubrication.{0,15}(problem|reduced|impaired))", "Arousal / lubrication difficulty"),
|
| 759 |
+
(r"(orgasm.{0,15}(difficult|problem|impaired|absent|reduced))", "Orgasmic dysfunction"),
|
| 760 |
+
(r"(vaginal dryness|decreased lubrication)", "Vaginal dryness / decreased lubrication"),
|
| 761 |
+
],
|
| 762 |
+
|
| 763 |
+
# LP-5: Mood and affect (sustained β distinct from pseudobulbar)
|
| 764 |
+
"mood_affect_ms": [
|
| 765 |
+
(r"(depression|depressed|low mood|feeling down|hopeless).{0,30}(ms|neurological|since|for months|for years)", "MS-related depression"),
|
| 766 |
+
(r"(anxiety|anxious|panic attack|worry).{0,30}(ms|neurological|symptoms|worsening)", "MS-related anxiety"),
|
| 767 |
+
(r"(mood swings|emotional lability|irritability|mood changes).{0,30}(ms|neurological|recent|new)", "Mood swings / lability"),
|
| 768 |
+
(r"(euphoria|euphoric).{0,20}(ms|inappropriate|unusual)", "Euphoria (MS sign)"),
|
| 769 |
+
(r"(emotional.{0,10}(flatness|blunting|numbing)|apathy|motivation.{0,10}(loss|reduced|low))", "Emotional flattening / apathy"),
|
| 770 |
+
],
|
| 771 |
+
|
| 772 |
+
# LP-6: Tinnitus / hearing changes
|
| 773 |
+
"tinnitus_hearing_ms": [
|
| 774 |
+
(r"(tinnitus|ringing in.{0,10}ear|buzzing in.{0,10}ear|ringing ear)", "Tinnitus (ringing in ears)"),
|
| 775 |
+
(r"(chronic.{0,10}buzzing|persistent.{0,10}buzzing|constant.{0,10}buzzing).{0,20}(ear|head)", "Chronic buzzing in ears"),
|
| 776 |
+
(r"(hearing loss|hearing impairment|hard of hearing|decreased hearing)", "Hearing loss / impairment"),
|
| 777 |
+
(r"(sudden hearing loss|sudden deafness)", "Sudden hearing loss"),
|
| 778 |
+
(r"(auditory.{0,15}(hallucination|distortion|problem)|sound.{0,10}(distorted|strange|weird))", "Auditory disturbance"),
|
| 779 |
+
],
|
| 780 |
+
|
| 781 |
+
# LP-7: Cognitive fatigue (specific β distinct from generalised cognitive_ms)
|
| 782 |
+
"cognitive_fatigue_ms": [
|
| 783 |
+
(r"(mental fatigue|cognitive fatigue|brain.{0,10}exhaust|mental exhaustion)", "Cognitive / mental fatigue"),
|
| 784 |
+
(r"(brain.{0,10}(shut|shut down|give up|stop working)|mind.{0,10}blank.{0,10}(exhaust|tired|fatigue))", "Brain shutting down feeling"),
|
| 785 |
+
(r"(cannot.{0,10}concentrate|hard to concentrate|concentration.{0,10}(problem|difficult|poor))", "Concentration difficulty"),
|
| 786 |
+
(r"(mental.{0,10}(fog|foggy|cloudy|slow)).{0,20}(after|following|when).{0,20}(effort|activity|task)", "Mental fog after effort"),
|
| 787 |
+
],
|
| 788 |
+
|
| 789 |
+
# LP-8: Bowel dysfunction (isolated β standard if combined with other autonomic)
|
| 790 |
+
"bowel_dysfunction_ms": [
|
| 791 |
+
(r"(constipation|bowel.{0,20}(problem|control|issue|incontinence))", "Constipation / bowel control problems"),
|
| 792 |
+
(r"(fecal incontinence|bowel incontinence|bowel leakage)", "Bowel incontinence"),
|
| 793 |
+
(r"(neurogenic bowel|bowel dysfunction)", "Neurogenic bowel dysfunction"),
|
| 794 |
+
],
|
| 795 |
+
|
| 796 |
+
# LP-9: Respiratory (MS-related)
|
| 797 |
+
"respiratory_ms": [
|
| 798 |
+
(r"(shortness of breath|breathing.{0,20}(difficulty|problem|trouble)).{0,20}(ms|neurological|weakness|fatigue)", "Shortness of breath (MS respiratory weakness)"),
|
| 799 |
+
(r"(respiratory.{0,20}(weakness|dysfunction|problem)).{0,20}(ms|neurological)", "Respiratory weakness in MS"),
|
| 800 |
+
(r"diaphragm.{0,20}(weakness|paralysis|dysfunction)", "Diaphragm weakness / dysfunction"),
|
| 801 |
+
],
|
| 802 |
+
|
| 803 |
+
# LP-10: Headache (MS context)
|
| 804 |
+
"headache_ms": [
|
| 805 |
+
(r"(headache|head pain).{0,20}(ms|multiple sclerosis|relapse|lesion|worsening)", "Headache in MS context"),
|
| 806 |
+
(r"(ms.{0,20}migraine|migraine.{0,20}ms)", "Migraine β MS comorbidity"),
|
| 807 |
+
(r"(persistent headache|chronic headache|new.{0,10}headache).{0,20}(neurological|ms|spine)", "Persistent headache (MS context)"),
|
| 808 |
+
(r"headache.{0,60}(started|began).{0,30}(neurological|ms|symptom)", "Headache onset with neurological symptoms"),
|
| 809 |
+
],
|
| 810 |
+
|
| 811 |
+
# LP-11: Skin sensation / hypersensitivity
|
| 812 |
+
"skin_sensation_ms": [
|
| 813 |
+
(r"(skin.{0,20}sensitive|sensitive skin|hypersensitive).{0,20}(ms|neurological|touch)", "Skin hypersensitivity"),
|
| 814 |
+
(r"\b(allodynia|hyperaesthesia|cutaneous.{0,15}(pain|sensitivity))\b", "Allodynia / hyperaesthesia"),
|
| 815 |
+
(r"(prickling|pins and needles).{0,20}(skin|face|arm|leg|body)", "Prickling / pins and needles on skin"),
|
| 816 |
+
],
|
| 817 |
+
|
| 818 |
+
# LP-12: Pain in MS (central / neuropathic β non-TN)
|
| 819 |
+
"pain_ms": [
|
| 820 |
+
(r"(neuropathic pain|central pain).{0,20}(ms|multiple sclerosis|neurological)", "Neuropathic / central pain in MS"),
|
| 821 |
+
(r"(trigeminal neuralgia|painful.{0,15}spasm)", "Painful spasm / TN-like pain"),
|
| 822 |
+
(r"(burning pain|stabbing pain|shooting pain).{0,20}(leg|arm|back|face|body|extremities)", "Burning / stabbing / shooting pain"),
|
| 823 |
+
],
|
| 824 |
+
|
| 825 |
+
# LP-13: Menstrual / perimenstrual worsening (v8.1 new)
|
| 826 |
+
# Source: MSAA, PMC 2024
|
| 827 |
+
"menstrual_ms": [
|
| 828 |
+
(r"(perimenstrual|menstrual|period).{0,20}(worse|worsen|relapse|trigger|symptom|ms)", "Perimenstrual symptom worsening"),
|
| 829 |
+
(r"(symptoms worse.{0,20}(period|menstruation|cycle)|period.{0,30}ms symptom)", "Symptoms worse around period"),
|
| 830 |
+
],
|
| 831 |
+
|
| 832 |
+
# LP-14: Stress-triggered worsening (v8.1 new)
|
| 833 |
+
# Source: NHS, WebMD
|
| 834 |
+
"stress_triggered_ms": [
|
| 835 |
+
(r"(psychological stress|emotional stress|stress).{0,30}(trigger|worsen|worse|uhthoff|ms|symptom)", "Stress triggering MS symptoms"),
|
| 836 |
+
(r"(stress.{0,20}trigger.{0,20}ms|ms.{0,20}stress.{0,20}trigger)", "Stress β MS pseudo-relapse trigger"),
|
| 837 |
+
],
|
| 838 |
+
|
| 839 |
+
# LP-15: Pregnancy / postpartum (v8.1 new)
|
| 840 |
+
# Source: NINDS, MS Society
|
| 841 |
+
"pregnancy_ms": [
|
| 842 |
+
(r"(pregnancy|pregnant|postpartum).{0,30}(ms|relapse|symptom|worse|improve)", "Pregnancy / postpartum MS risk"),
|
| 843 |
+
(r"(ms.{0,20}(pregnancy|pregnant|postpartum)|(pregnancy|pregnant|postpartum).{0,20}ms)", "MS and pregnancy / postpartum"),
|
| 844 |
+
],
|
| 845 |
+
}
|
| 846 |
+
|
| 847 |
+
|
| 848 |
+
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 849 |
+
# SEVERITY MODIFIERS
|
| 850 |
+
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 851 |
+
SEVERITY_MODIFIERS = {
|
| 852 |
+
"severe": {
|
| 853 |
+
"patterns": [r"\b(severe|complete|total|worst|extreme|unbearable|debilitating|paralyzed|blind)\b"],
|
| 854 |
+
"weight": 1.5,
|
| 855 |
+
"label": "Severe",
|
| 856 |
+
},
|
| 857 |
+
"mild": {
|
| 858 |
+
"patterns": [r"\b(mild|slight|faint|occasional|sometimes|a little|minor|brief)\b"],
|
| 859 |
+
"weight": 0.5,
|
| 860 |
+
"label": "Mild / Occasional",
|
| 861 |
+
},
|
| 862 |
+
}
|
| 863 |
+
|
| 864 |
+
|
| 865 |
+
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 866 |
+
# WORKUP RECOMMENDATIONS BY TIER
|
| 867 |
+
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 868 |
+
WORKUP_BY_TIER: Dict[str, List[str]] = {
|
| 869 |
+
"CRITICAL_EMERGENCY": [],
|
| 870 |
+
"HIGH": [
|
| 871 |
+
"MRI of orbits with and without contrast β screen for optic nerve involvement",
|
| 872 |
+
"MRI brain and spinal cord with and without contrast",
|
| 873 |
+
"Lumbar puncture β CSF for IgG index, oligoclonal bands (>2 exclusive to CSF), kappa free light chains",
|
| 874 |
+
"Serum cell-based assay β NMO antibody (AQP4-IgG) and MOGAD (MOG-IgG)",
|
| 875 |
+
"Full neurological examination by a neurologist",
|
| 876 |
+
"Exclude mimics: sarcoidosis, lupus, vasculitis, B12 deficiency, cervical myelopathy",
|
| 877 |
+
],
|
| 878 |
+
"MODERATE": [
|
| 879 |
+
"Neurology referral β clinical review of symptom pattern",
|
| 880 |
+
"Basic blood panel β FBC, B12, folate, thyroid, ESR, CRP, ANA",
|
| 881 |
+
"Consider MRI brain if symptoms persist or evolve",
|
| 882 |
+
"Ophthalmology review if visual symptoms are present",
|
| 883 |
+
"Keep a symptom diary β track onset, duration, and triggers",
|
| 884 |
+
],
|
| 885 |
+
"WATCH": [
|
| 886 |
+
"Document symptoms carefully β note dates of onset, frequency, and any new neurological signs",
|
| 887 |
+
"Schedule a GP / family physician review",
|
| 888 |
+
"If new neurological symptoms appear (visual change, numbness, weakness, coordination problems), seek neurology referral promptly",
|
| 889 |
+
"Re-assess in 4β8 weeks or sooner if symptoms worsen",
|
| 890 |
+
],
|
| 891 |
+
"LOW": [
|
| 892 |
+
"No MS-specific features detected at this time",
|
| 893 |
+
"Continue to monitor β if new neurological symptoms develop, seek medical review",
|
| 894 |
+
"Keep a symptom diary for any changes",
|
| 895 |
+
],
|
| 896 |
+
}
|
| 897 |
+
|
| 898 |
+
|
| 899 |
+
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 900 |
+
# TIER CONFIGURATION
|
| 901 |
+
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 902 |
+
TIER_CONFIG: Dict[str, dict] = {
|
| 903 |
+
"CRITICAL_EMERGENCY": {
|
| 904 |
+
"tier_label": "Emergency",
|
| 905 |
+
"tier_subtitle": "Seek immediate emergency care",
|
| 906 |
+
"action": "Call emergency services immediately (999 / 911). Do not wait.",
|
| 907 |
+
},
|
| 908 |
+
"HIGH": {
|
| 909 |
+
"tier_label": "High MS Risk",
|
| 910 |
+
"tier_subtitle": "Neurological referral recommended",
|
| 911 |
+
"action": (
|
| 912 |
+
"The symptom pattern is consistent with possible Multiple Sclerosis. "
|
| 913 |
+
"Urgent referral to neurology is recommended for a full Multiple Sclerosis workup including "
|
| 914 |
+
"MRI of the orbits, brain and spinal cord, lumbar puncture, and specialist examination."
|
| 915 |
+
),
|
| 916 |
+
},
|
| 917 |
+
"MODERATE": {
|
| 918 |
+
"tier_label": "Moderate β Monitor",
|
| 919 |
+
"tier_subtitle": "Neurological symptoms present β clinical review recommended",
|
| 920 |
+
"action": (
|
| 921 |
+
"Some neurologically relevant symptoms are present. "
|
| 922 |
+
"A clinical review and basic investigations are recommended. "
|
| 923 |
+
"Seek neurology referral if symptoms persist, recur, or new symptoms develop."
|
| 924 |
+
),
|
| 925 |
+
},
|
| 926 |
+
"WATCH": {
|
| 927 |
+
"tier_label": "Watch β Low-Priority Symptoms",
|
| 928 |
+
"tier_subtitle": "Recognised Multiple Sclerosis soft signs β clinical monitoring advised",
|
| 929 |
+
"action": (
|
| 930 |
+
"The symptoms described are recognised in MS but are non-specific and "
|
| 931 |
+
"insufficient on their own to indicate high risk. Monitor closely. "
|
| 932 |
+
"If any new or escalating neurological symptoms appear β particularly visual "
|
| 933 |
+
"changes, numbness, weakness, or coordination problems β seek medical review promptly."
|
| 934 |
+
),
|
| 935 |
+
},
|
| 936 |
+
"LOW": {
|
| 937 |
+
"tier_label": "No Specific Features Detected",
|
| 938 |
+
"tier_subtitle": "No Multiple Sclerosis-specific pattern identified",
|
| 939 |
+
"action": (
|
| 940 |
+
"No MS-specific symptom features were detected in this description. "
|
| 941 |
+
"If your symptoms persist or you develop new neurological symptoms, "
|
| 942 |
+
"please consult a healthcare professional."
|
| 943 |
+
),
|
| 944 |
+
},
|
| 945 |
+
}
|
| 946 |
+
|
| 947 |
+
|
| 948 |
+
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 949 |
+
# NLP HELPERS
|
| 950 |
+
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 951 |
+
_doc_cache: dict = {} # single-call cache: parse text ONCE per classify() call
|
| 952 |
+
|
| 953 |
+
|
| 954 |
+
def _get_doc(text_lower: str):
|
| 955 |
+
"""Parse text once and cache within a single classify() call."""
|
| 956 |
+
if text_lower not in _doc_cache:
|
| 957 |
+
_doc_cache.clear() # keep cache size = 1
|
| 958 |
+
_doc_cache[text_lower] = nlp(text_lower)
|
| 959 |
+
return _doc_cache[text_lower]
|
| 960 |
+
|
| 961 |
+
|
| 962 |
+
def _negex_check(text_lower: str, start_char: int, end_char: int) -> bool:
|
| 963 |
+
"""Returns True if the matched span is negated via NegEx. Uses cached doc."""
|
| 964 |
+
doc = _get_doc(text_lower)
|
| 965 |
+
span = doc.char_span(start_char, end_char, label="SYMPTOM", alignment_mode="expand")
|
| 966 |
+
return bool(span and span._.negex)
|
| 967 |
+
|
| 968 |
+
|
| 969 |
+
def _severity_multiplier(text_lower: str) -> float:
|
| 970 |
+
for mod in SEVERITY_MODIFIERS.values():
|
| 971 |
+
for p in mod["patterns"]:
|
| 972 |
+
if re.search(p, text_lower):
|
| 973 |
+
return mod["weight"]
|
| 974 |
+
return 1.0
|
| 975 |
+
|
| 976 |
+
|
| 977 |
+
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 978 |
+
# CORE CLASSIFIER
|
| 979 |
+
# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββοΏ½οΏ½ββββββββββ
|
| 980 |
+
def classify(text: str) -> ClassifyResponse:
|
| 981 |
+
"""
|
| 982 |
+
Three-tier MS symptom classification with NegEx negation detection.
|
| 983 |
+
|
| 984 |
+
Scoring:
|
| 985 |
+
Tier 1/2 (SYMPTOM_PATTERNS) β 3.0 pts Γ severity multiplier
|
| 986 |
+
Tier 3 (LOW_PRIORITY_PATTERNS) β 1.0 pt fixed
|
| 987 |
+
|
| 988 |
+
Tier assignment:
|
| 989 |
+
CRITICAL_EMERGENCY β emergency flag triggered
|
| 990 |
+
HIGH β anchor hit + score β₯ 3, OR standard score β₯ 6
|
| 991 |
+
MODERATE β standard score > 0
|
| 992 |
+
WATCH β LP-only (no Tier 1/2 hits, LP score β₯ 1)
|
| 993 |
+
LOW β nothing detected
|
| 994 |
+
"""
|
| 995 |
+
t = text.lower()
|
| 996 |
+
|
| 997 |
+
# 1. Emergency check β no NegEx (emergencies always fire)
|
| 998 |
+
for key, data in EMERGENCY_FLAGS.items():
|
| 999 |
+
if any(re.search(p, t) for p in data["patterns"]):
|
| 1000 |
+
cfg = TIER_CONFIG["CRITICAL_EMERGENCY"]
|
| 1001 |
+
return ClassifyResponse(
|
| 1002 |
+
tier="CRITICAL_EMERGENCY",
|
| 1003 |
+
tier_label=data["label"],
|
| 1004 |
+
tier_subtitle=cfg["tier_subtitle"],
|
| 1005 |
+
action=data["action"],
|
| 1006 |
+
workup=[],
|
| 1007 |
+
features=[],
|
| 1008 |
+
temporal_notes=[],
|
| 1009 |
+
)
|
| 1010 |
+
|
| 1011 |
+
# 2. Severity multiplier (applied globally)
|
| 1012 |
+
mult = _severity_multiplier(t)
|
| 1013 |
+
|
| 1014 |
+
# 3. Tier 1/2 extraction with NegEx
|
| 1015 |
+
features: List[FeatureFound] = []
|
| 1016 |
+
has_anchor = False
|
| 1017 |
+
t12_score = 0.0
|
| 1018 |
+
|
| 1019 |
+
for feat_key, patterns in SYMPTOM_PATTERNS.items():
|
| 1020 |
+
for pattern, label in patterns:
|
| 1021 |
+
for m in re.finditer(pattern, t):
|
| 1022 |
+
if not _negex_check(t, m.start(), m.end()):
|
| 1023 |
+
pts = 3.0 * mult
|
| 1024 |
+
t12_score += pts
|
| 1025 |
+
if feat_key in ANCHOR_FEATURES:
|
| 1026 |
+
has_anchor = True
|
| 1027 |
+
features.append(FeatureFound(key=feat_key, label=label, priority="standard"))
|
| 1028 |
+
break # one hit per feature key
|
| 1029 |
+
else:
|
| 1030 |
+
continue
|
| 1031 |
+
break
|
| 1032 |
+
|
| 1033 |
+
# 4. Tier 3 extraction with NegEx (1.0 pt fixed, no severity multiplier)
|
| 1034 |
+
lp_score = 0.0
|
| 1035 |
+
for feat_key, patterns in LOW_PRIORITY_PATTERNS.items():
|
| 1036 |
+
for pattern, label in patterns:
|
| 1037 |
+
for m in re.finditer(pattern, t):
|
| 1038 |
+
if not _negex_check(t, m.start(), m.end()):
|
| 1039 |
+
lp_score += 1.0
|
| 1040 |
+
features.append(FeatureFound(key=feat_key, label=label, priority="low"))
|
| 1041 |
+
break
|
| 1042 |
+
else:
|
| 1043 |
+
continue
|
| 1044 |
+
break
|
| 1045 |
+
|
| 1046 |
+
# 5. Temporal penalty β short-duration events (<24h) reduce score
|
| 1047 |
+
temporal_notes: List[str] = []
|
| 1048 |
+
if re.search(r"(minute|hour)s? ago", t) and not re.search(r"(day|week|month)s?", t):
|
| 1049 |
+
t12_score = max(0.0, t12_score - 2.0)
|
| 1050 |
+
temporal_notes.append(
|
| 1051 |
+
"Symptoms appear to be very short-duration (<24 hours). Clinical significance may be reduced."
|
| 1052 |
+
)
|
| 1053 |
+
|
| 1054 |
+
# 6. Tier assignment
|
| 1055 |
+
if t12_score >= 6 or (t12_score >= 3 and has_anchor):
|
| 1056 |
+
tier = "HIGH"
|
| 1057 |
+
elif t12_score > 0:
|
| 1058 |
+
tier = "MODERATE"
|
| 1059 |
+
elif lp_score >= 1:
|
| 1060 |
+
tier = "WATCH"
|
| 1061 |
+
else:
|
| 1062 |
+
tier = "LOW"
|
| 1063 |
+
|
| 1064 |
+
cfg = TIER_CONFIG[tier]
|
| 1065 |
+
return ClassifyResponse(
|
| 1066 |
+
tier=tier,
|
| 1067 |
+
tier_label=cfg["tier_label"],
|
| 1068 |
+
tier_subtitle=cfg["tier_subtitle"],
|
| 1069 |
+
action=cfg["action"],
|
| 1070 |
+
workup=WORKUP_BY_TIER.get(tier, []),
|
| 1071 |
+
features=features,
|
| 1072 |
+
temporal_notes=temporal_notes,
|
| 1073 |
+
)
|
| 1074 |
+
|
| 1075 |
+
|
| 1076 |
+
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 1077 |
+
# API ROUTES
|
| 1078 |
+
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 1079 |
+
|
| 1080 |
+
@app.get("/ping")
|
| 1081 |
+
async def ping():
|
| 1082 |
+
return "pong"
|
| 1083 |
+
|
| 1084 |
+
|
| 1085 |
+
@app.post("/analyze")
|
| 1086 |
+
async def analyze_endpoint(req: SymptomRequest):
|
| 1087 |
+
"""
|
| 1088 |
+
Live risk panel endpoint β classifies accumulated conversation text.
|
| 1089 |
+
Accepts up to 3000 chars of combined human messages for best accuracy.
|
| 1090 |
+
No auth required.
|
| 1091 |
+
"""
|
| 1092 |
+
try:
|
| 1093 |
+
# Strip common filler words that confuse the classifier
|
| 1094 |
+
# when full conversation is passed (greetings, "yes", "no" etc.)
|
| 1095 |
+
import re as _re
|
| 1096 |
+
text = req.text.strip()
|
| 1097 |
+
# Remove pure filler lines like "hi", "yes", "no", "ok", "thanks"
|
| 1098 |
+
lines = [l.strip() for l in text.split(".") if len(l.strip()) > 8]
|
| 1099 |
+
clean_text = ". ".join(lines) if lines else text
|
| 1100 |
+
|
| 1101 |
+
result = classify(clean_text or text)
|
| 1102 |
+
score_map = {
|
| 1103 |
+
"LOW": 5, "WATCH": 30, "MODERATE": 55,
|
| 1104 |
+
"HIGH": 80, "CRITICAL_EMERGENCY": 100
|
| 1105 |
+
}
|
| 1106 |
+
return {
|
| 1107 |
+
"tier": result.tier,
|
| 1108 |
+
"tier_label": result.tier_label,
|
| 1109 |
+
"tier_subtitle": result.tier_subtitle,
|
| 1110 |
+
"action": result.action,
|
| 1111 |
+
"score_pct": score_map.get(result.tier, 5),
|
| 1112 |
+
"features": [{"label": f.label, "priority": f.priority} for f in result.features],
|
| 1113 |
+
"workup": result.workup[:5],
|
| 1114 |
+
"temporal_notes": result.temporal_notes,
|
| 1115 |
+
}
|
| 1116 |
+
except Exception as e:
|
| 1117 |
+
logger.error("[analyze] {}", e)
|
| 1118 |
+
raise HTTPException(status_code=500, detail=str(e))
|
| 1119 |
+
|
| 1120 |
+
|
| 1121 |
+
@app.get("/health")
|
| 1122 |
+
async def health():
|
| 1123 |
+
return {
|
| 1124 |
+
"status": "ok",
|
| 1125 |
+
"model": "AxonIQ + Agentic AI",
|
| 1126 |
+
"negex": "active",
|
| 1127 |
+
"llm": "llama3.1:8b via Ollama",
|
| 1128 |
+
"rag": "ChromaDB (150 cases + MS guidelines)",
|
| 1129 |
+
"cases_validated": 150,
|
| 1130 |
+
"sources": "PMC 2024, NINDS, MSAA, NHS, Mayo, StatPearls, Cureus, Frontiers, Merck 2024",
|
| 1131 |
+
"team": {
|
| 1132 |
+
"domain_expert": "Dr. Avasarala, MD PhD β University of Kentucky, Lexington KY, USA",
|
| 1133 |
+
"lead_ai_architect": "Raghu Gangolu β NIT Warangal, Telangana, India",
|
| 1134 |
+
"principal_investigator": "Dr. Kadambari, PhD β NIT Warangal, Telangana, India",
|
| 1135 |
+
},
|
| 1136 |
+
}
|
| 1137 |
+
|
| 1138 |
+
|
| 1139 |
+
@app.post("/classify", response_model=ClassifyResponse)
|
| 1140 |
+
@limiter.limit("30/minute")
|
| 1141 |
+
async def classify_endpoint(request: Request, req: SymptomRequest):
|
| 1142 |
+
if nlp is None:
|
| 1143 |
+
raise HTTPException(status_code=503, detail="NLP model not loaded")
|
| 1144 |
+
logger.info("[classify] text_len={}", len(req.text))
|
| 1145 |
+
return classify(req.text)
|
| 1146 |
+
|
| 1147 |
+
|
| 1148 |
+
# ββ Agentic AI Chat Endpoints βββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 1149 |
+
|
| 1150 |
+
@app.post("/chat", response_model=ChatResponse)
|
| 1151 |
+
@limiter.limit("20/minute")
|
| 1152 |
+
async def chat_endpoint(
|
| 1153 |
+
request: Request,
|
| 1154 |
+
req: ChatRequest,
|
| 1155 |
+
current_user: dict = Depends(__import__("api.auth", fromlist=["get_current_user"]).get_current_user),
|
| 1156 |
+
):
|
| 1157 |
+
"""
|
| 1158 |
+
Main agentic AI chat endpoint (requires authentication).
|
| 1159 |
+
Creates a new session if session_id is not provided.
|
| 1160 |
+
Persists every message to SQLite with timestamps.
|
| 1161 |
+
"""
|
| 1162 |
+
from api.memory import new_session, get_session, append_message, get_history
|
| 1163 |
+
from api.agent import chat as agent_chat
|
| 1164 |
+
from api.database import (
|
| 1165 |
+
create_db_session, save_message, get_session_owner,
|
| 1166 |
+
update_session_title, get_message_count,
|
| 1167 |
+
)
|
| 1168 |
+
|
| 1169 |
+
user_id = current_user["id"]
|
| 1170 |
+
|
| 1171 |
+
# Create or retrieve session
|
| 1172 |
+
sid = req.session_id
|
| 1173 |
+
if not sid or get_session(sid) is None:
|
| 1174 |
+
sid = new_session()
|
| 1175 |
+
create_db_session(sid, user_id)
|
| 1176 |
+
logger.info("[chat] New session: {} user={}", sid, user_id)
|
| 1177 |
+
else:
|
| 1178 |
+
# Security: ensure the session belongs to this user
|
| 1179 |
+
owner = get_session_owner(sid)
|
| 1180 |
+
if owner is not None and owner != user_id:
|
| 1181 |
+
raise HTTPException(status_code=403, detail="Session belongs to another user")
|
| 1182 |
+
if owner is None:
|
| 1183 |
+
# Legacy session without DB record β adopt it
|
| 1184 |
+
create_db_session(sid, user_id)
|
| 1185 |
+
|
| 1186 |
+
# Persist user message to DB
|
| 1187 |
+
save_message(sid, "human", req.message)
|
| 1188 |
+
from api.database import log_action as _log_chat
|
| 1189 |
+
_log_chat("CHAT_MESSAGE", user_id=user_id, username=current_user["username"],
|
| 1190 |
+
detail=req.message[:120],
|
| 1191 |
+
session_uuid=sid,
|
| 1192 |
+
ip_address=getattr(request, 'client', None) and request.client.host)
|
| 1193 |
+
|
| 1194 |
+
# Auto-title the session from first user message
|
| 1195 |
+
if get_message_count(sid) <= 1:
|
| 1196 |
+
title = req.message[:60].strip()
|
| 1197 |
+
update_session_title(sid, title)
|
| 1198 |
+
|
| 1199 |
+
# Run classifier to extract structured conclusion and save to session
|
| 1200 |
+
try:
|
| 1201 |
+
from api.database import save_conclusion
|
| 1202 |
+
_cls = classify(req.message)
|
| 1203 |
+
if _cls.tier not in ("LOW",): # only save meaningful conclusions
|
| 1204 |
+
save_conclusion(
|
| 1205 |
+
session_uuid=sid,
|
| 1206 |
+
tier=_cls.tier,
|
| 1207 |
+
tier_label=_cls.tier_label,
|
| 1208 |
+
symptoms=[f.label for f in _cls.features],
|
| 1209 |
+
workup=_cls.workup[:6],
|
| 1210 |
+
action=_cls.action,
|
| 1211 |
+
)
|
| 1212 |
+
except Exception as _ce:
|
| 1213 |
+
logger.warning("[chat] Conclusion save failed: {}", _ce)
|
| 1214 |
+
|
| 1215 |
+
# Also keep in-memory store for agent context (existing logic)
|
| 1216 |
+
append_message(sid, "human", req.message)
|
| 1217 |
+
history = get_history(sid)
|
| 1218 |
+
|
| 1219 |
+
logger.info("[chat] session={} user={} turn={} msg_len={}", sid, user_id, len(history), len(req.message))
|
| 1220 |
+
|
| 1221 |
+
try:
|
| 1222 |
+
response_text = agent_chat(sid, req.message, history)
|
| 1223 |
+
except Exception as e:
|
| 1224 |
+
logger.error("[chat] Agent error: {}", e)
|
| 1225 |
+
raise HTTPException(status_code=500, detail=f"Agent error: {str(e)}")
|
| 1226 |
+
|
| 1227 |
+
# Persist assistant response to DB
|
| 1228 |
+
save_message(sid, "assistant", response_text)
|
| 1229 |
+
append_message(sid, "assistant", response_text)
|
| 1230 |
+
|
| 1231 |
+
return ChatResponse(
|
| 1232 |
+
session_id=sid,
|
| 1233 |
+
response=response_text,
|
| 1234 |
+
turn=len(get_history(sid)),
|
| 1235 |
+
)
|
| 1236 |
+
|
| 1237 |
+
|
| 1238 |
+
@app.post("/session/new")
|
| 1239 |
+
async def new_session_endpoint(
|
| 1240 |
+
current_user: dict = Depends(__import__("api.auth", fromlist=["get_current_user"]).get_current_user),
|
| 1241 |
+
):
|
| 1242 |
+
"""Create a new chat session for the authenticated user."""
|
| 1243 |
+
from api.memory import new_session
|
| 1244 |
+
from api.database import create_db_session
|
| 1245 |
+
sid = new_session()
|
| 1246 |
+
create_db_session(sid, current_user["id"])
|
| 1247 |
+
return {"session_id": sid}
|
| 1248 |
+
|
| 1249 |
+
|
| 1250 |
+
@app.get("/user/sessions")
|
| 1251 |
+
async def user_sessions(
|
| 1252 |
+
current_user: dict = Depends(__import__("api.auth", fromlist=["get_current_user"]).get_current_user),
|
| 1253 |
+
):
|
| 1254 |
+
"""List all chat sessions for the authenticated user (newest first)."""
|
| 1255 |
+
from api.database import get_user_sessions
|
| 1256 |
+
sessions = get_user_sessions(current_user["id"])
|
| 1257 |
+
return {"sessions": sessions}
|
| 1258 |
+
|
| 1259 |
+
|
| 1260 |
+
@app.get("/session/{session_id}/history")
|
| 1261 |
+
async def session_history(
|
| 1262 |
+
session_id: str,
|
| 1263 |
+
current_user: dict = Depends(__import__("api.auth", fromlist=["get_current_user"]).get_current_user),
|
| 1264 |
+
):
|
| 1265 |
+
"""Get full message history for a session (with timestamps)."""
|
| 1266 |
+
from api.database import get_messages, get_session_owner
|
| 1267 |
+
owner = get_session_owner(session_id)
|
| 1268 |
+
if owner is not None and owner != current_user["id"]:
|
| 1269 |
+
raise HTTPException(status_code=403, detail="Access denied")
|
| 1270 |
+
messages = get_messages(session_id)
|
| 1271 |
+
return {"session_id": session_id, "messages": messages}
|
| 1272 |
+
|
| 1273 |
+
|
| 1274 |
+
@app.delete("/session/{session_id}")
|
| 1275 |
+
async def delete_session(
|
| 1276 |
+
session_id: str,
|
| 1277 |
+
current_user: dict = Depends(__import__("api.auth", fromlist=["get_current_user"]).get_current_user),
|
| 1278 |
+
):
|
| 1279 |
+
"""Delete a session and all its messages."""
|
| 1280 |
+
from pathlib import Path
|
| 1281 |
+
from api.database import get_session_owner, delete_db_session
|
| 1282 |
+
owner = get_session_owner(session_id)
|
| 1283 |
+
if owner is not None and owner != current_user["id"]:
|
| 1284 |
+
raise HTTPException(status_code=403, detail="Access denied")
|
| 1285 |
+
delete_db_session(session_id)
|
| 1286 |
+
p = Path(f"/tmp/neurocheck_sessions/{session_id}.json")
|
| 1287 |
+
if p.exists():
|
| 1288 |
+
p.unlink()
|
| 1289 |
+
return {"deleted": session_id}
|
| 1290 |
+
|
| 1291 |
+
|
| 1292 |
+
# ββ Admin routes ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 1293 |
+
def require_admin(current_user: dict = Depends(__import__("api.auth", fromlist=["get_current_user"]).get_current_user)):
|
| 1294 |
+
if not current_user.get("is_admin"):
|
| 1295 |
+
raise HTTPException(status_code=403, detail="Admin access required")
|
| 1296 |
+
return current_user
|
| 1297 |
+
|
| 1298 |
+
|
| 1299 |
+
@app.post("/auth/change-password")
|
| 1300 |
+
async def change_password(
|
| 1301 |
+
request: Request,
|
| 1302 |
+
current_user: dict = Depends(__import__("api.auth", fromlist=["get_current_user"]).get_current_user),
|
| 1303 |
+
):
|
| 1304 |
+
"""Allow logged-in user to change their own password."""
|
| 1305 |
+
import bcrypt as _bcrypt
|
| 1306 |
+
body = await request.json()
|
| 1307 |
+
old_pw = body.get("old_password", "")
|
| 1308 |
+
new_pw = body.get("new_password", "")
|
| 1309 |
+
if not old_pw or not new_pw:
|
| 1310 |
+
raise HTTPException(status_code=400, detail="Both old and new password are required")
|
| 1311 |
+
if len(new_pw) < 6:
|
| 1312 |
+
raise HTTPException(status_code=400, detail="New password must be at least 6 characters")
|
| 1313 |
+
# Verify old password
|
| 1314 |
+
if not _bcrypt.checkpw(old_pw.encode("utf-8"), current_user["password_hash"].encode("utf-8")):
|
| 1315 |
+
raise HTTPException(status_code=401, detail="Current password is incorrect")
|
| 1316 |
+
# Set new password
|
| 1317 |
+
new_hash = _bcrypt.hashpw(new_pw.encode("utf-8"), _bcrypt.gensalt()).decode("utf-8")
|
| 1318 |
+
from api.database import get_conn
|
| 1319 |
+
with get_conn() as conn:
|
| 1320 |
+
conn.execute("UPDATE users SET password_hash=? WHERE id=?", (new_hash, current_user["id"]))
|
| 1321 |
+
return {"message": "Password changed successfully"}
|
| 1322 |
+
|
| 1323 |
+
|
| 1324 |
+
@app.get("/admin/users")
|
| 1325 |
+
async def admin_get_users(admin=Depends(require_admin)):
|
| 1326 |
+
"""Return all users with stats."""
|
| 1327 |
+
from api.database import get_all_users_admin, get_all_sessions_admin, migrate_add_admin_column
|
| 1328 |
+
migrate_add_admin_column()
|
| 1329 |
+
users = get_all_users_admin()
|
| 1330 |
+
total_sessions, total_messages = get_all_sessions_admin()
|
| 1331 |
+
return {
|
| 1332 |
+
"users": users,
|
| 1333 |
+
"total_sessions": total_sessions,
|
| 1334 |
+
"total_messages": total_messages,
|
| 1335 |
+
}
|
| 1336 |
+
|
| 1337 |
+
|
| 1338 |
+
@app.get("/admin/user/{user_id}/sessions")
|
| 1339 |
+
async def admin_get_user_sessions(user_id: int, admin=Depends(require_admin)):
|
| 1340 |
+
"""Return all sessions + full messages for a user."""
|
| 1341 |
+
from api.database import get_user_sessions_with_messages
|
| 1342 |
+
sessions = get_user_sessions_with_messages(user_id)
|
| 1343 |
+
return {"user_id": user_id, "sessions": sessions}
|
| 1344 |
+
|
| 1345 |
+
|
| 1346 |
+
|
| 1347 |
+
|
| 1348 |
+
@app.post("/auth/forgot-password")
|
| 1349 |
+
async def forgot_password(request: Request):
|
| 1350 |
+
"""Step 1: generate OTP and send/return it."""
|
| 1351 |
+
import hashlib, random, string
|
| 1352 |
+
from datetime import datetime, timedelta, timezone
|
| 1353 |
+
from api.database import get_user_by_email, save_otp, migrate_add_otp_table
|
| 1354 |
+
|
| 1355 |
+
migrate_add_otp_table()
|
| 1356 |
+
|
| 1357 |
+
body = await request.json()
|
| 1358 |
+
email = body.get("email", "").strip().lower()
|
| 1359 |
+
if not email:
|
| 1360 |
+
raise HTTPException(status_code=400, detail="Email is required")
|
| 1361 |
+
|
| 1362 |
+
user = get_user_by_email(email)
|
| 1363 |
+
if not user:
|
| 1364 |
+
return {"dev_mode": True, "dev_otp": None,
|
| 1365 |
+
"dev_error": "No account found with this email. Please register first."}
|
| 1366 |
+
|
| 1367 |
+
# Generate OTP
|
| 1368 |
+
otp = "".join(random.choices(string.digits, k=6))
|
| 1369 |
+
otp_hash = hashlib.sha256(otp.encode()).hexdigest()
|
| 1370 |
+
expires = (datetime.now(timezone.utc) + timedelta(minutes=15)).isoformat()
|
| 1371 |
+
save_otp(user["id"], email, otp_hash, expires)
|
| 1372 |
+
|
| 1373 |
+
# Try sending email
|
| 1374 |
+
smtp_ok = bool(os.environ.get("SMTP_EMAIL") and os.environ.get("SMTP_PASSWORD"))
|
| 1375 |
+
if smtp_ok:
|
| 1376 |
+
try:
|
| 1377 |
+
from api.email_utils import send_otp_email
|
| 1378 |
+
sent = send_otp_email(email, user["username"], otp)
|
| 1379 |
+
if sent:
|
| 1380 |
+
return {"message": "Code sent to your email"}
|
| 1381 |
+
except Exception as e:
|
| 1382 |
+
logger.error("[Auth] Email error: {}", e)
|
| 1383 |
+
|
| 1384 |
+
# Dev mode β return OTP directly
|
| 1385 |
+
logger.warning("[Auth] Returning OTP in response (dev mode)")
|
| 1386 |
+
return {"dev_mode": True, "dev_otp": otp,
|
| 1387 |
+
"message": "Email not configured β use code below"}
|
| 1388 |
+
|
| 1389 |
+
|
| 1390 |
+
@app.post("/auth/verify-otp")
|
| 1391 |
+
async def verify_otp_endpoint(request: Request):
|
| 1392 |
+
"""Step 2: verify OTP, return reset token."""
|
| 1393 |
+
import hashlib
|
| 1394 |
+
from api.database import get_valid_otp, mark_otp_used, migrate_add_otp_table
|
| 1395 |
+
from api.auth import create_access_token
|
| 1396 |
+
|
| 1397 |
+
migrate_add_otp_table()
|
| 1398 |
+
|
| 1399 |
+
body = await request.json()
|
| 1400 |
+
email = body.get("email", "").strip().lower()
|
| 1401 |
+
otp = body.get("otp", "").strip()
|
| 1402 |
+
|
| 1403 |
+
if not email or not otp:
|
| 1404 |
+
raise HTTPException(status_code=400, detail="Email and code are required")
|
| 1405 |
+
|
| 1406 |
+
record = get_valid_otp(email)
|
| 1407 |
+
if not record:
|
| 1408 |
+
raise HTTPException(status_code=400, detail="Code expired or not found. Request a new one.")
|
| 1409 |
+
|
| 1410 |
+
otp_hash = hashlib.sha256(otp.encode()).hexdigest()
|
| 1411 |
+
if otp_hash != record["otp_hash"]:
|
| 1412 |
+
raise HTTPException(status_code=400, detail="Incorrect code. Please try again.")
|
| 1413 |
+
|
| 1414 |
+
mark_otp_used(record["id"])
|
| 1415 |
+
reset_token = create_access_token(record["user_id"], "reset:" + email)
|
| 1416 |
+
return {"reset_token": reset_token, "message": "Code verified"}
|
| 1417 |
+
|
| 1418 |
+
|
| 1419 |
+
@app.post("/auth/reset-password")
|
| 1420 |
+
async def reset_password_with_token(request: Request):
|
| 1421 |
+
"""Step 3: set new password using reset token."""
|
| 1422 |
+
import bcrypt as _bcrypt
|
| 1423 |
+
from api.database import update_user_password
|
| 1424 |
+
from api.auth import decode_token
|
| 1425 |
+
|
| 1426 |
+
body = await request.json()
|
| 1427 |
+
token = body.get("reset_token", "")
|
| 1428 |
+
new_pw = body.get("new_password", "")
|
| 1429 |
+
|
| 1430 |
+
if not token or not new_pw:
|
| 1431 |
+
raise HTTPException(status_code=400, detail="Token and password are required")
|
| 1432 |
+
if len(new_pw) < 6:
|
| 1433 |
+
raise HTTPException(status_code=400, detail="Password must be at least 6 characters")
|
| 1434 |
+
|
| 1435 |
+
try:
|
| 1436 |
+
payload = decode_token(token)
|
| 1437 |
+
user_id = int(payload.get("sub", 0))
|
| 1438 |
+
if not str(payload.get("username", "")).startswith("reset:"):
|
| 1439 |
+
raise ValueError("Not a reset token")
|
| 1440 |
+
except Exception:
|
| 1441 |
+
raise HTTPException(status_code=400, detail="Reset link expired. Please request a new code.")
|
| 1442 |
+
|
| 1443 |
+
new_hash = _bcrypt.hashpw(new_pw.encode("utf-8"), _bcrypt.gensalt()).decode("utf-8")
|
| 1444 |
+
update_user_password(user_id, new_hash)
|
| 1445 |
+
return {"message": "Password updated successfully"}
|
| 1446 |
+
|
| 1447 |
+
|
| 1448 |
+
@app.post("/admin/user/{user_id}/reset-password")
|
| 1449 |
+
async def admin_reset_password(user_id: int, admin=Depends(require_admin)):
|
| 1450 |
+
"""Admin resets any user password directly."""
|
| 1451 |
+
from api.database import get_user_by_id
|
| 1452 |
+
import bcrypt as _bcrypt, secrets
|
| 1453 |
+
user = get_user_by_id(user_id)
|
| 1454 |
+
if not user:
|
| 1455 |
+
raise HTTPException(status_code=404, detail="User not found")
|
| 1456 |
+
# Generate a new random password
|
| 1457 |
+
new_password = secrets.token_urlsafe(10)
|
| 1458 |
+
new_hash = _bcrypt.hashpw(new_password.encode("utf-8"), _bcrypt.gensalt()).decode("utf-8")
|
| 1459 |
+
from api.database import get_conn
|
| 1460 |
+
with get_conn() as conn:
|
| 1461 |
+
conn.execute("UPDATE users SET password_hash=? WHERE id=?", (new_hash, user_id))
|
| 1462 |
+
return {
|
| 1463 |
+
"user_id": user_id,
|
| 1464 |
+
"username": user["username"],
|
| 1465 |
+
"new_password": new_password,
|
| 1466 |
+
"message": "Password reset. Share this with the user and ask them to change it after login."
|
| 1467 |
+
}
|
| 1468 |
+
|
| 1469 |
+
|
| 1470 |
+
@app.get("/admin/logs")
|
| 1471 |
+
async def admin_get_all_logs(admin=Depends(require_admin)):
|
| 1472 |
+
"""Return recent activity logs across all users."""
|
| 1473 |
+
from api.database import get_all_logs
|
| 1474 |
+
return {"logs": get_all_logs(limit=500)}
|
| 1475 |
+
|
| 1476 |
+
|
| 1477 |
+
@app.get("/admin/user/{user_id}/logs")
|
| 1478 |
+
async def admin_get_user_logs(user_id: int, admin=Depends(require_admin)):
|
| 1479 |
+
"""Return activity logs for a specific user."""
|
| 1480 |
+
from api.database import get_user_logs
|
| 1481 |
+
return {"user_id": user_id, "logs": get_user_logs(user_id, limit=200)}
|
| 1482 |
+
|
| 1483 |
+
|
| 1484 |
+
# ββ Serve frontend static files βββββββββββββββββββββββββββββββββββββββββββββββ
|
| 1485 |
+
FRONTEND_DIR = os.path.normpath(
|
| 1486 |
+
os.path.join(os.path.dirname(os.path.abspath(__file__)), "..", "frontend")
|
| 1487 |
+
)
|
| 1488 |
+
|
| 1489 |
+
# Serve frontend β explicit HTMLResponse ensures correct Content-Type on all
|
| 1490 |
+
# browsers and proxies (HuggingFace, ngrok, mobile Safari, etc.)
|
| 1491 |
+
from fastapi.responses import HTMLResponse
|
| 1492 |
+
|
| 1493 |
+
def _read_html(filename: str) -> str:
|
| 1494 |
+
path = os.path.join(FRONTEND_DIR, filename)
|
| 1495 |
+
with open(path, "r", encoding="utf-8") as f:
|
| 1496 |
+
return f.read()
|
| 1497 |
+
|
| 1498 |
+
# Mount static files
|
| 1499 |
+
if os.path.isdir(FRONTEND_DIR):
|
| 1500 |
+
app.mount("/static", StaticFiles(directory=FRONTEND_DIR), name="static")
|
| 1501 |
+
|
| 1502 |
+
# ββ Frontend routes β registered unconditionally so HF proxy never 404s ββββββ
|
| 1503 |
+
# Explicit HTMLResponse (not FileResponse) ensures correct Content-Type
|
| 1504 |
+
# on all clients including mobile Safari, Android Chrome, and HF proxy.
|
| 1505 |
+
|
| 1506 |
+
@app.get("/", response_class=HTMLResponse)
|
| 1507 |
+
async def serve_index():
|
| 1508 |
+
return HTMLResponse(content=_read_html("index.html"), status_code=200)
|
| 1509 |
+
|
| 1510 |
+
@app.get("/chat-ui", response_class=HTMLResponse)
|
| 1511 |
+
async def serve_chat():
|
| 1512 |
+
return HTMLResponse(content=_read_html("chat.html"), status_code=200)
|
| 1513 |
+
|
| 1514 |
+
@app.get("/chat-ui/", response_class=HTMLResponse)
|
| 1515 |
+
async def serve_chat_slash():
|
| 1516 |
+
return HTMLResponse(content=_read_html("chat.html"), status_code=200)
|
| 1517 |
+
|
| 1518 |
+
@app.get("/chat", response_class=HTMLResponse)
|
| 1519 |
+
async def serve_chat_alt():
|
| 1520 |
+
"""Alias β /chat redirects to chat UI on mobile browsers."""
|
| 1521 |
+
return HTMLResponse(content=_read_html("chat.html"), status_code=200)
|
| 1522 |
+
|
| 1523 |
+
@app.get("/admin", response_class=HTMLResponse)
|
| 1524 |
+
async def serve_admin_main():
|
| 1525 |
+
return HTMLResponse(content=_read_html("admin.html"), status_code=200)
|
| 1526 |
+
|
| 1527 |
+
@app.get("/admin/", response_class=HTMLResponse)
|
| 1528 |
+
async def serve_admin_slash_main():
|
| 1529 |
+
return HTMLResponse(content=_read_html("admin.html"), status_code=200)
|
| 1530 |
+
|
| 1531 |
+
|
| 1532 |
+
if __name__ == "__main__":
|
| 1533 |
+
import uvicorn
|
| 1534 |
+
uvicorn.run("api.main:app", host="0.0.0.0", port=8000, reload=True)
|
api/memory.py
ADDED
|
@@ -0,0 +1,92 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
NeuroCheck Agentic AI β Session Memory
|
| 3 |
+
File-based session store: no Redis required for local deployment.
|
| 4 |
+
Each session is a JSON file in /tmp/neurocheck_sessions/.
|
| 5 |
+
"""
|
| 6 |
+
from __future__ import annotations
|
| 7 |
+
import json, uuid, os
|
| 8 |
+
from datetime import datetime
|
| 9 |
+
from pathlib import Path
|
| 10 |
+
from typing import List, Dict, Any
|
| 11 |
+
|
| 12 |
+
SESSION_DIR = Path("/tmp/neurocheck_sessions")
|
| 13 |
+
SESSION_DIR.mkdir(parents=True, exist_ok=True)
|
| 14 |
+
|
| 15 |
+
MAX_HISTORY = 40 # max messages kept per session
|
| 16 |
+
|
| 17 |
+
|
| 18 |
+
def new_session() -> str:
|
| 19 |
+
"""Create a new session and return its ID."""
|
| 20 |
+
sid = str(uuid.uuid4())
|
| 21 |
+
_write(sid, {
|
| 22 |
+
"session_id": sid,
|
| 23 |
+
"created_at": _now(),
|
| 24 |
+
"messages": [],
|
| 25 |
+
"classification": None,
|
| 26 |
+
"symptoms_collected": [],
|
| 27 |
+
})
|
| 28 |
+
return sid
|
| 29 |
+
|
| 30 |
+
|
| 31 |
+
def get_session(sid: str) -> Dict[str, Any] | None:
|
| 32 |
+
p = _path(sid)
|
| 33 |
+
if not p.exists():
|
| 34 |
+
return None
|
| 35 |
+
return json.loads(p.read_text())
|
| 36 |
+
|
| 37 |
+
|
| 38 |
+
def append_message(sid: str, role: str, content: str) -> None:
|
| 39 |
+
"""Append a human/assistant message to session history."""
|
| 40 |
+
s = get_session(sid)
|
| 41 |
+
if s is None:
|
| 42 |
+
return
|
| 43 |
+
s["messages"].append({"role": role, "content": content, "ts": _now()})
|
| 44 |
+
# Keep last MAX_HISTORY messages
|
| 45 |
+
if len(s["messages"]) > MAX_HISTORY:
|
| 46 |
+
s["messages"] = s["messages"][-MAX_HISTORY:]
|
| 47 |
+
_write(sid, s)
|
| 48 |
+
|
| 49 |
+
|
| 50 |
+
def set_classification(sid: str, classification: Dict[str, Any]) -> None:
|
| 51 |
+
s = get_session(sid)
|
| 52 |
+
if s is None:
|
| 53 |
+
return
|
| 54 |
+
s["classification"] = classification
|
| 55 |
+
_write(sid, s)
|
| 56 |
+
|
| 57 |
+
|
| 58 |
+
def get_history(sid: str) -> List[Dict[str, str]]:
|
| 59 |
+
s = get_session(sid)
|
| 60 |
+
if s is None:
|
| 61 |
+
return []
|
| 62 |
+
return s.get("messages", [])
|
| 63 |
+
|
| 64 |
+
|
| 65 |
+
def get_lc_messages(sid: str):
|
| 66 |
+
"""Return LangChain-compatible message list for context injection."""
|
| 67 |
+
from langchain_core.messages import HumanMessage, AIMessage
|
| 68 |
+
msgs = get_history(sid)
|
| 69 |
+
lc = []
|
| 70 |
+
for m in msgs:
|
| 71 |
+
if m["role"] == "human":
|
| 72 |
+
lc.append(HumanMessage(content=m["content"]))
|
| 73 |
+
else:
|
| 74 |
+
lc.append(AIMessage(content=m["content"]))
|
| 75 |
+
return lc
|
| 76 |
+
|
| 77 |
+
|
| 78 |
+
def list_sessions() -> List[str]:
|
| 79 |
+
return [p.stem for p in SESSION_DIR.glob("*.json")]
|
| 80 |
+
|
| 81 |
+
|
| 82 |
+
# ββ Internal helpers ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 83 |
+
def _path(sid: str) -> Path:
|
| 84 |
+
return SESSION_DIR / f"{sid}.json"
|
| 85 |
+
|
| 86 |
+
|
| 87 |
+
def _write(sid: str, data: Dict) -> None:
|
| 88 |
+
_path(sid).write_text(json.dumps(data, indent=2))
|
| 89 |
+
|
| 90 |
+
|
| 91 |
+
def _now() -> str:
|
| 92 |
+
return datetime.utcnow().isoformat() + "Z"
|
api/rag.py
ADDED
|
@@ -0,0 +1,232 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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5 |
+
"""
|
| 6 |
+
from __future__ import annotations
|
| 7 |
+
import os, zipfile, re
|
| 8 |
+
from pathlib import Path
|
| 9 |
+
from typing import List
|
| 10 |
+
from loguru import logger
|
| 11 |
+
|
| 12 |
+
import chromadb
|
| 13 |
+
from chromadb.utils.embedding_functions import SentenceTransformerEmbeddingFunction
|
| 14 |
+
|
| 15 |
+
# ββ Paths βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 16 |
+
BASE_DIR = Path(__file__).parent.parent
|
| 17 |
+
DOCX_PATH = BASE_DIR / "AGENTIC AI chatbots.docx"
|
| 18 |
+
CHROMA_DIR = Path(os.environ.get("CHROMA_DB_PATH", str(BASE_DIR / "chroma_db")))
|
| 19 |
+
|
| 20 |
+
# ββ Embedding model (local, no API key) ββββββββββββββββββββββββββββββββββββββ
|
| 21 |
+
EMBED_MODEL = "all-MiniLM-L6-v2" # ~90MB, fast, good for clinical text
|
| 22 |
+
|
| 23 |
+
_client: chromadb.PersistentClient | None = None
|
| 24 |
+
_collection = None
|
| 25 |
+
|
| 26 |
+
|
| 27 |
+
def get_collection():
|
| 28 |
+
global _client, _collection
|
| 29 |
+
if _collection is not None:
|
| 30 |
+
return _collection
|
| 31 |
+
ef = SentenceTransformerEmbeddingFunction(model_name=EMBED_MODEL)
|
| 32 |
+
_client = chromadb.PersistentClient(path=str(CHROMA_DIR))
|
| 33 |
+
_collection = _client.get_or_create_collection(
|
| 34 |
+
name="ms_knowledge",
|
| 35 |
+
embedding_function=ef,
|
| 36 |
+
metadata={"hnsw:space": "cosine"},
|
| 37 |
+
)
|
| 38 |
+
return _collection
|
| 39 |
+
|
| 40 |
+
|
| 41 |
+
def build_knowledge_base(force: bool = False) -> None:
|
| 42 |
+
"""
|
| 43 |
+
Build the ChromaDB vector store from the docx file.
|
| 44 |
+
Only runs if the collection is empty (or force=True).
|
| 45 |
+
"""
|
| 46 |
+
col = get_collection()
|
| 47 |
+
if col.count() > 0 and not force:
|
| 48 |
+
logger.info(f"[RAG] Knowledge base already built ({col.count()} chunks). Skipping.")
|
| 49 |
+
return
|
| 50 |
+
|
| 51 |
+
logger.info("[RAG] Building knowledge base from docx...")
|
| 52 |
+
docs = _extract_docx(DOCX_PATH)
|
| 53 |
+
docs += _ms_guidelines() # inject hard-coded clinical knowledge
|
| 54 |
+
chunks = _chunk_documents(docs)
|
| 55 |
+
|
| 56 |
+
ids = [f"doc_{i}" for i in range(len(chunks))]
|
| 57 |
+
texts = [c["text"] for c in chunks]
|
| 58 |
+
metas = [c["meta"] for c in chunks]
|
| 59 |
+
|
| 60 |
+
# Upsert in batches of 100
|
| 61 |
+
for i in range(0, len(texts), 100):
|
| 62 |
+
col.upsert(
|
| 63 |
+
ids=ids[i:i+100],
|
| 64 |
+
documents=texts[i:i+100],
|
| 65 |
+
metadatas=metas[i:i+100],
|
| 66 |
+
)
|
| 67 |
+
|
| 68 |
+
logger.info(f"[RAG] Knowledge base ready: {col.count()} chunks indexed.")
|
| 69 |
+
|
| 70 |
+
|
| 71 |
+
def query(text: str, n_results: int = 5) -> List[dict]:
|
| 72 |
+
"""Return top-n relevant knowledge chunks for a given query."""
|
| 73 |
+
col = get_collection()
|
| 74 |
+
if col.count() == 0:
|
| 75 |
+
return []
|
| 76 |
+
results = col.query(query_texts=[text], n_results=min(n_results, col.count()))
|
| 77 |
+
output = []
|
| 78 |
+
for doc, meta, dist in zip(
|
| 79 |
+
results["documents"][0],
|
| 80 |
+
results["metadatas"][0],
|
| 81 |
+
results["distances"][0],
|
| 82 |
+
):
|
| 83 |
+
output.append({"text": doc, "source": meta.get("source", ""), "score": round(1 - dist, 3)})
|
| 84 |
+
return output
|
| 85 |
+
|
| 86 |
+
|
| 87 |
+
# ββ Document extraction βββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 88 |
+
def _extract_docx(path: Path) -> List[dict]:
|
| 89 |
+
if not path.exists():
|
| 90 |
+
logger.warning(f"[RAG] Docx not found at {path}")
|
| 91 |
+
return []
|
| 92 |
+
import xml.etree.ElementTree as ET
|
| 93 |
+
docs = []
|
| 94 |
+
with zipfile.ZipFile(str(path)) as z:
|
| 95 |
+
xml = z.read("word/document.xml")
|
| 96 |
+
root = ET.fromstring(xml)
|
| 97 |
+
ns = "{http://schemas.openxmlformats.org/wordprocessingml/2006/main}"
|
| 98 |
+
paras = []
|
| 99 |
+
for para in root.iter(f"{ns}p"):
|
| 100 |
+
line = "".join(node.text or "" for node in para.iter(f"{ns}t")).strip()
|
| 101 |
+
if line:
|
| 102 |
+
paras.append(line)
|
| 103 |
+
|
| 104 |
+
# Group into logical blocks of 3 paragraphs for context
|
| 105 |
+
for i in range(0, len(paras), 3):
|
| 106 |
+
block = " ".join(paras[i:i+3])
|
| 107 |
+
docs.append({"text": block, "meta": {"source": "AGENTIC_AI_chatbots.docx"}})
|
| 108 |
+
return docs
|
| 109 |
+
|
| 110 |
+
|
| 111 |
+
def _ms_guidelines() -> List[dict]:
|
| 112 |
+
"""Hard-coded authoritative MS clinical guidelines as RAG knowledge."""
|
| 113 |
+
guidelines = [
|
| 114 |
+
{
|
| 115 |
+
"text": (
|
| 116 |
+
"McDonald Criteria 2024: MS diagnosis requires dissemination in space (DIS) "
|
| 117 |
+
"and dissemination in time (DIT). DIS: lesions in β₯2 CNS regions (periventricular, "
|
| 118 |
+
"cortical/juxtacortical, infratentorial, spinal cord, optic nerve). "
|
| 119 |
+
"DIT: new T2/gadolinium lesion on follow-up MRI, or simultaneous enhancing + non-enhancing lesions."
|
| 120 |
+
),
|
| 121 |
+
"meta": {"source": "McDonald_Criteria_2024"},
|
| 122 |
+
},
|
| 123 |
+
{
|
| 124 |
+
"text": (
|
| 125 |
+
"MS Workup Standard: MRI orbits with/without contrast for optic nerve involvement. "
|
| 126 |
+
"MRI brain and spinal cord with/without contrast. Lumbar puncture: CSF oligoclonal bands "
|
| 127 |
+
">2 exclusive to CSF, elevated IgG index, kappa free light chains. "
|
| 128 |
+
"Serum cell-based assay for NMO (AQP4-IgG) and MOGAD (MOG-IgG). "
|
| 129 |
+
"Exclude mimics: sarcoidosis, lupus, vasculitis, B12 deficiency, cervical myelopathy."
|
| 130 |
+
),
|
| 131 |
+
"meta": {"source": "MS_Workup_Protocol"},
|
| 132 |
+
},
|
| 133 |
+
{
|
| 134 |
+
"text": (
|
| 135 |
+
"Optic Neuritis classic triad: monocular visual loss + pain on eye movement + dyschromatopsia "
|
| 136 |
+
"(red colour desaturation). Peak age 20-45. Female predominance. "
|
| 137 |
+
"Uhthoff phenomenon: vision worsens with heat/exercise. "
|
| 138 |
+
"Recovery in 85% within 3 months. Risk of MS after ON: 50% at 15 years."
|
| 139 |
+
),
|
| 140 |
+
"meta": {"source": "NINDS_Optic_Neuritis"},
|
| 141 |
+
},
|
| 142 |
+
{
|
| 143 |
+
"text": (
|
| 144 |
+
"NMOSD (Neuromyelitis Optica Spectrum Disorder): AQP4-IgG positive. "
|
| 145 |
+
"Area postrema syndrome: intractable hiccups + nausea/vomiting. "
|
| 146 |
+
"LETM: longitudinally extensive transverse myelitis >3 vertebral segments. "
|
| 147 |
+
"Bilateral/severe optic neuritis. Periependymal brain lesions. "
|
| 148 |
+
"Distinguished from MS by AQP4-IgG serum test (cell-based assay)."
|
| 149 |
+
),
|
| 150 |
+
"meta": {"source": "NMOSD_Guidelines"},
|
| 151 |
+
},
|
| 152 |
+
{
|
| 153 |
+
"text": (
|
| 154 |
+
"MOGAD (MOG-Antibody Associated Disease): MOG-IgG positive. "
|
| 155 |
+
"ADEM-like presentation with large hazy confluent white matter lesions. "
|
| 156 |
+
"Optic perineuritis (sheath enhancement, not nerve). Conus medullaris involvement. "
|
| 157 |
+
"Often affects younger patients. Differentiated by MOG-IgG cell-based assay."
|
| 158 |
+
),
|
| 159 |
+
"meta": {"source": "MOGAD_Guidelines"},
|
| 160 |
+
},
|
| 161 |
+
{
|
| 162 |
+
"text": (
|
| 163 |
+
"Lhermitte's Sign: Electric shock sensation down spine on neck flexion. "
|
| 164 |
+
"Pathognomonic for cervical cord demyelination. "
|
| 165 |
+
"Uhthoff Phenomenon: worsening of any MS symptom with heat, exercise, fever, hot bath. "
|
| 166 |
+
"MS Hug: tight band sensation around trunk/chest β thoracic cord lesion. "
|
| 167 |
+
"These are anchor features requiring urgent neurology referral."
|
| 168 |
+
),
|
| 169 |
+
"meta": {"source": "MS_Anchor_Symptoms"},
|
| 170 |
+
},
|
| 171 |
+
{
|
| 172 |
+
"text": (
|
| 173 |
+
"IIH vs MS in obese patients: IIH (idiopathic intracranial hypertension) "
|
| 174 |
+
"typically presents with papilledema, headache, pulsatile tinnitus in obese females. "
|
| 175 |
+
"However, MS can coexist. If colour vision is impaired (dyschromatopsia) in IIH, "
|
| 176 |
+
"suspect concurrent optic neuritis. Heavy legs, motor symptoms, or prior transient "
|
| 177 |
+
"neurological episodes in obese patients must trigger MS workup."
|
| 178 |
+
),
|
| 179 |
+
"meta": {"source": "IIH_MS_Overlap"},
|
| 180 |
+
},
|
| 181 |
+
{
|
| 182 |
+
"text": (
|
| 183 |
+
"CSF Analysis in MS: Oligoclonal bands (OCBs) >2 exclusive to CSF (not serum) β "
|
| 184 |
+
"present in 85-95% of MS. IgG index >0.7 (elevated). IgG synthesis rate elevated. "
|
| 185 |
+
"Kappa free light chains substitute for OCBs where OCB testing unavailable. "
|
| 186 |
+
"Cell count <50 lymphocytes. Glucose and protein usually normal. "
|
| 187 |
+
"Paired serum-CSF sample essential for OCB interpretation."
|
| 188 |
+
),
|
| 189 |
+
"meta": {"source": "CSF_MS_Protocol"},
|
| 190 |
+
},
|
| 191 |
+
{
|
| 192 |
+
"text": (
|
| 193 |
+
"Internuclear Ophthalmoplegia (INO): failure of ipsilateral eye adduction on lateral gaze "
|
| 194 |
+
"with contralateral eye nystagmus. Caused by MLF lesion. Bilateral INO pathognomonic for MS. "
|
| 195 |
+
"Sixth nerve palsy: lateral gaze palsy. Skew deviation: vertical misalignment of eyes. "
|
| 196 |
+
"Any new diplopia in young adult β MS must be excluded."
|
| 197 |
+
),
|
| 198 |
+
"meta": {"source": "MS_Eye_Movement_Disorders"},
|
| 199 |
+
},
|
| 200 |
+
{
|
| 201 |
+
"text": (
|
| 202 |
+
"Trigeminal Neuralgia in young adults (<45): electric shock face/jaw pain. "
|
| 203 |
+
"When occurring in young patients without vascular loop compression, MS pons lesion "
|
| 204 |
+
"must be excluded. MRI brain with specific pons protocol required. "
|
| 205 |
+
"Facial numbness + diplopia combination suggests brainstem MS lesion."
|
| 206 |
+
),
|
| 207 |
+
"meta": {"source": "TN_MS_Brainstem"},
|
| 208 |
+
},
|
| 209 |
+
]
|
| 210 |
+
return guidelines
|
| 211 |
+
|
| 212 |
+
|
| 213 |
+
def _chunk_documents(docs: List[dict], max_len: int = 400) -> List[dict]:
|
| 214 |
+
"""Split long texts into overlapping chunks."""
|
| 215 |
+
out = []
|
| 216 |
+
for d in docs:
|
| 217 |
+
text = d["text"]
|
| 218 |
+
if len(text) <= max_len:
|
| 219 |
+
out.append(d)
|
| 220 |
+
else:
|
| 221 |
+
# Split by sentence boundaries
|
| 222 |
+
sentences = re.split(r"(?<=[.!?])\s+", text)
|
| 223 |
+
chunk, chunk_len = [], 0
|
| 224 |
+
for s in sentences:
|
| 225 |
+
if chunk_len + len(s) > max_len and chunk:
|
| 226 |
+
out.append({"text": " ".join(chunk), "meta": d["meta"]})
|
| 227 |
+
chunk, chunk_len = [], 0
|
| 228 |
+
chunk.append(s)
|
| 229 |
+
chunk_len += len(s)
|
| 230 |
+
if chunk:
|
| 231 |
+
out.append({"text": " ".join(chunk), "meta": d["meta"]})
|
| 232 |
+
return out
|
frontend/admin.html
ADDED
|
@@ -0,0 +1,534 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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 |
+
<head>
|
| 4 |
+
<meta charset="UTF-8">
|
| 5 |
+
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
| 6 |
+
<title>AxonIQ β Admin Panel</title>
|
| 7 |
+
<link href="https://fonts.googleapis.com/css2?family=Libre+Baskerville:wght@400;700&family=DM+Sans:wght@300;400;500;600&family=DM+Mono:wght@400;500&display=swap" rel="stylesheet">
|
| 8 |
+
<style>
|
| 9 |
+
:root {
|
| 10 |
+
--navy:#0B1F3A;--teal:#0A7B74;--teal-lt:#E6F5F4;--red:#B53535;--amber:#C97B2A;
|
| 11 |
+
--sand:#F5F1EB;--warm-white:#FDFAF6;--border:#DDD8CF;--text:#1A1510;--muted:#6B6056;
|
| 12 |
+
}
|
| 13 |
+
*,*::before,*::after{box-sizing:border-box;margin:0;padding:0;}
|
| 14 |
+
body{font-family:'DM Sans',sans-serif;background:var(--warm-white);color:var(--text);min-height:100vh;}
|
| 15 |
+
|
| 16 |
+
/* AUTH */
|
| 17 |
+
#authOverlay{position:fixed;inset:0;background:rgba(11,31,58,0.92);backdrop-filter:blur(8px);display:flex;align-items:center;justify-content:center;z-index:100;}
|
| 18 |
+
.auth-card{background:#fff;border-radius:16px;padding:40px 44px;width:400px;max-width:95vw;box-shadow:0 24px 64px rgba(0,0,0,0.35);}
|
| 19 |
+
.auth-logo{display:flex;align-items:center;gap:12px;margin-bottom:28px;}
|
| 20 |
+
.auth-logo-mark{width:42px;height:42px;background:var(--red);border-radius:10px;display:flex;align-items:center;justify-content:center;font-size:18px;font-weight:700;color:#fff;font-family:'Libre Baskerville',serif;}
|
| 21 |
+
.auth-logo h2{font-family:'Libre Baskerville',serif;font-size:18px;color:var(--navy);font-weight:700;}
|
| 22 |
+
.auth-logo p{font-size:12px;color:var(--muted);}
|
| 23 |
+
.auth-field{margin-bottom:16px;}
|
| 24 |
+
.auth-field label{display:block;font-size:11px;font-weight:600;color:var(--muted);margin-bottom:6px;text-transform:uppercase;letter-spacing:0.5px;}
|
| 25 |
+
.auth-field input{width:100%;padding:11px 14px;border:1.5px solid var(--border);border-radius:9px;font-family:'DM Sans',sans-serif;font-size:14px;color:var(--text);outline:none;transition:border-color 0.2s;}
|
| 26 |
+
.auth-field input:focus{border-color:var(--red);}
|
| 27 |
+
.auth-btn{width:100%;padding:12px;background:var(--navy);color:#fff;border:none;border-radius:9px;font-family:'DM Sans',sans-serif;font-size:14px;font-weight:600;cursor:pointer;transition:background 0.2s;}
|
| 28 |
+
.auth-btn:hover{background:#162F52;}
|
| 29 |
+
.auth-error{background:#FEE2E2;border:1px solid #FECACA;border-radius:8px;padding:9px 14px;font-size:13px;color:#B91C1C;margin-bottom:14px;display:none;}
|
| 30 |
+
|
| 31 |
+
/* SHELL */
|
| 32 |
+
#adminShell{display:none;}
|
| 33 |
+
#adminShell.visible{display:block;}
|
| 34 |
+
header{background:var(--navy);padding:14px 28px;display:flex;align-items:center;gap:14px;border-bottom:3px solid var(--red);}
|
| 35 |
+
.logo-mark{width:34px;height:34px;background:var(--red);border-radius:8px;display:flex;align-items:center;justify-content:center;font-family:'Libre Baskerville',serif;font-size:15px;font-weight:700;color:#fff;}
|
| 36 |
+
.header-text h1{font-family:'Libre Baskerville',serif;font-size:17px;color:#fff;}
|
| 37 |
+
.header-text p{font-size:11px;color:#8FA8BF;}
|
| 38 |
+
.header-right{margin-left:auto;display:flex;align-items:center;gap:12px;}
|
| 39 |
+
.hdr-stat{background:rgba(255,255,255,0.08);border-radius:8px;padding:6px 14px;text-align:center;}
|
| 40 |
+
.hdr-stat .n{font-size:18px;font-weight:700;color:#fff;font-family:'Libre Baskerville',serif;}
|
| 41 |
+
.hdr-stat .l{font-size:10px;color:#8FA8BF;margin-top:1px;}
|
| 42 |
+
.sign-out-btn{background:rgba(181,53,53,0.2);border:1px solid rgba(181,53,53,0.4);color:#F87171;border-radius:8px;padding:6px 14px;font-size:12px;font-weight:500;cursor:pointer;transition:background 0.15s;}
|
| 43 |
+
.sign-out-btn:hover{background:rgba(181,53,53,0.35);}
|
| 44 |
+
|
| 45 |
+
/* LAYOUT */
|
| 46 |
+
.page{display:flex;height:calc(100vh - 59px);overflow:hidden;}
|
| 47 |
+
|
| 48 |
+
/* SIDEBAR */
|
| 49 |
+
.sidebar{width:280px;background:#F8F5F0;border-right:1px solid var(--border);display:flex;flex-direction:column;flex-shrink:0;}
|
| 50 |
+
.sidebar-section{padding:14px 16px 8px;border-bottom:1px solid var(--border);}
|
| 51 |
+
.sidebar-section-title{font-size:11px;font-weight:600;color:var(--muted);text-transform:uppercase;letter-spacing:0.6px;margin-bottom:8px;}
|
| 52 |
+
.search-input{width:100%;padding:8px 12px;border:1.5px solid var(--border);border-radius:8px;font-family:'DM Sans',sans-serif;font-size:13px;outline:none;background:#fff;}
|
| 53 |
+
.search-input:focus{border-color:var(--teal);}
|
| 54 |
+
.user-list{flex:1;overflow-y:auto;padding:8px;}
|
| 55 |
+
.user-list::-webkit-scrollbar{width:4px;}
|
| 56 |
+
.user-list::-webkit-scrollbar-thumb{background:var(--border);border-radius:2px;}
|
| 57 |
+
.user-item{padding:10px 12px;border-radius:9px;cursor:pointer;transition:background 0.12s;margin-bottom:2px;}
|
| 58 |
+
.user-item:hover{background:#EDEBE6;}
|
| 59 |
+
.user-item.active{background:var(--teal-lt);border-left:3px solid var(--teal);}
|
| 60 |
+
.user-item-name{font-size:13px;font-weight:600;color:var(--text);}
|
| 61 |
+
.user-item-meta{font-size:11px;color:var(--muted);margin-top:2px;}
|
| 62 |
+
.user-badge{display:inline-block;background:var(--teal-lt);color:var(--teal);font-size:10px;font-weight:600;padding:1px 7px;border-radius:10px;margin-left:6px;}
|
| 63 |
+
|
| 64 |
+
/* MAIN */
|
| 65 |
+
.main{flex:1;overflow-y:auto;padding:24px 28px;}
|
| 66 |
+
.main::-webkit-scrollbar{width:6px;}
|
| 67 |
+
.main::-webkit-scrollbar-thumb{background:var(--border);border-radius:3px;}
|
| 68 |
+
|
| 69 |
+
/* EMPTY STATE */
|
| 70 |
+
.empty-state{display:flex;flex-direction:column;align-items:center;justify-content:center;height:100%;gap:12px;color:var(--muted);}
|
| 71 |
+
.empty-state .icon{font-size:48px;opacity:0.4;}
|
| 72 |
+
.empty-state p{font-size:14px;}
|
| 73 |
+
|
| 74 |
+
/* USER HEADER */
|
| 75 |
+
.user-header{display:flex;align-items:center;gap:16px;margin-bottom:24px;padding-bottom:20px;border-bottom:1px solid var(--border);}
|
| 76 |
+
.user-avatar-lg{width:52px;height:52px;border-radius:50%;background:var(--teal);display:flex;align-items:center;justify-content:center;font-size:22px;font-weight:700;color:#fff;}
|
| 77 |
+
.user-header-info h2{font-family:'Libre Baskerville',serif;font-size:20px;color:var(--navy);}
|
| 78 |
+
.user-header-info p{font-size:12px;color:var(--muted);margin-top:3px;}
|
| 79 |
+
.user-stats{display:flex;gap:16px;margin-left:auto;}
|
| 80 |
+
.user-stat{text-align:center;}
|
| 81 |
+
.user-stat .n{font-size:20px;font-weight:700;color:var(--navy);font-family:'Libre Baskerville',serif;}
|
| 82 |
+
.user-stat .l{font-size:11px;color:var(--muted);}
|
| 83 |
+
|
| 84 |
+
/* SESSIONS */
|
| 85 |
+
.sessions-grid{display:flex;flex-direction:column;gap:16px;}
|
| 86 |
+
.session-card{background:#fff;border:1px solid var(--border);border-radius:12px;overflow:hidden;}
|
| 87 |
+
.session-card-header{padding:14px 18px;display:flex;align-items:center;gap:12px;cursor:pointer;background:#FAFAF8;border-bottom:1px solid var(--border);transition:background 0.12s;}
|
| 88 |
+
.session-card-header:hover{background:#F2F0EB;}
|
| 89 |
+
.session-card-header.open{background:var(--teal-lt);border-bottom-color:rgba(10,123,116,0.2);}
|
| 90 |
+
.session-icon{font-size:16px;}
|
| 91 |
+
.session-title-wrap{flex:1;min-width:0;}
|
| 92 |
+
.session-title{font-size:13px;font-weight:600;color:var(--text);white-space:nowrap;overflow:hidden;text-overflow:ellipsis;}
|
| 93 |
+
.session-date{font-size:11px;color:var(--muted);margin-top:2px;}
|
| 94 |
+
.session-toggle{font-size:12px;color:var(--muted);transition:transform 0.2s;}
|
| 95 |
+
.session-toggle.open{transform:rotate(180deg);}
|
| 96 |
+
.session-body{display:none;padding:0;}
|
| 97 |
+
.session-body.open{display:block;}
|
| 98 |
+
|
| 99 |
+
/* MESSAGES */
|
| 100 |
+
.msg-row{display:flex;gap:12px;padding:14px 18px;border-bottom:1px solid #F0EDE8;}
|
| 101 |
+
.msg-row:last-child{border-bottom:none;}
|
| 102 |
+
.msg-row.human{background:#FAFAF8;}
|
| 103 |
+
.msg-row.assistant{background:#fff;}
|
| 104 |
+
.msg-role{width:80px;flex-shrink:0;}
|
| 105 |
+
.msg-role-badge{display:inline-block;font-size:10px;font-weight:600;padding:2px 8px;border-radius:10px;text-transform:uppercase;letter-spacing:0.4px;}
|
| 106 |
+
.msg-role-badge.human{background:#E0EAF4;color:#185FA5;}
|
| 107 |
+
.msg-role-badge.assistant{background:var(--teal-lt);color:var(--teal);}
|
| 108 |
+
.msg-content{flex:1;font-size:13px;color:var(--text);line-height:1.7;white-space:pre-wrap;word-break:break-word;}
|
| 109 |
+
.msg-time{font-size:10px;color:#C0B8AF;flex-shrink:0;padding-top:2px;font-family:'DM Mono',monospace;}
|
| 110 |
+
|
| 111 |
+
/* EXPORT */
|
| 112 |
+
.export-bar{display:flex;gap:10px;margin-bottom:20px;align-items:center;}
|
| 113 |
+
.export-btn{padding:8px 18px;border-radius:8px;font-family:'DM Sans',sans-serif;font-size:13px;font-weight:500;cursor:pointer;border:1.5px solid var(--border);background:#fff;color:var(--text);transition:background 0.15s,border-color 0.15s;}
|
| 114 |
+
.export-btn:hover{background:var(--sand);border-color:var(--teal);}
|
| 115 |
+
.export-btn.primary{background:var(--navy);color:#fff;border-color:var(--navy);}
|
| 116 |
+
.export-btn.primary:hover{background:#162F52;}
|
| 117 |
+
.section-label{font-size:12px;color:var(--muted);margin-left:auto;}
|
| 118 |
+
|
| 119 |
+
/* LOADING */
|
| 120 |
+
.loading{display:flex;align-items:center;gap:8px;padding:20px;font-size:13px;color:var(--muted);}
|
| 121 |
+
.spin{width:16px;height:16px;border:2px solid var(--border);border-top-color:var(--teal);border-radius:50%;animation:spin 0.7s linear infinite;flex-shrink:0;}
|
| 122 |
+
@keyframes spin{to{transform:rotate(360deg);}}
|
| 123 |
+
|
| 124 |
+
/* LOGS */
|
| 125 |
+
.log-table{width:100%;border-collapse:collapse;font-size:12px;}
|
| 126 |
+
.log-table th{text-align:left;padding:8px 12px;font-size:10px;font-weight:600;color:var(--muted);text-transform:uppercase;letter-spacing:0.5px;border-bottom:1px solid var(--border);background:#FAFAF8;}
|
| 127 |
+
.log-table td{padding:8px 12px;border-bottom:1px solid #F0EDE8;vertical-align:top;color:var(--text);}
|
| 128 |
+
.log-table tr:hover td{background:#FAFAF8;}
|
| 129 |
+
.log-action{display:inline-block;font-size:10px;font-weight:600;padding:2px 8px;border-radius:10px;white-space:nowrap;}
|
| 130 |
+
.log-REGISTER{background:#D1FAE5;color:#065F46;}
|
| 131 |
+
.log-LOGIN{background:#DBEAFE;color:#1E40AF;}
|
| 132 |
+
.log-CHAT_MESSAGE{background:var(--teal-lt);color:var(--teal);}
|
| 133 |
+
.log-tabs{display:flex;gap:0;margin-bottom:20px;border:1.5px solid var(--border);border-radius:10px;overflow:hidden;width:fit-content;}
|
| 134 |
+
.log-tab{padding:8px 20px;font-size:13px;font-weight:500;cursor:pointer;background:none;border:none;color:var(--muted);transition:background 0.15s,color 0.15s;}
|
| 135 |
+
.log-tab.active{background:var(--navy);color:#fff;}
|
| 136 |
+
|
| 137 |
+
/* CONCLUSION */
|
| 138 |
+
.conclusion-bar{background:#F8F5F0;border-top:1px solid var(--border);padding:12px 18px;display:flex;gap:16px;flex-wrap:wrap;align-items:flex-start;}
|
| 139 |
+
.conclusion-tier{font-size:13px;font-weight:700;padding:3px 12px;border-radius:20px;white-space:nowrap;}
|
| 140 |
+
.tier-LOW{background:#D1FAE5;color:#065F46;}
|
| 141 |
+
.tier-WATCH{background:#EDE9FE;color:#5B21B6;}
|
| 142 |
+
.tier-MODERATE{background:#DBEAFE;color:#1E40AF;}
|
| 143 |
+
.tier-HIGH{background:#FEF3C7;color:#92400E;}
|
| 144 |
+
.tier-CRITICAL_EMERGENCY{background:#FEE2E2;color:#B91C1C;}
|
| 145 |
+
.conclusion-block{flex:1;min-width:180px;}
|
| 146 |
+
.conclusion-label{font-size:10px;font-weight:600;color:var(--muted);text-transform:uppercase;letter-spacing:0.5px;margin-bottom:4px;}
|
| 147 |
+
.conclusion-items{display:flex;flex-wrap:wrap;gap:4px;}
|
| 148 |
+
.conclusion-chip{font-size:11px;background:#fff;border:0.5px solid var(--border);border-radius:6px;padding:2px 8px;color:var(--text);}
|
| 149 |
+
.conclusion-action{font-size:12px;color:var(--text);line-height:1.5;font-style:italic;}
|
| 150 |
+
.no-conclusion{font-size:12px;color:var(--muted);padding:8px 18px;}
|
| 151 |
+
</style>
|
| 152 |
+
</head>
|
| 153 |
+
<body>
|
| 154 |
+
|
| 155 |
+
<!-- AUTH -->
|
| 156 |
+
<div id="authOverlay">
|
| 157 |
+
<div class="auth-card">
|
| 158 |
+
<div class="auth-logo">
|
| 159 |
+
<div class="auth-logo-mark">β</div>
|
| 160 |
+
<div><h2>AxonIQ Admin</h2><p>Restricted access β authorised personnel only</p></div>
|
| 161 |
+
</div>
|
| 162 |
+
<div id="authError" class="auth-error"></div>
|
| 163 |
+
<div class="auth-field">
|
| 164 |
+
<label>Username</label>
|
| 165 |
+
<input type="text" id="adminUser" placeholder="admin username" autocomplete="username">
|
| 166 |
+
</div>
|
| 167 |
+
<div class="auth-field">
|
| 168 |
+
<label>Password</label>
|
| 169 |
+
<input type="password" id="adminPass" placeholder="β’β’β’β’β’β’β’β’" autocomplete="current-password">
|
| 170 |
+
</div>
|
| 171 |
+
<button class="auth-btn" onclick="adminLogin()">Access Admin Panel</button>
|
| 172 |
+
</div>
|
| 173 |
+
</div>
|
| 174 |
+
|
| 175 |
+
<!-- SHELL -->
|
| 176 |
+
<div id="adminShell">
|
| 177 |
+
<header>
|
| 178 |
+
<div class="logo-mark">β</div>
|
| 179 |
+
<div class="header-text">
|
| 180 |
+
<h1>AxonIQ Admin</h1>
|
| 181 |
+
<p>User & Conversation Management</p>
|
| 182 |
+
</div>
|
| 183 |
+
<div class="header-right">
|
| 184 |
+
<div class="hdr-stat"><div class="n" id="statUsers">β</div><div class="l">Users</div></div>
|
| 185 |
+
<div class="hdr-stat"><div class="n" id="statSessions">β</div><div class="l">Sessions</div></div>
|
| 186 |
+
<div class="hdr-stat"><div class="n" id="statMessages">β</div><div class="l">Messages</div></div>
|
| 187 |
+
<button class="sign-out-btn" onclick="adminSignOut()">Sign Out</button>
|
| 188 |
+
</div>
|
| 189 |
+
</header>
|
| 190 |
+
|
| 191 |
+
<div class="page">
|
| 192 |
+
<div class="sidebar">
|
| 193 |
+
<div class="sidebar-section">
|
| 194 |
+
<div class="sidebar-section-title">Users</div>
|
| 195 |
+
<input type="text" class="search-input" id="userSearch" placeholder="Search usersβ¦" oninput="filterUsers()">
|
| 196 |
+
</div>
|
| 197 |
+
<div class="user-list" id="userList">
|
| 198 |
+
<div class="loading"><div class="spin"></div> Loading usersβ¦</div>
|
| 199 |
+
</div>
|
| 200 |
+
<div style="padding:12px 16px;border-top:1px solid var(--border);">
|
| 201 |
+
<button class="new-chat-side" style="width:100%;" onclick="showAllLogs()">π View All Logs</button>
|
| 202 |
+
</div>
|
| 203 |
+
</div>
|
| 204 |
+
|
| 205 |
+
<div class="main" id="mainPanel">
|
| 206 |
+
<div class="empty-state">
|
| 207 |
+
<div class="icon">π€</div>
|
| 208 |
+
<p>Select a user from the sidebar to view their conversations</p>
|
| 209 |
+
</div>
|
| 210 |
+
</div>
|
| 211 |
+
</div>
|
| 212 |
+
</div>
|
| 213 |
+
|
| 214 |
+
<script>
|
| 215 |
+
const API = window.location.origin;
|
| 216 |
+
let adminToken = sessionStorage.getItem('nc_admin_token') || null;
|
| 217 |
+
let allUsers = [];
|
| 218 |
+
let selectedUserId = null;
|
| 219 |
+
|
| 220 |
+
window.addEventListener('DOMContentLoaded', () => {
|
| 221 |
+
document.getElementById('adminPass').addEventListener('keydown', e => { if(e.key==='Enter') adminLogin(); });
|
| 222 |
+
if (adminToken) showAdmin();
|
| 223 |
+
});
|
| 224 |
+
|
| 225 |
+
// ββ Auth ββ
|
| 226 |
+
async function adminLogin() {
|
| 227 |
+
const user = document.getElementById('adminUser').value.trim();
|
| 228 |
+
const pass = document.getElementById('adminPass').value;
|
| 229 |
+
const err = document.getElementById('authError');
|
| 230 |
+
err.style.display = 'none';
|
| 231 |
+
if (!user || !pass) { err.textContent='Fill in all fields'; err.style.display='block'; return; }
|
| 232 |
+
|
| 233 |
+
const form = new URLSearchParams();
|
| 234 |
+
form.append('username', user);
|
| 235 |
+
form.append('password', pass);
|
| 236 |
+
|
| 237 |
+
try {
|
| 238 |
+
const res = await fetch(`${API}/auth/login`, {
|
| 239 |
+
method:'POST', headers:{'Content-Type':'application/x-www-form-urlencoded'}, body:form
|
| 240 |
+
});
|
| 241 |
+
const data = await res.json();
|
| 242 |
+
if (!res.ok) throw new Error(data.detail || 'Login failed');
|
| 243 |
+
|
| 244 |
+
// Check admin flag
|
| 245 |
+
const meRes = await fetch(`${API}/auth/me`, { headers:{'Authorization':`Bearer ${data.access_token}`} });
|
| 246 |
+
const me = await meRes.json();
|
| 247 |
+
if (!me.is_admin) throw new Error('Access denied β not an admin account');
|
| 248 |
+
|
| 249 |
+
adminToken = data.access_token;
|
| 250 |
+
sessionStorage.setItem('nc_admin_token', adminToken);
|
| 251 |
+
showAdmin();
|
| 252 |
+
} catch(e) {
|
| 253 |
+
err.textContent = e.message;
|
| 254 |
+
err.style.display = 'block';
|
| 255 |
+
}
|
| 256 |
+
}
|
| 257 |
+
|
| 258 |
+
function adminSignOut() {
|
| 259 |
+
sessionStorage.removeItem('nc_admin_token');
|
| 260 |
+
adminToken = null;
|
| 261 |
+
document.getElementById('adminShell').classList.remove('visible');
|
| 262 |
+
document.getElementById('authOverlay').style.display = 'flex';
|
| 263 |
+
}
|
| 264 |
+
|
| 265 |
+
function showAdmin() {
|
| 266 |
+
document.getElementById('authOverlay').style.display = 'none';
|
| 267 |
+
document.getElementById('adminShell').classList.add('visible');
|
| 268 |
+
loadDashboard();
|
| 269 |
+
}
|
| 270 |
+
|
| 271 |
+
function authFetch(path, opts={}) {
|
| 272 |
+
return fetch(`${API}${path}`, { ...opts, headers:{...(opts.headers||{}), 'Authorization':`Bearer ${adminToken}`} });
|
| 273 |
+
}
|
| 274 |
+
|
| 275 |
+
// ββ Dashboard ββ
|
| 276 |
+
async function loadDashboard() {
|
| 277 |
+
try {
|
| 278 |
+
const res = await authFetch('/admin/users');
|
| 279 |
+
const data = await res.json();
|
| 280 |
+
allUsers = data.users || [];
|
| 281 |
+
document.getElementById('statUsers').textContent = allUsers.length;
|
| 282 |
+
document.getElementById('statSessions').textContent = data.total_sessions || 0;
|
| 283 |
+
document.getElementById('statMessages').textContent = data.total_messages || 0;
|
| 284 |
+
renderUserList(allUsers);
|
| 285 |
+
} catch(e) { console.error(e); }
|
| 286 |
+
}
|
| 287 |
+
|
| 288 |
+
function renderUserList(users) {
|
| 289 |
+
const list = document.getElementById('userList');
|
| 290 |
+
if (!users.length) { list.innerHTML = '<div style="padding:16px;font-size:13px;color:var(--muted)">No users found</div>'; return; }
|
| 291 |
+
list.innerHTML = users.map(u => `
|
| 292 |
+
<div class="user-item ${u.id===selectedUserId?'active':''}" onclick="selectUser(${u.id},'${escHtml(u.username)}','${escHtml(u.email)}','${u.created_at}',${u.session_count},${u.message_count})">
|
| 293 |
+
<div class="user-item-name">${escHtml(u.username)}<span class="user-badge">${u.session_count}</span>
|
| 294 |
+
${u.latest_tier ? `<span class="conclusion-tier tier-${u.latest_tier}" style="font-size:9px;padding:1px 6px;margin-left:4px;">${u.latest_tier.replace('_',' ')}</span>` : ''}
|
| 295 |
+
</div>
|
| 296 |
+
<div class="user-item-meta">${escHtml(u.email)} Β· ${fmtDate(u.created_at)}</div>
|
| 297 |
+
</div>
|
| 298 |
+
`).join('');
|
| 299 |
+
}
|
| 300 |
+
|
| 301 |
+
function filterUsers() {
|
| 302 |
+
const q = document.getElementById('userSearch').value.toLowerCase();
|
| 303 |
+
renderUserList(allUsers.filter(u => u.username.toLowerCase().includes(q) || u.email.toLowerCase().includes(q)));
|
| 304 |
+
}
|
| 305 |
+
|
| 306 |
+
// ββ User Detail ββ
|
| 307 |
+
async function selectUser(id, username, email, createdAt, sessionCount, messageCount) {
|
| 308 |
+
selectedUserId = id;
|
| 309 |
+
document.querySelectorAll('.user-item').forEach(el => el.classList.remove('active'));
|
| 310 |
+
document.querySelectorAll('.user-item').forEach(el => {
|
| 311 |
+
if (el.querySelector('.user-item-name').textContent.startsWith(username)) el.classList.add('active');
|
| 312 |
+
});
|
| 313 |
+
|
| 314 |
+
const main = document.getElementById('mainPanel');
|
| 315 |
+
main.innerHTML = `<div class="loading"><div class="spin"></div> Loading conversationsβ¦</div>`;
|
| 316 |
+
|
| 317 |
+
try {
|
| 318 |
+
const res = await authFetch(`/admin/user/${id}/sessions`);
|
| 319 |
+
const data = await res.json();
|
| 320 |
+
const sessions = data.sessions || [];
|
| 321 |
+
|
| 322 |
+
main.innerHTML = `
|
| 323 |
+
<div class="user-header">
|
| 324 |
+
<div class="user-avatar-lg">${username[0].toUpperCase()}</div>
|
| 325 |
+
<div class="user-header-info">
|
| 326 |
+
<h2>${escHtml(username)}</h2>
|
| 327 |
+
<p>${escHtml(email)} Β· Joined ${fmtDate(createdAt)}</p>
|
| 328 |
+
</div>
|
| 329 |
+
<div class="user-stats">
|
| 330 |
+
<div class="user-stat"><div class="n">${sessionCount}</div><div class="l">Sessions</div></div>
|
| 331 |
+
<div class="user-stat"><div class="n">${messageCount}</div><div class="l">Messages</div></div>
|
| 332 |
+
<button class="export-btn" style="margin-left:8px;" onclick="showUserLogs(${id},'${escHtml(username)}')">π Logs</button>
|
| 333 |
+
<button class="export-btn" style="margin-left:4px;border-color:#FECACA;color:var(--red);" onclick="resetPassword(${id},'${escHtml(username)}')">π Reset PW</button>
|
| 334 |
+
</div>
|
| 335 |
+
</div>
|
| 336 |
+
<div class="export-bar">
|
| 337 |
+
<button class="export-btn primary" onclick="exportUserCSV(${id},'${username}')">β¬ Export CSV</button>
|
| 338 |
+
<button class="export-btn" onclick="exportUserJSON(${id},'${username}')">β¬ Export JSON</button>
|
| 339 |
+
<span class="section-label">${sessions.length} conversation${sessions.length!==1?'s':''}</span>
|
| 340 |
+
</div>
|
| 341 |
+
<div class="sessions-grid" id="sessionsGrid">
|
| 342 |
+
${sessions.length === 0
|
| 343 |
+
? '<div style="color:var(--muted);font-size:14px;padding:20px 0">No conversations yet.</div>'
|
| 344 |
+
: sessions.map((s,i) => renderSessionCard(s,i)).join('')}
|
| 345 |
+
</div>
|
| 346 |
+
`;
|
| 347 |
+
} catch(e) { main.innerHTML = `<div style="color:var(--red);padding:20px">Error loading sessions: ${e.message}</div>`; }
|
| 348 |
+
}
|
| 349 |
+
|
| 350 |
+
function renderSessionCard(s, idx) {
|
| 351 |
+
const msgs = s.messages || [];
|
| 352 |
+
const humanCount = msgs.filter(m=>m.role==='human').length;
|
| 353 |
+
const c = s.conclusion;
|
| 354 |
+
|
| 355 |
+
const conclusionHtml = c ? `
|
| 356 |
+
<div class="conclusion-bar">
|
| 357 |
+
<span class="conclusion-tier tier-${c.tier}">${escHtml(c.tier_label||c.tier)}</span>
|
| 358 |
+
${c.symptoms && c.symptoms.length ? `
|
| 359 |
+
<div class="conclusion-block">
|
| 360 |
+
<div class="conclusion-label">Detected Symptoms</div>
|
| 361 |
+
<div class="conclusion-items">
|
| 362 |
+
${c.symptoms.map(sym=>`<span class="conclusion-chip">${escHtml(sym)}</span>`).join('')}
|
| 363 |
+
</div>
|
| 364 |
+
</div>` : ''}
|
| 365 |
+
${c.workup && c.workup.length ? `
|
| 366 |
+
<div class="conclusion-block">
|
| 367 |
+
<div class="conclusion-label">Recommended Workup</div>
|
| 368 |
+
<div class="conclusion-items">
|
| 369 |
+
${c.workup.slice(0,3).map(w=>`<span class="conclusion-chip">${escHtml(w.substring(0,40)+(w.length>40?'β¦':''))}</span>`).join('')}
|
| 370 |
+
</div>
|
| 371 |
+
</div>` : ''}
|
| 372 |
+
${c.action ? `
|
| 373 |
+
<div class="conclusion-block" style="flex:2">
|
| 374 |
+
<div class="conclusion-label">Clinical Action</div>
|
| 375 |
+
<div class="conclusion-action">${escHtml(c.action)}</div>
|
| 376 |
+
</div>` : ''}
|
| 377 |
+
</div>` : `<div class="no-conclusion">No MS classification recorded for this session</div>`;
|
| 378 |
+
|
| 379 |
+
return `
|
| 380 |
+
<div class="session-card">
|
| 381 |
+
<div class="session-card-header" onclick="toggleSession('sess_${idx}')">
|
| 382 |
+
<div class="session-icon">π¬</div>
|
| 383 |
+
<div class="session-title-wrap">
|
| 384 |
+
<div class="session-title">${escHtml(s.title||'Untitled Chat')}
|
| 385 |
+
${c ? `<span class="conclusion-tier tier-${c.tier}" style="margin-left:8px;font-size:11px;">${escHtml(c.tier_label||c.tier)}</span>` : ''}
|
| 386 |
+
</div>
|
| 387 |
+
<div class="session-date">${fmtDateFull(s.created_at)} Β· ${humanCount} message${humanCount!==1?'s':''} from user</div>
|
| 388 |
+
</div>
|
| 389 |
+
<div class="session-toggle" id="toggle_sess_${idx}">βΌ</div>
|
| 390 |
+
</div>
|
| 391 |
+
<div class="session-body" id="sess_${idx}">
|
| 392 |
+
${conclusionHtml}
|
| 393 |
+
${msgs.map(m => `
|
| 394 |
+
<div class="msg-row ${m.role}">
|
| 395 |
+
<div class="msg-role"><span class="msg-role-badge ${m.role}">${m.role==='human'?'Patient':'AxonIQ'}</span></div>
|
| 396 |
+
<div class="msg-content">${escHtml(m.content)}</div>
|
| 397 |
+
<div class="msg-time">${fmtTime(m.created_at)}</div>
|
| 398 |
+
</div>
|
| 399 |
+
`).join('')}
|
| 400 |
+
</div>
|
| 401 |
+
</div>
|
| 402 |
+
`;
|
| 403 |
+
}
|
| 404 |
+
|
| 405 |
+
function toggleSession(id) {
|
| 406 |
+
const body = document.getElementById(id);
|
| 407 |
+
const toggle = document.getElementById('toggle_'+id);
|
| 408 |
+
const header = body.previousElementSibling;
|
| 409 |
+
const isOpen = body.classList.contains('open');
|
| 410 |
+
body.classList.toggle('open', !isOpen);
|
| 411 |
+
toggle.classList.toggle('open', !isOpen);
|
| 412 |
+
header.classList.toggle('open', !isOpen);
|
| 413 |
+
}
|
| 414 |
+
|
| 415 |
+
// ββ Export ββ
|
| 416 |
+
async function exportUserCSV(userId, username) {
|
| 417 |
+
const res = await authFetch(`/admin/user/${userId}/sessions`);
|
| 418 |
+
const data = await res.json();
|
| 419 |
+
const rows = [['username','session_title','role','content','timestamp']];
|
| 420 |
+
for (const s of (data.sessions||[])) {
|
| 421 |
+
for (const m of (s.messages||[])) {
|
| 422 |
+
rows.push([username, s.title||'', m.role, m.content.replace(/"/g,'""'), m.created_at]);
|
| 423 |
+
}
|
| 424 |
+
}
|
| 425 |
+
const csv = rows.map(r => r.map(c=>`"${c}"`).join(',')).join('\n');
|
| 426 |
+
download(`axoniq_${username}.csv`, csv, 'text/csv');
|
| 427 |
+
}
|
| 428 |
+
|
| 429 |
+
async function exportUserJSON(userId, username) {
|
| 430 |
+
const res = await authFetch(`/admin/user/${userId}/sessions`);
|
| 431 |
+
const data = await res.json();
|
| 432 |
+
download(`axoniq_${username}.json`, JSON.stringify(data, null, 2), 'application/json');
|
| 433 |
+
}
|
| 434 |
+
|
| 435 |
+
function download(filename, content, type) {
|
| 436 |
+
const a = document.createElement('a');
|
| 437 |
+
a.href = URL.createObjectURL(new Blob([content], {type}));
|
| 438 |
+
a.download = filename;
|
| 439 |
+
a.click();
|
| 440 |
+
}
|
| 441 |
+
|
| 442 |
+
// ββ Utils ββ
|
| 443 |
+
function escHtml(t) { return String(t).replace(/&/g,'&').replace(/</g,'<').replace(/>/g,'>').replace(/"/g,'"'); }
|
| 444 |
+
function fmtDate(iso) {
|
| 445 |
+
try { return new Date(iso).toLocaleDateString(undefined,{month:'short',day:'numeric',year:'numeric'}); } catch{return iso;}
|
| 446 |
+
}
|
| 447 |
+
function fmtDateFull(iso) {
|
| 448 |
+
try { return new Date(iso).toLocaleDateString(undefined,{month:'short',day:'numeric',year:'numeric',hour:'2-digit',minute:'2-digit'}); } catch{return iso;}
|
| 449 |
+
}
|
| 450 |
+
function fmtTime(iso) {
|
| 451 |
+
try {
|
| 452 |
+
const d=new Date(iso), now=new Date();
|
| 453 |
+
return d.toDateString()===now.toDateString()
|
| 454 |
+
? d.toLocaleTimeString([],{hour:'2-digit',minute:'2-digit'})
|
| 455 |
+
: d.toLocaleDateString([],{month:'short',day:'numeric'})+' '+d.toLocaleTimeString([],{hour:'2-digit',minute:'2-digit'});
|
| 456 |
+
} catch{return iso;}
|
| 457 |
+
}
|
| 458 |
+
|
| 459 |
+
// ββ Logs ββ
|
| 460 |
+
async function showAllLogs() {
|
| 461 |
+
selectedUserId = null;
|
| 462 |
+
document.querySelectorAll('.user-item').forEach(el => el.classList.remove('active'));
|
| 463 |
+
const main = document.getElementById('mainPanel');
|
| 464 |
+
main.innerHTML = `<div class="loading"><div class="spin"></div> Loading logsβ¦</div>`;
|
| 465 |
+
try {
|
| 466 |
+
const res = await authFetch('/admin/logs');
|
| 467 |
+
const data = await res.json();
|
| 468 |
+
renderLogsTable(main, data.logs || [], 'All User Activity');
|
| 469 |
+
} catch(e) { main.innerHTML = `<div style="color:var(--red);padding:20px">Error: ${e.message}</div>`; }
|
| 470 |
+
}
|
| 471 |
+
|
| 472 |
+
async function showUserLogs(userId, username) {
|
| 473 |
+
const main = document.getElementById('mainPanel');
|
| 474 |
+
const logsDiv = document.getElementById(`user_logs_${userId}`);
|
| 475 |
+
if (logsDiv) { logsDiv.remove(); return; }
|
| 476 |
+
try {
|
| 477 |
+
const res = await authFetch(`/admin/user/${userId}/logs`);
|
| 478 |
+
const data = await res.json();
|
| 479 |
+
const logs = data.logs || [];
|
| 480 |
+
const container = document.createElement('div');
|
| 481 |
+
container.id = `user_logs_${userId}`;
|
| 482 |
+
container.style.marginTop = '20px';
|
| 483 |
+
renderLogsTable(container, logs, `Activity Log β ${username}`);
|
| 484 |
+
main.appendChild(container);
|
| 485 |
+
container.scrollIntoView({behavior:'smooth'});
|
| 486 |
+
} catch(e) { console.error(e); }
|
| 487 |
+
}
|
| 488 |
+
|
| 489 |
+
function renderLogsTable(container, logs, title) {
|
| 490 |
+
if (!logs.length) {
|
| 491 |
+
container.innerHTML = `<h3 style="font-family:'Libre Baskerville',serif;font-size:17px;color:var(--navy);margin-bottom:16px;">${title}</h3><p style="color:var(--muted);font-size:13px;">No activity logged yet.</p>`;
|
| 492 |
+
return;
|
| 493 |
+
}
|
| 494 |
+
container.innerHTML = `
|
| 495 |
+
<div style="display:flex;align-items:center;justify-content:space-between;margin-bottom:14px;">
|
| 496 |
+
<h3 style="font-family:'Libre Baskerville',serif;font-size:17px;color:var(--navy);">${title}</h3>
|
| 497 |
+
<span style="font-size:12px;color:var(--muted);">${logs.length} events</span>
|
| 498 |
+
</div>
|
| 499 |
+
<table class="log-table">
|
| 500 |
+
<thead>
|
| 501 |
+
<tr>
|
| 502 |
+
<th>Time</th>
|
| 503 |
+
<th>User</th>
|
| 504 |
+
<th>Action</th>
|
| 505 |
+
<th>Detail</th>
|
| 506 |
+
<th>IP</th>
|
| 507 |
+
</tr>
|
| 508 |
+
</thead>
|
| 509 |
+
<tbody>
|
| 510 |
+
${logs.map(l => `
|
| 511 |
+
<tr>
|
| 512 |
+
<td style="font-family:'DM Mono',monospace;white-space:nowrap;color:var(--muted);">${fmtTime(l.created_at)}</td>
|
| 513 |
+
<td style="font-weight:500;">${escHtml(l.username||'β')}</td>
|
| 514 |
+
<td><span class="log-action log-${l.action}">${l.action}</span></td>
|
| 515 |
+
<td style="max-width:320px;word-break:break-word;">${escHtml(l.detail||'β')}</td>
|
| 516 |
+
<td style="font-family:'DM Mono',monospace;font-size:11px;color:var(--muted);">${escHtml(l.ip_address||'β')}</td>
|
| 517 |
+
</tr>
|
| 518 |
+
`).join('')}
|
| 519 |
+
</tbody>
|
| 520 |
+
</table>
|
| 521 |
+
`;
|
| 522 |
+
}
|
| 523 |
+
async function resetPassword(userId, username) {
|
| 524 |
+
if (!confirm(`Reset password for ${username}? A new random password will be generated.`)) return;
|
| 525 |
+
try {
|
| 526 |
+
const res = await authFetch(`/admin/user/${userId}/reset-password`, {method:'POST'});
|
| 527 |
+
const data = await res.json();
|
| 528 |
+
if (!res.ok) throw new Error(data.detail || 'Failed');
|
| 529 |
+
alert(`β
Password reset for ${data.username}\n\nNew password: ${data.new_password}\n\nShare this with the user securely.`);
|
| 530 |
+
} catch(e) { alert(`Error: ${e.message}`); }
|
| 531 |
+
}
|
| 532 |
+
</script>
|
| 533 |
+
</body>
|
| 534 |
+
</html>
|
frontend/chat.html
ADDED
|
@@ -0,0 +1,988 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
<!DOCTYPE html>
|
| 2 |
+
<html lang="en">
|
| 3 |
+
<head>
|
| 4 |
+
<meta charset="UTF-8">
|
| 5 |
+
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no">
|
| 6 |
+
<title>AxonIQ β AI Clinical Assistant</title>
|
| 7 |
+
<link href="https://fonts.googleapis.com/css2?family=Libre+Baskerville:ital,wght@0,400;0,700;1,400&family=DM+Sans:wght@300;400;500;600&display=swap" rel="stylesheet">
|
| 8 |
+
<style>
|
| 9 |
+
:root {
|
| 10 |
+
--navy:#0B1F3A;--teal:#0A7B74;--teal-lt:#E6F5F4;--amber:#C97B2A;--red:#B53535;
|
| 11 |
+
--sand:#F5F1EB;--warm-white:#FDFAF6;--border:#DDD8CF;--text:#1A1510;--muted:#6B6056;
|
| 12 |
+
--bubble-ai:#F0F7F6;--bubble-user:#0B1F3A;--sidebar-w:260px;
|
| 13 |
+
}
|
| 14 |
+
*,*::before,*::after{box-sizing:border-box;margin:0;padding:0;}
|
| 15 |
+
body{font-family:'DM Sans',sans-serif;background:var(--warm-white);color:var(--text);height:100vh;display:flex;flex-direction:column;overflow:hidden;}
|
| 16 |
+
|
| 17 |
+
/* AUTH */
|
| 18 |
+
#authOverlay{position:fixed;inset:0;background:rgba(11,31,58,0.85);backdrop-filter:blur(6px);display:flex;align-items:center;justify-content:center;z-index:1000;}
|
| 19 |
+
.auth-card{background:#fff;border-radius:20px;padding:40px 44px;width:420px;max-width:95vw;box-shadow:0 24px 64px rgba(0,0,0,0.3);}
|
| 20 |
+
.auth-logo{display:flex;align-items:center;gap:12px;margin-bottom:28px;}
|
| 21 |
+
.auth-logo-mark{width:44px;height:44px;background:var(--teal);border-radius:10px;display:flex;align-items:center;justify-content:center;font-family:'Libre Baskerville',serif;font-size:20px;font-weight:700;color:#fff;}
|
| 22 |
+
.auth-logo h2{font-family:'Libre Baskerville',serif;font-size:20px;color:var(--navy);font-weight:700;}
|
| 23 |
+
.auth-logo p{font-size:12px;color:var(--muted);}
|
| 24 |
+
.auth-tabs{display:flex;margin-bottom:24px;border:1.5px solid var(--border);border-radius:10px;overflow:hidden;}
|
| 25 |
+
.auth-tab{flex:1;padding:10px;text-align:center;font-size:14px;font-weight:500;cursor:pointer;background:none;border:none;color:var(--muted);transition:background 0.15s,color 0.15s;}
|
| 26 |
+
.auth-tab.active{background:var(--navy);color:#fff;}
|
| 27 |
+
.auth-field{margin-bottom:16px;}
|
| 28 |
+
.auth-field label{display:block;font-size:12px;font-weight:600;color:var(--muted);margin-bottom:6px;letter-spacing:0.4px;text-transform:uppercase;}
|
| 29 |
+
.auth-field input{width:100%;padding:11px 14px;border:1.5px solid var(--border);border-radius:9px;font-family:'DM Sans',sans-serif;font-size:14px;color:var(--text);outline:none;transition:border-color 0.2s,box-shadow 0.2s;}
|
| 30 |
+
.auth-field input:focus{border-color:var(--teal);box-shadow:0 0 0 3px rgba(10,123,116,0.1);}
|
| 31 |
+
.auth-btn{width:100%;padding:13px;background:var(--teal);color:#fff;border:none;border-radius:9px;font-family:'DM Sans',sans-serif;font-size:15px;font-weight:600;cursor:pointer;margin-top:6px;transition:background 0.2s;}
|
| 32 |
+
.auth-btn:hover{background:#088078;}
|
| 33 |
+
.auth-btn:disabled{background:#8FA8BF;cursor:not-allowed;}
|
| 34 |
+
.auth-error{background:#FEE2E2;border:1px solid #FECACA;border-radius:8px;padding:10px 14px;font-size:13px;color:#B91C1C;margin-bottom:14px;display:none;}
|
| 35 |
+
.auth-register-only{display:none;}
|
| 36 |
+
|
| 37 |
+
/* SHELL */
|
| 38 |
+
#appShell{display:none;flex-direction:column;height:100vh;}
|
| 39 |
+
#appShell.visible{display:flex;}
|
| 40 |
+
header{background:var(--navy);padding:14px 20px;display:flex;align-items:center;gap:14px;border-bottom:3px solid var(--teal);flex-shrink:0;z-index:10;}
|
| 41 |
+
.sidebar-toggle{width:32px;height:32px;border-radius:8px;background:rgba(255,255,255,0.08);border:none;color:#8FA8BF;cursor:pointer;font-size:18px;display:flex;align-items:center;justify-content:center;transition:background 0.15s;}
|
| 42 |
+
.sidebar-toggle:hover{background:rgba(255,255,255,0.15);}
|
| 43 |
+
.logo-mark{width:36px;height:36px;background:var(--teal);border-radius:9px;display:flex;align-items:center;justify-content:center;font-family:'Libre Baskerville',serif;font-size:16px;font-weight:700;color:#fff;}
|
| 44 |
+
.header-text h1{font-family:'Libre Baskerville',serif;font-size:18px;color:#fff;font-weight:700;}
|
| 45 |
+
.header-text p{font-size:11px;color:#8FA8BF;margin-top:1px;}
|
| 46 |
+
.header-right{margin-left:auto;display:flex;align-items:center;gap:10px;}
|
| 47 |
+
.model-badge{background:rgba(10,123,116,0.2);border:1px solid rgba(10,123,116,0.4);color:#5ECFC8;font-size:11px;font-weight:500;padding:3px 9px;border-radius:20px;letter-spacing:0.4px;}
|
| 48 |
+
.nav-link{color:#8FA8BF;font-size:12px;text-decoration:none;border:1px solid rgba(255,255,255,0.1);padding:4px 10px;border-radius:6px;}
|
| 49 |
+
.user-pill{display:flex;align-items:center;gap:8px;background:rgba(255,255,255,0.08);border-radius:20px;padding:4px 12px 4px 6px;cursor:pointer;transition:background 0.15s;position:relative;}
|
| 50 |
+
.user-pill:hover{background:rgba(255,255,255,0.15);}
|
| 51 |
+
.user-avatar{width:26px;height:26px;border-radius:50%;background:var(--teal);display:flex;align-items:center;justify-content:center;font-size:12px;font-weight:700;color:#fff;}
|
| 52 |
+
.user-name{font-size:13px;color:#E0EAF4;font-weight:500;}
|
| 53 |
+
.user-dropdown{position:absolute;top:calc(100% + 8px);right:0;background:#fff;border:1px solid var(--border);border-radius:10px;box-shadow:0 8px 24px rgba(0,0,0,0.12);min-width:160px;display:none;z-index:50;}
|
| 54 |
+
.user-dropdown.open{display:block;}
|
| 55 |
+
.user-dropdown a{display:block;padding:10px 16px;font-size:13px;color:var(--text);text-decoration:none;cursor:pointer;transition:background 0.1s;}
|
| 56 |
+
.user-dropdown a:hover{background:var(--sand);}
|
| 57 |
+
.user-dropdown a.danger{color:var(--red);}
|
| 58 |
+
.user-dropdown hr{border:none;border-top:1px solid var(--border);}
|
| 59 |
+
|
| 60 |
+
/* BODY */
|
| 61 |
+
.main-body{flex:1;display:flex;overflow:hidden;}
|
| 62 |
+
#sidebar{width:var(--sidebar-w);background:#F8F5F0;border-right:1px solid var(--border);display:flex;flex-direction:column;flex-shrink:0;transition:width 0.22s ease,opacity 0.2s;overflow:hidden;}
|
| 63 |
+
#sidebar.collapsed{width:0;opacity:0;}
|
| 64 |
+
.sidebar-header{padding:14px 16px 10px;border-bottom:1px solid var(--border);display:flex;align-items:center;justify-content:space-between;}
|
| 65 |
+
.sidebar-header span{font-size:12px;font-weight:600;color:var(--muted);text-transform:uppercase;letter-spacing:0.6px;}
|
| 66 |
+
.new-chat-side{background:var(--teal);color:#fff;border:none;border-radius:7px;padding:5px 11px;font-size:12px;font-weight:600;cursor:pointer;transition:background 0.15s;}
|
| 67 |
+
.new-chat-side:hover{background:#088078;}
|
| 68 |
+
.session-list{flex:1;overflow-y:auto;padding:8px;}
|
| 69 |
+
.session-list::-webkit-scrollbar{width:4px;}
|
| 70 |
+
.session-list::-webkit-scrollbar-thumb{background:var(--border);border-radius:2px;}
|
| 71 |
+
.session-item{padding:9px 12px;border-radius:9px;cursor:pointer;transition:background 0.12s;margin-bottom:2px;display:flex;align-items:flex-start;gap:8px;}
|
| 72 |
+
.session-item:hover{background:#EDEBE6;}
|
| 73 |
+
.session-item.active{background:var(--teal-lt);}
|
| 74 |
+
.session-item-icon{font-size:14px;flex-shrink:0;margin-top:1px;}
|
| 75 |
+
.session-item-body{flex:1;min-width:0;}
|
| 76 |
+
.session-title{font-size:13px;font-weight:500;color:var(--text);white-space:nowrap;overflow:hidden;text-overflow:ellipsis;}
|
| 77 |
+
.session-meta{font-size:11px;color:var(--muted);margin-top:2px;}
|
| 78 |
+
.session-delete{opacity:0;flex-shrink:0;background:none;border:none;color:var(--muted);cursor:pointer;font-size:14px;padding:0 2px;transition:opacity 0.15s,color 0.15s;}
|
| 79 |
+
.session-item:hover .session-delete{opacity:1;}
|
| 80 |
+
.session-delete:hover{color:var(--red);}
|
| 81 |
+
.sidebar-empty{padding:24px 16px;text-align:center;font-size:13px;color:var(--muted);line-height:1.6;}
|
| 82 |
+
|
| 83 |
+
/* CHAT */
|
| 84 |
+
.chat-wrapper{flex:3;min-width:0;display:flex;flex-direction:column;overflow:hidden;}
|
| 85 |
+
.disclaimer-bar{background:transparent;border-bottom:0.5px solid var(--border);padding:4px 16px;font-size:10px;color:var(--muted);text-align:center;flex-shrink:0;opacity:0.6;}
|
| 86 |
+
.chat-container{flex:1;display:flex;flex-direction:column;width:100%;padding:0 20px;overflow:hidden;}
|
| 87 |
+
.messages{flex:1;overflow-y:auto;padding:24px 0 16px;display:flex;flex-direction:column;gap:16px;scroll-behavior:smooth;}
|
| 88 |
+
.messages::-webkit-scrollbar{width:6px;}
|
| 89 |
+
.messages::-webkit-scrollbar-thumb{background:var(--border);border-radius:3px;}
|
| 90 |
+
.welcome{flex:1;display:flex;flex-direction:column;align-items:center;justify-content:center;text-align:center;gap:12px;padding:40px 20px;}
|
| 91 |
+
.welcome-icon{width:72px;height:72px;background:var(--teal-lt);border-radius:50%;display:flex;align-items:center;justify-content:center;font-size:32px;margin-bottom:4px;}
|
| 92 |
+
.welcome h2{font-family:'Libre Baskerville',serif;font-size:22px;color:var(--navy);}
|
| 93 |
+
.welcome p{font-size:14px;color:var(--muted);max-width:480px;line-height:1.7;}
|
| 94 |
+
.welcome-chips{display:flex;flex-wrap:wrap;gap:8px;justify-content:center;margin-top:8px;}
|
| 95 |
+
.chip{background:var(--sand);border:1px solid var(--border);border-radius:20px;padding:8px 16px;font-size:13px;color:var(--muted);cursor:pointer;transition:background 0.15s,color 0.15s,border-color 0.15s;}
|
| 96 |
+
.chip:hover{background:var(--teal-lt);border-color:var(--teal);color:var(--navy);}
|
| 97 |
+
.msg-row{display:flex;align-items:flex-end;gap:10px;animation:fadeUp 0.3s ease;}
|
| 98 |
+
@keyframes fadeUp{from{opacity:0;transform:translateY(8px);}to{opacity:1;transform:translateY(0);}}
|
| 99 |
+
.msg-row.user{flex-direction:row-reverse;}
|
| 100 |
+
.avatar{width:32px;height:32px;border-radius:50%;display:flex;align-items:center;justify-content:center;font-size:14px;flex-shrink:0;}
|
| 101 |
+
.avatar.ai{background:var(--teal-lt);color:var(--teal);font-weight:700;font-family:'Libre Baskerville',serif;}
|
| 102 |
+
.avatar.user{background:var(--navy);color:#fff;font-size:12px;}
|
| 103 |
+
.bubble{max-width:72%;padding:14px 18px;border-radius:18px;font-size:14px;line-height:1.7;}
|
| 104 |
+
.bubble.ai{background:var(--bubble-ai);border:1px solid var(--border);border-bottom-left-radius:4px;color:var(--text);}
|
| 105 |
+
.bubble.user{background:var(--bubble-user);color:#E8F0F8;border-bottom-right-radius:4px;}
|
| 106 |
+
.msg-ts{font-size:10px;color:#C0B8AF;margin-top:4px;}
|
| 107 |
+
.msg-row.user .msg-ts{text-align:right;}
|
| 108 |
+
.tier-label{font-size:12px;font-weight:600;color:var(--muted);margin-bottom:6px;display:block;}
|
| 109 |
+
.typing-bubble{background:var(--bubble-ai);border:1px solid var(--border);border-bottom-left-radius:4px;padding:14px 18px;border-radius:18px;display:flex;gap:4px;align-items:center;}
|
| 110 |
+
.dot{width:7px;height:7px;border-radius:50%;background:var(--teal);opacity:0.6;animation:bounce 1.2s infinite ease-in-out;}
|
| 111 |
+
.dot:nth-child(2){animation-delay:0.2s;}
|
| 112 |
+
.dot:nth-child(3){animation-delay:0.4s;}
|
| 113 |
+
@keyframes bounce{0%,80%,100%{transform:scale(0.8);opacity:.4;}40%{transform:scale(1.2);opacity:1;}}
|
| 114 |
+
.input-area{border-top:1px solid var(--border);padding:14px 0 18px;flex-shrink:0;}
|
| 115 |
+
.input-row{display:flex;gap:10px;align-items:flex-end;}
|
| 116 |
+
.msg-input{flex:1;min-height:48px;max-height:160px;padding:12px 16px;border:1.5px solid var(--border);border-radius:12px;font-family:'DM Sans',sans-serif;font-size:14px;line-height:1.5;color:var(--text);background:#fff;resize:none;outline:none;transition:border-color 0.2s,box-shadow 0.2s;}
|
| 117 |
+
.msg-input:focus{border-color:var(--teal);box-shadow:0 0 0 3px rgba(10,123,116,0.1);}
|
| 118 |
+
.msg-input::placeholder{color:#B0A898;}
|
| 119 |
+
.send-btn{width:48px;height:48px;background:var(--navy);color:#fff;border:none;border-radius:12px;cursor:pointer;display:flex;align-items:center;justify-content:center;transition:background 0.2s,transform 0.1s;flex-shrink:0;}
|
| 120 |
+
.send-btn:hover:not(:disabled){background:#162F52;}
|
| 121 |
+
.send-btn:active:not(:disabled){transform:scale(0.95);}
|
| 122 |
+
.send-btn:disabled{background:#8FA8BF;cursor:not-allowed;}
|
| 123 |
+
.send-btn svg{width:20px;height:20px;}
|
| 124 |
+
.input-hint{font-size:11px;color:var(--muted);margin-top:6px;}
|
| 125 |
+
.input-controls{display:flex;align-items:center;justify-content:space-between;margin-bottom:8px;}
|
| 126 |
+
.session-id{font-size:11px;color:#C0B8AF;font-family:monospace;}
|
| 127 |
+
.new-chat-btn{background:none;border:1px solid var(--border);border-radius:8px;padding:6px 14px;font-size:12px;color:var(--muted);cursor:pointer;transition:border-color 0.15s,color 0.15s;}
|
| 128 |
+
.new-chat-btn:hover{border-color:var(--teal);color:var(--teal);}
|
| 129 |
+
.session-loading{display:none;align-items:center;justify-content:center;gap:10px;padding:32px;font-size:14px;color:var(--muted);}
|
| 130 |
+
.session-loading.visible{display:flex;}
|
| 131 |
+
.spin{width:18px;height:18px;border:2px solid var(--border);border-top-color:var(--teal);border-radius:50%;animation:spin 0.7s linear infinite;}
|
| 132 |
+
@keyframes spin{to{transform:rotate(360deg);}}
|
| 133 |
+
/* ββ RISK PANEL βββββββββββββββββββββββββββββββββββββββββββββββ */
|
| 134 |
+
#riskPanel{flex:2;min-width:0;background:#F8F5F0;border-left:1px solid var(--border);display:flex;flex-direction:column;flex-shrink:0;transition:flex 0.22s ease,opacity 0.22s;overflow:hidden;}
|
| 135 |
+
#riskPanel.hidden{flex:0;min-width:0;max-width:0;opacity:0;pointer-events:none;overflow:hidden;}
|
| 136 |
+
.rp-header{padding:14px 18px 12px;border-bottom:1px solid var(--border);display:flex;align-items:center;justify-content:space-between;}
|
| 137 |
+
.rp-header span{font-size:12px;font-weight:600;color:var(--muted);text-transform:uppercase;letter-spacing:0.6px;}
|
| 138 |
+
.rp-close{background:none;border:none;color:var(--muted);cursor:pointer;font-size:17px;padding:0 2px;line-height:1;}
|
| 139 |
+
.rp-body{flex:1;overflow-y:auto;padding:18px 16px;}
|
| 140 |
+
.rp-body::-webkit-scrollbar{width:5px;}
|
| 141 |
+
.rp-body::-webkit-scrollbar-thumb{background:var(--border);border-radius:3px;}
|
| 142 |
+
.rp-idle{text-align:center;padding:40px 16px;font-size:13px;color:var(--muted);line-height:1.8;}
|
| 143 |
+
.rp-idle .idle-icon{font-size:36px;margin-bottom:12px;}
|
| 144 |
+
|
| 145 |
+
/* tier badge */
|
| 146 |
+
.rp-tier{text-align:center;padding:14px 0 10px;}
|
| 147 |
+
.rp-tier-label{font-size:20px;font-weight:700;margin-bottom:5px;font-family:'Libre Baskerville',serif;}
|
| 148 |
+
.rp-tier-sub{font-size:12px;color:var(--muted);}
|
| 149 |
+
.tier-color-LOW{color:#065F46;}
|
| 150 |
+
.tier-color-WATCH{color:#5B21B6;}
|
| 151 |
+
.tier-color-MODERATE{color:#1E40AF;}
|
| 152 |
+
.tier-color-HIGH{color:#92400E;}
|
| 153 |
+
.tier-color-CRITICAL_EMERGENCY{color:#B91C1C;}
|
| 154 |
+
|
| 155 |
+
/* sections */
|
| 156 |
+
.rp-section-title{font-size:11px;font-weight:600;color:var(--muted);text-transform:uppercase;letter-spacing:0.5px;margin:16px 0 8px;}
|
| 157 |
+
.feature-list{display:flex;flex-direction:column;gap:6px;}
|
| 158 |
+
.feature-chip{font-size:13px;padding:7px 12px;border-radius:8px;background:#fff;border:0.5px solid var(--border);color:var(--text);line-height:1.5;border-left:3px solid var(--teal);}
|
| 159 |
+
.workup-list{display:flex;flex-direction:column;gap:6px;}
|
| 160 |
+
.workup-item{font-size:12px;color:var(--text);padding:5px 0 5px 12px;border-left:2px solid var(--border);line-height:1.6;}
|
| 161 |
+
.action-box{background:#fff;border:1px solid var(--border);border-radius:10px;padding:14px 16px;font-size:13px;color:var(--text);line-height:1.7;margin-top:14px;}
|
| 162 |
+
|
| 163 |
+
/* CHANGE PASSWORD MODAL */
|
| 164 |
+
#changePwOverlay{position:fixed;inset:0;background:rgba(11,31,58,0.7);backdrop-filter:blur(4px);display:none;align-items:center;justify-content:center;z-index:200;}
|
| 165 |
+
#changePwOverlay.open{display:flex;}
|
| 166 |
+
.changepw-card{background:#fff;border-radius:16px;padding:32px 36px;width:380px;max-width:95vw;box-shadow:0 16px 48px rgba(0,0,0,0.25);}
|
| 167 |
+
.changepw-card h3{font-family:'Libre Baskerville',serif;font-size:18px;color:var(--navy);margin-bottom:20px;}
|
| 168 |
+
.changepw-error{background:#FEE2E2;border:1px solid #FECACA;border-radius:8px;padding:9px 14px;font-size:13px;color:#B91C1C;margin-bottom:14px;display:none;}
|
| 169 |
+
.changepw-success{background:#D1FAE5;border:1px solid #6EE7B7;border-radius:8px;padding:9px 14px;font-size:13px;color:#065F46;margin-bottom:14px;display:none;}
|
| 170 |
+
.changepw-cancel{width:100%;padding:10px;background:none;border:1.5px solid var(--border);border-radius:9px;font-family:'DM Sans',sans-serif;font-size:14px;color:var(--muted);cursor:pointer;margin-top:8px;transition:background 0.15s;}
|
| 171 |
+
.changepw-cancel:hover{background:var(--sand);}
|
| 172 |
+
@media(max-width:768px){
|
| 173 |
+
header{padding:10px 12px;gap:8px;}
|
| 174 |
+
.header-text h1{font-size:15px;}
|
| 175 |
+
.header-text p{display:none;}
|
| 176 |
+
.model-badge{display:none;}
|
| 177 |
+
.nav-link{display:none;}
|
| 178 |
+
.user-name{display:none;}
|
| 179 |
+
.bubble{max-width:88%;font-size:13px;}
|
| 180 |
+
.chat-container{padding:0 8px;}
|
| 181 |
+
#sidebar{position:absolute;height:calc(100% - 59px);z-index:20;box-shadow:4px 0 16px rgba(0,0,0,.15);}
|
| 182 |
+
.input-area{padding:10px 0 14px;}
|
| 183 |
+
.msg-input{font-size:14px;padding:10px 14px;}
|
| 184 |
+
.send-btn{width:44px;height:44px;}
|
| 185 |
+
.input-hint{display:none;}
|
| 186 |
+
.disclaimer-bar{font-size:10px;padding:3px 10px;}
|
| 187 |
+
}
|
| 188 |
+
@media(max-width:420px){
|
| 189 |
+
.bubble{max-width:95%;}
|
| 190 |
+
.avatar{width:28px;height:28px;font-size:12px;}
|
| 191 |
+
header{padding:8px 10px;}
|
| 192 |
+
}
|
| 193 |
+
/* Mobile input fixes β prevent iOS zoom on focus */
|
| 194 |
+
/* ββ RISK PANEL βββββββββββββββββββββββββββββββββββββββββββββββ */
|
| 195 |
+
#riskPanel{flex:2;min-width:0;background:#F8F5F0;border-left:1px solid var(--border);display:flex;flex-direction:column;flex-shrink:0;transition:flex 0.22s ease,opacity 0.22s;overflow:hidden;}
|
| 196 |
+
#riskPanel.hidden{flex:0;min-width:0;max-width:0;opacity:0;pointer-events:none;overflow:hidden;}
|
| 197 |
+
.rp-header{padding:14px 18px 12px;border-bottom:1px solid var(--border);display:flex;align-items:center;justify-content:space-between;}
|
| 198 |
+
.rp-header span{font-size:12px;font-weight:600;color:var(--muted);text-transform:uppercase;letter-spacing:0.6px;}
|
| 199 |
+
.rp-close{background:none;border:none;color:var(--muted);cursor:pointer;font-size:17px;padding:0 2px;line-height:1;}
|
| 200 |
+
.rp-body{flex:1;overflow-y:auto;padding:18px 16px;}
|
| 201 |
+
.rp-body::-webkit-scrollbar{width:5px;}
|
| 202 |
+
.rp-body::-webkit-scrollbar-thumb{background:var(--border);border-radius:3px;}
|
| 203 |
+
.rp-idle{text-align:center;padding:40px 16px;font-size:13px;color:var(--muted);line-height:1.8;}
|
| 204 |
+
.rp-idle .idle-icon{font-size:36px;margin-bottom:12px;}
|
| 205 |
+
|
| 206 |
+
/* tier badge */
|
| 207 |
+
.rp-tier{text-align:center;padding:14px 0 10px;}
|
| 208 |
+
.rp-tier-label{font-size:20px;font-weight:700;margin-bottom:5px;font-family:'Libre Baskerville',serif;}
|
| 209 |
+
.rp-tier-sub{font-size:12px;color:var(--muted);}
|
| 210 |
+
.tier-color-LOW{color:#065F46;}
|
| 211 |
+
.tier-color-WATCH{color:#5B21B6;}
|
| 212 |
+
.tier-color-MODERATE{color:#1E40AF;}
|
| 213 |
+
.tier-color-HIGH{color:#92400E;}
|
| 214 |
+
.tier-color-CRITICAL_EMERGENCY{color:#B91C1C;}
|
| 215 |
+
|
| 216 |
+
/* sections */
|
| 217 |
+
.rp-section-title{font-size:11px;font-weight:600;color:var(--muted);text-transform:uppercase;letter-spacing:0.5px;margin:16px 0 8px;}
|
| 218 |
+
.feature-list{display:flex;flex-direction:column;gap:6px;}
|
| 219 |
+
.feature-chip{font-size:13px;padding:7px 12px;border-radius:8px;background:#fff;border:0.5px solid var(--border);color:var(--text);line-height:1.5;border-left:3px solid var(--teal);}
|
| 220 |
+
.workup-list{display:flex;flex-direction:column;gap:6px;}
|
| 221 |
+
.workup-item{font-size:12px;color:var(--text);padding:5px 0 5px 12px;border-left:2px solid var(--border);line-height:1.6;}
|
| 222 |
+
.action-box{background:#fff;border:1px solid var(--border);border-radius:10px;padding:14px 16px;font-size:13px;color:var(--text);line-height:1.7;margin-top:14px;}
|
| 223 |
+
|
| 224 |
+
@media(max-width:768px){
|
| 225 |
+
.msg-input{font-size:16px !important;}
|
| 226 |
+
.send-btn{width:44px;height:44px;}
|
| 227 |
+
.header-text p{display:none;}
|
| 228 |
+
.model-badge{display:none;}
|
| 229 |
+
.nav-link{display:none;}
|
| 230 |
+
body{-webkit-text-size-adjust:100%;}
|
| 231 |
+
}
|
| 232 |
+
.tier-color-LOW{color:#065F46;}
|
| 233 |
+
.tier-color-WATCH{color:#5B21B6;}
|
| 234 |
+
.tier-color-MODERATE{color:#1E40AF;}
|
| 235 |
+
.tier-color-HIGH{color:#92400E;}
|
| 236 |
+
.tier-color-CRITICAL_EMERGENCY{color:#B91C1C;}
|
| 237 |
+
|
| 238 |
+
|
| 239 |
+
</style>
|
| 240 |
+
</head>
|
| 241 |
+
<body>
|
| 242 |
+
|
| 243 |
+
<!-- AUTH OVERLAY -->
|
| 244 |
+
<div id="authOverlay">
|
| 245 |
+
<div class="auth-card">
|
| 246 |
+
<div class="auth-logo">
|
| 247 |
+
<div class="auth-logo-mark">AQ</div>
|
| 248 |
+
<div><h2>AxonIQ</h2><p>AI-Powered MS Diagnostic Assistant β Sign in to continue</p></div>
|
| 249 |
+
</div>
|
| 250 |
+
<div class="auth-tabs">
|
| 251 |
+
<button class="auth-tab active" id="tabLogin" onclick="switchTab('login')">Sign In</button>
|
| 252 |
+
<button class="auth-tab" id="tabRegister" onclick="switchTab('register')">Register</button>
|
| 253 |
+
</div>
|
| 254 |
+
<div id="authError" class="auth-error"></div>
|
| 255 |
+
<div class="auth-field auth-register-only" id="fieldUsername">
|
| 256 |
+
<label>Username</label>
|
| 257 |
+
<input type="text" id="authUsername" placeholder="e.g. dr_smith" autocomplete="username">
|
| 258 |
+
</div>
|
| 259 |
+
<div class="auth-field">
|
| 260 |
+
<label id="emailLabel">Email or Username</label>
|
| 261 |
+
<input type="text" id="authEmail" placeholder="your@email.com" autocomplete="email">
|
| 262 |
+
</div>
|
| 263 |
+
<div class="auth-field">
|
| 264 |
+
<label>Password</label>
|
| 265 |
+
<input type="password" id="authPassword" placeholder="β’β’β’β’β’β’β’β’" autocomplete="current-password">
|
| 266 |
+
</div>
|
| 267 |
+
<button class="auth-btn" id="authSubmitBtn" onclick="submitAuth()">Sign In</button>
|
| 268 |
+
<p id="forgotLink" style="text-align:center;margin-top:12px;font-size:13px;color:var(--muted);">
|
| 269 |
+
Forgot your password?
|
| 270 |
+
<a onclick="showForgotPassword()" style="color:var(--teal);cursor:pointer;font-weight:500;">Reset it here</a>
|
| 271 |
+
</p>
|
| 272 |
+
</div>
|
| 273 |
+
</div>
|
| 274 |
+
|
| 275 |
+
<!-- APP SHELL -->
|
| 276 |
+
<div id="appShell">
|
| 277 |
+
<header>
|
| 278 |
+
<button class="sidebar-toggle" onclick="toggleSidebar()">β°</button>
|
| 279 |
+
<div class="logo-mark">AQ</div>
|
| 280 |
+
<div class="header-text">
|
| 281 |
+
<h1>AxonIQ</h1>
|
| 282 |
+
<p>AI-Powered MS Diagnostic Assistant Β· Powered by Llama 3.1 Β· RAG + NegEx</p>
|
| 283 |
+
</div>
|
| 284 |
+
<div class="header-right">
|
| 285 |
+
<span class="model-badge">π€ Agentic AI</span>
|
| 286 |
+
<div class="user-pill" onclick="toggleUserMenu()">
|
| 287 |
+
<div class="user-avatar" id="headerAvatar">?</div>
|
| 288 |
+
<span class="user-name" id="headerUsername">β¦</span>
|
| 289 |
+
<div class="user-dropdown" id="userDropdown">
|
| 290 |
+
<a onclick="newChat()">οΌ New Chat</a>
|
| 291 |
+
<hr>
|
| 292 |
+
<a onclick="showChangePassword()">π Change Password</a>
|
| 293 |
+
<a onclick="signOut()" class="danger">Sign Out</a>
|
| 294 |
+
</div>
|
| 295 |
+
</div>
|
| 296 |
+
</div>
|
| 297 |
+
</header>
|
| 298 |
+
|
| 299 |
+
<div class="main-body">
|
| 300 |
+
<div id="sidebar">
|
| 301 |
+
<div class="sidebar-header">
|
| 302 |
+
<span>Chat History</span>
|
| 303 |
+
<button class="new-chat-side" onclick="newChat()">+ New</button>
|
| 304 |
+
</div>
|
| 305 |
+
<div class="session-list" id="sessionList">
|
| 306 |
+
<div class="sidebar-empty" id="sidebarEmpty">No conversations yet.<br>Start a new chat!</div>
|
| 307 |
+
</div>
|
| 308 |
+
</div>
|
| 309 |
+
|
| 310 |
+
<!-- RISK PANEL -->
|
| 311 |
+
<div id="riskPanel" class="hidden">
|
| 312 |
+
<div class="rp-header">
|
| 313 |
+
<span>MS Risk Analysis</span>
|
| 314 |
+
<button class="rp-close" onclick="closeRiskPanel()" title="Close">β</button>
|
| 315 |
+
</div>
|
| 316 |
+
<div class="rp-body" id="riskBody">
|
| 317 |
+
<div class="rp-idle" id="riskIdle">
|
| 318 |
+
<div class="idle-icon">π§ </div>
|
| 319 |
+
Describe your symptoms and the risk analysis will appear here automatically.
|
| 320 |
+
</div>
|
| 321 |
+
<div id="riskContent" style="display:none;">
|
| 322 |
+
<div class="rp-tier" id="rpTier">
|
| 323 |
+
<div class="rp-tier-label" id="rpTierLabel"></div>
|
| 324 |
+
<div class="rp-tier-sub" id="rpTierSub"></div>
|
| 325 |
+
</div>
|
| 326 |
+
<div id="rpFeaturesSection" style="display:none;">
|
| 327 |
+
<div class="rp-section-title">Detected Symptoms</div>
|
| 328 |
+
<div class="feature-list" id="rpFeatureList"></div>
|
| 329 |
+
</div>
|
| 330 |
+
<div id="rpWorkupSection" style="display:none;">
|
| 331 |
+
<div class="rp-section-title">Recommended Workup</div>
|
| 332 |
+
<div class="workup-list" id="rpWorkupList"></div>
|
| 333 |
+
</div>
|
| 334 |
+
<div class="action-box" id="rpActionBox" style="display:none;"></div>
|
| 335 |
+
</div>
|
| 336 |
+
</div>
|
| 337 |
+
</div>
|
| 338 |
+
|
| 339 |
+
<div class="chat-wrapper">
|
| 340 |
+
<div class="disclaimer-bar">Clinical decision support only β not a diagnosis</div>
|
| 341 |
+
<div class="chat-container">
|
| 342 |
+
<div class="messages" id="messages">
|
| 343 |
+
<div class="session-loading" id="sessionLoading">
|
| 344 |
+
<div class="spin"></div> Loading conversationβ¦
|
| 345 |
+
</div>
|
| 346 |
+
<div class="welcome" id="welcome">
|
| 347 |
+
<div class="welcome-icon">π§ </div>
|
| 348 |
+
<h2>MS Clinical AI Assistant</h2>
|
| 349 |
+
<p>Describe your neurological symptoms in plain language. I will conduct a structured clinical interview, identify MS-specific patterns, and recommend the appropriate workup.</p>
|
| 350 |
+
<div class="welcome-chips">
|
| 351 |
+
<div class="chip" onclick="sendChip('I have been having blurry vision in my left eye for 3 days and pain when I move my eye.')">ποΈ Vision symptoms</div>
|
| 352 |
+
<div class="chip" onclick="sendChip('Every time I bend my neck forward I get an electric shock running down my spine.')">β‘ Lhermitte sign</div>
|
| 353 |
+
<div class="chip" onclick="sendChip('I woke up seeing double and my eyes feel jiggly. I also feel like I am on a boat when walking.')">π Double vision + balance</div>
|
| 354 |
+
<div class="chip" onclick="sendChip('I have numbness and tingling in my right arm and leg that started 2 days ago.')">π¦Ύ Numbness / tingling</div>
|
| 355 |
+
<div class="chip" onclick="sendChip('I feel a tight squeezing band around my chest like a corset being pulled tight.')">ποΈ MS Hug</div>
|
| 356 |
+
</div>
|
| 357 |
+
</div>
|
| 358 |
+
</div>
|
| 359 |
+
<div class="input-area">
|
| 360 |
+
<div class="input-controls">
|
| 361 |
+
<span class="session-id" id="sessionLabel"></span>
|
| 362 |
+
<button class="new-chat-btn" onclick="newChat()">+ New Chat</button>
|
| 363 |
+
</div>
|
| 364 |
+
<div class="input-row">
|
| 365 |
+
<textarea class="msg-input" id="msgInput" placeholder="Describe your symptoms⦠(Enter to send, Shift+Enter for new line)" rows="1"></textarea>
|
| 366 |
+
<button class="send-btn" id="sendBtn" onclick="sendMessage()">
|
| 367 |
+
<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
|
| 368 |
+
<line x1="22" y1="2" x2="11" y2="13"></line>
|
| 369 |
+
<polygon points="22 2 15 22 11 13 2 9 22 2"></polygon>
|
| 370 |
+
</svg>
|
| 371 |
+
</button>
|
| 372 |
+
</div>
|
| 373 |
+
</div>
|
| 374 |
+
</div>
|
| 375 |
+
</div>
|
| 376 |
+
</div>
|
| 377 |
+
</div>
|
| 378 |
+
|
| 379 |
+
<script>
|
| 380 |
+
const API = window.location.origin;
|
| 381 |
+
let authToken = localStorage.getItem('nc_token') || null;
|
| 382 |
+
let currentUser = JSON.parse(localStorage.getItem('nc_user') || 'null');
|
| 383 |
+
let sessionId = null;
|
| 384 |
+
let isWaiting = false;
|
| 385 |
+
let currentTab = 'login';
|
| 386 |
+
|
| 387 |
+
// Bootstrap
|
| 388 |
+
window.addEventListener('DOMContentLoaded', () => {
|
| 389 |
+
document.getElementById('authPassword').addEventListener('keydown', e => { if(e.key==='Enter') submitAuth(); });
|
| 390 |
+
if (authToken && currentUser) showApp();
|
| 391 |
+
});
|
| 392 |
+
|
| 393 |
+
// ββ Auth ββ
|
| 394 |
+
function switchTab(tab) {
|
| 395 |
+
currentTab = tab;
|
| 396 |
+
document.getElementById('tabLogin').classList.toggle('active', tab==='login');
|
| 397 |
+
document.getElementById('tabRegister').classList.toggle('active', tab==='register');
|
| 398 |
+
document.getElementById('authSubmitBtn').textContent = tab==='login' ? 'Sign In' : 'Create Account';
|
| 399 |
+
document.querySelectorAll('.auth-register-only').forEach(el => el.style.display = tab==='register' ? 'block' : 'none');
|
| 400 |
+
document.getElementById('emailLabel').textContent = tab==='login' ? 'Email or Username' : 'Email';
|
| 401 |
+
clearAuthError();
|
| 402 |
+
const fl = document.getElementById('forgotLink');
|
| 403 |
+
if (fl) fl.style.display = tab==='login' ? 'block' : 'none';
|
| 404 |
+
}
|
| 405 |
+
|
| 406 |
+
function showAuthError(msg) { const e=document.getElementById('authError'); e.textContent=msg; e.style.display='block'; }
|
| 407 |
+
function clearAuthError() { document.getElementById('authError').style.display='none'; }
|
| 408 |
+
|
| 409 |
+
async function submitAuth() {
|
| 410 |
+
clearAuthError();
|
| 411 |
+
const btn = document.getElementById('authSubmitBtn');
|
| 412 |
+
btn.disabled = true;
|
| 413 |
+
const email = document.getElementById('authEmail').value.trim();
|
| 414 |
+
const password = document.getElementById('authPassword').value;
|
| 415 |
+
const username = document.getElementById('authUsername').value.trim();
|
| 416 |
+
if (!email || !password) { showAuthError('Please fill in all fields.'); btn.disabled=false; return; }
|
| 417 |
+
if (currentTab==='register' && !username) { showAuthError('Please enter a username.'); btn.disabled=false; return; }
|
| 418 |
+
try {
|
| 419 |
+
let res;
|
| 420 |
+
if (currentTab==='register') {
|
| 421 |
+
res = await fetch(`${API}/auth/register`, {
|
| 422 |
+
method:'POST', headers:{'Content-Type':'application/json'},
|
| 423 |
+
body: JSON.stringify({ username, email, password }),
|
| 424 |
+
});
|
| 425 |
+
} else {
|
| 426 |
+
const form = new URLSearchParams();
|
| 427 |
+
form.append('username', email);
|
| 428 |
+
form.append('password', password);
|
| 429 |
+
res = await fetch(`${API}/auth/login`, {
|
| 430 |
+
method:'POST', headers:{'Content-Type':'application/x-www-form-urlencoded'}, body: form,
|
| 431 |
+
});
|
| 432 |
+
}
|
| 433 |
+
let data;
|
| 434 |
+
try { data = await res.json(); } catch { throw new Error(`Server error ${res.status}`); }
|
| 435 |
+
if (!res.ok) {
|
| 436 |
+
// data.detail can be a string OR a list of validation error objects
|
| 437 |
+
let errMsg = 'Authentication failed';
|
| 438 |
+
if (data.detail) {
|
| 439 |
+
if (typeof data.detail === 'string') {
|
| 440 |
+
errMsg = data.detail;
|
| 441 |
+
} else if (Array.isArray(data.detail)) {
|
| 442 |
+
errMsg = data.detail.map(e => e.msg || JSON.stringify(e)).join(', ');
|
| 443 |
+
} else {
|
| 444 |
+
errMsg = JSON.stringify(data.detail);
|
| 445 |
+
}
|
| 446 |
+
}
|
| 447 |
+
throw new Error(errMsg);
|
| 448 |
+
}
|
| 449 |
+
authToken = data.access_token;
|
| 450 |
+
currentUser = { id: data.user_id, username: data.username };
|
| 451 |
+
localStorage.setItem('nc_token', authToken);
|
| 452 |
+
localStorage.setItem('nc_user', JSON.stringify(currentUser));
|
| 453 |
+
showApp();
|
| 454 |
+
} catch(err) { showAuthError(err.message); }
|
| 455 |
+
finally { btn.disabled = false; }
|
| 456 |
+
}
|
| 457 |
+
|
| 458 |
+
function signOut() {
|
| 459 |
+
localStorage.removeItem('nc_token'); localStorage.removeItem('nc_user');
|
| 460 |
+
authToken=null; currentUser=null; sessionId=null;
|
| 461 |
+
document.getElementById('appShell').classList.remove('visible');
|
| 462 |
+
document.getElementById('authOverlay').style.display='flex';
|
| 463 |
+
clearMessages();
|
| 464 |
+
}
|
| 465 |
+
|
| 466 |
+
// ββ Shell ββ
|
| 467 |
+
function showApp() {
|
| 468 |
+
document.getElementById('authOverlay').style.display='none';
|
| 469 |
+
document.getElementById('appShell').classList.add('visible');
|
| 470 |
+
document.getElementById('headerUsername').textContent = currentUser.username;
|
| 471 |
+
document.getElementById('headerAvatar').textContent = currentUser.username[0].toUpperCase();
|
| 472 |
+
loadSessionList();
|
| 473 |
+
}
|
| 474 |
+
|
| 475 |
+
function toggleUserMenu() { document.getElementById('userDropdown').classList.toggle('open'); }
|
| 476 |
+
document.addEventListener('click', e => { if (!e.target.closest('.user-pill')) document.getElementById('userDropdown').classList.remove('open'); });
|
| 477 |
+
function toggleSidebar() { document.getElementById('sidebar').classList.toggle('collapsed'); }
|
| 478 |
+
|
| 479 |
+
// ββ Session list ββ
|
| 480 |
+
async function loadSessionList() {
|
| 481 |
+
try {
|
| 482 |
+
const res = await authFetch('/user/sessions');
|
| 483 |
+
const data = await res.json();
|
| 484 |
+
renderSessionList(data.sessions || []);
|
| 485 |
+
} catch(e) { console.error(e); }
|
| 486 |
+
}
|
| 487 |
+
|
| 488 |
+
function renderSessionList(sessions) {
|
| 489 |
+
const list = document.getElementById('sessionList');
|
| 490 |
+
const empty = document.getElementById('sidebarEmpty');
|
| 491 |
+
list.querySelectorAll('.session-item').forEach(el => el.remove());
|
| 492 |
+
if (!sessions.length) { empty.style.display='block'; return; }
|
| 493 |
+
empty.style.display='none';
|
| 494 |
+
sessions.forEach(s => {
|
| 495 |
+
const item = document.createElement('div');
|
| 496 |
+
item.className = 'session-item' + (s.session_uuid===sessionId ? ' active' : '');
|
| 497 |
+
item.dataset.uuid = s.session_uuid;
|
| 498 |
+
const ts = new Date(s.updated_at).toLocaleDateString(undefined,{month:'short',day:'numeric'});
|
| 499 |
+
item.innerHTML = `
|
| 500 |
+
<div class="session-item-icon">π¬</div>
|
| 501 |
+
<div class="session-item-body">
|
| 502 |
+
<div class="session-title">${escapeHtml(s.title||'Chat')}</div>
|
| 503 |
+
<div class="session-meta">${ts}</div>
|
| 504 |
+
</div>
|
| 505 |
+
<button class="session-delete" onclick="deleteSession(event,'${s.session_uuid}')">β</button>`;
|
| 506 |
+
item.addEventListener('click', () => loadSession(s.session_uuid));
|
| 507 |
+
list.appendChild(item);
|
| 508 |
+
});
|
| 509 |
+
}
|
| 510 |
+
|
| 511 |
+
async function loadSession(uuid) {
|
| 512 |
+
if (uuid===sessionId) return;
|
| 513 |
+
sessionId = uuid;
|
| 514 |
+
document.querySelectorAll('.session-item').forEach(el => el.classList.toggle('active', el.dataset.uuid===uuid));
|
| 515 |
+
clearMessages();
|
| 516 |
+
const loading = document.getElementById('sessionLoading');
|
| 517 |
+
loading.classList.add('visible');
|
| 518 |
+
try {
|
| 519 |
+
const res = await authFetch(`/session/${uuid}/history`);
|
| 520 |
+
const data = await res.json();
|
| 521 |
+
loading.classList.remove('visible');
|
| 522 |
+
if (data.messages && data.messages.length) {
|
| 523 |
+
document.getElementById('welcome').style.display='none';
|
| 524 |
+
data.messages.forEach(m => addBubble(m.role==='human'?'user':'ai', m.content, m.created_at));
|
| 525 |
+
resetRiskPanel();
|
| 526 |
+
const humanText = data.messages.filter(m=>m.role==='human').map(m=>m.content).join(' ');
|
| 527 |
+
if (humanText.trim().length > 8) scheduleRiskUpdate(humanText);
|
| 528 |
+
}
|
| 529 |
+
} catch(e) { loading.classList.remove('visible'); }
|
| 530 |
+
document.getElementById('sessionLabel').textContent = `Session: ${uuid.slice(0,8)}β¦`;
|
| 531 |
+
}
|
| 532 |
+
|
| 533 |
+
async function deleteSession(e, uuid) {
|
| 534 |
+
e.stopPropagation();
|
| 535 |
+
if (!confirm('Delete this conversation?')) return;
|
| 536 |
+
await authFetch(`/session/${uuid}`, {method:'DELETE'}).catch(()=>{});
|
| 537 |
+
if (sessionId===uuid) { sessionId=null; clearMessages(); }
|
| 538 |
+
loadSessionList();
|
| 539 |
+
}
|
| 540 |
+
|
| 541 |
+
// ββ Chat ββ
|
| 542 |
+
const input = document.getElementById('msgInput');
|
| 543 |
+
input.addEventListener('input', () => { input.style.height='auto'; input.style.height=Math.min(input.scrollHeight,160)+'px'; });
|
| 544 |
+
input.addEventListener('keydown', e => { if (e.key==='Enter' && !e.shiftKey) { e.preventDefault(); sendMessage(); } });
|
| 545 |
+
|
| 546 |
+
function sendChip(text) { input.value=text; sendMessage(); }
|
| 547 |
+
|
| 548 |
+
async function sendMessage() {
|
| 549 |
+
const text = input.value.trim();
|
| 550 |
+
if (!text || isWaiting || !authToken) return;
|
| 551 |
+
isWaiting = true;
|
| 552 |
+
input.value = ''; input.style.height='auto';
|
| 553 |
+
document.getElementById('sendBtn').disabled = true;
|
| 554 |
+
document.getElementById('welcome').style.display='none';
|
| 555 |
+
addBubble('user', text, new Date().toISOString());
|
| 556 |
+
scheduleRiskUpdate(text);
|
| 557 |
+
const typing = addTyping();
|
| 558 |
+
try {
|
| 559 |
+
const res = await authFetch('/chat', {
|
| 560 |
+
method:'POST', headers:{'Content-Type':'application/json'},
|
| 561 |
+
body: JSON.stringify({ message: text, session_id: sessionId }),
|
| 562 |
+
});
|
| 563 |
+
if (res.status===401) { signOut(); return; }
|
| 564 |
+
if (!res.ok) { const err=await res.json().catch(()=>{}); throw new Error(err.detail||`Error ${res.status}`); }
|
| 565 |
+
const data = await res.json();
|
| 566 |
+
sessionId = data.session_id;
|
| 567 |
+
document.getElementById('sessionLabel').textContent = `Session: ${sessionId.slice(0,8)}β¦`;
|
| 568 |
+
typing.remove();
|
| 569 |
+
addBubble('ai', data.response, new Date().toISOString());
|
| 570 |
+
loadSessionList();
|
| 571 |
+
// Re-analyze with full accumulated text after every AI response
|
| 572 |
+
rebuildRiskFromHistory();
|
| 573 |
+
} catch(err) {
|
| 574 |
+
typing.remove();
|
| 575 |
+
addBubble('ai', `β οΈ Error: ${err.message}`, new Date().toISOString());
|
| 576 |
+
} finally {
|
| 577 |
+
isWaiting=false;
|
| 578 |
+
document.getElementById('sendBtn').disabled=false;
|
| 579 |
+
input.focus();
|
| 580 |
+
}
|
| 581 |
+
}
|
| 582 |
+
|
| 583 |
+
function newChat() {
|
| 584 |
+
sessionId=null;
|
| 585 |
+
clearMessages();
|
| 586 |
+
resetRiskPanel();
|
| 587 |
+
document.getElementById('sessionLabel').textContent='';
|
| 588 |
+
document.querySelectorAll('.session-item').forEach(el => el.classList.remove('active'));
|
| 589 |
+
loadSessionList();
|
| 590 |
+
input.focus();
|
| 591 |
+
}
|
| 592 |
+
|
| 593 |
+
function clearMessages() {
|
| 594 |
+
document.getElementById('messages').querySelectorAll('.msg-row').forEach(el => el.remove());
|
| 595 |
+
document.getElementById('welcome').style.display='flex';
|
| 596 |
+
}
|
| 597 |
+
|
| 598 |
+
function addBubble(role, text, timestamp) {
|
| 599 |
+
const msgs = document.getElementById('messages');
|
| 600 |
+
const row = document.createElement('div');
|
| 601 |
+
row.className = `msg-row ${role}`;
|
| 602 |
+
const avatar = document.createElement('div');
|
| 603 |
+
avatar.className = `avatar ${role}`;
|
| 604 |
+
avatar.textContent = role==='ai' ? 'AQ' : (currentUser ? currentUser.username[0].toUpperCase() : 'U');
|
| 605 |
+
const inner = document.createElement('div');
|
| 606 |
+
const bubble = document.createElement('div');
|
| 607 |
+
bubble.className = `bubble ${role}`;
|
| 608 |
+
bubble.innerHTML = formatMessage(text);
|
| 609 |
+
const ts = document.createElement('div');
|
| 610 |
+
ts.className = 'msg-ts';
|
| 611 |
+
ts.textContent = formatTimestamp(timestamp);
|
| 612 |
+
inner.appendChild(bubble); inner.appendChild(ts);
|
| 613 |
+
row.appendChild(avatar); row.appendChild(inner);
|
| 614 |
+
msgs.appendChild(row); msgs.scrollTop=msgs.scrollHeight;
|
| 615 |
+
return row;
|
| 616 |
+
}
|
| 617 |
+
|
| 618 |
+
function addTyping() {
|
| 619 |
+
const msgs = document.getElementById('messages');
|
| 620 |
+
const row=document.createElement('div'); row.className='msg-row ai';
|
| 621 |
+
const av=document.createElement('div'); av.className='avatar ai'; av.textContent='AQ';
|
| 622 |
+
const b=document.createElement('div'); b.className='typing-bubble';
|
| 623 |
+
b.innerHTML='<div class="dot"></div><div class="dot"></div><div class="dot"></div>';
|
| 624 |
+
row.appendChild(av); row.appendChild(b); msgs.appendChild(row); msgs.scrollTop=msgs.scrollHeight;
|
| 625 |
+
return row;
|
| 626 |
+
}
|
| 627 |
+
|
| 628 |
+
function formatTimestamp(iso) {
|
| 629 |
+
if (!iso) return '';
|
| 630 |
+
try {
|
| 631 |
+
const d=new Date(iso), now=new Date();
|
| 632 |
+
const sameDay = d.toDateString()===now.toDateString();
|
| 633 |
+
return sameDay
|
| 634 |
+
? d.toLocaleTimeString([],{hour:'2-digit',minute:'2-digit'})
|
| 635 |
+
: d.toLocaleDateString([],{month:'short',day:'numeric'})+' '+d.toLocaleTimeString([],{hour:'2-digit',minute:'2-digit'});
|
| 636 |
+
} catch { return ''; }
|
| 637 |
+
}
|
| 638 |
+
|
| 639 |
+
function formatMessage(text) {
|
| 640 |
+
let html = escapeHtml(text);
|
| 641 |
+
// Bold markdown **text**
|
| 642 |
+
html = html.replace(/\*\*(.*?)\*\*/g, '<strong>$1</strong>');
|
| 643 |
+
// Paragraphs and line breaks
|
| 644 |
+
html = html.replace(/\n\n/g, '</p><p>');
|
| 645 |
+
html = html.replace(/\n/g, '<br>');
|
| 646 |
+
// Bold key clinical terms β word boundaries only, no mid-word replacement
|
| 647 |
+
['MRI','lumbar puncture','oligoclonal bands','optic neuritis',
|
| 648 |
+
'Lhermitte','Uhthoff','neurology referral'
|
| 649 |
+
].forEach(kw => {
|
| 650 |
+
const re = new RegExp('(?<![\\w>])' + kw.replace(/[.*+?^${}()|[\]\\]/g,'\\$&') + '(?![\\w<])', 'gi');
|
| 651 |
+
html = html.replace(re, '<strong>$&</strong>');
|
| 652 |
+
});
|
| 653 |
+
return `<p>${html}</p>`;
|
| 654 |
+
}
|
| 655 |
+
|
| 656 |
+
function escapeHtml(t) { return t.replace(/&/g,'&').replace(/</g,'<').replace(/>/g,'>'); }
|
| 657 |
+
|
| 658 |
+
function authFetch(path, opts={}) {
|
| 659 |
+
return fetch(`${API}${path}`, { ...opts, headers:{ ...(opts.headers||{}), 'Authorization':`Bearer ${authToken}` } });
|
| 660 |
+
}
|
| 661 |
+
// ββ Live Risk Panel ββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 662 |
+
let _riskDebounce = null;
|
| 663 |
+
let _riskText = '';
|
| 664 |
+
|
| 665 |
+
const TIER_COLORS = {
|
| 666 |
+
LOW: '#065F46',
|
| 667 |
+
WATCH: '#5B21B6',
|
| 668 |
+
MODERATE: '#1E40AF',
|
| 669 |
+
HIGH: '#92400E',
|
| 670 |
+
CRITICAL_EMERGENCY: '#B91C1C',
|
| 671 |
+
};
|
| 672 |
+
|
| 673 |
+
function closeRiskPanel() {
|
| 674 |
+
document.getElementById('riskPanel').classList.add('hidden');
|
| 675 |
+
}
|
| 676 |
+
|
| 677 |
+
function resetRiskPanel() {
|
| 678 |
+
_riskText = '';
|
| 679 |
+
document.getElementById('riskPanel').classList.add('hidden');
|
| 680 |
+
document.getElementById('riskIdle').style.display = 'block';
|
| 681 |
+
document.getElementById('riskContent').style.display = 'none';
|
| 682 |
+
}
|
| 683 |
+
|
| 684 |
+
function scheduleRiskUpdate(text) {
|
| 685 |
+
if (!text || text.trim().length < 3) return;
|
| 686 |
+
// Always append new text to accumulate full conversation context
|
| 687 |
+
_riskText = (_riskText + ' ' + text).trim();
|
| 688 |
+
clearTimeout(_riskDebounce);
|
| 689 |
+
_riskDebounce = setTimeout(() => _fetchRisk(_riskText), 700);
|
| 690 |
+
}
|
| 691 |
+
|
| 692 |
+
function rebuildRiskFromHistory() {
|
| 693 |
+
// Re-run analysis using ALL human messages in current conversation
|
| 694 |
+
const msgs = document.getElementById('messages').querySelectorAll('.msg-row.user .bubble');
|
| 695 |
+
const allText = Array.from(msgs).map(b => b.innerText || b.textContent).join(' ').trim();
|
| 696 |
+
if (allText.length > 5) {
|
| 697 |
+
_riskText = allText;
|
| 698 |
+
_fetchRisk(_riskText);
|
| 699 |
+
}
|
| 700 |
+
}
|
| 701 |
+
|
| 702 |
+
async function _fetchRisk(text) {
|
| 703 |
+
try {
|
| 704 |
+
const res = await fetch(`${API}/analyze`, {
|
| 705 |
+
method: 'POST',
|
| 706 |
+
headers: { 'Content-Type': 'application/json' },
|
| 707 |
+
body: JSON.stringify({ text }),
|
| 708 |
+
});
|
| 709 |
+
if (!res.ok) return;
|
| 710 |
+
renderRiskPanel(await res.json());
|
| 711 |
+
} catch(e) { /* silent */ }
|
| 712 |
+
}
|
| 713 |
+
|
| 714 |
+
function renderRiskPanel(data) {
|
| 715 |
+
const tier = data.tier || 'LOW';
|
| 716 |
+
const color = TIER_COLORS[tier] || TIER_COLORS.LOW;
|
| 717 |
+
document.getElementById('riskPanel').classList.remove('hidden');
|
| 718 |
+
document.getElementById('riskIdle').style.display = 'none';
|
| 719 |
+
document.getElementById('riskContent').style.display = 'block';
|
| 720 |
+
const lbl = document.getElementById('rpTierLabel');
|
| 721 |
+
lbl.textContent = data.tier_label || tier;
|
| 722 |
+
lbl.className = 'rp-tier-label tier-color-' + tier;
|
| 723 |
+
document.getElementById('rpTierSub').textContent = data.tier_subtitle || '';
|
| 724 |
+
const feats = data.features || [];
|
| 725 |
+
const fSec = document.getElementById('rpFeaturesSection');
|
| 726 |
+
if (feats.length) {
|
| 727 |
+
fSec.style.display = 'block';
|
| 728 |
+
document.getElementById('rpFeatureList').innerHTML =
|
| 729 |
+
feats.map(f => `<div class="feature-chip">${escapeHtml(f.label)}</div>`).join('');
|
| 730 |
+
} else { fSec.style.display = 'none'; }
|
| 731 |
+
const workup = data.workup || [];
|
| 732 |
+
const wSec = document.getElementById('rpWorkupSection');
|
| 733 |
+
if (workup.length) {
|
| 734 |
+
wSec.style.display = 'block';
|
| 735 |
+
document.getElementById('rpWorkupList').innerHTML =
|
| 736 |
+
workup.map(w => `<div class="workup-item">${escapeHtml(w)}</div>`).join('');
|
| 737 |
+
} else { wSec.style.display = 'none'; }
|
| 738 |
+
const aBox = document.getElementById('rpActionBox');
|
| 739 |
+
if (data.action && tier !== 'LOW') {
|
| 740 |
+
aBox.style.display = 'block';
|
| 741 |
+
aBox.style.borderColor = color;
|
| 742 |
+
aBox.innerHTML = `<strong>Recommended action:</strong><br>${escapeHtml(data.action)}`;
|
| 743 |
+
} else { aBox.style.display = 'none'; }
|
| 744 |
+
}
|
| 745 |
+
|
| 746 |
+
// ββ Change Password βββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 747 |
+
function showChangePassword() {
|
| 748 |
+
document.getElementById('userDropdown').classList.remove('open');
|
| 749 |
+
document.getElementById('changePwOverlay').classList.add('open');
|
| 750 |
+
document.getElementById('pwOld').value='';
|
| 751 |
+
document.getElementById('pwNew').value='';
|
| 752 |
+
document.getElementById('pwConfirm').value='';
|
| 753 |
+
document.getElementById('changePwError').style.display='none';
|
| 754 |
+
document.getElementById('changePwSuccess').style.display='none';
|
| 755 |
+
document.getElementById('pwOld').focus();
|
| 756 |
+
}
|
| 757 |
+
function hideChangePassword(){document.getElementById('changePwOverlay').classList.remove('open');}
|
| 758 |
+
async function submitChangePassword(){
|
| 759 |
+
const oldPw=document.getElementById('pwOld').value;
|
| 760 |
+
const newPw=document.getElementById('pwNew').value;
|
| 761 |
+
const confPw=document.getElementById('pwConfirm').value;
|
| 762 |
+
const errEl=document.getElementById('changePwError');
|
| 763 |
+
const okEl=document.getElementById('changePwSuccess');
|
| 764 |
+
errEl.style.display='none'; okEl.style.display='none';
|
| 765 |
+
if(!oldPw||!newPw||!confPw){errEl.textContent='Please fill in all fields.';errEl.style.display='block';return;}
|
| 766 |
+
if(newPw.length<6){errEl.textContent='New password must be at least 6 characters.';errEl.style.display='block';return;}
|
| 767 |
+
if(newPw!==confPw){errEl.textContent='Passwords do not match.';errEl.style.display='block';return;}
|
| 768 |
+
try{
|
| 769 |
+
const res=await authFetch('/auth/change-password',{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify({old_password:oldPw,new_password:newPw})});
|
| 770 |
+
const data=await res.json();
|
| 771 |
+
if(!res.ok) throw new Error(data.detail||'Failed');
|
| 772 |
+
okEl.textContent='β
Password changed successfully!';
|
| 773 |
+
okEl.style.display='block';
|
| 774 |
+
setTimeout(hideChangePassword,2000);
|
| 775 |
+
}catch(e){errEl.textContent=e.message;errEl.style.display='block';}
|
| 776 |
+
}
|
| 777 |
+
document.addEventListener('DOMContentLoaded',()=>{
|
| 778 |
+
const ov=document.getElementById('changePwOverlay');
|
| 779 |
+
if(ov) ov.addEventListener('click',function(e){if(e.target===this)hideChangePassword();});
|
| 780 |
+
const pc=document.getElementById('pwConfirm');
|
| 781 |
+
if(pc) pc.addEventListener('keydown',e=>{if(e.key==='Enter')submitChangePassword();});
|
| 782 |
+
});
|
| 783 |
+
|
| 784 |
+
// ββ Forgot Password βββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 785 |
+
let _fpResetToken = '';
|
| 786 |
+
|
| 787 |
+
function showForgotPassword() {
|
| 788 |
+
document.getElementById('forgotOverlay').style.display = 'flex';
|
| 789 |
+
document.getElementById('fpStep1').style.display = 'block';
|
| 790 |
+
document.getElementById('fpStep2').style.display = 'none';
|
| 791 |
+
document.getElementById('fpStep3').style.display = 'none';
|
| 792 |
+
document.getElementById('fpError').style.display = 'none';
|
| 793 |
+
document.getElementById('fpSuccess').style.display = 'none';
|
| 794 |
+
document.getElementById('fpTitle').textContent = 'Reset Password';
|
| 795 |
+
document.getElementById('fpSubtitle').textContent = 'Enter your registered email';
|
| 796 |
+
document.getElementById('fpEmail').value = '';
|
| 797 |
+
document.getElementById('fpOTP').value = '';
|
| 798 |
+
document.getElementById('fpNewPw').value = '';
|
| 799 |
+
document.getElementById('fpConfirmPw').value = '';
|
| 800 |
+
}
|
| 801 |
+
|
| 802 |
+
function hideForgotPassword() {
|
| 803 |
+
document.getElementById('forgotOverlay').style.display = 'none';
|
| 804 |
+
}
|
| 805 |
+
|
| 806 |
+
function fpErr(msg) {
|
| 807 |
+
const e = document.getElementById('fpError');
|
| 808 |
+
e.textContent = msg; e.style.display = 'block';
|
| 809 |
+
document.getElementById('fpSuccess').style.display = 'none';
|
| 810 |
+
}
|
| 811 |
+
|
| 812 |
+
function fpOk(msg) {
|
| 813 |
+
const s = document.getElementById('fpSuccess');
|
| 814 |
+
s.textContent = msg; s.style.display = 'block';
|
| 815 |
+
document.getElementById('fpError').style.display = 'none';
|
| 816 |
+
}
|
| 817 |
+
|
| 818 |
+
async function fpSendOTP() {
|
| 819 |
+
const email = document.getElementById('fpEmail').value.trim();
|
| 820 |
+
if (!email) { fpErr('Please enter your email address.'); return; }
|
| 821 |
+
document.getElementById('fpError').style.display = 'none';
|
| 822 |
+
|
| 823 |
+
// Show loading state
|
| 824 |
+
const btn = document.querySelector('#fpStep1 .auth-btn');
|
| 825 |
+
const originalText = btn.textContent;
|
| 826 |
+
btn.textContent = 'Sending...';
|
| 827 |
+
btn.disabled = true;
|
| 828 |
+
|
| 829 |
+
try {
|
| 830 |
+
const res = await fetch(`${API}/auth/forgot-password`, {
|
| 831 |
+
method: 'POST',
|
| 832 |
+
headers: {'Content-Type':'application/json'},
|
| 833 |
+
body: JSON.stringify({ email }),
|
| 834 |
+
});
|
| 835 |
+
|
| 836 |
+
if (!res.ok) {
|
| 837 |
+
const err = await res.json().catch(() => ({}));
|
| 838 |
+
fpErr(err.detail || 'Server error. Please try again.');
|
| 839 |
+
return;
|
| 840 |
+
}
|
| 841 |
+
|
| 842 |
+
const data = await res.json();
|
| 843 |
+
|
| 844 |
+
// Move to step 2
|
| 845 |
+
document.getElementById('fpEmailShow').textContent = email;
|
| 846 |
+
document.getElementById('fpStep1').style.display = 'none';
|
| 847 |
+
document.getElementById('fpStep2').style.display = 'block';
|
| 848 |
+
document.getElementById('fpTitle').textContent = 'Enter Reset Code';
|
| 849 |
+
|
| 850 |
+
if (data.dev_mode && data.dev_error) {
|
| 851 |
+
// Email not found in DB
|
| 852 |
+
document.getElementById('fpStep2').style.display = 'none';
|
| 853 |
+
document.getElementById('fpStep1').style.display = 'block';
|
| 854 |
+
document.getElementById('fpTitle').textContent = 'Reset Password';
|
| 855 |
+
fpErr(data.dev_error);
|
| 856 |
+
return;
|
| 857 |
+
} else if (data.dev_mode && data.dev_otp) {
|
| 858 |
+
// Dev mode β auto fill OTP and show it prominently
|
| 859 |
+
document.getElementById('fpSubtitle').textContent = 'Code shown below (email not configured)';
|
| 860 |
+
document.getElementById('fpOTP').value = data.dev_otp;
|
| 861 |
+
fpOk('Your reset code is: ' + data.dev_otp);
|
| 862 |
+
} else {
|
| 863 |
+
document.getElementById('fpSubtitle').textContent = 'Check your email inbox';
|
| 864 |
+
fpOk('Code sent! Check your inbox and spam folder.');
|
| 865 |
+
}
|
| 866 |
+
document.getElementById('fpOTP').focus();
|
| 867 |
+
|
| 868 |
+
} catch(e) {
|
| 869 |
+
fpErr('Network error. Please check your connection and try again.');
|
| 870 |
+
} finally {
|
| 871 |
+
btn.textContent = originalText;
|
| 872 |
+
btn.disabled = false;
|
| 873 |
+
}
|
| 874 |
+
}
|
| 875 |
+
|
| 876 |
+
async function fpVerifyOTP() {
|
| 877 |
+
const email = document.getElementById('fpEmail').value.trim();
|
| 878 |
+
const otp = document.getElementById('fpOTP').value.trim();
|
| 879 |
+
if (!otp || otp.length < 6) { fpErr('Please enter the 6-digit code.'); return; }
|
| 880 |
+
try {
|
| 881 |
+
const res = await fetch(`${API}/auth/verify-otp`, {
|
| 882 |
+
method: 'POST', headers: {'Content-Type':'application/json'},
|
| 883 |
+
body: JSON.stringify({ email, otp }),
|
| 884 |
+
});
|
| 885 |
+
const data = await res.json();
|
| 886 |
+
if (!res.ok) throw new Error(data.detail || 'Invalid or expired code');
|
| 887 |
+
_fpResetToken = data.reset_token;
|
| 888 |
+
document.getElementById('fpStep2').style.display = 'none';
|
| 889 |
+
document.getElementById('fpStep3').style.display = 'block';
|
| 890 |
+
document.getElementById('fpTitle').textContent = 'Set New Password';
|
| 891 |
+
document.getElementById('fpSubtitle').textContent = 'Choose a new password';
|
| 892 |
+
document.getElementById('fpSuccess').style.display = 'none';
|
| 893 |
+
document.getElementById('fpNewPw').focus();
|
| 894 |
+
} catch(e) { fpErr(e.message); }
|
| 895 |
+
}
|
| 896 |
+
|
| 897 |
+
async function fpSetPassword() {
|
| 898 |
+
const newPw = document.getElementById('fpNewPw').value;
|
| 899 |
+
const confPw = document.getElementById('fpConfirmPw').value;
|
| 900 |
+
if (!newPw || newPw.length < 6) { fpErr('Password must be at least 6 characters.'); return; }
|
| 901 |
+
if (newPw !== confPw) { fpErr('Passwords do not match.'); return; }
|
| 902 |
+
try {
|
| 903 |
+
const res = await fetch(`${API}/auth/reset-password`, {
|
| 904 |
+
method: 'POST', headers: {'Content-Type':'application/json'},
|
| 905 |
+
body: JSON.stringify({ reset_token: _fpResetToken, new_password: newPw }),
|
| 906 |
+
});
|
| 907 |
+
const data = await res.json();
|
| 908 |
+
if (!res.ok) throw new Error(data.detail || 'Reset failed');
|
| 909 |
+
fpOk('Password reset successfully! Redirecting to login...');
|
| 910 |
+
setTimeout(() => { hideForgotPassword(); switchTab('login'); }, 2000);
|
| 911 |
+
} catch(e) { fpErr(e.message); }
|
| 912 |
+
}
|
| 913 |
+
|
| 914 |
+
document.addEventListener('DOMContentLoaded', () => {
|
| 915 |
+
const ov = document.getElementById('forgotOverlay');
|
| 916 |
+
if (ov) ov.addEventListener('click', e => { if (e.target === ov) hideForgotPassword(); });
|
| 917 |
+
const otp = document.getElementById('fpOTP');
|
| 918 |
+
if (otp) otp.addEventListener('keydown', e => { if (e.key === 'Enter') fpVerifyOTP(); });
|
| 919 |
+
const cp = document.getElementById('fpConfirmPw');
|
| 920 |
+
if (cp) cp.addEventListener('keydown', e => { if (e.key === 'Enter') fpSetPassword(); });
|
| 921 |
+
});
|
| 922 |
+
|
| 923 |
+
</script>
|
| 924 |
+
<!-- CHANGE PASSWORD MODAL -->
|
| 925 |
+
<div id="changePwOverlay">
|
| 926 |
+
<div class="changepw-card">
|
| 927 |
+
<h3>π Change Password</h3>
|
| 928 |
+
<div id="changePwError" class="changepw-error"></div>
|
| 929 |
+
<div id="changePwSuccess" class="changepw-success"></div>
|
| 930 |
+
<div class="auth-field"><label>Current Password</label><input type="password" id="pwOld" placeholder="Your current password"></div>
|
| 931 |
+
<div class="auth-field"><label>New Password</label><input type="password" id="pwNew" placeholder="Min 6 characters"></div>
|
| 932 |
+
<div class="auth-field"><label>Confirm New Password</label><input type="password" id="pwConfirm" placeholder="Repeat new password"></div>
|
| 933 |
+
<button class="auth-btn" onclick="submitChangePassword()">Update Password</button>
|
| 934 |
+
<button class="changepw-cancel" onclick="hideChangePassword()">Cancel</button>
|
| 935 |
+
</div>
|
| 936 |
+
</div>
|
| 937 |
+
|
| 938 |
+
<!-- FORGOT PASSWORD MODAL -->
|
| 939 |
+
<div id="forgotOverlay" style="position:fixed;inset:0;background:rgba(11,31,58,0.85);backdrop-filter:blur(6px);display:none;align-items:center;justify-content:center;z-index:2000;">
|
| 940 |
+
<div class="auth-card" style="max-height:90vh;overflow-y:auto;">
|
| 941 |
+
<div class="auth-logo">
|
| 942 |
+
<div class="auth-logo-mark">AQ</div>
|
| 943 |
+
<div><h2 id="fpTitle">Reset Password</h2><p id="fpSubtitle">Enter your registered email</p></div>
|
| 944 |
+
</div>
|
| 945 |
+
<div id="fpError" class="auth-error"></div>
|
| 946 |
+
<div id="fpSuccess" style="background:#D1FAE5;border:1px solid #6EE7B7;border-radius:8px;padding:10px 14px;font-size:13px;color:#065F46;margin-bottom:14px;display:none;"></div>
|
| 947 |
+
|
| 948 |
+
<!-- Step 1: Email -->
|
| 949 |
+
<div id="fpStep1">
|
| 950 |
+
<div class="auth-field">
|
| 951 |
+
<label>Email Address</label>
|
| 952 |
+
<input type="email" id="fpEmail" placeholder="your@email.com">
|
| 953 |
+
</div>
|
| 954 |
+
<button class="auth-btn" onclick="fpSendOTP()">Send Reset Code</button>
|
| 955 |
+
<button onclick="hideForgotPassword()" style="width:100%;padding:10px;background:none;border:1.5px solid var(--border);border-radius:9px;font-family:'DM Sans',sans-serif;font-size:14px;color:var(--muted);cursor:pointer;margin-top:8px;">Cancel</button>
|
| 956 |
+
</div>
|
| 957 |
+
|
| 958 |
+
<!-- Step 2: OTP -->
|
| 959 |
+
<div id="fpStep2" style="display:none;">
|
| 960 |
+
<p style="font-size:13px;color:var(--muted);margin-bottom:16px;line-height:1.7;">A 6-digit code was sent to <strong id="fpEmailShow"></strong>. Check your inbox and spam folder.</p>
|
| 961 |
+
<div class="auth-field">
|
| 962 |
+
<label>6-Digit Reset Code</label>
|
| 963 |
+
<input type="text" id="fpOTP" placeholder="000000" maxlength="6" style="letter-spacing:8px;font-size:24px;text-align:center;font-family:monospace;">
|
| 964 |
+
</div>
|
| 965 |
+
<button class="auth-btn" onclick="fpVerifyOTP()">Verify Code</button>
|
| 966 |
+
<p style="text-align:center;margin-top:10px;font-size:12px;color:var(--muted);">
|
| 967 |
+
Didn't receive it? <a onclick="fpSendOTP()" style="color:var(--teal);cursor:pointer;">Resend</a>
|
| 968 |
+
Β· <a onclick="hideForgotPassword()" style="color:var(--muted);cursor:pointer;">Cancel</a>
|
| 969 |
+
</p>
|
| 970 |
+
</div>
|
| 971 |
+
|
| 972 |
+
<!-- Step 3: New Password -->
|
| 973 |
+
<div id="fpStep3" style="display:none;">
|
| 974 |
+
<div class="auth-field">
|
| 975 |
+
<label>New Password</label>
|
| 976 |
+
<input type="password" id="fpNewPw" placeholder="Min 6 characters">
|
| 977 |
+
</div>
|
| 978 |
+
<div class="auth-field">
|
| 979 |
+
<label>Confirm New Password</label>
|
| 980 |
+
<input type="password" id="fpConfirmPw" placeholder="Repeat new password">
|
| 981 |
+
</div>
|
| 982 |
+
<button class="auth-btn" onclick="fpSetPassword()">Set New Password</button>
|
| 983 |
+
</div>
|
| 984 |
+
</div>
|
| 985 |
+
</div>
|
| 986 |
+
|
| 987 |
+
</body>
|
| 988 |
+
</html>
|
frontend/index.html
ADDED
|
@@ -0,0 +1,573 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
<!DOCTYPE html>
|
| 2 |
+
<html lang="en">
|
| 3 |
+
<head>
|
| 4 |
+
<meta charset="UTF-8">
|
| 5 |
+
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
| 6 |
+
<title>AxonIQ β MS Symptom Checker</title>
|
| 7 |
+
<link href="https://fonts.googleapis.com/css2?family=Libre+Baskerville:ital,wght@0,400;0,700;1,400&family=DM+Sans:wght@300;400;500;600&display=swap" rel="stylesheet">
|
| 8 |
+
<style>
|
| 9 |
+
:root {
|
| 10 |
+
--navy: #0B1F3A;
|
| 11 |
+
--teal: #0A7B74;
|
| 12 |
+
--teal-lt: #E6F5F4;
|
| 13 |
+
--amber: #C97B2A;
|
| 14 |
+
--red: #B53535;
|
| 15 |
+
--purple: #5C3A8C;
|
| 16 |
+
--green: #1B6E44;
|
| 17 |
+
--sand: #F5F1EB;
|
| 18 |
+
--warm-white: #FDFAF6;
|
| 19 |
+
--border: #DDD8CF;
|
| 20 |
+
--text: #1A1510;
|
| 21 |
+
--muted: #6B6056;
|
| 22 |
+
}
|
| 23 |
+
|
| 24 |
+
*, *::before, *::after { box-sizing: border-box; margin: 0; padding: 0; }
|
| 25 |
+
|
| 26 |
+
body {
|
| 27 |
+
font-family: 'DM Sans', sans-serif;
|
| 28 |
+
background: var(--warm-white);
|
| 29 |
+
color: var(--text);
|
| 30 |
+
min-height: 100vh;
|
| 31 |
+
display: flex;
|
| 32 |
+
flex-direction: column;
|
| 33 |
+
}
|
| 34 |
+
|
| 35 |
+
header {
|
| 36 |
+
background: var(--navy);
|
| 37 |
+
padding: 28px 40px 24px;
|
| 38 |
+
display: flex;
|
| 39 |
+
align-items: flex-end;
|
| 40 |
+
gap: 20px;
|
| 41 |
+
border-bottom: 3px solid var(--teal);
|
| 42 |
+
}
|
| 43 |
+
.logo-mark {
|
| 44 |
+
width: 48px; height: 48px;
|
| 45 |
+
background: var(--teal);
|
| 46 |
+
border-radius: 12px;
|
| 47 |
+
display: flex; align-items: center; justify-content: center;
|
| 48 |
+
font-family: 'Libre Baskerville', serif;
|
| 49 |
+
font-size: 22px; font-weight: 700;
|
| 50 |
+
color: #fff; flex-shrink: 0;
|
| 51 |
+
letter-spacing: -1px;
|
| 52 |
+
}
|
| 53 |
+
.header-text h1 {
|
| 54 |
+
font-family: 'Libre Baskerville', serif;
|
| 55 |
+
font-size: 24px; font-weight: 700;
|
| 56 |
+
color: #fff; line-height: 1.1;
|
| 57 |
+
}
|
| 58 |
+
.header-text p { font-size: 13px; color: #8FA8BF; margin-top: 3px; font-weight: 300; }
|
| 59 |
+
.header-badge {
|
| 60 |
+
margin-left: auto;
|
| 61 |
+
background: rgba(10,123,116,0.25);
|
| 62 |
+
border: 1px solid rgba(10,123,116,0.5);
|
| 63 |
+
color: #5ECFC8;
|
| 64 |
+
font-size: 11px; font-weight: 500;
|
| 65 |
+
padding: 5px 12px; border-radius: 20px;
|
| 66 |
+
letter-spacing: 0.5px; text-transform: uppercase;
|
| 67 |
+
white-space: nowrap;
|
| 68 |
+
}
|
| 69 |
+
|
| 70 |
+
main {
|
| 71 |
+
flex: 1;
|
| 72 |
+
display: grid;
|
| 73 |
+
grid-template-columns: 1fr 1fr;
|
| 74 |
+
max-width: 1280px;
|
| 75 |
+
margin: 0 auto;
|
| 76 |
+
width: 100%;
|
| 77 |
+
}
|
| 78 |
+
|
| 79 |
+
/* LEFT */
|
| 80 |
+
.left-panel {
|
| 81 |
+
padding: 48px 40px;
|
| 82 |
+
border-right: 1px solid var(--border);
|
| 83 |
+
display: flex;
|
| 84 |
+
flex-direction: column;
|
| 85 |
+
gap: 28px;
|
| 86 |
+
}
|
| 87 |
+
.section-label {
|
| 88 |
+
font-size: 11px; font-weight: 600;
|
| 89 |
+
text-transform: uppercase; letter-spacing: 1.5px;
|
| 90 |
+
color: var(--muted); margin-bottom: 8px;
|
| 91 |
+
}
|
| 92 |
+
.symptom-textarea {
|
| 93 |
+
width: 100%; min-height: 260px;
|
| 94 |
+
padding: 18px 20px;
|
| 95 |
+
border: 1.5px solid var(--border); border-radius: 12px;
|
| 96 |
+
font-family: 'DM Sans', sans-serif; font-size: 15px; line-height: 1.7;
|
| 97 |
+
color: var(--text); background: #fff; resize: vertical; outline: none;
|
| 98 |
+
transition: border-color 0.2s, box-shadow 0.2s;
|
| 99 |
+
caret-color: var(--teal);
|
| 100 |
+
}
|
| 101 |
+
.symptom-textarea::placeholder { color: #B0A898; }
|
| 102 |
+
.symptom-textarea:focus {
|
| 103 |
+
border-color: var(--teal);
|
| 104 |
+
box-shadow: 0 0 0 3px rgba(10,123,116,0.1);
|
| 105 |
+
}
|
| 106 |
+
.char-count { margin-top: 6px; font-size: 12px; color: var(--muted); text-align: right; }
|
| 107 |
+
|
| 108 |
+
.example-prompts { display: flex; flex-direction: column; gap: 8px; }
|
| 109 |
+
.example-btn {
|
| 110 |
+
background: var(--sand); border: 1px solid var(--border); border-radius: 8px;
|
| 111 |
+
padding: 10px 14px; font-family: 'DM Sans', sans-serif;
|
| 112 |
+
font-size: 13px; color: var(--muted); cursor: pointer;
|
| 113 |
+
text-align: left; transition: background 0.15s, border-color 0.15s, color 0.15s;
|
| 114 |
+
line-height: 1.4;
|
| 115 |
+
}
|
| 116 |
+
.example-btn:hover { background: var(--teal-lt); border-color: var(--teal); color: var(--navy); }
|
| 117 |
+
.example-btn strong {
|
| 118 |
+
color: var(--navy); display: block; margin-bottom: 2px;
|
| 119 |
+
font-size: 12px; font-weight: 600;
|
| 120 |
+
text-transform: uppercase; letter-spacing: 0.5px;
|
| 121 |
+
}
|
| 122 |
+
|
| 123 |
+
.analyse-btn {
|
| 124 |
+
width: 100%; padding: 16px 24px;
|
| 125 |
+
background: var(--navy); color: #fff;
|
| 126 |
+
border: none; border-radius: 12px;
|
| 127 |
+
font-family: 'DM Sans', sans-serif;
|
| 128 |
+
font-size: 16px; font-weight: 600;
|
| 129 |
+
cursor: pointer;
|
| 130 |
+
display: flex; align-items: center; justify-content: center; gap: 10px;
|
| 131 |
+
transition: background 0.2s, transform 0.1s;
|
| 132 |
+
}
|
| 133 |
+
.analyse-btn:hover:not(:disabled) { background: #162F52; }
|
| 134 |
+
.analyse-btn:active:not(:disabled) { transform: scale(0.99); }
|
| 135 |
+
.analyse-btn:disabled { background: #8FA8BF; cursor: not-allowed; }
|
| 136 |
+
|
| 137 |
+
.spinner {
|
| 138 |
+
width: 18px; height: 18px;
|
| 139 |
+
border: 2px solid rgba(255,255,255,0.3);
|
| 140 |
+
border-top-color: #fff; border-radius: 50%;
|
| 141 |
+
animation: spin 0.7s linear infinite; display: none;
|
| 142 |
+
}
|
| 143 |
+
@keyframes spin { to { transform: rotate(360deg); } }
|
| 144 |
+
.loading .spinner { display: block; }
|
| 145 |
+
.loading .btn-label { opacity: 0.6; }
|
| 146 |
+
|
| 147 |
+
.error-banner {
|
| 148 |
+
background: #FEF2F2; border: 1px solid #FCA5A5; border-radius: 8px;
|
| 149 |
+
padding: 12px 16px; font-size: 13px; color: var(--red);
|
| 150 |
+
display: none; line-height: 1.5;
|
| 151 |
+
}
|
| 152 |
+
.error-banner.visible { display: block; }
|
| 153 |
+
|
| 154 |
+
.disclaimer {
|
| 155 |
+
font-size: 11.5px; color: var(--muted); line-height: 1.6;
|
| 156 |
+
padding: 14px 16px; background: var(--sand); border-radius: 8px;
|
| 157 |
+
border-left: 3px solid var(--amber);
|
| 158 |
+
}
|
| 159 |
+
|
| 160 |
+
/* RIGHT */
|
| 161 |
+
.right-panel {
|
| 162 |
+
padding: 48px 40px;
|
| 163 |
+
display: flex; flex-direction: column;
|
| 164 |
+
}
|
| 165 |
+
|
| 166 |
+
.idle-state {
|
| 167 |
+
flex: 1; display: flex; flex-direction: column;
|
| 168 |
+
align-items: center; justify-content: center;
|
| 169 |
+
text-align: center; gap: 16px; opacity: 0.45;
|
| 170 |
+
}
|
| 171 |
+
.idle-icon {
|
| 172 |
+
width: 64px; height: 64px; background: var(--sand); border-radius: 50%;
|
| 173 |
+
display: flex; align-items: center; justify-content: center; font-size: 28px;
|
| 174 |
+
}
|
| 175 |
+
.idle-state h3 { font-family: 'Libre Baskerville', serif; font-size: 18px; color: var(--navy); }
|
| 176 |
+
.idle-state p { font-size: 14px; color: var(--muted); max-width: 260px; line-height: 1.6; }
|
| 177 |
+
|
| 178 |
+
.result-card {
|
| 179 |
+
display: none; flex-direction: column; gap: 24px;
|
| 180 |
+
animation: fadeUp 0.4s ease;
|
| 181 |
+
}
|
| 182 |
+
@keyframes fadeUp {
|
| 183 |
+
from { opacity: 0; transform: translateY(12px); }
|
| 184 |
+
to { opacity: 1; transform: translateY(0); }
|
| 185 |
+
}
|
| 186 |
+
.result-card.visible { display: flex; }
|
| 187 |
+
|
| 188 |
+
.classification-banner {
|
| 189 |
+
border-radius: 14px; padding: 24px;
|
| 190 |
+
display: flex; align-items: center; gap: 16px;
|
| 191 |
+
position: relative; overflow: hidden;
|
| 192 |
+
}
|
| 193 |
+
.classification-banner::before {
|
| 194 |
+
content: ''; position: absolute; inset: 0; opacity: 0.07;
|
| 195 |
+
background-image: repeating-linear-gradient(45deg, currentColor 0, currentColor 1px, transparent 0, transparent 50%);
|
| 196 |
+
background-size: 8px 8px;
|
| 197 |
+
}
|
| 198 |
+
.tier-icon {
|
| 199 |
+
width: 52px; height: 52px; border-radius: 50%;
|
| 200 |
+
display: flex; align-items: center; justify-content: center;
|
| 201 |
+
font-size: 22px; flex-shrink: 0;
|
| 202 |
+
background: rgba(255,255,255,0.25);
|
| 203 |
+
}
|
| 204 |
+
.tier-info { flex: 1; }
|
| 205 |
+
.tier-name { font-family: 'Libre Baskerville', serif; font-size: 22px; font-weight: 700; line-height: 1.2; }
|
| 206 |
+
.tier-subtitle { font-size: 13px; margin-top: 4px; opacity: 0.85; }
|
| 207 |
+
|
| 208 |
+
.banner-emergency { background: #FEF2F2; color: var(--red); }
|
| 209 |
+
.banner-high { background: #FFF7ED; color: #92400E; }
|
| 210 |
+
.banner-moderate { background: #EFF6FF; color: #1E40AF; }
|
| 211 |
+
.banner-watch { background: #F5F3FF; color: var(--purple); }
|
| 212 |
+
.banner-low { background: #F0FDF4; color: var(--green); }
|
| 213 |
+
|
| 214 |
+
.action-section { background: var(--navy); border-radius: 14px; padding: 22px 24px; color: #fff; }
|
| 215 |
+
.action-section h3 {
|
| 216 |
+
font-size: 11px; font-weight: 600; text-transform: uppercase;
|
| 217 |
+
letter-spacing: 1.5px; color: #8FA8BF; margin-bottom: 10px;
|
| 218 |
+
}
|
| 219 |
+
.action-text { font-size: 15px; line-height: 1.65; color: #E8F0F8; }
|
| 220 |
+
|
| 221 |
+
.workup-section { background: var(--sand); border-radius: 14px; padding: 22px 24px; }
|
| 222 |
+
.workup-section h3 {
|
| 223 |
+
font-size: 11px; font-weight: 600; text-transform: uppercase;
|
| 224 |
+
letter-spacing: 1.5px; color: var(--muted); margin-bottom: 14px;
|
| 225 |
+
}
|
| 226 |
+
.workup-list { list-style: none; display: flex; flex-direction: column; gap: 8px; }
|
| 227 |
+
.workup-list li { display: flex; align-items: flex-start; gap: 10px; font-size: 13.5px; line-height: 1.5; }
|
| 228 |
+
.workup-check {
|
| 229 |
+
width: 18px; height: 18px; border-radius: 4px; background: var(--teal);
|
| 230 |
+
flex-shrink: 0; margin-top: 1px;
|
| 231 |
+
display: flex; align-items: center; justify-content: center;
|
| 232 |
+
}
|
| 233 |
+
.workup-check svg { width: 11px; height: 11px; }
|
| 234 |
+
|
| 235 |
+
.features-section { display: flex; flex-direction: column; gap: 10px; }
|
| 236 |
+
.features-section h3 {
|
| 237 |
+
font-size: 11px; font-weight: 600; text-transform: uppercase;
|
| 238 |
+
letter-spacing: 1.5px; color: var(--muted); margin-bottom: 2px;
|
| 239 |
+
}
|
| 240 |
+
.feature-tag {
|
| 241 |
+
display: inline-flex; align-items: center; gap: 7px;
|
| 242 |
+
background: var(--teal-lt); border: 1px solid rgba(10,123,116,0.2);
|
| 243 |
+
color: #065F5A; font-size: 13px; font-weight: 500;
|
| 244 |
+
padding: 7px 12px; border-radius: 20px; margin: 3px 4px 3px 0;
|
| 245 |
+
}
|
| 246 |
+
.feature-dot { width: 6px; height: 6px; border-radius: 50%; background: var(--teal); flex-shrink: 0; }
|
| 247 |
+
.lp-feature-tag {
|
| 248 |
+
display: inline-flex; align-items: center; gap: 7px;
|
| 249 |
+
background: #F5F3FF; border: 1px solid rgba(92,58,140,0.2);
|
| 250 |
+
color: #5B21B6; font-size: 13px; font-weight: 500;
|
| 251 |
+
padding: 7px 12px; border-radius: 20px; margin: 3px 4px 3px 0;
|
| 252 |
+
}
|
| 253 |
+
.lp-dot { width: 6px; height: 6px; border-radius: 50%; background: var(--purple); flex-shrink: 0; }
|
| 254 |
+
.lp-pill {
|
| 255 |
+
background: var(--purple); color: #fff;
|
| 256 |
+
font-size: 10px; font-weight: 600;
|
| 257 |
+
padding: 2px 8px; border-radius: 10px;
|
| 258 |
+
text-transform: uppercase; letter-spacing: 0.5px;
|
| 259 |
+
}
|
| 260 |
+
.temporal-note {
|
| 261 |
+
background: #FFFBEB; border: 1px solid #FCD34D; border-radius: 8px;
|
| 262 |
+
padding: 10px 14px; font-size: 13px; color: #78350F; line-height: 1.5;
|
| 263 |
+
}
|
| 264 |
+
|
| 265 |
+
.reset-btn {
|
| 266 |
+
align-self: flex-end; background: none;
|
| 267 |
+
border: 1.5px solid var(--border); border-radius: 8px;
|
| 268 |
+
padding: 8px 16px; font-family: 'DM Sans', sans-serif;
|
| 269 |
+
font-size: 13px; color: var(--muted);
|
| 270 |
+
cursor: pointer; transition: border-color 0.15s, color 0.15s;
|
| 271 |
+
margin-top: auto;
|
| 272 |
+
}
|
| 273 |
+
.reset-btn:hover { border-color: var(--navy); color: var(--navy); }
|
| 274 |
+
|
| 275 |
+
footer {
|
| 276 |
+
background: var(--navy); padding: 16px 40px;
|
| 277 |
+
display: flex; align-items: center; justify-content: space-between;
|
| 278 |
+
border-top: 1px solid rgba(255,255,255,0.08);
|
| 279 |
+
}
|
| 280 |
+
footer p { font-size: 12px; color: #5A7A99; }
|
| 281 |
+
.footer-credits { font-size: 12px; color: #5A7A99; text-align: right; line-height: 1.5; }
|
| 282 |
+
|
| 283 |
+
@media (max-width: 768px) {
|
| 284 |
+
main { grid-template-columns: 1fr; }
|
| 285 |
+
.left-panel { border-right: none; border-bottom: 1px solid var(--border); padding: 32px 24px; }
|
| 286 |
+
.right-panel { padding: 32px 24px; }
|
| 287 |
+
header { padding: 20px 24px; }
|
| 288 |
+
.header-badge { display: none; }
|
| 289 |
+
footer { flex-direction: column; gap: 6px; text-align: center; }
|
| 290 |
+
}
|
| 291 |
+
</style>
|
| 292 |
+
</head>
|
| 293 |
+
<body>
|
| 294 |
+
|
| 295 |
+
<header>
|
| 296 |
+
<div class="logo-mark">AQ</div>
|
| 297 |
+
<div class="header-text">
|
| 298 |
+
<h1>AxonIQ</h1>
|
| 299 |
+
<p>MS Symptom Analysis Β· Ocular Domain Β· v8.0 Β· Python Backend</p>
|
| 300 |
+
</div>
|
| 301 |
+
<div class="header-badge">Clinical Decision Support</div>
|
| 302 |
+
</header>
|
| 303 |
+
|
| 304 |
+
<main>
|
| 305 |
+
<div class="left-panel">
|
| 306 |
+
<div>
|
| 307 |
+
<div class="section-label">Describe your symptoms</div>
|
| 308 |
+
<textarea
|
| 309 |
+
class="symptom-textarea" id="symptomInput"
|
| 310 |
+
placeholder="Describe your symptoms in plain language. For example:
|
| 311 |
+
|
| 312 |
+
'My left eye has been blurry for the past 3 days. Colors look washed out β reds especially. It hurts when I move my eye. I also feel like the room is spinning when I try to focus.'"
|
| 313 |
+
oninput="updateChar()" maxlength="3000"
|
| 314 |
+
></textarea>
|
| 315 |
+
<div class="char-count"><span id="charCount">0</span> / 3000</div>
|
| 316 |
+
</div>
|
| 317 |
+
|
| 318 |
+
<div class="example-prompts">
|
| 319 |
+
<div class="section-label">Try an example</div>
|
| 320 |
+
<button class="example-btn" onclick="loadExample(0)">
|
| 321 |
+
<strong>Optic Neuritis</strong>
|
| 322 |
+
Left eye dimming, pain behind the eye worse when looking side-to-side. Colors washed out.
|
| 323 |
+
</button>
|
| 324 |
+
<button class="example-btn" onclick="loadExample(1)">
|
| 325 |
+
<strong>Brainstem / Double Vision</strong>
|
| 326 |
+
Woke up seeing double. Eyes feel jiggly. Poor balance β feels like being on a boat.
|
| 327 |
+
</button>
|
| 328 |
+
<button class="example-btn" onclick="loadExample(2)">
|
| 329 |
+
<strong>Lhermitte's Sign</strong>
|
| 330 |
+
Sharp electric shock runs down my spine whenever I bend my neck forward to look at my phone.
|
| 331 |
+
</button>
|
| 332 |
+
<button class="example-btn" onclick="loadExample(3)">
|
| 333 |
+
<strong>Low-Priority Signals</strong>
|
| 334 |
+
Sleeping poorly, restless legs every night. Feel much worse in hot weather. Constant ringing in both ears.
|
| 335 |
+
</button>
|
| 336 |
+
</div>
|
| 337 |
+
|
| 338 |
+
<div class="error-banner" id="errorBanner"></div>
|
| 339 |
+
|
| 340 |
+
<button class="analyse-btn" id="analyseBtn" onclick="runAnalysis()">
|
| 341 |
+
<div class="spinner" id="spinner"></div>
|
| 342 |
+
<span class="btn-label" id="btnLabel">Analyse Symptoms</span>
|
| 343 |
+
</button>
|
| 344 |
+
|
| 345 |
+
<div class="disclaimer">
|
| 346 |
+
<strong>β οΈ Clinical Decision Support Only</strong> β This tool is not a diagnosis.
|
| 347 |
+
All outputs must be reviewed by a qualified clinician.
|
| 348 |
+
MS workup includes MRI (orbits/brain/spine), LP for oligoclonal bands, and serum NMO/MOGAD assays.
|
| 349 |
+
</div>
|
| 350 |
+
</div>
|
| 351 |
+
|
| 352 |
+
<div class="right-panel">
|
| 353 |
+
<div class="idle-state" id="idleState">
|
| 354 |
+
<div class="idle-icon">π¬</div>
|
| 355 |
+
<h3>Ready to analyse</h3>
|
| 356 |
+
<p>Enter your symptoms on the left and click Analyse Symptoms.</p>
|
| 357 |
+
<p style="font-size:12px;color:#999;margin-top:4px;">Powered by Python NLP backend with NegEx negation detection</p>
|
| 358 |
+
</div>
|
| 359 |
+
|
| 360 |
+
<div class="result-card" id="resultCard">
|
| 361 |
+
<div class="classification-banner" id="classificationBanner">
|
| 362 |
+
<div class="tier-icon" id="tierIcon"></div>
|
| 363 |
+
<div class="tier-info">
|
| 364 |
+
<div class="tier-name" id="tierName"></div>
|
| 365 |
+
<div class="tier-subtitle" id="tierSubtitle"></div>
|
| 366 |
+
</div>
|
| 367 |
+
</div>
|
| 368 |
+
|
| 369 |
+
<!-- RECOMMENDED ACTION SECTION (commented out β content moved to Symptoms Identified)
|
| 370 |
+
<div class="action-section">
|
| 371 |
+
<h3>Recommended Action</h3>
|
| 372 |
+
<div class="action-text" id="actionText"></div>
|
| 373 |
+
</div>
|
| 374 |
+
-->
|
| 375 |
+
|
| 376 |
+
<div class="workup-section" id="workupSection" style="display:none">
|
| 377 |
+
<h3>Suggested Clinical Workup</h3>
|
| 378 |
+
<ul class="workup-list" id="workupList"></ul>
|
| 379 |
+
</div>
|
| 380 |
+
|
| 381 |
+
<div class="features-section" id="featuresSection" style="display:none">
|
| 382 |
+
<h3>Symptoms Identified</h3>
|
| 383 |
+
<div id="actionText" style="font-size:14px;line-height:1.65;color:var(--muted);margin-bottom:12px;padding:12px 14px;background:var(--teal-lt);border-radius:8px;border-left:3px solid var(--teal);"></div>
|
| 384 |
+
<div id="featureTags"></div>
|
| 385 |
+
<div id="lpSection" style="display:none;margin-top:10px;">
|
| 386 |
+
<div style="display:flex;align-items:center;gap:8px;margin-bottom:8px;">
|
| 387 |
+
<span style="font-size:11px;font-weight:600;text-transform:uppercase;letter-spacing:1.5px;color:var(--muted);">Additional signals</span>
|
| 388 |
+
<span class="lp-pill">low priority</span>
|
| 389 |
+
</div>
|
| 390 |
+
<div id="lpTags"></div>
|
| 391 |
+
</div>
|
| 392 |
+
</div>
|
| 393 |
+
|
| 394 |
+
<div id="temporalNotes"></div>
|
| 395 |
+
|
| 396 |
+
<button class="reset-btn" onclick="resetInterface()">β New Assessment</button>
|
| 397 |
+
</div>
|
| 398 |
+
</div>
|
| 399 |
+
</main>
|
| 400 |
+
|
| 401 |
+
<footer>
|
| 402 |
+
<p>AxonIQ v9.0 Β· FastAPI Β· spaCy + NegEx Β· LangGraph Agentic AI</p>
|
| 403 |
+
<div class="footer-credits">
|
| 404 |
+
Domain Expert: Dr. Avasarala, MD PhD, UKY, Lexington KY USA Β·
|
| 405 |
+
Lead AI Architect: Raghu Gangolu, NITW, Telangana India Β·
|
| 406 |
+
Principal Investigator: Dr. Kadambari, PhD, NITW, Telangana India
|
| 407 |
+
</div>
|
| 408 |
+
</footer>
|
| 409 |
+
|
| 410 |
+
<script>
|
| 411 |
+
// API base URL β change this to your deployed server URL
|
| 412 |
+
const API_BASE = window.location.origin;
|
| 413 |
+
|
| 414 |
+
const EXAMPLES = [
|
| 415 |
+
"My left eye has been dimming for 3 days. It feels like I am looking through dirty water. The colors look washed out, especially reds. There is an ache behind my eye that gets worse when I move my eye side to side.",
|
| 416 |
+
"I woke up this morning and I am seeing double. My eyes feel jiggly and crooked. I feel like I am on a boat β poor balance when walking. The room seems to be wobbling when I try to focus.",
|
| 417 |
+
"Every time I bend my neck forward to look at my phone, a sharp electric shock runs down my spine and into both my legs. It has been happening for 2 weeks.",
|
| 418 |
+
"I have been sleeping really poorly for months β restless legs every night. I feel significantly worse in hot weather. I also have a constant ringing in both ears.",
|
| 419 |
+
];
|
| 420 |
+
|
| 421 |
+
const TIER_ICONS = {
|
| 422 |
+
CRITICAL_EMERGENCY: "π¨",
|
| 423 |
+
HIGH: "β ",
|
| 424 |
+
MODERATE: "β",
|
| 425 |
+
WATCH: "β",
|
| 426 |
+
LOW: "β",
|
| 427 |
+
};
|
| 428 |
+
const TIER_BANNER_CLASS = {
|
| 429 |
+
CRITICAL_EMERGENCY: "banner-emergency",
|
| 430 |
+
HIGH: "banner-high",
|
| 431 |
+
MODERATE: "banner-moderate",
|
| 432 |
+
WATCH: "banner-watch",
|
| 433 |
+
LOW: "banner-low",
|
| 434 |
+
};
|
| 435 |
+
|
| 436 |
+
function loadExample(idx) {
|
| 437 |
+
document.getElementById("symptomInput").value = EXAMPLES[idx];
|
| 438 |
+
updateChar();
|
| 439 |
+
}
|
| 440 |
+
|
| 441 |
+
function updateChar() {
|
| 442 |
+
document.getElementById("charCount").textContent =
|
| 443 |
+
document.getElementById("symptomInput").value.length;
|
| 444 |
+
}
|
| 445 |
+
|
| 446 |
+
function showError(msg) {
|
| 447 |
+
const el = document.getElementById("errorBanner");
|
| 448 |
+
el.textContent = msg;
|
| 449 |
+
el.classList.add("visible");
|
| 450 |
+
}
|
| 451 |
+
|
| 452 |
+
function hideError() {
|
| 453 |
+
document.getElementById("errorBanner").classList.remove("visible");
|
| 454 |
+
}
|
| 455 |
+
|
| 456 |
+
function resetInterface() {
|
| 457 |
+
document.getElementById("idleState").style.display = "";
|
| 458 |
+
document.getElementById("resultCard").classList.remove("visible");
|
| 459 |
+
document.getElementById("symptomInput").value = "";
|
| 460 |
+
updateChar();
|
| 461 |
+
hideError();
|
| 462 |
+
}
|
| 463 |
+
|
| 464 |
+
async function runAnalysis() {
|
| 465 |
+
const text = document.getElementById("symptomInput").value.trim();
|
| 466 |
+
if (!text || text.length < 5) {
|
| 467 |
+
document.getElementById("symptomInput").focus();
|
| 468 |
+
return;
|
| 469 |
+
}
|
| 470 |
+
hideError();
|
| 471 |
+
|
| 472 |
+
const btn = document.getElementById("analyseBtn");
|
| 473 |
+
btn.classList.add("loading");
|
| 474 |
+
btn.disabled = true;
|
| 475 |
+
document.getElementById("btnLabel").textContent = "Analysingβ¦";
|
| 476 |
+
|
| 477 |
+
try {
|
| 478 |
+
const res = await fetch(`${API_BASE}/classify`, {
|
| 479 |
+
method: "POST",
|
| 480 |
+
headers: { "Content-Type": "application/json" },
|
| 481 |
+
body: JSON.stringify({ text }),
|
| 482 |
+
});
|
| 483 |
+
|
| 484 |
+
if (!res.ok) {
|
| 485 |
+
const err = await res.json().catch(() => ({}));
|
| 486 |
+
throw new Error(err.detail || `Server error ${res.status}`);
|
| 487 |
+
}
|
| 488 |
+
|
| 489 |
+
const data = await res.json();
|
| 490 |
+
renderResult(data);
|
| 491 |
+
} catch (e) {
|
| 492 |
+
showError(
|
| 493 |
+
`Could not reach the analysis server: ${e.message}. ` +
|
| 494 |
+
`Make sure the Python backend is running on ${API_BASE}`
|
| 495 |
+
);
|
| 496 |
+
} finally {
|
| 497 |
+
btn.classList.remove("loading");
|
| 498 |
+
btn.disabled = false;
|
| 499 |
+
document.getElementById("btnLabel").textContent = "Analyse Symptoms";
|
| 500 |
+
}
|
| 501 |
+
}
|
| 502 |
+
|
| 503 |
+
function renderResult(data) {
|
| 504 |
+
const banner = document.getElementById("classificationBanner");
|
| 505 |
+
banner.className = "classification-banner " + (TIER_BANNER_CLASS[data.tier] || "banner-low");
|
| 506 |
+
document.getElementById("tierIcon").textContent = TIER_ICONS[data.tier] || "β";
|
| 507 |
+
document.getElementById("tierName").textContent = data.tier_label;
|
| 508 |
+
document.getElementById("tierSubtitle").textContent = data.tier_subtitle;
|
| 509 |
+
document.getElementById("actionText").textContent = data.action;
|
| 510 |
+
|
| 511 |
+
// Workup
|
| 512 |
+
<!-- const workupSection = document.getElementById("workupSection");-->
|
| 513 |
+
<!-- if (data.workup && data.workup.length > 0 && data.tier !== "LOW") {-->
|
| 514 |
+
<!-- workupSection.style.display = "";-->
|
| 515 |
+
<!-- document.getElementById("workupList").innerHTML = data.workup-->
|
| 516 |
+
<!-- .map(item => `-->
|
| 517 |
+
<!-- <li>-->
|
| 518 |
+
<!-- <div class="workup-check">-->
|
| 519 |
+
<!-- <svg viewBox="0 0 11 11" fill="none">-->
|
| 520 |
+
<!-- <path d="M2 5.5L4.5 8L9 3" stroke="white" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/>-->
|
| 521 |
+
<!-- </svg>-->
|
| 522 |
+
<!-- </div>-->
|
| 523 |
+
<!-- <span>${item}</span>-->
|
| 524 |
+
<!-- </li>-->
|
| 525 |
+
<!-- `).join("");-->
|
| 526 |
+
<!-- } else {-->
|
| 527 |
+
<!-- workupSection.style.display = "none";-->
|
| 528 |
+
<!-- }-->sy
|
| 529 |
+
|
| 530 |
+
// Features
|
| 531 |
+
const std = (data.features || []).filter(f => f.priority === "standard");
|
| 532 |
+
const lp = (data.features || []).filter(f => f.priority === "low");
|
| 533 |
+
|
| 534 |
+
const featuresSection = document.getElementById("featuresSection");
|
| 535 |
+
if (data.action || std.length > 0 || lp.length > 0) {
|
| 536 |
+
featuresSection.style.display = "";
|
| 537 |
+
document.getElementById("featureTags").innerHTML = std
|
| 538 |
+
.map(f => `<span class="feature-tag"><span class="feature-dot"></span>${f.label}</span>`)
|
| 539 |
+
.join("");
|
| 540 |
+
|
| 541 |
+
const lpSection = document.getElementById("lpSection");
|
| 542 |
+
if (lp.length > 0) {
|
| 543 |
+
lpSection.style.display = "";
|
| 544 |
+
document.getElementById("lpTags").innerHTML = lp
|
| 545 |
+
.map(f => `<span class="lp-feature-tag"><span class="lp-dot"></span>${f.label}</span>`)
|
| 546 |
+
.join("");
|
| 547 |
+
} else {
|
| 548 |
+
lpSection.style.display = "none";
|
| 549 |
+
}
|
| 550 |
+
} else {
|
| 551 |
+
featuresSection.style.display = "none";
|
| 552 |
+
}
|
| 553 |
+
|
| 554 |
+
// Temporal
|
| 555 |
+
const temporalDiv = document.getElementById("temporalNotes");
|
| 556 |
+
temporalDiv.innerHTML = (data.temporal_notes || [])
|
| 557 |
+
.map(n => `<div class="temporal-note">β οΈ ${n}</div>`)
|
| 558 |
+
.join("");
|
| 559 |
+
|
| 560 |
+
document.getElementById("idleState").style.display = "none";
|
| 561 |
+
const card = document.getElementById("resultCard");
|
| 562 |
+
card.classList.add("visible");
|
| 563 |
+
card.scrollIntoView({ behavior: "smooth", block: "start" });
|
| 564 |
+
}
|
| 565 |
+
|
| 566 |
+
document.addEventListener("DOMContentLoaded", () => {
|
| 567 |
+
document.getElementById("symptomInput").addEventListener("keydown", e => {
|
| 568 |
+
if (e.key === "Enter" && (e.ctrlKey || e.metaKey)) runAnalysis();
|
| 569 |
+
});
|
| 570 |
+
});
|
| 571 |
+
</script>
|
| 572 |
+
</body>
|
| 573 |
+
</html>
|
scripts/setup_and_run.py
ADDED
|
@@ -0,0 +1,63 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python3
|
| 2 |
+
"""
|
| 3 |
+
NeuroCheck β One-command setup and launch script.
|
| 4 |
+
Run: python3 scripts/setup_and_run.py
|
| 5 |
+
"""
|
| 6 |
+
import subprocess, sys, os, pathlib
|
| 7 |
+
|
| 8 |
+
ROOT = pathlib.Path(__file__).parent.parent
|
| 9 |
+
MODEL_PATH = ROOT / "en_model"
|
| 10 |
+
|
| 11 |
+
def run(cmd, **kw):
|
| 12 |
+
print(f" $ {' '.join(cmd)}")
|
| 13 |
+
r = subprocess.run(cmd, **kw)
|
| 14 |
+
if r.returncode != 0:
|
| 15 |
+
print(f" ERROR (exit {r.returncode})")
|
| 16 |
+
sys.exit(r.returncode)
|
| 17 |
+
return r
|
| 18 |
+
|
| 19 |
+
print("\nββ NeuroCheck v9.0 Setup βββββββββββββββββββββββββββββ")
|
| 20 |
+
|
| 21 |
+
# 1. Build spaCy blank English model if not present
|
| 22 |
+
if not MODEL_PATH.exists():
|
| 23 |
+
print("\n[1/3] Building spaCy English model...")
|
| 24 |
+
script = f"""
|
| 25 |
+
import spacy
|
| 26 |
+
from spacy.lang.en import English
|
| 27 |
+
nlp = English()
|
| 28 |
+
nlp.add_pipe('sentencizer')
|
| 29 |
+
nlp.to_disk('{MODEL_PATH}')
|
| 30 |
+
print(' Model saved to {MODEL_PATH}')
|
| 31 |
+
"""
|
| 32 |
+
run([sys.executable, "-c", script])
|
| 33 |
+
else:
|
| 34 |
+
print(f"\n[1/3] spaCy model already exists at {MODEL_PATH} β")
|
| 35 |
+
|
| 36 |
+
# 2. Verify negspacy
|
| 37 |
+
print("\n[2/3] Verifying NegEx...")
|
| 38 |
+
run([sys.executable, "-c", """
|
| 39 |
+
import spacy
|
| 40 |
+
from negspacy.termsets import termset
|
| 41 |
+
from negspacy.negation import Negex
|
| 42 |
+
from pathlib import Path
|
| 43 |
+
root = Path.cwd()
|
| 44 |
+
model = root / 'en_model'
|
| 45 |
+
nlp = spacy.load(str(model) if model.exists() else 'en_core_web_sm')
|
| 46 |
+
ts = termset('en_clinical')
|
| 47 |
+
nlp.add_pipe('negex', config={'ent_types': ['SYMPTOM'], 'neg_termset': ts.get_patterns()})
|
| 48 |
+
print(' NegEx pipeline ready β')
|
| 49 |
+
"""], cwd=str(ROOT))
|
| 50 |
+
|
| 51 |
+
# 3. Launch FastAPI
|
| 52 |
+
print("\n[3/3] Starting FastAPI server on http://0.0.0.0:8000 ...")
|
| 53 |
+
print(" β Open http://localhost:8000 in your browser")
|
| 54 |
+
print(" β API docs: http://localhost:8000/docs")
|
| 55 |
+
print(" β Press Ctrl+C to stop\n")
|
| 56 |
+
|
| 57 |
+
os.environ["SPACY_MODEL"] = str(MODEL_PATH)
|
| 58 |
+
run([
|
| 59 |
+
sys.executable, "-m", "uvicorn", "api.main:app",
|
| 60 |
+
"--host", "0.0.0.0",
|
| 61 |
+
"--port", "8000",
|
| 62 |
+
"--reload",
|
| 63 |
+
], cwd=str(ROOT))
|