Spaces:
Sleeping
Sleeping
Update app.py (#8)
Browse files- Update app.py (a7e3df52fa5e792377b6e8c18ab743ae807cb09f)
app.py
CHANGED
|
@@ -1,74 +1,111 @@
|
|
| 1 |
-
import streamlit as st
|
| 2 |
import pandas as pd
|
| 3 |
-
|
|
|
|
| 4 |
import folium
|
| 5 |
from streamlit_folium import folium_static
|
| 6 |
import groq
|
| 7 |
|
| 8 |
-
# Load
|
| 9 |
-
data_path = "pdp.csv"
|
| 10 |
df = pd.read_csv(data_path)
|
| 11 |
|
| 12 |
-
# Dummy
|
| 13 |
USER_CREDENTIALS = {
|
| 14 |
-
"Muthuraja":"virat",
|
| 15 |
-
"Praveen":"dhoni",
|
| 16 |
-
"Pandi":"kabadi",
|
| 17 |
"admin": "password123",
|
| 18 |
"user": "buspass2025"
|
| 19 |
}
|
| 20 |
|
| 21 |
-
# Groq API Key
|
| 22 |
GROQ_API_KEY = "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"
|
| 23 |
groq.api_key = GROQ_API_KEY
|
| 24 |
|
| 25 |
-
|
|
|
|
| 26 |
def authenticate(username, password):
|
|
|
|
| 27 |
if username in USER_CREDENTIALS and USER_CREDENTIALS[username] == password:
|
| 28 |
return True
|
| 29 |
return False
|
| 30 |
|
| 31 |
-
|
| 32 |
-
|
| 33 |
-
|
|
|
|
|
|
|
| 34 |
try:
|
| 35 |
client = groq.Client(api_key=GROQ_API_KEY)
|
| 36 |
response = client.chat.completions.create(
|
| 37 |
-
model="llama3-70b-8192",
|
| 38 |
messages=[{"role": "system", "content": prompt}]
|
| 39 |
)
|
| 40 |
return response.choices[0].message.content.strip()
|
| 41 |
except Exception as e:
|
| 42 |
return f"Error: {e}"
|
| 43 |
|
| 44 |
-
# Plot bus locations using Folium with real coordinates
|
| 45 |
-
def plot_bus_map(area_df):
|
| 46 |
-
if area_df.empty:
|
| 47 |
-
st.warning("No bus data available for this area.")
|
| 48 |
-
return
|
| 49 |
|
| 50 |
-
|
| 51 |
-
|
| 52 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 53 |
|
| 54 |
-
|
| 55 |
-
|
|
|
|
|
|
|
|
|
|
| 56 |
|
| 57 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 58 |
|
| 59 |
-
|
| 60 |
-
|
| 61 |
-
|
| 62 |
-
|
| 63 |
-
|
| 64 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 65 |
|
| 66 |
folium_static(m)
|
| 67 |
|
| 68 |
-
|
|
|
|
| 69 |
st.title("๐ Tamil Nadu Bus Tracking & Prediction System")
|
| 70 |
|
| 71 |
-
# Login
|
| 72 |
if "authenticated" not in st.session_state:
|
| 73 |
st.session_state.authenticated = False
|
| 74 |
|
|
@@ -78,34 +115,44 @@ if not st.session_state.authenticated:
|
|
| 78 |
if st.button("Login"):
|
| 79 |
if authenticate(username, password):
|
| 80 |
st.session_state.authenticated = True
|
| 81 |
-
st.success("Login successful!")
|
|
|
|
| 82 |
else:
|
| 83 |
-
st.error("Invalid username or password")
|
| 84 |
|
|
|
|
| 85 |
if st.session_state.authenticated:
|
| 86 |
-
|
| 87 |
-
area = st.selectbox("Select Area", df[df["city"] == city]["area"].unique())
|
| 88 |
-
|
| 89 |
-
filtered_df = df[(df["city"] == city) & (df["area"] == area)]
|
| 90 |
|
| 91 |
-
st.
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 92 |
st.dataframe(filtered_df)
|
| 93 |
|
| 94 |
-
|
| 95 |
-
|
|
|
|
| 96 |
|
| 97 |
-
|
| 98 |
-
|
| 99 |
-
|
| 100 |
-
|
| 101 |
-
|
| 102 |
-
prediction = predict_bus_status(
|
| 103 |
-
|
| 104 |
-
return "โ ๏ธ No upcoming buses available."
|
| 105 |
|
| 106 |
-
|
| 107 |
-
|
|
|
|
| 108 |
|
|
|
|
| 109 |
if st.button("Logout"):
|
| 110 |
st.session_state.authenticated = False
|
| 111 |
-
st.
|
|
|
|
| 1 |
+
import streamlit as st
|
| 2 |
import pandas as pd
|
| 3 |
+
import random
|
| 4 |
+
from datetime import datetime, timedelta
|
| 5 |
import folium
|
| 6 |
from streamlit_folium import folium_static
|
| 7 |
import groq
|
| 8 |
|
| 9 |
+
# --- ๐ Load Bus Data ---
|
| 10 |
+
data_path = r"C:\Users\Muthuraja\OneDrive\Attachments\Desktop\second\pdp.csv"
|
| 11 |
df = pd.read_csv(data_path)
|
| 12 |
|
| 13 |
+
# --- ๐ Dummy User Credentials ---
|
| 14 |
USER_CREDENTIALS = {
|
| 15 |
+
"Muthuraja": "virat",
|
| 16 |
+
"Praveen": "dhoni",
|
| 17 |
+
"Pandi": "kabadi",
|
| 18 |
"admin": "password123",
|
| 19 |
"user": "buspass2025"
|
| 20 |
}
|
| 21 |
|
| 22 |
+
# --- ๐ Groq API Key ---
|
| 23 |
GROQ_API_KEY = "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"
|
| 24 |
groq.api_key = GROQ_API_KEY
|
| 25 |
|
| 26 |
+
|
| 27 |
+
# --- ๐ Authenticate User ---
|
| 28 |
def authenticate(username, password):
|
| 29 |
+
"""Authenticate user."""
|
| 30 |
if username in USER_CREDENTIALS and USER_CREDENTIALS[username] == password:
|
| 31 |
return True
|
| 32 |
return False
|
| 33 |
|
| 34 |
+
|
| 35 |
+
# --- ๐ฎ Predict Bus Status using Groq API ---
|
| 36 |
+
def predict_bus_status(bus_number, city, source_area, destination_area):
|
| 37 |
+
"""Predict bus arrival and status with Groq API."""
|
| 38 |
+
prompt = f"Predict the status, route, and arrival time for bus {bus_number} from {source_area} to {destination_area} in {city}."
|
| 39 |
try:
|
| 40 |
client = groq.Client(api_key=GROQ_API_KEY)
|
| 41 |
response = client.chat.completions.create(
|
| 42 |
+
model="llama3-70b-8192",
|
| 43 |
messages=[{"role": "system", "content": prompt}]
|
| 44 |
)
|
| 45 |
return response.choices[0].message.content.strip()
|
| 46 |
except Exception as e:
|
| 47 |
return f"Error: {e}"
|
| 48 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 49 |
|
| 50 |
+
# --- ๐ฐ๏ธ Add Random Delay to Predicted Time ---
|
| 51 |
+
def add_random_delay(arrival_time_str):
|
| 52 |
+
"""Add 1 to 10 minutes delay to arrival time."""
|
| 53 |
+
try:
|
| 54 |
+
# Handle 'DD-MM-YYYY HH:MM' format
|
| 55 |
+
arrival_time = datetime.strptime(arrival_time_str, "%d-%m-%Y %H:%M")
|
| 56 |
+
except ValueError:
|
| 57 |
+
# Fallback to 'YYYY-MM-DD HH:MM:SS' if needed
|
| 58 |
+
arrival_time = datetime.strptime(arrival_time_str, "%Y-%m-%d %H:%M:%S")
|
| 59 |
+
|
| 60 |
+
delay_minutes = random.randint(1, 10) # Add random delay of 1 to 10 minutes
|
| 61 |
+
new_arrival_time = arrival_time + timedelta(minutes=delay_minutes)
|
| 62 |
+
return new_arrival_time.strftime("%Y-%m-%d %H:%M:%S")
|
| 63 |
|
| 64 |
+
|
| 65 |
+
# --- ๐ Predict Upcoming Bus with Same Route ---
|
| 66 |
+
def predict_upcoming_buses(bus_number, city, area_df):
|
| 67 |
+
"""Predict upcoming buses on the same route."""
|
| 68 |
+
same_route_df = area_df[area_df["same_route_return"] == bus_number]
|
| 69 |
|
| 70 |
+
if not same_route_df.empty:
|
| 71 |
+
upcoming_buses = []
|
| 72 |
+
for _, row in same_route_df.iterrows():
|
| 73 |
+
upcoming_time = row['upcoming_arrival_time']
|
| 74 |
+
delayed_time = add_random_delay(upcoming_time)
|
| 75 |
+
upcoming_buses.append(f"๐ Bus {row['upcoming_bus_number']} โ {row['bus_route']} arriving at {delayed_time}")
|
| 76 |
+
return "\n".join(upcoming_buses)
|
| 77 |
+
return "โ ๏ธ No upcoming buses available on the same route."
|
| 78 |
+
|
| 79 |
+
|
| 80 |
+
# --- ๐บ๏ธ Plot Bus Route Map ---
|
| 81 |
+
def plot_bus_route(source_area, destination_area, area_df):
|
| 82 |
+
"""Plot bus route between source and destination with real-time location."""
|
| 83 |
+
source_df = area_df[area_df["area"] == source_area]
|
| 84 |
+
dest_df = area_df[area_df["area"] == destination_area]
|
| 85 |
+
|
| 86 |
+
if source_df.empty or dest_df.empty:
|
| 87 |
+
st.warning("โ Invalid source or destination. Please try again.")
|
| 88 |
+
return
|
| 89 |
|
| 90 |
+
source_lat, source_lon = source_df.iloc[0]["latitude"], source_df.iloc[0]["longitude"]
|
| 91 |
+
dest_lat, dest_lon = dest_df.iloc[0]["latitude"], dest_df.iloc[0]["longitude"]
|
| 92 |
+
|
| 93 |
+
m = folium.Map(location=[(source_lat + dest_lat) / 2, (source_lon + dest_lon) / 2], zoom_start=12)
|
| 94 |
+
|
| 95 |
+
# Mark Source & Destination
|
| 96 |
+
folium.Marker([source_lat, source_lon], popup=f"๐ Source: {source_area}", icon=folium.Icon(color="green")).add_to(m)
|
| 97 |
+
folium.Marker([dest_lat, dest_lon], popup=f"๐ Destination: {destination_area}", icon=folium.Icon(color="red")).add_to(m)
|
| 98 |
+
|
| 99 |
+
# Draw Route Line
|
| 100 |
+
folium.PolyLine([(source_lat, source_lon), (dest_lat, dest_lon)], color="blue", weight=5, opacity=0.8).add_to(m)
|
| 101 |
|
| 102 |
folium_static(m)
|
| 103 |
|
| 104 |
+
|
| 105 |
+
# --- ๐ Streamlit App Interface ---
|
| 106 |
st.title("๐ Tamil Nadu Bus Tracking & Prediction System")
|
| 107 |
|
| 108 |
+
# --- ๐ Login System ---
|
| 109 |
if "authenticated" not in st.session_state:
|
| 110 |
st.session_state.authenticated = False
|
| 111 |
|
|
|
|
| 115 |
if st.button("Login"):
|
| 116 |
if authenticate(username, password):
|
| 117 |
st.session_state.authenticated = True
|
| 118 |
+
st.success("โ
Login successful!")
|
| 119 |
+
st.rerun()
|
| 120 |
else:
|
| 121 |
+
st.error("โ Invalid username or password")
|
| 122 |
|
| 123 |
+
# --- ๐บ๏ธ Main Content after Login ---
|
| 124 |
if st.session_state.authenticated:
|
| 125 |
+
st.sidebar.header("๐ City, Source & Destination Selection")
|
|
|
|
|
|
|
|
|
|
| 126 |
|
| 127 |
+
city = st.sidebar.selectbox("Select City", df["city"].unique())
|
| 128 |
+
area_df = df[df["city"] == city]
|
| 129 |
+
|
| 130 |
+
# Select Source & Destination Area
|
| 131 |
+
source_area = st.sidebar.selectbox("Select Source Area", area_df["area"].unique())
|
| 132 |
+
destination_area = st.sidebar.selectbox("Select Destination Area", area_df["area"].unique())
|
| 133 |
+
|
| 134 |
+
# --- ๐ Show Bus Details ---
|
| 135 |
+
st.subheader(f"๐ Bus Details for Route: {source_area} โก๏ธ {destination_area} in {city}")
|
| 136 |
+
filtered_df = area_df[(area_df["area"] == source_area) | (area_df["area"] == destination_area)]
|
| 137 |
st.dataframe(filtered_df)
|
| 138 |
|
| 139 |
+
# --- ๐บ๏ธ Show Live Route Map ---
|
| 140 |
+
st.subheader("๐บ๏ธ Live Bus Route Map")
|
| 141 |
+
plot_bus_route(source_area, destination_area, area_df)
|
| 142 |
|
| 143 |
+
# --- ๐ฎ Predict Bus and Same Route Buses ---
|
| 144 |
+
st.subheader("๐ฎ Bus Prediction & Same Route Upcoming Buses")
|
| 145 |
+
if not filtered_df.empty:
|
| 146 |
+
for _, row in filtered_df.iterrows():
|
| 147 |
+
bus_number = row['bus_number']
|
| 148 |
+
prediction = predict_bus_status(bus_number, city, source_area, destination_area)
|
| 149 |
+
st.success(f"๐ฎ Prediction for Bus {bus_number}: {prediction}")
|
|
|
|
| 150 |
|
| 151 |
+
# Predict upcoming buses for same route
|
| 152 |
+
upcoming_buses_info = predict_upcoming_buses(bus_number, city, area_df)
|
| 153 |
+
st.info(upcoming_buses_info)
|
| 154 |
|
| 155 |
+
# --- ๐ Logout Option ---
|
| 156 |
if st.button("Logout"):
|
| 157 |
st.session_state.authenticated = False
|
| 158 |
+
st.rerun()
|