zayeem00 commited on
Commit
6e4fb10
·
verified ·
1 Parent(s): 77af354

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +238 -0
app.py ADDED
@@ -0,0 +1,238 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import streamlit as st
2
+ import pandas as pd
3
+ import numpy as np
4
+ import os
5
+ from pathlib import Path
6
+
7
+ # Print the versions of the packages
8
+ st.write(f"Streamlit version: {st.__version__}")
9
+ st.write(f"Pandas version: {pd.__version__}")
10
+ st.write(f"Numpy version: {np.__version__}")
11
+
12
+ # URLs for the logos
13
+ MAIN_LOGO_URL = "https://islamictrusthk.org/assets/images/top-logo.png"
14
+ SIDEBAR_LOGO_URL = "https://bot.islamictrusthk.org/assets/content_files/20240606095159123011.png"
15
+
16
+ # Configure the page to be mobile-friendly
17
+ st.set_page_config(layout="centered", page_title="Restaurant Data Viewer")
18
+
19
+ # Inject custom CSS for better mobile compatibility
20
+ st.markdown(
21
+ """
22
+ <style>
23
+ /* Adjust font sizes for mobile devices */
24
+ @media (max-width: 600px) {
25
+ .stTextInput, .stMultiSelect {
26
+ font-size: 14px;
27
+ }
28
+ .stDataFrame {
29
+ font-size: 12px;
30
+ }
31
+ .stButton button {
32
+ font-size: 14px;
33
+ }
34
+ }
35
+ </style>
36
+ """,
37
+ unsafe_allow_html=True,
38
+ )
39
+
40
+ # Directory to save uploaded files
41
+ UPLOAD_DIR = "uploaded_files"
42
+ os.makedirs(UPLOAD_DIR, exist_ok=True)
43
+
44
+ # Function to load data
45
+ @st.cache_data
46
+ def load_data(file_path):
47
+ df = pd.read_excel(file_path)
48
+ df.fillna("Not Available", inplace=True)
49
+ return df
50
+
51
+ # Function to convert dataframe to CSV
52
+ def convert_df_to_csv(df):
53
+ return df.to_csv(index=False).encode('utf-8')
54
+
55
+ # Function to format date
56
+ def format_date_column(df, column):
57
+ df[column] = pd.to_datetime(df[column], errors='coerce').dt.date
58
+ return df
59
+
60
+ # Function to verify required columns exist
61
+ def verify_columns(df, required_columns):
62
+ missing_columns = [col for col in required_columns if col not in df.columns]
63
+ return missing_columns
64
+
65
+ # Function to display data in tiles
66
+ def display_tiles(df, cols):
67
+ for i, (_, row) in enumerate(df.iterrows()):
68
+ col = cols[i % len(cols)]
69
+ with col:
70
+ st.markdown(f"**Name:** {row['Name']}")
71
+ st.markdown(f"**Cuisine:** {row['Cuisine']}")
72
+ st.markdown(f"**Location:** {row['Location']}")
73
+ st.markdown(f"**Restaurant Type:** {row['Restaurant Type']}")
74
+ st.markdown(f"**Expiry Date:** {row['Expiry Date']}")
75
+ st.markdown(f"**Website:** {row['Website']}")
76
+ st.markdown(f"**Directions:** {row['Directions']}")
77
+ st.markdown("---")
78
+
79
+ # Initialize session state
80
+ if 'df' not in st.session_state:
81
+ st.session_state.df = None
82
+ if 'authenticated' not in st.session_state:
83
+ st.session_state.authenticated = False
84
+ if 'just_logged_in' not in st.session_state:
85
+ st.session_state.just_logged_in = False
86
+
87
+ # List of valid usernames and passwords
88
+ user_credentials = {
89
+ 'user1': 'password1',
90
+ 'user2': 'password2'
91
+ }
92
+
93
+ # Authentication function
94
+ def authenticate(username, password):
95
+ if username in user_credentials and user_credentials[username] == password:
96
+ return True
97
+ return False
98
+
99
+ # Authentication block
100
+ if not st.session_state.authenticated:
101
+ st.title("Login")
102
+ username = st.text_input("Username")
103
+ password = st.text_input("Password", type="password")
104
+ if st.button("Login"):
105
+ if authenticate(username, password):
106
+ st.session_state.authenticated = True
107
+ st.session_state.just_logged_in = True
108
+ st.experimental_rerun() # Refresh the app to reflect the login state
109
+ else:
110
+ st.error("Invalid username or password")
111
+ elif st.session_state.just_logged_in:
112
+ st.session_state.just_logged_in = False
113
+ st.experimental_rerun()
114
+ else:
115
+ # Sidebar for logo, file upload, and file management
116
+ with st.sidebar:
117
+ st.image(SIDEBAR_LOGO_URL, use_column_width=True)
118
+
119
+ st.title("File Management")
120
+
121
+ # File uploader
122
+ uploaded_file = st.file_uploader("Choose an Excel file", type="xlsx")
123
+
124
+ if uploaded_file:
125
+ try:
126
+ # Save the uploaded file
127
+ file_path = os.path.join(UPLOAD_DIR, uploaded_file.name)
128
+ with open(file_path, "wb") as f:
129
+ f.write(uploaded_file.getbuffer())
130
+
131
+ st.success(f"File '{uploaded_file.name}' uploaded successfully.")
132
+
133
+ df = load_data(file_path)
134
+ st.session_state.df = df
135
+
136
+ except Exception as e:
137
+ st.error(f"An error occurred: {e}")
138
+
139
+ # Manage existing files
140
+ st.subheader("Manage Existing Files")
141
+ existing_files = [f for f in os.listdir(UPLOAD_DIR) if f.endswith(".xlsx")]
142
+ if existing_files:
143
+ selected_file = st.selectbox("Select a file to view or delete", existing_files)
144
+ if st.button("Delete Selected File"):
145
+ os.remove(os.path.join(UPLOAD_DIR, selected_file))
146
+ st.success(f"File '{selected_file}' deleted successfully.")
147
+ st.experimental_rerun() # Refresh the app to reflect changes
148
+
149
+ if st.button("Load Selected File") or st.session_state.df is None:
150
+ try:
151
+ file_path = os.path.join(UPLOAD_DIR, selected_file)
152
+ df = load_data(file_path)
153
+ st.session_state.df = df
154
+ except Exception as e:
155
+ st.error(f"An error occurred: {e}")
156
+ else:
157
+ st.info("No files available.")
158
+
159
+ # Display the main logo
160
+ st.image(MAIN_LOGO_URL, use_column_width=True)
161
+
162
+ st.title("Restaurant Data Viewer")
163
+
164
+ # Display and filter the loaded dataframe if available
165
+ if st.session_state.df is not None:
166
+ df = st.session_state.df
167
+
168
+ # Define required columns
169
+ required_columns = ['Name', 'Cuisine', 'Location', 'Restaurant Type', 'Expiry Date', 'Website', 'Directions']
170
+
171
+ # Verify required columns
172
+ missing_columns = verify_columns(df, required_columns)
173
+ if missing_columns:
174
+ st.error(f"The following required columns are missing from the uploaded file: {', '.join(missing_columns)}")
175
+ else:
176
+ # Format the expiry date column to remove time
177
+ df = format_date_column(df, 'Expiry Date')
178
+
179
+ # Display the dataframe
180
+ st.subheader("Loaded Data")
181
+ st.dataframe(df)
182
+
183
+ # Filter functionality
184
+ st.subheader("Filters")
185
+ # Use columns for a more responsive layout
186
+ col1, col2, col3, col4, col5 = st.columns(5)
187
+
188
+ with col1:
189
+ # Filter by Name
190
+ name_filter = st.text_input("Name contains")
191
+ with col2:
192
+ # Filter by Cuisine
193
+ cuisine_filter = st.multiselect("Cuisine", sorted(df['Cuisine'].unique()))
194
+ with col3:
195
+ # Filter by Location
196
+ location_filter = st.multiselect("Location", df['Location'].unique())
197
+ with col4:
198
+ # Filter by Restaurant Type
199
+ restaurant_type_filter = st.multiselect("Restaurant Type", df['Restaurant Type'].unique())
200
+ with col5:
201
+ # Filter by Expiry Date
202
+ expiry_date_filter = st.date_input("Expiry Date", [])
203
+
204
+ # Apply filters
205
+ filtered_df = df.copy()
206
+
207
+ if name_filter:
208
+ filtered_df = filtered_df[filtered_df['Name'].str.contains(name_filter, case=False, na=False)]
209
+ if cuisine_filter:
210
+ filtered_df = filtered_df[filtered_df['Cuisine'].isin(cuisine_filter)]
211
+ if location_filter:
212
+ filtered_df = filtered_df[filtered_df['Location'].isin(location_filter)]
213
+ if restaurant_type_filter:
214
+ filtered_df = filtered_df[filtered_df['Restaurant Type'].isin(restaurant_type_filter)]
215
+ if expiry_date_filter:
216
+ if len(expiry_date_filter) == 1:
217
+ filtered_df = filtered_df[filtered_df['Expiry Date'] == expiry_date_filter[0]]
218
+ elif len(expiry_date_filter) == 2:
219
+ start_date, end_date = expiry_date_filter
220
+ filtered_df = filtered_df[(filtered_df['Expiry Date'] >= start_date) & (filtered_df['Expiry Date'] <= end_date)]
221
+
222
+ # Display the filtered dataframe in a tile format
223
+ st.subheader("Filtered Data")
224
+ if not filtered_df.empty:
225
+ num_cols = 3 # Number of columns for the tile layout
226
+ cols = st.columns(num_cols)
227
+ display_tiles(filtered_df, cols)
228
+
229
+ # Download button for filtered data
230
+ csv = convert_df_to_csv(filtered_df)
231
+ st.download_button(
232
+ label="Download filtered data as CSV",
233
+ data=csv,
234
+ file_name='filtered_data.csv',
235
+ mime='text/csv',
236
+ )
237
+ else:
238
+ st.info("No data matches the filter criteria.")