-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.py
More file actions
385 lines (339 loc) · 12.7 KB
/
app.py
File metadata and controls
385 lines (339 loc) · 12.7 KB
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
import gradio as gr
import os
import json
from dotenv import load_dotenv
from groq import Groq
import pdfplumber
import tempfile
import traceback
# Load environment variables
load_dotenv()
# Initialize Groq client
client = Groq(
api_key=os.getenv("GROQ_API_KEY"),
)
# --- PDF Extraction and Text Cleaning Functions ---
def extract_text_from_pdf(pdf_file_binary_data):
full_text = ""
with tempfile.NamedTemporaryFile(delete=False, suffix=".pdf") as tmp_file:
tmp_file.write(pdf_file_binary_data)
tmp_file_path = tmp_file.name
try:
print(f"DEBUG: Attempting to open PDF from: {tmp_file_path}")
with pdfplumber.open(tmp_file_path) as pdf:
for page in pdf.pages:
text = page.extract_text()
if text:
full_text += text + "\n"
print(f"DEBUG: Full text length: {len(full_text)}")
return clean_text(full_text)
finally:
if os.path.exists(tmp_file_path):
os.unlink(tmp_file_path)
def clean_text(text):
lines = text.split("\n")
cleaned = [line.strip() for line in lines if line.strip()]
return "\n".join(cleaned)
# --- Text Chunking Function ---
def chunk_text(text, max_words=400):
words = text.split()
chunks = []
for i in range(0, len(words), max_words):
chunk = " ".join(words[i:i+max_words])
chunks.append(chunk)
print(f"DEBUG: Text chunked into {len(chunks)} chunks.")
return chunks
# --- Flashcard Generation Function ---
def generate_flashcards_from_chunk(chunk):
model_name = "llama3-8b-8192"
prompt = f"""
You are a helpful assistant that generates high-quality flashcards from lecture notes.
Generate 3 concise question-answer pairs from the following text. Format your answer as a JSON array of objects, where each object has "question" and "answer" keys. The array should be nested under a top-level key named "flashcards". For example:
{{
"flashcards": [
{{"question": "Question 1?", "answer": "Answer 1"}},
{{"question": "Question 2?", "answer": "Answer 2"}},
{{"question": "Question 3?", "answer": "Answer 3"}}
]
}}
Text:
\"\"\"{chunk}
\"\"\""""
flashcards = []
try:
chat_completion = client.chat.completions.create(
messages=[{"role": "user", "content": prompt}],
model=model_name,
temperature=0.7,
max_tokens=500,
response_format={"type": "json_object"}
)
content = chat_completion.choices[0].message.content
parsed_json = json.loads(content)
if "flashcards" in parsed_json and isinstance(parsed_json["flashcards"], list):
flashcards = parsed_json["flashcards"]
elif "questions" in parsed_json and isinstance(parsed_json["questions"], list):
flashcards = parsed_json["questions"]
else:
print(f"DEBUG: Unexpected JSON structure from Groq: {parsed_json}")
if isinstance(parsed_json, list) and all(isinstance(item, dict) for item in parsed_json):
flashcards = parsed_json
else:
flashcards = []
except json.JSONDecodeError as e:
print(f"ERROR: JSON decoding failed for Groq response: {e}")
print(f"Raw content that caused error: {content}")
flashcards = []
except Exception as e:
print(f"ERROR: Groq API call failed: {e}")
flashcards = []
return flashcards
# --- Overall Flashcard Generation Logic ---
def generate_all_flashcards(full_text):
chunks = chunk_text(full_text)
all_flashcards = []
for i, chunk in enumerate(chunks):
print(f"Processing chunk {i+1}/{len(chunks)}...")
cards = generate_flashcards_from_chunk(chunk)
all_flashcards.extend(cards)
print(f"DEBUG: Total flashcards generated: {len(all_flashcards)}")
return all_flashcards
# --- Gradio UI Logic ---
def process_pdf_and_generate_flashcards(pdf_file_binary_data, state):
print("DEBUG: process_pdf_and_generate_flashcards started.")
if state is None:
state = {"flashcards": [], "index": 0}
if pdf_file_binary_data is None:
print("ERROR: No PDF file uploaded.")
raise gr.Error("Please upload a PDF file.")
try:
raw_text = extract_text_from_pdf(pdf_file_binary_data)
print(f"DEBUG: Extracted text length: {len(raw_text)} chars, first 500 chars: {raw_text[:500]}...")
if not raw_text.strip():
print("ERROR: Could not extract text from PDF (empty text).")
raise gr.Error("Could not extract text from PDF. Please check the PDF content.")
flashcards = generate_all_flashcards(raw_text)
print(f"DEBUG: Generated flashcards: {len(flashcards)} cards")
if not flashcards:
print("ERROR: No flashcards generated from text.")
raise gr.Error("No flashcards generated. Please try a different PDF or adjust prompt.")
state["flashcards"] = flashcards
state["index"] = 0
first_card = state["flashcards"][state["index"]]
question = first_card.get('question', 'N/A - Missing Question')
total_cards = len(state["flashcards"])
print(f"DEBUG: Successfully prepared {total_cards} flashcards for practice.")
return (
f"Ready to practice! Total flashcards: {total_cards}",
question,
f"Card {state['index'] + 1} of {total_cards}",
gr.update(visible=True), # show show_answer_btn
gr.update(visible=True), # show next_btn
gr.update(visible=True), # show prev_btn
state # Return the updated state
)
except gr.Error as e:
raise e
except Exception as e:
print(f"CRITICAL ERROR in process_pdf_and_generate_flashcards: {e}")
traceback.print_exc()
raise gr.Error(f"An unexpected internal error occurred: {e}. Check console for details.", print_exception=True)
def show_answer(state):
if not state or not state.get("flashcards"):
return gr.update(value=""), gr.update(visible=False), state
card = state["flashcards"][state["index"]]
answer = card.get('answer', 'N/A - Missing Answer')
print(f"DEBUG: Showing answer for card {state['index'] + 1}.")
return gr.update(value=answer), gr.update(visible=True), state
def next_card(state):
if not state or not state.get("flashcards"):
return "", "", "No cards to display", gr.update(visible=False), gr.update(visible=False), state
state["index"] = (state["index"] + 1) % len(state["flashcards"])
card = state["flashcards"][state["index"]]
question = card.get('question', 'N/A - Missing Question')
total_cards = len(state["flashcards"])
print(f"DEBUG: Moving to next card: {state['index'] + 1}.")
return (
question,
"",
f"Card {state['index'] + 1} of {total_cards}",
gr.update(visible=True),
gr.update(visible=True),
state
)
def prev_card(state):
if not state or not state.get("flashcards"):
return "", "", "No cards to display", gr.update(visible=False), gr.update(visible=False), state
state["index"] = (state["index"] - 1 + len(state["flashcards"])) % len(state["flashcards"])
card = state["flashcards"][state["index"]]
question = card.get('question', 'N/A - Missing Question')
total_cards = len(state["flashcards"])
print(f"DEBUG: Moving to previous card: {state['index'] + 1}.")
return (
question,
"",
f"Card {state['index'] + 1} of {total_cards}",
gr.update(visible=True),
gr.update(visible=True),
state
)
# --- Gradio UI ---
with gr.Blocks(title="AI Flashcard Generator", theme=gr.themes.Default()) as demo:
state = gr.State(value={"flashcards": [], "index": 0})
# Header
gr.Markdown(
"""
<div style="text-align: center; padding: 15px;">
<h1 style="color: #1E3A8A; font-size: 2.4em; margin-bottom: 8px;">AI Flashcard Generator</h1>
<p style="color: #555; font-size: 1.05em;">
Upload your lecture PDF and let AI generate flashcards for effective study sessions.
</p>
</div>
"""
)
# Upload + Generate Section
with gr.Row(elem_id="upload_section_row"):
with gr.Column(scale=1):
pdf_input = gr.File(
label="Upload Lecture PDF",
type="binary",
file_types=[".pdf"],
elem_id="pdf_file_input"
)
with gr.Column(scale=1):
generate_btn = gr.Button("Generate Flashcards", variant="primary", size="lg")
output_message = gr.Markdown(
value="Upload a PDF and click **Generate Flashcards**.",
elem_id="output_status_message"
)
# Flashcard Display Section
with gr.Column(elem_id="flashcard_display_column"):
card_counter = gr.Markdown("Card 0 of 0", elem_id="card_counter_text")
question_output = gr.Textbox(
label="Question",
interactive=False,
lines=5,
placeholder="Your question will appear here..."
)
answer_output = gr.Textbox(
label="Answer",
interactive=False,
lines=5,
placeholder="The answer will appear here..."
)
with gr.Row():
prev_btn = gr.Button("Previous", variant="secondary", size="sm", visible=False)
show_answer_btn = gr.Button("Show Answer", variant="primary", size="sm", visible=False)
next_btn = gr.Button("Next", variant="secondary", size="sm", visible=False)
# --- Custom CSS ---
demo.css = """
body {
font-family: 'Segoe UI', sans-serif;
background-color: #f7f9fc;
}
.gradio-container {
max-width: 900px;
margin: auto;
padding: 15px;
}
#upload_section_row {
background-color: #f0f4f8;
padding: 5px;
border-radius: 8px;
box-shadow: 0 2px 8px rgba(0,0,0,0.05);
margin-bottom: 15px;
width: 450px;
min-height: 50px;
display: flex;
justify-content: center;
align-items: center;
margin-left: auto;
margin-right: auto;
}
#pdf_file_input {
border: 2px dashed #3B82F6;
background-color: #f8fafc;
border-radius: 6px;
padding: 5px;
height: 50px;
display: flex;
align-items: center;
justify-content: center;
}
#output_status_message {
text-align: center;
font-size: 1.05em;
color: #333;
}
#flashcard_display_column {
background-color: #ffffff;
border-radius: 10px;
padding: 20px;
box-shadow: 0 4px 10px rgba(0,0,0,0.1);
width: 450px;
min-height: 400px;
margin-left: auto;
margin-right: auto;
}
#card_counter_text {
color: #6b7280;
margin-bottom: 10px;
font-size: 1.05em;
}
.gr-textbox {
border: 1.5px solid #3B82F6;
border-radius: 6px;
background-color: #f9fafb;
font-size: 1.05em;
}
.gr-button.primary {
background-color: #2563EB;
color: white;
font-weight: bold;
padding: 5px 10px;
height: 40px;
}
.gr-button.primary:hover {
background-color: #1E40AF;
}
.gr-button.secondary {
background-color: #E5E7EB;
color: #111827;
padding: 5px 10px;
height: 40px;
}
.gr-button.secondary:hover {
background-color: #D1D5DB;
}
"""
# --- Event Bindings ---
generate_btn.click(
fn=process_pdf_and_generate_flashcards,
inputs=[pdf_input, state],
outputs=[
output_message,
question_output,
card_counter,
show_answer_btn,
next_btn,
prev_btn,
state
],
api_name="generate_flashcards"
)
show_answer_btn.click(
fn=show_answer,
inputs=[state],
outputs=[answer_output, next_btn, state]
)
next_btn.click(
fn=next_card,
inputs=[state],
outputs=[question_output, answer_output, card_counter, show_answer_btn, prev_btn, state]
)
prev_btn.click(
fn=prev_card,
inputs=[state],
outputs=[question_output, answer_output, card_counter, show_answer_btn, next_btn, state]
)
demo.launch()