Spaces:
Sleeping
Sleeping
File size: 20,658 Bytes
62fd510 e8c7fad 59ac371 24214fc 62fd510 e531bb9 62fd510 24214fc a2eebc7 24214fc d0d6d94 24214fc a2eebc7 24214fc a2eebc7 e8c7fad 24214fc 96e7507 24214fc 96e7507 a2eebc7 24214fc 96e7507 24214fc e8c7fad 96e7507 e8c7fad a2eebc7 e8c7fad 1d0741a 24214fc a2eebc7 e8c7fad 3abb514 24214fc e531bb9 24214fc e531bb9 f8dfa52 24214fc e531bb9 24214fc e531bb9 24214fc e531bb9 24214fc e531bb9 24214fc e531bb9 a8ed56d 24214fc a8ed56d 24214fc a8ed56d 24214fc a8ed56d 24214fc a8ed56d 24214fc f8dfa52 24214fc f8dfa52 24214fc e531bb9 24214fc f8dfa52 24214fc 672ce07 24214fc 3abb514 24214fc 3abb514 24214fc 3abb514 e531bb9 24214fc 3abb514 e531bb9 24214fc e531bb9 1d0741a 24214fc 3abb514 1d0741a 24214fc e8c7fad 3abb514 24214fc 3abb514 24214fc 3abb514 a2eebc7 24214fc e8c7fad 24214fc a8ed56d 24214fc 3abb514 a2eebc7 24214fc e531bb9 24214fc 1d0741a 24214fc 1d0741a 24214fc 1d0741a 24214fc 3abb514 24214fc a2eebc7 24214fc a8ed56d 24214fc a8ed56d 1d0741a 24214fc 1d0741a 24214fc 1d0741a 24214fc a8ed56d 24214fc a8ed56d 24214fc a8ed56d 24214fc a2eebc7 24214fc a2eebc7 24214fc a2eebc7 24214fc a2eebc7 24214fc 3abb514 24214fc 3abb514 24214fc a2eebc7 24214fc e531bb9 24214fc a2eebc7 24214fc e531bb9 24214fc a2eebc7 24214fc a2eebc7 24214fc a2eebc7 24214fc e531bb9 24214fc e531bb9 24214fc e531bb9 24214fc d0d6d94 24214fc e531bb9 24214fc a8ed56d e531bb9 24214fc a2eebc7 24214fc a2eebc7 24214fc 3abb514 24214fc 3abb514 24214fc a2eebc7 24214fc a2eebc7 24214fc a2eebc7 24214fc e8c7fad 24214fc a2eebc7 24214fc a2eebc7 24214fc 3abb514 e531bb9 3abb514 24214fc a2eebc7 24214fc a2eebc7 24214fc a2eebc7 24214fc a2eebc7 24214fc a2eebc7 3abb514 3512660 1d0741a 3512660 a8ed56d 1d0741a |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 |
---
title: Medical Assistant with Spiritual Support v.2.3.2
emoji: π©Ί
colorFrom: blue
colorTo: green
sdk: gradio
sdk_version: 6.0.2
app_file: src/interface/simplified_gradio_app.py
pinned: false
---
# Medical Assistant with Spiritual Support
A comprehensive medical chat application with **automatic background monitoring for spiritual distress** and **advanced prompt optimization system**.
This system provides seamless medical assistance while intelligently detecting and addressing spiritual care needs through a sophisticated AI-powered classification and triage system.
## β‘ Quick Start
### π― Two Interface Options
The project now offers **two interfaces** to suit different needs:
#### 1. **Simplified Interface** (Recommended for Testing Team)
- β
Provider Summary as **final exchange** in verification
- β
**Auto-save** reports with single button
- β
Streamlined UI focused on testing
```bash
python run_simplified_interface.py
# http://localhost:7861
```
π **Quick Guide:** See `QUICK_START_SIMPLIFIED.md` or `QUICK_START_SIMPLIFIED_EN.md`
#### 2. **Full Interface** (For Development & Configuration)
Complete feature set with all advanced options:
```bash
python app.py
# http://localhost:7860
```
### Local Setup
**π₯ Medical Assistant + ποΈ Spiritual Support + π§ Prompt Optimization**
```bash
# 1. Configure API Keys (first time)
cat > .env << EOF
GEMINI_API_KEY=your_gemini_api_key_here
ANTHROPIC_API_KEY=your_anthropic_api_key_here
EOF
# 2. Install Dependencies
python3 -m venv .venv
source .venv/bin/activate
pip install -r requirements.txt
# 3. Run Application
# Simplified Interface (for testing):
python run_simplified_interface.py
# OR Full Interface (for development):
python app.py
```
### Interface Comparison
| Feature | Simplified | Full |
|---------|-----------|------|
| Chat & Verification | β
| β
|
| Provider Summary as Final Exchange | β
| β |
| Auto-Save Reports | β
| β |
| Model Settings | β | β
|
| Edit Prompts | β | β
|
| Patient Profiles | β | β
|
π **Full Comparison:** See `COMPARISON.md`
**Main Interface Tabs (Full):**
- π¬ **Chat** β Primary medical conversation with automatic spiritual monitoring
- π§Ύ **Conversation Verification** β Review and export chat-derived verification sessions
- π **Enhanced Verification** β Manual input and file upload workflows for structured testing
- βοΈ **Model Settings** β Configure AI models for different tasks (session-scoped)
- π§ **Edit Prompts** β Real-time prompt editing with session-level overrides
- π₯ **Patient Profiles** β Predefined patient scenarios for testing
- π **Help** β Comprehensive user guide
**Main Interface Tabs (Simplified):**
- π¬ **Chat** β Test conversations with medical assistant
- π§Ύ **Conversation Verification** β Review exchanges with Provider Summary as final step
- π **Help** β User guide and documentation
---
## π― System Architecture
### Intelligent Spiritual Monitoring
The system operates as a **Medical Assistant** while continuously monitoring for spiritual distress:
```
Patient: "I'm feeling stressed about my treatment"
β
[Spiritual Monitor] β YELLOW (Potential distress detected)
β
[Soft Spiritual Triage] β Asks 2-3 gentle clarifying questions
β
[Triage Response Evaluator] β Evaluates responses
β
Result: GREEN (Coping well) or RED (Needs referral)
```
### Three-Tier Classification System (Enhanced v2.2)
**π’ GREEN (No Spiritual Distress)**
- Medical symptoms only
- Routine health questions
- Standard wellness topics
- **Clear positive statements** like "I am fine" (now correctly classified)
- No emotional or spiritual concerns
**π‘ YELLOW (Potential Spiritual Distress - Needs Clarification)**
- **Simple sadness without spiritual context** (improved classification)
- Stress, anxiety, sleep issues
- Grief and loss (without expressed distress)
- Existential questions
- Spiritual disconnection
- Feelings of isolation
- Loss of interest in activities
- **Ambiguous situations** requiring further investigation
**π΄ RED (Active Spiritual Distress - Immediate Attention)**
**Updated Definition:** Patient's situation appears to be **caused by or actively causing** emotional or spiritual distress (broader than crisis-only)
**Explicit RED Indicators (Always RED):**
- **Complex grief**
- **Loss of a loved one** (when patient expresses emotional distress)
- **Doubt about meaning of life** (e.g., "Life has no meaning anymore")
- **Doubt about meaning of suffering**
- **Doubt about personal dignity**
- **Loss of meaning and purpose**
- Suicidal ideation
- Severe hopelessness
- Spiritual crisis
- Anger at God/higher power
- Moral injury
---
## π Advanced Prompt Optimization System
### Centralized Prompt Management
- **PromptController**: Orchestrates all prompt operations with shared components
- **Shared Catalogs**: Centralized storage for indicators, rules, templates, and categories
- **Session Isolation**: Test prompt changes without affecting production
- **Three-tier Priority**: Session Overrides β Centralized Files β Default Fallbacks
### Session-Level Prompt Overrides
- **Real-time Testing**: Edit prompts and test immediately
- **Session Isolation**: Changes apply only to your current session
- **Promote to File**: Tested changes can be promoted to permanent files
- **Automatic Backups**: Original files backed up before promotion
### Enhanced Edit Prompts Interface
- **Visual Indicators**: Clear display of prompt sources (session vs centralized)
- **Real-time Validation**: Immediate feedback on prompt structure and syntax
- **CSS-Optimized Display**: No UI overflow issues with validation messages
- **Promote Workflow**: Easy promotion of tested changes to permanent files
---
## π¦ Core Components
### 1. π₯ Simplified Medical App
Main application logic with integrated spiritual monitoring.
**File:** `src/core/simplified_medical_app.py`
### 2. π Spiritual Monitor
Classifies patient messages into GREEN/YELLOW/RED categories.
**File:** `src/core/spiritual_monitor.py`
### 3. π‘ Soft Triage Manager
Conducts gentle spiritual triage questioning for YELLOW states.
**File:** `src/core/soft_triage_manager.py`
### 4. οΏ½ Provider Summary Generator
Generates structured summaries and compassionate LLM-based messages for spiritual care team.
**File:** `src/core/provider_summary_generator.py`
### 5. οΏ½π§ Prompt Management System
Centralized prompt optimization with session-level overrides.
**Files:** `src/config/prompt_management/`
### 6. π¨ Enhanced Gradio Interface
Comprehensive web interface with all features integrated.
**File:** `src/interface/gradio_app.py`
---
## οΏ½ ProjecΠ½t Structure
```
.
βββ src/
β βββ core/ # Core application logic
β β βββ simplified_medical_app.py # Main application
β β βββ spiritual_monitor.py # Distress classifier
β β βββ soft_triage_manager.py # Gentle triage questioning
β β βββ spiritual_state.py # State management
β β βββ ai_client.py # AI provider interface
β βββ config/
β β βββ prompt_management/ # π Prompt optimization system
β β β βββ prompt_controller.py # Central orchestrator
β β β βββ shared_components.py # Shared catalogs
β β β βββ data_models.py # Data structures
β β β βββ data/ # JSON storage
β β βββ prompts/ # Prompt files
β β βββ ai_providers_config.py # Model configurations
β βββ interface/
β βββ gradio_app.py # Main web interface
β βββ enhanced_prompt_editor.py # π Prompt editing UI
β
βββ tests/ # π Organized test structure
β βββ prompt_optimization/ # Prompt system tests
β βββ integration/ # Integration tests
β βββ unit/ # Unit tests
β βββ verification/ # Verification tests
β βββ chaplain_feedback/ # Chaplain feedback tests
β
βββ scripts/ # π Utility scripts
β βββ cleanup_test_data.py
β βββ reorganize_files.py
β βββ run_tests.py
β
βββ review/ # π Medical professional feedback
β βββ README.md # Comprehensive review documentation (Ukrainian)
β βββ Or_2.txt # Medical professional recommendations
β βββ *.json # Verified conversation examples
βββ docs/ # Documentation
βββ .verification_data/ # Test data and sessions
βββ requirements.txt # Dependencies
βββ .env # API keys (not in git)
βββ README.md # This file
```
---
## π― Key Features
### π₯ Medical Assistant with Spiritual Support
#### Intelligent Background Monitoring
- π Automatic spiritual distress detection
- π¦ Three-tier classification system (π’ π‘ π΄)
- π Provider summary generation for RED cases
- π¬ LLM-generated compassionate messages for spiritual care team
- β Gentle triage questioning for YELLOW cases
- π€ Consent-based referral process
#### Advanced AI Model Selection
- π€ Choose between Claude and Gemini models
- βοΈ Task-specific model configuration (6 distinct agents)
- π Dynamic model switching
- πΎ Session-scoped settings
#### Comprehensive Prompt Management
- π§ Edit 6 system prompts in real-time (including Spiritual Care Message)
- π Session-level prompt overrides
- β
Real-time validation and syntax checking
- π€ Promote tested changes to permanent files
- π Reset to defaults anytime
#### Verification & Export Capabilities
- π§Ύ **Conversation Verification**: Review chat exchanges and export results
- π **Enhanced Verification**: Manual input and file upload for batch testing
- π **Multiple Export Formats**: CSV and JSON with comprehensive metadata
- π **Analytics**: Detailed statistics and performance metrics
### π§ͺ Comprehensive Testing System
#### 65+ Test Suite
- β
All tests passing (65/65)
- π¬ Property-based testing with Hypothesis
- π― 9 correctness properties validated
- π Complete coverage of all scenarios
- π Automated test organization and execution
---
## π οΈ Technology Stack
- **Backend:** Python 3.14+
- **AI Models:** Google Gemini 2.5 Flash, Anthropic Claude 3.5 Sonnet
- **UI Framework:** Gradio 6.0.2
- **Testing:** Pytest + Hypothesis (property-based testing)
- **Storage:** JSON-based with automatic validation
- **Architecture:** Modular, scalable, and maintainable
---
## οΏ½ Implementation Status
### β
Core Medical Assistant (v2.2)
- β
Background spiritual monitoring with **enhanced classification logic**
- β
**Improved three-tier classification system** (GREEN/YELLOW/RED) based on medical feedback
- β
**Fixed critical classification bugs** (JSON parsing, specific case handling)
- β
**Medical Brain Compatible Summary** as primary provider handoff format
- β
Gentle triage questioning
- β
Consent-based referral process
- β
**Streamlined provider summary generation** (single format)
- β
**Enhanced RED flag definition** (broader than crisis-only)
- β
**Explicit RED indicators** for consistent classification
- β
Patient medical context integration in messages
- β
Multiple AI model support (6 distinct agents)
### β
Prompt Optimization System (v1.1)
- β
Centralized prompt management with PromptController
- β
Session-level prompt overrides with isolation
- β
Enhanced Edit Prompts UI with validation
- β
Shared component architecture (indicators, rules, templates)
- β
Promote to File workflow with automatic backups
- β
Real-time validation and syntax checking
- β
Spiritual Care Message prompt editing support
### β
Testing & Quality Assurance (v2.2)
- β
65+ comprehensive tests (all passing)
- β
**Enhanced classification accuracy** based on medical professional feedback
- β
**Critical bug fixes validated** (JSON parsing, classification logic)
- β
Property-based testing with 9 correctness properties
- β
Organized test structure with clear categorization
- β
Automated test execution and reporting
- β
Complete integration and end-to-end testing
- β
**Medical professional review integration** with verified conversation examples
### β
Enhanced User Experience
- β
Comprehensive Help documentation
- β
Patient profile management
- β
Conversation verification and export
- β
Enhanced verification with file upload
- β
Real-time model and prompt configuration
---
## π§ͺ Testing
### Run All Tests
```bash
python run_tests.py
```
**Current Status:** β
65/65 tests passing
### Test Categories
```bash
# Prompt Optimization Tests
python -m pytest tests/prompt_optimization/ -v
# Integration Tests
python -m pytest tests/integration/ -v
# Unit Tests
python -m pytest tests/unit/ -v
# Verification Tests
python -m pytest tests/verification/ -v
# Chaplain Feedback Tests
python -m pytest tests/chaplain_feedback/ -v
```
### Property-Based Testing
The system includes 9 correctness properties validated through property-based testing:
1. **Component Consistency Enforcement**
2. **Scenario-Targeted Question Generation**
3. **Structured Feedback Data Capture**
4. **Consent-Based Language Compliance**
5. **Shared Component Update Propagation**
6. **Context-Aware Classification Logic**
7. **Complete Provider Summary Generation**
8. **Comprehensive Performance Monitoring**
9. **Session-Level Prompt Override Preservation**
---
## π Security & Privacy
- β **No PHI Storage**: Protected Health Information is not stored
- π **Secure API Keys**: Stored in .env file (not in version control)
- π‘οΈ **Conservative Classification**: Errs on the side of caution
- π **Audit Logging**: All interactions logged for review
- π€ **Consent-Based**: Referrals only with explicit patient consent
- π **Session Isolation**: User sessions are completely isolated
---
## π Documentation
### Core Documentation
- `PROMPT_OPTIMIZATION_IMPLEMENTATION_REPORT.md` β Comprehensive implementation details
- `PROJECT_STRUCTURE.md` β Detailed project organization
- `docs/Spiritual Distress Testing Tool.md` β Customer specification
- `docs/Spiritual Distress Definition, Defining Characteristics, and Descriptions.md` β Clinical reference
- **`review/README.md`** β π Medical professional feedback and classification improvements (Ukrainian)
- **`review/Or_2.txt`** β π Medical professional recommendations that guided v2.2 improvements
### User Guides
- **Help Tab** β Built-in comprehensive user guide
- **Interface Documentation** β Embedded in each tab
- **Testing Guides** β Step-by-step verification workflows
---
## π Getting Started
### Prerequisites
- Python 3.14+
- API keys for Gemini and/or Claude
- Virtual environment (recommended)
### Installation
1. **Clone and Setup:**
```bash
git clone <repository>
cd <project-directory>
python3 -m venv .venv
source .venv/bin/activate
pip install -r requirements.txt
```
2. **Configure API Keys:**
```bash
cp .env.example .env
# Edit .env with your API keys
```
3. **Run Tests (Optional):**
```bash
python run_tests.py
```
4. **Start Application:**
```bash
python src/interface/gradio_app.py
```
5. **Access Interface:**
Open http://localhost:7860 in your browser
---
## π Support & Troubleshooting
### Common Issues
1. **Check Logs:**
```bash
tail -f ai_interactions.log
```
2. **Verify Tests:**
```bash
python run_tests.py
```
3. **Reset Configuration:**
- Use "Reset to Defaults" in Edit Prompts tab
- Clear browser cache if needed
### Documentation Resources
- **Help Tab**: Comprehensive user guide in the application
- **Implementation Report**: `PROMPT_OPTIMIZATION_IMPLEMENTATION_REPORT.md`
- **Project Structure**: `PROJECT_STRUCTURE.md`
---
## π Ready for Production
The Medical Assistant with Spiritual Support system is **fully functional and production-ready** with:
- β
**Complete Implementation**: All requirements satisfied
- β
**Comprehensive Testing**: 65+ tests with 100% pass rate
- β
**Advanced Features**: Prompt optimization, session management, verification workflows
- β
**User-Friendly Interface**: Intuitive design with built-in help
- β
**Robust Architecture**: Scalable, maintainable, and secure
- β
**Quality Assurance**: Property-based testing and continuous validation
---
**Version:** 2.3
**Last Updated:** January 7, 2026
**Status:** β
Production Ready with Enhanced Provider Summary
**Test Coverage:** 65/65 tests passing
### π Latest Updates (v2.3) - January 2026
#### Provider Summary Improvements
Based on medical professional feedback from `review/Or_3.txt`:
**β
Enhanced Provider Summary Content:**
- **Removed phone numbers** from provider summaries (team has direct access in application)
- **Include all patient inputs** throughout interaction instead of just final message
- **Comprehensive conversation context** for better spiritual care team understanding
**β
Automatic Summary Generation:**
- **Instant provider summary** when RED flag triggers and patient consents
- **No manual intervention required** - summary appears automatically in Provider Summary panel
- **Immediate review capability** for spiritual care team to comment on accuracy
**β
Improved User Experience:**
- **Fixed HTML badge rendering** issues in provider summary status
- **Clean text formatting** with proper Markdown compatibility
- **Enhanced debug logging** for better troubleshooting
#### Previous Updates (v2.2) - January 2026
#### Critical Classification Improvements
Based on medical professional feedback from `review/Or_2.txt`:
**β
Fixed Critical JSON Parsing Bug:**
- **Issue:** LLM returned `"classification"` field but parser expected `"state"` field
- **Solution:** Updated parser to handle both field formats
- **Impact:** Eliminated classification errors due to parsing failures
**β
Enhanced RED Flag Definition:**
- **Previous:** Limited to "severe distress or crisis"
- **Current:** Broader definition includes "active spiritual distress"
- **Benefit:** More accurate detection of patients needing spiritual care
**β
Added Explicit RED Indicators:**
- Complex grief β Always RED
- Loss of loved one (with distress) β Always RED
- Doubt about meaning of life β Always RED
- Doubt about meaning of suffering β Always RED
- Doubt about personal dignity β Always RED
**β
Improved Specific Case Handling:**
- **"I am fine"** now correctly classified as π’ GREEN (was incorrectly YELLOW)
- **"I feel sad"** now correctly classified as π‘ YELLOW (simple sadness without context)
- **"Life has no meaning"** now correctly classified as π΄ RED (explicit meaning loss)
#### Medical Brain Integration Optimization
**β
Streamlined Provider Summary Format:**
- Removed redundant "Message for Spiritual Care Team" functionality
- **Medical Brain Compatible Summary** is now the primary and only format
- Single coherent paragraph format for seamless Medical Brain integration
- Optimized prompt structure for Medical Brain compatibility
#### Documentation and Review
**β
Comprehensive Review Documentation:**
- Added detailed `review/README.md` (Ukrainian) with medical professional feedback
- Analyzed verified conversation examples with outcomes
- Documented all implemented improvements and validation results
#### Validation Results
```
β
"I am fine" β π’ GREEN (confidence: 1.0)
β
"I feel sad" β π‘ YELLOW (confidence: 0.9)
β
"Life has no meaning anymore" β π΄ RED (confidence: 1.0)
```
All test cases now pass according to medical professional recommendations.
---
## π Project Organization
### Test Files
- **`tests/`** - Automated test suite (65+ tests)
- **`manual_tests/`** - Manual validation scripts with detailed README
### Documentation
- **`docs/reports/`** - Implementation reports and feature documentation
- **`README.md`** - Main project documentation (this file)
- **`PROJECT_STRUCTURE.md`** - Detailed architecture overview |