Skip to content

ishanb18/Agroculture

 
 

Repository files navigation

🌾 Agroculture — AI-Powered Agriculture Assistant

Agroculture is a context-aware, AI-powered agriculture assistant built for Indian farmers. It combines real-time market data (Agmarknet), live weather forecasting, a RAG-based knowledge engine, bilingual (Hindi/English) voice I/O, proactive smart alerts, and a clean web UI — all in a single deployable backend.


✨ Key Features

Feature Description
🧠 Contextual Chat Agent Multi-intent NLP pipeline routes queries to weather, market, agri-advisory, policy, logistics, and compliance handlers
📈 Live Market Prices Real-time mandi prices via the Agmarknet / data.gov.in API with trend analysis and comparisons
🌦️ Weather Forecasting Open-Meteo powered daily forecasts with farmer-specific summaries (rain probability, ET₀, wind gusts)
🔔 Proactive Alerts Hourly scheduled background job generates personalised weather alerts and government scheme updates per user
🎙️ Bilingual Voice I/O Hindi-first ASR using OpenAI Whisper / faster-whisper; TTS via Microsoft Edge voices (hi-IN-SwaraNeural, en-IN-NeerjaNeural)
📚 RAG Knowledge Base ChromaDB + sentence-transformers vector store built from agronomy PDFs, Wikipedia articles, and ICAR publications
🌱 Planting Decision Engine Go/no-go planting advisor that fuses crop type, live weather, and LLM reasoning into a structured JSON decision
👤 Farmer Onboarding Conversational profile builder (location, land size, budget, crops) for personalised recommendations
🌐 Web UI Single-file index.html frontend — no build step required

🏗️ Architecture

┌─────────────────────────────────────────────────────────────┐
│                        index.html (UI)                      │
└───────────────────────────┬─────────────────────────────────┘
                            │  HTTP / REST
┌───────────────────────────▼─────────────────────────────────┐
│                   FastAPI  (main.py)                        │
│  ┌──────────────┐  ┌───────────────┐  ┌───────────────────┐ │
│  │ Intent Router│  │ Scheduler     │  │  Voice Endpoints  │ │
│  │ detect_intent│  │ APScheduler   │  │ /voice/transcribe │ │
│  │ _nlp()       │  │ (hourly jobs) │  │ /voice/ask  /tts  │ │
│  └──────┬───────┘  └───────────────┘  └───────────────────┘ │
└─────────┼───────────────────────────────────────────────────┘
          │
   ┌──────▼────────────────────────────────────────────┐
   │              Core Modules                         │
   │  data_sources.py  ──  Agmarknet + Open-Meteo APIs │
   │  qna.py           ──  RAG query + Mistral LLM     │
   │  rag.py           ──  ChromaDB ingestion pipeline  │
   │  ner_utils.py     ──  spaCy location extractor    │
   │  translator.py    ──  Language detect + translate  │
   │  url_checker.py   ──  Source validation utilities  │
   └───────────────────────────────────────────────────┘

📁 Project Structure

Agroculture/
├── main.py           # FastAPI application — all API endpoints & scheduler
├── data_sources.py   # Agmarknet market prices + Open-Meteo weather helpers
├── qna.py            # RAG query engine + Mistral LLM advisory generator
├── rag.py            # One-time script to build the ChromaDB vector store
├── ner_utils.py      # Named entity recognition (location extraction)
├── translator.py     # Language detection, translation & transliteration
├── url_checker.py    # URL validation and source management utilities
├── index.html        # Frontend single-page web UI
├── requirements.txt  # Python dependencies
└── agri_db/          # Auto-generated ChromaDB vector store (after rag.py)

🚀 Quick Start

1. Prerequisites

  • Python 3.10 or 3.11 (recommended)
  • pip installed
  • Internet connectivity for API calls and model downloads

2. Clone & Set Up Virtual Environment

# Windows PowerShell
python -m venv .venv
.venv\Scripts\Activate.ps1

# macOS / Linux
python -m venv .venv
source .venv/bin/activate

3. Install Dependencies

pip install -r requirements.txt

4. Configure Environment Variables

Create a .env file in the project root:

AGMARKNET_API_KEY=your_data_gov_in_api_key
MISTRAL_API_KEY=your_mistral_api_key
Variable Where to Get
AGMARKNET_API_KEY data.gov.in — register for a free API key
MISTRAL_API_KEY console.mistral.ai

5. Build the RAG Knowledge Base (one-time)

python rag.py

This downloads and embeds agronomy PDFs and Wikipedia articles into a local ChromaDB store at agri_db/. Takes ~5–10 minutes on first run.

6. Start the Backend

uvicorn main:app --host 127.0.0.1 --port 8000 --reload
  • 📖 Interactive API docs: http://127.0.0.1:8000/docs
  • 🔗 ReDoc: http://127.0.0.1:8000/redoc

7. Open the UI

Open index.html directly in your browser, or serve it locally:

python -m http.server 5173
# Then visit: http://127.0.0.1:5173/index.html

🔌 API Reference

Onboarding & Profile

Method Endpoint Description
GET /status?user_id=<id> Check if user has completed onboarding
POST /chat?user_id=<id> Step through the conversational onboarding flow

AI Advisory

Method Endpoint Description
POST /ask Context-aware Q&A (weather, market, policy, agri, logistics)
GET /get-suggestion?user_id=<id>&category=<crop|land|budget> On-demand personalised suggestion
POST /plan/plant Go/no-go planting decision based on live weather

Alerts

Method Endpoint Description
GET /alerts?user_id=<id> Fetch latest alerts and scheme suggestions
POST /alerts/run-now?user_id=<id> Trigger alert generation immediately

Weather

Method Endpoint Description
GET /weather_summary?location=<city> Compact dashboard weather metrics

Voice (ASR + TTS)

Method Endpoint Description
POST /voice/transcribe Upload audio → transcribed text (Whisper)
POST /voice/ask Upload audio → answer text + base64 MP3
POST /tts Text → base64 MP3 (auto en-IN / hi-IN voice)

🧠 How It Works

Intent Detection Pipeline

Each /ask query is routed through detect_intent_nlp() which classifies it into one of:

weather → get_weather_forecast() + Mistral LLM
market  → agmark_qna_answer()   (Agmarknet API + fuzzy matching)
agriculture → get_answer_from_books() (RAG + LLM)
policy  → get_answer_from_books() (RAG + LLM)
logistics / compliance / general → get_answer_from_books()

RAG Pipeline (rag.py)

  1. Fetch — Downloads PDFs (via PyMuPDF) and Wikipedia articles (via BeautifulSoup)
  2. Chunk — Splits into overlapping 1000-word chunks (200-word overlap)
  3. Embed — Uses all-MiniLM-L6-v2 via sentence-transformers
  4. Store — Persists to ChromaDB with cosine similarity index

Proactive Alerts (APScheduler)

Every hour the scheduler calls check_for_personalized_alerts() for each registered user:

  1. Fetches live weather for the user's location
  2. Prompts Mistral to generate ALERT: + 3 SUGGESTION: lines
  3. Fetches applicable Indian government schemes for the farmer's profile
  4. Stores results in an in-memory list, served via GET /alerts

🛠️ Tech Stack

Layer Technology
Backend FastAPI 0.115, Uvicorn, APScheduler 3.10
LLM Mistral AI (mistralai SDK)
Vector DB ChromaDB 0.5 + sentence-transformers (all-MiniLM-L6-v2)
ASR OpenAI Whisper (fallback: faster-whisper on CPU, int8)
TTS Microsoft Edge TTS (edge-tts) — Indian voices
Market Data Agmarknet via data.gov.in API
Weather Open-Meteo (free, no API key needed)
Geocoding pgeocode + Open-Meteo geocoder
NER / NLP rapidfuzz fuzzy matching, regex-based intent & commodity extractor
Frontend Vanilla HTML/CSS/JS (index.html)

⚙️ Configuration & Tips

  • Hindi ASR: Voice input defaults to lang=hi to avoid Urdu auto-detection. Pass ?lang=en to /voice/ask for English queries.
  • TTS Voices: English uses en-IN-NeerjaNeural; Hindi/Devanagari text automatically switches to hi-IN-SwaraNeural.
  • Alerts frequency: Default is hourly. Use POST /alerts/run-now?user_id=<id> to trigger on demand during development.
  • Whisper compatibility: If Whisper fails due to NumPy/Numba version mismatches, the system automatically falls back to faster-whisper (CPU, int8).
  • RAG refresh: Re-run python rag.py anytime to add new knowledge sources by editing SOURCE_URLS in rag.py.

📋 Requirements

See requirements.txt for pinned versions. Key dependencies:

fastapi==0.115.0
uvicorn[standard]==0.30.6
apscheduler==3.10.4
mistralai==0.4.0
chromadb==0.5.5
sentence-transformers==2.6.1
torch>=2.2.0
edge-tts==6.1.9
faster-whisper==1.0.3
openai-whisper==20231117
rapidfuzz==3.9.6
pgeocode==0.5.0

🗺️ Roadmap

  • PostgreSQL / Redis persistence for user profiles and alerts
  • Multi-language translation pipeline (Tamil, Telugu, Marathi)
  • Mobile-responsive PWA frontend
  • Real-time crop price push notifications
  • Image-based pest/disease detection (vision LLM)
  • Integration with e-NAM for direct market linkage

🤝 Contributing

Contributions are welcome! Please open an issue first to discuss major changes.

  1. Fork the repository
  2. Create a feature branch: git checkout -b feature/your-feature
  3. Commit your changes: git commit -m 'Add your feature'
  4. Push and open a Pull Request

📄 License

This project is licensed under the MIT License. See LICENSE for details.


Built with ❤️ for Indian farmers | Powered by Mistral AI, Open-Meteo & Agmarknet

About

No description, website, or topics provided.

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

 
 
 

Contributors

Languages

  • Python 73.0%
  • HTML 27.0%