ashok2216 commited on
Commit
47b8f4b
·
verified ·
1 Parent(s): 76220b0

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +653 -105
app.py CHANGED
@@ -1,3 +1,292 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
  '''Copyright 2024 Ashok Kumar
2
 
3
  Licensed under the Apache License, Version 2.0 (the "License");
@@ -29,11 +318,70 @@ from geopy.exc import GeocoderTimedOut
29
  from geopy.geocoders import Nominatim
30
  import warnings
31
  warnings.filterwarnings('ignore')
32
- from plotly.graph_objs import Marker
33
- import plotly.express as px
34
  import streamlit as st
 
35
  from data import flight_data
36
  from huggingface_hub import InferenceApi, login, InferenceClient
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
37
 
38
 
39
  hf_token = os.getenv("HF_TOKEN")
@@ -41,62 +389,123 @@ if hf_token is None:
41
  raise ValueError("Hugging Face token not found. Please set the HF_TOKEN environment variable.")
42
  login(hf_token)
43
 
44
-
45
- API_URL = "https://api-inference.huggingface.co/models/google/tapas-base-finetuned-wtq"
46
  headers = {"Authorization": f"Bearer {hf_token}"}
47
 
48
- def query(payload):
49
- response = requests.post(API_URL, headers=headers, json=payload)
50
- return response.json()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
51
 
52
  def query_flight_data(geo_df, question):
53
-
54
-
55
- table_data = {
56
- "icao24": geo_df["icao24"].astype(str).iloc[:100].tolist(),
57
- "callsign": geo_df["callsign"].astype(str).replace({np.nan: None, np.inf: '0'}).iloc[:100].tolist(),
58
- "origin_country": geo_df["origin_country"].astype(str).replace({np.nan: None, np.inf: '0'}).iloc[:100].tolist(),
59
- "time_position": geo_df["time_position"].astype(str).replace({np.nan: '0', np.inf: '0'}).iloc[:100].tolist(),
60
- "last_contact": geo_df["last_contact"].astype(str).replace({np.nan: '0', np.inf: '0'}).iloc[:100].tolist(),
61
- "longitude": geo_df["longitude"].astype(str).replace({np.nan: '0', np.inf: '0'}).iloc[:100].tolist(),
62
- "latitude": geo_df["latitude"].astype(str).replace({np.nan: '0', np.inf: '0'}).iloc[:100].tolist(),
63
- "baro_altitude": geo_df["baro_altitude"].astype(str).replace({np.nan: '0', np.inf: '0'}).iloc[:100].tolist(),
64
- "on_ground": geo_df["on_ground"].astype(str).iloc[:100].tolist(), # Assuming on_ground is boolean or categorical
65
- "velocity": geo_df["velocity"].astype(str).replace({np.nan: '0', np.inf: '0'}).iloc[:100].tolist(),
66
- "true_track": geo_df["true_track"].astype(str).replace({np.nan: '0', np.inf: '0'}).iloc[:100].tolist(),
67
- "vertical_rate": geo_df["vertical_rate"].astype(str).replace({np.nan: '0', np.inf: '0'}).iloc[:100].tolist(),
68
- "sensors": geo_df["sensors"].astype(str).replace({np.nan: None, np.inf: '0'}).iloc[:100].tolist(), # Assuming sensors can be None
69
- "geo_altitude": geo_df["geo_altitude"].astype(str).replace({np.nan: '0', np.inf: '0'}).iloc[:100].tolist(),
70
- "squawk": geo_df["squawk"].astype(str).replace({np.nan: None, np.inf: '0'}).iloc[:100].tolist(), # Assuming squawk can be None
71
- "spi": geo_df["spi"].astype(str).iloc[:100].tolist(), # Assuming spi is boolean or categorical
72
- "position_source": geo_df["position_source"].astype(str).iloc[:100].tolist(), # Assuming position_source is categorical
73
- "time": geo_df["time"].astype(str).replace({np.nan: '0', np.inf: '0'}).iloc[:100].tolist(),
74
- "geometry": geo_df["geometry"].astype(str).replace({np.nan: None, np.inf: '0'}).iloc[:100].tolist() # Assuming geometry can be None
75
  }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
76
 
 
77
 
78
- # Construct the payload
79
- payload = {
80
- "inputs": {
81
- "query": question,
82
- "table": table_data,
83
- }
84
- }
85
 
86
- # Get the model response
87
- response = query(payload)
88
 
89
- # Check if 'answer' is in response and return it as a sentence
90
- if 'answer' in response:
91
- answer = response['answer']
92
- return f"The answer to your question '{question}': :orange[{answer}]"
 
93
  else:
94
- return "The model could not find an answer to your question."
95
-
 
 
 
96
 
97
  def flight_tracking(flight_view_level, country, local_time_zone, flight_info, airport, color):
98
- geolocator = Nominatim(user_agent="flight_tracker")
99
- loc = geolocator.geocode(country)
 
 
 
 
100
  loc_box = loc[1]
101
  extend_left =+12*flight_view_level
102
  extend_right =+10*flight_view_level
@@ -105,76 +514,215 @@ def flight_tracking(flight_view_level, country, local_time_zone, flight_info, ai
105
  lat_min, lat_max = (loc_box[0] - extend_left), loc_box[0]+extend_right
106
  lon_min, lon_max = (loc_box[1] - extend_bottom), loc_box[1]+extend_top
107
 
108
- tile_zoom = 8 # zoom of the map loaded by contextily
109
- figsize = (15, 15)
110
  columns = ["icao24","callsign","origin_country","time_position","last_contact","longitude","latitude",
111
  "baro_altitude","on_ground","velocity","true_track","vertical_rate","sensors","geo_altitude",
112
  "squawk","spi","position_source",]
113
- data_url = "https://raw.githubusercontent.com/ashok2216-A/ashok_airport-data/main/data/airports.dat"
114
- column_names = ["Airport ID", "Name", "City", "Country", "IATA/FAA", "ICAO", "Latitude", "Longitude",
115
- "Altitude", "Timezone", "DST", "Tz database time zone", "Type", "Source"]
116
- airport_df = pd.read_csv(data_url, header=None, names=column_names)
117
  airport_locations = airport_df[["Name", "City", "Country", "IATA/FAA", "Latitude", "Longitude"]]
118
  airport_country_loc = airport_locations[airport_locations['Country'] == str(loc)]
119
- airport_country_loc = airport_country_loc[(airport_country_loc['Country'] == str(loc)) & (airport_country_loc['Latitude'] >= lat_min) &
120
- (airport_country_loc['Latitude'] <= lat_max) & (airport_country_loc['Longitude'] >= lon_min) &
121
- (airport_country_loc['Longitude'] <= lon_max)]
 
 
 
122
  def get_traffic_gdf():
123
- url_data = (
124
- f"https://@opensky-network.org/api/states/all?"
125
- f"lamin={str(lat_min)}"
126
- f"&lomin={str(lon_min)}"
127
- f"&lamax={str(lat_max)}"
128
- f"&lomax={str(lon_max)}")
129
- json_dict = requests.get(url_data).json()
130
-
131
- unix_timestamp = int(json_dict["time"])
132
- local_timezone = pytz.timezone(local_time_zone) # get pytz timezone
133
- local_time = datetime.fromtimestamp(unix_timestamp, local_timezone).strftime('%Y-%m-%d %H:%M:%S')
134
- time = []
135
- for i in range(len(json_dict['states'])):
136
- time.append(local_time)
137
- df_time = pd.DataFrame(time,columns=['time'])
138
- state_df = pd.DataFrame(json_dict["states"],columns=columns)
139
- state_df['time'] = df_time
140
- gdf = gpd.GeoDataFrame(
141
  state_df,
142
  geometry=gpd.points_from_xy(state_df.longitude, state_df.latitude),
143
- crs={"init": "epsg:4326"}, # WGS84
144
  )
145
- # banner_image = Image.open('banner.png')
146
- # st.image(banner_image, width=300)
147
- st.title("Live Flight Tracker")
148
- st.subheader('Flight Details', divider='rainbow')
149
- st.write('Location: {0}'.format(loc))
150
- st.write('Current Local Time: {0}-{1}:'.format(local_time, local_time_zone))
151
- st.write("Minimum_latitude is {0} and Maximum_latitude is {1}".format(lat_min, lat_max))
152
- st.write("Minimum_longitude is {0} and Maximum_longitude is {1}".format(lon_min, lon_max))
153
- st.write('Number of Visible Flights: {}'.format(len(json_dict['states'])))
154
- st.write('Plotting the flight: {}'.format(flight_info))
155
- st.subheader('Map Visualization', divider='rainbow')
156
- st.write('****Click ":orange[Update Map]" Button to Refresh the Map****')
157
- return gdf
 
 
 
 
158
 
 
159
  geo_df = get_traffic_gdf()
160
- if airport == 0:
161
- fig = px.scatter_mapbox(geo_df, lat="latitude", lon="longitude",color=flight_info,
162
- color_continuous_scale=color, zoom=4,width=1200, height=600,opacity=1,
163
- hover_name ='origin_country',hover_data=['callsign', 'baro_altitude',
164
- 'on_ground', 'velocity', 'true_track', 'vertical_rate', 'geo_altitude'], template='plotly_dark')
165
- elif airport == 1:
166
- fig = px.scatter_mapbox(geo_df, lat="latitude", lon="longitude",color=flight_info,
167
- color_continuous_scale=color, zoom=4,width=1200, height=600,opacity=1,
168
- hover_name ='origin_country',hover_data=['callsign', 'baro_altitude',
169
- 'on_ground', 'velocity', 'true_track', 'vertical_rate', 'geo_altitude'], template='plotly_dark')
170
- fig.add_trace(px.scatter_mapbox(airport_country_loc, lat="Latitude", lon="Longitude",
171
- hover_name ='Name', hover_data=["City", "Country", "IATA/FAA"]).data[0])
172
- else: None
173
- fig.update_layout(mapbox_style="carto-darkmatter")
174
- fig.update_layout(margin={"r": 0, "t": 0, "l": 0, "b": 0})
175
- # out = fig.show())
176
- out = st.plotly_chart(fig, theme=None)
177
- return out
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
178
  st.set_page_config(
179
  layout="wide"
180
  )
 
1
+ # '''Copyright 2024 Ashok Kumar
2
+
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.'''
14
+
15
+ # import os
16
+ # import requests
17
+ # import json
18
+ # import pandas as pd
19
+ # import numpy as np
20
+ # import requests
21
+ # import geopandas as gpd
22
+ # import contextily as ctx
23
+ # import tzlocal
24
+ # import pytz
25
+ # from PIL import Image
26
+ # from datetime import datetime
27
+ # import matplotlib.pyplot as plt
28
+ # from geopy.exc import GeocoderTimedOut
29
+ # from geopy.geocoders import Nominatim
30
+ # import warnings
31
+ # warnings.filterwarnings('ignore')
32
+ # from plotly.graph_objs import Marker
33
+ # import plotly.express as px
34
+ # import streamlit as st
35
+ # from data import flight_data
36
+ # from huggingface_hub import InferenceApi, login, InferenceClient
37
+
38
+
39
+ # hf_token = os.getenv("HF_TOKEN")
40
+ # if hf_token is None:
41
+ # raise ValueError("Hugging Face token not found. Please set the HF_TOKEN environment variable.")
42
+ # login(hf_token)
43
+
44
+
45
+ # API_URL = "https://api-inference.huggingface.co/models/google/tapas-base-finetuned-wtq"
46
+ # headers = {"Authorization": f"Bearer {hf_token}"}
47
+
48
+ # def query(payload):
49
+ # response = requests.post(API_URL, headers=headers, json=payload)
50
+ # return response.json()
51
+
52
+ # def query_flight_data(geo_df, question):
53
+
54
+
55
+ # table_data = {
56
+ # "icao24": geo_df["icao24"].astype(str).iloc[:100].tolist(),
57
+ # "callsign": geo_df["callsign"].astype(str).replace({np.nan: None, np.inf: '0'}).iloc[:100].tolist(),
58
+ # "origin_country": geo_df["origin_country"].astype(str).replace({np.nan: None, np.inf: '0'}).iloc[:100].tolist(),
59
+ # "time_position": geo_df["time_position"].astype(str).replace({np.nan: '0', np.inf: '0'}).iloc[:100].tolist(),
60
+ # "last_contact": geo_df["last_contact"].astype(str).replace({np.nan: '0', np.inf: '0'}).iloc[:100].tolist(),
61
+ # "longitude": geo_df["longitude"].astype(str).replace({np.nan: '0', np.inf: '0'}).iloc[:100].tolist(),
62
+ # "latitude": geo_df["latitude"].astype(str).replace({np.nan: '0', np.inf: '0'}).iloc[:100].tolist(),
63
+ # "baro_altitude": geo_df["baro_altitude"].astype(str).replace({np.nan: '0', np.inf: '0'}).iloc[:100].tolist(),
64
+ # "on_ground": geo_df["on_ground"].astype(str).iloc[:100].tolist(), # Assuming on_ground is boolean or categorical
65
+ # "velocity": geo_df["velocity"].astype(str).replace({np.nan: '0', np.inf: '0'}).iloc[:100].tolist(),
66
+ # "true_track": geo_df["true_track"].astype(str).replace({np.nan: '0', np.inf: '0'}).iloc[:100].tolist(),
67
+ # "vertical_rate": geo_df["vertical_rate"].astype(str).replace({np.nan: '0', np.inf: '0'}).iloc[:100].tolist(),
68
+ # "sensors": geo_df["sensors"].astype(str).replace({np.nan: None, np.inf: '0'}).iloc[:100].tolist(), # Assuming sensors can be None
69
+ # "geo_altitude": geo_df["geo_altitude"].astype(str).replace({np.nan: '0', np.inf: '0'}).iloc[:100].tolist(),
70
+ # "squawk": geo_df["squawk"].astype(str).replace({np.nan: None, np.inf: '0'}).iloc[:100].tolist(), # Assuming squawk can be None
71
+ # "spi": geo_df["spi"].astype(str).iloc[:100].tolist(), # Assuming spi is boolean or categorical
72
+ # "position_source": geo_df["position_source"].astype(str).iloc[:100].tolist(), # Assuming position_source is categorical
73
+ # "time": geo_df["time"].astype(str).replace({np.nan: '0', np.inf: '0'}).iloc[:100].tolist(),
74
+ # "geometry": geo_df["geometry"].astype(str).replace({np.nan: None, np.inf: '0'}).iloc[:100].tolist() # Assuming geometry can be None
75
+ # }
76
+
77
+
78
+ # # Construct the payload
79
+ # payload = {
80
+ # "inputs": {
81
+ # "query": question,
82
+ # "table": table_data,
83
+ # }
84
+ # }
85
+
86
+ # # Get the model response
87
+ # response = query(payload)
88
+
89
+ # # Check if 'answer' is in response and return it as a sentence
90
+ # if 'answer' in response:
91
+ # answer = response['answer']
92
+ # return f"The answer to your question '{question}': :orange[{answer}]"
93
+ # else:
94
+ # return "The model could not find an answer to your question."
95
+
96
+
97
+ # def flight_tracking(flight_view_level, country, local_time_zone, flight_info, airport, color):
98
+ # geolocator = Nominatim(user_agent="flight_tracker")
99
+ # loc = geolocator.geocode(country)
100
+ # loc_box = loc[1]
101
+ # extend_left =+12*flight_view_level
102
+ # extend_right =+10*flight_view_level
103
+ # extend_top =+10*flight_view_level
104
+ # extend_bottom =+ 18*flight_view_level
105
+ # lat_min, lat_max = (loc_box[0] - extend_left), loc_box[0]+extend_right
106
+ # lon_min, lon_max = (loc_box[1] - extend_bottom), loc_box[1]+extend_top
107
+
108
+ # tile_zoom = 8 # zoom of the map loaded by contextily
109
+ # figsize = (15, 15)
110
+ # columns = ["icao24","callsign","origin_country","time_position","last_contact","longitude","latitude",
111
+ # "baro_altitude","on_ground","velocity","true_track","vertical_rate","sensors","geo_altitude",
112
+ # "squawk","spi","position_source",]
113
+ # data_url = "https://raw.githubusercontent.com/ashok2216-A/ashok_airport-data/main/data/airports.dat"
114
+ # column_names = ["Airport ID", "Name", "City", "Country", "IATA/FAA", "ICAO", "Latitude", "Longitude",
115
+ # "Altitude", "Timezone", "DST", "Tz database time zone", "Type", "Source"]
116
+ # airport_df = pd.read_csv(data_url, header=None, names=column_names)
117
+ # airport_locations = airport_df[["Name", "City", "Country", "IATA/FAA", "Latitude", "Longitude"]]
118
+ # airport_country_loc = airport_locations[airport_locations['Country'] == str(loc)]
119
+ # airport_country_loc = airport_country_loc[(airport_country_loc['Country'] == str(loc)) & (airport_country_loc['Latitude'] >= lat_min) &
120
+ # (airport_country_loc['Latitude'] <= lat_max) & (airport_country_loc['Longitude'] >= lon_min) &
121
+ # (airport_country_loc['Longitude'] <= lon_max)]
122
+ # def get_traffic_gdf():
123
+ # url_data = (
124
+ # f"https://@opensky-network.org/api/states/all?"
125
+ # f"lamin={str(lat_min)}"
126
+ # f"&lomin={str(lon_min)}"
127
+ # f"&lamax={str(lat_max)}"
128
+ # f"&lomax={str(lon_max)}")
129
+ # json_dict = requests.get(url_data).json()
130
+
131
+ # unix_timestamp = int(json_dict["time"])
132
+ # local_timezone = pytz.timezone(local_time_zone) # get pytz timezone
133
+ # local_time = datetime.fromtimestamp(unix_timestamp, local_timezone).strftime('%Y-%m-%d %H:%M:%S')
134
+ # time = []
135
+ # for i in range(len(json_dict['states'])):
136
+ # time.append(local_time)
137
+ # df_time = pd.DataFrame(time,columns=['time'])
138
+ # state_df = pd.DataFrame(json_dict["states"],columns=columns)
139
+ # state_df['time'] = df_time
140
+ # gdf = gpd.GeoDataFrame(
141
+ # state_df,
142
+ # geometry=gpd.points_from_xy(state_df.longitude, state_df.latitude),
143
+ # crs={"init": "epsg:4326"}, # WGS84
144
+ # )
145
+ # # banner_image = Image.open('banner.png')
146
+ # # st.image(banner_image, width=300)
147
+ # st.title("Live Flight Tracker")
148
+ # st.subheader('Flight Details', divider='rainbow')
149
+ # st.write('Location: {0}'.format(loc))
150
+ # st.write('Current Local Time: {0}-{1}:'.format(local_time, local_time_zone))
151
+ # st.write("Minimum_latitude is {0} and Maximum_latitude is {1}".format(lat_min, lat_max))
152
+ # st.write("Minimum_longitude is {0} and Maximum_longitude is {1}".format(lon_min, lon_max))
153
+ # st.write('Number of Visible Flights: {}'.format(len(json_dict['states'])))
154
+ # st.write('Plotting the flight: {}'.format(flight_info))
155
+ # st.subheader('Map Visualization', divider='rainbow')
156
+ # st.write('****Click ":orange[Update Map]" Button to Refresh the Map****')
157
+ # return gdf
158
+
159
+ # geo_df = get_traffic_gdf()
160
+ # if airport == 0:
161
+ # fig = px.scatter_mapbox(geo_df, lat="latitude", lon="longitude",color=flight_info,
162
+ # color_continuous_scale=color, zoom=4,width=1200, height=600,opacity=1,
163
+ # hover_name ='origin_country',hover_data=['callsign', 'baro_altitude',
164
+ # 'on_ground', 'velocity', 'true_track', 'vertical_rate', 'geo_altitude'], template='plotly_dark')
165
+ # elif airport == 1:
166
+ # fig = px.scatter_mapbox(geo_df, lat="latitude", lon="longitude",color=flight_info,
167
+ # color_continuous_scale=color, zoom=4,width=1200, height=600,opacity=1,
168
+ # hover_name ='origin_country',hover_data=['callsign', 'baro_altitude',
169
+ # 'on_ground', 'velocity', 'true_track', 'vertical_rate', 'geo_altitude'], template='plotly_dark')
170
+ # fig.add_trace(px.scatter_mapbox(airport_country_loc, lat="Latitude", lon="Longitude",
171
+ # hover_name ='Name', hover_data=["City", "Country", "IATA/FAA"]).data[0])
172
+ # else: None
173
+ # fig.update_layout(mapbox_style="carto-darkmatter")
174
+ # fig.update_layout(margin={"r": 0, "t": 0, "l": 0, "b": 0})
175
+ # # out = fig.show())
176
+ # out = st.plotly_chart(fig, theme=None)
177
+ # return out
178
+ # st.set_page_config(
179
+ # layout="wide"
180
+ # )
181
+ # image = Image.open('logo.png')
182
+ # add_selectbox = st.sidebar.image(
183
+ # image, width=150
184
+ # )
185
+ # add_selectbox = st.sidebar.subheader(
186
+ # "Configure Map",divider='rainbow'
187
+ # )
188
+ # with st.sidebar:
189
+ # Refresh = st.button('Update Map', key=1)
190
+ # on = st.toggle('View Airports')
191
+ # if on:
192
+ # air_port = 1
193
+ # st.write(':rainbow[Nice Work Buddy!]')
194
+ # st.write('Now Airports are Visible')
195
+ # else:
196
+ # air_port=0
197
+ # view = st.slider('Increase Flight Visibility',1,6,2)
198
+ # st.write("You Selected:", view)
199
+ # cou = st.text_input('Type Country Name', 'north america')
200
+ # st.write('The current Country name is', cou)
201
+ # time = st.text_input('Type Time Zone Name (Ex: America/Toronto, Europe/Berlin)', 'Asia/Kolkata')
202
+ # st.write('The current Time Zone is', time)
203
+ # info = st.selectbox(
204
+ # 'Select Flight Information',
205
+ # ('baro_altitude',
206
+ # 'on_ground', 'velocity',
207
+ # 'geo_altitude'))
208
+ # st.write('Plotting the data of Flight:', info)
209
+ # clr = st.radio('Pick A Color for Scatter Plot',["rainbow","ice","hot"])
210
+ # if clr == "rainbow":
211
+ # st.write('The current color is', "****:rainbow[Rainbow]****")
212
+ # elif clr == 'ice':
213
+ # st.write('The current color is', "****:blue[Ice]****")
214
+ # elif clr == 'hot':
215
+ # st.write('The current color is', "****:red[Hot]****")
216
+ # else: None
217
+ # # with st.spinner('Wait!, We Requesting API Data...'):
218
+ # # try:
219
+ # flight_tracking(flight_view_level=view, country=cou,flight_info=info,
220
+ # local_time_zone=time, airport=air_port, color=clr)
221
+ # st.subheader('Ask your Questions!', divider='rainbow')
222
+ # st.write("Google's TAPAS base LLM model 🤖")
223
+ # geo_df = flight_data(flight_view_level = view, country= cou, flight_info=info, local_time_zone=time, airport=1)
224
+ # question = st.text_input('Type your questions here', "What is the squawk code for SWR9XD?")
225
+ # result = query_flight_data(geo_df, question)
226
+ # st.markdown(result)
227
+ # # except TypeError:
228
+ # # st.error(':red[Error: ] Please Re-run this page.', icon="🚨")
229
+ # # st.button('Re-run', type="primary")
230
+ # # st.snow()
231
+
232
+
233
+
234
+ # # import streamlit as st
235
+ # # from huggingface_hub import InferenceClient
236
+ # # import os
237
+
238
+ # # hf_token = os.getenv("HF_TOKEN")
239
+ # # # Set up the Hugging Face Inference Client
240
+ # # client = InferenceClient(
241
+ # # provider="together", # Replace with the correct provider if needed
242
+ # # api_key= hf_token # Replace with your Hugging Face API key
243
+ # # )
244
+
245
+ # # # Streamlit app title
246
+ # # st.title("🤖 Deepseek R1 Chatbot")
247
+ # # st.write("Chat with the Deepseek R1 model powered by Hugging Face Inference API.")
248
+
249
+ # # # Initialize session state to store chat history
250
+ # # if "messages" not in st.session_state:
251
+ # # st.session_state.messages = []
252
+
253
+ # # # Display chat history
254
+ # # for message in st.session_state.messages:
255
+ # # with st.chat_message(message["role"]):
256
+ # # st.markdown(message["content"])
257
+
258
+ # # # User input
259
+ # # if prompt := st.chat_input("What would you like to ask?"):
260
+ # # # Add user message to chat history
261
+ # # st.session_state.messages.append({"role": "user", "content": prompt})
262
+ # # with st.chat_message("user"):
263
+ # # st.markdown(prompt)
264
+
265
+ # # # Generate response from Deepseek R1 model
266
+ # # with st.spinner("Thinking..."):
267
+ # # try:
268
+ # # # Prepare the messages for the model
269
+ # # messages = [{"role": m["role"], "content": m["content"]} for m in st.session_state.messages]
270
+
271
+ # # # Call the Hugging Face Inference API
272
+ # # completion = client.chat.completions.create(
273
+ # # model="deepseek-ai/DeepSeek-R1", # Replace with the correct model name
274
+ # # messages=messages,
275
+ # # max_tokens=500
276
+ # # )
277
+
278
+ # # # Extract the model's response
279
+ # # response = completion.choices[0].message.content
280
+
281
+ # # # Add model's response to chat history
282
+ # # st.session_state.messages.append({"role": "assistant", "content": response})
283
+ # # with st.chat_message("assistant"):
284
+ # # st.markdown(response)
285
+
286
+ # # except Exception as e:
287
+ # # st.error(f"An error occurred: {e}")
288
+
289
+
290
  '''Copyright 2024 Ashok Kumar
291
 
292
  Licensed under the Apache License, Version 2.0 (the "License");
 
318
  from geopy.geocoders import Nominatim
319
  import warnings
320
  warnings.filterwarnings('ignore')
321
+ import folium
322
+ from folium import plugins
323
  import streamlit as st
324
+ import streamlit_folium as st_folium
325
  from data import flight_data
326
  from huggingface_hub import InferenceApi, login, InferenceClient
327
+ import branca.colormap as cm
328
+ from functools import lru_cache
329
+ import time
330
+
331
+ # Cache the airport data to avoid reloading it every time
332
+ @st.cache_data(ttl=3600) # Cache for 1 hour
333
+ def load_airport_data():
334
+ data_url = "https://raw.githubusercontent.com/ashok2216-A/ashok_airport-data/main/data/airports.dat"
335
+ column_names = ["Airport ID", "Name", "City", "Country", "IATA/FAA", "ICAO", "Latitude", "Longitude",
336
+ "Altitude", "Timezone", "DST", "Tz database time zone", "Type", "Source"]
337
+ return pd.read_csv(data_url, header=None, names=column_names)
338
+
339
+ # Cache geocoding results
340
+ @st.cache_data(ttl=3600)
341
+ def get_location(country):
342
+ geolocator = Nominatim(user_agent="flight_tracker")
343
+ return geolocator.geocode(country)
344
+
345
+ # Cache flight data fetching
346
+ @st.cache_data(ttl=60) # Cache for 1 minute
347
+ def fetch_flight_data(lat_min, lat_max, lon_min, lon_max):
348
+ try:
349
+ # OpenSky Network API endpoint
350
+ url = "https://opensky-network.org/api/states/all"
351
+
352
+ # Parameters for the request
353
+ params = {
354
+ 'lamin': lat_min,
355
+ 'lamax': lat_max,
356
+ 'lomin': lon_min,
357
+ 'lomax': lon_max
358
+ }
359
+
360
+ # Make the request with a timeout
361
+ response = requests.get(url, params=params, timeout=10)
362
+
363
+ # Check if the request was successful
364
+ response.raise_for_status()
365
+
366
+ # Parse the JSON response
367
+ data = response.json()
368
+
369
+ # Check if we got valid data
370
+ if not data or 'states' not in data:
371
+ st.warning("No flight data available for the selected area.")
372
+ return {'states': [], 'time': 0}
373
+
374
+ return data
375
+
376
+ except requests.exceptions.RequestException as e:
377
+ st.error(f"Error fetching flight data: {str(e)}")
378
+ return {'states': [], 'time': 0}
379
+ except json.JSONDecodeError as e:
380
+ st.error(f"Error parsing flight data: {str(e)}")
381
+ return {'states': [], 'time': 0}
382
+ except Exception as e:
383
+ st.error(f"Unexpected error: {str(e)}")
384
+ return {'states': [], 'time': 0}
385
 
386
 
387
  hf_token = os.getenv("HF_TOKEN")
 
389
  raise ValueError("Hugging Face token not found. Please set the HF_TOKEN environment variable.")
390
  login(hf_token)
391
 
392
+ # Hugging Face model configuration
393
+ HF_API_URL = "https://api-inference.huggingface.co/models/mistralai/Mistral-7B-Instruct-v0.2"
394
  headers = {"Authorization": f"Bearer {hf_token}"}
395
 
396
+ def query_llm(prompt):
397
+ try:
398
+ payload = {
399
+ "inputs": prompt,
400
+ "parameters": {
401
+ "max_new_tokens": 250,
402
+ "temperature": 0.1,
403
+ "top_p": 0.95,
404
+ "return_full_text": False
405
+ }
406
+ }
407
+
408
+ response = requests.post(HF_API_URL, headers=headers, json=payload)
409
+ response.raise_for_status()
410
+ return response.json()[0]['generated_text']
411
+ except Exception as e:
412
+ st.error(f"Error querying language model: {str(e)}")
413
+ return None
414
 
415
  def query_flight_data(geo_df, question):
416
+ # Preprocess the question to extract key information
417
+ question = question.lower().strip()
418
+
419
+ # Common flight information queries and their corresponding columns
420
+ query_mappings = {
421
+ 'callsign': ['callsign'],
422
+ 'altitude': ['baro_altitude', 'geo_altitude'],
423
+ 'speed': ['velocity'],
424
+ 'direction': ['true_track'],
425
+ 'country': ['origin_country'],
426
+ 'squawk': ['squawk'],
427
+ 'icao': ['icao24'],
428
+ 'vertical': ['vertical_rate'],
429
+ 'ground': ['on_ground'],
430
+ 'position': ['latitude', 'longitude'],
431
+ 'time': ['time_position', 'last_contact']
 
 
 
 
 
 
432
  }
433
+
434
+ # Extract the identifier (usually callsign or icao) from the question
435
+ identifier = None
436
+ if 'for' in question:
437
+ identifier = question.split('for')[-1].strip()
438
+ elif 'of' in question:
439
+ identifier = question.split('of')[-1].strip()
440
+ elif 'about' in question:
441
+ identifier = question.split('about')[-1].strip()
442
+
443
+ if not identifier:
444
+ return "Please specify a flight identifier (callsign or ICAO code) in your question."
445
+
446
+ # Try to find the flight by callsign or icao
447
+ flight_data = None
448
+ if identifier in geo_df['callsign'].values:
449
+ flight_data = geo_df[geo_df['callsign'] == identifier]
450
+ elif identifier in geo_df['icao24'].values:
451
+ flight_data = geo_df[geo_df['icao24'] == identifier]
452
+
453
+ if flight_data is None or flight_data.empty:
454
+ return f"Could not find flight information for {identifier}. Please check the flight identifier and try again."
455
+
456
+ # Prepare flight data for the LLM
457
+ flight_info = {}
458
+ for col in flight_data.columns:
459
+ if col in flight_data.columns:
460
+ value = flight_data[col].iloc[0]
461
+ if pd.notna(value):
462
+ if col == 'baro_altitude' or col == 'geo_altitude':
463
+ flight_info[col] = f"{value} meters"
464
+ elif col == 'velocity':
465
+ flight_info[col] = f"{value} m/s"
466
+ elif col == 'true_track':
467
+ flight_info[col] = f"{value} degrees"
468
+ elif col == 'vertical_rate':
469
+ flight_info[col] = f"{value} m/s"
470
+ elif col == 'latitude':
471
+ flight_info[col] = f"{value}° N"
472
+ elif col == 'longitude':
473
+ flight_info[col] = f"{value}° E"
474
+ else:
475
+ flight_info[col] = str(value)
476
+
477
+ if not flight_info:
478
+ return f"No information available for flight {identifier}."
479
+
480
+ # Create a prompt for the LLM
481
+ prompt = f"""You are a flight information assistant. Answer the following question about flight {identifier} using the provided flight data.
482
 
483
+ Question: {question}
484
 
485
+ Flight Data:
486
+ {json.dumps(flight_info, indent=2)}
 
 
 
 
 
487
 
488
+ Please provide a clear and concise answer focusing on the specific information requested in the question. If the question asks for information not available in the data, say so clearly."""
 
489
 
490
+ # Get response from LLM
491
+ llm_response = query_llm(prompt)
492
+
493
+ if llm_response:
494
+ return llm_response
495
  else:
496
+ # Fallback to direct data response if LLM fails
497
+ response = f"Flight Information for {identifier}:\n"
498
+ for key, value in flight_info.items():
499
+ response += f"- {key.replace('_', ' ').title()}: {value}\n"
500
+ return response
501
 
502
  def flight_tracking(flight_view_level, country, local_time_zone, flight_info, airport, color):
503
+ # Get cached location data
504
+ loc = get_location(country)
505
+ if not loc:
506
+ st.error("Could not find location. Please try a different country name.")
507
+ return
508
+
509
  loc_box = loc[1]
510
  extend_left =+12*flight_view_level
511
  extend_right =+10*flight_view_level
 
514
  lat_min, lat_max = (loc_box[0] - extend_left), loc_box[0]+extend_right
515
  lon_min, lon_max = (loc_box[1] - extend_bottom), loc_box[1]+extend_top
516
 
 
 
517
  columns = ["icao24","callsign","origin_country","time_position","last_contact","longitude","latitude",
518
  "baro_altitude","on_ground","velocity","true_track","vertical_rate","sensors","geo_altitude",
519
  "squawk","spi","position_source",]
520
+
521
+ # Get cached airport data
522
+ airport_df = load_airport_data()
 
523
  airport_locations = airport_df[["Name", "City", "Country", "IATA/FAA", "Latitude", "Longitude"]]
524
  airport_country_loc = airport_locations[airport_locations['Country'] == str(loc)]
525
+ airport_country_loc = airport_country_loc[(airport_country_loc['Country'] == str(loc)) &
526
+ (airport_country_loc['Latitude'] >= lat_min) &
527
+ (airport_country_loc['Latitude'] <= lat_max) &
528
+ (airport_country_loc['Longitude'] >= lon_min) &
529
+ (airport_country_loc['Longitude'] <= lon_max)]
530
+
531
  def get_traffic_gdf():
532
+ # Get cached flight data
533
+ json_dict = fetch_flight_data(lat_min, lat_max, lon_min, lon_max)
534
+
535
+ if not json_dict or not json_dict.get('states'):
536
+ st.warning("No flight data available for the selected area.")
537
+ return None
538
+
539
+ try:
540
+ unix_timestamp = int(json_dict["time"])
541
+ local_timezone = pytz.timezone(local_time_zone)
542
+ local_time = datetime.fromtimestamp(unix_timestamp, local_timezone).strftime('%Y-%m-%d %H:%M:%S')
543
+
544
+ # Optimize DataFrame creation
545
+ state_df = pd.DataFrame(json_dict["states"], columns=columns)
546
+ state_df['time'] = local_time
547
+
548
+ # Create GeoDataFrame more efficiently
549
+ gdf = gpd.GeoDataFrame(
550
  state_df,
551
  geometry=gpd.points_from_xy(state_df.longitude, state_df.latitude),
552
+ crs="EPSG:4326"
553
  )
554
+
555
+ # Display information
556
+ st.title("Live Flight Tracker")
557
+ st.subheader('Flight Details', divider='rainbow')
558
+ st.write('Location: {0}'.format(loc))
559
+ st.write('Current Local Time: {0}-{1}:'.format(local_time, local_time_zone))
560
+ st.write("Minimum_latitude is {0} and Maximum_latitude is {1}".format(lat_min, lat_max))
561
+ st.write("Minimum_longitude is {0} and Maximum_longitude is {1}".format(lon_min, lon_max))
562
+ st.write('Number of Visible Flights: {}'.format(len(json_dict['states'])))
563
+ st.write('Plotting the flight: {}'.format(flight_info))
564
+ st.subheader('Map Visualization', divider='rainbow')
565
+ st.write('****Click ":orange[Update Map]" Button to Refresh the Map****')
566
+ return gdf
567
+
568
+ except Exception as e:
569
+ st.error(f"Error processing flight data: {str(e)}")
570
+ return None
571
 
572
+ # Get traffic data
573
  geo_df = get_traffic_gdf()
574
+ if geo_df is None:
575
+ return
576
+
577
+ # Create a base map
578
+ m = folium.Map(
579
+ location=[loc_box[0], loc_box[1]],
580
+ zoom_start=6,
581
+ tiles='CartoDB dark_matter'
582
+ )
583
+
584
+ # Create colormap
585
+ if color == "rainbow":
586
+ colormap = cm.LinearColormap(
587
+ colors=['red', 'yellow', 'green', 'blue', 'purple'],
588
+ vmin=geo_df[flight_info].min(),
589
+ vmax=geo_df[flight_info].max()
590
+ )
591
+ elif color == "ice":
592
+ colormap = cm.LinearColormap(
593
+ colors=['white', 'lightblue', 'blue'],
594
+ vmin=geo_df[flight_info].min(),
595
+ vmax=geo_df[flight_info].max()
596
+ )
597
+ else: # hot
598
+ colormap = cm.LinearColormap(
599
+ colors=['yellow', 'orange', 'red'],
600
+ vmin=geo_df[flight_info].min(),
601
+ vmax=geo_df[flight_info].max()
602
+ )
603
+
604
+ # Pre-compute icon HTML template
605
+ icon_template = """
606
+ <div style="transform: rotate({rotation_angle}deg);">
607
+ <svg width="24" height="24" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
608
+ <path d="M21 16v-2l-8-5V3.5c0-.83-.67-1.5-1.5-1.5S10 2.67 10 3.5V9l-8 5v2l8-2.5V19l-2 1.5V22l3.5-1 3.5 1v-1.5L13 19v-5.5l8 2.5z" fill="{color_hex}"/>
609
+ </svg>
610
+ </div>
611
+ """
612
+
613
+ # Pre-compute tooltip template
614
+ tooltip_template = """
615
+ <div style="font-size: 12px; font-family: Arial, sans-serif; max-width: 300px;">
616
+ <div style="font-weight: bold; font-size: 14px; margin-bottom: 5px; color: #2c3e50;">
617
+ Flight: {callsign}
618
+ </div>
619
+ <div style="display: grid; grid-template-columns: 1fr 1fr; gap: 5px;">
620
+ {rows}
621
+ </div>
622
+ </div>
623
+ """
624
+
625
+ # Add flight markers
626
+ for idx, row in geo_df.iterrows():
627
+ if pd.notna(row['latitude']) and pd.notna(row['longitude']):
628
+ # Get color based on flight_info value
629
+ value = row[flight_info] if pd.notna(row[flight_info]) else geo_df[flight_info].min()
630
+ color_hex = colormap(value)
631
+
632
+ # Create custom flight icon with rotation
633
+ rotation_angle = row['true_track'] if pd.notna(row['true_track']) else 0
634
+ icon_html = icon_template.format(rotation_angle=rotation_angle, color_hex=color_hex)
635
+
636
+ # Create tooltip rows
637
+ tooltip_rows = []
638
+ for col in columns:
639
+ val = row[col] if pd.notna(row[col]) else 'N/A'
640
+ if col in ['baro_altitude', 'geo_altitude']:
641
+ val = f"{val} m"
642
+ elif col == 'velocity':
643
+ val = f"{val} m/s"
644
+ elif col == 'true_track':
645
+ val = f"{val}°"
646
+ tooltip_rows.append(f'<div style="font-weight: bold;">{col}:</div><div>{val}</div>')
647
+
648
+ # Create tooltip
649
+ tooltip_html = tooltip_template.format(
650
+ callsign=row['callsign'] if pd.notna(row['callsign']) else 'Unknown',
651
+ rows='\n'.join(tooltip_rows)
652
+ )
653
+
654
+ # Create popup content
655
+ popup_content = f"""
656
+ <div style="font-size: 14px; font-family: Arial, sans-serif; max-width: 300px;">
657
+ <div style="font-weight: bold; font-size: 16px; margin-bottom: 10px; color: #2c3e50;">
658
+ Flight: {row['callsign'] if pd.notna(row['callsign']) else 'Unknown'}
659
+ </div>
660
+ <div style="display: grid; grid-template-columns: 1fr 1fr; gap: 5px;">
661
+ <div style="font-weight: bold;">ICAO24:</div>
662
+ <div>{row['icao24'] if pd.notna(row['icao24']) else 'N/A'}</div>
663
+ <div style="font-weight: bold;">Origin Country:</div>
664
+ <div>{row['origin_country'] if pd.notna(row['origin_country']) else 'N/A'}</div>
665
+ <div style="font-weight: bold;">Time Position:</div>
666
+ <div>{row['time_position'] if pd.notna(row['time_position']) else 'N/A'}</div>
667
+ <div style="font-weight: bold;">Last Contact:</div>
668
+ <div>{row['last_contact'] if pd.notna(row['last_contact']) else 'N/A'}</div>
669
+ <div style="font-weight: bold;">Baro Altitude:</div>
670
+ <div>{row['baro_altitude'] if pd.notna(row['baro_altitude']) else 'N/A'} m</div>
671
+ <div style="font-weight: bold;">Geo Altitude:</div>
672
+ <div>{row['geo_altitude'] if pd.notna(row['geo_altitude']) else 'N/A'} m</div>
673
+ <div style="font-weight: bold;">Velocity:</div>
674
+ <div>{row['velocity'] if pd.notna(row['velocity']) else 'N/A'} m/s</div>
675
+ <div style="font-weight: bold;">True Track:</div>
676
+ <div>{row['true_track'] if pd.notna(row['true_track']) else 'N/A'}°</div>
677
+ <div style="font-weight: bold;">Vertical Rate:</div>
678
+ <div>{row['vertical_rate'] if pd.notna(row['vertical_rate']) else 'N/A'} m/s</div>
679
+ <div style="font-weight: bold;">Squawk:</div>
680
+ <div>{row['squawk'] if pd.notna(row['squawk']) else 'N/A'}</div>
681
+ <div style="font-weight: bold;">On Ground:</div>
682
+ <div>{row['on_ground'] if pd.notna(row['on_ground']) else 'N/A'}</div>
683
+ <div style="font-weight: bold;">SPI:</div>
684
+ <div>{row['spi'] if pd.notna(row['spi']) else 'N/A'}</div>
685
+ <div style="font-weight: bold;">Position Source:</div>
686
+ <div>{row['position_source'] if pd.notna(row['position_source']) else 'N/A'}</div>
687
+ </div>
688
+ </div>
689
+ """
690
+
691
+ # Create custom icon
692
+ icon = folium.DivIcon(
693
+ html=icon_html,
694
+ icon_size=(24, 24),
695
+ icon_anchor=(12, 12)
696
+ )
697
+
698
+ # Add marker to map
699
+ folium.Marker(
700
+ location=[row['latitude'], row['longitude']],
701
+ icon=icon,
702
+ popup=folium.Popup(popup_content, max_width=300),
703
+ tooltip=tooltip_html
704
+ ).add_to(m)
705
+
706
+ # Add airports if selected
707
+ if airport == 1:
708
+ for idx, row in airport_country_loc.iterrows():
709
+ folium.Marker(
710
+ location=[row['Latitude'], row['Longitude']],
711
+ icon=folium.Icon(icon='plane', prefix='fa', color='blue'),
712
+ popup=f"<b>{row['Name']}</b><br>IATA: {row['IATA/FAA']}<br>City: {row['City']}",
713
+ tooltip=f"Airport: {row['Name']}"
714
+ ).add_to(m)
715
+
716
+ # Add colormap to the map
717
+ colormap.add_to(m)
718
+
719
+ # Add a layer control
720
+ folium.LayerControl().add_to(m)
721
+
722
+ # Display the map in Streamlit
723
+ st_folium.folium_static(m, width=1200, height=600)
724
+ return None
725
+
726
  st.set_page_config(
727
  layout="wide"
728
  )