shukdevdatta123 commited on
Commit
2417560
·
verified ·
1 Parent(s): 34f45f4

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +180 -140
app.py CHANGED
@@ -1,157 +1,197 @@
1
  import streamlit as st
2
  import pandas as pd
3
  import plotly.graph_objects as go
4
- import time
5
 
6
  # Load the Excel file
7
  file_path = 'Dhaka Metro Rail Fare 2.XLSX' # Ensure the correct file path
8
  df = pd.read_excel(file_path)
9
 
10
- # Coordinates for stations (same as in your original code)
11
- coordinates = {
12
- "Uttara North": (23.869066, 90.367445),
13
- "Uttara Center": (23.860118, 90.365106),
14
- "Uttara South": (23.845934, 90.363175),
15
- "Pallabi": (23.82619516961383, 90.36481554252525),
16
- "Mirpur 11": (23.819438208310213, 90.36528532902963),
17
- "Mirpur 10": (23.808582994847285, 90.36821595330717),
18
- "Kazipara": (23.800017952100532, 90.37178261495391),
19
- "Shewrapara": (23.79070140857881, 90.37564622631841),
20
- "Agargaon": (23.778385546736345, 90.3800557456356),
21
- "Bijoy Sarani": (23.766638127271825, 90.38307537134754),
22
- "Farmgate": (23.75923604938459, 90.38694218434738),
23
- "Kawran Bazar": (23.751392319539104, 90.39275707447003),
24
- "Shahbagh": (23.740324209546923, 90.39600784811131),
25
- "Dhaka University": (23.732091083122114, 90.39659408796354),
26
- "Bangladesh Secretariat": (23.73004754106779, 90.40764881366906),
27
- "Motijheel": (23.72816566933198, 90.41923497972823),
28
- "Kamalapur": (23.732367758919807, 90.42547378971085)
29
- }
30
-
31
- # Add latitude and longitude for origin and destination
32
- df['Origin_Lat'] = df['Origin'].map(lambda x: coordinates.get(x, (None, None))[0])
33
- df['Origin_Lon'] = df['Origin'].map(lambda x: coordinates.get(x, (None, None))[1])
34
- df['Destination_Lat'] = df['Destination'].map(lambda x: coordinates.get(x, (None, None))[0])
35
- df['Destination_Lon'] = df['Destination'].map(lambda x: coordinates.get(x, (None, None))[1])
36
-
37
- # Filter rows with missing coordinates
38
- df.dropna(subset=['Origin_Lat', 'Origin_Lon', 'Destination_Lat', 'Destination_Lon'], inplace=True)
39
-
40
- # Streamlit UI setup
41
- st.title("Dhaka Metro Rail Fare Checker 🚇")
42
- st.write("Below is the fare chart for Dhaka Metro Rail 💶:")
43
-
44
- # Dropdown for selecting origin (with "Select Journey from" as a default placeholder)
45
- origin = st.selectbox(
46
- "Select your Location:",
47
- ['Select Journey from'] + df['Origin'].unique().tolist()
48
- )
49
-
50
- # Display buttons for destinations
51
- if origin != 'Select Journey from':
52
- st.write(f"Select your destination(s) from {origin}:")
53
- destinations = st.multiselect("Choose Destinations", df[df['Origin'] == origin]['Destination'].unique().tolist())
54
-
55
- if destinations:
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
56
  # Filter the dataframe based on user selection
57
  fare_data = df[(df['Origin'] == origin) & (df['Destination'].isin(destinations))]
 
 
 
58
  if not fare_data.empty:
59
  for index, row in fare_data.iterrows():
60
  origin_to_dest_fare = row['Fare (৳)']
61
  destination = row['Destination']
62
- st.write(f"Fare from {origin} to {destination}: {origin_to_dest_fare}৳")
63
-
64
- # Map for Dhaka Metro
65
- fig = go.Figure()
66
-
67
- # Define train icon
68
- train_icon = "train" # You can use Plotly's built-in train icon or any other icon if available
69
-
70
- # Add markers for each unique station
71
- unique_stations = pd.concat([df[['Origin', 'Origin_Lat', 'Origin_Lon']].rename(columns={'Origin': 'Station', 'Origin_Lat': 'Lat', 'Origin_Lon': 'Lon'}),
72
- df[['Destination', 'Destination_Lat', 'Destination_Lon']].rename(columns={'Destination': 'Station', 'Destination_Lat': 'Lat', 'Destination_Lon': 'Lon'})]).drop_duplicates()
73
-
74
- # Add markers for stations
75
- for i, row in unique_stations.iterrows():
76
- if row['Station'] == origin:
77
- fig.add_trace(go.Scattermapbox(
78
- mode="markers+text",
79
- lon=[row['Lon']],
80
- lat=[row['Lat']],
81
- marker={'size': 12, 'color': 'green'},
82
- text=row['Station'],
83
- textposition="top center",
84
- name=row['Station']
85
- ))
86
- elif row['Station'] in destinations:
87
- fig.add_trace(go.Scattermapbox(
88
- mode="markers+text",
89
- lon=[row['Lon']],
90
- lat=[row['Lat']],
91
- marker={'size': 12, 'color': 'blue'},
92
- text=row['Station'],
93
- textposition="top center",
94
- name=row['Station']
95
- ))
96
-
97
- # Add animated train movement
98
- train_path = [] # Coordinates for the train's path
99
- for destination in destinations:
100
- destination_row = df[(df['Origin'] == origin) & (df['Destination'] == destination)].iloc[0]
101
- path = [coordinates[origin], (destination_row['Destination_Lat'], destination_row['Destination_Lon'])]
102
- train_path.extend(path)
103
-
104
- # Animation to move the train along the path
105
- for i in range(len(train_path)):
 
 
 
 
 
 
 
 
 
 
 
 
 
 
106
  fig.add_trace(go.Scattermapbox(
107
- mode="markers",
108
- lon=[train_path[i][1]],
109
- lat=[train_path[i][0]],
110
- marker={'size': 20, 'symbol': train_icon, 'color': 'red'},
111
- name="Train",
112
- showlegend=False
 
 
113
  ))
114
 
115
- # Map layout
116
- fig.update_layout(
117
- mapbox=dict(
118
- style="open-street-map",
119
- center=go.layout.mapbox.Center(lat=23.780, lon=90.400),
120
- zoom=11
121
- ),
122
- margin={"r":0,"t":0,"l":0,"b":0},
123
- showlegend=False
124
- )
125
-
126
- # Set up animation frame and delay to move the train
127
- frames = []
128
- for i in range(1, len(train_path)):
129
- frame = go.Frame(
130
- data=[go.Scattermapbox(
131
- mode="markers",
132
- lon=[train_path[i][1]],
133
- lat=[train_path[i][0]],
134
- marker={'size': 20, 'symbol': train_icon, 'color': 'red'},
135
- name="Train"
136
- )],
137
- name=f"Frame_{i}"
138
- )
139
- frames.append(frame)
140
-
141
- fig.frames = frames
142
-
143
- # Animate train movement
144
- fig.update_layout(
145
- updatemenus=[dict(
146
- type="buttons",
147
- showactive=False,
148
- buttons=[dict(
149
- label="Play",
150
- method="animate",
151
- args=[None, dict(frame=dict(duration=2000, redraw=True), fromcurrent=True)]
152
- )]
153
- )]
154
- )
155
-
156
- # Show plot in Streamlit
157
- st.plotly_chart(fig)
 
1
  import streamlit as st
2
  import pandas as pd
3
  import plotly.graph_objects as go
 
4
 
5
  # Load the Excel file
6
  file_path = 'Dhaka Metro Rail Fare 2.XLSX' # Ensure the correct file path
7
  df = pd.read_excel(file_path)
8
 
9
+ # Ensure necessary columns are present
10
+ required_columns = ['Origin', 'Destination', 'Fare (৳)']
11
+ if not all(col in df.columns for col in required_columns):
12
+ st.write("Please ensure the file contains 'Origin', 'Destination', and 'Fare' columns.")
13
+ else:
14
+ # Add coordinates for each station (example coordinates for illustration)
15
+ coordinates = {
16
+ "Uttara North": (23.869066, 90.367445),
17
+ "Uttara Center": (23.860118, 90.365106),
18
+ "Uttara South": (23.845934, 90.363175),
19
+ "Pallabi": (23.82619516961383, 90.36481554252525),
20
+ "Mirpur 11": (23.819438208310213, 90.36528532902963),
21
+ "Mirpur 10": (23.808582994847285, 90.36821595330717),
22
+ "Kazipara": (23.800017952100532, 90.37178261495391),
23
+ "Shewrapara": (23.79070140857881, 90.37564622631841),
24
+ "Agargaon": (23.778385546736345, 90.3800557456356),
25
+ "Bijoy Sarani": (23.766638127271825, 90.38307537134754),
26
+ "Farmgate": (23.75923604938459, 90.38694218434738),
27
+ "Kawran Bazar": (23.751392319539104, 90.39275707447003),
28
+ "Shahbagh": (23.740324209546923, 90.39600784811131),
29
+ "Dhaka University": (23.732091083122114, 90.39659408796354),
30
+ "Bangladesh Secretariat": (23.73004754106779, 90.40764881366906),
31
+ "Motijheel": (23.72816566933198, 90.41923497972823),
32
+ "Kamalapur": (23.732367758919807, 90.42547378971085)
33
+ }
34
+
35
+ # Add latitude and longitude for origin and destination based on the coordinates dictionary
36
+ df['Origin_Lat'] = df['Origin'].map(lambda x: coordinates.get(x, (None, None))[0])
37
+ df['Origin_Lon'] = df['Origin'].map(lambda x: coordinates.get(x, (None, None))[1])
38
+ df['Destination_Lat'] = df['Destination'].map(lambda x: coordinates.get(x, (None, None))[0])
39
+ df['Destination_Lon'] = df['Destination'].map(lambda x: coordinates.get(x, (None, None))[1])
40
+
41
+ # Filter rows with missing coordinates
42
+ df.dropna(subset=['Origin_Lat', 'Origin_Lon', 'Destination_Lat', 'Destination_Lon'], inplace=True)
43
+
44
+ # Streamlit UI setup
45
+ st.title("Dhaka Metro Rail Fare Checker 🚇")
46
+ st.write("Below is the fare chart for Dhaka Metro Rail 💶:")
47
+
48
+ # Instruction sidebar
49
+ st.sidebar.title("Instructions")
50
+ st.sidebar.write("""
51
+ **Welcome to the Dhaka Metro Rail Fare Checker!**
52
+
53
+ *How to use:*
54
+ 1. Select your **Location station** from the dropdown menu.
55
+ 2. Select your **destination(s)** by clicking the destination buttons.
56
+ 3. The fare from your location to the selected destination(s) will be displayed below.
57
+ 4. You can also see the stations marked on a map.
58
+
59
+ **Note:** The map highlights your location in green and destinations in blue.
60
+
61
+ If you face any issues or need further assistance, feel free to [Contact Support on WhatsApp](https://wa.me/+8801719296601).
62
+ """)
63
+
64
+ # Define the default "Select Journey from" message
65
+ default_origin = "Select Journey from"
66
+
67
+ # Dropdown for selecting origin (with "Select Journey from" as a default placeholder)
68
+ origin = st.selectbox(
69
+ "Select your Location:",
70
+ [default_origin] + df['Origin'].unique().tolist(), # Add the "Select Journey from" option at the top
71
+ index=0 # Ensure the first option is selected by default
72
+ )
73
+
74
+ # Initialize session state for destination selection if not already set
75
+ if 'destination_select' not in st.session_state:
76
+ st.session_state.destination_select = []
77
+
78
+ # Display buttons for each destination in 3 columns
79
+ if origin != default_origin:
80
+ st.write(f"Select your destination(s) from {origin}:")
81
+
82
+ # Create 3 columns
83
+ cols = st.columns(3)
84
+
85
+ # Loop through all possible destinations and create a button for each in the columns
86
+ dest_buttons = df['Destination'].unique()
87
+ for i, dest in enumerate(dest_buttons):
88
+ col_idx = i % 3 # Determine column index based on button position
89
+ with cols[col_idx]:
90
+ if st.button(f"Select {dest}", key=f"btn_{dest}"):
91
+ if dest not in st.session_state.destination_select:
92
+ st.session_state.destination_select.append(dest)
93
+ else:
94
+ st.session_state.destination_select.remove(dest)
95
+
96
+ # Clear all selected destinations button
97
+ if st.button("Clear All Destinations"):
98
+ st.session_state.destination_select = []
99
+
100
+ # Display selected destinations and calculate fares
101
+ destinations = st.session_state.destination_select
102
+
103
+ if origin == default_origin:
104
+ st.write("Please select a valid origin station to proceed.")
105
+ elif origin and destinations:
106
  # Filter the dataframe based on user selection
107
  fare_data = df[(df['Origin'] == origin) & (df['Destination'].isin(destinations))]
108
+
109
+ # Display the fare data
110
+ # Display the fare data in a creative and aesthetic format
111
  if not fare_data.empty:
112
  for index, row in fare_data.iterrows():
113
  origin_to_dest_fare = row['Fare (৳)']
114
  destination = row['Destination']
115
+
116
+ # Creative output with icons, emojis, and styled text
117
+ fare_message = f"""
118
+ <div style="background-color: #f0f8ff; padding: 10px; margin-bottom: 12px; border-radius: 8px; box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);">
119
+ <h4 style="font-family: 'Arial', sans-serif; color: #003366;">
120
+ 🚇 <strong>{origin}</strong> to <strong>{destination}</strong> Fare
121
+ </h4>
122
+ <p style="font-family: 'Arial', sans-serif; font-size: 18px; color: #009688;">
123
+ 💵 Fare: <strong style="font-size: 20px; color: #e91e63;">{origin_to_dest_fare}৳</strong>
124
+ </p>
125
+ <p style="font-family: 'Arial', sans-serif; font-size: 14px; color: #555555;">
126
+ ✨ Enjoy your journey on the Dhaka Metro! 🚉
127
+ </p>
128
+ </div>
129
+ """
130
+ st.markdown(fare_message, unsafe_allow_html=True)
131
+ else:
132
+ st.write("No fare data available for the selected origin and destinations.")
133
+ else:
134
+ st.write("Please select both an origin and at least one destination.")
135
+
136
+ st.write("Below is the Map for Dhaka Metro Rail 💶:")
137
+
138
+ # Plotting the map using Plotly
139
+ fig = go.Figure()
140
+
141
+ # Add markers for each unique station
142
+ unique_stations = pd.concat([df[['Origin', 'Origin_Lat', 'Origin_Lon']].rename(columns={'Origin': 'Station', 'Origin_Lat': 'Lat', 'Origin_Lon': 'Lon'}),
143
+ df[['Destination', 'Destination_Lat', 'Destination_Lon']].rename(columns={'Destination': 'Station', 'Destination_Lat': 'Lat', 'Destination_Lon': 'Lon'})]).drop_duplicates()
144
+
145
+ # Add a map marker for each station
146
+ for i, row in unique_stations.iterrows():
147
+ if row['Station'] == origin:
148
+ # Mark the origin as green
149
+ fig.add_trace(go.Scattermapbox(
150
+ mode="markers+text",
151
+ lon=[row['Lon']],
152
+ lat=[row['Lat']],
153
+ marker={'size': 12, 'color': 'green'},
154
+ text=row['Station'],
155
+ textposition="top center",
156
+ name=row['Station'],
157
+ customdata=[row['Station']] # customdata is now a list
158
+ ))
159
+ elif row['Station'] in destinations:
160
+ # Mark the destination as blue
161
+ fig.add_trace(go.Scattermapbox(
162
+ mode="markers+text",
163
+ lon=[row['Lon']],
164
+ lat=[row['Lat']],
165
+ marker={'size': 12, 'color': 'blue'},
166
+ text=row['Station'],
167
+ textposition="top center",
168
+ name=row['Station'],
169
+ customdata=[row['Station']] # customdata is now a list
170
+ ))
171
+ else:
172
+ # Mark all other stations as red
173
  fig.add_trace(go.Scattermapbox(
174
+ mode="markers+text",
175
+ lon=[row['Lon']],
176
+ lat=[row['Lat']],
177
+ marker={'size': 12, 'color': 'red'},
178
+ text=row['Station'],
179
+ textposition="top center",
180
+ name=row['Station'],
181
+ customdata=[row['Station']] # customdata is now a list
182
  ))
183
 
184
+ # Map layout
185
+ fig.update_layout(
186
+ mapbox=dict(
187
+ style="open-street-map",
188
+ center=go.layout.mapbox.Center(lat=23.780, lon=90.400), # Center on Dhaka
189
+ zoom=11
190
+ ),
191
+ margin={"r":0,"t":0,"l":0,"b":0},
192
+ showlegend=False,
193
+ title="Dhaka Metro Rail Location Map"
194
+ )
195
+
196
+ # Show plot in Streamlit
197
+ st.plotly_chart(fig)