import gradio as gr import os import requests import re # Get Hugging Face token from environment variable HF_TOKEN = os.getenv("HUGGINGFACE_TOKEN") def call_hugging_face_api_content(prompt): """Call Hugging Face API for content generation""" if not HF_TOKEN: return None try: url = "https://api-inference.huggingface.co/models/microsoft/DialoGPT-medium" headers = {"Authorization": f"Bearer {HF_TOKEN}"} data = { "inputs": prompt, "parameters": { "max_length": 1000, "temperature": 0.7, "do_sample": True } } response = requests.post(url, headers=headers, json=data, timeout=30) if response.status_code == 200: result = response.json() if isinstance(result, list) and len(result) > 0: return result[0].get("generated_text", "") return None except Exception as e: print(f"API call error: {e}") return None def generate_worksheet_content(topic, subject, grade_level, difficulty, content_type, content_length): """Generate educational worksheet content""" # Try Hugging Face API first if token is available if HF_TOKEN: try: prompt = f"""Create a comprehensive educational {content_type.lower()} about "{topic}" for {grade_level} students studying {subject}. Requirements: - Grade Level: {grade_level} - Subject: {subject} - Topic: {topic} - Difficulty: {difficulty} - Content Type: {content_type} - Length: {content_length} IMPORTANT: DO NOT USE LaTeX expressions. Use simple HTML/markdown formatting instead: - For fractions: use "a/b" or "a over b" instead of \frac{{a}}{{b}} - For math: use plain text like "Speed = Distance/Time" instead of \text{{Speed}} = \frac{{\text{{Distance}}}}{{\text{{Time}}}} - For fill-in-blanks: use "_____" instead of \_\_\_ - For answer boxes: use "[ANSWER: ___]" instead of \boxed{{\_\_}} - For subscripts: use "H2O" instead of H_2O - For superscripts: use "x²" instead of x^2 Format the response as a structured worksheet with clear sections, examples, and exercises.""" result = call_hugging_face_api_content(prompt) if result: return result except Exception as e: print(f"API error: {e}") # Fallback content with LaTeX-free formatting fallback_content = f"""# **{topic} in {subject}: Interactive Worksheet** **Grade Level:** {grade_level} | **Subject:** {subject} | **Difficulty:** {difficulty} --- ## **Introduction** {topic} helps students understand important concepts in {subject}! In this worksheet, you'll explore {topic} through hands-on activities and real-world examples. --- ## **Learning Objectives** By the end of this worksheet, you will be able to: ☑ Understand the basic concepts of {topic} ☑ Apply {topic} to solve problems ☑ Use {topic} in real-world situations ☑ Check your work using self-assessment --- ## **Practice Problems** ### **1. Basic Concepts** Solve the following problems step by step. **Example:** If we have the equation: A = B × C Find A when B = 5 and C = 3 [ANSWER: A = 15] **Now you try:** a) If D = E + F, find D when E = 10 and F = 7 [ANSWER: _____] b) If G = H / I, find G when H = 20 and I = 4 [ANSWER: _____] --- ## **Word Problems** ### **2. Real-World Applications** Read each problem carefully and solve. **Problem 1:** A student travels 120 miles in 2 hours. What is their speed? Equation: Speed = Distance / Time Solution: Speed = _____ / _____ = _____ miles per hour [ANSWER: 60 mph] **Problem 2:** A container holds 50 liters of water. If 30 liters are used, how much remains? Equation: Remaining = Total - Used Solution: Remaining = _____ - _____ = _____ liters [ANSWER: 20 liters] --- ## **Self-Assessment** Rate your understanding: ☐ I need more practice ☐ I understand most problems ☐ I can teach this to someone else! **Reflection:** What was the most challenging part? [ANSWER: ________________________________] --- ## **Answer Key** **Practice Problems:** a) D = 17 b) G = 5 **Word Problems:** 1. Speed = 60 mph 2. Remaining = 20 liters --- ### **Worksheet Summary** Great job! You've practiced {topic} concepts and applied them to real-world problems. Keep practicing to master these skills! --- **Total Words:** ~800 | **Format:** Interactive Worksheet **Ready for Print/Digital Use!** ✅""" return fallback_content def apply_simple_styling(content): """Apply simple styling to make content look better""" # Style answer boxes content = re.sub(r'\[ANSWER: ([^\]]+)\]', r'[ANSWER: \1]', content) # Style fill-in-blank spaces content = re.sub(r'___+', r'     ', content) # Style checkboxes content = re.sub(r'☐', r'', content) content = re.sub(r'☑', r'', content) return content def generate_worksheet(topic, subject, grade_level, difficulty, content_type, content_length): """Main function to generate and style worksheet content""" content = generate_worksheet_content(topic, subject, grade_level, difficulty, content_type, content_length) styled_content = apply_simple_styling(content) return styled_content # Create the Gradio interface with gr.Blocks( title="BrightMind AI - Educational Worksheet Generator", theme=gr.themes.Soft(), css=""" .gradio-container { font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif; background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); min-height: 100vh; } .main-container { background: white; border-radius: 12px; padding: 20px; margin: 20px; box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1); } .worksheet-output { background: #f8f9fa; border-radius: 8px; padding: 20px; margin-top: 20px; border-left: 4px solid #3498db; } """ ) as demo: gr.Markdown(""" # 🧠 BrightMind AI ## Professional Educational Content Generator for Teachers Generate interactive worksheets tailored to your specific needs. Simply fill in the details below and click "Generate Worksheet" to create engaging educational materials. """) with gr.Row(): with gr.Column(scale=1): gr.Markdown("### 📝 Worksheet Settings") topic = gr.Textbox( label="📝 Topic", placeholder="e.g., algebra, photosynthesis, world war II", value="algebra" ) subject = gr.Dropdown( label="📚 Subject", choices=["Science", "Mathematics", "History", "English", "Geography", "Art", "Music", "Physical Education"], value="Science" ) grade_level = gr.Dropdown( label="🎓 Grade Level", choices=["K-2", "3-5", "6-8", "9-12"], value="6-8" ) difficulty = gr.Dropdown( label="🎯 Difficulty", choices=["Beginner", "Intermediate", "Advanced"], value="Intermediate" ) content_type = gr.Dropdown( label="📄 Content Type", choices=["Worksheets", "Handouts", "Study Guides", "Activities", "Presentations", "Lesson Materials"], value="Worksheets" ) content_length = gr.Dropdown( label="📏 Length", choices=["Short (1-2 pages)", "Medium (3-5 pages)", "Long (6+ pages)"], value="Medium (3-5 pages)" ) generate_btn = gr.Button( "🚀 Generate Worksheet", variant="primary", size="lg" ) clear_btn = gr.Button( "🗑️ Clear", variant="secondary" ) with gr.Column(scale=2): gr.Markdown("### 📄 Generated Worksheet") worksheet_output = gr.HTML( value="
Your educational worksheet will appear here...
", label="" ) # Event handlers generate_btn.click( fn=generate_worksheet, inputs=[topic, subject, grade_level, difficulty, content_type, content_length], outputs=worksheet_output ) clear_btn.click( fn=lambda: "
Your educational worksheet will appear here...
", outputs=worksheet_output ) if __name__ == "__main__": demo.launch()