# ============================================================================ # ๐Ÿ“ฆ INCLUSIVEEDU - FULL VERSION WITH GRADIO + INTEGRATED API # Compatible with Hugging Face Spaces + External API Access # ============================================================================ import os import re import time import random from datetime import datetime from typing import List, Optional, Dict, Any from dataclasses import dataclass from pydantic import BaseModel # FastAPI imports try: from fastapi import FastAPI, HTTPException from fastapi.middleware.cors import CORSMiddleware FASTAPI_AVAILABLE = True except ImportError: print("โš ๏ธ FastAPI not available - API mode disabled") FASTAPI_AVAILABLE = False # Gradio imports try: import gradio as gr GRADIO_AVAILABLE = True except ImportError: print("โš ๏ธ Gradio not available - Interface mode disabled") GRADIO_AVAILABLE = False # PyTorch imports (optional) try: import torch TORCH_AVAILABLE = True except ImportError: print("โš ๏ธ PyTorch not available - using CPU simulation") TORCH_AVAILABLE = False # ============================================================================ # 1. DATA MODELS # ============================================================================ @dataclass class ProfileInfo: """Profile information structure""" name: str description: str characteristics: List[str] best_for: List[str] # Pydantic models for API if FASTAPI_AVAILABLE: class ContentRequest(BaseModel): content: str profile: str = "visual_structure" interests: List[str] = [] complexity: str = "intermediate" format: str = "html" class ContentResponse(BaseModel): adapted_content: str gamification: Dict[str, Any] processing_time: float profile_used: str interests: List[str] complexity: str success: bool format: str timestamp: str raw_html: Optional[str] = None class HealthResponse(BaseModel): status: str ai_mode: str profiles_available: int timestamp: str version: str # ============================================================================ # 2. AI CONFIGURATION # ============================================================================ class AIConfig: """AI configuration and model management""" def __init__(self, safe_mode=True): self.simulation_mode = True # Always use simulation for safety self.safe_mode = safe_mode self.gemma3_model = None self.gemma3_tokenizer = None print("๐ŸŽญ AI Config initialized in simulation mode") def generate_with_gemma3(self, prompt, max_length=400): """Generate content using simulation""" # Simulate AI processing time time.sleep(random.uniform(0.1, 0.3)) # Generate realistic adaptive content based on prompt if "visual structure" in prompt.lower(): return self._generate_visual_content(prompt) elif "hyperfocus" in prompt.lower() or "technical" in prompt.lower(): return self._generate_technical_content(prompt) elif "sensory" in prompt.lower() or "calm" in prompt.lower(): return self._generate_sensory_content(prompt) elif "interests" in prompt.lower() or "gamif" in prompt.lower(): return self._generate_interest_content(prompt) else: return self._generate_default_content(prompt) def _generate_visual_content(self, prompt): return """ ## ๐Ÿ“š Structured Learning Overview **Key Concepts** organized for clarity: ### ๐ŸŽฏ Main Topic Clear presentation of core information with visual hierarchy and organized structure. ### ๐Ÿ“Š Important Details - **Primary points** highlighted for easy scanning - **Secondary information** properly categorized - **Visual elements** integrated for better comprehension ### โœ… Summary Points Essential takeaways presented in an accessible, scannable format with consistent organization. """ def _generate_technical_content(self, prompt): return """ ## ๐Ÿ”ฌ Technical Deep Dive **Comprehensive Analysis** with detailed specifications: ### ๐Ÿ”ง Technical Specifications Advanced implementation details with precise terminology and comprehensive coverage of all relevant aspects. ### ๐Ÿ“ˆ Performance Metrics - **Efficiency ratings**: 94.7% optimization achieved - **Processing speed**: 2.3ms average response time - **Accuracy measures**: 99.2% precision in target scenarios - **Resource utilization**: Optimal memory allocation patterns ### ๐ŸŽ›๏ธ Advanced Configuration Detailed parameter settings and fine-tuning options for specialized use cases and expert-level customization. """ def _generate_sensory_content(self, prompt): return """ ## ๐ŸŒธ Gentle Learning Space **Comfortable Environment** designed for ease: ### ๐Ÿ•Š๏ธ Peaceful Introduction A calm and welcoming approach to the topic, presented at a comfortable pace. ### ๐Ÿ’ซ Gentle Progression Learning unfolds naturally: โ€ข Soft transitions between concepts โ€ข Comfortable information density โ€ข Regular pause points for reflection ### ๐ŸŒฑ Supportive Summary Key insights presented gently, with encouragement and positive reinforcement for continued learning. """ def _generate_interest_content(self, prompt): return """ ## ๐ŸŽฎ Interactive Learning Adventure **Engaging Experience** tailored to your interests: ### ๐Ÿ† Achievement Unlocked You've started an exciting learning journey! Connect this topic to your favorite interests for maximum engagement. ### ๐ŸŽฏ Challenge Mode - **Discovery Quest**: Explore core concepts - **Knowledge Builder**: Stack new information - **Mastery Challenge**: Apply what you've learned - **Bonus Round**: Find real-world connections ### โญ Power-Up Summary Level up your understanding with these key insights, designed to fuel your curiosity and passion for learning! """ def _generate_default_content(self, prompt): return """ ## ๐Ÿ“– Adaptive Learning Content **Personalized Approach** for your learning style: ### ๐ŸŽ“ Core Concepts Essential information presented clearly and effectively for optimal understanding. ### ๐Ÿ” Key Details Important points highlighted with appropriate depth and clarity for your learning needs. ### ๐Ÿ“ Learning Summary Comprehensive overview designed to reinforce understanding and support continued learning progress. """ # ============================================================================ # 3. PROFILE SYSTEM # ============================================================================ class NeuroProfileSystem: """Neurodiverse learning profile system""" def __init__(self): self.profiles = { "visual_structure": { "name": "๐ŸŽฏ Visual Structure", "description": "Clear organization, visual hierarchy, and structured elements", "colors": ["#2E86AB", "#A23B72", "#F18F01", "#C73E1D"], "characteristics": [ "Clear hierarchical organization with consistent structure", "Strategic use of visual elements and color coding", "Predictable navigation patterns and layout design", "Visual learning aids and interactive elements" ], "best_for": [ "Visual learners who need structure", "People who benefit from clear organization", "Those who prefer predictable layouts" ] }, "hyperfocus_directed": { "name": "๐Ÿ”ฌ Directed Hyperfocus", "description": "Deep technical focus, detailed information, and comprehensive analysis", "colors": ["#1B4332", "#2D6A4F", "#40916C", "#52B788"], "characteristics": [ "Detailed technical content with comprehensive data", "In-depth analysis and specialized terminology", "Extended exploration opportunities and resources", "Advanced tools and expert-level information" ], "best_for": [ "Deep technical learning", "Specialized interest areas", "Comprehensive analysis needs" ] }, "sensory_adaptation": { "name": "๐ŸŒธ Sensory Adaptation", "description": "Calm environment, sensory awareness, and accessible design", "colors": ["#F7F3E9", "#E8DDBF", "#D4C5A9", "#C4A77D"], "characteristics": [ "Gentle presentation with calming visual design", "Reduced sensory load and minimal distractions", "Comfortable pacing with built-in break suggestions", "Accessibility features and customization options" ], "best_for": [ "Sensory-sensitive learners", "Those needing calm environments", "People requiring accessibility features" ] }, "special_interests": { "name": "๐ŸŽฎ Special Interests", "description": "Interest-based connections, gamification, and motivational design", "colors": ["#FF6B6B", "#4ECDC4", "#45B7D1", "#96CEB4"], "characteristics": [ "Gamification elements with achievement systems", "Personal interest integration and connections", "Motivational design with clear goal progression", "Community features and collaborative opportunities" ], "best_for": [ "Interest-driven learning", "Motivation through gamification", "Achievement-focused students" ] } } def get_profile(self, profile_key): return self.profiles.get(profile_key, self.profiles["visual_structure"]) def get_profile_names(self): return [(profile["name"], key) for key, profile in self.profiles.items()] def get_all_profiles_info(self): """Get detailed info for all profiles""" profiles_info = {} for key, profile in self.profiles.items(): profiles_info[key] = ProfileInfo( name=profile["name"], description=profile["description"], characteristics=profile["characteristics"], best_for=profile.get("best_for", []) ) return profiles_info # ============================================================================ # 4. CONTENT ADAPTATION PIPELINE # ============================================================================ class ContentAdaptationPipeline: """Main content adaptation pipeline""" def __init__(self, ai_config): self.ai_config = ai_config self.profile_system = NeuroProfileSystem() self.adaptation_count = 0 self.session_start = datetime.now() def adapt_content(self, content, profile_key, interests, complexity="intermediate"): """Main content adaptation function""" start_time = time.time() try: # Validate inputs if not content or not content.strip(): raise ValueError("Content cannot be empty") # Get profile information profile = self.profile_system.get_profile(profile_key) # Create adaptation prompt prompt = self._create_adaptation_prompt(content, profile_key, interests, complexity) # Generate adapted content adapted_text = self.ai_config.generate_with_gemma3(prompt, max_length=400) # Create enhanced HTML output html_content = self._create_enhanced_html(adapted_text, profile, interests, complexity) # Generate gamification elements gamification = self._create_gamification_system(interests, profile_key) # Calculate metrics processing_time = time.time() - start_time self.adaptation_count += 1 return { "adapted_content": html_content, "gamification": gamification, "processing_time": processing_time, "profile_used": profile_key, "interests": interests, "complexity": complexity, "gemma3_used": not self.ai_config.simulation_mode, "adaptation_count": self.adaptation_count, "success": True, "timestamp": datetime.now().isoformat() } except Exception as e: print(f"โŒ Adaptation error: {e}") return self._create_fallback_result(content, profile_key, str(e)) def _create_adaptation_prompt(self, content, profile_key, interests, complexity): """Create targeted adaptation prompt based on profile""" interest_text = ", ".join(interests) if interests else "general learning" prompts = { "visual_structure": f""" Adapt this educational content for VISUAL STRUCTURE learning: - Use clear headings and organization - Add visual elements and structured layout - Create scannable, hierarchical content - Include visual learning aids Content: {content} Interests: {interest_text} Complexity: {complexity} Visual structure adaptation: """, "hyperfocus_directed": f""" Adapt this educational content for DIRECTED HYPERFOCUS: - Add technical details and specifications - Include comprehensive analysis - Provide in-depth information - Use specialized terminology appropriately Content: {content} Interests: {interest_text} Complexity: {complexity} Technical deep-dive adaptation: """, "sensory_adaptation": f""" Adapt this educational content for SENSORY ADAPTATION: - Use gentle, calming language - Break into manageable sections - Reduce cognitive load - Create comfortable learning environment Content: {content} Interests: {interest_text} Complexity: {complexity} Sensory-friendly adaptation: """, "special_interests": f""" Adapt this educational content for SPECIAL INTERESTS: - Connect to personal interests: {interest_text} - Add gamification elements - Create motivational connections - Include achievement opportunities Content: {content} Interests: {interest_text} Complexity: {complexity} Interest-based gamified adaptation: """ } return prompts.get(profile_key, f"Adapt this content for {profile_key}: {content}") def _create_enhanced_html(self, content, profile, interests, complexity): """Create enhanced HTML with full styling and interactivity""" colors = profile["colors"] profile_name = profile["name"] # Complexity indicators complexity_colors = { "beginner": "#28a745", "intermediate": "#ffc107", "advanced": "#dc3545" } complexity_color = complexity_colors.get(complexity, "#6c757d") html = f"""
{profile_name}

Adaptive Learning Content

{profile['description']}

{self._format_content_advanced(content)}

๐Ÿ“Š Complexity Level

{complexity}

๐ŸŽฏ Interest Areas

{', '.join(interests) if interests else 'General Learning'}

โœจ Adaptation Features

{self._create_feature_cards_advanced(profile['characteristics'], colors)}
๐Ÿš€ Adapted with {'AI Model' if not self.ai_config.simulation_mode else 'Enhanced Simulation'} | ๐ŸŽฏ Profile: {profile_key.replace('_', ' ').title()} | โšก Processing: Optimized for accessibility and engagement | ๐Ÿ“… {datetime.now().strftime('%Y-%m-%d %H:%M')}
""" return html def _format_content_advanced(self, content): """Advanced content formatting with enhanced HTML""" # Convert markdown-style content to rich HTML content = re.sub(r'^## (.*)', r'

\1

', content, flags=re.MULTILINE) content = re.sub(r'^### (.*)', r'

\1

', content, flags=re.MULTILINE) # Enhanced list formatting content = re.sub(r'^\โ€ข (.*)', r'
  • \1
  • ', content, flags=re.MULTILINE) content = re.sub(r'^\* (.*)', r'
  • \1
  • ', content, flags=re.MULTILINE) # Bold and italic formatting content = re.sub(r'\*\*(.*?)\*\*', r'\1', content) content = re.sub(r'\*(.*?)\*', r'\1', content) # Wrap consecutive list items content = re.sub(r'(]*>.*?)', r'', content, flags=re.DOTALL) content = content.replace('\n