Skip to content

Repository files navigation

Medika AI Model

An intelligent, context-aware medical diagnosis assistant powered by machine learning.

Medika AI provides preliminary symptom assessments and personalized medical advice by combining a trained ML model with patient medical history, medications, allergies, and existing conditions. The system flags dangerous drug interactions, allergy conflicts, and high-risk patient profiles to ensure safer recommendations.


What It Does

Medika AI is a diagnostic support system that:

  • Analyzes symptoms using a scikit-learn classifier trained on disease-symptom data
  • Personalizes diagnoses by incorporating patient medical history, allergies, medications, and existing conditions
  • Detects red flags and routes critical cases directly to emergency
  • Flags risks including medication interactions, allergy conflicts, and condition-specific complications
  • Recommends appropriate care levels: Over-the-counter (OTC) advice, clinic visit, hospital referral, or emergency
  • Generates context-aware notes for patients based on their health profile
  • Provides confidence scoring and professional disclaimers

Core Capabilities

Feature Description
Symptom Input Free-text symptom description (e.g., "fever headache rash")
Patient Context Age, gender, existing conditions, medications, allergies, past diagnoses
Risk Detection Red flags (chest pain, difficulty breathing, etc.) → emergency protocol
Action Levels otc (over-the-counter), clinic (doctor visit), hospital, emergency
Interaction Warnings Flags dangerous drug/disease combinations and allergy conflicts
Personalized Advice Age/gender/history-adjusted recommendations

Architecture

app.py                    ← Flask REST API (port 5001)
  ↓ imports
model_core.py             ← AI brain: diagnose() function, patient context rules
  ├─ models/model.pkl     ← Trained ML classifier
  ├─ models/disease_info.json ← Disease descriptions & precautions
  ├─ models/meta.json     ← Model metadata
  └─ rules.json           ← Medical rules, referral logic, OTC advice

test_cli.py               ← Command-line interface for testing
train.py                  ← Model training script
mock_patients.py          ← Sample patient data for testing
backend_integration.py    ← Utilities for backend integration

requirements.txt          ← Python dependencies

Component Overview

  • app.py: Flask server that exposes /diagnose and /health endpoints (port 5001)
  • model_core.py: The AI engine with symptom analysis and patient context rules
  • train.py: Trains and saves the ML model to models/model.pkl
  • test_cli.py: CLI tool for manual testing without the API
  • rules.json: Medical rules (referral categories, OTC advice, red flags)

Installation & Setup

Prerequisites

  • Python 3.8+
  • pip (Python package manager)

Step 1: Clone the Repository

git clone https://github.com/Kayzm18/Medika_AI_Model.git
cd Medika_AI_Model

Step 2: Install Dependencies

pip install -r requirements.txt

Dependencies:

  • flask==3.0.3 — Web framework
  • flask-cors==4.0.1 — Cross-origin support
  • scikit-learn==1.5.1 — ML model & prediction
  • pandas==2.2.2 — Data handling
  • joblib==1.4.2 — Model persistence

Step 3: Train the Model (if not already present)

If models/model.pkl doesn't exist, train the model first:

python train.py

This will:

  • Load the training dataset
  • Train the scikit-learn classifier
  • Save the model to models/model.pkl
  • Generate models/disease_info.json and models/meta.json

How to Run

Option 1: Start the Flask API

python app.py

Output:

=======================================================
  MEDIKA AI Service — http://localhost:5001
  POST /diagnose   GET /health
=======================================================

The service is now running on http://localhost:5001.

Option 2: Use the Command-Line Interface

python test_cli.py

This provides an interactive CLI for testing diagnoses without the API.


API Usage

Health Check

Request:

curl http://localhost:5001/health

Response:

{
  "status": "ok",
  "accuracy": 0.87,
  "n_diseases": 41
}

Diagnose with Symptoms Only

Request:

curl -X POST http://localhost:5001/diagnose \
  -H "Content-Type: application/json" \
  -d '{"symptoms": "fever headache skin rash"}'

Response:

{
  "disease": "Malaria",
  "confidence": 0.92,
  "action": "hospital",
  "advice": "Based on your symptoms, this may be Malaria. This condition requires medical attention at a hospital or clinic. Please go as soon as possible.",
  "otc": "",
  "description": "A mosquito-borne parasitic infection...",
  "precautions": ["Seek immediate medical attention", "Get blood tests"],
  "refer": true,
  "context_notes": [],
  "warnings": [],
  "patient_summary": {},
  "disclaimer": "This is an AI-assisted preliminary assessment, not a medical diagnosis. Always consult a qualified healthcare professional."
}

Diagnose with Patient Context

The backend sends patient data to enable personalized recommendations:

Request:

curl -X POST http://localhost:5001/diagnose \
  -H "Content-Type: application/json" \
  -d '{
    "symptoms": "chest pain shortness of breath",
    "patient": {
      "age": 68,
      "gender": "M",
      "conditions": ["diabetes", "hypertension"],
      "medications": ["metformin 500mg", "lisinopril 10mg"],
      "allergies": ["penicillin"],
      "past_diagnoses": ["Heart attack"],
      "last_visit_reason": "chest pain and palpitations"
    }
  }'

Response includes:

  • Severity escalated based on age (>65) and existing conditions
  • Warnings about medication interactions
  • Personalized context notes (e.g., "Your existing hypertension means...")
  • Referral automatically promoted to hospital

Patient Context Fields

When sending patient data, the backend can include any of these fields (all optional):

Field Type Example Purpose
age int 34 Age-based risk adjustment (pediatric, geriatric)
gender str "M" or "F" Gender-specific risks (e.g., UTIs in women)
conditions list ["diabetes", "hypertension"] Flag disease combinations
medications list ["metformin", "aspirin"] Detect drug interactions
allergies list ["penicillin", "ibuprofen"] Filter OTC suggestions
past_diagnoses list ["Malaria", "Pneumonia"] Detect recurrence patterns
last_visit_reason str "fever and joint pain" Spot recurring issues

Medical Rules

Referral Categories

Medical rules are stored in rules.json:

  • Refer to Hospital: Serious conditions (Heart attack, Stroke, Malaria, etc.)
  • Refer to Clinic: Moderate conditions (Common Cold, Fungal infection, etc.)
  • OTC Advice: Mild self-care recommendations

Red Flags

Certain symptoms trigger an immediate emergency response:

  • Chest pain
  • Difficulty breathing / shortness of breath
  • Loss of consciousness
  • Severe bleeding
  • Severe abdominal pain

Context Rules: Patient History Integration

Condition Risk Map

If a patient has an existing condition and the diagnosis suggests a related disease, severity is escalated:

"diabetes" → ["Fungal infection", "Urinary tract infection", "Heart attack"]
"hypertension" → ["Heart attack", "Stroke", "Hypertension"]
"asthma" → ["Pneumonia", "Bronchial Asthma", "Influenza"]

Medication Interactions

Dangerous combinations are flagged:

"metformin" + "Hypoglycemia"Warning
"warfarin" + "Dengue"Warning (bleeding risk)
"aspirin" + "Dengue"Warning

Allergy Protection

If the patient is allergic to a substance in the OTC advice, it's removed and replaced with a warning:

Allergy: "penicillin" + OTC contains "amoxicillin"Warn & remove
Allergy: "ibuprofen" + OTC contains "ibuprofen"Warn & remove

Age & Gender Adjustments

  • < 5 years old: Always refer to clinic (children require doctor evaluation)
  • 5–12 years old: Medication warnings (avoid without doctor approval)
  • > 65 years old: Lower threshold for clinic referral
  • Female + Urinary Tract Infection: Enhanced advice (more common in women)
  • Female + Certain diseases (Malaria, Diabetes, etc.): Pregnancy warning

Output Fields Explained

Field Type Example Meaning
disease str "Malaria" Predicted disease name
confidence float 0.92 Model confidence (0–1)
action str "hospital" Recommended care level
advice str "Go to hospital..." Plain-English advice
otc str "Take paracetamol..." Over-the-counter suggestion (empty if hospital/emergency)
description str "Mosquito-borne..." Disease background info
precautions list ["Get blood test", ...] Safety precautions
refer bool true Should see a doctor?
context_notes list ["You have diabetes, ...] Personalized notes from patient history
warnings list ["WARNING: You're allergic...", ...] Drug/allergy alerts
patient_summary dict {"age": 34, "allergies": [...]} Echo of patient data used
disclaimer str "This is AI-assisted..." Safety notice (always included)

File Structure

Medika_AI_Model/
├── README.md                      ← This file
├── requirements.txt               ← Python dependencies
├── app.py                         ← Flask REST API
├── model_core.py                  ← AI diagnosis engine
├── train.py                       ← Model training script
├── test_cli.py                    ← CLI testing tool
├── mock_patients.py               ← Sample patient data
├── backend_integration.py         ← Backend utilities
├── rules.json                     ← Medical rules & referral logic
├── data/                          ← Training dataset directory
├── models/                        ← Trained model directory
│   ├── model.pkl                  ← Trained classifier (generated by train.py)
│   ├── disease_info.json          ← Disease descriptions (generated by train.py)
│   └── meta.json                  ← Model metadata (generated by train.py)
├── MEDIKA_AI_Build_Guide.pdf      ← Detailed setup documentation
└── MEDIKA_Integration_Testing_Guide.pdf ← Testing guide

Troubleshooting

Model Not Found

Error:

FileNotFoundError: models/model.pkl not found.
Run python train.py first.

Solution:

python train.py

Port Already in Use

Error:

OSError: [Errno 48] Address already in use

Solution: The Flask server is already running, or another service is using port 5001. Kill the process or use a different port:

# On macOS/Linux: Find and kill the process
lsof -i :5001
kill -9 <PID>

# Or modify app.py to use a different port

Confidence Too Low

Response:

{
  "disease": "Uncertain",
  "action": "clinic",
  "advice": "Your symptoms could not be matched..."
}

Meaning: The model's confidence is below 25%. The patient should see a doctor for proper evaluation.


Testing

Manual Testing with CLI

python test_cli.py

Interactive prompts guide you through symptom entry and optional patient data.

Automated Testing

# Run test suite (if available)
pytest test_cli.py

Medical Disclaimer

⚠️ IMPORTANT: Medika AI is an AI-assisted preliminary assessment tool, not a substitute for professional medical diagnosis. Always consult a qualified healthcare professional for proper evaluation and treatment.

This tool should only be used for:

  • Initial symptom screening
  • Educational purposes
  • Supporting (not replacing) clinical decision-making

Documentation

  • Setup Guide: See MEDIKA_AI_Build_Guide.pdf for detailed installation steps
  • Testing Guide: See MEDIKA_Integration_Testing_Guide.pdf for comprehensive testing procedures
  • API Reference: See app.py docstrings for endpoint specifications

License

(Add your license here if applicable)


Support & Contributing

For issues, feature requests, or contributions:

  1. Open an issue on GitHub
  2. Describe the problem or enhancement
  3. Provide test cases if reporting a bug

Author

Kayzm18 — Medical AI Research & Development


Last Updated: 2026-07-21

About

No description, website, or topics provided.

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages