Krish-05 commited on
Commit
cfc8c70
ยท
verified ยท
1 Parent(s): b2b9a16

Update src/streamlit_app.py

Browse files
Files changed (1) hide show
  1. src/streamlit_app.py +806 -38
src/streamlit_app.py CHANGED
@@ -1,40 +1,808 @@
1
- import altair as alt
2
- import numpy as np
3
- import pandas as pd
4
  import streamlit as st
 
 
 
 
 
 
5
 
6
- """
7
- # Welcome to Streamlit!
8
-
9
- Edit `/streamlit_app.py` to customize this app to your heart's desire :heart:.
10
- If you have any questions, checkout our [documentation](https://docs.streamlit.io) and [community
11
- forums](https://discuss.streamlit.io).
12
-
13
- In the meantime, below is an example of what you can do with just a few lines of code:
14
- """
15
-
16
- num_points = st.slider("Number of points in spiral", 1, 10000, 1100)
17
- num_turns = st.slider("Number of turns in spiral", 1, 300, 31)
18
-
19
- indices = np.linspace(0, 1, num_points)
20
- theta = 2 * np.pi * num_turns * indices
21
- radius = indices
22
-
23
- x = radius * np.cos(theta)
24
- y = radius * np.sin(theta)
25
-
26
- df = pd.DataFrame({
27
- "x": x,
28
- "y": y,
29
- "idx": indices,
30
- "rand": np.random.randn(num_points),
31
- })
32
-
33
- st.altair_chart(alt.Chart(df, height=700, width=700)
34
- .mark_point(filled=True)
35
- .encode(
36
- x=alt.X("x", axis=None),
37
- y=alt.Y("y", axis=None),
38
- color=alt.Color("idx", legend=None, scale=alt.Scale()),
39
- size=alt.Size("rand", legend=None, scale=alt.Scale(range=[1, 150])),
40
- ))
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
  import streamlit as st
2
+ import requests
3
+ import json
4
+ import os
5
+ from datetime import datetime
6
+ import time
7
+ # For potential small delays to improve UI experience
8
 
9
+ # Import Firebase Admin SDK
10
+ import firebase_admin
11
+ from firebase_admin import credentials, firestore, auth
12
+ from firebase_admin.exceptions import FirebaseError
13
+
14
+ # --- Constants & Environment Variables ---
15
+ APP_ID = os.getenv('__app_id', 'default-app-id')
16
+ FIREBASE_CONFIG_STR = os.getenv('__firebase_config', '{}')
17
+ INITIAL_AUTH_TOKEN = os.getenv('__initial_auth_token', None)
18
+
19
+ OLLAMA_API_BASE_URL = os.getenv("OLLAMA_HOST", "http://localhost:11434")
20
+ OLLAMA_MODEL_NAME = 'krishna_choudhary/AI_Assistant_Chatbot'
21
+ # Your specific model name
22
+
23
+ # --- Firebase Initialization ---
24
+ if not firebase_admin._apps:
25
+ try:
26
+ # Use ApplicationDefault credentials which Canvas environment should provide
27
+ cred = credentials.ApplicationDefault()
28
+ firebase_admin.initialize_app(cred, name=APP_ID)
29
+ st.session_state.db = firestore.client()
30
+ st.session_state.auth = auth
31
+ st.session_state.firebase_initialized = True
32
+ print("Firebase Admin SDK initialized successfully.")
33
+ except Exception as e:
34
+ st.error(f"Error initializing Firebase Admin SDK: {e}")
35
+ st.session_state.firebase_initialized = False
36
+ print(f"Failed to initialize Firebase Admin SDK: {e}")
37
+
38
+ # --- Session State Initialization ---
39
+ if 'current_page' not in st.session_state:
40
+ st.session_state.current_page = 'dashboard'
41
+ if 'messages' not in st.session_state:
42
+ st.session_state.messages = []
43
+ if 'input_message' not in st.session_state:
44
+ st.session_state.input_message = ''
45
+ if 'is_loading' not in st.session_state:
46
+ st.session_state.is_loading = False
47
+ if 'current_chat_id' not in st.session_state:
48
+ st.session_state.current_chat_id = None
49
+ if 'ollama_api_error' not in st.session_state:
50
+ st.session_state.ollama_api_error = None
51
+ if 'user_id' not in st.session_state:
52
+ st.session_state.user_id = None # Will be set after login/signup
53
+ if 'user_email' not in st.session_state:
54
+ st.session_state.user_email = None # Store email for display/auth
55
+ if 'user_name' not in st.session_state:
56
+ st.session_state.user_name = ""
57
+ if 'loaded_user_name' not in st.session_state:
58
+ st.session_state.loaded_user_name = False
59
+ if 'raw_ollama_response' not in st.session_state:
60
+ st.session_state.raw_ollama_response = None # To store full raw response for debug
61
+
62
+ # --- Custom CSS for "Code Mentor AI" Styling ---
63
+ st.markdown(
64
+ """
65
+ <style>
66
+ /* General Styles */
67
+ body {
68
+ color: #E0E0E0;
69
+ background-color: #0F172A;
70
+ }
71
+ .stApp {
72
+ background-color: #0F172A; /* Main app background */
73
+ }
74
+
75
+ /* Main Content Area */
76
+ .main .block-container {
77
+ padding-top: 2rem;
78
+ padding-bottom: 2rem;
79
+ padding-left: 5rem;
80
+ padding-right: 5rem;
81
+ }
82
+
83
+ /* Sidebar Styles */
84
+ [data-testid="stSidebar"] {
85
+ background-color: #1E293B;
86
+ border-right: 1px solid #334155;
87
+ padding-top: 2rem;
88
+ }
89
+ [data-testid="stSidebar"] h2 {
90
+ color: #FFFFFF;
91
+ font-weight: bold;
92
+ text-align: center;
93
+ margin-bottom: 2rem;
94
+ }
95
+ /* Sidebar buttons - selected/active state */
96
+ [data-testid="stSidebar"] .stButton>button {
97
+ background-color: transparent;
98
+ color: #94A3B8;
99
+ border: none;
100
+ width: 100%;
101
+ text-align: left;
102
+ padding: 0.75rem 1rem;
103
+ border-radius: 0.5rem;
104
+ font-size: 1rem;
105
+ display: flex;
106
+ align-items: center;
107
+ gap: 10px; /* Space between icon and text */
108
+ }
109
+ [data-testid="stSidebar"] .stButton>button:hover {
110
+ background-color: #334155;
111
+ color: #FFFFFF;
112
+ }
113
+ /* Streamlit applies an internal class to selected buttons.
114
+ This targets the active button in the sidebar based on session state. */
115
+ .sidebar-button-active {
116
+ background-color: #4A5568 !important; /* Brighter background for active */
117
+ color: #FFFFFF !important;
118
+ font-weight: bold;
119
+ }
120
+
121
+ /* Chat Interface Styles */
122
+ div[data-testid="stVerticalBlock"] > div[data-testid="stVerticalBlock"] > div[data-testid="stVerticalBlock"]:has([data-testid="stChatInput"]) {
123
+ background-color: #1E293B;
124
+ border-radius: 0.75rem;
125
+ padding: 1rem;
126
+ border-top: 1px solid #334155;
127
+ margin-top: 1rem;
128
+ }
129
+ [data-testid="stChatInput"] {
130
+ background-color: transparent !important;
131
+ }
132
+ [data-testid="stChatInput"] input {
133
+ background-color: #2D3748 !important;
134
+ color: #E0E0E0 !important;
135
+ border: 1px solid #4A5568 !important;
136
+ border-radius: 0.5rem !important;
137
+ padding: 0.75rem 1rem;
138
+ }
139
+ [data-testid="stChatMessage"] {
140
+ background-color: #334155;
141
+ border-radius: 0.5rem;
142
+ padding: 1rem;
143
+ margin-bottom: 1rem;
144
+ }
145
+ .st-chat-message-user {
146
+ background-color: #2D3748 !important;
147
+ border: 1px solid #4A5568;
148
+ }
149
+ .st-chat-message-assistant {
150
+ background-color: #1E293B !important;
151
+ border: 1px solid #334155;
152
+ }
153
+ .stCodeBlock {
154
+ background-color: #0F172A !important;
155
+ border: 1px solid #334155 !important;
156
+ border-radius: 0.5rem;
157
+ padding: 1rem;
158
+ overflow-x: auto;
159
+ }
160
+
161
+ /* Custom Cards for Stats */
162
+ .stat-card {
163
+ background-color: #1E293B;
164
+ border-radius: 0.75rem;
165
+ padding: 1.5rem;
166
+ text-align: center;
167
+ border: 1px solid #334155;
168
+ }
169
+ .stat-card h3 {
170
+ color: #94A3B8;
171
+ font-size: 1rem;
172
+ margin-bottom: 0.5rem;
173
+ }
174
+ .stat-card p {
175
+ color: #FFFFFF;
176
+ font-size: 2.5rem;
177
+ font-weight: bold;
178
+ }
179
+
180
+ /* Popular Topics styling */
181
+ .popular-topics-card {
182
+ background-color: #1E293B;
183
+ border-radius: 0.75rem;
184
+ padding: 1.5rem;
185
+ border: 1px solid #334155;
186
+ }
187
+ .popular-topics-card h3 {
188
+ color: #FFFFFF;
189
+ font-size: 1.2rem;
190
+ margin-bottom: 1rem;
191
+ }
192
+ .popular-topics-card ul {
193
+ list-style-type: none;
194
+ padding-left: 0;
195
+ }
196
+ .popular-topics-card li {
197
+ color: #94A3B8;
198
+ padding: 0.25rem 0;
199
+ font-size: 0.95rem;
200
+ }
201
+ .popular-topics-card li::before {
202
+ content: "โฏ ";
203
+ color: #69BFF8;
204
+ font-weight: bold;
205
+ margin-right: 0.5rem;
206
+ }
207
+
208
+ /* Info Box for How to Use */
209
+ .info-box {
210
+ background-color: #2D3748;
211
+ border-left: 5px solid #69BFF8;
212
+ border-radius: 0.5rem;
213
+ padding: 1rem;
214
+ margin-bottom: 1rem;
215
+ color: #E0E0E0;
216
+ }
217
+ .info-box strong {
218
+ color: #FFFFFF;
219
+ }
220
+
221
+ /* Custom Button for "Ask Coding Instructor" */
222
+ .stButton.coding-instructor-button button {
223
+ background-color: #69BFF8;
224
+ color: white;
225
+ font-size: 1.1rem;
226
+ padding: 0.8rem 2rem;
227
+ border-radius: 0.75rem;
228
+ width: 100%;
229
+ margin-top: 1.5rem;
230
+ border: none;
231
+ transition: background-color 0.3s ease;
232
+ }
233
+ .stButton.coding-instructor-button button:hover {
234
+ background-color: #4CAF50;
235
+ }
236
+
237
+ /* Dark mode toggle and profile button in header */
238
+ .header-buttons {
239
+ display: flex;
240
+ justify-content: flex-end;
241
+ gap: 10px;
242
+ margin-bottom: 1rem;
243
+ }
244
+ .header-buttons .stButton>button {
245
+ background-color: #1E293B;
246
+ border: 1px solid #334155;
247
+ color: #94A3B8;
248
+ padding: 0.5rem 1rem;
249
+ border-radius: 0.5rem;
250
+ }
251
+ </style>
252
+ """,
253
+ unsafe_allow_html=True
254
+ )
255
+
256
+
257
+ # --- Firebase Helpers ---
258
+ def get_user_doc_ref(db_client, user_id):
259
+ return db_client.collection(f"artifacts/{APP_ID}/users").document(user_id)
260
+
261
+ def get_chats_collection_ref(db_client, user_id):
262
+ return get_user_doc_ref(db_client, user_id).collection("chats")
263
+
264
+ def get_settings_doc_ref(db_client, user_id):
265
+ return get_user_doc_ref(db_client, user_id).collection("settings").document("userSettings")
266
+
267
+ # --- Authentication Functions ---
268
+ def login_user(username, password):
269
+ if not st.session_state.firebase_initialized:
270
+ st.error("Firebase not initialized.")
271
+ return False
272
+
273
+ email = f"{username}@app.com" # Map username to email for Firebase Auth
274
+ try:
275
+ user = st.session_state.auth.get_user_by_email(email)
276
+ # In a real app, you'd verify the password here securely.
277
+ # Firebase Admin SDK doesn't directly verify passwords from client.
278
+ # This is a SIMULATION for Canvas environment.
279
+ # A real client-side login would use signInWithEmailAndPassword.
280
+
281
+ # For this server-side simulation, if user exists, we assume success.
282
+ # This is INSECURE for production.
283
+ st.session_state.user_id = user.uid
284
+ st.session_state.user_email = user.email
285
+ st.session_state.user_name = username
286
+ st.success(f"Logged in as {username}!")
287
+ st.rerun() # Rerun to update UI
288
+ return True
289
+ except FirebaseError as e:
290
+ if "user-not-found" in str(e):
291
+ st.error("User not found. Please sign up or check your username.")
292
+ else:
293
+ st.error(f"Login failed: {e}")
294
+ return False
295
+ except Exception as e:
296
+ st.error(f"An unexpected error occurred during login: {e}")
297
+ return False
298
+
299
+ def signup_user(username, password):
300
+ if not st.session_state.firebase_initialized:
301
+ st.error("Firebase not initialized.")
302
+ return False
303
+
304
+ email = f"{username}@app.com" # Map username to email for Firebase Auth
305
+ try:
306
+ user = st.session_state.auth.create_user(email=email, password=password)
307
+ st.session_state.user_id = user.uid
308
+ st.session_state.user_email = user.email
309
+ st.session_state.user_name = username
310
+
311
+ # Store username in Firestore settings for display
312
+ settings_doc_ref = get_settings_doc_ref(st.session_state.db, user.uid)
313
+ settings_doc_ref.set({'userName': username}, merge=True)
314
+
315
+ st.success(f"Signed up and logged in as {username}!")
316
+ st.rerun() # Rerun to update UI
317
+ return True
318
+ except FirebaseError as e:
319
+ if "email-already-exists" in str(e):
320
+ st.error("Username already exists. Please log in.")
321
+ elif "invalid-password" in str(e):
322
+ st.error("Password must be at least 6 characters long.")
323
+ else:
324
+ st.error(f"Signup failed: {e}")
325
+ return False
326
+ except Exception as e:
327
+ st.error(f"An unexpected error occurred during signup: {e}")
328
+ return False
329
+
330
+ def logout_user():
331
+ st.session_state.user_id = None
332
+ st.session_state.user_email = None
333
+ st.session_state.user_name = ""
334
+ st.session_state.current_chat_id = None
335
+ st.session_state.messages = []
336
+ st.session_state.ollama_api_error = None
337
+ st.session_state.raw_ollama_response = None
338
+ st.success("Logged out successfully.")
339
+ st.rerun()
340
+
341
+ # --- Functions for Chatbot Logic ---
342
+ def load_chat_messages(chat_id):
343
+ if not st.session_state.firebase_initialized or not st.session_state.user_id or not chat_id:
344
+ return []
345
+ try:
346
+ messages_ref = get_chats_collection_ref(st.session_state.db, st.session_state.user_id).document(chat_id).collection("messages")
347
+ messages_docs = messages_ref.order_by('timestamp').get()
348
+ loaded_messages = []
349
+ for doc in messages_docs:
350
+ data = doc.to_dict()
351
+ if 'timestamp' in data and hasattr(data['timestamp'], 'to_datetime'):
352
+ data['timestamp'] = data['timestamp'].to_datetime()
353
+ loaded_messages.append({'id': doc.id, **data})
354
+ return loaded_messages
355
+ except Exception as e:
356
+ st.error(f"Error loading chat messages: {e}")
357
+ return []
358
+
359
+ def start_new_chat_session():
360
+ if not st.session_state.firebase_initialized or not st.session_state.user_id:
361
+ st.session_state.ollama_api_error = "Database not ready. Cannot start new chat."
362
+ return
363
+
364
+ if not st.session_state.is_loading:
365
+ st.session_state.is_loading = True
366
+ st.session_state.ollama_api_error = None
367
+ st.session_state.input_message = ''
368
+ st.session_state.messages = []
369
+
370
+ try:
371
+ new_chat_ref = get_chats_collection_ref(st.session_state.db, st.session_state.user_id).add({
372
+ 'createdAt': firestore.SERVER_TIMESTAMP,
373
+ 'title': "New Chat"
374
+ })
375
+ st.session_state.current_chat_id = new_chat_ref[1].id
376
+ print(f"New chat session started: {st.session_state.current_chat_id}")
377
+ except Exception as e:
378
+ st.session_state.ollama_api_error = f"Failed to start new chat: {e}"
379
+ print(f"Error starting new chat: {e}")
380
+ finally:
381
+ st.session_state.is_loading = False
382
+ st.rerun()
383
+
384
+ def send_message():
385
+ user_message_content = st.session_state.input_message.strip()
386
+
387
+ if not user_message_content or st.session_state.is_loading:
388
+ return
389
+
390
+ if not st.session_state.firebase_initialized or not st.session_state.user_id:
391
+ st.session_state.ollama_api_error = "Database not ready. Cannot send message. Please log in."
392
+ return
393
+
394
+ st.session_state.is_loading = True
395
+ st.session_state.ollama_api_error = None
396
+
397
+ if not st.session_state.current_chat_id:
398
+ st.session_state.is_loading = False
399
+ start_new_chat_session()
400
+ return
401
+
402
+ chat_messages_ref = get_chats_collection_ref(st.session_state.db, st.session_state.user_id).document(st.session_state.current_chat_id).collection("messages")
403
+
404
+ user_message_data = {
405
+ 'role': 'user',
406
+ 'content': user_message_content,
407
+ 'timestamp': firestore.SERVER_TIMESTAMP,
408
+ }
409
+ try:
410
+ chat_messages_ref.add(user_message_data)
411
+ st.session_state.messages.append({'id': 'temp_user', 'role': 'user', 'content': user_message_content, 'timestamp': datetime.now()})
412
+ st.session_state.input_message = ''
413
+ except Exception as e:
414
+ st.session_state.ollama_api_error = f"Failed to save user message: {e}"
415
+ st.session_state.is_loading = False
416
+ st.rerun()
417
+ return
418
+
419
+ if st.session_state.current_chat_id and st.session_state.messages and len(st.session_state.messages) == 1:
420
+ try:
421
+ get_chats_collection_ref(st.session_state.db, st.session_state.user_id).document(st.session_state.current_chat_id).update({
422
+ 'title': user_message_content[:50] + "..." if len(user_message_content) > 50 else user_message_content
423
+ })
424
+ except Exception as e:
425
+ print(f"Warning: Could not update new chat title: {e}")
426
+
427
+ ollama_messages = [{'role': msg['role'], 'content': msg['content']} for msg in st.session_state.messages]
428
+
429
+ try:
430
+ response = requests.post(
431
+ f'{OLLAMA_API_BASE_URL}/api/chat',
432
+ json={
433
+ 'model': OLLAMA_MODEL_NAME,
434
+ 'messages': ollama_messages,
435
+ 'stream': False,
436
+ 'options': {
437
+ 'temperature': 0.7,
438
+ 'num_predict': 2048, # CRUCIAL: Increased max tokens for full responses
439
+ 'top_p': 0.9,
440
+ },
441
+ },
442
+ timeout=120
443
+ )
444
+ response.raise_for_status()
445
+ result = response.json()
446
+ st.session_state.raw_ollama_response = json.dumps(result, indent=2) # Store raw response
447
+
448
+ assistant_response_content = result.get('message', {}).get('content', "No response from model.")
449
+
450
+ chat_messages_ref.add({
451
+ 'role': 'assistant',
452
+ 'content': assistant_response_content,
453
+ 'timestamp': firestore.SERVER_TIMESTAMP,
454
+ })
455
+ st.session_state.messages.append({'id': 'temp_assistant', 'role': 'assistant', 'content': assistant_response_content, 'timestamp': datetime.now()})
456
+
457
+ except requests.exceptions.Timeout:
458
+ st.session_state.ollama_api_error = "Ollama connection timed out."
459
+ print("Ollama connection timed out.")
460
+ except requests.exceptions.RequestException as e:
461
+ st.session_state.ollama_api_error = f"Ollama connection error: {e}. Is the Ollama server running and accessible?"
462
+ print(f"Ollama connection error: {e}")
463
+ except json.JSONDecodeError:
464
+ st.session_state.ollama_api_error = "Ollama returned an unreadable response. Check server logs."
465
+ print(f"Ollama JSON decode error: {response.text if 'response' in locals() else 'No response'}")
466
+ except Exception as e:
467
+ st.session_state.ollama_api_error = f"An unexpected error occurred: {e}"
468
+ print(f"General Ollama error: {e}")
469
+ finally:
470
+ st.session_state.is_loading = False
471
+ st.rerun()
472
+
473
+ # --- UI Page Components ---
474
+
475
+ def auth_ui():
476
+ st.title("Welcome to Code Mentor AI")
477
+ st.markdown("---")
478
+ st.warning("""
479
+ **Security Warning:** For demonstration purposes, this app uses a simplified username/password login.
480
+ In a production environment, user-facing authentication should be handled by Firebase Client SDK
481
+ or a secure backend API, not directly via Admin SDK in the frontend.
482
+ """)
483
+
484
+ auth_tab = st.tabs(["Login", "Sign Up"])
485
+
486
+ with auth_tab[0]:
487
+ st.subheader("Login")
488
+ with st.form("login_form"):
489
+ login_username = st.text_input("Username", key="login_username_input")
490
+ login_password = st.text_input("Password", type="password", key="login_password_input")
491
+ login_submitted = st.form_submit_button("Login")
492
+
493
+ if login_submitted:
494
+ if login_username and login_password:
495
+ login_user(login_username, login_password)
496
+ else:
497
+ st.error("Please enter both username and password.")
498
+
499
+ with auth_tab[1]:
500
+ st.subheader("Sign Up")
501
+ with st.form("signup_form"):
502
+ signup_username = st.text_input("New Username", key="signup_username_input")
503
+ signup_password = st.text_input("New Password", type="password", key="signup_password_input")
504
+ signup_submitted = st.form_submit_button("Sign Up")
505
+
506
+ if signup_submitted:
507
+ if signup_username and signup_password:
508
+ signup_user(signup_username, signup_password)
509
+ else:
510
+ st.error("Please enter both username and password.")
511
+
512
+ def dashboard_ui():
513
+ # Header buttons (Dark Mode, Profile) - Placeholder functionality
514
+ header_cols = st.columns([0.8, 0.1, 0.1])
515
+ with header_cols[1]:
516
+ st.button("๐ŸŒ™", key="dark_mode_btn", help="Toggle Dark Mode")
517
+ with header_cols[2]:
518
+ if st.button("๐Ÿ‘ค", key="profile_btn", help="User Profile"):
519
+ st.session_state.current_page = 'settings' # Go to settings on profile click
520
+ st.rerun()
521
+
522
+ st.title("Coding Instructor AI")
523
+ st.markdown("---")
524
+
525
+ # --- Popular Topics ---
526
+ st.markdown("""
527
+ <div class="popular-topics-card">
528
+ <h3><span style="color: #F8B400; font-size: 1.2rem;">๐Ÿ’ก</span> Popular Topics</h3>
529
+ <ul>
530
+ <li>JavaScript Closures</li>
531
+ <li>Python Decorators</li>
532
+ <li>React Hooks</li>
533
+ <li>Recursion Patterns</li>
534
+ <li>Async/Await</li>
535
+ </ul>
536
+ </div>
537
+ """, unsafe_allow_html=True)
538
+
539
+ st.markdown("<br>", unsafe_allow_html=True)
540
+
541
+ # --- Stats Cards ---
542
+ col1, col2 = st.columns(2)
543
+ with col1:
544
+ st.markdown('<div class="stat-card"><h3>Questions Solved</h3><p>1,248</p></div>', unsafe_allow_html=True)
545
+ with col2:
546
+ st.markdown('<div class="stat-card"><h3>Languages</h3><p>24</p></div>', unsafe_allow_html=True)
547
+
548
+ st.markdown("<br>", unsafe_allow_html=True)
549
+
550
+ # --- Ask a Coding Question Section ---
551
+ st.subheader("๐Ÿ’ฌ Ask a Coding Question")
552
+
553
+ # How to use info box
554
+ st.markdown("""
555
+ <div class="info-box">
556
+ <strong>โ“˜ How to use:</strong> Ask any coding-related question in any programming language. The AI is specialized to help with coding problems and concepts.
557
+ <br>For non-coding questions, responses may be unpredictable.
558
+ </div>
559
+ """, unsafe_allow_html=True)
560
+
561
+ # Initial load of messages for the current chat ID
562
+ if st.session_state.current_chat_id and not st.session_state.messages:
563
+ with st.spinner("Loading chat..."):
564
+ st.session_state.messages = load_chat_messages(st.session_state.current_chat_id)
565
+ time.sleep(0.5)
566
+
567
+ # Display messages
568
+ chat_container = st.container(height=400, border=False)
569
+ with chat_container:
570
+ if not st.session_state.messages and not st.session_state.is_loading:
571
+ st.session_state.messages.append({"role": "assistant", "content": "How can I help you with your coding questions today?", "timestamp": datetime.now()})
572
+ # No rerun here, let the main loop handle it to avoid infinite reruns on first load
573
+
574
+ for msg in st.session_state.messages:
575
+ message_class = "st-chat-message-user" if msg['role'] == 'user' else "st-chat-message-assistant"
576
+ st.markdown(f'<div class="stChatMessage {message_class}">', unsafe_allow_html=True)
577
+ st.markdown(msg['content'])
578
+ if 'timestamp' in msg and msg['timestamp']:
579
+ st.caption(f"Sent: {msg['timestamp'].strftime('%Y-%m-%d %H:%M:%S')}")
580
+ st.markdown('</div>', unsafe_allow_html=True)
581
+
582
+ if st.session_state.ollama_api_error:
583
+ st.error(st.session_state.ollama_api_error)
584
+
585
+ with st.form("chat_form", clear_on_submit=True):
586
+ user_input = st.text_input(
587
+ "Your Coding Question",
588
+ key="chat_input_text",
589
+ placeholder="e.g., Explain closures in JavaScript. How to implement binary search in Python. What is recursion?",
590
+ disabled=st.session_state.is_loading or not st.session_state.user_id,
591
+ label_visibility="visible"
592
+ )
593
+
594
+ col_send_new = st.columns([1, 1])
595
+ with col_send_new[0]:
596
+ send_button = st.form_submit_button(
597
+ "Ask Coding Instructor",
598
+ disabled=st.session_state.is_loading or not user_input.strip() or not st.session_state.user_id,
599
+ help="Send your coding question to the AI.",
600
+ use_container_width=True
601
+ )
602
+ with col_send_new[1]:
603
+ new_chat_button = st.form_submit_button(
604
+ "Start New Chat",
605
+ disabled=st.session_state.is_loading or not st.session_state.user_id,
606
+ help="Clear current chat and start a new conversation.",
607
+ use_container_width=True
608
+ )
609
+
610
+ if send_button:
611
+ st.session_state.input_message = user_input
612
+ send_message()
613
+ elif new_chat_button:
614
+ start_new_chat_session()
615
+
616
+
617
+ def history_ui():
618
+ st.title("๐Ÿ“œ Chat History")
619
+ st.markdown("---")
620
+ if not st.session_state.firebase_initialized or not st.session_state.user_id:
621
+ st.warning("Database not ready or user not logged in. Cannot load history.")
622
+ return
623
+
624
+ st.write(f"Logged in as: **{st.session_state.user_name}** (User ID: `{st.session_state.user_id}`)")
625
+
626
+ try:
627
+ chats_ref = get_chats_collection_ref(st.session_state.db, st.session_state.user_id)
628
+ chat_docs = chats_ref.order_by('createdAt', direction=firestore.Query.DESCENDING).get()
629
+
630
+ if not chat_docs:
631
+ st.info("No chat sessions found. Start a new chat from the Dashboard!")
632
+ return
633
+
634
+ for chat_doc in chat_docs:
635
+ chat_data = chat_doc.to_dict()
636
+ chat_id = chat_doc.id
637
+ created_at = chat_data.get('createdAt')
638
+ if created_at and hasattr(created_at, 'strftime'):
639
+ created_at_str = created_at.strftime('%Y-%m-%d %H:%M')
640
+ else:
641
+ created_at_str = "Unknown Date"
642
+
643
+ title = chat_data.get('title', f"Chat ({created_at_str})")
644
+
645
+ col_chat, col_delete = st.columns([5, 1])
646
+ with col_chat:
647
+ if st.button(f"**{title}**", key=f"chat_{chat_id}_select", use_container_width=True):
648
+ st.session_state.current_chat_id = chat_id
649
+ st.session_state.messages = load_chat_messages(chat_id)
650
+ st.session_state.current_page = 'dashboard'
651
+ st.rerun()
652
+ with col_delete:
653
+ if st.button("Delete", key=f"chat_{chat_id}_delete", use_container_width=True):
654
+ # Confirmation for deletion
655
+ if st.checkbox(f"Confirm delete '{title}'?", key=f"confirm_del_{chat_id}"):
656
+ delete_chat_and_messages(chat_id, chats_ref)
657
+ st.success(f"Chat '{title}' deleted.")
658
+ st.rerun()
659
+ except Exception as e:
660
+ st.error(f"Error fetching chat history: {e}")
661
+
662
+ def delete_chat_and_messages(chat_id, chats_ref):
663
+ messages_ref = chats_ref.document(chat_id).collection("messages")
664
+ for msg_doc in messages_ref.get():
665
+ msg_doc.reference.delete()
666
+ chats_ref.document(chat_id).delete()
667
+ if st.session_state.current_chat_id == chat_id:
668
+ st.session_state.current_chat_id = None
669
+ st.session_state.messages = []
670
+
671
+
672
+ def tutorials_ui():
673
+ st.title("๐Ÿ“š Tutorials")
674
+ st.markdown("---")
675
+ st.info("This section is under construction. Future updates will include interactive coding tutorials!")
676
+
677
+ def playground_ui():
678
+ st.title("โ–ถ๏ธ Playground")
679
+ st.markdown("---")
680
+ st.info("This section is under construction. Future updates will include a coding playground to test your code.")
681
+
682
+ def settings_ui():
683
+ st.title("โš™๏ธ Settings")
684
+ st.markdown("---")
685
+ if not st.session_state.firebase_initialized or not st.session_state.user_id:
686
+ st.warning("Database not ready or user not logged in. Cannot load/save settings.")
687
+ return
688
+
689
+ settings_doc_ref = get_settings_doc_ref(st.session_state.db, st.session_state.user_id)
690
+
691
+ if not st.session_state.loaded_user_name:
692
+ try:
693
+ settings_snap = settings_doc_ref.get()
694
+ if settings_snap.exists:
695
+ st.session_state.user_name = settings_snap.to_dict().get('userName', '')
696
+ st.session_state.loaded_user_name = True
697
+ except Exception as e:
698
+ st.error(f"Error loading user settings: {e}")
699
+ st.session_state.loaded_user_name = True
700
+
701
+ new_user_name = st.text_input("Your Name:", value=st.session_state.user_name, key="settings_user_name_input")
702
+ if st.button("Save Settings"):
703
+ if new_user_name.strip():
704
+ try:
705
+ settings_doc_ref.set({'userName': new_user_name.strip()}, merge=True)
706
+ st.session_state.user_name = new_user_name.strip()
707
+ st.success("Settings saved successfully!")
708
+ except Exception as e:
709
+ st.error(f"Failed to save settings: {e}")
710
+ else:
711
+ st.warning("User name cannot be empty.")
712
+
713
+ st.info(f"Your current User ID: `{st.session_state.user_id}`")
714
+ if st.session_state.user_email:
715
+ st.info(f"Your associated email: `{st.session_state.user_email}`")
716
+ st.markdown("---")
717
+ st.write("### Authentication Status")
718
+ st.write("For persistent data across sessions, ensure your Hugging Face Space is configured with persistent authentication or link your account.")
719
+ st.write("Currently, the app uses a session-based ID or the `__initial_auth_token` provided by the Canvas environment.")
720
+
721
+ st.button("Logout", on_click=logout_user)
722
+
723
+ st.markdown("---")
724
+ st.write("### Raw Ollama Response (Debug)")
725
+ if st.session_state.raw_ollama_response:
726
+ st.code(st.session_state.raw_ollama_response, language="json")
727
+ else:
728
+ st.info("No raw Ollama response available yet. Send a message in the chat to see it here.")
729
+
730
+
731
+ # --- Main App Navigation and Page Rendering ---
732
+ # Sidebar navigation
733
+ with st.sidebar:
734
+ st.markdown("## ๐Ÿค– Code Mentor AI")
735
+
736
+ if st.session_state.user_id: # Show user name if logged in
737
+ st.markdown(f"<p style='text-align: center; color: #69BFF8; font-weight: bold;'>Welcome, {st.session_state.user_name}!</p>", unsafe_allow_html=True)
738
+
739
+ st.markdown("<br>", unsafe_allow_html=True)
740
+
741
+ def set_page_and_rerun(page_name):
742
+ st.session_state.current_page = page_name
743
+ st.rerun()
744
+
745
+ # Dashboard button
746
+ dashboard_button_class = "sidebar-button-active" if st.session_state.current_page == "dashboard" else ""
747
+ st.markdown(f'<button class="stButton secondary-button {dashboard_button_class}" onclick="window.parent.document.querySelector(\'[data-testid=stSidebar] button[key=sidebar_dashboard]\').click()" key="sidebar_dashboard">๐Ÿ’ฌ Dashboard</button>', unsafe_allow_html=True)
748
+ st.button("Dashboard", on_click=set_page_and_rerun, args=("dashboard",), key="sidebar_dashboard",
749
+ type="secondary", use_container_width=True,
750
+ help="Go to the main dashboard")
751
+
752
+ # History button
753
+ history_button_class = "sidebar-button-active" if st.session_state.current_page == "history" else ""
754
+ st.markdown(f'<button class="stButton secondary-button {history_button_class}" onclick="window.parent.document.querySelector(\'[data-testid=stSidebar] button[key=sidebar_history]\').click()" key="sidebar_history">๐Ÿ“š History</button>', unsafe_allow_html=True)
755
+ st.button("History", on_click=set_page_and_rerun, args=("history",), key="sidebar_history",
756
+ type="secondary", use_container_width=True,
757
+ help="View your past conversations")
758
+
759
+ # Tutorials button
760
+ tutorials_button_class = "sidebar-button-active" if st.session_state.current_page == "tutorials" else ""
761
+ st.markdown(f'<button class="stButton secondary-button {tutorials_button_class}" onclick="window.parent.document.querySelector(\'[data-testid=stSidebar] button[key=sidebar_tutorials]\').click()" key="sidebar_tutorials">๐Ÿ“– Tutorials</button>', unsafe_allow_html=True)
762
+ st.button("Tutorials", on_click=set_page_and_rerun, args=("tutorials",), key="sidebar_tutorials",
763
+ type="secondary", use_container_width=True,
764
+ help="Access coding tutorials")
765
+
766
+ # Playground button
767
+ playground_button_class = "sidebar-button-active" if st.session_state.current_page == "playground" else ""
768
+ st.markdown(f'<button class="stButton secondary-button {playground_button_class}" onclick="window.parent.document.querySelector(\'[data-testid=stSidebar] button[key=sidebar_playground]\').click()" key="sidebar_playground">โ–ถ๏ธ Playground</button>', unsafe_allow_html=True)
769
+ st.button("Playground", on_click=set_page_and_rerun, args=("playground",), key="sidebar_playground",
770
+ type="secondary", use_container_width=True,
771
+ help="Experiment with code snippets")
772
+
773
+ # Settings button
774
+ settings_button_class = "sidebar-button-active" if st.session_state.current_page == "settings" else ""
775
+ st.markdown(f'<button class="stButton secondary-button {settings_button_class}" onclick="window.parent.document.querySelector(\'[data-testid=stSidebar] button[key=sidebar_settings]\').click()" key="sidebar_settings">โš™๏ธ Settings</button>', unsafe_allow_html=True)
776
+ st.button("Settings", on_click=set_page_and_rerun, args=("settings",), key="sidebar_settings",
777
+ type="secondary", use_container_width=True,
778
+ help="Adjust application settings")
779
+
780
+ st.markdown("""
781
+ ---
782
+ <div style="text-align:center; color: #94A3B8; font-size: 0.8rem;">
783
+ Code Mentor AI v2.0<br>
784
+ Powered by Streamlit & Ollama
785
+ </div>
786
+ """, unsafe_allow_html=True)
787
+
788
+
789
+ # Render Current Page based on st.session_state.current_page
790
+ if not st.session_state.user_id:
791
+ auth_ui()
792
+ elif st.session_state.current_page == 'dashboard':
793
+ dashboard_ui()
794
+ elif st.session_state.current_page == 'history':
795
+ history_ui()
796
+ elif st.session_state.current_page == 'tutorials':
797
+ tutorials_ui()
798
+ elif st.session_state.current_page == 'playground':
799
+ playground_ui()
800
+ elif st.session_state.current_page == 'settings':
801
+ settings_ui()
802
+
803
+ # Initial chat session creation on first run if no chat is selected and user is logged in
804
+ if (st.session_state.firebase_initialized and st.session_state.user_id and
805
+ st.session_state.current_page == 'dashboard' and
806
+ not st.session_state.current_chat_id and
807
+ not st.session_state.messages):
808
+ start_new_chat_session()