Muthuraja18 commited on
Commit
b1b06e6
ยท
verified ยท
1 Parent(s): 5b39ab8
Files changed (1) hide show
  1. app.py +100 -53
app.py CHANGED
@@ -1,74 +1,111 @@
1
- import streamlit as st
2
  import pandas as pd
3
- from datetime import datetime
 
4
  import folium
5
  from streamlit_folium import folium_static
6
  import groq
7
 
8
- # Load bus data
9
- data_path = "pdp.csv"
10
  df = pd.read_csv(data_path)
11
 
12
- # Dummy user credentials
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
- # User login
 
26
  def authenticate(username, password):
 
27
  if username in USER_CREDENTIALS and USER_CREDENTIALS[username] == password:
28
  return True
29
  return False
30
 
31
- # Generate bus prediction using Groq API
32
- def predict_bus_status(bus_number, city, area):
33
- prompt = f"Predict the status and arrival time for bus {bus_number} in {city}, {area}."
 
 
34
  try:
35
  client = groq.Client(api_key=GROQ_API_KEY)
36
  response = client.chat.completions.create(
37
- model="llama3-70b-8192", # Correct model name for Groq # Use Groq's model, adjust if needed
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
- if "latitude" not in area_df.columns or "longitude" not in area_df.columns:
51
- st.error("Latitude and longitude columns missing. Please update CSV.")
52
- return
 
 
 
 
 
 
 
 
 
 
53
 
54
- center_lat = area_df["latitude"].mean()
55
- center_lon = area_df["longitude"].mean()
 
 
 
56
 
57
- m = folium.Map(location=[center_lat, center_lon], zoom_start=12)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
58
 
59
- for _, row in area_df.iterrows():
60
- folium.Marker(
61
- location=[row["latitude"], row["longitude"]],
62
- popup=f"{row['bus_number']} - {row['bus_route']}\nArrival: {row['arrival_time']}\nStatus: {row['status']}",
63
- icon=folium.Icon(color="blue" if row["status"].lower() == "on time" else "red")
64
- ).add_to(m)
 
 
 
 
 
65
 
66
  folium_static(m)
67
 
68
- # Streamlit UI
 
69
  st.title("๐Ÿš Tamil Nadu Bus Tracking & Prediction System")
70
 
71
- # Login form
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
- city = st.selectbox("Select City", df["city"].unique())
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.subheader(f"๐ŸšŒ Bus Details for {city}, {area}")
 
 
 
 
 
 
 
 
 
92
  st.dataframe(filtered_df)
93
 
94
- st.subheader("๐Ÿ—บ๏ธ Bus Map View")
95
- plot_bus_map(filtered_df)
 
96
 
97
- def predict_next_bus(area_df):
98
- now = datetime.now()
99
- upcoming_buses = area_df[area_df["arrival_time"] > now.strftime("%Y-%m-%d %H:%M:%S")]
100
- if not upcoming_buses.empty:
101
- next_bus = upcoming_buses.iloc[0]
102
- prediction = predict_bus_status(next_bus['bus_number'], city, area)
103
- return f"๐Ÿš Next bus: {next_bus['bus_number']} arriving at {next_bus['arrival_time']}\n๐Ÿ”ฎ Prediction: {prediction}"
104
- return "โš ๏ธ No upcoming buses available."
105
 
106
- prediction = predict_next_bus(filtered_df)
107
- st.success(prediction)
 
108
 
 
109
  if st.button("Logout"):
110
  st.session_state.authenticated = False
111
- st.experimental_rerun()
 
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()