File size: 8,827 Bytes
32cdc66
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
from flask import Flask, jsonify, request
from flask_cors import CORS
from data_fetcher import DiCRADataFetcher
from forecaster import ClimateHazardForecaster
from config import API_HOST, API_PORT, DEBUG_MODE, DROUGHT_THRESHOLD, FLOOD_THRESHOLD, HEAT_WAVE_THRESHOLD
import pandas as pd
import numpy as np

app = Flask(__name__)
CORS(app)

# Initialize components
fetcher = DiCRADataFetcher()
forecaster = ClimateHazardForecaster()

@app.route('/health', methods=['GET'])
def health():
    """Health check endpoint."""
    return jsonify({'status': 'healthy', 'service': 'KisanSuraksha API'}), 200

@app.route('/api/v1/districts', methods=['GET'])
def get_districts():
    """Get list of Maharashtra districts."""
    try:
        districts = fetcher.get_districts()
        maharashtra_dists = [d for d in districts if d.get('state') == 'Maharashtra']
        return jsonify({'districts': maharashtra_dists}), 200
    except Exception as e:
        return jsonify({'error': str(e)}), 500

@app.route('/api/v1/fetch-data', methods=['POST'])
def fetch_data():
    """Fetch data from DiCRA for training."""
    try:
        data = request.json
        parameters = data.get('parameters', ['soil_moisture_index', 'ndvi', 'rainfall', 'temperature'])
        start_date = data.get('start_date', '2020-01-01')
        end_date = data.get('end_date', '2024-12-31')
        
        df = fetcher.get_maharashtra_data(parameters, start_date, end_date)
        fetcher.save_data(df, 'maharashtra_climate_data.csv')
        
        return jsonify({
            'message': 'Data fetched successfully',
            'rows': len(df),
            'parameters': parameters
        }), 200
    except Exception as e:
        return jsonify({'error': str(e)}), 500

@app.route('/api/v1/train', methods=['POST'])
def train_model():
    """Train forecasting models."""
    try:
        # Load data
        df = fetcher.load_data('maharashtra_climate_data.csv')
        if df is None:
            return jsonify({'error': 'Data not available. Run /fetch-data first.'}), 400
        
        # Train models
        success = forecaster.train_random_forest(df)
        if success:
            forecaster.save_model()
            return jsonify({
                'message': 'Models trained successfully',
                'metrics': forecaster.metrics
            }), 200
        else:
            return jsonify({'error': 'Training failed'}), 500
    except Exception as e:
        return jsonify({'error': str(e)}), 500

@app.route('/api/v1/forecast', methods=['POST'])
def forecast_hazards():
    """Get hazard forecasts for a district."""
    try:
        data = request.json
        district = data.get('district')
        year = int(data.get('year', 2030))
        date_range = data.get('date_range', 'next_30_days')
        
        # Load model if not already loaded
        if not forecaster.models:
            forecaster.load_model()
        
        if not forecaster.models:
            return jsonify({'error': 'Model not trained. Run /train first.'}), 400
        
        # Get recent data for the district
        df = fetcher.load_data('maharashtra_climate_data.csv')
        district_data = df[df['district'] == district].copy()
        
        if district_data.empty:
            return jsonify({'error': f'No data for district: {district}'}), 404
        
        # Prepare features for prediction
        features_df = forecaster.prepare_features(district_data)
        feature_cols = [col for col in features_df.columns 
                       if col not in ['district', 'date']]
        
        latest_features = features_df[feature_cols].iloc[-1:].values
        predictions = forecaster.predict_hazards(latest_features)
        
        # Generate crop advisory based on hazard scores
        # Apply climate projection logic (synchronized with frontend simulation)
        year_diff = max(0, year - 2030)
        
        drought_risk = np.clip(predictions['drought']['risk_score'][0] + (year_diff * 0.015), 0, 1)
        flood_risk = np.clip(predictions['flood']['risk_score'][0] + (year_diff * 0.008), 0, 1)
        heat_risk = np.clip(predictions['heat_wave']['risk_score'][0] + (year_diff * 0.021), 0, 1)
        
        advisory = generate_crop_advisory(drought_risk, flood_risk, heat_risk)
        
        return jsonify({
            'district': district,
            'drought_risk': float(drought_risk),
            'flood_risk': float(flood_risk),
            'heat_wave_risk': float(heat_risk),
            'crop_advisory': advisory
        }), 200
    except Exception as e:
        return jsonify({'error': str(e)}), 500

@app.route('/api/v1/insurance-trigger', methods=['POST'])
def check_insurance_trigger():
    """Check if automatic PMFBY insurance trigger is warranted."""
    try:
        data = request.json
        district = data.get('district')
        year = int(data.get('year', 2030))
        
        if not forecaster.models:
            forecaster.load_model()
        
        df = fetcher.load_data('maharashtra_climate_data.csv')
        district_data = df[df['district'] == district]
        
        features_df = forecaster.prepare_features(district_data)
        feature_cols = [col for col in features_df.columns 
                       if col not in ['district', 'date']]
        
        latest_features = features_df[feature_cols].iloc[-1:].values
        predictions = forecaster.predict_hazards(latest_features)
        
        # Apply projection
        year_diff = max(0, year - 2030)
        drought_risk = np.clip(predictions['drought']['risk_score'][0] + (year_diff * 0.015), 0, 1)
        flood_risk = np.clip(predictions['flood']['risk_score'][0] + (year_diff * 0.008), 0, 1)
        
        trigger = drought_risk > DROUGHT_THRESHOLD or flood_risk > FLOOD_THRESHOLD
        
        return jsonify({
            'district': district,
            'trigger_insurance': trigger,
            'drought_risk': float(drought_risk),
            'flood_risk': float(flood_risk),
            'reason': f"Drought: {drought_risk:.2f}, Flood: {flood_risk:.2f}"
        }), 200
    except Exception as e:
        return jsonify({'error': str(e)}), 500

@app.route('/api/v1/credit-risk', methods=['POST'])
def check_credit_risk():
    """Check NABARD credit risk flag for Kisan Credit Card lending."""
    try:
        data = request.json
        district = data.get('district')
        year = int(data.get('year', 2030))
        
        if not forecaster.models:
            forecaster.load_model()
        
        df = fetcher.load_data('maharashtra_climate_data.csv')
        district_data = df[df['district'] == district]
        
        features_df = forecaster.prepare_features(district_data)
        feature_cols = [col for col in features_df.columns 
                       if col not in ['district', 'date']]
        
        latest_features = features_df[feature_cols].iloc[-1:].values
        predictions = forecaster.predict_hazards(latest_features)
        
        # Apply projection
        year_diff = max(0, year - 2030)
        d_p = np.clip(predictions['drought']['risk_score'][0] + (year_diff * 0.015), 0, 1)
        f_p = np.clip(predictions['flood']['risk_score'][0] + (year_diff * 0.008), 0, 1)
        h_p = np.clip(predictions['heat_wave']['risk_score'][0] + (year_diff * 0.021), 0, 1)
        
        max_risk = max(d_p, f_p, h_p)
        
        risk_level = 'HIGH' if max_risk > 0.7 else 'MEDIUM' if max_risk > 0.5 else 'LOW'
        
        return jsonify({
            'district': district,
            'credit_risk_flag': risk_level,
            'max_hazard_risk': float(max_risk)
        }), 200
    except Exception as e:
        return jsonify({'error': str(e)}), 500

def generate_crop_advisory(drought_risk, flood_risk, heat_risk):
    """Generate crop advisory based on hazard scores."""
    advisory = []
    
    if drought_risk > DROUGHT_THRESHOLD:
        advisory.append("DROUGHT WARNING: Use drought-resistant varieties. Increase irrigation frequency.")
    
    if flood_risk > FLOOD_THRESHOLD:
        advisory.append("FLOOD WARNING: Ensure drainage systems are clear. Avoid planting in low-lying areas.")
    
    if heat_risk > HEAT_WAVE_THRESHOLD:
        advisory.append("HEAT WAVE WARNING: Provide mulching. Increase soil moisture retention.")
    
    if not advisory:
        advisory.append("CONDITIONS FAVORABLE: Current hazard risks are low. Standard crop management recommended.")
    
    return " | ".join(advisory)

if __name__ == '__main__':
    app.run(host=API_HOST, port=API_PORT, debug=DEBUG_MODE)