Spaces:
Running
Running
File size: 35,409 Bytes
bc49df4 7ba185a bc49df4 7ba185a e9bf540 e17a0bf bc49df4 7ba185a bc49df4 5675df2 bc49df4 21ac1d0 5675df2 21ac1d0 1048031 21ac1d0 bc49df4 7ba185a 5675df2 bc49df4 21ac1d0 bc49df4 7ba185a 5675df2 7ba185a bc49df4 7ba185a bc49df4 7ba185a bc49df4 7ba185a bc49df4 5675df2 21ac1d0 5675df2 21ac1d0 bc49df4 7ba185a bc49df4 5675df2 21ac1d0 bc49df4 21ac1d0 5675df2 21ac1d0 5675df2 21ac1d0 5675df2 bc49df4 5675df2 bc49df4 e17a0bf 5675df2 21ac1d0 bc49df4 21ac1d0 bc49df4 d43d475 bc49df4 5675df2 bc49df4 21ac1d0 bc49df4 5675df2 21ac1d0 5675df2 21ac1d0 888a320 21ac1d0 5675df2 bc49df4 21ac1d0 bc49df4 21ac1d0 bc49df4 21ac1d0 e17a0bf 1048031 21ac1d0 1048031 21ac1d0 1048031 21ac1d0 1048031 21ac1d0 1048031 21ac1d0 1048031 21ac1d0 1048031 21ac1d0 1048031 21ac1d0 1048031 21ac1d0 1048031 21ac1d0 1048031 21ac1d0 1048031 21ac1d0 1048031 21ac1d0 1048031 21ac1d0 1048031 21ac1d0 1048031 21ac1d0 1048031 21ac1d0 1048031 e17a0bf 5675df2 e17a0bf |
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 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 |
import streamlit as st
import tempfile
import json
import random
from pathlib import Path
from PyPDF2 import PdfReader
from openai import OpenAI
import os
from ast import literal_eval
# Initialize the OpenAI client
api_key = os.getenv("OPENAI_API_KEY")
client = OpenAI(api_key = api_key)
# ---------------------------
# Helper Function: Extract text from PDF
# ---------------------------
def extract_text(uploaded_file):
# Check file size (max 10MB)
uploaded_file.seek(0, os.SEEK_END)
file_size = uploaded_file.tell()
uploaded_file.seek(0)
if file_size > 10 * 1024 * 1024:
st.error("File size exceeds 10MB limit.")
return ""
pdf_reader = PdfReader(uploaded_file)
text = ""
for page in pdf_reader.pages:
page_text = page.extract_text()
if page_text:
text += page_text + "\n"
return text
# ---------------------------
# OpenAI Response Functions (using new style)
# ---------------------------
def generate_summary_from_text(text):
prompt = (
f"Summarize the following document in a concise manner, highlighting the key points that a student should know:\n\n{text}"
)
messages = [
{"role": "system", "content": "You are an educational assistant."},
{"role": "user", "content": prompt}
]
completion = client.chat.completions.create(
model="gpt-4o-mini",
messages=messages
)
return completion.choices[0].message.content.strip()
def chat_with_document(text, conversation_history, user_query):
messages = conversation_history + [
{"role": "user", "content": f"Based on the following document:\n\n{text}\n\nQuestion: {user_query}"}
]
completion = client.chat.completions.create(
model="gpt-4o-mini",
messages=messages
)
return completion.choices[0].message.content.strip()
def generate_questions_from_text(text, num_questions):
prompt = (
f"Generate up to {num_questions} study questions with answers based on the following document.\n"
f"Return the output as a table with two columns: 'Question' and 'Answer'.\n\nDocument:\n\n{text}"
)
messages = [
{"role": "system", "content": "You are an educational assistant that generates study questions."},
{"role": "user", "content": prompt}
]
completion = client.chat.completions.create(
model="gpt-4o-mini",
messages=messages
)
return completion.choices[0].message.content.strip()
def generate_flashcards_from_text(text, num_cards):
prompt = (
f"Generate {num_cards} flashcards based on the following document.\n\nDocument:\n\n{text}\n\n"
"Return a Python dictionary where each key is a flashcard question and its corresponding value is the answer. "
"Do not include any additional text."
)
messages = [
{"role": "system", "content": "You are an educational assistant that creates study flashcards."},
{"role": "user", "content": prompt}
]
completion = client.chat.completions.create(
model="gpt-4o-mini",
messages=messages
)
output = completion.choices[0].message.content.strip()
try:
flashcards = literal_eval(output)
if isinstance(flashcards, dict):
return flashcards
else:
return {}
except Exception as e:
st.error(f"Error parsing flashcards: {e}")
return {}
# ---------------------------
# Sidebar: File Upload & Mode Selection
# ---------------------------
st.sidebar.title("Study Companion Setup")
uploaded_pdf = st.sidebar.file_uploader("Upload your study PDF (max 10MB)", type="pdf")
mode = st.sidebar.radio("Select Mode", ("Chat", "Test Your Knowledge"))# , "Flashcards"))
# For Test Your Knowledge and Flashcards modes, allow number input.
num_questions = None
num_flashcards = None
if mode == "Test Your Knowledge":
num_questions = st.sidebar.number_input("Number of questions to generate (max 50):", min_value=1, max_value=50, value=10, step=1)
elif mode == "Flashcards":
num_flashcards = st.sidebar.number_input("Number of flashcards to generate (max 5):", min_value=1, max_value=5, value=3, step=1)
# ---------------------------
# Session State Initialization
# ---------------------------
if "pdf_text" not in st.session_state:
st.session_state.pdf_text = None
if "summary" not in st.session_state:
st.session_state.summary = None
if "chat_history" not in st.session_state:
st.session_state.chat_history = [{"role": "assistant", "content": "Hi, how can I help you with your study material?"}]
if "questions_table" not in st.session_state:
st.session_state.questions_table = None
if "flashcards" not in st.session_state:
st.session_state.flashcards = {}
if "current_card" not in st.session_state:
st.session_state.current_card = 0
if "score" not in st.session_state:
st.session_state.score = 0
if "show_answer" not in st.session_state:
st.session_state.show_answer = False
# ---------------------------
# Process PDF Upload
# ---------------------------
if uploaded_pdf is not None:
st.session_state.pdf_text = extract_text(uploaded_pdf)
if st.session_state.pdf_text:
st.sidebar.success("PDF uploaded and processed successfully!")
else:
st.sidebar.error("Failed to extract text. Please check your PDF file.")
# ---------------------------
# Main Area: Mode-Based Display (all functions via side menu)
# ---------------------------
st.title("Study Companion 📚")
if st.session_state.pdf_text is None:
st.info("Please upload a PDF from the sidebar to begin.")
else:
if mode == "Chat":
st.header("Chat with Your Study Companion")
# Display persistent chat history
for msg in st.session_state.chat_history:
st.chat_message(msg["role"]).write(msg["content"])
user_question = st.chat_input("Ask a question about the document:")
if user_question:
st.session_state.chat_history.append({"role": "user", "content": user_question})
st.chat_message("user").write(user_question)
with st.spinner("Processing your question..."):
response = chat_with_document(st.session_state.pdf_text, st.session_state.chat_history, user_question)
st.session_state.chat_history.append({"role": "assistant", "content": response})
st.chat_message("assistant").write(response)
elif mode == "Test Your Knowledge":
st.header("Test Your Knowledge")
if num_questions is None:
st.info("Please specify the number of questions in the sidebar.")
else:
with st.spinner("Generating questions..."):
questions_output = generate_questions_from_text(st.session_state.pdf_text, num_questions)
# Assume the output is a table in markdown format
#st.markdown("### Generated Questions")
st.markdown(questions_output)
# Optionally, you can parse the table and display it with st.table if it's in a CSV-like format.
elif mode == "Flashcards":
st.header("Practice Flashcards")
if st.button("Generate Flashcards"):
with st.spinner("Generating flashcards..."):
flashcards = generate_flashcards_from_text(st.session_state.pdf_text, num_flashcards)
st.session_state.flashcards = flashcards
st.session_state.current_card = 0
st.session_state.score = 0
st.session_state.show_answer = False
st.success("Flashcards generated successfully!")
if not st.session_state.flashcards:
st.info("No flashcards available. Click the button above to generate flashcards.")
else:
total_cards = len(st.session_state.flashcards)
if st.session_state.current_card >= total_cards:
st.success(f"You've completed all flashcards! Final Score: {st.session_state.score} / {total_cards}")
st.info("Restart the session or generate new flashcards from the sidebar.")
else:
flashcards = st.session_state.flashcards
current_keys = list(flashcards.keys())
current_question = current_keys[st.session_state.current_card]
current_answer = flashcards[current_question]
st.write(f"**Question:** {current_question}")
if st.button("Show Answer"):
st.session_state.show_answer = True
if st.session_state.show_answer:
st.write(f"**Answer:** {current_answer}")
col1, col2 = st.columns(2)
with col1:
if st.button("Correct"):
st.session_state.score += 1
st.success("Correct!")
with col2:
if st.button("Wrong"):
st.error("Incorrect!")
if st.button("Next Card"):
st.session_state.current_card += 1
st.session_state.show_answer = False
st.rerun()
st.write(f"**Current Score:** {st.session_state.score} / {total_cards}")
# # Import the CrewAI flashcard module (modified below to remove page range)
# from crewai_flashcard import generate_flashcards
# # ---------------------------
# # Helper Function: Extract text from PDF
# # ---------------------------
# def extract_text(uploaded_file):
# # Ensure file size is less than 10MB
# uploaded_file.seek(0, os.SEEK_END)
# if uploaded_file.tell() > 10 * 1024 * 1024:
# st.error("File exceeds 10MB limit.")
# return ""
# uploaded_file.seek(0)
# pdf_reader = PdfReader(uploaded_file)
# text = ""
# for page in pdf_reader.pages:
# page_text = page.extract_text()
# if page_text:
# text += page_text + "\n"
# return text
# # ---------------------------
# # OpenAI Response Functions
# # ---------------------------
# def generate_summary_from_text(text):
# prompt = (
# f"Summarize the following document in a concise manner, highlighting the key points that a student should know:\n\n{text}"
# )
# messages = [
# {"role": "system", "content": "You are an educational assistant."},
# {"role": "user", "content": prompt}
# ]
# completion = client.chat.completions.create(
# model="gpt-4o-mini",
# messages=messages
# )
# return completion.choices[0].message.content.strip()
# def chat_with_document(text, conversation_history, user_query):
# messages = conversation_history + [
# {"role": "user", "content": f"Based on the following document:\n\n{text}\n\nQuestion: {user_query}"}
# ]
# completion = client.chat.completions.create(
# model="gpt-4o-mini",
# messages=messages
# )
# return completion.choices[0].message.content.strip()
# def generate_questions_from_text(text, num_questions):
# prompt = (
# f"Generate {num_questions} study questions with answers based on the following document. "
# "Return the output as a table in CSV format with two columns: 'Question' and 'Answer'.\n\nDocument:\n\n{text}"
# )
# messages = [
# {"role": "system", "content": "You are an educational assistant that generates study questions."},
# {"role": "user", "content": prompt}
# ]
# completion = client.chat.completions.create(
# model="gpt-4o-mini",
# messages=messages
# )
# # Expecting CSV output (with header: Question,Answer)
# return completion.choices[0].message.content.strip()
# # ---------------------------
# # Sidebar: File Upload & Mode Selection
# # ---------------------------
# st.sidebar.title("Study Companion Setup")
# uploaded_pdf = st.sidebar.file_uploader("Upload your study PDF (max 10MB)", type="pdf")
# mode = st.sidebar.radio("Select Mode", ("Chat", "Test Your Knowledge", "Flashcards"))
# # For Test Your Knowledge: number of questions (max 50)
# num_questions = None
# if mode == "Test Your Knowledge":
# num_questions = st.sidebar.number_input("Number of questions to generate (max 50):", min_value=1, max_value=50, value=10, step=1)
# if st.sidebar.button("Generate Questions"):
# st.session_state.gen_questions = True
# # For Flashcards: number of flashcards (max 5)
# num_flashcards = None
# if mode == "Flashcards":
# num_flashcards = st.sidebar.number_input("Number of flashcards to generate (max 5):", min_value=1, max_value=5, value=3, step=1)
# if st.sidebar.button("Generate Flashcards"):
# st.session_state.gen_flashcards = True
# # ---------------------------
# # Session State Initialization
# # ---------------------------
# if "pdf_text" not in st.session_state:
# st.session_state.pdf_text = None
# if "summary" not in st.session_state:
# st.session_state.summary = None
# if "chat_history" not in st.session_state:
# st.session_state.chat_history = [{"role": "assistant", "content": "Hi, how can I help you with your study material?"}]
# if "questions_table" not in st.session_state:
# st.session_state.questions_table = None
# if "flashcards" not in st.session_state:
# st.session_state.flashcards = {}
# if "current_card" not in st.session_state:
# st.session_state.current_card = 0
# if "score" not in st.session_state:
# st.session_state.score = 0
# if "show_answer" not in st.session_state:
# st.session_state.show_answer = False
# # ---------------------------
# # Process PDF Upload
# # ---------------------------
# if uploaded_pdf is not None:
# with tempfile.NamedTemporaryFile(delete=False, suffix=".pdf") as tmp:
# tmp.write(uploaded_pdf.read())
# st.session_state.pdf_file_path = tmp.name
# st.session_state.pdf_text = extract_text(uploaded_pdf)
# if st.session_state.pdf_text:
# st.sidebar.success("PDF uploaded and processed successfully!")
# else:
# st.sidebar.error("Failed to extract text from the PDF.")
# # ---------------------------
# # Main Area: Mode-Based Display (using side menu)
# # ---------------------------
# st.title("Study Companion: PDF-based Learning")
# if st.session_state.pdf_text is None:
# st.info("Please upload a PDF from the sidebar to begin.")
# else:
# if mode == "Chat":
# st.header("Chat with Your Study Companion")
# for msg in st.session_state.chat_history:
# st.chat_message(msg["role"]).write(msg["content"])
# user_question = st.chat_input("Ask a question about the document:")
# if user_question:
# st.session_state.chat_history.append({"role": "user", "content": user_question})
# st.chat_message("user").write(user_question)
# with st.spinner("Processing your question..."):
# response = chat_with_document(st.session_state.pdf_text, st.session_state.chat_history, user_question)
# st.session_state.chat_history.append({"role": "assistant", "content": response})
# st.chat_message("assistant").write(response)
# elif mode == "Test Your Knowledge":
# st.header("Test Your Knowledge")
# if num_questions is None or not st.session_state.get("gen_questions", False):
# st.info("Enter the number of questions and press 'Generate Questions' from the sidebar.")
# else:
# with st.spinner("Generating questions..."):
# questions_csv = generate_questions_from_text(st.session_state.pdf_text, num_questions)
# # Convert CSV output into a table (assuming header row "Question,Answer")
# try:
# lines = questions_csv.splitlines()
# if len(lines) < 2:
# st.error("Failed to generate questions properly.")
# else:
# header = lines[0].split(",")
# data = [line.split(",") for line in lines[1:]]
# st.table(data, headers=header)
# st.session_state.questions_table = data
# except Exception as e:
# st.error(f"Error processing questions: {e}")
# elif mode == "Flashcards":
# st.header("Practice Flashcards")
# if not st.session_state.get("gen_flashcards", False):
# st.info("Enter the number of flashcards and press 'Generate Flashcards' from the sidebar.")
# else:
# if st.button("Reset Flashcards"):
# st.session_state.flashcards = {}
# st.session_state.current_card = 0
# st.session_state.score = 0
# st.session_state.show_answer = False
# st.session_state.gen_flashcards = False
# if st.session_state.get("gen_flashcards", False):
# # Generate flashcards using the CrewAI module (which returns a Python dictionary)
# flashcards = generate_flashcards(st.session_state.pdf_file_path, num_flashcards)
# st.session_state.flashcards = flashcards
# st.session_state.current_card = 0
# st.session_state.score = 0
# st.session_state.show_answer = False
# st.success("Flashcards generated successfully!")
# st.session_state.gen_flashcards = False # reset flag after generation
# if not st.session_state.flashcards:
# st.info("No flashcards available. Click the 'Generate Flashcards' button in the sidebar.")
# else:
# total_cards = len(st.session_state.flashcards)
# if st.session_state.current_card >= total_cards:
# st.success(f"You've completed all flashcards! Final Score: {st.session_state.score} / {total_cards}")
# st.info("Restart the session or generate new flashcards from the sidebar.")
# else:
# flashcards = st.session_state.flashcards
# current_keys = list(flashcards.keys())
# current_question = current_keys[st.session_state.current_card]
# current_answer = flashcards[current_question]
# st.write(f"**Question:** {current_question}")
# if st.button("Show Answer"):
# st.session_state.show_answer = True
# if st.session_state.show_answer:
# st.write(f"**Answer:** {current_answer}")
# col1, col2 = st.columns(2)
# with col1:
# if st.button("Correct"):
# st.session_state.score += 1
# st.success("Correct!")
# with col2:
# if st.button("Wrong"):
# st.error("Incorrect!")
# if st.button("Next Card"):
# st.session_state.current_card += 1
# st.session_state.show_answer = False
# st.rerun()
# st.write(f"**Current Score:** {st.session_state.score} / {total_cards}")
######################################################################################################
# # ---------------------------
# # Helper Function: Extract text from PDF
# # ---------------------------
# def extract_text(uploaded_file):
# pdf_reader = PdfReader(uploaded_file)
# text = ""
# for page in pdf_reader.pages:
# page_text = page.extract_text()
# if page_text:
# text += page_text
# return text
# # ---------------------------
# # OpenAI Response Functions (using new style)
# # ---------------------------
# def generate_summary_from_text(text):
# prompt = (
# f"Summarize the following document in a concise manner, "
# "highlighting the key points that a student should know:\n\n{text}"
# )
# messages = [
# {"role": "system", "content": "You are an educational assistant."},
# {"role": "user", "content": prompt}
# ]
# completion = client.chat.completions.create(
# model="gpt-4o-mini",
# messages=messages
# )
# return completion.choices[0].message.content.strip()
# def chat_with_document(text, conversation_history, user_query):
# messages = conversation_history + [
# {"role": "user", "content": f"Based on the following document:\n\n{text}\n\nQuestion: {user_query}"}
# ]
# completion = client.chat.completions.create(
# model="gpt-4o-mini",
# messages=messages
# )
# return completion.choices[0].message.content.strip()
# def generate_flashcards_from_text(text, num_cards):
# prompt = (
# f"Generate {num_cards} flashcards based on the following document. \n\nDocument:\n\n{text} "
# "Return a Python dictionary where each key is a flashcard question and its corresponding value is the answer. "
# #"Do not include any additional text.\n\nDocument:\n\n{text}"
# )
# messages = [
# {"role": "system", "content": "You are an educational assistant that creates study flashcards."},
# {"role": "user", "content": prompt}
# ]
# completion = client.chat.completions.create(
# model="gpt-4o-mini",
# messages=messages
# )
# output = completion.choices[0].message.content.strip()
# try:
# # Use literal_eval to safely evaluate the string as a Python dictionary.
# flashcards = literal_eval(output)
# if isinstance(flashcards, dict):
# return flashcards
# else:
# return {}
# except Exception as e:
# st.error(f"Error parsing flashcards: {e}")
# return {}
# # ---------------------------
# # Sidebar: File Upload & Mode Selection
# # ---------------------------
# st.sidebar.title("Study Companion Setup")
# uploaded_pdf = st.sidebar.file_uploader("Upload your study PDF", type="pdf")
# mode = st.sidebar.radio("Select Mode", ("Summary", "Chat", "Flashcards"))
# num_flashcards = None
# if mode == "Flashcards":
# num_flashcards = st.sidebar.number_input("Number of flashcards to generate:", min_value=1, max_value=20, value=5, step=1)
# # ---------------------------
# # Session State Initialization
# # ---------------------------
# if "pdf_text" not in st.session_state:
# st.session_state.pdf_text = None
# if "summary" not in st.session_state:
# st.session_state.summary = None
# if "chat_history" not in st.session_state:
# st.session_state.chat_history = [{"role": "assistant", "content": "Hi, how can I help you with your study material?"}]
# if "flashcards" not in st.session_state:
# st.session_state.flashcards = {}
# if "current_card" not in st.session_state:
# st.session_state.current_card = 0
# if "score" not in st.session_state:
# st.session_state.score = 0
# if "show_answer" not in st.session_state:
# st.session_state.show_answer = False
# # ---------------------------
# # Process PDF Upload
# # ---------------------------
# if uploaded_pdf is not None:
# with tempfile.NamedTemporaryFile(delete=False, suffix=".pdf") as tmp:
# tmp.write(uploaded_pdf.read())
# st.session_state.pdf_file_path = tmp.name
# st.session_state.pdf_text = extract_text(uploaded_pdf)
# st.sidebar.success("PDF uploaded and processed successfully!")
# # ---------------------------
# # Main Area: Mode-Based Display
# # ---------------------------
# st.title("Study Companion: PDF-based Learning")
# if st.session_state.pdf_text is None:
# st.info("Please upload a PDF from the sidebar to begin.")
# else:
# if mode == "Summary":
# st.header("Summary & Key Points")
# if st.session_state.summary is None:
# with st.spinner("Generating summary..."):
# st.session_state.summary = generate_summary_from_text(st.session_state.pdf_text)
# st.write(st.session_state.summary)
# elif mode == "Chat":
# st.header("Chat with Your Study Companion")
# for msg in st.session_state.chat_history:
# st.chat_message(msg["role"]).write(msg["content"])
# user_question = st.chat_input("Ask a question about the document:")
# if user_question:
# st.session_state.chat_history.append({"role": "user", "content": user_question})
# st.chat_message("user").write(user_question)
# with st.spinner("Processing your question..."):
# response = chat_with_document(st.session_state.pdf_text, st.session_state.chat_history, user_question)
# st.session_state.chat_history.append({"role": "assistant", "content": response})
# st.chat_message("assistant").write(response)
# elif mode == "Flashcards":
# st.header("Practice Flashcards")
# if st.button("Generate Flashcards"):
# with st.spinner("Generating flashcards..."):
# flashcards = generate_flashcards_from_text(st.session_state.pdf_text, num_flashcards)
# st.session_state.flashcards = flashcards
# st.session_state.current_card = 0
# st.session_state.score = 0
# st.session_state.show_answer = False
# st.success("Flashcards generated successfully!")
# if not st.session_state.flashcards:
# st.info("No flashcards available. Click the button above to generate flashcards.")
# else:
# total_cards = len(st.session_state.flashcards)
# if st.session_state.current_card >= total_cards:
# st.success(f"You've completed all flashcards! Final Score: {st.session_state.score} / {total_cards}")
# st.info("Restart the session or generate new flashcards from the sidebar.")
# else:
# flashcards = st.session_state.flashcards
# current_keys = list(flashcards.keys())
# current_question = current_keys[st.session_state.current_card]
# current_answer = flashcards[current_question]
# st.write(f"**Question:** {current_question}")
# if st.button("Show Answer"):
# st.session_state.show_answer = True
# if st.session_state.show_answer:
# st.write(f"**Answer:** {current_answer}")
# col1, col2 = st.columns(2)
# with col1:
# if st.button("Correct"):
# st.session_state.score += 1
# st.success("Correct!")
# with col2:
# if st.button("Wrong"):
# st.error("Incorrect!")
# if st.button("Next Card"):
# st.session_state.current_card += 1
# st.session_state.show_answer = False
# st.rerun()
# st.write(f"**Current Score:** {st.session_state.score} / {total_cards}")
# # ---------------------------
# # Helper Function: Extract text from PDF
# # ---------------------------
# def extract_text(uploaded_file):
# pdf_reader = PdfReader(uploaded_file)
# text = ""
# for page in pdf_reader.pages:
# page_text = page.extract_text()
# if page_text:
# text += page_text
# return text
# # ---------------------------
# # OpenAI Response Functions (using new style)
# # ---------------------------
# def generate_summary_from_text(text):
# prompt = (
# f"Summarize the following document in a concise manner, "
# "highlighting the key points that a student should know:\n\n{text}"
# )
# messages = [
# {"role": "system", "content": "You are an educational assistant."},
# {"role": "user", "content": prompt}
# ]
# completion = client.chat.completions.create(
# model="gpt-4o-mini",
# messages=messages
# )
# return completion.choices[0].message.content.strip()
# def chat_with_document(text, conversation_history, user_query):
# # Build a message list that includes the conversation history plus the new query with context.
# messages = conversation_history + [
# {"role": "user", "content": f"Based on the following document:\n\n{text}\n\nQuestion: {user_query}"}
# ]
# completion = client.chat.completions.create(
# model="gpt-4o-mini",
# messages=messages
# )
# return completion.choices[0].message.content.strip()
# def generate_flashcards_from_text(text, num_cards):
# prompt = (
# f"Generate {num_cards} flashcards based on the following document. "
# "Return a Python dictionary (in valid JSON format) where each key is a flashcard question and its value is the corresponding answer. "
# f"Document:\n\n{text}"
# )
# messages = [
# {"role": "system", "content": "You are an educational assistant that creates study flashcards."},
# {"role": "user", "content": prompt}
# ]
# completion = client.chat.completions.create(
# model="gpt-4o-mini",
# messages=messages
# )
# output = completion.choices[0].message.content.strip()
# try:
# flashcards = json.loads(output)
# if isinstance(flashcards, dict):
# return flashcards
# else:
# return {}
# except Exception as e:
# st.error(f"Error parsing flashcards: {e}")
# return {}
# # ---------------------------
# # Sidebar: File Upload & Mode Selection
# # ---------------------------
# st.sidebar.title("Study Companion Setup")
# uploaded_pdf = st.sidebar.file_uploader("Upload your study PDF", type="pdf")
# mode = st.sidebar.radio("Select Mode", ("Summary", "Chat", "Flashcards"))
# # For Flashcards, allow user to input number of flashcards
# num_flashcards = None
# if mode == "Flashcards":
# num_flashcards = st.sidebar.number_input("Number of flashcards to generate:", min_value=1, max_value=20, value=5, step=1)
# # ---------------------------
# # Session State Initialization
# # ---------------------------
# if "pdf_text" not in st.session_state:
# st.session_state.pdf_text = None
# if "summary" not in st.session_state:
# st.session_state.summary = None
# if "chat_history" not in st.session_state:
# st.session_state.chat_history = [{"role": "assistant", "content": "Hi, how can I help you with your study material?"}]
# if "flashcards" not in st.session_state:
# st.session_state.flashcards = {}
# if "current_card" not in st.session_state:
# st.session_state.current_card = 0
# if "score" not in st.session_state:
# st.session_state.score = 0
# if "show_answer" not in st.session_state:
# st.session_state.show_answer = False
# # ---------------------------
# # Process PDF Upload
# # ---------------------------
# if uploaded_pdf is not None:
# with tempfile.NamedTemporaryFile(delete=False, suffix=".pdf") as tmp:
# tmp.write(uploaded_pdf.read())
# pdf_file_path = tmp.name
# # Extract text from the PDF (all pages)
# st.session_state.pdf_text = extract_text(pdf_file_path)
# st.sidebar.success("PDF uploaded and processed successfully!")
# # ---------------------------
# # Main Area: Mode-Based Display
# # ---------------------------
# st.title("Study Companion: PDF-based Learning")
# if st.session_state.pdf_text is None:
# st.info("Please upload a PDF from the sidebar to begin.")
# else:
# if mode == "Summary":
# st.header("Summary & Key Points")
# if st.session_state.summary is None:
# with st.spinner("Generating summary..."):
# st.session_state.summary = generate_summary_from_text(st.session_state.pdf_text)
# st.write(st.session_state.summary)
# elif mode == "Chat":
# st.header("Chat with Your Study Companion")
# # Display persistent chat history
# for msg in st.session_state.chat_history:
# st.chat_message(msg["role"]).write(msg["content"])
# user_question = st.chat_input("Ask a question about the document:")
# if user_question:
# st.session_state.chat_history.append({"role": "user", "content": user_question})
# st.chat_message("user").write(user_question)
# with st.spinner("Processing your question..."):
# response = chat_with_document(st.session_state.pdf_text, st.session_state.chat_history, user_question)
# st.session_state.chat_history.append({"role": "assistant", "content": response})
# st.chat_message("assistant").write(response)
# elif mode == "Flashcards":
# st.header("Practice Flashcards")
# # Provide a button to generate flashcards on demand.
# if st.button("Generate Flashcards"):
# with st.spinner("Generating flashcards..."):
# flashcards = generate_flashcards_from_text(st.session_state.pdf_text, num_flashcards)
# st.session_state.flashcards = flashcards
# st.session_state.current_card = 0
# st.session_state.score = 0
# st.session_state.show_answer = False
# st.success("Flashcards generated successfully!")
# if not st.session_state.flashcards:
# st.info("No flashcards available. Click the button above to generate flashcards.")
# else:
# total_cards = len(st.session_state.flashcards)
# if st.session_state.current_card >= total_cards:
# st.success(f"You've completed all flashcards! Final Score: {st.session_state.score} / {total_cards}")
# st.info("Restart the session or generate new flashcards from the sidebar.")
# else:
# flashcards = st.session_state.flashcards
# # Get the current flashcard key-value pair.
# current_keys = list(flashcards.keys())
# current_key = current_keys[st.session_state.current_card]
# current_answer = flashcards[current_key]
# st.write(f"**Question:** {current_key}")
# if st.button("Show Answer"):
# st.session_state.show_answer = True
# if st.session_state.show_answer:
# st.write(f"**Answer:** {current_answer}")
# col1, col2 = st.columns(2)
# with col1:
# if st.button("Correct"):
# st.session_state.score += 1
# st.success("Correct!")
# with col2:
# if st.button("Wrong"):
# st.error("Incorrect!")
# if st.button("Next Card"):
# st.session_state.current_card += 1
# st.session_state.show_answer = False
# st.rerun()
# st.write(f"**Current Score:** {st.session_state.score} / {total_cards}")
|