ZeroNinerOne commited on
Commit
a4f8c46
Β·
verified Β·
1 Parent(s): bc642b6

Upload 14 files

Browse files
Files changed (14) hide show
  1. .env +25 -0
  2. .env.example +16 -0
  3. .gitignore +23 -0
  4. Dockerfile +28 -0
  5. README.md +18 -4
  6. README_SETUP.md +199 -0
  7. build_spacy.py +8 -0
  8. docker-compose.yml +61 -0
  9. make_admin.py +26 -0
  10. railway.toml +24 -0
  11. render.yaml +28 -0
  12. requirements.txt +44 -0
  13. setup.py +270 -0
  14. start.py +70 -0
.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=CHANGE_THIS_TO_A_LONG_RANDOM_SECRET_BEFORE_RUNNING
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
.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
.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
Dockerfile ADDED
@@ -0,0 +1,28 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ FROM python:3.12-slim
2
+
3
+ RUN apt-get update && apt-get install -y gcc g++ git && rm -rf /var/lib/apt/lists/*
4
+
5
+ WORKDIR /app
6
+
7
+ COPY requirements.txt .
8
+ RUN pip install --no-cache-dir -r requirements.txt
9
+
10
+ COPY . .
11
+
12
+ RUN python3 build_spacy.py
13
+
14
+ # /data = HuggingFace persistent storage bucket (mounted at runtime)
15
+ # Everything user-related lives here and NEVER gets deleted on restart
16
+ RUN mkdir -p /data/db /data/chroma /data/backups
17
+
18
+ ENV PORT=7860
19
+ ENV HOST=0.0.0.0
20
+ ENV WORKERS=1
21
+ ENV SPACY_MODEL=/app/en_model
22
+ ENV NEUROCHECK_DB=/data/db/neurocheck.db
23
+ ENV CHROMA_DB_PATH=/data/chroma
24
+ ENV PYTHONPATH=/app
25
+
26
+ EXPOSE 7860
27
+
28
+ CMD ["python3", "-m", "uvicorn", "api.main:app", "--host", "0.0.0.0", "--port", "7860", "--app-dir", "/app"]
README.md CHANGED
@@ -1,10 +1,24 @@
1
  ---
2
  title: AxonIQ Testing
3
- emoji: ⚑
4
- colorFrom: pink
5
- colorTo: gray
6
  sdk: docker
7
  pinned: false
 
 
8
  ---
9
 
10
- Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference
 
 
 
 
 
 
 
 
 
 
 
 
 
1
  ---
2
  title: AxonIQ Testing
3
+ emoji: 🧠
4
+ colorFrom: blue
5
+ colorTo: indigo
6
  sdk: docker
7
  pinned: false
8
+ license: mit
9
+ short_description: AI-Powered MS Diagnostic Assistant
10
  ---
11
 
12
+ # AxonIQ β€” AI-Powered MS Diagnostic Assistant
13
+
14
+ **Testing Space** β€” Development and testing environment.
15
+
16
+ **Features:**
17
+ - MS symptom classifier with NegEx negation detection
18
+ - Agentic AI chat with LangGraph + LLM
19
+ - RAG knowledge base (ChromaDB + sentence-transformers)
20
+ - JWT auth with session history
21
+ - Live risk panel
22
+ - Admin panel with user logs
23
+
24
+ **Built by:** Dr. Avasarala (UKY) Β· Dr. Kadambari (NITW)
README_SETUP.md ADDED
@@ -0,0 +1,199 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ ```
build_spacy.py ADDED
@@ -0,0 +1,8 @@
 
 
 
 
 
 
 
 
 
1
+ from pathlib import Path
2
+ import spacy
3
+ from spacy.lang.en import English
4
+ nlp = English()
5
+ nlp.add_pipe("sentencizer")
6
+ Path("en_model").mkdir(exist_ok=True)
7
+ nlp.to_disk("en_model")
8
+ print("spaCy model built OK")
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"
make_admin.py ADDED
@@ -0,0 +1,26 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Run this once to grant admin access to your account:
3
+ python make_admin.py YOUR_USERNAME
4
+
5
+ On HuggingFace β€” add this as a startup command or run it via the Space terminal.
6
+ """
7
+ import sys, os
8
+ os.environ.setdefault("NEUROCHECK_DB", "neurocheck.db")
9
+
10
+ from api.database import init_db, set_admin, migrate_add_admin_column, get_user_by_username
11
+
12
+ username = sys.argv[1] if len(sys.argv) > 1 else os.environ.get("ADMIN_USERNAME", "")
13
+ if not username:
14
+ print("Usage: python make_admin.py YOUR_USERNAME")
15
+ sys.exit(1)
16
+
17
+ init_db()
18
+ migrate_add_admin_column()
19
+
20
+ user = get_user_by_username(username)
21
+ if not user:
22
+ print(f"User '{username}' not found. Register first at /chat-ui then run this.")
23
+ sys.exit(1)
24
+
25
+ ok = set_admin(username, True)
26
+ print(f"{'βœ…' if ok else '❌'} Admin access {'granted to' if ok else 'failed for'} '{username}'")
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"
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
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
setup.py ADDED
@@ -0,0 +1,270 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ """)
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)