https://github.com/aryankdev/agro-ai
AI-powered Plant Disease Detection System using TensorFlow, Flask, and Gemini AI
https://github.com/aryankdev/agro-ai
ai computer-vision deep-learning flask gemini-ai huggingface machine-learning plant-disease-detection tensorflow
Last synced: about 1 month ago
JSON representation
AI-powered Plant Disease Detection System using TensorFlow, Flask, and Gemini AI
- Host: GitHub
- URL: https://github.com/aryankdev/agro-ai
- Owner: aryanKDev
- Created: 2026-05-08T19:46:34.000Z (about 2 months ago)
- Default Branch: main
- Last Pushed: 2026-05-28T19:34:07.000Z (about 1 month ago)
- Last Synced: 2026-05-28T21:18:13.705Z (about 1 month ago)
- Topics: ai, computer-vision, deep-learning, flask, gemini-ai, huggingface, machine-learning, plant-disease-detection, tensorflow
- Language: Python
- Homepage: https://aryan-29-agro-ai.hf.space
- Size: 82.8 MB
- Stars: 0
- Watchers: 0
- Forks: 0
- Open Issues: 0
-
Metadata Files:
- Readme: README.md
Awesome Lists containing this project
README
# πΏ AgroAI β Intelligent Plant Disease Detection Platform
**Phase 1 Complete Β· Multi-User SaaS Β· AI-Powered Β· Real-Time Intelligence**
[](https://python.org)
[](https://flask.palletsprojects.com)
[](https://mongodb.com/atlas)
[](https://tensorflow.org)
[](LICENSE)
> AgroAI is a production-grade agricultural intelligence SaaS platform that combines **TensorFlow deep learning**, **Google Gemini AI**, **real-time weather data**, and a **predictive disease risk engine** to help farmers detect plant diseases, understand risk, and take action β all from their browser.
---
## β¨ Features
| Feature | Description |
|---|---|
| π¬ **AI Disease Detection** | TensorFlow CNN model trained on 87,000+ plant images across 38 disease classes |
| π **JWT Authentication** | Secure register/login/logout with bcrypt password hashing |
| π€ **Multi-User SaaS** | Full data isolation β each user sees only their own scans, history, and analytics |
| βοΈ **MongoDB Atlas** | Cloud-persisted scan history with user-scoped queries |
| π¦οΈ **Weather Intelligence** | Real-time weather via OpenWeatherMap API with 30-min cache and simulated fallback |
| π **Geolocation Weather** | Auto-detects user's GPS location via `navigator.geolocation` |
| π¦ **Disease Risk Engine** | Fuzzy-logic risk scoring (HIGH/MEDIUM/LOW) based on disease type + weather conditions |
| π **Analytics Dashboard** | Personalised KPIs, risk distribution charts, and activity timeline per user |
| π¬ **Gemini AI Chatbot** | Context-aware plant disease assistant powered by Google Gemini 1.5 Flash |
| π **PDF Reports** | Premium AI-generated scan reports via ReportLab |
| π **Farming Insights** | 9 threshold-based agronomic advisory rules from weather data |
---
## ποΈ Architecture
```
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β AgroAI Platform β
βββββββββββββββββ¬ββββββββββββββββββββββ¬ββββββββββββββββββββββββ€
β Frontend β Backend β Intelligence β
β β β β
β HTML5/CSS3 β Flask 3.x β TensorFlow CNN β
β Vanilla JS β Flask-JWT-Extendedβ Gemini 1.5 Flash β
β Chart.js β PyMongo β Risk Engine (Fuzzy) β
β Glassmorphismβ Flask-Bcrypt β Weather Service (OWM) β
β β ReportLab β Farming Insights β
βββββββββββββββββ΄ββββββββββββββββββββββ΄ββββββββββββββββββββββββ
β
MongoDB Atlas
(User-Scoped Data)
```
### Data Flow β Authenticated Scan
```
Browser (logged in)
β POST /predict + Authorization: Bearer
β get_optional_user_id() β ObjectId("user123")
β TensorFlow prediction β disease_name, confidence
β get_weather("Bhopal") β humidity, temperature
β risk_engine.analyse_risk() β HIGH/MEDIUM/LOW
β MongoDB: { disease, confidence, userId, riskLevel, weatherSnapshot }
β Response: { disease_name, riskLevel, riskScore, riskReason }
β Frontend: History page updates immediately β
```
---
## π Quick Start
### Prerequisites
- Python 3.10+
- MongoDB Atlas cluster (free tier works)
- Google Gemini API key ([get one](https://aistudio.google.com/app/apikey))
- OpenWeatherMap API key ([get one](https://openweathermap.org/api)) *(optional β has simulation fallback)*
### Installation
```bash
# 1. Clone the repository
git clone https://github.com/yourusername/PDDS.git
cd PDDS/plant-disease-detection-system
# 2. Create and activate virtual environment
python -m venv venv
venv\Scripts\activate # Windows
# source venv/bin/activate # macOS/Linux
# 3. Install dependencies
pip install -r requirements.txt
# 4. Configure environment variables
cp .env.example .env
# Edit .env with your actual keys (see Environment Variables section)
# 5. Run the application
python app.py
```
Open **http://127.0.0.1:5000** in your browser.
---
## π Environment Variables
Create a `.env` file in the project root (never commit this file):
```env
# Google Gemini AI
GOOGLE_API_KEY=your_gemini_api_key_here
# MongoDB Atlas
MONGO_URI=mongodb+srv://username:password@cluster.mongodb.net/agroai?retryWrites=true&w=majority
# JWT Authentication
JWT_SECRET_KEY=your_strong_random_secret_here_min_32_chars
JWT_ACCESS_TOKEN_EXPIRES=86400
# OpenWeatherMap (optional β falls back to simulation if missing)
OPENWEATHER_API_KEY=your_openweathermap_api_key_here
```
> β οΈ **Security**: The `.env` file is listed in `.gitignore` and will never be committed. All secrets must live here only.
---
## π Project Structure
```
plant-disease-detection-system/
βββ app.py # Flask application & all API routes
βββ database.py # MongoDB Atlas CRUD operations (user-scoped)
βββ risk_engine.py # Fuzzy-logic disease spread risk scoring
βββ pdf_generator.py # ReportLab PDF report generation
βββ disease_rules.json # 38-class diseaseβrisk threshold mapping
βββ auth/
β βββ routes.py # JWT auth blueprints (register/login/logout/profile)
βββ services/
β βββ weather_service.py # OpenWeatherMap + GPS coord lookup + fallback
β βββ farming_insights.py # Agronomic threshold-based advisory rules
βββ index.html # Single-page application shell
βββ script.js # Frontend modules (Router, Storage, Analytics, Weather, RiskCard)
βββ auth.js # JWT auth state manager (window.Auth)
βββ style.css # Glassmorphic CSS design system
βββ requirements.txt # Python dependencies
βββ .env.example # Environment variable template
βββ .gitignore # Excludes .env, __pycache__, venv, etc.
βββ trained_plant_disease_model.keras # TensorFlow CNN (38 classes)
```
---
## π API Reference
### Authentication
| Method | Endpoint | Auth | Description |
|---|---|---|---|
| `POST` | `/api/auth/register` | None | Create new account |
| `POST` | `/api/auth/login` | None | Login, returns JWT |
| `POST` | `/api/auth/logout` | JWT | Invalidate session |
| `GET` | `/api/auth/profile` | JWT | Get user profile |
| `PUT` | `/api/auth/profile` | JWT | Update profile |
### Core AI
| Method | Endpoint | Auth | Description |
|---|---|---|---|
| `POST` | `/predict` | Optional | Run disease detection + risk analysis |
| `POST` | `/chat` | None | Gemini AI chatbot |
| `POST` | `/generate-report` | None | Generate PDF report |
### Data & Intelligence
| Method | Endpoint | Auth | Description |
|---|---|---|---|
| `GET` | `/api/scans` | Optional | Get scan history (user-scoped if JWT present) |
| `DELETE` | `/api/scans/` | Optional | Delete a scan |
| `GET` | `/api/dashboard` | **Required** | Personalised KPIs and analytics |
| `GET` | `/api/weather?city=X` | None | Weather by city name |
| `GET` | `/api/weather?lat=X&lon=Y` | None | Weather by GPS coordinates |
| `POST` | `/api/risk-analysis` | None | Standalone risk analysis |
---
## π§ͺ Testing
Run the automated regression suite (requires server running):
```bash
# Start server in one terminal
python app.py
# Run regression tests in another
python verify_bugfix.py # 29 API tests
python prove_scan_fix.py # Scan persistence proof
```
---
## πΏ Supported Diseases (38 Classes)
The model detects diseases across **14 plant species**:
| Plant | Diseases Detected |
|---|---|
| Tomato | Early Blight, Late Blight, Leaf Mold, Septoria, Spider Mites, Target Spot, Mosaic Virus, Yellow Leaf Curl, Bacterial Spot, Healthy |
| Potato | Early Blight, Late Blight, Healthy |
| Corn/Maize | Cercospora, Common Rust, Northern Blight, Healthy |
| Apple | Black Rot, Cedar Rust, Scab, Healthy |
| Grape | Black Rot, Esca, Isariopsis Leaf Spot, Healthy |
| + 9 more | Peach, Cherry, Pepper, Strawberry, Soybean, Squash, Blueberry, Raspberry, Orange |
---
## π Security Features
- **Password hashing**: `bcrypt` with salt rounds
- **JWT tokens**: HS256 signed, 24-hour expiry
- **Data isolation**: All MongoDB queries scoped by `userId` (ObjectId)
- **Optional auth on `/predict`**: JWT injected automatically when logged in
- **No secrets in source**: All credentials in `.env` (git-ignored)
- **CORS**: Configured for local dev; restrict origins in production
---
## πΈ Screenshots
> *Glassmorphic dark UI with real-time intelligence*
| Feature | Screenshot |
|---|---|
| Disease Detection | Upload β AI Analysis β Risk Card |
| Weather Dashboard | Live weather + Smart Farming Insights |
| Analytics Page | KPI cards + Risk distribution chart |
| Scan History | Per-user MongoDB-backed history with risk badges |
---
## πΊοΈ Roadmap
- [x] **Phase 1A** β JWT Auth + Multi-User SaaS
- [x] **Phase 1B** β User Dashboard & Analytics
- [x] **Phase 1C** β Real-Time Weather Integration
- [x] **Phase 1D** β Farming Insights Engine
- [x] **Phase 1E** β Disease Risk Prediction Engine
- [ ] **Phase 2** β Subscription tiers + Stripe billing
- [ ] **Phase 2** β Mobile PWA with offline detection
- [ ] **Phase 3** β Multi-farm management + team accounts
- [ ] **Phase 3** β Historical weather trend analysis
---
## π€ Contributing
1. Fork the repository
2. Create your feature branch (`git checkout -b feature/phase-2-billing`)
3. Commit your changes (`git commit -m 'Add Stripe billing integration'`)
4. Push to the branch (`git push origin feature/phase-2-billing`)
5. Open a Pull Request
---
## π License
This project is licensed under the MIT License β see the [LICENSE](LICENSE) file for details.
---
Built with πΏ by the AgroAI Team Β· Powered by TensorFlow, Flask, MongoDB Atlas & Google Gemini