5t4l1n/ai-eye-disease-detection
AI Eye Disease Detection
A web-based application for detecting glaucoma severity from retinal images using a ResNet101-based deep learning model with Squeeze-and-Excitation (SE) blocks. The app features a Flask backend for image processing and a frontend for user interaction. The pre-trained model is hosted on Hugging Face.
Table of Contents
- Project Overview
- Prerequisites
- Installation
- Project Structure
- Usage
- Running the Application
- Testing via API
- Using the Frontend
- Training the Model
- Troubleshooting
- Contributing
Project Overview
This application predicts glaucoma severity (Normal, Mild, Moderate, Severe) from retinal images by estimating the Cup-to-Disc Ratio (CDR) and providing confidence scores. The backend, served via Flask on port 5000, uses a pre-trained ResNet101 model. The frontend, served on port 8000, allows users to upload images and view results. The model is available at Hugging Face, and the dataset includes images in dataset/G1020/Images_Square/ (e.g., 237.jpg).
Prerequisites
- Python 3.10.16 (recommended for PyTorch compatibility)
- Git
- Dependencies listed in
backend/requirements.txt - GPU recommended for faster inference/training (CPU supported)
- Retinal images in
dataset/G1020/Images_Square/(e.g.,237.jpg) - Pre-trained model from Hugging Face
Installation
- Clone the Repository:
git clone https://github.com/Stalin-143/ai-eye-disease-detection.git
cd ai-eye-disease-detection- Create Virtual Environment:
python3.10 -m venv venv
source venv/bin/activate # Linux/Mac
venv\Scripts\activate # Windows
pip install --upgrade pip- Install Dependencies:
cd backend
pip install -r requirements.txt If torch==2.0.1 fails, try:
pip install torch==2.0.1 torchvision==0.15.2- Download the Model:
mkdir -p backend/model
wget https://huggingface.co/5t4l1n/ai-eye-disease-detection/resolve/main/model/best_glaucoma_model.pth -O backend/model/best_glaucoma_model.pth- Configure Environment Variables: Create
backend/.env:
FLASK_ENV=development
FLASK_DEBUG=True
FLASK_HOST=0.0.0.0
FLASK_PORT=5000
MODEL_PATH=./backend/model/best_glaucoma_model.pth
MAX_CONTENT_LENGTH=16777216
ALLOWED_ORIGINS=http://localhost:8000 Update MODEL_PATH with the absolute path if needed (e.g., /home/stalin/Projects/ai-eye-disease-detection/backend/model/best_glaucoma_model.pth).
- Clear Cache:
rm -rf __pycache__ backend/__pycache__ backend/app/__pycache__Project Structure
ai-eye-disease-detection/
├── backend/
│ ├── app/
│ │ ├── main.py # Flask app entry point
│ │ ├── routes/prediction.py # API endpoints for predictions
│ │ ├── utils/glaucoma_predictor.py # Model inference logic
│ ├── model/
│ │ ├── best_glaucoma_model.pth # Pre-trained model
│ ├── requirements.txt # Backend dependencies
│ ├── .env # Environment variables
├── frontend/
│ ├── index.html # Frontend UI
│ ├── script.js # Frontend JavaScript
│ ├── styles.css # Frontend styles
├── dataset/
│ ├── G1020/
│ │ ├── Images_Square/ # Retinal images (e.g., 237.jpg)
│ ├── training.ipynb # Jupyter notebook for training
├── server.py # Runs backend and frontend
├── venv/ # Virtual environment
├── backup.ipynb # Backup notebook
├── models/ # Additional models (optional)
├── README.md # Project documentation
├── requirements.txt # Root-level dependencies (optional)
├── templates/ # Flask templates (if used)Usage
Running the Application
- Start Servers:
cd ai-eye-disease-detection
source venv/bin/activate
python server.py- Backend:
http://localhost:5000 - Frontend:
http://localhost:8000Expected logs:
INFO:__main__:Starting Flask backend on http://localhost:5000...
Backend: DEBUG:__main__:✅ Glaucoma predictor initialized successfully!
INFO:__main__:Starting frontend HTTP server on http://localhost:8000...
INFO:__main__:Both servers started successfully!
- Stop Servers: Press
Ctrl+C.
Build Docker Image
Linux
docker build -t ai-eye-disease-detection .Windows (Command Prompt or PowerShell)
docker build -t ai-eye-disease-detection .Run Docker Container
Mount the dataset/ directory to access images.
Linux
docker run -d \
-p 5000:5000 \
-p 8000:8000 \
-v $(pwd)/dataset:/app/dataset \
--name ai-eye-disease-container \
ai-eye-disease-detectionWindows (PowerShell)
docker run -d `
-p 5000:5000 `
-p 8000:8000 `
-v ${PWD}/dataset:/app/dataset `
--name ai-eye-disease-container `
ai-eye-disease-detectionWindows (Command Prompt)
docker run -d ^
-p 5000:5000 ^
-p 8000:8000 ^
-v %CD%\dataset:/app/dataset ^
--name ai-eye-disease-container ^
ai-eye-disease-detectionNotes
-vmounts the localdataset/directory to/app/datasetin the container.- Use backticks (`) in PowerShell or carets (^) in Command Prompt for line continuation.
- Ensure the
dataset/directory exists locally.
Verify Container
Linux/Windows
docker ps
docker logs ai-eye-disease-containerExpected Logs
INFO:__main__:Starting Flask backend on http://localhost:5000...
Backend: DEBUG:__main__:✅ Glaucoma predictor initialized successfully!
INFO:__main__:Starting frontend HTTP server on http://localhost:8000...Testing via API
- Check Health:
curl http://localhost:5000/healthExpected:
{"status":"healthy","model_loaded":true}
- Get Model Info:
curl http://localhost:5000/api/model-infoExpected:
{"success":true,"data":{"model_type":"GlaucomaSeverityModel","architecture":"ResNet101 with SE Blocks",...}}
- Predict Glaucoma:
curl -F "image=@dataset/G1020/Images_Square/237.jpg" -F "return_probabilities=true" http://localhost:5000/api/predictExpected:
{"success":true,"data":{"cdr":0.45,"severity":"Normal","severity_description":"No significant glaucoma signs","confidence":0.95,"risk_level":"Low","probabilities":{"Normal":0.95,"Mild":0.03,"Moderate":0.01,"Severe":0.01}},"filename":"237.jpg"}
Using the Frontend
- Open
http://localhost:8000in a browser. - Get Model Info: Click “Get Model Info” to view model details.
- Predict Glaucoma:
- Upload an image (e.g.,
237.jpg). - Check “Show Probabilities” (optional).
- Click “Predict” to view results.
Training the Model
- Prepare Dataset:
- Ensure
dataset/G1020/Images_Square/has labeled images. - Check labels in a CSV or directory structure (e.g.,
Normal/,Mild/). - Run:
ls dataset/G1020- Install Jupyter:
source venv/bin/activate
pip install jupyter- Run training.ipynb:
jupyter notebook dataset/training.ipynb- Update dataset path (e.g.,
dataset/G1020/Images_Square/). - Configure model (ResNet101 with SE blocks).
- Adjust hyperparameters (e.g., learning rate, batch size).
- Example:
import torch
import torchvision
from torch.utils.data import DataLoader
from torchvision import transforms
transform = transforms.Compose([
transforms.Resize((224, 224)),
transforms.ToTensor(),
transforms.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225])
])
dataset = torchvision.datasets.ImageFolder('dataset/G1020/Images_Square/', transform=transform)
loader = DataLoader(dataset, batch_size=32, shuffle=True)
model = torchvision.models.resnet101(pretrained=True)
model.fc = torch.nn.Linear(model.fc.in_features, 4)
optimizer = torch.optim.Adam(model.parameters(), lr=0.001)
criterion = torch.nn.CrossEntropyLoss()- Save Model:
torch.save(model.state_dict(), 'backend/model/new_glaucoma_model.pth')- Update .env: Set
MODEL_PATHto the new model inbackend/.env.
Troubleshooting
- Model Not Loaded:
- Check:
ls backend/model/- Verify
MODEL_PATHinbackend/.env. - Share logs.
- Prediction Fails:
- Run:
curl -F "image=@dataset/G1020/Images_Square/237.jpg" -F "return_probabilities=true" http://localhost:5000/api/predict- Share output and logs.
- Check browser console (F12).
- Pip Install Fails:
- Share error. Try:
pip install torch==2.0.1 torchvision==0.15.2Contributing
- Fork:
https://github.com/Stalin-143/ai-eye-disease-detection - Branch:
git checkout -b feature/your-feature - Commit:
git commit -m "Add your feature" - Push:
git push origin feature/your-feature - Open a pull request.
