from collections import defaultdict import json import random import requests import streamlit as st from datetime import datetime, timedelta from youtube_transcript_api import YouTubeTranscriptApi from session_page_alt import display_pre_test_results, pre_generate_questions, pre_save_subjective_test, submit_pre_subjective_test from utils.helpers import display_progress_bar, create_notification, format_datetime from file_upload_vectorize import upload_resource, extract_text_from_file, create_vector_store, resources_collection, model, assignment_submit from db import courses_collection2, chat_history_collection, students_collection, faculty_collection, vectors_collection from chatbot import give_chat_response from bson import ObjectId from live_polls import LivePollFeature import pandas as pd import plotly.express as px from dotenv import load_dotenv import os from pymongo import MongoClient from gen_mcqs import generate_mcqs, generate_pre_class_question_bank, get_randomized_questions, save_pre_class_quiz, save_pre_class_quiz_with_bank, save_quiz, quizzes_collection, get_student_quiz_score, submit_quiz_answers from create_course import courses_collection # from pre_class_analytics import NovaScholarAnalytics from pre_class_analytics2 import NovaScholarAnalytics import openai from openai import OpenAI import google.generativeai as genai from google.generativeai import caching from goals2 import GoalAnalyzer from openai import OpenAI import asyncio import numpy as np import re from analytics import derive_analytics, create_embeddings, cosine_similarity from bs4 import BeautifulSoup import streamlit.components.v1 as components from live_chat_feature import display_live_chat_interface from code_playground import display_code_playground from urllib.parse import urlparse, parse_qs from bs4 import BeautifulSoup from rubrics import display_rubrics_tab from subjective_test_evaluation import evaluate_subjective_answers, display_evaluation_to_faculty # Load environment variables load_dotenv() MONGO_URI = os.getenv('MONGO_URI') PERPLEXITY_API_KEY = os.getenv('PERPLEXITY_KEY') OPENAI_API_KEY = os.getenv('OPENAI_KEY') client = MongoClient(MONGO_URI) db = client["novascholar_db"] polls_collection = db["polls"] subjective_tests_collection = db["subjective_tests"] subjective_test_evaluation_collection = db["subjective_test_evaluation"] assignment_evaluation_collection = db["assignment_evaluation"] subjective_tests_collection = db["subjective_tests"] synoptic_store_collection = db["synoptic_store"] assignments_collection = db["assignments"] chat_time_collection = db["chat_time"] # for implementing Context Caching: # PROJECT_ID = "novascholar-446709" # vertexai.init(project=PROJECT_ID, location="us-west4") def get_current_user(): if 'current_user' not in st.session_state: return None return students_collection.find_one({"_id": st.session_state.user_id}) # def display_preclass_content(session, student_id, course_id): """Display pre-class materials for a session""" # Initialize 'messages' in session_state if it doesn't exist if 'messages' not in st.session_state: st.session_state.messages = [] # Display pre-class materials materials = list(resources_collection.find({"course_id": course_id, "session_id": session['session_id']})) st.subheader("Pre-class Materials") if materials: for material in materials: with st.expander(f"{material['file_name']} ({material['material_type'].upper()})"): file_type = material.get('file_type', 'unknown') if file_type == 'application/pdf': st.markdown(f"📑 [Open PDF Document]({material['file_name']})") if st.button("View PDF", key=f"view_pdf_{material['file_name']}"): st.text_area("PDF Content", material['text_content'], height=300) if st.button("Download PDF", key=f"download_pdf_{material['file_name']}"): st.download_button( label="Download PDF", data=material['file_content'], file_name=material['file_name'], mime='application/pdf' ) if st.button("Mark PDF as Read", key=f"pdf_{material['file_name']}"): create_notification("PDF marked as read!", "success") else: st.info("No pre-class materials uploaded by the faculty.") st.subheader("Upload Pre-class Material") # File upload section for students uploaded_file = st.file_uploader("Upload Material", type=['txt', 'pdf', 'docx']) if uploaded_file is not None: with st.spinner("Processing document..."): file_name = uploaded_file.name file_content = extract_text_from_file(uploaded_file) if file_content: material_type = st.selectbox("Select Material Type", ["pdf", "docx", "txt"]) if st.button("Upload Material"): upload_resource(course_id, session['session_id'], file_name, uploaded_file, material_type) # Search for the newly uploaded resource's _id in resources_collection resource_id = resources_collection.find_one({"file_name": file_name})["_id"] create_vector_store(file_content, resource_id) st.success("Material uploaded successfully!") st.subheader("Learn the Topic Using Chatbot") st.write(f"**Session Title:** {session['title']}") st.write(f"**Description:** {session.get('description', 'No description available.')}") # Chatbot interface if prompt := st.chat_input("Ask a question about the session topic"): if len(st.session_state.messages) >= 20: st.warning("Message limit (20) reached for this session.") return st.session_state.messages.append({"role": "user", "content": prompt}) # Display User Message with st.chat_message("user"): st.markdown(prompt) # Get response from chatbot context = "" for material in materials: if 'text_content' in material: context += material['text_content'] + "\n" response = give_chat_response(student_id, session['session_id'], prompt, session['title'], session.get('description', ''), context) st.session_state.messages.append({"role": "assistant", "content": response}) # Display Assistant Response with st.chat_message("assistant"): st.markdown(response) # st.subheader("Your Chat History") # for message in st.session_state.messages: # content = message.get("content", "") # Default to an empty string if "content" is not present # role = message.get("role", "user") # Default to "user" if "role" is not present # with st.chat_message(role): # st.markdown(content) # user = get_current_user() def display_preclass_content(session, student_id, course_id): """Display pre-class materials for a session including external resources""" st.subheader("Pre-class Materials") print("Session ID is: ", session['session_id']) # Display uploaded materials materials = resources_collection.find({"session_id": session['session_id']}) for material in materials: file_type = material.get('file_type', 'unknown') # Handle external resources if file_type == 'external' or file_type == 'video': with st.expander(f"📌 {material['file_name']}"): st.markdown(f"Source: [{material['source_url']}]({material['source_url']})") if material['material_type'].lower() == 'video': # Embed YouTube video if it's a YouTube URL if 'youtube.com' in material['source_url'] or 'youtu.be' in material['source_url']: video_id = extract_youtube_id(material['source_url']) if video_id: st.video(f"https://youtube.com/watch?v={video_id}") if st.button("View Content", key=f"view_external_{material['_id']}"): st.text_area("Extracted Content", material['text_content'], height=300) if st.button("Mark as Read", key=f"external_{material['_id']}"): create_notification(f"{material['material_type']} content marked as read!", "success") # Handle traditional file types else: with st.expander(f"{material['file_name']} ({material['material_type'].upper()})"): if file_type == 'application/pdf': st.markdown(f"📑 [Open PDF Document]({material['file_name']})") if st.button("View PDF", key=f"view_pdf_{material['_id']}"): st.text_area("PDF Content", material['text_content'], height=300) if st.button("Download PDF", key=f"download_pdf_{material['_id']}"): st.download_button( label="Download PDF", data=material['file_content'], file_name=material['file_name'], mime='application/pdf' ) if st.button("Mark PDF as Read", key=f"pdf_{material['_id']}"): create_notification("PDF marked as read!", "success") elif file_type == 'text/plain': st.markdown(f"📄 [Open Text Document]({material['file_name']})") if st.button("View Text", key=f"view_text_{material['_id']}"): st.text_area("Text Content", material['text_content'], height=300) if st.button("Download Text", key=f"download_text_{material['_id']}"): st.download_button( label="Download Text", data=material['file_content'], file_name=material['file_name'], mime='text/plain' ) if st.button("Mark Text as Read", key=f"text_{material['_id']}"): create_notification("Text marked as read!", "success") elif file_type == 'application/vnd.openxmlformats-officedocument.wordprocessingml.document': st.markdown(f"📄 [Open Word Document]({material['file_name']})") if st.button("View Word", key=f"view_word_{material['_id']}"): st.text_area("Word Content", material['text_content'], height=300) if st.button("Download Word", key=f"download_word_{material['_id']}"): st.download_button( label="Download Word", data=material['file_content'], file_name=material['file_name'], mime='application/vnd.openxmlformats-officedocument.wordprocessingml.document' ) if st.button("Mark Word as Read", key=f"word_{material['_id']}"): create_notification("Word document marked as read!", "success") elif file_type == 'application/vnd.openxmlformats-officedocument.presentationml.presentation': st.markdown(f"📊 [Open PowerPoint Presentation]({material['file_name']})") if st.button("View PowerPoint", key=f"view_pptx_{material['_id']}"): st.text_area("PowerPoint Content", material['text_content'], height=300) if st.button("Download PowerPoint", key=f"download_pptx_{material['_id']}"): st.download_button( label="Download PowerPoint", data=material['file_content'], file_name=material['file_name'], mime='application/vnd.openxmlformats-officedocument.presentationml.presentation' ) if st.button("Mark PowerPoint as Read", key=f"pptx_{material['_id']}"): create_notification("PowerPoint presentation marked as read!", "success") elif file_type == 'web_resource': # Display resource details st.markdown(f"**Type:** {material['material_type']}") if material.get('description'): st.markdown(f"**Description:** {material['description']}") # Display resource link st.markdown(f"**Resource Link:** [{material['file_name']}]({material['source_url']})") # Add "Open in New Tab" button if st.button("Open in New Tab", key=f"open_{material['_id']}"): # Use JavaScript to open in new tab st.markdown(f""" """, unsafe_allow_html=True) # Add "Mark as Read" functionality if st.button("Mark as Read", key=f"read_{material['_id']}"): create_notification(f"{material['material_type']} marked as read!", "success") # Initialize 'messages' in session_state if it doesn't exist if 'messages' not in st.session_state: st.session_state.messages = [] # Chat input # Add a check, if materials are available, only then show the chat input # if(st.session_state.user_type == "student"): # if materials: # if prompt := st.chat_input("Ask a question about Pre-class Materials"): # # if len(st.session_state.messages) >= 20: # # st.warning("Message limit (20) reached for this session.") # # return # st.session_state.messages.append({"role": "user", "content": prompt}) # # Display User Message # with st.chat_message("user"): # st.markdown(prompt) # # Get document context # context = "" # print("Session ID is: ", session['session_id']) # materials = resources_collection.find({"session_id": session['session_id']}) # print(materials) # context = "" # vector_data = None # # for material in materials: # # print(material) # context = "" # for material in materials: # resource_id = material['_id'] # print("Supposed Resource ID is: ", resource_id) # vector_data = vectors_collection.find_one({"resource_id": resource_id}) # # print(vector_data) # if vector_data and 'text' in vector_data: # context += vector_data['text'] + "\n" # if not vector_data: # st.error("No Pre-class materials found for this session.") # return # try: # # Generate response using Gemini # # context_prompt = f""" # # Based on the following context, answer the user's question: # # Context: # # {context} # # Question: {prompt} # # Please provide a clear and concise answer based only on the information provided in the context. # # """ # # context_prompt = f""" # # You are a highly intelligent and resourceful assistant capable of synthesizing information from the provided context. # # Context: # # {context} # # Instructions: # # 1. Base your answers primarily on the given context. # # 2. If the answer to the user's question is not explicitly in the context but can be inferred or synthesized from the information provided, do so thoughtfully. # # 3. Only use external knowledge or web assistance when: # # - The context lacks sufficient information, and # # - The question requires knowledge beyond what can be reasonably inferred from the context. # # 4. Clearly state if you are relying on web assistance for any part of your answer. # # 5. Do not respond with a negative. If the answer is not in the context, provide a thoughtful response based on the information available on the web about it. # # Question: {prompt} # # Please provide a clear and comprehensive answer based on the above instructions. # # """ # context_prompt = f""" # You are a highly intelligent and resourceful assistant capable of synthesizing information from the provided context and external sources. # Context: # {context} # Instructions: # 1. Base your answers on the provided context wherever possible. # 2. If the answer to the user's question is not explicitly in the context: # - Use external knowledge or web assistance to provide a clear and accurate response. # 3. Do not respond negatively. If the answer is not in the context, use web assistance or your knowledge to generate a thoughtful response. # 4. Clearly state if part of your response relies on web assistance. # Question: {prompt} # Please provide a clear and comprehensive answer based on the above instructions. # """ # response = model.generate_content(context_prompt) # if not response or not response.text: # st.error("No response received from the model") # return # assistant_response = response.text # # Display Assistant Response # with st.chat_message("assistant"): # st.markdown(assistant_response) # # Build the message # new_message = { # "prompt": prompt, # "response": assistant_response, # "timestamp": datetime.utcnow() # } # st.session_state.messages.append(new_message) # # Update database # try: # chat_history_collection.update_one( # { # "user_id": student_id, # "session_id": session['session_id'] # }, # { # "$push": {"messages": new_message}, # "$setOnInsert": { # "user_id": student_id, # "session_id": session['session_id'], # "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 generating response: {str(e)}") if 'chat_session_active' not in st.session_state: st.session_state.chat_session_active = False if 'chat_session_start' not in st.session_state: st.session_state.chat_session_start = None # Chat input # Add a check, if materials are available, only then show the chat input if st.session_state.user_type == "student": if materials: # Start chat session button chat_time = chat_time_collection.find_one( {"session_id": session["session_id"], "user_id": student_id, "course_id": course_id} ) # Calculate session status and time remaining current_time = datetime.now() chat_active = False time_remaining = None if chat_time and "start_time" in chat_time: session_end_time = chat_time["start_time"] + timedelta(minutes=20) time_remaining = session_end_time - current_time chat_active = time_remaining.total_seconds() > 0 # Display appropriate interface based on session status if not chat_time or "start_time" not in chat_time: # New session case if st.button("Start Chat Session (20 minutes)"): st.session_state.chat_session_start = current_time st.session_state.chat_session_active = True # Update database chat_time_collection.update_one( { "session_id": session["session_id"], "user_id": student_id, "course_id": course_id }, { "$set": { "start_time": current_time, "end_time": current_time + timedelta(minutes=20) } }, upsert=True ) st.rerun() elif chat_active: # Active session case minutes = int(time_remaining.total_seconds() // 60) seconds = int(time_remaining.total_seconds() % 60) st.info(f"⏱️ Time remaining: {minutes:02d}:{seconds:02d}") # Show chat input if prompt := st.chat_input("Ask a question about Pre-class Materials"): st.session_state.messages.append({"role": "user", "content": prompt}) # Display User Message with st.chat_message("user"): st.markdown(prompt) try: context = get_chat_context(session['session_id']) try: context_prompt = f""" You are a highly intelligent and resourceful assistant capable of synthesizing information from the provided context and external sources. Context: {context} Instructions: 1. Base your answers on the provided context wherever possible. 2. If the answer to the user's question is not explicitly in the context: - Use external knowledge or web assistance to provide a clear and accurate response. 3. Do not respond negatively. If the answer is not in the context, use web assistance or your knowledge to generate a thoughtful response. 4. Clearly state if part of your response relies on web assistance. Question: {prompt} Please provide a clear and comprehensive answer based on the above instructions. """ response = model.generate_content(context_prompt) if not response or not response.text: st.error("No response received from the model") return assistant_response = response.text # Display Assistant Response with st.chat_message("assistant"): st.markdown(assistant_response) # Build the message new_message = { "prompt": prompt, "response": assistant_response, "timestamp": datetime.utcnow(), } st.session_state.messages.append(new_message) # Update database try: chat_history_collection.update_one( { "user_id": student_id, "session_id": session["session_id"], }, { "$push": {"messages": new_message}, "$setOnInsert": { "user_id": student_id, "session_id": session["session_id"], "timestamp": datetime.utcnow(), }, }, upsert=True, ) chat_time_collection.update_one( {"session_id": session["session_id"], "user_id": student_id, "course_id": course_id}, {"$set": {"end_time": datetime.now()}}, 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 generating response: {str(e)}") except Exception as e: st.error(f"Error processing message: {str(e)}") else: # Expired session case st.info("Chat session has ended. Time limit (20 minutes) reached.") else: st.subheader("Upload Pre-class Material") # File upload section for students uploaded_file = st.file_uploader("Upload Material", type=['txt', 'pdf', 'docx']) if uploaded_file is not None: with st.spinner("Processing document..."): file_name = uploaded_file.name file_content = extract_text_from_file(uploaded_file) if file_content: material_type = st.selectbox("Select Material Type", ["pdf", "docx", "txt"]) if st.button("Upload Material"): upload_resource(course_id, session['session_id'], file_name, uploaded_file, material_type) # print("Resource ID is: ", resource_id) # Search for the newly uploaded resource's _id in resources_collection # resource_id = resources_collection.find_one({"file_name": file_name})["_id"] st.success("Material uploaded successfully!") # st.experimental_rerun() # st.subheader("Your Chat History") if st.button("View Chat History"): # Initialize chat messages from database if 'messages' not in st.session_state or not st.session_state.messages: existing_chat = chat_history_collection.find_one({ "user_id": student_id, "session_id": session['session_id'] }) if existing_chat and 'messages' in existing_chat: st.session_state.messages = existing_chat['messages'] else: st.session_state.messages = [] # Display existing chat history try: for message in st.session_state.messages: if 'prompt' in message and 'response' in message: with st.chat_message("user"): st.markdown(message["prompt"]) with st.chat_message("assistant"): st.markdown(message["response"]) except Exception as e: st.error(f"Error displaying chat history: {str(e)}") st.session_state.messages = [] if st.session_state.user_type == 'student': display_pre_subjective_test_tab(student_id, course_id, session["session_id"]) st.subheader("Create a Practice Quiz") questions = [] quiz_id = "" with st.form("create_quiz_form"): num_questions = st.number_input("Number of Questions", min_value=1, max_value=20, value=2) submit_quiz = st.form_submit_button("Generate Quiz") if submit_quiz: # Get pre-class materials from resources_collection materials = resources_collection.find({"session_id": session['session_id']}) context = "" for material in materials: if 'text_content' in material: context += material['text_content'] + "\n" if not context: st.error("No pre-class materials found for this session.") return # Generate MCQs from context questions = generate_mcqs(context, num_questions, session['title'], session.get('description', '')) if questions: quiz_id = save_quiz(course_id, session['session_id'], "Practice Quiz", questions, student_id) if quiz_id: st.success("Quiz saved successfully!") st.session_state.show_quizzes = True else: st.error("Error saving quiz.") else: st.error("Error generating questions.") # # if st.button("Attempt Practice Quizzes "): # # quizzes = list(quizzes_collection.find({"course_id": course_id, "session_id": session['session_id'], "user_id": student_id})) # if getattr(st.session_state, 'show_quizzes', False): # # quiz = quizzes_collection.find_one({"course_id": course_id, "session_id": session['session_id'], "user_id": student_id}) # quiz = quizzes_collection.find_one( # {"course_id": course_id, "session_id": session['session_id'], "user_id": student_id}, # sort=[("created_at", -1)] # ) # if not quiz: # st.info("No practice quizzes created.") # else: # with st.expander(f"📝 Practice Quiz", expanded=False): # # Check if student has already taken this quiz # existing_score = get_student_quiz_score(quiz['_id'], student_id) # if existing_score is not None: # st.success(f"Quiz completed! Your score: {existing_score:.1f}%") # # Display correct answers after submission # st.subheader("Quiz Review") # for i, question in enumerate(quiz['questions']): # st.markdown(f"**Question {i+1}:** {question['question']}") # for opt in question['options']: # if opt.startswith(question['correct_option']): # st.markdown(f"✅ {opt}") # else: # st.markdown(f"- {opt}") # else: # # Initialize quiz state for this specific quiz # quiz_key = f"quiz_{quiz['_id']}_student_{student_id}" # if quiz_key not in st.session_state: # st.session_state[quiz_key] = { # 'submitted': False, # 'score': None, # 'answers': {} # } # # If quiz was just submitted, show the results # if st.session_state[quiz_key]['submitted']: # st.success(f"Quiz submitted successfully! Your score: {st.session_state[quiz_key]['score']:.1f}%") # # Reset the quiz state # st.session_state[quiz_key]['submitted'] = False # # Display quiz questions # st.write("Please select your answers:") # # Create a form for quiz submission # form_key = f"quiz_form_{quiz['_id']}_student_{student_id}" # with st.form(key=form_key): # student_answers = {} # for i, question in enumerate(quiz['questions']): # st.markdown(f"**Question {i+1}:** {question['question']}") # options = [opt for opt in question['options']] # # student_answers[str(i)] = st.radio( # # f"Select answer for question {i+1}:", # # options=options, # # key=f"q_{i}", # # index=None # # ) # answer = st.radio( # f"Select answer for question {i+1}:", # options=options, # key=f"{quiz['_id']}_{i}", # Simplify the radio button key # index=None # ) # if answer: # Only add to answers if a selection was made # student_answers[str(i)] = answer # # Submit button # # submitted = st.form_submit_button("Submit Quiz") # print("Before the submit button") # submit_button = st.form_submit_button("Submit Quiz") # print("After the submit button") # if submit_button and student_answers: # print("Clicked the button") # print(student_answers) # correct_answers = 0 # for i, question in enumerate(quiz['questions']): # if student_answers[str(i)] == question['correct_option']: # correct_answers += 1 # score = (correct_answers / len(quiz['questions'])) * 100 # if score is not None: # st.success(f"Quiz submitted successfully! Your score: {score:.1f}%") # st.session_state[quiz_key]['submitted'] = True # st.session_state[quiz_key]['score'] = score # st.session_state[quiz_key]['answers'] = student_answers # # This will trigger a rerun, but now we'll handle it properly # st.rerun() # else: # st.error("Error submitting quiz. Please try again.") # # correct_answers = 0 # # for i, question in enumerate(quiz['questions']): # # if student_answers[str(i)] == question['correct_option']: # # correct_answers += 1 # # score = (correct_answers / len(quiz['questions'])) * 100 # # print(score) # # try: # # quizzes_collection.update_one( # # {"_id": quiz['_id']}, # # {"$push": {"submissions": {"student_id": student_id, "score": score}}} # # ) # # st.success(f"Quiz submitted successfully! Your score: {score:.1f}%") # # except Exception as db_error: # # st.error(f"Error saving submission: {str(db_error)}") if getattr(st.session_state, 'show_quizzes', False): quiz = quizzes_collection.find_one( { "course_id": course_id, "session_id": session['session_id'], "user_id": student_id }, sort=[("created_at", -1)] ) if not quiz: st.info("No practice quizzes created.") else: with st.expander(f"📝 Practice Quiz", expanded=True): existing_score = get_student_quiz_score(quiz['_id'], student_id) if existing_score is not None: st.success(f"Quiz completed! Your score: {existing_score:.1f}%") # Show review st.subheader("Quiz Review") for i, question in enumerate(quiz['questions']): st.markdown(f"**Q{i+1}:** {question['question']}") for opt in question['options']: if opt == question['correct_option']: st.markdown(f"✅ {opt}") else: st.markdown(f"- {opt}") else: with st.form(key=f"quiz_form_{quiz['_id']}"): student_answers = {} for i, question in enumerate(quiz['questions']): st.markdown(f"**Q{i+1}:** {question['question']}") options = question['options'] answer = st.radio( f"Select answer:", options=options, key=f"q_{quiz['_id']}_{i}", index=None ) if answer: student_answers[str(i)] = answer submit_button = st.form_submit_button("Submit Quiz") if submit_button: if len(student_answers) != len(quiz['questions']): st.error("Please answer all questions before submitting.") else: # Calculate score correct_answers = 0 total_questions = len(quiz['questions']) for q_idx, question in enumerate(quiz['questions']): student_answer = student_answers.get(str(q_idx)) correct_option = question['correct_option'] if student_answer == correct_option: correct_answers += 1 score = (correct_answers / total_questions) * 100 # Save submission to database try: result = quizzes_collection.update_one( {"_id": quiz['_id']}, { "$push": { "submissions": { "student_id": student_id, "answers": student_answers, "score": score, "submitted_at": datetime.utcnow() } } } ) if result.modified_count > 0: st.success(f"Quiz submitted successfully! Score: {score:.1f}%") st.rerun() else: st.error("Error saving submission. Please try again.") except Exception as e: st.error(f"Database error: {str(e)}") display_pre_class_quiz_tab(student_id, course_id, session["session_id"]) def display_pre_class_quiz_tab(student_id, course_id, session_id): """Display pre-class quizzes for students""" st.markdown("### Pre-class Quizzes") quizzes = quizzes_collection.find({ "course_id": course_id, "session_id": session_id, "status": "active", "quiz_type": "pre_class" }) # Get available quizzes # quizzes = quizzes_collection.find({ # "course_id": course_id, # "session_id": session_id, # "status": "active" # }) quizzes = list(quizzes) if not quizzes: st.info("No pre-class quizzes available.") return for quiz in quizzes: with st.expander(f"📝 {quiz['title']}", expanded=True): # Check if already taken existing_score = get_student_quiz_score(quiz["_id"], student_id) if existing_score is not None: st.success(f"Quiz completed! Score: {existing_score:.1f}%") # Show review st.markdown("#### Quiz Review") submission = next( (sub for sub in quiz["submissions"] if sub["student_id"] == student_id), None ) # for i, question in enumerate(quiz["questions"]): # st.markdown(f"**Q{i+1}:** {question['question']}") # for opt in question["options"]: # if opt.startswith(question["correct_option"]): # st.markdown(f"✅ {opt}") # else: # st.markdown(f"- {opt}") if submission: questions = submission.get("allocated_questions", []) answers = submission.get("answers", {}) for i, question in enumerate(questions): st.markdown(f"**Q{i+1}:** {question['question']}") for opt in question["options"]: if opt == question["correct_option"]: st.markdown(f"✅ {opt}") elif opt == answers.get(str(i)): st.markdown(f"❌ {opt}") else: st.markdown(f"- {opt}") else: # # Check time remaining # start_time = quiz.get('start_time') # if not start_time: # if st.button("Start Quiz", key=f"start_{quiz['_id']}"): # quizzes_collection.update_one( # {"_id": quiz["_id"]}, # {"$set": {"start_time": datetime.now()}} # ) # st.rerun() # Start quiz flow quiz_state = quizzes_collection.find_one({ "_id": quiz["_id"], "student_states.student_id": student_id }) if not quiz_state or "student_states" not in quiz_state: # Not started yet if st.button("Start Quiz", key=f"start_{quiz['_id']}"): # Get random questions questions = get_randomized_questions(quiz["_id"]) if questions: # Save allocated questions and start time result = quizzes_collection.update_one( {"_id": quiz["_id"]}, { "$push": { "student_states": { "student_id": student_id, "allocated_questions": questions, "start_time": datetime.now(), "completed": False } } } ) if result.modified_count > 0: st.rerun() else: st.error("Error getting quiz questions") else: # Quiz already started student_state = next( (state for state in quiz_state["student_states"] if state["student_id"] == student_id), None ) if student_state: start_time = student_state["start_time"] time_remaining = (start_time + timedelta(minutes=quiz['duration_minutes'])) - datetime.now() if time_remaining.total_seconds() > 0: st.info(f"Time remaining: {int(time_remaining.total_seconds() // 60)}:{int(time_remaining.total_seconds() % 60):02d}") # Display questions questions = student_state["allocated_questions"] with st.form(f"pre_class_quiz_{quiz['_id']}"): student_answers = {} for i, question in enumerate(questions): st.markdown(f"**Q{i+1}:** {question['question']}") options = question["options"] answer = st.radio( "Select answer:", options=options, key=f"q_{quiz['_id']}_{i}" ) if answer: student_answers[str(i)] = answer if st.form_submit_button("Submit Quiz"): if len(student_answers) != len(questions): st.error("Please answer all questions before submitting.") else: # Calculate score correct_answers = 0 for i, question in enumerate(questions): if student_answers.get(str(i)) == question["correct_option"]: correct_answers += 1 score = (correct_answers / len(questions)) * 100 # Save submission result = quizzes_collection.update_one( {"_id": quiz["_id"]}, { "$push": { "submissions": { "student_id": student_id, "allocated_questions": questions, "answers": student_answers, "score": score, "submitted_at": datetime.now() } }, "$set": { "student_states.$[state].completed": True } }, array_filters=[ {"state.student_id": student_id} ] ) if result.modified_count > 0: st.success(f"Quiz submitted! Score: {score:.1f}%") st.rerun() else: st.error("Error submitting quiz") else: st.error("Quiz time expired") # start_time = quiz.get("start_time") # if not start_time: # if st.button("Start Quiz", key=f"start_{quiz['_id']}"): # # Get random questions when starting # questions = get_randomized_questions(quiz["_id"]) # if questions: # # Save selected questions and start time # result = quizzes_collection.update_one( # {"_id": quiz["_id"]}, # { # "$set": { # "start_time": datetime.now(), # f"student_questions.{student_id}": questions # } # } # ) # if result.modified_count > 0: # st.rerun() # else: # st.error("Error getting quiz questions") # else: # time_remaining = (start_time + timedelta(minutes=quiz['duration_minutes'])) - datetime.now() # # if time_remaining.total_seconds() > 0: # # st.info(f"Time remaining: {int(time_remaining.total_seconds() // 60)}:{int(time_remaining.total_seconds() % 60):02d}") # # # Display quiz form # # with st.form(f"pre_class_quiz_{quiz['_id']}"): # # student_answers = {} # # for i, question in enumerate(quiz["questions"]): # # st.markdown(f"**Q{i+1}:** {question['question']}") # # options = [opt for opt in question["options"]] # # student_answers[str(i)] = st.radio( # # f"Select answer:", # # options=options, # # key=f"q_{quiz['_id']}_{i}" # # ) # # if st.form_submit_button("Submit Quiz"): # # score = submit_quiz_answers( # # quiz["_id"], # # student_id, # # student_answers # # ) # # if score is not None: # # st.success(f"Quiz submitted! Score: {score:.1f}%") # # st.rerun() # # else: # # st.error("Error submitting quiz") # # else: # # st.error("Quiz time expired") # if time_remaining.total_seconds() > 0: # st.info(f"Time remaining: {int(time_remaining.total_seconds() // 60)}:{int(time_remaining.total_seconds() % 60):02d}") # # Get student's randomized questions # student_questions = quiz.get("student_questions", {}).get(student_id) # if student_questions: # with st.form(f"pre_class_quiz_{quiz['_id']}"): # student_answers = {} # for i, question in enumerate(student_questions): # st.markdown(f"**Q{i+1}:** {question['question']}") # options = question["options"] # student_answers[str(i)] = st.radio( # "Select answer:", # options=options, # key=f"q_{quiz['_id']}_{i}" # ) # if st.form_submit_button("Submit Quiz"): # score = submit_quiz_answers( # quiz["_id"], # student_id, # student_answers, # student_questions # ) # if score is not None: # st.success(f"Quiz submitted! Score: {score:.1f}%") # st.rerun() # else: # st.error("Error submitting quiz") # else: # st.error("Quiz time expired") def get_chat_context(session_id): """Get context from session materials""" materials = resources_collection.find({"session_id": session_id}) context = "" for material in materials: if 'text_content' in material: context += f"{material['text_content']}\n" return context import requests def get_supported_url_formats(): """Return a list of supported URL formats for faculty reference""" return """ Supported YouTube URL formats: 1. Standard watch URL: https://www.youtube.com/watch?v=VIDEO_ID 2. Short URL: https://youtu.be/VIDEO_ID 3. Embed URL: https://www.youtube.com/embed/VIDEO_ID 4. Mobile URL: https://m.youtube.com/watch?v=VIDEO_ID 5. YouTube Shorts: https://www.youtube.com/shorts/VIDEO_ID You can copy any of these formats from: - YouTube website (Share button) - YouTube mobile app (Share button) - Browser address bar while watching the video """ def display_url_guidance(): """Display guidance for faculty on how to get the correct URL""" st.info(""" 📝 How to get the correct YouTube URL: 1. Go to the YouTube video you want to share 2. Click the 'Share' button below the video 3. Copy the URL provided in the share dialog 4. Paste it here The URL should start with either 'youtube.com' or 'youtu.be' """) def fetch_youtube_video_title(video_url): """ Fetch the title of a YouTube video with detailed error handling """ api_key = os.getenv("YOUTUBE_API_KEY") if not api_key: st.error("⚠️ System Configuration Error: YouTube API key not configured.") st.write("Please contact technical support for assistance.") return None video_id = extract_youtube_id(video_url) if not video_id: return None url = f"https://www.googleapis.com/youtube/v3/videos?id={video_id}&key={api_key}&part=snippet" try: response = requests.get(url, timeout=10) response.raise_for_status() data = response.json() if not data.get("items"): st.error("⚠️ Video not found or might be private.") st.write(""" Please check if: 1. The video is publicly available 2. The URL is correct 3. The video hasn't been deleted """) return None return data["items"][0]["snippet"]["title"] except requests.exceptions.RequestException as e: if "quotaExceeded" in str(e): st.error("⚠️ YouTube API quota exceeded.") st.write(""" The system has reached its daily limit for video processing. Please try: 1. Waiting a few hours 2. Trying again tomorrow 3. Contact support if the issue persists """) else: st.error(f"Error fetching video title: {str(e)}") st.write("Please try again or choose a different video.") return None def upload_video_source(course_id, session_id, video_url): """ Upload video source and its transcript with comprehensive error handling """ if not video_url: st.error("Please provide a YouTube URL.") display_url_guidance() return None # Display processing message # with st.spinner("Processing your YouTube video..."): # Validate video URL video_id = extract_youtube_id(video_url) if not video_id: return None # Fetch video title video_title = fetch_youtube_video_title(video_url) if not video_title: return None # Extract transcript transcript = extract_youtube_transcript(video_url) if not transcript: return None # Create resource document resource_data = { "_id": ObjectId(), "course_id": course_id, "session_id": session_id, "file_name": video_title, "file_type": "video", "text_content": transcript, "material_type": "video", "source_url": video_url, "uploaded_at": datetime.utcnow(), "video_id": video_id } # Check if resource already exists existing_resource = resources_collection.find_one({ "session_id": session_id, "video_id": video_id }) if existing_resource: st.warning("⚠️ This video has already been added to this session.") st.write(""" Options: 1. Choose a different video 2. Use the existing video resource 3. Remove the existing video first if you want to re-add it """) return existing_resource["_id"] try: # Insert new resource result = resources_collection.insert_one(resource_data) resource_id = result.inserted_id # Update course document update_result = courses_collection.update_one( { "course_id": course_id, "sessions.session_id": session_id }, { "$push": {"sessions.$.pre_class.resources": resource_id} } ) if update_result.modified_count == 0: st.error("⚠️ Failed to update course with new resource.") st.write(""" The video was processed but couldn't be added to the course. This might be because: 1. The course or session ID is invalid 2. You don't have permission to modify this course 3. There was a system error Please try again or contact support if the issue persists. """) # Rollback resource insertion resources_collection.delete_one({"_id": resource_id}) return None # Create vector store for the transcript # create_vector_store(transcript, resource_id) # Create vector store for the transcript vector_store_result = create_vector_store(transcript, resource_id) if not vector_store_result: st.error("⚠️ Failed to create vector store for the transcript.") # Rollback insertions resources_collection.delete_one({"_id": resource_id}) return None st.success("✅ Video successfully added to your course!") st.write(f""" Added: "{video_title}" You can now: 1. Add more videos 2. Preview the added video 3. Continue building your course """) return resource_id except Exception as e: st.error("⚠️ Error uploading video source.") st.write(f""" There was an error while saving the video: {str(e)} Please: 1. Try again 2. Choose a different video 3. Contact support if the issue persists """) return None def upload_preclass_materials(session_id, course_id, student_id): """Upload pre-class materials and manage external resources for a session""" st.subheader("Pre-class Materials Management") # Create tabs for different functionalities upload_tab, videos_tab, web_resources ,external_tab, pre_class_tab, pre_class_evaluate, pre_class_quiz = st.tabs(["Upload Materials","Upload Video Sources","Web Resources", "Resources by Perplexity", "Pre-class Questions", "Pre-class Evaluation", "Pre-class Quiz"]) with upload_tab: # Original file upload functionality uploaded_file = st.file_uploader("Upload Material", type=['txt', 'pdf', 'docx']) if uploaded_file is not None: with st.spinner("Processing document..."): file_name = uploaded_file.name file_content = extract_text_from_file(uploaded_file) if file_content: material_type = st.selectbox("Select Material Type", ["pdf", "docx", "txt"]) if st.button("Upload Material"): upload_resource(course_id, session_id, file_name, uploaded_file, material_type) st.success("Material uploaded successfully!") # Display pre-class materials # Group resources by their types grouped_resources = defaultdict(list) materials = resources_collection.find({"session_id": session_id}) for material in materials: grouped_resources[material['material_type']].append(material) # Display grouped resources for material_type, resources in grouped_resources.items(): st.markdown(f"##### {material_type.capitalize()} Resources") for material in resources: resource_info = f"- **{material['file_name']}** ({material['file_type']})" if 'source_url' in material: resource_info += f" - [URL]({material['source_url']})" st.markdown(resource_info) with videos_tab: # Upload video sources st.info("Upload video sources for this session.") video_url = st.text_input("Enter a Youtube Video URL") if st.button("Upload Video"): with st.spinner("Processing video source..."): video_resource_id = upload_video_source(course_id, session_id, video_url) # if video_resource_id: # st.success("Video source uploaded successfully!") with web_resources: st.markdown("##### Upload Web Resource Links") st.info(""" Share online resources with your students. Supported links include: - Google Colab notebooks - Google Slides presentations - Online documentation - Educational websites - Any web-based learning resource """) # Form for adding web resource with st.form("web_resource_form"): resource_title = st.text_input("Resource Title", placeholder="e.g., Python Basics Notebook, Data Visualization Tutorial") resource_url = st.text_input("Resource URL", placeholder="https://colab.research.google.com/... or other web resource") resource_type = st.selectbox("Resource Type", ["Jupyter Notebook", "Presentation", "Documentation", "Tutorial", "Other"]) resource_description = st.text_area("Description (Optional)", placeholder="Brief description of the resource") submit_resource = st.form_submit_button("Add Resource") if submit_resource: if not resource_title or not resource_url: st.error("Please provide both a title and URL.") else: try: # Create resource document resource_data = { "_id": ObjectId(), "course_id": course_id, "session_id": session_id, "file_name": resource_title, "file_type": "web_resource", "material_type": resource_type, "source_url": resource_url, "description": resource_description, "uploaded_at": datetime.utcnow() } # Check if resource already exists existing_resource = resources_collection.find_one({ "session_id": session_id, "source_url": resource_url }) if existing_resource: st.warning("This resource has already been added.") else: # Insert new resource resources_collection.insert_one(resource_data) resource_id = resource_data["_id"] # Update course document courses_collection.update_one( { "course_id": course_id, "sessions.session_id": session_id }, { "$push": {"sessions.$.pre_class.resources": resource_id} } ) st.success(f"✅ Resource '{resource_title}' added successfully!") except Exception as e: st.error(f"Error adding resource: {str(e)}") with external_tab: # Fetch and display external resources session_data = courses_collection.find_one( {"course_id": course_id, "sessions.session_id": session_id}, {"sessions.$": 1} ) if session_data and session_data.get('sessions'): session = session_data['sessions'][0] external = session.get('external_resources', {}) # Display web articles if 'readings' in external: st.subheader("Web Articles and Videos") for reading in external['readings']: col1, col2 = st.columns([3, 1]) with col1: st.markdown(f"**{reading['title']}**") st.markdown(f"Type: {reading['type']} | Est. time: {reading['estimated_read_time']}") st.markdown(f"URL: [{reading['url']}]({reading['url']})") with col2: if st.button("Extract Content", key=f"extract_{reading['url']}"): with st.spinner("Extracting content..."): content = extract_external_content(reading['url'], reading['type']) if content: resource_id = upload_external_resource( course_id, session_id, reading['title'], content, reading['type'].lower(), reading['url'] ) st.success("Content extracted and stored successfully!") # Display books if 'books' in external: st.subheader("Recommended Books") for book in external['books']: st.markdown(f""" **{book['title']}** by {book['author']} - ISBN: {book['isbn']} - Chapters: {book['chapters']} """) # Display additional resources if 'additional_resources' in external: st.subheader("Additional Resources") for resource in external['additional_resources']: st.markdown(f""" **{resource['title']}** ({resource['type']}) - {resource['description']} - URL: [{resource['url']}]({resource['url']}) """) with pre_class_tab: if st.session_state.user_type == "faculty": faculty_id = st.session_state.user_id st.subheader("Create Pre class Subjective Test") # Create a form for test generation with st.form("pre_create_subjective_test_form"): test_title = st.text_input("Test Title") num_subjective_questions = st.number_input( "Number of Pre class Subjective Questions", min_value=1, value=5 ) generation_method = st.radio( "Question Generation Method", ["Generate from Pre-class Materials"] ) generate_test_btn = st.form_submit_button("Generate Test for Pre Class") # Handle test generation outside the form if generate_test_btn: if not test_title: st.error("Please enter a test title.") return context = "" if generation_method == "Generate from Pre-class Materials": materials = resources_collection.find( {"session_id": session["session_id"]} ) for material in materials: if "text_content" in material: context += material["text_content"] + "\n" with st.spinner("Generating questions and synoptic..."): try: # Store generated content in session state to persist between rerenders questions = pre_generate_questions( context if context else None, num_subjective_questions, session["title"], session.get("description", ""), ) if questions: synoptic = generate_synoptic( questions, context if context else None, session["title"], num_subjective_questions, ) if synoptic: # Store in session state st.session_state.generated_questions = questions st.session_state.generated_synoptic = synoptic st.session_state.test_title = test_title # Display preview st.subheader( "Preview Subjective Questions and Synoptic" ) for i, (q, s) in enumerate(zip(questions, synoptic), 1): st.markdown(f"**Question {i}:** {q['question']}") with st.expander(f"View Synoptic {i}"): st.markdown(s) # Save button outside the form if st.button("Pre Save Test"): test_id = pre_save_subjective_test( course_id, session["session_id"], test_title, questions, ) if test_id: st.success( "Subjective test saved successfully!" ) else: st.error("Error saving subjective test.") else: st.error( "Error generating synoptic answers. Please try again." ) else: st.error("Error generating questions. Please try again.") except Exception as e: st.error(f"An error occurred: {str(e)}") # Display previously generated test if it exists in session state elif hasattr(st.session_state, "generated_questions") and hasattr( st.session_state, "generated_synoptic" ): st.subheader("Preview Subjective Questions and Synoptic") for i, (q, s) in enumerate( zip( st.session_state.generated_questions, st.session_state.generated_synoptic, ), 1, ): st.markdown(f"**Question {i}:** {q['question']}") with st.expander(f"View Synoptic {i}"): st.markdown(s) if st.button("Pre Save Test"): test_id = pre_save_subjective_test( course_id, session["session_id"], st.session_state.test_title, st.session_state.generated_questions, ) if test_id: st.success("Subjective test saved successfully!") # Clear session state after successful save del st.session_state.generated_questions del st.session_state.generated_synoptic del st.session_state.test_title else: st.error("Error saving subjective test.") with pre_class_evaluate: from subjective_test_evaluation import pre_display_evaluation_to_faculty pre_display_evaluation_to_faculty(session["session_id"], student_id, course_id) with pre_class_quiz: if st.session_state.user_type == "faculty": st.subheader("Create Pre-class Quiz") # with st.form("create_pre_class_quiz_form"): # quiz_title = st.text_input("Quiz Title") # num_questions = st.number_input( # "Number of Questions", # min_value=1, # max_value=20, # value=5 # ) # duration = st.number_input( # "Quiz Duration (minutes)", # min_value=5, # max_value=60, # value=15 # ) # # Generate quiz button # if st.form_submit_button("Generate Pre-class Quiz"): # if not quiz_title: # st.error("Please enter a quiz title") # return # # Get pre-class materials # materials = resources_collection.find({"session_id": session_id}) # context = "" # for material in materials: # if 'text_content' in material: # context += material['text_content'] + "\n" # if not context: # st.error("No pre-class materials found") # return # # Generate questions # questions = generate_mcqs( # context=context, # num_questions=num_questions, # session_title=session['title'], # session_description=session.get('description', '') # ) # if questions: # # Preview questions # st.subheader("Preview Questions") # for i, q in enumerate(questions, 1): # st.markdown(f"**Q{i}:** {q['question']}") # for opt in q['options']: # st.markdown(f"- {opt}") # st.markdown(f"*Correct: {q['correct_option']}*") # # Save quiz # quiz_id = save_pre_class_quiz( # course_id=course_id, # session_id=session_id, # title=quiz_title, # questions=questions, # user_id=st.session_state.user_id, # duration=duration # ) # if quiz_id: # st.success("Pre-class quiz created successfully!") # else: # st.error("Error saving quiz") with st.form("create_pre_class_quiz_form"): quiz_title = st.text_input("Quiz Title") num_questions = st.number_input( "Number of Questions per Student", min_value=5, max_value=30, value=10 ) duration = st.number_input( "Quiz Duration (minutes)", min_value=5, max_value=60, value=15 ) if st.form_submit_button("Generate Question Bank"): with st.spinner("Generating question bank..."): try: if not quiz_title: st.error("Please enter a quiz title") return # Get pre-class materials materials = resources_collection.find({"session_id": session_id}) context = "" for material in materials: if 'text_content' in material: context += material['text_content'] + "\n" if not context: st.error("No pre-class materials found") return # Generate question bank question_bank = generate_pre_class_question_bank( context=context, session_title=session['title'], session_description=session.get('description', '') ) if question_bank: print(question_bank) # Preview question bank st.subheader("Question Bank Preview") # Show statistics difficulties = [q['difficulty'] for q in question_bank] st.write("Question Distribution:") st.write(f"- Easy: {difficulties.count('easy')}") st.write(f"- Medium: {difficulties.count('medium')}") st.write(f"- Hard: {difficulties.count('hard')}") # Show questions for i, q in enumerate(question_bank, 1): with st.expander(f"Q{i}: {q['topic']} ({q['difficulty']})"): st.markdown(f"**Question:** {q['question']}") st.markdown("**Options:**") for opt in q['options']: if opt == q['correct_option']: st.markdown(f"✅ {opt}") else: st.markdown(f"- {opt}") # Save quiz with question bank quiz_id = save_pre_class_quiz_with_bank( course_id=course_id, session_id=session_id, title=quiz_title, question_bank=question_bank, num_questions=num_questions, duration=duration, user_id=st.session_state.user_id ) if quiz_id: st.success("Pre-class quiz created successfully!") else: st.error("Error generating question bank") except Exception as e: st.error("Error saving quiz", e) # else: # st.error("Error generating question bank") # question_banks = quizzes_collection.find({ # "course_id": course_id, # "session_id": session_id, # "quiz_type": "pre_class" # }) question_banks = list(quizzes_collection.find({ "course_id": course_id, "session_id": session_id, "quiz_type": "pre_class" })) if question_banks and len(question_banks) > 0: st.markdown("#### Existing Question Banks") for bank in question_banks: try: faculty_member = faculty_collection.find_one({"_id": ObjectId(bank['user_id'])}) faculty_name = faculty_member['full_name'] if faculty_member else "Unknown Faculty" with st.expander(f"📚 {bank.get('title', 'Untitled Quiz')}"): # Check if question bank exists if 'question_bank' in bank and bank['question_bank']: st.markdown(f"**Number of Questions:** {len(bank['question_bank'])}") st.markdown(f"**Created By:** {faculty_name}") st.markdown(f"**Created At:** {bank['created_at'].strftime('%Y-%m-%d %H:%M:%S')}") # Display questions for i, question in enumerate(bank['question_bank'], 1): st.markdown(f"**Question {i}:** {question['question']}") st.markdown("**Options:**") for opt in question['options']: if opt == question['correct_option']: st.markdown(f"✅ {opt}") else: st.markdown(f"- {opt}") st.markdown(f"**Difficulty:** {question['difficulty']}") st.markdown(f"**Topic:** {question['topic']}") else: st.warning("This question bank appears to be empty") except Exception as e: st.error(f"Error displaying question bank: {str(e)}") else: st.info("No question banks yet for this session") def extract_external_content(url, content_type): """Extract content from external resources based on their type""" try: if content_type.lower() == 'video' and 'youtube.com' in url: return extract_youtube_transcript(url) else: return extract_web_article(url) except Exception as e: st.error(f"Error extracting content: {str(e)}") return None def extract_youtube_transcript(url): """ Extract transcript from YouTube videos with detailed error handling """ try: video_id = extract_youtube_id(url) if not video_id: return None # Get transcript with retries max_retries = 3 for attempt in range(max_retries): try: transcript = YouTubeTranscriptApi.get_transcript(video_id) # Combine transcript text with proper spacing and punctuation full_text = '' for entry in transcript: text = entry['text'].strip() if text: if not full_text.endswith(('.', '!', '?', '..."')): full_text += '. ' full_text += text + ' ' return full_text.strip() except Exception as e: if attempt == max_retries - 1: raise e continue except Exception as e: error_message = str(e) if "Video unavailable" in error_message: st.error("⚠️ This video is unavailable or private. Please check if:") st.write(""" - The video is set to public or unlisted - The video hasn't been deleted - You have the correct URL """) elif "Subtitles are disabled" in error_message: st.error("⚠️ This video doesn't have subtitles/transcript available.") st.write(""" Unfortunately, this video cannot be used because: - It doesn't have closed captions or subtitles - The creator hasn't enabled transcript generation Please choose another video that has subtitles available. You can check if a video has subtitles by: 1. Playing the video on YouTube 2. Clicking the 'CC' button in the video player """) else: st.error(f"Could not extract YouTube transcript: {error_message}") st.write("Please try again or choose a different video.") return None def extract_web_article(url): """Extract text content from web articles""" try: headers = { 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36' } response = requests.get(url, headers=headers) response.raise_for_status() soup = BeautifulSoup(response.text, 'html.parser') # Remove unwanted tags for tag in soup(['script', 'style', 'nav', 'footer', 'header']): tag.decompose() # Extract text from paragraphs paragraphs = soup.find_all('p') text_content = ' '.join([p.get_text().strip() for p in paragraphs]) return text_content except Exception as e: st.error(f"Could not extract web article content: {str(e)}") return None def upload_external_resource(course_id, session_id, title, content, content_type, source_url): """Upload extracted external resource content to the database""" resource_data = { "_id": ObjectId(), "course_id": course_id, "session_id": session_id, "file_name": f"{title} ({content_type})", "file_type": "external", "text_content": content, "material_type": content_type, "source_url": source_url, "uploaded_at": datetime.utcnow() } # Check if resource already exists existing_resource = resources_collection.find_one({ "session_id": session_id, "source_url": source_url }) if existing_resource: return existing_resource["_id"] # Insert new resource resources_collection.insert_one(resource_data) resource_id = resource_data["_id"] # Update course document courses_collection.update_one( { "course_id": course_id, "sessions.session_id": session_id }, { "$push": {"sessions.$.pre_class.resources": resource_id} } ) if content: create_vector_store(content, resource_id) return resource_id def extract_youtube_id(url): """ Extract YouTube video ID from various URL formats """ if not url: st.error("Please provide a YouTube URL.") display_url_guidance() return None # Clean the URL url = url.strip() # Basic URL validation if not ('youtube.com' in url or 'youtu.be' in url): st.error("This doesn't appear to be a YouTube URL.") st.write(get_supported_url_formats()) return None # Try to extract using regex patterns patterns = [ r'(?:youtube\.com\/watch\?v=|youtu\.be\/|youtube\.com\/embed\/|youtube\.com\/v\/|youtube\.com\/e\/|youtube\.com\/shorts\/)([^&\n?#]+)', r'(?:youtube\.com\/(?:[^\/]+\/.+\/|(?:v|e(?:mbed)?)\/|.*[?&]v=)|youtu\.be\/)([^"&?\/\s]{11})' ] for pattern in patterns: match = re.search(pattern, url) if match: video_id = match.group(1) if len(video_id) != 11: # YouTube IDs are always 11 characters st.error("Invalid YouTube video ID length. Please check your URL.") display_url_guidance() return None return video_id # If regex fails, try parsing URL components try: parsed_url = urlparse(url) if 'youtube.com' in parsed_url.netloc: query_params = parse_qs(parsed_url.query) if 'v' in query_params: return query_params['v'][0] elif 'youtu.be' in parsed_url.netloc: return parsed_url.path.lstrip('/') except Exception: pass # If all extraction methods fail st.error("Could not extract video ID from the provided URL.") st.write(get_supported_url_formats()) return None def display_live_presentation(session, user_type, course_id): st.markdown("#### Live Presentation") # Get active presentation session_data = courses_collection.find_one( {"course_id": course_id, "sessions.session_id": session['session_id']}, {"sessions.$": 1} ) active_presentation = session_data["sessions"][0].get("in_class", {}).get("active_presentation") # Faculty Interface if user_type == 'faculty': if not active_presentation: st.markdown(""" """, unsafe_allow_html=True) # URL input section with st.container(): ppt_url = st.text_input("🔗 Enter Google Slides Presentation URL", placeholder="https://docs.google.com/presentation/...") if ppt_url: if st.button("▶️ Activate Presentation", use_container_width=True): courses_collection.update_one( {"course_id": course_id, "sessions.session_id": session['session_id']}, {"$set": {"sessions.$.in_class.active_presentation": ppt_url}} ) st.success("✅ Presentation activated successfully!") st.rerun() else: # Display active presentation st.markdown("#### 🎯 Active Presentation") components.iframe(active_presentation, height=800) # Deactivate button st.markdown("
", unsafe_allow_html=True) if st.button("⏹️ Deactivate Presentation", type="secondary", use_container_width=True): courses_collection.update_one( {"course_id": course_id, "sessions.session_id": session['session_id']}, {"$unset": {"sessions.$.in_class.active_presentation": ""}} ) st.success("✅ Presentation deactivated successfully!") st.rerun() # Student Interface else: if active_presentation: st.markdown("#### 🎯 Active Presentation") components.iframe(active_presentation, height=800) else: st.info("📝 No active presentations at this time.") def generate_session_outline(session_id, course_id): """ Generate a comprehensive session outline based on pre-class materials, learning outcomes, and analytics. """ try: # Fetch session details session_data = courses_collection.find_one( {"course_id": course_id, "sessions.session_id": session_id}, {"sessions.$": 1} ) if not session_data or 'sessions' not in session_data: st.error("Session data not found") return None session = session_data['sessions'][0] # Fetch pre-class materials materials = resources_collection.find({"session_id": session_id}) materials_context = "" for material in materials: if 'text_content' in material: materials_context += f"\nMaterial: {material['file_name']}\n{material['text_content']}\n" # Get learning outcomes learning_outcomes = session.get('session_learning_outcomes', []) outcomes_text = "\n".join([ f"Outcome {i+1}: {outcome.get('outcome_description', '')}" for i, outcome in enumerate(learning_outcomes) ]) # Get analytics analytics = session.get('pre_class', {}).get('analytics', {}) # Craft the prompt for Gemini prompt = f""" As an expert educational planner, create a detailed session outline based on the following context: SESSION INFORMATION: Title: {session.get('title', '')} Duration: 70 minutes LEARNING OUTCOMES: {outcomes_text} PRE-CLASS MATERIALS SUMMARY: {materials_context} ANALYTICS INSIGHTS: Struggling Topics: {[topic['topic'] for topic in analytics.get('topic_wise_insights', [])]} Key Issues: {[topic.get('key_issues', []) for topic in analytics.get('topic_wise_insights', [])]} Student Understanding: {analytics.get('course_health', {}).get('overall_engagement', 'N/A')} Based on this context, create a detailed session outline that includes: 1. Opening (8-10 minutes): - How to start the session - Initial engagement activities - Connection to pre-class materials 2. Main Activities (50 minutes): - Sequence of learning activities - Teaching strategies for struggling topics - Interactive elements and discussions - Time allocation for each activity 3. Closing (10-12 minutes): - Assessment strategies - Summary activities - Preview of next session 4. Additional Considerations: - Student engagement strategies - Addressing identified misconceptions - Integration of technology/tools - Backup activities if needed Format the response as a JSON object with these exact keys: {{ "opening_activities": [{{ "activity": "string", "duration": "string", "purpose": "string", "materials_needed": ["string"] }}], "main_activities": [{{ "activity": "string", "duration": "string", "learning_outcome_addressed": "string", "teaching_strategy": "string", "materials_needed": ["string"] }}], "closing_activities": [{{ "activity": "string", "duration": "string", "purpose": "string" }}], "contingency_plans": [{{ "scenario": "string", "alternative_activity": "string" }}] }} """ GEMINI_API_KEY = os.getenv("GEMINI_KEY") genai.configure(api_key=GEMINI_API_KEY) model = genai.GenerativeModel("gemini-1.5-flash") # Generate response using Gemini response = model.generate_content( prompt, generation_config=genai.GenerationConfig( temperature=0.3, response_mime_type="application/json" ) ) if not response or not response.text: st.error("No response received from Gemini") return None # Parse and validate the response try: outline = json.loads(response.text) return outline except json.JSONDecodeError as e: st.error(f"Error parsing response: {str(e)}") return None except Exception as e: st.error(f"Error generating session outline: {str(e)}") return None def display_session_outline(session, outline, course_id): """Display the generated session outline in a structured format""" if not outline: return # Initialize session state for storing outline if not exists if 'session_outline' not in st.session_state: st.session_state.session_outline = None # Store the outline in session state st.session_state.session_outline = outline # Main Display st.markdown(""" """, unsafe_allow_html=True) # st.markdown("### 📋 Session Outline") # # Opening Activities # st.markdown("#### 🎯 Opening Activities") # for activity in outline["opening_activities"]: # with st.expander(f"{activity['activity']} ({activity['duration']})"): # st.markdown(f"**Purpose:** {activity['purpose']}") # st.markdown("**Materials Needed:**") # for material in activity["materials_needed"]: # st.markdown(f"- {material}") st.markdown("#### 📋 Session Outline") with st.expander("View Session Outline"): # Opening Activities Section # st.markdown('Purpose: {activity['purpose']}
Learning Outcome: {activity['learning_outcome_addressed']}
Teaching Strategy: {activity['teaching_strategy']}
Purpose: {activity['purpose']}
If: {plan['scenario']}
Alternative Activity: {plan['alternative_activity']}
{rec["action"]}
Reason: {rec["reasoning"]}
Expected Outcome: {rec["expected_outcome"]}