krishikarm 0.1.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Kisan-Eye Contributors
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1 @@
1
+ recursive-include krishikarm/weights *.pth
@@ -0,0 +1,143 @@
1
+ Metadata-Version: 2.4
2
+ Name: krishikarm
3
+ Version: 0.1.0
4
+ Summary: Crop distress prediction from satellite and weather data using a cross-attention transformer (KisanNet v3).
5
+ Author-email: Varshini CB <varshinicb1@gmail.com>
6
+ License: MIT
7
+ Project-URL: Homepage, https://github.com/varshinicb1/Krishikarm
8
+ Project-URL: Repository, https://github.com/varshinicb1/Krishikarm
9
+ Project-URL: Issues, https://github.com/varshinicb1/Krishikarm/issues
10
+ Keywords: agriculture,satellite,crop-prediction,deep-learning,transformer,india,farming
11
+ Classifier: Development Status :: 4 - Beta
12
+ Classifier: Intended Audience :: Science/Research
13
+ Classifier: License :: OSI Approved :: MIT License
14
+ Classifier: Programming Language :: Python :: 3
15
+ Classifier: Programming Language :: Python :: 3.9
16
+ Classifier: Programming Language :: Python :: 3.10
17
+ Classifier: Programming Language :: Python :: 3.11
18
+ Classifier: Programming Language :: Python :: 3.12
19
+ Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
20
+ Classifier: Topic :: Scientific/Engineering :: Atmospheric Science
21
+ Requires-Python: >=3.9
22
+ Description-Content-Type: text/markdown
23
+ License-File: LICENSE
24
+ Requires-Dist: torch>=2.0
25
+ Requires-Dist: numpy>=1.24
26
+ Dynamic: license-file
27
+
28
+ # Krishikarm
29
+
30
+ **Crop distress prediction from satellite and weather data.**
31
+
32
+ Krishikarm uses KisanNet v3, a cross-attention transformer trained on 82,000+ real
33
+ satellite observations across 127 Indian districts, to predict crop health risk
34
+ in real time.
35
+
36
+ ## Installation
37
+
38
+ ```bash
39
+ pip install krishikarm
40
+ ```
41
+
42
+ ## Quick Start
43
+
44
+ ```python
45
+ from krishikarm import Predictor
46
+
47
+ predictor = Predictor()
48
+
49
+ result = predictor.predict({
50
+ "lat": 12.97,
51
+ "lon": 77.59,
52
+ "T2M": 32,
53
+ "RH2M": 65,
54
+ "PREC": 2.5,
55
+ "SOLAR": 18,
56
+ "WIND": 3,
57
+ "state": "KA",
58
+ "irrig": "borewell",
59
+ "crops": ["rice"],
60
+ })
61
+
62
+ print(result)
63
+ # {
64
+ # "distress_score": 0.12,
65
+ # "intervention_days": 26.4,
66
+ # "risk_class": 0,
67
+ # "risk_label": "Healthy"
68
+ # }
69
+ ```
70
+
71
+ ## Model Architecture
72
+
73
+ KisanNet v3 is a cross-attention transformer with:
74
+
75
+ - **42 input features** derived from weather, soil, atmosphere, and location data
76
+ - **State and irrigation embeddings** for regional context
77
+ - **4-layer, 8-head cross-attention** fusion between satellite and context encoders
78
+ - **Three prediction heads**: distress score (0-1), intervention window (days), risk class (5 levels)
79
+ - **96.8% accuracy** on held-out test data
80
+
81
+ ### Input Features
82
+
83
+ | Source | Features |
84
+ |--------------|------------------------------------------------------------------|
85
+ | Weather | Temperature, humidity, precipitation, wind, cloud cover, dew point |
86
+ | Solar | Shortwave radiation, UV index, longwave radiation |
87
+ | Soil | Moisture (3 depths), temperature (2 depths), clay, sand, SOC, pH |
88
+ | Atmosphere | PM2.5, PM10, dust, aerosol optical depth |
89
+ | Derived | NDVI proxy, VPD, GDD, thermal range |
90
+ | Location | Latitude, longitude, elevation, day-of-year encoding |
91
+
92
+ ### Risk Classes
93
+
94
+ | Class | Label | Distress Range |
95
+ |-------|-----------|----------------|
96
+ | 0 | Healthy | 0.00 - 0.15 |
97
+ | 1 | Watch | 0.15 - 0.30 |
98
+ | 2 | Alert | 0.30 - 0.50 |
99
+ | 3 | Critical | 0.50 - 0.75 |
100
+ | 4 | Emergency | 0.75 - 1.00 |
101
+
102
+ ## Data Sources
103
+
104
+ All training data was collected from free, open APIs:
105
+
106
+ - **NASA POWER** -- Solar radiation, temperature, humidity
107
+ - **Open-Meteo** -- Weather forecasts, soil moisture, UV, air quality
108
+ - **SoilGrids** -- Soil composition (clay, sand, SOC, pH)
109
+ - **Open-Elevation** -- Terrain altitude
110
+
111
+ No proprietary data or paid APIs were used.
112
+
113
+ ## API Reference
114
+
115
+ ### `Predictor`
116
+
117
+ ```python
118
+ Predictor(weights_path=None, device=None)
119
+ ```
120
+
121
+ - `weights_path` -- Path to a `.pth` checkpoint. Defaults to the bundled v3 weights.
122
+ - `device` -- `"cpu"` or `"cuda"`. Defaults to CUDA when available.
123
+
124
+ #### Methods
125
+
126
+ - `predict(observation: dict) -> dict` -- Run prediction on a single observation.
127
+ - `predict_batch(observations: list[dict]) -> list[dict]` -- Batch prediction.
128
+ - `info() -> dict` -- Return model metadata.
129
+
130
+ ### `KisanNetV3`
131
+
132
+ The raw PyTorch model class, for advanced users who want to integrate the
133
+ architecture into their own training pipeline.
134
+
135
+ ## Requirements
136
+
137
+ - Python >= 3.9
138
+ - PyTorch >= 2.0
139
+ - NumPy >= 1.24
140
+
141
+ ## License
142
+
143
+ MIT
@@ -0,0 +1,116 @@
1
+ # Krishikarm
2
+
3
+ **Crop distress prediction from satellite and weather data.**
4
+
5
+ Krishikarm uses KisanNet v3, a cross-attention transformer trained on 82,000+ real
6
+ satellite observations across 127 Indian districts, to predict crop health risk
7
+ in real time.
8
+
9
+ ## Installation
10
+
11
+ ```bash
12
+ pip install krishikarm
13
+ ```
14
+
15
+ ## Quick Start
16
+
17
+ ```python
18
+ from krishikarm import Predictor
19
+
20
+ predictor = Predictor()
21
+
22
+ result = predictor.predict({
23
+ "lat": 12.97,
24
+ "lon": 77.59,
25
+ "T2M": 32,
26
+ "RH2M": 65,
27
+ "PREC": 2.5,
28
+ "SOLAR": 18,
29
+ "WIND": 3,
30
+ "state": "KA",
31
+ "irrig": "borewell",
32
+ "crops": ["rice"],
33
+ })
34
+
35
+ print(result)
36
+ # {
37
+ # "distress_score": 0.12,
38
+ # "intervention_days": 26.4,
39
+ # "risk_class": 0,
40
+ # "risk_label": "Healthy"
41
+ # }
42
+ ```
43
+
44
+ ## Model Architecture
45
+
46
+ KisanNet v3 is a cross-attention transformer with:
47
+
48
+ - **42 input features** derived from weather, soil, atmosphere, and location data
49
+ - **State and irrigation embeddings** for regional context
50
+ - **4-layer, 8-head cross-attention** fusion between satellite and context encoders
51
+ - **Three prediction heads**: distress score (0-1), intervention window (days), risk class (5 levels)
52
+ - **96.8% accuracy** on held-out test data
53
+
54
+ ### Input Features
55
+
56
+ | Source | Features |
57
+ |--------------|------------------------------------------------------------------|
58
+ | Weather | Temperature, humidity, precipitation, wind, cloud cover, dew point |
59
+ | Solar | Shortwave radiation, UV index, longwave radiation |
60
+ | Soil | Moisture (3 depths), temperature (2 depths), clay, sand, SOC, pH |
61
+ | Atmosphere | PM2.5, PM10, dust, aerosol optical depth |
62
+ | Derived | NDVI proxy, VPD, GDD, thermal range |
63
+ | Location | Latitude, longitude, elevation, day-of-year encoding |
64
+
65
+ ### Risk Classes
66
+
67
+ | Class | Label | Distress Range |
68
+ |-------|-----------|----------------|
69
+ | 0 | Healthy | 0.00 - 0.15 |
70
+ | 1 | Watch | 0.15 - 0.30 |
71
+ | 2 | Alert | 0.30 - 0.50 |
72
+ | 3 | Critical | 0.50 - 0.75 |
73
+ | 4 | Emergency | 0.75 - 1.00 |
74
+
75
+ ## Data Sources
76
+
77
+ All training data was collected from free, open APIs:
78
+
79
+ - **NASA POWER** -- Solar radiation, temperature, humidity
80
+ - **Open-Meteo** -- Weather forecasts, soil moisture, UV, air quality
81
+ - **SoilGrids** -- Soil composition (clay, sand, SOC, pH)
82
+ - **Open-Elevation** -- Terrain altitude
83
+
84
+ No proprietary data or paid APIs were used.
85
+
86
+ ## API Reference
87
+
88
+ ### `Predictor`
89
+
90
+ ```python
91
+ Predictor(weights_path=None, device=None)
92
+ ```
93
+
94
+ - `weights_path` -- Path to a `.pth` checkpoint. Defaults to the bundled v3 weights.
95
+ - `device` -- `"cpu"` or `"cuda"`. Defaults to CUDA when available.
96
+
97
+ #### Methods
98
+
99
+ - `predict(observation: dict) -> dict` -- Run prediction on a single observation.
100
+ - `predict_batch(observations: list[dict]) -> list[dict]` -- Batch prediction.
101
+ - `info() -> dict` -- Return model metadata.
102
+
103
+ ### `KisanNetV3`
104
+
105
+ The raw PyTorch model class, for advanced users who want to integrate the
106
+ architecture into their own training pipeline.
107
+
108
+ ## Requirements
109
+
110
+ - Python >= 3.9
111
+ - PyTorch >= 2.0
112
+ - NumPy >= 1.24
113
+
114
+ ## License
115
+
116
+ MIT
@@ -0,0 +1,135 @@
1
+ # Krishikarm
2
+
3
+ **AI-powered farming intelligence platform combining satellite data with voice AI.**
4
+
5
+ Krishikarm provides personalized agricultural advice to Indian farmers through
6
+ real-time satellite analysis, multilingual voice interaction, and live market prices.
7
+ The platform is built around KisanNet v3, a cross-attention transformer trained on
8
+ 82,000+ real satellite observations across 127 Indian districts with 96.8% accuracy.
9
+
10
+ ---
11
+
12
+ ## Features
13
+
14
+ ### KisanNet v3 (Trained Model)
15
+
16
+ - Cross-attention transformer with 42 input features
17
+ - Trained on real satellite data from NASA POWER, Open-Meteo, and SoilGrids
18
+ - Predicts crop distress score, intervention window, and 5-level risk classification
19
+ - Inference time: ~4ms on GPU
20
+ - Available as a standalone Python package: `pip install krishikarm`
21
+
22
+ ### Voice-First Interface
23
+
24
+ - Speech-to-text and text-to-speech powered by Sarvam AI
25
+ - Supports 11 Indian languages: Hindi, Kannada, Telugu, Tamil, Marathi, Bengali,
26
+ Gujarati, Punjabi, Odia, Malayalam, and English
27
+ - Designed for accessibility in rural areas
28
+
29
+ ### Satellite Intelligence
30
+
31
+ - Real-time data fusion from NASA GIBS, ISRO Bhuvan, Open-Meteo, and SoilGrids
32
+ - Visual map layers: NDVI (crop health), soil moisture, temperature, true color
33
+
34
+ ### Krishikarm Buddy
35
+
36
+ - Context-aware AI assistant for farming queries
37
+ - Knows your farm location, soil type, and weather forecast
38
+ - WhatsApp integration for sending reports and advisories
39
+
40
+ ### Mandi Marketplace
41
+
42
+ - Real-time commodity prices from data.gov.in (AgMarkNet)
43
+ - Covers all major agricultural markets across India
44
+
45
+ ---
46
+
47
+ ## Tech Stack
48
+
49
+ | Layer | Technologies |
50
+ |-----------|-----------------------------------------------------------------|
51
+ | Frontend | Vite, Vanilla JS, Leaflet, Chart.js, TensorFlow.js |
52
+ | Backend | FastAPI, Python, SQLite, Sarvam AI |
53
+ | AI/ML | PyTorch (training), ONNX (inference), Transformer architecture |
54
+ | Data | NASA POWER, ISRO Bhuvan, Open-Meteo, AgMarkNet, SoilGrids |
55
+
56
+ ---
57
+
58
+ ## Setup
59
+
60
+ ### Prerequisites
61
+
62
+ - Node.js (v18+)
63
+ - Python (v3.9+)
64
+
65
+ ### 1. Clone
66
+
67
+ ```bash
68
+ git clone https://github.com/varshinicb1/Krishikarm.git
69
+ cd Krishikarm
70
+ ```
71
+
72
+ ### 2. Backend
73
+
74
+ ```bash
75
+ cd backend
76
+ python -m venv venv
77
+ .\venv\Scripts\activate # Windows
78
+ # source venv/bin/activate # Linux/Mac
79
+
80
+ pip install -r requirements.txt
81
+
82
+ cp .env.example .env
83
+ # Edit .env and set SARVAM_API_KEY and MANDI_API_KEY
84
+
85
+ python server.py
86
+ ```
87
+
88
+ ### 3. Frontend
89
+
90
+ ```bash
91
+ npm install
92
+ npm run dev
93
+ ```
94
+
95
+ The backend runs at `http://localhost:8000`, the frontend at `http://localhost:5173`.
96
+
97
+ ---
98
+
99
+ ## Python Package
100
+
101
+ The trained model is also available as a standalone package:
102
+
103
+ ```bash
104
+ pip install krishikarm
105
+ ```
106
+
107
+ ```python
108
+ from krishikarm import Predictor
109
+
110
+ p = Predictor()
111
+ result = p.predict({
112
+ "lat": 12.97, "lon": 77.59,
113
+ "T2M": 32, "RH2M": 65, "PREC": 2.5,
114
+ "state": "KA", "irrig": "borewell",
115
+ "crops": ["rice"],
116
+ })
117
+ print(result["risk_label"]) # "Healthy"
118
+ ```
119
+
120
+ See [PKG_README.md](PKG_README.md) for full API documentation.
121
+
122
+ ---
123
+
124
+ ## Environment Variables
125
+
126
+ | Variable | Description | Required |
127
+ |------------------|--------------------------------------|----------|
128
+ | `SARVAM_API_KEY` | Sarvam AI key for voice/translation | Yes |
129
+ | `MANDI_API_KEY` | data.gov.in key for market prices | Yes |
130
+
131
+ ---
132
+
133
+ ## License
134
+
135
+ MIT. See [LICENSE](LICENSE) for details.
@@ -0,0 +1,33 @@
1
+ """
2
+ Krishikarm -- AI-powered crop distress prediction from satellite data.
3
+
4
+ Quick start::
5
+
6
+ from krishikarm import Predictor
7
+
8
+ p = Predictor()
9
+ result = p.predict({
10
+ "lat": 12.97, "lon": 77.59,
11
+ "T2M": 32, "RH2M": 65, "PREC": 2.5,
12
+ "state": "KA", "irrig": "borewell",
13
+ "crops": ["rice"],
14
+ })
15
+ print(result["risk_label"]) # "Healthy"
16
+ """
17
+
18
+ __version__ = "0.1.0"
19
+
20
+ from .model import KisanNetV3, RISK_LABELS, STATES, IRRIGATION, N_FEATURES
21
+ from .predict import Predictor
22
+ from .features import engineer_sample, to_tensors
23
+
24
+ __all__ = [
25
+ "KisanNetV3",
26
+ "Predictor",
27
+ "engineer_sample",
28
+ "to_tensors",
29
+ "RISK_LABELS",
30
+ "STATES",
31
+ "IRRIGATION",
32
+ "N_FEATURES",
33
+ ]
@@ -0,0 +1,161 @@
1
+ """
2
+ Feature engineering for KisanNet v3.
3
+
4
+ Converts raw satellite / weather observations into the 42-dimensional
5
+ feature vector and 9-dimensional context vector expected by the model.
6
+ """
7
+
8
+ import math
9
+ import numpy as np
10
+ import torch
11
+
12
+ from .model import STATES, IRRIGATION, N_FEATURES
13
+
14
+
15
+ def safe(value, default=0, scale=1.0):
16
+ """Return a normalised float, falling back to *default* on None / NaN / -999."""
17
+ if value is None or value == -999:
18
+ return default
19
+ if isinstance(value, float) and math.isnan(value):
20
+ return default
21
+ return float(value) / scale
22
+
23
+
24
+ def engineer_sample(s: dict) -> dict:
25
+ """Add derived fields (VPD, TRANGE, NDVI_PROXY, GDD, DISTRESS, etc.) to a
26
+ single raw observation dict *s*. Mutates and returns *s*."""
27
+ t = safe(s.get("T2M"), 25)
28
+ td = safe(s.get("TDEW"), 15)
29
+ rh = safe(s.get("RH2M"), 50)
30
+ prec = safe(s.get("PREC"), 0)
31
+
32
+ # Vapor pressure deficit
33
+ es = 0.6108 * math.exp(17.27 * t / (t + 237.3)) if t > -40 else 0.6
34
+ ea = 0.6108 * math.exp(17.27 * td / (td + 237.3)) if td > -40 else 0.3
35
+ s["VPD"] = max(es - ea, 0)
36
+
37
+ tmax = safe(s.get("T2M_MAX"), t + 5)
38
+ tmin = safe(s.get("T2M_MIN"), t - 5)
39
+ s["TRANGE"] = tmax - tmin
40
+
41
+ # NDVI proxy from available meteorological data
42
+ solar = safe(s.get("SOLAR"), 15)
43
+ mf = min(1.0, (prec * 7 + rh * 0.3) / 100)
44
+ tf2 = 1.0 - abs(t - 25) / 25
45
+ sf = min(solar / 25, 1.0)
46
+ s["NDVI_PROXY"] = float(np.clip(0.2 + 0.6 * mf * max(tf2, 0) * sf, 0, 0.95))
47
+
48
+ s["GDD"] = max(0, t - 10)
49
+
50
+ # Distress label
51
+ distress = 0.0
52
+ if t > 38:
53
+ distress += (t - 38) * 0.05
54
+ if t > 42:
55
+ distress += 0.15
56
+ if t < 5:
57
+ distress += (5 - t) * 0.04
58
+ if prec < 1 and rh < 40:
59
+ distress += 0.15
60
+ if prec < 0.5 and s.get("i") == "rainfed":
61
+ distress += 0.2
62
+ if s["VPD"] > 2.0:
63
+ distress += (s["VPD"] - 2) * 0.1
64
+ if prec > 50:
65
+ distress += (prec - 50) * 0.005
66
+ if prec > 100:
67
+ distress += 0.2
68
+ if 0 < solar < 8:
69
+ distress += (8 - solar) * 0.02
70
+ w = safe(s.get("WIND"), 2)
71
+ if w > 8:
72
+ distress += (w - 8) * 0.03
73
+ pm = safe(s.get("PM25"), 20)
74
+ if pm > 100:
75
+ distress += (pm - 100) * 0.001
76
+ uv = safe(s.get("UV"), 5)
77
+ if uv > 10:
78
+ distress += (uv - 10) * 0.01
79
+
80
+ s["DISTRESS"] = float(np.clip(distress, 0, 1))
81
+ s["INTERVENTION"] = max(0, 30 * (1 - s["DISTRESS"]))
82
+ d = s["DISTRESS"]
83
+ s["RISK"] = 0 if d < 0.15 else 1 if d < 0.30 else 2 if d < 0.50 else 3 if d < 0.75 else 4
84
+ return s
85
+
86
+
87
+ def to_tensors(s: dict):
88
+ """Convert a single (already-engineered) observation dict into the four
89
+ tensors required by ``KisanNetV3.forward``.
90
+
91
+ Returns
92
+ -------
93
+ feat : Tensor (1, 42)
94
+ ctx : Tensor (1, 9)
95
+ state_idx : Tensor (1,)
96
+ irrig_idx : Tensor (1,)
97
+ """
98
+ feat = torch.tensor([[
99
+ safe(s.get("NDVI_PROXY"), 0.4),
100
+ safe(s.get("SM0"), 0.3),
101
+ safe(s.get("SM1"), 0.25),
102
+ safe(s.get("SM3"), 0.2),
103
+ safe(s.get("ST0"), 25, 50),
104
+ safe(s.get("ST6"), 22, 50),
105
+ safe(s.get("T2M"), 25, 50),
106
+ safe(s.get("T2M_MAX"), 30, 50),
107
+ safe(s.get("T2M_MIN"), 20, 50),
108
+ safe(s.get("TRANGE"), 10, 25),
109
+ safe(s.get("RH2M"), 50, 100),
110
+ min(safe(s.get("PREC"), 0) / 50, 1),
111
+ safe(s.get("SOLAR"), 15, 30),
112
+ safe(s.get("WIND"), 2, 15),
113
+ safe(s.get("VPD"), 1, 5),
114
+ safe(s.get("CLOUD"), 50, 100),
115
+ safe(s.get("TDEW"), 15, 35),
116
+ safe(s.get("PS"), 100, 110),
117
+ safe(s.get("LW"), 300, 500),
118
+ min(safe(s.get("ET0"), 4) / 10, 1),
119
+ safe(s.get("RAD"), 15, 35),
120
+ min(safe(s.get("WMAX"), 5) / 20, 1),
121
+ safe(s.get("PM25"), 20, 200),
122
+ safe(s.get("PM10"), 40, 300),
123
+ safe(s.get("DUST"), 5, 50),
124
+ safe(s.get("UV"), 5, 15),
125
+ safe(s.get("AOD"), 0.2, 1),
126
+ safe(s.get("soil_clay"), 25, 100),
127
+ safe(s.get("soil_sand"), 50, 100),
128
+ safe(s.get("soil_soc"), 10, 50),
129
+ safe(s.get("soil_ph"), 6.5, 14),
130
+ safe(s.get("elevation"), 200, 5000),
131
+ safe(s.get("GDD"), 15, 35),
132
+ safe(s.get("WCODE"), 0, 100),
133
+ s.get("DOY_SIN", 0),
134
+ s.get("DOY_COS", 0),
135
+ s.get("MON_SIN", 0),
136
+ s.get("MON_COS", 0),
137
+ safe(s.get("lat"), 20, 35),
138
+ safe(s.get("lon"), 80, 100),
139
+ len(s.get("crops", [])) / 5.0,
140
+ 1.0 if any(c in s.get("crops", []) for c in ["rice", "wheat"]) else 0.0,
141
+ ]], dtype=torch.float32)
142
+
143
+ crops = s.get("crops", [])
144
+ ctx = torch.tensor([[
145
+ safe(s.get("lat"), 20, 35),
146
+ safe(s.get("lon"), 80, 100),
147
+ len(crops) / 5.0,
148
+ 1.0 if "rice" in crops else 0.0,
149
+ 1.0 if "wheat" in crops else 0.0,
150
+ 1.0 if "cotton" in crops else 0.0,
151
+ 1.0 if "sugarcane" in crops else 0.0,
152
+ safe(s.get("soil_clay"), 25, 100),
153
+ safe(s.get("elevation"), 200, 5000),
154
+ ]], dtype=torch.float32)
155
+
156
+ st = s.get("state", "Other")
157
+ state_idx = torch.tensor([STATES.index(st) if st in STATES else len(STATES) - 1])
158
+ ir = s.get("irrig", "rainfed")
159
+ irrig_idx = torch.tensor([IRRIGATION.index(ir) if ir in IRRIGATION else 0])
160
+
161
+ return feat, ctx, state_idx, irrig_idx
@@ -0,0 +1,120 @@
1
+ """
2
+ KisanNet v3 -- Cross-Attention Transformer for Crop Distress Prediction.
3
+
4
+ Architecture:
5
+ - 42-dimensional satellite feature encoder (3-layer MLP)
6
+ - 45-dimensional context encoder (location + state + irrigation embeddings)
7
+ - 4-layer, 8-head cross-attention fusion
8
+ - Three prediction heads: distress score, intervention days, risk class
9
+ """
10
+
11
+ import torch
12
+ import torch.nn as nn
13
+
14
+
15
+ STATES = [
16
+ "UP", "PB", "HR", "MH", "MP", "RJ", "GJ", "KA", "AP", "TS", "TN", "KL",
17
+ "WB", "BR", "OR", "AS", "JH", "CG", "UK", "HP", "TR", "MN", "ML", "GA",
18
+ "JK", "AR", "MZ", "NL", "SK", "Other",
19
+ ]
20
+
21
+ IRRIGATION = ["rainfed", "canal", "borewell", "drip"]
22
+
23
+ RISK_LABELS = ["Healthy", "Watch", "Alert", "Critical", "Emergency"]
24
+
25
+ N_FEATURES = 42
26
+
27
+
28
+ class KisanNetV3(nn.Module):
29
+ """
30
+ Multi-modal crop distress prediction model.
31
+
32
+ Inputs:
33
+ feat -- (B, 42) normalised satellite / weather features
34
+ ctx -- (B, 9) context vector (lat, lon, crop flags, soil, elev)
35
+ state_idx -- (B,) integer index into STATES
36
+ irrig_idx -- (B,) integer index into IRRIGATION
37
+
38
+ Outputs (dict):
39
+ distress_score -- (B,) float in [0, 1]
40
+ intervention_days -- (B,) float >= 0
41
+ risk_logits -- (B, 5)
42
+ risk_class -- (B,) argmax of risk_logits
43
+ """
44
+
45
+ def __init__(
46
+ self,
47
+ feat_dim: int = 42,
48
+ ctx_dim: int = 9,
49
+ n_states: int = 30,
50
+ n_irrig: int = 4,
51
+ hidden: int = 256,
52
+ n_heads: int = 8,
53
+ n_layers: int = 4,
54
+ dropout: float = 0.15,
55
+ ):
56
+ super().__init__()
57
+ self.state_emb = nn.Embedding(n_states, 24)
58
+ self.irrig_emb = nn.Embedding(n_irrig, 12)
59
+
60
+ self.sat_enc = nn.Sequential(
61
+ nn.Linear(feat_dim, hidden), nn.LayerNorm(hidden), nn.GELU(), nn.Dropout(dropout),
62
+ nn.Linear(hidden, hidden), nn.LayerNorm(hidden), nn.GELU(), nn.Dropout(dropout),
63
+ nn.Linear(hidden, hidden), nn.LayerNorm(hidden), nn.GELU(),
64
+ )
65
+
66
+ ctx_total = ctx_dim + 24 + 12
67
+ self.ctx_enc = nn.Sequential(
68
+ nn.Linear(ctx_total, hidden), nn.LayerNorm(hidden), nn.GELU(), nn.Dropout(dropout),
69
+ nn.Linear(hidden, hidden), nn.LayerNorm(hidden), nn.GELU(),
70
+ )
71
+
72
+ self.xattn = nn.ModuleList()
73
+ self.xnorm = nn.ModuleList()
74
+ self.xffn = nn.ModuleList()
75
+ for _ in range(n_layers):
76
+ self.xattn.append(nn.MultiheadAttention(hidden, n_heads, batch_first=True, dropout=0.1))
77
+ self.xnorm.append(nn.LayerNorm(hidden))
78
+ self.xffn.append(nn.Sequential(
79
+ nn.Linear(hidden, hidden * 4), nn.GELU(), nn.Dropout(0.1),
80
+ nn.Linear(hidden * 4, hidden), nn.LayerNorm(hidden),
81
+ ))
82
+
83
+ self.distress_head = nn.Sequential(
84
+ nn.Linear(hidden * 2, hidden), nn.GELU(), nn.Dropout(0.1),
85
+ nn.Linear(hidden, 64), nn.GELU(), nn.Linear(64, 1), nn.Sigmoid(),
86
+ )
87
+ self.intervention_head = nn.Sequential(
88
+ nn.Linear(hidden * 2, hidden), nn.GELU(), nn.Dropout(0.1),
89
+ nn.Linear(hidden, 64), nn.GELU(), nn.Linear(64, 1), nn.ReLU(),
90
+ )
91
+ self.risk_head = nn.Sequential(
92
+ nn.Linear(hidden * 2, hidden), nn.GELU(), nn.Dropout(0.1),
93
+ nn.Linear(hidden, 64), nn.GELU(), nn.Linear(64, 5),
94
+ )
95
+
96
+ def forward(self, feat, ctx, state_idx, irrig_idx):
97
+ se = self.state_emb(state_idx)
98
+ ie = self.irrig_emb(irrig_idx)
99
+ ctx_in = torch.cat([ctx, se, ie], dim=-1)
100
+
101
+ sat = self.sat_enc(feat)
102
+ ctx_out = self.ctx_enc(ctx_in)
103
+
104
+ fused = sat
105
+ ctx_kv = ctx_out.unsqueeze(1)
106
+ for attn, norm, ffn in zip(self.xattn, self.xnorm, self.xffn):
107
+ a, _ = attn(fused.unsqueeze(1), ctx_kv, ctx_kv)
108
+ fused = norm(fused + a.squeeze(1))
109
+ fused = fused + ffn(fused)
110
+
111
+ combined = torch.cat([fused, ctx_out], dim=-1)
112
+ return {
113
+ "distress_score": self.distress_head(combined).squeeze(-1),
114
+ "intervention_days": self.intervention_head(combined).squeeze(-1),
115
+ "risk_logits": self.risk_head(combined),
116
+ "risk_class": torch.argmax(self.risk_head(combined), dim=-1),
117
+ }
118
+
119
+ def count_parameters(self) -> int:
120
+ return sum(p.numel() for p in self.parameters() if p.requires_grad)
@@ -0,0 +1,113 @@
1
+ """
2
+ High-level inference API for KisanNet v3.
3
+
4
+ Usage::
5
+
6
+ from krishikarm import Predictor
7
+
8
+ predictor = Predictor() # loads bundled weights
9
+ result = predictor.predict({
10
+ "lat": 12.97, "lon": 77.59,
11
+ "T2M": 32, "RH2M": 65, "PREC": 2.5,
12
+ "SOLAR": 18, "WIND": 3,
13
+ "state": "KA", "irrig": "borewell",
14
+ "crops": ["rice"],
15
+ })
16
+ print(result)
17
+ # {
18
+ # "distress_score": 0.12,
19
+ # "intervention_days": 26.4,
20
+ # "risk_class": 0,
21
+ # "risk_label": "Healthy",
22
+ # }
23
+ """
24
+
25
+ from pathlib import Path
26
+ from typing import Optional
27
+
28
+ import torch
29
+
30
+ from .model import KisanNetV3, RISK_LABELS
31
+ from .features import engineer_sample, to_tensors
32
+
33
+ _DEFAULT_WEIGHTS = Path(__file__).parent / "weights" / "kisan_net_v3.pth"
34
+
35
+
36
+ class Predictor:
37
+ """Load a trained KisanNet v3 checkpoint and run inference.
38
+
39
+ Parameters
40
+ ----------
41
+ weights_path : str or Path, optional
42
+ Path to a ``.pth`` checkpoint. Defaults to the bundled weights
43
+ shipped with this package.
44
+ device : str, optional
45
+ ``"cpu"`` or ``"cuda"``. Defaults to CUDA when available.
46
+ """
47
+
48
+ def __init__(
49
+ self,
50
+ weights_path: Optional[str] = None,
51
+ device: Optional[str] = None,
52
+ ):
53
+ self.device = torch.device(
54
+ device or ("cuda" if torch.cuda.is_available() else "cpu")
55
+ )
56
+
57
+ self.model = KisanNetV3()
58
+ path = Path(weights_path) if weights_path else _DEFAULT_WEIGHTS
59
+
60
+ if not path.exists():
61
+ raise FileNotFoundError(
62
+ f"Model weights not found at {path}. "
63
+ "Pass weights_path explicitly or ensure the bundled weights exist."
64
+ )
65
+
66
+ ckpt = torch.load(path, map_location=self.device, weights_only=True)
67
+ self.model.load_state_dict(ckpt["model_state_dict"])
68
+ self.model.to(self.device)
69
+ self.model.eval()
70
+
71
+ self.metadata = ckpt.get("metadata", {})
72
+
73
+ @torch.no_grad()
74
+ def predict(self, observation: dict) -> dict:
75
+ """Run prediction on a single observation dict.
76
+
77
+ The dict should contain raw satellite / weather fields such as
78
+ ``T2M``, ``RH2M``, ``PREC``, ``SOLAR``, ``lat``, ``lon``, etc.
79
+ Missing fields are filled with sensible defaults.
80
+
81
+ Returns a dict with ``distress_score``, ``intervention_days``,
82
+ ``risk_class`` (int), and ``risk_label`` (str).
83
+ """
84
+ s = engineer_sample(dict(observation)) # copy to avoid mutating caller
85
+ feat, ctx, state_idx, irrig_idx = to_tensors(s)
86
+
87
+ feat = feat.to(self.device)
88
+ ctx = ctx.to(self.device)
89
+ state_idx = state_idx.to(self.device)
90
+ irrig_idx = irrig_idx.to(self.device)
91
+
92
+ out = self.model(feat, ctx, state_idx, irrig_idx)
93
+
94
+ risk_class = int(out["risk_class"].item())
95
+ return {
96
+ "distress_score": round(float(out["distress_score"].item()), 4),
97
+ "intervention_days": round(float(out["intervention_days"].item()), 1),
98
+ "risk_class": risk_class,
99
+ "risk_label": RISK_LABELS[risk_class],
100
+ }
101
+
102
+ @torch.no_grad()
103
+ def predict_batch(self, observations: list[dict]) -> list[dict]:
104
+ """Run prediction on a list of observation dicts."""
105
+ return [self.predict(obs) for obs in observations]
106
+
107
+ def info(self) -> dict:
108
+ """Return model metadata from the checkpoint."""
109
+ return {
110
+ "parameters": self.model.count_parameters(),
111
+ "device": str(self.device),
112
+ **self.metadata,
113
+ }
@@ -0,0 +1,143 @@
1
+ Metadata-Version: 2.4
2
+ Name: krishikarm
3
+ Version: 0.1.0
4
+ Summary: Crop distress prediction from satellite and weather data using a cross-attention transformer (KisanNet v3).
5
+ Author-email: Varshini CB <varshinicb1@gmail.com>
6
+ License: MIT
7
+ Project-URL: Homepage, https://github.com/varshinicb1/Krishikarm
8
+ Project-URL: Repository, https://github.com/varshinicb1/Krishikarm
9
+ Project-URL: Issues, https://github.com/varshinicb1/Krishikarm/issues
10
+ Keywords: agriculture,satellite,crop-prediction,deep-learning,transformer,india,farming
11
+ Classifier: Development Status :: 4 - Beta
12
+ Classifier: Intended Audience :: Science/Research
13
+ Classifier: License :: OSI Approved :: MIT License
14
+ Classifier: Programming Language :: Python :: 3
15
+ Classifier: Programming Language :: Python :: 3.9
16
+ Classifier: Programming Language :: Python :: 3.10
17
+ Classifier: Programming Language :: Python :: 3.11
18
+ Classifier: Programming Language :: Python :: 3.12
19
+ Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
20
+ Classifier: Topic :: Scientific/Engineering :: Atmospheric Science
21
+ Requires-Python: >=3.9
22
+ Description-Content-Type: text/markdown
23
+ License-File: LICENSE
24
+ Requires-Dist: torch>=2.0
25
+ Requires-Dist: numpy>=1.24
26
+ Dynamic: license-file
27
+
28
+ # Krishikarm
29
+
30
+ **Crop distress prediction from satellite and weather data.**
31
+
32
+ Krishikarm uses KisanNet v3, a cross-attention transformer trained on 82,000+ real
33
+ satellite observations across 127 Indian districts, to predict crop health risk
34
+ in real time.
35
+
36
+ ## Installation
37
+
38
+ ```bash
39
+ pip install krishikarm
40
+ ```
41
+
42
+ ## Quick Start
43
+
44
+ ```python
45
+ from krishikarm import Predictor
46
+
47
+ predictor = Predictor()
48
+
49
+ result = predictor.predict({
50
+ "lat": 12.97,
51
+ "lon": 77.59,
52
+ "T2M": 32,
53
+ "RH2M": 65,
54
+ "PREC": 2.5,
55
+ "SOLAR": 18,
56
+ "WIND": 3,
57
+ "state": "KA",
58
+ "irrig": "borewell",
59
+ "crops": ["rice"],
60
+ })
61
+
62
+ print(result)
63
+ # {
64
+ # "distress_score": 0.12,
65
+ # "intervention_days": 26.4,
66
+ # "risk_class": 0,
67
+ # "risk_label": "Healthy"
68
+ # }
69
+ ```
70
+
71
+ ## Model Architecture
72
+
73
+ KisanNet v3 is a cross-attention transformer with:
74
+
75
+ - **42 input features** derived from weather, soil, atmosphere, and location data
76
+ - **State and irrigation embeddings** for regional context
77
+ - **4-layer, 8-head cross-attention** fusion between satellite and context encoders
78
+ - **Three prediction heads**: distress score (0-1), intervention window (days), risk class (5 levels)
79
+ - **96.8% accuracy** on held-out test data
80
+
81
+ ### Input Features
82
+
83
+ | Source | Features |
84
+ |--------------|------------------------------------------------------------------|
85
+ | Weather | Temperature, humidity, precipitation, wind, cloud cover, dew point |
86
+ | Solar | Shortwave radiation, UV index, longwave radiation |
87
+ | Soil | Moisture (3 depths), temperature (2 depths), clay, sand, SOC, pH |
88
+ | Atmosphere | PM2.5, PM10, dust, aerosol optical depth |
89
+ | Derived | NDVI proxy, VPD, GDD, thermal range |
90
+ | Location | Latitude, longitude, elevation, day-of-year encoding |
91
+
92
+ ### Risk Classes
93
+
94
+ | Class | Label | Distress Range |
95
+ |-------|-----------|----------------|
96
+ | 0 | Healthy | 0.00 - 0.15 |
97
+ | 1 | Watch | 0.15 - 0.30 |
98
+ | 2 | Alert | 0.30 - 0.50 |
99
+ | 3 | Critical | 0.50 - 0.75 |
100
+ | 4 | Emergency | 0.75 - 1.00 |
101
+
102
+ ## Data Sources
103
+
104
+ All training data was collected from free, open APIs:
105
+
106
+ - **NASA POWER** -- Solar radiation, temperature, humidity
107
+ - **Open-Meteo** -- Weather forecasts, soil moisture, UV, air quality
108
+ - **SoilGrids** -- Soil composition (clay, sand, SOC, pH)
109
+ - **Open-Elevation** -- Terrain altitude
110
+
111
+ No proprietary data or paid APIs were used.
112
+
113
+ ## API Reference
114
+
115
+ ### `Predictor`
116
+
117
+ ```python
118
+ Predictor(weights_path=None, device=None)
119
+ ```
120
+
121
+ - `weights_path` -- Path to a `.pth` checkpoint. Defaults to the bundled v3 weights.
122
+ - `device` -- `"cpu"` or `"cuda"`. Defaults to CUDA when available.
123
+
124
+ #### Methods
125
+
126
+ - `predict(observation: dict) -> dict` -- Run prediction on a single observation.
127
+ - `predict_batch(observations: list[dict]) -> list[dict]` -- Batch prediction.
128
+ - `info() -> dict` -- Return model metadata.
129
+
130
+ ### `KisanNetV3`
131
+
132
+ The raw PyTorch model class, for advanced users who want to integrate the
133
+ architecture into their own training pipeline.
134
+
135
+ ## Requirements
136
+
137
+ - Python >= 3.9
138
+ - PyTorch >= 2.0
139
+ - NumPy >= 1.24
140
+
141
+ ## License
142
+
143
+ MIT
@@ -0,0 +1,15 @@
1
+ LICENSE
2
+ MANIFEST.in
3
+ PKG_README.md
4
+ README.md
5
+ pyproject.toml
6
+ krishikarm/__init__.py
7
+ krishikarm/features.py
8
+ krishikarm/model.py
9
+ krishikarm/predict.py
10
+ krishikarm.egg-info/PKG-INFO
11
+ krishikarm.egg-info/SOURCES.txt
12
+ krishikarm.egg-info/dependency_links.txt
13
+ krishikarm.egg-info/requires.txt
14
+ krishikarm.egg-info/top_level.txt
15
+ krishikarm/weights/kisan_net_v3.pth
@@ -0,0 +1,2 @@
1
+ torch>=2.0
2
+ numpy>=1.24
@@ -0,0 +1 @@
1
+ krishikarm
@@ -0,0 +1,50 @@
1
+ [build-system]
2
+ requires = ["setuptools>=68.0", "wheel"]
3
+ build-backend = "setuptools.build_meta"
4
+
5
+ [project]
6
+ name = "krishikarm"
7
+ version = "0.1.0"
8
+ description = "Crop distress prediction from satellite and weather data using a cross-attention transformer (KisanNet v3)."
9
+ readme = "PKG_README.md"
10
+ license = {text = "MIT"}
11
+ requires-python = ">=3.9"
12
+ authors = [
13
+ {name = "Varshini CB", email = "varshinicb1@gmail.com"},
14
+ ]
15
+ keywords = [
16
+ "agriculture",
17
+ "satellite",
18
+ "crop-prediction",
19
+ "deep-learning",
20
+ "transformer",
21
+ "india",
22
+ "farming",
23
+ ]
24
+ classifiers = [
25
+ "Development Status :: 4 - Beta",
26
+ "Intended Audience :: Science/Research",
27
+ "License :: OSI Approved :: MIT License",
28
+ "Programming Language :: Python :: 3",
29
+ "Programming Language :: Python :: 3.9",
30
+ "Programming Language :: Python :: 3.10",
31
+ "Programming Language :: Python :: 3.11",
32
+ "Programming Language :: Python :: 3.12",
33
+ "Topic :: Scientific/Engineering :: Artificial Intelligence",
34
+ "Topic :: Scientific/Engineering :: Atmospheric Science",
35
+ ]
36
+ dependencies = [
37
+ "torch>=2.0",
38
+ "numpy>=1.24",
39
+ ]
40
+
41
+ [project.urls]
42
+ Homepage = "https://github.com/varshinicb1/Krishikarm"
43
+ Repository = "https://github.com/varshinicb1/Krishikarm"
44
+ Issues = "https://github.com/varshinicb1/Krishikarm/issues"
45
+
46
+ [tool.setuptools.packages.find]
47
+ include = ["krishikarm*"]
48
+
49
+ [tool.setuptools.package-data]
50
+ krishikarm = ["weights/*.pth"]
@@ -0,0 +1,4 @@
1
+ [egg_info]
2
+ tag_build =
3
+ tag_date = 0
4
+