File size: 21,561 Bytes
459b8b0 b771940 459b8b0 b771940 459b8b0 b771940 459b8b0 b771940 459b8b0 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 |
import streamlit as st
from pymongo import MongoClient
from datetime import datetime, timedelta
from dotenv import load_dotenv
import os
import google.generativeai as genai
from file_upload_vectorize import resources_collection, vectors_collection
# Load environment variables
load_dotenv()
MONGO_URI = os.getenv("MONGO_URI")
client = MongoClient(MONGO_URI)
db = client["novascholar_db"]
live_chat_sessions_collection = db["live_chat_sessions"]
# Initialize AI model
genai.configure(api_key=os.getenv("GEMINI_KEY"))
model = genai.GenerativeModel("gemini-1.5-flash")
def display_live_chat_interface(session, user_id, course_id):
"""Main interface for live chat sessions - handles both faculty and student views"""
st.markdown("<div style='margin-top: 20px;'></div>", unsafe_allow_html=True)
st.markdown("#### In-class Chatbot Session")
# Initialize session states
if 'chat_active' not in st.session_state:
st.session_state.chat_active = False
if 'chat_end_time' not in st.session_state:
st.session_state.chat_end_time = None
if 'messages' not in st.session_state:
st.session_state.messages = []
# Faculty View
if st.session_state.user_type == "faculty":
display_faculty_controls(session, user_id, course_id)
# Student View
else:
display_student_view(session, user_id, course_id)
def create_timer_html(end_time):
"""Create a simplified but reliable timer component"""
end_timestamp = int(end_time.timestamp() * 1000) # Convert to milliseconds
current_timestamp = int(datetime.utcnow().timestamp() * 1000)
return f"""
<div id="timer-container">
<style>
.timer-box {{
background: #f0f2f6;
border-radius: 8px;
padding: 15px;
text-align: center;
margin: 10px 0;
}}
.timer-display {{
font-size: 24px;
font-weight: bold;
color: #0066cc;
margin-bottom: 10px;
}}
.progress-bar {{
width: 100%;
height: 8px;
background: #e0e0e0;
border-radius: 4px;
overflow: hidden;
}}
.progress {{
height: 100%;
background: #00aa00;
transition: width 1s linear;
}}
</style>
<div class="timer-box">
<div id="timer" class="timer-display">Calculating...</div>
<div class="progress-bar">
<div id="progress" class="progress"></div>
</div>
</div>
<script>
function updateTimer() {{
const endTime = {end_timestamp};
const startTime = {current_timestamp};
const now = new Date().getTime();
const totalDuration = endTime - startTime;
const timeLeft = endTime - now;
const timer = document.getElementById('timer');
const progress = document.getElementById('progress');
if (timeLeft <= 0) {{
timer.innerHTML = 'Session Ended';
timer.style.color = '#ff4444';
progress.style.width = '100%';
progress.style.background = '#ff4444';
return;
}}
const minutes = Math.floor(timeLeft / (1000 * 60));
const seconds = Math.floor((timeLeft % (1000 * 60)) / 1000);
const progressWidth = ((totalDuration - timeLeft) / totalDuration) * 100;
timer.innerHTML = `${{minutes}}:${{seconds < 10 ? '0' : ''}}${{seconds}}`;
progress.style.width = `${{progressWidth}}%`;
if (minutes < 5) {{
progress.style.background = '#ffa500';
}}
}}
const timerInterval = setInterval(updateTimer, 1000);
updateTimer();
</script>
</div>
"""
# def display_timer(end_time):
# """Display a simple countdown timer"""
# if not isinstance(end_time, datetime):
# return
# # Calculate remaining time
# remaining_time = end_time - datetime.utcnow()
# if remaining_time.total_seconds() <= 0:
# st.session_state.chat_active = False
# st.session_state.chat_end_time = None
# return
# # Convert to minutes and seconds
# total_seconds = int(remaining_time.total_seconds())
# minutes = total_seconds // 60
# seconds = total_seconds % 60
# # Create a progress value between 0 and 100
# original_duration = st.session_state.get('original_duration', 15) * 60 # default 15 minutes in seconds
# progress = ((original_duration - total_seconds) / original_duration)
# # Display timer using columns for better layout
# col1, col2 = st.columns([1, 28])
# with col1:
# st.markdown("### β±οΈ")
# with col2:
# # Display time remaining
# st.markdown(f"### {minutes:02d}:{seconds:02d}")
# # Display progress bar
# if minutes < 5:
# color = "orange"
# else:
# color = "blue"
# st.progress(progress, text="Session Progress")
def display_timer(end_time):
"""Display a simple countdown timer"""
if not isinstance(end_time, datetime):
return
# Calculate remaining time
remaining_time = end_time - datetime.utcnow()
if remaining_time.total_seconds() <= 0:
st.session_state.chat_active = False
st.session_state.chat_end_time = None
return
# Convert to minutes and seconds
total_seconds = int(remaining_time.total_seconds())
minutes = total_seconds // 60
seconds = total_seconds % 60
# Create a progress value between 0 and 100
original_duration = st.session_state.get('original_duration', 15) * 60 # default 15 minutes in seconds
progress = ((original_duration - total_seconds) / original_duration)
# Custom CSS for timer layout
st.markdown("""
<style>
.timer-container {{
margin: 1rem 0;
}}
.timer-row {{
display: flex;
justify-content: space-between;
align-items: center;
gap: 1rem;
margin-bottom: 0.15rem;
}}
.timer-icon {{
font-size: 1.5rem;
}}
.timer-text {{
font-size: 1.2rem;
font-weight: bold;
}}
.timer-progress-label {{
font-size: 1.1rem;
font-weight: semi-bold;
}}
.stProgress {{
margin-bottom: 0.25rem;
}}
.stChatInputContainer {{
margin-top: 1rem;
}}
</style>
<div class="timer-container">
<div class="timer-row">
<div class="progress-text"><span class="timer-progress-label">Session Progress</span></div>
<div class="timer-progress">
<span class="timer-icon">β±οΈ</span>
<span class="timer-text">{:02d}:{:02d}</span>
</div>
</div>
</div>
""".format(minutes, seconds), unsafe_allow_html=True)
# Display progress bar
color = "orange" if minutes < 5 else "blue"
st.progress(progress)
def display_faculty_controls(session, faculty_id, course_id):
"""Display faculty controls for managing chat sessions"""
# Show scheduled sessions
st.markdown("<div style='margin-top: 20px;'></div>", unsafe_allow_html=True)
st.markdown("##### π
Scheduled Chatbot Sessions")
scheduled_sessions = list(live_chat_sessions_collection.find({
"session_id": session['session_id'],
"status": "scheduled"
}))
# Schedule new session
with st.expander("β Schedule New Chatbot Session"):
col1, col2, col3 = st.columns([2, 2, 1])
with col1:
session_date = st.date_input("π
Date", min_value=datetime.now().date())
with col2:
session_time = st.time_input("π Time", value=datetime.now().time())
with col3:
duration = st.selectbox(
"β±οΈ Duration (mins)",
options=[5, 10, 15, 20, 30, 45, 60],
index=2
)
if st.button("π Schedule Session"):
session_datetime = datetime.combine(session_date, session_time)
if session_datetime < datetime.now():
st.error("β Cannot schedule sessions in the past!")
else:
live_chat_sessions_collection.insert_one({
"session_id": session['session_id'],
"course_id": course_id,
"faculty_id": faculty_id,
"start_time": session_datetime,
"duration": duration,
"status": "scheduled",
"chats": []
})
st.success("β
Chat session scheduled successfully!")
st.rerun()
if scheduled_sessions:
for scheduled in scheduled_sessions:
with st.expander(f"π Scheduled: {scheduled['start_time'].strftime('%I:%M %p')}"):
st.write(f"β±οΈ Duration: {scheduled['duration']} minutes")
if st.button("β Cancel Session", key=f"cancel_{scheduled['_id']}", type="secondary"):
live_chat_sessions_collection.delete_one({"_id": scheduled['_id']})
st.rerun()
# Start immediate session
if not st.session_state.get('chat_active', False):
st.markdown("<div style='margin-top: 20px;'></div>", unsafe_allow_html=True)
st.markdown("##### π― Start an Immediate Session")
col1, col2 = st.columns([3, 1])
with col1:
immediate_duration = st.selectbox(
"β±οΈ Select duration (minutes)",
options=[5, 10, 15, 20, 30, 45, 60],
index=2
)
with col2:
st.markdown("<div style='margin-top: 26px;'>", unsafe_allow_html=True)
if st.button("βΆοΈ Start", use_container_width=True):
st.session_state.chat_active = True
st.session_state.chat_end_time = datetime.utcnow() + timedelta(minutes=immediate_duration)
st.session_state.original_duration = immediate_duration # Store original duration
live_chat_sessions_collection.insert_one({
"session_id": session['session_id'],
"course_id": course_id,
"faculty_id": faculty_id,
"start_time": datetime.utcnow(),
"duration": immediate_duration,
"status": "active",
"chats": []
})
st.rerun()
st.markdown("</div>", unsafe_allow_html=True)
else:
# Show timer for active session
if hasattr(st.session_state, 'chat_end_time'):
display_timer(st.session_state.chat_end_time)
if st.button("βΉοΈ End Session", type="secondary"):
st.session_state.chat_active = False
st.session_state.chat_end_time = None
live_chat_sessions_collection.update_one(
{"session_id": session['session_id'], "status": "active"},
{"$set": {"status": "completed", "end_time": datetime.utcnow()}}
)
st.rerun()
def get_session_context(session, session_id, course_id):
"""Retrieve session context for AI model"""
# Get session data
session = live_chat_sessions_collection.find_one({"session_id": session_id})
if not session:
st.error("Session not found")
return
# Get pre-class materials
context = ""
materials = resources_collection.find({"session_id": session_id})
for material in materials:
resource_id = material['_id']
vector_data = vectors_collection.find_one({"resource_id": resource_id})
if vector_data and 'text' in vector_data:
context += vector_data['text'] + "\n"
courses_collection = db["courses"]
course = courses_collection.find_one({"_id": course_id})
session = courses_collection.find_one({"sessions.session_id": session_id})
if course:
context += f"Course: {course['course_name']}\n"
if session:
context += f"Session: {session['title']}\n"
if 'session_learning_outcomes' in session:
context += f"Session Learning Outcomes: {', '.join(session['session_learning_outcomes'])}\n"
return context
def display_student_view(session, student_id, course_id):
"""Display student interface for chat sessions"""
# Show upcoming scheduled sessions
st.markdown("<div style='margin-top: 20px;'></div>", unsafe_allow_html=True)
st.markdown("##### π
Upcoming Chat Sessions")
upcoming_sessions = list(live_chat_sessions_collection.find({
"session_id": session['session_id'],
"status": "scheduled",
"start_time": {"$gt": datetime.utcnow()}
}).sort("start_time", 1))
if upcoming_sessions:
for upcoming in upcoming_sessions:
with st.expander(f"π {upcoming['start_time'].strftime('%I:%M %p')}"):
st.write(f"β±οΈ Duration: {upcoming['duration']} minutes")
time_until = upcoming['start_time'] - datetime.utcnow()
st.write(f"π Starts in: {time_until.seconds // 3600}h {(time_until.seconds % 3600) // 60}m")
else:
st.info("π No upcoming chat sessions scheduled")
# Check for active session
active_session = live_chat_sessions_collection.find_one({
"session_id": session['session_id'],
"status": "active"
})
# if active_session:
# st.session_state.chat_active = True
# st.session_state.chat_end_time = active_session['start_time'] + timedelta(minutes=active_session['duration'])
if active_session and not st.session_state.get('chat_active', False):
st.session_state.chat_active = True
st.session_state.chat_end_time = active_session['start_time'] + timedelta(minutes=active_session['duration'])
st.session_state.original_duration = active_session['duration']
if st.session_state.get('chat_active', False):
st.markdown("<div style='margin-top: 20px;'></div>", unsafe_allow_html=True)
st.markdown("##### π΄ Live Chat Section")
if hasattr(st.session_state, 'chat_end_time'):
reamining_time = st.session_state.chat_end_time - datetime.utcnow()
if reamining_time.total_seconds() > 0:
display_timer(st.session_state.chat_end_time)
active_session = live_chat_sessions_collection.find_one({
"session_id": session['session_id'],
"status": "active"
})
if active_session:
faculty_id = active_session['faculty_id']
display_chat_interface(session, student_id, course_id, faculty_id)
else:
st.error("β No active session found.")
st.session_state.chat_active = False
st.session_state.chat_end_time = None
else:
st.session_state.chat_active = False
st.session_state.chat_end_time = None
live_chat_sessions_collection.update_one(
{"session_id": session['session_id'], "status": "active"},
{"$set": {"status": "completed", "end_time": datetime.utcnow()}}
)
st.rerun()
def display_chat_interface(session, user_id, course_id, faculty_id):
"""Display the actual chat interface with messages"""
# Display chat messages
# Initialize 'messages' in session_state if it doesn't exist
if 'messages' not in st.session_state:
st.session_state.messages = []
# Chat input
if prompt := st.chat_input("Ask Questions about the Session"):
# Get session context
context = ""
context = get_session_context(session, session['session_id'], course_id)
st.session_state.messages.append({"role": "user", "content": prompt})
# Display user message
with st.chat_message("user"):
st.markdown(prompt)
try:
# Generate AI response
context_prompt = f"""
You are an intelligent teaching assistant participating in a live class discussion.
Session Context:
{context}
Current Question by the Student: {prompt}
Instructions:
1. Provide clear, concise responses that relate to the session's key concepts and learning outcomes
2. Encourage critical thinking and discussion
3. Keep responses focused and relevant to the current topic
4. If students seem confused, provide clarifying examples
Please provide an appropriate response for this live classroom discussion.
"""
response = model.generate_content(context_prompt)
assistant_response = response.text
# Display assistant response
with st.chat_message("assistant"):
st.markdown(assistant_response)
# Save chat message
chat_message = {
"session_id": session['session_id'],
"timestamp": datetime.utcnow(),
"user_id": user_id,
"user_type": st.session_state.user_type,
"message": prompt,
"response": assistant_response
}
st.session_state.messages.append(chat_message)
# chat_messages_collection.insert_one(chat_message)
# Update database
try:
current_session = live_chat_sessions_collection.find_one({"session_id": session['session_id'], "status": "active"})
live_chat_sessions_collection.update_one(
{
"session_id": session['session_id'],
"course_id": course_id,
"faculty_id": faculty_id,
"start_time": current_session['start_time'],
"duration": current_session['duration'],
"status": current_session['status'],
"chats.user_id": user_id
},
{
"$push": {
"chats.$.messages": {
"prompt": prompt,
"response": assistant_response,
"timestamp": datetime.utcnow()
}
}
}
)
# If no existing chat object for the user, create a new one
if live_chat_sessions_collection.find_one({
"session_id": session['session_id'],
"course_id": course_id,
"faculty_id": faculty_id,
"start_time": current_session['start_time'],
"duration": current_session['duration'],
"status": current_session['status'],
"chats.user_id": user_id
}) is None:
live_chat_sessions_collection.update_one(
{
"session_id": session['session_id'],
"course_id": course_id,
"faculty_id": faculty_id,
"start_time": current_session['start_time'],
"duration": current_session['duration'],
"status": current_session['status']
},
{
"$push": {
"chats": {
"user_id": user_id,
"messages": [
{
"prompt": prompt,
"response": assistant_response,
"timestamp": datetime.utcnow()
}
]
}
}
},
upsert=True
)
except Exception as db_error:
st.error(f"Error saving chat history: {str(db_error)}")
except Exception as e:
st.error(f"Error processing message: {str(e)}") |