Spaces:
Sleeping
Sleeping
Upload 22 files
Browse files- git_ms_code/.env +25 -0
- git_ms_code/.env.example +16 -0
- git_ms_code/.github/workflows/ci.yml +127 -0
- git_ms_code/.gitignore +23 -0
- git_ms_code/Dockerfile +38 -0
- git_ms_code/README.md +23 -0
- git_ms_code/README_SETUP.md +199 -0
- git_ms_code/api/agent.py +503 -0
- git_ms_code/api/auth.py +162 -0
- git_ms_code/api/database.py +202 -0
- git_ms_code/api/main.py +1264 -0
- git_ms_code/api/memory.py +92 -0
- git_ms_code/api/rag.py +232 -0
- git_ms_code/docker-compose.yml +61 -0
- git_ms_code/frontend/chat.html +690 -0
- git_ms_code/frontend/index.html +573 -0
- git_ms_code/railway.toml +24 -0
- git_ms_code/render.yaml +28 -0
- git_ms_code/requirements.txt +44 -0
- git_ms_code/scripts/setup_and_run.py +63 -0
- git_ms_code/setup.py +270 -0
- git_ms_code/start.py +70 -0
git_ms_code/.env
ADDED
|
@@ -0,0 +1,25 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# NeuroCheck v9.1 - Environment Configuration
|
| 2 |
+
# Copy to .env, fill in JWT_SECRET before running setup.py
|
| 3 |
+
|
| 4 |
+
# Server
|
| 5 |
+
HOST=0.0.0.0
|
| 6 |
+
PORT=8000
|
| 7 |
+
WORKERS=1
|
| 8 |
+
|
| 9 |
+
# spaCy model path (relative to project root)
|
| 10 |
+
SPACY_MODEL=en_model
|
| 11 |
+
|
| 12 |
+
# SQLite database file
|
| 13 |
+
NEUROCHECK_DB=neurocheck.db
|
| 14 |
+
|
| 15 |
+
# JWT Auth - CHANGE THIS before first run!
|
| 16 |
+
# Generate: python -c "import secrets; print(secrets.token_hex(32))"
|
| 17 |
+
JWT_SECRET=c31e550c4f1a913d6fa2b08faefd1c49054b6ff249c3218e477fdd2f477455e3
|
| 18 |
+
JWT_EXPIRE_MINUTES=10080
|
| 19 |
+
|
| 20 |
+
# Ollama LLM (install from https://ollama.com)
|
| 21 |
+
OLLAMA_HOST=http://localhost:11434
|
| 22 |
+
LLM_MODEL=llama3.1:8b
|
| 23 |
+
|
| 24 |
+
# Logging
|
| 25 |
+
LOG_LEVEL=INFO
|
git_ms_code/.env.example
ADDED
|
@@ -0,0 +1,16 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# NeuroCheck v9.1 - Environment Configuration Template
|
| 2 |
+
# 1. Copy this file to .env
|
| 3 |
+
# 2. Generate a JWT secret: python -c "import secrets; print(secrets.token_hex(32))"
|
| 4 |
+
# 3. Paste the secret into JWT_SECRET below
|
| 5 |
+
# 4. Run: python setup.py
|
| 6 |
+
|
| 7 |
+
HOST=0.0.0.0
|
| 8 |
+
PORT=8000
|
| 9 |
+
WORKERS=1
|
| 10 |
+
SPACY_MODEL=en_model
|
| 11 |
+
NEUROCHECK_DB=neurocheck.db
|
| 12 |
+
JWT_SECRET=CHANGE_THIS_TO_A_LONG_RANDOM_SECRET_BEFORE_RUNNING
|
| 13 |
+
JWT_EXPIRE_MINUTES=10080
|
| 14 |
+
OLLAMA_HOST=http://localhost:11434
|
| 15 |
+
LLM_MODEL=llama3.1:8b
|
| 16 |
+
LOG_LEVEL=INFO
|
git_ms_code/.github/workflows/ci.yml
ADDED
|
@@ -0,0 +1,127 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
name: NeuroCheck CI/CD
|
| 2 |
+
|
| 3 |
+
on:
|
| 4 |
+
push:
|
| 5 |
+
branches: [main]
|
| 6 |
+
pull_request:
|
| 7 |
+
branches: [main]
|
| 8 |
+
|
| 9 |
+
jobs:
|
| 10 |
+
# ββ Test ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 11 |
+
test:
|
| 12 |
+
name: Run API Tests
|
| 13 |
+
runs-on: ubuntu-latest
|
| 14 |
+
|
| 15 |
+
steps:
|
| 16 |
+
- uses: actions/checkout@v4
|
| 17 |
+
|
| 18 |
+
- name: Set up Python 3.12
|
| 19 |
+
uses: actions/setup-python@v5
|
| 20 |
+
with:
|
| 21 |
+
python-version: "3.12"
|
| 22 |
+
cache: pip
|
| 23 |
+
|
| 24 |
+
- name: Install dependencies
|
| 25 |
+
run: pip install -r requirements.txt
|
| 26 |
+
|
| 27 |
+
- name: Build spaCy model
|
| 28 |
+
run: |
|
| 29 |
+
python3 -c "
|
| 30 |
+
import spacy
|
| 31 |
+
from spacy.lang.en import English
|
| 32 |
+
nlp = English()
|
| 33 |
+
nlp.add_pipe('sentencizer')
|
| 34 |
+
nlp.to_disk('en_model')
|
| 35 |
+
print('Model built')
|
| 36 |
+
"
|
| 37 |
+
|
| 38 |
+
- name: Start server and run tests
|
| 39 |
+
run: |
|
| 40 |
+
SPACY_MODEL=en_model python3 -m uvicorn api.main:app \
|
| 41 |
+
--host 127.0.0.1 --port 8000 --log-level error &
|
| 42 |
+
sleep 5
|
| 43 |
+
|
| 44 |
+
python3 -c "
|
| 45 |
+
import urllib.request, json, sys, time
|
| 46 |
+
|
| 47 |
+
def classify(text):
|
| 48 |
+
data = json.dumps({'text': text}).encode()
|
| 49 |
+
req = urllib.request.Request(
|
| 50 |
+
'http://127.0.0.1:8000/classify', data=data,
|
| 51 |
+
headers={'Content-Type': 'application/json'})
|
| 52 |
+
with urllib.request.urlopen(req, timeout=10) as r:
|
| 53 |
+
return json.loads(r.read())
|
| 54 |
+
|
| 55 |
+
tests = [
|
| 56 |
+
('Optic Neuritis', 'HIGH', 'Left eye dimming like dirty water. Colors washed out. Pain when moving my eye.'),
|
| 57 |
+
('Lhermitte Sign', 'HIGH', 'Sharp electric shock runs down spine when I bend my neck forward.'),
|
| 58 |
+
('Diplopia', 'HIGH', 'Woke up seeing double. Eyes feel jiggly. Poor balance.'),
|
| 59 |
+
('MS Hug', 'HIGH', 'Tight squeezing pressure around my midsection like a corset pulled too tight.'),
|
| 60 |
+
('Emergency Stroke', 'CRITICAL_EMERGENCY', 'Sudden face droop and arm weakness on the left side.'),
|
| 61 |
+
('WATCH tier', 'WATCH', 'Restless legs every night. Symptoms worse in hot weather. Ringing in both ears.'),
|
| 62 |
+
('Area Postrema', 'HIGH', 'Vision loss plus hiccups and vomiting.'),
|
| 63 |
+
('Uhthoff', 'HIGH', 'Vision shimmers after hot shower. Symptoms worse in heat.'),
|
| 64 |
+
('Vertigo Falls', 'HIGH', 'Constant vertigo and increasingly frequent falls over 6 weeks.'),
|
| 65 |
+
]
|
| 66 |
+
|
| 67 |
+
passed = 0
|
| 68 |
+
for name, expected, text in tests:
|
| 69 |
+
r = classify(text)
|
| 70 |
+
got = r['tier']
|
| 71 |
+
ok = got == expected
|
| 72 |
+
if ok: passed += 1
|
| 73 |
+
status = 'PASS' if ok else 'FAIL'
|
| 74 |
+
print(f' [{status}] {name}: expected={expected} got={got}')
|
| 75 |
+
|
| 76 |
+
print(f'\n {passed}/{len(tests)} tests passed')
|
| 77 |
+
if passed < len(tests):
|
| 78 |
+
sys.exit(1)
|
| 79 |
+
"
|
| 80 |
+
|
| 81 |
+
# ββ Docker Build ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 82 |
+
docker:
|
| 83 |
+
name: Build Docker Image
|
| 84 |
+
runs-on: ubuntu-latest
|
| 85 |
+
needs: test
|
| 86 |
+
if: github.ref == 'refs/heads/main'
|
| 87 |
+
|
| 88 |
+
steps:
|
| 89 |
+
- uses: actions/checkout@v4
|
| 90 |
+
|
| 91 |
+
- name: Set up Docker Buildx
|
| 92 |
+
uses: docker/setup-buildx-action@v3
|
| 93 |
+
|
| 94 |
+
- name: Log in to Docker Hub
|
| 95 |
+
uses: docker/login-action@v3
|
| 96 |
+
with:
|
| 97 |
+
username: ${{ secrets.DOCKERHUB_USERNAME }}
|
| 98 |
+
password: ${{ secrets.DOCKERHUB_TOKEN }}
|
| 99 |
+
# Remove this step if you are not pushing to Docker Hub
|
| 100 |
+
|
| 101 |
+
- name: Build and push Docker image
|
| 102 |
+
uses: docker/build-push-action@v5
|
| 103 |
+
with:
|
| 104 |
+
context: .
|
| 105 |
+
push: true
|
| 106 |
+
tags: |
|
| 107 |
+
${{ secrets.DOCKERHUB_USERNAME }}/neurocheck:latest
|
| 108 |
+
${{ secrets.DOCKERHUB_USERNAME }}/neurocheck:${{ github.sha }}
|
| 109 |
+
cache-from: type=gha
|
| 110 |
+
cache-to: type=gha,mode=max
|
| 111 |
+
|
| 112 |
+
# ββ Deploy to Render ββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 113 |
+
# Uncomment and add RENDER_API_KEY + RENDER_SERVICE_ID secrets to enable.
|
| 114 |
+
#
|
| 115 |
+
# deploy-render:
|
| 116 |
+
# name: Deploy to Render
|
| 117 |
+
# runs-on: ubuntu-latest
|
| 118 |
+
# needs: [test, docker]
|
| 119 |
+
# if: github.ref == 'refs/heads/main'
|
| 120 |
+
# steps:
|
| 121 |
+
# - name: Trigger Render deploy
|
| 122 |
+
# run: |
|
| 123 |
+
# curl -X POST \
|
| 124 |
+
# "https://api.render.com/v1/services/${{ secrets.RENDER_SERVICE_ID }}/deploys" \
|
| 125 |
+
# -H "Authorization: Bearer ${{ secrets.RENDER_API_KEY }}" \
|
| 126 |
+
# -H "Content-Type: application/json" \
|
| 127 |
+
# -d '{"clearCache": false}'
|
git_ms_code/.gitignore
ADDED
|
@@ -0,0 +1,23 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Python
|
| 2 |
+
__pycache__/
|
| 3 |
+
*.py[cod]
|
| 4 |
+
*.pyo
|
| 5 |
+
.venv/
|
| 6 |
+
venv/
|
| 7 |
+
*.egg-info/
|
| 8 |
+
|
| 9 |
+
# Secrets β NEVER commit these
|
| 10 |
+
.env
|
| 11 |
+
|
| 12 |
+
# Generated at runtime β don't commit
|
| 13 |
+
en_model/
|
| 14 |
+
chroma_db/
|
| 15 |
+
neurocheck.db
|
| 16 |
+
*.db
|
| 17 |
+
|
| 18 |
+
# OS
|
| 19 |
+
.DS_Store
|
| 20 |
+
Thumbs.db
|
| 21 |
+
|
| 22 |
+
# Logs
|
| 23 |
+
*.log
|
git_ms_code/Dockerfile
ADDED
|
@@ -0,0 +1,38 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
FROM python:3.12-slim
|
| 2 |
+
|
| 3 |
+
# System deps needed for spaCy, chromadb, bcrypt
|
| 4 |
+
RUN apt-get update && apt-get install -y \
|
| 5 |
+
gcc g++ git curl \
|
| 6 |
+
&& rm -rf /var/lib/apt/lists/*
|
| 7 |
+
|
| 8 |
+
WORKDIR /app
|
| 9 |
+
|
| 10 |
+
# Install Python deps first (cached layer)
|
| 11 |
+
COPY requirements.txt .
|
| 12 |
+
RUN pip install --no-cache-dir -r requirements.txt
|
| 13 |
+
|
| 14 |
+
# Copy app code
|
| 15 |
+
COPY . .
|
| 16 |
+
|
| 17 |
+
# Build spaCy model at image build time
|
| 18 |
+
RUN python3 -c "
|
| 19 |
+
from pathlib import Path
|
| 20 |
+
import spacy
|
| 21 |
+
from spacy.lang.en import English
|
| 22 |
+
nlp = English()
|
| 23 |
+
nlp.add_pipe('sentencizer')
|
| 24 |
+
Path('en_model').mkdir(exist_ok=True)
|
| 25 |
+
nlp.to_disk('en_model')
|
| 26 |
+
print('spaCy model built')
|
| 27 |
+
"
|
| 28 |
+
|
| 29 |
+
# HuggingFace Spaces runs as port 7860
|
| 30 |
+
ENV PORT=7860
|
| 31 |
+
ENV HOST=0.0.0.0
|
| 32 |
+
ENV WORKERS=1
|
| 33 |
+
ENV SPACY_MODEL=/app/en_model
|
| 34 |
+
ENV NEUROCHECK_DB=/tmp/neurocheck.db
|
| 35 |
+
|
| 36 |
+
EXPOSE 7860
|
| 37 |
+
|
| 38 |
+
CMD ["python3", "-m", "uvicorn", "api.main:app", "--host", "0.0.0.0", "--port", "7860", "--workers", "1"]
|
git_ms_code/README.md
ADDED
|
@@ -0,0 +1,23 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
---
|
| 2 |
+
title: NeuroCheck AI
|
| 3 |
+
emoji: π§
|
| 4 |
+
colorFrom: blue
|
| 5 |
+
colorTo: teal
|
| 6 |
+
sdk: docker
|
| 7 |
+
pinned: false
|
| 8 |
+
license: mit
|
| 9 |
+
short_description: MS Clinical AI Assistant - Symptom Classification + Agentic Chat
|
| 10 |
+
---
|
| 11 |
+
|
| 12 |
+
# NeuroCheck AI v9.1
|
| 13 |
+
|
| 14 |
+
MS Clinical Decision Support Assistant powered by Llama 3.1, RAG, and NegEx.
|
| 15 |
+
|
| 16 |
+
**Features:**
|
| 17 |
+
- MS symptom classifier with NegEx negation detection
|
| 18 |
+
- Agentic AI chat with LangGraph + Llama 3.1
|
| 19 |
+
- RAG knowledge base (ChromaDB + sentence-transformers)
|
| 20 |
+
- JWT auth with session history
|
| 21 |
+
- Live risk panel
|
| 22 |
+
|
| 23 |
+
**Built by:** Dr. Avasarala (UKY) Β· Dr. Kadambari (NITW)
|
git_ms_code/README_SETUP.md
ADDED
|
@@ -0,0 +1,199 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
| 1 |
+
# NeuroCheck v9.1 β Local Setup Guide
|
| 2 |
+
|
| 3 |
+
## Prerequisites
|
| 4 |
+
|
| 5 |
+
| Software | Version | Download |
|
| 6 |
+
|----------|---------|----------|
|
| 7 |
+
| Python | 3.10+ | https://python.org/downloads |
|
| 8 |
+
| Ollama | Latest | https://ollama.com/download |
|
| 9 |
+
| Git | Any | https://git-scm.com |
|
| 10 |
+
|
| 11 |
+
---
|
| 12 |
+
|
| 13 |
+
## One-Time Setup (run this once)
|
| 14 |
+
|
| 15 |
+
```bash
|
| 16 |
+
# 1. Clone / unzip the project, then enter it
|
| 17 |
+
cd neurocheck
|
| 18 |
+
|
| 19 |
+
# 2. Run the full setup script
|
| 20 |
+
python3 setup.py
|
| 21 |
+
```
|
| 22 |
+
|
| 23 |
+
The setup script will:
|
| 24 |
+
- Create a `.venv` virtual environment
|
| 25 |
+
- Install all Python packages from `requirements.txt`
|
| 26 |
+
- Build the spaCy English model (`en_model/`)
|
| 27 |
+
- Verify the NegEx negation pipeline
|
| 28 |
+
- Create and initialise the SQLite database (`neurocheck.db`)
|
| 29 |
+
- Check Ollama and pull `llama3.1:8b` if needed
|
| 30 |
+
|
| 31 |
+
---
|
| 32 |
+
|
| 33 |
+
## Before First Run β Set Your JWT Secret
|
| 34 |
+
|
| 35 |
+
Open `.env` and replace the placeholder:
|
| 36 |
+
|
| 37 |
+
```env
|
| 38 |
+
JWT_SECRET=CHANGE_THIS_TO_A_LONG_RANDOM_SECRET_BEFORE_RUNNING
|
| 39 |
+
```
|
| 40 |
+
|
| 41 |
+
Generate a real secret:
|
| 42 |
+
```bash
|
| 43 |
+
python3 -c "import secrets; print(secrets.token_hex(32))"
|
| 44 |
+
```
|
| 45 |
+
|
| 46 |
+
Copy the output into `.env`:
|
| 47 |
+
```env
|
| 48 |
+
JWT_SECRET=a1b2c3d4e5f6... (your generated value)
|
| 49 |
+
```
|
| 50 |
+
|
| 51 |
+
---
|
| 52 |
+
|
| 53 |
+
## Start the Server
|
| 54 |
+
|
| 55 |
+
```bash
|
| 56 |
+
python3 start.py
|
| 57 |
+
```
|
| 58 |
+
|
| 59 |
+
Or manually:
|
| 60 |
+
```bash
|
| 61 |
+
.venv/bin/python -m uvicorn api.main:app --host 0.0.0.0 --port 8000 --reload
|
| 62 |
+
```
|
| 63 |
+
|
| 64 |
+
### Open in Browser
|
| 65 |
+
|
| 66 |
+
| URL | Description |
|
| 67 |
+
|-----|-------------|
|
| 68 |
+
| http://localhost:8000 | MS Symptom Classifier |
|
| 69 |
+
| http://localhost:8000/chat-ui | AI Chat (login required) |
|
| 70 |
+
| http://localhost:8000/docs | Swagger API docs |
|
| 71 |
+
|
| 72 |
+
---
|
| 73 |
+
|
| 74 |
+
## Ollama Setup (for AI Chat)
|
| 75 |
+
|
| 76 |
+
Ollama runs the local LLM (Llama 3.1) that powers the chat assistant.
|
| 77 |
+
|
| 78 |
+
### Install Ollama
|
| 79 |
+
|
| 80 |
+
**Windows / macOS:** Download from https://ollama.com/download and run the installer.
|
| 81 |
+
|
| 82 |
+
**Linux:**
|
| 83 |
+
```bash
|
| 84 |
+
curl -fsSL https://ollama.com/install.sh | sh
|
| 85 |
+
```
|
| 86 |
+
|
| 87 |
+
### Start Ollama and Pull the Model
|
| 88 |
+
|
| 89 |
+
```bash
|
| 90 |
+
# Start the Ollama server (runs in background)
|
| 91 |
+
ollama serve
|
| 92 |
+
|
| 93 |
+
# Pull the model (4.7 GB β do this once)
|
| 94 |
+
ollama pull llama3.1:8b
|
| 95 |
+
|
| 96 |
+
# Verify it's working
|
| 97 |
+
ollama run llama3.1:8b "Hello"
|
| 98 |
+
```
|
| 99 |
+
|
| 100 |
+
> **Note:** The MS Symptom Classifier (`/classify`) works without Ollama.
|
| 101 |
+
> Only the `/chat` AI assistant requires Ollama to be running.
|
| 102 |
+
|
| 103 |
+
---
|
| 104 |
+
|
| 105 |
+
## Database
|
| 106 |
+
|
| 107 |
+
NeuroCheck uses SQLite β no separate database server needed.
|
| 108 |
+
|
| 109 |
+
**File:** `neurocheck.db` (created automatically by `setup.py`)
|
| 110 |
+
|
| 111 |
+
**Tables:**
|
| 112 |
+
|
| 113 |
+
| Table | What it stores |
|
| 114 |
+
|-------|---------------|
|
| 115 |
+
| `users` | Registered accounts (username, email, hashed password) |
|
| 116 |
+
| `chat_sessions` | Each conversation linked to a user (title, timestamps) |
|
| 117 |
+
| `messages` | Every message with role and UTC timestamp |
|
| 118 |
+
|
| 119 |
+
### Inspect the Database
|
| 120 |
+
|
| 121 |
+
```bash
|
| 122 |
+
# Open SQLite shell
|
| 123 |
+
sqlite3 neurocheck.db
|
| 124 |
+
|
| 125 |
+
# Inside the shell:
|
| 126 |
+
.tables
|
| 127 |
+
SELECT * FROM users;
|
| 128 |
+
SELECT session_uuid, title, updated_at FROM chat_sessions ORDER BY updated_at DESC;
|
| 129 |
+
SELECT role, content, created_at FROM messages WHERE session_uuid='<uuid>' ORDER BY id;
|
| 130 |
+
.quit
|
| 131 |
+
```
|
| 132 |
+
|
| 133 |
+
---
|
| 134 |
+
|
| 135 |
+
## Project Structure
|
| 136 |
+
|
| 137 |
+
```
|
| 138 |
+
neurocheck/
|
| 139 |
+
βββ api/
|
| 140 |
+
β βββ main.py β FastAPI app + all endpoints
|
| 141 |
+
β βββ auth.py β JWT login / register (NEW)
|
| 142 |
+
β βββ database.py β SQLite layer (NEW)
|
| 143 |
+
β βββ memory.py β In-memory session store
|
| 144 |
+
β βββ agent.py β LangGraph AI agent
|
| 145 |
+
β βββ rag.py β ChromaDB RAG knowledge base
|
| 146 |
+
βββ frontend/
|
| 147 |
+
β βββ chat.html β AI Chat UI (login + session sidebar)
|
| 148 |
+
β βββ index.html β MS Classifier UI
|
| 149 |
+
βββ en_model/ β Built by setup.py (spaCy)
|
| 150 |
+
βββ neurocheck.db β Created by setup.py (SQLite)
|
| 151 |
+
βββ chroma_db/ β Created at runtime (ChromaDB)
|
| 152 |
+
βββ .env β Your config (never commit this)
|
| 153 |
+
βββ .env.example β Template
|
| 154 |
+
βββ setup.py β One-time setup script
|
| 155 |
+
βββ start.py β Start the server
|
| 156 |
+
βββ requirements.txt
|
| 157 |
+
```
|
| 158 |
+
|
| 159 |
+
---
|
| 160 |
+
|
| 161 |
+
## Auth Endpoints
|
| 162 |
+
|
| 163 |
+
| Method | URL | Description |
|
| 164 |
+
|--------|-----|-------------|
|
| 165 |
+
| `POST` | `/auth/register` | Create account |
|
| 166 |
+
| `POST` | `/auth/login` | Get JWT token |
|
| 167 |
+
| `GET` | `/auth/me` | Current user info |
|
| 168 |
+
|
| 169 |
+
---
|
| 170 |
+
|
| 171 |
+
## Common Issues
|
| 172 |
+
|
| 173 |
+
### `spacy.errors.E050` β Model not found
|
| 174 |
+
```bash
|
| 175 |
+
python3 setup.py # rebuilds en_model/
|
| 176 |
+
```
|
| 177 |
+
|
| 178 |
+
### `Connection refused` on `/chat`
|
| 179 |
+
Ollama is not running. Start it:
|
| 180 |
+
```bash
|
| 181 |
+
ollama serve
|
| 182 |
+
```
|
| 183 |
+
|
| 184 |
+
### `401 Unauthorized` on `/chat`
|
| 185 |
+
Your JWT token expired or you are not logged in.
|
| 186 |
+
Open `http://localhost:8000/chat-ui` and log in again.
|
| 187 |
+
|
| 188 |
+
### Port 8000 already in use
|
| 189 |
+
```bash
|
| 190 |
+
python3 start.py --port 8080
|
| 191 |
+
```
|
| 192 |
+
|
| 193 |
+
### Database errors
|
| 194 |
+
```bash
|
| 195 |
+
python3 -c "
|
| 196 |
+
import os; os.environ['NEUROCHECK_DB']='neurocheck.db'
|
| 197 |
+
from api.database import init_db; init_db(); print('OK')
|
| 198 |
+
"
|
| 199 |
+
```
|
git_ms_code/api/agent.py
ADDED
|
@@ -0,0 +1,503 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
NeuroCheck Agentic AI β LangGraph Agent
|
| 3 |
+
Multi-turn clinical MS reasoning agent powered by Llama 3.1 via Ollama.
|
| 4 |
+
|
| 5 |
+
Architecture:
|
| 6 |
+
LangGraph StateGraph
|
| 7 |
+
βββ route_node β decides: greet / ask_more / classify / respond
|
| 8 |
+
βββ classify_node β runs NeuroCheck classifier (existing engine)
|
| 9 |
+
βββ rag_node β retrieves relevant MS knowledge chunks
|
| 10 |
+
βββ respond_node β LLM generates final clinical response
|
| 11 |
+
|
| 12 |
+
Tools available to the agent:
|
| 13 |
+
β’ classify_symptoms β runs the existing regex+NegEx MS classifier
|
| 14 |
+
β’ search_knowledge β queries ChromaDB RAG for clinical context
|
| 15 |
+
β’ get_workup β returns tier-specific workup recommendations
|
| 16 |
+
β’ check_emergency β checks for emergency patterns
|
| 17 |
+
"""
|
| 18 |
+
from __future__ import annotations
|
| 19 |
+
|
| 20 |
+
import json
|
| 21 |
+
import re
|
| 22 |
+
from typing import Any, Dict, List, TypedDict, Annotated
|
| 23 |
+
from loguru import logger
|
| 24 |
+
|
| 25 |
+
from langchain_ollama import ChatOllama
|
| 26 |
+
from langchain_huggingface import HuggingFaceEndpoint, ChatHuggingFace
|
| 27 |
+
from langchain_core.messages import HumanMessage, AIMessage, SystemMessage
|
| 28 |
+
from langchain_core.tools import tool
|
| 29 |
+
from langgraph.graph import StateGraph, END
|
| 30 |
+
from langgraph.prebuilt import ToolNode
|
| 31 |
+
from langgraph.graph.message import add_messages
|
| 32 |
+
|
| 33 |
+
# ββ LLM Setup βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 34 |
+
LLM_MODEL = "llama3.1:8b"
|
| 35 |
+
# ββ LLM backend: HuggingFace hosted or local Ollama ββββββββββββββββββββββββββ
|
| 36 |
+
_HF_TOKEN = os.environ.get("HF_TOKEN", "")
|
| 37 |
+
_USE_HF = bool(_HF_TOKEN) and _HF_TOKEN not in ("", "none", "local")
|
| 38 |
+
|
| 39 |
+
if _USE_HF:
|
| 40 |
+
logger.info("[NeuroCheck] Using HuggingFace Inference API ({})", LLM_MODEL)
|
| 41 |
+
_hf_endpoint = HuggingFaceEndpoint(
|
| 42 |
+
repo_id=os.environ.get("HF_MODEL", "meta-llama/Llama-3.1-8B-Instruct"),
|
| 43 |
+
huggingfacehub_api_token=_HF_TOKEN,
|
| 44 |
+
temperature=0.1,
|
| 45 |
+
max_new_tokens=1024,
|
| 46 |
+
)
|
| 47 |
+
llm = ChatHuggingFace(llm=_hf_endpoint)
|
| 48 |
+
else:
|
| 49 |
+
logger.info("[NeuroCheck] Using local Ollama ({})", LLM_MODEL)
|
| 50 |
+
llm = ChatOllama(model=LLM_MODEL, temperature=0.1, num_predict=1024)
|
| 51 |
+
|
| 52 |
+
# ββ System Prompt βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 53 |
+
SYSTEM_PROMPT = """You are NeuroCheck, an advanced clinical decision support AI specializing in Multiple Sclerosis (MS) symptom analysis. You were designed by Dr. Avasarala (MD PhD, University of Kentucky) and Dr. Kadambari (PhD, NIT Warangal).
|
| 54 |
+
|
| 55 |
+
YOUR ROLE:
|
| 56 |
+
- Conduct a structured clinical interview to gather neurological symptoms
|
| 57 |
+
- Identify patterns consistent with MS, NMOSD, MOGAD, or mimics
|
| 58 |
+
- Always recommend the standard MS workup when MS is suspected
|
| 59 |
+
- Ask focused follow-up questions to clarify key diagnostic anchors
|
| 60 |
+
- Never diagnose β you provide clinical decision support only
|
| 61 |
+
|
| 62 |
+
KEY MS ANCHOR SYMPTOMS to probe for:
|
| 63 |
+
1. Visual: Monocular blurring/dimming, pain on eye movement, colour fading (especially red), double vision, eye jiggling
|
| 64 |
+
2. Sensory: Electric shock down spine on neck bending (Lhermitte's), numbness/tingling in limbs, burning feet, dead limb feeling
|
| 65 |
+
3. Motor: Weakness in limbs, grip failure, foot drop, spasticity, tremor, gait unsteadiness
|
| 66 |
+
4. Brainstem: Diplopia, dizziness/vertigo, swallowing difficulty, facial pain/numbness
|
| 67 |
+
5. Autonomic: Bladder urgency, bowel dysfunction
|
| 68 |
+
6. Heat sensitivity (Uhthoff's): Symptoms worsen in heat, after hot shower, during exercise
|
| 69 |
+
7. Tight band sensation around chest/trunk (MS Hug)
|
| 70 |
+
8. Prior episodes that resolved spontaneously (Clinically Isolated Syndrome pattern)
|
| 71 |
+
|
| 72 |
+
STANDARD MS WORKUP (always recommend when MS is suspected):
|
| 73 |
+
- MRI Orbits with/without contrast (if optic nerve involvement suspected)
|
| 74 |
+
- MRI Brain and Spinal Cord with/without contrast
|
| 75 |
+
- Lumbar Puncture: CSF for oligoclonal bands (>2 exclusive to CSF), IgG index, kappa free light chains
|
| 76 |
+
- Serum Cell-Based Assay: NMO (AQP4-IgG) and MOGAD (MOG-IgG)
|
| 77 |
+
- Mimic Screen: Sarcoidosis, Lupus, Vasculitis, B12 deficiency, Cervical Myelopathy
|
| 78 |
+
|
| 79 |
+
EMERGENCY FLAGS (respond immediately):
|
| 80 |
+
- Sudden face droop + arm weakness + slurred speech β Possible Stroke (999/911)
|
| 81 |
+
- Fever + neck stiffness + photophobia β Possible Meningitis (999/911)
|
| 82 |
+
- Sudden worst-ever thunderclap headache β Possible Subarachnoid Haemorrhage (999/911)
|
| 83 |
+
- Ascending bilateral leg weakness spreading to arms β Possible GBS (999/911)
|
| 84 |
+
|
| 85 |
+
TONE: Professional, empathetic, clear. Ask ONE focused follow-up question at a time.
|
| 86 |
+
|
| 87 |
+
STRICT RESPONSE RULES β follow these exactly:
|
| 88 |
+
- NEVER end a response with "Would you like me to guide you through the next steps?"
|
| 89 |
+
- NEVER end with "Would you like more information on what to expect?"
|
| 90 |
+
- NEVER end with "Would you like to know more about X?"
|
| 91 |
+
- NEVER end with "Do you have any questions?" or "Feel free to ask if you have questions."
|
| 92 |
+
- NEVER end with "I'm here to support you throughout this process."
|
| 93 |
+
- NEVER repeat the same closing question twice in a conversation.
|
| 94 |
+
- If you have already asked a follow-up question in a previous turn, do NOT ask the same one again.
|
| 95 |
+
- After delivering clinical findings and recommendations, STOP. Do not append generic offers to help.
|
| 96 |
+
- If the patient answers "yes" to your follow-up question, move forward with the next clinical step β do NOT re-ask the same question.
|
| 97 |
+
|
| 98 |
+
GREETING BEHAVIOUR:
|
| 99 |
+
- If the user sends a greeting (hi, hello, hey, thanks, ok, yes, no, good morning, etc.) with NO symptom content, DO NOT call any tools.
|
| 100 |
+
- Instead respond warmly, introduce yourself briefly, and ask what symptoms brought them here today.
|
| 101 |
+
- Example: "Hello! I'm NeuroCheck, your MS clinical assistant. I'm here to help evaluate neurological symptoms. Could you describe what you've been experiencing?"
|
| 102 |
+
- Only call classify_symptoms or search_knowledge when the user has actually described a symptom.
|
| 103 |
+
"""
|
| 104 |
+
|
| 105 |
+
# ββ Agent State βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 106 |
+
class AgentState(TypedDict):
|
| 107 |
+
messages: Annotated[List, add_messages]
|
| 108 |
+
session_id: str
|
| 109 |
+
classification: Dict[str, Any] | None
|
| 110 |
+
rag_context: str
|
| 111 |
+
turn_count: int
|
| 112 |
+
|
| 113 |
+
|
| 114 |
+
# ββ Tools βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 115 |
+
@tool
|
| 116 |
+
def classify_symptoms(symptom_text: str) -> str:
|
| 117 |
+
"""
|
| 118 |
+
Run the NeuroCheck MS symptom classifier on the provided text.
|
| 119 |
+
Returns tier, detected features, and recommended action.
|
| 120 |
+
Use this after gathering sufficient symptom information.
|
| 121 |
+
"""
|
| 122 |
+
try:
|
| 123 |
+
# Import here to avoid circular imports
|
| 124 |
+
from api.main import classify as _classify
|
| 125 |
+
result = _classify(symptom_text)
|
| 126 |
+
return json.dumps({
|
| 127 |
+
"tier": result.tier,
|
| 128 |
+
"tier_label": result.tier_label,
|
| 129 |
+
"action": result.action,
|
| 130 |
+
"features": [{"label": f.label, "priority": f.priority} for f in result.features],
|
| 131 |
+
"temporal_notes": result.temporal_notes,
|
| 132 |
+
"workup": result.workup,
|
| 133 |
+
}, indent=2)
|
| 134 |
+
except Exception as e:
|
| 135 |
+
return f"Classifier error: {e}"
|
| 136 |
+
|
| 137 |
+
|
| 138 |
+
@tool
|
| 139 |
+
def search_knowledge(query: str) -> str:
|
| 140 |
+
"""
|
| 141 |
+
Search the MS clinical knowledge base (150 validated cases + guidelines).
|
| 142 |
+
Use this to find relevant case examples or clinical context for the patient's symptoms.
|
| 143 |
+
"""
|
| 144 |
+
try:
|
| 145 |
+
from api.rag import query as _query
|
| 146 |
+
results = _query(query, n_results=3)
|
| 147 |
+
if not results:
|
| 148 |
+
return "No relevant knowledge found."
|
| 149 |
+
out = []
|
| 150 |
+
for r in results:
|
| 151 |
+
out.append(f"[{r['source']} | relevance: {r['score']}]\n{r['text']}")
|
| 152 |
+
return "\n\n---\n\n".join(out)
|
| 153 |
+
except Exception as e:
|
| 154 |
+
return f"Knowledge search error: {e}"
|
| 155 |
+
|
| 156 |
+
|
| 157 |
+
@tool
|
| 158 |
+
def get_workup_recommendations(tier: str) -> str:
|
| 159 |
+
"""
|
| 160 |
+
Get specific workup recommendations for a given MS risk tier.
|
| 161 |
+
Tier options: HIGH, MODERATE, WATCH, LOW, CRITICAL_EMERGENCY
|
| 162 |
+
"""
|
| 163 |
+
workup_map = {
|
| 164 |
+
"CRITICAL_EMERGENCY": "Call emergency services immediately (999/911). Do not wait.",
|
| 165 |
+
"HIGH": (
|
| 166 |
+
"Urgent MS Workup Required:\n"
|
| 167 |
+
"1. MRI Orbits with/without contrast β screen for optic nerve involvement\n"
|
| 168 |
+
"2. MRI Brain and Spinal Cord with/without contrast\n"
|
| 169 |
+
"3. Lumbar Puncture β CSF for oligoclonal bands (>2 exclusive to CSF), IgG index, kappa free light chains\n"
|
| 170 |
+
"4. Serum Cell-Based Assay β NMO (AQP4-IgG) and MOGAD (MOG-IgG)\n"
|
| 171 |
+
"5. Mimic Screen β Sarcoidosis, Lupus, Vasculitis, B12 deficiency, Cervical Myelopathy\n"
|
| 172 |
+
"6. Urgent Neurology Referral"
|
| 173 |
+
),
|
| 174 |
+
"MODERATE": (
|
| 175 |
+
"Clinical Review Recommended:\n"
|
| 176 |
+
"1. Neurology referral for assessment\n"
|
| 177 |
+
"2. Basic blood panel β FBC, B12, folate, thyroid, ESR, CRP, ANA\n"
|
| 178 |
+
"3. Consider MRI Brain if symptoms persist\n"
|
| 179 |
+
"4. Ophthalmology review if visual symptoms present\n"
|
| 180 |
+
"5. Symptom diary β track onset, duration, triggers"
|
| 181 |
+
),
|
| 182 |
+
"WATCH": (
|
| 183 |
+
"Monitoring Advised:\n"
|
| 184 |
+
"1. Document symptoms β dates, frequency, new neurological signs\n"
|
| 185 |
+
"2. GP/Family physician review\n"
|
| 186 |
+
"3. Seek neurology referral if visual change, numbness, weakness, or coordination problems develop\n"
|
| 187 |
+
"4. Re-assess in 4-8 weeks"
|
| 188 |
+
),
|
| 189 |
+
"LOW": (
|
| 190 |
+
"No Specific MS Features:\n"
|
| 191 |
+
"1. Continue monitoring\n"
|
| 192 |
+
"2. Keep symptom diary\n"
|
| 193 |
+
"3. Seek medical review if new neurological symptoms develop"
|
| 194 |
+
),
|
| 195 |
+
}
|
| 196 |
+
return workup_map.get(tier.upper(), workup_map["LOW"])
|
| 197 |
+
|
| 198 |
+
|
| 199 |
+
TOOLS = [classify_symptoms, search_knowledge, get_workup_recommendations]
|
| 200 |
+
tool_node = ToolNode(TOOLS)
|
| 201 |
+
llm_with_tools = llm.bind_tools(TOOLS)
|
| 202 |
+
|
| 203 |
+
|
| 204 |
+
# ββ Graph Nodes βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 205 |
+
def agent_node(state: AgentState) -> AgentState:
|
| 206 |
+
"""Main reasoning node β LLM decides what to do next."""
|
| 207 |
+
messages = state["messages"]
|
| 208 |
+
turn = state.get("turn_count", 0)
|
| 209 |
+
|
| 210 |
+
# Inject RAG context if available
|
| 211 |
+
rag_ctx = state.get("rag_context", "")
|
| 212 |
+
system_content = SYSTEM_PROMPT
|
| 213 |
+
if rag_ctx:
|
| 214 |
+
system_content += f"\n\nRELEVANT CLINICAL CONTEXT:\n{rag_ctx}"
|
| 215 |
+
|
| 216 |
+
full_messages = [SystemMessage(content=system_content)] + messages
|
| 217 |
+
response = llm_with_tools.invoke(full_messages)
|
| 218 |
+
|
| 219 |
+
return {
|
| 220 |
+
**state,
|
| 221 |
+
"messages": [response],
|
| 222 |
+
"turn_count": turn + 1,
|
| 223 |
+
}
|
| 224 |
+
|
| 225 |
+
|
| 226 |
+
def should_continue(state: AgentState) -> str:
|
| 227 |
+
"""Router: if the LLM called a tool, run tools; else end."""
|
| 228 |
+
last = state["messages"][-1]
|
| 229 |
+
if hasattr(last, "tool_calls") and last.tool_calls:
|
| 230 |
+
return "tools"
|
| 231 |
+
return END
|
| 232 |
+
|
| 233 |
+
|
| 234 |
+
def rag_prefetch_node(state: AgentState) -> AgentState:
|
| 235 |
+
"""Pre-fetch RAG context based on the latest user message."""
|
| 236 |
+
try:
|
| 237 |
+
from api.rag import query as _query
|
| 238 |
+
# Get the last human message
|
| 239 |
+
last_human = ""
|
| 240 |
+
for m in reversed(state["messages"]):
|
| 241 |
+
if isinstance(m, HumanMessage):
|
| 242 |
+
last_human = m.content
|
| 243 |
+
break
|
| 244 |
+
if last_human:
|
| 245 |
+
results = _query(last_human, n_results=3)
|
| 246 |
+
ctx = "\n".join(f"- {r['text']}" for r in results if r["score"] > 0.3)
|
| 247 |
+
return {**state, "rag_context": ctx}
|
| 248 |
+
except Exception:
|
| 249 |
+
pass
|
| 250 |
+
return state
|
| 251 |
+
|
| 252 |
+
|
| 253 |
+
# ββ Build Graph βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 254 |
+
def build_graph() -> StateGraph:
|
| 255 |
+
graph = StateGraph(AgentState)
|
| 256 |
+
|
| 257 |
+
graph.add_node("rag_prefetch", rag_prefetch_node)
|
| 258 |
+
graph.add_node("agent", agent_node)
|
| 259 |
+
graph.add_node("tools", tool_node)
|
| 260 |
+
|
| 261 |
+
graph.set_entry_point("rag_prefetch")
|
| 262 |
+
graph.add_edge("rag_prefetch", "agent")
|
| 263 |
+
graph.add_conditional_edges("agent", should_continue, {"tools": "tools", END: END})
|
| 264 |
+
graph.add_edge("tools", "agent")
|
| 265 |
+
|
| 266 |
+
return graph.compile()
|
| 267 |
+
|
| 268 |
+
|
| 269 |
+
# ββ Public API βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 270 |
+
_graph = None
|
| 271 |
+
|
| 272 |
+
|
| 273 |
+
def get_graph():
|
| 274 |
+
global _graph
|
| 275 |
+
if _graph is None:
|
| 276 |
+
_graph = build_graph()
|
| 277 |
+
return _graph
|
| 278 |
+
|
| 279 |
+
|
| 280 |
+
# Greetings / filler words that carry no symptom content
|
| 281 |
+
# ββ Non-symptom messages that should never hit the classifier βββββββββββββββββ
|
| 282 |
+
_GREETINGS = {
|
| 283 |
+
# Basic greetings
|
| 284 |
+
"hi","hey","hello","hiya","howdy","greetings","sup","yo","hai",
|
| 285 |
+
"good morning","good afternoon","good evening","good night","good day",
|
| 286 |
+
"morning","afternoon","evening",
|
| 287 |
+
|
| 288 |
+
# Acknowledgements / filler
|
| 289 |
+
"ok","okay","k","kk","sure","alright","got it","understood","i see",
|
| 290 |
+
"noted","makes sense","that makes sense","i understand","understood",
|
| 291 |
+
"oh i see","oh okay","oh ok","ah ok","ah i see","i get it",
|
| 292 |
+
|
| 293 |
+
# Agreements / affirmations
|
| 294 |
+
"yes","yeah","yep","yup","yah","ye","yea","correct","exactly","right",
|
| 295 |
+
"absolutely","definitely","of course","certainly","indeed","true",
|
| 296 |
+
"that's right","thats right","that is right","sounds right",
|
| 297 |
+
|
| 298 |
+
# Disagreements / negations (without symptoms)
|
| 299 |
+
"no","nope","nah","not really","not sure","i don't know","idk","hmm",
|
| 300 |
+
"not yet","maybe","possibly","i think so","i guess","i suppose",
|
| 301 |
+
|
| 302 |
+
# Thanks / appreciation
|
| 303 |
+
"thanks","thank you","thank you so much","thanks a lot","thank u",
|
| 304 |
+
"ty","thnx","thx","many thanks","much appreciated","appreciate it",
|
| 305 |
+
"appreciate that","that's helpful","thats helpful","very helpful",
|
| 306 |
+
"that helped","that was helpful","that was very helpful",
|
| 307 |
+
|
| 308 |
+
# Compliments / positive reactions
|
| 309 |
+
"great","awesome","amazing","wonderful","excellent","fantastic","nice",
|
| 310 |
+
"good","very good","cool","perfect","brilliant","superb","impressive",
|
| 311 |
+
"wow","oh wow","that's great","thats great","that's amazing",
|
| 312 |
+
"that's good","thats good","good to know","interesting",
|
| 313 |
+
|
| 314 |
+
# Requests to continue / encouragement
|
| 315 |
+
"please continue","go on","continue","go ahead","please go on",
|
| 316 |
+
"tell me more","and then","and","what else","ok go on","okay go on",
|
| 317 |
+
|
| 318 |
+
# Farewells
|
| 319 |
+
"bye","goodbye","good bye","see you","see ya","take care","later",
|
| 320 |
+
"talk later","ttyl","cya","have a good day","have a nice day",
|
| 321 |
+
"farewell","until next time",
|
| 322 |
+
|
| 323 |
+
# Meta / about the bot
|
| 324 |
+
"who are you","what are you","what is neurocheck","what's neurocheck",
|
| 325 |
+
"whats neurocheck","what can you do","how does this work",
|
| 326 |
+
"how do you work","what do you do","tell me about yourself",
|
| 327 |
+
"are you a doctor","are you an ai","are you real","are you human",
|
| 328 |
+
|
| 329 |
+
# Confusion / unclear short inputs
|
| 330 |
+
"what","huh","sorry","pardon","can you repeat","come again",
|
| 331 |
+
"i didn't understand","i don't understand","please repeat",
|
| 332 |
+
"say that again","what do you mean","what does that mean",
|
| 333 |
+
|
| 334 |
+
# Common Indian English conversational starters
|
| 335 |
+
"hello ji","hi ji","namaste","namaskar","jai hind",
|
| 336 |
+
"haan","haan ji","nahi","theek hai","theek","bilkul","accha",
|
| 337 |
+
"thoda","shukriya","dhanyawad",
|
| 338 |
+
}
|
| 339 |
+
|
| 340 |
+
# Regex patterns for non-symptom messages (applied after set lookup)
|
| 341 |
+
_GREETING_PATTERNS = [
|
| 342 |
+
r"^(hi|hey|hello|good[\s]\w+)[!. ]*$",
|
| 343 |
+
r"^(thanks?( you)?[\w ]*)$",
|
| 344 |
+
r"^(ok(ay)?|sure|alright|got it)[!. ]*$",
|
| 345 |
+
r"^(yes|no|yeah|nope|yep|nah)[!., ]*$",
|
| 346 |
+
r"^(that.s (helpful|great|good|amazing|clear))[!. ]*$",
|
| 347 |
+
r"^(how are you|how.s it going)[?!. ]*$",
|
| 348 |
+
r"^(nice to meet you|pleased to meet you)[!. ]*$",
|
| 349 |
+
r"^(can you help me|i need help)[?!. ]*$",
|
| 350 |
+
r"^(what should i do|what do i do|what now)[?!. ]*$",
|
| 351 |
+
]
|
| 352 |
+
|
| 353 |
+
def _is_greeting(text: str) -> bool:
|
| 354 |
+
"""Return True if the message has no symptom content and is conversational filler."""
|
| 355 |
+
cleaned = text.strip().lower().rstrip("!.,? ")
|
| 356 |
+
# Direct set match
|
| 357 |
+
if cleaned in _GREETINGS:
|
| 358 |
+
return True
|
| 359 |
+
# Regex pattern match
|
| 360 |
+
for pat in _GREETING_PATTERNS:
|
| 361 |
+
if re.match(pat, cleaned):
|
| 362 |
+
return True
|
| 363 |
+
# Very short (1-2 words) and in set
|
| 364 |
+
if len(cleaned.split()) <= 3 and cleaned in _GREETINGS:
|
| 365 |
+
return True
|
| 366 |
+
return False
|
| 367 |
+
|
| 368 |
+
|
| 369 |
+
def chat(session_id: str, user_message: str, history: List[Dict]) -> str:
|
| 370 |
+
"""
|
| 371 |
+
Process a single user message and return the agent's response.
|
| 372 |
+
history: list of {"role": "human"/"assistant", "content": "..."}
|
| 373 |
+
"""
|
| 374 |
+
from langchain_core.messages import HumanMessage as HM, AIMessage as AM
|
| 375 |
+
|
| 376 |
+
# Fast-path: greetings & conversational inputs bypass the tool-calling graph
|
| 377 |
+
# IMPORTANT: only intercept on first turn OR pure openers (hi/hello/hey).
|
| 378 |
+
# Mid-conversation short replies like "no", "yes", "ok", "sure" must reach the LLM
|
| 379 |
+
# so they are interpreted in context (e.g. answering a clinical follow-up question).
|
| 380 |
+
human_turns = len([m for m in history if m["role"] == "human"])
|
| 381 |
+
is_first_turn = human_turns <= 1
|
| 382 |
+
|
| 383 |
+
# These words are ONLY intercepted on the very first turn β they carry
|
| 384 |
+
# meaning mid-conversation so must pass through to the LLM after turn 1.
|
| 385 |
+
_CONTEXT_DEPENDENT = {
|
| 386 |
+
"yes","yeah","yep","yup","yah","ye","yea","no","nope","nah",
|
| 387 |
+
"ok","okay","k","kk","sure","alright","got it","understood",
|
| 388 |
+
"correct","exactly","right","true","not really","maybe",
|
| 389 |
+
"possibly","i think so","i guess","i suppose","i don't know","idk",
|
| 390 |
+
"not sure","not yet","hmm","huh","what","go on","continue",
|
| 391 |
+
"please continue","go ahead","and","and then","what else",
|
| 392 |
+
"good","great","nice","cool","interesting","i see","oh i see",
|
| 393 |
+
"makes sense","that makes sense","noted","that's right","thats right",
|
| 394 |
+
}
|
| 395 |
+
|
| 396 |
+
msg = user_message.strip().lower().rstrip("!.,? ")
|
| 397 |
+
if _is_greeting(user_message) and (is_first_turn or msg not in _CONTEXT_DEPENDENT):
|
| 398 |
+
|
| 399 |
+
# "Who are you / what are you / what is neurocheck"
|
| 400 |
+
if any(x in msg for x in ["who are you","what are you","what is neurocheck",
|
| 401 |
+
"whats neurocheck","what can you do","tell me about",
|
| 402 |
+
"how does this work","how do you work","what do you do"]):
|
| 403 |
+
return (
|
| 404 |
+
"I'm NeuroCheck, an AI-powered clinical decision support assistant "
|
| 405 |
+
"specialising in Multiple Sclerosis (MS) and related neurological conditions.\n\n"
|
| 406 |
+
"I was designed by Dr. Avasarala (MD PhD, University of Kentucky) and "
|
| 407 |
+
"Dr. Kadambari (PhD, NIT Warangal).\n\n"
|
| 408 |
+
"I can help you:\n"
|
| 409 |
+
"β’ Analyse neurological symptoms for MS-related patterns\n"
|
| 410 |
+
"β’ Identify red-flag emergency signs\n"
|
| 411 |
+
"β’ Recommend the appropriate clinical workup (MRI, lumbar puncture, blood tests)\n"
|
| 412 |
+
"β’ Provide clinical context using our MS knowledge base\n\n"
|
| 413 |
+
"Please describe your symptoms and I'll begin a structured clinical assessment."
|
| 414 |
+
)
|
| 415 |
+
|
| 416 |
+
# "Are you a doctor / are you an AI / are you human"
|
| 417 |
+
if any(x in msg for x in ["are you a doctor","are you an ai","are you real",
|
| 418 |
+
"are you human","are you a robot"]):
|
| 419 |
+
return (
|
| 420 |
+
"I'm an AI assistant β not a doctor. I provide clinical decision support "
|
| 421 |
+
"to help identify patterns that may be consistent with MS or related conditions, "
|
| 422 |
+
"but I cannot diagnose.\n\n"
|
| 423 |
+
"Now, could you tell me what symptoms you've been experiencing?"
|
| 424 |
+
)
|
| 425 |
+
|
| 426 |
+
# "Can you help me / I need help"
|
| 427 |
+
if any(x in msg for x in ["can you help","i need help","help me","need some help"]):
|
| 428 |
+
return (
|
| 429 |
+
"Absolutely, I'm here to help. Please describe your neurological symptoms "
|
| 430 |
+
"in as much detail as you can β what you're feeling, where it is, when it "
|
| 431 |
+
"started, and whether it has happened before. I'll conduct a structured "
|
| 432 |
+
"clinical assessment from there."
|
| 433 |
+
)
|
| 434 |
+
|
| 435 |
+
# "Sorry / I didn't understand / what do you mean"
|
| 436 |
+
if any(x in msg for x in ["sorry","didn't understand","don't understand",
|
| 437 |
+
"what do you mean","what does that mean","confused",
|
| 438 |
+
"can you repeat","say that again","pardon","huh","what"]):
|
| 439 |
+
return (
|
| 440 |
+
"No problem! Let me know which part was unclear and I'll explain it "
|
| 441 |
+
"differently. Or if you'd like to start fresh, just describe your symptoms "
|
| 442 |
+
"and I'll begin the assessment."
|
| 443 |
+
)
|
| 444 |
+
|
| 445 |
+
# Farewell
|
| 446 |
+
if any(x in msg for x in ["bye","goodbye","good bye","see you","take care",
|
| 447 |
+
"farewell","talk later","ttyl","have a good day",
|
| 448 |
+
"have a nice day"]):
|
| 449 |
+
return (
|
| 450 |
+
"Take care! If your symptoms change or new ones develop, don't hesitate "
|
| 451 |
+
"to return. Wishing you good health."
|
| 452 |
+
)
|
| 453 |
+
|
| 454 |
+
# Thanks / appreciation
|
| 455 |
+
if any(x in msg for x in ["thank","thanks","ty","thnx","appreciate",
|
| 456 |
+
"helpful","that helped","very helpful"]):
|
| 457 |
+
return (
|
| 458 |
+
"You're welcome! If you have more symptoms to discuss or any follow-up "
|
| 459 |
+
"questions, I'm here. Is there anything else you'd like me to assess?"
|
| 460 |
+
)
|
| 461 |
+
|
| 462 |
+
# Default greeting / filler (first turn vs returning)
|
| 463 |
+
if is_first_turn:
|
| 464 |
+
return (
|
| 465 |
+
"Hello! I'm NeuroCheck, your MS clinical decision support assistant.\n\n"
|
| 466 |
+
"I'm here to help evaluate neurological symptoms that may be related to "
|
| 467 |
+
"Multiple Sclerosis or similar conditions. Could you describe what you've "
|
| 468 |
+
"been experiencing? Please include when it started, which part of the body "
|
| 469 |
+
"is affected, and whether it has happened before."
|
| 470 |
+
)
|
| 471 |
+
else:
|
| 472 |
+
return (
|
| 473 |
+
"Of course! Please go ahead and describe your symptoms. "
|
| 474 |
+
"Include when they started, which part of the body is affected, "
|
| 475 |
+
"and whether anything makes them better or worse."
|
| 476 |
+
)
|
| 477 |
+
|
| 478 |
+
# Rebuild message history for LangGraph
|
| 479 |
+
lc_history = []
|
| 480 |
+
for m in history[:-1]: # exclude the latest (just added)
|
| 481 |
+
if m["role"] == "human":
|
| 482 |
+
lc_history.append(HM(content=m["content"]))
|
| 483 |
+
else:
|
| 484 |
+
lc_history.append(AM(content=m["content"]))
|
| 485 |
+
|
| 486 |
+
lc_history.append(HM(content=user_message))
|
| 487 |
+
|
| 488 |
+
state: AgentState = {
|
| 489 |
+
"messages": lc_history,
|
| 490 |
+
"session_id": session_id,
|
| 491 |
+
"classification": None,
|
| 492 |
+
"rag_context": "",
|
| 493 |
+
"turn_count": len(history),
|
| 494 |
+
}
|
| 495 |
+
|
| 496 |
+
g = get_graph()
|
| 497 |
+
result = g.invoke(state)
|
| 498 |
+
|
| 499 |
+
# Extract final text response
|
| 500 |
+
final_msg = result["messages"][-1]
|
| 501 |
+
if hasattr(final_msg, "content"):
|
| 502 |
+
return final_msg.content
|
| 503 |
+
return str(final_msg)
|
git_ms_code/api/auth.py
ADDED
|
@@ -0,0 +1,162 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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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 |
+
|
| 59 |
+
|
| 60 |
+
# ββ Helpers βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 61 |
+
|
| 62 |
+
def hash_password(plain: str) -> str:
|
| 63 |
+
return _bcrypt.hashpw(plain.encode("utf-8"), _bcrypt.gensalt()).decode("utf-8")
|
| 64 |
+
|
| 65 |
+
|
| 66 |
+
def verify_password(plain: str, hashed: str) -> bool:
|
| 67 |
+
try:
|
| 68 |
+
return _bcrypt.checkpw(plain.encode("utf-8"), hashed.encode("utf-8"))
|
| 69 |
+
except Exception:
|
| 70 |
+
return False
|
| 71 |
+
|
| 72 |
+
|
| 73 |
+
def create_access_token(user_id: int, username: str) -> str:
|
| 74 |
+
expire = datetime.now(timezone.utc) + timedelta(minutes=ACCESS_TOKEN_EXPIRE_MINUTES)
|
| 75 |
+
payload = {"sub": str(user_id), "username": username, "exp": expire}
|
| 76 |
+
return jwt.encode(payload, SECRET_KEY, algorithm=ALGORITHM)
|
| 77 |
+
|
| 78 |
+
|
| 79 |
+
def decode_token(token: str) -> dict:
|
| 80 |
+
try:
|
| 81 |
+
return jwt.decode(token, SECRET_KEY, algorithms=[ALGORITHM])
|
| 82 |
+
except JWTError:
|
| 83 |
+
raise HTTPException(
|
| 84 |
+
status_code=status.HTTP_401_UNAUTHORIZED,
|
| 85 |
+
detail="Invalid or expired token",
|
| 86 |
+
headers={"WWW-Authenticate": "Bearer"},
|
| 87 |
+
)
|
| 88 |
+
|
| 89 |
+
|
| 90 |
+
# ββ Dependency: get current user from Bearer token ββββββββββββββββββββββββββββ
|
| 91 |
+
|
| 92 |
+
def get_current_user(token: str = Depends(oauth2_scheme)) -> dict:
|
| 93 |
+
"""FastAPI dependency β inject into any protected route."""
|
| 94 |
+
payload = decode_token(token)
|
| 95 |
+
user_id = int(payload.get("sub", 0))
|
| 96 |
+
user = get_user_by_id(user_id)
|
| 97 |
+
if not user:
|
| 98 |
+
raise HTTPException(status_code=401, detail="User not found")
|
| 99 |
+
return user
|
| 100 |
+
|
| 101 |
+
|
| 102 |
+
def get_optional_user(token: Optional[str] = Depends(oauth2_scheme)) -> Optional[dict]:
|
| 103 |
+
"""Like get_current_user but returns None instead of raising (for semi-public routes)."""
|
| 104 |
+
if not token:
|
| 105 |
+
return None
|
| 106 |
+
try:
|
| 107 |
+
return get_current_user(token)
|
| 108 |
+
except HTTPException:
|
| 109 |
+
return None
|
| 110 |
+
|
| 111 |
+
|
| 112 |
+
# ββ Routes ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 113 |
+
|
| 114 |
+
@router.post("/register", status_code=201)
|
| 115 |
+
async def register(req: RegisterRequest):
|
| 116 |
+
"""Create a new user account."""
|
| 117 |
+
init_db()
|
| 118 |
+
|
| 119 |
+
if get_user_by_username(req.username):
|
| 120 |
+
raise HTTPException(status_code=409, detail="Username already taken")
|
| 121 |
+
if get_user_by_email(req.email):
|
| 122 |
+
raise HTTPException(status_code=409, detail="Email already registered")
|
| 123 |
+
|
| 124 |
+
hashed = hash_password(req.password)
|
| 125 |
+
uid = create_user(req.username, req.email, hashed)
|
| 126 |
+
token = create_access_token(uid, req.username)
|
| 127 |
+
|
| 128 |
+
return LoginResponse(
|
| 129 |
+
access_token=token,
|
| 130 |
+
user_id=uid,
|
| 131 |
+
username=req.username,
|
| 132 |
+
)
|
| 133 |
+
|
| 134 |
+
|
| 135 |
+
@router.post("/login", response_model=LoginResponse)
|
| 136 |
+
async def login(form: OAuth2PasswordRequestForm = Depends()):
|
| 137 |
+
"""Authenticate and return JWT. Accepts username OR email in the username field."""
|
| 138 |
+
user = get_user_by_username(form.username) or get_user_by_email(form.username)
|
| 139 |
+
if not user or not verify_password(form.password, user["password_hash"]):
|
| 140 |
+
raise HTTPException(
|
| 141 |
+
status_code=status.HTTP_401_UNAUTHORIZED,
|
| 142 |
+
detail="Incorrect username/email or password",
|
| 143 |
+
headers={"WWW-Authenticate": "Bearer"},
|
| 144 |
+
)
|
| 145 |
+
|
| 146 |
+
token = create_access_token(user["id"], user["username"])
|
| 147 |
+
return LoginResponse(
|
| 148 |
+
access_token=token,
|
| 149 |
+
user_id=user["id"],
|
| 150 |
+
username=user["username"],
|
| 151 |
+
)
|
| 152 |
+
|
| 153 |
+
|
| 154 |
+
@router.get("/me", response_model=UserInfo)
|
| 155 |
+
async def me(current_user: dict = Depends(get_current_user)):
|
| 156 |
+
"""Return current user's profile info."""
|
| 157 |
+
return UserInfo(
|
| 158 |
+
user_id=current_user["id"],
|
| 159 |
+
username=current_user["username"],
|
| 160 |
+
email=current_user["email"],
|
| 161 |
+
created_at=current_user["created_at"],
|
| 162 |
+
)
|
git_ms_code/api/database.py
ADDED
|
@@ -0,0 +1,202 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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 |
+
with get_conn() as conn:
|
| 48 |
+
conn.executescript("""
|
| 49 |
+
CREATE TABLE IF NOT EXISTS users (
|
| 50 |
+
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
| 51 |
+
username TEXT NOT NULL UNIQUE COLLATE NOCASE,
|
| 52 |
+
email TEXT NOT NULL UNIQUE COLLATE NOCASE,
|
| 53 |
+
password_hash TEXT NOT NULL,
|
| 54 |
+
created_at TEXT NOT NULL
|
| 55 |
+
);
|
| 56 |
+
|
| 57 |
+
CREATE TABLE IF NOT EXISTS chat_sessions (
|
| 58 |
+
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
| 59 |
+
session_uuid TEXT NOT NULL UNIQUE,
|
| 60 |
+
user_id INTEGER NOT NULL REFERENCES users(id) ON DELETE CASCADE,
|
| 61 |
+
title TEXT NOT NULL DEFAULT 'New Chat',
|
| 62 |
+
created_at TEXT NOT NULL,
|
| 63 |
+
updated_at TEXT NOT NULL
|
| 64 |
+
);
|
| 65 |
+
|
| 66 |
+
CREATE TABLE IF NOT EXISTS messages (
|
| 67 |
+
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
| 68 |
+
session_uuid TEXT NOT NULL REFERENCES chat_sessions(session_uuid) ON DELETE CASCADE,
|
| 69 |
+
role TEXT NOT NULL CHECK(role IN ('human','assistant','system')),
|
| 70 |
+
content TEXT NOT NULL,
|
| 71 |
+
created_at TEXT NOT NULL
|
| 72 |
+
);
|
| 73 |
+
|
| 74 |
+
CREATE INDEX IF NOT EXISTS idx_sessions_user ON chat_sessions(user_id);
|
| 75 |
+
CREATE INDEX IF NOT EXISTS idx_messages_session ON messages(session_uuid);
|
| 76 |
+
""")
|
| 77 |
+
|
| 78 |
+
|
| 79 |
+
# ββ User CRUD βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 80 |
+
|
| 81 |
+
def create_user(username: str, email: str, password_hash: str) -> int:
|
| 82 |
+
"""Insert a new user. Returns the new user's integer id."""
|
| 83 |
+
with get_conn() as conn:
|
| 84 |
+
cur = conn.execute(
|
| 85 |
+
"INSERT INTO users (username, email, password_hash, created_at) VALUES (?,?,?,?)",
|
| 86 |
+
(username.strip(), email.strip().lower(), password_hash, _now()),
|
| 87 |
+
)
|
| 88 |
+
return cur.lastrowid
|
| 89 |
+
|
| 90 |
+
|
| 91 |
+
def get_user_by_username(username: str) -> Optional[Dict[str, Any]]:
|
| 92 |
+
with get_conn() as conn:
|
| 93 |
+
row = conn.execute(
|
| 94 |
+
"SELECT * FROM users WHERE username = ? COLLATE NOCASE", (username,)
|
| 95 |
+
).fetchone()
|
| 96 |
+
return dict(row) if row else None
|
| 97 |
+
|
| 98 |
+
|
| 99 |
+
def get_user_by_email(email: str) -> Optional[Dict[str, Any]]:
|
| 100 |
+
with get_conn() as conn:
|
| 101 |
+
row = conn.execute(
|
| 102 |
+
"SELECT * FROM users WHERE email = ? COLLATE NOCASE", (email.strip().lower(),)
|
| 103 |
+
).fetchone()
|
| 104 |
+
return dict(row) if row else None
|
| 105 |
+
|
| 106 |
+
|
| 107 |
+
def get_user_by_id(user_id: int) -> Optional[Dict[str, Any]]:
|
| 108 |
+
with get_conn() as conn:
|
| 109 |
+
row = conn.execute("SELECT * FROM users WHERE id = ?", (user_id,)).fetchone()
|
| 110 |
+
return dict(row) if row else None
|
| 111 |
+
|
| 112 |
+
|
| 113 |
+
# ββ Session CRUD ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 114 |
+
|
| 115 |
+
def create_db_session(session_uuid: str, user_id: int, title: str = "New Chat") -> None:
|
| 116 |
+
"""Persist a new chat session linked to a user."""
|
| 117 |
+
now = _now()
|
| 118 |
+
with get_conn() as conn:
|
| 119 |
+
conn.execute(
|
| 120 |
+
"INSERT OR IGNORE INTO chat_sessions (session_uuid, user_id, title, created_at, updated_at) "
|
| 121 |
+
"VALUES (?,?,?,?,?)",
|
| 122 |
+
(session_uuid, user_id, title, now, now),
|
| 123 |
+
)
|
| 124 |
+
|
| 125 |
+
|
| 126 |
+
def get_user_sessions(user_id: int) -> List[Dict[str, Any]]:
|
| 127 |
+
"""Return all sessions for a user, newest first."""
|
| 128 |
+
with get_conn() as conn:
|
| 129 |
+
rows = conn.execute(
|
| 130 |
+
"SELECT * FROM chat_sessions WHERE user_id = ? ORDER BY updated_at DESC",
|
| 131 |
+
(user_id,),
|
| 132 |
+
).fetchall()
|
| 133 |
+
return [dict(r) for r in rows]
|
| 134 |
+
|
| 135 |
+
|
| 136 |
+
def update_session_title(session_uuid: str, title: str) -> None:
|
| 137 |
+
now = _now()
|
| 138 |
+
with get_conn() as conn:
|
| 139 |
+
conn.execute(
|
| 140 |
+
"UPDATE chat_sessions SET title=?, updated_at=? WHERE session_uuid=?",
|
| 141 |
+
(title[:80], now, session_uuid),
|
| 142 |
+
)
|
| 143 |
+
|
| 144 |
+
|
| 145 |
+
def touch_session(session_uuid: str) -> None:
|
| 146 |
+
"""Update the updated_at timestamp on a session."""
|
| 147 |
+
with get_conn() as conn:
|
| 148 |
+
conn.execute(
|
| 149 |
+
"UPDATE chat_sessions SET updated_at=? WHERE session_uuid=?",
|
| 150 |
+
(_now(), session_uuid),
|
| 151 |
+
)
|
| 152 |
+
|
| 153 |
+
|
| 154 |
+
def delete_db_session(session_uuid: str) -> None:
|
| 155 |
+
with get_conn() as conn:
|
| 156 |
+
conn.execute("DELETE FROM chat_sessions WHERE session_uuid=?", (session_uuid,))
|
| 157 |
+
|
| 158 |
+
|
| 159 |
+
def get_session_owner(session_uuid: str) -> Optional[int]:
|
| 160 |
+
"""Return user_id that owns this session, or None."""
|
| 161 |
+
with get_conn() as conn:
|
| 162 |
+
row = conn.execute(
|
| 163 |
+
"SELECT user_id FROM chat_sessions WHERE session_uuid=?", (session_uuid,)
|
| 164 |
+
).fetchone()
|
| 165 |
+
return row["user_id"] if row else None
|
| 166 |
+
|
| 167 |
+
|
| 168 |
+
# ββ Message CRUD ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 169 |
+
|
| 170 |
+
def save_message(session_uuid: str, role: str, content: str) -> int:
|
| 171 |
+
"""Append a message to a session. Returns new message id."""
|
| 172 |
+
now = _now()
|
| 173 |
+
with get_conn() as conn:
|
| 174 |
+
cur = conn.execute(
|
| 175 |
+
"INSERT INTO messages (session_uuid, role, content, created_at) VALUES (?,?,?,?)",
|
| 176 |
+
(session_uuid, role, content, now),
|
| 177 |
+
)
|
| 178 |
+
# touch session updated_at
|
| 179 |
+
conn.execute(
|
| 180 |
+
"UPDATE chat_sessions SET updated_at=? WHERE session_uuid=?",
|
| 181 |
+
(now, session_uuid),
|
| 182 |
+
)
|
| 183 |
+
return cur.lastrowid
|
| 184 |
+
|
| 185 |
+
|
| 186 |
+
def get_messages(session_uuid: str) -> List[Dict[str, Any]]:
|
| 187 |
+
"""Return all messages for a session in chronological order."""
|
| 188 |
+
with get_conn() as conn:
|
| 189 |
+
rows = conn.execute(
|
| 190 |
+
"SELECT role, content, created_at FROM messages "
|
| 191 |
+
"WHERE session_uuid=? ORDER BY id ASC",
|
| 192 |
+
(session_uuid,),
|
| 193 |
+
).fetchall()
|
| 194 |
+
return [dict(r) for r in rows]
|
| 195 |
+
|
| 196 |
+
|
| 197 |
+
def get_message_count(session_uuid: str) -> int:
|
| 198 |
+
with get_conn() as conn:
|
| 199 |
+
row = conn.execute(
|
| 200 |
+
"SELECT COUNT(*) as n FROM messages WHERE session_uuid=?", (session_uuid,)
|
| 201 |
+
).fetchone()
|
| 202 |
+
return row["n"] if row else 0
|
git_ms_code/api/main.py
ADDED
|
@@ -0,0 +1,1264 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
| 1 |
+
"""
|
| 2 |
+
NeuroCheck v9.0 β FastAPI Backend + Agentic AI
|
| 3 |
+
MS Symptom Classifier Β· spaCy NegEx Β· LangGraph Agent Β· RAG Knowledge Base
|
| 4 |
+
|
| 5 |
+
Tier 1/2 (SYMPTOM_PATTERNS) β 3.0 pts Γ severity multiplier
|
| 6 |
+
Tier 3 (LOW_PRIORITY_PATTERNS)β 1.0 pt fixed
|
| 7 |
+
|
| 8 |
+
Tiers: CRITICAL_EMERGENCY β 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("[NeuroCheck v9.0] spaCy model loaded: {}", model_path)
|
| 66 |
+
|
| 67 |
+
# Init persistent database
|
| 68 |
+
from api.database import init_db
|
| 69 |
+
init_db()
|
| 70 |
+
logger.info("[NeuroCheck] SQLite database initialized.")
|
| 71 |
+
|
| 72 |
+
# Build RAG knowledge base (runs once, persists to disk)
|
| 73 |
+
try:
|
| 74 |
+
from api.rag import build_knowledge_base
|
| 75 |
+
build_knowledge_base()
|
| 76 |
+
except Exception as e:
|
| 77 |
+
logger.warning("[RAG] Could not build knowledge base: {}", e)
|
| 78 |
+
|
| 79 |
+
yield
|
| 80 |
+
logger.info("[NeuroCheck v9.0] Shutting down.")
|
| 81 |
+
|
| 82 |
+
|
| 83 |
+
app = FastAPI(
|
| 84 |
+
title="NeuroCheck MS Classifier + Agentic AI",
|
| 85 |
+
version="9.0.0",
|
| 86 |
+
description=(
|
| 87 |
+
"MS Symptom Classifier + Agentic AI β 150-case validated. "
|
| 88 |
+
"Clinical decision support only. Not a diagnosis."
|
| 89 |
+
),
|
| 90 |
+
lifespan=lifespan,
|
| 91 |
+
)
|
| 92 |
+
|
| 93 |
+
app.state.limiter = limiter
|
| 94 |
+
app.add_exception_handler(RateLimitExceeded, _rate_limit_exceeded_handler)
|
| 95 |
+
|
| 96 |
+
app.add_middleware(
|
| 97 |
+
CORSMiddleware,
|
| 98 |
+
allow_origins=["*"],
|
| 99 |
+
allow_methods=["POST", "GET", "DELETE", "OPTIONS"],
|
| 100 |
+
allow_headers=["*"],
|
| 101 |
+
)
|
| 102 |
+
|
| 103 |
+
# ββ Auth router ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 104 |
+
from api.auth import router as auth_router
|
| 105 |
+
app.include_router(auth_router)
|
| 106 |
+
|
| 107 |
+
|
| 108 |
+
# ββ Pydantic schemas ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 109 |
+
class SymptomRequest(BaseModel):
|
| 110 |
+
text: str = Field(..., min_length=5, max_length=3000)
|
| 111 |
+
|
| 112 |
+
|
| 113 |
+
class ChatRequest(BaseModel):
|
| 114 |
+
message: str = Field(..., min_length=1, max_length=3000)
|
| 115 |
+
session_id: Optional[str] = None
|
| 116 |
+
user_id: Optional[int] = None # set server-side from JWT
|
| 117 |
+
|
| 118 |
+
|
| 119 |
+
class ChatResponse(BaseModel):
|
| 120 |
+
session_id: str
|
| 121 |
+
response: str
|
| 122 |
+
turn: int
|
| 123 |
+
|
| 124 |
+
|
| 125 |
+
class FeatureFound(BaseModel):
|
| 126 |
+
key: str
|
| 127 |
+
label: str
|
| 128 |
+
priority: str # "standard" | "low"
|
| 129 |
+
|
| 130 |
+
|
| 131 |
+
class ClassifyResponse(BaseModel):
|
| 132 |
+
tier: str
|
| 133 |
+
tier_label: str
|
| 134 |
+
tier_subtitle: str
|
| 135 |
+
action: str
|
| 136 |
+
workup: List[str]
|
| 137 |
+
features: List[FeatureFound]
|
| 138 |
+
temporal_notes: List[str]
|
| 139 |
+
disclaimer: str = (
|
| 140 |
+
"Clinical Decision Support Only β Not a diagnosis. "
|
| 141 |
+
"All outputs must be reviewed by a qualified clinician."
|
| 142 |
+
)
|
| 143 |
+
|
| 144 |
+
|
| 145 |
+
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 146 |
+
# EMERGENCY FLAGS (bypass scoring β fire immediately)
|
| 147 |
+
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 148 |
+
EMERGENCY_FLAGS: Dict[str, dict] = {
|
| 149 |
+
"stroke_suspected": {
|
| 150 |
+
"patterns": [r"(sudden|woke up).{0,20}(face droop|arm weak|slurred speech)"],
|
| 151 |
+
"label": "Possible Acute Stroke",
|
| 152 |
+
"action": "Call emergency services immediately (999 / 911). Do not wait β time is critical.",
|
| 153 |
+
},
|
| 154 |
+
"meningitis_suspected": {
|
| 155 |
+
"patterns": [
|
| 156 |
+
r"(fever|high temp).{0,30}(neck).{0,20}(stiff|rigid|pain)",
|
| 157 |
+
r"photophobia.{0,20}fever",
|
| 158 |
+
],
|
| 159 |
+
"label": "Possible Meningitis / Encephalitis",
|
| 160 |
+
"action": "Seek emergency care immediately. Meningitis is life-threatening.",
|
| 161 |
+
},
|
| 162 |
+
"hemorrhage_suspected": {
|
| 163 |
+
"patterns": [r"(sudden|worst).{0,20}(headache).{0,20}(life|ever|thunderclap)"],
|
| 164 |
+
"label": "Possible Subarachnoid Haemorrhage",
|
| 165 |
+
"action": "Call emergency services immediately. Thunderclap headache requires emergency evaluation.",
|
| 166 |
+
},
|
| 167 |
+
"gbs_suspected": {
|
| 168 |
+
"patterns": [
|
| 169 |
+
r"(both legs|feet).{0,30}(weak|paralyzed).{0,30}(moving up|spreading up|hands)",
|
| 170 |
+
r"ascending paralysis",
|
| 171 |
+
r"weakness.{0,30}(spreading|moving up).{0,20}(arm|hand)",
|
| 172 |
+
],
|
| 173 |
+
"label": "Possible Guillain-BarrΓ© Syndrome",
|
| 174 |
+
"action": "Seek emergency care immediately. Ascending weakness requires urgent neurological assessment.",
|
| 175 |
+
},
|
| 176 |
+
}
|
| 177 |
+
|
| 178 |
+
|
| 179 |
+
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 180 |
+
# ANCHOR FEATURES
|
| 181 |
+
# Any anchor hit β₯ 3 pts β HIGH regardless of total score
|
| 182 |
+
# Updated v8.1: added paroxysmal_ms, tonic_spasms_ms, tumefactive_ms,
|
| 183 |
+
# lhermittes_variant, sensory_idioms, limb_numbness
|
| 184 |
+
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 185 |
+
ANCHOR_FEATURES = {
|
| 186 |
+
# ββ Visual / optic ββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 187 |
+
"lhermittes_sign",
|
| 188 |
+
"lhermittes_variant",
|
| 189 |
+
"uhthoff_phenomenon",
|
| 190 |
+
"pain_on_eye_movement",
|
| 191 |
+
"monocular_vision_loss",
|
| 192 |
+
"ino_features",
|
| 193 |
+
"ms_hug",
|
| 194 |
+
"oscillopsia",
|
| 195 |
+
"bilateral_vision_loss",
|
| 196 |
+
"diplopia",
|
| 197 |
+
# ββ Brainstem / TN ββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 198 |
+
"paroxysmal_tn_young",
|
| 199 |
+
"area_postrema",
|
| 200 |
+
# ββ Spinal / sensory ββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 201 |
+
"sensory_idioms",
|
| 202 |
+
"limb_numbness",
|
| 203 |
+
# ββ Ocular / IIH overlap ββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 204 |
+
"optic_neuritis_idioms",
|
| 205 |
+
"obesity_disc_flag",
|
| 206 |
+
# ββ History / DIT βββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 207 |
+
"prior_cis_episode",
|
| 208 |
+
# ββ Vestibular ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 209 |
+
"vertigo_ms",
|
| 210 |
+
# ββ Paroxysmal / rare (v8.1) ββββββββββββββββββββββββββββββββββββββββββββββ
|
| 211 |
+
"paroxysmal_ms",
|
| 212 |
+
"tonic_spasms_ms",
|
| 213 |
+
"tumefactive_ms",
|
| 214 |
+
}
|
| 215 |
+
|
| 216 |
+
|
| 217 |
+
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 218 |
+
# TIER 1 + 2: SYMPTOM PATTERNS (3.0 pts each Γ severity multiplier)
|
| 219 |
+
# v8.1: 17 new categories added from 150-case internet testing
|
| 220 |
+
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 221 |
+
SYMPTOM_PATTERNS: Dict[str, List[tuple]] = {
|
| 222 |
+
|
| 223 |
+
# ββ ANCHOR: Lhermitte's sign ββββββββββββββββββββββββββββββββββββββββββββββ
|
| 224 |
+
"lhermittes_sign": [
|
| 225 |
+
(r"electric.{0,20}(shock|jolt|current|zap).{0,30}spine", "Lhermitte's sign β electric shock down spine"),
|
| 226 |
+
(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"),
|
| 227 |
+
(r"(sharp|sudden).{0,20}(electric|zap|jolt|current).{0,20}(run|shoot|travel).{0,30}(spine|leg|back)", "Lhermitte-type electric sensation"),
|
| 228 |
+
(r"\blhermitte.{0,20}(sign|phenomenon|symptom)\b", "Lhermitte's sign (clinical)"),
|
| 229 |
+
],
|
| 230 |
+
|
| 231 |
+
# ββ ANCHOR: Lhermitte variant (cough/sneeze trigger) β v8.1 βββββββββββββ
|
| 232 |
+
"lhermittes_variant": [
|
| 233 |
+
(r"(shock|jolt|electric).{0,20}(cough|coughing|sneeze|sneezing|limb movement)", "Lhermitte variant β cough/sneeze trigger"),
|
| 234 |
+
(r"\blhermitte.{0,20}(cough|movement|limb|trigger|variant)\b", "Lhermitte variant trigger"),
|
| 235 |
+
],
|
| 236 |
+
|
| 237 |
+
# ββ ANCHOR: Uhthoff's phenomenon βββββββββββββββββββββββββββββββββββββββββ
|
| 238 |
+
# v8.1: must have visual OR gait/balance component to distinguish from
|
| 239 |
+
# generic heat sensitivity (LP category)
|
| 240 |
+
"uhthoff_phenomenon": [
|
| 241 |
+
(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"),
|
| 242 |
+
(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"),
|
| 243 |
+
(r"(shimmer|shimmers|obscur).{0,40}(hot shower|warm shower|shower|bath|exercise|heat|fever)", "Uhthoff's β shimmer in heat"),
|
| 244 |
+
(r"worsening.{0,20}(vision|balance|weakness|gait).{0,30}(exercise|warm|heat|hot|fever)", "Uhthoff's β visual/gait worsening in heat"),
|
| 245 |
+
(r"\buhthoff.{0,20}(phenomenon|sign|syndrome)\b", "Uhthoff's phenomenon (clinical)"),
|
| 246 |
+
(r"heat intolerance.{0,40}(gait|walk|stumbl|fall|vision)", "Uhthoff's β heat intolerance with visual/gait"),
|
| 247 |
+
],
|
| 248 |
+
|
| 249 |
+
# ββ ANCHOR: Pain on eye movement βββββββββββββββββββββββββββββββββββββββββ
|
| 250 |
+
"pain_on_eye_movement": [
|
| 251 |
+
(r"pain.{0,30}(mov|look).{0,15}eye", "Pain on eye movement"),
|
| 252 |
+
(r"(move|moving|turning|side.to.side).{0,20}(eye|eyes).{0,30}(pain|hurt|ache|sore|throb)", "Moving eyes causes pain"),
|
| 253 |
+
(r"(exacerbated|worse|painful).{0,30}(looking up|side.to.side|look.{0,5}side)", "Pain exacerbated by eye movement"),
|
| 254 |
+
(r"pain.{0,20}(eye.{0,10}movement|moving the eye)", "Pain on eye movement"),
|
| 255 |
+
(r"retrobulbar.{0,15}pain", "Retrobulbar pain (ON)"),
|
| 256 |
+
(r"(discomfort|pain).{0,20}(left eye|right eye|eye).{0,20}(worse|made worse|exacerbated)", "Discomfort worse with eye movements"),
|
| 257 |
+
],
|
| 258 |
+
|
| 259 |
+
# ββ ANCHOR: Monocular vision loss βββββββββββββββββββββββββββββββββββββββββ
|
| 260 |
+
"monocular_vision_loss": [
|
| 261 |
+
(r"(one|left|right|l-eye|r-eye) eye.{0,30}(blur|vision|dim|loss|blind)", "Monocular vision loss"),
|
| 262 |
+
(r"blurring in one eye", "Blurring in one eye"),
|
| 263 |
+
(r"(left|right).{0,5}eye.{0,20}(dimm|blur|dull|fad|fog|dim|vision|loss)", "One eye dimming / blurring"),
|
| 264 |
+
(r"vision.{0,20}(painful|pain).{0,20}(monocular|one eye)", "Painful monocular vision loss"),
|
| 265 |
+
(r"(monocular).{0,20}(vision loss|blind|dim|blur|visual|impairment)", "Monocular vision loss (clinical)"),
|
| 266 |
+
(r"unilateral.{0,20}(visual|vision).{0,20}(impairment|loss|deficit|blurr|acuity)", "Unilateral visual impairment"),
|
| 267 |
+
(r"(optic neuritis|optic nerve).{0,30}(vision|visual|acuity|pain)", "Optic neuritis (clinical)"),
|
| 268 |
+
],
|
| 269 |
+
|
| 270 |
+
# ββ Dyschromatopsia βββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 271 |
+
"dyschromatopsia": [
|
| 272 |
+
(r"(red|colour|color).{0,20}(fad|wash|dim|dull|less|pale|grey|gray|wrong|off|not bright|desatur|less vivid)", "Dyschromatopsia β colour fading"),
|
| 273 |
+
(r"(grey|gray|greyed|greyed out|less vibrant).{0,20}(eye|vision|right|left)", "Vision greyed out / less vibrant"),
|
| 274 |
+
(r"red.green color loss", "Red-green colour loss"),
|
| 275 |
+
(r"(fading|faded).{0,15}(color|colour)", "Faded colours"),
|
| 276 |
+
(r"colors (look|appear|seem).{0,20}(dull|washed|faded|wrong|off|different)", "Colours appear wrong"),
|
| 277 |
+
],
|
| 278 |
+
|
| 279 |
+
# ββ ANCHOR: INO / eye movement disorder ββββββββββββββββββββββββββββββββββ
|
| 280 |
+
# v8.1: word-boundary fix prevents 'ino' matching in 'coordination'
|
| 281 |
+
# v8.1: added lateral gaze palsy / sixth nerve palsy patterns
|
| 282 |
+
"ino_features": [
|
| 283 |
+
(r"(eye|eyes).{0,20}(jiggle|wobble|bounce|shake|jump).{0,20}(look|gaze|side)", "INO β eyes jiggle on gaze"),
|
| 284 |
+
(r"\b(adduction lag|internuclear ophthalmoplegia|ophthalmoplegia)\b", "Internuclear ophthalmoplegia"),
|
| 285 |
+
(r"cannot.{0,20}move.{0,20}(eye|eyes).{0,20}(nose|toward|nasal)", "INO β eye cannot adduct"),
|
| 286 |
+
(r"(eye|eyes).{0,10}(crooked|jiggly|nystagmus|wiggling|oscillating)", "Jiggly / crooked eyes (INO/nystagmus)"),
|
| 287 |
+
(r"(lateral gaze palsy|sixth nerve palsy|6th nerve palsy)", "Sixth nerve / lateral gaze palsy"),
|
| 288 |
+
(r"(eye|eyes).{0,20}(cannot|can.{0,5}not).{0,20}(move outward|abduct|lateral)", "Eye cannot abduct"),
|
| 289 |
+
(r"abduction (deficit|palsy|weakness)", "Abduction deficit (6th nerve)"),
|
| 290 |
+
],
|
| 291 |
+
|
| 292 |
+
# ββ ANCHOR: Oscillopsia βββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 293 |
+
"oscillopsia": [
|
| 294 |
+
(r"(room|world|everything|objects|things).{0,30}(wiggl|wobbl|bounc|shak|oscillat|vibrat|jump)", "Oscillopsia β room appears to wiggle"),
|
| 295 |
+
(r"world.{0,20}(split|splits)", "World splits on gaze"),
|
| 296 |
+
(r"object.{0,15}jump.{0,15}(focus|see|gaze)", "Objects jump when focusing"),
|
| 297 |
+
(r"vision.{0,20}(jump|jumpy|jiggly|shimmer)", "Jumpy / shimmery vision"),
|
| 298 |
+
(r"\b(opsoclonus|oscillopsia)\b", "Oscillopsia / opsoclonus (clinical)"),
|
| 299 |
+
],
|
| 300 |
+
|
| 301 |
+
# ββ ANCHOR: MS Hug ββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 302 |
+
"ms_hug": [
|
| 303 |
+
(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"),
|
| 304 |
+
(r"(banding|girdle).{0,20}(sensation|feeling|pain).{0,20}(chest|abdomen|trunk|waist)", "Girdle / banding sensation"),
|
| 305 |
+
],
|
| 306 |
+
|
| 307 |
+
# ββ ANCHOR: Bilateral vision loss (NMOSD) ββββββββββββββββββββββββββββββββ
|
| 308 |
+
"bilateral_vision_loss": [
|
| 309 |
+
(r"(bilateral|both eyes).{0,30}(vision loss|blind|blur|dim|black|loss of sight)", "Bilateral vision loss"),
|
| 310 |
+
(r"(vision loss|blind|blur|dim|black|loss of sight).{0,30}(bilateral|both eyes)", "Bilateral vision loss"),
|
| 311 |
+
(r"(nlp|no light perception)", "No light perception (NLP)"),
|
| 312 |
+
(r"(bottom half|top half|altitudinal).{0,20}(gone|lost|blind|vision)", "Altitudinal vision loss"),
|
| 313 |
+
(r"both eyes.{0,20}(painful|pain)", "Both eyes painful (ADEM / NMO flag)"),
|
| 314 |
+
(r"(simultaneous).{0,30}vision loss", "Simultaneous bilateral vision loss"),
|
| 315 |
+
],
|
| 316 |
+
|
| 317 |
+
# Post-viral vision (ADEM flag)
|
| 318 |
+
"post_viral_vision": [
|
| 319 |
+
(r"(flu|illness|viral|flu-like).{0,30}(both eyes|bilateral|eye|vision)", "Post-viral vision loss (ADEM flag)"),
|
| 320 |
+
(r"(flu.like illness|viral illness).{0,40}(eye|vision|painful)", "Post-viral eye involvement"),
|
| 321 |
+
],
|
| 322 |
+
|
| 323 |
+
# ββ ANCHOR: Diplopia ββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 324 |
+
"diplopia": [
|
| 325 |
+
(r"double vision", "Double vision (diplopia)"),
|
| 326 |
+
(r"seeing double", "Seeing double"),
|
| 327 |
+
(r"diplopia", "Diplopia (clinical)"),
|
| 328 |
+
(r"(seeing|see).{0,10}two", "Seeing two images"),
|
| 329 |
+
(r"world.{0,20}split.{0,20}(left|right|look)", "World splits on gaze"),
|
| 330 |
+
(r"(eyes.{0,20}crooked|jiggly eyes)", "Crooked / jiggly eyes"),
|
| 331 |
+
(r"(eyes? pointing|eye pointing).{0,20}(wrong direction|wrong way|deviation)", "Eye pointing wrong direction"),
|
| 332 |
+
(r"binocular.{0,15}(diplopia|vision)", "Binocular diplopia"),
|
| 333 |
+
],
|
| 334 |
+
|
| 335 |
+
# ββ ANCHOR: Paroxysmal TN / facial pain ββββββββββββββββββββββββββββββββββ
|
| 336 |
+
"paroxysmal_tn_young": [
|
| 337 |
+
(r"electric shocks? in (jaw|face)", "Electric shock in jaw / face (TN)"),
|
| 338 |
+
(r"severe face pain", "Severe face pain (TN)"),
|
| 339 |
+
(r"trigeminal neuralgia", "Trigeminal neuralgia"),
|
| 340 |
+
(r"facial shock", "Facial shock"),
|
| 341 |
+
(r"(facial|face).{0,20}(numb|numbness|pain.{0,15}young|electric|stab|shock)", "Facial numbness / pain"),
|
| 342 |
+
(r"(face|jaw).{0,15}pain.{0,20}(cold wind|trigger|touch|brush)", "Trigger-evoked face pain (TN)"),
|
| 343 |
+
(r"(sharp facial|facial).{0,10}(pain|shock)", "Sharp facial pain"),
|
| 344 |
+
(r"(v1|v2|trigeminal).{0,20}(pain|numb|symptom)", "V1/V2 trigeminal pain"),
|
| 345 |
+
(r"on and off.{0,20}facial pain", "Paroxysmal facial pain"),
|
| 346 |
+
(r"(severe facial|severe face).{0,10}(pain|ache)", "Severe facial pain"),
|
| 347 |
+
(r"(face|facial).{0,15}(weakness|numb|numbness)", "Facial weakness / numbness"),
|
| 348 |
+
(r"(face|jaw|cheek).{0,20}pain.{0,30}(light touch|touch|trigger|cold|wind|brush)", "Light-touch triggered facial pain (TN)"),
|
| 349 |
+
(r"stabbing.{0,20}(face|jaw|cheek|facial|character)", "Stabbing facial pain"),
|
| 350 |
+
],
|
| 351 |
+
|
| 352 |
+
# ββ ANCHOR: Area postrema (NMO) βββββββββββββββββββββββββββββββββββββββββββ
|
| 353 |
+
"area_postrema": [
|
| 354 |
+
(r"intractable hiccups", "Intractable hiccups (area postrema)"),
|
| 355 |
+
(r"uncontrollable vomiting", "Uncontrollable vomiting"),
|
| 356 |
+
(r"hiccups and vomiting", "Hiccups and vomiting (NMO sign)"),
|
| 357 |
+
(r"nausea and vomiting", "Nausea and vomiting"),
|
| 358 |
+
(r"\barea postrema\b", "Area postrema syndrome (NMO)"),
|
| 359 |
+
],
|
| 360 |
+
|
| 361 |
+
# ββ ANCHOR: Vertigo / vestibular MS ββββββββββββββββββββββββββββββββββββββ
|
| 362 |
+
"vertigo_ms": [
|
| 363 |
+
(r"(vertigo|dizziness|dizzy).{0,30}(fall|balance|walk|gait)", "Vertigo with falls / gait problems"),
|
| 364 |
+
(r"(constant|persistent|abrupt|sudden).{0,15}(vertigo|dizziness)", "Constant or sudden-onset vertigo"),
|
| 365 |
+
(r"(increasingly frequent falls|progressively.{0,15}fall|frequent falls)", "Increasingly frequent falls"),
|
| 366 |
+
(r"(lost all equilibrium|loss of equilibrium|lost equilibrium)", "Loss of equilibrium"),
|
| 367 |
+
(r"(lightheadedness|lightheaded|light.headed).{0,30}(dizziness|balance|standing)", "Lightheadedness with balance difficulty"),
|
| 368 |
+
],
|
| 369 |
+
|
| 370 |
+
# ββ ANCHOR: Optic neuritis idioms βββββββββββββββββββββββββββββββββββββββββ
|
| 371 |
+
"optic_neuritis_idioms": [
|
| 372 |
+
(r"(dirty water|smudge|foggy|foggy vision|fog).{0,20}(eye|vision|see)", "ON β foggy / smudged vision"),
|
| 373 |
+
(r"(looking through|vision like).{0,20}(dirty|foggy|cloudy|smeared|smudge|mist|haze)", "ON β dirty / foggy vision"),
|
| 374 |
+
(r"(scotoma|central blur|central blurr|central loss|central vision)", "Scotoma / central vision loss"),
|
| 375 |
+
(r"(eye soreness|eye sore|sore eye|soreness behind the eye|eye ache|ache behind the eye)", "Eye soreness (ON)"),
|
| 376 |
+
(r"pulling sensation.{0,20}(behind|eye)", "Pulling sensation behind the eye"),
|
| 377 |
+
(r"(vision|visual).{0,20}(deficit|dimming)", "Visual deficit / dimming"),
|
| 378 |
+
(r"(blurring|blur).{0,20}one eye", "Blurring in one eye (ON)"),
|
| 379 |
+
(r"transient obscur", "Transient obscurations"),
|
| 380 |
+
(r"(washed out|less vibrant|world.{0,10}dim)", "Washed-out / dim vision"),
|
| 381 |
+
(r"(optic neuritis|optic nerve)", "Optic neuritis (clinical)"),
|
| 382 |
+
(r"(visual acuity|visual impairment|visual field).{0,30}(decreas|loss|reduced|impair|defect)", "Visual acuity / field loss"),
|
| 383 |
+
(r"(blurry vision|blurred vision|blurring of vision)", "Blurred vision"),
|
| 384 |
+
(r"\b(afferent pupillary defect|relative afferent)\b", "Afferent pupillary defect (RAPD)"),
|
| 385 |
+
],
|
| 386 |
+
|
| 387 |
+
# ββ ANCHOR: IIH / obesity / disc swelling ββββββββββββββββββββββββββββββββ
|
| 388 |
+
"obesity_disc_flag": [
|
| 389 |
+
(r"(disc swelling|papilledema|disc edema|swelling.{0,20}eye|swelling.{0,20}optic)", "Disc swelling (papilledema)"),
|
| 390 |
+
(r"(bilateral disc|disc.{0,10}swelling)", "Bilateral disc swelling"),
|
| 391 |
+
(r"(eyes.{0,20}abnormal|abnormal.{0,20}eye)", "Abnormal eye exam finding"),
|
| 392 |
+
(r"(heavy legs|heavy leg|legs feel heavy|leg heaviness).{0,30}(walk|walking|clinic|stand)", "Heavy legs (spinal cord flag)"),
|
| 393 |
+
(r"(\d{3}\s*kg|obese|high bmi|overweight|obesity)", "Obesity marker (IIH / MS overlap)"),
|
| 394 |
+
],
|
| 395 |
+
|
| 396 |
+
# ββ ANCHOR: Prior CIS / DIT βββββββββββββββββββββββββββββββββββββββββββββββ
|
| 397 |
+
"prior_cis_episode": [
|
| 398 |
+
(r"(years?|months?) ago.{0,40}(numb|weak|vision|tingling|balance).{0,60}(better|resolved|went away|recovered)", "Prior resolved neurological episode"),
|
| 399 |
+
(r"(episode|attack|event).{0,20}(numb|weakness|vision|tingling).{0,20}(resolved|recovered|cleared)", "Prior episode resolved"),
|
| 400 |
+
(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"),
|
| 401 |
+
(r"history of optic neuritis", "History of optic neuritis (DIT)"),
|
| 402 |
+
(r"(previous|prior|history of).{0,30}(episode|attack|relapse|event|numbness|tingling|weakness|vision)", "Prior neurological episode"),
|
| 403 |
+
(r"(spontaneously resolved|resolved spontaneously|went away on its own|resolved on its own)", "Spontaneous resolution (CIS pattern)"),
|
| 404 |
+
(r"clinically isolated syndrome|first (episode|attack|event|relapse)", "Clinically isolated syndrome"),
|
| 405 |
+
(r"(tingling|numbness|numb).{0,40}(last monsoon|last year|years? ago|months? ago)", "Prior monsoon / seasonal episode (DIT)"),
|
| 406 |
+
(r"monsoon.{0,40}(resolved|better|went away|numb|tingle)", "Monsoon-triggered episode resolved"),
|
| 407 |
+
(r"(episode|attack).{0,50}(numb|weak|tingling|vision).{0,50}(resolved|went away|got better|cleared)", "Prior episode resolved (flexible)"),
|
| 408 |
+
],
|
| 409 |
+
|
| 410 |
+
# ββ Standard: Cerebellar ataxia βββββββββββββββββββββββββββββββββββββββββββ
|
| 411 |
+
"cerebellar_ataxia": [
|
| 412 |
+
(r"(clumsiness|clumsy|dropping keys|drops things|cerebellar)", "Cerebellar clumsiness"),
|
| 413 |
+
(r"(steady|steady myself|off balance|balance problems|poor balance)", "Balance problems (cerebellar)"),
|
| 414 |
+
(r"(seasick|feels seasick|nausea.{0,20}walk|dizzy.{0,20}walk)", "Seasick feeling (cerebellar)"),
|
| 415 |
+
(r"swallowing difficulty", "Swallowing difficulty (brainstem)"),
|
| 416 |
+
(r"\b(dysdiadochokinesia|ataxia|coordination deficit)\b", "Ataxia / coordination deficit"),
|
| 417 |
+
(r"(impaired balance|loss of balance|balance impair|vestibular)", "Impaired balance"),
|
| 418 |
+
(r"(equilibrium|lost.{0,10}equilibrium|lost.{0,10}balance)", "Loss of equilibrium"),
|
| 419 |
+
(r"(heel.to.shin|finger.to.nose|tandem gait)", "Cerebellar examination findings"),
|
| 420 |
+
],
|
| 421 |
+
|
| 422 |
+
# ββ Standard: Motor weakness / grip ββββββββββββββββββββββββββββββββββββββ
|
| 423 |
+
"motor_weakness_grip": [
|
| 424 |
+
(r"(weak|lose|loss of|give out|clumsy).{0,20}(grip|grasp|hand|power|oomph|button|zip)", "Weak grip / clumsy hands"),
|
| 425 |
+
(r"(drop|dropping).{0,20}(cup|keys|things|mug|bottle)", "Dropping objects"),
|
| 426 |
+
(r"(typing errors|typos|handwriting|script)|(buttoning trouble|loss of oomph)", "Fine motor deficit"),
|
| 427 |
+
(r"(hand|arm|upper extremity|upper limb).{0,20}(weakness|weak|paresis|paresthesia)", "Upper extremity weakness"),
|
| 428 |
+
(r"(decreased|reduced).{0,20}(dexterity|grip|coordination|finger)", "Decreased dexterity"),
|
| 429 |
+
(r"\b(tremor|tremors|intention tremor|action tremor)\b", "Tremor"),
|
| 430 |
+
(r"\b(hemiparesis|paraparesis|monoparesis|quadriparesis)\b", "Paresis / paralysis"),
|
| 431 |
+
(r"(hyperreflexia|babinski.{0,10}(sign|positive)|extensor plantar)", "Upper motor neuron signs"),
|
| 432 |
+
(r"left lower limb weakness|right lower limb weakness|lower limb weakness", "Lower limb weakness"),
|
| 433 |
+
],
|
| 434 |
+
|
| 435 |
+
# ββ Standard: Gait ataxia βββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 436 |
+
"gait_ataxia": [
|
| 437 |
+
(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"),
|
| 438 |
+
(r"(occasional falls|fall|tripping|trips).{0,20}(walk|balance|gait)", "Falls (gait / balance)"),
|
| 439 |
+
(r"(stumbling gait|stumbl.{0,10}gait|stumbl.{0,10}walk)", "Stumbling gait"),
|
| 440 |
+
(r"(gait disturbance|gait disorder|gait impairment|difficulty.{0,10}walk|difficulty.{0,10}ambul)", "Gait disturbance (clinical)"),
|
| 441 |
+
(r"(tendency to fall|multiple falls|several falls|bad falls|frequent falls)", "Tendency to fall"),
|
| 442 |
+
(r"(ambulation|ambulating|ambulatory).{0,20}(difficult|impaired|problem)", "Ambulation difficulty"),
|
| 443 |
+
(r"(increasingly frequent falls|progressively.{0,15}fall)", "Increasingly frequent falls"),
|
| 444 |
+
(r"(ataxic gait|ataxic walking)", "Ataxic gait"),
|
| 445 |
+
],
|
| 446 |
+
|
| 447 |
+
# ββ Standard: Spasticity βββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 448 |
+
"spasticity": [
|
| 449 |
+
(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"),
|
| 450 |
+
(r"(locked muscles|stiff fingers|stiff knee)", "Locked / stiff muscles"),
|
| 451 |
+
(r"\b(spasticity|hyperreflexia|hyperreflexic|extensor plantar|babinski|clonus)\b", "Spasticity (clinical)"),
|
| 452 |
+
(r"(increased tone|increased reflexes|brisk reflexes)", "Increased tone / reflexes"),
|
| 453 |
+
(r"spastic (quadriparesis|paraparesis|hemiparesis)", "Spastic paresis"),
|
| 454 |
+
(r"(muscle spasm|muscle cramp).{0,20}(ms|neurological|multiple sclerosis)", "MS-related muscle spasm"),
|
| 455 |
+
],
|
| 456 |
+
|
| 457 |
+
# ββ Standard: Tremor (v8.1 β separated from motor_weakness_grip) ββββββββ
|
| 458 |
+
"tremor_standard": [
|
| 459 |
+
(r"(uncontrollable shaking|uncontrollable trembling|tremor).{0,20}(arm|leg|head|hand|body)", "Uncontrollable tremor"),
|
| 460 |
+
(r"\b(intention tremor|action tremor|cerebellar tremor)\b", "Intention / cerebellar tremor"),
|
| 461 |
+
],
|
| 462 |
+
|
| 463 |
+
# ββ Standard: Foot drop βββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 464 |
+
"foot_drop": [
|
| 465 |
+
(r"(foot|toe|toes|feet).{0,20}(drag|dragging|drop|dropping|scuff|scrape)", "Foot drop"),
|
| 466 |
+
(r"toe dragging", "Toe dragging"),
|
| 467 |
+
(r"(lift|lifting).{0,15}(knee|foot).{0,20}(clear|foot|toe|floor|step)", "Lifting knee to clear foot (foot drop)"),
|
| 468 |
+
(r"foot drop|drop foot", "Foot drop (clinical)"),
|
| 469 |
+
],
|
| 470 |
+
|
| 471 |
+
# ββ ANCHOR: Limb numbness / paresthesia βββββοΏ½οΏ½βββββββββββββββββββββββββββββ
|
| 472 |
+
"limb_numbness": [
|
| 473 |
+
(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"),
|
| 474 |
+
(r"(numbness|numb|tingling).{0,30}(fingertip|finger|hand|arm|leg|ankle)", "Fingertip / limb numbness"),
|
| 475 |
+
(r"(tingling in|numbness in|numb in).{0,20}(extremities|arm|leg|hand|foot|body|side|face|ankle)", "Tingling / numbness in extremities"),
|
| 476 |
+
(r"\b(hemibody|hemi.body|hemisensory)\b.{0,30}(paresthesia|numb|weak|sensory)", "Hemibody paresthesia (MS relapse)"),
|
| 477 |
+
(r"\b(paresthesia|paresthesias|dysesthesia)\b.{0,20}(sensory|numb|tingle|sensation|deficit)", "Clinical paresthesia"),
|
| 478 |
+
(r"(altered sensation|sensory deficit|sensory loss|hemisensory)", "Sensory deficit (clinical)"),
|
| 479 |
+
(r"(paresthesia|tingling|numbness).{0,30}(ascend|ascending|spread|spreading).{0,30}(leg|limb|trunk|umbilicus|body)", "Ascending paresthesia (myelitis)"),
|
| 480 |
+
(r"(right.sided|left.sided).{0,20}(weakness|numbness|numb|paresthesia)", "Hemisensory / hemibody symptoms"),
|
| 481 |
+
(r"glove.{0,10}stocking.{0,10}(pattern|numbness|paresthesia)", "Glove-and-stocking pattern"),
|
| 482 |
+
(r"(radiation|radiating).{0,20}(numb|numbness|tingling|pain).{0,20}(ankle|leg|arm|foot|thigh|shin)", "Radiating numbness / tingling"),
|
| 483 |
+
],
|
| 484 |
+
|
| 485 |
+
# ββ ANCHOR: Sensory idioms / dysesthesia βββββββββββββββββββββββββββββββββ
|
| 486 |
+
"sensory_idioms": [
|
| 487 |
+
(r"(cold|water|ice|frozen).{0,20}(trickle|trickling|running|poured|pack)", "Cold water / ice sensation"),
|
| 488 |
+
(r"(twice its size|swollen|puffy).{0,30}(looks normal|looks fine|perfectly normal)", "Phantom swelling (dysesthesia)"),
|
| 489 |
+
(r"(hand|arm|leg|foot).{0,20}feels.{0,20}(twice|swollen|puffy|bigger).{0,30}(normal|fine)", "Phantom swelling"),
|
| 490 |
+
(r"(dead|wooden|block|dead feeling|completely dead).{0,20}(arm|leg|patch|skin|left arm|right arm)", "Dead / wooden sensation"),
|
| 491 |
+
(r"(completely dead|dead feeling|deadness).{0,20}(arm|leg|hand|foot)", "Dead limb sensation"),
|
| 492 |
+
(r"(left arm|right arm|arm|leg).{0,30}(completely dead|dead|wooden|numb)", "Arm / leg feels dead"),
|
| 493 |
+
(r"(arm|leg).{0,20}(feels|feel|is|are).{0,10}(completely dead|dead|wooden)", "Limb feels dead"),
|
| 494 |
+
(r"(hot coals|stinging needles|bee sting|stinging).{0,20}(feet|foot|sole|face|skin|soles)", "Hot coals / stinging sensation"),
|
| 495 |
+
(r"(walking on hot coals|feel like hot coals|feels like hot coals)", "Walking on hot coals"),
|
| 496 |
+
(r"soles.{0,30}(hot coals|needles|stinging|burning|fire)", "Burning soles"),
|
| 497 |
+
(r"(sandpaper).{0,20}(skin|rubbing|touch|wound|on a wound)", "Allodynia β sandpaper sensation"),
|
| 498 |
+
(r"(light touch|cotton|shirt).{0,30}(sandpaper|stinging|hurts|pain|painful|wound)", "Allodynia β light touch painful"),
|
| 499 |
+
(r"(cell phone|vibration).{0,20}(hip|bone|deep)", "Internal vibration (pallanaesthesia)"),
|
| 500 |
+
(r"(gloves|socks).{0,30}(muffled|numb|thick)", "Glove-and-stocking numbness"),
|
| 501 |
+
(r"(sloshy|wet).{0,20}(shoes|feet)", "Sloshy / wet sensation"),
|
| 502 |
+
(r"(ants|ant|insect|bug).{0,20}(crawl|crawling|creeping).{0,20}(scalp|neck|skin|face|arm|leg)", "Formication (ants crawling)"),
|
| 503 |
+
(r"(palm.sized|patch).{0,40}(wooden|numb)", "Specific numb patch"),
|
| 504 |
+
(r"felt.{0,10}(wooden|completely numb)", "Felt wooden / numb"),
|
| 505 |
+
],
|
| 506 |
+
|
| 507 |
+
# ββ Standard: Proprioception loss βββββββββββββββββββββββββββββββββββββββββ
|
| 508 |
+
"proprioception_loss": [
|
| 509 |
+
(r"(lose|loses|lost|where).{0,20}(feet|track of|dark|look down)", "Proprioception loss"),
|
| 510 |
+
(r"(walk.{0,15}dark|dark.{0,15}walk).{0,30}(look down|feet|where)", "Proprioception loss in dark"),
|
| 511 |
+
(r"vibratory sense.{0,20}(loss|impaired|decreased|reduced)", "Vibratory sense loss"),
|
| 512 |
+
(r"(position sense|proprioception).{0,20}(impaired|loss|reduced)", "Proprioception impaired (clinical)"),
|
| 513 |
+
],
|
| 514 |
+
|
| 515 |
+
# ββ Standard: Autonomic / bladder / bowel ββββββββββββββββββββββββββββββββ
|
| 516 |
+
"autonomic_ms": [
|
| 517 |
+
(r"(urinary urgency|bladder urgency|urge to urinate|urgency urination|frequency urination)", "Urinary urgency"),
|
| 518 |
+
(r"(bowel|bladder).{0,20}(problem|control|urgency|incontinence|dysfunction)", "Bladder / bowel dysfunction"),
|
| 519 |
+
(r"(urinary|urinating).{0,20}(problem|urgency|frequent|difficult)", "Urinary dysfunction"),
|
| 520 |
+
(r"(incontinence|incontinent|nocturia|multiple voids|voiding)", "Incontinence / nocturia"),
|
| 521 |
+
(r"(incomplete bladder|bladder emptying|urinary bladder)", "Incomplete bladder emptying"),
|
| 522 |
+
(r"\b(neurogenic bladder|neurogenic bowel)\b", "Neurogenic bladder / bowel"),
|
| 523 |
+
(r"(constipation|bowel.{0,20}(control|incontinence|problem)).{0,20}(ms|neurological|multiple sclerosis)", "MS-related bowel dysfunction"),
|
| 524 |
+
(r"(fecal incontinence|bowel incontinence|bowel leakage)", "Fecal / bowel incontinence"),
|
| 525 |
+
],
|
| 526 |
+
|
| 527 |
+
# ββ Standard: Visual mimic flags βββββββββββββββββββββββββββββββββββββββββ
|
| 528 |
+
"visual_mimic_flags": [
|
| 529 |
+
(r"(floater|floaters|dark spot|black spot|spot.{0,15}moves|moving spot)", "Floaters / dark spot (retinal flag)"),
|
| 530 |
+
(r"(red.{0,10}eye|red.{0,10}painful eye|painful.{0,10}red eye)", "Red painful eye (mimic flag)"),
|
| 531 |
+
(r"(flickering lights|flicker.{0,15}light|scintillating).{0,30}(20 min|min|lasts|aura)", "Flickering lights β migraine aura flag"),
|
| 532 |
+
(r"(chronic|progressive).{0,20}(vision loss|visual loss).{0,30}(1 year|year|months?)", "Chronic progressive vision loss β tumour flag"),
|
| 533 |
+
],
|
| 534 |
+
|
| 535 |
+
# ββ Standard: Cognitive / brain fog ββββββββββββββββββββββββββββββββββββββ
|
| 536 |
+
"cognitive_ms": [
|
| 537 |
+
(r"(brain|mind).{0,15}(fog|cloudy|slow|blank|mush)", "Brain fog"),
|
| 538 |
+
(r"(memory|remember).{0,20}(loss|lapse|bad|poor|failing|forget)", "Memory lapses"),
|
| 539 |
+
(r"(cognitive|concentration|attention).{0,20}(impair|problem|difficult|decline|deficit)", "Cognitive impairment (clinical)"),
|
| 540 |
+
(r"impaired.{0,10}(memory|short.term memory|recall)", "Impaired memory"),
|
| 541 |
+
(r"(word.{0,10}finding|anomia|forget.{0,10}words|lose.{0,10}words)", "Word-finding difficulty"),
|
| 542 |
+
(r"(slow.{0,10}processing|processing speed|slow.{0,10}thinking|thinking.{0,10}slow)", "Slowed cognitive processing"),
|
| 543 |
+
],
|
| 544 |
+
|
| 545 |
+
# ββ Standard: Fatigue βββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 546 |
+
"fatigue_ms": [
|
| 547 |
+
(r"(severe|extreme|debilitating|significant|profound|marked).{0,20}(fatigue|exhaustion|tiredness)", "Severe MS fatigue"),
|
| 548 |
+
(r"(fatigue|exhaustion).{0,20}(ms|multiple sclerosis|relapse|symptom)", "MS-associated fatigue"),
|
| 549 |
+
(r"(chronic fatigue|persistent fatigue|overwhelming fatigue|constant fatigue)", "Chronic / persistent fatigue"),
|
| 550 |
+
],
|
| 551 |
+
|
| 552 |
+
# ββ Standard: Dysarthria / dysphagia βββββββββββββββββββββββββββββββββββββ
|
| 553 |
+
"dysarthria_dysphagia": [
|
| 554 |
+
(r"(slurred speech|dysarthria|speech.{0,15}(slur|difficult|impaired))", "Dysarthria (slurred speech)"),
|
| 555 |
+
(r"(swallowing.{0,20}(difficult|problem|impaired)|dysphagia|aspirat)", "Dysphagia / aspiration"),
|
| 556 |
+
(r"(tongue.{0,15}(slow|weak|impaired)|difficulty speaking)", "Tongue / speech difficulty"),
|
| 557 |
+
],
|
| 558 |
+
|
| 559 |
+
# ββ Standard: Dysphagia isolated (v8.1) ββββββββββββββββββββββββββββββββββ
|
| 560 |
+
"dysphagia_ms": [
|
| 561 |
+
(r"(swallowing.{0,20}(difficult|problem|impaired|trouble)|dysphagia)", "Swallowing difficulty"),
|
| 562 |
+
(r"(food.{0,20}stuck.{0,20}throat|choking.{0,20}(eat|drink|swallow))", "Food stuck / choking"),
|
| 563 |
+
(r"(coughing.{0,20}(eat|drink|swallow)|aspiration)", "Aspiration / coughing when eating"),
|
| 564 |
+
],
|
| 565 |
+
|
| 566 |
+
# ββ Standard: Pseudobulbar affect ββββββββββββββββββββββββββββββββββββββββ
|
| 567 |
+
"pseudobulbar_affect": [
|
| 568 |
+
(r"(laugh|laughing|cry|crying|weep).{0,30}(uncontrollable|random|no reason|inappropriate)", "Pseudobulbar affect (PBA)"),
|
| 569 |
+
(r"\b(pseudobulbar|emotional lability)\b.{0,20}", "Pseudobulbar affect / emotional lability"),
|
| 570 |
+
],
|
| 571 |
+
|
| 572 |
+
# ββ Standard: Nocturnal spasms ββββββββββββββββββββββββββββββββββββββββββββ
|
| 573 |
+
# Note: RLS intentionally omitted here β stays in sleep_disturbance_ms (LP)
|
| 574 |
+
"nocturnal_spasms": [
|
| 575 |
+
(r"(spasm|cramp|stiff|jerk|kick).{0,30}(night|sleep|bed|nocturnal|waking)", "Nocturnal spasms / kicks"),
|
| 576 |
+
(r"(night kick|night kicks)", "Night kicks"),
|
| 577 |
+
],
|
| 578 |
+
|
| 579 |
+
# ββ Standard: Thermal dysesthesia ββββββββββββββββββββββββββββββββββββββββ
|
| 580 |
+
"thermal_dysesthesia": [
|
| 581 |
+
(r"(feet|legs|foot|soles).{0,20}(burn|fire|hot|hot coals|stinging|needles)", "Burning / hot feet / legs"),
|
| 582 |
+
],
|
| 583 |
+
|
| 584 |
+
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 585 |
+
# NEW IN v8.1 β Paroxysmal / Rare / Internet-sourced categories
|
| 586 |
+
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 587 |
+
|
| 588 |
+
# ββ ANCHOR: Paroxysmal MS symptoms βββββββββοΏ½οΏ½ββββββββββββββββββββββββββββββ
|
| 589 |
+
# Source: PMC 2024, Frontiers in Neurology, StatPearls
|
| 590 |
+
"paroxysmal_ms": [
|
| 591 |
+
(r"(paroxysmal).{0,30}(dysarthria|ataxia|diplopia|hemiparesis|sensory|symptom)", "Paroxysmal MS symptom"),
|
| 592 |
+
(r"(episodic|stereotyped|brief.{0,10}recurring).{0,20}(motor|sensory|speech|movement|neurological)", "Stereotyped recurring neurological episodes"),
|
| 593 |
+
(r"(dystonic|dystonia).{0,20}(episode|attack|spasm).{0,20}(ms|sclerosis|neurological)", "Dystonic episode (paroxysmal MS)"),
|
| 594 |
+
(r"(paroxysmal dysarthria|paroxysmal ataxia|paroxysmal hemiparesis|paroxysmal sensory)", "Paroxysmal dysarthria / ataxia / hemiparesis"),
|
| 595 |
+
(r"(paroxysmal.{0,20}(symptom|episode|attack)).{0,20}(ms|sclerosis|demyelinating)", "Paroxysmal MS episode"),
|
| 596 |
+
(r"(paroxysmal dystonia|paroxysmal posturing).{0,20}(ms|first|initial|manifestation)", "Paroxysmal dystonia β MS first sign"),
|
| 597 |
+
],
|
| 598 |
+
|
| 599 |
+
# ββ ANCHOR: Tonic spasms ββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 600 |
+
# Source: Frontiers 2024, PubMed, Cureus
|
| 601 |
+
"tonic_spasms_ms": [
|
| 602 |
+
(r"(tonic spasm|painful tonic|tonic seizure).{0,20}(ms|multiple sclerosis|episodic|brief|posture|limb)", "Tonic spasms in MS"),
|
| 603 |
+
(r"(involuntary.{0,20}(flexion|extension|posturing|tonic).{0,20}(ms|episodic|brief))", "Involuntary tonic posturing"),
|
| 604 |
+
(r"(painful.{0,15}stereotyped.{0,15}(episode|spasm|attack)|stereotyped.{0,15}painful.{0,15}episode)", "Painful stereotyped episodes"),
|
| 605 |
+
],
|
| 606 |
+
|
| 607 |
+
# ββ ANCHOR: Tumefactive MS ββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 608 |
+
# Source: Frontiers 2024, ScienceDirect
|
| 609 |
+
"tumefactive_ms": [
|
| 610 |
+
(r"(tumefactive|large lesion|mass effect).{0,20}(ms|multiple sclerosis|demyelinating)", "Tumefactive MS"),
|
| 611 |
+
(r"(rapid.{0,15}deterioration|progressive.{0,15}deterioration).{0,20}(ms|lesion|neurological)", "Rapid neurological deterioration"),
|
| 612 |
+
(r"ring.{0,10}enhancement.{0,20}(ms|lesion|gadolinium|mri)", "Ring-enhancing lesion (tumefactive)"),
|
| 613 |
+
(r"tumefactive multiple sclerosis", "Tumefactive multiple sclerosis"),
|
| 614 |
+
],
|
| 615 |
+
|
| 616 |
+
# ββ Standard: Paroxysmal pruritis βββββββββββββββββββββββββββββββββββββββββ
|
| 617 |
+
# Source: PMC 2020 review, Cureus case report
|
| 618 |
+
"paroxysmal_pruritis": [
|
| 619 |
+
(r"(paroxysmal|intense|episodic|sudden).{0,15}(itch|itching|pruritis|pruritus)", "Paroxysmal itching"),
|
| 620 |
+
(r"(intense itching|severe itching).{0,20}(dermatome|ms|neurological|skin|no.{0,10}rash)", "Intense dermatome itching"),
|
| 621 |
+
(r"itch.{0,30}(ms|multiple sclerosis|dermatome|neurological|spinal cord)", "Neurological pruritis in MS"),
|
| 622 |
+
],
|
| 623 |
+
|
| 624 |
+
# ββ Standard: Transverse myelitis ββββββββββββββββββββββββββββββββββββββββ
|
| 625 |
+
# Source: NINDS, StatPearls
|
| 626 |
+
"transverse_myelitis": [
|
| 627 |
+
(r"(transverse myelitis|myelitis|spinal cord.{0,20}(inflam|lesion|demyelinating))", "Transverse / spinal cord myelitis"),
|
| 628 |
+
(r"(acute myelitis|subacute myelitis|partial myelitis)", "Acute / partial myelitis"),
|
| 629 |
+
],
|
| 630 |
+
|
| 631 |
+
# ββ Standard: Cerebellar variant βββββββββββββββββββββββββββββββββββββββββ
|
| 632 |
+
# Source: StatPearls, WebMD
|
| 633 |
+
"cerebellar_ms": [
|
| 634 |
+
(r"\b(cerebellar.{0,20}(ataxia|tremor|variant|ms|lesion))\b", "Cerebellar MS variant"),
|
| 635 |
+
(r"(charcot triad|intention tremor.{0,20}nystagmus|nystagmus.{0,20}intention tremor)", "Charcot triad (cerebellar MS)"),
|
| 636 |
+
],
|
| 637 |
+
|
| 638 |
+
# ββ Standard: Gustatory / taste disturbance βββββββββββββββββββββββββββββββ
|
| 639 |
+
# Source: StatPearls, PMC
|
| 640 |
+
"gustatory_ms": [
|
| 641 |
+
(r"(taste.{0,20}(hallucination|altered|distorted|loss|abnormal|changed))", "Taste hallucination / disturbance"),
|
| 642 |
+
(r"(dysgeusia|ageusia|gustatory.{0,15}(symptom|disturbance|hallucination))", "Dysgeusia / ageusia (clinical)"),
|
| 643 |
+
(r"(food.{0,15}(taste|tastes).{0,15}(different|wrong|strange|metallic|bland|off)).{0,20}(neurological|ms)", "Food tastes wrong / metallic"),
|
| 644 |
+
(r"(altered taste|taste disturbance).{0,20}(neurological|ms|sclerosis)", "Altered taste (MS context)"),
|
| 645 |
+
],
|
| 646 |
+
|
| 647 |
+
# ββ Standard: Euphoria / inappropriate affect βββββββββββββββββββββββββββββ
|
| 648 |
+
# Source: Merck Manual 2024
|
| 649 |
+
"euphoria_ms": [
|
| 650 |
+
(r"(euphoria|euphoric|inappropriate happiness|manic episode).{0,20}(ms|neurological|cerebral|brain)", "Euphoria in MS"),
|
| 651 |
+
(r"(apathy|poor judgment|inattention).{0,20}(ms|neurological|cerebral|cognitive)", "Apathy / poor judgment (MS)"),
|
| 652 |
+
],
|
| 653 |
+
|
| 654 |
+
# βοΏ½οΏ½οΏ½ Standard: Useless hand (Oppenheim) βββββββββββββββββββββββββββββββββββ
|
| 655 |
+
# Source: StatPearls 2024
|
| 656 |
+
"useless_hand_ms": [
|
| 657 |
+
(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)"),
|
| 658 |
+
(r"(difficulty.{0,20}(crossing road|pour|pouring|playing ball).{0,20}(ms|neurological|dexterity))", "Difficulty pouring / crossing road"),
|
| 659 |
+
(r"(sense of.{0,10}uselessness.{0,10}hand|hand.{0,10}function.{0,10}lost)", "Sense of hand uselessness"),
|
| 660 |
+
],
|
| 661 |
+
|
| 662 |
+
# ββ Standard: Seizures in MS βββββββββββββββββββββββββββββββββββββββββββββ
|
| 663 |
+
# Source: StatPearls, Frontiers, PubMed
|
| 664 |
+
"seizures_ms": [
|
| 665 |
+
(r"(seizure|epileptic).{0,30}(ms|multiple sclerosis|demyelinating)", "Seizures in MS"),
|
| 666 |
+
(r"(focal seizure|tonic.clonic|absence seizure).{0,20}(ms|neurological|brain lesion)", "Focal / generalised seizure in MS"),
|
| 667 |
+
(r"(epilepsy|epileptic).{0,20}(ms|multiple sclerosis)", "Epilepsy / MS comorbidity"),
|
| 668 |
+
],
|
| 669 |
+
|
| 670 |
+
# ββ Standard: Prodromal / RIS (2024 McDonald) ββββββββββββββββββββββββββββ
|
| 671 |
+
# Source: PMC 2024, McDonald criteria 2024
|
| 672 |
+
"prodromal_ms": [
|
| 673 |
+
(r"(radiologically isolated syndrome|\bris\b).{0,20}(ms|white matter|lesion)", "Radiologically isolated syndrome (RIS)"),
|
| 674 |
+
(r"(subclinical|asymptomatic).{0,20}(ms|lesion|demyelinating|white matter)", "Subclinical / asymptomatic MS lesions"),
|
| 675 |
+
(r"(prodromal.{0,20}ms|ms.{0,20}prodromal)", "Prodromal MS"),
|
| 676 |
+
],
|
| 677 |
+
|
| 678 |
+
# ββ Standard: Psychiatric first presentation ββββββββββββββββββββββββββββββ
|
| 679 |
+
# Source: Merck, Cureus
|
| 680 |
+
"psychiatric_ms": [
|
| 681 |
+
(r"(psychiatric.{0,20}(symptom|presentation|ms|first))", "Psychiatric first presentation of MS"),
|
| 682 |
+
(r"(mood disorder.{0,20}(ms|neurological|brain|lesion))", "Mood disorder with MS lesion"),
|
| 683 |
+
(r"(psychosis|mania|bipolar).{0,20}(ms|multiple sclerosis|demyelinating)", "Psychosis / mania in MS"),
|
| 684 |
+
],
|
| 685 |
+
|
| 686 |
+
# ββ Standard: Functional overlay on MS βββββββββββββββββββββββββββββββββββ
|
| 687 |
+
# Source: NHS, Frontiers
|
| 688 |
+
"functional_ms": [
|
| 689 |
+
(r"(functional neurological|functional overlay).{0,20}(ms|multiple sclerosis|confirmed)", "Functional overlay on MS"),
|
| 690 |
+
(r"(functional.{0,15}disorder|non.organic).{0,20}(ms|confirmed|comorbid)", "Functional neurological disorder comorbid MS"),
|
| 691 |
+
(r"functional overlay on.{0,15}(ms|multiple sclerosis|confirmed ms)", "Functional overlay on confirmed MS"),
|
| 692 |
+
],
|
| 693 |
+
}
|
| 694 |
+
|
| 695 |
+
|
| 696 |
+
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 697 |
+
# TIER 3: LOW-PRIORITY PATTERNS (1.0 pt each β fixed weight)
|
| 698 |
+
#
|
| 699 |
+
# These are recognised MS symptoms but non-specific and insufficient alone to
|
| 700 |
+
# independently trigger HIGH. They:
|
| 701 |
+
# β’ Add 1.0 pt each to combined score
|
| 702 |
+
# β’ LP-only β WATCH tier
|
| 703 |
+
# β’ LP + standard β can escalate WATCH β MODERATE
|
| 704 |
+
# β’ LP + anchor β HIGH (anchor override)
|
| 705 |
+
#
|
| 706 |
+
# To add a new low-priority category: add key + patterns here.
|
| 707 |
+
# No other code changes needed.
|
| 708 |
+
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 709 |
+
LOW_PRIORITY_PATTERNS: Dict[str, List[tuple]] = {
|
| 710 |
+
|
| 711 |
+
# LP-1: Heat sensitivity (non-visual)
|
| 712 |
+
# Distinct from Uhthoff's (which requires visual/gait component).
|
| 713 |
+
# Generalised heat intolerance, summer worsening β common MS soft sign.
|
| 714 |
+
"heat_sensitivity_general": [
|
| 715 |
+
(r"(heat|warm|hot).{0,30}(worsen|worse|trigger|tired|exhaust|weak|fatigue)", "Heat worsening general symptoms"),
|
| 716 |
+
(r"(feel worse|feel bad|symptoms worse).{0,20}(heat|warm|hot|summer|sauna)", "Symptoms worse in heat"),
|
| 717 |
+
(r"(cannot tolerate|intolerant to|sensitive to).{0,20}(heat|warm|hot|sun)", "Heat intolerance (general)"),
|
| 718 |
+
(r"(summer|hot weather|warm weather).{0,20}(worse|bad|difficult|relapse|trigger)", "Summer symptom worsening"),
|
| 719 |
+
],
|
| 720 |
+
|
| 721 |
+
# LP-2: Chronic pain (non-TN)
|
| 722 |
+
"chronic_pain_ms": [
|
| 723 |
+
(r"(chronic|persistent|constant|ongoing).{0,15}(pain|aching|burning|discomfort)", "Chronic pain"),
|
| 724 |
+
(r"(back pain|leg pain|arm pain|body pain|joint pain).{0,30}(ms|neurological|nerve|numb)", "MS-related pain"),
|
| 725 |
+
(r"(burning|aching).{0,20}(legs|arms|back|body|limbs).{0,30}(constant|chronic|always|persistent)", "Burning / aching extremities"),
|
| 726 |
+
(r"(central sensitiz|central sensitisation|neuropathic pain|allodynia).{0,20}", "Central sensitisation / neuropathic pain"),
|
| 727 |
+
(r"(pain.{0,15}unresponsive|pain.{0,15}not respond).{0,20}(paracetamol|ibuprofen|nsaid|analgesic)", "Pain unresponsive to analgesia"),
|
| 728 |
+
],
|
| 729 |
+
|
| 730 |
+
# LP-3: Sleep disturbance
|
| 731 |
+
"sleep_disturbance_ms": [
|
| 732 |
+
(r"(insomnia|cannot sleep|trouble sleeping|poor sleep|sleep disturbance)", "Insomnia / sleep disturbance"),
|
| 733 |
+
(r"(non.restorative sleep|unrefreshing sleep|wake.{0,10}unrefreshed|tired after sleep)", "Non-restorative sleep"),
|
| 734 |
+
(r"(periodic limb|limb movement).{0,20}(sleep|night|bed)", "Periodic limb movement in sleep"),
|
| 735 |
+
(r"(sleep.{0,15}(problem|issue|disorder)).{0,20}(ms|fatigue|spasm|pain)", "Sleep problem (MS context)"),
|
| 736 |
+
],
|
| 737 |
+
|
| 738 |
+
# LP-4: Sexual dysfunction
|
| 739 |
+
"sexual_dysfunction_ms": [
|
| 740 |
+
(r"(sexual dysfunction|sexual problem|sexual difficulty|sex.{0,10}problem)", "Sexual dysfunction"),
|
| 741 |
+
(r"(reduced libido|low libido|decreased libido|loss of libido|no desire)", "Reduced libido"),
|
| 742 |
+
(r"(erectile dysfunction|impotence|erection problem)", "Erectile dysfunction"),
|
| 743 |
+
(r"(genital.{0,15}(numb|numbness|tingle|sensation|sensory))", "Genital numbness / tingling"),
|
| 744 |
+
(r"(arousal.{0,15}(problem|difficult|reduced|impaired)|lubrication.{0,15}(problem|reduced|impaired))", "Arousal / lubrication difficulty"),
|
| 745 |
+
(r"(orgasm.{0,15}(difficult|problem|impaired|absent|reduced))", "Orgasmic dysfunction"),
|
| 746 |
+
(r"(vaginal dryness|decreased lubrication)", "Vaginal dryness / decreased lubrication"),
|
| 747 |
+
],
|
| 748 |
+
|
| 749 |
+
# LP-5: Mood and affect (sustained β distinct from pseudobulbar)
|
| 750 |
+
"mood_affect_ms": [
|
| 751 |
+
(r"(depression|depressed|low mood|feeling down|hopeless).{0,30}(ms|neurological|since|for months|for years)", "MS-related depression"),
|
| 752 |
+
(r"(anxiety|anxious|panic attack|worry).{0,30}(ms|neurological|symptoms|worsening)", "MS-related anxiety"),
|
| 753 |
+
(r"(mood swings|emotional lability|irritability|mood changes).{0,30}(ms|neurological|recent|new)", "Mood swings / lability"),
|
| 754 |
+
(r"(euphoria|euphoric).{0,20}(ms|inappropriate|unusual)", "Euphoria (MS sign)"),
|
| 755 |
+
(r"(emotional.{0,10}(flatness|blunting|numbing)|apathy|motivation.{0,10}(loss|reduced|low))", "Emotional flattening / apathy"),
|
| 756 |
+
],
|
| 757 |
+
|
| 758 |
+
# LP-6: Tinnitus / hearing changes
|
| 759 |
+
"tinnitus_hearing_ms": [
|
| 760 |
+
(r"(tinnitus|ringing in.{0,10}ear|buzzing in.{0,10}ear|ringing ear)", "Tinnitus (ringing in ears)"),
|
| 761 |
+
(r"(chronic.{0,10}buzzing|persistent.{0,10}buzzing|constant.{0,10}buzzing).{0,20}(ear|head)", "Chronic buzzing in ears"),
|
| 762 |
+
(r"(hearing loss|hearing impairment|hard of hearing|decreased hearing)", "Hearing loss / impairment"),
|
| 763 |
+
(r"(sudden hearing loss|sudden deafness)", "Sudden hearing loss"),
|
| 764 |
+
(r"(auditory.{0,15}(hallucination|distortion|problem)|sound.{0,10}(distorted|strange|weird))", "Auditory disturbance"),
|
| 765 |
+
],
|
| 766 |
+
|
| 767 |
+
# LP-7: Cognitive fatigue (specific β distinct from generalised cognitive_ms)
|
| 768 |
+
"cognitive_fatigue_ms": [
|
| 769 |
+
(r"(mental fatigue|cognitive fatigue|brain.{0,10}exhaust|mental exhaustion)", "Cognitive / mental fatigue"),
|
| 770 |
+
(r"(brain.{0,10}(shut|shut down|give up|stop working)|mind.{0,10}blank.{0,10}(exhaust|tired|fatigue))", "Brain shutting down feeling"),
|
| 771 |
+
(r"(cannot.{0,10}concentrate|hard to concentrate|concentration.{0,10}(problem|difficult|poor))", "Concentration difficulty"),
|
| 772 |
+
(r"(mental.{0,10}(fog|foggy|cloudy|slow)).{0,20}(after|following|when).{0,20}(effort|activity|task)", "Mental fog after effort"),
|
| 773 |
+
],
|
| 774 |
+
|
| 775 |
+
# LP-8: Bowel dysfunction (isolated β standard if combined with other autonomic)
|
| 776 |
+
"bowel_dysfunction_ms": [
|
| 777 |
+
(r"(constipation|bowel.{0,20}(problem|control|issue|incontinence))", "Constipation / bowel control problems"),
|
| 778 |
+
(r"(fecal incontinence|bowel incontinence|bowel leakage)", "Bowel incontinence"),
|
| 779 |
+
(r"(neurogenic bowel|bowel dysfunction)", "Neurogenic bowel dysfunction"),
|
| 780 |
+
],
|
| 781 |
+
|
| 782 |
+
# LP-9: Respiratory (MS-related)
|
| 783 |
+
"respiratory_ms": [
|
| 784 |
+
(r"(shortness of breath|breathing.{0,20}(difficulty|problem|trouble)).{0,20}(ms|neurological|weakness|fatigue)", "Shortness of breath (MS respiratory weakness)"),
|
| 785 |
+
(r"(respiratory.{0,20}(weakness|dysfunction|problem)).{0,20}(ms|neurological)", "Respiratory weakness in MS"),
|
| 786 |
+
(r"diaphragm.{0,20}(weakness|paralysis|dysfunction)", "Diaphragm weakness / dysfunction"),
|
| 787 |
+
],
|
| 788 |
+
|
| 789 |
+
# LP-10: Headache (MS context)
|
| 790 |
+
"headache_ms": [
|
| 791 |
+
(r"(headache|head pain).{0,20}(ms|multiple sclerosis|relapse|lesion|worsening)", "Headache in MS context"),
|
| 792 |
+
(r"(ms.{0,20}migraine|migraine.{0,20}ms)", "Migraine β MS comorbidity"),
|
| 793 |
+
(r"(persistent headache|chronic headache|new.{0,10}headache).{0,20}(neurological|ms|spine)", "Persistent headache (MS context)"),
|
| 794 |
+
(r"headache.{0,60}(started|began).{0,30}(neurological|ms|symptom)", "Headache onset with neurological symptoms"),
|
| 795 |
+
],
|
| 796 |
+
|
| 797 |
+
# LP-11: Skin sensation / hypersensitivity
|
| 798 |
+
"skin_sensation_ms": [
|
| 799 |
+
(r"(skin.{0,20}sensitive|sensitive skin|hypersensitive).{0,20}(ms|neurological|touch)", "Skin hypersensitivity"),
|
| 800 |
+
(r"\b(allodynia|hyperaesthesia|cutaneous.{0,15}(pain|sensitivity))\b", "Allodynia / hyperaesthesia"),
|
| 801 |
+
(r"(prickling|pins and needles).{0,20}(skin|face|arm|leg|body)", "Prickling / pins and needles on skin"),
|
| 802 |
+
],
|
| 803 |
+
|
| 804 |
+
# LP-12: Pain in MS (central / neuropathic β non-TN)
|
| 805 |
+
"pain_ms": [
|
| 806 |
+
(r"(neuropathic pain|central pain).{0,20}(ms|multiple sclerosis|neurological)", "Neuropathic / central pain in MS"),
|
| 807 |
+
(r"(trigeminal neuralgia|painful.{0,15}spasm)", "Painful spasm / TN-like pain"),
|
| 808 |
+
(r"(burning pain|stabbing pain|shooting pain).{0,20}(leg|arm|back|face|body|extremities)", "Burning / stabbing / shooting pain"),
|
| 809 |
+
],
|
| 810 |
+
|
| 811 |
+
# LP-13: Menstrual / perimenstrual worsening (v8.1 new)
|
| 812 |
+
# Source: MSAA, PMC 2024
|
| 813 |
+
"menstrual_ms": [
|
| 814 |
+
(r"(perimenstrual|menstrual|period).{0,20}(worse|worsen|relapse|trigger|symptom|ms)", "Perimenstrual symptom worsening"),
|
| 815 |
+
(r"(symptoms worse.{0,20}(period|menstruation|cycle)|period.{0,30}ms symptom)", "Symptoms worse around period"),
|
| 816 |
+
],
|
| 817 |
+
|
| 818 |
+
# LP-14: Stress-triggered worsening (v8.1 new)
|
| 819 |
+
# Source: NHS, WebMD
|
| 820 |
+
"stress_triggered_ms": [
|
| 821 |
+
(r"(psychological stress|emotional stress|stress).{0,30}(trigger|worsen|worse|uhthoff|ms|symptom)", "Stress triggering MS symptoms"),
|
| 822 |
+
(r"(stress.{0,20}trigger.{0,20}ms|ms.{0,20}stress.{0,20}trigger)", "Stress β MS pseudo-relapse trigger"),
|
| 823 |
+
],
|
| 824 |
+
|
| 825 |
+
# LP-15: Pregnancy / postpartum (v8.1 new)
|
| 826 |
+
# Source: NINDS, MS Society
|
| 827 |
+
"pregnancy_ms": [
|
| 828 |
+
(r"(pregnancy|pregnant|postpartum).{0,30}(ms|relapse|symptom|worse|improve)", "Pregnancy / postpartum MS risk"),
|
| 829 |
+
(r"(ms.{0,20}(pregnancy|pregnant|postpartum)|(pregnancy|pregnant|postpartum).{0,20}ms)", "MS and pregnancy / postpartum"),
|
| 830 |
+
],
|
| 831 |
+
}
|
| 832 |
+
|
| 833 |
+
|
| 834 |
+
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 835 |
+
# SEVERITY MODIFIERS
|
| 836 |
+
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 837 |
+
SEVERITY_MODIFIERS = {
|
| 838 |
+
"severe": {
|
| 839 |
+
"patterns": [r"\b(severe|complete|total|worst|extreme|unbearable|debilitating|paralyzed|blind)\b"],
|
| 840 |
+
"weight": 1.5,
|
| 841 |
+
"label": "Severe",
|
| 842 |
+
},
|
| 843 |
+
"mild": {
|
| 844 |
+
"patterns": [r"\b(mild|slight|faint|occasional|sometimes|a little|minor|brief)\b"],
|
| 845 |
+
"weight": 0.5,
|
| 846 |
+
"label": "Mild / Occasional",
|
| 847 |
+
},
|
| 848 |
+
}
|
| 849 |
+
|
| 850 |
+
|
| 851 |
+
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 852 |
+
# WORKUP RECOMMENDATIONS BY TIER
|
| 853 |
+
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 854 |
+
WORKUP_BY_TIER: Dict[str, List[str]] = {
|
| 855 |
+
"CRITICAL_EMERGENCY": [],
|
| 856 |
+
"HIGH": [
|
| 857 |
+
"MRI of orbits with and without contrast β screen for optic nerve involvement",
|
| 858 |
+
"MRI brain and spinal cord with and without contrast",
|
| 859 |
+
"Lumbar puncture β CSF for IgG index, oligoclonal bands (>2 exclusive to CSF), kappa free light chains",
|
| 860 |
+
"Serum cell-based assay β NMO antibody (AQP4-IgG) and MOGAD (MOG-IgG)",
|
| 861 |
+
"Full neurological examination by a neurologist",
|
| 862 |
+
"Exclude mimics: sarcoidosis, lupus, vasculitis, B12 deficiency, cervical myelopathy",
|
| 863 |
+
],
|
| 864 |
+
"MODERATE": [
|
| 865 |
+
"Neurology referral β clinical review of symptom pattern",
|
| 866 |
+
"Basic blood panel β FBC, B12, folate, thyroid, ESR, CRP, ANA",
|
| 867 |
+
"Consider MRI brain if symptoms persist or evolve",
|
| 868 |
+
"Ophthalmology review if visual symptoms are present",
|
| 869 |
+
"Keep a symptom diary β track onset, duration, and triggers",
|
| 870 |
+
],
|
| 871 |
+
"WATCH": [
|
| 872 |
+
"Document symptoms carefully β note dates of onset, frequency, and any new neurological signs",
|
| 873 |
+
"Schedule a GP / family physician review",
|
| 874 |
+
"If new neurological symptoms appear (visual change, numbness, weakness, coordination problems), seek neurology referral promptly",
|
| 875 |
+
"Re-assess in 4β8 weeks or sooner if symptoms worsen",
|
| 876 |
+
],
|
| 877 |
+
"LOW": [
|
| 878 |
+
"No MS-specific features detected at this time",
|
| 879 |
+
"Continue to monitor β if new neurological symptoms develop, seek medical review",
|
| 880 |
+
"Keep a symptom diary for any changes",
|
| 881 |
+
],
|
| 882 |
+
}
|
| 883 |
+
|
| 884 |
+
|
| 885 |
+
# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββοΏ½οΏ½οΏ½ββββββββββ
|
| 886 |
+
# TIER CONFIGURATION
|
| 887 |
+
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 888 |
+
TIER_CONFIG: Dict[str, dict] = {
|
| 889 |
+
"CRITICAL_EMERGENCY": {
|
| 890 |
+
"tier_label": "Emergency",
|
| 891 |
+
"tier_subtitle": "Seek immediate emergency care",
|
| 892 |
+
"action": "Call emergency services immediately (999 / 911). Do not wait.",
|
| 893 |
+
},
|
| 894 |
+
"HIGH": {
|
| 895 |
+
"tier_label": "High MS Risk",
|
| 896 |
+
"tier_subtitle": "Neurological referral recommended",
|
| 897 |
+
"action": (
|
| 898 |
+
"The symptom pattern is consistent with possible Multiple Sclerosis. "
|
| 899 |
+
"Urgent referral to neurology is recommended for a full Multiple Sclerosis workup including "
|
| 900 |
+
"MRI of the orbits, brain and spinal cord, lumbar puncture, and specialist examination."
|
| 901 |
+
),
|
| 902 |
+
},
|
| 903 |
+
"MODERATE": {
|
| 904 |
+
"tier_label": "Moderate β Monitor",
|
| 905 |
+
"tier_subtitle": "Neurological symptoms present β clinical review recommended",
|
| 906 |
+
"action": (
|
| 907 |
+
"Some neurologically relevant symptoms are present. "
|
| 908 |
+
"A clinical review and basic investigations are recommended. "
|
| 909 |
+
"Seek neurology referral if symptoms persist, recur, or new symptoms develop."
|
| 910 |
+
),
|
| 911 |
+
},
|
| 912 |
+
"WATCH": {
|
| 913 |
+
"tier_label": "Watch β Low-Priority Symptoms",
|
| 914 |
+
"tier_subtitle": "Recognised Multiple Sclerosis soft signs β clinical monitoring advised",
|
| 915 |
+
"action": (
|
| 916 |
+
"The symptoms described are recognised in MS but are non-specific and "
|
| 917 |
+
"insufficient on their own to indicate high risk. Monitor closely. "
|
| 918 |
+
"If any new or escalating neurological symptoms appear β particularly visual "
|
| 919 |
+
"changes, numbness, weakness, or coordination problems β seek medical review promptly."
|
| 920 |
+
),
|
| 921 |
+
},
|
| 922 |
+
"LOW": {
|
| 923 |
+
"tier_label": "No Specific Features Detected",
|
| 924 |
+
"tier_subtitle": "No Multiple Sclerosis-specific pattern identified",
|
| 925 |
+
"action": (
|
| 926 |
+
"No MS-specific symptom features were detected in this description. "
|
| 927 |
+
"If your symptoms persist or you develop new neurological symptoms, "
|
| 928 |
+
"please consult a healthcare professional."
|
| 929 |
+
),
|
| 930 |
+
},
|
| 931 |
+
}
|
| 932 |
+
|
| 933 |
+
|
| 934 |
+
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 935 |
+
# NLP HELPERS
|
| 936 |
+
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 937 |
+
_doc_cache: dict = {} # single-call cache: parse text ONCE per classify() call
|
| 938 |
+
|
| 939 |
+
|
| 940 |
+
def _get_doc(text_lower: str):
|
| 941 |
+
"""Parse text once and cache within a single classify() call."""
|
| 942 |
+
if text_lower not in _doc_cache:
|
| 943 |
+
_doc_cache.clear() # keep cache size = 1
|
| 944 |
+
_doc_cache[text_lower] = nlp(text_lower)
|
| 945 |
+
return _doc_cache[text_lower]
|
| 946 |
+
|
| 947 |
+
|
| 948 |
+
def _negex_check(text_lower: str, start_char: int, end_char: int) -> bool:
|
| 949 |
+
"""Returns True if the matched span is negated via NegEx. Uses cached doc."""
|
| 950 |
+
doc = _get_doc(text_lower)
|
| 951 |
+
span = doc.char_span(start_char, end_char, label="SYMPTOM", alignment_mode="expand")
|
| 952 |
+
return bool(span and span._.negex)
|
| 953 |
+
|
| 954 |
+
|
| 955 |
+
def _severity_multiplier(text_lower: str) -> float:
|
| 956 |
+
for mod in SEVERITY_MODIFIERS.values():
|
| 957 |
+
for p in mod["patterns"]:
|
| 958 |
+
if re.search(p, text_lower):
|
| 959 |
+
return mod["weight"]
|
| 960 |
+
return 1.0
|
| 961 |
+
|
| 962 |
+
|
| 963 |
+
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 964 |
+
# CORE CLASSIFIER
|
| 965 |
+
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 966 |
+
def classify(text: str) -> ClassifyResponse:
|
| 967 |
+
"""
|
| 968 |
+
Three-tier MS symptom classification with NegEx negation detection.
|
| 969 |
+
|
| 970 |
+
Scoring:
|
| 971 |
+
Tier 1/2 (SYMPTOM_PATTERNS) β 3.0 pts Γ severity multiplier
|
| 972 |
+
Tier 3 (LOW_PRIORITY_PATTERNS) β 1.0 pt fixed
|
| 973 |
+
|
| 974 |
+
Tier assignment:
|
| 975 |
+
CRITICAL_EMERGENCY β emergency flag triggered
|
| 976 |
+
HIGH β anchor hit + score β₯ 3, OR standard score β₯ 6
|
| 977 |
+
MODERATE β standard score > 0
|
| 978 |
+
WATCH β LP-only (no Tier 1/2 hits, LP score β₯ 1)
|
| 979 |
+
LOW β nothing detected
|
| 980 |
+
"""
|
| 981 |
+
t = text.lower()
|
| 982 |
+
|
| 983 |
+
# 1. Emergency check β no NegEx (emergencies always fire)
|
| 984 |
+
for key, data in EMERGENCY_FLAGS.items():
|
| 985 |
+
if any(re.search(p, t) for p in data["patterns"]):
|
| 986 |
+
cfg = TIER_CONFIG["CRITICAL_EMERGENCY"]
|
| 987 |
+
return ClassifyResponse(
|
| 988 |
+
tier="CRITICAL_EMERGENCY",
|
| 989 |
+
tier_label=data["label"],
|
| 990 |
+
tier_subtitle=cfg["tier_subtitle"],
|
| 991 |
+
action=data["action"],
|
| 992 |
+
workup=[],
|
| 993 |
+
features=[],
|
| 994 |
+
temporal_notes=[],
|
| 995 |
+
)
|
| 996 |
+
|
| 997 |
+
# 2. Severity multiplier (applied globally)
|
| 998 |
+
mult = _severity_multiplier(t)
|
| 999 |
+
|
| 1000 |
+
# 3. Tier 1/2 extraction with NegEx
|
| 1001 |
+
features: List[FeatureFound] = []
|
| 1002 |
+
has_anchor = False
|
| 1003 |
+
t12_score = 0.0
|
| 1004 |
+
|
| 1005 |
+
for feat_key, patterns in SYMPTOM_PATTERNS.items():
|
| 1006 |
+
for pattern, label in patterns:
|
| 1007 |
+
for m in re.finditer(pattern, t):
|
| 1008 |
+
if not _negex_check(t, m.start(), m.end()):
|
| 1009 |
+
pts = 3.0 * mult
|
| 1010 |
+
t12_score += pts
|
| 1011 |
+
if feat_key in ANCHOR_FEATURES:
|
| 1012 |
+
has_anchor = True
|
| 1013 |
+
features.append(FeatureFound(key=feat_key, label=label, priority="standard"))
|
| 1014 |
+
break # one hit per feature key
|
| 1015 |
+
else:
|
| 1016 |
+
continue
|
| 1017 |
+
break
|
| 1018 |
+
|
| 1019 |
+
# 4. Tier 3 extraction with NegEx (1.0 pt fixed, no severity multiplier)
|
| 1020 |
+
lp_score = 0.0
|
| 1021 |
+
for feat_key, patterns in LOW_PRIORITY_PATTERNS.items():
|
| 1022 |
+
for pattern, label in patterns:
|
| 1023 |
+
for m in re.finditer(pattern, t):
|
| 1024 |
+
if not _negex_check(t, m.start(), m.end()):
|
| 1025 |
+
lp_score += 1.0
|
| 1026 |
+
features.append(FeatureFound(key=feat_key, label=label, priority="low"))
|
| 1027 |
+
break
|
| 1028 |
+
else:
|
| 1029 |
+
continue
|
| 1030 |
+
break
|
| 1031 |
+
|
| 1032 |
+
# 5. Temporal penalty β short-duration events (<24h) reduce score
|
| 1033 |
+
temporal_notes: List[str] = []
|
| 1034 |
+
if re.search(r"(minute|hour)s? ago", t) and not re.search(r"(day|week|month)s?", t):
|
| 1035 |
+
t12_score = max(0.0, t12_score - 2.0)
|
| 1036 |
+
temporal_notes.append(
|
| 1037 |
+
"Symptoms appear to be very short-duration (<24 hours). Clinical significance may be reduced."
|
| 1038 |
+
)
|
| 1039 |
+
|
| 1040 |
+
# 6. Tier assignment
|
| 1041 |
+
if t12_score >= 6 or (t12_score >= 3 and has_anchor):
|
| 1042 |
+
tier = "HIGH"
|
| 1043 |
+
elif t12_score > 0:
|
| 1044 |
+
tier = "MODERATE"
|
| 1045 |
+
elif lp_score >= 1:
|
| 1046 |
+
tier = "WATCH"
|
| 1047 |
+
else:
|
| 1048 |
+
tier = "LOW"
|
| 1049 |
+
|
| 1050 |
+
cfg = TIER_CONFIG[tier]
|
| 1051 |
+
return ClassifyResponse(
|
| 1052 |
+
tier=tier,
|
| 1053 |
+
tier_label=cfg["tier_label"],
|
| 1054 |
+
tier_subtitle=cfg["tier_subtitle"],
|
| 1055 |
+
action=cfg["action"],
|
| 1056 |
+
workup=WORKUP_BY_TIER.get(tier, []),
|
| 1057 |
+
features=features,
|
| 1058 |
+
temporal_notes=temporal_notes,
|
| 1059 |
+
)
|
| 1060 |
+
|
| 1061 |
+
|
| 1062 |
+
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 1063 |
+
# API ROUTES
|
| 1064 |
+
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 1065 |
+
|
| 1066 |
+
@app.get("/ping")
|
| 1067 |
+
async def ping():
|
| 1068 |
+
return "pong"
|
| 1069 |
+
|
| 1070 |
+
|
| 1071 |
+
@app.post("/analyze")
|
| 1072 |
+
async def analyze_endpoint(req: SymptomRequest):
|
| 1073 |
+
"""
|
| 1074 |
+
Lightweight classifier endpoint used by the live risk panel in chat UI.
|
| 1075 |
+
Runs the full MS classifier on the provided text and returns structured JSON.
|
| 1076 |
+
No auth required β text is analyzed in real time as conversation progresses.
|
| 1077 |
+
"""
|
| 1078 |
+
try:
|
| 1079 |
+
result = classify(req.text)
|
| 1080 |
+
# Build a score percentage for the UI gauge (cap at 100)
|
| 1081 |
+
score_map = {"LOW": 5, "WATCH": 30, "MODERATE": 55, "HIGH": 80, "CRITICAL_EMERGENCY": 100}
|
| 1082 |
+
return {
|
| 1083 |
+
"tier": result.tier,
|
| 1084 |
+
"tier_label": result.tier_label,
|
| 1085 |
+
"tier_subtitle": result.tier_subtitle,
|
| 1086 |
+
"action": result.action,
|
| 1087 |
+
"score_pct": score_map.get(result.tier, 5),
|
| 1088 |
+
"features": [{"label": f.label, "priority": f.priority} for f in result.features],
|
| 1089 |
+
"workup": result.workup[:4], # top 4 only for panel
|
| 1090 |
+
"temporal_notes": result.temporal_notes,
|
| 1091 |
+
}
|
| 1092 |
+
except Exception as e:
|
| 1093 |
+
logger.error("[analyze] {}", e)
|
| 1094 |
+
raise HTTPException(status_code=500, detail=str(e))
|
| 1095 |
+
|
| 1096 |
+
|
| 1097 |
+
@app.get("/health")
|
| 1098 |
+
async def health():
|
| 1099 |
+
return {
|
| 1100 |
+
"status": "ok",
|
| 1101 |
+
"model": "NeuroCheck v9.0 + Agentic AI",
|
| 1102 |
+
"negex": "active",
|
| 1103 |
+
"llm": "llama3.1:8b via Ollama",
|
| 1104 |
+
"rag": "ChromaDB (150 cases + MS guidelines)",
|
| 1105 |
+
"cases_validated": 150,
|
| 1106 |
+
"sources": "PMC 2024, NINDS, MSAA, NHS, Mayo, StatPearls, Cureus, Frontiers, Merck 2024",
|
| 1107 |
+
"team": {
|
| 1108 |
+
"domain_expert": "Dr. Avasarala, MD PhD β University of Kentucky, Lexington KY, USA",
|
| 1109 |
+
"lead_ai_architect": "Raghu Gangolu β NIT Warangal, Telangana, India",
|
| 1110 |
+
"principal_investigator": "Dr. Kadambari, PhD β NIT Warangal, Telangana, India",
|
| 1111 |
+
},
|
| 1112 |
+
}
|
| 1113 |
+
|
| 1114 |
+
|
| 1115 |
+
@app.post("/classify", response_model=ClassifyResponse)
|
| 1116 |
+
@limiter.limit("30/minute")
|
| 1117 |
+
async def classify_endpoint(request: Request, req: SymptomRequest):
|
| 1118 |
+
if nlp is None:
|
| 1119 |
+
raise HTTPException(status_code=503, detail="NLP model not loaded")
|
| 1120 |
+
logger.info("[classify] text_len={}", len(req.text))
|
| 1121 |
+
return classify(req.text)
|
| 1122 |
+
|
| 1123 |
+
|
| 1124 |
+
# ββ Agentic AI Chat Endpoints βββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 1125 |
+
|
| 1126 |
+
@app.post("/chat", response_model=ChatResponse)
|
| 1127 |
+
@limiter.limit("20/minute")
|
| 1128 |
+
async def chat_endpoint(
|
| 1129 |
+
request: Request,
|
| 1130 |
+
req: ChatRequest,
|
| 1131 |
+
current_user: dict = Depends(__import__("api.auth", fromlist=["get_current_user"]).get_current_user),
|
| 1132 |
+
):
|
| 1133 |
+
"""
|
| 1134 |
+
Main agentic AI chat endpoint (requires authentication).
|
| 1135 |
+
Creates a new session if session_id is not provided.
|
| 1136 |
+
Persists every message to SQLite with timestamps.
|
| 1137 |
+
"""
|
| 1138 |
+
from api.memory import new_session, get_session, append_message, get_history
|
| 1139 |
+
from api.agent import chat as agent_chat
|
| 1140 |
+
from api.database import (
|
| 1141 |
+
create_db_session, save_message, get_session_owner,
|
| 1142 |
+
update_session_title, get_message_count,
|
| 1143 |
+
)
|
| 1144 |
+
|
| 1145 |
+
user_id = current_user["id"]
|
| 1146 |
+
|
| 1147 |
+
# Create or retrieve session
|
| 1148 |
+
sid = req.session_id
|
| 1149 |
+
if not sid or get_session(sid) is None:
|
| 1150 |
+
sid = new_session()
|
| 1151 |
+
create_db_session(sid, user_id)
|
| 1152 |
+
logger.info("[chat] New session: {} user={}", sid, user_id)
|
| 1153 |
+
else:
|
| 1154 |
+
# Security: ensure the session belongs to this user
|
| 1155 |
+
owner = get_session_owner(sid)
|
| 1156 |
+
if owner is not None and owner != user_id:
|
| 1157 |
+
raise HTTPException(status_code=403, detail="Session belongs to another user")
|
| 1158 |
+
if owner is None:
|
| 1159 |
+
# Legacy session without DB record β adopt it
|
| 1160 |
+
create_db_session(sid, user_id)
|
| 1161 |
+
|
| 1162 |
+
# Persist user message to DB
|
| 1163 |
+
save_message(sid, "human", req.message)
|
| 1164 |
+
|
| 1165 |
+
# Auto-title the session from first user message
|
| 1166 |
+
if get_message_count(sid) <= 1:
|
| 1167 |
+
title = req.message[:60].strip()
|
| 1168 |
+
update_session_title(sid, title)
|
| 1169 |
+
|
| 1170 |
+
# Also keep in-memory store for agent context (existing logic)
|
| 1171 |
+
append_message(sid, "human", req.message)
|
| 1172 |
+
history = get_history(sid)
|
| 1173 |
+
|
| 1174 |
+
logger.info("[chat] session={} user={} turn={} msg_len={}", sid, user_id, len(history), len(req.message))
|
| 1175 |
+
|
| 1176 |
+
try:
|
| 1177 |
+
response_text = agent_chat(sid, req.message, history)
|
| 1178 |
+
except Exception as e:
|
| 1179 |
+
logger.error("[chat] Agent error: {}", e)
|
| 1180 |
+
raise HTTPException(status_code=500, detail=f"Agent error: {str(e)}")
|
| 1181 |
+
|
| 1182 |
+
# Persist assistant response to DB
|
| 1183 |
+
save_message(sid, "assistant", response_text)
|
| 1184 |
+
append_message(sid, "assistant", response_text)
|
| 1185 |
+
|
| 1186 |
+
return ChatResponse(
|
| 1187 |
+
session_id=sid,
|
| 1188 |
+
response=response_text,
|
| 1189 |
+
turn=len(get_history(sid)),
|
| 1190 |
+
)
|
| 1191 |
+
|
| 1192 |
+
|
| 1193 |
+
@app.post("/session/new")
|
| 1194 |
+
async def new_session_endpoint(
|
| 1195 |
+
current_user: dict = Depends(__import__("api.auth", fromlist=["get_current_user"]).get_current_user),
|
| 1196 |
+
):
|
| 1197 |
+
"""Create a new chat session for the authenticated user."""
|
| 1198 |
+
from api.memory import new_session
|
| 1199 |
+
from api.database import create_db_session
|
| 1200 |
+
sid = new_session()
|
| 1201 |
+
create_db_session(sid, current_user["id"])
|
| 1202 |
+
return {"session_id": sid}
|
| 1203 |
+
|
| 1204 |
+
|
| 1205 |
+
@app.get("/user/sessions")
|
| 1206 |
+
async def user_sessions(
|
| 1207 |
+
current_user: dict = Depends(__import__("api.auth", fromlist=["get_current_user"]).get_current_user),
|
| 1208 |
+
):
|
| 1209 |
+
"""List all chat sessions for the authenticated user (newest first)."""
|
| 1210 |
+
from api.database import get_user_sessions
|
| 1211 |
+
sessions = get_user_sessions(current_user["id"])
|
| 1212 |
+
return {"sessions": sessions}
|
| 1213 |
+
|
| 1214 |
+
|
| 1215 |
+
@app.get("/session/{session_id}/history")
|
| 1216 |
+
async def session_history(
|
| 1217 |
+
session_id: str,
|
| 1218 |
+
current_user: dict = Depends(__import__("api.auth", fromlist=["get_current_user"]).get_current_user),
|
| 1219 |
+
):
|
| 1220 |
+
"""Get full message history for a session (with timestamps)."""
|
| 1221 |
+
from api.database import get_messages, get_session_owner
|
| 1222 |
+
owner = get_session_owner(session_id)
|
| 1223 |
+
if owner is not None and owner != current_user["id"]:
|
| 1224 |
+
raise HTTPException(status_code=403, detail="Access denied")
|
| 1225 |
+
messages = get_messages(session_id)
|
| 1226 |
+
return {"session_id": session_id, "messages": messages}
|
| 1227 |
+
|
| 1228 |
+
|
| 1229 |
+
@app.delete("/session/{session_id}")
|
| 1230 |
+
async def delete_session(
|
| 1231 |
+
session_id: str,
|
| 1232 |
+
current_user: dict = Depends(__import__("api.auth", fromlist=["get_current_user"]).get_current_user),
|
| 1233 |
+
):
|
| 1234 |
+
"""Delete a session and all its messages."""
|
| 1235 |
+
from pathlib import Path
|
| 1236 |
+
from api.database import get_session_owner, delete_db_session
|
| 1237 |
+
owner = get_session_owner(session_id)
|
| 1238 |
+
if owner is not None and owner != current_user["id"]:
|
| 1239 |
+
raise HTTPException(status_code=403, detail="Access denied")
|
| 1240 |
+
delete_db_session(session_id)
|
| 1241 |
+
p = Path(f"/tmp/neurocheck_sessions/{session_id}.json")
|
| 1242 |
+
if p.exists():
|
| 1243 |
+
p.unlink()
|
| 1244 |
+
return {"deleted": session_id}
|
| 1245 |
+
|
| 1246 |
+
|
| 1247 |
+
# ββ Serve frontend static files βββββββββββββββββββββββββββββββββββββββββββββββ
|
| 1248 |
+
FRONTEND_DIR = os.path.join(os.path.dirname(os.path.abspath(__file__)), "..", "frontend")
|
| 1249 |
+
|
| 1250 |
+
if os.path.isdir(FRONTEND_DIR):
|
| 1251 |
+
app.mount("/static", StaticFiles(directory=FRONTEND_DIR), name="static")
|
| 1252 |
+
|
| 1253 |
+
@app.get("/")
|
| 1254 |
+
async def serve_index():
|
| 1255 |
+
return FileResponse(os.path.join(FRONTEND_DIR, "index.html"))
|
| 1256 |
+
|
| 1257 |
+
@app.get("/chat-ui")
|
| 1258 |
+
async def serve_chat():
|
| 1259 |
+
return FileResponse(os.path.join(FRONTEND_DIR, "chat.html"))
|
| 1260 |
+
|
| 1261 |
+
|
| 1262 |
+
if __name__ == "__main__":
|
| 1263 |
+
import uvicorn
|
| 1264 |
+
uvicorn.run("api.main:app", host="0.0.0.0", port=8000, reload=True)
|
git_ms_code/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"
|
git_ms_code/api/rag.py
ADDED
|
@@ -0,0 +1,232 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
NeuroCheck Agentic AI β RAG Knowledge Base
|
| 3 |
+
Embeds the 150 MS cases from the docx + MS clinical guidelines into ChromaDB.
|
| 4 |
+
Uses local sentence-transformers (no API key needed).
|
| 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 = 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
|
git_ms_code/docker-compose.yml
ADDED
|
@@ -0,0 +1,61 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version: "3.9"
|
| 2 |
+
|
| 3 |
+
# ββ NeuroCheck v8.0 β Docker Compose βββββββββββββββββββββββββββββββββββββββββ
|
| 4 |
+
# Usage:
|
| 5 |
+
# docker compose up β start everything
|
| 6 |
+
# docker compose up --build β rebuild and start
|
| 7 |
+
# docker compose down β stop and remove containers
|
| 8 |
+
|
| 9 |
+
services:
|
| 10 |
+
|
| 11 |
+
# ββ API Server ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 12 |
+
api:
|
| 13 |
+
build:
|
| 14 |
+
context: .
|
| 15 |
+
dockerfile: Dockerfile
|
| 16 |
+
container_name: neurocheck-api
|
| 17 |
+
restart: unless-stopped
|
| 18 |
+
ports:
|
| 19 |
+
- "8000:8000"
|
| 20 |
+
environment:
|
| 21 |
+
- SPACY_MODEL=/app/en_model
|
| 22 |
+
- PORT=8000
|
| 23 |
+
healthcheck:
|
| 24 |
+
test: ["CMD", "python3", "-c",
|
| 25 |
+
"import urllib.request; urllib.request.urlopen('http://localhost:8000/health')"]
|
| 26 |
+
interval: 30s
|
| 27 |
+
timeout: 10s
|
| 28 |
+
retries: 3
|
| 29 |
+
start_period: 20s
|
| 30 |
+
volumes:
|
| 31 |
+
# Mount source for hot-reload during development
|
| 32 |
+
- ./api:/app/api:ro
|
| 33 |
+
- ./frontend:/app/frontend:ro
|
| 34 |
+
labels:
|
| 35 |
+
- "traefik.enable=true"
|
| 36 |
+
- "traefik.http.routers.neurocheck.rule=Host(`neurocheck.yourdomain.com`)"
|
| 37 |
+
- "traefik.http.routers.neurocheck.tls=true"
|
| 38 |
+
- "traefik.http.routers.neurocheck.tls.certresolver=letsencrypt"
|
| 39 |
+
|
| 40 |
+
# ββ Reverse Proxy (optional β for production with HTTPS) ββββββββββββββββββββ
|
| 41 |
+
# Uncomment this block to enable Traefik with automatic Let's Encrypt SSL.
|
| 42 |
+
# Update the domain in the api service labels above.
|
| 43 |
+
#
|
| 44 |
+
# proxy:
|
| 45 |
+
# image: traefik:v3.0
|
| 46 |
+
# container_name: traefik
|
| 47 |
+
# restart: unless-stopped
|
| 48 |
+
# ports:
|
| 49 |
+
# - "80:80"
|
| 50 |
+
# - "443:443"
|
| 51 |
+
# volumes:
|
| 52 |
+
# - /var/run/docker.sock:/var/run/docker.sock:ro
|
| 53 |
+
# - ./traefik/acme.json:/acme.json
|
| 54 |
+
# command:
|
| 55 |
+
# - "--providers.docker=true"
|
| 56 |
+
# - "--providers.docker.exposedbydefault=false"
|
| 57 |
+
# - "--entrypoints.web.address=:80"
|
| 58 |
+
# - "--entrypoints.websecure.address=:443"
|
| 59 |
+
# - "--certificatesresolvers.letsencrypt.acme.email=your@email.com"
|
| 60 |
+
# - "--certificatesresolvers.letsencrypt.acme.storage=/acme.json"
|
| 61 |
+
# - "--certificatesresolvers.letsencrypt.acme.httpchallenge.entrypoint=web"
|
git_ms_code/front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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>NeuroCheck β 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:1;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;max-width:860px;width:100%;margin:0 auto;padding:0 16px;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 |
+
@media(max-width:640px){header{padding:10px 14px;}.bubble{max-width:90%;}.chat-container{padding:0 10px;}#sidebar{position:absolute;height:100%;z-index:20;box-shadow:4px 0 16px rgba(0,0,0,.1);}}
|
| 134 |
+
|
| 135 |
+
/* ββ RISK PANEL βββββββββββββββββββββββββββββββββββββββββββββββ */
|
| 136 |
+
#riskPanel{width:260px;background:#F8F5F0;border-left:1px solid var(--border);display:flex;flex-direction:column;flex-shrink:0;transition:width 0.22s ease,opacity 0.2s;overflow:hidden;}
|
| 137 |
+
#riskPanel.hidden{width:0;opacity:0;}
|
| 138 |
+
.rp-header{padding:14px 16px 10px;border-bottom:1px solid var(--border);display:flex;align-items:center;justify-content:space-between;}
|
| 139 |
+
.rp-header span{font-size:12px;font-weight:600;color:var(--muted);text-transform:uppercase;letter-spacing:0.6px;}
|
| 140 |
+
.rp-body{flex:1;overflow-y:auto;padding:14px 14px;}
|
| 141 |
+
.rp-body::-webkit-scrollbar{width:4px;}
|
| 142 |
+
.rp-body::-webkit-scrollbar-thumb{background:var(--border);border-radius:2px;}
|
| 143 |
+
.rp-idle{text-align:center;padding:32px 12px;font-size:12px;color:var(--muted);line-height:1.7;}
|
| 144 |
+
.rp-idle .idle-icon{font-size:28px;margin-bottom:8px;}
|
| 145 |
+
|
| 146 |
+
.gauge-tier{font-size:12px;font-weight:600;margin-top:6px;text-align:center;}
|
| 147 |
+
.tier-color-LOW{color:#065F46;}
|
| 148 |
+
.tier-color-WATCH{color:#5B21B6;}
|
| 149 |
+
.tier-color-MODERATE{color:#1E40AF;}
|
| 150 |
+
.tier-color-HIGH{color:#92400E;}
|
| 151 |
+
.tier-color-CRITICAL_EMERGENCY{color:#B91C1C;}
|
| 152 |
+
|
| 153 |
+
/* feature chips */
|
| 154 |
+
.rp-section-title{font-size:11px;font-weight:600;color:var(--muted);text-transform:uppercase;letter-spacing:0.5px;margin:12px 0 6px;}
|
| 155 |
+
.feature-list{display:flex;flex-direction:column;gap:4px;}
|
| 156 |
+
.feature-chip{font-size:12px;padding:5px 10px;border-radius:7px;background:#fff;border:0.5px solid var(--border);color:var(--text);line-height:1.4;}
|
| 157 |
+
.feature-chip.high{border-left:3px solid #C97B2A;}
|
| 158 |
+
.feature-chip.low{border-left:3px solid #8FA8BF;}
|
| 159 |
+
|
| 160 |
+
/* workup */
|
| 161 |
+
.workup-list{display:flex;flex-direction:column;gap:4px;margin-top:2px;}
|
| 162 |
+
.workup-item{font-size:12px;color:var(--text);padding:4px 0 4px 12px;border-left:2px solid var(--border);line-height:1.4;}
|
| 163 |
+
|
| 164 |
+
/* action box */
|
| 165 |
+
.action-box{background:#fff;border:0.5px solid var(--border);border-radius:9px;padding:10px 12px;font-size:12px;color:var(--text);line-height:1.6;margin-top:12px;}
|
| 166 |
+
</style>
|
| 167 |
+
</head>
|
| 168 |
+
<body>
|
| 169 |
+
|
| 170 |
+
<!-- AUTH OVERLAY -->
|
| 171 |
+
<div id="authOverlay">
|
| 172 |
+
<div class="auth-card">
|
| 173 |
+
<div class="auth-logo">
|
| 174 |
+
<div class="auth-logo-mark">NC</div>
|
| 175 |
+
<div><h2>NeuroCheck AI</h2><p>MS Clinical Assistant β Sign in to continue</p></div>
|
| 176 |
+
</div>
|
| 177 |
+
<div class="auth-tabs">
|
| 178 |
+
<button class="auth-tab active" id="tabLogin" onclick="switchTab('login')">Sign In</button>
|
| 179 |
+
<button class="auth-tab" id="tabRegister" onclick="switchTab('register')">Register</button>
|
| 180 |
+
</div>
|
| 181 |
+
<div id="authError" class="auth-error"></div>
|
| 182 |
+
<div class="auth-field auth-register-only" id="fieldUsername">
|
| 183 |
+
<label>Username</label>
|
| 184 |
+
<input type="text" id="authUsername" placeholder="e.g. dr_smith" autocomplete="username">
|
| 185 |
+
</div>
|
| 186 |
+
<div class="auth-field">
|
| 187 |
+
<label id="emailLabel">Email or Username</label>
|
| 188 |
+
<input type="text" id="authEmail" placeholder="your@email.com" autocomplete="email">
|
| 189 |
+
</div>
|
| 190 |
+
<div class="auth-field">
|
| 191 |
+
<label>Password</label>
|
| 192 |
+
<input type="password" id="authPassword" placeholder="β’β’β’β’β’β’β’β’" autocomplete="current-password">
|
| 193 |
+
</div>
|
| 194 |
+
<button class="auth-btn" id="authSubmitBtn" onclick="submitAuth()">Sign In</button>
|
| 195 |
+
</div>
|
| 196 |
+
</div>
|
| 197 |
+
|
| 198 |
+
<!-- APP SHELL -->
|
| 199 |
+
<div id="appShell">
|
| 200 |
+
<header>
|
| 201 |
+
<button class="sidebar-toggle" onclick="toggleSidebar()">β°</button>
|
| 202 |
+
<div class="logo-mark">NC</div>
|
| 203 |
+
<div class="header-text">
|
| 204 |
+
<h1>NeuroCheck AI</h1>
|
| 205 |
+
<p>MS Clinical Assistant Β· Powered by Llama 3.1 Β· RAG + NegEx</p>
|
| 206 |
+
</div>
|
| 207 |
+
<div class="header-right">
|
| 208 |
+
<span class="model-badge">π€ Agentic AI</span>
|
| 209 |
+
<a href="/" class="nav-link">Classifier</a>
|
| 210 |
+
<div class="user-pill" onclick="toggleUserMenu()">
|
| 211 |
+
<div class="user-avatar" id="headerAvatar">?</div>
|
| 212 |
+
<span class="user-name" id="headerUsername">β¦</span>
|
| 213 |
+
<div class="user-dropdown" id="userDropdown">
|
| 214 |
+
<a onclick="newChat()">οΌ New Chat</a>
|
| 215 |
+
<hr>
|
| 216 |
+
<a onclick="signOut()" class="danger">Sign Out</a>
|
| 217 |
+
</div>
|
| 218 |
+
</div>
|
| 219 |
+
</div>
|
| 220 |
+
</header>
|
| 221 |
+
|
| 222 |
+
<div class="main-body">
|
| 223 |
+
<div id="sidebar">
|
| 224 |
+
<div class="sidebar-header">
|
| 225 |
+
<span>Chat History</span>
|
| 226 |
+
<button class="new-chat-side" onclick="newChat()">+ New</button>
|
| 227 |
+
</div>
|
| 228 |
+
<div class="session-list" id="sessionList">
|
| 229 |
+
<div class="sidebar-empty" id="sidebarEmpty">No conversations yet.<br>Start a new chat!</div>
|
| 230 |
+
</div>
|
| 231 |
+
</div>
|
| 232 |
+
|
| 233 |
+
<!-- RISK PANEL -->
|
| 234 |
+
<div id="riskPanel" class="hidden">
|
| 235 |
+
<div class="rp-header">
|
| 236 |
+
<span>MS Risk Analysis</span>
|
| 237 |
+
</div>
|
| 238 |
+
<div class="rp-body" id="riskBody">
|
| 239 |
+
<div class="rp-idle" id="riskIdle">
|
| 240 |
+
<div class="idle-icon">π§ </div>
|
| 241 |
+
Start describing your symptoms and the risk panel will update automatically.
|
| 242 |
+
</div>
|
| 243 |
+
<div id="riskContent" style="display:none;">
|
| 244 |
+
<!-- Tier label only -->
|
| 245 |
+
<div style="text-align:center;padding:14px 0 8px;">
|
| 246 |
+
<div class="gauge-tier" id="gaugeTier" style="font-size:15px;"></div>
|
| 247 |
+
<div style="font-size:11px;color:var(--muted);margin-top:4px;" id="gaugeSubtitle"></div>
|
| 248 |
+
</div>
|
| 249 |
+
|
| 250 |
+
<!-- Detected features -->
|
| 251 |
+
<div id="featuresSection" style="display:none;">
|
| 252 |
+
<div class="rp-section-title">Detected Symptoms</div>
|
| 253 |
+
<div class="feature-list" id="featureList"></div>
|
| 254 |
+
</div>
|
| 255 |
+
|
| 256 |
+
<!-- Recommended workup -->
|
| 257 |
+
<div id="workupSection" style="display:none;">
|
| 258 |
+
<div class="rp-section-title">Recommended Workup</div>
|
| 259 |
+
<div class="workup-list" id="workupList"></div>
|
| 260 |
+
</div>
|
| 261 |
+
|
| 262 |
+
<!-- Action -->
|
| 263 |
+
<div class="action-box" id="actionBox" style="display:none;"></div>
|
| 264 |
+
</div>
|
| 265 |
+
</div>
|
| 266 |
+
</div>
|
| 267 |
+
|
| 268 |
+
<div class="chat-wrapper">
|
| 269 |
+
<div class="disclaimer-bar">Clinical decision support only β not a diagnosis</div>
|
| 270 |
+
<div class="chat-container">
|
| 271 |
+
<div class="messages" id="messages">
|
| 272 |
+
<div class="session-loading" id="sessionLoading">
|
| 273 |
+
<div class="spin"></div> Loading conversationβ¦
|
| 274 |
+
</div>
|
| 275 |
+
<div class="welcome" id="welcome">
|
| 276 |
+
<div class="welcome-icon">π§ </div>
|
| 277 |
+
<h2>MS Clinical AI Assistant</h2>
|
| 278 |
+
<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>
|
| 279 |
+
<div class="welcome-chips">
|
| 280 |
+
<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>
|
| 281 |
+
<div class="chip" onclick="sendChip('Every time I bend my neck forward I get an electric shock running down my spine.')">β‘ Lhermitte sign</div>
|
| 282 |
+
<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>
|
| 283 |
+
<div class="chip" onclick="sendChip('I have numbness and tingling in my right arm and leg that started 2 days ago.')">π¦Ύ Numbness / tingling</div>
|
| 284 |
+
<div class="chip" onclick="sendChip('I feel a tight squeezing band around my chest like a corset being pulled tight.')">ποΈ MS Hug</div>
|
| 285 |
+
</div>
|
| 286 |
+
</div>
|
| 287 |
+
</div>
|
| 288 |
+
<div class="input-area">
|
| 289 |
+
<div class="input-controls">
|
| 290 |
+
<span class="session-id" id="sessionLabel"></span>
|
| 291 |
+
<button class="new-chat-btn" onclick="newChat()">+ New Chat</button>
|
| 292 |
+
</div>
|
| 293 |
+
<div class="input-row">
|
| 294 |
+
<textarea class="msg-input" id="msgInput" placeholder="Describe your symptoms⦠(Enter to send, Shift+Enter for new line)" rows="1"></textarea>
|
| 295 |
+
<button class="send-btn" id="sendBtn" onclick="sendMessage()">
|
| 296 |
+
<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
|
| 297 |
+
<line x1="22" y1="2" x2="11" y2="13"></line>
|
| 298 |
+
<polygon points="22 2 15 22 11 13 2 9 22 2"></polygon>
|
| 299 |
+
</svg>
|
| 300 |
+
</button>
|
| 301 |
+
</div>
|
| 302 |
+
<div class="input-hint">Domain Expert: Dr. Avasarala, MD PhD, UKY Β· Lead AI Architect: Raghu Gangolu, NITW Β· PI: Dr. Kadambari, PhD, NITW</div>
|
| 303 |
+
</div>
|
| 304 |
+
</div>
|
| 305 |
+
</div>
|
| 306 |
+
</div>
|
| 307 |
+
</div>
|
| 308 |
+
|
| 309 |
+
<script>
|
| 310 |
+
const API = window.location.origin;
|
| 311 |
+
let authToken = localStorage.getItem('nc_token') || null;
|
| 312 |
+
let currentUser = JSON.parse(localStorage.getItem('nc_user') || 'null');
|
| 313 |
+
let sessionId = null;
|
| 314 |
+
let isWaiting = false;
|
| 315 |
+
let currentTab = 'login';
|
| 316 |
+
|
| 317 |
+
// Bootstrap
|
| 318 |
+
window.addEventListener('DOMContentLoaded', () => {
|
| 319 |
+
document.getElementById('authPassword').addEventListener('keydown', e => { if(e.key==='Enter') submitAuth(); });
|
| 320 |
+
if (authToken && currentUser) showApp();
|
| 321 |
+
});
|
| 322 |
+
|
| 323 |
+
// ββ Auth ββ
|
| 324 |
+
function switchTab(tab) {
|
| 325 |
+
currentTab = tab;
|
| 326 |
+
document.getElementById('tabLogin').classList.toggle('active', tab==='login');
|
| 327 |
+
document.getElementById('tabRegister').classList.toggle('active', tab==='register');
|
| 328 |
+
document.getElementById('authSubmitBtn').textContent = tab==='login' ? 'Sign In' : 'Create Account';
|
| 329 |
+
document.querySelectorAll('.auth-register-only').forEach(el => el.style.display = tab==='register' ? 'block' : 'none');
|
| 330 |
+
document.getElementById('emailLabel').textContent = tab==='login' ? 'Email or Username' : 'Email';
|
| 331 |
+
clearAuthError();
|
| 332 |
+
}
|
| 333 |
+
|
| 334 |
+
function showAuthError(msg) { const e=document.getElementById('authError'); e.textContent=msg; e.style.display='block'; }
|
| 335 |
+
function clearAuthError() { document.getElementById('authError').style.display='none'; }
|
| 336 |
+
|
| 337 |
+
async function submitAuth() {
|
| 338 |
+
clearAuthError();
|
| 339 |
+
const btn = document.getElementById('authSubmitBtn');
|
| 340 |
+
btn.disabled = true;
|
| 341 |
+
const email = document.getElementById('authEmail').value.trim();
|
| 342 |
+
const password = document.getElementById('authPassword').value;
|
| 343 |
+
const username = document.getElementById('authUsername').value.trim();
|
| 344 |
+
if (!email || !password) { showAuthError('Please fill in all fields.'); btn.disabled=false; return; }
|
| 345 |
+
if (currentTab==='register' && !username) { showAuthError('Please enter a username.'); btn.disabled=false; return; }
|
| 346 |
+
try {
|
| 347 |
+
let res;
|
| 348 |
+
if (currentTab==='register') {
|
| 349 |
+
res = await fetch(`${API}/auth/register`, {
|
| 350 |
+
method:'POST', headers:{'Content-Type':'application/json'},
|
| 351 |
+
body: JSON.stringify({ username, email, password }),
|
| 352 |
+
});
|
| 353 |
+
} else {
|
| 354 |
+
const form = new URLSearchParams();
|
| 355 |
+
form.append('username', email);
|
| 356 |
+
form.append('password', password);
|
| 357 |
+
res = await fetch(`${API}/auth/login`, {
|
| 358 |
+
method:'POST', headers:{'Content-Type':'application/x-www-form-urlencoded'}, body: form,
|
| 359 |
+
});
|
| 360 |
+
}
|
| 361 |
+
let data;
|
| 362 |
+
try { data = await res.json(); } catch { throw new Error(`Server error ${res.status} β check terminal`); }
|
| 363 |
+
if (!res.ok) throw new Error(data.detail || 'Authentication failed');
|
| 364 |
+
authToken = data.access_token;
|
| 365 |
+
currentUser = { id: data.user_id, username: data.username };
|
| 366 |
+
localStorage.setItem('nc_token', authToken);
|
| 367 |
+
localStorage.setItem('nc_user', JSON.stringify(currentUser));
|
| 368 |
+
showApp();
|
| 369 |
+
} catch(err) { showAuthError(err.message); }
|
| 370 |
+
finally { btn.disabled = false; }
|
| 371 |
+
}
|
| 372 |
+
|
| 373 |
+
function signOut() {
|
| 374 |
+
localStorage.removeItem('nc_token'); localStorage.removeItem('nc_user');
|
| 375 |
+
authToken=null; currentUser=null; sessionId=null;
|
| 376 |
+
document.getElementById('appShell').classList.remove('visible');
|
| 377 |
+
document.getElementById('authOverlay').style.display='flex';
|
| 378 |
+
clearMessages();
|
| 379 |
+
}
|
| 380 |
+
|
| 381 |
+
// ββ Shell ββ
|
| 382 |
+
function showApp() {
|
| 383 |
+
document.getElementById('authOverlay').style.display='none';
|
| 384 |
+
document.getElementById('appShell').classList.add('visible');
|
| 385 |
+
document.getElementById('headerUsername').textContent = currentUser.username;
|
| 386 |
+
document.getElementById('headerAvatar').textContent = currentUser.username[0].toUpperCase();
|
| 387 |
+
loadSessionList();
|
| 388 |
+
}
|
| 389 |
+
|
| 390 |
+
function toggleUserMenu() { document.getElementById('userDropdown').classList.toggle('open'); }
|
| 391 |
+
document.addEventListener('click', e => { if (!e.target.closest('.user-pill')) document.getElementById('userDropdown').classList.remove('open'); });
|
| 392 |
+
function toggleSidebar() { document.getElementById('sidebar').classList.toggle('collapsed'); }
|
| 393 |
+
|
| 394 |
+
// ββ Session list ββ
|
| 395 |
+
async function loadSessionList() {
|
| 396 |
+
try {
|
| 397 |
+
const res = await authFetch('/user/sessions');
|
| 398 |
+
const data = await res.json();
|
| 399 |
+
renderSessionList(data.sessions || []);
|
| 400 |
+
} catch(e) { console.error(e); }
|
| 401 |
+
}
|
| 402 |
+
|
| 403 |
+
function renderSessionList(sessions) {
|
| 404 |
+
const list = document.getElementById('sessionList');
|
| 405 |
+
const empty = document.getElementById('sidebarEmpty');
|
| 406 |
+
list.querySelectorAll('.session-item').forEach(el => el.remove());
|
| 407 |
+
if (!sessions.length) { empty.style.display='block'; return; }
|
| 408 |
+
empty.style.display='none';
|
| 409 |
+
sessions.forEach(s => {
|
| 410 |
+
const item = document.createElement('div');
|
| 411 |
+
item.className = 'session-item' + (s.session_uuid===sessionId ? ' active' : '');
|
| 412 |
+
item.dataset.uuid = s.session_uuid;
|
| 413 |
+
const ts = new Date(s.updated_at).toLocaleDateString(undefined,{month:'short',day:'numeric'});
|
| 414 |
+
item.innerHTML = `
|
| 415 |
+
<div class="session-item-icon">π¬</div>
|
| 416 |
+
<div class="session-item-body">
|
| 417 |
+
<div class="session-title">${escapeHtml(s.title||'Chat')}</div>
|
| 418 |
+
<div class="session-meta">${ts}</div>
|
| 419 |
+
</div>
|
| 420 |
+
<button class="session-delete" onclick="deleteSession(event,'${s.session_uuid}')">β</button>`;
|
| 421 |
+
item.addEventListener('click', () => loadSession(s.session_uuid));
|
| 422 |
+
list.appendChild(item);
|
| 423 |
+
});
|
| 424 |
+
}
|
| 425 |
+
|
| 426 |
+
async function loadSession(uuid) {
|
| 427 |
+
if (uuid===sessionId) return;
|
| 428 |
+
sessionId = uuid;
|
| 429 |
+
document.querySelectorAll('.session-item').forEach(el => el.classList.toggle('active', el.dataset.uuid===uuid));
|
| 430 |
+
clearMessages();
|
| 431 |
+
const loading = document.getElementById('sessionLoading');
|
| 432 |
+
loading.classList.add('visible');
|
| 433 |
+
try {
|
| 434 |
+
const res = await authFetch(`/session/${uuid}/history`);
|
| 435 |
+
const data = await res.json();
|
| 436 |
+
loading.classList.remove('visible');
|
| 437 |
+
if (data.messages && data.messages.length) {
|
| 438 |
+
document.getElementById('welcome').style.display='none';
|
| 439 |
+
resetRiskPanel();
|
| 440 |
+
data.messages.forEach(m => addBubble(m.role==='human'?'user':'ai', m.content, m.created_at));
|
| 441 |
+
// Re-analyze the full loaded history
|
| 442 |
+
const humanText = data.messages.filter(m=>m.role==='human').map(m=>m.content).join(' ');
|
| 443 |
+
if (humanText.trim().length > 10) updateRiskPanelWithText(humanText);
|
| 444 |
+
}
|
| 445 |
+
} catch(e) { loading.classList.remove('visible'); }
|
| 446 |
+
document.getElementById('sessionLabel').textContent = `Session: ${uuid.slice(0,8)}β¦`;
|
| 447 |
+
}
|
| 448 |
+
|
| 449 |
+
async function deleteSession(e, uuid) {
|
| 450 |
+
e.stopPropagation();
|
| 451 |
+
if (!confirm('Delete this conversation?')) return;
|
| 452 |
+
await authFetch(`/session/${uuid}`, {method:'DELETE'}).catch(()=>{});
|
| 453 |
+
if (sessionId===uuid) { sessionId=null; clearMessages(); }
|
| 454 |
+
loadSessionList();
|
| 455 |
+
}
|
| 456 |
+
|
| 457 |
+
// ββ Chat ββ
|
| 458 |
+
const input = document.getElementById('msgInput');
|
| 459 |
+
input.addEventListener('input', () => { input.style.height='auto'; input.style.height=Math.min(input.scrollHeight,160)+'px'; });
|
| 460 |
+
input.addEventListener('keydown', e => { if (e.key==='Enter' && !e.shiftKey) { e.preventDefault(); sendMessage(); } });
|
| 461 |
+
|
| 462 |
+
function sendChip(text) { input.value=text; sendMessage(); }
|
| 463 |
+
|
| 464 |
+
async function sendMessage() {
|
| 465 |
+
const text = input.value.trim();
|
| 466 |
+
if (!text || isWaiting || !authToken) return;
|
| 467 |
+
isWaiting = true;
|
| 468 |
+
input.value = ''; input.style.height='auto';
|
| 469 |
+
document.getElementById('sendBtn').disabled = true;
|
| 470 |
+
document.getElementById('welcome').style.display='none';
|
| 471 |
+
addBubble('user', text, new Date().toISOString());
|
| 472 |
+
updateRiskPanelWithText(text); // live risk update on every user message
|
| 473 |
+
const typing = addTyping();
|
| 474 |
+
try {
|
| 475 |
+
const res = await authFetch('/chat', {
|
| 476 |
+
method:'POST', headers:{'Content-Type':'application/json'},
|
| 477 |
+
body: JSON.stringify({ message: text, session_id: sessionId }),
|
| 478 |
+
});
|
| 479 |
+
if (res.status===401) { signOut(); return; }
|
| 480 |
+
if (!res.ok) { const err=await res.json().catch(()=>{}); throw new Error(err.detail||`Error ${res.status}`); }
|
| 481 |
+
const data = await res.json();
|
| 482 |
+
sessionId = data.session_id;
|
| 483 |
+
document.getElementById('sessionLabel').textContent = `Session: ${sessionId.slice(0,8)}β¦`;
|
| 484 |
+
typing.remove();
|
| 485 |
+
addBubble('ai', data.response, new Date().toISOString());
|
| 486 |
+
loadSessionList();
|
| 487 |
+
} catch(err) {
|
| 488 |
+
typing.remove();
|
| 489 |
+
addBubble('ai', `β οΈ Error: ${err.message}`, new Date().toISOString());
|
| 490 |
+
} finally {
|
| 491 |
+
isWaiting=false;
|
| 492 |
+
document.getElementById('sendBtn').disabled=false;
|
| 493 |
+
input.focus();
|
| 494 |
+
}
|
| 495 |
+
}
|
| 496 |
+
|
| 497 |
+
function newChat() {
|
| 498 |
+
sessionId=null;
|
| 499 |
+
clearMessages();
|
| 500 |
+
resetRiskPanel();
|
| 501 |
+
document.getElementById('sessionLabel').textContent='';
|
| 502 |
+
document.querySelectorAll('.session-item').forEach(el => el.classList.remove('active'));
|
| 503 |
+
loadSessionList();
|
| 504 |
+
input.focus();
|
| 505 |
+
}
|
| 506 |
+
|
| 507 |
+
function clearMessages() {
|
| 508 |
+
document.getElementById('messages').querySelectorAll('.msg-row').forEach(el => el.remove());
|
| 509 |
+
document.getElementById('welcome').style.display='flex';
|
| 510 |
+
}
|
| 511 |
+
|
| 512 |
+
function addBubble(role, text, timestamp) {
|
| 513 |
+
const msgs = document.getElementById('messages');
|
| 514 |
+
const row = document.createElement('div');
|
| 515 |
+
row.className = `msg-row ${role}`;
|
| 516 |
+
const avatar = document.createElement('div');
|
| 517 |
+
avatar.className = `avatar ${role}`;
|
| 518 |
+
avatar.textContent = role==='ai' ? 'NC' : (currentUser ? currentUser.username[0].toUpperCase() : 'U');
|
| 519 |
+
const inner = document.createElement('div');
|
| 520 |
+
const bubble = document.createElement('div');
|
| 521 |
+
bubble.className = `bubble ${role}`;
|
| 522 |
+
bubble.innerHTML = formatMessage(text);
|
| 523 |
+
const ts = document.createElement('div');
|
| 524 |
+
ts.className = 'msg-ts';
|
| 525 |
+
ts.textContent = formatTimestamp(timestamp);
|
| 526 |
+
inner.appendChild(bubble); inner.appendChild(ts);
|
| 527 |
+
row.appendChild(avatar); row.appendChild(inner);
|
| 528 |
+
msgs.appendChild(row); msgs.scrollTop=msgs.scrollHeight;
|
| 529 |
+
return row;
|
| 530 |
+
}
|
| 531 |
+
|
| 532 |
+
function addTyping() {
|
| 533 |
+
const msgs = document.getElementById('messages');
|
| 534 |
+
const row=document.createElement('div'); row.className='msg-row ai';
|
| 535 |
+
const av=document.createElement('div'); av.className='avatar ai'; av.textContent='NC';
|
| 536 |
+
const b=document.createElement('div'); b.className='typing-bubble';
|
| 537 |
+
b.innerHTML='<div class="dot"></div><div class="dot"></div><div class="dot"></div>';
|
| 538 |
+
row.appendChild(av); row.appendChild(b); msgs.appendChild(row); msgs.scrollTop=msgs.scrollHeight;
|
| 539 |
+
return row;
|
| 540 |
+
}
|
| 541 |
+
|
| 542 |
+
function formatTimestamp(iso) {
|
| 543 |
+
if (!iso) return '';
|
| 544 |
+
try {
|
| 545 |
+
const d=new Date(iso), now=new Date();
|
| 546 |
+
const sameDay = d.toDateString()===now.toDateString();
|
| 547 |
+
return sameDay
|
| 548 |
+
? d.toLocaleTimeString([],{hour:'2-digit',minute:'2-digit'})
|
| 549 |
+
: d.toLocaleDateString([],{month:'short',day:'numeric'})+' '+d.toLocaleTimeString([],{hour:'2-digit',minute:'2-digit'});
|
| 550 |
+
} catch { return ''; }
|
| 551 |
+
}
|
| 552 |
+
|
| 553 |
+
function formatMessage(text) {
|
| 554 |
+
let html = escapeHtml(text);
|
| 555 |
+
// Bold markdown **text**
|
| 556 |
+
html = html.replace(/\*\*(.*?)\*\*/g, '<strong>$1</strong>');
|
| 557 |
+
// Paragraphs and line breaks
|
| 558 |
+
html = html.replace(/\n\n/g, '</p><p>');
|
| 559 |
+
html = html.replace(/\n/g, '<br>');
|
| 560 |
+
// Plain inline highlight for tier words β no badges, no colours
|
| 561 |
+
const tierWords = {
|
| 562 |
+
'CRITICAL_EMERGENCY': 'Emergency',
|
| 563 |
+
'HIGH': 'High MS Risk',
|
| 564 |
+
'MODERATE': 'Moderate MS Risk',
|
| 565 |
+
'WATCH': 'Watch',
|
| 566 |
+
'LOW': 'Low MS Risk'
|
| 567 |
+
};
|
| 568 |
+
for (const [key, label] of Object.entries(tierWords)) {
|
| 569 |
+
const re = new RegExp(key.replace('_', '[_ ]?'), 'gi');
|
| 570 |
+
html = html.replace(re, `<strong>${label}</strong>`);
|
| 571 |
+
}
|
| 572 |
+
// Bold key clinical terms
|
| 573 |
+
['MRI','lumbar puncture','oligoclonal bands','optic neuritis',
|
| 574 |
+
'NMO','MOGAD','Lhermitte','Uhthoff','neurology referral','emergency'
|
| 575 |
+
].forEach(kw => {
|
| 576 |
+
html = html.replace(new RegExp(`\\b${kw}\\b`, 'gi'), '<strong>$&</strong>');
|
| 577 |
+
});
|
| 578 |
+
return `<p>${html}</p>`;
|
| 579 |
+
}
|
| 580 |
+
|
| 581 |
+
function escapeHtml(t) { return t.replace(/&/g,'&').replace(/</g,'<').replace(/>/g,'>'); }
|
| 582 |
+
|
| 583 |
+
function authFetch(path, opts={}) {
|
| 584 |
+
return fetch(`${API}${path}`, { ...opts, headers:{ ...(opts.headers||{}), 'Authorization':`Bearer ${authToken}` } });
|
| 585 |
+
}
|
| 586 |
+
|
| 587 |
+
// ββ Live Risk Panel ββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 588 |
+
let riskDebounce = null;
|
| 589 |
+
let conversationText = ''; // accumulates all human messages for full-context analysis
|
| 590 |
+
|
| 591 |
+
const TIER_COLORS = {
|
| 592 |
+
LOW: '#0A7B74',
|
| 593 |
+
WATCH: '#7C3AED',
|
| 594 |
+
MODERATE: '#2563EB',
|
| 595 |
+
HIGH: '#C97B2A',
|
| 596 |
+
CRITICAL_EMERGENCY: '#B91C1C',
|
| 597 |
+
};
|
| 598 |
+
|
| 599 |
+
function showRiskPanel() {
|
| 600 |
+
document.getElementById('riskPanel').classList.remove('hidden');
|
| 601 |
+
}
|
| 602 |
+
|
| 603 |
+
function updateRiskPanelWithText(text) {
|
| 604 |
+
// Accumulate context β full conversation gives better classification
|
| 605 |
+
if (text && !conversationText.includes(text)) {
|
| 606 |
+
conversationText += ' ' + text;
|
| 607 |
+
}
|
| 608 |
+
const combined = conversationText.trim();
|
| 609 |
+
if (combined.length < 15) return; // too short to analyze
|
| 610 |
+
|
| 611 |
+
// Debounce β wait 800ms after last update before calling API
|
| 612 |
+
clearTimeout(riskDebounce);
|
| 613 |
+
riskDebounce = setTimeout(() => analyzeRisk(combined), 800);
|
| 614 |
+
}
|
| 615 |
+
|
| 616 |
+
async function analyzeRisk(text) {
|
| 617 |
+
try {
|
| 618 |
+
const res = await fetch(`${API}/analyze`, {
|
| 619 |
+
method: 'POST',
|
| 620 |
+
headers: { 'Content-Type': 'application/json' },
|
| 621 |
+
body: JSON.stringify({ text }),
|
| 622 |
+
});
|
| 623 |
+
if (!res.ok) return;
|
| 624 |
+
const data = await res.json();
|
| 625 |
+
renderRiskPanel(data);
|
| 626 |
+
} catch(e) { /* silent fail β panel just won't update */ }
|
| 627 |
+
}
|
| 628 |
+
|
| 629 |
+
function renderRiskPanel(data) {
|
| 630 |
+
// Show panel and hide idle state
|
| 631 |
+
showRiskPanel();
|
| 632 |
+
document.getElementById('riskIdle').style.display = 'none';
|
| 633 |
+
document.getElementById('riskContent').style.display = 'block';
|
| 634 |
+
|
| 635 |
+
const pct = data.score_pct || 0;
|
| 636 |
+
const tier = data.tier || 'LOW';
|
| 637 |
+
const color = TIER_COLORS[tier] || TIER_COLORS.LOW;
|
| 638 |
+
|
| 639 |
+
// Tier label
|
| 640 |
+
const tierEl = document.getElementById('gaugeTier');
|
| 641 |
+
tierEl.textContent = data.tier_label || '';
|
| 642 |
+
tierEl.style.color = color;
|
| 643 |
+
document.getElementById('gaugeSubtitle').textContent = data.tier_subtitle || '';
|
| 644 |
+
|
| 645 |
+
// Features
|
| 646 |
+
const features = data.features || [];
|
| 647 |
+
const featSec = document.getElementById('featuresSection');
|
| 648 |
+
const featList = document.getElementById('featureList');
|
| 649 |
+
if (features.length > 0) {
|
| 650 |
+
featSec.style.display = 'block';
|
| 651 |
+
featList.innerHTML = features.map(f =>
|
| 652 |
+
`<div class="feature-chip ${f.priority === 'standard' ? 'high' : 'low'}">${escapeHtml(f.label)}</div>`
|
| 653 |
+
).join('');
|
| 654 |
+
} else {
|
| 655 |
+
featSec.style.display = 'none';
|
| 656 |
+
}
|
| 657 |
+
|
| 658 |
+
// Workup
|
| 659 |
+
const workup = data.workup || [];
|
| 660 |
+
const wkSec = document.getElementById('workupSection');
|
| 661 |
+
const wkList = document.getElementById('workupList');
|
| 662 |
+
if (workup.length > 0) {
|
| 663 |
+
wkSec.style.display = 'block';
|
| 664 |
+
wkList.innerHTML = workup.map(w =>
|
| 665 |
+
`<div class="workup-item">${escapeHtml(w)}</div>`
|
| 666 |
+
).join('');
|
| 667 |
+
} else {
|
| 668 |
+
wkSec.style.display = 'none';
|
| 669 |
+
}
|
| 670 |
+
|
| 671 |
+
// Action
|
| 672 |
+
const actionBox = document.getElementById('actionBox');
|
| 673 |
+
if (data.action && tier !== 'LOW') {
|
| 674 |
+
actionBox.style.display = 'block';
|
| 675 |
+
actionBox.innerHTML = `<strong>Recommended action:</strong><br>${escapeHtml(data.action)}`;
|
| 676 |
+
actionBox.style.borderColor = color;
|
| 677 |
+
} else {
|
| 678 |
+
actionBox.style.display = 'none';
|
| 679 |
+
}
|
| 680 |
+
}
|
| 681 |
+
|
| 682 |
+
function resetRiskPanel() {
|
| 683 |
+
conversationText = '';
|
| 684 |
+
document.getElementById('riskPanel').classList.add('hidden');
|
| 685 |
+
document.getElementById('riskIdle').style.display = 'block';
|
| 686 |
+
document.getElementById('riskContent').style.display = 'none';
|
| 687 |
+
}
|
| 688 |
+
</script>
|
| 689 |
+
</body>
|
| 690 |
+
</html>
|
git_ms_code/frontend/index.html
ADDED
|
@@ -0,0 +1,573 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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="en">
|
| 3 |
+
<head>
|
| 4 |
+
<meta charset="UTF-8">
|
| 5 |
+
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
| 6 |
+
<title>NeuroCheck β 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">NC</div>
|
| 297 |
+
<div class="header-text">
|
| 298 |
+
<h1>NeuroCheck</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>NeuroCheck 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>
|
git_ms_code/railway.toml
ADDED
|
@@ -0,0 +1,24 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# ββ NeuroCheck v8.0 β Railway Deployment Config ββββββββββββββββββββββββββββββ
|
| 2 |
+
# Deploy to Railway: https://railway.app
|
| 3 |
+
# Steps:
|
| 4 |
+
# 1. railway login
|
| 5 |
+
# 2. railway init (in this folder)
|
| 6 |
+
# 3. railway up
|
| 7 |
+
# 4. railway domain (get your public URL)
|
| 8 |
+
#
|
| 9 |
+
# Or connect GitHub repo in Railway dashboard for auto-deploy on push.
|
| 10 |
+
|
| 11 |
+
[build]
|
| 12 |
+
builder = "DOCKERFILE"
|
| 13 |
+
dockerfilePath = "Dockerfile"
|
| 14 |
+
|
| 15 |
+
[deploy]
|
| 16 |
+
startCommand = "python3 -m uvicorn api.main:app --host 0.0.0.0 --port $PORT --workers 1"
|
| 17 |
+
healthcheckPath = "/health"
|
| 18 |
+
healthcheckTimeout = 30
|
| 19 |
+
restartPolicyType = "ON_FAILURE"
|
| 20 |
+
restartPolicyMaxRetries = 3
|
| 21 |
+
|
| 22 |
+
[environments.production.variables]
|
| 23 |
+
SPACY_MODEL = "/app/en_model"
|
| 24 |
+
PYTHONUNBUFFERED = "1"
|
git_ms_code/render.yaml
ADDED
|
@@ -0,0 +1,28 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# ββ NeuroCheck v8.0 β Render Deployment Config βββββββββββββββββββββββββββββββ
|
| 2 |
+
# Deploy to Render: https://render.com
|
| 3 |
+
# Steps:
|
| 4 |
+
# 1. Push this folder to a GitHub repo
|
| 5 |
+
# 2. Go to render.com β New Web Service β Connect repo
|
| 6 |
+
# 3. Render auto-detects this file and configures everything
|
| 7 |
+
# 4. Free tier available (spins down after inactivity)
|
| 8 |
+
|
| 9 |
+
services:
|
| 10 |
+
- type: web
|
| 11 |
+
name: neurocheck-ms
|
| 12 |
+
runtime: docker
|
| 13 |
+
dockerfilePath: ./Dockerfile
|
| 14 |
+
plan: free # change to "starter" ($7/mo) for always-on
|
| 15 |
+
region: oregon # options: oregon, ohio, frankfurt, singapore
|
| 16 |
+
|
| 17 |
+
envVars:
|
| 18 |
+
- key: SPACY_MODEL
|
| 19 |
+
value: /app/en_model
|
| 20 |
+
- key: PYTHONUNBUFFERED
|
| 21 |
+
value: "1"
|
| 22 |
+
- key: PORT
|
| 23 |
+
value: "8000"
|
| 24 |
+
|
| 25 |
+
healthCheckPath: /health
|
| 26 |
+
|
| 27 |
+
# Auto-deploy on push to main branch
|
| 28 |
+
autoDeploy: true
|
git_ms_code/requirements.txt
ADDED
|
@@ -0,0 +1,44 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# NeuroCheck v9.1 - HuggingFace Spaces compatible
|
| 2 |
+
fastapi==0.135.2
|
| 3 |
+
uvicorn[standard]==0.42.0
|
| 4 |
+
python-multipart==0.0.20
|
| 5 |
+
starlette>=0.27.0
|
| 6 |
+
|
| 7 |
+
# NLP
|
| 8 |
+
spacy==3.8.13
|
| 9 |
+
negspacy==1.0.4
|
| 10 |
+
|
| 11 |
+
# Pydantic
|
| 12 |
+
pydantic==2.12.5
|
| 13 |
+
|
| 14 |
+
# Rate limiting + logging
|
| 15 |
+
slowapi==0.1.9
|
| 16 |
+
loguru==0.7.3
|
| 17 |
+
|
| 18 |
+
# Agentic AI
|
| 19 |
+
langchain
|
| 20 |
+
langchain-ollama
|
| 21 |
+
langchain-huggingface
|
| 22 |
+
langchain-community
|
| 23 |
+
langchain-core
|
| 24 |
+
langchain-text-splitters
|
| 25 |
+
langgraph
|
| 26 |
+
langgraph-prebuilt
|
| 27 |
+
|
| 28 |
+
# RAG
|
| 29 |
+
chromadb
|
| 30 |
+
sentence-transformers
|
| 31 |
+
|
| 32 |
+
# Document parsing
|
| 33 |
+
python-docx
|
| 34 |
+
|
| 35 |
+
# Report generation
|
| 36 |
+
reportlab
|
| 37 |
+
|
| 38 |
+
# Auth
|
| 39 |
+
python-jose[cryptography]
|
| 40 |
+
bcrypt
|
| 41 |
+
email-validator
|
| 42 |
+
|
| 43 |
+
# HuggingFace
|
| 44 |
+
huggingface-hub
|
git_ms_code/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))
|
git_ms_code/setup.py
ADDED
|
@@ -0,0 +1,270 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python3
|
| 2 |
+
"""
|
| 3 |
+
NeuroCheck v9.1 β Full Local Setup Script
|
| 4 |
+
==========================================
|
| 5 |
+
Run once before first launch:
|
| 6 |
+
python3 setup.py
|
| 7 |
+
|
| 8 |
+
What this does:
|
| 9 |
+
1. Checks Python version (needs 3.10+)
|
| 10 |
+
2. Creates / activates a virtual environment (.venv)
|
| 11 |
+
3. Installs ALL pip requirements
|
| 12 |
+
4. Builds the spaCy English model (en_model/)
|
| 13 |
+
5. Verifies NegEx pipeline
|
| 14 |
+
6. Initialises the SQLite database (neurocheck.db)
|
| 15 |
+
7. Checks Ollama + pulls llama3.1:8b if missing
|
| 16 |
+
8. Prints a ready summary + how to start the server
|
| 17 |
+
"""
|
| 18 |
+
from __future__ import annotations
|
| 19 |
+
import subprocess, sys, os, pathlib, json, textwrap, shutil, platform, urllib.request
|
| 20 |
+
|
| 21 |
+
ROOT = pathlib.Path(__file__).parent.resolve()
|
| 22 |
+
VENV = ROOT / ".venv"
|
| 23 |
+
DB = ROOT / "neurocheck.db"
|
| 24 |
+
MODEL = ROOT / "en_model"
|
| 25 |
+
ENV = ROOT / ".env"
|
| 26 |
+
|
| 27 |
+
# ββ colour helpers ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 28 |
+
def green(s): return f"\033[92m{s}\033[0m"
|
| 29 |
+
def red(s): return f"\033[91m{s}\033[0m"
|
| 30 |
+
def yellow(s): return f"\033[93m{s}\033[0m"
|
| 31 |
+
def bold(s): return f"\033[1m{s}\033[0m"
|
| 32 |
+
def cyan(s): return f"\033[96m{s}\033[0m"
|
| 33 |
+
|
| 34 |
+
def header(msg):
|
| 35 |
+
print(f"\n{bold(cyan('ββ'))} {bold(msg)}")
|
| 36 |
+
|
| 37 |
+
def ok(msg): print(f" {green('β')} {msg}")
|
| 38 |
+
def warn(msg): print(f" {yellow('β ')} {msg}")
|
| 39 |
+
def fail(msg): print(f" {red('β')} {msg}")
|
| 40 |
+
def step(msg): print(f" {cyan('β')} {msg}")
|
| 41 |
+
|
| 42 |
+
def run(cmd, *, cwd=None, capture=False, check=True):
|
| 43 |
+
r = subprocess.run(cmd, cwd=cwd or ROOT,
|
| 44 |
+
capture_output=capture,
|
| 45 |
+
text=True)
|
| 46 |
+
if check and r.returncode != 0:
|
| 47 |
+
fail(f"Command failed: {' '.join(str(c) for c in cmd)}")
|
| 48 |
+
if capture:
|
| 49 |
+
print(r.stderr or r.stdout)
|
| 50 |
+
sys.exit(1)
|
| 51 |
+
return r
|
| 52 |
+
|
| 53 |
+
# ββ Resolve python inside venv ββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 54 |
+
def venv_python():
|
| 55 |
+
if platform.system() == "Windows":
|
| 56 |
+
return VENV / "Scripts" / "python.exe"
|
| 57 |
+
return VENV / "bin" / "python"
|
| 58 |
+
|
| 59 |
+
def venv_pip():
|
| 60 |
+
return [str(venv_python()), "-m", "pip"]
|
| 61 |
+
|
| 62 |
+
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 63 |
+
# STEP 0 β Python version check
|
| 64 |
+
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 65 |
+
header("Step 0 Β· Python version check")
|
| 66 |
+
major, minor = sys.version_info.major, sys.version_info.minor
|
| 67 |
+
if major < 3 or (major == 3 and minor < 10):
|
| 68 |
+
fail(f"Python 3.10+ required. You have {major}.{minor}.")
|
| 69 |
+
fail("Download from https://python.org/downloads")
|
| 70 |
+
sys.exit(1)
|
| 71 |
+
ok(f"Python {major}.{minor} β")
|
| 72 |
+
|
| 73 |
+
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 74 |
+
# STEP 1 β Virtual environment
|
| 75 |
+
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 76 |
+
header("Step 1 Β· Virtual environment")
|
| 77 |
+
if VENV.exists():
|
| 78 |
+
ok(f".venv already exists at {VENV}")
|
| 79 |
+
else:
|
| 80 |
+
step("Creating .venv β¦")
|
| 81 |
+
run([sys.executable, "-m", "venv", str(VENV)])
|
| 82 |
+
ok(".venv created")
|
| 83 |
+
|
| 84 |
+
PY = str(venv_python())
|
| 85 |
+
step(f"Using Python: {PY}")
|
| 86 |
+
|
| 87 |
+
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 88 |
+
# STEP 2 β Install requirements
|
| 89 |
+
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 90 |
+
header("Step 2 Β· Install Python dependencies")
|
| 91 |
+
|
| 92 |
+
req_file = ROOT / "requirements.txt"
|
| 93 |
+
if not req_file.exists():
|
| 94 |
+
fail("requirements.txt not found"); sys.exit(1)
|
| 95 |
+
|
| 96 |
+
step("Upgrading pip β¦")
|
| 97 |
+
run(venv_pip() + ["install", "--quiet", "--upgrade", "pip"])
|
| 98 |
+
ok("pip upgraded")
|
| 99 |
+
|
| 100 |
+
step("Installing requirements (this may take 3-8 minutes first time) β¦")
|
| 101 |
+
run(venv_pip() + ["install", "--quiet", "-r", str(req_file)])
|
| 102 |
+
ok("All requirements installed β")
|
| 103 |
+
|
| 104 |
+
# ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββοΏ½οΏ½οΏ½ββββββββββββββββ
|
| 105 |
+
# STEP 3 β Build spaCy model
|
| 106 |
+
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 107 |
+
header("Step 3 Β· spaCy English model")
|
| 108 |
+
if MODEL.exists() and (MODEL / "config.cfg").exists():
|
| 109 |
+
ok(f"Model already built at {MODEL}")
|
| 110 |
+
else:
|
| 111 |
+
step("Building blank spaCy English model β¦")
|
| 112 |
+
script = textwrap.dedent(f"""
|
| 113 |
+
import spacy
|
| 114 |
+
from spacy.lang.en import English
|
| 115 |
+
from pathlib import Path
|
| 116 |
+
nlp = English()
|
| 117 |
+
nlp.add_pipe('sentencizer')
|
| 118 |
+
out = Path(r'{MODEL}')
|
| 119 |
+
out.mkdir(parents=True, exist_ok=True)
|
| 120 |
+
nlp.to_disk(str(out))
|
| 121 |
+
print('Model saved to', out)
|
| 122 |
+
""")
|
| 123 |
+
run([PY, "-c", script])
|
| 124 |
+
ok("spaCy model built β")
|
| 125 |
+
|
| 126 |
+
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 127 |
+
# STEP 4 β Verify NegEx
|
| 128 |
+
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 129 |
+
header("Step 4 Β· Verify NegEx pipeline")
|
| 130 |
+
script = textwrap.dedent(f"""
|
| 131 |
+
import spacy
|
| 132 |
+
from negspacy.termsets import termset
|
| 133 |
+
from negspacy.negation import Negex
|
| 134 |
+
nlp = spacy.load(r'{MODEL}')
|
| 135 |
+
ts = termset('en_clinical')
|
| 136 |
+
nlp.add_pipe('negex', config={{'ent_types': ['SYMPTOM'], 'neg_termset': ts.get_patterns()}})
|
| 137 |
+
print('NegEx OK')
|
| 138 |
+
""")
|
| 139 |
+
r = run([PY, "-c", script], capture=True, check=False)
|
| 140 |
+
if "NegEx OK" in (r.stdout or ""):
|
| 141 |
+
ok("NegEx pipeline verified β")
|
| 142 |
+
else:
|
| 143 |
+
warn(f"NegEx warning: {r.stderr.strip()[:200]}")
|
| 144 |
+
warn("App will still run β NegEx may degrade negation detection")
|
| 145 |
+
|
| 146 |
+
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 147 |
+
# STEP 5 β .env file
|
| 148 |
+
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 149 |
+
header("Step 5 Β· Environment file (.env)")
|
| 150 |
+
if not ENV.exists():
|
| 151 |
+
warn(".env not found β creating from defaults")
|
| 152 |
+
import shutil as _sh
|
| 153 |
+
example = ROOT / ".env.example"
|
| 154 |
+
if example.exists():
|
| 155 |
+
_sh.copy(example, ENV)
|
| 156 |
+
else:
|
| 157 |
+
ENV.write_text(
|
| 158 |
+
"SPACY_MODEL=en_model\nNEUROCHECK_DB=neurocheck.db\n"
|
| 159 |
+
"JWT_SECRET=CHANGE_THIS\nJWT_EXPIRE_MINUTES=10080\n"
|
| 160 |
+
"HOST=0.0.0.0\nPORT=8000\nWORKERS=1\n",
|
| 161 |
+
encoding="utf-8",
|
| 162 |
+
)
|
| 163 |
+
warn(f"Edit {ENV} and set a real JWT_SECRET!")
|
| 164 |
+
else:
|
| 165 |
+
env_text = ENV.read_text(encoding="utf-8")
|
| 166 |
+
if "CHANGE_THIS" in env_text:
|
| 167 |
+
warn(f".env exists but JWT_SECRET is still the placeholder!")
|
| 168 |
+
warn(" Open .env and set: JWT_SECRET=<your random string>")
|
| 169 |
+
warn(" Generate one: python3 -c \"import secrets; print(secrets.token_hex(32))\"")
|
| 170 |
+
else:
|
| 171 |
+
ok(".env configured β")
|
| 172 |
+
|
| 173 |
+
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 174 |
+
# STEP 6 β Initialise SQLite database
|
| 175 |
+
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 176 |
+
header("Step 6 Β· SQLite database")
|
| 177 |
+
|
| 178 |
+
# Load .env vars so database.py sees NEUROCHECK_DB
|
| 179 |
+
for line in ENV.read_text(encoding="utf-8").splitlines():
|
| 180 |
+
line = line.strip()
|
| 181 |
+
if line and not line.startswith("#") and "=" in line:
|
| 182 |
+
k, _, v = line.partition("=")
|
| 183 |
+
os.environ.setdefault(k.strip(), v.strip())
|
| 184 |
+
|
| 185 |
+
db_path = ROOT / os.environ.get("NEUROCHECK_DB", "neurocheck.db")
|
| 186 |
+
step(f"Database path: {db_path}")
|
| 187 |
+
|
| 188 |
+
script = textwrap.dedent(f"""
|
| 189 |
+
import sys, os
|
| 190 |
+
sys.path.insert(0, r'{ROOT}')
|
| 191 |
+
os.environ['NEUROCHECK_DB'] = r'{db_path}'
|
| 192 |
+
from api.database import init_db
|
| 193 |
+
init_db()
|
| 194 |
+
print('DB_OK')
|
| 195 |
+
""")
|
| 196 |
+
r = run([PY, "-c", script], capture=True, check=False)
|
| 197 |
+
if "DB_OK" in (r.stdout or ""):
|
| 198 |
+
ok(f"Database initialised: {db_path} β")
|
| 199 |
+
# Show table info
|
| 200 |
+
import sqlite3
|
| 201 |
+
if db_path.exists():
|
| 202 |
+
with sqlite3.connect(str(db_path)) as conn:
|
| 203 |
+
tables = conn.execute("SELECT name FROM sqlite_master WHERE type='table'").fetchall()
|
| 204 |
+
for (t,) in tables:
|
| 205 |
+
count = conn.execute(f"SELECT COUNT(*) FROM {t}").fetchone()[0]
|
| 206 |
+
ok(f" Table '{t}': {count} rows")
|
| 207 |
+
else:
|
| 208 |
+
fail(f"Database init failed:\n{r.stderr.strip()[:500]}")
|
| 209 |
+
sys.exit(1)
|
| 210 |
+
|
| 211 |
+
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 212 |
+
# STEP 7 β Ollama check
|
| 213 |
+
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 214 |
+
header("Step 7 Β· Ollama & LLM model")
|
| 215 |
+
|
| 216 |
+
ollama_bin = shutil.which("ollama")
|
| 217 |
+
if not ollama_bin:
|
| 218 |
+
warn("Ollama not found in PATH.")
|
| 219 |
+
warn("Download + install from: https://ollama.com/download")
|
| 220 |
+
warn("Then run: ollama pull llama3.1:8b")
|
| 221 |
+
warn("The app will start but /chat will fail until Ollama is running.")
|
| 222 |
+
else:
|
| 223 |
+
ok(f"Ollama found: {ollama_bin}")
|
| 224 |
+
# Check if server running
|
| 225 |
+
try:
|
| 226 |
+
with urllib.request.urlopen("http://localhost:11434/api/tags", timeout=3) as resp:
|
| 227 |
+
tags = json.loads(resp.read())
|
| 228 |
+
models = [m["name"] for m in tags.get("models", [])]
|
| 229 |
+
if any("llama3.1" in m for m in models):
|
| 230 |
+
ok(f"llama3.1 model present β")
|
| 231 |
+
else:
|
| 232 |
+
warn("llama3.1:8b not pulled yet.")
|
| 233 |
+
step("Pulling llama3.1:8b (β4.7 GB) β this runs in background β¦")
|
| 234 |
+
subprocess.Popen(["ollama", "pull", "llama3.1:8b"])
|
| 235 |
+
warn("Pull started in background. Wait for it before using /chat.")
|
| 236 |
+
except Exception:
|
| 237 |
+
warn("Ollama is installed but not running.")
|
| 238 |
+
warn("Start it with: ollama serve")
|
| 239 |
+
warn("Then pull model: ollama pull llama3.1:8b")
|
| 240 |
+
|
| 241 |
+
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 242 |
+
# FINAL SUMMARY
|
| 243 |
+
# βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 244 |
+
print(f"""
|
| 245 |
+
{bold(green('ββββββββββββββββββββββββββββββββββββββββββββββββββ'))}
|
| 246 |
+
{bold(green(' NeuroCheck setup complete!'))}
|
| 247 |
+
{bold(green('ββββββββββββββββββββββββββββββββββββββββββββββββββ'))}
|
| 248 |
+
|
| 249 |
+
{bold('To start the server:')}
|
| 250 |
+
|
| 251 |
+
{cyan('# Option A β using the venv directly (recommended)')}
|
| 252 |
+
{yellow('.venv/bin/python -m uvicorn api.main:app --host 0.0.0.0 --port 8000 --reload')}
|
| 253 |
+
|
| 254 |
+
{cyan('# Option B β using the setup script')}
|
| 255 |
+
{yellow('.venv/bin/python scripts/setup_and_run.py')}
|
| 256 |
+
|
| 257 |
+
{bold('Once running, open:')}
|
| 258 |
+
π http://localhost:8000 β MS Symptom Classifier
|
| 259 |
+
π¬ http://localhost:8000/chat-ui β AI Chat (login required)
|
| 260 |
+
π http://localhost:8000/docs β API docs (Swagger UI)
|
| 261 |
+
|
| 262 |
+
{bold('Database:')}
|
| 263 |
+
π {db_path}
|
| 264 |
+
Tables: users Β· chat_sessions Β· messages
|
| 265 |
+
|
| 266 |
+
{bold('Before first user login:')}
|
| 267 |
+
Open .env and change JWT_SECRET to a real secret.
|
| 268 |
+
Generate one:
|
| 269 |
+
{yellow("python3 -c \"import secrets; print(secrets.token_hex(32))\"")}
|
| 270 |
+
""")
|
git_ms_code/start.py
ADDED
|
@@ -0,0 +1,70 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python3
|
| 2 |
+
"""
|
| 3 |
+
NeuroCheck v9.1 β Start Server
|
| 4 |
+
================================
|
| 5 |
+
Run after setup.py:
|
| 6 |
+
python3 start.py
|
| 7 |
+
python3 start.py --port 8080
|
| 8 |
+
python3 start.py --workers 2
|
| 9 |
+
"""
|
| 10 |
+
from __future__ import annotations
|
| 11 |
+
import argparse, os, pathlib, subprocess, sys
|
| 12 |
+
|
| 13 |
+
ROOT = pathlib.Path(__file__).parent.resolve()
|
| 14 |
+
ENV = ROOT / ".env"
|
| 15 |
+
VENV = ROOT / ".venv"
|
| 16 |
+
|
| 17 |
+
# Load .env
|
| 18 |
+
if ENV.exists():
|
| 19 |
+
for line in ENV.read_text(encoding="utf-8").splitlines():
|
| 20 |
+
line = line.strip()
|
| 21 |
+
if line and not line.startswith("#") and "=" in line:
|
| 22 |
+
k, _, v = line.partition("=")
|
| 23 |
+
os.environ.setdefault(k.strip(), v.strip())
|
| 24 |
+
|
| 25 |
+
# Warn about placeholder secret
|
| 26 |
+
if os.environ.get("JWT_SECRET", "CHANGE") in ("CHANGE_THIS_TO_A_LONG_RANDOM_SECRET_BEFORE_RUNNING", "CHANGE_THIS", "CHANGE"):
|
| 27 |
+
print("\033[93mβ JWT_SECRET is still the placeholder! Edit .env before storing real data.\033[0m")
|
| 28 |
+
|
| 29 |
+
# Decide which python to use
|
| 30 |
+
def best_python():
|
| 31 |
+
candidates = [VENV / "bin" / "python", VENV / "Scripts" / "python.exe", pathlib.Path(sys.executable)]
|
| 32 |
+
for p in candidates:
|
| 33 |
+
if p.exists():
|
| 34 |
+
return str(p)
|
| 35 |
+
return sys.executable
|
| 36 |
+
|
| 37 |
+
parser = argparse.ArgumentParser(description="Start NeuroCheck server")
|
| 38 |
+
parser.add_argument("--host", default=os.environ.get("HOST", "0.0.0.0"))
|
| 39 |
+
parser.add_argument("--port", default=int(os.environ.get("PORT", 8000)), type=int) # HF uses 7860
|
| 40 |
+
parser.add_argument("--workers", default=int(os.environ.get("WORKERS", 1)), type=int)
|
| 41 |
+
parser.add_argument("--reload", action="store_true", default=True, help="Auto-reload on code change (dev mode)")
|
| 42 |
+
parser.add_argument("--no-reload", dest="reload", action="store_false")
|
| 43 |
+
args = parser.parse_args()
|
| 44 |
+
|
| 45 |
+
py = best_python()
|
| 46 |
+
cmd = [
|
| 47 |
+
py, "-m", "uvicorn", "api.main:app",
|
| 48 |
+
"--host", args.host,
|
| 49 |
+
"--port", str(args.port),
|
| 50 |
+
"--workers", str(args.workers),
|
| 51 |
+
"--log-level", os.environ.get("LOG_LEVEL", "info").lower(),
|
| 52 |
+
]
|
| 53 |
+
if args.reload and args.workers == 1:
|
| 54 |
+
cmd.append("--reload")
|
| 55 |
+
|
| 56 |
+
print(f"""
|
| 57 |
+
\033[96mββ NeuroCheck v9.1 ββββββββββββββββββββββββββ\033[0m
|
| 58 |
+
\033[1mClassifier :\033[0m http://localhost:{args.port}
|
| 59 |
+
\033[1mChat UI :\033[0m http://localhost:{args.port}/chat-ui
|
| 60 |
+
\033[1mAPI Docs :\033[0m http://localhost:{args.port}/docs
|
| 61 |
+
\033[1mWorkers :\033[0m {args.workers}
|
| 62 |
+
\033[1mReload :\033[0m {args.reload and args.workers == 1}
|
| 63 |
+
\033[96mβββββββββββββββββββββββββββββββββββββββββββββ\033[0m
|
| 64 |
+
""")
|
| 65 |
+
|
| 66 |
+
os.environ["SPACY_MODEL"] = str(ROOT / os.environ.get("SPACY_MODEL", "en_model"))
|
| 67 |
+
os.environ["NEUROCHECK_DB"] = str(ROOT / os.environ.get("NEUROCHECK_DB", "neurocheck.db"))
|
| 68 |
+
|
| 69 |
+
os.chdir(ROOT)
|
| 70 |
+
os.execv(py, cmd)
|