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 (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 |
+
|