File size: 12,740 Bytes
8dfc891
 
7973235
 
5c02e21
 
b86605e
8dfc891
b86605e
c4ab81d
 
 
 
 
 
 
 
 
b86605e
c4ab81d
 
 
 
 
 
 
 
74a5f75
5c02e21
b86605e
5c02e21
 
 
 
 
 
 
 
 
 
 
a07334a
5c02e21
7c43484
5c02e21
 
a07334a
5c02e21
a07334a
 
 
 
5c02e21
7c43484
 
 
 
5944a16
5c02e21
a07334a
5c02e21
a07334a
 
5c02e21
b86605e
7c43484
 
 
 
 
 
5c02e21
7c43484
 
 
 
 
 
5c02e21
 
 
 
a07334a
5c02e21
b86605e
5c02e21
 
 
 
a07334a
5c02e21
 
 
a07334a
5c02e21
 
 
5944a16
 
 
 
 
5c02e21
 
 
 
 
7c43484
5c02e21
 
 
 
 
7c43484
5c02e21
 
a07334a
 
7c43484
 
 
5c02e21
 
a07334a
 
7c43484
5c02e21
 
5944a16
5c02e21
 
 
a07334a
5c02e21
7973235
b86605e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5944a16
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a07334a
 
7c43484
a07334a
 
 
 
 
 
7c43484
a07334a
 
 
 
 
 
7c43484
a07334a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7c43484
a07334a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7973235
a07334a
 
 
 
 
 
7c43484
 
a07334a
7c43484
 
a07334a
 
 
7c43484
a07334a
7c43484
 
 
 
a07334a
7c43484
 
 
 
 
 
 
a07334a
7973235
b86605e
5944a16
 
 
 
b86605e
5944a16
 
 
b86605e
 
 
 
 
 
 
5944a16
b86605e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5944a16
2ebb842
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7973235
5c02e21
 
a07334a
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
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
import os
import urllib.request
import gradio as gr
import numpy as np
from part1_data import TobaccoAnalyzer
from part2_visualization import VisualizationHandler
from part3 import SAMAnalyzer
import time

# Add a simple progress indicator
def download_with_progress(url, filename):
    print(f"Downloading {filename}...")
    start_time = time.time()
    urllib.request.urlretrieve(url, filename)
    end_time = time.time()
    print(f"Download completed in {end_time - start_time:.2f} seconds")

# Download SAM model if it doesn't exist
if not os.path.exists('sam_vit_h_4b8939.pth'):
    try:
        download_with_progress(
            'https://dl.fbaipublicfiles.com/segment_anything/sam_vit_h_4b8939.pth',
            'sam_vit_h_4b8939.pth'
        )
    except Exception as e:
        print(f"Error downloading SAM model: {e}")
        print("Please ensure you have internet connection and sufficient disk space.")

def analyze_location(location_name):
    """Analyze location using weather and satellite data"""
    try:
        analyzer = TobaccoAnalyzer()
        visualizer = VisualizationHandler(analyzer.optimal_conditions)
        
        # Get coordinates from location name
        location_data = analyzer.geocode_location(location_name)
        if not location_data:
            return None, None, "Location not found. Please try a different location name.", None
        
        lat, lon = location_data['lat'], location_data['lon']
        
        # Get weather data
        df = analyzer.get_weather_data(lat, lon, historical_days=90, forecast_days=90)
        if df is None or df.empty:
            return None, None, "Unable to fetch weather data. Please try again.", None
        
        # Separate historical and forecast data
        historical = df[df['type'] == 'historical']
        forecast = df[df['type'] != 'historical']
        
        if historical.empty:
            return None, None, "No historical data available.", None
        
        # Calculate base scores
        temp_score = np.clip((historical['temperature'].mean() - 15) / (30 - 15), 0, 1)
        humidity_score = np.clip((historical['humidity'].mean() - 50) / (80 - 50), 0, 1)
        rainfall_score = np.clip(historical['rainfall'].mean() / 5, 0, 1)
        ndvi_score = np.clip((historical['estimated_ndvi'].mean() + 1) / 2, 0, 1)
        
        # Get trends analysis
        trends = analyzer.analyze_trends(df)
        if trends is None:
            return None, None, "Error calculating trends.", None
        
        # Calculate overall score
        weights = {
            'temperature': 0.3,
            'humidity': 0.2,
            'rainfall': 0.2,
            'ndvi': 0.3
        }
        
        overall_score = (
            temp_score * weights['temperature'] +
            humidity_score * weights['humidity'] +
            rainfall_score * weights['rainfall'] +
            ndvi_score * weights['ndvi']
        )
        
        # Create visualizations
        time_series_plot = visualizer.create_interactive_plots(df)
        gauge_plot = visualizer.create_gauge_chart(overall_score)
        location_map = visualizer.create_enhanced_map(lat, lon, overall_score, historical['estimated_ndvi'].mean())
        
        # Generate analysis text
        analysis_text = f"""
        📍 Location Analysis:
        Location: {location_data['address']}
        Coordinates: {lat:.4f}°N, {lon:.4f}°E
        Region: {location_data['region'] if location_data['region'] else 'Unknown'}
        
        🌡️ Historical Weather Analysis (Past 90 Days):
        Temperature: {historical['temperature'].mean():.1f}°C (±{historical['temperature'].std():.1f}°C)
        Daily Range: {historical['temp_range'].mean():.1f}°C
        Humidity: {historical['humidity'].mean():.1f}% (±{historical['humidity'].std():.1f}%)
        Rainfall: {historical['rainfall'].mean():.1f}mm/day (±{historical['rainfall'].std():.1f}mm)
        
        🌿 Vegetation Analysis:
        Current NDVI: {historical['estimated_ndvi'].mean():.2f}
        Minimum NDVI: {historical['estimated_ndvi'].min():.2f}
        Maximum NDVI: {historical['estimated_ndvi'].max():.2f}
        Vegetation Status: {get_vegetation_status(historical['estimated_ndvi'].mean())}
        
        🔮 Forecast Analysis (Next 90 Days):
        Temperature: {forecast['temperature'].mean():.1f}°C (±{forecast['temperature'].std():.1f}°C)
        Humidity: {forecast['humidity'].mean():.1f}% (±{forecast['humidity'].std():.1f}%)
        Rainfall: {forecast['rainfall'].mean():.1f}mm/day (±{forecast['rainfall'].std():.1f}mm)
        Expected NDVI: {forecast['estimated_ndvi'].mean():.2f}
        
        📊 Growing Condition Scores:
        Temperature Score: {temp_score:.2f}
        Humidity Score: {humidity_score:.2f}
        Rainfall Score: {rainfall_score:.2f}
        Vegetation Score: {ndvi_score:.2f}
        Overall Score: {overall_score:.2f}
        
        🎯 Recommendations:
        {get_recommendations(overall_score, ndvi_score)}
        
        ⚠️ Risk Factors:
        {get_risk_factors(df, trends)}
        
        📝 Additional Notes:
        • Growing Season: {is_growing_season(historical['season'].iloc[-1])}
        • Weather Stability: {get_weather_stability(historical)}
        • Long-term Outlook: {get_long_term_outlook(trends)}
        """
        
        return location_map, analysis_text, time_series_plot, gauge_plot
        
    except Exception as e:
        error_message = f"An error occurred: {str(e)}"
        print(f"Error details: {e}")
        return None, None, error_message, None

def analyze_satellite_image(image):
    """Analyze satellite image using SAM2"""
    try:
        analyzer = SAMAnalyzer()
        veg_index, health_analysis, viz_plot = analyzer.process_image(image)
        
        if veg_index is None:
            return None, "Error processing image. Please try again."
        
        analysis_text = analyzer.format_analysis_text(health_analysis)
        
        return viz_plot, analysis_text
    except Exception as e:
        return None, f"Error analyzing image: {str(e)}"

def get_vegetation_status(ndvi):
    """Get detailed vegetation status based on NDVI value"""
    if ndvi < 0:
        return "Very Low - Bare soil or water bodies"
    elif ndvi < 0.1:
        return "Low - Very sparse vegetation"
    elif ndvi < 0.2:
        return "Sparse - Stressed vegetation"
    elif ndvi < 0.3:
        return "Moderate - Typical agricultural land"
    elif ndvi < 0.4:
        return "Good - Healthy vegetation"
    elif ndvi < 0.5:
        return "High - Very healthy vegetation"
    elif ndvi < 0.6:
        return "Very High - Dense vegetation"
    else:
        return "Dense - Very dense, healthy vegetation"

def get_recommendations(score, ndvi):
    """Get detailed recommendations based on scores"""
    if score >= 0.8 and ndvi >= 0.6:
        return """
        ✅ Excellent conditions for tobacco growing
        • Proceed with standard planting schedule
        • Regular monitoring recommended
        • Consider expansion opportunities
        """
    elif score >= 0.6:
        return """
        👍 Good conditions with some considerations
        • Implement basic risk mitigation measures
        • Regular monitoring essential
        • Consider crop insurance
        """
    elif score >= 0.4:
        return """
        ⚠️ Marginal conditions - proceed with caution
        • Enhanced monitoring required
        • Strong risk mitigation needed
        • Crop insurance strongly recommended
        • Consider alternative timing
        """
    else:
        return """
        ❌ Poor conditions - high risk
        • Not recommended for planting
        • Consider alternative locations
        • Extensive risk mitigation needed
        • Alternative crops suggested
        """

def get_risk_factors(df, trends):
    """Analyze and return risk factors"""
    risks = []
    
    if df['temp_range'].mean() > 15:
        risks.append("• High daily temperature variations")
    if trends['historical']['temperature']['trend'] < 0:
        risks.append("• Declining temperature trend")
    if df['rainfall'].std() > df['rainfall'].mean():
        risks.append("• Inconsistent rainfall patterns")
    if trends['historical']['rainfall']['trend'] < 0:
        risks.append("• Decreasing rainfall trend")
    if trends['historical']['ndvi']['trend'] < 0:
        risks.append("• Declining vegetation health")
    
    return "\n".join(risks) if risks else "No major risk factors identified"

def is_growing_season(season):
    """Check if current season is suitable for growing"""
    season_suitability = {
        'Main': "Prime growing season - Optimal conditions",
        'Early': "Early growing season - Good potential",
        'Late': "Late growing season - Monitor closely",
        'Dry': "Dry season - Higher risk period"
    }
    return season_suitability.get(season, "Season not identified")

def get_weather_stability(df):
    """Assess weather stability"""
    temp_std = df['temperature'].std()
    if temp_std < 2:
        return "Very stable weather patterns"
    elif temp_std < 4:
        return "Moderately stable weather"
    return "Unstable weather patterns - higher risk"

def get_long_term_outlook(trends):
    """Assess long-term outlook based on trends"""
    temp_trend = trends['historical']['temperature']['trend']
    rain_trend = trends['historical']['rainfall']['trend']
    
    if temp_trend > 0 and rain_trend > 0:
        return "Improving conditions"
    elif temp_trend < 0 and rain_trend < 0:
        return "Deteriorating conditions"
    return "Mixed conditions - monitor closely"

# Create Gradio interface
with gr.Blocks(theme=gr.themes.Base()) as demo:
    gr.Markdown(
        """
        # 🌱 Agricultural Credit Risk Assessment System
        ## Weather, Vegetation, and Credit Scoring Analysis for Tobacco Farming
        """
    )
    
    with gr.Tab("📊 Location Analysis"):
        # Input Section
        with gr.Row():
            location_input = gr.Textbox(
                label="Enter Location",
                placeholder="e.g., Tabora, Tanzania",
                scale=4
            )
            analyze_button = gr.Button("Analyze", variant="primary", scale=1)

        # Map and Analysis Section
        with gr.Row():
            with gr.Column(scale=2):
                location_map = gr.HTML(label="NDVI Analysis Map")
            with gr.Column(scale=1):
                analysis_text = gr.Textbox(
                    label="Analysis Results",
                    lines=25,
                    show_label=False
                )
        
        # Plots Section
        with gr.Row():
            weather_plot = gr.Plot(label="Weather Analysis")
        
        with gr.Row():
            score_gauge = gr.Plot(label="Growing Conditions Score")
        
        # Location Examples
        gr.Examples(
            examples=[
                ["Tabora, Tanzania"],
                ["Urambo, Tabora, Tanzania"],
                ["Sikonge, Tabora, Tanzania"],
                ["Nzega, Tabora, Tanzania"]
            ],
            inputs=location_input,
            outputs=[location_map, analysis_text, weather_plot, score_gauge],
            fn=analyze_location,
            cache_examples=True
        )
        
        # Handle location analysis
        analyze_button.click(
            fn=analyze_location,
            inputs=[location_input],
            outputs=[location_map, analysis_text, weather_plot, score_gauge]
        )
    
        with gr.Tab("🛰️ Satellite Image Analysis"):
                gr.Markdown("""
                ## Satellite Image Analysis with SAM2
                Upload a satellite or aerial image to analyze vegetation health using advanced segmentation.
                """)
                
                with gr.Row():
                    image_input = gr.Image(
                        label="Upload Satellite/Aerial Image"
                    )
                
                with gr.Row():
                    analyze_image_button = gr.Button("🔍 Analyze Image", variant="primary")
                
                with gr.Row():
                    with gr.Column():
                        image_plot = gr.Plot(label="Vegetation Analysis Results")
                    with gr.Column():
                        image_analysis = gr.Textbox(
                            label="Analysis Results",
                            lines=10,
                            show_label=False
                        )

# Launch the app
if __name__ == "__main__":
    demo.launch()