Skip to content

Latest commit

 

History

10 Commits

Folders and files

NameName
Last commit message
Last commit date
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

CureLens AI - Personalized Medication Risk Prediction & Management Platform

Summary

CureLens AI is a comprehensive medication safety platform that uses machine learning to predict drug interactions, assess personalized medication risks, and recommend safer alternatives. The system employs explainable AI techniques (SHAP/LIME) to provide transparent, interpretable predictions, helping healthcare professionals make informed decisions about medication safety.

Project Information

Author: Mohamed Shiras Mohamed Saabith
University: University of Wolverhampton
Award: BSc.(Hons) Computer Science & Software Engineering
Contact: saabithsp@gmail.com


Features

  • Drug-Drug Interaction Prediction: Identifies potential interactions between medications with severity classification
  • Personalized Risk Assessment: Evaluates medication risks based on patient-specific factors
  • Safe Drug Recommendations: Suggests safer alternatives based on patient profile and current medications
  • Explainable AI: All predictions come with SHAP/LIME explanations for transparency
  • No LLM Dependencies: Uses only traditional ML models for reliability and predictability

Project Structure

curelens-ai/
├── ml/                         # Machine Learning & Backend
│   ├── data/                   # Data storage
│   │   ├── raw/               # Raw DrugBank XML files
│   │   ├── processed/          # Processed datasets
│   │   └── external/          # External datasets (TWOSIDES, BioSNAP)
│   ├── models/                 # Model files
│   │   ├── artifacts/         # Trained model files (.pkl, .json)
│   │   └── configs/           # Model configurations
│   ├── src/                   # Source code
│   │   ├── data/              # Data processing modules
│   │   ├── models/            # Model implementations
│   │   ├── explainability/    # SHAP/LIME implementations
│   │   └── utils/             # Utility functions
│   ├── api/                   # REST API endpoints
│   │   ├── main.py            # FastAPI application
│   │   └── routes/            # API route handlers
│   └── requirements.txt       # Python dependencies
├── backend/                    # Backend API (Unified FastAPI)
│   ├── main.py                # Unified FastAPI app (Port 8000)
│   ├── routes/                # API route handlers
│   │   ├── users.py          # User management endpoints
│   │   ├── history.py        # History endpoints
│   │   └── models.py         # ML model endpoints
│   ├── models/                # Database models
│   ├── config/                # Configuration
│   └── utils/                 # Utilities
├── frontend/                   # Frontend (React + TypeScript)
│   ├── components/            # React components
│   ├── pages/                 # Page components
│   ├── services/              # API service layer
│   └── package.json           # Node.js dependencies
└── tests/                     # Unit and integration tests

Prerequisites

  • Python 3.8 or higher
  • Node.js (for frontend)
  • MongoDB (for database)
  • pip package manager
  • npm (comes with Node.js)

Installation

1. Clone the Repository

git clone https://github.com/curelens/curelens-ai.git
cd curelens-ai

2. Set Up Python Environment

# Create virtual environment
python -m venv venv

# Activate virtual environment
# On Windows:
venv\Scripts\activate
# On Linux/Mac:
source venv/bin/activate

# Install Python dependencies
pip install -r requirements.txt

3. Set Up Frontend

cd frontend

# Install dependencies
npm install

# If you encounter React 19 dependency conflicts, use:
npm install --legacy-peer-deps

4. Download DrugBank Database

IMPORTANT: The DrugBank database file is required for the ML models to work.

  1. Download the data folder from Google Drive
  2. Extract the downloaded folder at ml/ directory (the extracted folder should be inside ml/)
  3. Locate the drugbank_database.xml file inside the extracted folder - it will be in a raw/ subfolder within the extracted folder
  4. Copy the drugbank_database.xml file from the raw/ subfolder
  5. Paste it directly into the ml/ folder (NOT in ml/raw/, but directly in ml/)
  6. The final path should be: ml/drugbank_database.xml

Note: The data/ folder and its contents are ignored by git. You must download the database file separately from Google Drive and copy only the XML file to ml/.

5. Environment Variables

Create a .env file in the project root:

MONGODB_URI=mongodb://localhost:27017/
MONGODB_DATABASE=curelens_ai

Running the Application

1. Start MongoDB

# Windows - Start MongoDB service or run:
mongod

# Linux/Mac
sudo systemctl start mongod
# or
mongod

2. Train ML Models (First Time Only)

Before running the application, you need to train the ML models:

# Quick test (5-10 minutes) - Recommended first
python ml/src/test_training_quick.py

# Full training (1-3 hours) - After quick test passes
python ml/src/train_pipeline.py

Note: Training results and model artifacts (.pkl, .json files) are saved to ml/models/artifacts/ and are ignored by git.

3. Start Backend Server

# From project root
python backend/main.py

# Or using uvicorn directly:
uvicorn backend.main:app --reload --host 0.0.0.0 --port 8000

The API will be available at: http://localhost:8000

API documentation:

4. Start Frontend Server

# From frontend directory
cd frontend
npm run dev

The frontend will be available at: http://localhost:3000 (or http://localhost:5173 for Vite default)

Testing

The project includes comprehensive testing covering Unit Testing, Integration Testing, and System Testing.

Total Tests: 70

  • Backend/ML Tests: 53 tests (Python/pytest)
  • Frontend Tests: 17 tests (TypeScript/Vitest)

Quick Test Commands

Run All Tests

Backend + ML Tests:

# From project root
pytest tests/ -v

Frontend Tests:

# From frontend directory
cd frontend
npm test

All Tests (Backend + Frontend):

# Run sequentially
pytest tests/ -v
cd frontend && npm test

# Or using Python script
python run_tests.py --type all
cd frontend && npm test

Run by Test Category

Unit Tests (20 tests):

# All unit tests (Backend + ML)
pytest tests/unit/ -v

# Backend unit tests only
pytest tests/unit/test_backend/ -v

# ML unit tests only
pytest tests/unit/test_ml/ -v

# Using markers
pytest -m unit -v

Integration Tests (6 tests):

# All integration tests
pytest tests/integration/ -v

# Backend integration tests
pytest tests/integration/test_api_routes.py -v

# ML integration tests
pytest tests/integration/test_ml_integration.py -v

# Using markers
pytest -m integration -v

System Tests (27 tests):

# All system tests
pytest tests/system/ -v

# Performance tests (5 tests)
pytest tests/system/test_performance.py -v
pytest -m performance -v

# Security tests (8 tests)
pytest tests/system/test_security.py -v
pytest -m security -v

# Error handling tests (10 tests)
pytest tests/system/test_error_handling.py -v
pytest -m error_handling -v

# Using markers
pytest -m system -v

End-to-End Tests (4 tests):

# All E2E tests
pytest tests/e2e/ -v

# User flow tests
pytest tests/e2e/test_user_flows.py -v

# ML workflow tests
pytest tests/e2e/test_ml_workflows.py -v

# Using markers
pytest -m e2e -v

Frontend Testing

Run All Frontend Tests (17 tests):

cd frontend
npm test

Frontend Test Categories:

  • Component Tests: 7 tests (Loader, Footer, DynamicDrugInput, PatientProfileForm)
  • Hook Tests: 2 tests (useAuth)
  • Service Tests: 3 tests (registerUser, loginUser, checkInteraction)
  • Integration Tests: 3 tests (Dashboard, InteractionChecker, RiskAssessment)
  • E2E Tests: 2 tests (Registration flow, Login flow)

Frontend Test Options:

cd frontend

# Run with UI
npm run test:ui

# Run with coverage
npm run test:coverage

# Run integration tests only
npm run test:integration

Test Coverage Reports

Backend + ML Coverage:

# Generate HTML and terminal coverage reports
pytest tests/ --cov=backend --cov=ml/src --cov-report=html --cov-report=term

# Coverage for specific test categories
pytest tests/unit/ --cov=backend --cov=ml/src --cov-report=html:htmlcov/unit
pytest tests/integration/ --cov=backend --cov=ml/src --cov-report=html:htmlcov/integration
pytest tests/system/ --cov=backend --cov=ml/src --cov-report=html:htmlcov/system

# View HTML coverage report: Open htmlcov/index.html in browser

Frontend Coverage:

cd frontend
npm run test:coverage

Using Python Test Runner Script

The project includes run_tests.py for convenient test execution:

# Run all tests
python run_tests.py --type all

# Run specific test categories
python run_tests.py --type unit
python run_tests.py --type integration
python run_tests.py --type e2e
python run_tests.py --type ml

# Run with coverage
python run_tests.py --type all --coverage

# Run specific test file
python run_tests.py --file tests/unit/test_backend/test_models.py

# Run specific test
python run_tests.py --test tests/unit/test_backend/test_models.py::test_create_user

Test Summary

Category Subcategory Count Command
Unit Tests (3.5.1) Backend Unit 10 pytest tests/unit/test_backend/ -v
ML Unit 10 pytest tests/unit/test_ml/ -v
Total Unit 20 pytest tests/unit/ -v
Integration Tests (3.5.2) Backend Integration 3 pytest tests/integration/test_api_routes.py -v
ML Integration 3 pytest tests/integration/test_ml_integration.py -v
Total Integration 6 pytest tests/integration/ -v
System Tests (3.5.3) Performance 5 pytest tests/system/test_performance.py -v
Security 8 pytest tests/system/test_security.py -v
Error Handling 10 pytest tests/system/test_error_handling.py -v
Total System 23 pytest tests/system/ -v
E2E Tests Backend E2E 2 pytest tests/e2e/test_user_flows.py -v
ML E2E 2 pytest tests/e2e/test_ml_workflows.py -v
Total E2E 4 pytest tests/e2e/ -v
TOTAL (Backend/ML) 53 pytest tests/ -v
Frontend Tests Component Unit 7 cd frontend && npm test
Hook Unit 2 cd frontend && npm test
Service Unit 3 cd frontend && npm test
Integration 3 cd frontend && npm test
E2E 2 cd frontend && npm test
Total Frontend 17 cd frontend && npm test
GRAND TOTAL 70 See commands above

Test Environment

  • Test Database: curelens_test (automatically created and cleaned before each test)
  • Isolation: Each test runs independently with isolated test data
  • Fixtures: Shared test fixtures in tests/conftest.py
  • No Real Data Affected: All tests use mock/test data

Prerequisites for Testing:

  • MongoDB must be running
  • Virtual environment activated (if using one)
  • All dependencies installed:
    pip install -r requirements.txt
    cd frontend && npm install

Saving Test Results

You can save test output to files for documentation:

# Save results to files
pytest tests/unit/ -v > unit_test_results.txt
pytest tests/integration/ -v > integration_test_results.txt
pytest tests/system/ -v > system_test_results.txt
pytest tests/e2e/ -v > e2e_test_results.txt

Admin Panel

Access Admin Panel

  1. Start the backend server: python backend/main.py
  2. Start the frontend: cd frontend && npm run dev
  3. Navigate to: http://localhost:3000/#/admin (or your frontend URL)
  4. Login with admin credentials

Default Admin Credentials

  • Email: admin@gmail.com
  • Password: Admin@123
  • Name: Mohamed Saabith

Creating Additional Admin Users

Use the admin creation script:

python backend/scripts/create_admin.py <email> <password> [name]

Example:

python backend/scripts/create_admin.py admin@curelens.ai admin123 "Admin User"

Admin Features

  • User Management: View, delete users, grant/revoke admin privileges
  • History Management: View, delete user history entries
  • Usage Statistics: Charts and reports on system usage
  • Dashboard: Overview of system metrics

Admin API Endpoints

All admin endpoints are prefixed with /api/admin:

  • POST /api/admin/login - Admin login
  • GET /api/admin/users - Get all users
  • DELETE /api/admin/users/{user_id} - Delete user
  • PUT /api/admin/users/{user_id}/admin - Set admin status
  • GET /api/admin/history - Get all history
  • DELETE /api/admin/history/{history_id} - Delete history entry
  • DELETE /api/admin/history/user/{user_id} - Delete user history
  • GET /api/admin/stats/usage - Get usage statistics
  • GET /api/admin/stats/summary - Get admin summary

API Endpoints

ML Model Endpoints (/api)

  • POST /api/check-interaction - Check drug-drug interactions
  • POST /api/batch/check-interactions - Batch check interactions
  • POST /api/calculate-risk - Calculate personalized medication risk
  • POST /api/get-alternatives - Get safe drug alternatives
  • GET /api/drugs/search - Search drugs
  • GET /api/stats - System statistics
  • GET /api/explain/{model_id}/{prediction_id} - Get model explanations

User Management (/api/users)

  • POST /api/users/register - Register new user
  • POST /api/users/login - Login user
  • GET /api/users/me - Get current user
  • PUT /api/users/me - Update user
  • DELETE /api/users/me - Delete user

History Tracking (/api/history)

  • POST /api/history - Create history entry
  • GET /api/history/{user_id} - Get user history
  • GET /api/history/stats/{user_id} - Get history statistics
  • GET /api/history/{id} - Get specific entry
  • DELETE /api/history/{id} - Delete entry
  • DELETE /api/history - Delete all user history

Model Performance

Model Task Metric Score
Model 1 Drug Interaction Prediction ROC-AUC >0.85
Model 2 Risk Assessment ROC-AUC >0.80
Model 3 Drug Recommendation Precision@5 >0.75

Development

Backend Development

The backend is a unified FastAPI application that combines:

  • User Management - Registration, login, profile management
  • History Tracking - Save and retrieve user interaction history
  • ML Model Predictions - Drug interactions, risk assessment, recommendations

All services run on a single FastAPI application (Port 8000).

Frontend Development

The React frontend connects to the unified backend:

  • All API calls go to http://localhost:8000
  • ML endpoints: /api/*
  • User endpoints: /api/users/*
  • History endpoints: /api/history/*

History Tracking

When ML endpoints are called with the X-User-ID header, history is automatically saved:

  • Interaction checks → interaction_check
  • Risk assessments → risk_assessment
  • Recommendations → recommendation
  • Batch checks → batch_check

Troubleshooting

MongoDB Connection Error

Error: Failed to connect to MongoDB

Solution:

  • Ensure MongoDB is running: mongod
  • Check connection: mongosh or mongo
  • Verify MONGODB_URI in .env file

Import Errors

Error: ModuleNotFoundError: No module named 'backend'

Solution:

  • Run commands from project root directory
  • Ensure virtual environment is activated
  • Install dependencies: pip install -r requirements.txt

Frontend Test Errors

Error: Cannot find module '../../../components/Loader'

Solution:

  • Run from frontend directory
  • Ensure npm install completed successfully
  • Check file paths in test files
  • If React 19 conflicts: npm install --legacy-peer-deps

Test Database Issues

Error: Database not found

Solution:

  • Tests automatically create curelens_test database
  • Ensure MongoDB is accessible
  • Check MongoDB connection string

ML Model Not Found

Error: Model file not found

Solution:

  • Train models first: python ml/src/train_pipeline.py
  • Check that models exist in ml/models/artifacts/
  • Verify model files are .pkl format

DrugBank Database Missing

Error: drugbank_database.xml not found

Solution:

  • Download the data folder from Google Drive
  • Extract it at ml/
  • Copy drugbank_database.xml from the extracted folder (may be in raw/ subfolder)
  • Paste it directly into ml/ folder (not in raw/)
  • Final path should be: ml/drugbank_database.xml

Safety Disclaimer

Important: CureLens AI is a research tool designed to assist healthcare professionals. It should NOT be used as a replacement for professional medical advice. Always consult with qualified healthcare providers for medical decisions.

License

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

Acknowledgments

  • DrugBank for comprehensive drug data
  • TWOSIDES and BioSNAP for interaction datasets
  • SHAP and LIME libraries for explainability

Contact

For questions and support, please open an issue on GitHub or contact the team at contact@curelens-ai.com.

About

CureLens AI is an AI-powered medication safety platform designed to help healthcare professionals and patients make safer medication decisions. The platform uses machine learning models to predict potential drug-drug interactions, assess personalized medication risks based on patient profiles, and recommend safer alternative medications.

Topics

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages