JustusI commited on
Commit
21ac1d0
·
verified ·
1 Parent(s): e0278de

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +175 -170
app.py CHANGED
@@ -13,19 +13,18 @@ api_key = os.getenv("OPENAI_API_KEY")
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,7 +34,7 @@ def extract_text(uploaded_file):
35
  return text
36
 
37
  # ---------------------------
38
- # OpenAI Response Functions
39
  # ---------------------------
40
  def generate_summary_from_text(text):
41
  prompt = (
@@ -63,8 +62,8 @@ def chat_with_document(text, conversation_history, user_query):
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,30 +73,48 @@ def generate_questions_from_text(text, num_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
  # ---------------------------
83
  st.sidebar.title("Study Companion Setup")
84
 
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,17 +140,14 @@ if "show_answer" not in st.session_state:
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,6 +156,7 @@ if st.session_state.pdf_text is None:
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,90 +170,75 @@ else:
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:
@@ -248,7 +248,7 @@ else:
248
  # return text
249
 
250
  # # ---------------------------
251
- # # OpenAI Response Functions (using new style)
252
  # # ---------------------------
253
  # def generate_summary_from_text(text):
254
  # prompt = (
@@ -276,8 +276,8 @@ else:
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."},
@@ -287,33 +287,9 @@ else:
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
  # # ---------------------------
@@ -322,13 +298,19 @@ else:
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
@@ -354,14 +336,17 @@ else:
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
 
@@ -370,7 +355,6 @@ else:
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:")
@@ -384,57 +368,78 @@ else:
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
 
 
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
+ # Check file size (max 10MB)
22
  uploaded_file.seek(0, os.SEEK_END)
23
+ file_size = uploaded_file.tell()
 
 
24
  uploaded_file.seek(0)
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
  return text
35
 
36
  # ---------------------------
37
+ # OpenAI Response Functions (using new style)
38
  # ---------------------------
39
  def generate_summary_from_text(text):
40
  prompt = (
 
62
 
63
  def generate_questions_from_text(text, num_questions):
64
  prompt = (
65
+ f"Generate up to {num_questions} study questions with answers based on the following document.\n"
66
+ f"Return the output as a table with two columns: 'Question' and 'Answer'.\n\nDocument:\n\n{text}"
67
  )
68
  messages = [
69
  {"role": "system", "content": "You are an educational assistant that generates study 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
  # ---------------------------
106
  st.sidebar.title("Study Companion Setup")
107
 
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 and Flashcards modes, allow number input.
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
+ elif mode == "Flashcards":
 
 
 
 
 
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
  # 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. Please check your PDF file.")
148
 
149
  # ---------------------------
150
+ # Main Area: Mode-Based Display (all functions via side menu)
151
  # ---------------------------
152
  st.title("Study Companion: PDF-based Learning")
153
 
 
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
 
171
  elif mode == "Test Your Knowledge":
172
  st.header("Test Your Knowledge")
173
+ if num_questions is None:
174
+ st.info("Please specify the number of questions in the sidebar.")
175
  else:
176
  with st.spinner("Generating questions..."):
177
+ questions_output = generate_questions_from_text(st.session_state.pdf_text, num_questions)
178
+ # Assume the output is a table in markdown format
179
+ st.markdown("### Generated Questions")
180
+ st.markdown(questions_output)
181
+ # Optionally, you can parse the table and display it with st.table if it's in a CSV-like format.
 
 
 
 
 
 
 
 
182
 
183
  elif mode == "Flashcards":
184
  st.header("Practice Flashcards")
185
+ if st.button("Generate Flashcards"):
186
+ with st.spinner("Generating flashcards..."):
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
+ total_cards = len(st.session_state.flashcards)
198
+ if st.session_state.current_card >= total_cards:
199
+ st.success(f"You've completed all flashcards! Final Score: {st.session_state.score} / {total_cards}")
200
+ st.info("Restart the session or generate new flashcards from the sidebar.")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
201
  else:
202
+ flashcards = st.session_state.flashcards
203
+ current_keys = list(flashcards.keys())
204
+ current_question = current_keys[st.session_state.current_card]
205
+ current_answer = flashcards[current_question]
206
+ st.write(f"**Question:** {current_question}")
207
+ if st.button("Show Answer"):
208
+ st.session_state.show_answer = True
209
+ if st.session_state.show_answer:
210
+ st.write(f"**Answer:** {current_answer}")
211
+ col1, col2 = st.columns(2)
212
+ with col1:
213
+ if st.button("Correct"):
214
+ st.session_state.score += 1
215
+ st.success("Correct!")
216
+ with col2:
217
+ if st.button("Wrong"):
218
+ st.error("Incorrect!")
219
+ if st.button("Next Card"):
220
+ st.session_state.current_card += 1
221
+ st.session_state.show_answer = False
222
+ st.rerun()
223
+ st.write(f"**Current Score:** {st.session_state.score} / {total_cards}")
 
 
 
 
 
224
 
225
 
226
 
227
 
228
+
229
+ # # Import the CrewAI flashcard module (modified below to remove page range)
230
+ # from crewai_flashcard import generate_flashcards
231
+
232
  # # ---------------------------
233
  # # Helper Function: Extract text from PDF
234
  # # ---------------------------
235
  # def extract_text(uploaded_file):
236
+ # # Ensure file size is less than 10MB
237
  # uploaded_file.seek(0, os.SEEK_END)
238
+ # if uploaded_file.tell() > 10 * 1024 * 1024:
239
+ # st.error("File exceeds 10MB limit.")
 
 
240
  # return ""
241
+ # uploaded_file.seek(0)
242
  # pdf_reader = PdfReader(uploaded_file)
243
  # text = ""
244
  # for page in pdf_reader.pages:
 
248
  # return text
249
 
250
  # # ---------------------------
251
+ # # OpenAI Response Functions
252
  # # ---------------------------
253
  # def generate_summary_from_text(text):
254
  # prompt = (
 
276
 
277
  # def generate_questions_from_text(text, num_questions):
278
  # prompt = (
279
+ # f"Generate {num_questions} study questions with answers based on the following document. "
280
+ # "Return the output as a table in CSV format 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."},
 
287
  # model="gpt-4o-mini",
288
  # messages=messages
289
  # )
290
+ # # Expecting CSV output (with header: Question,Answer)
291
  # return completion.choices[0].message.content.strip()
292
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
293
  # # ---------------------------
294
  # # Sidebar: File Upload & Mode Selection
295
  # # ---------------------------
 
298
  # uploaded_pdf = st.sidebar.file_uploader("Upload your study PDF (max 10MB)", type="pdf")
299
  # mode = st.sidebar.radio("Select Mode", ("Chat", "Test Your Knowledge", "Flashcards"))
300
 
301
+ # # For Test Your Knowledge: number of questions (max 50)
302
  # num_questions = None
 
303
  # if mode == "Test Your Knowledge":
304
  # num_questions = st.sidebar.number_input("Number of questions to generate (max 50):", min_value=1, max_value=50, value=10, step=1)
305
+ # if st.sidebar.button("Generate Questions"):
306
+ # st.session_state.gen_questions = True
307
+
308
+ # # For Flashcards: number of flashcards (max 5)
309
+ # num_flashcards = None
310
+ # if mode == "Flashcards":
311
  # num_flashcards = st.sidebar.number_input("Number of flashcards to generate (max 5):", min_value=1, max_value=5, value=3, step=1)
312
+ # if st.sidebar.button("Generate Flashcards"):
313
+ # st.session_state.gen_flashcards = True
314
 
315
  # # ---------------------------
316
  # # Session State Initialization
 
336
  # # Process PDF Upload
337
  # # ---------------------------
338
  # if uploaded_pdf is not None:
339
+ # with tempfile.NamedTemporaryFile(delete=False, suffix=".pdf") as tmp:
340
+ # tmp.write(uploaded_pdf.read())
341
+ # st.session_state.pdf_file_path = tmp.name
342
  # st.session_state.pdf_text = extract_text(uploaded_pdf)
343
  # if st.session_state.pdf_text:
344
  # st.sidebar.success("PDF uploaded and processed successfully!")
345
  # else:
346
+ # st.sidebar.error("Failed to extract text from the PDF.")
347
 
348
  # # ---------------------------
349
+ # # Main Area: Mode-Based Display (using side menu)
350
  # # ---------------------------
351
  # st.title("Study Companion: PDF-based Learning")
352
 
 
355
  # else:
356
  # if mode == "Chat":
357
  # st.header("Chat with Your Study Companion")
 
358
  # for msg in st.session_state.chat_history:
359
  # st.chat_message(msg["role"]).write(msg["content"])
360
  # user_question = st.chat_input("Ask a question about the document:")
 
368
 
369
  # elif mode == "Test Your Knowledge":
370
  # st.header("Test Your Knowledge")
371
+ # if num_questions is None or not st.session_state.get("gen_questions", False):
372
+ # st.info("Enter the number of questions and press 'Generate Questions' from the sidebar.")
373
  # else:
374
  # with st.spinner("Generating questions..."):
375
+ # questions_csv = generate_questions_from_text(st.session_state.pdf_text, num_questions)
376
+ # # Convert CSV output into a table (assuming header row "Question,Answer")
377
+ # try:
378
+ # lines = questions_csv.splitlines()
379
+ # if len(lines) < 2:
380
+ # st.error("Failed to generate questions properly.")
381
+ # else:
382
+ # header = lines[0].split(",")
383
+ # data = [line.split(",") for line in lines[1:]]
384
+ # st.table(data, headers=header)
385
+ # st.session_state.questions_table = data
386
+ # except Exception as e:
387
+ # st.error(f"Error processing questions: {e}")
388
 
389
  # elif mode == "Flashcards":
390
  # st.header("Practice Flashcards")
391
+ # if not st.session_state.get("gen_flashcards", False):
392
+ # st.info("Enter the number of flashcards and press 'Generate Flashcards' from the sidebar.")
 
 
 
 
 
 
 
 
 
393
  # else:
394
+ # if st.button("Reset Flashcards"):
395
+ # st.session_state.flashcards = {}
396
+ # st.session_state.current_card = 0
397
+ # st.session_state.score = 0
398
+ # st.session_state.show_answer = False
399
+ # st.session_state.gen_flashcards = False
400
+ # if st.session_state.get("gen_flashcards", False):
401
+ # # Generate flashcards using the CrewAI module (which returns a Python dictionary)
402
+ # flashcards = generate_flashcards(st.session_state.pdf_file_path, num_flashcards)
403
+ # st.session_state.flashcards = flashcards
404
+ # st.session_state.current_card = 0
405
+ # st.session_state.score = 0
406
+ # st.session_state.show_answer = False
407
+ # st.success("Flashcards generated successfully!")
408
+ # st.session_state.gen_flashcards = False # reset flag after generation
409
+
410
+ # if not st.session_state.flashcards:
411
+ # st.info("No flashcards available. Click the 'Generate Flashcards' button in the sidebar.")
412
  # else:
413
+ # total_cards = len(st.session_state.flashcards)
414
+ # if st.session_state.current_card >= total_cards:
415
+ # st.success(f"You've completed all flashcards! Final Score: {st.session_state.score} / {total_cards}")
416
+ # st.info("Restart the session or generate new flashcards from the sidebar.")
417
+ # else:
418
+ # flashcards = st.session_state.flashcards
419
+ # current_keys = list(flashcards.keys())
420
+ # current_question = current_keys[st.session_state.current_card]
421
+ # current_answer = flashcards[current_question]
422
+ # st.write(f"**Question:** {current_question}")
423
+ # if st.button("Show Answer"):
424
+ # st.session_state.show_answer = True
425
+ # if st.session_state.show_answer:
426
+ # st.write(f"**Answer:** {current_answer}")
427
+ # col1, col2 = st.columns(2)
428
+ # with col1:
429
+ # if st.button("Correct"):
430
+ # st.session_state.score += 1
431
+ # st.success("Correct!")
432
+ # with col2:
433
+ # if st.button("Wrong"):
434
+ # st.error("Incorrect!")
435
+ # if st.button("Next Card"):
436
+ # st.session_state.current_card += 1
437
+ # st.session_state.show_answer = False
438
+ # st.rerun()
439
+ # st.write(f"**Current Score:** {st.session_state.score} / {total_cards}")
440
+
441
+
442
+
443
 
444
  ######################################################################################################
445