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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import gradio as gr
|
2 |
+
import PyPDF2
|
3 |
+
import docx
|
4 |
+
from openai import OpenAI
|
5 |
+
import io
|
6 |
+
import json
|
7 |
+
import time
|
8 |
+
from typing import List, Dict, Any, Optional
|
9 |
+
import spaces
|
10 |
+
import os
|
11 |
+
|
12 |
+
# Global variables to store API key and document text
|
13 |
+
API_KEY = ""
|
14 |
+
DOCUMENT_TEXT = ""
|
15 |
+
MODEL = "google/gemma-3-27b-it:free"
|
16 |
+
|
17 |
+
def setup_client(api_key: str):
|
18 |
+
"""Initialize and test API key"""
|
19 |
+
global API_KEY
|
20 |
+
try:
|
21 |
+
if not api_key or api_key.strip() == "":
|
22 |
+
return "β Please enter a valid API key"
|
23 |
+
|
24 |
+
# Test the API key by creating a client
|
25 |
+
client = OpenAI(
|
26 |
+
base_url="https://openrouter.ai/api/v1",
|
27 |
+
api_key=api_key.strip(),
|
28 |
+
)
|
29 |
+
# Store the API key globally
|
30 |
+
API_KEY = api_key.strip()
|
31 |
+
return "β
API Key configured successfully!"
|
32 |
+
except Exception as e:
|
33 |
+
return f"β Error configuring API: {str(e)}"
|
34 |
+
|
35 |
+
def create_client() -> Optional[OpenAI]:
|
36 |
+
"""Create OpenAI client with stored API key"""
|
37 |
+
if not API_KEY:
|
38 |
+
return None
|
39 |
+
return OpenAI(
|
40 |
+
base_url="https://openrouter.ai/api/v1",
|
41 |
+
api_key=API_KEY,
|
42 |
+
)
|
43 |
+
|
44 |
+
def extract_text_from_pdf(file_path: str) -> str:
|
45 |
+
"""Extract text from PDF file"""
|
46 |
+
try:
|
47 |
+
with open(file_path, 'rb') as file:
|
48 |
+
pdf_reader = PyPDF2.PdfReader(file)
|
49 |
+
text = ""
|
50 |
+
for page_num, page in enumerate(pdf_reader.pages):
|
51 |
+
try:
|
52 |
+
page_text = page.extract_text()
|
53 |
+
if page_text:
|
54 |
+
text += page_text + "\n"
|
55 |
+
except Exception as e:
|
56 |
+
print(f"Error extracting text from page {page_num}: {e}")
|
57 |
+
continue
|
58 |
+
return text.strip()
|
59 |
+
except Exception as e:
|
60 |
+
return f"Error reading PDF: {str(e)}"
|
61 |
+
|
62 |
+
def extract_text_from_docx(file_path: str) -> str:
|
63 |
+
"""Extract text from DOCX file"""
|
64 |
+
try:
|
65 |
+
doc = docx.Document(file_path)
|
66 |
+
text = ""
|
67 |
+
for paragraph in doc.paragraphs:
|
68 |
+
if paragraph.text.strip():
|
69 |
+
text += paragraph.text + "\n"
|
70 |
+
|
71 |
+
# Also extract text from tables
|
72 |
+
for table in doc.tables:
|
73 |
+
for row in table.rows:
|
74 |
+
for cell in row.cells:
|
75 |
+
if cell.text.strip():
|
76 |
+
text += cell.text + "\n"
|
77 |
+
|
78 |
+
return text.strip()
|
79 |
+
except Exception as e:
|
80 |
+
return f"Error reading DOCX: {str(e)}"
|
81 |
+
|
82 |
+
def process_document(file):
|
83 |
+
"""Process uploaded document and extract text"""
|
84 |
+
global DOCUMENT_TEXT
|
85 |
+
|
86 |
+
print(f"Processing file: {file}") # Debug print
|
87 |
+
|
88 |
+
if file is None:
|
89 |
+
DOCUMENT_TEXT = ""
|
90 |
+
return "β No file uploaded", "β No document loaded"
|
91 |
+
|
92 |
+
try:
|
93 |
+
file_path = file.name if hasattr(file, 'name') else str(file)
|
94 |
+
print(f"File path: {file_path}") # Debug print
|
95 |
+
|
96 |
+
# Check if file exists
|
97 |
+
if not os.path.exists(file_path):
|
98 |
+
DOCUMENT_TEXT = ""
|
99 |
+
return "β File not found", "β No document loaded"
|
100 |
+
|
101 |
+
# Get file extension
|
102 |
+
file_extension = file_path.lower().split('.')[-1]
|
103 |
+
print(f"File extension: {file_extension}") # Debug print
|
104 |
+
|
105 |
+
# Extract text based on file type
|
106 |
+
if file_extension == 'pdf':
|
107 |
+
extracted_text = extract_text_from_pdf(file_path)
|
108 |
+
elif file_extension in ['docx', 'doc']:
|
109 |
+
extracted_text = extract_text_from_docx(file_path)
|
110 |
+
else:
|
111 |
+
DOCUMENT_TEXT = ""
|
112 |
+
return "β Unsupported file format. Please upload PDF or DOCX files.", "β No document loaded"
|
113 |
+
|
114 |
+
print(f"Extracted text length: {len(extracted_text) if extracted_text else 0}") # Debug print
|
115 |
+
|
116 |
+
# Check if extraction was successful
|
117 |
+
if extracted_text.startswith("Error"):
|
118 |
+
DOCUMENT_TEXT = ""
|
119 |
+
return extracted_text, "β No document loaded"
|
120 |
+
|
121 |
+
# Clean and set the global variable
|
122 |
+
DOCUMENT_TEXT = extracted_text.strip()
|
123 |
+
|
124 |
+
if DOCUMENT_TEXT and len(DOCUMENT_TEXT) > 10: # Minimum length check
|
125 |
+
word_count = len(DOCUMENT_TEXT.split())
|
126 |
+
char_count = len(DOCUMENT_TEXT)
|
127 |
+
preview = DOCUMENT_TEXT[:300] + "..." if len(DOCUMENT_TEXT) > 300 else DOCUMENT_TEXT
|
128 |
+
|
129 |
+
status_msg = f"β
Document loaded ({word_count} words, {char_count} characters)"
|
130 |
+
process_msg = f"β
Document processed successfully!\nπ Word count: {word_count}\nπ Character count: {char_count}\n\nπ Preview:\n{preview}"
|
131 |
+
|
132 |
+
print(f"Document processed successfully. Word count: {word_count}") # Debug print
|
133 |
+
return process_msg, status_msg
|
134 |
+
else:
|
135 |
+
DOCUMENT_TEXT = ""
|
136 |
+
return "β Could not extract meaningful text from the document. The document might be empty, contain only images, or be corrupted.", "β No document loaded"
|
137 |
+
|
138 |
+
except Exception as e:
|
139 |
+
DOCUMENT_TEXT = ""
|
140 |
+
error_msg = f"β Error processing document: {str(e)}"
|
141 |
+
print(f"Error: {error_msg}") # Debug print
|
142 |
+
return error_msg, "β No document loaded"
|
143 |
+
|
144 |
+
def generate_content(prompt: str, max_tokens: int = 2000) -> str:
|
145 |
+
"""Generate content using the AI model"""
|
146 |
+
global DOCUMENT_TEXT, API_KEY
|
147 |
+
|
148 |
+
print(f"Generate content called. API_KEY exists: {bool(API_KEY)}, DOCUMENT_TEXT length: {len(DOCUMENT_TEXT) if DOCUMENT_TEXT else 0}") # Debug print
|
149 |
+
|
150 |
+
if not API_KEY or API_KEY.strip() == "":
|
151 |
+
return "β Please configure your API key first"
|
152 |
+
|
153 |
+
if not DOCUMENT_TEXT or len(DOCUMENT_TEXT.strip()) < 10:
|
154 |
+
return "β Please upload and process a document first. Make sure the document contains readable text."
|
155 |
+
|
156 |
+
try:
|
157 |
+
client = create_client()
|
158 |
+
if not client:
|
159 |
+
return "β Failed to create API client"
|
160 |
+
|
161 |
+
print("Sending request to API...") # Debug print
|
162 |
+
|
163 |
+
completion = client.chat.completions.create(
|
164 |
+
extra_headers={
|
165 |
+
"HTTP-Referer": "https://educational-assistant.app",
|
166 |
+
"X-Title": "Educational Content Creator",
|
167 |
+
},
|
168 |
+
model=MODEL,
|
169 |
+
messages=[
|
170 |
+
{
|
171 |
+
"role": "system",
|
172 |
+
"content": "You are an expert educational content creator. Create comprehensive, engaging, and pedagogically sound educational materials based on the provided document content."
|
173 |
+
},
|
174 |
+
{
|
175 |
+
"role": "user",
|
176 |
+
"content": f"Document Content:\n{DOCUMENT_TEXT[:4000]}\n\n{prompt}" # Limit document content to avoid token limits
|
177 |
+
}
|
178 |
+
],
|
179 |
+
max_tokens=max_tokens,
|
180 |
+
temperature=0.7
|
181 |
+
)
|
182 |
+
|
183 |
+
result = completion.choices[0].message.content
|
184 |
+
print(f"API response received. Length: {len(result) if result else 0}") # Debug print
|
185 |
+
return result
|
186 |
+
|
187 |
+
except Exception as e:
|
188 |
+
error_msg = f"β Error generating content: {str(e)}"
|
189 |
+
print(f"API Error: {error_msg}") # Debug print
|
190 |
+
return error_msg
|
191 |
+
|
192 |
+
# Content generation functions with @spaces.GPU decorator
|
193 |
+
@spaces.GPU
|
194 |
+
def generate_summary():
|
195 |
+
"""Generate comprehensive summary"""
|
196 |
+
prompt = """Create a comprehensive summary of this document with the following structure:
|
197 |
+
|
198 |
+
## π Executive Summary
|
199 |
+
Provide a brief overview in 2-3 sentences.
|
200 |
+
|
201 |
+
## π― Key Points
|
202 |
+
List the main concepts, ideas, or arguments presented.
|
203 |
+
|
204 |
+
## π Detailed Summary
|
205 |
+
Provide a thorough summary organized by topics or sections.
|
206 |
+
|
207 |
+
## π‘ Important Takeaways
|
208 |
+
Highlight the most crucial information students should remember.
|
209 |
+
"""
|
210 |
+
return generate_content(prompt)
|
211 |
+
|
212 |
+
@spaces.GPU
|
213 |
+
def generate_study_notes():
|
214 |
+
"""Generate structured study notes"""
|
215 |
+
prompt = """Create comprehensive study notes from this document with:
|
216 |
+
|
217 |
+
## π Study Notes
|
218 |
+
|
219 |
+
### π Key Concepts
|
220 |
+
- Define important terms and concepts
|
221 |
+
- Explain their significance
|
222 |
+
|
223 |
+
### π Main Topics
|
224 |
+
Organize content into clear sections with:
|
225 |
+
- Topic headings
|
226 |
+
- Key points under each topic
|
227 |
+
- Supporting details and examples
|
228 |
+
|
229 |
+
### π§ Memory Aids
|
230 |
+
- Create mnemonics for complex information
|
231 |
+
- Suggest visualization techniques
|
232 |
+
- Provide connection points between concepts
|
233 |
+
|
234 |
+
### β‘ Quick Review Points
|
235 |
+
- Bullet points for rapid review
|
236 |
+
- Essential facts and figures
|
237 |
+
"""
|
238 |
+
return generate_content(prompt)
|
239 |
+
|
240 |
+
@spaces.GPU
|
241 |
+
def generate_quiz():
|
242 |
+
"""Generate quiz questions"""
|
243 |
+
prompt = """Create a comprehensive quiz based on this document:
|
244 |
+
|
245 |
+
## π Quiz Questions
|
246 |
+
|
247 |
+
### Multiple Choice Questions (5 questions)
|
248 |
+
For each question, provide:
|
249 |
+
- Clear question
|
250 |
+
- 4 options (A, B, C, D)
|
251 |
+
- Correct answer
|
252 |
+
- Brief explanation
|
253 |
+
|
254 |
+
### Short Answer Questions (5 questions)
|
255 |
+
- Questions requiring 2-3 sentence answers
|
256 |
+
- Cover key concepts and applications
|
257 |
+
|
258 |
+
### Essay Questions (2 questions)
|
259 |
+
- Thought-provoking questions requiring detailed responses
|
260 |
+
- Focus on analysis, synthesis, or evaluation
|
261 |
+
|
262 |
+
### Answer Key
|
263 |
+
Provide all correct answers with explanations.
|
264 |
+
"""
|
265 |
+
return generate_content(prompt, max_tokens=3000)
|
266 |
+
|
267 |
+
@spaces.GPU
|
268 |
+
def generate_flashcards():
|
269 |
+
"""Generate flashcards"""
|
270 |
+
prompt = """Create 15-20 flashcards based on this document:
|
271 |
+
|
272 |
+
## π΄ Flashcards
|
273 |
+
|
274 |
+
Format each flashcard as:
|
275 |
+
**Card X:**
|
276 |
+
**Front:** [Question/Term]
|
277 |
+
**Back:** [Answer/Definition/Explanation]
|
278 |
+
|
279 |
+
Include flashcards for:
|
280 |
+
- Key terms and definitions
|
281 |
+
- Important concepts
|
282 |
+
- Facts and figures
|
283 |
+
- Cause and effect relationships
|
284 |
+
- Applications and examples
|
285 |
+
|
286 |
+
Make questions clear and answers comprehensive but concise.
|
287 |
+
"""
|
288 |
+
return generate_content(prompt, max_tokens=2500)
|
289 |
+
|
290 |
+
@spaces.GPU
|
291 |
+
def generate_mind_map():
|
292 |
+
"""Generate mind map structure"""
|
293 |
+
prompt = """Create a detailed mind map structure for this document:
|
294 |
+
|
295 |
+
## π§ Mind Map Structure
|
296 |
+
|
297 |
+
**Central Topic:** [Main subject of the document]
|
298 |
+
|
299 |
+
### Primary Branches:
|
300 |
+
For each main topic, create branches with:
|
301 |
+
- **Branch 1:** [Topic Name]
|
302 |
+
- Sub-branch 1.1: [Subtopic]
|
303 |
+
- Detail 1.1.1
|
304 |
+
- Detail 1.1.2
|
305 |
+
- Sub-branch 1.2: [Subtopic]
|
306 |
+
- Detail 1.2.1
|
307 |
+
- Detail 1.2.2
|
308 |
+
|
309 |
+
### Connections:
|
310 |
+
- Identify relationships between different branches
|
311 |
+
- Note cross-references and dependencies
|
312 |
+
- Highlight cause-effect relationships
|
313 |
+
|
314 |
+
### Visual Elements Suggestions:
|
315 |
+
- Color coding recommendations
|
316 |
+
- Symbol suggestions for different types of information
|
317 |
+
- Emphasis techniques for key concepts
|
318 |
+
"""
|
319 |
+
return generate_content(prompt)
|
320 |
+
|
321 |
+
@spaces.GPU
|
322 |
+
def generate_lesson_plan():
|
323 |
+
"""Generate lesson plan"""
|
324 |
+
prompt = """Create a detailed lesson plan based on this document:
|
325 |
+
|
326 |
+
## π Lesson Plan
|
327 |
+
|
328 |
+
### Learning Objectives
|
329 |
+
By the end of this lesson, students will be able to:
|
330 |
+
- [Specific, measurable objectives]
|
331 |
+
|
332 |
+
### Prerequisites
|
333 |
+
- Required background knowledge
|
334 |
+
- Recommended prior reading
|
335 |
+
|
336 |
+
### Lesson Structure (60 minutes)
|
337 |
+
|
338 |
+
**Introduction (10 minutes)**
|
339 |
+
- Hook/attention grabber
|
340 |
+
- Learning objectives overview
|
341 |
+
|
342 |
+
**Main Content (35 minutes)**
|
343 |
+
- Key concepts presentation
|
344 |
+
- Activities and examples
|
345 |
+
- Discussion points
|
346 |
+
|
347 |
+
**Practice & Application (10 minutes)**
|
348 |
+
- Practice exercises
|
349 |
+
- Real-world applications
|
350 |
+
|
351 |
+
**Wrap-up & Assessment (5 minutes)**
|
352 |
+
- Summary of key points
|
353 |
+
- Quick assessment questions
|
354 |
+
|
355 |
+
### Materials Needed
|
356 |
+
- List of required resources
|
357 |
+
|
358 |
+
### Assessment Methods
|
359 |
+
- How to evaluate student understanding
|
360 |
+
|
361 |
+
### Homework/Extension Activities
|
362 |
+
- Additional practice opportunities
|
363 |
+
"""
|
364 |
+
return generate_content(prompt, max_tokens=2500)
|
365 |
+
|
366 |
+
@spaces.GPU
|
367 |
+
def generate_concept_explanations():
|
368 |
+
"""Generate detailed concept explanations"""
|
369 |
+
prompt = """Provide detailed explanations of key concepts from this document:
|
370 |
+
|
371 |
+
## π Concept Deep Dive
|
372 |
+
|
373 |
+
For each major concept, provide:
|
374 |
+
|
375 |
+
### Concept Name
|
376 |
+
**Definition:** Clear, precise definition
|
377 |
+
|
378 |
+
**Explanation:** Detailed explanation in simple terms
|
379 |
+
|
380 |
+
**Examples:** Real-world examples and applications
|
381 |
+
|
382 |
+
**Analogies:** Helpful comparisons to familiar concepts
|
383 |
+
|
384 |
+
**Common Misconceptions:** What students often get wrong
|
385 |
+
|
386 |
+
**Connection to Other Concepts:** How it relates to other topics
|
387 |
+
|
388 |
+
**Practice Application:** Simple exercise or question
|
389 |
+
|
390 |
+
---
|
391 |
+
|
392 |
+
Repeat this structure for all major concepts in the document.
|
393 |
+
"""
|
394 |
+
return generate_content(prompt, max_tokens=3000)
|
395 |
+
|
396 |
+
@spaces.GPU
|
397 |
+
def generate_practice_problems():
|
398 |
+
"""Generate practice problems"""
|
399 |
+
prompt = """Create practice problems based on this document:
|
400 |
+
|
401 |
+
## πͺ Practice Problems
|
402 |
+
|
403 |
+
### Beginner Level (5 problems)
|
404 |
+
- Basic application of concepts
|
405 |
+
- Direct recall and simple calculations
|
406 |
+
- Step-by-step solutions provided
|
407 |
+
|
408 |
+
### Intermediate Level (5 problems)
|
409 |
+
- Multi-step problems
|
410 |
+
- Requires understanding of relationships
|
411 |
+
- Guided solutions with explanations
|
412 |
+
|
413 |
+
### Advanced Level (3 problems)
|
414 |
+
- Complex scenarios
|
415 |
+
- Requires analysis and synthesis
|
416 |
+
- Detailed solution strategies
|
417 |
+
|
418 |
+
### Challenge Problems (2 problems)
|
419 |
+
- Extension beyond document content
|
420 |
+
- Creative application
|
421 |
+
- Multiple solution approaches
|
422 |
+
|
423 |
+
**For each problem, include:**
|
424 |
+
- Clear problem statement
|
425 |
+
- Required formulas/concepts
|
426 |
+
- Step-by-step solution
|
427 |
+
- Common mistakes to avoid
|
428 |
+
"""
|
429 |
+
return generate_content(prompt, max_tokens=3500)
|
430 |
+
|
431 |
+
def get_document_status():
|
432 |
+
"""Get current document status"""
|
433 |
+
global DOCUMENT_TEXT
|
434 |
+
if DOCUMENT_TEXT and len(DOCUMENT_TEXT.strip()) > 10:
|
435 |
+
word_count = len(DOCUMENT_TEXT.split())
|
436 |
+
char_count = len(DOCUMENT_TEXT)
|
437 |
+
return f"β
Document loaded ({word_count} words, {char_count} characters)"
|
438 |
+
else:
|
439 |
+
return "β No document loaded"
|
440 |
+
|
441 |
+
def get_api_status():
|
442 |
+
"""Get current API status"""
|
443 |
+
global API_KEY
|
444 |
+
if API_KEY and API_KEY.strip():
|
445 |
+
return "β
API Key configured"
|
446 |
+
else:
|
447 |
+
return "β API Key not configured"
|
448 |
+
|
449 |
+
# Create Gradio interface
|
450 |
+
def create_interface():
|
451 |
+
with gr.Blocks(title="π Educational Content Creator Assistant", theme=gr.themes.Soft()) as app:
|
452 |
+
gr.Markdown("""
|
453 |
+
# π Educational Content Creator Assistant
|
454 |
+
Transform your documents into comprehensive educational materials using AI!
|
455 |
+
|
456 |
+
**Features:** Study Notes β’ Quizzes β’ Flashcards β’ Mind Maps β’ Lesson Plans β’ Practice Problems & More!
|
457 |
+
|
458 |
+
*Powered by ZeroGPU for enhanced performance*
|
459 |
+
""")
|
460 |
+
|
461 |
+
with gr.Row():
|
462 |
+
with gr.Column(scale=1):
|
463 |
+
gr.Markdown("### π Setup")
|
464 |
+
api_key = gr.Textbox(
|
465 |
+
label="OpenRouter API Key",
|
466 |
+
type="password",
|
467 |
+
placeholder="Enter your OpenRouter API key...",
|
468 |
+
info="Get your API key from https://openrouter.ai/"
|
469 |
+
)
|
470 |
+
setup_btn = gr.Button("π§ Configure API", variant="primary")
|
471 |
+
setup_status = gr.Textbox(label="API Status", value=get_api_status(), interactive=False)
|
472 |
+
|
473 |
+
gr.Markdown("### π Document Upload")
|
474 |
+
file_upload = gr.File(
|
475 |
+
label="Upload Document (PDF or DOCX)",
|
476 |
+
file_types=[".pdf", ".docx", ".doc"],
|
477 |
+
type="filepath"
|
478 |
+
)
|
479 |
+
process_btn = gr.Button("π Process Document", variant="secondary")
|
480 |
+
process_status = gr.Textbox(label="Processing Status", interactive=False, lines=4)
|
481 |
+
|
482 |
+
# Document status indicator
|
483 |
+
doc_status = gr.Textbox(
|
484 |
+
label="Document Status",
|
485 |
+
value=get_document_status(),
|
486 |
+
interactive=False
|
487 |
+
)
|
488 |
+
|
489 |
+
with gr.Column(scale=2):
|
490 |
+
gr.Markdown("### π― Generate Educational Content")
|
491 |
+
|
492 |
+
with gr.Row():
|
493 |
+
summary_btn = gr.Button("π Generate Summary", variant="primary")
|
494 |
+
notes_btn = gr.Button("π Study Notes", variant="primary")
|
495 |
+
quiz_btn = gr.Button("π Create Quiz", variant="primary")
|
496 |
+
|
497 |
+
with gr.Row():
|
498 |
+
flashcards_btn = gr.Button("π΄ Flashcards", variant="secondary")
|
499 |
+
mindmap_btn = gr.Button("π§ Mind Map", variant="secondary")
|
500 |
+
lesson_btn = gr.Button("π Lesson Plan", variant="secondary")
|
501 |
+
|
502 |
+
with gr.Row():
|
503 |
+
concepts_btn = gr.Button("π Concept Explanations", variant="secondary")
|
504 |
+
problems_btn = gr.Button("πͺ Practice Problems", variant="secondary")
|
505 |
+
|
506 |
+
output = gr.Textbox(
|
507 |
+
label="Generated Content",
|
508 |
+
lines=20,
|
509 |
+
max_lines=30,
|
510 |
+
placeholder="Generated educational content will appear here...",
|
511 |
+
show_copy_button=True
|
512 |
+
)
|
513 |
+
|
514 |
+
gr.Markdown("""
|
515 |
+
### π How to Use:
|
516 |
+
1. **Get API Key:** Sign up at [OpenRouter](https://openrouter.ai/) and get your free API key
|
517 |
+
2. **Configure:** Enter your API key and click "Configure API"
|
518 |
+
3. **Upload:** Upload a PDF or DOCX document (make sure it contains readable text)
|
519 |
+
4. **Process:** Click "Process Document" to extract text
|
520 |
+
5. **Generate:** Choose any educational content type to generate
|
521 |
+
|
522 |
+
### π― Content Types:
|
523 |
+
- **Summary:** Comprehensive overview with key points
|
524 |
+
- **Study Notes:** Structured notes with key concepts and memory aids
|
525 |
+
- **Quiz:** Multiple choice, short answer, and essay questions with answers
|
526 |
+
- **Flashcards:** Question-answer pairs for memorization
|
527 |
+
- **Mind Map:** Visual structure of document concepts
|
528 |
+
- **Lesson Plan:** Complete teaching plan with objectives and activities
|
529 |
+
- **Concept Explanations:** Deep dive into key concepts with examples
|
530 |
+
- **Practice Problems:** Graded exercises from beginner to advanced
|
531 |
+
|
532 |
+
### π‘ Tips:
|
533 |
+
- Make sure your PDF contains selectable text (not just images)
|
534 |
+
- For best results, use documents with clear structure and headings
|
535 |
+
- The app works with academic papers, textbooks, reports, and study materials
|
536 |
+
|
537 |
+
### β‘ Performance Note:
|
538 |
+
This app uses ZeroGPU for enhanced processing. Functions will automatically utilize GPU resources when needed.
|
539 |
+
""")
|
540 |
+
|
541 |
+
# Event handlers
|
542 |
+
def setup_api_and_update_status(api_key):
|
543 |
+
result = setup_client(api_key)
|
544 |
+
status = get_api_status()
|
545 |
+
return result, status
|
546 |
+
|
547 |
+
setup_btn.click(
|
548 |
+
setup_api_and_update_status,
|
549 |
+
inputs=[api_key],
|
550 |
+
outputs=[setup_status, setup_status]
|
551 |
+
)
|
552 |
+
|
553 |
+
def process_and_update_all_status(file):
|
554 |
+
process_result, doc_status_result = process_document(file)
|
555 |
+
return process_result, doc_status_result
|
556 |
+
|
557 |
+
process_btn.click(
|
558 |
+
process_and_update_all_status,
|
559 |
+
inputs=[file_upload],
|
560 |
+
outputs=[process_status, doc_status]
|
561 |
+
)
|
562 |
+
|
563 |
+
# Content generation button handlers
|
564 |
+
summary_btn.click(generate_summary, outputs=[output])
|
565 |
+
notes_btn.click(generate_study_notes, outputs=[output])
|
566 |
+
quiz_btn.click(generate_quiz, outputs=[output])
|
567 |
+
flashcards_btn.click(generate_flashcards, outputs=[output])
|
568 |
+
mindmap_btn.click(generate_mind_map, outputs=[output])
|
569 |
+
lesson_btn.click(generate_lesson_plan, outputs=[output])
|
570 |
+
concepts_btn.click(generate_concept_explanations, outputs=[output])
|
571 |
+
problems_btn.click(generate_practice_problems, outputs=[output])
|
572 |
+
|
573 |
+
# Update status on app load
|
574 |
+
def update_initial_status():
|
575 |
+
return get_api_status(), get_document_status()
|
576 |
+
|
577 |
+
app.load(
|
578 |
+
update_initial_status,
|
579 |
+
outputs=[setup_status, doc_status]
|
580 |
+
)
|
581 |
+
|
582 |
+
return app
|
583 |
+
|
584 |
+
# Launch the application
|
585 |
+
if __name__ == "__main__":
|
586 |
+
app = create_interface()
|
587 |
+
app.launch(
|
588 |
+
debug=True,
|
589 |
+
share=False
|
590 |
+
)
|