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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
9
+
10
+ class EducationalContentCreator:
11
+ def __init__(self):
12
+ self.client = None
13
+ self.document_text = ""
14
+ self.model = "google/gemma-3-27b-it:free"
15
+
16
+ def setup_client(self, api_key: str):
17
+ """Initialize OpenAI client with OpenRouter"""
18
+ try:
19
+ self.client = OpenAI(
20
+ base_url="https://openrouter.ai/api/v1",
21
+ api_key=api_key,
22
+ )
23
+ return "βœ… API Key configured successfully!"
24
+ except Exception as e:
25
+ return f"❌ Error configuring API: {str(e)}"
26
+
27
+ def extract_text_from_pdf(self, file_path: str) -> str:
28
+ """Extract text from PDF file"""
29
+ try:
30
+ with open(file_path, 'rb') as file:
31
+ pdf_reader = PyPDF2.PdfReader(file)
32
+ text = ""
33
+ for page in pdf_reader.pages:
34
+ text += page.extract_text() + "\n"
35
+ return text
36
+ except Exception as e:
37
+ return f"Error reading PDF: {str(e)}"
38
+
39
+ def extract_text_from_docx(self, file_path: str) -> str:
40
+ """Extract text from DOCX file"""
41
+ try:
42
+ doc = docx.Document(file_path)
43
+ text = ""
44
+ for paragraph in doc.paragraphs:
45
+ text += paragraph.text + "\n"
46
+ return text
47
+ except Exception as e:
48
+ return f"Error reading DOCX: {str(e)}"
49
+
50
+ def process_document(self, file):
51
+ """Process uploaded document and extract text"""
52
+ if file is None:
53
+ return "❌ No file uploaded"
54
+
55
+ file_path = file.name
56
+ file_extension = file_path.lower().split('.')[-1]
57
+
58
+ if file_extension == 'pdf':
59
+ self.document_text = self.extract_text_from_pdf(file_path)
60
+ elif file_extension in ['docx', 'doc']:
61
+ self.document_text = self.extract_text_from_docx(file_path)
62
+ else:
63
+ return "❌ Unsupported file format. Please upload PDF or DOCX files."
64
+
65
+ if self.document_text and len(self.document_text.strip()) > 0:
66
+ word_count = len(self.document_text.split())
67
+ return f"βœ… Document processed successfully!\nπŸ“„ Word count: {word_count}\nπŸ“ Preview: {self.document_text[:200]}..."
68
+ else:
69
+ return "❌ Could not extract text from the document"
70
+
71
+ def generate_content(self, prompt: str, max_tokens: int = 2000) -> str:
72
+ """Generate content using the AI model"""
73
+ if not self.client:
74
+ return "❌ Please configure your API key first"
75
+
76
+ if not self.document_text:
77
+ return "❌ Please upload and process a document first"
78
+
79
+ try:
80
+ completion = self.client.chat.completions.create(
81
+ extra_headers={
82
+ "HTTP-Referer": "https://educational-assistant.app",
83
+ "X-Title": "Educational Content Creator",
84
+ },
85
+ model=self.model,
86
+ messages=[
87
+ {
88
+ "role": "system",
89
+ "content": "You are an expert educational content creator. Create comprehensive, engaging, and pedagogically sound educational materials based on the provided document content."
90
+ },
91
+ {
92
+ "role": "user",
93
+ "content": f"Document Content:\n{self.document_text}\n\n{prompt}"
94
+ }
95
+ ],
96
+ max_tokens=max_tokens,
97
+ temperature=0.7
98
+ )
99
+ return completion.choices[0].message.content
100
+ except Exception as e:
101
+ return f"❌ Error generating content: {str(e)}"
102
+
103
+ def generate_summary(self):
104
+ """Generate comprehensive summary"""
105
+ prompt = """Create a comprehensive summary of this document with the following structure:
106
+
107
+ ## πŸ“‹ Executive Summary
108
+ Provide a brief overview in 2-3 sentences.
109
+
110
+ ## 🎯 Key Points
111
+ List the main concepts, ideas, or arguments presented.
112
+
113
+ ## πŸ“š Detailed Summary
114
+ Provide a thorough summary organized by topics or sections.
115
+
116
+ ## πŸ’‘ Important Takeaways
117
+ Highlight the most crucial information students should remember.
118
+ """
119
+ return self.generate_content(prompt)
120
+
121
+ def generate_study_notes(self):
122
+ """Generate structured study notes"""
123
+ prompt = """Create comprehensive study notes from this document with:
124
+
125
+ ## πŸ“– Study Notes
126
+
127
+ ### πŸ”‘ Key Concepts
128
+ - Define important terms and concepts
129
+ - Explain their significance
130
+
131
+ ### πŸ“Š Main Topics
132
+ Organize content into clear sections with:
133
+ - Topic headings
134
+ - Key points under each topic
135
+ - Supporting details and examples
136
+
137
+ ### 🧠 Memory Aids
138
+ - Create mnemonics for complex information
139
+ - Suggest visualization techniques
140
+ - Provide connection points between concepts
141
+
142
+ ### ⚑ Quick Review Points
143
+ - Bullet points for rapid review
144
+ - Essential facts and figures
145
+ """
146
+ return self.generate_content(prompt)
147
+
148
+ def generate_quiz(self):
149
+ """Generate quiz questions"""
150
+ prompt = """Create a comprehensive quiz based on this document:
151
+
152
+ ## πŸ“ Quiz Questions
153
+
154
+ ### Multiple Choice Questions (5 questions)
155
+ For each question, provide:
156
+ - Clear question
157
+ - 4 options (A, B, C, D)
158
+ - Correct answer
159
+ - Brief explanation
160
+
161
+ ### Short Answer Questions (5 questions)
162
+ - Questions requiring 2-3 sentence answers
163
+ - Cover key concepts and applications
164
+
165
+ ### Essay Questions (2 questions)
166
+ - Thought-provoking questions requiring detailed responses
167
+ - Focus on analysis, synthesis, or evaluation
168
+
169
+ ### Answer Key
170
+ Provide all correct answers with explanations.
171
+ """
172
+ return self.generate_content(prompt, max_tokens=3000)
173
+
174
+ def generate_flashcards(self):
175
+ """Generate flashcards"""
176
+ prompt = """Create 15-20 flashcards based on this document:
177
+
178
+ ## 🎴 Flashcards
179
+
180
+ Format each flashcard as:
181
+ **Card X:**
182
+ **Front:** [Question/Term]
183
+ **Back:** [Answer/Definition/Explanation]
184
+
185
+ Include flashcards for:
186
+ - Key terms and definitions
187
+ - Important concepts
188
+ - Facts and figures
189
+ - Cause and effect relationships
190
+ - Applications and examples
191
+
192
+ Make questions clear and answers comprehensive but concise.
193
+ """
194
+ return self.generate_content(prompt, max_tokens=2500)
195
+
196
+ def generate_mind_map(self):
197
+ """Generate mind map structure"""
198
+ prompt = """Create a detailed mind map structure for this document:
199
+
200
+ ## 🧠 Mind Map Structure
201
+
202
+ **Central Topic:** [Main subject of the document]
203
+
204
+ ### Primary Branches:
205
+ For each main topic, create branches with:
206
+ - **Branch 1:** [Topic Name]
207
+ - Sub-branch 1.1: [Subtopic]
208
+ - Detail 1.1.1
209
+ - Detail 1.1.2
210
+ - Sub-branch 1.2: [Subtopic]
211
+ - Detail 1.2.1
212
+ - Detail 1.2.2
213
+
214
+ ### Connections:
215
+ - Identify relationships between different branches
216
+ - Note cross-references and dependencies
217
+ - Highlight cause-effect relationships
218
+
219
+ ### Visual Elements Suggestions:
220
+ - Color coding recommendations
221
+ - Symbol suggestions for different types of information
222
+ - Emphasis techniques for key concepts
223
+ """
224
+ return self.generate_content(prompt)
225
+
226
+ def generate_lesson_plan(self):
227
+ """Generate lesson plan"""
228
+ prompt = """Create a detailed lesson plan based on this document:
229
+
230
+ ## πŸ“š Lesson Plan
231
+
232
+ ### Learning Objectives
233
+ By the end of this lesson, students will be able to:
234
+ - [Specific, measurable objectives]
235
+
236
+ ### Prerequisites
237
+ - Required background knowledge
238
+ - Recommended prior reading
239
+
240
+ ### Lesson Structure (60 minutes)
241
+
242
+ **Introduction (10 minutes)**
243
+ - Hook/attention grabber
244
+ - Learning objectives overview
245
+
246
+ **Main Content (35 minutes)**
247
+ - Key concepts presentation
248
+ - Activities and examples
249
+ - Discussion points
250
+
251
+ **Practice & Application (10 minutes)**
252
+ - Practice exercises
253
+ - Real-world applications
254
+
255
+ **Wrap-up & Assessment (5 minutes)**
256
+ - Summary of key points
257
+ - Quick assessment questions
258
+
259
+ ### Materials Needed
260
+ - List of required resources
261
+
262
+ ### Assessment Methods
263
+ - How to evaluate student understanding
264
+
265
+ ### Homework/Extension Activities
266
+ - Additional practice opportunities
267
+ """
268
+ return self.generate_content(prompt, max_tokens=2500)
269
+
270
+ def generate_concept_explanations(self):
271
+ """Generate detailed concept explanations"""
272
+ prompt = """Provide detailed explanations of key concepts from this document:
273
+
274
+ ## πŸ” Concept Deep Dive
275
+
276
+ For each major concept, provide:
277
+
278
+ ### Concept Name
279
+ **Definition:** Clear, precise definition
280
+
281
+ **Explanation:** Detailed explanation in simple terms
282
+
283
+ **Examples:** Real-world examples and applications
284
+
285
+ **Analogies:** Helpful comparisons to familiar concepts
286
+
287
+ **Common Misconceptions:** What students often get wrong
288
+
289
+ **Connection to Other Concepts:** How it relates to other topics
290
+
291
+ **Practice Application:** Simple exercise or question
292
+
293
+ ---
294
+
295
+ Repeat this structure for all major concepts in the document.
296
+ """
297
+ return self.generate_content(prompt, max_tokens=3000)
298
+
299
+ def generate_practice_problems(self):
300
+ """Generate practice problems"""
301
+ prompt = """Create practice problems based on this document:
302
+
303
+ ## πŸ’ͺ Practice Problems
304
+
305
+ ### Beginner Level (5 problems)
306
+ - Basic application of concepts
307
+ - Direct recall and simple calculations
308
+ - Step-by-step solutions provided
309
+
310
+ ### Intermediate Level (5 problems)
311
+ - Multi-step problems
312
+ - Requires understanding of relationships
313
+ - Guided solutions with explanations
314
+
315
+ ### Advanced Level (3 problems)
316
+ - Complex scenarios
317
+ - Requires analysis and synthesis
318
+ - Detailed solution strategies
319
+
320
+ ### Challenge Problems (2 problems)
321
+ - Extension beyond document content
322
+ - Creative application
323
+ - Multiple solution approaches
324
+
325
+ **For each problem, include:**
326
+ - Clear problem statement
327
+ - Required formulas/concepts
328
+ - Step-by-step solution
329
+ - Common mistakes to avoid
330
+ """
331
+ return self.generate_content(prompt, max_tokens=3500)
332
+
333
+ # Initialize the educational content creator
334
+ creator = EducationalContentCreator()
335
+
336
+ # Create Gradio interface
337
+ def create_interface():
338
+ with gr.Blocks(title="πŸ“š Educational Content Creator Assistant", theme=gr.themes.Soft()) as app:
339
+ gr.Markdown("""
340
+ # πŸ“š Educational Content Creator Assistant
341
+ Transform your documents into comprehensive educational materials using AI!
342
+
343
+ **Features:** Study Notes β€’ Quizzes β€’ Flashcards β€’ Mind Maps β€’ Lesson Plans β€’ Practice Problems & More!
344
+ """)
345
+
346
+ with gr.Row():
347
+ with gr.Column(scale=1):
348
+ gr.Markdown("### πŸ”‘ Setup")
349
+ api_key = gr.Textbox(
350
+ label="OpenRouter API Key",
351
+ type="password",
352
+ placeholder="Enter your OpenRouter API key..."
353
+ )
354
+ setup_btn = gr.Button("πŸ”§ Configure API", variant="primary")
355
+ setup_status = gr.Textbox(label="Status", interactive=False)
356
+
357
+ gr.Markdown("### πŸ“„ Document Upload")
358
+ file_upload = gr.File(
359
+ label="Upload Document (PDF or DOCX)",
360
+ file_types=[".pdf", ".docx", ".doc"]
361
+ )
362
+ process_btn = gr.Button("πŸ”„ Process Document", variant="secondary")
363
+ process_status = gr.Textbox(label="Processing Status", interactive=False)
364
+
365
+ with gr.Column(scale=2):
366
+ gr.Markdown("### 🎯 Generate Educational Content")
367
+
368
+ with gr.Row():
369
+ summary_btn = gr.Button("πŸ“‹ Generate Summary", variant="primary")
370
+ notes_btn = gr.Button("πŸ“– Study Notes", variant="primary")
371
+ quiz_btn = gr.Button("πŸ“ Create Quiz", variant="primary")
372
+
373
+ with gr.Row():
374
+ flashcards_btn = gr.Button("🎴 Flashcards", variant="secondary")
375
+ mindmap_btn = gr.Button("🧠 Mind Map", variant="secondary")
376
+ lesson_btn = gr.Button("πŸ“š Lesson Plan", variant="secondary")
377
+
378
+ with gr.Row():
379
+ concepts_btn = gr.Button("πŸ” Concept Explanations", variant="secondary")
380
+ problems_btn = gr.Button("πŸ’ͺ Practice Problems", variant="secondary")
381
+
382
+ output = gr.Textbox(
383
+ label="Generated Content",
384
+ lines=20,
385
+ max_lines=30,
386
+ placeholder="Generated educational content will appear here...",
387
+ show_copy_button=True
388
+ )
389
+
390
+ gr.Markdown("""
391
+ ### πŸ“‹ How to Use:
392
+ 1. **Get API Key:** Sign up at [OpenRouter](https://openrouter.ai/) and get your API key
393
+ 2. **Configure:** Enter your API key and click "Configure API"
394
+ 3. **Upload:** Upload a PDF or DOCX document
395
+ 4. **Process:** Click "Process Document" to extract text
396
+ 5. **Generate:** Choose any educational content type to generate
397
+
398
+ ### 🎯 Content Types:
399
+ - **Summary:** Comprehensive overview with key points
400
+ - **Study Notes:** Structured notes with key concepts and memory aids
401
+ - **Quiz:** Multiple choice, short answer, and essay questions
402
+ - **Flashcards:** Question-answer pairs for memorization
403
+ - **Mind Map:** Visual structure of document concepts
404
+ - **Lesson Plan:** Complete teaching plan with objectives and activities
405
+ - **Concept Explanations:** Deep dive into key concepts with examples
406
+ - **Practice Problems:** Graded exercises from beginner to advanced
407
+ """)
408
+
409
+ # Event handlers
410
+ setup_btn.click(
411
+ creator.setup_client,
412
+ inputs=[api_key],
413
+ outputs=[setup_status]
414
+ )
415
+
416
+ process_btn.click(
417
+ creator.process_document,
418
+ inputs=[file_upload],
419
+ outputs=[process_status]
420
+ )
421
+
422
+ summary_btn.click(
423
+ creator.generate_summary,
424
+ outputs=[output]
425
+ )
426
+
427
+ notes_btn.click(
428
+ creator.generate_study_notes,
429
+ outputs=[output]
430
+ )
431
+
432
+ quiz_btn.click(
433
+ creator.generate_quiz,
434
+ outputs=[output]
435
+ )
436
+
437
+ flashcards_btn.click(
438
+ creator.generate_flashcards,
439
+ outputs=[output]
440
+ )
441
+
442
+ mindmap_btn.click(
443
+ creator.generate_mind_map,
444
+ outputs=[output]
445
+ )
446
+
447
+ lesson_btn.click(
448
+ creator.generate_lesson_plan,
449
+ outputs=[output]
450
+ )
451
+
452
+ concepts_btn.click(
453
+ creator.generate_concept_explanations,
454
+ outputs=[output]
455
+ )
456
+
457
+ problems_btn.click(
458
+ creator.generate_practice_problems,
459
+ outputs=[output]
460
+ )
461
+
462
+ return app
463
+
464
+ # Launch the application
465
+ if __name__ == "__main__":
466
+ app = create_interface()
467
+ app.launch(
468
+ server_name="0.0.0.0",
469
+ server_port=7860,
470
+ share=True,
471
+ show_error=True
472
+ )