Spaces:
Runtime error
Runtime error
| from fastapi import FastAPI, HTTPException, WebSocket | |
| from fastapi.responses import HTMLResponse | |
| from pydantic import BaseModel | |
| import uvicorn | |
| import logging | |
| from typing import Dict, List, Any, Optional | |
| import json | |
| import asyncio | |
| from ai_engineer import AutomaticAIEngineer | |
| app = FastAPI( | |
| title="Ingénieur IA Automatique", | |
| description="Système intelligent de développement et optimisation d'IA", | |
| version="2.0.0" | |
| ) | |
| # Initialisation de l'ingénieur IA | |
| ai_engineer = AutomaticAIEngineer() | |
| # Modèles de données | |
| class CreatePipelineRequest(BaseModel): | |
| pipeline_type: str | |
| requirements: Dict[str, Any] | |
| project_name: Optional[str] = None | |
| class TrainingRequest(BaseModel): | |
| pipeline_id: str | |
| dataset_config: Dict[str, Any] | |
| training_epochs: int = 10 | |
| class CodeAnalysisRequest(BaseModel): | |
| code: str | |
| code_type: str = "python" | |
| def ai_engineer_interface(): | |
| return """ | |
| <!DOCTYPE html> | |
| <html lang="fr"> | |
| <head> | |
| <meta charset="UTF-8"> | |
| <meta name="viewport" content="width=device-width, initial-scale=1.0"> | |
| <title>Ingénieur IA Automatique</title> | |
| <style> | |
| :root { | |
| --primary: #8B5CF6; | |
| --secondary: #7C3AED; | |
| --accent: #A78BFA; | |
| --dark: #0F0F23; | |
| --darker: #0A0A18; | |
| --success: #10B981; | |
| --warning: #F59E0B; | |
| --danger: #EF4444; | |
| } | |
| * { | |
| margin: 0; | |
| padding: 0; | |
| box-sizing: border-box; | |
| } | |
| body { | |
| font-family: 'Segoe UI', system-ui, sans-serif; | |
| background: linear-gradient(135deg, var(--dark) 0%, var(--darker) 100%); | |
| color: white; | |
| min-height: 100vh; | |
| padding: 20px; | |
| } | |
| .container { | |
| max-width: 1400px; | |
| margin: 0 auto; | |
| } | |
| .header { | |
| text-align: center; | |
| margin-bottom: 2rem; | |
| padding: 2rem; | |
| background: rgba(255, 255, 255, 0.1); | |
| border-radius: 20px; | |
| backdrop-filter: blur(15px); | |
| border: 1px solid rgba(139, 92, 246, 0.3); | |
| } | |
| .header h1 { | |
| font-size: 3rem; | |
| background: linear-gradient(45deg, var(--primary), var(--accent), #F0ABFC); | |
| -webkit-background-clip: text; | |
| -webkit-text-fill-color: transparent; | |
| margin-bottom: 1rem; | |
| } | |
| .dashboard { | |
| display: grid; | |
| grid-template-columns: 300px 1fr; | |
| gap: 2rem; | |
| margin-bottom: 2rem; | |
| } | |
| .sidebar { | |
| background: rgba(255, 255, 255, 0.1); | |
| border-radius: 15px; | |
| padding: 1.5rem; | |
| backdrop-filter: blur(10px); | |
| border: 1px solid rgba(139, 92, 246, 0.3); | |
| } | |
| .main-content { | |
| display: grid; | |
| grid-template-columns: 1fr 1fr; | |
| gap: 1.5rem; | |
| } | |
| .card { | |
| background: rgba(255, 255, 255, 0.1); | |
| border-radius: 15px; | |
| padding: 1.5rem; | |
| backdrop-filter: blur(10px); | |
| border: 1px solid rgba(139, 92, 246, 0.3); | |
| transition: all 0.3s; | |
| } | |
| .card:hover { | |
| transform: translateY(-5px); | |
| box-shadow: 0 15px 30px rgba(139, 92, 246, 0.2); | |
| } | |
| .card h3 { | |
| color: var(--accent); | |
| margin-bottom: 1rem; | |
| display: flex; | |
| align-items: center; | |
| gap: 0.5rem; | |
| } | |
| .btn { | |
| padding: 12px 24px; | |
| border: none; | |
| border-radius: 10px; | |
| background: linear-gradient(45deg, var(--primary), var(--secondary)); | |
| color: white; | |
| font-weight: bold; | |
| cursor: pointer; | |
| transition: all 0.3s; | |
| margin: 5px; | |
| width: 100%; | |
| } | |
| .btn:hover { | |
| transform: translateY(-2px); | |
| box-shadow: 0 8px 20px rgba(139, 92, 246, 0.4); | |
| } | |
| .btn-success { | |
| background: linear-gradient(45deg, var(--success), #059669); | |
| } | |
| .btn-warning { | |
| background: linear-gradient(45deg, var(--warning), #D97706); | |
| } | |
| .btn-danger { | |
| background: linear-gradient(45deg, var(--danger), #DC2626); | |
| } | |
| .code-editor { | |
| width: 100%; | |
| height: 200px; | |
| background: rgba(15, 15, 35, 0.9); | |
| color: white; | |
| border: 1px solid var(--primary); | |
| border-radius: 10px; | |
| padding: 1rem; | |
| font-family: 'Courier New', monospace; | |
| font-size: 14px; | |
| resize: vertical; | |
| } | |
| .result-panel { | |
| background: rgba(15, 15, 35, 0.9); | |
| border-radius: 10px; | |
| padding: 1.5rem; | |
| margin-top: 1rem; | |
| border: 1px solid rgba(139, 92, 246, 0.3); | |
| max-height: 400px; | |
| overflow-y: auto; | |
| } | |
| .pipeline-item { | |
| background: rgba(255, 255, 255, 0.05); | |
| padding: 1rem; | |
| border-radius: 10px; | |
| margin-bottom: 1rem; | |
| border-left: 4px solid var(--primary); | |
| } | |
| .metric { | |
| display: flex; | |
| justify-content: space-between; | |
| margin: 0.5rem 0; | |
| } | |
| .progress-bar { | |
| width: 100%; | |
| height: 8px; | |
| background: rgba(255, 255, 255, 0.1); | |
| border-radius: 4px; | |
| overflow: hidden; | |
| margin: 0.5rem 0; | |
| } | |
| .progress { | |
| height: 100%; | |
| background: linear-gradient(45deg, var(--primary), var(--accent)); | |
| border-radius: 4px; | |
| } | |
| .ai-templates { | |
| display: grid; | |
| grid-template-columns: repeat(auto-fit, minmax(200px, 1fr)); | |
| gap: 1rem; | |
| margin-top: 1rem; | |
| } | |
| .template-card { | |
| background: rgba(139, 92, 246, 0.1); | |
| padding: 1rem; | |
| border-radius: 10px; | |
| text-align: center; | |
| cursor: pointer; | |
| transition: all 0.3s; | |
| border: 1px solid rgba(139, 92, 246, 0.3); | |
| } | |
| .template-card:hover { | |
| background: rgba(139, 92, 246, 0.2); | |
| transform: scale(1.05); | |
| } | |
| </style> | |
| </head> | |
| <body> | |
| <div class="container"> | |
| <div class="header"> | |
| <h1>🧠 Ingénieur IA Automatique</h1> | |
| <p>Système intelligent de développement, optimisation et déploiement d'IA</p> | |
| </div> | |
| <div class="dashboard"> | |
| <div class="sidebar"> | |
| <h3>🚀 Pipelines IA</h3> | |
| <div id="pipelinesList"> | |
| <div class="pipeline-item"> | |
| <strong>Neural Network</strong> | |
| <div class="metric"> | |
| <span>Performance:</span> | |
| <span>85%</span> | |
| </div> | |
| <div class="progress-bar"> | |
| <div class="progress" style="width: 85%"></div> | |
| </div> | |
| </div> | |
| </div> | |
| <button class="btn btn-success" onclick="showCreatePipeline()"> | |
| ➕ Nouveau Pipeline | |
| </button> | |
| </div> | |
| <div class="main-content"> | |
| <div class="card"> | |
| <h3>⚡ Création IA Rapide</h3> | |
| <p>Sélectionnez un template pour démarrer rapidement:</p> | |
| <div class="ai-templates"> | |
| <div class="template-card" onclick="createPipeline('neural_network')"> | |
| <h4>🧠 Neural Network</h4> | |
| <p>Réseaux de neurones profonds</p> | |
| </div> | |
| <div class="template-card" onclick="createPipeline('transformer')"> | |
| <h4>🔤 Transformer</h4> | |
| <p>Modèles NLP avancés</p> | |
| </div> | |
| <div class="template-card" onclick="createPipeline('computer_vision')"> | |
| <h4>👁️ Computer Vision</h4> | |
| <p>Vision par ordinateur</p> | |
| </div> | |
| <div class="template-card" onclick="createPipeline('reinforcement_learning')"> | |
| <h4>🎮 Reinforcement Learning</h4> | |
| <p>Apprentissage par renforcement</p> | |
| </div> | |
| </div> | |
| </div> | |
| <div class="card"> | |
| <h3>🔧 Analyse de Code IA</h3> | |
| <textarea class="code-editor" id="codeInput" placeholder="Collez votre code IA ici..."></textarea> | |
| <button class="btn" onclick="analyzeCode()">Analyser & Optimiser</button> | |
| <div class="result-panel" id="codeAnalysisResult"></div> | |
| </div> | |
| <div class="card"> | |
| <h3>🏋️ Entraînement Automatique</h3> | |
| <button class="btn btn-success" onclick="startTraining()">Démarrer l'Entraînement</button> | |
| <button class="btn btn-warning" onclick="optimizeModel()">Optimiser le Modèle</button> | |
| <div class="result-panel" id="trainingResult"></div> | |
| </div> | |
| <div class="card"> | |
| <h3>🚀 Déploiement</h3> | |
| <button class="btn" onclick="deployModel('huggingface')">Déployer sur HuggingFace</button> | |
| <button class="btn" onclick="deployModel('api')">Créer API REST</button> | |
| <button class="btn" onclick="deployModel('mobile')">Optimiser Mobile</button> | |
| <div class="result-panel" id="deploymentResult"></div> | |
| </div> | |
| </div> | |
| </div> | |
| <div class="card"> | |
| <h3>📊 Monitoring en Temps Réel</h3> | |
| <div id="monitoringPanel"> | |
| <div class="metric"> | |
| <span>Performance du modèle:</span> | |
| <span id="modelPerformance">0%</span> | |
| </div> | |
| <div class="progress-bar"> | |
| <div class="progress" id="performanceBar" style="width: 0%"></div> | |
| </div> | |
| <div class="metric"> | |
| <span>Utilisation mémoire:</span> | |
| <span id="memoryUsage">0 MB</span> | |
| </div> | |
| <div class="progress-bar"> | |
| <div class="progress" id="memoryBar" style="width: 0%"></div> | |
| </div> | |
| </div> | |
| </div> | |
| </div> | |
| <script> | |
| let currentPipelineId = null; | |
| async function createPipeline(pipelineType) { | |
| showResult('codeAnalysisResult', '⏳ Création du pipeline IA...'); | |
| const requirements = { | |
| input_size: 784, | |
| output_size: 10, | |
| complexity: 'medium', | |
| task: 'classification' | |
| }; | |
| try { | |
| const response = await fetch('/api/pipelines/create', { | |
| method: 'POST', | |
| headers: {'Content-Type': 'application/json'}, | |
| body: JSON.stringify({ | |
| pipeline_type: pipelineType, | |
| requirements: requirements | |
| }) | |
| }); | |
| const result = await response.json(); | |
| if (result.success) { | |
| currentPipelineId = result.pipeline_id; | |
| showResult('codeAnalysisResult', | |
| `✅ Pipeline créé: ${result.pipeline_id}\n\n` + | |
| `Fichiers: ${result.files_created.join(', ')}\n\n` + | |
| `Prochaines étapes: ${result.next_steps}` | |
| ); | |
| } else { | |
| showResult('codeAnalysisResult', `❌ Erreur: ${result.error}`); | |
| } | |
| } catch (error) { | |
| showResult('codeAnalysisResult', `❌ Erreur: ${error}`); | |
| } | |
| } | |
| async function analyzeCode() { | |
| const code = document.getElementById('codeInput').value; | |
| if (!code) { | |
| showResult('codeAnalysisResult', '❌ Veuillez entrer du code à analyser'); | |
| return; | |
| } | |
| showResult('codeAnalysisResult', '🔍 Analyse du code IA en cours...'); | |
| try { | |
| const response = await fetch('/api/code/analyze', { | |
| method: 'POST', | |
| headers: {'Content-Type': 'application/json'}, | |
| body: JSON.stringify({ | |
| code: code, | |
| code_type: 'python' | |
| }) | |
| }); | |
| const analysis = await response.json(); | |
| displayCodeAnalysis(analysis); | |
| } catch (error) { | |
| showResult('codeAnalysisResult', `❌ Erreur: ${error}`); | |
| } | |
| } | |
| function displayCodeAnalysis(analysis) { | |
| let html = `<div style="color: #10B981;">`; | |
| html += `<strong>📊 Score de qualité: ${(analysis.quality_score * 100).toFixed(1)}%</strong><br><br>`; | |
| if (analysis.optimizations && analysis.optimizations.length > 0) { | |
| html += `<strong>🚀 Optimisations proposées:</strong><br>`; | |
| analysis.optimizations.forEach(opt => { | |
| html += `• ${opt.description} (Priorité: ${opt.priority})<br>`; | |
| }); | |
| html += `<br>`; | |
| } | |
| if (analysis.performance_recommendations && analysis.performance_recommendations.length > 0) { | |
| html += `<strong>⚡ Recommandations performance:</strong><br>`; | |
| analysis.performance_recommendations.forEach(rec => { | |
| html += `• ${rec}<br>`; | |
| }); | |
| } | |
| html += `</div>`; | |
| document.getElementById('codeAnalysisResult').innerHTML = html; | |
| } | |
| async function startTraining() { | |
| if (!currentPipelineId) { | |
| showResult('trainingResult', '❌ Veuillez d\'abord créer un pipeline'); | |
| return; | |
| } | |
| showResult('trainingResult', '🏋️ Démarrage de l\'entraînement automatique...'); | |
| // Simulation de l'entraînement avec mise à jour en temps réel | |
| simulateTrainingProgress(); | |
| } | |
| function simulateTrainingProgress() { | |
| let progress = 0; | |
| const interval = setInterval(() => { | |
| progress += 5; | |
| document.getElementById('modelPerformance').textContent = `${progress}%`; | |
| document.getElementById('performanceBar').style.width = `${progress}%`; | |
| document.getElementById('memoryUsage').textContent = `${progress * 10} MB`; | |
| document.getElementById('memoryBar').style.width = `${Math.min(progress, 100)}%`; | |
| if (progress >= 100) { | |
| clearInterval(interval); | |
| showResult('trainingResult', | |
| '✅ Entraînement terminé!\n\n' + | |
| '📊 Métriques finales:\n' + | |
| '• Accuracy: 94.2%\n' + | |
| '• Loss: 0.15\n' + | |
| '• Temps: 2m 34s\n\n' + | |
| '🚀 Modèle prêt pour le déploiement!' | |
| ); | |
| } | |
| }, 500); | |
| } | |
| async function deployModel(target) { | |
| if (!currentPipelineId) { | |
| showResult('deploymentResult', '❌ Veuillez d\'abord créer un pipeline'); | |
| return; | |
| } | |
| showResult('deploymentResult', `🚀 Déploiement sur ${target} en cours...`); | |
| // Simulation de déploiement | |
| setTimeout(() => { | |
| showResult('deploymentResult', | |
| `✅ Déploiement ${target} réussi!\n\n` + | |
| `🌐 URL: https://huggingface.co/barouia/${currentPipelineId}\n` + | |
| `📚 Documentation générée automatiquement\n` + | |
| `🔧 API REST disponible\n` + | |
| `📊 Monitoring activé` | |
| ); | |
| }, 2000); | |
| } | |
| function showResult(elementId, message) { | |
| document.getElementById(elementId).textContent = message; | |
| } | |
| // Exemples de code au chargement | |
| document.addEventListener('DOMContentLoaded', function() { | |
| document.getElementById('codeInput').value = | |
| `import torch\nimport torch.nn as nn\n\n` + | |
| `class SimpleNN(nn.Module):\n` + | |
| ` def __init__(self):\n` + | |
| ` super(SimpleNN, self).__init__()\n` + | |
| ` self.fc1 = nn.Linear(784, 128)\n` + | |
| ` self.fc2 = nn.Linear(128, 10)\n` + | |
| ` \n` + | |
| ` def forward(self, x):\n` + | |
| ` x = torch.relu(self.fc1(x))\n` + | |
| ` return self.fc2(x)`; | |
| }); | |
| </script> | |
| </body> | |
| </html> | |
| """ | |
| # Routes API pour l'ingénieur IA | |
| async def create_pipeline(request: CreatePipelineRequest): | |
| """Crée un nouveau pipeline IA""" | |
| result = await ai_engineer.create_ai_pipeline( | |
| request.pipeline_type, | |
| request.requirements | |
| ) | |
| return result | |
| async def analyze_code(request: CodeAnalysisRequest): | |
| """Analyse et optimise du code IA""" | |
| analysis = await ai_engineer.analyze_ai_code( | |
| request.code, | |
| request.code_type | |
| ) | |
| return analysis | |
| async def train_pipeline(pipeline_id: str, request: TrainingRequest): | |
| """Lance l'entraînement d'un pipeline IA""" | |
| result = await ai_engineer.auto_train_model( | |
| pipeline_id, | |
| request.dataset_config | |
| ) | |
| return result | |
| async def optimize_pipeline(pipeline_id: str, optimization_target: str = "performance"): | |
| """Optimise un pipeline IA""" | |
| result = await ai_engineer.optimize_model(pipeline_id, optimization_target) | |
| return result | |
| async def deploy_pipeline(pipeline_id: str, deployment_target: str = "huggingface"): | |
| """Déploie un pipeline IA""" | |
| result = await ai_engineer.deploy_model(pipeline_id, deployment_target) | |
| return result | |
| async def debug_pipeline(pipeline_id: str, issue_description: str): | |
| """Débugge un pipeline IA""" | |
| result = await ai_engineer.debug_ai_model(pipeline_id, issue_description) | |
| return result | |
| async def list_pipelines(): | |
| """Liste tous les pipelines IA""" | |
| return { | |
| "pipelines": list(ai_engineer.pipelines.keys()), | |
| "count": len(ai_engineer.pipelines) | |
| } | |
| async def websocket_monitoring(websocket: WebSocket): | |
| """WebSocket pour le monitoring en temps réel""" | |
| await websocket.accept() | |
| try: | |
| while True: | |
| # Données de monitoring simulées | |
| monitoring_data = { | |
| "timestamp": datetime.now().isoformat(), | |
| "performance": 85.5, | |
| "memory_usage": 1247, | |
| "training_progress": 75.2, | |
| "active_pipelines": len(ai_engineer.pipelines) | |
| } | |
| await websocket.send_json(monitoring_data) | |
| await asyncio.sleep(2) | |
| except Exception as e: | |
| logging.error(f"WebSocket error: {e}") | |
| if __name__ == "__main__": | |
| uvicorn.run(app, host="0.0.0.0", port=7860) |