Spaces:
Runtime error
Runtime error
File size: 22,673 Bytes
992a63e | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 | 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"
@app.get("/", response_class=HTMLResponse)
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
@app.post("/api/pipelines/create")
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
@app.post("/api/code/analyze")
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
@app.post("/api/pipelines/{pipeline_id}/train")
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
@app.post("/api/pipelines/{pipeline_id}/optimize")
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
@app.post("/api/pipelines/{pipeline_id}/deploy")
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
@app.post("/api/pipelines/{pipeline_id}/debug")
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
@app.get("/api/pipelines")
async def list_pipelines():
"""Liste tous les pipelines IA"""
return {
"pipelines": list(ai_engineer.pipelines.keys()),
"count": len(ai_engineer.pipelines)
}
@app.websocket("/ws/ai-monitoring")
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) |