diff --git "a/app.py" "b/app.py" --- "a/app.py" +++ "b/app.py" @@ -4,1557 +4,203 @@ # ============================================================================ import os -import gc -import time -import warnings -import logging import re +import time import random -from datetime import datetime, timedelta -from typing import Dict, List, Tuple, Optional -import threading -import asyncio - -# Suppress warnings for cleaner output -warnings.filterwarnings('ignore') - -# Data processing and utilities -import json -import numpy as np -import pandas as pd - -# Web interface and API -import gradio as gr -from fastapi import FastAPI, HTTPException, BackgroundTasks +from datetime import datetime +from typing import List, Optional, Dict, Any +from dataclasses import dataclass from pydantic import BaseModel -import uvicorn -from threading import Thread - -# Machine Learning and AI -import torch -print("๐Ÿง  InclusiveEdu - Neurodiverse Education Platform") -print("โœ… Gradio + FastAPI integrated version") -print("๐ŸŽฏ Compatible with Hugging Face Spaces + External API") -print("=" * 70) +# 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. API MODELS AND SCHEMAS +# 1. DATA MODELS # ============================================================================ -class ContentRequest(BaseModel): - """Request model for content adaptation API""" - content: str - profile: str = "visual_structure" - interests: List[str] = [] - complexity: str = "intermediate" - format: str = "html" # "html" or "text" - -class ContentResponse(BaseModel): - """Response model for adapted content""" - adapted_content: str - gamification: dict - 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): - """Health check response model""" - status: str - ai_mode: str - profiles_available: int - timestamp: str - version: str - -class ProfileInfo(BaseModel): - """Profile information model""" +@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. SAFE AI CONFIGURATION FOR SPACES +# 2. AI CONFIGURATION # ============================================================================ class AIConfig: - """AI Configuration with Spaces-safe loading""" - - _instance = None - _model_loaded = False # Fixed: removed asterisks and added underscore + """AI configuration and model management""" - def __new__(cls, *args, **kwargs): # Fixed: proper dunder method - if cls._instance is None: - cls._instance = super().__new__(cls) - return cls._instance - - def __init__(self, safe_mode=True): # Fixed: proper dunder method - if hasattr(self, '_initialized'): - print("โš ๏ธ AIConfig already initialized - reusing") - return - - print("๐Ÿ”ง Initializing AIConfig (Spaces Safe Mode)...") - - # Initial states - self.simulation_mode = True + 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 - self.hf_token = os.environ.get("HF_TOKEN") - self.model_loading = False - - # Create intelligent simulation patterns - self._create_simulation_patterns() - - # Try to load model if possible (safe mode) - if safe_mode: - self._safe_model_loading() - - self._initialized = True - - def _create_simulation_patterns(self): # Fixed: proper method definition - """Create intelligent simulation patterns for each profile""" - self.simulation_patterns = { - "visual_structure": """ -## ๐Ÿ“Š VISUAL STRUCTURE ADAPTATION -๐ŸŽฏ **ORGANIZED FOR VISUAL LEARNING:** -### ๐Ÿ“‹ Clear Information Hierarchy -โ€ข **Main Concepts:** Structured with clear headings and subheadings -โ€ข **Visual Elements:** Strategic use of icons, colors, and layout -โ€ข **Organization:** Logical flow with numbered sections -โ€ข **Navigation:** Consistent and predictable structure -### ๐ŸŽจ Visual Design Features -โ€ข **Layout:** Clean, organized, and scannable format -โ€ข **Typography:** Clear fonts with appropriate sizing -โ€ข **Spacing:** Adequate white space for readability -โ€ข **Colors:** Consistent color coding for different content types -### ๐Ÿ“Š Interactive Elements -โ€ข **Progress Indicators:** Visual progress tracking -โ€ข **Quick Navigation:** Jump-to-section functionality -โ€ข **Visual Summaries:** Key points highlighted visually -โ€ข **Structured Assessments:** Organized quiz and review sections -โœจ **Result:** Content optimized for visual processing and structured learning - """, - - "hyperfocus_directed": """ -## ๐Ÿ”ฌ TECHNICAL DEEP-DIVE ADAPTATION -๐ŸŽฏ **OPTIMIZED FOR DIRECTED HYPERFOCUS:** -### ๐Ÿ“Š Comprehensive Technical Analysis -โ€ข **Detailed Specifications:** In-depth technical parameters and data -โ€ข **Quantitative Metrics:** Precise measurements and statistical analysis -โ€ข **Technical Terminology:** Appropriate use of specialized vocabulary -โ€ข **Research Depth:** Extended exploration with multiple perspectives -### ๐Ÿ” Advanced Resources and Tools -โ€ข **Primary Sources:** Access to original research and documentation -โ€ข **Data Visualizations:** Complex charts, graphs, and technical diagrams -โ€ข **Analytical Tools:** Interactive calculators and simulation tools -โ€ข **Expert Commentary:** Insights from subject matter experts -### ๐Ÿ“ˆ Deep Learning Pathways -โ€ข **Progressive Complexity:** Building from fundamentals to advanced concepts -โ€ข **Cross-References:** Extensive linking to related technical topics -โ€ข **Practical Applications:** Real-world implementation examples -โ€ข **Research Opportunities:** Suggestions for further investigation -โœจ **Result:** Content enriched for intensive technical exploration and analysis - """, - - "sensory_adaptation": """ -## ๐ŸŒธ SENSORY-FRIENDLY ADAPTATION -๐ŸŽฏ **CALM AND ACCESSIBLE LEARNING:** -### โœจ Gentle Presentation Approach -โ€ข **Soft Language:** Calming, non-overwhelming tone and vocabulary -โ€ข **Paced Delivery:** Information presented in manageable, digestible chunks -โ€ข **Minimal Stimuli:** Reduced visual and cognitive overload -โ€ข **Comfort Focus:** Emphasis on creating a stress-free learning environment -### ๐ŸŽจ Peaceful Learning Environment -โ€ข **Harmonious Colors:** Soft, muted color palette for visual comfort -โ€ข **Gentle Transitions:** Smooth, non-jarring changes between sections -โ€ข **Break Reminders:** Built-in suggestions for processing pauses -โ€ข **Flexible Pacing:** Self-directed learning rhythm options -### ๐Ÿ›ก๏ธ Accessibility Features -โ€ข **Font Options:** Adjustable text size and dyslexia-friendly fonts -โ€ข **Audio Support:** Text-to-speech capabilities -โ€ข **Contrast Control:** Adjustable visual contrast settings -โ€ข **Distraction Reduction:** Minimal interface with focus tools -โœจ **Result:** Content adapted for comfortable and accessible sensory experience - """, - - "special_interests": """ -## ๐ŸŽฎ GAMIFIED INTEREST-BASED ADAPTATION -๐ŸŽฏ **ENGAGING AND MOTIVATIONAL LEARNING:** -### ๐Ÿ† Gamification and Achievement System -โ€ข **Progress Tracking:** Visual progress bars and milestone markers -โ€ข **Achievement Badges:** Unlockable rewards for learning milestones -โ€ข **Challenge Levels:** Adaptive difficulty with optional advanced challenges -โ€ข **Leaderboards:** Personal progress tracking and goal setting -### โญ Personal Interest Integration -โ€ข **Interest Connections:** Links to hobbies, passions, and personal interests -โ€ข **Relevant Examples:** Real-world applications in areas of interest -โ€ข **Creative Projects:** Hands-on activities related to personal interests -โ€ข **Community Features:** Connect with others sharing similar interests -### ๐ŸŽฏ Motivation Enhancement -โ€ข **Clear Goals:** Specific, achievable learning objectives -โ€ข **Immediate Feedback:** Real-time progress updates and encouragement -โ€ข **Choice and Agency:** Multiple learning paths and content options -โ€ข **Celebration:** Recognition of efforts and achievements -โœจ **Result:** Learning experience designed to connect with personal interests and motivate engagement - """ - } - - def _safe_model_loading(self): # Fixed: proper method definition - """Safe background model loading without threading issues""" - try: - # Check if we should attempt model loading - memory_available = True # Assume true for now - - if memory_available: - print("๐Ÿ”„ Attempting safe model loading...") - success = self._load_model_safely() - - if success: - print("๐ŸŽ‰ Model loaded successfully!") - self.simulation_mode = False - self._model_loaded = True - else: - print("โš ๏ธ Model loading failed - using enhanced simulation") - else: - print("โš ๏ธ Insufficient resources - using simulation mode") - - except Exception as e: - print(f"โš ๏ธ Safe loading error: {e}") - print("๐ŸŽญ Continuing with enhanced simulation mode") - - def _load_model_safely(self): - """Load model with safe error handling""" - try: - # Import here to avoid issues - from transformers import AutoTokenizer, AutoModelForCausalLM, pipeline - - print("๐Ÿ“ Loading tokenizer...") - self.gemma3_tokenizer = AutoTokenizer.from_pretrained( - "google/gemma-2-2b-it", # Updated to available model - trust_remote_code=True, - use_fast=True, - token=self.hf_token - ) - - if self.gemma3_tokenizer.pad_token is None: - self.gemma3_tokenizer.pad_token = self.gemma3_tokenizer.eos_token - - print("๐Ÿค– Loading model...") - model = AutoModelForCausalLM.from_pretrained( - "google/gemma-2-2b-it", # Updated to available model - torch_dtype=torch.float32, - device_map=None, - trust_remote_code=True, - low_cpu_mem_usage=True, - token=self.hf_token - ) - - print("๐Ÿ”„ Creating pipeline...") - self.gemma3_model = pipeline( - "text-generation", - model=model, - tokenizer=self.gemma3_tokenizer, - device=-1, # Force CPU - return_full_text=False, - max_length=256 - ) - - # Quick test - print("๐Ÿงช Testing model...") - test_result = self.gemma3_model( - "Hello:", - max_new_tokens=3, - do_sample=False - ) - - if test_result and len(test_result) > 0: - print("โœ… Model test successful!") - return True - else: - print("โš ๏ธ Model test failed") - return False - - except Exception as e: - print(f"โŒ Model loading error: {e}") - return False - - return False - - def generate_with_gemma3(self, prompt, max_length=200, temperature=0.7): - """Generate content with model or enhanced simulation""" - - # If model is available, try to use it - if self.gemma3_model is not None and not self.simulation_mode: - try: - result = self.gemma3_model( - prompt[:400], # Limit prompt - max_new_tokens=min(max_length, 150), - temperature=temperature, - do_sample=True, - pad_token_id=self.gemma3_tokenizer.eos_token_id - ) - - if result and len(result) > 0: - return result[0]['generated_text'].strip() - - except Exception as e: - print(f"โš ๏ธ Generation error, falling back to simulation: {e}") - - # Use enhanced simulation - return self._enhanced_simulation(prompt) - - def _enhanced_simulation(self, prompt): - """Enhanced simulation based on prompt analysis""" - prompt_lower = prompt.lower() - - # Determine profile type from prompt - if "visual" in prompt_lower or "structure" in prompt_lower: - return self.simulation_patterns["visual_structure"] - elif "hyperfocus" in prompt_lower or "technical" in prompt_lower: - return self.simulation_patterns["hyperfocus_directed"] - elif "sensory" in prompt_lower or "gentle" in prompt_lower: - return self.simulation_patterns["sensory_adaptation"] - elif "special" in prompt_lower or "gamif" in prompt_lower or "interest" in prompt_lower: - return self.simulation_patterns["special_interests"] - else: - # Create dynamic response based on content - return self._create_dynamic_response(prompt) - - def _create_dynamic_response(self, prompt): - """Create dynamic response based on prompt content""" - - # Extract key topics - topics = [] - educational_keywords = { - "science": ["science", "physics", "chemistry", "biology", "research"], - "technology": ["technology", "programming", "computer", "software", "AI"], - "mathematics": ["math", "calculation", "number", "equation", "formula"], - "arts": ["art", "creative", "design", "music", "literature"], - "history": ["history", "historical", "past", "civilization", "culture"] - } - - prompt_lower = prompt.lower() - for topic, keywords in educational_keywords.items(): - if any(keyword in prompt_lower for keyword in keywords): - topics.append(topic) - - main_topic = topics[0] if topics else "learning" - - return f""" -## ๐Ÿ“š ADAPTIVE CONTENT ENHANCEMENT -๐ŸŽฏ **PERSONALIZED FOR {main_topic.upper()} LEARNING:** -### ๐Ÿ” Content Analysis and Adaptation -The educational content has been analyzed and enhanced for optimal learning experience: -**Core Topic:** {main_topic.title()} -**Content Focus:** {prompt[:150]}... -### โœจ Enhanced Learning Features -โ€ข **Structured Organization:** Clear progression and logical flow -โ€ข **Multiple Perspectives:** Different approaches to understanding -โ€ข **Interactive Elements:** Engaging activities and exercises -โ€ข **Progress Tracking:** Learning milestone recognition -โ€ข **Accessibility Options:** Multiple formats and pacing -### ๐ŸŽจ Adaptive Presentation -โ€ข **Visual Organization:** Clear hierarchy and scannable layout -โ€ข **Engagement Tools:** Interactive components and activities -โ€ข **Personalization:** Adapted to individual learning preferences -โ€ข **Support Systems:** Additional resources and help options -### ๐ŸŽฏ Learning Outcomes -โ€ข **Knowledge Retention:** Structured for better memory formation -โ€ข **Skill Development:** Practical application opportunities -โ€ข **Critical Thinking:** Analysis and evaluation exercises -โ€ข **Creative Expression:** Opportunities for personal interpretation -โœจ **Result:** Content optimized for diverse learning needs and enhanced engagement - """ - -# ============================================================================ -# FIXED GRADIO INTERFACE SECTION -# ============================================================================ - -class GradioInterface: - """Enhanced Gradio interface with API integration info""" - - def __init__(self): - print("๐ŸŒ Initializing Enhanced Gradio interface...") - # Initialize AI config and pipeline properly - self.ai_config = AIConfig(safe_mode=True) - self.pipeline = ContentAdaptationPipeline(self.ai_config) - self.session_stats = { - "adaptations": 0, - "start_time": datetime.now(), - "profiles_used": {}, - "total_processing_time": 0.0 - } - - def adapt_content_interface(self, content, profile_name, interests_text, complexity): - """Main interface function for content adaptation""" - - if not content or not content.strip(): - return ( - "
" - "

โš ๏ธ Input Required

" - "

Please enter some educational content to adapt for different learning styles.

" - "
", - "", "", "" - ) - - try: - # Convert profile name to key - profile_map = { - "๐ŸŽฏ Visual Structure": "visual_structure", - "๐Ÿ”ฌ Directed Hyperfocus": "hyperfocus_directed", - "๐ŸŒธ Sensory Adaptation": "sensory_adaptation", - "๐ŸŽฎ Special Interests": "special_interests" - } - - profile_key = profile_map.get(profile_name, "visual_structure") - interests = [i.strip() for i in interests_text.split(',') if i.strip()] - - # Perform adaptation - result = self.pipeline.adapt_content( - content=content.strip(), - profile_key=profile_key, - interests=interests, - complexity=complexity - ) - - # Update session stats - self._update_session_stats(result) - - # Format outputs for interface - adapted_html = result['adapted_content'] - - gamification_info = self._format_gamification_output(result['gamification']) - processing_info = self._format_processing_output(result) - stats_info = self._format_stats_output() - - return adapted_html, gamification_info, processing_info, stats_info - - except Exception as e: - error_msg = f"โŒ Adaptation error: {str(e)}" - print(f"Interface error: {e}") - - return ( - f"
" - f"

โŒ Processing Error

" - f"

An error occurred during content adaptation: {str(e)}

" - f"

Please try again with different content or settings.

" - f"
", - "", "", "" - ) - - def _update_session_stats(self, result): - """Update session statistics""" - self.session_stats["adaptations"] += 1 - - profile_used = result.get("profile_used", "unknown") - if profile_used in self.session_stats["profiles_used"]: - self.session_stats["profiles_used"][profile_used] += 1 + 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: - self.session_stats["profiles_used"][profile_used] = 1 - - self.session_stats["total_processing_time"] += result.get("processing_time", 0) - - def _format_gamification_output(self, gamification): - """Format gamification information for display""" - - level = gamification.get("current_level", 1) - xp = gamification.get("xp_points", 0) - progress = gamification.get("progress_percentage", 0) - achievements = len(gamification.get("achievements", [])) - - return ( - f"๐ŸŽฎ Level {level} | โญ {xp:,} XP | ๐Ÿ“ˆ {progress}% to next level | " - f"๐Ÿ† {achievements} achievements unlocked" - ) - - def _format_processing_output(self, result): - """Format processing information for display""" - - processing_time = result.get("processing_time", 0) - ai_status = "๐Ÿง  AI Model" if result.get("gemma3_used", False) else "๐ŸŽญ Enhanced Simulation" - profile = result.get("profile_used", "unknown").replace("_", " ").title() - success = "โœ… Success" if result.get("success", False) else "โš ๏ธ Fallback" - - return ( - f"โšก {processing_time:.2f}s processing | {ai_status} | " - f"๐ŸŽฏ {profile} profile | {success}" - ) - - def _format_stats_output(self): - """Format session statistics for display""" - - total_adaptations = self.session_stats["adaptations"] - session_time = (datetime.now() - self.session_stats["start_time"]).total_seconds() / 60 - avg_processing = ( - self.session_stats["total_processing_time"] / total_adaptations - if total_adaptations > 0 else 0 - ) - - most_used_profile = "None" - if self.session_stats["profiles_used"]: - most_used_profile = max( - self.session_stats["profiles_used"].items(), - key=lambda x: x[1] - )[0].replace("_", " ").title() - - return ( - f"๐Ÿ“Š Session: {total_adaptations} adaptations | " - f"โฑ๏ธ {session_time:.1f}min active | " - f"โšก {avg_processing:.2f}s avg | " - f"๐ŸŽฏ Most used: {most_used_profile}" - ) + return self._generate_default_content(prompt) - def get_system_status(self): - """Get current system status with API info""" - - model_status = "๐Ÿง  AI Model Active" if not self.ai_config.simulation_mode else "๐ŸŽญ Simulation Mode" - device_info = "๐Ÿš€ GPU" if torch.cuda.is_available() else "๐Ÿ’ป CPU" - - # Determine base URL for API - base_url = "http://localhost:8000" if "SPACE_ID" not in os.environ else "https://your-space.hf.space" - - return f""" -## ๐Ÿ”ง System Status -**AI Engine:** {model_status} -**Device:** {device_info} -**Profiles:** 4 neurodiverse learning profiles available -**Features:** Content adaptation, gamification, analytics -**Session:** {self.session_stats['adaptations']} adaptations completed + def _generate_visual_content(self, prompt): + return """ +## ๐Ÿ“š Structured Learning Overview -## ๐Ÿ”Œ API Integration -**API Status:** โœ… Active and ready -**Base URL:** `{base_url}` -**Documentation:** `{base_url}/docs` -**Health Check:** `{base_url}/health` +**Key Concepts** organized for clarity: -**Available Endpoints:** -- `POST /adapt` - Content adaptation -- `GET /profiles` - List profiles -- `GET /examples` - Usage examples -- `GET /health` - Health check +### ๐ŸŽฏ Main Topic +Clear presentation of core information with visual hierarchy and organized structure. -## ๐ŸŽฏ Profile System -- ๐ŸŽฏ **Visual Structure:** Clear organization and hierarchy -- ๐Ÿ”ฌ **Directed Hyperfocus:** Technical depth and detail -- ๐ŸŒธ **Sensory Adaptation:** Calm and accessible design -- ๐ŸŽฎ **Special Interests:** Gamification and motivation +### ๐Ÿ“Š Important Details +- **Primary points** highlighted for easy scanning +- **Secondary information** properly categorized +- **Visual elements** integrated for better comprehension -## โœจ Capabilities -โœ… Real-time content adaptation -โœ… Multiple complexity levels -โœ… Interest-based personalization -โœ… Accessibility features -โœ… Progress tracking and gamification -โœ… **REST API for external access** -โœ… **Gradio web interface** +### โœ… Summary Points +Essential takeaways presented in an accessible, scannable format with consistent organization. """ - def get_api_examples_display(self): - """Get API examples for display in Gradio""" - - base_url = "http://localhost:8000" if "SPACE_ID" not in os.environ else "https://your-space.hf.space" - - return f""" -## ๐Ÿ”Œ API Usage Examples + def _generate_technical_content(self, prompt): + return """ +## ๐Ÿ”ฌ Technical Deep Dive -### Python Example -```python -import requests +**Comprehensive Analysis** with detailed specifications: -url = "{base_url}/adapt" -data = {{ - "content": "Your educational content here...", - "profile": "visual_structure", - "interests": ["technology", "programming"], - "complexity": "intermediate", - "format": "html" -}} +### ๐Ÿ”ง Technical Specifications +Advanced implementation details with precise terminology and comprehensive coverage of all relevant aspects. -response = requests.post(url, json=data) -result = response.json() - -print("Adapted:", result["adapted_content"]) -print("Gamification:", result["gamification"]) -``` +### ๐Ÿ“ˆ 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 -### JavaScript Example -```javascript -const response = await fetch('{base_url}/adapt', {{ - method: 'POST', - headers: {{ 'Content-Type': 'application/json' }}, - body: JSON.stringify({{ - content: 'Your educational content...', - profile: 'visual_structure', - interests: ['technology'], - complexity: 'intermediate' - }}) -}}); - -const result = await response.json(); -console.log('Adapted:', result.adapted_content); -``` - -### cURL Example -```bash -curl -X POST "{base_url}/adapt" \\ - -H "Content-Type: application/json" \\ - -d '{{ - "content": "AI is transforming education...", - "profile": "visual_structure", - "interests": ["technology", "AI"], - "complexity": "intermediate" - }}' -``` - -### Available Profiles -- `visual_structure` - Clear organization and hierarchy -- `hyperfocus_directed` - Technical depth and detail -- `sensory_adaptation` - Calm and accessible design -- `special_interests` - Gamification and motivation - -### Response Format -```json -{{ - "adapted_content": "Enhanced HTML content...", - "gamification": {{ - "current_level": 15, - "xp_points": 1250, - "achievements": ["Explorer", "Scholar"] - }}, - "processing_time": 0.45, - "profile_used": "visual_structure", - "success": true -}} -``` +### ๐ŸŽ›๏ธ Advanced Configuration +Detailed parameter settings and fine-tuning options for specialized use cases and expert-level customization. """ - def create_interface(self): - """Create the main Gradio interface with API integration""" - - with gr.Blocks( - title="๐Ÿง  InclusiveEdu - Neurodiverse Learning Platform + API", - theme=gr.themes.Soft() - ) as interface: - - # Main Header with API info - header_html = """ -
-

๐Ÿง  InclusiveEdu

-

AI-Powered Neurodiverse Learning Platform

-

- โœจ Adaptive content for every learning style | ๐Ÿš€ Powered by advanced AI -

-

- ๐ŸŒ Web Interface + ๐Ÿ”Œ REST API | Optimized for Hugging Face Spaces -

-
-""" - - gr.HTML(header_html) - - # Main Interface Layout - with gr.Row(): - # Input Section - with gr.Column(scale=1): - gr.Markdown("## ๐Ÿ“ Content Input & Settings") - - content_input = gr.Textbox( - label="Educational Content", - placeholder="Enter the educational content you want to adapt...", - lines=8, - max_lines=12 - ) - - with gr.Row(): - profile_dropdown = gr.Dropdown( - label="๐ŸŽฏ Neurodiverse Learning Profile", - choices=[ - "๐ŸŽฏ Visual Structure", - "๐Ÿ”ฌ Directed Hyperfocus", - "๐ŸŒธ Sensory Adaptation", - "๐ŸŽฎ Special Interests" - ], - value="๐ŸŽฏ Visual Structure" - ) - - complexity_dropdown = gr.Dropdown( - label="๐Ÿ“Š Content Complexity", - choices=[ - "beginner", - "intermediate", - "advanced" - ], - value="intermediate" - ) - - interests_input = gr.Textbox( - label="๐ŸŽฏ Personal Interests (comma-separated)", - placeholder="technology, science, programming, art...", - value="technology, learning, science" - ) - - adapt_button = gr.Button( - "๐Ÿš€ Adapt Content", - variant="primary" - ) - - # Output Section - with gr.Column(scale=1): - gr.Markdown("## โœจ Adapted Learning Content") - - adapted_output = gr.HTML( - label="Neurodiverse Adapted Content" - ) - - # Status and Information Row - with gr.Row(): - gamification_output = gr.Textbox( - label="๐ŸŽฎ Gamification & Progress", - lines=2, - interactive=False - ) - - processing_output = gr.Textbox( - label="โšก Processing Information", - lines=2, - interactive=False - ) - - stats_output = gr.Textbox( - label="๐Ÿ“Š Session Statistics", - lines=2, - interactive=False - ) - - # System Information Section with API Status - with gr.Accordion("๐Ÿ”ง System Information & API Status", open=False): - system_status = gr.Markdown(self.get_system_status()) - - refresh_status_btn = gr.Button("๐Ÿ”„ Refresh System Status", variant="secondary") - refresh_status_btn.click( - fn=self.get_system_status, - outputs=[system_status] - ) - - # API Examples Section - with gr.Accordion("๐Ÿ”Œ API Usage Examples", open=False): - api_examples = gr.Markdown(self.get_api_examples_display()) - - # Learning Profiles Information - with gr.Accordion("๐Ÿ“‹ Neurodiverse Learning Profiles Guide", open=False): - - profiles_html = """ -
- """ - - for profile_key, profile_data in self.pipeline.profile_system.profiles.items(): - colors = profile_data['colors'] - profiles_html += f""" -
- -

- {profile_data['name']} -

- -

- Focus: {profile_data['description']} -

- -
-

- ๐Ÿ” Key Characteristics: -

-
    - {''.join([f"
  • {char}
  • " for char in profile_data['characteristics']])} -
-
- -
-

- ๐ŸŽฏ Best For: -

-
    - {''.join([f"
  • {item}
  • " for item in profile_data.get('best_for', [])])} -
-
-
- """ - - profiles_html += "
" - gr.HTML(profiles_html) - - # Usage Examples Section - with gr.Accordion("๐Ÿ’ก Content Examples & Templates", open=False): - - gr.Markdown("### ๐Ÿ“š Try these example contents with different profiles:") - - examples_data = [ - [ - "Artificial intelligence (AI) refers to the simulation of human intelligence in machines. AI applications include expert systems, natural language processing, speech recognition and machine vision.", - "๐ŸŽฏ Visual Structure", - "technology, computer science, artificial intelligence", - "intermediate" - ], - [ - "Photosynthesis is a process used by plants to convert light energy into chemical energy. This chemical energy is stored in carbohydrate molecules synthesized from carbon dioxide and water.", - "๐ŸŒธ Sensory Adaptation", - "biology, nature, science, plants", - "beginner" - ], - [ - "Object-oriented programming (OOP) is a programming paradigm based on the concept of objects, which can contain data and code. A feature of objects is that procedures can access and modify data fields.", - "๐Ÿ”ฌ Directed Hyperfocus", - "programming, software development, coding", - "advanced" - ], - [ - "Mathematics is the study of topics such as quantity, structure, space, and change. Mathematical discoveries have been made throughout history and continue today.", - "๐ŸŽฎ Special Interests", - "mathematics, problem solving, logic", - "intermediate" - ] - ] - - gr.Examples( - examples=examples_data, - inputs=[content_input, profile_dropdown, interests_input, complexity_dropdown] - ) - - # Connect the main adaptation function - adapt_button.click( - fn=self.adapt_content_interface, - inputs=[content_input, profile_dropdown, interests_input, complexity_dropdown], - outputs=[adapted_output, gamification_output, processing_output, stats_output] - ) - - # Enhanced Footer with API Information - footer_html = f""" -
- -

๐Ÿง  InclusiveEdu - Empowering Every Learner

- -
- -
-

๐Ÿš€ Technology Stack

-
    -
  • AI-powered content adaptation
  • -
  • Gradio 4.0.0 web interface
  • -
  • FastAPI REST endpoints
  • -
  • Enhanced simulation fallbacks
  • -
  • Dual deployment ready
  • -
-
- -
-

๐ŸŽฏ Learning Profiles

-
    -
  • Visual Structure & Organization
  • -
  • Directed Hyperfocus & Detail
  • -
  • Sensory Adaptation & Comfort
  • -
  • Special Interests & Gamification
  • -
-
- -
-

โœจ Key Features

-
    -
  • Real-time content adaptation
  • -
  • Progress tracking & gamification
  • -
  • Accessibility optimization
  • -
  • Interest-based personalization
  • -
  • REST API for external access
  • -
-
- -
-

๐Ÿ”Œ API Access

-
    -
  • POST /adapt - Content adaptation
  • -
  • GET /profiles - List profiles
  • -
  • GET /health - System status
  • -
  • GET /docs - Interactive docs
  • -
  • External device integration
  • -
-
-
- - - Version: {datetime.now().strftime('%Y.%m.%d')} | - AI Status: {"๐Ÿง  Active" if not self.ai_config.simulation_mode else "๐ŸŽญ Enhanced Simulation"} | - ๐ŸŒ Web Interface + ๐Ÿ”Œ REST API | - Optimized for cloud deployment - -
- """ - - gr.HTML(footer_html) - - return interface + def _generate_sensory_content(self, prompt): + return """ +## ๐ŸŒธ Gentle Learning Space -# ============================================================================ -# 7. API SERVER RUNNER FOR DUAL MODE -# ============================================================================ +**Comfortable Environment** designed for ease: -def run_api_server(): - """Run API server in separate thread""" - try: - print("๐Ÿ”Œ Starting API server...") - uvicorn.run( - api, - host="0.0.0.0", - port=8000, - log_level="info", - access_log=False # Reduce noise in logs - ) - except Exception as e: - print(f"โŒ API server error: {e}") - -def launch_dual_mode(): - """Launch both Gradio and API simultaneously""" - - print("๐Ÿš€ Initializing dual mode: Gradio + API...") - - # Initialize shared components first - initialize_global_instances() - - # Start API server in background thread - api_thread = Thread(target=run_api_server, daemon=True) - api_thread.start() - - # Give API server time to start - time.sleep(2) - - # Create and launch Gradio interface - gradio_interface = GradioInterface() - app = gradio_interface.create_interface() - - print("\n๐ŸŽ‰ InclusiveEdu running in dual mode!") - print("๐ŸŒ Gradio Interface: http://localhost:7860") - print("๐Ÿ”Œ REST API: http://localhost:8000") - print("๐Ÿ“– API Documentation: http://localhost:8000/docs") - print("๐Ÿงช API Health Check: http://localhost:8000/health") - print("\n๐Ÿ’ก Tip: External devices can use the API endpoints for integration") - - # Launch Gradio (this will block) - app.launch( - server_name="0.0.0.0", - server_port=7860, - share=False, - show_error=True - ) - -# ============================================================================ -# 8. MAIN APPLICATION FUNCTIONS -# ============================================================================ +### ๐Ÿ•Š๏ธ Peaceful Introduction +A calm and welcoming approach to the topic, presented at a comfortable pace. -def create_app(): - """Create the main application instance""" - print("๐ŸŒ Creating InclusiveEdu application...") - - try: - # Initialize components - ai_config, pipeline = initialize_global_instances() - - # Create Gradio interface - gradio_interface = GradioInterface() - interface = gradio_interface.create_interface() - - print("โœ… Application created successfully!") - print(f"๐Ÿ”ง AI Status: {'Model Active' if not ai_config.simulation_mode else 'Enhanced Simulation'}") - print(f"๐Ÿ–ฅ๏ธ Device: {'GPU' if torch.cuda.is_available() else 'CPU'}") - print(f"๏ฟฝ๏ฟฝ๏ฟฝ Profiles: 4 neurodiverse learning profiles available") - print(f"๐Ÿ”Œ API: Integrated FastAPI endpoints") - - return interface - - except Exception as e: - print(f"โŒ Application creation error: {e}") - return create_emergency_interface() +### ๐Ÿ’ซ Gentle Progression +Learning unfolds naturally: +โ€ข Soft transitions between concepts +โ€ข Comfortable information density +โ€ข Regular pause points for reflection -def create_emergency_interface(): - """Create emergency fallback interface""" - print("๐Ÿšจ Creating emergency fallback interface...") - - def emergency_adaptation(content, profile): - if not content: - return "Please enter some content to adapt." - - return f""" -
-

๐Ÿ“š {profile} - Emergency Mode

-
-

Original Content:

-

{content}

-

Adaptation Status:

-

Content prepared for {profile} learning style.

-

โœจ Basic adaptation active. Full features will be available once system initialization completes.

-
-
- System Status: Emergency mode - core functionality available -
-
+### ๐ŸŒฑ Supportive Summary +Key insights presented gently, with encouragement and positive reinforcement for continued learning. """ - return gr.Interface( - fn=emergency_adaptation, - inputs=[ - gr.Textbox(label="Content", lines=5, placeholder="Enter educational content..."), - gr.Dropdown( - label="Profile", - choices=["Visual Structure", "Directed Hyperfocus", "Sensory Adaptation", "Special Interests"], - value="Visual Structure" - ) - ], - outputs=gr.HTML(label="Adapted Content"), - title="๐Ÿง  InclusiveEdu - Emergency Mode", - description="Basic content adaptation system. Full features loading...", - theme=gr.themes.Soft() - ) - -# ============================================================================ -# 9. MAIN EXECUTION AND LAUNCH -# ============================================================================ - -if __name__ == "__main__": - print("๐Ÿš€ Starting InclusiveEdu - Enhanced with API Integration...") - print("=" * 70) - - # System check - print(f"๐Ÿ“Š System Information:") - print(f" ๐Ÿ Python: Ready") - print(f" ๐Ÿ”ฅ PyTorch: {torch.__version__}") - print(f" ๐ŸŽจ Gradio: Compatible version") - print(f" ๐Ÿ”Œ FastAPI: Integrated") - print(f" ๐Ÿ–ฅ๏ธ Device: {'๐Ÿš€ GPU Available' if torch.cuda.is_available() else '๐Ÿ’ป CPU Mode'}") - if torch.cuda.is_available(): - print(f" ๐Ÿ’พ GPU Memory: {torch.cuda.get_device_properties(0).total_memory / 1e9:.1f}GB") - - # Determine run mode - print("\n๐ŸŽฏ InclusiveEdu - Choose execution mode:") - print("1. ๐ŸŽจ Gradio Interface only (default for Spaces)") - print("2. ๐Ÿ”Œ API Server only") - print("3. ๐ŸŒ Dual Mode: Gradio + API") - - # Auto-detect Hugging Face Spaces - if "SPACE_ID" in os.environ: - print("๐Ÿค— Hugging Face Spaces detected - using Gradio mode") - mode = "1" - else: - mode = input("Choose mode (1/2/3): ").strip() or "1" - - try: - if mode == "1": - # Gradio only mode - print("\n๐ŸŽจ Starting Gradio Interface...") - app = create_app() - - print("\n๐ŸŽ‰ InclusiveEdu ready to launch!") - print("๐ŸŽฏ Available features:") - print(" โ€ข AI-powered content adaptation") - print(" โ€ข 4 specialized neurodiverse learning profiles") - print(" โ€ข Real-time gamification and progress tracking") - print(" โ€ข Interest-based personalization") - print(" โ€ข Accessibility optimization") - print(" โ€ข Session analytics and statistics") - - app.launch( - server_name="0.0.0.0", - server_port=7860, - share=False, - show_error=True - ) - - elif mode == "2": - # API only mode - print("\n๐Ÿ”Œ Starting API Server only...") - initialize_global_instances() - - print("๐ŸŽ‰ InclusiveEdu API ready!") - print("๐Ÿ”Œ API Endpoints:") - print(" โ€ข POST /adapt - Content adaptation") - print(" โ€ข GET /profiles - List learning profiles") - print(" โ€ข GET /health - Health check") - print(" โ€ข GET /docs - Interactive documentation") - print(" โ€ข GET /examples - Usage examples") - - uvicorn.run( - api, - host="0.0.0.0", - port=8000, - log_level="info" - ) - - elif mode == "3": - # Dual mode - print("\n๐ŸŒ Starting Dual Mode...") - launch_dual_mode() - - else: - print("โŒ Invalid option. Using default Gradio mode...") - app = create_app() - app.launch(server_name="0.0.0.0", server_port=7860, share=False) - - except Exception as e: - print(f"โŒ Launch error: {e}") - print("\n๐Ÿšจ Activating emergency mode...") - - try: - emergency_app = create_emergency_interface() - emergency_app.launch( - server_name="0.0.0.0", - server_port=7860, - share=False - ) - except Exception as emergency_error: - print(f"โŒ Emergency mode failed: {emergency_error}") - print("๐Ÿ’ก Please check system requirements and try again") - -# ============================================================================ -# 10. UTILITY FUNCTIONS AND EXPORTS -# ============================================================================ - -def test_system_comprehensive(): - """Comprehensive system test including API""" - print("๐Ÿงช Running comprehensive system test...") - - try: - # Test basic components - ai_config, pipeline = initialize_global_instances() - - # Test content adaptation - result = pipeline.adapt_content( - content="Test content for comprehensive system verification", - profile_key="visual_structure", - interests=["testing", "verification"], - complexity="intermediate" - ) - - print(f"โœ… Core system test passed!") - print(f" Processing time: {result['processing_time']:.2f}s") - print(f" AI status: {'Active' if result.get('gemma3_used', False) else 'Simulation'}") - print(f" Success: {result.get('success', False)}") - - # Test API functionality - print("๐Ÿ”Œ Testing API components...") - - # Simulate API request - test_request = ContentRequest( - content="Test API content", - profile="visual_structure", - interests=["testing"], - complexity="intermediate" - ) - - print("โœ… API components test passed!") - print("๐ŸŽ‰ Comprehensive system test completed successfully!") - - return True - - except Exception as e: - print(f"โŒ System test failed: {e}") - return False - -def get_memory_usage(): - """Get current memory usage""" - if torch.cuda.is_available(): - allocated = torch.cuda.memory_allocated(0) / 1e9 - cached = torch.cuda.memory_reserved(0) / 1e9 - total = torch.cuda.get_device_properties(0).total_memory / 1e9 - - print(f"๐Ÿ’พ GPU Memory Usage:") - print(f" Total: {total:.1f}GB") - print(f" Allocated: {allocated:.1f}GB ({allocated/total*100:.1f}%)") - print(f" Cached: {cached:.1f}GB ({cached/total*100:.1f}%)") - print(f" Free: {total - allocated:.1f}GB") - else: - print("๐Ÿ’ป Running on CPU - no GPU memory tracking") - -def cleanup_memory(): - """Clean up memory usage""" - print("๐Ÿงน Cleaning up memory...") - gc.collect() - if torch.cuda.is_available(): - torch.cuda.empty_cache() - print("โœ… Memory cleanup completed") - -def get_api_status(): - """Get API status information""" - try: - import requests - response = requests.get("http://localhost:8000/health", timeout=5) - if response.status_code == 200: - return "๐ŸŸข API Active" - else: - return "๐ŸŸก API Responding with issues" - except: - return "๐Ÿ”ด API Not accessible" - -# Export main components -__all__ = [ - 'AIConfig', - 'NeuroProfileSystem', - 'ContentAdaptationPipeline', - 'GradioInterface', - 'ContentRequest', - 'ContentResponse', - 'api', - 'create_app', - 'launch_dual_mode', - 'test_system_comprehensive', - 'get_memory_usage', - 'cleanup_memory', - 'get_api_status' -] - -print(""" -๐ŸŽฏ ENHANCED DEPLOYMENT READY! -โœ… This version includes: - - Gradio 4.0.0 web interface - - FastAPI REST API integration - - Dual deployment modes - - Enhanced error handling - - Comprehensive documentation -๐Ÿš€ Features included: - - 4 neurodiverse learning profiles - - AI-powered content adaptation - - Real-time gamification - - Session analytics - - REST API for external devices - - Interactive API documentation - - Emergency fallback modes - - Full accessibility support -๐Ÿ“‹ Deployment Options: - 1. Hugging Face Spaces: Gradio interface - 2. Local/Server: Gradio + API dual mode - 3. API-only: For backend services -๐Ÿ”Œ API Endpoints: - - POST /adapt - Content adaptation - - GET /profiles - Learning profiles - - GET /health - System status - - GET /docs - Interactive documentation -""") - -# ============================================================================ -# 11. REQUIREMENTS AND CONFIGURATION -# ============================================================================ - -requirements_txt = """ -# InclusiveEdu - Complete Requirements -gradio>=4.0.0 -fastapi>=0.104.0 -uvicorn[standard]>=0.24.0 -pydantic>=2.5.0 -torch>=2.0.0 -transformers>=4.35.0 -numpy>=1.24.0 -pandas>=2.0.0 -python-multipart>=0.0.6 -""" - -print("\n๐Ÿ“ฆ Required packages:") -for req in requirements_txt.strip().split('\n')[1:]: - if req.strip() and not req.startswith('#'): - print(f" โ€ข {req.strip()}") + def _generate_interest_content(self, prompt): + return """ +## ๐ŸŽฎ Interactive Learning Adventure -print("\n๐Ÿ“ฆ Required packages:") -for req in requirements_txt.strip().split('\n')[1:]: - if req.strip() and not req.startswith('#'): - print(f" โ€ข {req.strip()}") +**Engaging Experience** tailored to your interests: -print(f"\n๐ŸŽ‰ InclusiveEdu Enhanced - Ready for deployment!") +### ๐Ÿ† Achievement Unlocked +You've started an exciting learning journey! Connect this topic to your favorite interests for maximum engagement. -def create_simulation_patterns(): - """Create intelligent simulation patterns for each profile""" - simulation_patterns = { - "visual_structure": """ -## ๐Ÿ“Š VISUAL STRUCTURE ADAPTATION -๐ŸŽฏ **ORGANIZED FOR VISUAL LEARNING:** -### ๐Ÿ“‹ Clear Information Hierarchy -โ€ข **Main Concepts:** Structured with clear headings and subheadings -โ€ข **Visual Elements:** Strategic use of icons, colors, and layout -โ€ข **Organization:** Logical flow with numbered sections -โ€ข **Navigation:** Consistent and predictable structure +### ๐ŸŽฏ 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 -### ๐ŸŽจ Visual Design Features -โ€ข **Layout:** Clean, organized, and scannable format -โ€ข **Typography:** Clear fonts with appropriate sizing -โ€ข **Spacing:** Adequate white space for readability -โ€ข **Colors:** Consistent color coding for different content types - -### ๐Ÿ“Š Interactive Elements -โ€ข **Progress Indicators:** Visual progress tracking -โ€ข **Quick Navigation:** Jump-to-section functionality -โ€ข **Visual Summaries:** Key points highlighted visually -โ€ข **Structured Assessments:** Organized quiz and review sections - -โœจ **Result:** Content optimized for visual processing and structured learning - """, - - "hyperfocus_directed": """ -## ๐Ÿ”ฌ TECHNICAL DEEP-DIVE ADAPTATION -๐ŸŽฏ **OPTIMIZED FOR DIRECTED HYPERFOCUS:** -### ๐Ÿ“Š Comprehensive Technical Analysis -โ€ข **Detailed Specifications:** In-depth technical parameters and data -โ€ข **Quantitative Metrics:** Precise measurements and statistical analysis -โ€ข **Technical Terminology:** Appropriate use of specialized vocabulary -โ€ข **Research Depth:** Extended exploration with multiple perspectives - -### ๐Ÿ” Advanced Resources and Tools -โ€ข **Primary Sources:** Access to original research and documentation -โ€ข **Data Visualizations:** Complex charts, graphs, and technical diagrams -โ€ข **Analytical Tools:** Interactive calculators and simulation tools -โ€ข **Expert Commentary:** Insights from subject matter experts - -### ๐Ÿ“ˆ Deep Learning Pathways -โ€ข **Progressive Complexity:** Building from fundamentals to advanced concepts -โ€ข **Cross-References:** Extensive linking to related technical topics -โ€ข **Practical Applications:** Real-world implementation examples -โ€ข **Research Opportunities:** Suggestions for further investigation - -โœจ **Result:** Content enriched for intensive technical exploration and analysis - """, - - "sensory_adaptation": """ -## ๐ŸŒธ SENSORY-FRIENDLY ADAPTATION -๐ŸŽฏ **CALM AND ACCESSIBLE LEARNING:** -### โœจ Gentle Presentation Approach -โ€ข **Soft Language:** Calming, non-overwhelming tone and vocabulary -โ€ข **Paced Delivery:** Information presented in manageable, digestible chunks -โ€ข **Minimal Stimuli:** Reduced visual and cognitive overload -โ€ข **Comfort Focus:** Emphasis on creating a stress-free learning environment - -### ๐ŸŽจ Peaceful Learning Environment -โ€ข **Harmonious Colors:** Soft, muted color palette for visual comfort -โ€ข **Gentle Transitions:** Smooth, non-jarring changes between sections -โ€ข **Break Reminders:** Built-in suggestions for processing pauses -โ€ข **Flexible Pacing:** Self-directed learning rhythm options - -### ๐Ÿ›ก๏ธ Accessibility Features -โ€ข **Font Options:** Adjustable text size and dyslexia-friendly fonts -โ€ข **Audio Support:** Text-to-speech capabilities -โ€ข **Contrast Control:** Adjustable visual contrast settings -โ€ข **Distraction Reduction:** Minimal interface with focus tools - -โœจ **Result:** Content adapted for comfortable and accessible sensory experience - """, - - "special_interests": """ -## ๐ŸŽฎ GAMIFIED INTEREST-BASED ADAPTATION -๐ŸŽฏ **ENGAGING AND MOTIVATIONAL LEARNING:** -### ๐Ÿ† Gamification and Achievement System -โ€ข **Progress Tracking:** Visual progress bars and milestone markers -โ€ข **Achievement Badges:** Unlockable rewards for learning milestones -โ€ข **Challenge Levels:** Adaptive difficulty with optional advanced challenges -โ€ข **Leaderboards:** Personal progress tracking and goal setting - -### โญ Personal Interest Integration -โ€ข **Interest Connections:** Links to hobbies, passions, and personal interests -โ€ข **Relevant Examples:** Real-world applications in areas of interest -โ€ข **Creative Projects:** Hands-on activities related to personal interests -โ€ข **Community Features:** Connect with others sharing similar interests - -### ๐ŸŽฏ Motivation Enhancement -โ€ข **Clear Goals:** Specific, achievable learning objectives -โ€ข **Immediate Feedback:** Real-time progress updates and encouragement -โ€ข **Choice and Agency:** Multiple learning paths and content options -โ€ข **Celebration:** Recognition of efforts and achievements - -โœจ **Result:** Learning experience designed to connect with personal interests and motivate engagement +### โญ Power-Up Summary +Level up your understanding with these key insights, designed to fuel your curiosity and passion for learning! """ - } - - return simulation_patterns - - -# Esta parte deve estar dentro de uma classe -class YourModelClass: - def __init__(self): - self.simulation_mode = True - self.gemma3_model = None - self.gemma3_tokenizer = None - self._model_loaded = False - self.hf_token = None # Configure seu token aqui - self.simulation_patterns = create_simulation_patterns() - - def _safe_model_loading(self): - """Safe background model loading without threading issues""" - try: - # Check if we should attempt model loading - memory_available = True # Assume true for now - - if memory_available: - print("๐Ÿ”„ Attempting safe model loading...") - success = self._load_model_safely() - - if success: - print("๐ŸŽ‰ Model loaded successfully!") - self.simulation_mode = False - self._model_loaded = True - else: - print("โš ๏ธ Model loading failed - using enhanced simulation") - else: - print("โš ๏ธ Insufficient resources - using simulation mode") - - except Exception as e: - print(f"โš ๏ธ Safe loading error: {e}") - print("๐ŸŽญ Continuing with enhanced simulation mode") - - def _load_model_safely(self): - """Load model with safe error handling""" - try: - # Import here to avoid issues - from transformers import AutoTokenizer, AutoModelForCausalLM, pipeline - import torch - - print("๐Ÿ“ Loading tokenizer...") - self.gemma3_tokenizer = AutoTokenizer.from_pretrained( - "google/gemma-2-2b-it", # Updated to available model - trust_remote_code=True, - use_fast=True, - token=self.hf_token - ) - - if self.gemma3_tokenizer.pad_token is None: - self.gemma3_tokenizer.pad_token = self.gemma3_tokenizer.eos_token - - print("๐Ÿค– Loading model...") - model = AutoModelForCausalLM.from_pretrained( - "google/gemma-2-2b-it", # Updated to available model - torch_dtype=torch.float32, - device_map=None, - trust_remote_code=True, - low_cpu_mem_usage=True, - token=self.hf_token - ) - - print("๐Ÿ”„ Creating pipeline...") - self.gemma3_model = pipeline( - "text-generation", - model=model, - tokenizer=self.gemma3_tokenizer, - device=-1, # Force CPU - return_full_text=False, - max_length=256 - ) - - # Quick test - print("๐Ÿงช Testing model...") - test_result = self.gemma3_model( - "Hello:", - max_new_tokens=3, - do_sample=False - ) - - if test_result and len(test_result) > 0: - print("โœ… Model test successful!") - return True - else: - print("โš ๏ธ Model test failed") - return False - - except Exception as e: - print(f"โŒ Model loading error: {e}") - return False - - return False - - def generate_with_gemma3(self, prompt, max_length=200, temperature=0.7): - """Generate content with model or enhanced simulation""" - - # If model is available, try to use it - if self.gemma3_model is not None and not self.simulation_mode: - try: - result = self.gemma3_model( - prompt[:400], # Limit prompt - max_new_tokens=min(max_length, 150), - temperature=temperature, - do_sample=True, - pad_token_id=self.gemma3_tokenizer.eos_token_id - ) - - if result and len(result) > 0: - return result[0]['generated_text'].strip() - - except Exception as e: - print(f"โš ๏ธ Generation error, falling back to simulation: {e}") - - # Use enhanced simulation - return self._enhanced_simulation(prompt) - - def _enhanced_simulation(self, prompt): - """Enhanced simulation based on prompt analysis""" - prompt_lower = prompt.lower() - - # Determine profile type from prompt - if "visual" in prompt_lower or "structure" in prompt_lower: - return self.simulation_patterns["visual_structure"] - elif "hyperfocus" in prompt_lower or "technical" in prompt_lower: - return self.simulation_patterns["hyperfocus_directed"] - elif "sensory" in prompt_lower or "gentle" in prompt_lower: - return self.simulation_patterns["sensory_adaptation"] - elif "special" in prompt_lower or "gamif" in prompt_lower or "interest" in prompt_lower: - return self.simulation_patterns["special_interests"] - else: - # Create dynamic response based on content - return self._create_dynamic_response(prompt) - def _create_dynamic_response(self, prompt): - """Create dynamic response based on prompt content""" - - # Extract key topics - topics = [] - educational_keywords = { - "science": ["science", "physics", "chemistry", "biology", "research"], - "technology": ["technology", "programming", "computer", "software", "AI"], - "mathematics": ["math", "calculation", "number", "equation", "formula"], - "arts": ["art", "creative", "design", "music", "literature"], - "history": ["history", "historical", "past", "civilization", "culture"] - } - - prompt_lower = prompt.lower() - for topic, keywords in educational_keywords.items(): - if any(keyword in prompt_lower for keyword in keywords): - topics.append(topic) - - main_topic = topics[0] if topics else "learning" - - return f""" -## ๐Ÿ“š ADAPTIVE CONTENT ENHANCEMENT -๐ŸŽฏ **PERSONALIZED FOR {main_topic.upper()} LEARNING:** -### ๐Ÿ” Content Analysis and Adaptation -The educational content has been analyzed and enhanced for optimal learning experience: -**Core Topic:** {main_topic.title()} -**Content Focus:** {prompt[:150]}... -### โœจ Enhanced Learning Features -โ€ข **Structured Organization:** Clear progression and logical flow -โ€ข **Multiple Perspectives:** Different approaches to understanding -โ€ข **Interactive Elements:** Engaging activities and exercises -โ€ข **Progress Tracking:** Learning milestone recognition -โ€ข **Accessibility Options:** Multiple formats and pacing -### ๐ŸŽจ Adaptive Presentation -โ€ข **Visual Organization:** Clear hierarchy and scannable layout -โ€ข **Engagement Tools:** Interactive components and activities -โ€ข **Personalization:** Adapted to individual learning preferences -โ€ข **Support Systems:** Additional resources and help options -### ๐ŸŽฏ Learning Outcomes -โ€ข **Knowledge Retention:** Structured for better memory formation -โ€ข **Skill Development:** Practical application opportunities -โ€ข **Critical Thinking:** Analysis and evaluation exercises -โ€ข **Creative Expression:** Opportunities for personal interpretation -โœจ **Result:** Content optimized for diverse learning needs and enhanced engagement + 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. STREAMLINED PROFILE SYSTEM +# 3. PROFILE SYSTEM # ============================================================================ class NeuroProfileSystem: @@ -1635,7 +281,7 @@ class NeuroProfileSystem: return [(profile["name"], key) for key, profile in self.profiles.items()] def get_all_profiles_info(self): - """Get detailed info for all profiles for API""" + """Get detailed info for all profiles""" profiles_info = {} for key, profile in self.profiles.items(): profiles_info[key] = ProfileInfo( @@ -1675,7 +321,7 @@ class ContentAdaptationPipeline: # Create adaptation prompt prompt = self._create_adaptation_prompt(content, profile_key, interests, complexity) - # Generate adapted content using AI or simulation + # Generate adapted content adapted_text = self.ai_config.generate_with_gemma3(prompt, max_length=400) # Create enhanced HTML output @@ -1990,216 +636,198 @@ Interest-based gamified adaptation: } # ============================================================================ -# 5. FASTAPI SETUP +# 5. GLOBAL INSTANCES MANAGEMENT # ============================================================================ -# Create FastAPI instance -api = FastAPI( - title="๐Ÿง  InclusiveEdu API", - description="API REST para adaptaรงรฃo de conteรบdo educacional neurodiverso", - version="2.0.0", - docs_url="/docs", - redoc_url="/redoc" -) - # Global instances global_ai_config = None global_pipeline = None def initialize_global_instances(): - """Initialize global instances for API and Gradio - FIXED VERSION""" + """Initialize global instances for API and Gradio""" global global_ai_config, global_pipeline if global_ai_config is None: print("๐Ÿ”ง Initializing global instances...") - - # Import AIConfig if not already available - try: - # Assuming AIConfig is defined elsewhere in your main file - from your_main_file import AIConfig # Replace with actual import - except ImportError: - print("โš ๏ธ AIConfig import failed, using mock") - # Use a mock AIConfig for testing - class MockAIConfig: - def __init__(self, safe_mode=True): - self.simulation_mode = True - self.gemma3_model = None - self.gemma3_tokenizer = None - print("๐ŸŽญ Mock AIConfig initialized") - - def generate_with_gemma3(self, prompt, max_length=400): - return "Mock AI generated content for testing" - - AIConfig = MockAIConfig - global_ai_config = AIConfig(safe_mode=True) global_pipeline = ContentAdaptationPipeline(global_ai_config) print("โœ… Global instances initialized successfully!") return global_ai_config, global_pipeline -# CORS middleware -from fastapi.middleware.cors import CORSMiddleware - -api.add_middleware( - CORSMiddleware, - allow_origins=["*"], - allow_credentials=True, - allow_methods=["*"], - allow_headers=["*"], -) - -@api.on_event("startup") -async def startup_event(): - """Initialize API on startup""" - print("๐Ÿš€ Starting InclusiveEdu API...") - initialize_global_instances() - print("โœ… API ready for requests!") - -@api.get("/", response_model=dict) -async def root(): - """API root endpoint""" - return { - "app": "InclusiveEdu API", - "version": "2.0.0", - "status": "running", - "description": "AI-powered neurodiverse learning content adaptation", - "features": [ - "Content adaptation for 4 neurodiverse profiles", - "Gamification and progress tracking", - "Interest-based personalization", - "Multiple complexity levels" - ], - "endpoints": { - "adapt_content": "/adapt", - "health_check": "/health", - "list_profiles": "/profiles", - "api_docs": "/docs" - }, - "profiles": [ - "visual_structure", - "hyperfocus_directed", - "sensory_adaptation", - "special_interests" - ] - } +# ============================================================================ +# 6. FASTAPI SETUP +# ============================================================================ -@api.get("/health", response_model=HealthResponse) -async def health_check(): - """Health check endpoint""" - ai_config, pipeline = initialize_global_instances() - - return HealthResponse( - status="healthy", - ai_mode="simulation" if ai_config.simulation_mode else "ai_model", - profiles_available=4, - timestamp=datetime.now().isoformat(), - version="2.0.0" +if FASTAPI_AVAILABLE: + # Create FastAPI instance + api = FastAPI( + title="๐Ÿง  InclusiveEdu API", + description="API REST para adaptaรงรฃo de conteรบdo educacional neurodiverso", + version="2.0.0", + docs_url="/docs", + redoc_url="/redoc" ) - -@api.post("/adapt", response_model=ContentResponse) -async def adapt_content_api(request: ContentRequest): - """Main content adaptation endpoint""" - # Validate request - if not request.content.strip(): - raise HTTPException(status_code=400, detail="Content cannot be empty") + # CORS middleware + api.add_middleware( + CORSMiddleware, + allow_origins=["*"], + allow_credentials=True, + allow_methods=["*"], + allow_headers=["*"], + ) - # Initialize instances - ai_config, pipeline = initialize_global_instances() + @api.on_event("startup") + async def startup_event(): + """Initialize API on startup""" + print("๐Ÿš€ Starting InclusiveEdu API...") + initialize_global_instances() + print("โœ… API ready for requests!") - try: - # Map profile names - profile_map = { - "visual": "visual_structure", - "visual_structure": "visual_structure", - "structure": "visual_structure", - "hyperfocus": "hyperfocus_directed", - "hyperfocus_directed": "hyperfocus_directed", - "technical": "hyperfocus_directed", - "deep": "hyperfocus_directed", - "sensory": "sensory_adaptation", - "sensory_adaptation": "sensory_adaptation", - "calm": "sensory_adaptation", - "gentle": "sensory_adaptation", - "interests": "special_interests", - "special_interests": "special_interests", - "gamification": "special_interests", - "game": "special_interests" + @api.get("/", response_model=dict) + async def root(): + """API root endpoint""" + return { + "app": "InclusiveEdu API", + "version": "2.0.0", + "status": "running", + "description": "AI-powered neurodiverse learning content adaptation", + "features": [ + "Content adaptation for 4 neurodiverse profiles", + "Gamification and progress tracking", + "Interest-based personalization", + "Multiple complexity levels" + ], + "endpoints": { + "adapt_content": "/adapt", + "health_check": "/health", + "list_profiles": "/profiles", + "api_docs": "/docs" + }, + "profiles": [ + "visual_structure", + "hyperfocus_directed", + "sensory_adaptation", + "special_interests" + ] } + + @api.get("/health", response_model=HealthResponse) + async def health_check(): + """Health check endpoint""" + ai_config, pipeline = initialize_global_instances() - profile_key = profile_map.get(request.profile.lower(), "visual_structure") - - # Perform adaptation - result = pipeline.adapt_content( - content=request.content, - profile_key=profile_key, - interests=request.interests, - complexity=request.complexity + return HealthResponse( + status="healthy", + ai_mode="simulation" if ai_config.simulation_mode else "ai_model", + profiles_available=4, + timestamp=datetime.now().isoformat(), + version="2.0.0" ) + + @api.post("/adapt", response_model=ContentResponse) + async def adapt_content_api(request: ContentRequest): + """Main content adaptation endpoint""" - # Process output format - if request.format == "text": - # Clean HTML for text-only output - import re - clean_content = re.sub('<[^<]+?>', '', result['adapted_content']) - clean_content = re.sub(r'\s+', ' ', clean_content).strip() - adapted_content = clean_content - raw_html = result['adapted_content'] - else: - # Return HTML format - adapted_content = result['adapted_content'] - raw_html = None + # Validate request + if not request.content.strip(): + raise HTTPException(status_code=400, detail="Content cannot be empty") - return ContentResponse( - adapted_content=adapted_content, - gamification=result['gamification'], - processing_time=result['processing_time'], - profile_used=result['profile_used'], - interests=result['interests'], - complexity=result['complexity'], - success=result['success'], - format=request.format, - timestamp=result['timestamp'], - raw_html=raw_html - ) + # Initialize instances + ai_config, pipeline = initialize_global_instances() - except Exception as e: - print(f"โŒ API adaptation error: {e}") - raise HTTPException( - status_code=500, - detail=f"Content adaptation failed: {str(e)}" - ) + try: + # Map profile names + profile_map = { + "visual": "visual_structure", + "visual_structure": "visual_structure", + "structure": "visual_structure", + "hyperfocus": "hyperfocus_directed", + "hyperfocus_directed": "hyperfocus_directed", + "technical": "hyperfocus_directed", + "deep": "hyperfocus_directed", + "sensory": "sensory_adaptation", + "sensory_adaptation": "sensory_adaptation", + "calm": "sensory_adaptation", + "gentle": "sensory_adaptation", + "interests": "special_interests", + "special_interests": "special_interests", + "gamification": "special_interests", + "game": "special_interests" + } + + profile_key = profile_map.get(request.profile.lower(), "visual_structure") + + # Perform adaptation + result = pipeline.adapt_content( + content=request.content, + profile_key=profile_key, + interests=request.interests, + complexity=request.complexity + ) + + # Process output format + if request.format == "text": + # Clean HTML for text-only output + clean_content = re.sub('<[^<]+?>', '', result['adapted_content']) + clean_content = re.sub(r'\s+', ' ', clean_content).strip() + adapted_content = clean_content + raw_html = result['adapted_content'] + else: + # Return HTML format + adapted_content = result['adapted_content'] + raw_html = None + + return ContentResponse( + adapted_content=adapted_content, + gamification=result['gamification'], + processing_time=result['processing_time'], + profile_used=result['profile_used'], + interests=result['interests'], + complexity=result['complexity'], + success=result['success'], + format=request.format, + timestamp=result['timestamp'], + raw_html=raw_html + ) + + except Exception as e: + print(f"โŒ API adaptation error: {e}") + raise HTTPException( + status_code=500, + detail=f"Content adaptation failed: {str(e)}" + ) -@api.get("/profiles") -async def get_profiles_api(): - """Get all available learning profiles""" - - ai_config, pipeline = initialize_global_instances() - - profiles_info = {} - for key, profile in pipeline.profile_system.profiles.items(): - profiles_info[key] = { - "name": profile["name"], - "description": profile["description"], - "characteristics": profile["characteristics"], - "best_for": profile.get("best_for", []) + @api.get("/profiles") + async def get_profiles_api(): + """Get all available learning profiles""" + + ai_config, pipeline = initialize_global_instances() + + profiles_info = {} + for key, profile in pipeline.profile_system.profiles.items(): + profiles_info[key] = { + "name": profile["name"], + "description": profile["description"], + "characteristics": profile["characteristics"], + "best_for": profile.get("best_for", []) + } + + return { + "profiles": profiles_info, + "total_profiles": len(profiles_info), + "default_profile": "visual_structure" } - - return { - "profiles": profiles_info, - "total_profiles": len(profiles_info), - "default_profile": "visual_structure" - } -@api.get("/examples") -async def get_api_examples(): - """Get API usage examples""" - - return { - "curl_example": { - "description": "Example using cURL", - "command": """curl -X POST "http://localhost:8000/adapt" \\ + @api.get("/examples") + async def get_api_examples(): + """Get API usage examples""" + + return { + "curl_example": { + "description": "Example using cURL", + "command": """curl -X POST "http://localhost:8000/adapt" \\ -H "Content-Type: application/json" \\ -d '{ "content": "Artificial intelligence (AI) refers to the simulation of human intelligence in machines...", @@ -2208,14 +836,12 @@ async def get_api_examples(): "complexity": "intermediate", "format": "html" }'""" - }, - "python_example": { - "description": "Example using Python requests", - "code": """import requests - + }, + "python_example": { + "description": "Example using Python requests", + "code": """import requests # API endpoint url = "http://localhost:8000/adapt" - # Request data data = { "content": "Your educational content here...", @@ -2224,19 +850,17 @@ data = { "complexity": "intermediate", # beginner, intermediate, advanced "format": "html" # html or text } - # Make request response = requests.post(url, json=data) result = response.json() - # Use adapted content print("Adapted content:", result["adapted_content"]) print("Gamification:", result["gamification"]) print("Processing time:", result["processing_time"])""" - }, - "javascript_example": { - "description": "Example using JavaScript fetch", - "code": """// API request + }, + "javascript_example": { + "description": "Example using JavaScript fetch", + "code": """// API request const response = await fetch('http://localhost:8000/adapt', { method: 'POST', headers: { @@ -2250,208 +874,160 @@ const response = await fetch('http://localhost:8000/adapt', { format: 'html' }) }); - const result = await response.json(); - // Use the adapted content console.log('Adapted:', result.adapted_content); console.log('Gamification:', result.gamification);""" - }, - "react_example": { - "description": "Example React component", - "code": """import React, { useState } from 'react'; - -function InclusiveEduAPI() { - const [content, setContent] = useState(''); - const [result, setResult] = useState(null); - const [loading, setLoading] = useState(false); - - const adaptContent = async () => { - setLoading(true); - try { - const response = await fetch('/adapt', { - method: 'POST', - headers: { 'Content-Type': 'application/json' }, - body: JSON.stringify({ - content, - profile: 'visual_structure', - interests: ['technology'], - complexity: 'intermediate' - }) - }); - const data = await response.json(); - setResult(data); - } catch (error) { - console.error('Error:', error); - } - setLoading(false); - }; - - return ( -
-