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.
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.
- ๐ฌ 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.
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 |
- Python 3.11
- A Google Gemini API key (get one)
- (Optional) a Firebase service-account JSON for persistence
git clone https://github.com/Mohamedkhattab02/PlantGuard-AI
cd "PlantGuard AI"python -m venv .venv
.\.venv\Scripts\Activate.ps1pip install -r requirements.txtCopy-Item .env.example .envGEMINI_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=falsePlace 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.jsonare git-ignored. Only.env.exampleis tracked.
python micro_final.py # backward-compatible entry point
# or: python -m plantguard.appThe UI launches at http://127.0.0.1:7860. A public link is created only if GRADIO_SHARE=true.
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.
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
| 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 |
pytest # 33 tests: label parsing, gamification, MapReduce, alerts, i18n, + UI build smoke test
ruff check . # lint
black . # formatThe UI build smoke test constructs the entire Gradio graph without the model, network, or API keys โ catching component-API regressions in CI.
| 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_labeluses a known-plant table + overrides (e.g."Cedar Apple Rust"โ Apple) instead of a naive first-word heuristic.
| 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 |
transformers5.x droppedtext2text-generationโ local FLAN-T5 replaced by Gemini.transformers5.x can't auto-detect the image processor โ explicitAutoModelForImageClassification+AutoImageProcessor.- Gradio 6 moved
theme/cssfromBlocks(...)tolaunch()โ 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.
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.
Released under the MIT License โ see LICENSE.
Built with ๐ฑ for healthier crops.