JustusI commited on
Commit
e17a0bf
·
verified ·
1 Parent(s): e9bf540

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +194 -14
app.py CHANGED
@@ -6,6 +6,7 @@ from pathlib import Path
6
  from PyPDF2 import PdfReader
7
  from openai import OpenAI
8
  import os
 
9
 
10
  # Initialize the OpenAI client
11
  api_key = os.getenv("OPENAI_API_KEY")
@@ -42,7 +43,6 @@ def generate_summary_from_text(text):
42
  return completion.choices[0].message.content.strip()
43
 
44
  def chat_with_document(text, conversation_history, user_query):
45
- # Build a message list that includes the conversation history plus the new query with context.
46
  messages = conversation_history + [
47
  {"role": "user", "content": f"Based on the following document:\n\n{text}\n\nQuestion: {user_query}"}
48
  ]
@@ -55,8 +55,8 @@ def chat_with_document(text, conversation_history, user_query):
55
  def generate_flashcards_from_text(text, num_cards):
56
  prompt = (
57
  f"Generate {num_cards} flashcards based on the following document. "
58
- "Return a Python dictionary (in valid JSON format) where each key is a flashcard question and its value is the corresponding answer. "
59
- f"Document:\n\n{text}"
60
  )
61
  messages = [
62
  {"role": "system", "content": "You are an educational assistant that creates study flashcards."},
@@ -68,7 +68,8 @@ def generate_flashcards_from_text(text, num_cards):
68
  )
69
  output = completion.choices[0].message.content.strip()
70
  try:
71
- flashcards = json.loads(output)
 
72
  if isinstance(flashcards, dict):
73
  return flashcards
74
  else:
@@ -85,7 +86,6 @@ st.sidebar.title("Study Companion Setup")
85
  uploaded_pdf = st.sidebar.file_uploader("Upload your study PDF", type="pdf")
86
  mode = st.sidebar.radio("Select Mode", ("Summary", "Chat", "Flashcards"))
87
 
88
- # For Flashcards, allow user to input number of flashcards
89
  num_flashcards = None
90
  if mode == "Flashcards":
91
  num_flashcards = st.sidebar.number_input("Number of flashcards to generate:", min_value=1, max_value=20, value=5, step=1)
@@ -114,9 +114,8 @@ if "show_answer" not in st.session_state:
114
  if uploaded_pdf is not None:
115
  with tempfile.NamedTemporaryFile(delete=False, suffix=".pdf") as tmp:
116
  tmp.write(uploaded_pdf.read())
117
- pdf_file_path = tmp.name
118
- # Extract text from the PDF (all pages)
119
- st.session_state.pdf_text = extract_text(pdf_file_path)
120
  st.sidebar.success("PDF uploaded and processed successfully!")
121
 
122
  # ---------------------------
@@ -136,7 +135,6 @@ else:
136
 
137
  elif mode == "Chat":
138
  st.header("Chat with Your Study Companion")
139
- # Display persistent chat history
140
  for msg in st.session_state.chat_history:
141
  st.chat_message(msg["role"]).write(msg["content"])
142
  user_question = st.chat_input("Ask a question about the document:")
@@ -150,7 +148,6 @@ else:
150
 
151
  elif mode == "Flashcards":
152
  st.header("Practice Flashcards")
153
- # Provide a button to generate flashcards on demand.
154
  if st.button("Generate Flashcards"):
155
  with st.spinner("Generating flashcards..."):
156
  flashcards = generate_flashcards_from_text(st.session_state.pdf_text, num_flashcards)
@@ -169,11 +166,10 @@ else:
169
  st.info("Restart the session or generate new flashcards from the sidebar.")
170
  else:
171
  flashcards = st.session_state.flashcards
172
- # Get the current flashcard key-value pair.
173
  current_keys = list(flashcards.keys())
174
- current_key = current_keys[st.session_state.current_card]
175
- current_answer = flashcards[current_key]
176
- st.write(f"**Question:** {current_key}")
177
  if st.button("Show Answer"):
178
  st.session_state.show_answer = True
179
  if st.session_state.show_answer:
@@ -191,3 +187,187 @@ else:
191
  st.session_state.show_answer = False
192
  st.rerun()
193
  st.write(f"**Current Score:** {st.session_state.score} / {total_cards}")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6
  from PyPDF2 import PdfReader
7
  from openai import OpenAI
8
  import os
9
+ from ast import literal_eval
10
 
11
  # Initialize the OpenAI client
12
  api_key = os.getenv("OPENAI_API_KEY")
 
43
  return completion.choices[0].message.content.strip()
44
 
45
  def chat_with_document(text, conversation_history, user_query):
 
46
  messages = conversation_history + [
47
  {"role": "user", "content": f"Based on the following document:\n\n{text}\n\nQuestion: {user_query}"}
48
  ]
 
55
  def generate_flashcards_from_text(text, num_cards):
56
  prompt = (
57
  f"Generate {num_cards} flashcards based on the following document. "
58
+ "Return a Python dictionary where each key is a flashcard question and its corresponding value is the answer. "
59
+ "Do not include any additional text.\n\nDocument:\n\n{text}"
60
  )
61
  messages = [
62
  {"role": "system", "content": "You are an educational assistant that creates study flashcards."},
 
68
  )
69
  output = completion.choices[0].message.content.strip()
70
  try:
71
+ # Use literal_eval to safely evaluate the string as a Python dictionary.
72
+ flashcards = literal_eval(output)
73
  if isinstance(flashcards, dict):
74
  return flashcards
75
  else:
 
86
  uploaded_pdf = st.sidebar.file_uploader("Upload your study PDF", type="pdf")
87
  mode = st.sidebar.radio("Select Mode", ("Summary", "Chat", "Flashcards"))
88
 
 
89
  num_flashcards = None
90
  if mode == "Flashcards":
91
  num_flashcards = st.sidebar.number_input("Number of flashcards to generate:", min_value=1, max_value=20, value=5, step=1)
 
114
  if uploaded_pdf is not None:
115
  with tempfile.NamedTemporaryFile(delete=False, suffix=".pdf") as tmp:
116
  tmp.write(uploaded_pdf.read())
117
+ st.session_state.pdf_file_path = tmp.name
118
+ st.session_state.pdf_text = extract_text(uploaded_pdf)
 
119
  st.sidebar.success("PDF uploaded and processed successfully!")
120
 
121
  # ---------------------------
 
135
 
136
  elif mode == "Chat":
137
  st.header("Chat with Your Study Companion")
 
138
  for msg in st.session_state.chat_history:
139
  st.chat_message(msg["role"]).write(msg["content"])
140
  user_question = st.chat_input("Ask a question about the document:")
 
148
 
149
  elif mode == "Flashcards":
150
  st.header("Practice Flashcards")
 
151
  if st.button("Generate Flashcards"):
152
  with st.spinner("Generating flashcards..."):
153
  flashcards = generate_flashcards_from_text(st.session_state.pdf_text, num_flashcards)
 
166
  st.info("Restart the session or generate new flashcards from the sidebar.")
167
  else:
168
  flashcards = st.session_state.flashcards
 
169
  current_keys = list(flashcards.keys())
170
+ current_question = current_keys[st.session_state.current_card]
171
+ current_answer = flashcards[current_question]
172
+ st.write(f"**Question:** {current_question}")
173
  if st.button("Show Answer"):
174
  st.session_state.show_answer = True
175
  if st.session_state.show_answer:
 
187
  st.session_state.show_answer = False
188
  st.rerun()
189
  st.write(f"**Current Score:** {st.session_state.score} / {total_cards}")
190
+
191
+
192
+
193
+
194
+ # # ---------------------------
195
+ # # Helper Function: Extract text from PDF
196
+ # # ---------------------------
197
+ # def extract_text(uploaded_file):
198
+ # pdf_reader = PdfReader(uploaded_file)
199
+ # text = ""
200
+ # for page in pdf_reader.pages:
201
+ # page_text = page.extract_text()
202
+ # if page_text:
203
+ # text += page_text
204
+ # return text
205
+
206
+ # # ---------------------------
207
+ # # OpenAI Response Functions (using new style)
208
+ # # ---------------------------
209
+ # def generate_summary_from_text(text):
210
+ # prompt = (
211
+ # f"Summarize the following document in a concise manner, "
212
+ # "highlighting the key points that a student should know:\n\n{text}"
213
+ # )
214
+ # messages = [
215
+ # {"role": "system", "content": "You are an educational assistant."},
216
+ # {"role": "user", "content": prompt}
217
+ # ]
218
+ # completion = client.chat.completions.create(
219
+ # model="gpt-4o-mini",
220
+ # messages=messages
221
+ # )
222
+ # return completion.choices[0].message.content.strip()
223
+
224
+ # def chat_with_document(text, conversation_history, user_query):
225
+ # # Build a message list that includes the conversation history plus the new query with context.
226
+ # messages = conversation_history + [
227
+ # {"role": "user", "content": f"Based on the following document:\n\n{text}\n\nQuestion: {user_query}"}
228
+ # ]
229
+ # completion = client.chat.completions.create(
230
+ # model="gpt-4o-mini",
231
+ # messages=messages
232
+ # )
233
+ # return completion.choices[0].message.content.strip()
234
+
235
+ # def generate_flashcards_from_text(text, num_cards):
236
+ # prompt = (
237
+ # f"Generate {num_cards} flashcards based on the following document. "
238
+ # "Return a Python dictionary (in valid JSON format) where each key is a flashcard question and its value is the corresponding answer. "
239
+ # f"Document:\n\n{text}"
240
+ # )
241
+ # messages = [
242
+ # {"role": "system", "content": "You are an educational assistant that creates study flashcards."},
243
+ # {"role": "user", "content": prompt}
244
+ # ]
245
+ # completion = client.chat.completions.create(
246
+ # model="gpt-4o-mini",
247
+ # messages=messages
248
+ # )
249
+ # output = completion.choices[0].message.content.strip()
250
+ # try:
251
+ # flashcards = json.loads(output)
252
+ # if isinstance(flashcards, dict):
253
+ # return flashcards
254
+ # else:
255
+ # return {}
256
+ # except Exception as e:
257
+ # st.error(f"Error parsing flashcards: {e}")
258
+ # return {}
259
+
260
+ # # ---------------------------
261
+ # # Sidebar: File Upload & Mode Selection
262
+ # # ---------------------------
263
+ # st.sidebar.title("Study Companion Setup")
264
+
265
+ # uploaded_pdf = st.sidebar.file_uploader("Upload your study PDF", type="pdf")
266
+ # mode = st.sidebar.radio("Select Mode", ("Summary", "Chat", "Flashcards"))
267
+
268
+ # # For Flashcards, allow user to input number of flashcards
269
+ # num_flashcards = None
270
+ # if mode == "Flashcards":
271
+ # num_flashcards = st.sidebar.number_input("Number of flashcards to generate:", min_value=1, max_value=20, value=5, step=1)
272
+
273
+ # # ---------------------------
274
+ # # Session State Initialization
275
+ # # ---------------------------
276
+ # if "pdf_text" not in st.session_state:
277
+ # st.session_state.pdf_text = None
278
+ # if "summary" not in st.session_state:
279
+ # st.session_state.summary = None
280
+ # if "chat_history" not in st.session_state:
281
+ # st.session_state.chat_history = [{"role": "assistant", "content": "Hi, how can I help you with your study material?"}]
282
+ # if "flashcards" not in st.session_state:
283
+ # st.session_state.flashcards = {}
284
+ # if "current_card" not in st.session_state:
285
+ # st.session_state.current_card = 0
286
+ # if "score" not in st.session_state:
287
+ # st.session_state.score = 0
288
+ # if "show_answer" not in st.session_state:
289
+ # st.session_state.show_answer = False
290
+
291
+ # # ---------------------------
292
+ # # Process PDF Upload
293
+ # # ---------------------------
294
+ # if uploaded_pdf is not None:
295
+ # with tempfile.NamedTemporaryFile(delete=False, suffix=".pdf") as tmp:
296
+ # tmp.write(uploaded_pdf.read())
297
+ # pdf_file_path = tmp.name
298
+ # # Extract text from the PDF (all pages)
299
+ # st.session_state.pdf_text = extract_text(pdf_file_path)
300
+ # st.sidebar.success("PDF uploaded and processed successfully!")
301
+
302
+ # # ---------------------------
303
+ # # Main Area: Mode-Based Display
304
+ # # ---------------------------
305
+ # st.title("Study Companion: PDF-based Learning")
306
+
307
+ # if st.session_state.pdf_text is None:
308
+ # st.info("Please upload a PDF from the sidebar to begin.")
309
+ # else:
310
+ # if mode == "Summary":
311
+ # st.header("Summary & Key Points")
312
+ # if st.session_state.summary is None:
313
+ # with st.spinner("Generating summary..."):
314
+ # st.session_state.summary = generate_summary_from_text(st.session_state.pdf_text)
315
+ # st.write(st.session_state.summary)
316
+
317
+ # elif mode == "Chat":
318
+ # st.header("Chat with Your Study Companion")
319
+ # # Display persistent chat history
320
+ # for msg in st.session_state.chat_history:
321
+ # st.chat_message(msg["role"]).write(msg["content"])
322
+ # user_question = st.chat_input("Ask a question about the document:")
323
+ # if user_question:
324
+ # st.session_state.chat_history.append({"role": "user", "content": user_question})
325
+ # st.chat_message("user").write(user_question)
326
+ # with st.spinner("Processing your question..."):
327
+ # response = chat_with_document(st.session_state.pdf_text, st.session_state.chat_history, user_question)
328
+ # st.session_state.chat_history.append({"role": "assistant", "content": response})
329
+ # st.chat_message("assistant").write(response)
330
+
331
+ # elif mode == "Flashcards":
332
+ # st.header("Practice Flashcards")
333
+ # # Provide a button to generate flashcards on demand.
334
+ # if st.button("Generate Flashcards"):
335
+ # with st.spinner("Generating flashcards..."):
336
+ # flashcards = generate_flashcards_from_text(st.session_state.pdf_text, num_flashcards)
337
+ # st.session_state.flashcards = flashcards
338
+ # st.session_state.current_card = 0
339
+ # st.session_state.score = 0
340
+ # st.session_state.show_answer = False
341
+ # st.success("Flashcards generated successfully!")
342
+
343
+ # if not st.session_state.flashcards:
344
+ # st.info("No flashcards available. Click the button above to generate flashcards.")
345
+ # else:
346
+ # total_cards = len(st.session_state.flashcards)
347
+ # if st.session_state.current_card >= total_cards:
348
+ # st.success(f"You've completed all flashcards! Final Score: {st.session_state.score} / {total_cards}")
349
+ # st.info("Restart the session or generate new flashcards from the sidebar.")
350
+ # else:
351
+ # flashcards = st.session_state.flashcards
352
+ # # Get the current flashcard key-value pair.
353
+ # current_keys = list(flashcards.keys())
354
+ # current_key = current_keys[st.session_state.current_card]
355
+ # current_answer = flashcards[current_key]
356
+ # st.write(f"**Question:** {current_key}")
357
+ # if st.button("Show Answer"):
358
+ # st.session_state.show_answer = True
359
+ # if st.session_state.show_answer:
360
+ # st.write(f"**Answer:** {current_answer}")
361
+ # col1, col2 = st.columns(2)
362
+ # with col1:
363
+ # if st.button("Correct"):
364
+ # st.session_state.score += 1
365
+ # st.success("Correct!")
366
+ # with col2:
367
+ # if st.button("Wrong"):
368
+ # st.error("Incorrect!")
369
+ # if st.button("Next Card"):
370
+ # st.session_state.current_card += 1
371
+ # st.session_state.show_answer = False
372
+ # st.rerun()
373
+ # st.write(f"**Current Score:** {st.session_state.score} / {total_cards}")