Muthuraja18 commited on
Commit
b4a460e
·
verified ·
1 Parent(s): 0d3f03f
Files changed (1) hide show
  1. app.py +111 -110
app.py CHANGED
@@ -1,110 +1,111 @@
1
- import streamlit as st
2
- import serial
3
- import time
4
- import folium
5
- from folium.plugins import MarkerCluster
6
- import io
7
- import base64
8
-
9
- # Setup serial connection
10
- arduino_port = "COM3" # Replace with your Arduino port. If necessary, change to a different port.
11
- baud_rate = 9600
12
-
13
- # Check if the port is available before attempting to open it
14
- try:
15
- ser = serial.Serial(arduino_port, baud_rate)
16
- except serial.SerialException as e:
17
- st.error(f"Error: {e}")
18
- st.stop() # Stop the script if the serial connection fails
19
-
20
- # Dummy user credentials (for login)
21
- USER_CREDENTIALS = {
22
- "admin": "password123", # Username: admin, Password: password123
23
- "user1": "mypassword" # Username: user1, Password: mypassword
24
- }
25
-
26
- # Function to display login page
27
- def login_page():
28
- st.title("Bus System Status Monitoring")
29
- st.subheader("Please login to access the system")
30
-
31
- # Input for username and password
32
- username = st.text_input("Username", "")
33
- password = st.text_input("Password", "", type="password")
34
-
35
- # Check if the user submits the login form
36
- if st.button("Login"):
37
- if username in USER_CREDENTIALS and USER_CREDENTIALS[username] == password:
38
- st.success("Login Successful!")
39
- return username # return username to proceed to the monitoring page
40
- else:
41
- st.error("Invalid credentials, please try again.")
42
- return None
43
-
44
- # Function to read data from Arduino (simulating bus data including GPS location)
45
- def read_data_from_arduino():
46
- bus_name = ""
47
- seat_status = ""
48
- distance = 0
49
- latitude = 0.0
50
- longitude = 0.0
51
-
52
- while True:
53
- if ser.in_waiting > 0:
54
- data = ser.readline().decode('utf-8').strip()
55
- if "Bus Name:" in data:
56
- bus_name = data.split("Bus Name: ")[1]
57
- if "Seat Status:" in data:
58
- seat_status = data.split("Seat Status: ")[1]
59
- if "Distance:" in data:
60
- distance = int(data.split("Distance: ")[1])
61
- if "Latitude:" in data:
62
- latitude = float(data.split("Latitude: ")[1])
63
- if "Longitude:" in data:
64
- longitude = float(data.split("Longitude: ")[1])
65
-
66
- # Display data in Streamlit
67
- st.subheader(f"Bus Name: {bus_name}")
68
- st.subheader(f"Seat Status: {seat_status}")
69
- st.subheader(f"Distance to Bus: {distance} cm")
70
- st.subheader(f"Latitude: {latitude}, Longitude: {longitude}")
71
-
72
- # Plot Bus on Map
73
- plot_map(latitude, longitude)
74
-
75
- time.sleep(1) # Delay for 1 second before reading next set of data
76
-
77
- # Function to plot the map with the bus location
78
- def plot_map(latitude, longitude):
79
- # Create a map centered around the bus location
80
- bus_map = folium.Map(location=[latitude, longitude], zoom_start=15)
81
-
82
- # Add a marker for the bus location
83
- folium.Marker([latitude, longitude], popup="Bus Location").add_to(bus_map)
84
-
85
- # Render the map in Streamlit
86
- st.subheader("Real-Time Bus Location")
87
- # Save the map to a PNG image
88
- map_stream = io.BytesIO()
89
- bus_map.save(map_stream, close_file=False)
90
-
91
- # Convert the map to base64 for display in Streamlit
92
- map_stream.seek(0)
93
- map_data = base64.b64encode(map_stream.getvalue()).decode()
94
- st.markdown(f'<img src="data:image/png;base64,{map_data}" width="100%" />', unsafe_allow_html=True)
95
-
96
- # Main function for the Streamlit app
97
- def main():
98
- # Show the login page
99
- username = login_page()
100
-
101
- # If the user is logged in, show the bus system page
102
- if username:
103
- st.write("Loading the Bus System Monitoring Dashboard...")
104
-
105
- # Run the real-time data reading from Arduino
106
- read_data_from_arduino()
107
-
108
- # Run the app
109
- if __name__ == "__main__":
110
- main()
 
 
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 = r"C:\Users\Muthuraja\OneDrive\Attachments\Desktop\second\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
+
75
+ if not st.session_state.authenticated:
76
+ username = st.text_input("Username")
77
+ password = st.text_input("Password", type="password")
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()