Update app.py
Browse files
app.py
CHANGED
@@ -2,9 +2,18 @@ import gradio as gr
|
|
2 |
import numpy as np
|
3 |
from part1_data import TobaccoAnalyzer
|
4 |
from part2_visualization import VisualizationHandler
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
5 |
|
6 |
def analyze_location(location_name):
|
7 |
-
"""
|
8 |
try:
|
9 |
analyzer = TobaccoAnalyzer()
|
10 |
visualizer = VisualizationHandler(analyzer.optimal_conditions)
|
@@ -39,7 +48,7 @@ def analyze_location(location_name):
|
|
39 |
if trends is None:
|
40 |
return None, None, "Error calculating trends.", None
|
41 |
|
42 |
-
# Calculate overall score
|
43 |
weights = {
|
44 |
'temperature': 0.3,
|
45 |
'humidity': 0.2,
|
@@ -59,7 +68,7 @@ def analyze_location(location_name):
|
|
59 |
gauge_plot = visualizer.create_gauge_chart(overall_score)
|
60 |
location_map = visualizer.create_enhanced_map(lat, lon, overall_score, historical['estimated_ndvi'].mean())
|
61 |
|
62 |
-
# Generate
|
63 |
analysis_text = f"""
|
64 |
π Location Analysis:
|
65 |
Location: {location_data['address']}
|
@@ -110,6 +119,21 @@ def analyze_location(location_name):
|
|
110 |
print(f"Error details: {e}")
|
111 |
return None, None, error_message, None
|
112 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
113 |
def get_vegetation_status(ndvi):
|
114 |
"""Get detailed vegetation status based on NDVI value"""
|
115 |
if ndvi < 0:
|
@@ -166,19 +190,14 @@ def get_risk_factors(df, trends):
|
|
166 |
"""Analyze and return risk factors"""
|
167 |
risks = []
|
168 |
|
169 |
-
# Temperature risks
|
170 |
if df['temp_range'].mean() > 15:
|
171 |
risks.append("β’ High daily temperature variations")
|
172 |
if trends['historical']['temperature']['trend'] < 0:
|
173 |
risks.append("β’ Declining temperature trend")
|
174 |
-
|
175 |
-
# Rainfall risks
|
176 |
if df['rainfall'].std() > df['rainfall'].mean():
|
177 |
risks.append("β’ Inconsistent rainfall patterns")
|
178 |
if trends['historical']['rainfall']['trend'] < 0:
|
179 |
risks.append("β’ Decreasing rainfall trend")
|
180 |
-
|
181 |
-
# NDVI risks
|
182 |
if trends['historical']['ndvi']['trend'] < 0:
|
183 |
risks.append("β’ Declining vegetation health")
|
184 |
|
@@ -214,62 +233,96 @@ def get_long_term_outlook(trends):
|
|
214 |
return "Deteriorating conditions"
|
215 |
return "Mixed conditions - monitor closely"
|
216 |
|
217 |
-
# Create Gradio interface
|
218 |
with gr.Blocks(theme=gr.themes.Base()) as demo:
|
219 |
gr.Markdown(
|
220 |
"""
|
221 |
# π± Agricultural Credit Risk Assessment System
|
222 |
-
|
223 |
"""
|
224 |
)
|
225 |
|
226 |
-
|
227 |
-
|
228 |
-
|
229 |
-
|
230 |
-
|
231 |
-
|
232 |
-
|
233 |
-
analyze_button = gr.Button("Analyze", variant="primary", scale=1)
|
234 |
-
|
235 |
-
# Map and Analysis Section
|
236 |
-
with gr.Row():
|
237 |
-
with gr.Column(scale=2): # Larger map
|
238 |
-
location_map = gr.HTML(label="NDVI Analysis Map")
|
239 |
-
with gr.Column(scale=1):
|
240 |
-
analysis_text = gr.Textbox(
|
241 |
-
label="Analysis Results",
|
242 |
-
lines=25,
|
243 |
-
show_label=False
|
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 |
# Launch the app
|
275 |
if __name__ == "__main__":
|
|
|
2 |
import numpy as np
|
3 |
from part1_data import TobaccoAnalyzer
|
4 |
from part2_visualization import VisualizationHandler
|
5 |
+
from part3 import SAMAnalyzer
|
6 |
+
|
7 |
+
if not os.path.exists('sam_vit_h_4b8939.pth'):
|
8 |
+
print("Downloading SAM model...")
|
9 |
+
urllib.request.urlretrieve(
|
10 |
+
'https://dl.fbaipublicfiles.com/segment_anything/sam_vit_h_4b8939.pth',
|
11 |
+
'sam_vit_h_4b8939.pth'
|
12 |
+
)
|
13 |
+
print("SAM model downloaded successfully")
|
14 |
|
15 |
def analyze_location(location_name):
|
16 |
+
"""Analyze location using weather and satellite data"""
|
17 |
try:
|
18 |
analyzer = TobaccoAnalyzer()
|
19 |
visualizer = VisualizationHandler(analyzer.optimal_conditions)
|
|
|
48 |
if trends is None:
|
49 |
return None, None, "Error calculating trends.", None
|
50 |
|
51 |
+
# Calculate overall score
|
52 |
weights = {
|
53 |
'temperature': 0.3,
|
54 |
'humidity': 0.2,
|
|
|
68 |
gauge_plot = visualizer.create_gauge_chart(overall_score)
|
69 |
location_map = visualizer.create_enhanced_map(lat, lon, overall_score, historical['estimated_ndvi'].mean())
|
70 |
|
71 |
+
# Generate analysis text
|
72 |
analysis_text = f"""
|
73 |
π Location Analysis:
|
74 |
Location: {location_data['address']}
|
|
|
119 |
print(f"Error details: {e}")
|
120 |
return None, None, error_message, None
|
121 |
|
122 |
+
def analyze_satellite_image(image):
|
123 |
+
"""Analyze satellite image using SAM2"""
|
124 |
+
try:
|
125 |
+
analyzer = SAMAnalyzer()
|
126 |
+
veg_index, health_analysis, viz_plot = analyzer.process_image(image)
|
127 |
+
|
128 |
+
if veg_index is None:
|
129 |
+
return None, "Error processing image. Please try again."
|
130 |
+
|
131 |
+
analysis_text = analyzer.format_analysis_text(health_analysis)
|
132 |
+
|
133 |
+
return viz_plot, analysis_text
|
134 |
+
except Exception as e:
|
135 |
+
return None, f"Error analyzing image: {str(e)}"
|
136 |
+
|
137 |
def get_vegetation_status(ndvi):
|
138 |
"""Get detailed vegetation status based on NDVI value"""
|
139 |
if ndvi < 0:
|
|
|
190 |
"""Analyze and return risk factors"""
|
191 |
risks = []
|
192 |
|
|
|
193 |
if df['temp_range'].mean() > 15:
|
194 |
risks.append("β’ High daily temperature variations")
|
195 |
if trends['historical']['temperature']['trend'] < 0:
|
196 |
risks.append("β’ Declining temperature trend")
|
|
|
|
|
197 |
if df['rainfall'].std() > df['rainfall'].mean():
|
198 |
risks.append("β’ Inconsistent rainfall patterns")
|
199 |
if trends['historical']['rainfall']['trend'] < 0:
|
200 |
risks.append("β’ Decreasing rainfall trend")
|
|
|
|
|
201 |
if trends['historical']['ndvi']['trend'] < 0:
|
202 |
risks.append("β’ Declining vegetation health")
|
203 |
|
|
|
233 |
return "Deteriorating conditions"
|
234 |
return "Mixed conditions - monitor closely"
|
235 |
|
236 |
+
# Create Gradio interface
|
237 |
with gr.Blocks(theme=gr.themes.Base()) as demo:
|
238 |
gr.Markdown(
|
239 |
"""
|
240 |
# π± Agricultural Credit Risk Assessment System
|
241 |
+
## Weather, Vegetation, and Credit Scoring Analysis for Tobacco Farming
|
242 |
"""
|
243 |
)
|
244 |
|
245 |
+
with gr.Tab("π Location Analysis"):
|
246 |
+
# Input Section
|
247 |
+
with gr.Row():
|
248 |
+
location_input = gr.Textbox(
|
249 |
+
label="Enter Location",
|
250 |
+
placeholder="e.g., Tabora, Tanzania",
|
251 |
+
scale=4
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
252 |
)
|
253 |
+
analyze_button = gr.Button("Analyze", variant="primary", scale=1)
|
254 |
+
|
255 |
+
# Map and Analysis Section
|
256 |
+
with gr.Row():
|
257 |
+
with gr.Column(scale=2):
|
258 |
+
location_map = gr.HTML(label="NDVI Analysis Map")
|
259 |
+
with gr.Column(scale=1):
|
260 |
+
analysis_text = gr.Textbox(
|
261 |
+
label="Analysis Results",
|
262 |
+
lines=25,
|
263 |
+
show_label=False
|
264 |
+
)
|
265 |
+
|
266 |
+
# Plots Section
|
267 |
+
with gr.Row():
|
268 |
+
weather_plot = gr.Plot(label="Weather Analysis")
|
269 |
+
|
270 |
+
with gr.Row():
|
271 |
+
score_gauge = gr.Plot(label="Growing Conditions Score")
|
272 |
+
|
273 |
+
# Location Examples
|
274 |
+
gr.Examples(
|
275 |
+
examples=[
|
276 |
+
["Tabora, Tanzania"],
|
277 |
+
["Urambo, Tabora, Tanzania"],
|
278 |
+
["Sikonge, Tabora, Tanzania"],
|
279 |
+
["Nzega, Tabora, Tanzania"]
|
280 |
+
],
|
281 |
+
inputs=location_input,
|
282 |
+
outputs=[location_map, analysis_text, weather_plot, score_gauge],
|
283 |
+
fn=analyze_location,
|
284 |
+
cache_examples=True
|
285 |
+
)
|
286 |
+
|
287 |
+
# Handle location analysis
|
288 |
+
analyze_button.click(
|
289 |
+
fn=analyze_location,
|
290 |
+
inputs=[location_input],
|
291 |
+
outputs=[location_map, analysis_text, weather_plot, score_gauge]
|
292 |
+
)
|
293 |
|
294 |
+
with gr.Tab("π°οΈ Satellite Image Analysis"):
|
295 |
+
gr.Markdown("""
|
296 |
+
## Satellite Image Analysis with SAM2
|
297 |
+
Upload a satellite or aerial image to analyze vegetation health using advanced segmentation.
|
298 |
+
""")
|
299 |
+
|
300 |
+
with gr.Row():
|
301 |
+
image_input = gr.Image(
|
302 |
+
label="Upload Satellite/Aerial Image",
|
303 |
+
type="file",
|
304 |
+
tool="select"
|
305 |
+
)
|
306 |
+
|
307 |
+
with gr.Row():
|
308 |
+
analyze_image_button = gr.Button("π Analyze Image", variant="primary")
|
309 |
+
|
310 |
+
with gr.Row():
|
311 |
+
with gr.Column():
|
312 |
+
image_plot = gr.Plot(label="Vegetation Analysis Results")
|
313 |
+
with gr.Column():
|
314 |
+
image_analysis = gr.Textbox(
|
315 |
+
label="Analysis Results",
|
316 |
+
lines=10,
|
317 |
+
show_label=False
|
318 |
+
)
|
319 |
+
|
320 |
+
# Handle image analysis
|
321 |
+
analyze_image_button.click(
|
322 |
+
fn=analyze_satellite_image,
|
323 |
+
inputs=[image_input],
|
324 |
+
outputs=[image_plot, image_analysis]
|
325 |
+
)
|
326 |
|
327 |
# Launch the app
|
328 |
if __name__ == "__main__":
|