Spaces:
Running
Running
Update app.py
Browse files
app.py
CHANGED
|
@@ -13,18 +13,19 @@ api_key = os.getenv("OPENAI_API_KEY")
|
|
| 13 |
client = OpenAI(api_key = api_key)
|
| 14 |
|
| 15 |
|
|
|
|
|
|
|
| 16 |
|
| 17 |
# ---------------------------
|
| 18 |
# Helper Function: Extract text from PDF
|
| 19 |
# ---------------------------
|
| 20 |
def extract_text(uploaded_file):
|
| 21 |
-
#
|
| 22 |
uploaded_file.seek(0, os.SEEK_END)
|
| 23 |
-
|
| 24 |
-
|
| 25 |
-
if file_size > 10 * 1024 * 1024:
|
| 26 |
-
st.error("File size exceeds 10MB limit.")
|
| 27 |
return ""
|
|
|
|
| 28 |
pdf_reader = PdfReader(uploaded_file)
|
| 29 |
text = ""
|
| 30 |
for page in pdf_reader.pages:
|
|
@@ -34,7 +35,7 @@ def extract_text(uploaded_file):
|
|
| 34 |
return text
|
| 35 |
|
| 36 |
# ---------------------------
|
| 37 |
-
# OpenAI Response Functions
|
| 38 |
# ---------------------------
|
| 39 |
def generate_summary_from_text(text):
|
| 40 |
prompt = (
|
|
@@ -62,8 +63,8 @@ def chat_with_document(text, conversation_history, user_query):
|
|
| 62 |
|
| 63 |
def generate_questions_from_text(text, num_questions):
|
| 64 |
prompt = (
|
| 65 |
-
f"Generate
|
| 66 |
-
|
| 67 |
)
|
| 68 |
messages = [
|
| 69 |
{"role": "system", "content": "You are an educational assistant that generates study questions."},
|
|
@@ -73,33 +74,9 @@ def generate_questions_from_text(text, num_questions):
|
|
| 73 |
model="gpt-4o-mini",
|
| 74 |
messages=messages
|
| 75 |
)
|
|
|
|
| 76 |
return completion.choices[0].message.content.strip()
|
| 77 |
|
| 78 |
-
def generate_flashcards_from_text(text, num_cards):
|
| 79 |
-
prompt = (
|
| 80 |
-
f"Generate {num_cards} flashcards based on the following document.\n\nDocument:\n\n{text}\n\n"
|
| 81 |
-
"Return a Python dictionary where each key is a flashcard question and its corresponding value is the answer. "
|
| 82 |
-
"Do not include any additional text."
|
| 83 |
-
)
|
| 84 |
-
messages = [
|
| 85 |
-
{"role": "system", "content": "You are an educational assistant that creates study flashcards."},
|
| 86 |
-
{"role": "user", "content": prompt}
|
| 87 |
-
]
|
| 88 |
-
completion = client.chat.completions.create(
|
| 89 |
-
model="gpt-4o-mini",
|
| 90 |
-
messages=messages
|
| 91 |
-
)
|
| 92 |
-
output = completion.choices[0].message.content.strip()
|
| 93 |
-
try:
|
| 94 |
-
flashcards = literal_eval(output)
|
| 95 |
-
if isinstance(flashcards, dict):
|
| 96 |
-
return flashcards
|
| 97 |
-
else:
|
| 98 |
-
return {}
|
| 99 |
-
except Exception as e:
|
| 100 |
-
st.error(f"Error parsing flashcards: {e}")
|
| 101 |
-
return {}
|
| 102 |
-
|
| 103 |
# ---------------------------
|
| 104 |
# Sidebar: File Upload & Mode Selection
|
| 105 |
# ---------------------------
|
|
@@ -108,13 +85,19 @@ st.sidebar.title("Study Companion Setup")
|
|
| 108 |
uploaded_pdf = st.sidebar.file_uploader("Upload your study PDF (max 10MB)", type="pdf")
|
| 109 |
mode = st.sidebar.radio("Select Mode", ("Chat", "Test Your Knowledge", "Flashcards"))
|
| 110 |
|
| 111 |
-
# For Test Your Knowledge
|
| 112 |
num_questions = None
|
| 113 |
-
num_flashcards = None
|
| 114 |
if mode == "Test Your Knowledge":
|
| 115 |
num_questions = st.sidebar.number_input("Number of questions to generate (max 50):", min_value=1, max_value=50, value=10, step=1)
|
| 116 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 117 |
num_flashcards = st.sidebar.number_input("Number of flashcards to generate (max 5):", min_value=1, max_value=5, value=3, step=1)
|
|
|
|
|
|
|
| 118 |
|
| 119 |
# ---------------------------
|
| 120 |
# Session State Initialization
|
|
@@ -140,14 +123,17 @@ if "show_answer" not in st.session_state:
|
|
| 140 |
# Process PDF Upload
|
| 141 |
# ---------------------------
|
| 142 |
if uploaded_pdf is not None:
|
|
|
|
|
|
|
|
|
|
| 143 |
st.session_state.pdf_text = extract_text(uploaded_pdf)
|
| 144 |
if st.session_state.pdf_text:
|
| 145 |
st.sidebar.success("PDF uploaded and processed successfully!")
|
| 146 |
else:
|
| 147 |
-
st.sidebar.error("Failed to extract text
|
| 148 |
|
| 149 |
# ---------------------------
|
| 150 |
-
# Main Area: Mode-Based Display (
|
| 151 |
# ---------------------------
|
| 152 |
st.title("Study Companion: PDF-based Learning")
|
| 153 |
|
|
@@ -156,7 +142,6 @@ if st.session_state.pdf_text is None:
|
|
| 156 |
else:
|
| 157 |
if mode == "Chat":
|
| 158 |
st.header("Chat with Your Study Companion")
|
| 159 |
-
# Display persistent chat history
|
| 160 |
for msg in st.session_state.chat_history:
|
| 161 |
st.chat_message(msg["role"]).write(msg["content"])
|
| 162 |
user_question = st.chat_input("Ask a question about the document:")
|
|
@@ -170,59 +155,288 @@ else:
|
|
| 170 |
|
| 171 |
elif mode == "Test Your Knowledge":
|
| 172 |
st.header("Test Your Knowledge")
|
| 173 |
-
if num_questions is None:
|
| 174 |
-
st.info("
|
| 175 |
else:
|
| 176 |
with st.spinner("Generating questions..."):
|
| 177 |
-
|
| 178 |
-
#
|
| 179 |
-
|
| 180 |
-
|
| 181 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 182 |
|
| 183 |
elif mode == "Flashcards":
|
| 184 |
st.header("Practice Flashcards")
|
| 185 |
-
if st.
|
| 186 |
-
|
| 187 |
-
flashcards = generate_flashcards_from_text(st.session_state.pdf_text, num_flashcards)
|
| 188 |
-
st.session_state.flashcards = flashcards
|
| 189 |
-
st.session_state.current_card = 0
|
| 190 |
-
st.session_state.score = 0
|
| 191 |
-
st.session_state.show_answer = False
|
| 192 |
-
st.success("Flashcards generated successfully!")
|
| 193 |
-
|
| 194 |
-
if not st.session_state.flashcards:
|
| 195 |
-
st.info("No flashcards available. Click the button above to generate flashcards.")
|
| 196 |
else:
|
| 197 |
-
|
| 198 |
-
|
| 199 |
-
st.
|
| 200 |
-
st.
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 201 |
else:
|
| 202 |
-
|
| 203 |
-
|
| 204 |
-
|
| 205 |
-
|
| 206 |
-
|
| 207 |
-
|
| 208 |
-
|
| 209 |
-
|
| 210 |
-
|
| 211 |
-
|
| 212 |
-
|
| 213 |
-
|
| 214 |
-
|
| 215 |
-
|
| 216 |
-
|
| 217 |
-
|
| 218 |
-
st.
|
| 219 |
-
|
| 220 |
-
|
| 221 |
-
|
| 222 |
-
|
| 223 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 224 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 225 |
|
|
|
|
| 226 |
|
| 227 |
|
| 228 |
# # ---------------------------
|
|
|
|
| 13 |
client = OpenAI(api_key = api_key)
|
| 14 |
|
| 15 |
|
| 16 |
+
# Import the CrewAI flashcard module (modified below to remove page range)
|
| 17 |
+
from crewai_flashcard import generate_flashcards
|
| 18 |
|
| 19 |
# ---------------------------
|
| 20 |
# Helper Function: Extract text from PDF
|
| 21 |
# ---------------------------
|
| 22 |
def extract_text(uploaded_file):
|
| 23 |
+
# Ensure file size is less than 10MB
|
| 24 |
uploaded_file.seek(0, os.SEEK_END)
|
| 25 |
+
if uploaded_file.tell() > 10 * 1024 * 1024:
|
| 26 |
+
st.error("File exceeds 10MB limit.")
|
|
|
|
|
|
|
| 27 |
return ""
|
| 28 |
+
uploaded_file.seek(0)
|
| 29 |
pdf_reader = PdfReader(uploaded_file)
|
| 30 |
text = ""
|
| 31 |
for page in pdf_reader.pages:
|
|
|
|
| 35 |
return text
|
| 36 |
|
| 37 |
# ---------------------------
|
| 38 |
+
# OpenAI Response Functions
|
| 39 |
# ---------------------------
|
| 40 |
def generate_summary_from_text(text):
|
| 41 |
prompt = (
|
|
|
|
| 63 |
|
| 64 |
def generate_questions_from_text(text, num_questions):
|
| 65 |
prompt = (
|
| 66 |
+
f"Generate {num_questions} study questions with answers based on the following document. "
|
| 67 |
+
"Return the output as a table in CSV format with two columns: 'Question' and 'Answer'.\n\nDocument:\n\n{text}"
|
| 68 |
)
|
| 69 |
messages = [
|
| 70 |
{"role": "system", "content": "You are an educational assistant that generates study questions."},
|
|
|
|
| 74 |
model="gpt-4o-mini",
|
| 75 |
messages=messages
|
| 76 |
)
|
| 77 |
+
# Expecting CSV output (with header: Question,Answer)
|
| 78 |
return completion.choices[0].message.content.strip()
|
| 79 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 80 |
# ---------------------------
|
| 81 |
# Sidebar: File Upload & Mode Selection
|
| 82 |
# ---------------------------
|
|
|
|
| 85 |
uploaded_pdf = st.sidebar.file_uploader("Upload your study PDF (max 10MB)", type="pdf")
|
| 86 |
mode = st.sidebar.radio("Select Mode", ("Chat", "Test Your Knowledge", "Flashcards"))
|
| 87 |
|
| 88 |
+
# For Test Your Knowledge: number of questions (max 50)
|
| 89 |
num_questions = None
|
|
|
|
| 90 |
if mode == "Test Your Knowledge":
|
| 91 |
num_questions = st.sidebar.number_input("Number of questions to generate (max 50):", min_value=1, max_value=50, value=10, step=1)
|
| 92 |
+
if st.sidebar.button("Generate Questions"):
|
| 93 |
+
st.session_state.gen_questions = True
|
| 94 |
+
|
| 95 |
+
# For Flashcards: number of flashcards (max 5)
|
| 96 |
+
num_flashcards = None
|
| 97 |
+
if mode == "Flashcards":
|
| 98 |
num_flashcards = st.sidebar.number_input("Number of flashcards to generate (max 5):", min_value=1, max_value=5, value=3, step=1)
|
| 99 |
+
if st.sidebar.button("Generate Flashcards"):
|
| 100 |
+
st.session_state.gen_flashcards = True
|
| 101 |
|
| 102 |
# ---------------------------
|
| 103 |
# Session State Initialization
|
|
|
|
| 123 |
# Process PDF Upload
|
| 124 |
# ---------------------------
|
| 125 |
if uploaded_pdf is not None:
|
| 126 |
+
with tempfile.NamedTemporaryFile(delete=False, suffix=".pdf") as tmp:
|
| 127 |
+
tmp.write(uploaded_pdf.read())
|
| 128 |
+
st.session_state.pdf_file_path = tmp.name
|
| 129 |
st.session_state.pdf_text = extract_text(uploaded_pdf)
|
| 130 |
if st.session_state.pdf_text:
|
| 131 |
st.sidebar.success("PDF uploaded and processed successfully!")
|
| 132 |
else:
|
| 133 |
+
st.sidebar.error("Failed to extract text from the PDF.")
|
| 134 |
|
| 135 |
# ---------------------------
|
| 136 |
+
# Main Area: Mode-Based Display (using side menu)
|
| 137 |
# ---------------------------
|
| 138 |
st.title("Study Companion: PDF-based Learning")
|
| 139 |
|
|
|
|
| 142 |
else:
|
| 143 |
if mode == "Chat":
|
| 144 |
st.header("Chat with Your Study Companion")
|
|
|
|
| 145 |
for msg in st.session_state.chat_history:
|
| 146 |
st.chat_message(msg["role"]).write(msg["content"])
|
| 147 |
user_question = st.chat_input("Ask a question about the document:")
|
|
|
|
| 155 |
|
| 156 |
elif mode == "Test Your Knowledge":
|
| 157 |
st.header("Test Your Knowledge")
|
| 158 |
+
if num_questions is None or not st.session_state.get("gen_questions", False):
|
| 159 |
+
st.info("Enter the number of questions and press 'Generate Questions' from the sidebar.")
|
| 160 |
else:
|
| 161 |
with st.spinner("Generating questions..."):
|
| 162 |
+
questions_csv = generate_questions_from_text(st.session_state.pdf_text, num_questions)
|
| 163 |
+
# Convert CSV output into a table (assuming header row "Question,Answer")
|
| 164 |
+
try:
|
| 165 |
+
lines = questions_csv.splitlines()
|
| 166 |
+
if len(lines) < 2:
|
| 167 |
+
st.error("Failed to generate questions properly.")
|
| 168 |
+
else:
|
| 169 |
+
header = lines[0].split(",")
|
| 170 |
+
data = [line.split(",") for line in lines[1:]]
|
| 171 |
+
st.table(data, headers=header)
|
| 172 |
+
st.session_state.questions_table = data
|
| 173 |
+
except Exception as e:
|
| 174 |
+
st.error(f"Error processing questions: {e}")
|
| 175 |
|
| 176 |
elif mode == "Flashcards":
|
| 177 |
st.header("Practice Flashcards")
|
| 178 |
+
if not st.session_state.get("gen_flashcards", False):
|
| 179 |
+
st.info("Enter the number of flashcards and press 'Generate Flashcards' from the sidebar.")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 180 |
else:
|
| 181 |
+
if st.button("Reset Flashcards"):
|
| 182 |
+
st.session_state.flashcards = {}
|
| 183 |
+
st.session_state.current_card = 0
|
| 184 |
+
st.session_state.score = 0
|
| 185 |
+
st.session_state.show_answer = False
|
| 186 |
+
st.session_state.gen_flashcards = False
|
| 187 |
+
if st.session_state.get("gen_flashcards", False):
|
| 188 |
+
# Generate flashcards using the CrewAI module (which returns a Python dictionary)
|
| 189 |
+
flashcards = generate_flashcards(st.session_state.pdf_file_path, num_flashcards)
|
| 190 |
+
st.session_state.flashcards = flashcards
|
| 191 |
+
st.session_state.current_card = 0
|
| 192 |
+
st.session_state.score = 0
|
| 193 |
+
st.session_state.show_answer = False
|
| 194 |
+
st.success("Flashcards generated successfully!")
|
| 195 |
+
st.session_state.gen_flashcards = False # reset flag after generation
|
| 196 |
+
|
| 197 |
+
if not st.session_state.flashcards:
|
| 198 |
+
st.info("No flashcards available. Click the 'Generate Flashcards' button in the sidebar.")
|
| 199 |
else:
|
| 200 |
+
total_cards = len(st.session_state.flashcards)
|
| 201 |
+
if st.session_state.current_card >= total_cards:
|
| 202 |
+
st.success(f"You've completed all flashcards! Final Score: {st.session_state.score} / {total_cards}")
|
| 203 |
+
st.info("Restart the session or generate new flashcards from the sidebar.")
|
| 204 |
+
else:
|
| 205 |
+
flashcards = st.session_state.flashcards
|
| 206 |
+
current_keys = list(flashcards.keys())
|
| 207 |
+
current_question = current_keys[st.session_state.current_card]
|
| 208 |
+
current_answer = flashcards[current_question]
|
| 209 |
+
st.write(f"**Question:** {current_question}")
|
| 210 |
+
if st.button("Show Answer"):
|
| 211 |
+
st.session_state.show_answer = True
|
| 212 |
+
if st.session_state.show_answer:
|
| 213 |
+
st.write(f"**Answer:** {current_answer}")
|
| 214 |
+
col1, col2 = st.columns(2)
|
| 215 |
+
with col1:
|
| 216 |
+
if st.button("Correct"):
|
| 217 |
+
st.session_state.score += 1
|
| 218 |
+
st.success("Correct!")
|
| 219 |
+
with col2:
|
| 220 |
+
if st.button("Wrong"):
|
| 221 |
+
st.error("Incorrect!")
|
| 222 |
+
if st.button("Next Card"):
|
| 223 |
+
st.session_state.current_card += 1
|
| 224 |
+
st.session_state.show_answer = False
|
| 225 |
+
st.rerun()
|
| 226 |
+
st.write(f"**Current Score:** {st.session_state.score} / {total_cards}")
|
| 227 |
+
|
| 228 |
+
|
| 229 |
+
|
| 230 |
+
|
| 231 |
+
# # ---------------------------
|
| 232 |
+
# # Helper Function: Extract text from PDF
|
| 233 |
+
# # ---------------------------
|
| 234 |
+
# def extract_text(uploaded_file):
|
| 235 |
+
# # Check file size (max 10MB)
|
| 236 |
+
# uploaded_file.seek(0, os.SEEK_END)
|
| 237 |
+
# file_size = uploaded_file.tell()
|
| 238 |
+
# uploaded_file.seek(0)
|
| 239 |
+
# if file_size > 10 * 1024 * 1024:
|
| 240 |
+
# st.error("File size exceeds 10MB limit.")
|
| 241 |
+
# return ""
|
| 242 |
+
# pdf_reader = PdfReader(uploaded_file)
|
| 243 |
+
# text = ""
|
| 244 |
+
# for page in pdf_reader.pages:
|
| 245 |
+
# page_text = page.extract_text()
|
| 246 |
+
# if page_text:
|
| 247 |
+
# text += page_text + "\n"
|
| 248 |
+
# return text
|
| 249 |
+
|
| 250 |
+
# # ---------------------------
|
| 251 |
+
# # OpenAI Response Functions (using new style)
|
| 252 |
+
# # ---------------------------
|
| 253 |
+
# def generate_summary_from_text(text):
|
| 254 |
+
# prompt = (
|
| 255 |
+
# f"Summarize the following document in a concise manner, highlighting the key points that a student should know:\n\n{text}"
|
| 256 |
+
# )
|
| 257 |
+
# messages = [
|
| 258 |
+
# {"role": "system", "content": "You are an educational assistant."},
|
| 259 |
+
# {"role": "user", "content": prompt}
|
| 260 |
+
# ]
|
| 261 |
+
# completion = client.chat.completions.create(
|
| 262 |
+
# model="gpt-4o-mini",
|
| 263 |
+
# messages=messages
|
| 264 |
+
# )
|
| 265 |
+
# return completion.choices[0].message.content.strip()
|
| 266 |
+
|
| 267 |
+
# def chat_with_document(text, conversation_history, user_query):
|
| 268 |
+
# messages = conversation_history + [
|
| 269 |
+
# {"role": "user", "content": f"Based on the following document:\n\n{text}\n\nQuestion: {user_query}"}
|
| 270 |
+
# ]
|
| 271 |
+
# completion = client.chat.completions.create(
|
| 272 |
+
# model="gpt-4o-mini",
|
| 273 |
+
# messages=messages
|
| 274 |
+
# )
|
| 275 |
+
# return completion.choices[0].message.content.strip()
|
| 276 |
+
|
| 277 |
+
# def generate_questions_from_text(text, num_questions):
|
| 278 |
+
# prompt = (
|
| 279 |
+
# f"Generate up to {num_questions} study questions with answers based on the following document.\n"
|
| 280 |
+
# f"Return the output as a table with two columns: 'Question' and 'Answer'.\n\nDocument:\n\n{text}"
|
| 281 |
+
# )
|
| 282 |
+
# messages = [
|
| 283 |
+
# {"role": "system", "content": "You are an educational assistant that generates study questions."},
|
| 284 |
+
# {"role": "user", "content": prompt}
|
| 285 |
+
# ]
|
| 286 |
+
# completion = client.chat.completions.create(
|
| 287 |
+
# model="gpt-4o-mini",
|
| 288 |
+
# messages=messages
|
| 289 |
+
# )
|
| 290 |
+
# return completion.choices[0].message.content.strip()
|
| 291 |
+
|
| 292 |
+
# def generate_flashcards_from_text(text, num_cards):
|
| 293 |
+
# prompt = (
|
| 294 |
+
# f"Generate {num_cards} flashcards based on the following document.\n\nDocument:\n\n{text}\n\n"
|
| 295 |
+
# "Return a Python dictionary where each key is a flashcard question and its corresponding value is the answer. "
|
| 296 |
+
# "Do not include any additional text."
|
| 297 |
+
# )
|
| 298 |
+
# messages = [
|
| 299 |
+
# {"role": "system", "content": "You are an educational assistant that creates study flashcards."},
|
| 300 |
+
# {"role": "user", "content": prompt}
|
| 301 |
+
# ]
|
| 302 |
+
# completion = client.chat.completions.create(
|
| 303 |
+
# model="gpt-4o-mini",
|
| 304 |
+
# messages=messages
|
| 305 |
+
# )
|
| 306 |
+
# output = completion.choices[0].message.content.strip()
|
| 307 |
+
# try:
|
| 308 |
+
# flashcards = literal_eval(output)
|
| 309 |
+
# if isinstance(flashcards, dict):
|
| 310 |
+
# return flashcards
|
| 311 |
+
# else:
|
| 312 |
+
# return {}
|
| 313 |
+
# except Exception as e:
|
| 314 |
+
# st.error(f"Error parsing flashcards: {e}")
|
| 315 |
+
# return {}
|
| 316 |
+
|
| 317 |
+
# # ---------------------------
|
| 318 |
+
# # Sidebar: File Upload & Mode Selection
|
| 319 |
+
# # ---------------------------
|
| 320 |
+
# st.sidebar.title("Study Companion Setup")
|
| 321 |
+
|
| 322 |
+
# uploaded_pdf = st.sidebar.file_uploader("Upload your study PDF (max 10MB)", type="pdf")
|
| 323 |
+
# mode = st.sidebar.radio("Select Mode", ("Chat", "Test Your Knowledge", "Flashcards"))
|
| 324 |
+
|
| 325 |
+
# # For Test Your Knowledge and Flashcards modes, allow number input.
|
| 326 |
+
# num_questions = None
|
| 327 |
+
# num_flashcards = None
|
| 328 |
+
# if mode == "Test Your Knowledge":
|
| 329 |
+
# num_questions = st.sidebar.number_input("Number of questions to generate (max 50):", min_value=1, max_value=50, value=10, step=1)
|
| 330 |
+
# elif mode == "Flashcards":
|
| 331 |
+
# num_flashcards = st.sidebar.number_input("Number of flashcards to generate (max 5):", min_value=1, max_value=5, value=3, step=1)
|
| 332 |
+
|
| 333 |
+
# # ---------------------------
|
| 334 |
+
# # Session State Initialization
|
| 335 |
+
# # ---------------------------
|
| 336 |
+
# if "pdf_text" not in st.session_state:
|
| 337 |
+
# st.session_state.pdf_text = None
|
| 338 |
+
# if "summary" not in st.session_state:
|
| 339 |
+
# st.session_state.summary = None
|
| 340 |
+
# if "chat_history" not in st.session_state:
|
| 341 |
+
# st.session_state.chat_history = [{"role": "assistant", "content": "Hi, how can I help you with your study material?"}]
|
| 342 |
+
# if "questions_table" not in st.session_state:
|
| 343 |
+
# st.session_state.questions_table = None
|
| 344 |
+
# if "flashcards" not in st.session_state:
|
| 345 |
+
# st.session_state.flashcards = {}
|
| 346 |
+
# if "current_card" not in st.session_state:
|
| 347 |
+
# st.session_state.current_card = 0
|
| 348 |
+
# if "score" not in st.session_state:
|
| 349 |
+
# st.session_state.score = 0
|
| 350 |
+
# if "show_answer" not in st.session_state:
|
| 351 |
+
# st.session_state.show_answer = False
|
| 352 |
|
| 353 |
+
# # ---------------------------
|
| 354 |
+
# # Process PDF Upload
|
| 355 |
+
# # ---------------------------
|
| 356 |
+
# if uploaded_pdf is not None:
|
| 357 |
+
# st.session_state.pdf_text = extract_text(uploaded_pdf)
|
| 358 |
+
# if st.session_state.pdf_text:
|
| 359 |
+
# st.sidebar.success("PDF uploaded and processed successfully!")
|
| 360 |
+
# else:
|
| 361 |
+
# st.sidebar.error("Failed to extract text. Please check your PDF file.")
|
| 362 |
+
|
| 363 |
+
# # ---------------------------
|
| 364 |
+
# # Main Area: Mode-Based Display (all functions via side menu)
|
| 365 |
+
# # ---------------------------
|
| 366 |
+
# st.title("Study Companion: PDF-based Learning")
|
| 367 |
+
|
| 368 |
+
# if st.session_state.pdf_text is None:
|
| 369 |
+
# st.info("Please upload a PDF from the sidebar to begin.")
|
| 370 |
+
# else:
|
| 371 |
+
# if mode == "Chat":
|
| 372 |
+
# st.header("Chat with Your Study Companion")
|
| 373 |
+
# # Display persistent chat history
|
| 374 |
+
# for msg in st.session_state.chat_history:
|
| 375 |
+
# st.chat_message(msg["role"]).write(msg["content"])
|
| 376 |
+
# user_question = st.chat_input("Ask a question about the document:")
|
| 377 |
+
# if user_question:
|
| 378 |
+
# st.session_state.chat_history.append({"role": "user", "content": user_question})
|
| 379 |
+
# st.chat_message("user").write(user_question)
|
| 380 |
+
# with st.spinner("Processing your question..."):
|
| 381 |
+
# response = chat_with_document(st.session_state.pdf_text, st.session_state.chat_history, user_question)
|
| 382 |
+
# st.session_state.chat_history.append({"role": "assistant", "content": response})
|
| 383 |
+
# st.chat_message("assistant").write(response)
|
| 384 |
+
|
| 385 |
+
# elif mode == "Test Your Knowledge":
|
| 386 |
+
# st.header("Test Your Knowledge")
|
| 387 |
+
# if num_questions is None:
|
| 388 |
+
# st.info("Please specify the number of questions in the sidebar.")
|
| 389 |
+
# else:
|
| 390 |
+
# with st.spinner("Generating questions..."):
|
| 391 |
+
# questions_output = generate_questions_from_text(st.session_state.pdf_text, num_questions)
|
| 392 |
+
# # Assume the output is a table in markdown format
|
| 393 |
+
# st.markdown("### Generated Questions")
|
| 394 |
+
# st.markdown(questions_output)
|
| 395 |
+
# # Optionally, you can parse the table and display it with st.table if it's in a CSV-like format.
|
| 396 |
+
|
| 397 |
+
# elif mode == "Flashcards":
|
| 398 |
+
# st.header("Practice Flashcards")
|
| 399 |
+
# if st.button("Generate Flashcards"):
|
| 400 |
+
# with st.spinner("Generating flashcards..."):
|
| 401 |
+
# flashcards = generate_flashcards_from_text(st.session_state.pdf_text, num_flashcards)
|
| 402 |
+
# st.session_state.flashcards = flashcards
|
| 403 |
+
# st.session_state.current_card = 0
|
| 404 |
+
# st.session_state.score = 0
|
| 405 |
+
# st.session_state.show_answer = False
|
| 406 |
+
# st.success("Flashcards generated successfully!")
|
| 407 |
+
|
| 408 |
+
# if not st.session_state.flashcards:
|
| 409 |
+
# st.info("No flashcards available. Click the button above to generate flashcards.")
|
| 410 |
+
# else:
|
| 411 |
+
# total_cards = len(st.session_state.flashcards)
|
| 412 |
+
# if st.session_state.current_card >= total_cards:
|
| 413 |
+
# st.success(f"You've completed all flashcards! Final Score: {st.session_state.score} / {total_cards}")
|
| 414 |
+
# st.info("Restart the session or generate new flashcards from the sidebar.")
|
| 415 |
+
# else:
|
| 416 |
+
# flashcards = st.session_state.flashcards
|
| 417 |
+
# current_keys = list(flashcards.keys())
|
| 418 |
+
# current_question = current_keys[st.session_state.current_card]
|
| 419 |
+
# current_answer = flashcards[current_question]
|
| 420 |
+
# st.write(f"**Question:** {current_question}")
|
| 421 |
+
# if st.button("Show Answer"):
|
| 422 |
+
# st.session_state.show_answer = True
|
| 423 |
+
# if st.session_state.show_answer:
|
| 424 |
+
# st.write(f"**Answer:** {current_answer}")
|
| 425 |
+
# col1, col2 = st.columns(2)
|
| 426 |
+
# with col1:
|
| 427 |
+
# if st.button("Correct"):
|
| 428 |
+
# st.session_state.score += 1
|
| 429 |
+
# st.success("Correct!")
|
| 430 |
+
# with col2:
|
| 431 |
+
# if st.button("Wrong"):
|
| 432 |
+
# st.error("Incorrect!")
|
| 433 |
+
# if st.button("Next Card"):
|
| 434 |
+
# st.session_state.current_card += 1
|
| 435 |
+
# st.session_state.show_answer = False
|
| 436 |
+
# st.rerun()
|
| 437 |
+
# st.write(f"**Current Score:** {st.session_state.score} / {total_cards}")
|
| 438 |
|
| 439 |
+
######################################################################################################
|
| 440 |
|
| 441 |
|
| 442 |
# # ---------------------------
|