Update app.py
Browse files
app.py
CHANGED
@@ -1,135 +1,197 @@
|
|
1 |
-
#
|
|
|
|
|
|
|
|
|
|
|
2 |
from folium import plugins
|
3 |
-
import
|
|
|
|
|
|
|
|
|
|
|
|
|
4 |
|
5 |
-
|
6 |
-
def
|
7 |
-
|
8 |
-
|
9 |
-
|
10 |
-
|
11 |
-
|
12 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
13 |
|
14 |
-
|
15 |
-
|
16 |
-
|
17 |
-
|
18 |
-
|
19 |
-
|
20 |
-
|
21 |
-
|
22 |
-
|
23 |
-
|
24 |
-
|
25 |
-
|
26 |
-
|
27 |
-
fillOpacity=0.4
|
28 |
-
).add_to(m)
|
29 |
-
|
30 |
-
# Add terrain analysis circles
|
31 |
-
for radius in [1000, 1500]:
|
32 |
-
folium.Circle(
|
33 |
-
radius=radius,
|
34 |
-
location=[lat, lon],
|
35 |
-
color=color,
|
36 |
-
fill=False,
|
37 |
-
weight=1
|
38 |
-
).add_to(m)
|
39 |
-
|
40 |
-
# Add custom legend
|
41 |
-
legend_html = """
|
42 |
-
<div style="position: fixed; bottom: 50px; left: 50px; z-index: 1000; background-color: white;
|
43 |
-
padding: 10px; border-radius: 5px; border: 2px solid grey;">
|
44 |
-
<h4>Suitability Score</h4>
|
45 |
-
<div><i style="background: green"></i> High (>0.8)</div>
|
46 |
-
<div><i style="background: yellow"></i> Good (>0.6)</div>
|
47 |
-
<div><i style="background: orange"></i> Moderate (>0.4)</div>
|
48 |
-
<div><i style="background: red"></i> Low (<0.4)</div>
|
49 |
-
</div>
|
50 |
-
"""
|
51 |
-
m.get_root().html.add_child(folium.Element(legend_html))
|
52 |
-
|
53 |
-
# Add measurement tool
|
54 |
-
plugins.MeasureControl(position='topright').add_to(m)
|
55 |
-
|
56 |
-
# Add fullscreen option
|
57 |
-
plugins.Fullscreen().add_to(m)
|
58 |
-
|
59 |
-
# Add mini map
|
60 |
-
minimap = plugins.MiniMap()
|
61 |
-
m.add_child(minimap)
|
62 |
-
|
63 |
-
return m._repr_html_()
|
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 |
-
with gr.Column(scale=1):
|
100 |
-
location_map = gr.HTML(label="Location Analysis")
|
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 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# app.py
|
2 |
+
|
3 |
+
import gradio as gr
|
4 |
+
import numpy as np
|
5 |
+
from datetime import datetime, timedelta
|
6 |
+
import folium
|
7 |
from folium import plugins
|
8 |
+
import requests
|
9 |
+
from geopy.geocoders import Nominatim
|
10 |
+
from geopy.exc import GeocoderTimedOut
|
11 |
+
import pandas as pd
|
12 |
+
from scipy import stats
|
13 |
+
import plotly.graph_objects as go
|
14 |
+
from plotly.subplots import make_subplots
|
15 |
|
16 |
+
class TobaccoAnalyzer:
|
17 |
+
def __init__(self):
|
18 |
+
self.api_key = 'your_api_key' # Your existing API key setup
|
19 |
+
self.optimal_conditions = {
|
20 |
+
'temperature': {'min': 20, 'max': 30},
|
21 |
+
'humidity': {'min': 60, 'max': 80},
|
22 |
+
'rainfall': {'min': 500/365, 'max': 1200/365}
|
23 |
+
}
|
24 |
+
self.geolocator = Nominatim(user_agent="tobacco_analyzer")
|
25 |
+
self.seasons = {
|
26 |
+
1: 'Winter', 2: 'Winter', 3: 'Spring',
|
27 |
+
4: 'Spring', 5: 'Spring', 6: 'Summer',
|
28 |
+
7: 'Summer', 8: 'Summer', 9: 'Fall',
|
29 |
+
10: 'Fall', 11: 'Fall', 12: 'Winter'
|
30 |
+
}
|
31 |
|
32 |
+
def geocode_location(self, location_name):
|
33 |
+
"""Convert location name to coordinates"""
|
34 |
+
try:
|
35 |
+
location = self.geolocator.geocode(location_name)
|
36 |
+
if location:
|
37 |
+
return {
|
38 |
+
'lat': location.latitude,
|
39 |
+
'lon': location.longitude,
|
40 |
+
'address': location.address
|
41 |
+
}
|
42 |
+
return None
|
43 |
+
except GeocoderTimedOut:
|
44 |
+
return None
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
45 |
|
46 |
+
def get_weather_data(self, lat, lon, historical_days=90, forecast_days=90):
|
47 |
+
"""Get historical and forecast weather data"""
|
48 |
+
historical_data = []
|
49 |
+
|
50 |
+
# Get historical data
|
51 |
+
for day in range(historical_days):
|
52 |
+
date = datetime.now() - timedelta(days=day)
|
53 |
+
url = f"https://api.openweathermap.org/data/2.5/weather?lat={lat}&lon={lon}&appid={self.api_key}&units=metric&dt={int(date.timestamp())}"
|
54 |
+
try:
|
55 |
+
response = requests.get(url)
|
56 |
+
if response.status_code == 200:
|
57 |
+
data = response.json()
|
58 |
+
weather_data = {
|
59 |
+
'date': date,
|
60 |
+
'temperature': data['main']['temp'],
|
61 |
+
'humidity': data['main']['humidity'],
|
62 |
+
'rainfall': data.get('rain', {}).get('1h', 0) * 24,
|
63 |
+
'type': 'historical',
|
64 |
+
'description': data['weather'][0]['description']
|
65 |
+
}
|
66 |
+
historical_data.append(weather_data)
|
67 |
+
except Exception as e:
|
68 |
+
print(f"Error fetching historical data: {e}")
|
69 |
|
70 |
+
# Get forecast data
|
71 |
+
forecast_data = []
|
72 |
+
try:
|
73 |
+
forecast_url = f"https://api.openweathermap.org/data/2.5/forecast?lat={lat}&lon={lon}&appid={self.api_key}&units=metric"
|
74 |
+
response = requests.get(forecast_url)
|
75 |
+
if response.status_code == 200:
|
76 |
+
data = response.json()
|
77 |
+
for item in data['list']:
|
78 |
+
forecast = {
|
79 |
+
'date': datetime.fromtimestamp(item['dt']),
|
80 |
+
'temperature': item['main']['temp'],
|
81 |
+
'humidity': item['main']['humidity'],
|
82 |
+
'rainfall': item.get('rain', {}).get('3h', 0) * 8,
|
83 |
+
'type': 'forecast_5day',
|
84 |
+
'description': item['weather'][0]['description']
|
85 |
+
}
|
86 |
+
forecast_data.append(forecast)
|
87 |
+
|
88 |
+
# Generate extended forecast
|
89 |
+
last_date = max(d['date'] for d in forecast_data)
|
90 |
+
historical_df = pd.DataFrame(historical_data)
|
91 |
+
|
92 |
+
if not historical_df.empty:
|
93 |
+
for day in range(1, forecast_days - 5):
|
94 |
+
date = last_date + timedelta(days=day)
|
95 |
+
temp_trend = stats.linregress(range(len(historical_df)), historical_df['temperature'])[0]
|
96 |
+
humidity_trend = stats.linregress(range(len(historical_df)), historical_df['humidity'])[0]
|
97 |
+
rainfall_trend = stats.linregress(range(len(historical_df)), historical_df['rainfall'])[0]
|
98 |
+
|
99 |
+
recent_temps = [d['temperature'] for d in forecast_data[-5:]]
|
100 |
+
recent_humidity = [d['humidity'] for d in forecast_data[-5:]]
|
101 |
+
recent_rainfall = [d['rainfall'] for d in forecast_data[-5:]]
|
102 |
+
|
103 |
+
extended_forecast = {
|
104 |
+
'date': date,
|
105 |
+
'temperature': np.mean(recent_temps) + temp_trend * day,
|
106 |
+
'humidity': np.mean(recent_humidity) + humidity_trend * day,
|
107 |
+
'rainfall': np.mean(recent_rainfall) + rainfall_trend * day,
|
108 |
+
'type': 'forecast_extended',
|
109 |
+
'description': 'Extended Forecast'
|
110 |
+
}
|
111 |
+
forecast_data.append(extended_forecast)
|
112 |
+
|
113 |
+
except Exception as e:
|
114 |
+
print(f"Error fetching forecast data: {e}")
|
115 |
+
|
116 |
+
if not historical_data and not forecast_data:
|
117 |
+
return None
|
118 |
+
|
119 |
+
# Combine and process data
|
120 |
+
all_data = pd.DataFrame(historical_data + forecast_data)
|
121 |
+
if not all_data.empty:
|
122 |
+
all_data = all_data.sort_values('date')
|
123 |
+
all_data['month'] = all_data['date'].dt.month
|
124 |
+
all_data['season'] = all_data['month'].map(self.seasons)
|
125 |
|
126 |
+
all_data['temp_7day_avg'] = all_data['temperature'].rolling(window=7, min_periods=1).mean()
|
127 |
+
all_data['humidity_7day_avg'] = all_data['humidity'].rolling(window=7, min_periods=1).mean()
|
128 |
+
all_data['rainfall_7day_avg'] = all_data['rainfall'].rolling(window=7, min_periods=1).mean()
|
|
|
|
|
129 |
|
130 |
+
return all_data
|
131 |
+
|
132 |
+
def analyze_trends(self, df):
|
133 |
+
"""Analyze weather trends and patterns"""
|
134 |
+
try:
|
135 |
+
historical = df[df['type'] == 'historical']
|
136 |
+
forecast = df[df['type'].isin(['forecast_5day', 'forecast_extended'])]
|
137 |
+
|
138 |
+
if historical.empty:
|
139 |
+
return None
|
140 |
+
|
141 |
+
analysis = {
|
142 |
+
'historical': {
|
143 |
+
'temperature': {
|
144 |
+
'mean': historical['temperature'].mean(),
|
145 |
+
'std': historical['temperature'].std(),
|
146 |
+
'trend': stats.linregress(range(len(historical)), historical['temperature'])[0]
|
147 |
+
},
|
148 |
+
'humidity': {
|
149 |
+
'mean': historical['humidity'].mean(),
|
150 |
+
'std': historical['humidity'].std(),
|
151 |
+
'trend': stats.linregress(range(len(historical)), historical['humidity'])[0]
|
152 |
+
},
|
153 |
+
'rainfall': {
|
154 |
+
'mean': historical['rainfall'].mean(),
|
155 |
+
'std': historical['rainfall'].std(),
|
156 |
+
'trend': stats.linregress(range(len(historical)), historical['rainfall'])[0]
|
157 |
+
}
|
158 |
+
}
|
159 |
+
}
|
160 |
|
161 |
+
if not forecast.empty:
|
162 |
+
analysis['forecast'] = {
|
163 |
+
'temperature': {
|
164 |
+
'mean': forecast['temperature'].mean(),
|
165 |
+
'std': forecast['temperature'].std(),
|
166 |
+
},
|
167 |
+
'humidity': {
|
168 |
+
'mean': forecast['humidity'].mean(),
|
169 |
+
'std': forecast['humidity'].std(),
|
170 |
+
},
|
171 |
+
'rainfall': {
|
172 |
+
'mean': forecast['rainfall'].mean(),
|
173 |
+
'std': forecast['rainfall'].std(),
|
174 |
+
}
|
175 |
+
}
|
176 |
+
|
177 |
+
return analysis
|
178 |
+
except Exception as e:
|
179 |
+
print(f"Error in trend analysis: {e}")
|
180 |
+
return None
|
181 |
+
|
182 |
+
class VisualizationHandler:
|
183 |
+
def __init__(self, optimal_conditions):
|
184 |
+
self.optimal_conditions = optimal_conditions
|
185 |
+
|
186 |
+
def create_interactive_plots(self, df):
|
187 |
+
"""Create enhanced interactive Plotly visualizations"""
|
188 |
+
fig = make_subplots(
|
189 |
+
rows=3, cols=1,
|
190 |
+
subplot_titles=(
|
191 |
+
'<b>Temperature (°C)</b>',
|
192 |
+
'<b>Humidity (%)</b>',
|
193 |
+
'<b>Rainfall (mm/day)</b>'
|
194 |
+
),
|
195 |
+
vertical_spacing=0.12,
|
196 |
+
row_heights=[0.33, 0.33, 0.33]
|
197 |
+
)
|