ECCA / app.py
shukdevdatta123's picture
Create app.py
7fe0b2b verified
raw
history blame
16.7 kB
import gradio as gr
import PyPDF2
import docx
from openai import OpenAI
import io
import json
import time
from typing import List, Dict, Any
class EducationalContentCreator:
def __init__(self):
self.client = None
self.document_text = ""
self.model = "google/gemma-3-27b-it:free"
def setup_client(self, api_key: str):
"""Initialize OpenAI client with OpenRouter"""
try:
self.client = OpenAI(
base_url="https://openrouter.ai/api/v1",
api_key=api_key,
)
return "βœ… API Key configured successfully!"
except Exception as e:
return f"❌ Error configuring API: {str(e)}"
def extract_text_from_pdf(self, file_path: str) -> str:
"""Extract text from PDF file"""
try:
with open(file_path, 'rb') as file:
pdf_reader = PyPDF2.PdfReader(file)
text = ""
for page in pdf_reader.pages:
text += page.extract_text() + "\n"
return text
except Exception as e:
return f"Error reading PDF: {str(e)}"
def extract_text_from_docx(self, file_path: str) -> str:
"""Extract text from DOCX file"""
try:
doc = docx.Document(file_path)
text = ""
for paragraph in doc.paragraphs:
text += paragraph.text + "\n"
return text
except Exception as e:
return f"Error reading DOCX: {str(e)}"
def process_document(self, file):
"""Process uploaded document and extract text"""
if file is None:
return "❌ No file uploaded"
file_path = file.name
file_extension = file_path.lower().split('.')[-1]
if file_extension == 'pdf':
self.document_text = self.extract_text_from_pdf(file_path)
elif file_extension in ['docx', 'doc']:
self.document_text = self.extract_text_from_docx(file_path)
else:
return "❌ Unsupported file format. Please upload PDF or DOCX files."
if self.document_text and len(self.document_text.strip()) > 0:
word_count = len(self.document_text.split())
return f"βœ… Document processed successfully!\nπŸ“„ Word count: {word_count}\nπŸ“ Preview: {self.document_text[:200]}..."
else:
return "❌ Could not extract text from the document"
def generate_content(self, prompt: str, max_tokens: int = 2000) -> str:
"""Generate content using the AI model"""
if not self.client:
return "❌ Please configure your API key first"
if not self.document_text:
return "❌ Please upload and process a document first"
try:
completion = self.client.chat.completions.create(
extra_headers={
"HTTP-Referer": "https://educational-assistant.app",
"X-Title": "Educational Content Creator",
},
model=self.model,
messages=[
{
"role": "system",
"content": "You are an expert educational content creator. Create comprehensive, engaging, and pedagogically sound educational materials based on the provided document content."
},
{
"role": "user",
"content": f"Document Content:\n{self.document_text}\n\n{prompt}"
}
],
max_tokens=max_tokens,
temperature=0.7
)
return completion.choices[0].message.content
except Exception as e:
return f"❌ Error generating content: {str(e)}"
def generate_summary(self):
"""Generate comprehensive summary"""
prompt = """Create a comprehensive summary of this document with the following structure:
## πŸ“‹ Executive Summary
Provide a brief overview in 2-3 sentences.
## 🎯 Key Points
List the main concepts, ideas, or arguments presented.
## πŸ“š Detailed Summary
Provide a thorough summary organized by topics or sections.
## πŸ’‘ Important Takeaways
Highlight the most crucial information students should remember.
"""
return self.generate_content(prompt)
def generate_study_notes(self):
"""Generate structured study notes"""
prompt = """Create comprehensive study notes from this document with:
## πŸ“– Study Notes
### πŸ”‘ Key Concepts
- Define important terms and concepts
- Explain their significance
### πŸ“Š Main Topics
Organize content into clear sections with:
- Topic headings
- Key points under each topic
- Supporting details and examples
### 🧠 Memory Aids
- Create mnemonics for complex information
- Suggest visualization techniques
- Provide connection points between concepts
### ⚑ Quick Review Points
- Bullet points for rapid review
- Essential facts and figures
"""
return self.generate_content(prompt)
def generate_quiz(self):
"""Generate quiz questions"""
prompt = """Create a comprehensive quiz based on this document:
## πŸ“ Quiz Questions
### Multiple Choice Questions (5 questions)
For each question, provide:
- Clear question
- 4 options (A, B, C, D)
- Correct answer
- Brief explanation
### Short Answer Questions (5 questions)
- Questions requiring 2-3 sentence answers
- Cover key concepts and applications
### Essay Questions (2 questions)
- Thought-provoking questions requiring detailed responses
- Focus on analysis, synthesis, or evaluation
### Answer Key
Provide all correct answers with explanations.
"""
return self.generate_content(prompt, max_tokens=3000)
def generate_flashcards(self):
"""Generate flashcards"""
prompt = """Create 15-20 flashcards based on this document:
## 🎴 Flashcards
Format each flashcard as:
**Card X:**
**Front:** [Question/Term]
**Back:** [Answer/Definition/Explanation]
Include flashcards for:
- Key terms and definitions
- Important concepts
- Facts and figures
- Cause and effect relationships
- Applications and examples
Make questions clear and answers comprehensive but concise.
"""
return self.generate_content(prompt, max_tokens=2500)
def generate_mind_map(self):
"""Generate mind map structure"""
prompt = """Create a detailed mind map structure for this document:
## 🧠 Mind Map Structure
**Central Topic:** [Main subject of the document]
### Primary Branches:
For each main topic, create branches with:
- **Branch 1:** [Topic Name]
- Sub-branch 1.1: [Subtopic]
- Detail 1.1.1
- Detail 1.1.2
- Sub-branch 1.2: [Subtopic]
- Detail 1.2.1
- Detail 1.2.2
### Connections:
- Identify relationships between different branches
- Note cross-references and dependencies
- Highlight cause-effect relationships
### Visual Elements Suggestions:
- Color coding recommendations
- Symbol suggestions for different types of information
- Emphasis techniques for key concepts
"""
return self.generate_content(prompt)
def generate_lesson_plan(self):
"""Generate lesson plan"""
prompt = """Create a detailed lesson plan based on this document:
## πŸ“š Lesson Plan
### Learning Objectives
By the end of this lesson, students will be able to:
- [Specific, measurable objectives]
### Prerequisites
- Required background knowledge
- Recommended prior reading
### Lesson Structure (60 minutes)
**Introduction (10 minutes)**
- Hook/attention grabber
- Learning objectives overview
**Main Content (35 minutes)**
- Key concepts presentation
- Activities and examples
- Discussion points
**Practice & Application (10 minutes)**
- Practice exercises
- Real-world applications
**Wrap-up & Assessment (5 minutes)**
- Summary of key points
- Quick assessment questions
### Materials Needed
- List of required resources
### Assessment Methods
- How to evaluate student understanding
### Homework/Extension Activities
- Additional practice opportunities
"""
return self.generate_content(prompt, max_tokens=2500)
def generate_concept_explanations(self):
"""Generate detailed concept explanations"""
prompt = """Provide detailed explanations of key concepts from this document:
## πŸ” Concept Deep Dive
For each major concept, provide:
### Concept Name
**Definition:** Clear, precise definition
**Explanation:** Detailed explanation in simple terms
**Examples:** Real-world examples and applications
**Analogies:** Helpful comparisons to familiar concepts
**Common Misconceptions:** What students often get wrong
**Connection to Other Concepts:** How it relates to other topics
**Practice Application:** Simple exercise or question
---
Repeat this structure for all major concepts in the document.
"""
return self.generate_content(prompt, max_tokens=3000)
def generate_practice_problems(self):
"""Generate practice problems"""
prompt = """Create practice problems based on this document:
## πŸ’ͺ Practice Problems
### Beginner Level (5 problems)
- Basic application of concepts
- Direct recall and simple calculations
- Step-by-step solutions provided
### Intermediate Level (5 problems)
- Multi-step problems
- Requires understanding of relationships
- Guided solutions with explanations
### Advanced Level (3 problems)
- Complex scenarios
- Requires analysis and synthesis
- Detailed solution strategies
### Challenge Problems (2 problems)
- Extension beyond document content
- Creative application
- Multiple solution approaches
**For each problem, include:**
- Clear problem statement
- Required formulas/concepts
- Step-by-step solution
- Common mistakes to avoid
"""
return self.generate_content(prompt, max_tokens=3500)
# Initialize the educational content creator
creator = EducationalContentCreator()
# Create Gradio interface
def create_interface():
with gr.Blocks(title="πŸ“š Educational Content Creator Assistant", theme=gr.themes.Soft()) as app:
gr.Markdown("""
# πŸ“š Educational Content Creator Assistant
Transform your documents into comprehensive educational materials using AI!
**Features:** Study Notes β€’ Quizzes β€’ Flashcards β€’ Mind Maps β€’ Lesson Plans β€’ Practice Problems & More!
""")
with gr.Row():
with gr.Column(scale=1):
gr.Markdown("### πŸ”‘ Setup")
api_key = gr.Textbox(
label="OpenRouter API Key",
type="password",
placeholder="Enter your OpenRouter API key..."
)
setup_btn = gr.Button("πŸ”§ Configure API", variant="primary")
setup_status = gr.Textbox(label="Status", interactive=False)
gr.Markdown("### πŸ“„ Document Upload")
file_upload = gr.File(
label="Upload Document (PDF or DOCX)",
file_types=[".pdf", ".docx", ".doc"]
)
process_btn = gr.Button("πŸ”„ Process Document", variant="secondary")
process_status = gr.Textbox(label="Processing Status", interactive=False)
with gr.Column(scale=2):
gr.Markdown("### 🎯 Generate Educational Content")
with gr.Row():
summary_btn = gr.Button("πŸ“‹ Generate Summary", variant="primary")
notes_btn = gr.Button("πŸ“– Study Notes", variant="primary")
quiz_btn = gr.Button("πŸ“ Create Quiz", variant="primary")
with gr.Row():
flashcards_btn = gr.Button("🎴 Flashcards", variant="secondary")
mindmap_btn = gr.Button("🧠 Mind Map", variant="secondary")
lesson_btn = gr.Button("πŸ“š Lesson Plan", variant="secondary")
with gr.Row():
concepts_btn = gr.Button("πŸ” Concept Explanations", variant="secondary")
problems_btn = gr.Button("πŸ’ͺ Practice Problems", variant="secondary")
output = gr.Textbox(
label="Generated Content",
lines=20,
max_lines=30,
placeholder="Generated educational content will appear here...",
show_copy_button=True
)
gr.Markdown("""
### πŸ“‹ How to Use:
1. **Get API Key:** Sign up at [OpenRouter](https://openrouter.ai/) and get your API key
2. **Configure:** Enter your API key and click "Configure API"
3. **Upload:** Upload a PDF or DOCX document
4. **Process:** Click "Process Document" to extract text
5. **Generate:** Choose any educational content type to generate
### 🎯 Content Types:
- **Summary:** Comprehensive overview with key points
- **Study Notes:** Structured notes with key concepts and memory aids
- **Quiz:** Multiple choice, short answer, and essay questions
- **Flashcards:** Question-answer pairs for memorization
- **Mind Map:** Visual structure of document concepts
- **Lesson Plan:** Complete teaching plan with objectives and activities
- **Concept Explanations:** Deep dive into key concepts with examples
- **Practice Problems:** Graded exercises from beginner to advanced
""")
# Event handlers
setup_btn.click(
creator.setup_client,
inputs=[api_key],
outputs=[setup_status]
)
process_btn.click(
creator.process_document,
inputs=[file_upload],
outputs=[process_status]
)
summary_btn.click(
creator.generate_summary,
outputs=[output]
)
notes_btn.click(
creator.generate_study_notes,
outputs=[output]
)
quiz_btn.click(
creator.generate_quiz,
outputs=[output]
)
flashcards_btn.click(
creator.generate_flashcards,
outputs=[output]
)
mindmap_btn.click(
creator.generate_mind_map,
outputs=[output]
)
lesson_btn.click(
creator.generate_lesson_plan,
outputs=[output]
)
concepts_btn.click(
creator.generate_concept_explanations,
outputs=[output]
)
problems_btn.click(
creator.generate_practice_problems,
outputs=[output]
)
return app
# Launch the application
if __name__ == "__main__":
app = create_interface()
app.launch(
server_name="0.0.0.0",
server_port=7860,
share=True,
show_error=True
)