# routes/predict.py """ POST /predict?lang=en|fr Accepts multipart/form-data with a 'file' field (JPEG / PNG / WEBP). """ import queue import time import threading import cv2 import numpy as np from flask import Blueprint, request, jsonify from config.settings import ( MAX_FILE_SIZE, REQUEST_TIMEOUT, CLASS_TRANSLATIONS_EN, CLASS_TRANSLATIONS_FR, SKIN_TYPE_CLASSES_EN, SKIN_TYPE_CLASSES_FR, ) from services.image_utils import optimize_image, detect_skin from services.inference import run_inference from services.analysis import analyze_skin_issues predict_bp = Blueprint('predict', __name__) @predict_bp.route('/predict', methods=['POST']) def predict(): start_time = time.time() print("[predict] New request received") # ── Language ─────────────────────────────────────────────────────────────── language = request.args.get('lang', 'en').lower() if language not in ('en', 'fr'): language = 'en' class_translations = CLASS_TRANSLATIONS_FR if language == 'fr' else CLASS_TRANSLATIONS_EN skin_type_classes = SKIN_TYPE_CLASSES_FR if language == 'fr' else SKIN_TYPE_CLASSES_EN # ── File validation ──────────────────────────────────────────────────────── if 'file' not in request.files: return jsonify({'error': 'No file found'}), 400 file = request.files['file'] if file.filename == '': return jsonify({'error': 'No file selected'}), 400 file_bytes = file.read() if len(file_bytes) > MAX_FILE_SIZE: return jsonify({'error': f'File too large. Max {MAX_FILE_SIZE // 1024 // 1024} MB'}), 400 # ── Decode & resize ──────────────────────────────────────────────────────── nparr = np.frombuffer(file_bytes, np.uint8) img = cv2.imdecode(nparr, cv2.IMREAD_COLOR) if img is None: return jsonify({'error': 'Invalid image format'}), 400 original_shape = img.shape img = optimize_image(img) new_shape = img.shape if original_shape != new_shape: print(f"[predict] Resized {original_shape} → {new_shape}") # ── Skin check ───────────────────────────────────────────────────────────── if not detect_skin(img): return jsonify({'error': 'No skin detected in the image'}), 400 # ── Main processing (with overall timeout) ───────────────────────────────── result_queue: queue.Queue = queue.Queue() def process(): try: detections, skin_type_result = run_inference( img, class_translations, skin_type_classes ) ai_t0 = time.time() ai_analysis = analyze_skin_issues(detections, language) print(f"[predict] AI analysis: {time.time()-ai_t0:.2f}s") result_queue.put(('ok', { 'success': True, 'detections': detections, 'ai_analysis': ai_analysis, 'skin_type': skin_type_result['skin_type'], 'skin_type_probabilities': skin_type_result['probabilities'], 'processing_time': round(time.time() - start_time, 2), 'image_size': {'width': new_shape[1], 'height': new_shape[0]}, 'disclaimer': ( "This analysis is not a medical diagnosis. " "For persistent issues, consult a dermatologist." ), })) except Exception as exc: result_queue.put(('err', str(exc))) threading.Thread(target=process, daemon=True).start() try: status, payload = result_queue.get(timeout=REQUEST_TIMEOUT) if status == 'ok': print(f"[predict] Total: {time.time()-start_time:.2f}s") return jsonify(payload) print(f"[predict] Processing error: {payload}") return jsonify({'error': 'Internal processing error', 'message': payload}), 500 except queue.Empty: print(f"[predict] Timed out after {REQUEST_TIMEOUT}s") return jsonify({ 'error': 'Request timed out. Try a smaller image or retry later.', 'suggestion': 'Upload an image under 1 MB for faster processing.', }), 504