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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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 |
+
|
| 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 |
+
|
| 37 |
+
|
| 38 |
+
API_URL = "https://api-inference.huggingface.co/models/google/tapas-base-finetuned-wtq"
|
| 39 |
+
headers = {"Authorization": f"Bearer {HF_TOKEN}"}
|
| 40 |
+
|
| 41 |
+
def query(payload):
|
| 42 |
+
response = requests.post(API_URL, headers=headers, json=payload)
|
| 43 |
+
return response.json()
|
| 44 |
+
|
| 45 |
+
def query_flight_data(geo_df, question):
|
| 46 |
+
|
| 47 |
+
|
| 48 |
+
table_data = {
|
| 49 |
+
"icao24": geo_df["icao24"].astype(str).iloc[:100].tolist(),
|
| 50 |
+
"callsign": geo_df["callsign"].astype(str).replace({np.nan: None, np.inf: '0'}).iloc[:100].tolist(),
|
| 51 |
+
"origin_country": geo_df["origin_country"].astype(str).replace({np.nan: None, np.inf: '0'}).iloc[:100].tolist(),
|
| 52 |
+
"time_position": geo_df["time_position"].astype(str).replace({np.nan: '0', np.inf: '0'}).iloc[:100].tolist(),
|
| 53 |
+
"last_contact": geo_df["last_contact"].astype(str).replace({np.nan: '0', np.inf: '0'}).iloc[:100].tolist(),
|
| 54 |
+
"longitude": geo_df["longitude"].astype(str).replace({np.nan: '0', np.inf: '0'}).iloc[:100].tolist(),
|
| 55 |
+
"latitude": geo_df["latitude"].astype(str).replace({np.nan: '0', np.inf: '0'}).iloc[:100].tolist(),
|
| 56 |
+
"baro_altitude": geo_df["baro_altitude"].astype(str).replace({np.nan: '0', np.inf: '0'}).iloc[:100].tolist(),
|
| 57 |
+
"on_ground": geo_df["on_ground"].astype(str).iloc[:100].tolist(), # Assuming on_ground is boolean or categorical
|
| 58 |
+
"velocity": geo_df["velocity"].astype(str).replace({np.nan: '0', np.inf: '0'}).iloc[:100].tolist(),
|
| 59 |
+
"true_track": geo_df["true_track"].astype(str).replace({np.nan: '0', np.inf: '0'}).iloc[:100].tolist(),
|
| 60 |
+
"vertical_rate": geo_df["vertical_rate"].astype(str).replace({np.nan: '0', np.inf: '0'}).iloc[:100].tolist(),
|
| 61 |
+
"sensors": geo_df["sensors"].astype(str).replace({np.nan: None, np.inf: '0'}).iloc[:100].tolist(), # Assuming sensors can be None
|
| 62 |
+
"geo_altitude": geo_df["geo_altitude"].astype(str).replace({np.nan: '0', np.inf: '0'}).iloc[:100].tolist(),
|
| 63 |
+
"squawk": geo_df["squawk"].astype(str).replace({np.nan: None, np.inf: '0'}).iloc[:100].tolist(), # Assuming squawk can be None
|
| 64 |
+
"spi": geo_df["spi"].astype(str).iloc[:100].tolist(), # Assuming spi is boolean or categorical
|
| 65 |
+
"position_source": geo_df["position_source"].astype(str).iloc[:100].tolist(), # Assuming position_source is categorical
|
| 66 |
+
"time": geo_df["time"].astype(str).replace({np.nan: '0', np.inf: '0'}).iloc[:100].tolist(),
|
| 67 |
+
"geometry": geo_df["geometry"].astype(str).replace({np.nan: None, np.inf: '0'}).iloc[:100].tolist() # Assuming geometry can be None
|
| 68 |
+
}
|
| 69 |
+
|
| 70 |
+
# Construct the payload
|
| 71 |
+
payload = {
|
| 72 |
+
"inputs": {
|
| 73 |
+
"query": question,
|
| 74 |
+
"table": table_data,
|
| 75 |
+
}
|
| 76 |
+
}
|
| 77 |
+
|
| 78 |
+
# Get the model response
|
| 79 |
+
response = query(payload)
|
| 80 |
+
|
| 81 |
+
# Check if 'answer' is in response and return it as a sentence
|
| 82 |
+
if 'answer' in response:
|
| 83 |
+
answer = response['answer']
|
| 84 |
+
return f"The answer to your question '{question}': :orange[{answer}]"
|
| 85 |
+
else:
|
| 86 |
+
return "The model could not find an answer to your question."
|
| 87 |
+
|
| 88 |
+
|
| 89 |
+
def flight_tracking(flight_view_level, country, local_time_zone, flight_info, airport, color):
|
| 90 |
+
geolocator = Nominatim(user_agent="flight_tracker")
|
| 91 |
+
loc = geolocator.geocode(country)
|
| 92 |
+
loc_box = loc[1]
|
| 93 |
+
extend_left =+12*flight_view_level
|
| 94 |
+
extend_right =+10*flight_view_level
|
| 95 |
+
extend_top =+10*flight_view_level
|
| 96 |
+
extend_bottom =+ 18*flight_view_level
|
| 97 |
+
lat_min, lat_max = (loc_box[0] - extend_left), loc_box[0]+extend_right
|
| 98 |
+
lon_min, lon_max = (loc_box[1] - extend_bottom), loc_box[1]+extend_top
|
| 99 |
+
|
| 100 |
+
tile_zoom = 8 # zoom of the map loaded by contextily
|
| 101 |
+
figsize = (15, 15)
|
| 102 |
+
columns = ["icao24","callsign","origin_country","time_position","last_contact","longitude","latitude",
|
| 103 |
+
"baro_altitude","on_ground","velocity","true_track","vertical_rate","sensors","geo_altitude",
|
| 104 |
+
"squawk","spi","position_source",]
|
| 105 |
+
data_url = "https://raw.githubusercontent.com/ashok2216-A/ashok_airport-data/main/data/airports.dat"
|
| 106 |
+
column_names = ["Airport ID", "Name", "City", "Country", "IATA/FAA", "ICAO", "Latitude", "Longitude",
|
| 107 |
+
"Altitude", "Timezone", "DST", "Tz database time zone", "Type", "Source"]
|
| 108 |
+
airport_df = pd.read_csv(data_url, header=None, names=column_names)
|
| 109 |
+
airport_locations = airport_df[["Name", "City", "Country", "IATA/FAA", "Latitude", "Longitude"]]
|
| 110 |
+
airport_country_loc = airport_locations[airport_locations['Country'] == str(loc)]
|
| 111 |
+
airport_country_loc = airport_country_loc[(airport_country_loc['Country'] == str(loc)) & (airport_country_loc['Latitude'] >= lat_min) &
|
| 112 |
+
(airport_country_loc['Latitude'] <= lat_max) & (airport_country_loc['Longitude'] >= lon_min) &
|
| 113 |
+
(airport_country_loc['Longitude'] <= lon_max)]
|
| 114 |
+
def get_traffic_gdf():
|
| 115 |
+
url_data = (
|
| 116 |
+
f"https://@opensky-network.org/api/states/all?"
|
| 117 |
+
f"lamin={str(lat_min)}"
|
| 118 |
+
f"&lomin={str(lon_min)}"
|
| 119 |
+
f"&lamax={str(lat_max)}"
|
| 120 |
+
f"&lomax={str(lon_max)}")
|
| 121 |
+
json_dict = requests.get(url_data).json()
|
| 122 |
+
|
| 123 |
+
unix_timestamp = int(json_dict["time"])
|
| 124 |
+
local_timezone = pytz.timezone(local_time_zone) # get pytz timezone
|
| 125 |
+
local_time = datetime.fromtimestamp(unix_timestamp, local_timezone).strftime('%Y-%m-%d %H:%M:%S')
|
| 126 |
+
time = []
|
| 127 |
+
for i in range(len(json_dict['states'])):
|
| 128 |
+
time.append(local_time)
|
| 129 |
+
df_time = pd.DataFrame(time,columns=['time'])
|
| 130 |
+
state_df = pd.DataFrame(json_dict["states"],columns=columns)
|
| 131 |
+
state_df['time'] = df_time
|
| 132 |
+
gdf = gpd.GeoDataFrame(
|
| 133 |
+
state_df,
|
| 134 |
+
geometry=gpd.points_from_xy(state_df.longitude, state_df.latitude),
|
| 135 |
+
crs={"init": "epsg:4326"}, # WGS84
|
| 136 |
+
)
|
| 137 |
+
# banner_image = Image.open('banner.png')
|
| 138 |
+
# st.image(banner_image, width=300)
|
| 139 |
+
st.title("Live Flight Tracker")
|
| 140 |
+
st.subheader('Flight Details', divider='rainbow')
|
| 141 |
+
st.write('Location: {0}'.format(loc))
|
| 142 |
+
st.write('Current Local Time: {0}-{1}:'.format(local_time, local_time_zone))
|
| 143 |
+
st.write("Minimum_latitude is {0} and Maximum_latitude is {1}".format(lat_min, lat_max))
|
| 144 |
+
st.write("Minimum_longitude is {0} and Maximum_longitude is {1}".format(lon_min, lon_max))
|
| 145 |
+
st.write('Number of Visible Flights: {}'.format(len(json_dict['states'])))
|
| 146 |
+
st.write('Plotting the flight: {}'.format(flight_info))
|
| 147 |
+
st.subheader('Map Visualization', divider='rainbow')
|
| 148 |
+
st.write('****Click ":orange[Update Map]" Button to Refresh the Map****')
|
| 149 |
+
return gdf
|
| 150 |
+
|
| 151 |
+
geo_df = get_traffic_gdf()
|
| 152 |
+
if airport == 0:
|
| 153 |
+
fig = px.scatter_mapbox(geo_df, lat="latitude", lon="longitude",color=flight_info,
|
| 154 |
+
color_continuous_scale=color, zoom=4,width=1200, height=600,opacity=1,
|
| 155 |
+
hover_name ='origin_country',hover_data=['callsign', 'baro_altitude',
|
| 156 |
+
'on_ground', 'velocity', 'true_track', 'vertical_rate', 'geo_altitude'], template='plotly_dark')
|
| 157 |
+
elif airport == 1:
|
| 158 |
+
fig = px.scatter_mapbox(geo_df, lat="latitude", lon="longitude",color=flight_info,
|
| 159 |
+
color_continuous_scale=color, zoom=4,width=1200, height=600,opacity=1,
|
| 160 |
+
hover_name ='origin_country',hover_data=['callsign', 'baro_altitude',
|
| 161 |
+
'on_ground', 'velocity', 'true_track', 'vertical_rate', 'geo_altitude'], template='plotly_dark')
|
| 162 |
+
fig.add_trace(px.scatter_mapbox(airport_country_loc, lat="Latitude", lon="Longitude",
|
| 163 |
+
hover_name ='Name', hover_data=["City", "Country", "IATA/FAA"]).data[0])
|
| 164 |
+
else: None
|
| 165 |
+
fig.update_layout(mapbox_style="carto-darkmatter")
|
| 166 |
+
fig.update_layout(margin={"r": 0, "t": 0, "l": 0, "b": 0})
|
| 167 |
+
# out = fig.show())
|
| 168 |
+
out = st.plotly_chart(fig, theme=None)
|
| 169 |
+
return out
|
| 170 |
+
st.set_page_config(
|
| 171 |
+
layout="wide"
|
| 172 |
+
)
|
| 173 |
+
image = Image.open('logo.png')
|
| 174 |
+
add_selectbox = st.sidebar.image(
|
| 175 |
+
image, width=150
|
| 176 |
+
)
|
| 177 |
+
add_selectbox = st.sidebar.subheader(
|
| 178 |
+
"Configure Map",divider='rainbow'
|
| 179 |
+
)
|
| 180 |
+
with st.sidebar:
|
| 181 |
+
Refresh = st.button('Update Map', key=1)
|
| 182 |
+
on = st.toggle('View Airports')
|
| 183 |
+
if on:
|
| 184 |
+
air_port = 1
|
| 185 |
+
st.write(':rainbow[Nice Work Buddy!]')
|
| 186 |
+
st.write('Now Airports are Visible')
|
| 187 |
+
else:
|
| 188 |
+
air_port=0
|
| 189 |
+
view = st.slider('Increase Flight Visibility',1,6,2)
|
| 190 |
+
st.write("You Selected:", view)
|
| 191 |
+
cou = st.text_input('Type Country Name', 'north america')
|
| 192 |
+
st.write('The current Country name is', cou)
|
| 193 |
+
time = st.text_input('Type Time Zone Name (Ex: America/Toronto, Europe/Berlin)', 'Asia/Kolkata')
|
| 194 |
+
st.write('The current Time Zone is', time)
|
| 195 |
+
info = st.selectbox(
|
| 196 |
+
'Select Flight Information',
|
| 197 |
+
('baro_altitude',
|
| 198 |
+
'on_ground', 'velocity',
|
| 199 |
+
'geo_altitude'))
|
| 200 |
+
st.write('Plotting the data of Flight:', info)
|
| 201 |
+
clr = st.radio('Pick A Color for Scatter Plot',["rainbow","ice","hot"])
|
| 202 |
+
if clr == "rainbow":
|
| 203 |
+
st.write('The current color is', "****:rainbow[Rainbow]****")
|
| 204 |
+
elif clr == 'ice':
|
| 205 |
+
st.write('The current color is', "****:blue[Ice]****")
|
| 206 |
+
elif clr == 'hot':
|
| 207 |
+
st.write('The current color is', "****:red[Hot]****")
|
| 208 |
+
else: None
|
| 209 |
+
# with st.spinner('Wait!, We Requesting API Data...'):
|
| 210 |
+
# try:
|
| 211 |
+
flight_tracking(flight_view_level=view, country=cou,flight_info=info,
|
| 212 |
+
local_time_zone=time, airport=air_port, color=clr)
|
| 213 |
+
st.subheader('Ask your Questions!', divider='rainbow')
|
| 214 |
+
st.write("Google's TAPAS base LLM model 🤖")
|
| 215 |
+
geo_df = flight_data(flight_view_level = view, country= cou, flight_info=info, local_time_zone=time, airport=1)
|
| 216 |
+
question = st.text_input('Type your questions here', "What is the squawk code for SWR9XD?")
|
| 217 |
+
result = query_flight_data(geo_df, question)
|
| 218 |
+
st.markdown(result)
|
| 219 |
+
# except TypeError:
|
| 220 |
+
# st.error(':red[Error: ] Please Re-run this page.', icon="🚨")
|
| 221 |
+
# st.button('Re-run', type="primary")
|
| 222 |
+
# st.snow()
|
| 223 |
+
|