import os from datetime import date, datetime, timedelta import pandas as pd import streamlit as st import torch from transformers import AutoTokenizer, AutoModelForSeq2SeqLM, pipeline # ============================================================ # APP CONFIGURATION # ============================================================ st.set_page_config( page_title="KLE Smart Study Companion", page_icon="🎓", layout="wide", initial_sidebar_state="expanded" ) MODEL_ID = os.getenv( "MODEL_ID", "google/flan-t5-base" ) # ============================================================ # CUSTOM CSS # ============================================================ st.markdown( """ """, unsafe_allow_html=True ) # ============================================================ # LOAD AI MODEL # ============================================================ @st.cache_resource( show_spinner="Loading the AI Study Assistant..." ) def load_model(): tokenizer = AutoTokenizer.from_pretrained( MODEL_ID ) model = AutoModelForSeq2SeqLM.from_pretrained( MODEL_ID, torch_dtype=torch.float32, low_cpu_mem_usage=True ) generator = pipeline( "text2text-generation", model=model, tokenizer=tokenizer, device=-1 ) return generator @st.cache_resource(show_spinner=False) def get_ai(): return load_model() # ============================================================ # AI TEXT GENERATION # ============================================================ def generate_text( prompt, max_new_tokens=350 ): ai = get_ai() try: response = ai( prompt, max_new_tokens=max_new_tokens, # More reliable output do_sample=False, # Better instruction following num_beams=4, # Prevent repetitive loops no_repeat_ngram_size=3, repetition_penalty=1.15, # Allow model to stop naturally early_stopping=True, truncation=True ) return response[0][ "generated_text" ].strip() except Exception as e: return ( "Unable to generate AI response: " f"{str(e)}" ) # ============================================================ # SESSION STATE # ============================================================ if "study_plan" not in st.session_state: st.session_state.study_plan = pd.DataFrame() if "reminders" not in st.session_state: st.session_state.reminders = [] if "summary" not in st.session_state: st.session_state.summary = "" if "qa" not in st.session_state: st.session_state.qa = "" # ============================================================ # STUDY PLAN GENERATOR # ============================================================ def create_study_plan( subject, topics, start_date, exam_date, hours_per_day ): topic_list = [ topic.strip() for topic in topics .replace("\n", ",") .split(",") if topic.strip() ] if not topic_list: return pd.DataFrame() total_days = max( ( exam_date - start_date ).days + 1, 1 ) plan = [] for i, topic in enumerate( topic_list ): day_offset = int( ( i * total_days ) / len(topic_list) ) study_date = ( start_date + timedelta( days=day_offset ) ) days_remaining = ( exam_date - study_date ).days if days_remaining <= 2: activity = ( "Quick revision + " "important questions" ) elif i == len( topic_list ) - 1: activity = ( "Learn topic + revision" ) else: activity = ( "Understand concepts + " "make short notes" ) plan.append( { "Date": study_date.strftime( "%d-%m-%Y" ), "Subject": subject, "Topic": topic, "Recommended Time": f"{hours_per_day} hour(s)", "Activity": activity, "Status": "Pending" } ) return pd.DataFrame(plan) # ============================================================ # HEADER # ============================================================ st.markdown( """
🎓 KLE Smart Study Companion
""", unsafe_allow_html=True ) st.markdown( """Plan smarter • Learn faster • Revise better • Be exam ready
""", unsafe_allow_html=True ) # ============================================================ # SIDEBAR # ============================================================ with st.sidebar: st.header( "🎓 KLE Study Assistant" ) st.write( """ An AI-powered MVP designed to help students organise, understand and revise their studies. """ ) st.divider() st.subheader( "What can I do?" ) st.write( "📅 Create Study Plans" ) st.write( "⏰ Track Study Reminders" ) st.write( "🧠 Learn Topics with AI" ) st.write( "❓ Generate Important Questions" ) st.divider() st.caption( "MVP Demonstration | " "Startup Validation & " "MVP Development" ) # ============================================================ # TABS # ============================================================ tab1, tab2, tab3, tab4 = st.tabs( [ "📅 Study Planner", "⏰ Reminders", "🧠 Learn a Topic", "❓ Exam Q&A" ] ) # ============================================================ # TAB 1 — STUDY PLANNER # ============================================================ with tab1: st.header( "📅 AI Study Planner" ) st.write( """ Tell us what you need to study and when your exam is. """ ) col1, col2 = st.columns(2) with col1: subject = st.text_input( "Subject", placeholder=( "Example: " "Python Programming" ) ) start_date = st.date_input( "Start studying from", value=date.today() ) hours_per_day = st.slider( "How many hours can " "you study per day?", min_value=1, max_value=6, value=2 ) with col2: topics = st.text_area( "Topics / Chapters", height=150, placeholder=( "Variables, Functions, " "Lists, Dictionaries, " "File Handling, OOP" ) ) exam_date = st.date_input( "Exam date", value=( date.today() + timedelta(days=7) ) ) if st.button( "✨ Create My Study Plan", type="primary", use_container_width=True ): if not subject: st.warning( "Please enter a subject." ) elif not topics: st.warning( "Please enter at least " "one topic." ) elif exam_date < start_date: st.error( "Exam date must be " "after the study " "start date." ) else: plan = create_study_plan( subject, topics, start_date, exam_date, hours_per_day ) st.session_state.study_plan = ( plan ) st.success( "Your personalised " "study plan is ready! 🎉" ) if not st.session_state.study_plan.empty: st.subheader( "Your Study Schedule" ) edited_plan = st.data_editor( st.session_state.study_plan, use_container_width=True, hide_index=True, num_rows="dynamic" ) st.session_state.study_plan = ( edited_plan ) st.download_button( "⬇️ Download Study Plan", data=edited_plan.to_csv( index=False ), file_name=( "KLE_Study_Plan.csv" ), mime="text/csv" ) st.divider() if st.button( "⏰ Add Study Plan " "to Reminders", use_container_width=True ): added = 0 for _, row in ( edited_plan.iterrows() ): try: reminder_date = ( datetime.strptime( row["Date"], "%d-%m-%Y" ).date() ) reminder = { "Task": ( f"{row['Subject']} - " f"{row['Topic']}" ), "Due Date": reminder_date, "Status": "Pending" } st.session_state.reminders.append( reminder ) added += 1 except Exception: pass st.success( f"{added} study task(s) " "added to reminders." ) # ============================================================ # TAB 2 — REMINDERS # ============================================================ with tab2: st.header( "⏰ Study Reminders" ) st.info( """ For this MVP, reminders are shown when the student opens the application. Future versions could send WhatsApp, email or mobile notifications. """ ) with st.expander( "➕ Add a New Reminder", expanded=False ): reminder_task = st.text_input( "What do you need to study?", placeholder=( "Example: Revise " "Python Functions" ) ) reminder_date = st.date_input( "Due date", value=date.today(), key="manual_reminder_date" ) if st.button( "Add Reminder" ): if reminder_task: st.session_state.reminders.append( { "Task": reminder_task, "Due Date": reminder_date, "Status": "Pending" } ) st.success( "Reminder added." ) else: st.warning( "Enter a study task." ) st.divider() if not st.session_state.reminders: st.write( "No reminders yet." ) else: today = date.today() for index, reminder in enumerate( st.session_state.reminders ): due_date = ( reminder["Due Date"] ) if isinstance( due_date, str ): try: due_date = ( datetime.strptime( due_date, "%d-%m-%Y" ).date() ) except Exception: due_date = today days_left = ( due_date - today ).days col1, col2, col3 = st.columns( [5, 2, 2] ) with col1: st.markdown( f"### 📚 " f"{reminder['Task']}" ) st.caption( "Due: " f"{due_date.strftime('%d %B %Y')}" ) with col2: if ( reminder["Status"] == "Completed" ): st.success( "✅ Completed" ) elif days_left < 0: st.error( "⚠️ Overdue by " f"{abs(days_left)} " "day(s)" ) elif days_left == 0: st.warning( "🔔 Due Today!" ) elif days_left == 1: st.warning( "⏳ Due Tomorrow" ) else: st.info( f"{days_left} " "days left" ) with col3: if ( reminder["Status"] != "Completed" ): if st.button( "Mark Done", key=( f"done_{index}" ) ): st.session_state.reminders[ index ]["Status"] = ( "Completed" ) st.rerun() else: if st.button( "Remove", key=( f"remove_{index}" ) ): st.session_state.reminders.pop( index ) st.rerun() st.divider() # ============================================================ # TAB 3 — AI LEARNING TUTOR # ============================================================ with tab3: st.header( "🧠 Learn a Topic with AI" ) st.write( """ Enter any topic, concept, chapter or class note. Your AI Study Tutor will explain it directly here in simple, student-friendly language. """ ) # -------------------------------------------------------- # TOPIC INPUT # -------------------------------------------------------- study_content = st.text_area( "What would you like to learn?", height=180, placeholder=( "Examples:\n" "What is Normalisation in DBMS?\n" "Explain ACID properties\n" "What is inheritance in Python?\n" "Explain Machine Learning" ) ) # -------------------------------------------------------- # LEARNING OPTIONS # -------------------------------------------------------- col1, col2 = st.columns(2) with col1: explanation_mode = st.selectbox( "How would you like to learn?", [ "Detailed Explanation", "Beginner Friendly", "Quick Summary", "Learn with Examples", "Exam Revision" ] ) with col2: detail_level = st.selectbox( "Explanation depth", [ "Short", "Detailed", "Deep Learning" ], index=1 ) # -------------------------------------------------------- # GENERATE LESSON # -------------------------------------------------------- if st.button( "✨ Teach Me This Topic", type="primary", use_container_width=True ): if not study_content.strip(): st.warning( "Please enter a topic " "or paste some " "study material." ) else: with st.spinner( "Your AI tutor is " "preparing the lesson..." ): # ================================================= # DETAILED EXPLANATION # ================================================= if explanation_mode == ( "Detailed Explanation" ): prompt = f""" Explain this topic to a college student in simple language: {study_content} Teach the topic clearly. Include: - Definition - Main idea - How it works - Important concepts - Simple example - Real-world application - Key points to remember Do not repeat the question. Do not create a list of questions. Explain the topic as a teacher. """ # ================================================= # BEGINNER FRIENDLY # ================================================= elif explanation_mode == ( "Beginner Friendly" ): prompt = f""" Teach this topic to a complete beginner: {study_content} Assume the student has no previous knowledge. Explain: - What it means - Why it is needed - How it works - Important terms - A very simple example - Where it is used Use easy language and short paragraphs. Do not repeat the question. """ # ================================================= # QUICK SUMMARY # ================================================= elif explanation_mode == ( "Quick Summary" ): prompt = f""" Give a simple educational summary of: {study_content} Explain: - What it is - Why it is important - Main concepts - One example - Five key points to remember Do not repeat the question. """ # ================================================= # LEARN WITH EXAMPLES # ================================================= elif explanation_mode == ( "Learn with Examples" ): prompt = f""" Teach this topic using examples: {study_content} First explain the concept simply. Then provide: - One basic example - One real-life example - One technical example if relevant - Explain what each example demonstrates - Key points to remember Do not repeat the question. """ # ================================================= # EXAM REVISION # ================================================= else: prompt = f""" Prepare student-friendly examination revision notes for: {study_content} Include: - Definition - Important concepts - Important terms - Key points - One example - Important exam points - Three possible exam questions with short answers Keep the explanation accurate and easy to revise. Do not repeat the topic unnecessarily. """ # ================================================= # OUTPUT LENGTH # ================================================= if detail_level == "Short": token_limit = 180 elif detail_level == "Detailed": token_limit = 320 else: token_limit = 420 result = generate_text( prompt, max_new_tokens=token_limit ) st.session_state.summary = ( result ) # -------------------------------------------------------- # DISPLAY LESSON # -------------------------------------------------------- if st.session_state.summary: st.divider() st.subheader( "📖 Your AI Lesson" ) st.markdown( st.session_state.summary ) st.divider() st.caption( "AI-generated learning content. " "Students should cross-check " "important academic information " "with their course material." ) # ============================================================ # TAB 4 — EXAM Q&A # ============================================================ with tab4: st.header( "❓ Potential Exam Questions" ) st.write( """ Enter a chapter, topic or study material. AI will identify concepts that may deserve additional attention during revision. """ ) qa_content = st.text_area( "Chapter / Topic / Study Notes", height=260, key="qa_content", placeholder=( "Example:\n" "Normalization in DBMS\n\n" "Or paste your class notes here..." ) ) col1, col2 = st.columns(2) with col1: question_count = st.selectbox( "Number of Questions", [ 5, 8, 10 ], index=1 ) with col2: difficulty = st.selectbox( "Difficulty", [ "Easy", "Medium", "Exam Focused" ] ) if st.button( "🎯 Generate Important Q&A", type="primary", use_container_width=True ): if not qa_content.strip(): st.warning( "Please provide " "a chapter or topic first." ) else: with st.spinner( "Finding important " "examination areas..." ): prompt = f""" Create study questions and answers from this topic: {qa_content} Generate {question_count} questions. Difficulty: {difficulty} Each question must test a different concept. Use this format: Q1: Question Answer: Short correct answer Q2: Question Answer: Short correct answer Do not repeat questions. Keep the answers clear and student-friendly. """ result = generate_text( prompt, max_new_tokens=420 ) st.session_state.qa = ( result ) if st.session_state.qa: st.divider() st.subheader( "🎯 Questions to Pay Attention To" ) st.markdown( st.session_state.qa ) st.info( """ 💡 These questions are AI-generated revision aids. Actual examination questions depend on the curriculum and faculty assessment. """ ) # ============================================================ # FOOTER # ============================================================ st.divider() st.markdown( """