🌱 AI-powered market intelligence for Indian agriculture

AgriPrice AI

“Helping farmers make smarter selling decisions with AI.”

Forecast crop prices, compare markets, estimate revenue, and make data-driven decisions — explained in plain language, in English · தமிழ் · తెలుగు · ಕನ್ನಡ · മലയാളം, by touch or by voice. Then sell to real buyers through the built-in farmer marketplace.

🧠 Real ML pipeline (Ridge · RF · HistGB · XGBoost vs naive)🎯 80 % prediction intervals🟢🟡🔵 Explainable SELL / MONITOR / WAIT🎙️ Voice in 5 languages🛒 Farmer marketplace🔒 No API keys needed
25crop × market models, chosen by hold-out RMSE
28,086cleaned daily price rows (synthetic demo set, Agmarknet-compatible)
6.0 %mean MAPE of selected models (hold-out, 1–30 d)
+42 %mean RMSE improvement over “price stays the same”
5languages · voice in & out
33 + 26backend tests + browser E2E steps, all green

The problem, our solution, the impact

Most Indian farmers decide when and where to sell with yesterday's mandi gossip. Prices for perishables swing 20–40 % within weeks; selling into a trough or hauling to the wrong market erases a season's margin.

❗

Problem

  • No forward view of prices — only today's rate, if that.
  • Market choice ignores transport, storage and spoilage.
  • Advice, when available, is in English and unexplained.
  • Distress sales right after harvest when supply peaks.
💡

Our solution

  • 7 / 14 / 30-day price estimates with uncertainty, from a transparent ML pipeline.
  • SELL NOW / MONITOR / WAIT with reasons — shelf life and storage cost included.
  • Market comparison on net revenue, profit calculator, grounded advisor.
  • Five languages, voice in and out, and a marketplace to close the sale.
🌾

Economic impact

  • Better timing: avoid selling into predictable dips; hold storable crops when the expected gain beats holding cost.
  • Better routing: the best price is not always the best profit after transport.
  • Less waste: shelf-life-aware advice avoids holding perishables too long.
  • Direct buyer contact without commission.

No guaranteed-income claims: forecasts are estimates and the bundled data is synthetic.

Real model output — the five judge examples

Everything below was produced by the running app's own API (captured , demo dataset). Pick a case; change the quantity to see revenue scale. This is the same data the live dashboard shows.

Price history → estimated price₹ per kg · last 90 days + 30-day path
Actual modal priceEstimated price80 % prediction range

Sell today vs sell later

Quantity (kg): · revenue scales with quantity; holding cost includes crop-specific spoilage

Horizon table

HorizonEstimate80 % rangeChangeAdviceNet revenue

    Top model drivers (permutation importance)

    Recommendation reasoning

      Candidate models for this series

      ModelMAERMSEMAPER²SkillDir. acc.

      Compare markets —

      MarketToday7-day est.ChangeConfidenceAdviceNet todayNet in 7 d

      Net = expected revenue − transport − storage − spoilage. Transport costs are per market and editable in the app; here they are 0, so ranking follows price × quantity after holding losses.

      Price forecasts are estimates based on historical data and available market information. Actual prices may vary due to weather, supply, demand, transportation, government policies and other market conditions. The bundled dataset is synthetic and labelled as such on every screen; the ingestion layer accepts real Agmarknet / data.gov.in exports without code changes.

      What the product does

      A complete decision-support flow: crop → location → market → quantity → period → forecast → dashboard → compare → decide → sell.

      📈

      Price forecasting

      7 / 14 / 30-day estimates with an 80 % prediction interval, trend direction and a High / Medium / Low confidence label — never presented as a guarantee.

      🧭

      Explainable SELL / MONITOR / WAIT

      Rules over current price, estimate, trend, volatility, uncertainty, quantity, shelf life and storage cost. Every verdict comes with reasons and caveats.

      ⚖️

      Compare markets on net revenue

      Expected revenue − transport − storage − spoilage per market, so the best price is also the best profit.

      🧮

      Farmer profit calculator

      Gross → spoilage → transport → storage → other costs → net; break-even price; waterfall chart.

      🤖

      AgriAdvisor

      Rule-based assistant grounded in the same prediction numbers: "Should I sell my tomatoes today?", "What if price falls 10 %?", "Which market pays most?"

      🎙️

      Voice assistant

      Speak in English, Tamil, Telugu, Kannada or Malayalam: the app runs predictions, compares markets, opens pages, switches language, pre-fills a listing — and reads the answer aloud.

      🌐

      Five languages

      Whole UI, recommendation and explanation texts, advisor and voice. One type-checked dictionary per language.

      🛒

      Farmer marketplace

      List produce at an AI-suggested asking price, buyers call / WhatsApp / send interest; owner view with inquiries; admin moderation. No payments handled.

      🔍

      Why this prediction?

      Recent % change, seasonal pattern, arrivals, similar historical periods, model confidence, top model drivers.

      🛠️

      Admin & data layer

      Upload CSV / Excel / JSON, column auto-mapping, cleaning report, data-quality view, retrain, model registry, prediction history. Agmarknet-compatible.

      🔒

      Security & honesty

      Input validation, upload sanitising, token-protected admin, secrets via env vars, synthetic data labelled on every screen.

      ⚡

      Demo mode

      One-click examples (Tomato, Onion, Potato, Rice, Wheat) that render instantly — no API keys needed.

      Voice assistant & five languages

      Many farmers prefer to ask. The floating mic understands spoken commands in five languages and operates the app — then reads the grounded answer aloud.

      How it works

      • Speech → text in the browser (Web Speech API, recognizer set to ta-IN / te-IN / kn-IN / ml-IN / en-IN). Only the transcript is sent to the server.
      • POST /api/voice/command parses intent + entities (crop, market, quantity, horizon, language) and returns a structured action: predict · compare · navigate · set_language · sell_online · chat · stop · repeat.
      • The UI executes it (runs the prediction, opens the comparison, switches language, pre-fills a listing) and speaks the reply.

      Honest by design

      • Answers come from the same prediction services as the dashboard — nothing is made up.
      • No Tamil/Telugu/Kannada/Malayalam voice on the device? The text stays in that language, the English version is spoken, and the user is told why.
      • No microphone? A keyboard mode runs the same command pipeline.
      • No audio leaves the device; no cloud speech keys.

      Try saying…

      Tomato price in KoyambeduShould I sell 500 kg onion today?Which market is best for potato?கோயம்பேடு தக்காளி விலை என்னಕೋಲಾರದಲ್ಲಿ ಟೊಮೇಟೊ ಬೆಲೆ ಎಷ್ಟುSell my 500 kg tomatoes onlineSwitch to TeluguOpen the calculator

      Languages

      🇬🇧 Englishதமிழ்తెలుగుಕನ್ನಡമലയാളം

      Whole UI, recommendation and “why” texts, advisor and voice. One type-checked dictionary file per language — the compiler rejects a missing key. Numbers and dates use the matching Indian locale.

      Voice assistant
      Voice assistant“Should I sell 500 kg onion today?” → prediction runs, answer is read aloud.
      Tamil voice
      TamilSpoken Tamil → Tamil dashboard + Tamil speech.

      Farmer marketplace — from insight to sale

      The forecast tells the farmer when to sell; the marketplace helps with to whom. Currently 8 active sample listings · 17,850 kg.

      🏷️

      AI-suggested asking price

      Pre-filled from today's mandi modal price and the 7-day estimate, with the range, trend and confidence shown — a starting point, not advice.

      📞

      Direct buyer contact

      Call, WhatsApp, or an “I'm interested” form with offer and quantity. Phone numbers are masked unless the seller opts in.

      🗂️

      Owner tools

      One-time edit key, inquiries list, mark as sold, remove, WhatsApp share. Admin moderation tab with full details.

      🛡️

      Safety by design

      No payments, escrow or logistics; on-page safety notice; rate limits, input sanitising, Indian mobile validation.

      ML methodology & evaluation

      A real, reproducible pipeline — no random numbers. Every number in the UI traces back to a trained, evaluated model stored with its metrics.

      1 · Clean

      • Drop rows missing essentials, de-duplicate, fix swapped min/max
      • Flag abnormal prices (rolling MAD outliers), chronological sort, ₹/quintal → ₹/kg
      • Daily aggregation with a transparent cleaning report (28,921 → 28,086 rows)

      2 · Features

      • Calendar: day, week, month, year, day-of-week, seasonal sin/cos
      • Lags 1–30, rolling mean/min/max/std, % changes, moving averages
      • Arrivals, volatility, horizon feature h ∈ 1…30 (direct multi-horizon), log-return target

      3 · Models

      • Baseline: naive last value · Linear (Ridge)
      • Improved: Random Forest · HistGradientBoosting · XGBoost
      • Per crop × market: hold-out last 120 days, select by RMSE, fall back to naive unless beaten by > 2 % — honesty over show
      • 80 % intervals from hold-out residual quantiles; LSTM/Prophet deliberately not used for show

      Average over all 25 series (hold-out, horizons 1–30)

      ModelMAE ₹/kgRMSEMAPER²Skill vs naiveBest in
      Naive (last price)2.583.388.9 %0.19—1 / 25
      Linear Regression (Ridge)1.782.276.1 %0.43+33 %7 / 25
      Random Forest1.752.366.0 %0.40+30 %14 / 25
      Gradient Boosting (HistGB)1.882.546.5 %——2 / 25
      XGBoost1.842.476.3 %——1 / 25

      Selected models: mean MAPE 6.0 %, mean skill +42 %; 24 of 25 series beat naive by more than 2 % RMSE. Full per-series table in the README and notebook.

      By crop (selected model)

      CropMAPESkillModel
      🧅 Onion4.9 %+79 %Random Forest (all 5 markets)
      🥔 Potato5.7 %+21 %Ridge (all 5 markets)
      🌾 Rice (Paddy)1.6 %+17 %Ridge / RF; Thanjavur honestly falls back to naive
      🍅 Tomato12.7 %+63 %HistGB, Ridge, XGBoost (per market)
      🌾 Wheat2.5 %+27 %Random Forest (all 5 markets)

      Tomato is the hardest (volatile, perishable) and is where skill over naive is largest; Rice/Thanjavur is the one series where the honest naive fallback wins.

      Decision engine (explainable rules)

      Spoilage = daily loss × days (tomato 1 %/day, shelf life 7 d · onion 0.25 %/day, 60 d · potato 0.2 %/day, 75 d · rice/wheat 0.02 %/day). Net expected change = (estimate × qty × (1 − spoilage) − storage − revenue now) ÷ revenue now. WAIT when net gain ≥ 5 %, downside of the 80 % band better than −8 % and confidence not low · SELL NOW when net ≤ −2 % or past shelf life with no gain · otherwise MONITOR. Every verdict lists its reasons and caveats and is never framed as certainty.

      Architecture & tech stack

      React + TypeScript + Tailwind + Recharts in front; FastAPI + Pandas/NumPy/scikit-learn/XGBoost behind; SQLite (PostgreSQL-ready via DATABASE_URL); joblib model registry. Single process in production: FastAPI serves the built frontend.

      frontend/

      • pages: Landing · Predict · Compare · Calculator · Advisor · Marketplace · Admin
      • components: charts, results, forms, AgriAdvisor, voice/
      • voice/useSpeech.ts — Web Speech wrapper
      • i18n: en · ta · te · kn · ml (one Dict type)

      backend/app/

      • api/routes: public · voice · marketplace · admin
      • ml: preprocessing · features · models · forecaster · recommender · explainer
      • services: prediction (registry + cache) · advisor · voice · marketplace
      • core: config (env) · security (admin token, upload validation)

      data & models

      • data/generate_sample_dataset.py → sample/agri_prices_demo.csv (synthetic, seeded)
      • ingestion: CSV · Excel · JSON · data.gov.in API, auto column mapping
      • models/<crop>__<market>.joblib + metrics in SQLite
      • notebooks/01_eda_and_model_comparison.ipynb

      quality

      • 33 pytest tests (API, ML, voice, marketplace)
      • Playwright E2E: voice, 5 languages, marketplace (26 steps)
      • Docker compose, Makefile, typed API client, tsc strict
      Browser ──/api/predict──▶ FastAPI ──▶ prediction_service.get_or_train() ├─ series_frame() from SQLite ├─ model registry + joblib cache (fingerprint-validated) ├─ forecaster.forecast_series() → 30-day path + 80 % intervals ├─ recommender.recommend() → SELL / MONITOR / WAIT + reasons └─ explainer.explain() → "why" bullets + drivers Mic ──(browser STT)──▶ /api/voice/command ──▶ intent + entities ──▶ same services ──▶ action + reply ──▶ UI + TTS

      REST API

      MethodRoutePurpose
      GET/api/crops · /api/markets · /api/locationscatalogue with history coverage
      POST/api/predictforecast + recommendation + explanation + model metrics
      POST/api/compare-marketsnet revenue by market after transport & holding costs
      POST/api/calculate-revenueprofit calculator arithmetic
      GET/api/price-history · /api/model-metricscleaned history, registry metrics
      POST/api/chatAgriAdvisor (grounded, 5 languages, TTS-ready text)
      POST/api/voice/commandtranscript → structured UI action + spoken reply
      GET/POST/api/marketplace/…price suggestion, listings, inquiries, status, stats
      POST/api/upload-data 🔒 · /api/admin/… 🔒ingestion, dataset, retrain, moderation (X-Admin-Token)

      Explicit errors: 404 unknown crop/market · 422 “Not enough historical data is available for this crop and market. Please select another market or prediction period.” · 401 admin · 400/413 bad or oversized upload.

      Screenshots

      Captured from the running app with Playwright (1366 px and 390 px). Click to enlarge.

      The 90-second demo

      Open the app → View Demo (Demo Mode banner states the data is synthetic).
      Click 🍅 Tomato · Koyambedu · 500 kg · 7 d — the form fills and the prediction runs.
      Read the five cards: current price, estimated price, expected change, recommendation, additional revenue.
      Scroll: forecast chart with the 80 % band, price history, sell-today-vs-later bars, the 7/14/30-day table.
      “Why this prediction?” and the model table (naive vs linear vs trees with skill %).
      Click 🧅 Onion · Tiruchirappalli · 2000 kg · 14 d → a 🔵 WAIT case (+16 %, high confidence, ₹9.7 k more net).
      Compare Markets → add a transport cost → the best market is ranked by net revenue, not headline price.
      Ask AgriAdvisor “What happens if the price falls by 10 %?” — the answer uses the same numbers.
      Switch to தமிழ் — everything, including the recommendation, is translated.
      Tap Talk to AgriPrice: “Which market is best for potato?” → comparison opens and is read aloud; “Sell my 500 kg tomatoes online” → marketplace pre-filled with an AI asking price.

      Run it locally

      git clone <repo> && cd agriprice-ai make setup # pip + npm install make demo # data → seed → sample listings → train 25 models → build UI make backend # http://localhost:8000 (API docs at /api/docs)

      Or ADMIN_TOKEN=secret docker compose up --build. Voice input needs https:// or localhost (browser microphone policy).

      Limitations & next steps

      • Synthetic demo data — accuracy must be re-validated on live Agmarknet feeds (ingestion is ready).
      • No weather / policy / export-ban features yet; horizons beyond ~2 weeks for volatile vegetables carry wide intervals.
      • Advisor and voice are rule-based: dependable within their intents, not open-ended chat.
      • Marketplace is a moderated classifieds board — no identity verification, payments or logistics.
      • Next: live data sync, weather & festival features, quantile boosting, SMS/IVR, OTP-verified sellers, PostgreSQL + scheduled retraining.

      Team

      Built as an original hackathon project by the AgriPrice AI team. Edit the cards below with your names and roles.

      Team member 1Role · e.g. ML pipeline & backend
      Team member 2Role · e.g. Frontend, voice & i18n
      Team member 3Role · e.g. Data, marketplace & QA