vishalkatheriya commited on
Commit
09e0b20
β€’
1 Parent(s): 44fa3c6

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +133 -123
app.py CHANGED
@@ -3,6 +3,8 @@ import time
3
  import random
4
  import psutil
5
  import base64
 
 
6
 
7
  # Set page config
8
  st.set_page_config(page_title="Enhanced Chatbot", layout="wide")
@@ -95,130 +97,20 @@ if 'messages' not in st.session_state:
95
  st.session_state.messages = []
96
  if 'uploaded_file' not in st.session_state:
97
  st.session_state.uploaded_file = None
 
 
98
 
99
- # Sidebar - Left
100
- with st.sidebar:
101
- st.subheader("Chat History")
102
- if st.button("Clear History"):
103
- st.session_state.messages = []
104
-
105
- st.subheader("Recent Conversations")
106
- for i, msg in enumerate(st.session_state.messages[-5:]):
107
- st.text(f"{msg['role'].capitalize()}: {msg['content'][:30]}...")
108
-
109
- # Main layout
110
- col1, col2 = st.columns([3, 1])
111
 
112
- with col1:
113
- st.title("πŸ€– Enhanced Chatbot")
114
-
115
- # Chat container with fixed height and scrolling
116
- chat_container = st.container()
117
-
118
- # Display chat messages
119
- with chat_container:
120
- st.markdown('<div class="chat-container">', unsafe_allow_html=True)
121
- for message in st.session_state.messages:
122
- with st.chat_message(message["role"]):
123
- st.write(message["content"])
124
- if message.get("file"):
125
- file_info = message["file"]
126
- file_type = file_info["type"]
127
- file_name = file_info["name"]
128
-
129
- if file_type.startswith("image/"):
130
- st.image(file_info["data"], caption=file_name, use_column_width=True)
131
- else:
132
- icon = "πŸ“„"
133
- if file_type == "application/pdf":
134
- icon = "πŸ“•"
135
- elif file_type.startswith("audio/"):
136
- icon = "🎡"
137
- elif file_type.startswith("video/"):
138
- icon = "🎬"
139
-
140
- st.markdown(f"""
141
- <div class="file-info">
142
- <span class="file-icon">{icon}</span>
143
- <span>{file_name}</span>
144
- </div>
145
- """, unsafe_allow_html=True)
146
- st.markdown('</div>', unsafe_allow_html=True)
147
 
148
- # Input area
149
- with st.form(key='chat_form'):
150
- user_input = st.text_input("You:", key="user_input")
151
- col1, col2, col3 = st.columns([1, 8, 1])
152
- with col1:
153
- st.markdown("""
154
- <div class="upload-btn-wrapper">
155
- <button class="btn">πŸ“Ž</button>
156
- <input type="file" name="myfile" id="fileUpload" />
157
- </div>
158
- """, unsafe_allow_html=True)
159
- with col2:
160
- submit_button = st.form_submit_button("Send")
161
- with col3:
162
- st.empty()
163
-
164
- # Handle file upload
165
- file_upload_placeholder = st.empty()
166
-
167
- # JavaScript to handle file upload
168
- st.markdown("""
169
- <script>
170
- const fileInput = document.getElementById('fileUpload');
171
- fileInput.addEventListener('change', (event) => {
172
- const file = event.target.files[0];
173
- const reader = new FileReader();
174
- reader.onload = (e) => {
175
- const fileData = e.target.result;
176
- window.parent.postMessage({
177
- type: 'uploadFile',
178
- data: fileData,
179
- name: file.name,
180
- mimeType: file.type
181
- }, '*');
182
- };
183
- reader.readAsDataURL(file);
184
- });
185
- </script>
186
- """, unsafe_allow_html=True)
187
-
188
- # Handle the uploaded file
189
- if st.session_state.uploaded_file:
190
- file_data = st.session_state.uploaded_file["data"]
191
- file_name = st.session_state.uploaded_file["name"]
192
- file_type = st.session_state.uploaded_file["type"]
193
-
194
- st.session_state.messages.append({
195
- "role": "user",
196
- "content": f"Uploaded a file: {file_name}",
197
- "file": {
198
- "name": file_name,
199
- "type": file_type,
200
- "data": file_data
201
- }
202
- })
203
- st.session_state.uploaded_file = None
204
- st.rerun()
205
-
206
- if submit_button and user_input:
207
- st.session_state.messages.append({"role": "user", "content": user_input})
208
-
209
- # Simulate bot response
210
- with st.spinner("Bot is thinking..."):
211
- time.sleep(random.uniform(0.5, 1.5)) # Simulate variable response time
212
- bot_response = f"I understood your message: '{user_input}'. How can I assist you further?"
213
- st.session_state.messages.append({"role": "assistant", "content": bot_response})
214
-
215
- # Clear the input box
216
- st.session_state.user_input = ""
217
-
218
- # Rerun to update the chat display
219
- st.rerun()
220
-
221
- with col2:
222
  st.subheader("System Status")
223
 
224
  # Fetch real CPU usage
@@ -236,14 +128,132 @@ with col2:
236
 
237
  # Add more dynamic elements
238
  st.subheader("Active Users")
239
- active_users = random.randint(50, 200)
240
  st.metric(label="Current Active Users", value=active_users, delta=random.randint(-10, 10))
241
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
242
  # Accessibility considerations
243
  st.markdown("""
244
  <div class="sr-only">
245
  This is a chatbot interface. You can type messages in the input field and press send to chat with the bot.
246
- There's also an option to upload files. The left sidebar shows chat history, and the right column displays system status.
247
  </div>
248
  """, unsafe_allow_html=True)
249
 
 
3
  import random
4
  import psutil
5
  import base64
6
+ import json
7
+ from datetime import datetime
8
 
9
  # Set page config
10
  st.set_page_config(page_title="Enhanced Chatbot", layout="wide")
 
97
  st.session_state.messages = []
98
  if 'uploaded_file' not in st.session_state:
99
  st.session_state.uploaded_file = None
100
+ if 'visitors' not in st.session_state:
101
+ st.session_state.visitors = {}
102
 
103
+ # Function to get visitor IP (simulated in this example)
104
+ def get_visitor_ip():
105
+ return f"192.168.1.{random.randint(1, 255)}"
 
 
 
 
 
 
 
 
 
106
 
107
+ # Update visitor information
108
+ visitor_ip = get_visitor_ip()
109
+ current_time = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
110
+ st.session_state.visitors[visitor_ip] = current_time
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
111
 
112
+ # Sidebar
113
+ with st.sidebar:
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
114
  st.subheader("System Status")
115
 
116
  # Fetch real CPU usage
 
128
 
129
  # Add more dynamic elements
130
  st.subheader("Active Users")
131
+ active_users = len(st.session_state.visitors)
132
  st.metric(label="Current Active Users", value=active_users, delta=random.randint(-10, 10))
133
 
134
+ st.subheader("Chat History")
135
+ if st.button("Clear History"):
136
+ st.session_state.messages = []
137
+
138
+ st.subheader("Recent Conversations")
139
+ for i, msg in enumerate(st.session_state.messages[-5:]):
140
+ st.text(f"{msg['role'].capitalize()}: {msg['content'][:30]}...")
141
+
142
+ # Main layout
143
+ st.title("πŸ€– Enhanced Chatbot")
144
+
145
+ # Chat container with fixed height and scrolling
146
+ chat_container = st.container()
147
+
148
+ # Display chat messages
149
+ with chat_container:
150
+ st.markdown('<div class="chat-container">', unsafe_allow_html=True)
151
+ for message in st.session_state.messages:
152
+ with st.chat_message(message["role"]):
153
+ st.write(message["content"])
154
+ if message.get("file"):
155
+ file_info = message["file"]
156
+ file_type = file_info["type"]
157
+ file_name = file_info["name"]
158
+
159
+ if file_type.startswith("image/"):
160
+ st.image(file_info["data"], caption=file_name, use_column_width=True)
161
+ else:
162
+ icon = "πŸ“„"
163
+ if file_type == "application/pdf":
164
+ icon = "πŸ“•"
165
+ elif file_type.startswith("audio/"):
166
+ icon = "🎡"
167
+ elif file_type.startswith("video/"):
168
+ icon = "🎬"
169
+
170
+ st.markdown(f"""
171
+ <div class="file-info">
172
+ <span class="file-icon">{icon}</span>
173
+ <span>{file_name}</span>
174
+ </div>
175
+ """, unsafe_allow_html=True)
176
+ st.markdown('</div>', unsafe_allow_html=True)
177
+
178
+ # Input area
179
+ with st.form(key='chat_form'):
180
+ user_input = st.text_input("You:", key="user_input")
181
+ col1, col2, col3 = st.columns([1, 8, 1])
182
+ with col1:
183
+ st.markdown("""
184
+ <div class="upload-btn-wrapper">
185
+ <button class="btn">πŸ“Ž</button>
186
+ <input type="file" name="myfile" id="fileUpload" />
187
+ </div>
188
+ """, unsafe_allow_html=True)
189
+ with col2:
190
+ submit_button = st.form_submit_button("Send")
191
+ with col3:
192
+ st.empty()
193
+
194
+ # Handle file upload
195
+ file_upload_placeholder = st.empty()
196
+
197
+ # JavaScript to handle file upload
198
+ st.markdown("""
199
+ <script>
200
+ const fileInput = document.getElementById('fileUpload');
201
+ fileInput.addEventListener('change', (event) => {
202
+ const file = event.target.files[0];
203
+ const reader = new FileReader();
204
+ reader.onload = (e) => {
205
+ const fileData = e.target.result;
206
+ window.parent.postMessage({
207
+ type: 'uploadFile',
208
+ data: fileData,
209
+ name: file.name,
210
+ mimeType: file.type
211
+ }, '*');
212
+ };
213
+ reader.readAsDataURL(file);
214
+ });
215
+ </script>
216
+ """, unsafe_allow_html=True)
217
+
218
+ # Handle the uploaded file
219
+ if st.session_state.uploaded_file:
220
+ file_data = st.session_state.uploaded_file["data"]
221
+ file_name = st.session_state.uploaded_file["name"]
222
+ file_type = st.session_state.uploaded_file["type"]
223
+
224
+ st.session_state.messages.append({
225
+ "role": "user",
226
+ "content": f"Uploaded a file: {file_name}",
227
+ "file": {
228
+ "name": file_name,
229
+ "type": file_type,
230
+ "data": file_data
231
+ }
232
+ })
233
+ st.session_state.uploaded_file = None
234
+ st.rerun()
235
+
236
+ if submit_button and user_input:
237
+ st.session_state.messages.append({"role": "user", "content": user_input})
238
+
239
+ # Simulate bot response
240
+ with st.spinner("Bot is thinking..."):
241
+ time.sleep(random.uniform(0.5, 1.5)) # Simulate variable response time
242
+ bot_response = f"I understood your message: '{user_input}'. How can I assist you further?"
243
+ st.session_state.messages.append({"role": "assistant", "content": bot_response})
244
+
245
+ # Rerun to update the chat display
246
+ st.rerun()
247
+
248
+ # Display visitor information
249
+ st.subheader("Visitor Information")
250
+ st.json(st.session_state.visitors)
251
+
252
  # Accessibility considerations
253
  st.markdown("""
254
  <div class="sr-only">
255
  This is a chatbot interface. You can type messages in the input field and press send to chat with the bot.
256
+ There's also an option to upload files. The sidebar shows system status and chat history.
257
  </div>
258
  """, unsafe_allow_html=True)
259