Update app.py
Browse files
app.py
CHANGED
@@ -229,231 +229,100 @@
|
|
229 |
# # st.button('Re-run', type="primary")
|
230 |
# # st.snow()
|
231 |
|
232 |
-
'''Copyright 2024 Ashok Kumar
|
233 |
-
|
234 |
-
Licensed under the Apache License, Version 2.0 (the "License");
|
235 |
-
you may not use this file except in compliance with the License.
|
236 |
-
You may obtain a copy of the License at
|
237 |
-
|
238 |
-
http://www.apache.org/licenses/LICENSE-2.0
|
239 |
-
|
240 |
-
Unless required by applicable law or agreed to in writing, software
|
241 |
-
distributed under the License is distributed on an "AS IS" BASIS,
|
242 |
-
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
243 |
-
See the License for the specific language governing permissions and
|
244 |
-
limitations under the License.'''
|
245 |
-
|
246 |
-
import os
|
247 |
-
import requests
|
248 |
-
import json
|
249 |
-
import pandas as pd
|
250 |
-
import numpy as np
|
251 |
-
import geopandas as gpd
|
252 |
-
import contextily as ctx
|
253 |
-
import tzlocal
|
254 |
-
import pytz
|
255 |
-
from PIL import Image
|
256 |
-
from datetime import datetime
|
257 |
-
import matplotlib.pyplot as plt
|
258 |
-
from geopy.exc import GeocoderTimedOut
|
259 |
-
from geopy.geocoders import Nominatim
|
260 |
-
import warnings
|
261 |
-
warnings.filterwarnings('ignore')
|
262 |
-
from plotly.graph_objs import Marker
|
263 |
-
import plotly.express as px
|
264 |
import streamlit as st
|
265 |
-
|
266 |
-
|
267 |
-
|
268 |
|
|
|
269 |
hf_token = os.getenv("HF_TOKEN")
|
270 |
if hf_token is None:
|
271 |
raise ValueError("Hugging Face token not found. Please set the HF_TOKEN environment variable.")
|
272 |
login(hf_token)
|
273 |
|
274 |
-
|
275 |
-
# Replace with the correct model name for Deepseek r1
|
276 |
API_URL = "https://api-inference.huggingface.co/models/deepseek-ai/deepseek-r1"
|
277 |
headers = {"Authorization": f"Bearer {hf_token}"}
|
278 |
|
279 |
-
|
|
|
|
|
|
|
|
|
280 |
response = requests.post(API_URL, headers=headers, json=payload)
|
281 |
return response.json()
|
282 |
|
283 |
-
|
284 |
-
|
285 |
-
|
286 |
-
|
287 |
-
|
288 |
-
|
289 |
-
|
290 |
-
|
291 |
-
|
292 |
-
|
293 |
-
|
294 |
-
"on_ground": geo_df["on_ground"].astype(str).iloc[:100].tolist(), # Assuming on_ground is boolean or categorical
|
295 |
-
"velocity": geo_df["velocity"].astype(str).replace({np.nan: '0', np.inf: '0'}).iloc[:100].tolist(),
|
296 |
-
"true_track": geo_df["true_track"].astype(str).replace({np.nan: '0', np.inf: '0'}).iloc[:100].tolist(),
|
297 |
-
"vertical_rate": geo_df["vertical_rate"].astype(str).replace({np.nan: '0', np.inf: '0'}).iloc[:100].tolist(),
|
298 |
-
"sensors": geo_df["sensors"].astype(str).replace({np.nan: None, np.inf: '0'}).iloc[:100].tolist(), # Assuming sensors can be None
|
299 |
-
"geo_altitude": geo_df["geo_altitude"].astype(str).replace({np.nan: '0', np.inf: '0'}).iloc[:100].tolist(),
|
300 |
-
"squawk": geo_df["squawk"].astype(str).replace({np.nan: None, np.inf: '0'}).iloc[:100].tolist(), # Assuming squawk can be None
|
301 |
-
"spi": geo_df["spi"].astype(str).iloc[:100].tolist(), # Assuming spi is boolean or categorical
|
302 |
-
"position_source": geo_df["position_source"].astype(str).iloc[:100].tolist(), # Assuming position_source is categorical
|
303 |
-
"time": geo_df["time"].astype(str).replace({np.nan: '0', np.inf: '0'}).iloc[:100].tolist(),
|
304 |
-
"geometry": geo_df["geometry"].astype(str).replace({np.nan: None, np.inf: '0'}).iloc[:100].tolist() # Assuming geometry can be None
|
305 |
}
|
306 |
-
|
307 |
-
|
308 |
-
|
309 |
-
|
310 |
-
|
311 |
-
"context": json.dumps(table_data), # Convert table data to JSON string
|
312 |
-
}
|
313 |
}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
314 |
|
315 |
-
|
316 |
-
|
317 |
-
|
318 |
-
|
319 |
-
|
320 |
-
|
321 |
-
|
322 |
-
|
323 |
-
|
324 |
-
|
325 |
-
|
326 |
-
|
327 |
-
|
328 |
-
|
329 |
-
|
330 |
-
|
331 |
-
|
332 |
-
|
333 |
-
|
334 |
-
|
335 |
-
|
336 |
-
|
337 |
-
tile_zoom = 8 # zoom of the map loaded by contextily
|
338 |
-
figsize = (15, 15)
|
339 |
-
columns = ["icao24","callsign","origin_country","time_position","last_contact","longitude","latitude",
|
340 |
-
"baro_altitude","on_ground","velocity","true_track","vertical_rate","sensors","geo_altitude",
|
341 |
-
"squawk","spi","position_source",]
|
342 |
-
data_url = "https://raw.githubusercontent.com/ashok2216-A/ashok_airport-data/main/data/airports.dat"
|
343 |
-
column_names = ["Airport ID", "Name", "City", "Country", "IATA/FAA", "ICAO", "Latitude", "Longitude",
|
344 |
-
"Altitude", "Timezone", "DST", "Tz database time zone", "Type", "Source"]
|
345 |
-
airport_df = pd.read_csv(data_url, header=None, names=column_names)
|
346 |
-
airport_locations = airport_df[["Name", "City", "Country", "IATA/FAA", "Latitude", "Longitude"]]
|
347 |
-
airport_country_loc = airport_locations[airport_locations['Country'] == str(loc)]
|
348 |
-
airport_country_loc = airport_country_loc[(airport_country_loc['Country'] == str(loc)) & (airport_country_loc['Latitude'] >= lat_min) &
|
349 |
-
(airport_country_loc['Latitude'] <= lat_max) & (airport_country_loc['Longitude'] >= lon_min) &
|
350 |
-
(airport_country_loc['Longitude'] <= lon_max)]
|
351 |
-
def get_traffic_gdf():
|
352 |
-
url_data = (
|
353 |
-
f"https://@opensky-network.org/api/states/all?"
|
354 |
-
f"lamin={str(lat_min)}"
|
355 |
-
f"&lomin={str(lon_min)}"
|
356 |
-
f"&lamax={str(lat_max)}"
|
357 |
-
f"&lomax={str(lon_max)}")
|
358 |
-
json_dict = requests.get(url_data).json()
|
359 |
-
|
360 |
-
unix_timestamp = int(json_dict["time"])
|
361 |
-
local_timezone = pytz.timezone(local_time_zone) # get pytz timezone
|
362 |
-
local_time = datetime.fromtimestamp(unix_timestamp, local_timezone).strftime('%Y-%m-%d %H:%M:%S')
|
363 |
-
time = []
|
364 |
-
for i in range(len(json_dict['states'])):
|
365 |
-
time.append(local_time)
|
366 |
-
df_time = pd.DataFrame(time,columns=['time'])
|
367 |
-
state_df = pd.DataFrame(json_dict["states"],columns=columns)
|
368 |
-
state_df['time'] = df_time
|
369 |
-
gdf = gpd.GeoDataFrame(
|
370 |
-
state_df,
|
371 |
-
geometry=gpd.points_from_xy(state_df.longitude, state_df.latitude),
|
372 |
-
crs={"init": "epsg:4326"}, # WGS84
|
373 |
-
)
|
374 |
-
# banner_image = Image.open('banner.png')
|
375 |
-
# st.image(banner_image, width=300)
|
376 |
-
st.title("Live Flight Tracker")
|
377 |
-
st.subheader('Flight Details', divider='rainbow')
|
378 |
-
st.write('Location: {0}'.format(loc))
|
379 |
-
st.write('Current Local Time: {0}-{1}:'.format(local_time, local_time_zone))
|
380 |
-
st.write("Minimum_latitude is {0} and Maximum_latitude is {1}".format(lat_min, lat_max))
|
381 |
-
st.write("Minimum_longitude is {0} and Maximum_longitude is {1}".format(lon_min, lon_max))
|
382 |
-
st.write('Number of Visible Flights: {}'.format(len(json_dict['states'])))
|
383 |
-
st.write('Plotting the flight: {}'.format(flight_info))
|
384 |
-
st.subheader('Map Visualization', divider='rainbow')
|
385 |
-
st.write('****Click ":orange[Update Map]" Button to Refresh the Map****')
|
386 |
-
return gdf
|
387 |
-
|
388 |
-
geo_df = get_traffic_gdf()
|
389 |
-
if airport == 0:
|
390 |
-
fig = px.scatter_mapbox(geo_df, lat="latitude", lon="longitude",color=flight_info,
|
391 |
-
color_continuous_scale=color, zoom=4,width=1200, height=600,opacity=1,
|
392 |
-
hover_name ='origin_country',hover_data=['callsign', 'baro_altitude',
|
393 |
-
'on_ground', 'velocity', 'true_track', 'vertical_rate', 'geo_altitude'], template='plotly_dark')
|
394 |
-
elif airport == 1:
|
395 |
-
fig = px.scatter_mapbox(geo_df, lat="latitude", lon="longitude",color=flight_info,
|
396 |
-
color_continuous_scale=color, zoom=4,width=1200, height=600,opacity=1,
|
397 |
-
hover_name ='origin_country',hover_data=['callsign', 'baro_altitude',
|
398 |
-
'on_ground', 'velocity', 'true_track', 'vertical_rate', 'geo_altitude'], template='plotly_dark')
|
399 |
-
fig.add_trace(px.scatter_mapbox(airport_country_loc, lat="Latitude", lon="Longitude",
|
400 |
-
hover_name ='Name', hover_data=["City", "Country", "IATA/FAA"]).data[0])
|
401 |
-
else: None
|
402 |
-
fig.update_layout(mapbox_style="carto-darkmatter")
|
403 |
-
fig.update_layout(margin={"r": 0, "t": 0, "l": 0, "b": 0})
|
404 |
-
# out = fig.show())
|
405 |
-
out = st.plotly_chart(fig, theme=None)
|
406 |
-
return out
|
407 |
-
st.set_page_config(
|
408 |
-
layout="wide"
|
409 |
-
)
|
410 |
-
image = Image.open('logo.png')
|
411 |
-
add_selectbox = st.sidebar.image(
|
412 |
-
image, width=150
|
413 |
-
)
|
414 |
-
add_selectbox = st.sidebar.subheader(
|
415 |
-
"Configure Map",divider='rainbow'
|
416 |
-
)
|
417 |
-
with st.sidebar:
|
418 |
-
Refresh = st.button('Update Map', key=1)
|
419 |
-
on = st.toggle('View Airports')
|
420 |
-
if on:
|
421 |
-
air_port = 1
|
422 |
-
st.write(':rainbow[Nice Work Buddy!]')
|
423 |
-
st.write('Now Airports are Visible')
|
424 |
-
else:
|
425 |
-
air_port=0
|
426 |
-
view = st.slider('Increase Flight Visibility',1,6,2)
|
427 |
-
st.write("You Selected:", view)
|
428 |
-
cou = st.text_input('Type Country Name', 'north america')
|
429 |
-
st.write('The current Country name is', cou)
|
430 |
-
time = st.text_input('Type Time Zone Name (Ex: America/Toronto, Europe/Berlin)', 'Asia/Kolkata')
|
431 |
-
st.write('The current Time Zone is', time)
|
432 |
-
info = st.selectbox(
|
433 |
-
'Select Flight Information',
|
434 |
-
('baro_altitude',
|
435 |
-
'on_ground', 'velocity',
|
436 |
-
'geo_altitude'))
|
437 |
-
st.write('Plotting the data of Flight:', info)
|
438 |
-
clr = st.radio('Pick A Color for Scatter Plot',["rainbow","ice","hot"])
|
439 |
-
if clr == "rainbow":
|
440 |
-
st.write('The current color is', "****:rainbow[Rainbow]****")
|
441 |
-
elif clr == 'ice':
|
442 |
-
st.write('The current color is', "****:blue[Ice]****")
|
443 |
-
elif clr == 'hot':
|
444 |
-
st.write('The current color is', "****:red[Hot]****")
|
445 |
-
else: None
|
446 |
-
# with st.spinner('Wait!, We Requesting API Data...'):
|
447 |
-
# try:
|
448 |
-
flight_tracking(flight_view_level=view, country=cou,flight_info=info,
|
449 |
-
local_time_zone=time, airport=air_port, color=clr)
|
450 |
-
st.subheader('Ask your Questions!', divider='rainbow')
|
451 |
-
st.write("Deepseek r1 model 🤖")
|
452 |
-
geo_df = flight_data(flight_view_level = view, country= cou, flight_info=info, local_time_zone=time, airport=1)
|
453 |
-
question = st.text_input('Type your questions here', "What is the squawk code for SWR9XD?")
|
454 |
-
result = query_flight_data(geo_df, question)
|
455 |
-
st.markdown(result)
|
456 |
-
# except TypeError:
|
457 |
-
# st.error(':red[Error: ] Please Re-run this page.', icon="🚨")
|
458 |
-
# st.button('Re-run', type="primary")
|
459 |
-
# st.snow()
|
|
|
229 |
# # st.button('Re-run', type="primary")
|
230 |
# # st.snow()
|
231 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
232 |
import streamlit as st
|
233 |
+
import requests
|
234 |
+
import os
|
235 |
+
from huggingface_hub import login
|
236 |
|
237 |
+
# Set up Hugging Face token
|
238 |
hf_token = os.getenv("HF_TOKEN")
|
239 |
if hf_token is None:
|
240 |
raise ValueError("Hugging Face token not found. Please set the HF_TOKEN environment variable.")
|
241 |
login(hf_token)
|
242 |
|
243 |
+
# Hugging Face Inference API URL for Deepseek model
|
|
|
244 |
API_URL = "https://api-inference.huggingface.co/models/deepseek-ai/deepseek-r1"
|
245 |
headers = {"Authorization": f"Bearer {hf_token}"}
|
246 |
|
247 |
+
# Function to query the Deepseek model
|
248 |
+
def query_deepseek(payload):
|
249 |
+
"""
|
250 |
+
Sends a query to the Deepseek model using Hugging Face Inference API.
|
251 |
+
"""
|
252 |
response = requests.post(API_URL, headers=headers, json=payload)
|
253 |
return response.json()
|
254 |
|
255 |
+
# Streamlit app configuration
|
256 |
+
st.set_page_config(page_title="Deepseek Chatbot", page_icon="🤖", layout="wide")
|
257 |
+
|
258 |
+
# Custom CSS for chatbot UI
|
259 |
+
st.markdown("""
|
260 |
+
<style>
|
261 |
+
.chat-message {
|
262 |
+
padding: 10px;
|
263 |
+
border-radius: 10px;
|
264 |
+
margin: 5px 0;
|
265 |
+
max-width: 70%;
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
266 |
}
|
267 |
+
.user-message {
|
268 |
+
background-color: #0078D4;
|
269 |
+
color: white;
|
270 |
+
margin-left: auto;
|
271 |
+
margin-right: 0;
|
|
|
|
|
272 |
}
|
273 |
+
.bot-message {
|
274 |
+
background-color: #f1f1f1;
|
275 |
+
color: black;
|
276 |
+
margin-left: 0;
|
277 |
+
margin-right: auto;
|
278 |
+
}
|
279 |
+
</style>
|
280 |
+
""", unsafe_allow_html=True)
|
281 |
+
|
282 |
+
# Initialize session state for chat history
|
283 |
+
if "chat_history" not in st.session_state:
|
284 |
+
st.session_state.chat_history = []
|
285 |
+
|
286 |
+
# Streamlit app title
|
287 |
+
st.title("🤖 Deepseek Chatbot")
|
288 |
+
st.write("Welcome to the Deepseek Chatbot! Ask me anything, and I'll do my best to help.")
|
289 |
+
|
290 |
+
# Chat input
|
291 |
+
user_input = st.text_input("You:", placeholder="Type your message here...", key="user_input")
|
292 |
+
|
293 |
+
# Send button
|
294 |
+
if st.button("Send"):
|
295 |
+
if user_input.strip() != "":
|
296 |
+
# Add user message to chat history
|
297 |
+
st.session_state.chat_history.append({"role": "user", "content": user_input})
|
298 |
+
|
299 |
+
# Prepare payload for Deepseek model
|
300 |
+
payload = {
|
301 |
+
"inputs": {
|
302 |
+
"question": user_input,
|
303 |
+
"context": "", # Add context if needed
|
304 |
+
}
|
305 |
+
}
|
306 |
|
307 |
+
# Query the Deepseek model
|
308 |
+
with st.spinner("Thinking..."):
|
309 |
+
try:
|
310 |
+
response = query_deepseek(payload)
|
311 |
+
bot_response = response.get("answer", "Sorry, I couldn't understand that.")
|
312 |
+
except Exception as e:
|
313 |
+
bot_response = f"An error occurred: {str(e)}"
|
314 |
+
|
315 |
+
# Add bot response to chat history
|
316 |
+
st.session_state.chat_history.append({"role": "bot", "content": bot_response})
|
317 |
+
|
318 |
+
# Display chat history
|
319 |
+
for message in st.session_state.chat_history:
|
320 |
+
if message["role"] == "user":
|
321 |
+
st.markdown(f'<div class="chat-message user-message">{message["content"]}</div>', unsafe_allow_html=True)
|
322 |
+
elif message["role"] == "bot":
|
323 |
+
st.markdown(f'<div class="chat-message bot-message">{message["content"]}</div>', unsafe_allow_html=True)
|
324 |
+
|
325 |
+
# Clear chat history button
|
326 |
+
if st.button("Clear Chat"):
|
327 |
+
st.session_state.chat_history = []
|
328 |
+
st.experimental_rerun()
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|