Spaces:
Running
Running
File size: 4,810 Bytes
8cff4cb | 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 | # 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
|