An intelligent agricultural advisory platform designed to bridge the gap between farmers and verified agricultural experts. The system leverages AI-powered crop recommendations, CNN-based image-to-soil detection, real-time location mapping, a multilingual generative voice chatbot, and real-time Socket.io-driven video/audio communication.
The application comprises three core components:
- React Frontend (Vite): An interactive, multilingual, and highly responsive user interface.
- Node.js Express Server: The central logic handler, managing user roles (Farmer, Expert, Admin), live signaling, and community forums.
- Python Flask ML Service: A microservice dedicated to running TensorFlow models for crop recommendations and soil classifications.
graph TD
classDef client fill:#e1f5fe,stroke:#039be5,stroke-width:2px;
classDef node fill:#efebe9,stroke:#5d4037,stroke-width:2px;
classDef python fill:#e8f5e9,stroke:#2e7d32,stroke-width:2px;
classDef db fill:#fbe9e7,stroke:#d84315,stroke-width:2px;
classDef external fill:#fff8e1,stroke:#f57f17,stroke-width:2px;
%% Nodes
React[React Frontend<br/>Vite / Socket.io Client]:::client
Express[Express Backend<br/>Node.js - Port 5000]:::node
Flask[ML Microservice<br/>Python Flask - Port 5001]:::python
Mongo[(MongoDB Database)]:::db
%% External API Nodes
Gemini[Google Gemini API]:::external
TTS[Google TTS & Translate]:::external
OSM[OpenStreetMap Nominatim]:::external
HF[HuggingFace API]:::external
Reddit[Reddit API]:::external
%% Connections
React <-->|Socket.io / HTTP| Express
React -->|navigator.geolocation| OSM
Express <-->|Mongoose| Mongo
Express <-->|Axios Proxy| Flask
Express <-->|Google GenAI SDK| Gemini
Express <-->|Axios Proxy| TTS
Express <-->|Inference SDK| HF
Express <-->|Axios| Reddit
%% Sub-features inside Flask
subgraph Python Flask Services
Flask -->|Predict Crop| CropModel[crop_model.h5<br/>TensorFlow Neural Network]
Flask -->|Classify Soil| SoilModel[soil_model_cnn.h5<br/>ResNet50 CNN]
end
%% Sub-features inside Node
subgraph Express Services
Express -->|Chat requests / signalling| SocketIO[Socket.io Signaling Server]
SocketIO <-->|WebRTC Video Calls| React
end
- Feature: Allows farmers to input soil and climate parameters (Nitrogen, Phosphorus, Potassium, pH, humidity, temperature, rainfall) to find the most suitable crop to plant.
- Implementation: The parameters are sent to the Python Flask microservice, scaled using a pre-saved
scaler.pkl, and classified using a trained neural network (crop_model.h5). The result is mapped back usinglabel_encoder.pkland returned to the frontend.
- Feature: Farmers can upload an image of their soil to immediately classify its type (Red, Black, Alluvial, Laterite) and obtain a plausible pH level.
-
Implementation: Uses a ResNet50 Convolutional Neural Network architecture built inside
train_soil_cnn.py. The Flask service accepts the image atPOST /predict-soil, resizes it to$224 \times 224$ , runs it through the preprocessor, and feeds it into the CNN modelsoil_model_cnn.h5.
- Feature: Automatically maps the farmer's location during registration/profile updates to deduce localized weather and regional soil patterns.
- Implementation: Uses the native HTML5 Web Geolocation API (
navigator.geolocation) to extract{ latitude, longitude }coordinates. The frontend resolves these coordinates via the OpenStreetMap Nominatim reverse geocoding API to identify local divisions (suburb, village, city, county).
- Feature: Voice-enabled AI chatbot allowing farmers to speak queries in English, Hindi, or Telugu and receive tailored responses from distinct AI expert "personas".
- Implementation: Utilizes the browser-based
Web Speech APIfor live transcription. The text is sent to the Node.js backend which coordinates requests to the Google Gemini API (gemini-2.5-flash) using customized prompts tailored for Weather, Fertilizer, or Disease experts. The response is spoken back via a custom node proxy endpoint/api/ttsquerying Google Translate's TTS stream.
- Feature: A collaborative forum where farmers post agricultural questions and verified experts post helpful answers.
- Implementation: Managed by Mongoose Schemas (
PostandAnswer). It supports asynchronous comments, chronologically ordered feeds, and user-to-expert linkages.
- Feature: Farmers can request live consultations, message chat, or launch WebRTC video/audio sessions with verified experts.
- Implementation: Built with
Socket.ioover HTTP. Standard chat messages are cached to a MongoDB collection (Message) for persistence. Audio/video calls use a custom WebRTC signaling protocol: when a farmer initiates a call, Socket.io manages call routing, offering, answering, and ICE candidate exchange. An expert approval mechanism restricts excessive calls through the database collectionCallRecord.
- Feature: A workflow where experienced farmers can apply to become verified experts, reviewed and approved by administrators.
- Implementation: Farmers submit applications from their profile dashboard. Admins can view pending applications, audit credentials, and trigger a
PUTrequest to update their role toexpert, automatically instantiating theirExpertdetails in the database.
agri-ai-advisory-system/
βββ backend/ # Node.js Express server
β βββ agents/ # AI Agent prompts & instructions
β βββ config/ # Database and API setups
β βββ controllers/ # Request handler functions
β βββ models/ # MongoDB Mongoose Schemas (User, Post, Answer, Expert, etc.)
β βββ routes/ # Express endpoints (auth, crops, admin, etc.)
β βββ services/ # Third-party integrations (Gemini, HuggingFace)
β βββ uploads/ # Temp storage for soil image classification
β βββ utils/ # Helper files
β βββ server.js # Main server entrypoint
β βββ .env # Server environment configuration
β
βββ frontend/ # React client application (Vite)
β βββ src/
β β βββ api/ # API caller functions (axios)
β β βββ assets/ # Global assets & styling sheet
β β βββ components/ # Reusable components (Navbar, Chat, etc.)
β β βββ pages/ # Application pages (Forum, Market, Advisor, etc.)
β β βββ App.jsx # Main routing & app composition
β β βββ main.jsx # React entrypoint
β βββ index.html
β βββ vite.config.js
β
βββ ml-service/ # Python ML Flask microservice
β βββ Crop_recommendation.csv
β βββ app.py # Flask entry point (Port 5001)
β βββ crop_model.h5 # Crop classification weights
β βββ soil_model_cnn.h5 # Soil ResNet50 CNN model weights
β βββ train_model.py # Model training script for Crops
β βββ train_soil_cnn.py # ResNet50 soil classifier trainer
β βββ requirements.txt # Python dependencies
β
βββ README.md # Project README
βββ package.json # Root configurations
- Set up a MongoDB cluster (local or Atlas) and copy the URI.
- Note: The database seeds three default administrator accounts upon initial server startup:
- Admins:
admin1@harvestmate.com,admin2@harvestmate.com, oradmin3@harvestmate.com - Password:
admin123
- Admins:
Navigate to the machine learning service directory:
cd ml-serviceCreate a virtual environment and activate it:
# Windows
python -m venv venv
venv\Scripts\activate
# macOS/Linux
python3 -m venv venv
source venv/bin/activateInstall requirements:
pip install -r requirements.txtStart the ML service (runs on http://localhost:5001):
python app.pyOpen a new terminal tab, navigate to the server directory:
cd serverInstall dependencies:
npm installCreate a .env file in the server directory:
MONGO_URI=your_mongodb_connection_string
GEMINI_API_KEY=your_google_gemini_api_key
HF_TOKEN=your_huggingface_token
WEATHER_API_KEY=your_openweathermap_api_key
OPENAI_API_KEY=your_openai_api_key
PORT=5000Start the server:
npm startThe server will boot on http://localhost:5000 and establish a MongoDB connection.
Open a new terminal tab, navigate to the frontend directory:
cd frontendInstall packages:
npm installStart the dev server:
npm run devOpen your browser and visit http://localhost:5173.
| Method | Endpoint | Description |
|---|---|---|
POST |
/auth/register |
Register new Farmers or Experts |
POST |
/auth/login |
Login and acquire JWT |
GET |
/experts |
Retrieve all verified experts |
POST |
/request-chat |
Farmer registers a private chat request with an expert |
GET |
/api/tts |
Proxy to play back generated spoken audio (bypassing CORS) |
POST |
/api/detect-soil |
Multipart request that proxies soil image to Python Flask API |
GET |
/api/daily-tip/:farmerId |
Generate a personalized daily tip using Gemini API |
GET |
/api/agri-news |
Pull live hot topics from agriculture subreddits |
| Method | Endpoint | Description |
|---|---|---|
POST |
/predict |
Accept soil statistics (N, P, K, etc.) and predict optimal crop |
POST |
/predict-soil |
Accept soil image stream and perform classification |
Contributions are highly encouraged! Please make sure to test your code locally, update configurations accordingly, and submit a pull request with clear description details.
This project is licensed under the MIT License.