Skip to content

adenueltech/CAREFLUXA-AI

Folders and files

NameName
Last commit message
Last commit date

Latest commit

Β 

History

4 Commits
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 

Repository files navigation

πŸ₯ AI Patient Risk Assessment System (Carefluxa)

An enterprise-grade AI-powered patient risk assessment system that analyzes comprehensive patient data to predict risk levels and enable proactive healthcare delivery.

Python FastAPI Tests Coverage License

πŸš€ Key Features

🎯 Core Functionality

  • Real-time Risk Scoring: 0-100 scale risk assessment with confidence intervals
  • ML Ensemble: XGBoost, Random Forest, and Neural Network models for robust predictions
  • Multi-source Integration: FHIR R4, EHR systems, medical devices, and manual entry
  • Critical Patient Detection: Automated flagging and alerting for high-risk patients (β‰₯80 score)
  • Contributing Factors Analysis: Detailed breakdown of risk factors influencing scores

πŸ”’ Enterprise Security & Compliance

  • HIPAA Compliant: Comprehensive audit logging and data protection
  • JWT Authentication: Role-based access control (Doctor, Nurse, Admin)
  • Data Anonymization: Automatic PII removal for model training
  • Audit Trails: Complete tracking of all data access and risk assessments

πŸ“Š Performance & Monitoring

  • Real-time Performance Metrics: Model accuracy, response times, system health
  • Automated Model Retraining: Triggers when accuracy drops below 80%
  • Health Monitoring: Component-level health checks and system diagnostics
  • Batch Processing: Handle up to 100 patients per API call

πŸ”§ Developer Experience

  • Property-Based Testing: Comprehensive test coverage using Hypothesis
  • Integration Testing: End-to-end workflow validation
  • API Documentation: Interactive Swagger/OpenAPI docs
  • Type Safety: Full TypeScript-style type hints throughout

πŸ—οΈ System Architecture

graph TB
    A[Data Ingestion Layer] --> B[Data Validation & Preprocessing]
    B --> C[Feature Engineering Pipeline]
    C --> D[ML Model Ensemble]
    D --> E[Risk Score Calculator]
    E --> F[Alert Generation System]
    F --> G[API Gateway]
    G --> H[External Systems]
    
    I[Model Training Pipeline] --> D
    J[Model Performance Monitor] --> I
    K[Data Storage Layer] --> B
    K --> I
Loading

🧩 Core Components

Component Description Technology
Data Ingestion Multi-source patient data processing FHIR R4, HL7 v2.x
ML Ensemble Risk prediction models XGBoost, Random Forest, MLP
API Gateway RESTful API with authentication FastAPI, JWT
Alert System Critical patient notifications Real-time alerting
Audit System Compliance and logging Structured logging
Performance Monitor System metrics and health Custom metrics tracking

πŸ“ Project Structure

carefluxa-ai/
β”œβ”€β”€ πŸ“ src/                           # Source code
β”‚   β”œβ”€β”€ πŸ“„ config.py                  # Configuration management
β”‚   β”œβ”€β”€ πŸ“„ logging_config.py          # Logging setup
β”‚   β”œβ”€β”€ πŸ“„ startup.py                 # Application initialization
β”‚   β”œβ”€β”€ πŸ“„ integration.py             # System integration layer
β”‚   β”œβ”€β”€ πŸ“ data/                      # Data processing & ingestion
β”‚   β”‚   β”œβ”€β”€ πŸ“„ models.py              # Pydantic data models
β”‚   β”‚   β”œβ”€β”€ πŸ“„ ingestion.py           # Multi-source data ingestion
β”‚   β”‚   β”œβ”€β”€ πŸ“„ integration.py         # Data source integration
β”‚   β”‚   └── πŸ“„ validation.py          # Data validation rules
β”‚   β”œβ”€β”€ πŸ“ api/                       # REST API & web interface
β”‚   β”‚   β”œβ”€β”€ πŸ“„ app.py                 # FastAPI application
β”‚   β”‚   β”œβ”€β”€ πŸ“„ auth.py                # Authentication & authorization
β”‚   β”‚   β”œβ”€β”€ πŸ“„ models.py              # API request/response models
β”‚   β”‚   └── πŸ“„ risk_service.py        # Risk assessment service
β”‚   β”œβ”€β”€ πŸ“ alerts/                    # Alert generation system
β”‚   β”‚   β”œβ”€β”€ πŸ“„ alert_system.py        # Alert management
β”‚   β”‚   └── πŸ“„ critical_detection.py  # Critical patient detection
β”‚   β”œβ”€β”€ πŸ“ audit/                     # Audit logging & compliance
β”‚   β”‚   β”œβ”€β”€ πŸ“„ logger.py              # Audit trail generation
β”‚   β”‚   β”œβ”€β”€ πŸ“„ compliance.py          # HIPAA compliance tools
β”‚   β”‚   └── πŸ“„ models.py              # Audit data models
β”‚   β”œβ”€β”€ πŸ“ performance/               # Performance monitoring
β”‚   β”‚   β”œβ”€β”€ πŸ“„ performance_monitor.py # System performance tracking
β”‚   β”‚   β”œβ”€β”€ πŸ“„ metrics_tracker.py     # Metrics collection
β”‚   β”‚   └── πŸ“„ models.py              # Performance data models
β”‚   └── πŸ“ privacy/                   # Data privacy & anonymization
β”‚       β”œβ”€β”€ πŸ“„ anonymization.py       # PII removal for training
β”‚       └── πŸ“„ validation.py          # Privacy compliance checks
β”œβ”€β”€ πŸ“ tests/                         # Comprehensive test suite
β”‚   β”œβ”€β”€ πŸ“ unit/                      # Unit tests
β”‚   β”œβ”€β”€ πŸ“ integration/               # Integration tests
β”‚   └── πŸ“ property/                  # Property-based tests (Hypothesis)
β”œβ”€β”€ πŸ“ docs/                          # Documentation and specifications
β”‚   └── πŸ“ specs/                     # Feature specifications
β”œβ”€β”€ πŸ“„ main.py                        # Application entry point
β”œβ”€β”€ πŸ“„ requirements.txt               # Python dependencies
β”œβ”€β”€ πŸ“„ pyproject.toml                # Project configuration
β”œβ”€β”€ πŸ“„ Makefile                      # Development commands
└── πŸ“„ README.md                     # This file

πŸš€ Quick Start

Prerequisites

  • Python 3.9+ (3.12 recommended)
  • pip or poetry for dependency management
  • Git for version control

⚑ Installation

  1. Clone the repository:
git clone https://github.com/adenueltech/carefluxa-ai.git
cd carefluxa-ai
  1. Create virtual environment:
python -m venv venv
source venv/bin/activate  # On Windows: venv\Scripts\activate
  1. Install dependencies:
pip install -r requirements.txt
  1. Set up environment variables:
cp .env.example .env
# Edit .env with your configuration
export DATABASE_URL="sqlite:///./carefluxa.db"
export SECRET_KEY="your-secret-key-here"

πŸƒβ€β™‚οΈ Running the Application

Start the server:

python main.py

Access the application:

πŸ§ͺ Testing

Run all tests:

pytest

Run with coverage:

pytest --cov=src --cov-report=html

Run specific test types:

# Unit tests only
pytest tests/unit/

# Integration tests only
pytest tests/integration/

# Property-based tests only
pytest tests/property/

πŸ› οΈ Development Commands

Using the Makefile:

make install     # Install dependencies
make test        # Run tests
make lint        # Code linting
make format      # Code formatting
make clean       # Clean up temporary files

πŸ“‘ API Usage Examples

πŸ” Authentication

# Login to get JWT token
curl -X POST "http://localhost:8000/api/v1/auth/login" \
  -H "Content-Type: application/json" \
  -d '{"username": "doctor_smith", "password": "secure_password"}'

# Response
{
  "access_token": "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9...",
  "token_type": "bearer",
  "expires_in": 3600,
  "user_id": "doc_001",
  "role": "doctor"
}

πŸ₯ Patient Risk Assessment

# Assess individual patient risk
curl -X POST "http://localhost:8000/api/v1/risk-assessment" \
  -H "Authorization: Bearer YOUR_JWT_TOKEN" \
  -H "Content-Type: application/json" \
  -d '{
    "patient_id": "patient_12345",
    "include_factors": true,
    "force_refresh": true
  }'

# Response
{
  "success": true,
  "patient_id": "patient_12345",
  "risk_assessment": {
    "risk_score": 85,
    "confidence_interval": [78, 92],
    "alert_level": "critical",
    "contributing_factors": [
      {
        "factor_name": "Elevated Heart Rate",
        "impact_score": 15.2,
        "category": "vitals"
      },
      {
        "factor_name": "Diabetes History",
        "impact_score": 12.8,
        "category": "medical_history"
      }
    ],
    "assessment_timestamp": "2024-01-12T10:30:00Z"
  },
  "processing_time_ms": 245.7
}

🚨 Critical Patients Monitoring

# Get current critical patients
curl -X GET "http://localhost:8000/api/v1/critical-patients" \
  -H "Authorization: Bearer YOUR_JWT_TOKEN"

# Response
{
  "critical_patients": [
    {
      "patient_id": "patient_12345",
      "risk_score": 85,
      "alert_level": "critical",
      "last_assessment": "2024-01-12T10:30:00Z",
      "time_in_critical_status": "02:15:30"
    }
  ],
  "total_count": 1,
  "last_updated": "2024-01-12T10:30:00Z"
}

πŸ“Š System Performance

# Get performance metrics (Admin only)
curl -X GET "http://localhost:8000/api/v1/performance-metrics" \
  -H "Authorization: Bearer YOUR_ADMIN_JWT_TOKEN"

# Response
{
  "individual_models": [
    {
      "model_name": "XGBoost",
      "accuracy": 0.92,
      "precision": 0.89,
      "recall": 0.94,
      "f1_score": 0.91,
      "auc_roc": 0.95
    }
  ],
  "ensemble_accuracy": 0.94,
  "average_response_time_ms": 850.0,
  "assessments_per_hour": 450.0,
  "critical_alerts_generated": 12,
  "system_uptime_percent": 99.8
}

βš™οΈ Configuration

Environment Variables

Create a .env file with the following configuration:

# Database Configuration
DATABASE_URL=sqlite:///./carefluxa.db
DATABASE_TEST_URL=sqlite:///./test_carefluxa.db

# API Configuration
API_HOST=0.0.0.0
API_PORT=8000
API_RELOAD=true

# Security
SECRET_KEY=your-super-secret-key-change-this-in-production
ACCESS_TOKEN_EXPIRE_MINUTES=60

# ML Model Configuration
CRITICAL_RISK_THRESHOLD=80
BATCH_SIZE_LIMIT=100
MODEL_RETRAIN_THRESHOLD=0.80

# Logging
LOG_LEVEL=INFO
ENABLE_METRICS=true

# Environment
ENVIRONMENT=development  # development, testing, production

Key Configuration Areas

Category Description Environment Variables
Database SQLite/PostgreSQL connection DATABASE_URL, DATABASE_TEST_URL
API Server settings and CORS API_HOST, API_PORT, API_RELOAD
Security JWT tokens and encryption SECRET_KEY, ACCESS_TOKEN_EXPIRE_MINUTES
ML Models Risk thresholds and limits CRITICAL_RISK_THRESHOLD, BATCH_SIZE_LIMIT
Monitoring Logging and metrics LOG_LEVEL, ENABLE_METRICS

πŸ§ͺ Testing Strategy

Test Coverage Overview

Test Type Coverage Description
Unit Tests 85% Individual component testing
Integration Tests 90% End-to-end workflow validation
Property Tests 95% Hypothesis-based correctness validation
API Tests 100% Complete API endpoint coverage

Property-Based Testing

We use Hypothesis for property-based testing to ensure correctness across all possible inputs:

# Example: Risk score validity property
@given(patient_data=patient_data_strategy())
def test_risk_score_always_valid_range(patient_data):
    """Risk scores must always be between 0-100."""
    response = risk_service.assess_patient_risk(patient_data)
    assert 0 <= response.risk_assessment.risk_score <= 100

Running Specific Tests

# Run property-based tests with verbose output
pytest tests/property/ -v --hypothesis-show-statistics

# Run integration tests for specific component
pytest tests/integration/test_system_integration.py -v

# Run tests with coverage report
pytest --cov=src --cov-report=term-missing

πŸ“š API Documentation

Interactive Documentation

Once the application is running, explore the comprehensive API documentation:

API Endpoints Overview

Endpoint Method Description Auth Required
/health GET System health check ❌
/api/v1/auth/login POST User authentication ❌
/api/v1/risk-assessment POST Individual patient risk assessment βœ…
/api/v1/risk-assessment/batch POST Batch patient risk assessment βœ…
/api/v1/critical-patients GET Get critical patients list βœ…
/api/v1/performance-metrics GET System performance metrics βœ… (Admin)
/api/v1/ingest/patient POST Ingest complete patient data βœ…
/api/v1/ingest/fhir-bundle POST Ingest FHIR R4 bundle βœ…

Authentication & Authorization

The system uses JWT-based authentication with role-based access control:

  • Doctor: Can assess patients, view critical patients
  • Nurse: Can assess patients, manage alerts
  • Admin: Full system access including performance metrics

πŸ—οΈ Development

Code Quality Standards

We maintain high code quality through:

  • Type Hints: Full type annotation coverage
  • Linting: Flake8 for code style enforcement
  • Formatting: Black for consistent code formatting
  • Testing: 95%+ test coverage requirement
  • Documentation: Comprehensive docstrings and API docs

Development Workflow

# 1. Create feature branch
git checkout -b feature/new-feature

# 2. Make changes and test
make test
make lint
make format

# 3. Run full test suite
pytest --cov=src

# 4. Commit and push
git add .
git commit -m "feat: add new feature"
git push origin feature/new-feature

Adding New Features

  1. Update Requirements: Add to docs/specs/ if it's a major feature
  2. Write Tests First: Follow TDD approach
  3. Implement Feature: Keep functions small and focused
  4. Add Documentation: Update API docs and README
  5. Test Integration: Ensure end-to-end workflows work

πŸš€ Deployment

Production Deployment

# 1. Set production environment
export ENVIRONMENT=production
export DATABASE_URL=postgresql://user:pass@host:5432/carefluxa
export SECRET_KEY=your-production-secret-key

# 2. Install production dependencies
pip install -r requirements.txt

# 3. Run database migrations (if applicable)
# python -m alembic upgrade head

# 4. Start with production server
uvicorn src.api.app:app --host 0.0.0.0 --port 8000 --workers 4

Docker Deployment

# Dockerfile example
FROM python:3.12-slim

WORKDIR /app
COPY requirements.txt .
RUN pip install -r requirements.txt

COPY src/ ./src/
COPY main.py .

EXPOSE 8000
CMD ["python", "main.py"]

🀝 Contributing

We welcome contributions! Please follow these guidelines:

Getting Started

  1. Fork the repository
  2. Create a feature branch: git checkout -b feature/amazing-feature
  3. Follow code standards: Use Black formatting and type hints
  4. Add tests: Maintain 95%+ coverage
  5. Update documentation: Keep README and API docs current
  6. Submit a Pull Request

Code Standards

  • Python Style: Follow PEP 8 with Black formatting
  • Type Hints: All functions must have type annotations
  • Docstrings: Use Google-style docstrings
  • Testing: Write both unit and property-based tests
  • Commit Messages: Use conventional commits (feat:, fix:, docs:)

Development Setup

# Install development dependencies
pip install -e ".[dev]"

# Set up pre-commit hooks
pre-commit install

# Run quality checks
make lint
make format
make test

πŸ“„ License

This project is licensed under the MIT License - see the LICENSE file for details.

πŸ™ Acknowledgments

  • FastAPI - Modern, fast web framework for building APIs
  • Hypothesis - Property-based testing framework
  • Pydantic - Data validation using Python type annotations
  • XGBoost - Gradient boosting framework for ML
  • FHIR - Healthcare interoperability standards

πŸ“ž Support


Built with ❀️ for better healthcare outcomes

⭐ Star this repo | πŸ› Report Bug | πŸ’‘ Request Feature

About

An enterprise-grade AI-powered patient risk assessment system that analyzes comprehensive patient data to predict risk levels and enable proactive healthcare delivery.

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

 
 
 

Contributors