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 (
-
- );
-}"""
+ }
}
- }
# ============================================================================
-# 6. GRADIO INTERFACE - ENHANCED WITH API INTEGRATION
+# 7. GRADIO INTERFACE
# ============================================================================
-class GradioInterface:
- """Enhanced Gradio interface with API integration info"""
-
- def __init__(self):
- print("๐ Initializing Enhanced Gradio interface...")
- self.ai_config, self.pipeline = initialize_global_instances()
- 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"
+if GRADIO_AVAILABLE:
+ class GradioInterface:
+ """Enhanced Gradio interface with API integration info"""
+
+ def __init__(self):
+ print("๐ Initializing Enhanced Gradio interface...")
+ self.ai_config, self.pipeline = initialize_global_instances()
+ 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"""
- profile_key = profile_map.get(profile_name, "visual_structure")
- interests = [i.strip() for i in interests_text.split(',') if i.strip()]
+ if not content or not content.strip():
+ return (
+ ""
+ "
โ ๏ธ Input Required
"
+ "
Please enter some educational content to adapt for different learning styles.
"
+ "
",
+ "", "", ""
+ )
- # Perform adaptation
- result = self.pipeline.adapt_content(
- content=content.strip(),
- profile_key=profile_key,
- interests=interests,
- complexity=complexity
- )
+ 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
- # Update session stats
- self._update_session_stats(result)
+ profile_used = result.get("profile_used", "unknown")
+ if profile_used in self.session_stats["profiles_used"]:
+ self.session_stats["profiles_used"][profile_used] += 1
+ else:
+ self.session_stats["profiles_used"][profile_used] = 1
- # Format outputs for interface
- adapted_html = result['adapted_content']
+ self.session_stats["total_processing_time"] += result.get("processing_time", 0)
+
+ def _format_gamification_output(self, gamification):
+ """Format gamification information for display"""
- gamification_info = self._format_gamification_output(result['gamification'])
- processing_info = self._format_processing_output(result)
- stats_info = self._format_stats_output()
+ level = gamification.get("current_level", 1)
+ xp = gamification.get("xp_points", 0)
+ progress = gamification.get("progress_percentage", 0)
+ achievements = len(gamification.get("achievements", []))
- return adapted_html, gamification_info, processing_info, stats_info
+ 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"""
- except Exception as e:
- error_msg = f"โ Adaptation error: {str(e)}"
- print(f"Interface error: {e}")
+ 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""
- f"
โ Processing Error
"
- f"
An error occurred during content adaptation: {str(e)}
"
- f"
Please try again with different content or settings.
"
- f"
",
- "", "", ""
+ f"โก {processing_time:.2f}s processing | {ai_status} | "
+ f"๐ฏ {profile} profile | {success}"
)
-
- 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
- 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}"
- )
-
- 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"
+ 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 f"""
+ 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_AVAILABLE and 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}
@@ -2460,7 +1036,7 @@ class GradioInterface:
**Session:** {self.session_stats['adaptations']} adaptations completed
## ๐ API Integration
-**API Status:** โ
Active and ready
+**API Status:** {'โ
Active and ready' if FASTAPI_AVAILABLE else 'โ FastAPI not available'}
**Base URL:** `{base_url}`
**Documentation:** `{base_url}/docs`
**Health Check:** `{base_url}/health`
@@ -2483,22 +1059,30 @@ class GradioInterface:
โ
Interest-based personalization
โ
Accessibility features
โ
Progress tracking and gamification
-โ
**REST API for external access**
+{'โ
**REST API for external access**' if FASTAPI_AVAILABLE else 'โ **REST API disabled (FastAPI not available)**'}
โ
**Gradio web interface**
- """
-
- 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"""
+ def get_api_examples_display(self):
+ """Get API examples for display in Gradio"""
+
+ if not FASTAPI_AVAILABLE:
+ return """
+## ๐ API Not Available
+FastAPI is not installed. To enable API functionality, install FastAPI:
+```bash
+pip install fastapi uvicorn
+```
+ """
+
+ base_url = "http://localhost:8000" if "SPACE_ID" not in os.environ else "https://your-space.hf.space"
+
+ return f"""
## ๐ API Usage Examples
### Python Example
```python
import requests
-
url = "{base_url}/adapt"
data = {{
"content": "Your educational content here...",
@@ -2507,10 +1091,8 @@ data = {{
"complexity": "intermediate",
"format": "html"
}}
-
response = requests.post(url, json=data)
result = response.json()
-
print("Adapted:", result["adapted_content"])
print("Gamification:", result["gamification"])
```
@@ -2527,7 +1109,6 @@ const response = await fetch('{base_url}/adapt', {{
complexity: 'intermediate'
}})
}});
-
const result = await response.json();
console.log('Adapted:', result.adapted_content);
```
@@ -2564,4 +1145,359 @@ curl -X POST "{base_url}/adapt" \\
"success": true
}}
```
- """
\ No newline at end of file
+ """
+
+ def create_gradio_interface():
+ """Create the main Gradio interface"""
+
+ print("๐จ Creating Gradio interface...")
+
+ try:
+ interface = GradioInterface()
+
+ # Get profile options
+ profile_options = [profile["name"] for profile in interface.pipeline.profile_system.profiles.values()]
+
+ # Create the interface
+ with gr.Blocks(
+ title="๐ง InclusiveEdu - Neurodiverse Learning Platform",
+ theme=gr.themes.Soft(),
+ css="""
+ .gradio-container {
+ max-width: 1200px !important;
+ margin: 0 auto !important;
+ }
+ .main-header {
+ text-align: center;
+ background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
+ color: white;
+ padding: 2rem;
+ border-radius: 15px;
+ margin-bottom: 2rem;
+ }
+ """
+ ) as demo:
+
+ # Header
+ gr.HTML("""
+
+
๐ง InclusiveEdu
+
AI-Powered Neurodiverse Learning Content Adaptation
+
Transform educational content to match different learning styles and neurodivergent needs
+
+ """)
+
+ with gr.Tab("๐ฏ Content Adaptation") as main_tab:
+ with gr.Row():
+ with gr.Column(scale=2):
+ gr.Markdown("### ๐ Input Content")
+ content_input = gr.Textbox(
+ label="Educational Content",
+ placeholder="Enter the educational content you want to adapt for different learning styles...",
+ lines=8,
+ max_lines=15
+ )
+
+ with gr.Row():
+ profile_select = gr.Dropdown(
+ choices=profile_options,
+ value=profile_options[0],
+ label="๐ฏ Learning Profile",
+ info="Select the neurodiverse learning profile for adaptation"
+ )
+
+ complexity_select = gr.Dropdown(
+ choices=["beginner", "intermediate", "advanced"],
+ value="intermediate",
+ label="๐ Complexity Level",
+ info="Choose the appropriate difficulty level"
+ )
+
+ interests_input = gr.Textbox(
+ label="๐จ Interests (comma-separated)",
+ placeholder="technology, science, art, music, gaming, sports...",
+ info="Personal interests to integrate into the content"
+ )
+
+ adapt_btn = gr.Button(
+ "๐ Adapt Content",
+ variant="primary",
+ size="lg"
+ )
+
+ with gr.Column(scale=3):
+ gr.Markdown("### โจ Adapted Content")
+ adapted_output = gr.HTML(
+ label="Adapted Learning Content",
+ value="Enter content and click 'Adapt Content' to see the personalized version
"
+ )
+
+ # Status displays
+ with gr.Row():
+ gamification_status = gr.Textbox(
+ label="๐ฎ Gamification Status",
+ interactive=False,
+ max_lines=1
+ )
+
+ processing_status = gr.Textbox(
+ label="โก Processing Info",
+ interactive=False,
+ max_lines=1
+ )
+
+ session_status = gr.Textbox(
+ label="๐ Session Stats",
+ interactive=False,
+ max_lines=1
+ )
+
+ # Connect the adaptation function
+ adapt_btn.click(
+ fn=interface.adapt_content_interface,
+ inputs=[content_input, profile_select, interests_input, complexity_select],
+ outputs=[adapted_output, gamification_status, processing_status, session_status]
+ )
+
+ with gr.Tab("๐ง System Status") as status_tab:
+ gr.Markdown(interface.get_system_status())
+
+ with gr.Tab("๐ API Examples") as api_tab:
+ gr.Markdown(interface.get_api_examples_display())
+
+ with gr.Tab("๐ About Profiles") as profiles_tab:
+ with gr.Row():
+ for profile_key, profile in interface.pipeline.profile_system.profiles.items():
+ with gr.Column():
+ gr.Markdown(f"""
+### {profile['name']}
+**{profile['description']}**
+
+**Characteristics:**
+{chr(10).join([f"โข {char}" for char in profile['characteristics']])}
+
+**Best for:**
+{chr(10).join([f"โข {best}" for best in profile['best_for']])}
+ """)
+
+ # Footer
+ gr.HTML("""
+
+
๐ง InclusiveEdu - Empowering neurodiverse learners through AI-adapted content
+
Supporting Visual Structure, Directed Hyperfocus, Sensory Adaptation, and Special Interest learning styles
+
+ """)
+
+ return demo
+
+ except Exception as e:
+ print(f"โ Gradio interface creation error: {e}")
+ # Create emergency fallback interface
+ return create_emergency_interface()
+
+ def create_emergency_interface():
+ """Create emergency fallback interface"""
+
+ print("๐จ Creating emergency fallback interface...")
+
+ with gr.Blocks(title="InclusiveEdu - Emergency Mode") as demo:
+ gr.HTML("""
+
+
๐จ InclusiveEdu - Emergency Mode
+
The system is running in emergency mode. Basic functionality is available.
+
+ """)
+
+ with gr.Row():
+ with gr.Column():
+ content_input = gr.Textbox(
+ label="Content",
+ placeholder="Enter educational content...",
+ lines=5
+ )
+
+ def emergency_adapt(content):
+ if not content:
+ return "Please enter some content to adapt.
"
+
+ return f"""
+
+
๐ Emergency Adaptation
+
Original Content:
+
+ {content}
+
+
โ
Content processed in emergency mode. Full features will be available when the system is fully operational.
+
+ """
+
+ adapt_btn = gr.Button("Adapt Content", variant="primary")
+
+ with gr.Column():
+ output = gr.HTML()
+
+ adapt_btn.click(
+ fn=emergency_adapt,
+ inputs=[content_input],
+ outputs=[output]
+ )
+
+ gr.HTML("""
+
+
Emergency Mode Active - Please check system logs for more information
+
+ """)
+
+ return demo
+
+# ============================================================================
+# 8. MAIN APPLICATION LAUNCHER
+# ============================================================================
+
+def main():
+ """Main application launcher"""
+
+ print("="*70)
+ print("๐ง InclusiveEdu - Neurodiverse Education Platform")
+ print("โ
Fixed version with proper error handling")
+ print("๐ฏ Compatible with Hugging Face Spaces + External API")
+ print("="*70)
+
+ print("๐ Starting InclusiveEdu - Enhanced with API Integration...")
+ print("="*70)
+
+ # System information
+ print("๐ System Information:")
+ print("๐ Python: Ready")
+ if TORCH_AVAILABLE:
+ print(f"๐ฅ PyTorch: {torch.__version__}")
+ else:
+ print("๐ฅ PyTorch: Not available")
+ print(f"๐จ Gradio: {'Available' if GRADIO_AVAILABLE else 'Not available'}")
+ print(f"๐ FastAPI: {'Available' if FASTAPI_AVAILABLE else 'Not available'}")
+ print(f"๐ฅ๏ธ Device: {'๐ GPU' if TORCH_AVAILABLE and torch.cuda.is_available() else '๐ป CPU Mode'}")
+
+ # Initialize global instances
+ try:
+ print("\n๐ง Initializing system...")
+ initialize_global_instances()
+ print("โ
System initialization successful!")
+ except Exception as e:
+ print(f"โ System initialization error: {e}")
+ print("โ ๏ธ Continuing with emergency mode...")
+
+ # Determine execution mode
+ is_spaces = "SPACE_ID" in os.environ
+
+ if is_spaces:
+ print("\n๐ค Hugging Face Spaces detected - using Gradio mode")
+ mode = "gradio"
+ else:
+ 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")
+
+ try:
+ choice = input("\nEnter choice (1-3, default=1): ").strip()
+ if choice == "2":
+ mode = "api"
+ elif choice == "3":
+ mode = "dual"
+ else:
+ mode = "gradio"
+ except:
+ mode = "gradio"
+
+ # Launch based on mode
+ if mode == "gradio":
+ if not GRADIO_AVAILABLE:
+ print("โ Gradio not available! Please install gradio.")
+ return
+
+ print("๐จ Starting Gradio Interface...")
+ try:
+ demo = create_gradio_interface()
+ print("๐ InclusiveEdu ready to launch!")
+
+ # Launch configuration
+ launch_kwargs = {
+ "server_name": "0.0.0.0",
+ "server_port": 7860,
+ "show_error": True,
+ "show_tips": True,
+ "enable_queue": True
+ }
+
+ if not is_spaces:
+ launch_kwargs["share"] = False
+ launch_kwargs["inbrowser"] = True
+
+ demo.launch(**launch_kwargs)
+
+ except Exception as e:
+ print(f"โ Gradio launch error: {e}")
+ print("๐จ Creating emergency interface...")
+ emergency_demo = create_emergency_interface()
+ emergency_demo.launch(
+ server_name="0.0.0.0",
+ server_port=7860,
+ show_error=True
+ )
+
+ elif mode == "api":
+ if not FASTAPI_AVAILABLE:
+ print("โ FastAPI not available! Please install fastapi and uvicorn.")
+ return
+
+ print("๐ Starting API Server only...")
+ import uvicorn
+ uvicorn.run(
+ api,
+ host="0.0.0.0",
+ port=8000,
+ reload=False,
+ log_level="info"
+ )
+
+ elif mode == "dual":
+ if not (GRADIO_AVAILABLE and FASTAPI_AVAILABLE):
+ print("โ Both Gradio and FastAPI required for dual mode!")
+ return
+
+ print("๐ Starting Dual Mode: Gradio + API...")
+ import threading
+ import uvicorn
+
+ # Start API server in background thread
+ def start_api():
+ uvicorn.run(
+ api,
+ host="0.0.0.0",
+ port=8000,
+ reload=False,
+ log_level="warning"
+ )
+
+ api_thread = threading.Thread(target=start_api, daemon=True)
+ api_thread.start()
+
+ print("โ
API server starting on http://localhost:8000")
+ time.sleep(2) # Give API time to start
+
+ # Start Gradio interface
+ demo = create_gradio_interface()
+ print("๐ InclusiveEdu ready - Dual mode active!")
+ print("๐จ Gradio: http://localhost:7860")
+ print("๐ API: http://localhost:8000")
+ print("๐ API Docs: http://localhost:8000/docs")
+
+ demo.launch(
+ server_name="0.0.0.0",
+ server_port=7860,
+ show_error=True,
+ inbrowser=True
+ )
+
+if __name__ == "__main__":
+ main()
\ No newline at end of file