Spaces:
Sleeping

tutor / src /streamlit_app.py
faiz3123's picture
Update src/streamlit_app.py
8b0d8d3 verified
Raw History Blame Contribute Delete
20.8 kB
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(
"""
<style>
.main-header { font-size: 3rem; color: #6a11cb; text-align: center; margin-bottom: 1rem; background: linear-gradient(45deg, #6a11cb, #2575fc); -webkit-background-clip: text; -webkit-text-fill-color: transparent; font-weight: 800; }
.sub-header { font-size: 1.5rem; color: #2575fc; margin-bottom: 1rem; }
.stButton>button { background: linear-gradient(45deg, #6a11cb, #2575fc); color: white; border: none; border-radius: 12px; padding: 0.5rem 1rem; font-weight: 600; }
.stButton>button:hover { background: linear-gradient(45deg, #2575fc, #6a11cb); color: white; }
.chat-message { padding: 1rem; border-radius: 12px; margin-bottom: 1rem; box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1); }
.user-message { background-color: #e6f7ff; border-left: 4px solid #2575fc; }
.assistant-message { background-color: #f0f8ff; border-left: 4px solid #6a11cb; }
.file-upload-area { border: 2px dashed #6a11cb; border-radius: 12px; padding: 2rem; text-align: center; margin-bottom: 1rem; }
.progress-bar { height: 10px; background: linear-gradient(45deg, #6a11cb, #2575fc); border-radius: 5px; margin-bottom: 1rem; }
</style>
""",
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('<h1 class="main-header">StudyBuddy AI Tutor ๐Ÿค–</h1>', unsafe_allow_html=True)
st.markdown("### Your personal learning companion that adapts to your style! ๐Ÿ“šโœจ")
# Sidebar: upload & settings
with st.sidebar:
st.markdown('<div class="file-upload-area">', 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('</div>', 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'<div class="chat-message user-message">๐Ÿ‘ค <strong>You:</strong> {m.get("user","")}</div>',
unsafe_allow_html=True,
)
if m.get("assistant"):
st.markdown(
f'<div class="chat-message assistant-message">๐Ÿค– <strong>StudyBuddy:</strong> {m.get("assistant","")}</div>',
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(
"""
<div style="text-align: center;">
<h1 style="color: #6a11cb; margin: 0;">3 days</h1>
<p>Current learning streak!</p>
</div>
""",
unsafe_allow_html=True,
)