Muthuraja18 commited on
Commit
d15b1e2
ยท
verified ยท
1 Parent(s): b517951
Files changed (1) hide show
  1. app.py +50 -22
app.py CHANGED
@@ -5,6 +5,7 @@ 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 = "pdp.csv"
@@ -27,9 +28,7 @@ groq.api_key = GROQ_API_KEY
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 ---
@@ -51,35 +50,49 @@ def predict_bus_status(bus_number, city, source_area, destination_area):
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
 
@@ -92,16 +105,28 @@ def plot_bus_route(source_area, destination_area, area_df):
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
 
@@ -122,8 +147,12 @@ if not st.session_state.authenticated:
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
 
@@ -141,15 +170,14 @@ if st.session_state.authenticated:
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 ---
 
5
  import folium
6
  from streamlit_folium import folium_static
7
  import groq
8
+ import time
9
 
10
  # --- ๐Ÿ“‚ Load Bus Data ---
11
  data_path = "pdp.csv"
 
28
  # --- ๐Ÿ”“ Authenticate User ---
29
  def authenticate(username, password):
30
  """Authenticate user."""
31
+ return USER_CREDENTIALS.get(username) == password
 
 
32
 
33
 
34
  # --- ๐Ÿ”ฎ Predict Bus Status using Groq API ---
 
50
  def add_random_delay(arrival_time_str):
51
  """Add 1 to 10 minutes delay to arrival time."""
52
  try:
 
53
  arrival_time = datetime.strptime(arrival_time_str, "%d-%m-%Y %H:%M")
54
  except ValueError:
 
55
  arrival_time = datetime.strptime(arrival_time_str, "%Y-%m-%d %H:%M:%S")
56
 
57
+ delay_minutes = random.randint(1, 10)
58
  new_arrival_time = arrival_time + timedelta(minutes=delay_minutes)
59
  return new_arrival_time.strftime("%Y-%m-%d %H:%M:%S")
60
 
61
 
62
+ # --- ๐Ÿš Predict Upcoming Buses on Same Route / Nearby Area ---
63
+ def predict_upcoming_buses(bus_number, city, source_area, destination_area, area_df):
64
+ """Predict upcoming buses on the same route or nearby areas."""
65
+ # Filter buses on the same route
66
+ same_route_df = area_df[
67
+ (area_df["bus_route"] == area_df[area_df["bus_number"] == bus_number]["bus_route"].values[0]) &
68
+ (area_df["arrival_time"] > datetime.now().strftime("%Y-%m-%d %H:%M:%S"))
69
+ ]
70
+
71
  if not same_route_df.empty:
72
  upcoming_buses = []
73
  for _, row in same_route_df.iterrows():
74
+ delayed_time = add_random_delay(row['arrival_time'])
75
+ upcoming_buses.append(f"๐ŸšŒ Bus {row['bus_number']} โ†’ {row['bus_route']} arriving at {delayed_time}")
 
76
  return "\n".join(upcoming_buses)
77
+
78
+ # Fallback: Suggest nearby same-area buses
79
+ nearby_buses_df = area_df[
80
+ (area_df["area"] == source_area) | (area_df["area"] == destination_area)
81
+ ]
82
+
83
+ if not nearby_buses_df.empty:
84
+ nearby_buses = []
85
+ for _, row in nearby_buses_df.iterrows():
86
+ delayed_time = add_random_delay(row['arrival_time'])
87
+ nearby_buses.append(f"๐ŸšŒ Nearby Bus {row['bus_number']} โ†’ {row['bus_route']} arriving at {delayed_time}")
88
+ return "\n".join(nearby_buses)
89
+
90
+ return "โš ๏ธ No upcoming buses available for the same route or nearby areas."
91
 
92
 
93
  # --- ๐Ÿ—บ๏ธ Plot Bus Route Map ---
94
  def plot_bus_route(source_area, destination_area, area_df):
95
+ """Plot bus route between source and destination."""
96
  source_df = area_df[area_df["area"] == source_area]
97
  dest_df = area_df[area_df["area"] == destination_area]
98
 
 
105
 
106
  m = folium.Map(location=[(source_lat + dest_lat) / 2, (source_lon + dest_lon) / 2], zoom_start=12)
107
 
 
108
  folium.Marker([source_lat, source_lon], popup=f"๐ŸšŒ Source: {source_area}", icon=folium.Icon(color="green")).add_to(m)
109
  folium.Marker([dest_lat, dest_lon], popup=f"๐Ÿ Destination: {destination_area}", icon=folium.Icon(color="red")).add_to(m)
110
 
 
111
  folium.PolyLine([(source_lat, source_lon), (dest_lat, dest_lon)], color="blue", weight=5, opacity=0.8).add_to(m)
112
 
113
  folium_static(m)
114
 
115
 
116
+ # --- โฐ Stable Real-Time Clock on Top ---
117
+ def update_clock(clock_placeholder):
118
+ """Continuously update and display a real-time clock after login."""
119
+ now = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
120
+ clock_placeholder.markdown(
121
+ f"""
122
+ <h3 style="text-align: center; color: green;">
123
+ โฐ Live Time: {now}
124
+ </h3>
125
+ """,
126
+ unsafe_allow_html=True
127
+ )
128
+
129
+
130
  # --- ๐Ÿš€ Streamlit App Interface ---
131
  st.title("๐Ÿš Tamil Nadu Bus Tracking & Prediction System")
132
 
 
147
 
148
  # --- ๐Ÿ—บ๏ธ Main Content after Login ---
149
  if st.session_state.authenticated:
150
+ # --- โฐ Live Clock after Login ---
151
+ clock_placeholder = st.empty()
152
+ update_clock(clock_placeholder)
153
+
154
  st.sidebar.header("๐ŸŒ† City, Source & Destination Selection")
155
+
156
  city = st.sidebar.selectbox("Select City", df["city"].unique())
157
  area_df = df[df["city"] == city]
158
 
 
170
  plot_bus_route(source_area, destination_area, area_df)
171
 
172
  # --- ๐Ÿ”ฎ Predict Bus and Same Route Buses ---
173
+ st.subheader("๐Ÿ”ฎ Bus Prediction & Same Route/Area Upcoming Buses")
174
  if not filtered_df.empty:
175
  for _, row in filtered_df.iterrows():
176
  bus_number = row['bus_number']
177
  prediction = predict_bus_status(bus_number, city, source_area, destination_area)
178
  st.success(f"๐Ÿ”ฎ Prediction for Bus {bus_number}: {prediction}")
179
 
180
+ upcoming_buses_info = predict_upcoming_buses(bus_number, city, source_area, destination_area, area_df)
 
181
  st.info(upcoming_buses_info)
182
 
183
  # --- ๐Ÿ”“ Logout Option ---