Skip to content

Mohamedkhattab02/PlantGuard-AI

Folders and files

NameName
Last commit message
Last commit date

Latest commit

ย 

History

6 Commits
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 
ย 

Repository files navigation

๐ŸŒฑ PlantGuard AI

AI-Powered Plant Disease Diagnosis, Research & Field Monitoring

Computer-vision diagnosis ยท semantic RAG research assistant ยท live IoT telemetry with smart alerts ยท weather context ยท gamification โ€” in one elegant app, plus a headless REST API.

Python Gradio Transformers Gemini FastAPI Firebase Tests License


๐Ÿ“– Overview

PlantGuard AI helps growers and researchers detect plant diseases from a photo, ask grounded questions over a corpus of scientific papers, and monitor live field conditions with smart alerts โ€” behind a single, polished web UI and a decoupled REST API.

Capability Engine What it does
๐Ÿ”ฌ Image diagnosis MobileNetV2 (38-class) Classifies a leaf photo into plant + disease with a confidence score, top-3, and a low-confidence guard.
๐Ÿ“š Semantic RAG Gemini embeddings + Gemini 2.5 Flash Vector retrieval over a local PDF library; answers grounded in sources with citations.
๐Ÿฉบ Diagnosis + treatment One structured Gemini call + curated knowledge base Returns explanation, severity, and a dosage-aware treatment plan in a single round-trip.
๐Ÿ“ก IoT + alerts REST backend + Firebase RTDB Concurrent feed fetch, live dashboards, and agronomic threshold alerts.
๐ŸŒฆ๏ธ Weather context Open-Meteo (no key) Correlates humidity/rain with fungal-disease risk.
๐Ÿ—‚๏ธ History & PDF Firebase + fpdf2 Per-user diagnosis history and one-click PDF reports.
๐ŸŽฎ Gamification Per-user, persistent Daily missions and points that persist across restarts.

Origin: started as a single-file Colab port (micro_final.py) and was refactored into a modular, tested, production-grade package. See ROADMAP.md for the full engineering plan โ€” every item in it has been implemented.


โœจ Features

  • ๐Ÿ”ฌ Disease Diagnosis โ€” upload or capture from webcam; get plant, disease, confidence, top-3 predictions, a low-confidence warning, a grounded explanation, and a treatment plan. Batch mode diagnoses many images at once for field surveys.
  • ๐Ÿ“š Research Assistant โ€” semantic (embedding-based) Q&A over your PDF library, with citations and answer caching.
  • ๐Ÿ“Š Sensors & ๐Ÿ“ˆ Dashboard โ€” fetch raw feeds, or render concurrent live time-series with aggregated stats and threshold alerts (e.g. soil low โ†’ irrigate), plus weather.
  • ๐Ÿ—‚๏ธ History โ€” every diagnosis saved per user, with an image gallery and timeline.
  • ๐Ÿ“„ PDF Reports โ€” export any diagnosis (image + disease + treatment) to a branded PDF.
  • ๐ŸŽฎ Daily Missions โ€” per-user, persistent points/levels that auto-reset daily.
  • ๐Ÿค– Elegant Floating Assistant โ€” a redesigned chat widget explaining the platform.
  • ๐Ÿ”Œ REST API โ€” the same engines exposed via FastAPI for automations or a future mobile app.
  • ๐Ÿ›ก๏ธ Graceful degradation โ€” missing Firebase / offline sensors / unavailable embeddings all degrade to safe fallbacks instead of crashing.

๐Ÿ—๏ธ Architecture

A clean, microservice-style package with a thin UI and API on top. Heavy initialization happens once at startup; nothing expensive runs at import time, so the logic is fully testable.

                        โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”
                        โ”‚   plantguard/app.py   (Gradio UI)         โ”‚
                        โ”‚   plantguard/api.py   (FastAPI REST)      โ”‚
                        โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”ฌโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜
                                        โ”‚  build_services()
        โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”ผโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”
        โ–ผ               โ–ผ                โ–ผ                โ–ผ               โ–ผ
  โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”  โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”   โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”   โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”  โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”
  โ”‚  image    โ”‚  โ”‚    rag     โ”‚   โ”‚    iot     โ”‚   โ”‚gamificationโ”‚  โ”‚  history   โ”‚
  โ”‚ MobileNet โ”‚  โ”‚ embeddings โ”‚   โ”‚ retry +    โ”‚   โ”‚ per-user   โ”‚  โ”‚ per-user   โ”‚
  โ”‚ +labels   โ”‚  โ”‚ +Gemini    โ”‚   โ”‚ concurrent โ”‚   โ”‚ +persist   โ”‚  โ”‚ +PDF       โ”‚
  โ”‚ +top-3    โ”‚  โ”‚ +KB +cache โ”‚   โ”‚ +MapReduce โ”‚   โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜  โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜
  โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜  โ””โ”€โ”€โ”€โ”€โ”€โ”ฌโ”€โ”€โ”€โ”€โ”€โ”€โ”˜   โ””โ”€โ”€โ”€โ”€โ”€โ”ฌโ”€โ”€โ”€โ”€โ”€โ”€โ”˜
                       โ”‚                 โ”‚
                 โ”Œโ”€โ”€โ”€โ”€โ”€โ–ผโ”€โ”€โ”€โ”€โ”€โ”    โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ–ผโ”€โ”€โ”€โ”€โ”€โ”€โ”   โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”  โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”
                 โ”‚ documents โ”‚    โ”‚   alerts    โ”‚   โ”‚ weather  โ”‚  โ”‚  store   โ”‚
                 โ”‚ parse-onceโ”‚    โ”‚ thresholds  โ”‚   โ”‚OpenMeteo โ”‚  โ”‚ Firebase โ”‚
                 โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜    โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜   โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜  โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜

  Cross-cutting:  config.py (settings/logging) ยท http_client.py (retry session) ยท i18n.py
Module Responsibility
config.py Typed settings from env, logging, UTF-8 console
http_client.py Shared requests session with exponential-backoff retry
services/store.py Firebase RTDB wrapper (no insecure key download)
services/image.py Classifier, robust label parsing, confidence, validation
services/rag.py Embedding/TF-IDF retrieval, system-instruction, caching, rate limiting
services/documents.py Parse each PDF once into a shared corpus
services/knowledge_base.py Curated treatment guidance with dosages
services/iot.py History, concurrent fetch, MapReduce aggregates
services/alerts.py Pure agronomic threshold rules
services/gamification.py Per-user, persistent missions/points
services/history.py ยท reports.py ยท weather.py History, PDF reports, weather context

๐Ÿš€ Quick Start

Prerequisites

  • Python 3.11
  • A Google Gemini API key (get one)
  • (Optional) a Firebase service-account JSON for persistence

1. Clone & enter

git clone https://github.com/Mohamedkhattab02/PlantGuard-AI
cd "PlantGuard AI"

2. Virtual environment (recommended)

python -m venv .venv
.\.venv\Scripts\Activate.ps1

3. Install (pinned, reproducible)

pip install -r requirements.txt

4. Configure secrets

Copy-Item .env.example .env
GEMINI_API_KEY=your_gemini_api_key_here
DATABASE_URL=https://your-project-default-rtdb.firebaseio.com/
FIREBASE_KEY_PATH=firebase-key.json
BASE_URL=https://your-server.onrender.com/
# Optional launch controls (default to local/safe):
# GRADIO_SHARE=false
# DEBUG=false

Place your Firebase key as firebase-key.json in the project root (it is never auto-downloaded โ€” provide it yourself).

๐Ÿ”’ .env, firebase-key.json, and *-key.json are git-ignored. Only .env.example is tracked.

5. Run the app

python micro_final.py        # backward-compatible entry point
# or:  python -m plantguard.app

The UI launches at http://127.0.0.1:7860. A public link is created only if GRADIO_SHARE=true.


๐Ÿ”Œ REST API (headless)

uvicorn plantguard.api:create_app --factory --port 8000
Method & path Purpose
GET /health Liveness + Firebase status
POST /diagnose Multipart image upload โ†’ diagnosis (+ advice if diseased)
POST /research { "question": "...", "top_k": 2 } โ†’ grounded answer + sources
GET /sensors/{feed}?limit=10 Raw sensor history
GET /dashboard Aggregated stats + alerts

Interactive docs at http://127.0.0.1:8000/docs.


๐Ÿ“‚ Project Structure

PlantGuard AI/
โ”œโ”€โ”€ micro_final.py          # Backward-compatible launcher (delegates to the package)
โ”œโ”€โ”€ plantguard/             # The application package
โ”‚   โ”œโ”€โ”€ config.py ยท http_client.py ยท i18n.py
โ”‚   โ”œโ”€โ”€ app.py              # Gradio UI
โ”‚   โ”œโ”€โ”€ api.py              # FastAPI service
โ”‚   โ””โ”€โ”€ services/           # image ยท rag ยท documents ยท knowledge_base ยท iot ยท
โ”‚                           #   alerts ยท gamification ยท history ยท reports ยท weather ยท store
โ”œโ”€โ”€ tests/                  # pytest suite (pure logic + UI build smoke test)
โ”œโ”€โ”€ articles/               # ๐Ÿ“š Research PDFs โ€” indexed for RAG
โ”œโ”€โ”€ IOT_DETAILS/            # ๐Ÿ“ก IoT JSON exports
โ”œโ”€โ”€ requirements.txt        # Pinned dependencies
โ”œโ”€โ”€ pyproject.toml          # Packaging + ruff/black + pytest config
โ”œโ”€โ”€ ROADMAP.md              # Engineering plan (fully implemented)
โ””โ”€โ”€ LICENSE                 # MIT

โš™๏ธ Configuration

Variable Default Purpose
GEMINI_API_KEY โ€” (required) Gemini key; the app fails loudly without it
DATABASE_URL demo RTDB Firebase Realtime DB URL
FIREBASE_KEY_PATH firebase-key.json Service-account key path
BASE_URL demo Render URL IoT REST backend
GRADIO_SHARE false Create a public tunnel
DEBUG false Verbose logs + Gradio debug
GRADIO_SERVER_NAME / GRADIO_SERVER_PORT 127.0.0.1 / 7860 Bind address

๐Ÿงช Testing & Quality

pytest          # 33 tests: label parsing, gamification, MapReduce, alerts, i18n, + UI build smoke test
ruff check .    # lint
black .         # format

The UI build smoke test constructs the entire Gradio graph without the model, network, or API keys โ€” catching component-API regressions in CI.


๐Ÿง  Model & API Reference

Component Identifier / Endpoint
Image classifier linkanjarad/mobilenet_v2_1.0_224-plant-disease-identification
LLM gemini-2.5-flash (system-instruction, JSON mode for structured advice)
Embeddings models/text-embedding-004 (cosine retrieval, disk-cached; TF-IDF fallback)
IoT API GET {BASE_URL}/history?feed=<feed>&limit=<n>
Weather Open-Meteo (geocoding + current conditions, no key)

Label parsing: the model emits human-readable labels ("Tomato with Late Blight", "Healthy Apple"). parse_label uses a known-plant table + overrides (e.g. "Cedar Apple Rust" โ†’ Apple) instead of a naive first-word heuristic.


๐Ÿ› ๏ธ Tech Stack

Layer Technology
UI Gradio 6.x (custom theme + CSS, redesigned chat widget)
API FastAPI ยท Uvicorn ยท Pydantic
Vision ๐Ÿค— Transformers 5.x ยท PyTorch ยท MobileNetV2
LLM / RAG Google Gemini 2.5 Flash ยท Gemini embeddings ยท scikit-learn (TF-IDF fallback) ยท NumPy
Docs / Data pypdf ยท pandas ยท matplotlib ยท fpdf2
Backend Firebase Admin ยท requests (retry session)
Tooling pytest ยท ruff ยท black ยท python-dotenv

โš ๏ธ Compatibility Notes

  • transformers 5.x dropped text2text-generation โ†’ local FLAN-T5 replaced by Gemini.
  • transformers 5.x can't auto-detect the image processor โ†’ explicit AutoModelForImageClassification + AutoImageProcessor.
  • Gradio 6 moved theme/css from Blocks(...) to launch() โ€” applied accordingly.
  • Gradio 6 chatbot uses the messages format ({"role","content"}) by default.
  • Windows console is cp1252 โ†’ UTF-8 is forced at startup so emoji never crash logging.

๐Ÿ—บ๏ธ Roadmap Status

All ROADMAP.md items are implemented. Pragmatic scoping notes:

  • User accounts use lightweight username-based persistence (per-user history/progress) rather than full OAuth.
  • Sensor alerting ships the rule engine + in-app alerts; email/Telegram push is left as a hook.
  • Bilingual UI was intentionally consolidated to English-only per product decision.

๐Ÿ“œ License

Released under the MIT License โ€” see LICENSE.


Built with ๐ŸŒฑ for healthier crops.

About

๐ŸŒฑ AI-powered plant disease diagnosis, RAG research assistant, and live IoT field monitoring โ€” unified in one elegant app, plus a FastAPI REST API.

Topics

Resources

License

Stars

Watchers

Forks

Releases

No releases published

Packages

 
 
 

Contributors

Languages