File size: 20,761 Bytes
3ac2769 05373b0 3ac2769 05373b0 5695961 05373b0 5695961 3ac2769 8b0d8d3 05373b0 3ac2769 5695961 3ac2769 5695961 3ac2769 5695961 05373b0 3ac2769 05373b0 3ac2769 05373b0 3ac2769 05373b0 3ac2769 05373b0 3ac2769 05373b0 3ac2769 05373b0 3ac2769 05373b0 3ac2769 05373b0 3ac2769 05373b0 3ac2769 05373b0 3ac2769 05373b0 3ac2769 05373b0 3ac2769 05373b0 3ac2769 05373b0 3ac2769 05373b0 3ac2769 05373b0 3ac2769 05373b0 3ac2769 05373b0 3ac2769 05373b0 3ac2769 05373b0 3ac2769 05373b0 3ac2769 05373b0 3ac2769 05373b0 3ac2769 05373b0 3ac2769 05373b0 3ac2769 5695961 05373b0 3ac2769 05373b0 5695961 3ac2769 5695961 3ac2769 05373b0 9f8c5b5 5695961 3ac2769 5695961 05373b0 3ac2769 9f8c5b5 5695961 3ac2769 9f8c5b5 5695961 9f8c5b5 5695961 3ac2769 5695961 3ac2769 05373b0 5695961 05373b0 3ac2769 05373b0 3ac2769 05373b0 5695961 3ac2769 05373b0 3ac2769 5695961 3ac2769 5695961 3ac2769 5695961 05373b0 3ac2769 05373b0 5695961 3ac2769 05373b0 3ac2769 05373b0 3ac2769 05373b0 5695961 3ac2769 05373b0 5695961 3ac2769 05373b0 5695961 3ac2769 05373b0 5695961 05373b0 5695961 3ac2769 5695961 05373b0 3ac2769 05373b0 3ac2769 5695961 3ac2769 5695961 3ac2769 5695961 3ac2769 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 | 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,
)
|