A complete real-time crop disease detection and decision support system built with YOLOv8, Firebase, and React.
- Overview
- System Architecture
- Features
- Tech Stack
- Prerequisites
- Installation Guide
- Project Structure
- Configuration
- Usage Guide
- Troubleshooting
- API Reference
- Contributing
- License
This system revolutionizes precision agriculture by combining:
- Real-time AI detection of crop diseases using drone imagery
- Spatial intelligence for precision spray path planning
- Economic impact analysis with ROI calculation
- Multimodal fusion of vision + sensor data
- Intelligent alerts and decision recommendations
- Mission reporting with complete audit trail
Problem Solved: Farmers lose 30-40% of crops to disease and waste 78% of chemicals by spraying entire fields. Our solution detects diseased zones in real-time and generates precision treatment paths, saving money and reducing environmental impact.
βββββββββββββββββββ
β Drone Camera β
β (Image Feed) β
ββββββββββ¬βββββββββ
β
βΌ
βββββββββββββββββββββββββββββββ
β Edge AI (YOLOv8) β
β - Real-time detection β
β - Runs on drone/ground PC β
β - No cloud dependency β
ββββββββββ¬βββββββββββββββββββββ
β
βΌ
βββββββββββββββββββββββββββββββ
β Firebase Realtime DB β
β - Event streaming β
β - Sub-500ms latency β
ββββββββββ¬βββββββββββββββββββββ
β
βΌ
βββββββββββββββββββββββββββββββ
β React Dashboard β
β - Live map visualization β
β - Path planning β
β - Economic analysis β
β - Decision support β
β - PDF report generation β
βββββββββββββββββββββββββββββββ
- β Real-time crop disease detection using YOLOv8
- β Live GPS-mapped visualization with Leaflet
- β Automated precision spray path generation
- β Economic impact & ROI calculation
- β Multimodal fusion (vision + soil sensors)
- β Intelligent alert system with prioritization
- β Mission report generation (PDF export)
- β Sub-500ms detection-to-dashboard latency
- Map View - Interactive field map with drone position, detection pins, spray path overlay
- Spray Path Generator - Automated path planning for infected zones
- Economic/ROI Panel - Cost comparison, savings calculation, net benefit
- Multimodal Intelligence - Fused diagnosis from vision + sensor data
- Analytics - Detection statistics and disease distribution
- Detection Feed - Live stream of all detections with confidence scores
- Alerts & Decisions - Prioritized alerts with recommended actions
- Python 3.8+
- YOLOv8 (Ultralytics)
- OpenCV
- Firebase Admin SDK
- NumPy
- React 18
- React Leaflet (Maps)
- Firebase SDK
- jsPDF (Report generation)
- date-fns
- CSS3 Grid Layout
- Firebase Realtime Database
- Firebase Authentication (optional)
- Node.js 16+
Before installation, ensure you have:
- Python 3.8 or higher (Download)
- Node.js 16 or higher (Download)
- npm or yarn (comes with Node.js)
- Git (Download)
- Firebase account (Sign up free)
- Webcam or video file (for testing)
- 4GB+ RAM (for YOLOv8 inference)
python --version # Should show 3.8+
node --version # Should show 16+
npm --version # Should show 8+
git --version # Any recent version# Clone the project
git clone https://github.com/yourusername/precision-agriculture-analytics.git
cd precision-agriculture-analytics
# Project structure
# precision-agriculture-analytics/
# βββ backend/ # Edge AI inference
# βββ dashboard/ # React frontend
# βββ models/ # YOLOv8 weights
# βββ README.mdcd backend
# Create virtual environment
python -m venv venv
# Activate virtual environment
# On Windows:
venv\Scripts\activate
# On macOS/Linux:
source venv/bin/activate
# Your prompt should now show (venv)# Upgrade pip
pip install --upgrade pip
# Install required packages
pip install ultralytics opencv-python firebase-admin python-dotenv numpy pillow
# Verify installations
pip listExpected packages:
ultralytics 8.0.0+
opencv-python 4.8.0+
firebase-admin 6.2.0+
python-dotenv 1.0.0+
numpy 1.24.0+
pillow 10.0.0+
# Create models directory
mkdir -p ../models
cd ../models
# Option A: Use pre-trained YOLOv8 (for testing)
# The model will auto-download on first run
# Option B: Use custom-trained model (recommended for production)
# Place your trained weights here:
# models/crop_disease_yolov8.ptcd ../backend
# Create .env file
touch .env
# Edit .env with your settings
nano .env # or use any text editorbackend/.env content:
# Firebase Configuration
FIREBASE_CREDS_PATH=./firebase-credentials.json
FIREBASE_DATABASE_URL=https://your-project.firebaseio.com
# Video Source
VIDEO_SOURCE=0 # 0 for webcam, or path to video file
# VIDEO_SOURCE=test_videos/field_video.mp4
# Model Configuration
MODEL_PATH=../models/crop_disease_yolov8.pt
CONFIDENCE_THRESHOLD=0.5
# Session Configuration
SESSION_ID=FIELD-001
FIELD_CENTER_LAT=28.6139
FIELD_CENTER_LNG=77.2090- Go to Firebase Console
- Click "Add project"
- Enter project name:
precision-agriculture - Disable Google Analytics (optional)
- Click "Create project"
- In Firebase Console, go to "Build" β "Realtime Database"
- Click "Create Database"
- Select location: United States or closest to you
- Start in "Test mode" (for development)
- Click "Enable"
Set up security rules:
{
"rules": {
".read": "auth != null || true",
".write": "auth != null || true"
}
}- In Firebase Console, go to Project Settings (βοΈ icon)
- Go to "Service accounts" tab
- Click "Generate new private key"
- Click "Generate key" (downloads JSON file)
- Rename file to
firebase-credentials.json - Move to
backend/directory
# Move downloaded key to backend folder
mv ~/Downloads/your-project-firebase-adminsdk-xxxxx.json backend/firebase-credentials.json
# Verify file exists
ls backend/firebase-credentials.json- In Realtime Database page, copy the database URL
- It looks like:
https://your-project-default-rtdb.firebaseio.com/ - Update
FIREBASE_DATABASE_URLinbackend/.env
cd dashboard
# Install all npm packages
npm install
# This installs:
# - react
# - react-leaflet
# - leaflet
# - firebase
# - jspdf
# - date-fns
# - and all other dependenciesIf you get errors, try:
# Clear npm cache
npm cache clean --force
# Delete node_modules and reinstall
rm -rf node_modules package-lock.json
npm install# Get Firebase config from Firebase Console
# Project Settings β General β Your apps β Web app
# Create .env file
touch .env.local
# Edit .env.local
nano .env.localdashboard/.env.local content:
REACT_APP_FIREBASE_API_KEY=AIzaSyXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
REACT_APP_FIREBASE_AUTH_DOMAIN=your-project.firebaseapp.com
REACT_APP_FIREBASE_DATABASE_URL=https://your-project.firebaseio.com
REACT_APP_FIREBASE_PROJECT_ID=your-project
REACT_APP_FIREBASE_STORAGE_BUCKET=your-project.appspot.com
REACT_APP_FIREBASE_MESSAGING_SENDER_ID=123456789012
REACT_APP_FIREBASE_APP_ID=1:123456789012:web:xxxxxxxxxxxxxTo get Firebase config:
- Firebase Console β Project Settings
- Scroll to "Your apps" section
- Click "Web app" icon (</>)
- Copy the config values
Edit dashboard/src/firebase/config.js:
import { initializeApp } from 'firebase/app';
import { getDatabase } from 'firebase/database';
const firebaseConfig = {
apiKey: process.env.REACT_APP_FIREBASE_API_KEY,
authDomain: process.env.REACT_APP_FIREBASE_AUTH_DOMAIN,
databaseURL: process.env.REACT_APP_FIREBASE_DATABASE_URL,
projectId: process.env.REACT_APP_FIREBASE_PROJECT_ID,
storageBucket: process.env.REACT_APP_FIREBASE_STORAGE_BUCKET,
messagingSenderId: process.env.REACT_APP_FIREBASE_MESSAGING_SENDER_ID,
appId: process.env.REACT_APP_FIREBASE_APP_ID
};
const app = initializeApp(firebaseConfig);
export const database = getDatabase(app);cd backend
# Activate virtual environment if not already active
source venv/bin/activate # macOS/Linux
# OR
venv\Scripts\activate # Windows
# Run inference
python inference.py
# Expected output:
# β
Firebase initialized
# β
YOLOv8 model loaded
# π₯ Video source opened
# π‘ Streaming detections to Firebase...Open a NEW terminal window:
cd dashboard
# Start React development server
npm start
# Dashboard will open automatically at:
# http://localhost:3000
# Expected output:
# Compiled successfully!
# webpack compiled with 0 warnings
# Dashboard running on http://localhost:3000-
Backend Terminal: Should show detections being processed
Frame 45 | Detections: 3 | Uploaded to Firebase β Frame 46 | Detections: 2 | Uploaded to Firebase β -
Dashboard: Should show:
- β LIVE connection badge (green)
- β Detection markers appearing on map
- β Detection feed updating in real-time
- β Live metrics incrementing
precision-agriculture-analytics/
β
βββ backend/ # Edge AI inference
β βββ inference.py # Main detection script
β βββ firebase_handler.py # Firebase upload logic
β βββ gps_simulator.py # GPS coordinate generation
β βββ firebase-credentials.json # Service account key (private)
β βββ .env # Environment variables
β βββ requirements.txt # Python dependencies
β βββ venv/ # Virtual environment
β
βββ dashboard/ # React frontend
β βββ public/
β β βββ index.html
β βββ src/
β β βββ components/
β β β βββ Dashboard.jsx # Main dashboard component
β β β βββ MapView.jsx # Interactive map
β β β βββ PathPlanningPanel.jsx
β β β βββ EconomicImpactPanel.jsx
β β β βββ FusionInsightPanel.jsx
β β β βββ AlertsDecisionPanel.jsx
β β β βββ DetectionFeed.jsx
β β β βββ StatsPanel.jsx
β β β βββ LiveStatus.jsx
β β β βββ MissionReportPanel.jsx
β β βββ hooks/
β β β βββ useDetections.js # Firebase data subscription
β β βββ utils/
β β β βββ pathPlanner.js # Spray path algorithm
β β β βββ economicCalculator.js
β β β βββ fusionEngine.js
β β β βββ alertRuleEngine.js
β β β βββ reportGenerator.js
β β βββ firebase/
β β β βββ config.js # Firebase client config
β β βββ App.js
β β βββ index.js
β βββ .env.local # Firebase config (private)
β βββ package.json
β βββ package-lock.json
β
βββ models/ # YOLOv8 model weights
β βββ crop_disease_yolov8.pt
β
βββ test_videos/ # Sample videos for testing
β βββ field_video.mp4
β
βββ README.md # This file
| Variable | Description | Example |
|---|---|---|
FIREBASE_CREDS_PATH |
Path to service account JSON | ./firebase-credentials.json |
FIREBASE_DATABASE_URL |
Firebase Realtime DB URL | https://project.firebaseio.com |
VIDEO_SOURCE |
Video input (0=webcam, path=file) | 0 or test_videos/field.mp4 |
MODEL_PATH |
YOLOv8 model weights path | ../models/crop_disease_yolov8.pt |
CONFIDENCE_THRESHOLD |
Detection confidence filter | 0.5 (0.0 to 1.0) |
SESSION_ID |
Mission/field identifier | FIELD-001 |
FIELD_CENTER_LAT |
Field center latitude | 28.6139 |
FIELD_CENTER_LNG |
Field center longitude | 77.2090 |
All variables must start with REACT_APP_:
| Variable | Description |
|---|---|
REACT_APP_FIREBASE_API_KEY |
Firebase Web API key |
REACT_APP_FIREBASE_AUTH_DOMAIN |
Firebase auth domain |
REACT_APP_FIREBASE_DATABASE_URL |
Realtime Database URL |
REACT_APP_FIREBASE_PROJECT_ID |
Firebase project ID |
REACT_APP_FIREBASE_STORAGE_BUCKET |
Storage bucket URL |
REACT_APP_FIREBASE_MESSAGING_SENDER_ID |
FCM sender ID |
REACT_APP_FIREBASE_APP_ID |
Firebase app ID |
- Start Backend - Begin inference on drone/ground station
- Open Dashboard - Monitor detections in real-time
- Analyze Field - Watch detection markers populate map
- Generate Path - Click "Generate Precision Path" button
- Review Economics - Check ROI and cost savings
- Check Alerts - Review prioritized recommendations
- Generate Report - Click "Generate Mission Report" for PDF
# In backend/inference.py, modify video source:
# Option 1: RTSP stream from drone
VIDEO_SOURCE = "rtsp://drone_ip:8554/stream"
# Option 2: USB camera
VIDEO_SOURCE = 0
# Option 3: IP camera
VIDEO_SOURCE = "http://camera_ip:8080/video"# Place test video in test_videos/
cp /path/to/your/video.mp4 test_videos/field_video.mp4
# Update backend/.env
VIDEO_SOURCE=test_videos/field_video.mp4
# Run backend
python inference.pySymptom: Backend crashes with authentication error
Solution:
# Verify credentials file exists
ls backend/firebase-credentials.json
# Check .env has correct path
cat backend/.env | grep FIREBASE_CREDS_PATH
# Ensure Firebase Admin SDK is installed
pip show firebase-adminSymptom: Connection badge is red, no data flowing
Solution:
# Check backend is running
# Backend terminal should show "Streaming detections..."
# Verify Firebase Database URL matches in both:
# - backend/.env
# - dashboard/.env.local
# Check Firebase Realtime Database rules allow read/write
# Test Firebase connection in browser console:
# Open dashboard β F12 β Console β Check for errorsSymptom: FileNotFoundError: model path not found
Solution:
# Option A: Let YOLOv8 auto-download
# In inference.py, use:
model = YOLO('yolov8n.pt') # Auto-downloads
# Option B: Download manually
cd models
wget https://github.com/ultralytics/assets/releases/download/v0.0.0/yolov8n.pt
# Update MODEL_PATH in .env
MODEL_PATH=../models/yolov8n.ptSymptom: Error: Cannot open video source
Solution:
# Test camera access
python -c "import cv2; print(cv2.VideoCapture(0).read())"
# Try different camera indices
VIDEO_SOURCE=1 # or 2, 3, etc.
# On Linux, check permissions
sudo usermod -a -G video $USER
# Logout and login again
# On macOS, grant terminal camera access
# System Preferences β Security & Privacy β CameraSymptom: Dependency installation errors
Solution:
# Clear npm cache
npm cache clean --force
# Remove node_modules
rm -rf node_modules package-lock.json
# Update npm
npm install -g npm@latest
# Reinstall
npm install
# If still failing, use yarn
npm install -g yarn
yarn installSymptom: Something is already running on port 3000
Solution:
# Option A: Kill process on port 3000
# On macOS/Linux:
lsof -ti:3000 | xargs kill -9
# On Windows:
netstat -ano | findstr :3000
taskkill /PID <PID> /F
# Option B: Use different port
PORT=3001 npm startSymptom: Blank white panel where map should be
Solution:
# Check Leaflet CSS is imported
# In dashboard/src/index.js or App.js:
import 'leaflet/dist/leaflet.css';
# Verify internet connection (map tiles load from OpenStreetMap)
# Check browser console for errors
# F12 β Console β Look for 404 errors
# Try clearing browser cache
# Ctrl+Shift+R (hard refresh)Symptom: All detection markers at same location
Solution:
# This is normal if using simulated GPS
# GPS simulator adds random offsets to FIELD_CENTER
# To use real GPS:
# 1. Ensure drone sends GPS in detection payload
# 2. Modify backend/inference.py to include actual GPS
# 3. Remove GPS enrichment from Dashboard.jsx# Use smaller YOLOv8 model
model = YOLO('yolov8n.pt') # Nano (fastest)
# vs
model = YOLO('yolov8x.pt') # Extra large (slowest)
# Reduce frame processing
# In inference.py, skip frames:
if frame_count % 3 == 0: # Process every 3rd frame
results = model(frame)# In inference.py, add:
import gc
gc.collect() # Periodically free memory
# Reduce detection history retention
# In Dashboard.jsx:
const recentDetections = detections.slice(0, 20) # Keep only 20{
"detections": {
"SESSION-ID": {
"detection-uuid-1": {
"frame_id": 123,
"timestamp": "2026-01-17T01:50:00.000Z",
"detection_count": 2,
"detections": [
{
"class_name": "Early Blight",
"confidence": 0.87,
"bbox": [100, 150, 200, 250]
}
],
"gps": {
"lat": 28.6145,
"lng": 77.2095
}
}
}
}
}| Field | Type | Description |
|---|---|---|
id |
string | Unique detection ID (UUID) |
frame_id |
integer | Video frame number |
timestamp |
ISO 8601 | Detection timestamp |
detection_count |
integer | Number of diseases in frame |
detections |
array | List of detected diseases |
gps |
object | GPS coordinates {lat, lng} |
| Field | Type | Description |
|---|---|---|
class_name |
string | Disease name |
confidence |
float | Confidence score (0.0-1.0) |
bbox |
array | Bounding box [x1, y1, x2, y2] |
We welcome contributions! Please follow these guidelines:
- Fork the repository
- Create feature branch:
git checkout -b feature/your-feature - Commit changes:
git commit -m 'Add your feature' - Push to branch:
git push origin feature/your-feature - Submit Pull Request
# Install development dependencies
pip install black flake8 pytest # Python
npm install --save-dev eslint prettier # JavaScript
# Run linters
black backend/ # Format Python code
npm run lint # Format JavaScriptThis project is licensed under the MIT License - see the LICENSE file for details.