Spaces:
Running
Running
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 | |
# 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" | |
client = OpenAI( | |
base_url="https://openrouter.ai/api/v1", | |
api_key=api_key.strip(), | |
) | |
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" | |
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 | |
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) | |
if not os.path.exists(file_path): | |
DOCUMENT_TEXT = "" | |
return "β File not found", "β No document loaded" | |
file_extension = file_path.lower().split('.')[-1] | |
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" | |
if extracted_text.startswith("Error"): | |
DOCUMENT_TEXT = "" | |
return extracted_text, "β No document loaded" | |
DOCUMENT_TEXT = extracted_text.strip() | |
if DOCUMENT_TEXT and len(DOCUMENT_TEXT) > 10: | |
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}" | |
return process_msg, status_msg | |
else: | |
DOCUMENT_TEXT = "" | |
return "β Could not extract meaningful text from the document.", "β No document loaded" | |
except Exception as e: | |
DOCUMENT_TEXT = "" | |
return f"β Error processing document: {str(e)}", "β No document loaded" | |
def generate_content(prompt: str, max_tokens: int = 2000) -> str: | |
"""Generate content using the AI model""" | |
global DOCUMENT_TEXT, API_KEY | |
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." | |
try: | |
client = create_client() | |
if not client: | |
return "β Failed to create API client" | |
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 engaging educational materials based on the provided document content. Format your response using proper HTML tags, but do not include <html>, <head>, <body>, or code block markers. Start directly with the content using tags like <h1>, <h2>, <p>, etc." | |
}, | |
{ | |
"role": "user", | |
"content": f"Document Content:\n{DOCUMENT_TEXT[:4000]}\n\n{prompt}" | |
} | |
], | |
max_tokens=max_tokens, | |
temperature=0.7 | |
) | |
result = completion.choices[0].message.content | |
result = result.replace("```html", "").replace("```", "").strip() | |
return result | |
except Exception as e: | |
return f"β Error generating content: {str(e)}" | |
def create_download_file(content: str, filename: str) -> str: | |
"""Create downloadable HTML file with full structure and interactivity""" | |
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-slider {{ | |
width: 100%; | |
max-width: 400px; | |
margin: 20px auto; | |
overflow: hidden; | |
position: relative; | |
cursor: pointer; | |
}} | |
.slides {{ | |
display: flex; | |
width: 200%; | |
transition: transform 0.3s ease; | |
}} | |
.slide {{ | |
width: 50%; | |
box-sizing: border-box; | |
padding: 30px; | |
background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); | |
color: white; | |
border-radius: 15px; | |
min-height: 200px; | |
display: flex; | |
flex-direction: column; | |
justify-content: center; | |
text-align: center; | |
}} | |
.showing-answer .slides {{ | |
transform: translateX(-50%); | |
}} | |
.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 toggleFlashcard(id) {{ | |
const flashcard = document.getElementById(id); | |
if (flashcard) {{ | |
flashcard.classList.toggle('showing-answer'); | |
}} | |
}} | |
</script> | |
</body> | |
</html> | |
""" | |
temp_filename = f"temp_{filename}.html" | |
with open(temp_filename, 'w', encoding='utf-8') as f: | |
f.write(html_template) | |
return temp_filename | |
def generate_summary(): | |
"""Generate comprehensive summary""" | |
prompt = """Create a comprehensive summary of this document with proper HTML formatting. Do not include <html>, <head>, <body>, or code block markers. Start directly with the content using tags like <h1>, <h2>, <p>, etc. | |
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> | |
""" | |
return generate_content(prompt) | |
def generate_study_notes(): | |
"""Generate structured study notes""" | |
prompt = """Create comprehensive study notes from this document using proper HTML formatting. Do not include <html>, <head>, <body>, or code block markers. Start directly with the content. | |
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> | |
""" | |
return generate_content(prompt) | |
def generate_quiz(): | |
"""Generate quiz questions""" | |
prompt = """Create a comprehensive quiz based on this document using HTML formatting. Do not include <html>, <head>, <body>, or code block markers. Start directly with the content. | |
<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. | |
""" | |
return generate_content(prompt, max_tokens=3000) | |
def generate_flashcards(): | |
"""Generate interactive flashcards with slider functionality""" | |
prompt = """Create 15-20 interactive flashcards based on this document. Do not include <html>, <head>, <body>, or code block markers. Start directly with the content. | |
Format each flashcard using this exact HTML structure: | |
<h1>π΄ Interactive Flashcards</h1> | |
<p><em>Click on a card to slide between question and answer!</em></p> | |
<div class="flashcard-slider" id="card1" onclick="toggleFlashcard('card1')"> | |
<div class="slides"> | |
<div class="slide question"> | |
<h3>Card 1</h3> | |
<p><strong>[Question/Term]</strong></p> | |
</div> | |
<div class="slide answer"> | |
<h3>Answer</h3> | |
<p>[Answer/Definition/Explanation]</p> | |
</div> | |
</div> | |
</div> | |
Continue this pattern for each flashcard, incrementing the card numbers (card2, card3, 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. | |
""" | |
return generate_content(prompt, max_tokens=2500) | |
def generate_mind_map(): | |
"""Generate mind map structure""" | |
prompt = """Create a detailed mind map structure for this document using HTML. Do not include <html>, <head>, <body>, or code block markers. Start directly with the content. | |
<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> | |
""" | |
return generate_content(prompt) | |
def generate_lesson_plan(): | |
"""Generate lesson plan""" | |
prompt = """Create a detailed lesson plan based on this document using HTML formatting. Do not include <html>, <head>, <body>, or code block markers. Start directly with the content. | |
<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> | |
""" | |
return generate_content(prompt, max_tokens=2500) | |
def generate_concept_explanations(): | |
"""Generate detailed concept explanations""" | |
prompt = """Provide detailed explanations of key concepts from this document using HTML. Do not include <html>, <head>, <body>, or code block markers. Start directly with the content. | |
<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. | |
""" | |
return generate_content(prompt, max_tokens=3000) | |
def generate_practice_problems(): | |
"""Generate practice problems""" | |
prompt = """Create practice problems based on this document using HTML formatting. Do not include <html>, <head>, <body>, or code block markers. Start directly with the content. | |
<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. | |
""" | |
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" | |
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! | |
**New Feature:** | |
- π΄ Interactive Flashcards now work like an image sliderβclick to slide between question and answer! | |
*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) | |
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") | |
output = gr.HTML( | |
label="Generated Content", | |
value="<p>Generated content will appear here...</p>" | |
) | |
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/) | |
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 a content type to generate | |
6. **Download:** Download the HTML file to see interactive flashcards | |
### π‘ Tips: | |
- Flashcards slide between question and answer when clicked (in the downloaded file). | |
- Use the downloaded HTML file in a browser for full interactivity. | |
""") | |
last_content = gr.State("") | |
last_content_type = gr.State("") | |
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] | |
) | |
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) | |
def prepare_download(content, content_type): | |
if not content or content.startswith("β"): | |
return None | |
temp_file = create_download_file(content, content_type) | |
return temp_file | |
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] | |
) | |
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] | |
) | |
def update_initial_status(): | |
return get_api_status(), get_document_status() | |
app.load( | |
update_initial_status, | |
outputs=[setup_status, doc_status] | |
) | |
return app | |
if __name__ == "__main__": | |
app = create_interface() | |
app.launch( | |
debug=True, | |
share=False | |
) |