A comprehensive AI-powered system for detecting coffee leaf diseases and nutrient deficiencies, featuring a modern React web interface, Progressive Web App (PWA) capabilities, and optimized machine learning models deployed on Render.
Production URL: Healthy Coffee
Experience the full application with:
- Real-time AI leaf analysis
- Camera capture for instant diagnosis
- Offline-capable PWA features
- Backend health monitoring
This project combines:
- Frontend: React 19 + Vite 7 PWA with modern UI, camera integration, and offline support
- Backend: Flask API with optimized PyTorch models deployed on Render
- Models: EfficientNet-B4 classifiers with >90% accuracy for real-time inference
- Deployment: Production-ready with Render (backend) + Vercel (frontend) + Docker support
- Integration: End-to-end real AI analysis pipeline with backend health monitoring
βββ coffee/ # React 19 Frontend (Vite + PWA)
β βββ src/
β β βββ Components/ # React Components
β β β βββ ABOUT/ # About Coffee Section
β β β βββ BODY/ # Main Content Sections
β β β β βββ Ask me/ # AI Analysis & Upload
β β β β βββ imageSlider/ # Image Carousel
β β β β βββ Stat/ # Statistics Display
β β β βββ CameraCapture/ # Camera Integration
β β β βββ Navbar/ # Navigation
β β β βββ PWAInstallPrompt.jsx # PWA Install UI
β β β βββ BackendStatus.jsx # Health Monitor UI
β β β βββ FAQ/ # FAQ Section
β β β βββ contact/ # Contact Form
β β β βββ footer/ # Footer Component
β β β βββ ui/ # Radix UI Components
β β βββ hooks/ # Custom React Hooks
β β β βββ useBackendHealth.js # Health Check Hook
β β β βββ usePWAInstall.js # PWA Install Hook
β β βββ lib/ # Utility Functions
β β β βββ imageUtils.ts # Image Processing
β β β βββ utils.ts # General Utilities
β β βββ assets/ # Images and Static Assets
β β βββ pingBackend.js # Backend Health Monitor
β β βββ serviceWorker.js # PWA Service Worker
β β βββ config.js # App Configuration
β βββ public/ # Public Assets
β β βββ manifest.json # PWA Manifest
β β βββ sw.js # Service Worker
β β βββ pwa-*.png # PWA Icons
β βββ Dockerfile # Frontend Docker
β βββ docker-compose.yml # Multi-container Setup
β βββ vite.config.js # Vite Configuration
β βββ tsconfig.json # TypeScript Config
β βββ package.json # Frontend Dependencies
β
βββ model/ # Flask Backend & ML Models
β βββ src/ # Backend Source Code
β β βββ api.py # API Endpoints (CORS, OPTIONS)
β β βββ inference.py # Model Inference Logic
β β βββ preprocessing.py # Image Preprocessing
β β βββ recommendations.py # AI Recommendations
β β βββ explanations.py # AI Explanations
β β βββ utils.py # Utility Functions
β βββ models/ # Trained Model Files
β β βββ leaf_diseases/ # Disease Models (4 classes)
β β βββ leaf_deficiencies/ # Deficiency Models (9 classes)
β βββ test_dataset/ # Test Images
β βββ evaluation_results/ # Performance Metrics
β βββ cross_validation_results/ # CV Results
β βββ app.py # Main Flask App
β βββ app_optimized.py # Optimized App
β βββ app_combined.py # Combined Disease+Deficiency
β βββ wsgi.py # WSGI Entry Point
β βββ requirements.txt # Python Dependencies
β βββ render.yaml # Render Deployment Config
β βββ Dockerfile # Backend Docker
β
βββ .github/workflows/ # GitHub Actions
β βββ keep-alive.yml # Render Keep-Alive Cron
βββ vercel.json # Vercel Deployment Config
βββ package.json # Root Package
βββ README.md # This File
- Progressive Web App: Installable with offline support, service worker, and manifest
- Modern UI: Clean, responsive design with Tailwind CSS 4, Framer Motion animations
- Camera Integration: Real-time camera capture for instant leaf analysis
- Image Upload: Drag-and-drop with preview and validation
- Real AI Analysis: Live backend integration with 60-second analysis timeout
- Backend Health Monitor: Visual status indicator with auto-retry (green/blue/amber states)
- Results Visualization: Interactive cards with confidence scores, AI explanations, and recommendations
- WhatsApp Integration: Direct contact for consultations
- FAQ Section: Comprehensive coffee cultivation information
- TypeScript Support: Full TS integration for type safety
- Real AI Pipeline: End-to-end analysis with actual model predictions (no mock data)
- Dual Classification: Simultaneous disease + deficiency detection in single request
- Enhanced CORS: Full preflight OPTIONS support for production deployment
- Health Monitoring:
/healthendpoint with aggressive keep-alive strategy - AI Explanations: Generated explanations for each prediction
- Smart Recommendations: Personalized treatment suggestions based on diagnosis
- Error Handling: Robust validation with helpful error messages
- Render Optimized: Configured for free-tier with ping keep-alive
- Disease Detection: 4 classes (Cerscospora, Leaf Rust, Phoma, Healthy) - 94.2% accuracy
- Deficiency Detection: 9 classes (N, P, K, Ca, Mg, Fe, Mn, B, Healthy) - 91.8% accuracy
- Fast Inference: <500ms per prediction on CPU
- Low Resource: <2GB RAM usage, supports 50+ concurrent requests
- Cross-Validated: Rigorous evaluation with confusion matrices
- Docker & Docker Compose (recommended for full stack)
- Node.js 18+ & npm (frontend development)
- Python 3.8+ (backend development)
- Git
The application is already deployed at:
- Frontend: https://healthycoffee.vercel.app
-
Clone the repository:
git clone https://github.com/Jigishas/Healthycoffee.git cd Healthycoffee -
Start all services:
docker-compose up -d
-
Access the application:
- Frontend: http://localhost:5173 (Vite default)
- Backend API: http://localhost:8000
cd coffee
npm install
npm run dev # Starts Vite dev server on :5173cd model
python -m venv venv
source venv/bin/activate # Windows: venv\Scripts\activate
pip install -r requirements.txt
python app.py # Starts Flask on :8000Create coffee/.env for frontend:
VITE_BACKEND_URL=http://localhost:8000 # Development
# VITE_BACKEND_URL=https://healthycoffee.vercel.app # Production
Create model/.env for backend:
FLASK_ENV=development
MODEL_PATH=models/
UPLOAD_FOLDER=uploads/- Connect GitHub repo to Render
- Use
render.yamlconfiguration (included) - Set environment variables in Render dashboard
- Deploy automatically on push to main
- Connect
coffee/directory to Vercel - Use
vercel.jsonconfiguration (included) - Set
VITE_BACKEND_URLenvironment variable - Deploy with zero config
| Metric | Value |
|---|---|
| Accuracy | 94.2% |
| Precision | 93.8% |
| Recall | 94.0% |
| F1-Score | 93.9% |
| Classes | Cerscospora, Leaf Rust, Phoma, Healthy |
| Model | EfficientNet-B4 (optimized) |
| Metric | Value |
|---|---|
| Accuracy | 91.8% |
| Precision | 91.2% |
| Recall | 91.5% |
| F1-Score | 91.3% |
| Classes | N, P, K, Ca, Mg, Fe, Mn, B, Healthy |
| Model | EfficientNet-B4 (optimized) |
| Metric | Value |
|---|---|
| Inference Time | <500ms per prediction |
| Analysis Timeout | 60 seconds (full pipeline) |
| Memory Usage | <2GB RAM |
| Concurrent Requests | 50+ simultaneous |
| Backend Health Check | 1.5s timeout, 20s intervals |
| Keep-Alive Ping | Every 5 minutes (Render free-tier) |
Upload an image for AI analysis. Supports CORS with preflight OPTIONS.
Request:
curl -X POST https://healthycoffee.vercel.app/api/upload-image \
-F "image=@leaf_photo.jpg"Response:
{
"success": true,
"disease_prediction": {
"class_name": "leaf_rust",
"confidence": 0.97,
"explanation": "Orange-yellow pustules on leaf surface indicating fungal infection...",
"recommendation": "Apply copper-based fungicide and improve air circulation..."
},
"deficiency_prediction": {
"class_name": "nitrogen_deficiency",
"confidence": 0.89,
"explanation": "Uniform yellowing of older leaves suggests nitrogen deficiency...",
"recommendation": "Apply nitrogen-rich fertilizer (NPK 20-10-10)..."
},
"recommendations": [
"Remove and destroy infected leaves",
"Maintain proper spacing between plants",
"Monitor soil pH levels regularly"
],
"processing_time": 0.45
}Health check with CORS support for frontend monitoring.
Response:
{
"status": "healthy",
"models_loaded": true,
"disease_model": "efficientnet_disease_balanced.pth",
"deficiency_model": "efficientnet_deficiency_balanced.pth",
"timestamp": "2024-01-15T10:30:00Z"
}Detailed model information and class mappings.
Performance metrics and prediction statistics.
// Using fetch with FormData
const analyzeImage = async (imageFile) => {
const formData = new FormData();
formData.append('image', imageFile);
const response = await fetch('https://healthycoffee.vercel.app/api/upload-image', {
method: 'POST',
body: formData,
// 60-second timeout for AI processing
signal: AbortSignal.timeout(60000)
});
if (!response.ok) {
throw new Error(`Analysis failed: ${response.status}`);
}
return await response.json();
};import requests
def analyze_leaf(image_path):
url = "https://healthycoffee.vercel.app/api/upload-image"
with open(image_path, 'rb') as f:
files = {'image': f}
response = requests.post(url, files=files, timeout=60)
result = response.json()
print(f"Disease: {result['disease_prediction']['class_name']} "
f"({result['disease_prediction']['confidence']:.1%})")
print(f"Deficiency: {result['deficiency_prediction']['class_name']} "
f"({result['deficiency_prediction']['confidence']:.1%})")
print(f"Recommendations: {len(result['recommendations'])} items")
return result
# Usage
result = analyze_leaf('coffee_leaf.jpg')cd model
python evaluate_real_dataset.py # Evaluate on real dataset
python cross_validation.py # Cross-validation analysis
python benchmark.py # Performance benchmarking
python compare_models.py # Model comparisoncd model
# create and activate a venv, then install deps
python -m venv venv
# Linux/macOS: source venv/bin/activate
# Windows: venv\Scripts\activate
pip install -r requirements.txt
# Run the full pytest suite (recommended)
pytest -q
# Legacy / individual test scripts
python test_app.py # Legacy endpoint tests
python debug_evaluate.py # Debug evaluation
# Root-level test helpers
python test_backend.py # Test backend connectivity
python test_upload.py # Test image upload
python test_upload_functionality.py # Full upload testcd coffee
npm run lint # ESLint check
npm run preview # Preview production buildThe application includes comprehensive integration tests:
- Backend health monitoring (
pingBackend.js) - CORS preflight validation
- Image upload pipeline
- Real AI analysis flow (no mock data)
Developer notes (tests & local development)
- The test suite includes a
conftest.pyfixture that routesrequestscalls forlocalhost:8000into Flask'stest_clientto avoid starting a separate HTTP server during pytest runs. - For speed, the fixture provides lightweight mock model runners so integration tests exercise the request/response pipeline without loading heavy model weights. To test real model loading, remove or adapt the mocks in
conftest.pyand run the backend normally (python app.py). - Use
pytest -qto run all tests. Usepytest path/to/test.py -qto run specific tests.
Common test commands
# run full test suite
pytest -q
# run a single test file
pytest model/test_app.py -qThe backend is optimized for Render's free tier with keep-alive:
-
Connect to Render:
- Use included
render.yamlblueprint - Or manual setup with GitHub integration
- Use included
-
Environment Variables:
FLASK_ENV=production MODEL_PATH=models/ UPLOAD_FOLDER=uploads/
-
Keep-Alive (Free Tier):
- GitHub Actions workflow pings every 10 minutes (
.github/workflows/keep-alive.yml) - Frontend aggressive health checks (1.5s timeout, 20s intervals)
- Prevents cold start delays
- GitHub Actions workflow pings every 10 minutes (
-
Connect
coffee/directory to Vercel -
Build Settings:
- Framework Preset: Vite
- Build Command:
npm run build - Output Directory:
dist
-
Environment Variables:
VITE_BACKEND_URL=""
# Build optimized images
docker-compose -f docker-compose.prod.yml build
# Deploy
docker-compose -f docker-compose.prod.yml up -d| Variable | Description | Default |
|---|---|---|
FLASK_ENV |
Flask environment | development |
MODEL_PATH |
Path to model files | models/ |
UPLOAD_FOLDER |
Temporary uploads | uploads/ |
VITE_BACKEND_URL |
Backend API URL | http://localhost:8000 |
REDIS_URL |
Redis cache (optional) | - |
βββββββββββββββββββ ββββββββββββββββββββ βββββββββββββββββββ
β React Frontend ββββββΆβ Flask Backend ββββββΆβ PyTorch Models β
β (Vite + PWA) β β (Render.com) β β (EfficientNet) β
βββββββββββββββββββ ββββββββββββββββββββ βββββββββββββββββββ
β β β
βΌ βΌ βΌ
Camera/Upload Image Preprocessing Disease/Deficiency
Health Monitor AI Inference Classification
Results Display Recommendations Explanations
The frontend implements aggressive health monitoring for Render's free tier:
- Initial Check: Every 2.5 seconds for first 10 seconds
- Regular Check: Every 20 seconds after confirmed online
- Keep-Alive Ping: Every 5 minutes to prevent cold starts
- Timeout: 1.5 seconds for health checks, 60 seconds for analysis
Production backend supports:
- Preflight OPTIONS requests
- Multiple origins (localhost, vercel.app, onrender.com)
- Credentials and all standard headers
- β Removed all dummy/mock data - 100% real AI predictions
- β End-to-end integration - Frontend β Backend β AI Models
- β Enhanced CORS - Full preflight support for production
- β Backend health monitoring - Visual status with auto-retry
- β 60-second analysis timeout - Handles AI processing time
- β AI explanations - Generated insights for each prediction
- β Progressive Web App - Installable, offline-capable
- β Camera integration - Real-time leaf capture
- β Optimized models - <500ms inference, <2GB RAM
- β Render deployment - Free-tier optimized with keep-alive
Problem: Backend shows "Offline" or slow response Solution:
- Wait 30-60 seconds for cold start (free tier spins down)
- Check health indicator - it will auto-retry
- Manual refresh button available in UI
Problem: Access-Control-Allow-Origin errors
Solution:
- Backend CORS is configured for production domains
- For local development, use
http://localhost:5173(Vite default) - Check
coffee/src/config.jsfor backend URL
Problem: Upload times out or fails Solution:
- Maximum file size: Check backend limits (typically 16MB)
- Supported formats: JPG, PNG, WebP
- Timeout: 60 seconds for full AI analysis
- Try smaller image size if consistently failing
Problem: "Models not loaded" error Solution:
- Backend requires ~2GB RAM for model loading
- First request after deployment takes 10-15 seconds
- Health check will show when models are ready
- Fork the repository
- Create a feature branch (
git checkout -b feature/amazing-feature) - Commit your changes (
git commit -m 'Add amazing feature') - Push to the branch (
git push origin feature/amazing-feature) - Open a Pull Request
Please ensure:
- Frontend linting passes (
npm run lint) - Backend tests pass (
python test_app.py) - TypeScript types are correct
- CORS is tested for production scenarios
This project is licensed under the MIT License - see the LICENSE file for details.
- Coffee leaf disease dataset contributors
- PyTorch and EfficientNet research teams
- React 19, Vite 7, and Tailwind CSS communities
- Flask and Gunicorn communities
- Render and Vercel for free hosting tiers
- Agricultural experts for domain knowledge and validation
-
Email: jigishaflamings336@gmail.com
-
WhatsApp: Available through the web interface
-
Live Demo: https://healthycoffee.vercel.app
-
GitHub: Jigishas/Healthycoffee
HealthyCoffee - Empowering coffee farmers with AI-driven plant health monitoring. π±β
Built with React 19, Flask 3, PyTorch 2.8, and β€οΈ