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.
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
| 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 |
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
- app.py: Flask server that exposes
/diagnoseand/healthendpoints (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)
- Python 3.8+
- pip (Python package manager)
git clone https://github.com/Kayzm18/Medika_AI_Model.git
cd Medika_AI_Modelpip install -r requirements.txtDependencies:
flask==3.0.3— Web frameworkflask-cors==4.0.1— Cross-origin supportscikit-learn==1.5.1— ML model & predictionpandas==2.2.2— Data handlingjoblib==1.4.2— Model persistence
If models/model.pkl doesn't exist, train the model first:
python train.pyThis will:
- Load the training dataset
- Train the scikit-learn classifier
- Save the model to
models/model.pkl - Generate
models/disease_info.jsonandmodels/meta.json
python app.pyOutput:
=======================================================
MEDIKA AI Service — http://localhost:5001
POST /diagnose GET /health
=======================================================
The service is now running on http://localhost:5001.
python test_cli.pyThis provides an interactive CLI for testing diagnoses without the API.
Request:
curl http://localhost:5001/healthResponse:
{
"status": "ok",
"accuracy": 0.87,
"n_diseases": 41
}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."
}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
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 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
Certain symptoms trigger an immediate emergency response:
- Chest pain
- Difficulty breathing / shortness of breath
- Loss of consciousness
- Severe bleeding
- Severe abdominal pain
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"]Dangerous combinations are flagged:
"metformin" + "Hypoglycemia" → Warning
"warfarin" + "Dengue" → Warning (bleeding risk)
"aspirin" + "Dengue" → WarningIf 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- < 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
| 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) |
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
Error:
FileNotFoundError: models/model.pkl not found.
Run python train.py first.
Solution:
python train.pyError:
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 portResponse:
{
"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.
python test_cli.pyInteractive prompts guide you through symptom entry and optional patient data.
# Run test suite (if available)
pytest test_cli.pyThis tool should only be used for:
- Initial symptom screening
- Educational purposes
- Supporting (not replacing) clinical decision-making
- Setup Guide: See
MEDIKA_AI_Build_Guide.pdffor detailed installation steps - Testing Guide: See
MEDIKA_Integration_Testing_Guide.pdffor comprehensive testing procedures - API Reference: See
app.pydocstrings for endpoint specifications
(Add your license here if applicable)
For issues, feature requests, or contributions:
- Open an issue on GitHub
- Describe the problem or enhancement
- Provide test cases if reporting a bug
Kayzm18 — Medical AI Research & Development
Last Updated: 2026-07-21