Download backend/weather_shock.py from bapi143/CropAI: direct link, hf CLI and curl.
- Browser
- Download file 12.3 kB
-
https://huggingface.co/spaces/bapi143/CropAI/resolve/main/backend/weather_shock.py
- Command line
-
hf download hf://spaces/bapi143/CropAI/backend/weather_shock.py
-
curl -L -o weather_shock.py https://huggingface.co/spaces/bapi143/CropAI/resolve/main/backend/weather_shock.py
12.3 kB
| # -*- coding: utf-8 -*- | |
| """ | |
| CropAI Extreme Weather Shock & Crop Thermal Protection Engine | |
| Predicts and delivers urgent prophylactic intervention protocols for: | |
| 1. Nocturnal Ground Radiation Frost (पाला) - Stefan-Boltzmann radiative cooling (T <= 2.0°C) | |
| 2. Terminal Heatwave Shock (लू) - Reproductive & grain-shrivel thermal stress (T >= 38.0°C) | |
| Calibrated to Indian knapsack sprayers (16L tank) with emergency bio-chemical recipes. | |
| """ | |
| from typing import Dict, Any, Optional, List | |
| import logging | |
| import math | |
| logger = logging.getLogger("cropai.weather_shock") | |
| # ========================================================================= | |
| # Thermal Vulnerability Crop Stage Matrix | |
| # ========================================================================= | |
| THERMAL_VULNERABILITY_MATRIX: Dict[str, Dict[str, Any]] = { | |
| "Potato": { | |
| "crop_name": "Potato (आलू)", | |
| "frost_critical_temp_c": 2.5, | |
| "heat_critical_temp_c": 32.0, | |
| "vulnerable_stage": "Tuber Initiation & Foliar Canopy Growth", | |
| "frost_damage_description": "Frost crystallizes intracellular water, bursting cell walls and turning foliage black overnight.", | |
| "heat_damage_description": "Excess heat halts tuberization and causes internal brown spot and heat necrosis." | |
| }, | |
| "Tomato": { | |
| "crop_name": "Tomato (टमाटर)", | |
| "frost_critical_temp_c": 2.0, | |
| "heat_critical_temp_c": 35.0, | |
| "vulnerable_stage": "Flowering & Fruit Setting (फूल एवं फल विकास)", | |
| "frost_damage_description": "Terminal flower drop, fruit blistering, and rapid stem collapse.", | |
| "heat_damage_description": "High temperature causes severe flower drop, blossom end rot, and sunscald." | |
| }, | |
| "Wheat": { | |
| "crop_name": "Wheat (गेहूं)", | |
| "frost_critical_temp_c": 0.5, | |
| "heat_critical_temp_c": 36.0, | |
| "vulnerable_stage": "Flowering & Dough/Grain Filling (दुग्ध व दाना भराव)", | |
| "frost_damage_description": "Earhead sterility, floret damage, and tip chlorosis.", | |
| "heat_damage_description": "Terminal heat shock forces premature drying, resulting in shriveled, lightweight grains (दाना सिकुड़ना)." | |
| }, | |
| "Mustard": { | |
| "crop_name": "Mustard (सरसों)", | |
| "frost_critical_temp_c": 2.0, | |
| "heat_critical_temp_c": 34.0, | |
| "vulnerable_stage": "Siliqua / Pod Formation (फलियां बनने की अवस्था)", | |
| "frost_damage_description": "Pod freezing, seed abortion, and white blistered pods.", | |
| "heat_damage_description": "Early pod shattering and reduced oil content." | |
| }, | |
| "Chickpea": { | |
| "crop_name": "Gram / Chickpea (चना)", | |
| "frost_critical_temp_c": 2.0, | |
| "heat_critical_temp_c": 35.0, | |
| "vulnerable_stage": "Flowering & Pod Filling (फूल एवं दाना भराव)", | |
| "frost_damage_description": "Flower shedding and hollow unfilled pods.", | |
| "heat_damage_description": "Forced maturity and pod borer resurgence." | |
| } | |
| } | |
| def evaluate_thermal_weather_shock( | |
| crop: str = "Potato", | |
| ambient_temp_c: float = 4.0, | |
| min_predicted_temp_c: float = 1.5, | |
| max_predicted_temp_c: float = 24.0, | |
| relative_humidity: float = 55.0, | |
| wind_speed_kmh: float = 3.0, | |
| cloud_cover_pct: float = 5.0, | |
| growth_stage: Optional[str] = None | |
| ) -> Dict[str, Any]: | |
| """ | |
| Evaluates microclimate thermal extremes: | |
| 1. Ground Radiation Frost (पाला) Risk: | |
| Clear skies (cloud < 20%), calm wind (< 5 km/h), min temp <= 2.5°C. | |
| 2. Terminal Heatwave (लू) Risk: | |
| Max temp >= 36.0°C - 38.0°C with low humidity. | |
| """ | |
| crop_info = THERMAL_VULNERABILITY_MATRIX.get(crop, THERMAL_VULNERABILITY_MATRIX["Potato"]) | |
| frost_thresh = crop_info["frost_critical_temp_c"] | |
| heat_thresh = crop_info["heat_critical_temp_c"] | |
| # ===================================================================== | |
| # 1. Nocturnal Radiation Frost Modeling | |
| # ===================================================================== | |
| # Stefan-Boltzmann clear-sky radiative cooling factor | |
| # Clear night with low humidity radiates heat rapidly; canopy is typically 1.5°C to 2.5°C colder than air at 2m! | |
| canopy_night_offset = 0.0 | |
| if cloud_cover_pct < 25.0 and wind_speed_kmh < 8.0: | |
| # Radiation inversion condition | |
| canopy_night_offset = 2.0 * (1.0 - (cloud_cover_pct / 100.0)) * max(0.4, 1.0 - (relative_humidity / 100.0)) | |
| estimated_canopy_min_c = round(min_predicted_temp_c - canopy_night_offset, 1) | |
| frost_risk = False | |
| frost_severity = "SAFE" | |
| frost_alert_hi = None | |
| frost_alert_en = None | |
| frost_recipe = None | |
| if estimated_canopy_min_c <= frost_thresh: | |
| frost_risk = True | |
| if estimated_canopy_min_c <= 0.5: | |
| frost_severity = "CRITICAL_FREEZE_SIREN" | |
| frost_alert_hi = f"🚨 आपातकालीन पाला सायरन! आज रात खेत की सतह का तापमान {estimated_canopy_min_c}°C तक गिरने की आशंका है। पाले से {crop_info['crop_name']} पूरी तरह काली पड़ सकती है!" | |
| frost_alert_en = f"EMERGENCY FROST SIREN: Nocturnal surface temperature projected to reach {estimated_canopy_min_c}°C. Severe freeze necrosis imminent." | |
| else: | |
| frost_severity = "HIGH_FROST_WARNING" | |
| frost_alert_hi = f"⚠️ पाला चेतावनी: आज रात तापमान {estimated_canopy_min_c}°C तक गिर सकता है। फसल सुरक्षा उपाय तुरंत करें।" | |
| frost_alert_en = f"FROST WARNING: Canopy temp dropping to {estimated_canopy_min_c}°C tonight. Deploy protective measures." | |
| frost_recipe = { | |
| "emergency_actions": [ | |
| { | |
| "action_hi": "खेत की मेड़ों पर धुआं करना (Smoke Smudge Barrier)", | |
| "action_en": "Create border smoke smudge blanket", | |
| "details_hi": "रात 2:00 बजे से सुबह 6:00 बजे तक खेत की उत्तर-पश्चिम दिशा में गीली घास व पराली जलाकर धुआं करें। धुआं चादर बनकर तापमान को 2°C तक बढ़ा देता है।" | |
| }, | |
| { | |
| "action_hi": "रात्रि हल्की सिंचाई (Light Night Irrigation)", | |
| "action_en": "Light midnight flood irrigation", | |
| "details_hi": "शाम या रात में खेत में हल्का पानी चलाएं। पानी की विशिष्ट ऊष्मा (Specific Heat) अधिक होने से खेत की मिट्टी का तापमान शून्य से नीचे नहीं गिरता।" | |
| }, | |
| { | |
| "action_hi": "घुलनशील सल्फर का स्प्रे (Soluble Sulphur Osmoprotectant)", | |
| "action_en": "Foliar soluble sulphur spray", | |
| "details_hi": "16 लीटर के पंप में 16 ग्राम घुलनशील गंधक (Sulphur 80% WDG) या 30 ग्राम ग्लूकोज घोलकर शाम 4 बजे छिड़कें। यह कोशिका रस को जमने से रोकता है।" | |
| } | |
| ], | |
| "knapsack_dose": "16g Sulphur 80% WDG per 16L spray tank" | |
| } | |
| # ===================================================================== | |
| # 2. Terminal Heatwave Modeling (लू) | |
| # ===================================================================== | |
| heat_risk = False | |
| heat_severity = "SAFE" | |
| heat_alert_hi = None | |
| heat_alert_en = None | |
| heat_recipe = None | |
| if max_predicted_temp_c >= heat_thresh: | |
| heat_risk = True | |
| if max_predicted_temp_c >= 40.0: | |
| heat_severity = "CRITICAL_HEATWAVE_SIREN" | |
| heat_alert_hi = f"🔥 प्रचंड लू चेतावनी! तापमान {max_predicted_temp_c}°C तक पहुंचेगा। {crop_info['crop_name']} में फूल और दाना झुलसने (दाना सिकुड़ना) का खतरा है!" | |
| heat_alert_en = f"CRITICAL HEATWAVE SIREN: Peak temperature {max_predicted_temp_c}°C exceeds lethal threshold ({heat_thresh}°C). Severe flower/grain desiccation risk." | |
| else: | |
| heat_severity = "MODERATE_HEAT_STRESS" | |
| heat_alert_hi = f"☀️ गर्मी का तनाव: तापमान {max_predicted_temp_c}°C रहने से परागकण सूखने का खतरा है।" | |
| heat_alert_en = f"HEAT STRESS ALERT: Maximum temp {max_predicted_temp_c}°C approaching critical threshold." | |
| heat_recipe = { | |
| "emergency_actions": [ | |
| { | |
| "action_hi": "पोटैशियम नाइट्रेट स्प्रे (Potassium Nitrate 13:0:45)", | |
| "action_en": "1% Potassium Nitrate Osmoprotectant Spray", | |
| "details_hi": "16 लीटर के पंप में 160 ग्राम पोटैशियम नाइट्रेट (KNO3 13:0:45) घोलकर सुबह के समय स्प्रे करें। यह पौधों के रंध्रों (Stomata) को नियंत्रित कर पानी की बर्बादी रोकता है।" | |
| }, | |
| { | |
| "action_hi": "दोपहर की हल्की फव्वारा सिंचाई (Micro-Sprinkler Mist)", | |
| "action_en": "Canopy cooling micro-sprinklers", | |
| "details_hi": "दोपहर 12 से 2 बजे के बीच 15 मिनट फव्वारा चलाएं ताकि खेत का तापमान तुरंत 3°C से 4°C ठंडा हो जाए।" | |
| } | |
| ], | |
| "knapsack_dose": "160g Potassium Nitrate (13:0:45) in 16L spray tank" | |
| } | |
| # Synthesize unified assessment | |
| primary_threat = "NONE" | |
| if frost_risk and heat_risk: | |
| primary_threat = "DIURNAL_EXTREME_FLUCTUATION" | |
| elif frost_risk: | |
| primary_threat = "FROST_RADIATION_COLD" | |
| elif heat_risk: | |
| primary_threat = "TERMINAL_HEATWAVE_SHOCK" | |
| return { | |
| "status": "success", | |
| "crop": crop_info["crop_name"], | |
| "vulnerable_stage": growth_stage or crop_info["vulnerable_stage"], | |
| "primary_threat": primary_threat, | |
| "microclimate_snapshot": { | |
| "ambient_temp_c": ambient_temp_c, | |
| "min_predicted_temp_c": min_predicted_temp_c, | |
| "estimated_canopy_surface_min_c": estimated_canopy_min_c, | |
| "max_predicted_temp_c": max_predicted_temp_c, | |
| "relative_humidity_pct": relative_humidity, | |
| "wind_speed_kmh": wind_speed_kmh, | |
| "cloud_cover_pct": cloud_cover_pct | |
| }, | |
| "frost_assessment": { | |
| "risk_detected": frost_risk, | |
| "severity": frost_severity, | |
| "threshold_critical_c": frost_thresh, | |
| "alert_hi": frost_alert_hi, | |
| "alert_en": frost_alert_en, | |
| "damage_mechanism": crop_info["frost_damage_description"], | |
| "intervention": frost_recipe | |
| }, | |
| "heatwave_assessment": { | |
| "risk_detected": heat_risk, | |
| "severity": heat_severity, | |
| "threshold_critical_c": heat_thresh, | |
| "alert_hi": heat_alert_hi, | |
| "alert_en": heat_alert_en, | |
| "damage_mechanism": crop_info["heat_damage_description"], | |
| "intervention": heat_recipe | |
| } | |
| } | |