Skip to content

Latest commit

Β 

History

6 Commits

Folders and files

NameName
Last commit message
Last commit date
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 

Repository files navigation


🌾 AgriIntelligence

An explainable, multi-module AI platform for precision farming β€” soil to market, in one service.

Thirteen production modules. Every prediction explained. Every number reproducible.


Python FastAPI React TypeScript PyTorch scikit-learn LightGBM Docker Tests License: MIT


🧭 The story behind this project

Most digital-agriculture tools share two flaws. They are fragmented β€” one app for crop selection, another for disease, a third for prices, none of them talking to each other β€” and they are opaque, returning a number with no account of why.

AgriIntelligence was built to prove that a single, coherent platform can do better: thirteen decision modules behind one API and one UI, where every prediction carries its own explanation (SHAP for tabular models, Grad-CAM for vision), every model is trained on public data under a leakage-free protocol, and every reported number is reproducible from the repo.

It is engineered like a product, not a notebook: typed APIs, 68 automated tests, a one-command container, CI, an end-to-end smoke test, a React/TypeScript front end β€” and an IEEE-style research paper generated from the same models, complete with an ablation and a statistical significance test.

πŸ’‘ What makes it honest: when a model fails, this project reports it. The disease classifier hits 96.5% on clean images but collapses to 10.1% under blur β€” a finding included in the paper as a real-world deployment caveat rather than hidden. Engineering integrity is a feature here.


✨ Highlights

🧩 13 modules, one service Crop, disease, weather, irrigation, yield, fertilizer, profit, market, sustainability, digital twin, schemes, dashboards, AI assistant
πŸ” Explainable by construction SHAP attributions on every tabular prediction; Grad-CAM saliency on every diagnosis
πŸ”— End-to-end decision chain Soil β†’ recommended crop β†’ predicted yield β†’ forecast price β†’ profit & ROI, fully wired
πŸ€– Tool-calling AI assistant A multilingual LLM that answers by invoking the platform's own models, not hallucinating
πŸ“Š Honest, reproducible evaluation Leakage-free splits, an ablation, a Diebold-Mariano test, per-class tables, a robustness study
πŸš€ Ships like a product Typed REST API, 68 tests, Docker + Hugging Face Spaces deploy, CI, smoke test, React UI
πŸ“„ Research-grade An IEEE manuscript with 11 figures generated from the real trained models

πŸ–₯️ The platform

Add a screenshot of the running dashboard here: docs/assets/dashboard.png The React UI ships a Dashboard, Digital Twin, and a dedicated page for each of the 13 modules, with light/dark themes, Recharts visualizations, and Framer Motion transitions.

Grad-CAM disease diagnosis Price forecast with uncertainty band
Left: a leaf diagnosis with its Grad-CAM saliency overlay (real model output). Right: a 9-month price forecast with an 80% uncertainty band.

Architecture

A modular monolith: a single FastAPI gateway fronts thirteen self-contained Python packages, each with its own pipeline and tests. Models load lazily to bound memory. Only weather, commodity prices, and the optional LLM call out to external services.

flowchart TD
    subgraph Clients
        A[React + TypeScript SPA]
        B[Built-in Web UI]
    end
    A & B --> GW[FastAPI Gateway<br/>REST Β· CORS Β· OpenAPI Β· lazy loading]

    GW --> AG[Agronomy<br/>Crop Β· Yield Β· Fertilizer]
    GW --> CV[Computer Vision<br/>Disease Β· Grad-CAM]
    GW --> EN[Environment<br/>Weather Β· Irrigation FAO-56]
    GW --> EC[Economics<br/>Profit Β· Market LSTM]
    GW --> SU[Sustainability Β· Digital Twin Β· Schemes]
    GW --> AS[AI Assistant<br/>tool-calling router]

    AS -.calls.-> AG & CV & EN & EC & SU

    AG & CV & EC --> M[(Models & artifacts<br/>.pkl / .pt / .csv)]
    EN --> EXT1[Open-Meteo API]
    EC --> EXT2[World Bank prices]
    AS --> EXT3[LLM API]
Loading

The full architecture diagram (vector) lives at docs/assets/architecture.png.


Quick start

Run locally (Python)

git clone https://github.com/bodapatisaikrishna/agri-intelligence.git
cd agri-intelligence
pip install -r api/requirements.txt
python -m vision.download_data        # fetch disease training images (regenerable)
uvicorn api.main:app --reload         # β†’ http://127.0.0.1:8000

Run with Docker (one command)

docker compose up --build             # β†’ http://127.0.0.1:8000
docker compose run --rm smoke         # prove every endpoint responds (skips LLM)

Run the React front end

cd frontend && npm install && npm run dev   # β†’ http://127.0.0.1:5173

Deploy free

The repo is Hugging Face Spaces (Docker SDK) ready β€” CPU-only PyTorch, non-root, port 8000. See docs/DEPLOY.md.


Usage examples

Recommend a crop (with SHAP explanation):

curl -X POST localhost:8000/predict -H "Content-Type: application/json" \
  -d '{"N":90,"P":42,"K":43,"temperature":20.9,"humidity":82,"ph":6.5,"rainfall":202.9}'

The full decision chain β€” yield and price pulled automatically into a profit analysis:

curl -X POST localhost:8000/analyze-profit -H "Content-Type: application/json" -d '{
  "area_ha": 2,
  "yield_query": {"Area":"India","Item":"Wheat","Year":2013,
                  "average_rain_fall_mm_per_year":1100,"pesticides_tonnes":75000,"avg_temp":25},
  "price_query": {"commodity":"Wheat","use":"current"}
}'

Diagnose a leaf (returns disease, severity, treatment, Grad-CAM):

curl -X POST localhost:8000/predict-disease -F "file=@leaf.jpg"

Interactive API docs are auto-generated at http://127.0.0.1:8000/docs.


Results & benchmarks

All metrics are on held-out test data with feature scaling fit on the training partition only. Numbers are reproducible via the scripts in paper/ and stored in reports/.

Module Model Metric Result
Crop recommendation Random Forest (+ SHAP) Accuracy / Macro-F1 99.5% (CV 99.49 Β± 0.52%)
Leaf disease EfficientNet-B0 (+ Grad-CAM) Accuracy (16 classes) 96.5%
Yield prediction LightGBM quantile (+ SHAP) RΒ² / MAE 0.97 / 0.58 t/ha
Market forecast LSTM (log-return) MAPE vs. random walk 4.89% vs 4.91%

Where this project earns trust: it reports what doesn't work

Disease robustness under corruptions Forecasting ablation
  • Robustness (left): the disease model is robust to brightness and moderate noise, but collapses to 10.1% under blur β€” a quantified lab-to-field domain gap, reported honestly.
  • Forecasting ablation (right): commodity prices are near-random-walk. A naive level-LSTM (5.15% MAPE) loses; our log-return-anchored design (4.89%) matches the random walk β€” and a Diebold-Mariano test (p = 0.33) confirms there is no significant difference. We report this rather than cherry-pick a flattering metric.
  • Latency: rule/boosted modules respond in < 3 ms, the SHAP-explained crop model in 14 ms, and disease diagnosis with Grad-CAM in 245 ms β€” all interactive on CPU, no GPU required.

Engineering decisions that matter

1. Three OpenMP runtimes in one process β†’ a single-thread fix


PyTorch, LightGBM, and scikit-learn each bundle their own OpenMP runtime. Loading all three in one process segfaults on macOS/Anaconda. The platform pins OMP_NUM_THREADS=1 before any numerical import β€” which also happens to be the correct setting for single-request inference workers. Documented in conftest.py and the Dockerfile.

2. Forecasting that can't lose to the baseline (by design)


Predicting price levels directly lags badly. The market model instead predicts a next-month log-return and anchors the forecast on the last price: pΜ‚β‚œ = exp(log pβ‚œβ‚‹β‚ + rΜ‚β‚œ). A zero prediction reduces exactly to a random walk, so the model can only add value β€” never underperform the naive baseline. The ablation above proves it.

3. Explainability is mandatory, not optional


Every tabular endpoint returns SHAP attributions; every vision diagnosis returns a Grad-CAM overlay. Explanations aren't a debug afterthought β€” they're part of the response contract.

4. The AI assistant is grounded, not generative


Native LLM tool-calling proved unreliable on the target endpoint, so the assistant uses a robust two-stage JSON router: the LLM emits a structured action selecting one of the platform's tools, the tool runs locally against the real models, and the LLM composes the final answer from that output β€” in the user's language.


Tech stack & why

Layer Choice Why
API FastAPI Async, typed, auto OpenAPI docs, trivial to test
Tabular ML scikit-learn, LightGBM Strong baselines, native SHAP support, fast CPU inference
Vision PyTorch / EfficientNet-B0 High accuracy at low compute; clean Grad-CAM hooks
Forecasting PyTorch LSTM Sequence modeling with a custom return-anchoring head
Explainability SHAP, Grad-CAM The de-facto standards for tabular and vision attribution
Frontend React + TypeScript + Tailwind + Recharts + Framer Motion Type-safe, component-driven, premium UX with real charts
Infra Docker, GitHub Actions, Hugging Face Spaces One-command reproducible deploy on free infrastructure

Project structure

agri-intelligence/
β”œβ”€β”€ api/               FastAPI app + crop module      (entrypoint: api.main:app)
β”œβ”€β”€ vision/            Disease detection (EfficientNet-B0 + Grad-CAM)
β”œβ”€β”€ weather/  irrigation/        Weather risk Β· FAO-56 irrigation
β”œβ”€β”€ yield_pred/ fertilizer/ profit/ market/   Agronomy + economics
β”œβ”€β”€ carbon/ twin/ schemes/ dashboards/         Sustainability Β· twin Β· schemes Β· dashboards
β”œβ”€β”€ assistant/         Multilingual tool-calling LLM assistant
β”œβ”€β”€ satellite/         Sentinel-2 / Google Earth Engine script
β”œβ”€β”€ data/  models/  reports/      Artifacts + metrics loaded at runtime
β”œβ”€β”€ frontend/          React + TypeScript SPA
β”œβ”€β”€ paper/             IEEE manuscript, figures, reproducible eval scripts
β”œβ”€β”€ scripts/           smoke_test.py Β· deploy_hf.py
β”œβ”€β”€ notebooks/  docs/  Legacy exploration Β· deploy guide Β· report
└── Dockerfile  docker-compose.yml  conftest.py  pytest.ini

Service packages sit at the top level by design β€” they import one another by name and resolve data//models/ from the repo root, keeping the entrypoint, container, and tests simple.


Testing & reproducibility

pytest -m "not network"          # 68 tests across all modules
python scripts/smoke_test.py     # hit every endpoint end-to-end and assert 200
python -m paper.make_figures     # regenerate every paper figure from the real models
  • 68 automated tests, model-loading guarded so they stay green on a fresh checkout.
  • A smoke test that boots the app and verifies every module endpoint.
  • Every figure, table, ablation, and significance test in the paper is regenerated from versioned artifacts.

πŸ“„ Research

This work is written up as an IEEE-style manuscript in paper/ β€” architecture, methodology, an ablation, a Diebold-Mariano test, per-class tables, a robustness study, and 11 figures generated from the real models. Build it with any TeX Live install or on Overleaf.


Roadmap

  • Field-image fine-tuning (PlantDoc) to close the disease domain gap
  • Persistence layer (SQLite) so dashboards remember farms and assistant history
  • Auth + multi-tenant farm management for a real pilot
  • Integrate Sentinel-2 NDVI into the digital twin
  • Federated training across farms (privacy-preserving)
  • Provider-agnostic assistant with a self-hosted model fallback

Contributing

Contributions are welcome.

  1. Fork the repo and create a branch: git checkout -b feature/your-feature
  2. Install deps and run the suite: pytest -m "not network"
  3. Keep the bar: new modules ship with tests and an explanation contract (SHAP/Grad-CAM or a documented rule trace).
  4. Open a PR describing the change and the evidence it works.

License

Released under the MIT License β€” see LICENSE.


Acknowledgements

Built on the shoulders of open data and open source: the PlantVillage dataset, the FAO/World Bank crop-yield and commodity-price data, Open-Meteo, and the FAO-56 evapotranspiration methodology. Models and methods build on EfficientNet, LightGBM, SHAP, and Grad-CAM. Full citations are in paper/references.bib.


Designed and engineered by bodapatisaikrishna Β· built to be useful, explainable, and honest.

About

AI-powered agricultural intelligence platform: 13 explainable modules (crop, disease, weather, irrigation, yield, fertilizer, profit, market, sustainability, digital twin, schemes, dashboards, AI assistant) behind one FastAPI service + React frontend. SHAP/Grad-CAM explainability, tests, Docker deploy, and an IEEE manuscript.

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages