Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
|
@@ -1,15 +1,14 @@
|
|
| 1 |
import streamlit as st
|
| 2 |
-
import os
|
| 3 |
import tempfile
|
| 4 |
import json
|
| 5 |
import random
|
|
|
|
| 6 |
from PyPDF2 import PdfReader
|
| 7 |
-
|
| 8 |
|
| 9 |
-
#
|
| 10 |
-
|
| 11 |
-
|
| 12 |
-
openai.api_key = os.getenv("OPENAI_API_KEY") # Ensure this is set in your environment/Space secrets
|
| 13 |
|
| 14 |
# ---------------------------
|
| 15 |
# Helper Function: Extract text from PDF
|
|
@@ -18,28 +17,39 @@ def extract_text(uploaded_file):
|
|
| 18 |
pdf_reader = PdfReader(uploaded_file)
|
| 19 |
text = ""
|
| 20 |
for page in pdf_reader.pages:
|
| 21 |
-
|
|
|
|
|
|
|
| 22 |
return text
|
| 23 |
|
| 24 |
# ---------------------------
|
| 25 |
-
# OpenAI
|
| 26 |
# ---------------------------
|
| 27 |
def generate_summary_from_text(text):
|
| 28 |
-
prompt =
|
|
|
|
|
|
|
|
|
|
| 29 |
messages = [
|
| 30 |
{"role": "system", "content": "You are an educational assistant."},
|
| 31 |
{"role": "user", "content": prompt}
|
| 32 |
]
|
| 33 |
-
|
| 34 |
-
|
|
|
|
|
|
|
|
|
|
| 35 |
|
| 36 |
def chat_with_document(text, conversation_history, user_query):
|
| 37 |
-
#
|
| 38 |
messages = conversation_history + [
|
| 39 |
-
{"role": "user", "content": f"
|
| 40 |
]
|
| 41 |
-
|
| 42 |
-
|
|
|
|
|
|
|
|
|
|
| 43 |
|
| 44 |
def generate_flashcards_from_text(text, num_cards):
|
| 45 |
prompt = (
|
|
@@ -51,10 +61,12 @@ def generate_flashcards_from_text(text, num_cards):
|
|
| 51 |
{"role": "system", "content": "You are an educational assistant that creates study flashcards."},
|
| 52 |
{"role": "user", "content": prompt}
|
| 53 |
]
|
| 54 |
-
|
| 55 |
-
|
|
|
|
|
|
|
|
|
|
| 56 |
try:
|
| 57 |
-
# Try to parse the output as JSON and convert it into a Python dict.
|
| 58 |
flashcards = json.loads(output)
|
| 59 |
if isinstance(flashcards, dict):
|
| 60 |
return flashcards
|
|
@@ -65,14 +77,14 @@ def generate_flashcards_from_text(text, num_cards):
|
|
| 65 |
return {}
|
| 66 |
|
| 67 |
# ---------------------------
|
| 68 |
-
# Sidebar: Upload
|
| 69 |
# ---------------------------
|
| 70 |
st.sidebar.title("Study Companion Setup")
|
| 71 |
|
| 72 |
uploaded_pdf = st.sidebar.file_uploader("Upload your study PDF", type="pdf")
|
| 73 |
mode = st.sidebar.radio("Select Mode", ("Summary", "Chat", "Flashcards"))
|
| 74 |
|
| 75 |
-
# For Flashcards
|
| 76 |
num_flashcards = None
|
| 77 |
if mode == "Flashcards":
|
| 78 |
num_flashcards = st.sidebar.number_input("Number of flashcards to generate:", min_value=1, max_value=20, value=5, step=1)
|
|
@@ -102,7 +114,7 @@ if uploaded_pdf is not None:
|
|
| 102 |
with tempfile.NamedTemporaryFile(delete=False, suffix=".pdf") as tmp:
|
| 103 |
tmp.write(uploaded_pdf.read())
|
| 104 |
pdf_file_path = tmp.name
|
| 105 |
-
# Extract
|
| 106 |
st.session_state.pdf_text = extract_text(pdf_file_path)
|
| 107 |
st.sidebar.success("PDF uploaded and processed successfully!")
|
| 108 |
|
|
@@ -116,7 +128,6 @@ if st.session_state.pdf_text is None:
|
|
| 116 |
else:
|
| 117 |
if mode == "Summary":
|
| 118 |
st.header("Summary & Key Points")
|
| 119 |
-
# Generate summary only once
|
| 120 |
if st.session_state.summary is None:
|
| 121 |
with st.spinner("Generating summary..."):
|
| 122 |
st.session_state.summary = generate_summary_from_text(st.session_state.pdf_text)
|
|
@@ -124,12 +135,11 @@ else:
|
|
| 124 |
|
| 125 |
elif mode == "Chat":
|
| 126 |
st.header("Chat with Your Study Companion")
|
| 127 |
-
# Display chat history
|
| 128 |
for msg in st.session_state.chat_history:
|
| 129 |
st.chat_message(msg["role"]).write(msg["content"])
|
| 130 |
user_question = st.chat_input("Ask a question about the document:")
|
| 131 |
if user_question:
|
| 132 |
-
# Preserve current history and then update
|
| 133 |
st.session_state.chat_history.append({"role": "user", "content": user_question})
|
| 134 |
st.chat_message("user").write(user_question)
|
| 135 |
with st.spinner("Processing your question..."):
|
|
@@ -152,14 +162,12 @@ else:
|
|
| 152 |
if not st.session_state.flashcards:
|
| 153 |
st.info("No flashcards available. Click the button above to generate flashcards.")
|
| 154 |
else:
|
| 155 |
-
|
| 156 |
-
flashcards = st.session_state.flashcards
|
| 157 |
-
total_cards = len(flashcards)
|
| 158 |
-
# Check if all flashcards have been practiced.
|
| 159 |
if st.session_state.current_card >= total_cards:
|
| 160 |
st.success(f"You've completed all flashcards! Final Score: {st.session_state.score} / {total_cards}")
|
| 161 |
st.info("Restart the session or generate new flashcards from the sidebar.")
|
| 162 |
else:
|
|
|
|
| 163 |
# Get the current flashcard key-value pair.
|
| 164 |
current_keys = list(flashcards.keys())
|
| 165 |
current_key = current_keys[st.session_state.current_card]
|
|
|
|
| 1 |
import streamlit as st
|
|
|
|
| 2 |
import tempfile
|
| 3 |
import json
|
| 4 |
import random
|
| 5 |
+
from pathlib import Path
|
| 6 |
from PyPDF2 import PdfReader
|
| 7 |
+
from openai import OpenAI
|
| 8 |
|
| 9 |
+
# Initialize the OpenAI client
|
| 10 |
+
api_key = os.getenv("OPENAI_API_KEY")
|
| 11 |
+
client = OpenAI(api_key = api_key)
|
|
|
|
| 12 |
|
| 13 |
# ---------------------------
|
| 14 |
# Helper Function: Extract text from PDF
|
|
|
|
| 17 |
pdf_reader = PdfReader(uploaded_file)
|
| 18 |
text = ""
|
| 19 |
for page in pdf_reader.pages:
|
| 20 |
+
page_text = page.extract_text()
|
| 21 |
+
if page_text:
|
| 22 |
+
text += page_text
|
| 23 |
return text
|
| 24 |
|
| 25 |
# ---------------------------
|
| 26 |
+
# OpenAI Response Functions (using new style)
|
| 27 |
# ---------------------------
|
| 28 |
def generate_summary_from_text(text):
|
| 29 |
+
prompt = (
|
| 30 |
+
f"Summarize the following document in a concise manner, "
|
| 31 |
+
"highlighting the key points that a student should know:\n\n{text}"
|
| 32 |
+
)
|
| 33 |
messages = [
|
| 34 |
{"role": "system", "content": "You are an educational assistant."},
|
| 35 |
{"role": "user", "content": prompt}
|
| 36 |
]
|
| 37 |
+
completion = client.chat.completions.create(
|
| 38 |
+
model="gpt-4o-mini",
|
| 39 |
+
messages=messages
|
| 40 |
+
)
|
| 41 |
+
return completion.choices[0].message.content.strip()
|
| 42 |
|
| 43 |
def chat_with_document(text, conversation_history, user_query):
|
| 44 |
+
# Build a message list that includes the conversation history plus the new query with context.
|
| 45 |
messages = conversation_history + [
|
| 46 |
+
{"role": "user", "content": f"Based on the following document:\n\n{text}\n\nQuestion: {user_query}"}
|
| 47 |
]
|
| 48 |
+
completion = client.chat.completions.create(
|
| 49 |
+
model="gpt-4o-mini",
|
| 50 |
+
messages=messages
|
| 51 |
+
)
|
| 52 |
+
return completion.choices[0].message.content.strip()
|
| 53 |
|
| 54 |
def generate_flashcards_from_text(text, num_cards):
|
| 55 |
prompt = (
|
|
|
|
| 61 |
{"role": "system", "content": "You are an educational assistant that creates study flashcards."},
|
| 62 |
{"role": "user", "content": prompt}
|
| 63 |
]
|
| 64 |
+
completion = client.chat.completions.create(
|
| 65 |
+
model="gpt-4o-mini",
|
| 66 |
+
messages=messages
|
| 67 |
+
)
|
| 68 |
+
output = completion.choices[0].message.content.strip()
|
| 69 |
try:
|
|
|
|
| 70 |
flashcards = json.loads(output)
|
| 71 |
if isinstance(flashcards, dict):
|
| 72 |
return flashcards
|
|
|
|
| 77 |
return {}
|
| 78 |
|
| 79 |
# ---------------------------
|
| 80 |
+
# Sidebar: File Upload & Mode Selection
|
| 81 |
# ---------------------------
|
| 82 |
st.sidebar.title("Study Companion Setup")
|
| 83 |
|
| 84 |
uploaded_pdf = st.sidebar.file_uploader("Upload your study PDF", type="pdf")
|
| 85 |
mode = st.sidebar.radio("Select Mode", ("Summary", "Chat", "Flashcards"))
|
| 86 |
|
| 87 |
+
# For Flashcards, allow user to input number of flashcards
|
| 88 |
num_flashcards = None
|
| 89 |
if mode == "Flashcards":
|
| 90 |
num_flashcards = st.sidebar.number_input("Number of flashcards to generate:", min_value=1, max_value=20, value=5, step=1)
|
|
|
|
| 114 |
with tempfile.NamedTemporaryFile(delete=False, suffix=".pdf") as tmp:
|
| 115 |
tmp.write(uploaded_pdf.read())
|
| 116 |
pdf_file_path = tmp.name
|
| 117 |
+
# Extract text from the PDF (all pages)
|
| 118 |
st.session_state.pdf_text = extract_text(pdf_file_path)
|
| 119 |
st.sidebar.success("PDF uploaded and processed successfully!")
|
| 120 |
|
|
|
|
| 128 |
else:
|
| 129 |
if mode == "Summary":
|
| 130 |
st.header("Summary & Key Points")
|
|
|
|
| 131 |
if st.session_state.summary is None:
|
| 132 |
with st.spinner("Generating summary..."):
|
| 133 |
st.session_state.summary = generate_summary_from_text(st.session_state.pdf_text)
|
|
|
|
| 135 |
|
| 136 |
elif mode == "Chat":
|
| 137 |
st.header("Chat with Your Study Companion")
|
| 138 |
+
# Display persistent chat history
|
| 139 |
for msg in st.session_state.chat_history:
|
| 140 |
st.chat_message(msg["role"]).write(msg["content"])
|
| 141 |
user_question = st.chat_input("Ask a question about the document:")
|
| 142 |
if user_question:
|
|
|
|
| 143 |
st.session_state.chat_history.append({"role": "user", "content": user_question})
|
| 144 |
st.chat_message("user").write(user_question)
|
| 145 |
with st.spinner("Processing your question..."):
|
|
|
|
| 162 |
if not st.session_state.flashcards:
|
| 163 |
st.info("No flashcards available. Click the button above to generate flashcards.")
|
| 164 |
else:
|
| 165 |
+
total_cards = len(st.session_state.flashcards)
|
|
|
|
|
|
|
|
|
|
| 166 |
if st.session_state.current_card >= total_cards:
|
| 167 |
st.success(f"You've completed all flashcards! Final Score: {st.session_state.score} / {total_cards}")
|
| 168 |
st.info("Restart the session or generate new flashcards from the sidebar.")
|
| 169 |
else:
|
| 170 |
+
flashcards = st.session_state.flashcards
|
| 171 |
# Get the current flashcard key-value pair.
|
| 172 |
current_keys = list(flashcards.keys())
|
| 173 |
current_key = current_keys[st.session_state.current_card]
|