File size: 21,429 Bytes
c96664a ed3694d c96664a a8f2815 c96664a 60f6561 c96664a 4c63ae2 c96664a a8f2815 c96664a ed3694d c96664a ed3694d c96664a ed3694d c96664a ed3694d c96664a 60f6561 c96664a ed3694d c96664a ed3694d c96664a ed3694d c96664a 3e0359e c96664a 3e0359e c96664a 3e0359e c96664a 3e0359e a5b9bcb 3e0359e a5b9bcb 3e0359e a5b9bcb 3509487 3e0359e a5b9bcb 3e0359e a5b9bcb 3e0359e a5b9bcb 3e0359e a5b9bcb 3e0359e a5b9bcb 3e0359e a5b9bcb c96664a ed3694d c96664a ed3694d c96664a ed3694d c96664a ed3694d c96664a ed3694d c96664a ed3694d c96664a bd74fdc c7caad9 bd74fdc 60f6561 bd74fdc 60f6561 bd74fdc 60f6561 bd74fdc 60f6561 bd74fdc 60f6561 bd74fdc 60f6561 defefdc bd74fdc 60f6561 bd74fdc 60f6561 bd74fdc 60f6561 bd74fdc 60f6561 bd74fdc c96664a | 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 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 | """
Wakee API - Production
ONNX Runtime UNIQUEMENT (pas de PyTorch)
"""
import os
os.environ["HUGGINGFACE_HUB_DISABLE_XET"] = "1"
from fastapi import FastAPI, File, UploadFile, HTTPException, Form
from fastapi.middleware.cors import CORSMiddleware
from pydantic import BaseModel, Field
from typing import List, Optional
from huggingface_hub import hf_hub_download
import onnxruntime as ort
import onnxscript
from PIL import Image
import io
import numpy as np
from datetime import datetime
import base64
from sqlalchemy import create_engine, text
from sqlalchemy.exc import SQLAlchemyError
import boto3
from botocore.exceptions import ClientError
# ============================================================================
# PREPROCESSING SANS PYTORCH (Pillow + numpy)
# ============================================================================
def preprocess_image(pil_image: Image.Image) -> np.ndarray:
"""
Preprocessing identique à ton cnn.py
SANS dépendance PyTorch (juste Pillow + numpy)
"""
# 1. Resize to 256x256
img = pil_image.resize((256, 256), Image.BILINEAR)
# 2. Center crop to 224x224
left = (256 - 224) // 2
top = (256 - 224) // 2
img = img.crop((left, top, left + 224, top + 224))
# 3. Convert to numpy array [0, 1]
img_array = np.array(img).astype(np.float32) / 255.0
# 4. ImageNet normalization
mean = np.array([0.485, 0.456, 0.406])
std = np.array([0.229, 0.224, 0.225])
img_array = (img_array - mean) / std
# 5. Transpose to CHW (channels, height, width)
img_array = np.transpose(img_array, (2, 0, 1))
# 6. Add batch dimension (1, 3, 224, 224)
img_array = np.expand_dims(img_array, axis=0).astype(np.float32)
return img_array
# ============================================================================
# CONFIGURATION
# ============================================================================
def load_env_vars():
"""Charge .env en local, utilise env vars en prod"""
is_production = os.getenv("SPACE_ID") is not None
if not is_production:
from pathlib import Path
try:
from dotenv import load_dotenv
root_dir = Path(__file__).resolve().parent.parent
dotenv_path = root_dir / '.env'
if dotenv_path.exists():
load_dotenv(dotenv_path)
print(f"✅ .env chargé depuis : {dotenv_path}")
except ImportError:
print("⚠️ python-dotenv non installé (OK en production)")
load_env_vars()
HF_MODEL_REPO = "Terorra/wakee-reloaded"
MODEL_FILENAME = "model.onnx"
NEON_DATABASE_URL = os.getenv("NEONDB_WR")
R2_ACCOUNT_ID = os.getenv("R2_ACCOUNT_ID")
R2_ACCESS_KEY_ID = os.getenv("R2_ACCESS_KEY_ID")
R2_SECRET_ACCESS_KEY = os.getenv("R2_SECRET_ACCESS_KEY")
R2_BUCKET_NAME = os.getenv("R2_WR_IMG_BUCKET_NAME", "wr-img-store")
# ============================================================================
# PYDANTIC MODELS
# ============================================================================
class PredictionResponse(BaseModel):
boredom: float = Field(..., ge=0, le=3)
confusion: float = Field(..., ge=0, le=3)
engagement: float = Field(..., ge=0, le=3)
frustration: float = Field(..., ge=0, le=3)
timestamp: str
# class AnnotationInsert(BaseModel):
# image_base64: str
# predicted_boredom: float = Field(..., ge=0, le=3)
# predicted_confusion: float = Field(..., ge=0, le=3)
# predicted_engagement: float = Field(..., ge=0, le=3)
# predicted_frustration: float = Field(..., ge=0, le=3)
# user_boredom: float = Field(..., ge=0, le=3)
# user_confusion: float = Field(..., ge=0, le=3)
# user_engagement: float = Field(..., ge=0, le=3)
# user_frustration: float = Field(..., ge=0, le=3)
class InsertResponse(BaseModel):
status: str
message: str
img_name: str
s3_url: Optional[str] = None
class LoadResponse(BaseModel):
total_samples: int
validated_samples: int
recent_predictions: List[dict]
statistics: dict
# ============================================================================
# FASTAPI APP
# ============================================================================
app = FastAPI(
title="Wakee Emotion API",
description="Multi-label emotion detection (ONNX Runtime)",
version="1.0.0",
docs_url="/docs",
redoc_url="/redoc"
)
app.add_middleware(
CORSMiddleware,
allow_origins=["*"],
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"],
)
# ============================================================================
# GLOBAL VARIABLES
# ============================================================================
onnx_session = None
db_engine = None
s3_client = None
# ============================================================================
# STARTUP
# ============================================================================
@app.on_event("startup")
async def startup_event():
global onnx_session, db_engine, s3_client
print("=" * 70)
print("🚀 DÉMARRAGE API WAKEE (ONNX Runtime)")
print("=" * 70)
onnx_session = None
try:
print("\n📥 Tentative chargement ONNX depuis HF...")
onnx_path = hf_hub_download(
repo_id=HF_MODEL_REPO,
filename="model.onnx",
cache_dir="/tmp/models"
)
# ✅ Vérifier la taille avant de charger
file_size_mb = os.path.getsize(onnx_path) / 1e6
print(f" ONNX file size: {file_size_mb:.2f} MB")
if file_size_mb < 10:
print(f"⚠️ ONNX file too small ({file_size_mb:.2f} MB), using fallback")
raise ValueError("ONNX file incomplete")
onnx_session = ort.InferenceSession(onnx_path)
print("✅ ONNX chargé directement")
except Exception as e:
print(f"⚠️ ONNX indisponible: {e}")
print("🔁 Fallback → PyTorch .bin → conversion ONNX...")
try:
# -------------------------
# 1. Download .bin
# -------------------------
bin_path = hf_hub_download(
repo_id=HF_MODEL_REPO,
filename="pytorch_model.bin",
cache_dir="/tmp/models"
)
# ✅ Vérifier la taille du .bin
bin_size_mb = os.path.getsize(bin_path) / 1e6
print(f" PyTorch .bin size: {bin_size_mb:.2f} MB")
# -------------------------
# 2. Charger PyTorch
# -------------------------
import torch
from torchvision import models
import torch.nn as nn
NUM_CLASSES = 4
DEVICE = "cpu"
model = models.efficientnet_b4(weights=None)
model.classifier[1] = nn.Linear(
model.classifier[1].in_features,
NUM_CLASSES
)
# ✅ CORRECTION : Ajouter weights_only=False
state_dict = torch.load(bin_path, map_location=DEVICE, weights_only=False)
# ✅ CORRECTION : Gérer les cas où state_dict est nested
if isinstance(state_dict, dict):
if 'model' in state_dict:
state_dict = state_dict['model']
elif 'state_dict' in state_dict:
state_dict = state_dict['state_dict']
model.load_state_dict(state_dict, strict=False)
model.eval()
print("✅ PyTorch chargé")
# -------------------------
# 3. Export ONNX local
# -------------------------
tmp_onnx = "/tmp/models/fallback_model.onnx"
dummy = torch.randn(1, 3, 224, 224)
# ✅ CORRECTION PRINCIPALE : do_constant_folding=True
torch.onnx.export(
model,
dummy,
tmp_onnx,
export_params=True, # ✅ OK
opset_version=17, # ✅ OK
do_constant_folding=True, # ✅ CHANGÉ : True au lieu de False !
input_names=["input"],
output_names=["output"],
dynamic_axes={ # ✅ AJOUTÉ : Pour batch dynamique
'input': {0: 'batch_size'},
'output': {0: 'batch_size'}
},
verbose=False
)
print("✅ Conversion ONNX locale OK")
# ✅ AJOUTÉ : Vérifier la taille du ONNX
onnx_size_mb = os.path.getsize(tmp_onnx) / 1e6
print(f" ONNX file size: {onnx_size_mb:.2f} MB")
if onnx_size_mb < 10:
raise ValueError(f"ONNX file too small ({onnx_size_mb:.2f} MB)! Weights not exported.")
# -------------------------
# 4. ORT session
# -------------------------
onnx_session = ort.InferenceSession(tmp_onnx)
# ✅ AJOUTÉ : Test que le modèle marche
test_input = np.random.randn(1, 3, 224, 224).astype(np.float32)
test_output = onnx_session.run(['output'], {'input': test_input})
print(f" Test inference OK, output shape: {test_output[0].shape}")
except Exception as e2:
print(f"❌ Fallback PyTorch échoué : {e2}")
onnx_session = None
if onnx_session:
input_name = onnx_session.get_inputs()[0].name
input_shape = onnx_session.get_inputs()[0].shape
print(f" Input : {input_name} {input_shape}\n")
# 2. Database
if NEON_DATABASE_URL:
try:
db_engine = create_engine(NEON_DATABASE_URL)
with db_engine.connect() as conn:
conn.execute(text("SELECT 1"))
print("✅ Connexion NeonDB établie\n")
except Exception as e:
print(f"⚠️ NeonDB non disponible : {e}\n")
db_engine = None
else:
print("⚠️ NEON_DATABASE_URL non défini\n")
# 3. Cloudflare R2
if all([R2_ACCOUNT_ID, R2_ACCESS_KEY_ID, R2_SECRET_ACCESS_KEY]):
try:
s3_client = boto3.client(
's3',
endpoint_url=f'https://{R2_ACCOUNT_ID}.r2.cloudflarestorage.com',
aws_access_key_id=R2_ACCESS_KEY_ID,
aws_secret_access_key=R2_SECRET_ACCESS_KEY,
region_name='auto'
)
s3_client.head_bucket(Bucket=R2_BUCKET_NAME)
print(f"✅ Connexion Cloudflare R2 (bucket: {R2_BUCKET_NAME})\n")
except Exception as e:
print(f"⚠️ Cloudflare R2 non disponible : {e}\n")
s3_client = None
else:
print("⚠️ R2 secrets non définis\n")
print("=" * 70)
print("🎉 API WAKEE PRÊTE !")
print("=" * 70)
print(f"📊 Status :")
print(f" - Modèle ONNX : {'✅' if onnx_session else '❌'}")
print(f" - Database : {'✅' if db_engine else '❌'}")
print(f" - Storage : {'✅' if s3_client else '❌'}")
print("=" * 70 + "\n")
# ============================================================================
# ENDPOINTS (identiques à avant)
# ============================================================================
@app.get("/")
async def root():
return {
"message": "Wakee Emotion API",
"version": "1.0.0",
"runtime": "ONNX Runtime (no PyTorch)",
"model_source": HF_MODEL_REPO
}
@app.get("/health")
async def health_check():
return {
"status": "healthy",
"model_loaded": onnx_session is not None,
"runtime": "ONNX",
"timestamp": datetime.now().isoformat()
}
@app.post("/predict", response_model=PredictionResponse)
async def predict_emotion(file: UploadFile = File(...)):
"""
Prédiction des 4 émotions depuis une image
⚠️ RIEN N'EST SAUVEGARDÉ à cette étape
L'utilisateur doit ensuite appeler /insert pour sauvegarder
"""
if not onnx_session:
raise HTTPException(
status_code=503,
detail="Model not loaded"
)
if not file.content_type.startswith('image/'):
raise HTTPException(status_code=400, detail="File must be an image")
try:
# 1. Load image
image_bytes = await file.read()
image = Image.open(io.BytesIO(image_bytes)).convert("RGB")
# 2. Preprocessing
input_tensor = preprocess_image(image)
# 3. Inference ONNX
outputs = onnx_session.run(['output'], {'input': input_tensor})
scores_array = outputs[0][0]
# raw = outputs[0][0]
# scores_array = 3.0 * (1 / (1 + np.exp(-raw)))
# 4. Format résultats
return PredictionResponse(
boredom=round(float(scores_array[0]), 2),
confusion=round(float(scores_array[1]), 2),
engagement=round(float(scores_array[2]), 2),
frustration=round(float(scores_array[3]), 2),
timestamp=datetime.now().isoformat()
)
# ⚠️ PAS de sauvegarde R2
# ⚠️ PAS de sauvegarde NeonDB
# → L'utilisateur décide s'il valide via /insert
except Exception as e:
print(f"❌ Erreur prédiction : {e}")
raise HTTPException(status_code=500, detail=str(e))
@app.post("/insert", response_model=InsertResponse)
async def insert_annotation(
file: UploadFile = File(...),
predicted_boredom: float = Form(...),
predicted_confusion: float = Form(...),
predicted_engagement: float = Form(...),
predicted_frustration: float = Form(...),
user_boredom: float = Form(...),
user_confusion: float = Form(...),
user_engagement: float = Form(...),
user_frustration: float = Form(...)
):
"""
Insert annotation utilisateur
NOUVEAU : Reçoit directement l'image (pas de base64)
"""
# Vérifications
if not db_engine:
raise HTTPException(status_code=503, detail="Database not available")
if not s3_client:
raise HTTPException(status_code=503, detail="Storage not available")
if not file.content_type.startswith('image/'):
raise HTTPException(status_code=400, detail="File must be an image")
try:
# 1. Lire l'image
image_bytes = await file.read()
# 2. Générer nom unique
timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
random_suffix = hash(image_bytes) % 10000
img_name = f"{timestamp}_{random_suffix:04d}.jpg"
s3_key = f"{img_name}"
# 3. Upload vers Cloudflare R2
print(f"📤 Upload vers R2 : {s3_key}")
try:
s3_client.put_object(
Bucket=R2_BUCKET_NAME,
Key=s3_key,
Body=image_bytes,
ContentType='image/jpeg'
)
print(f"✅ Upload R2 réussi : {img_name}")
except ClientError as e:
print(f"❌ Erreur upload R2 : {e}")
raise HTTPException(status_code=500, detail=f"R2 upload failed: {e}")
# 4. Insert dans NeonDB avec img_name
query = text("""
INSERT INTO emotion_labels
(img_name, s3_path,
predicted_boredom, predicted_confusion, predicted_engagement, predicted_frustration,
user_boredom, user_confusion, user_engagement, user_frustration,
source, is_validated, timestamp)
VALUES
(:img_name, :s3_path,
:pred_boredom, :pred_confusion, :pred_engagement, :pred_frustration,
:user_boredom, :user_confusion, :user_engagement, :user_frustration,
'app_sourcing', TRUE, :timestamp)
""")
with db_engine.connect() as conn:
conn.execute(query, {
'img_name': img_name,
's3_path': s3_key,
'pred_boredom': predicted_boredom,
'pred_confusion': predicted_confusion,
'pred_engagement': predicted_engagement,
'pred_frustration': predicted_frustration,
'user_boredom': user_boredom,
'user_confusion': user_confusion,
'user_engagement': user_engagement,
'user_frustration': user_frustration,
'timestamp': datetime.now()
})
conn.commit()
print(f"✅ Insert NeonDB réussi : {img_name}")
return InsertResponse(
status="success",
message="Image uploaded and labels saved",
img_name=img_name, # ← RETOURNÉ au frontend
s3_url=None
)
except SQLAlchemyError as e:
print(f"❌ Erreur NeonDB : {e}")
raise HTTPException(status_code=500, detail=f"Database error: {str(e)}")
except Exception as e:
print(f"❌ Erreur insert : {e}")
raise HTTPException(status_code=500, detail=str(e))
@app.get("/load", response_model=LoadResponse)
async def load_data(limit: int = 10):
"""
Charge les données depuis NeonDB
Retourne :
- Nombre total d'échantillons
- Nombre d'échantillons validés
- Dernières prédictions (avec corrections utilisateur)
- Statistiques globales
"""
if not db_engine:
raise HTTPException(status_code=503, detail="Database not available")
try:
with db_engine.connect() as conn:
# Total samples
total = conn.execute(text(
"SELECT COUNT(*) FROM emotion_labels"
)).scalar()
# Validated samples (ceux insérés via /insert)
validated = conn.execute(text(
"SELECT COUNT(*) FROM emotion_labels WHERE is_validated = TRUE"
)).scalar()
# Recent predictions
recent = conn.execute(text(f"""
SELECT
img_name,
s3_path,
predicted_boredom,
predicted_confusion,
predicted_engagement,
predicted_frustration,
user_boredom,
user_confusion,
user_engagement,
user_frustration,
timestamp
FROM emotion_labels
WHERE is_validated = TRUE
ORDER BY timestamp DESC
LIMIT :limit
"""), {'limit': limit}).fetchall()
recent_list = [
{
'img_name': row[0],
's3_path': row[1],
'predicted': {
'boredom': float(row[2]),
'confusion': float(row[3]),
'engagement': float(row[4]),
'frustration': float(row[5])
},
'user_corrected': {
'boredom': float(row[6]),
'confusion': float(row[7]),
'engagement': float(row[8]),
'frustration': float(row[9])
},
'timestamp': row[10].isoformat() if row[10] else None
}
for row in recent
]
# Statistics (moyennes)
stats = conn.execute(text("""
SELECT
AVG(predicted_boredom) as avg_pred_boredom,
AVG(predicted_confusion) as avg_pred_confusion,
AVG(predicted_engagement) as avg_pred_engagement,
AVG(predicted_frustration) as avg_pred_frustration,
AVG(user_boredom) as avg_user_boredom,
AVG(user_confusion) as avg_user_confusion,
AVG(user_engagement) as avg_user_engagement,
AVG(user_frustration) as avg_user_frustration
FROM emotion_labels
WHERE is_validated = TRUE
""")).fetchone()
statistics = {
'predictions': {
'boredom': round(float(stats[0] or 0), 2),
'confusion': round(float(stats[1] or 0), 2),
'engagement': round(float(stats[2] or 0), 2),
'frustration': round(float(stats[3] or 0), 2)
},
'user_corrections': {
'boredom': round(float(stats[4] or 0), 2),
'confusion': round(float(stats[5] or 0), 2),
'engagement': round(float(stats[6] or 0), 2),
'frustration': round(float(stats[7] or 0), 2)
}
}
return LoadResponse(
total_samples=total or 0,
validated_samples=validated or 0,
recent_predictions=recent_list,
statistics=statistics
)
except SQLAlchemyError as e:
raise HTTPException(status_code=500, detail=f"Database error: {str(e)}")
if __name__ == "__main__":
import uvicorn
uvicorn.run(app, host="0.0.0.0", port=8000) |