nextgenyeild-api / api /rules.py
Hassan132's picture
Deploy NextGenYeild API to Hugging Face Spaces
c54c1bf
Raw History Blame Contribute Delete
7.54 kB
"""
NextGenYeild: Deterministic Agronomic Decision Support Engine
Encodes the official 6-stage wheat growth-stage agronomic matrix.
Strictly follows the principle: NO hallucinated LLM advice;
all recommendations are derived from validated agricultural science guidelines.
"""
from typing import Dict, Any, List
AGRONOMIC_MATRIX: Dict[str, Dict[str, Any]] = {
"0_tillering": {
"display_name": "Tillering",
"stage_index": 0,
"primary_objective": "Root system establishment & vigorous tiller development.",
"summary": "Crop is in the Tillering stage. Vegetative shoots are actively multiplying from the crown.",
"irrigation_guidance": "Moderate irrigation required. The Crown Root Initiation (CRI) window (20–25 days after sowing) is the single most sensitive irrigation stage.",
"nutrient_guidance": "Apply the first split of Nitrogen top-dressing (e.g., Urea). Ensure adequate root-zone Phosphorus availability.",
"protection_guidance": "Scout for broadleaf and grassy weed competition. Apply selective post-emergence herbicide if weed density exceeds economic threshold.",
"risk_alerts": [
"Weed competition during early tillering severely inhibits tiller density.",
"Water stress at Crown Root Initiation causes irreversible root stunting."
],
},
"1_jointing": {
"display_name": "Jointing (Stem Elongation)",
"stage_index": 1,
"primary_objective": "Rapid stem elongation, internode expansion, and embryonic spikelet development.",
"summary": "Crop is in the Jointing stage. The first stem node is detectable above ground; rapid height growth underway.",
"irrigation_guidance": "High water demand. Maintain continuous optimal soil moisture to prevent internode shortening and spikelet abortion.",
"nutrient_guidance": "Apply the second Nitrogen split before the flag leaf emerges. Avoid excessive nitrogen doses to prevent future crop lodging.",
"protection_guidance": "Actively inspect lower canopy for initial pustules of stripe/yellow rust. Check stems for early stem borer boring holes.",
"risk_alerts": [
"Yellow/Stripe rust spreads rapidly under cool, humid weather during stem elongation.",
"Excessive nitrogen application increases lodging risk later during grain fill."
],
},
"2_booting": {
"display_name": "Booting",
"stage_index": 2,
"primary_objective": "Pollen development and wheat spike protection inside the flag leaf sheath.",
"summary": "Crop is in the Booting stage. The head is actively swelling inside the sheath of the flag leaf.",
"irrigation_guidance": "Critical moisture window. Water deficit during booting irreversibly reduces potential spikelet count and head length.",
"nutrient_guidance": "Avoid heavy granular nitrogen. Apply corrective foliar micronutrients (Zinc, Boron) if micronutrient deficiency symptoms are visible.",
"protection_guidance": "Protect the flag leaf at all costs (it drives > 50% of eventual grain yield). Spray protective fungicide if stripe rust or powdery mildew is present in the field.",
"risk_alerts": [
"Flag leaf damage directly slashes ultimate harvest yield by up to 50%.",
"Moisture stress right before heading causes sterile florets."
],
},
"3_anthesis": {
"display_name": "Anthesis (Flowering)",
"stage_index": 3,
"primary_objective": "Pollination, fertilization, and initial seed set.",
"summary": "Crop is in the Anthesis stage. Yellow anthers are extruded from spikelets and active pollination is occurring.",
"irrigation_guidance": "Maintain adequate root-zone moisture. Avoid high-pressure overhead sprinkler irrigation during peak anthesis to preserve viable pollen.",
"nutrient_guidance": "Strictly no further nitrogen application needed; plant has concluded vegetative nutrient uptake.",
"protection_guidance": "Monitor for Head Blight (Fusarium) if heavy rains or high relative humidity coincide with flowering.",
"risk_alerts": [
"Extreme heat (> 32°C) during anthesis causes floret sterility and poor grain set.",
"Avoid chemical spraying during midday pollinator and pollen-shed hours."
],
},
"4_grain_filling": {
"display_name": "Grain Filling",
"stage_index": 4,
"primary_objective": "Starch, protein, and dry matter accumulation in developing kernels (milk to dough stages).",
"summary": "Crop is in the Grain Filling stage. Kernels are accumulating starch; the green canopy begins a gradual pale yellow transition.",
"irrigation_guidance": "Final irrigation window (early milk stage). Avoid irrigating during late soft dough or during high-wind forecasts to prevent root lodging.",
"nutrient_guidance": "No granular soil fertilizers. Optional potassium foliar spray if terminal drought or high temperatures threaten early kernel desiccation.",
"protection_guidance": "Inspect heads and upper leaves for aphid colonies and late leaf blight. Protect against late-season fungal damage.",
"risk_alerts": [
"Terminal heat waves ('hot dry winds') accelerate premature forced maturity, reducing thousand-grain weight (TGW).",
"Heavy irrigation on tall crops under windy weather will cause severe crop lodging."
],
},
"5_maturity": {
"display_name": "Maturity",
"stage_index": 5,
"primary_objective": "Desiccation, grain hardening, and preparation for timely combine harvesting.",
"summary": "Crop has reached physiological maturity. Canopy is completely golden-brown; kernels are hard and dry.",
"irrigation_guidance": "Cease all irrigation completely. The field must dry out thoroughly to allow combine harvesters and tractors field access.",
"nutrient_guidance": "Strictly zero fertilizer applications.",
"protection_guidance": "Monitor grain moisture percentage regularly (target harvest range: 12%–14%). Harvest promptly to prevent shattering losses or rain-induced pre-harvest sprouting.",
"risk_alerts": [
"Unseasonal late rains can cause pre-harvest sprouting, severely downgrading seed quality and market price.",
"Delayed harvesting increases mechanical shattering loss."
],
},
}
def get_advisory_for_stage(stage_key: str) -> Dict[str, Any]:
"""Retrieves agronomic rules and recommendations for a given growth stage."""
# Standardize stage key
clean_key = stage_key.lower().strip()
if clean_key not in AGRONOMIC_MATRIX:
# Fallback search by number or name
for k, v in AGRONOMIC_MATRIX.items():
if clean_key in k or clean_key in v["display_name"].lower():
clean_key = k
break
return AGRONOMIC_MATRIX.get(clean_key, {
"display_name": "Unknown Stage",
"stage_index": -1,
"primary_objective": "Maintain standard field care.",
"summary": "Stage not identified with sufficient certainty.",
"irrigation_guidance": "Ensure regular soil moisture check.",
"nutrient_guidance": "Consult local agricultural extension.",
"protection_guidance": "Scout for visible pests or leaf discolouration.",
"risk_alerts": ["Uncertain growth stage. Repeat photo under clear, non-blurry lighting."]
})