import os import re import json import tempfile from datetime import datetime from pathlib import Path import streamlit as st import google.generativeai as genai # Optional deps used only when available try: import PyPDF2 # type: ignore except Exception: # pragma: no cover PyPDF2 = None try: from docx import Document # python-docx except Exception: # pragma: no cover Document = None # ============================= # Page config MUST be the first Streamlit call # ============================= st.set_page_config( page_title="StudyBuddy AI Tutor 🤖", page_icon="📚", layout="wide", initial_sidebar_state="expanded", ) # ============================= # Secrets & Configuration # ============================= # DO NOT hardcode API keys. Prefer Streamlit Secrets or Environment Variables. GEMINI_API_KEY = "AIzaSyCWxM6Ic9zs-hZiovnMU8a4UJko7ObqPqU" # Allow overriding the model name via secrets/env (default: gemini-2.0-flash) GEMINI_MODEL = "gemini-2.0-flash" if not GEMINI_API_KEY: st.error( "❌ Gemini API key not found. Set `GEMINI_API_KEY` in Streamlit Secrets or as an environment variable.") st.stop() # Configure Gemini once try: genai.configure(api_key=GEMINI_API_KEY) except Exception as e: st.error(f"Failed to configure Gemini API: {e}") st.stop() # ============================= # Session State Initialization # ============================= def _ensure_state(): ss = st.session_state ss.setdefault("conversation_history", []) ss.setdefault("knowledge_gaps", {}) ss.setdefault( "learning_profile", { "learning_speed": "medium", "preferred_style": "conceptual", "mastery_level": {}, "last_interaction": None, }, ) ss.setdefault("document_text", "") ss.setdefault("structured_data", {}) ss.setdefault("file_uploaded", False) ss.setdefault("file_name", "") ss.setdefault("processing_error", None) ss.setdefault("study_plan", None) _ensure_state() # ============================= # Styles # ============================= st.markdown( """ """, unsafe_allow_html=True, ) # ============================= # Helpers # ============================= @st.cache_data(show_spinner=False) def _read_entire_file_to_temp(uploaded_file) -> tuple[str, str]: """Save uploaded file to a temp file and return (path, suffix).""" suffix = "" if not uploaded_file else f".{uploaded_file.name.split('.')[-1].lower()}" with tempfile.NamedTemporaryFile(delete=False, suffix=suffix) as tmp: tmp.write(uploaded_file.getvalue()) return tmp.name, suffix def extract_text_from_file(uploaded_file) -> str | None: if uploaded_file is None: return None text = [] file_ext = uploaded_file.name.split(".")[-1].lower() try: tmp_file_path, _ = _read_entire_file_to_temp(uploaded_file) if file_ext == "pdf": if PyPDF2 is None: st.session_state.processing_error = ( "PyPDF2 not installed. Please add `pypdf2` to your requirements.") return None with open(tmp_file_path, "rb") as f: reader = PyPDF2.PdfReader(f) for page in reader.pages: page_text = page.extract_text() or "" text.append(page_text) elif file_ext == "docx": if Document is None: st.session_state.processing_error = ( "python-docx not installed. Please add `python-docx` to your requirements.") return None doc = Document(tmp_file_path) for para in doc.paragraphs: text.append(para.text) elif file_ext == "txt": # Try UTF-8 then fallback try: with open(tmp_file_path, "r", encoding="utf-8") as f: text.append(f.read()) except UnicodeDecodeError: with open(tmp_file_path, "r", encoding="utf-16", errors="ignore") as f: text.append(f.read()) else: st.session_state.processing_error = ( "Unsupported file type. Please upload a PDF, DOCX, or TXT file.") return None return "\n".join(text).strip() except Exception as e: st.session_state.processing_error = f"Error reading file: {e}" return None finally: try: if 'tmp_file_path' in locals() and Path(tmp_file_path).exists(): os.unlink(tmp_file_path) except Exception: pass def _safe_json_from_text(text: str): """Try hard to extract JSON from a model response text.""" if not text: return None # 1) Look for ```json ... ``` fenced block fence = re.search(r"```json\s*(\{[\s\S]*?\}|\[[\s\S]*?\])\s*```", text, re.IGNORECASE) if fence: try: return json.loads(fence.group(1)) except Exception: pass # 2) Try to find the first JSON object/array using a streaming decode decoder = json.JSONDecoder() for i in range(len(text)): try: obj, idx = decoder.raw_decode(text[i:]) return obj except Exception: continue # 3) Last resort: greedy braces (may fail on complex text) m = re.search(r"(\{[\s\S]*\}|\[[\s\S]*\])", text) if m: try: return json.loads(m.group(1)) except Exception: pass return None def _get_model(): try: return genai.GenerativeModel(GEMINI_MODEL) except Exception: # Fallback commonly available model names (best effort) for name in [ "gemini-2.0-flash", "gemini-1.5-flash", "gemini-1.5-flash-8b", ]: try: return genai.GenerativeModel(name) except Exception: continue raise # ============================= # Core LLM utilities # ============================= def structure_document_content(text: str): model = _get_model() prompt = ( "Analyze the following educational content and structure it into key topics and concepts. " "For each topic, identify: \n" "1. The main concept\n" "2. Prerequisite knowledge needed\n" "3. Key points to understand\n" "4. Common questions or difficulties students might have\n\n" "Return ONLY valid JSON with this structure (no extra commentary):\n" "{\n" " \"title\": \"Document Title\",\n" " \"topics\": [\n" " {\n" " \"name\": \"Topic Name\",\n" " \"prerequisites\": [\"prerequisite1\", \"prerequisite2\"],\n" " \"key_points\": [\"point1\", \"point2\", \"point3\"],\n" " \"difficulties\": [\"difficulty1\", \"difficulty2\"]\n" " }\n" " ]\n" "}\n\n" "Content to analyze (truncated):\n" + text[:15000] ) try: resp = model.generate_content(prompt) data = _safe_json_from_text(getattr(resp, "text", "")) if isinstance(data, dict) and "topics" in data: return data st.session_state.processing_error = ( "Could not parse structured content from model response.") return None except Exception as e: st.session_state.processing_error = f"Error structuring content: {e}" return None def update_learning_profile(question: str, response_text: str, understanding_score: float): st.session_state.learning_profile["last_interaction"] = datetime.now().isoformat() model = _get_model() prompt = ( "Based on the following question and response, identify which educational topics are being discussed.\n" "Return ONLY a JSON array of topic names.\n\n" f"Question: {question}\n" f"Response: {response_text}\n" ) try: topics_resp = model.generate_content(prompt) topics = _safe_json_from_text(getattr(topics_resp, "text", "")) if not isinstance(topics, list): return # silently skip if not parseable for topic in topics: try: t = str(topic) except Exception: continue current = st.session_state.learning_profile["mastery_level"].get(t, 0.5) st.session_state.learning_profile["mastery_level"][t] = min( 1.0, max(0.0, current + (understanding_score * 0.1)) ) except Exception: # Non-fatal pass def generate_adaptive_response(user_input: str, conversation_history: list[dict]): model = _get_model() # Prepare context from structured data context = "" sd = st.session_state.structured_data if sd and isinstance(sd, dict): title = sd.get("title", "") topics = ", ".join([t.get("name", "?") for t in sd.get("topics", []) if isinstance(t, dict)]) context = f"Based on the document: {title}. Key topics: {topics}.\n" # Prepare learning profile context lp = st.session_state.learning_profile learning_context = ( "Student learning profile:\n" f"- Learning speed: {lp['learning_speed']}\n" f"- Preferred style: {lp['preferred_style']}\n" f"- Mastery levels: {json.dumps(lp['mastery_level'])}\n" ) # Prepare conversation history (last 5) history_text = "\n".join( [f"Student: {m.get('user','')}\nTutor: {m.get('assistant','')}" for m in conversation_history[-5:]] ) prompt = ( "You are a cool, friendly personal tutor helping a teenager understand educational material.\n" f"{context}\n{learning_context}\n" "Previous conversation:\n" + history_text + "\n\n" f"Current student question: {user_input}\n\n" "Respond in a way that:\n" "1. Answers the question clearly and simply\n" "2. Adapts to the student's learning speed and style\n" "3. Identifies and addresses potential knowledge gaps\n" "4. Asks a leading question to encourage deeper thinking\n" "5. Is encouraging and supportive\n" "6. Uses emojis and a casual, friendly tone that teenagers would appreciate\n\n" "Format your response with:\n" "- Explanation: Clear explanation of the concept\n" "- Connection: How it relates to what they already know\n" "- Question: A thought-provoking question to deepen understanding\n" ) try: resp = model.generate_content(prompt) return getattr(resp, "text", "I'm having trouble responding right now.") except Exception as e: return f"I'm having trouble responding right now. Error: {e}" def analyze_knowledge_gaps(): if not st.session_state.conversation_history: return {} recent = "\n".join( [f"Student: {m.get('user','')}\nTutor: {m.get('assistant','')}" for m in st.session_state.conversation_history[-10:]] ) model = _get_model() prompt = ( "Analyze the following student-tutor conversation to identify knowledge gaps or misconceptions the student might have.\n" "Return ONLY a JSON object with topics as keys and the suspected gap/misconception as values.\n\n" f"Conversation:\n{recent}\n" ) try: resp = model.generate_content(prompt) data = _safe_json_from_text(getattr(resp, "text", "")) return data if isinstance(data, dict) else {} except Exception: return {} def generate_study_plan(): sd = st.session_state.structured_data mastery = st.session_state.learning_profile.get("mastery_level", {}) if not sd or not mastery: return "Upload a document and have a conversation to generate a study plan." model = _get_model() prompt = ( "Based on the following document structure and student mastery levels, create a personalized study plan.\n\n" f"Document topics: {json.dumps([t.get('name','?') for t in sd.get('topics', []) if isinstance(t, dict)])}\n\n" f"Student mastery levels: {json.dumps(mastery)}\n\n" f"Knowledge gaps: {json.dumps(st.session_state.knowledge_gaps)}\n\n" f"Create a study plan that:\n" f"1. Focuses on areas with low mastery or known gaps\n" f"2. Builds on prerequisites before advanced topics\n" f"3. Matches the student's learning speed ({st.session_state.learning_profile['learning_speed']})\n" f"4. Uses their preferred learning style ({st.session_state.learning_profile['preferred_style']})\n" f"5. Is engaging and fun for a teenager\n\n" "Return a concise, structured plan (markdown is OK)." ) try: resp = model.generate_content(prompt) return getattr(resp, "text", "") except Exception as e: return f"Error generating study plan: {e}" # ============================= # UI Layout # ============================= st.markdown('

StudyBuddy AI Tutor 🤖

', unsafe_allow_html=True) st.markdown("### Your personal learning companion that adapts to your style! 📚✨") # Sidebar: upload & settings with st.sidebar: st.markdown('
', unsafe_allow_html=True) st.markdown("### 📁 Upload Your Study Materials") uploaded_file = st.file_uploader( "Drag and drop or click to browse", type=["pdf", "docx", "txt"], label_visibility="collapsed", ) st.markdown('
', unsafe_allow_html=True) if uploaded_file is not None: st.session_state.file_uploaded = True st.session_state.file_name = uploaded_file.name st.session_state.processing_error = None with st.spinner("🔄 Processing your document..."): extracted_text = extract_text_from_file(uploaded_file) if extracted_text: st.session_state.document_text = extracted_text structured = structure_document_content(extracted_text) if structured: st.session_state.structured_data = structured st.success(f"✅ {uploaded_file.name} processed successfully!") st.balloons() else: st.error(st.session_state.processing_error or "Failed to extract text.") # File status if st.session_state.file_uploaded: st.info(f"📄 **Current file:** {st.session_state.file_name}") if st.session_state.structured_data: st.success("✅ Document analyzed successfully!") elif st.session_state.processing_error: st.error(f"❌ {st.session_state.processing_error}") else: st.warning("⚠️ **No file uploaded yet**") st.info("Upload a PDF, DOCX, or TXT file to get started!") st.markdown("---") st.markdown("### 🎯 Learning Profile") st.session_state.learning_profile["learning_speed"] = st.select_slider( "Learning Speed 🚀", options=["slow", "medium", "fast"], value=st.session_state.learning_profile.get("learning_speed", "medium"), help="How quickly do you prefer to learn new concepts?", ) styles = ["conceptual", "practical", "visual", "detailed"] current_style = st.session_state.learning_profile.get("preferred_style", "conceptual") try: default_index = styles.index(current_style) except ValueError: default_index = 0 st.session_state.learning_profile["preferred_style"] = st.selectbox( "Learning Style 🎨", options=styles, index=default_index, help="Conceptual (big ideas), Practical (examples), Visual (diagrams), Detailed (in-depth)", ) if st.button("🔍 Analyze Knowledge Gaps", use_container_width=True): with st.spinner("Analyzing your knowledge gaps..."): st.session_state.knowledge_gaps = analyze_knowledge_gaps() if st.session_state.knowledge_gaps: st.success("Knowledge gaps analyzed!") else: st.info("No clear gaps detected yet. Keep chatting!") if st.button("📋 Generate Study Plan", use_container_width=True): with st.spinner("Creating your personalized study plan..."): st.session_state.study_plan = generate_study_plan() st.success("Study plan created!") # Main area col1, col2 = st.columns([2, 1], gap="large") with col1: st.markdown("### 💬 Chat with Your Tutor") # Display conversation history for m in st.session_state.conversation_history: if m.get("user"): st.markdown( f'
👤 You: {m.get("user","")}
', unsafe_allow_html=True, ) if m.get("assistant"): st.markdown( f'
🤖 StudyBuddy: {m.get("assistant","")}
', unsafe_allow_html=True, ) user_input = st.chat_input("Ask a question about your study material...") if user_input: st.session_state.conversation_history.append({"user": user_input, "assistant": ""}) with st.spinner("StudyBuddy is thinking..."): resp_text = generate_adaptive_response(user_input, st.session_state.conversation_history) st.session_state.conversation_history[-1]["assistant"] = resp_text # Simulate understanding score; could be collected via thumbs up/down UI update_learning_profile(user_input, resp_text, 0.7) st.rerun() with col2: st.markdown("### 📊 Learning Insights") if st.session_state.structured_data: st.markdown("#### 📚 Document Topics") topics = st.session_state.structured_data.get("topics", []) for t in topics: if not isinstance(t, dict): continue name = t.get("name", "(untitled)") mastery = float(st.session_state.learning_profile["mastery_level"].get(name, 0)) * 100.0 st.markdown(f"- **{name}** ({mastery:.1f}% mastery)") st.progress(mastery / 100.0) if st.session_state.knowledge_gaps: st.markdown("#### 🚧 Knowledge Gaps") for topic, gap in st.session_state.knowledge_gaps.items(): st.markdown(f"- **{topic}**: {gap}") if st.session_state.get("study_plan"): st.markdown("#### 📋 Study Plan") st.info(st.session_state.study_plan) # Extracted content preview if st.session_state.document_text: with st.expander("View Extracted Document Content"): txt = st.session_state.document_text st.text(txt[:2000] + ("..." if len(txt) > 2000 else "")) # Fun widgets st.markdown("---") col1, col2, col3 = st.columns(3) with col1: st.markdown("### 🏆 Achievements") st.info( """ - 📖 Document Master: Uploaded 1 file - 💬 Chat Champion: Sent 5 messages - 🧠 Knowledge Seeker: Asked 3 questions """ ) with col2: st.markdown("### 🎮 Learning Games") st.button("Flashcards 🎴", use_container_width=True) st.button("Quiz Time ❓", use_container_width=True) st.button("Concept Match 🧩", use_container_width=True) with col3: st.markdown("### 🔥 Streak") st.markdown( """

3 days

Current learning streak!

""", unsafe_allow_html=True, )