LiamKhoaLe commited on
Commit
ad276ed
·
1 Parent(s): 3c1ba50

Upd README

Browse files
Files changed (2) hide show
  1. README.md +112 -299
  2. UI_SETUP.md +147 -0
README.md CHANGED
@@ -13,337 +13,150 @@ app_port: 7860
13
 
14
  # Medical AI Assistant
15
 
16
- A sophisticated AI-powered medical chatbot system with ChatGPT-like UI, multi-user support, session management, and medical context awareness.
17
 
18
- ## 🚀 Features
19
 
20
- ### Core Functionality
21
- - **AI-Powered Medical Chat**: Intelligent responses to medical questions using advanced language models
22
- - **Multi-User Support**: Individual user profiles with role-based customization (Physician, Nurse, Medical Student, etc.)
23
- - **Chat Session Management**: Multiple concurrent chat sessions per user with persistent history
24
- - **Medical Context Memory**: LRU-based memory system that maintains conversation context and medical history
25
- - **API Key Rotation**: Dynamic rotation of Gemini API keys for reliability and rate limit management
 
 
 
26
 
27
- ### User Interface
28
- - **ChatGPT-like Design**: Familiar, intuitive interface optimized for medical professionals
29
- - **Responsive Design**: Works seamlessly on desktop, tablet, and mobile devices
30
- - **Dark/Light Theme**: Automatic theme switching with system preference detection
31
- - **Real-time Chat**: Smooth, responsive chat experience with typing indicators
32
- - **Session Management**: Easy navigation between different chat sessions
33
 
34
  ### Medical Features
35
- - **Medical Knowledge Base**: Built-in medical information for common symptoms, conditions, and medications
36
- - **Context Awareness**: Remembers previous conversations and provides relevant medical context
 
 
37
  - **Role-Based Responses**: Tailored responses based on user's medical role and specialty
38
  - **Medical Disclaimers**: Appropriate warnings and disclaimers for medical information
39
- - **Export Functionality**: Export chat sessions for medical records or educational purposes
 
40
 
41
- ## ✨ Recent Updates (Mongo-backed memory & patient context)
42
- - **Long-term memory in MongoDB**: Up to 20 latest QA summaries per patient are persisted for RAG continuity.
43
- - **Short-term cache**: Last 3 summaries are kept in an in-memory LRU for immediate context.
44
- - **Chat history persistence**: All chat messages are stored in MongoDB per session.
45
- - **Patient/Doctor context**:
46
- - Frontend sidebar now includes a Patient ID input (8 digits).
47
- - Backend accepts `patient_id` and `doctor_id` and saves data per patient with assigned doctor.
48
- - **Context retrieval**: Combines short-term cache (3) with long-term Mongo (20) for robust continuity.
49
 
50
- ## 🏗️ Architecture
 
 
51
 
52
- ### Core Components
53
- ```
54
- MedicalDiagnosisSystem/
55
- ├── app.py # FastAPI main application
56
- ├── memo/
57
- │ ├── memory.py # Enhanced LRU memory system
58
- │ └── history.py # Medical history manager
59
- ├── utils/
60
- │ ├── rotator.py # API key rotation system
61
- │ ├── embeddings.py # Embedding client with fallback
62
- │ └── logger.py # Structured logging
63
- └── static/
64
- ├── index.html # Main UI
65
- ├── styles.css # Styling
66
- └── app.js # Frontend logic
67
- ```
68
-
69
- ### Memory System
70
- - **User Profiles**: Persistent user data with preferences and roles
71
- - **Chat Sessions**: Individual conversation threads with message history
72
- - **Medical Context**: QA summaries stored in LRU cache for quick retrieval
73
- - **Semantic Search**: Embedding-based similarity search for relevant medical information
74
-
75
- ### API Integration
76
- - **Gemini API**: Google's advanced language model for medical responses
77
- - **Key Rotation**: Automatic rotation on rate limits or errors
78
- - **Fallback Support**: Graceful degradation when external APIs are unavailable
79
-
80
- ## 🛠️ Installation
81
 
82
  ### Prerequisites
83
- - Python 3.8+
84
- - pip package manager
85
- - Modern web browser
86
 
87
  ### Setup
88
- 1. **Clone the repository**
89
- ```bash
90
- git clone <repository-url>
91
- cd MedicalDiagnosisSystem
92
- ```
93
-
94
- 2. **Install dependencies**
95
- ```bash
96
- pip install -r requirements.txt
97
- ```
98
-
99
- 3. **Set environment variables**
100
- ```bash
101
- # Create .env file
102
- echo "GEMINI_API_1=your_gemini_api_key_1" > .env
103
- echo "GEMINI_API_2=your_gemini_api_key_2" >> .env
104
- echo "GEMINI_API_3=your_gemini_api_key_3" >> .env
105
- # MongoDB (required for persistence)
106
- echo "MONGO_USER=your_mongodb_connection_string" >> .env
107
- # Optional: override DB name (default: medicaldiagnosissystem)
108
- echo "MONGO_DB=medicaldiagnosissystem" >> .env
109
- ```
110
-
111
- 4. **Run the application**
112
- ```bash
113
- python app.py
114
- ```
115
-
116
- 5. **Access the UI**
117
- Open your browser and navigate to `http://localhost:8000`
118
-
119
- ## 🔧 Configuration
120
-
121
- ### Environment Variables
122
- - `GEMINI_API_1` through `GEMINI_API_5`: Gemini API keys for rotation
123
- - `MONGO_USER`: MongoDB connection string (Atlas or local)
124
- - `MONGO_DB`: MongoDB database name (default: `medicaldiagnosissystem`)
125
- - `LOG_LEVEL`: Logging level (DEBUG, INFO, WARNING, ERROR)
126
- - `PORT`: Server port (default: 8000)
127
-
128
- ### Memory Settings
129
- - **LRU Capacity (short-term cache)**: Default 3 QA summaries per patient/user (fast context)
130
- - **Long-term Memory**: Up to 20 persisted summaries per patient in MongoDB
131
- - **Max Sessions**: Default 20 sessions per user
132
 
133
- ### Embedding Model
134
- - **Default Model**: `all-MiniLM-L6-v2` (384 dimensions)
135
- - **Fallback Mode**: Hash-based embeddings when model unavailable
136
- - **GPU Support**: Optional CUDA acceleration for embeddings
 
137
 
138
  ## 📱 Usage
139
-
140
- ### Getting Started
141
- 1. **Access the Application**: Navigate to the provided URL
142
- 2. **Create User Profile**: Click on your profile to set name, role, and specialty
143
- 3. **Select Patient**: Enter an 8-digit Patient ID in the sidebar and press the patient icon or Enter
144
- 4. **Start New Chat**: Click "New Chat" to begin a conversation
145
- 5. **Ask Medical Questions**: Type your medical queries in natural language
146
- 6. **Manage Sessions**: Use the sidebar to switch between different chat sessions
147
-
148
- ### User Roles
149
- - **Physician**: Full medical context with clinical guidance
150
- - **Nurse**: Nursing-focused responses and care instructions
151
- - **Medical Student**: Educational content with learning objectives
152
- - **Healthcare Professional**: General medical information
153
- - **Patient**: Educational content with appropriate disclaimers
154
-
155
- ### Features
156
- - **Real-time Chat**: Instant responses with typing indicators
157
- - **Session Export**: Download chat history as JSON files
158
- - **Context Memory**: System remembers previous conversations
159
- - **Medical Disclaimers**: Appropriate warnings for medical information
160
- - **Responsive Design**: Works on all device sizes
161
-
162
- ## 🔌 API Endpoints (selected)
163
- - `POST /chat`
164
- - Body: `{ user_id, patient_id, doctor_id, session_id, message, user_role?, user_specialty?, title? }`
165
- - Returns: `{ response, session_id, timestamp, medical_context? }`
166
- - `POST /sessions`
167
- - Body: `{ user_id, patient_id, doctor_id, title? }`
168
- - Returns: `{ session_id }`
169
- - `GET /patients/{patient_id}/sessions`: List sessions for a patient (Mongo)
170
- - `GET /sessions/{session_id}/messages`: List messages in a session (Mongo)
171
-
172
- ## 🔒 Security & Privacy
173
-
174
- ### Data Protection
175
- - **MongoDB Persistence**: Chat history and long-term memory are stored in MongoDB keyed by `patient_id` with `doctor_id` attribution.
176
- - **Local Storage (UI)**: The sidebar may cache view state locally for UX; authoritative history is in MongoDB.
177
- - **PII Handling**: Ensure no sensitive PHI is logged; configure Mongo access securely.
178
- - **Medical Disclaimers**: Clear warnings about information limitations
179
-
180
- ### API Security
181
- - **Key Rotation**: Automatic API key rotation for security
182
- - **Rate Limiting**: Built-in protection against API abuse
183
- - **Error Handling**: Graceful degradation on API failures
184
-
185
- ## 🧪 Development
186
-
187
- ### Local Development
188
  ```bash
189
- # Install development dependencies
190
  pip install -r requirements.txt
191
-
192
- # Run with auto-reload
193
- python app.py
194
-
195
- # Run tests
196
- pytest
197
-
198
- # Format code
199
- black .
200
-
201
- # Lint code
202
- flake8
203
  ```
204
 
205
  ### Project Structure
206
  ```
207
- medical_diagnosis_system/
208
- ├── scripts/
209
- │ └── download_model.py # Model downloading script
210
  ├── src/
211
  │ ├── api/
212
- │ │ └── routes/ # API endpoint handlers
213
- │ │ ├── chat.py
214
- │ │ ├── session.py
215
- │ │ ├── static.py
216
- │ │ ├── system.py
217
- │ │ └── user.py
218
  │ ├── core/
219
- │ │ ├── memory/ # Memory management
220
- │ │ │ ├── memory.py
221
- │ │ │ └── history.py
222
- │ │ └── state.py # Application state management
223
- │ ├── domain/
224
- │ │ └── knowledge/ # Domain-specific knowledge
225
- │ └── medical_kb.py
226
- │ ├── models/ # Data models
227
  │ │ ├── chat.py
228
  │ │ └── user.py
229
- │ ├── services/ # Business logic services
230
- │ │ ├── medical_response.py
231
- │ │ └── summariser.py
232
- │ ├── utils/ # Utility functions
233
- │ │ ├── __init__.py
234
  │ │ ├── embeddings.py
235
  │ │ ├── logger.py
236
- │ │ ├── naming.py
237
  │ │ └── rotator.py
238
- main.py # Application entry point
239
- ├── static/ # Frontend assets
240
- │ ├── js/
241
- │ │ ├── app.js
242
- │ │ └── health.js
243
  │ ├── css/
244
- │ │ └── styles.css
245
- ├── health.html
246
- │ ├── icon.svg
247
- └── index.html
248
- ├── .dockerignore
249
- ├── .gitattributes
250
- ├── .gitignore
251
- ├── docker-compose.yml
252
  ├── Dockerfile
253
- ├── LICENSE # Project license
254
- ├── README.md # Project documentation
255
- ├── requirements.txt # Production dependencies
256
- ├── requirements-dev.txt # Development dependencies
257
- ├── SETUP_GUIDE.md # Detailed setup instructions
258
- └── start.py # Application launcher
259
- ```
260
-
261
- ### Adding New Features
262
- 1. **Backend**: Add/extend endpoints under `src/api/routes`
263
- 2. **Memory**: Extend cache logic in `src/core/memory/memory.py` and persistence in `src/data/mongodb.py`
264
- 3. **Frontend**: Update UI components in `static/` files
265
- 4. **Testing**: Add tests for new functionality
266
-
267
- ## 🚀 Deployment
268
-
269
- ### Production Considerations
270
- - **Environment Variables**: Secure API key and database management
271
- - **HTTPS**: Enable SSL/TLS for production
272
- - **Rate Limiting**: Implement request rate limiting
273
- - **Monitoring**: Add health checks and logging
274
- - **Database**: Ensure MongoDB backups and appropriate indexes
275
-
276
- ### Docker Deployment
277
- ```dockerfile
278
- FROM python:3.9-slim
279
- WORKDIR /app
280
- COPY requirements.txt .
281
- RUN pip install -r requirements.txt
282
- COPY . .
283
- EXPOSE 8000
284
- CMD ["python", "app.py"]
285
  ```
286
 
287
- ### Cloud Deployment
288
- - **AWS**: Deploy on EC2 or Lambda
289
- - **Google Cloud**: Use Cloud Run or App Engine
290
- - **Azure**: Deploy on App Service
291
- - **Heroku**: Simple deployment with Procfile
292
-
293
- ## 📊 Performance
294
-
295
- ### Optimization Features
296
- - **Lazy Loading**: Embedding models loaded on demand
297
- - **LRU Caching**: Efficient memory management
298
- - **API Rotation**: Load balancing across multiple API keys
299
- - **Fallback Modes**: Graceful degradation on failures
300
-
301
- ### Monitoring
302
- - **Health Checks**: `/health` endpoint for system status
303
- - **Resource Usage**: CPU and memory monitoring
304
- - **API Metrics**: Response times and success rates
305
- - **Error Tracking**: Comprehensive error logging
306
-
307
- ## 🤝 Contributing
308
-
309
- ### Development Guidelines
310
- 1. **Code Style**: Follow PEP 8 and use Black formatter
311
- 2. **Testing**: Add tests for new features
312
- 3. **Documentation**: Update README and docstrings
313
- 4. **Security**: Follow security best practices
314
- 5. **Performance**: Consider performance implications
315
-
316
- ### Pull Request Process
317
- 1. Fork the repository
318
- 2. Create a feature branch
319
- 3. Make your changes
320
- 4. Add tests and documentation
321
- 5. Submit a pull request
322
-
323
- ## 📄 License
324
-
325
- This project is licensed under the MIT License - see the LICENSE file for details.
326
-
327
- ## ⚠️ Disclaimer
328
-
329
- **Medical Information Disclaimer**: This application provides educational medical information only. It is not a substitute for professional medical advice, diagnosis, or treatment. Always consult with qualified healthcare professionals for medical decisions.
330
-
331
- **AI Limitations**: While this system uses advanced AI technology, it has limitations and should not be relied upon for critical medical decisions.
332
-
333
- ## 🆘 Support
334
-
335
- ### Getting Help
336
- - **Issues**: Report bugs via GitHub Issues
337
- - **Documentation**: Check this README and code comments
338
- - **Community**: Join discussions in GitHub Discussions
339
-
340
- ### Common Issues
341
- - **API Keys**: Ensure Gemini API keys are properly set
342
- - **Database**: Ensure `MONGO_USER` is configured and reachable
343
- - **Dependencies**: Verify all requirements are installed
344
- - **Port Conflicts**: Check if port 8000 is available
345
- - **Memory Issues**: Monitor system resources
346
-
347
- ---
348
-
349
- **Built with ❤️ for the medical community**
 
13
 
14
  # Medical AI Assistant
15
 
16
+ AI-powered medical chatbot with patient-centric memory, MongoDB persistence, and a fast, modern UI.
17
 
18
+ ## 🚀 Key Features
19
 
20
+ - Patient-centric RAG memory
21
+ - Short-term: last 3 QA summaries in in-memory LRU (fast context)
22
+ - Long-term: last 20 QA summaries per patient persisted in MongoDB (continuity)
23
+ - Chat history persistence per session in MongoDB
24
+ - Patient/Doctor context saved on all messages and summaries
25
+ - Patient search typeahead (name or ID) with instant session hydration
26
+ - Doctor dropdown with built‑in "Create doctor user..." flow
27
+ - Modern UI: sidebar sessions, modals (doctor, settings, patient profile), dark/light mode, mobile-friendly
28
+ - Model integration: Gemini responses, NVIDIA summariser fallback via key rotators
29
 
30
+ ## 🏗️ Architecture (high-level)
 
 
 
 
 
31
 
32
  ### Medical Features
33
+ - **Medical Knowledge Base**: Built-in medical information for common symptoms,
34
+ conditions, and medications
35
+ - **Context Awareness**: Remembers previous conversations and provides relevant medical
36
+ context
37
  - **Role-Based Responses**: Tailored responses based on user's medical role and specialty
38
  - **Medical Disclaimers**: Appropriate warnings and disclaimers for medical information
39
+ - **Export Functionality**: Export chat sessions for medical records or educational
40
+ purposes
41
 
42
+ Backend (FastAPI):
43
+ - `src/core/memory/memory.py`: LRU short‑term memory + sessions
44
+ - `src/core/memory/history.py`: builds context; writes memory/messages to Mongo
45
+ - `src/data/mongodb.py`: Mongo helpers (sessions, messages, memory, patients, search)
46
+ - `src/api/routes/`: `chat`, `session`, `user` (patients), `system`, `static`
 
 
 
47
 
48
+ Frontend (static):
49
+ - `static/index.html`, `static/css/styles.css`
50
+ - `static/js/app.js` (or modularized under `static/js/ui/*` and `static/js/chat/*` — see `UI_SETUP.md`)
51
 
52
+ ## 🛠️ Quick Start
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
53
 
54
  ### Prerequisites
55
+ - Python 3.11+
56
+ - pip
 
57
 
58
  ### Setup
59
+ 1. Clone and install
60
+ ```bash
61
+ git clone https://huggingface.co/spaces/MedAI-COS30018/MedicalDiagnosisSystem
62
+ cd MedAI
63
+ pip install -r requirements.txt
64
+ ```
65
+ 2. Configure environment
66
+ ```bash
67
+ # Create .env
68
+ echo "GEMINI_API_1=your_gemini_api_key_1" > .env
69
+ echo "NVIDIA_API_1=your_nvidia_api_key_1" >> .env
70
+ # MongoDB (required)
71
+ echo "MONGO_USER=your_mongodb_connection_string" >> .env
72
+ # Optional DB name (default: medicaldiagnosissystem)
73
+ echo "MONGO_DB=medicaldiagnosissystem" >> .env
74
+ ```
75
+ 3. Run
76
+ ```bash
77
+ python -m src.main
78
+ ```
79
+ Helpful: [UI SETUP](https://huggingface.co/spaces/MedAI-COS30018/MedicalDiagnosisSystem/blob/main/UI_SETUP.md) | [SETUP GUIDE](https://huggingface.co/spaces/MedAI-COS30018/MedicalDiagnosisSystem/blob/main/SETUP_GUIDE.md)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
80
 
81
+ ## 🔧 Config
82
+ - `GEMINI_API_1..5`, `NVIDIA_API_1..5`
83
+ - `MONGO_USER`, `MONGO_DB`
84
+ - `LOG_LEVEL`, `PORT`
85
+ - Memory: 3 short‑term, 20 long‑term
86
 
87
  ## 📱 Usage
88
+ 1. Select/create a doctor; set role/specialty.
89
+ 2. Search patient by name/ID; select a result.
90
+ 3. Start a new chat; ask your question.
91
+ 4. Manage sessions in the sidebar (rename/delete from menu).
92
+ 5. View patient profile and create/edit via modals/pages.
93
+
94
+ ## 🔌 Endpoints (selected)
95
+ - `POST /chat` `{ response, session_id, timestamp, medical_context? }`
96
+ - `POST /sessions` → `{ session_id }`
97
+ - `GET /patients/{patient_id}/sessions`
98
+ - `GET /sessions/{session_id}/messages`
99
+ - `GET /patients/search?q=term&limit=8`
100
+
101
+ ## 🔒 Data & Privacy
102
+ - MongoDB persistence keyed by `patient_id` with `doctor_id` attribution
103
+ - UI localStorage for UX (doctor list, preferences, selected patient)
104
+ - Avoid logging PHI; secure Mongo credentials
105
+
106
+ ## 🧪 Dev
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
107
  ```bash
 
108
  pip install -r requirements.txt
109
+ python -m src.main # run
110
+ pytest # tests
111
+ black . && flake8 # format + lint
 
 
 
 
 
 
 
 
 
112
  ```
113
 
114
  ### Project Structure
115
  ```
116
+ MedAI/
 
 
117
  ├── src/
118
  │ ├── api/
119
+ │ │ └── routes/
120
+ │ │ ├── chat.py # Chat endpoint
121
+ │ │ ├── session.py # Session endpoints
122
+ │ │ ├── user.py # Patient APIs (get/create/update/search)
123
+ │ │ ├── system.py # Health/info
124
+ │ │ └── static.py # Serve index
125
  │ ├── core/
126
+ │ │ ├── memory/
127
+ │ │ │ ├── memory.py # LRU short‑term memory + sessions
128
+ │ │ │ └── history.py # Context builder, persistence hooks
129
+ │ │ └── state.py # App state (rotators, embeddings, memory)
130
+ │ ├── data/
131
+ │ │ └── mongodb.py # Mongo helpers (sessions, messages, memory, patients)
132
+ ├── models/
 
133
  │ │ ├── chat.py
134
  │ │ └── user.py
135
+ │ ├── services/
136
+ │ │ ├── medical_response.py # Calls model(s)
137
+ │ │ └── summariser.py # Title/QA summarisation
138
+ │ ├── utils/
 
139
  │ │ ├── embeddings.py
140
  │ │ ├── logger.py
 
141
  │ │ └── rotator.py
142
+ └── main.py # FastAPI entrypoint
143
+ ├── static/
144
+ │ ├── index.html
 
 
145
  │ ├── css/
146
+ │ │ ├── styles.css
147
+ │ └── patient.css
148
+ │ ├── js/
149
+ │ ├── app.js # Submodules under /ui/* and /chat/*
150
+ │ │ └── patient.js
151
+ │ └── patient.html
152
+ ├── requirements.txt
153
+ ├── requirements-dev.txt
154
  ├── Dockerfile
155
+ ├── docker-compose.yml
156
+ ├── LICENSE
157
+ └── README.md
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
158
  ```
159
 
160
+ ## 🧾 License & Disclaimer
161
+ - MIT License (see [LICENSE](https://huggingface.co/spaces/MedAI-COS30018/MedicalDiagnosisSystem/blob/main/LICENSE))
162
+ - Educational information only; not a substitute for professional medical advice
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
UI_SETUP.md ADDED
@@ -0,0 +1,147 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ## UI setup and structure
2
+
3
+ This document explains the browser UI code structure, responsibilities of each module, how the app boots, what localStorage keys are used, and how the UI communicates with the Python backend.
4
+
5
+ ### 1) Directory layout (frontend)
6
+
7
+ ```
8
+ static/
9
+ index.html # Main UI page
10
+ css/
11
+ styles.css # Global theme + layout
12
+ patient.css # Patient registration page
13
+ js/
14
+ app.js # Legacy monolith boot (kept for compatibility)
15
+ core.js # (optional) Core app bootstrap if using modules
16
+ boot.js # (optional) Bootstrapping helpers for modules
17
+ ui/ # UI-layer modules (DOM + events)
18
+ sidebar.js # Sidebar open/close, overlay, sessions list
19
+ modals.js # User/doctor modal, settings modal, edit-title modal
20
+ patient.js # Patient section: typeahead, status, select
21
+ theme.js # Theme/font-size handling
22
+ voice.js # Web Speech API setup (optional)
23
+ utils.js # Small DOM utilities (qs, on, etc.)
24
+ chat/ # Chat logic modules
25
+ messages.js # Render and manage messages in chat pane
26
+ sessions.js # Client-side session CRUD (local + fetch from backend)
27
+ api.js # Fetch helpers to talk to backend endpoints
28
+ state.js # Ephemeral UI state (current user/patient/session)
29
+
30
+ patient.html # Patient registration page
31
+ ```
32
+
33
+ Notes:
34
+ - If `core.js` and `boot.js` are present and loaded as type="module", they should import from `js/ui/*` and `js/chat/*`. If you continue using `app.js`, it should delegate to these modules (or keep the current inline logic).
35
+
36
+ ### 2) Boot sequence
37
+
38
+ Minimal boot (non-module):
39
+ - `index.html` loads `app.js` (non-module). `app.js` wires events, restores local state, applies theme, renders sidebar sessions, and binds modals.
40
+
41
+ Module-based boot (recommended):
42
+ - `index.html` includes:
43
+ - `<script type="module" src="/static/js/core.js"></script>`
44
+ - `core.js` imports from `ui/*` and `chat/*`, builds the app, and calls `boot.init()`.
45
+ - `boot.js` provides `init()` that wires all UI modules in a deterministic order.
46
+
47
+ Expected init order:
48
+ 1. Load preferences (theme, font size) and apply to `document.documentElement`.
49
+ 2. Restore user (doctor) profile from localStorage.
50
+ 3. Restore selected patient id from localStorage and, if present, preload sessions from backend.
51
+ 4. Wire global UI events: sidebar toggle, outside-click overlay, send, clear, export.
52
+ 5. Wire modals: user/doctor modal, settings modal, edit-session-title modal.
53
+ 6. Wire patient section: typeahead search + selection + status.
54
+ 7. Render current session messages.
55
+
56
+ ### 3) State model (in-memory)
57
+
58
+ - `state.user`: current doctor `{ id, name, role, specialty, createdAt }`.
59
+ - `state.patientId`: 8-digit patient id string kept in localStorage under `medicalChatbotPatientId`.
60
+ - `state.currentSession`: `{ id, title, messages[], createdAt, lastActivity, source }`.
61
+ - `state.sessions`: local session cache (for non-backend sessions).
62
+
63
+ LocalStorage keys:
64
+ - `medicalChatbotUser`: current doctor object.
65
+ - `medicalChatbotDoctors`: array of `{ name }` (unique, used for the dropdown).
66
+ - `medicalChatbotPatientId`: selected patient id.
67
+ - `medicalChatbotPreferences`: `{ theme, fontSize, autoSave, notifications }`.
68
+
69
+ ### 4) Components and responsibilities
70
+
71
+ UI modules (ui/*):
72
+ - `sidebar.js`: opens/closes sidebar, manages `#sidebarOverlay`, renders session cards, handles outside-click close.
73
+ - `modals.js`: shows/hides user/doctor modal, settings modal, edit-title modal. Populates doctor dropdown with a first item "Create doctor user..." and injects current doctor name if missing.
74
+ - `patient.js`: typeahead over `/patients/search?q=...`, renders suggestions, sets `state.patientId` and persists to localStorage, triggers sessions preload.
75
+ - `theme.js`: reads/writes `medicalChatbotPreferences`, applies `data-theme` on `<html>`, sets root font-size.
76
+ - `voice.js`: optional Web Speech API wiring to fill `#chatInput`.
77
+
78
+ Chat modules (chat/*):
79
+ - `messages.js`: adds user/assistant messages, formats content, timestamps, scrolls to bottom.
80
+ - `sessions.js`: saves/loads local sessions, hydrates backend sessions (`GET /sessions/{id}/messages`), deletes/renames sessions.
81
+ - `api.js`: wrappers around backend endpoints (`/chat`, `/patients/*`, `/sessions/*`). Adds `Accept: application/json` and logs responses.
82
+ - `state.js`: exports a singleton state object used by UI and chat modules.
83
+
84
+ ### 5) Backend endpoints used by the UI
85
+
86
+ - `POST /chat` — main inference call.
87
+ - `GET /patients/search?q=...&limit=...` — typeahead. Returns `{ results: [{ name, patient_id, ...}, ...] }`.
88
+ - `GET /patients/{patient_id}` — patient profile (used by patient modal).
89
+ - `POST /patients` — create patient (used by patient.html). Returns `{ patient_id, name, ... }`.
90
+ - `PATCH /patients/{patient_id}` — update patient fields.
91
+ - `GET /patients/{patient_id}/sessions` — list sessions.
92
+ - `GET /sessions/{session_id}/messages?limit=...` — hydrate messages.
93
+
94
+ ### 6) Theming
95
+
96
+ - CSS variables are declared under `:root` and overridden under `[data-theme="dark"]`.
97
+ - On boot, the app reads `medicalChatbotPreferences.theme` and applies:
98
+ - `auto` => matches `prefers-color-scheme`.
99
+ - `light`/`dark` => sets `document.documentElement.dataset.theme` accordingly.
100
+
101
+ ### 7) Patient typeahead contract
102
+
103
+ - Input: `#patientIdInput`.
104
+ - Suggestions container: `#patientSuggestions` (absolute, below input).
105
+ - Debounce: ~200 ms. Request: `GET /patients/search?q=<term>&limit=8`.
106
+ - On selection: set `state.patientId`, persist to localStorage, update `#patientStatus`, call sessions preload, close suggestions.
107
+ - On Enter:
108
+ - If exact 8 digits, call `loadPatient()`.
109
+ - Otherwise, search and pick the first match if any.
110
+
111
+ ### 8) Sidebar behavior
112
+
113
+ - Open: click `#sidebarToggle`.
114
+ - Close: clicking outside (main area) or on `#sidebarOverlay` hides the sidebar on all viewports.
115
+
116
+ ### 9) Doctor dropdown rules
117
+
118
+ - First option is always "Create doctor user..." (value: `__create__`).
119
+ - If the current doctor name is not in `medicalChatbotDoctors`, it is inserted and saved.
120
+ - Choosing the create option reveals an inline mini-form to add a new doctor; Confirm inserts and selects it.
121
+
122
+ ### 10) Voice input (optional)
123
+
124
+ - If using `voice.js`: checks `window.SpeechRecognition || window.webkitSpeechRecognition`.
125
+ - Streams interim results into `#chatInput`, toggled by `#microphoneBtn`.
126
+
127
+ ### 11) Patient registration flow
128
+
129
+ - `patient.html` posts to `POST /patients` with name/age/sex/etc.
130
+ - On success, shows a modal with the new Patient ID and two actions: Return to main page, Edit patient profile.
131
+ - Stores `medicalChatbotPatientId` and redirects when appropriate.
132
+
133
+ ### 12) Troubleshooting
134
+
135
+ - Sidebar won’t close: ensure `#sidebarOverlay` exists and that `sidebar.js`/`app.js` wires outside-click and overlay click listeners.
136
+ - Doctor dropdown empty: confirm `medicalChatbotDoctors` exists or `populateDoctorSelect()` runs on opening the modal.
137
+ - Typeahead doesn’t show results: open network tab and hit `/patients/search?q=test`; ensure 200 and JSON. Logs are printed by FastAPI (see server console).
138
+ - Theme not changing: ensure `theme.js` sets `data-theme` on `<html>` and `styles.css` uses `[data-theme="dark"]` overrides.
139
+
140
+ ### 13) Migration from app.js to modules
141
+
142
+ If you refactored into `ui/*` and `chat/*`:
143
+ 1. Ensure `index.html` loads `core.js` as a module.
144
+ 2. In `core.js`, import and initialize modules in the order described in Boot sequence.
145
+ 3. Keep `app.js` only if you need compatibility; progressively move code into the relevant module files.
146
+
147
+