Update app.py
Browse files
app.py
CHANGED
@@ -38,76 +38,6 @@ from huggingface_hub import InferenceApi, login, InferenceClient
|
|
38 |
import branca.colormap as cm
|
39 |
from functools import lru_cache
|
40 |
import time
|
41 |
-
import math
|
42 |
-
|
43 |
-
# Weather API configuration
|
44 |
-
# WEATHER_API_KEY = os.getenv("OPENWEATHER_API_KEY")
|
45 |
-
# WEATHER_API_KEY = os.getenv("OPENWEATHER_API_KEY")
|
46 |
-
WEATHER_API_KEY = "80abcb4987dcd87229eb4f36d2a2e7e2"
|
47 |
-
|
48 |
-
if not WEATHER_API_KEY:
|
49 |
-
st.warning("Please set OPENWEATHER_API_KEY environment variable to show weather data")
|
50 |
-
WEATHER_API_URL = "https://api.openweathermap.org/data/2.5/weather"
|
51 |
-
|
52 |
-
@st.cache_data(ttl=1800) # Cache for 30 minutes
|
53 |
-
def fetch_weather_data(lat, lon):
|
54 |
-
"""Fetch weather data for a specific location"""
|
55 |
-
if not WEATHER_API_KEY:
|
56 |
-
return None
|
57 |
-
try:
|
58 |
-
params = {
|
59 |
-
'lat': lat,
|
60 |
-
'lon': lon,
|
61 |
-
'appid': WEATHER_API_KEY,
|
62 |
-
'units': 'metric'
|
63 |
-
}
|
64 |
-
response = requests.get(WEATHER_API_URL, params=params, timeout=10)
|
65 |
-
response.raise_for_status()
|
66 |
-
return response.json()
|
67 |
-
except Exception as e:
|
68 |
-
st.warning(f"Could not fetch weather data: {str(e)}")
|
69 |
-
return None
|
70 |
-
|
71 |
-
def create_weather_heatmap(weather_data, map_obj):
|
72 |
-
"""Create a heatmap layer for weather conditions"""
|
73 |
-
if not weather_data:
|
74 |
-
return
|
75 |
-
|
76 |
-
# Extract weather data points
|
77 |
-
heat_data = []
|
78 |
-
for data in weather_data:
|
79 |
-
if data and 'main' in data and 'coord' in data:
|
80 |
-
lat = data['coord']['lat']
|
81 |
-
lon = data['coord']['lon']
|
82 |
-
temp = data['main']['temp']
|
83 |
-
humidity = data['main']['humidity']
|
84 |
-
# Use temperature as the weight for the heatmap
|
85 |
-
heat_data.append([lat, lon, temp])
|
86 |
-
|
87 |
-
if heat_data:
|
88 |
-
# Create heatmap layer
|
89 |
-
plugins.HeatMap(
|
90 |
-
heat_data,
|
91 |
-
min_opacity=0.5,
|
92 |
-
max_val=max([point[2] for point in heat_data]),
|
93 |
-
radius=25,
|
94 |
-
blur=15,
|
95 |
-
gradient={0.4: 'blue', 0.6: 'lime', 0.7: 'yellow', 1: 'red'}
|
96 |
-
).add_to(map_obj)
|
97 |
-
|
98 |
-
def get_weather_grid(lat_min, lat_max, lon_min, lon_max, grid_size=5):
|
99 |
-
"""Create a grid of points for weather data collection"""
|
100 |
-
lat_step = (lat_max - lat_min) / grid_size
|
101 |
-
lon_step = (lon_max - lon_min) / grid_size
|
102 |
-
|
103 |
-
weather_points = []
|
104 |
-
for i in range(grid_size + 1):
|
105 |
-
for j in range(grid_size + 1):
|
106 |
-
lat = lat_min + (i * lat_step)
|
107 |
-
lon = lon_min + (j * lon_step)
|
108 |
-
weather_points.append((lat, lon))
|
109 |
-
|
110 |
-
return weather_points
|
111 |
|
112 |
# Cache the airport data to avoid reloading it every time
|
113 |
@st.cache_data(ttl=3600) # Cache for 1 hour
|
@@ -340,7 +270,7 @@ def query_flight_data(geo_df, question):
|
|
340 |
flight_info[col] = f"{value}° N"
|
341 |
elif col == 'longitude':
|
342 |
flight_info[col] = f"{value}° E"
|
343 |
-
|
344 |
flight_info[col] = str(value)
|
345 |
|
346 |
if not flight_info:
|
@@ -395,7 +325,7 @@ def flight_tracking(flight_view_level, country, local_time_zone, flight_info, ai
|
|
395 |
(airport_country_loc['Latitude'] >= lat_min) &
|
396 |
(airport_country_loc['Latitude'] <= lat_max) &
|
397 |
(airport_country_loc['Longitude'] >= lon_min) &
|
398 |
-
|
399 |
|
400 |
def get_traffic_gdf():
|
401 |
# Get cached flight data
|
@@ -406,34 +336,34 @@ def flight_tracking(flight_view_level, country, local_time_zone, flight_info, ai
|
|
406 |
return None
|
407 |
|
408 |
try:
|
409 |
-
|
410 |
local_timezone = pytz.timezone(local_time_zone)
|
411 |
-
|
412 |
|
413 |
# Optimize DataFrame creation
|
414 |
state_df = pd.DataFrame(json_dict["states"], columns=columns)
|
415 |
state_df['time'] = local_time
|
416 |
|
417 |
# Create GeoDataFrame more efficiently
|
418 |
-
|
419 |
state_df,
|
420 |
geometry=gpd.points_from_xy(state_df.longitude, state_df.latitude),
|
421 |
crs="EPSG:4326"
|
422 |
)
|
423 |
|
424 |
# Display information
|
425 |
-
|
426 |
-
|
427 |
-
|
428 |
-
|
429 |
-
|
430 |
-
|
431 |
-
|
432 |
-
|
433 |
-
|
434 |
-
|
435 |
-
|
436 |
-
|
437 |
except Exception as e:
|
438 |
st.error(f"Error processing flight data: {str(e)}")
|
439 |
return None
|
@@ -450,39 +380,6 @@ def flight_tracking(flight_view_level, country, local_time_zone, flight_info, ai
|
|
450 |
tiles='CartoDB dark_matter'
|
451 |
)
|
452 |
|
453 |
-
# Add weather heatmap if API key is available
|
454 |
-
if WEATHER_API_KEY:
|
455 |
-
with st.spinner('Fetching weather data...'):
|
456 |
-
# Get weather grid points
|
457 |
-
weather_points = get_weather_grid(lat_min, lat_max, lon_min, lon_max)
|
458 |
-
|
459 |
-
# Fetch weather data for all points
|
460 |
-
weather_data = []
|
461 |
-
for lat, lon in weather_points:
|
462 |
-
data = fetch_weather_data(lat, lon)
|
463 |
-
if data:
|
464 |
-
weather_data.append(data)
|
465 |
-
|
466 |
-
# Create weather heatmap
|
467 |
-
create_weather_heatmap(weather_data, m)
|
468 |
-
|
469 |
-
# Add weather legend
|
470 |
-
legend_html = '''
|
471 |
-
<div style="position: fixed;
|
472 |
-
bottom: 50px; right: 50px; width: 150px; height: 100px;
|
473 |
-
background-color: white; padding: 10px; border-radius: 5px;
|
474 |
-
border: 2px solid grey; z-index: 9999;">
|
475 |
-
<h4 style="margin: 0 0 5px 0;">Temperature (°C)</h4>
|
476 |
-
<div style="background: linear-gradient(to right, blue, lime, yellow, red);
|
477 |
-
height: 20px; width: 100%; margin-bottom: 5px;"></div>
|
478 |
-
<div style="display: flex; justify-content: space-between;">
|
479 |
-
<span>Cold</span>
|
480 |
-
<span>Hot</span>
|
481 |
-
</div>
|
482 |
-
</div>
|
483 |
-
'''
|
484 |
-
m.get_root().html.add_child(folium.Element(legend_html))
|
485 |
-
|
486 |
# Create colormap
|
487 |
if color == "rainbow":
|
488 |
colormap = cm.LinearColormap(
|
@@ -644,15 +541,6 @@ with st.sidebar:
|
|
644 |
st.write('Now Airports are Visible')
|
645 |
else:
|
646 |
air_port=0
|
647 |
-
|
648 |
-
# Add weather toggle
|
649 |
-
weather_on = st.toggle('Show Weather Heatmap')
|
650 |
-
if weather_on:
|
651 |
-
if not WEATHER_API_KEY:
|
652 |
-
st.warning("Please set OPENWEATHER_API_KEY environment variable to show weather data")
|
653 |
-
else:
|
654 |
-
st.write(':rainbow[Weather data will be displayed as a heatmap]')
|
655 |
-
|
656 |
view = st.slider('Increase Flight Visibility',1,6,2)
|
657 |
st.write("You Selected:", view)
|
658 |
cou = st.text_input('Type Country Name', 'north america')
|
@@ -673,7 +561,6 @@ with st.sidebar:
|
|
673 |
elif clr == 'hot':
|
674 |
st.write('The current color is', "****:red[Hot]****")
|
675 |
else: None
|
676 |
-
|
677 |
# with st.spinner('Wait!, We Requesting API Data...'):
|
678 |
# try:
|
679 |
flight_tracking(flight_view_level=view, country=cou,flight_info=info,
|
|
|
38 |
import branca.colormap as cm
|
39 |
from functools import lru_cache
|
40 |
import time
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
41 |
|
42 |
# Cache the airport data to avoid reloading it every time
|
43 |
@st.cache_data(ttl=3600) # Cache for 1 hour
|
|
|
270 |
flight_info[col] = f"{value}° N"
|
271 |
elif col == 'longitude':
|
272 |
flight_info[col] = f"{value}° E"
|
273 |
+
else:
|
274 |
flight_info[col] = str(value)
|
275 |
|
276 |
if not flight_info:
|
|
|
325 |
(airport_country_loc['Latitude'] >= lat_min) &
|
326 |
(airport_country_loc['Latitude'] <= lat_max) &
|
327 |
(airport_country_loc['Longitude'] >= lon_min) &
|
328 |
+
(airport_country_loc['Longitude'] <= lon_max)]
|
329 |
|
330 |
def get_traffic_gdf():
|
331 |
# Get cached flight data
|
|
|
336 |
return None
|
337 |
|
338 |
try:
|
339 |
+
unix_timestamp = int(json_dict["time"])
|
340 |
local_timezone = pytz.timezone(local_time_zone)
|
341 |
+
local_time = datetime.fromtimestamp(unix_timestamp, local_timezone).strftime('%Y-%m-%d %H:%M:%S')
|
342 |
|
343 |
# Optimize DataFrame creation
|
344 |
state_df = pd.DataFrame(json_dict["states"], columns=columns)
|
345 |
state_df['time'] = local_time
|
346 |
|
347 |
# Create GeoDataFrame more efficiently
|
348 |
+
gdf = gpd.GeoDataFrame(
|
349 |
state_df,
|
350 |
geometry=gpd.points_from_xy(state_df.longitude, state_df.latitude),
|
351 |
crs="EPSG:4326"
|
352 |
)
|
353 |
|
354 |
# Display information
|
355 |
+
st.title("Live Flight Tracker")
|
356 |
+
st.subheader('Flight Details', divider='rainbow')
|
357 |
+
st.write('Location: {0}'.format(loc))
|
358 |
+
st.write('Current Local Time: {0}-{1}:'.format(local_time, local_time_zone))
|
359 |
+
st.write("Minimum_latitude is {0} and Maximum_latitude is {1}".format(lat_min, lat_max))
|
360 |
+
st.write("Minimum_longitude is {0} and Maximum_longitude is {1}".format(lon_min, lon_max))
|
361 |
+
st.write('Number of Visible Flights: {}'.format(len(json_dict['states'])))
|
362 |
+
st.write('Plotting the flight: {}'.format(flight_info))
|
363 |
+
st.subheader('Map Visualization', divider='rainbow')
|
364 |
+
st.write('****Click ":orange[Update Map]" Button to Refresh the Map****')
|
365 |
+
return gdf
|
366 |
+
|
367 |
except Exception as e:
|
368 |
st.error(f"Error processing flight data: {str(e)}")
|
369 |
return None
|
|
|
380 |
tiles='CartoDB dark_matter'
|
381 |
)
|
382 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
383 |
# Create colormap
|
384 |
if color == "rainbow":
|
385 |
colormap = cm.LinearColormap(
|
|
|
541 |
st.write('Now Airports are Visible')
|
542 |
else:
|
543 |
air_port=0
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
544 |
view = st.slider('Increase Flight Visibility',1,6,2)
|
545 |
st.write("You Selected:", view)
|
546 |
cou = st.text_input('Type Country Name', 'north america')
|
|
|
561 |
elif clr == 'hot':
|
562 |
st.write('The current color is', "****:red[Hot]****")
|
563 |
else: None
|
|
|
564 |
# with st.spinner('Wait!, We Requesting API Data...'):
|
565 |
# try:
|
566 |
flight_tracking(flight_view_level=view, country=cou,flight_info=info,
|