ECCA / app.py
shukdevdatta123's picture
Update app.py
beaa443 verified
raw
history blame
36.9 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, Optional
import spaces
import os
import re
# Global variables to store API key and document text
API_KEY = ""
DOCUMENT_TEXT = ""
MODEL = "google/gemma-3-27b-it:free"
def setup_client(api_key: str):
"""Initialize and test API key"""
global API_KEY
try:
if not api_key or api_key.strip() == "":
return "❌ Please enter a valid API key"
# Test the API key by creating a client
client = OpenAI(
base_url="https://openrouter.ai/api/v1",
api_key=api_key.strip(),
)
# Store the API key globally
API_KEY = api_key.strip()
return "βœ… API Key configured successfully!"
except Exception as e:
return f"❌ Error configuring API: {str(e)}"
def create_client() -> Optional[OpenAI]:
"""Create OpenAI client with stored API key"""
if not API_KEY:
return None
return OpenAI(
base_url="https://openrouter.ai/api/v1",
api_key=API_KEY,
)
def extract_text_from_pdf(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_num, page in enumerate(pdf_reader.pages):
try:
page_text = page.extract_text()
if page_text:
text += page_text + "\n"
except Exception as e:
print(f"Error extracting text from page {page_num}: {e}")
continue
return text.strip()
except Exception as e:
return f"Error reading PDF: {str(e)}"
def extract_text_from_docx(file_path: str) -> str:
"""Extract text from DOCX file"""
try:
doc = docx.Document(file_path)
text = ""
for paragraph in doc.paragraphs:
if paragraph.text.strip():
text += paragraph.text + "\n"
# Also extract text from tables
for table in doc.tables:
for row in table.rows:
for cell in row.cells:
if cell.text.strip():
text += cell.text + "\n"
return text.strip()
except Exception as e:
return f"Error reading DOCX: {str(e)}"
def process_document(file):
"""Process uploaded document and extract text"""
global DOCUMENT_TEXT
print(f"Processing file: {file}") # Debug print
if file is None:
DOCUMENT_TEXT = ""
return "❌ No file uploaded", "❌ No document loaded"
try:
file_path = file.name if hasattr(file, 'name') else str(file)
print(f"File path: {file_path}") # Debug print
# Check if file exists
if not os.path.exists(file_path):
DOCUMENT_TEXT = ""
return "❌ File not found", "❌ No document loaded"
# Get file extension
file_extension = file_path.lower().split('.')[-1]
print(f"File extension: {file_extension}") # Debug print
# Extract text based on file type
if file_extension == 'pdf':
extracted_text = extract_text_from_pdf(file_path)
elif file_extension in ['docx', 'doc']:
extracted_text = extract_text_from_docx(file_path)
else:
DOCUMENT_TEXT = ""
return "❌ Unsupported file format. Please upload PDF or DOCX files.", "❌ No document loaded"
print(f"Extracted text length: {len(extracted_text) if extracted_text else 0}") # Debug print
# Check if extraction was successful
if extracted_text.startswith("Error"):
DOCUMENT_TEXT = ""
return extracted_text, "❌ No document loaded"
# Clean and set the global variable
DOCUMENT_TEXT = extracted_text.strip()
if DOCUMENT_TEXT and len(DOCUMENT_TEXT) > 10: # Minimum length check
word_count = len(DOCUMENT_TEXT.split())
char_count = len(DOCUMENT_TEXT)
preview = DOCUMENT_TEXT[:300] + "..." if len(DOCUMENT_TEXT) > 300 else DOCUMENT_TEXT
status_msg = f"βœ… Document loaded ({word_count} words, {char_count} characters)"
process_msg = f"βœ… Document processed successfully!\nπŸ“„ Word count: {word_count}\nπŸ“ Character count: {char_count}\n\nπŸ“– Preview:\n{preview}"
print(f"Document processed successfully. Word count: {word_count}") # Debug print
return process_msg, status_msg
else:
DOCUMENT_TEXT = ""
return "❌ Could not extract meaningful text from the document. The document might be empty, contain only images, or be corrupted.", "❌ No document loaded"
except Exception as e:
DOCUMENT_TEXT = ""
error_msg = f"❌ Error processing document: {str(e)}"
print(f"Error: {error_msg}") # Debug print
return error_msg, "❌ No document loaded"
def clean_html_response(content: str) -> str:
"""Clean HTML response by removing markdown code blocks and fixing formatting"""
if not content:
return content
# Remove ```html and ``` blocks
content = re.sub(r'```html\s*', '', content)
content = re.sub(r'```\s*$', '', content, flags=re.MULTILINE)
content = re.sub(r'```', '', content)
# Remove any remaining markdown code block indicators
content = re.sub(r'^```.*?\n', '', content, flags=re.MULTILINE)
# Clean up extra whitespace
content = re.sub(r'\n\s*\n\s*\n', '\n\n', content)
return content.strip()
def generate_content(prompt: str, max_tokens: int = 2000) -> str:
"""Generate content using the AI model"""
global DOCUMENT_TEXT, API_KEY
print(f"Generate content called. API_KEY exists: {bool(API_KEY)}, DOCUMENT_TEXT length: {len(DOCUMENT_TEXT) if DOCUMENT_TEXT else 0}") # Debug print
if not API_KEY or API_KEY.strip() == "":
return "❌ Please configure your API key first"
if not DOCUMENT_TEXT or len(DOCUMENT_TEXT.strip()) < 10:
return "❌ Please upload and process a document first. Make sure the document contains readable text."
try:
client = create_client()
if not client:
return "❌ Failed to create API client"
print("Sending request to API...") # Debug print
completion = client.chat.completions.create(
extra_headers={
"HTTP-Referer": "https://educational-assistant.app",
"X-Title": "Educational Content Creator",
},
model=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. Format your response using proper HTML tags for better presentation. IMPORTANT: Do not wrap your response in ```html or ``` code blocks. Return clean HTML content only."
},
{
"role": "user",
"content": f"Document Content:\n{DOCUMENT_TEXT[:4000]}\n\n{prompt}" # Limit document content to avoid token limits
}
],
max_tokens=max_tokens,
temperature=0.7
)
result = completion.choices[0].message.content
print(f"API response received. Length: {len(result) if result else 0}") # Debug print
# Clean the HTML response
cleaned_result = clean_html_response(result)
return cleaned_result
except Exception as e:
error_msg = f"❌ Error generating content: {str(e)}"
print(f"API Error: {error_msg}") # Debug print
return error_msg
def create_download_file(content: str, filename: str) -> str:
"""Create downloadable HTML file"""
html_template = f"""
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Educational Content - {filename}</title>
<style>
body {{
font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
line-height: 1.6;
margin: 0;
padding: 20px;
background-color: #f5f5f5;
}}
.container {{
max-width: 1200px;
margin: 0 auto;
background: white;
padding: 30px;
border-radius: 10px;
box-shadow: 0 0 20px rgba(0,0,0,0.1);
}}
h1, h2, h3, h4, h5, h6 {{
color: #2c3e50;
margin-top: 30px;
margin-bottom: 15px;
}}
.flashcard {{
background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
border-radius: 15px;
padding: 20px;
margin: 15px;
box-shadow: 0 8px 25px rgba(0,0,0,0.15);
cursor: pointer;
transition: all 0.3s ease;
color: white;
position: relative;
min-height: 150px;
display: flex;
flex-direction: column;
justify-content: center;
}}
.flashcard:hover {{
transform: translateY(-5px);
box-shadow: 0 12px 35px rgba(0,0,0,0.25);
}}
.flashcard-front, .flashcard-back {{
text-align: center;
}}
.flashcard-back {{
display: none;
}}
.play-btn {{
position: absolute;
top: 10px;
right: 15px;
background: rgba(255,255,255,0.2);
border: none;
border-radius: 50%;
width: 40px;
height: 40px;
font-size: 16px;
color: white;
cursor: pointer;
transition: all 0.3s ease;
}}
.play-btn:hover {{
background: rgba(255,255,255,0.3);
transform: scale(1.1);
}}
.quiz-question {{
background: #f8f9fa;
border-left: 4px solid #007bff;
padding: 15px;
margin: 15px 0;
border-radius: 5px;
}}
.answer-key {{
background: #d4edda;
border: 1px solid #c3e6cb;
padding: 15px;
border-radius: 5px;
margin: 10px 0;
}}
.concept-box {{
background: #fff3cd;
border: 1px solid #ffeaa7;
border-radius: 8px;
padding: 20px;
margin: 15px 0;
}}
.mind-map-branch {{
background: #e3f2fd;
border-left: 4px solid #2196f3;
padding: 15px;
margin: 10px 0;
border-radius: 5px;
}}
.print-btn {{
position: fixed;
top: 20px;
right: 20px;
background: #007bff;
color: white;
border: none;
padding: 10px 20px;
border-radius: 5px;
cursor: pointer;
font-size: 14px;
}}
@media print {{
.print-btn {{ display: none; }}
body {{ background: white; }}
.container {{ box-shadow: none; }}
}}
</style>
</head>
<body>
<button class="print-btn" onclick="window.print()">πŸ–¨οΈ Print</button>
<div class="container">
{content}
</div>
<script>
function toggleCard(cardId) {{
console.log('Toggling card:', cardId);
const front = document.getElementById(cardId + '-front');
const back = document.getElementById(cardId + '-back');
const btn = document.getElementById(cardId + '-btn');
if (front && back && btn) {{
if (front.style.display !== 'none') {{
front.style.display = 'none';
back.style.display = 'block';
btn.innerHTML = 'πŸ”„';
}} else {{
front.style.display = 'block';
back.style.display = 'none';
btn.innerHTML = '▢️';
}}
}} else {{
console.error('Could not find elements for card:', cardId);
}}
}}
// Alternative method - listen for clicks on flashcards
document.addEventListener('DOMContentLoaded', function() {{
const flashcards = document.querySelectorAll('.flashcard');
flashcards.forEach(function(card) {{
card.addEventListener('click', function(e) {{
e.preventDefault();
const cardId = this.getAttribute('data-card-id');
if (cardId) {{
toggleCard(cardId);
}}
}});
}});
// Also listen for button clicks
const playBtns = document.querySelectorAll('.play-btn');
playBtns.forEach(function(btn) {{
btn.addEventListener('click', function(e) {{
e.stopPropagation();
const cardId = this.getAttribute('data-card-id');
if (cardId) {{
toggleCard(cardId);
}}
}});
}});
}});
</script>
</body>
</html>
"""
# Save to temporary file
temp_filename = f"temp_{filename}.html"
with open(temp_filename, 'w', encoding='utf-8') as f:
f.write(html_template)
return temp_filename
# Content generation functions with @spaces.GPU decorator
@spaces.GPU
def generate_summary():
"""Generate comprehensive summary"""
prompt = """Create a comprehensive summary of this document with proper HTML formatting:
Use these HTML tags for structure:
- <h1> for main title
- <h2> for section headers (Executive Summary, Key Points, etc.)
- <h3> for subsections
- <ul> and <li> for bullet points
- <p> for paragraphs
- <strong> for emphasis
- <div class="concept-box"> for important concepts
Structure:
<h1>πŸ“‹ Document Summary</h1>
<h2>🎯 Executive Summary</h2>
<p>Provide a brief overview in 2-3 sentences.</p>
<h2>πŸ”‘ Key Points</h2>
<ul>
<li>List the main concepts, ideas, or arguments presented</li>
</ul>
<h2>πŸ“š Detailed Summary</h2>
<p>Provide a thorough summary organized by topics or sections.</p>
<h2>πŸ’‘ Important Takeaways</h2>
<div class="concept-box">
<p>Highlight the most crucial information students should remember.</p>
</div>
Remember: Return only clean HTML content without code block markers.
"""
return generate_content(prompt)
@spaces.GPU
def generate_study_notes():
"""Generate structured study notes"""
prompt = """Create comprehensive study notes from this document using proper HTML formatting:
Use HTML structure with:
- <h1> for main title: Study Notes
- <h2> for major sections
- <h3> for subsections
- <ul><li> for lists
- <div class="concept-box"> for key concepts
- <strong> for important terms
Structure:
<h1>πŸ“– Study Notes</h1>
<h2>πŸ”‘ Key Concepts</h2>
<div class="concept-box">
Define important terms and concepts with their significance
</div>
<h2>πŸ“Š Main Topics</h2>
Organize content into clear sections with topic headings, key points, and supporting details
<h2>🧠 Memory Aids</h2>
<ul>
<li>Mnemonics for complex information</li>
<li>Visualization techniques</li>
<li>Connection points between concepts</li>
</ul>
<h2>⚑ Quick Review Points</h2>
<ul>
<li>Essential facts and figures for rapid review</li>
</ul>
Remember: Return only clean HTML content without code block markers.
"""
return generate_content(prompt)
@spaces.GPU
def generate_quiz():
"""Generate quiz questions"""
prompt = """Create a comprehensive quiz based on this document using HTML formatting:
<h1>πŸ“ Quiz Questions</h1>
<h2>Multiple Choice Questions</h2>
For each question, use this format:
<div class="quiz-question">
<h3>Question 1:</h3>
<p>[Question text]</p>
<ol type="A">
<li>Option A</li>
<li>Option B</li>
<li>Option C</li>
<li>Option D</li>
</ol>
</div>
<h2>Short Answer Questions</h2>
<div class="quiz-question">
Questions requiring 2-3 sentence answers covering key concepts
</div>
<h2>Essay Questions</h2>
<div class="quiz-question">
Thought-provoking questions requiring detailed responses
</div>
<h2>πŸ“š Answer Key</h2>
<div class="answer-key">
<h3>Multiple Choice Answers:</h3>
<p>Provide all correct answers with explanations</p>
</div>
Create 5 multiple choice, 5 short answer, and 2 essay questions.
Remember: Return only clean HTML content without code block markers.
"""
return generate_content(prompt, max_tokens=3000)
@spaces.GPU
def generate_flashcards():
"""Generate interactive flashcards"""
prompt = """Create 15-20 interactive flashcards based on this document.
Format each flashcard using this exact HTML structure:
<h1>🎴 Interactive Flashcards</h1>
<p><em>Click on each card or the play button (▢️) to reveal the answer!</em></p>
<div class="flashcard" data-card-id="card1">
<button class="play-btn" data-card-id="card1" id="card1-btn">▢️</button>
<div class="flashcard-front" id="card1-front">
<h3>Card 1</h3>
<p><strong>[Question/Term]</strong></p>
</div>
<div class="flashcard-back" id="card1-back">
<h3>Answer</h3>
<p>[Answer/Definition/Explanation]</p>
</div>
</div>
Continue this pattern for each flashcard, ensuring:
- Each card has a unique data-card-id (card1, card2, card3, etc.)
- Button has matching data-card-id attribute
- Front and back divs have correct IDs (card1-front, card1-back, etc.)
- Button has correct ID (card1-btn, card2-btn, etc.)
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. Use proper HTML formatting throughout.
Remember: Return only clean HTML content without code block markers.
"""
return generate_content(prompt, max_tokens=2500)
@spaces.GPU
def generate_mind_map():
"""Generate mind map structure"""
prompt = """Create a detailed mind map structure for this document using HTML:
<h1>🧠 Mind Map Structure</h1>
<div class="concept-box">
<h2>Central Topic:</h2>
<p><strong>[Main subject of the document]</strong></p>
</div>
<h2>Primary Branches:</h2>
For each main topic, create branches using this structure:
<div class="mind-map-branch">
<h3>Branch 1: [Topic Name]</h3>
<ul>
<li><strong>Sub-branch 1.1:</strong> [Subtopic]
<ul>
<li>Detail 1.1.1</li>
<li>Detail 1.1.2</li>
</ul>
</li>
</ul>
</div>
<h2>πŸ”— Connections</h2>
<div class="concept-box">
<ul>
<li>Relationships between different branches</li>
<li>Cross-references and dependencies</li>
<li>Cause-effect relationships</li>
</ul>
</div>
<h2>🎨 Visual Elements Suggestions</h2>
<ul>
<li>Color coding recommendations</li>
<li>Symbol suggestions for different types of information</li>
<li>Emphasis techniques for key concepts</li>
</ul>
Remember: Return only clean HTML content without code block markers.
"""
return generate_content(prompt)
@spaces.GPU
def generate_lesson_plan():
"""Generate lesson plan"""
prompt = """Create a detailed lesson plan based on this document using HTML formatting:
<h1>πŸ“š Lesson Plan</h1>
<h2>🎯 Learning Objectives</h2>
<p>By the end of this lesson, students will be able to:</p>
<ul>
<li>[Specific, measurable objectives]</li>
</ul>
<h2>πŸ“‹ Prerequisites</h2>
<div class="concept-box">
<ul>
<li>Required background knowledge</li>
<li>Recommended prior reading</li>
</ul>
</div>
<h2>⏰ Lesson Structure (60 minutes)</h2>
<h3>Introduction (10 minutes)</h3>
<ul>
<li>Hook/attention grabber</li>
<li>Learning objectives overview</li>
</ul>
<h3>Main Content (35 minutes)</h3>
<ul>
<li>Key concepts presentation</li>
<li>Activities and examples</li>
<li>Discussion points</li>
</ul>
<h3>Practice & Application (10 minutes)</h3>
<ul>
<li>Practice exercises</li>
<li>Real-world applications</li>
</ul>
<h3>Wrap-up & Assessment (5 minutes)</h3>
<ul>
<li>Summary of key points</li>
<li>Quick assessment questions</li>
</ul>
<h2>πŸ“¦ Materials Needed</h2>
<ul>
<li>List of required resources</li>
</ul>
<h2>πŸ“Š Assessment Methods</h2>
<div class="answer-key">
<p>How to evaluate student understanding</p>
</div>
<h2>πŸ“ Homework/Extension Activities</h2>
<ul>
<li>Additional practice opportunities</li>
</ul>
Remember: Return only clean HTML content without code block markers.
"""
return generate_content(prompt, max_tokens=2500)
@spaces.GPU
def generate_concept_explanations():
"""Generate detailed concept explanations"""
prompt = """Provide detailed explanations of key concepts from this document using HTML:
<h1>πŸ” Concept Deep Dive</h1>
For each major concept, use this structure:
<div class="concept-box">
<h2>[Concept Name]</h2>
<p><strong>Definition:</strong> Clear, precise definition</p>
<p><strong>Explanation:</strong> Detailed explanation in simple terms</p>
<p><strong>Examples:</strong> Real-world examples and applications</p>
<p><strong>Analogies:</strong> Helpful comparisons to familiar concepts</p>
<p><strong>Common Misconceptions:</strong> What students often get wrong</p>
<p><strong>Connection to Other Concepts:</strong> How it relates to other topics</p>
<p><strong>Practice Application:</strong> Simple exercise or question</p>
</div>
<hr>
Repeat this structure for all major concepts in the document using proper HTML formatting.
Remember: Return only clean HTML content without code block markers.
"""
return generate_content(prompt, max_tokens=3000)
@spaces.GPU
def generate_practice_problems():
"""Generate practice problems"""
prompt = """Create practice problems based on this document using HTML formatting:
<h1>πŸ’ͺ Practice Problems</h1>
<h2>🟒 Beginner Level</h2>
<div class="quiz-question">
<h3>Problem 1:</h3>
<p>[Problem statement]</p>
<div class="answer-key">
<p><strong>Solution:</strong> Step-by-step solution provided</p>
</div>
</div>
<h2>🟑 Intermediate Level</h2>
<div class="quiz-question">
<h3>Problem 1:</h3>
<p>[Multi-step problem requiring understanding of relationships]</p>
<div class="answer-key">
<p><strong>Solution:</strong> Guided solutions with explanations</p>
</div>
</div>
<h2>πŸ”΄ Advanced Level</h2>
<div class="quiz-question">
<h3>Problem 1:</h3>
<p>[Complex scenarios requiring analysis and synthesis]</p>
<div class="answer-key">
<p><strong>Solution:</strong> Detailed solution strategies</p>
</div>
</div>
<h2>πŸ† Challenge Problems</h2>
<div class="concept-box">
<h3>Challenge 1:</h3>
<p>[Extension beyond document content with creative application]</p>
<div class="answer-key">
<p><strong>Multiple Solution Approaches:</strong> Various ways to solve</p>
</div>
</div>
For each problem, include:
- Clear problem statement with HTML formatting
- Required formulas/concepts in <strong> tags
- Step-by-step solution in answer-key divs
- Common mistakes to avoid
Create 5 beginner, 5 intermediate, 3 advanced, and 2 challenge problems.
Remember: Return only clean HTML content without code block markers.
"""
return generate_content(prompt, max_tokens=3500)
def get_document_status():
"""Get current document status"""
global DOCUMENT_TEXT
if DOCUMENT_TEXT and len(DOCUMENT_TEXT.strip()) > 10:
word_count = len(DOCUMENT_TEXT.split())
char_count = len(DOCUMENT_TEXT)
return f"βœ… Document loaded ({word_count} words, {char_count} characters)"
else:
return "❌ No document loaded"
def get_api_status():
"""Get current API status"""
global API_KEY
if API_KEY and API_KEY.strip():
return "βœ… API Key configured"
else:
return "❌ API Key not configured"
# 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 with interactive features!
**New Features:**
- 🎴 Interactive Flashcards with Play Buttons
- πŸ“„ HTML Formatted Responses
- πŸ’Ύ Download All Content as HTML Files
- πŸ–¨οΈ Print-Ready Formats
*Powered by ZeroGPU for enhanced performance*
""")
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...",
info="Get your API key from https://openrouter.ai/"
)
setup_btn = gr.Button("πŸ”§ Configure API", variant="primary")
setup_status = gr.Textbox(label="API Status", value=get_api_status(), interactive=False)
gr.Markdown("### πŸ“„ Document Upload")
file_upload = gr.File(
label="Upload Document (PDF or DOCX)",
file_types=[".pdf", ".docx", ".doc"],
type="filepath"
)
process_btn = gr.Button("πŸ”„ Process Document", variant="secondary")
process_status = gr.Textbox(label="Processing Status", interactive=False, lines=4)
# Document status indicator
doc_status = gr.Textbox(
label="Document Status",
value=get_document_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("🎴 Interactive 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")
# HTML output with download capability
output = gr.HTML(
label="Generated Content (Interactive)",
value="<p>Generated educational content will appear here with interactive features...</p>"
)
# Download buttons
with gr.Row():
download_file = gr.File(label="πŸ“₯ Download Content", visible=False)
download_btn = gr.Button("πŸ’Ύ Prepare Download", variant="secondary", visible=False)
gr.Markdown("""
### πŸ“‹ How to Use:
1. **Get API Key:** Sign up at [OpenRouter](https://openrouter.ai/) and get your free API key
2. **Configure:** Enter your API key and click "Configure API"
3. **Upload:** Upload a PDF or DOCX document (make sure it contains readable text)
4. **Process:** Click "Process Document" to extract text
5. **Generate:** Choose any educational content type to generate interactive HTML content
6. **Download:** Use the "Prepare Download" button to get an HTML file with all content
### 🎯 Enhanced Content Types:
- **πŸ“‹ Summary:** Comprehensive overview with styled HTML sections
- **πŸ“– Study Notes:** Structured notes with highlighted key concepts
- **πŸ“ Quiz:** Interactive quiz with styled questions and answer keys
- **🎴 Interactive Flashcards:** Click-to-flip cards with play buttons!
- **🧠 Mind Map:** Visual structure with styled branches
- **πŸ“š Lesson Plan:** Complete teaching plan with time management
- **πŸ” Concept Explanations:** Deep dive with styled concept boxes
- **πŸ’ͺ Practice Problems:** Graded exercises with solution reveals
### ✨ New Interactive Features:
- **🎴 Flashcards:** Click the play button (▢️) to flip cards and see answers
- **πŸ“„ HTML Formatting:** All content now uses proper HTML styling
- **πŸ’Ύ Download:** Get complete HTML files with embedded CSS and JavaScript
- **πŸ–¨οΈ Print Ready:** Downloaded files include print-optimized styling
### πŸ’‘ Tips:
- Make sure your PDF contains selectable text (not just images)
- For best results, use documents with clear structure and headings
- The app works with academic papers, textbooks, reports, and study materials
- Interactive flashcards work best when viewed in the HTML output
- Downloaded files can be opened in any web browser for offline use
### ⚑ Performance Note:
This app uses ZeroGPU for enhanced processing. Functions will automatically utilize GPU resources when needed.
""")
# Store the last generated content for download
last_content = gr.State("")
last_content_type = gr.State("")
# Event handlers
def setup_api_and_update_status(api_key):
result = setup_client(api_key)
status = get_api_status()
return result, status
setup_btn.click(
setup_api_and_update_status,
inputs=[api_key],
outputs=[setup_status, setup_status]
)
def process_and_update_all_status(file):
process_result, doc_status_result = process_document(file)
return process_result, doc_status_result
process_btn.click(
process_and_update_all_status,
inputs=[file_upload],
outputs=[process_status, doc_status]
)
# Enhanced content generation functions that return HTML and enable download
def generate_and_display_summary():
content = generate_summary()
return content, content, "summary", gr.update(visible=True)
def generate_and_display_notes():
content = generate_study_notes()
return content, content, "study_notes", gr.update(visible=True)
def generate_and_display_quiz():
content = generate_quiz()
return content, content, "quiz", gr.update(visible=True)
def generate_and_display_flashcards():
content = generate_flashcards()
return content, content, "flashcards", gr.update(visible=True)
def generate_and_display_mindmap():
content = generate_mind_map()
return content, content, "mind_map", gr.update(visible=True)
def generate_and_display_lesson():
content = generate_lesson_plan()
return content, content, "lesson_plan", gr.update(visible=True)
def generate_and_display_concepts():
content = generate_concept_explanations()
return content, content, "concept_explanations", gr.update(visible=True)
def generate_and_display_problems():
content = generate_practice_problems()
return content, content, "practice_problems", gr.update(visible=True)
# Download preparation function
def prepare_download(content, content_type):
if not content or content.startswith("❌"):
return None
# Create downloadable file
filename = f"educational_content_{content_type}"
temp_file = create_download_file(content, filename)
return temp_file
# Content generation button handlers with download capability
summary_btn.click(
generate_and_display_summary,
outputs=[output, last_content, last_content_type, download_btn]
)
notes_btn.click(
generate_and_display_notes,
outputs=[output, last_content, last_content_type, download_btn]
)
quiz_btn.click(
generate_and_display_quiz,
outputs=[output, last_content, last_content_type, download_btn]
)
flashcards_btn.click(
generate_and_display_flashcards,
outputs=[output, last_content, last_content_type, download_btn]
)
mindmap_btn.click(
generate_and_display_mindmap,
outputs=[output, last_content, last_content_type, download_btn]
)
lesson_btn.click(
generate_and_display_lesson,
outputs=[output, last_content, last_content_type, download_btn]
)
concepts_btn.click(
generate_and_display_concepts,
outputs=[output, last_content, last_content_type, download_btn]
)
problems_btn.click(
generate_and_display_problems,
outputs=[output, last_content, last_content_type, download_btn]
)
# Download button handler
def handle_download(content, content_type):
if content and not content.startswith("❌"):
temp_file = prepare_download(content, content_type)
return temp_file, gr.update(visible=True)
return None, gr.update(visible=False)
download_btn.click(
handle_download,
inputs=[last_content, last_content_type],
outputs=[download_file, download_file]
)
# Update status on app load
def update_initial_status():
return get_api_status(), get_document_status()
app.load(
update_initial_status,
outputs=[setup_status, doc_status]
)
return app
# Launch the application
if __name__ == "__main__":
app = create_interface()
app.launch(
debug=True,
share=False
)