Spaces:
Running
Running
first commit feat :Performance enhancement ,
Browse files- Dockerfile +36 -0
- app.py +454 -0
- model_moncef.pt +3 -0
- requirements.txt +12 -0
- skin_type_classification85.pth +3 -0
- yolov11x1.1-trained.pt +3 -0
Dockerfile
ADDED
|
@@ -0,0 +1,36 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
FROM python:3.9-slim
|
| 2 |
+
|
| 3 |
+
RUN apt-get update && apt-get install -y --no-install-recommends \
|
| 4 |
+
build-essential \
|
| 5 |
+
libgl1 \
|
| 6 |
+
libglib2.0-0 \
|
| 7 |
+
libsm6 \
|
| 8 |
+
libxext6 \
|
| 9 |
+
libxrender-dev \
|
| 10 |
+
libgl1-mesa-glx \
|
| 11 |
+
&& rm -rf /var/lib/apt/lists/*
|
| 12 |
+
|
| 13 |
+
# Set up non-root user
|
| 14 |
+
RUN useradd -m -u 1000 user
|
| 15 |
+
USER user
|
| 16 |
+
|
| 17 |
+
ENV HOME=/home/user \
|
| 18 |
+
PATH=/home/user/.local/bin:$PATH \
|
| 19 |
+
PYTHONUNBUFFERED=1
|
| 20 |
+
|
| 21 |
+
WORKDIR $HOME/app
|
| 22 |
+
|
| 23 |
+
# Copy requirements first for better caching
|
| 24 |
+
COPY --chown=user requirements.txt .
|
| 25 |
+
|
| 26 |
+
# Install Python dependencies
|
| 27 |
+
RUN pip install --no-cache-dir -r requirements.txt
|
| 28 |
+
|
| 29 |
+
# Copy application code
|
| 30 |
+
COPY --chown=user . .
|
| 31 |
+
|
| 32 |
+
# Expose the correct port for Flask
|
| 33 |
+
EXPOSE 8000
|
| 34 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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
from flask import Flask, request, jsonify
|
| 3 |
+
from flask_cors import CORS
|
| 4 |
+
from ultralytics import YOLO
|
| 5 |
+
import cv2
|
| 6 |
+
import numpy as np
|
| 7 |
+
from groq import Groq
|
| 8 |
+
import threading
|
| 9 |
+
import torch
|
| 10 |
+
from torchvision import transforms, models
|
| 11 |
+
from PIL import Image
|
| 12 |
+
import json
|
| 13 |
+
import re
|
| 14 |
+
import time
|
| 15 |
+
import queue
|
| 16 |
+
|
| 17 |
+
app = Flask(__name__)
|
| 18 |
+
CORS(app) # Allow all origins for RapidAPI compatibility
|
| 19 |
+
|
| 20 |
+
# Configuration
|
| 21 |
+
MODEL_PATH = 'model_moncef.pt'
|
| 22 |
+
SKIN_TYPE_MODEL_PATH = 'skin_type_classification85.pth'
|
| 23 |
+
MAX_IMAGE_SIZE = 1024 # Maximum dimension for input images
|
| 24 |
+
GROQ_TIMEOUT = 8.0 # Timeout for Groq API calls in seconds
|
| 25 |
+
REQUEST_TIMEOUT = 30.0 # Overall request timeout in seconds
|
| 26 |
+
MAX_FILE_SIZE = 10 * 1024 * 1024 # 10MB max file size
|
| 27 |
+
|
| 28 |
+
# Translation dictionaries
|
| 29 |
+
class_translations_en = {
|
| 30 |
+
'acne': 'Acne', 'blackheads': 'Blackheads', 'dark circles': 'Dark Circles',
|
| 31 |
+
'dark spot': 'Dark Spot', 'eyebags': 'Eye Bags', 'redness': 'Redness',
|
| 32 |
+
'whiteheads': 'Whiteheads', 'wrinkles': 'Wrinkles', 'Acne': 'Acne',
|
| 33 |
+
'Acne Scar': 'Acne Scar', 'Blackhead': 'Blackhead', 'Dark Circles': 'Dark Circles',
|
| 34 |
+
'Dark Spots': 'Dark Spots', 'Enlarged Pores': 'Enlarged Pores', 'Eyebags': 'Eye Bags',
|
| 35 |
+
'Freckle': 'Freckle', 'Melasma': 'Melasma', 'Nodules': 'Nodules',
|
| 36 |
+
'Papules': 'Papules', 'Pustules': 'Pustules', 'Skin Redness': 'Skin Redness',
|
| 37 |
+
'Sun Spots': 'Sun Spots', 'Vascular': 'Vascular Lesions', 'Whitehead': 'Whitehead',
|
| 38 |
+
'Wrinkles': 'Wrinkles'
|
| 39 |
+
}
|
| 40 |
+
|
| 41 |
+
class_translations_fr = {
|
| 42 |
+
'acne': 'Acné', 'blackheads': 'Points noirs', 'dark circles': 'Cernes',
|
| 43 |
+
'dark spot': 'Tache brune', 'eyebags': 'Poches sous les yeux', 'redness': 'Rougeurs',
|
| 44 |
+
'whiteheads': 'Points blancs', 'wrinkles': 'Rides', 'Acne': 'Acné',
|
| 45 |
+
'Acne Scar': 'Cicatrice d\'acné', 'Blackhead': 'Point noir', 'Dark Circles': 'Cernes',
|
| 46 |
+
'Dark Spots': 'Taches brunes', 'Enlarged Pores': 'Pores dilatés', 'Eyebags': 'Poches sous les yeux',
|
| 47 |
+
'Freckle': 'Tache de rousseur', 'Melasma': 'Mélasma', 'Nodules': 'Nodules',
|
| 48 |
+
'Papules': 'Papules', 'Pustules': 'Pustules', 'Skin Redness': 'Rougeurs',
|
| 49 |
+
'Sun Spots': 'Taches solaires', 'Vascular': 'Lésions vasculaires', 'Whitehead': 'Point blanc',
|
| 50 |
+
'Wrinkles': 'Rides'
|
| 51 |
+
}
|
| 52 |
+
|
| 53 |
+
skin_type_classes_en = {0: 'Dry Skin', 1: 'Normal Skin', 2: 'Oily Skin'}
|
| 54 |
+
skin_type_classes_fr = {0: 'Peau sèche', 1: 'Peau normale', 2: 'Peau grasse'}
|
| 55 |
+
|
| 56 |
+
# Initialize models
|
| 57 |
+
device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
|
| 58 |
+
print(f"Using device: {device}")
|
| 59 |
+
|
| 60 |
+
# Load YOLO model
|
| 61 |
+
print("Loading YOLO model...")
|
| 62 |
+
model = YOLO(MODEL_PATH)
|
| 63 |
+
|
| 64 |
+
# Load skin type model
|
| 65 |
+
print("Loading skin type model...")
|
| 66 |
+
skin_type_model = models.resnet50(weights=None)
|
| 67 |
+
num_ftrs = skin_type_model.fc.in_features
|
| 68 |
+
skin_type_model.fc = torch.nn.Linear(num_ftrs, 3)
|
| 69 |
+
|
| 70 |
+
try:
|
| 71 |
+
checkpoint = torch.load(SKIN_TYPE_MODEL_PATH, map_location=device)
|
| 72 |
+
model_dict = skin_type_model.state_dict()
|
| 73 |
+
pretrained_dict = {}
|
| 74 |
+
|
| 75 |
+
for k, v in checkpoint.items():
|
| 76 |
+
if k in model_dict and v.shape == model_dict[k].shape:
|
| 77 |
+
pretrained_dict[k] = v
|
| 78 |
+
elif k == 'fc.weight' and model_dict['fc.weight'].shape[1] == v.shape[1]:
|
| 79 |
+
pretrained_dict['fc.weight'] = v[:3, :]
|
| 80 |
+
elif k == 'fc.bias' and len(v) >= 3:
|
| 81 |
+
pretrained_dict['fc.bias'] = v[:3]
|
| 82 |
+
|
| 83 |
+
skin_type_model.load_state_dict(pretrained_dict, strict=False)
|
| 84 |
+
print("Skin type model loaded successfully")
|
| 85 |
+
except Exception as e:
|
| 86 |
+
print(f"Error loading skin type model: {str(e)}")
|
| 87 |
+
|
| 88 |
+
skin_type_model = skin_type_model.to(device)
|
| 89 |
+
skin_type_model.eval()
|
| 90 |
+
|
| 91 |
+
# Image transform for skin type model
|
| 92 |
+
transform = transforms.Compose([
|
| 93 |
+
transforms.ToPILImage(),
|
| 94 |
+
transforms.Resize((224, 224)),
|
| 95 |
+
transforms.ToTensor(),
|
| 96 |
+
transforms.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225])
|
| 97 |
+
])
|
| 98 |
+
|
| 99 |
+
def optimize_image(img, max_size=MAX_IMAGE_SIZE):
|
| 100 |
+
"""Resize large images to improve processing speed"""
|
| 101 |
+
h, w = img.shape[:2]
|
| 102 |
+
if max(h, w) > max_size:
|
| 103 |
+
scale = max_size / max(h, w)
|
| 104 |
+
new_w, new_h = int(w * scale), int(h * scale)
|
| 105 |
+
img = cv2.resize(img, (new_w, new_h), interpolation=cv2.INTER_AREA)
|
| 106 |
+
return img
|
| 107 |
+
|
| 108 |
+
def detect_skin(image):
|
| 109 |
+
"""Detect skin regions in the image using HSV color space"""
|
| 110 |
+
hsv = cv2.cvtColor(image, cv2.COLOR_BGR2HSV)
|
| 111 |
+
lower_skin = np.array([0, 20, 70], dtype=np.uint8)
|
| 112 |
+
upper_skin = np.array([20, 255, 255], dtype=np.uint8)
|
| 113 |
+
mask = cv2.inRange(hsv, lower_skin, upper_skin)
|
| 114 |
+
skin_pixels = cv2.countNonZero(mask)
|
| 115 |
+
total_pixels = image.shape[0] * image.shape[1]
|
| 116 |
+
skin_ratio = skin_pixels / total_pixels
|
| 117 |
+
return skin_ratio > 0.05
|
| 118 |
+
|
| 119 |
+
def analyze_skin_issues_with_timeout(detections, language='en', timeout=GROQ_TIMEOUT):
|
| 120 |
+
"""Analyze skin issues with timeout protection"""
|
| 121 |
+
result = {}
|
| 122 |
+
exception = None
|
| 123 |
+
|
| 124 |
+
def worker():
|
| 125 |
+
nonlocal exception
|
| 126 |
+
try:
|
| 127 |
+
result['analysis'] = analyze_skin_issues(detections, language)
|
| 128 |
+
except Exception as e:
|
| 129 |
+
exception = e
|
| 130 |
+
|
| 131 |
+
thread = threading.Thread(target=worker)
|
| 132 |
+
thread.start()
|
| 133 |
+
thread.join(timeout)
|
| 134 |
+
|
| 135 |
+
if thread.is_alive():
|
| 136 |
+
print("Groq API call timed out")
|
| 137 |
+
return get_default_analysis(language, timeout=True)
|
| 138 |
+
|
| 139 |
+
if exception:
|
| 140 |
+
print(f"Groq API error: {str(exception)}")
|
| 141 |
+
return get_default_analysis(language)
|
| 142 |
+
|
| 143 |
+
return result.get('analysis', get_default_analysis(language))
|
| 144 |
+
|
| 145 |
+
def analyze_skin_issues(detections, language='en'):
|
| 146 |
+
"""Analyze skin issues using Groq LLM"""
|
| 147 |
+
groq_api_key = os.environ.get("GROQ_API_KEY")
|
| 148 |
+
if not groq_api_key:
|
| 149 |
+
return get_default_analysis(language, reason="API key missing")
|
| 150 |
+
|
| 151 |
+
client = Groq(api_key=groq_api_key)
|
| 152 |
+
|
| 153 |
+
problems = []
|
| 154 |
+
for detection in detections:
|
| 155 |
+
problems.append(f"{detection['class_name']} (confidence: {detection['confidence']:.2f})")
|
| 156 |
+
|
| 157 |
+
skin_issues = ", ".join(problems)
|
| 158 |
+
|
| 159 |
+
if language == 'fr':
|
| 160 |
+
prompt = f"""En tant que spécialiste en dermatologie, analyse les problèmes de peau suivants détectés par IA: {skin_issues}.
|
| 161 |
+
|
| 162 |
+
Réponds exactement dans ce format JSON:
|
| 163 |
+
{{
|
| 164 |
+
"conseils": "Liste de conseils précis et pratiques pour traiter ces problèmes spécifiques de peau",
|
| 165 |
+
"interpretation": "Explication claire des causes possibles et de la gravité des problèmes détectés",
|
| 166 |
+
"routine": "Proposition d'une routine quotidienne adaptée pour améliorer l'état de la peau. Termine toujours par la phrase: 'Consultez la section des produits recommandés ci-dessous pour voir les solutions adaptées à vos besoins spécifiques.'"
|
| 167 |
+
}}
|
| 168 |
+
|
| 169 |
+
Ne mets rien d'autre dans ta réponse que ce JSON correctement formaté."""
|
| 170 |
+
else:
|
| 171 |
+
prompt = f"""As a dermatology specialist, analyze the following skin problems detected by AI: {skin_issues}.
|
| 172 |
+
|
| 173 |
+
Respond exactly in this JSON format:
|
| 174 |
+
{{
|
| 175 |
+
"conseils": "List of precise and practical advice for treating these specific skin problems",
|
| 176 |
+
"interpretation": "Clear explanation of possible causes and severity of the detected problems",
|
| 177 |
+
"routine": "Proposal for a daily routine adapted to improve skin condition. Always end with the phrase: 'Check the recommended products section below to see solutions tailored to your specific needs.'"
|
| 178 |
+
}}
|
| 179 |
+
|
| 180 |
+
Put nothing else in your response except this properly formatted JSON."""
|
| 181 |
+
|
| 182 |
+
start_time = time.time()
|
| 183 |
+
chat_completion = client.chat.completions.create(
|
| 184 |
+
messages=[{"role": "user", "content": prompt}],
|
| 185 |
+
model="llama-3.3-70b-versatile",
|
| 186 |
+
stream=False,
|
| 187 |
+
)
|
| 188 |
+
response_time = time.time() - start_time
|
| 189 |
+
print(f"Groq API response time: {response_time:.2f}s")
|
| 190 |
+
|
| 191 |
+
response_content = chat_completion.choices[0].message.content
|
| 192 |
+
|
| 193 |
+
# Try to parse JSON from the response
|
| 194 |
+
json_match = re.search(r'\{.*\}', response_content, re.DOTALL)
|
| 195 |
+
if json_match:
|
| 196 |
+
try:
|
| 197 |
+
return json.loads(json_match.group(0))
|
| 198 |
+
except json.JSONDecodeError:
|
| 199 |
+
pass
|
| 200 |
+
|
| 201 |
+
# Fallback parsing if JSON extraction fails
|
| 202 |
+
conseils = "Consult a dermatologist for personalized advice."
|
| 203 |
+
interpretation = "Professional analysis is recommended for these skin problems."
|
| 204 |
+
routine = "Follow a basic routine: cleansing, moisturizing, and daily sun protection."
|
| 205 |
+
|
| 206 |
+
if language == 'fr':
|
| 207 |
+
conseils = "Consultez un dermatologue pour des conseils personnalisés."
|
| 208 |
+
interpretation = "Une analyse professionnelle est recommandée pour ces problèmes de peau."
|
| 209 |
+
routine = "Suivez une routine de base: nettoyage, hydratation et protection solaire quotidienne."
|
| 210 |
+
|
| 211 |
+
return {
|
| 212 |
+
"conseils": conseils,
|
| 213 |
+
"interpretation": interpretation,
|
| 214 |
+
"routine": routine
|
| 215 |
+
}
|
| 216 |
+
|
| 217 |
+
def get_default_analysis(language='en', timeout=False, reason=None):
|
| 218 |
+
"""Return default analysis when Groq API fails or times out"""
|
| 219 |
+
if language == 'fr':
|
| 220 |
+
if timeout:
|
| 221 |
+
return {
|
| 222 |
+
"conseils": "L'analyse prend plus de temps que prévu. Veuillez réessayer plus tard.",
|
| 223 |
+
"interpretation": "Le système d'analyse IA est temporairement occupé.",
|
| 224 |
+
"routine": "Routine standard: nettoyer doucement, hydrater et protéger du soleil."
|
| 225 |
+
}
|
| 226 |
+
return {
|
| 227 |
+
"conseils": "Consultez un dermatologue pour des conseils personnalisés.",
|
| 228 |
+
"interpretation": "Une analyse professionnelle est recommandée pour ces problèmes de peau.",
|
| 229 |
+
"routine": "Suivez une routine de base: nettoyage, hydratation et protection solaire quotidienne."
|
| 230 |
+
}
|
| 231 |
+
else:
|
| 232 |
+
if timeout:
|
| 233 |
+
return {
|
| 234 |
+
"conseils": "Analysis is taking longer than expected. Please try again later.",
|
| 235 |
+
"interpretation": "The AI analysis system is temporarily busy.",
|
| 236 |
+
"routine": "Standard routine: gentle cleansing, moisturizing, and sun protection."
|
| 237 |
+
}
|
| 238 |
+
return {
|
| 239 |
+
"conseils": "Consult a dermatologist for personalized advice.",
|
| 240 |
+
"interpretation": "Professional analysis is recommended for these skin problems.",
|
| 241 |
+
"routine": "Follow a basic routine: cleansing, moisturizing, and daily sun protection."
|
| 242 |
+
}
|
| 243 |
+
|
| 244 |
+
def warm_up_models():
|
| 245 |
+
"""Pre-load models and run dummy inference to reduce cold start time"""
|
| 246 |
+
print("Warming up models...")
|
| 247 |
+
dummy_img = np.zeros((224, 224, 3), dtype=np.uint8)
|
| 248 |
+
|
| 249 |
+
# Warm up YOLO model
|
| 250 |
+
start_time = time.time()
|
| 251 |
+
model(dummy_img, conf=0.15, iou=0.2)
|
| 252 |
+
print(f"YOLO warm-up time: {time.time() - start_time:.2f}s")
|
| 253 |
+
|
| 254 |
+
# Warm up skin type model
|
| 255 |
+
start_time = time.time()
|
| 256 |
+
dummy_tensor = transform(dummy_img).unsqueeze(0).to(device)
|
| 257 |
+
with torch.no_grad():
|
| 258 |
+
skin_type_model(dummy_tensor)
|
| 259 |
+
print(f"Skin type model warm-up time: {time.time() - start_time:.2f}s")
|
| 260 |
+
print("Models warmed up and ready")
|
| 261 |
+
|
| 262 |
+
# Call the warm-up function immediately after model loading
|
| 263 |
+
with app.app_context():
|
| 264 |
+
warm_up_models()
|
| 265 |
+
|
| 266 |
+
@app.route('/predict', methods=['POST'])
|
| 267 |
+
def predict():
|
| 268 |
+
"""Main prediction endpoint with timeout protection"""
|
| 269 |
+
try:
|
| 270 |
+
start_time = time.time()
|
| 271 |
+
print("Processing new request")
|
| 272 |
+
|
| 273 |
+
# Get language parameter, default to English
|
| 274 |
+
language = request.args.get('lang', 'en').lower()
|
| 275 |
+
if language not in ['en', 'fr']:
|
| 276 |
+
language = 'en'
|
| 277 |
+
|
| 278 |
+
class_translations = class_translations_fr if language == 'fr' else class_translations_en
|
| 279 |
+
skin_type_classes = skin_type_classes_fr if language == 'fr' else skin_type_classes_en
|
| 280 |
+
|
| 281 |
+
# Validate file upload
|
| 282 |
+
if 'file' not in request.files:
|
| 283 |
+
return jsonify({'error': 'No file found'}), 400
|
| 284 |
+
|
| 285 |
+
file = request.files['file']
|
| 286 |
+
if file.filename == '':
|
| 287 |
+
return jsonify({'error': 'No file selected'}), 400
|
| 288 |
+
|
| 289 |
+
# Check file size
|
| 290 |
+
file_bytes = file.read()
|
| 291 |
+
if len(file_bytes) > MAX_FILE_SIZE:
|
| 292 |
+
return jsonify({'error': f'File too large. Maximum size is {MAX_FILE_SIZE//1024//1024}MB'}), 400
|
| 293 |
+
|
| 294 |
+
# Decode image
|
| 295 |
+
nparr = np.frombuffer(file_bytes, np.uint8)
|
| 296 |
+
img = cv2.imdecode(nparr, cv2.IMREAD_COLOR)
|
| 297 |
+
if img is None:
|
| 298 |
+
return jsonify({'error': 'Invalid image format'}), 400
|
| 299 |
+
|
| 300 |
+
# Optimize image size
|
| 301 |
+
original_shape = img.shape
|
| 302 |
+
img = optimize_image(img, MAX_IMAGE_SIZE)
|
| 303 |
+
new_shape = img.shape
|
| 304 |
+
if original_shape != new_shape:
|
| 305 |
+
print(f"Resized image from {original_shape} to {new_shape}")
|
| 306 |
+
|
| 307 |
+
# Check for skin in image
|
| 308 |
+
if not detect_skin(img):
|
| 309 |
+
return jsonify({'error': 'No skin detected in the image'}), 400
|
| 310 |
+
|
| 311 |
+
# Use a queue to handle the result with timeout
|
| 312 |
+
result_queue = queue.Queue()
|
| 313 |
+
|
| 314 |
+
def process_request():
|
| 315 |
+
try:
|
| 316 |
+
# Run inference in parallel threads
|
| 317 |
+
detections = []
|
| 318 |
+
skin_type_result = {}
|
| 319 |
+
errors = {}
|
| 320 |
+
|
| 321 |
+
def run_yolo():
|
| 322 |
+
nonlocal detections
|
| 323 |
+
try:
|
| 324 |
+
start = time.time()
|
| 325 |
+
results = model(img, conf=0.15, iou=0.2)[0]
|
| 326 |
+
for box in results.boxes:
|
| 327 |
+
x1, y1, x2, y2 = box.xyxy[0].cpu().numpy().astype(int)
|
| 328 |
+
confidence = float(box.conf[0])
|
| 329 |
+
class_id = int(box.cls[0])
|
| 330 |
+
class_name = results.names[class_id]
|
| 331 |
+
translated_name = class_translations.get(class_name, class_name)
|
| 332 |
+
|
| 333 |
+
detections.append({
|
| 334 |
+
'class_id': class_id,
|
| 335 |
+
'class_name': translated_name,
|
| 336 |
+
'confidence': confidence,
|
| 337 |
+
'bbox': [int(x1), int(y1), int(x2), int(y2)]
|
| 338 |
+
})
|
| 339 |
+
print(f"YOLO inference time: {time.time() - start:.2f}s, found {len(detections)} issues")
|
| 340 |
+
except Exception as e:
|
| 341 |
+
errors['yolo'] = str(e)
|
| 342 |
+
print(f"YOLO error: {str(e)}")
|
| 343 |
+
|
| 344 |
+
def run_skin_type():
|
| 345 |
+
nonlocal skin_type_result
|
| 346 |
+
try:
|
| 347 |
+
start = time.time()
|
| 348 |
+
pil_image = Image.fromarray(cv2.cvtColor(img, cv2.COLOR_BGR2RGB))
|
| 349 |
+
img_tensor = transform(np.array(pil_image)).unsqueeze(0).to(device)
|
| 350 |
+
|
| 351 |
+
with torch.no_grad():
|
| 352 |
+
output = skin_type_model(img_tensor)
|
| 353 |
+
probabilities = torch.nn.functional.softmax(output, dim=1)[0]
|
| 354 |
+
predicted_class = output.argmax(1).item()
|
| 355 |
+
|
| 356 |
+
skin_type_result = {
|
| 357 |
+
'skin_type': skin_type_classes[predicted_class],
|
| 358 |
+
'probabilities': {
|
| 359 |
+
'dry': float(probabilities[0] * 100),
|
| 360 |
+
'normal': float(probabilities[1] * 100),
|
| 361 |
+
'oily': float(probabilities[2] * 100)
|
| 362 |
+
}
|
| 363 |
+
}
|
| 364 |
+
print(f"Skin type inference time: {time.time() - start:.2f}s")
|
| 365 |
+
except Exception as e:
|
| 366 |
+
errors['skin_type'] = str(e)
|
| 367 |
+
print(f"Skin type model error: {str(e)}")
|
| 368 |
+
|
| 369 |
+
# Start threads
|
| 370 |
+
yolo_thread = threading.Thread(target=run_yolo)
|
| 371 |
+
skin_thread = threading.Thread(target=run_skin_type)
|
| 372 |
+
|
| 373 |
+
yolo_thread.start()
|
| 374 |
+
skin_thread.start()
|
| 375 |
+
|
| 376 |
+
# Wait for threads with timeout
|
| 377 |
+
yolo_thread.join(timeout=15.0)
|
| 378 |
+
skin_thread.join(timeout=15.0)
|
| 379 |
+
|
| 380 |
+
# Check if threads completed successfully
|
| 381 |
+
if 'yolo' in errors or len(detections) == 0:
|
| 382 |
+
print("YOLO inference failed or timed out")
|
| 383 |
+
detections = [] # Reset to empty list
|
| 384 |
+
|
| 385 |
+
if 'skin_type' in errors or not skin_type_result:
|
| 386 |
+
print("Skin type inference failed or timed out")
|
| 387 |
+
skin_type_result = {
|
| 388 |
+
'skin_type': skin_type_classes[1], # Default to normal skin
|
| 389 |
+
'probabilities': {'dry': 0.0, 'normal': 100.0, 'oily': 0.0}
|
| 390 |
+
}
|
| 391 |
+
|
| 392 |
+
# Get AI analysis with timeout protection
|
| 393 |
+
ai_analysis_start = time.time()
|
| 394 |
+
ai_analysis = analyze_skin_issues_with_timeout(detections, language)
|
| 395 |
+
print(f"AI analysis time: {time.time() - ai_analysis_start:.2f}s")
|
| 396 |
+
|
| 397 |
+
# Prepare response
|
| 398 |
+
response_data = {
|
| 399 |
+
'success': True,
|
| 400 |
+
'detections': detections,
|
| 401 |
+
'ai_analysis': ai_analysis,
|
| 402 |
+
'skin_type': skin_type_result['skin_type'],
|
| 403 |
+
'skin_type_probabilities': skin_type_result['probabilities'],
|
| 404 |
+
'processing_time': round(time.time() - start_time, 2),
|
| 405 |
+
'image_size': {'width': new_shape[1], 'height': new_shape[0]}
|
| 406 |
+
}
|
| 407 |
+
|
| 408 |
+
result_queue.put(('success', response_data))
|
| 409 |
+
except Exception as e:
|
| 410 |
+
result_queue.put(('error', str(e)))
|
| 411 |
+
|
| 412 |
+
# Start processing in a separate thread
|
| 413 |
+
processing_thread = threading.Thread(target=process_request)
|
| 414 |
+
processing_thread.start()
|
| 415 |
+
|
| 416 |
+
# Wait for the result with timeout
|
| 417 |
+
try:
|
| 418 |
+
status, result = result_queue.get(timeout=REQUEST_TIMEOUT)
|
| 419 |
+
if status == 'success':
|
| 420 |
+
total_time = time.time() - start_time
|
| 421 |
+
print(f"Total processing time: {total_time:.2f}s")
|
| 422 |
+
return jsonify(result)
|
| 423 |
+
else:
|
| 424 |
+
print(f"Processing error: {result}")
|
| 425 |
+
return jsonify({'error': 'Internal processing error', 'message': result}), 500
|
| 426 |
+
except queue.Empty:
|
| 427 |
+
# Timeout occurred
|
| 428 |
+
print(f"Request timed out after {REQUEST_TIMEOUT} seconds")
|
| 429 |
+
return jsonify({
|
| 430 |
+
'error': 'Request timed out. Please try a smaller image or try again later.',
|
| 431 |
+
'suggestion': 'Try uploading a smaller image (under 1MB) for faster processing'
|
| 432 |
+
}), 504
|
| 433 |
+
|
| 434 |
+
except Exception as e:
|
| 435 |
+
print(f"Unexpected error: {str(e)}")
|
| 436 |
+
return jsonify({
|
| 437 |
+
'error': 'Internal server error',
|
| 438 |
+
'message': str(e)
|
| 439 |
+
}), 500
|
| 440 |
+
|
| 441 |
+
@app.route('/health', methods=['GET'])
|
| 442 |
+
def health():
|
| 443 |
+
"""Health check endpoint"""
|
| 444 |
+
return jsonify({
|
| 445 |
+
'status': 'API online',
|
| 446 |
+
'timestamp': time.time(),
|
| 447 |
+
'device': str(device),
|
| 448 |
+
'model_status': 'loaded'
|
| 449 |
+
})
|
| 450 |
+
|
| 451 |
+
if __name__ == '__main__':
|
| 452 |
+
port = int(os.environ.get("PORT", 8000))
|
| 453 |
+
print(f"Starting server on port {port}")
|
| 454 |
+
app.run(debug=False, host='0.0.0.0', port=port)
|
model_moncef.pt
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:9fe2c0954d86ee90a276fa1f34a6162cac4158477e5f73ac22b710353be320e3
|
| 3 |
+
size 51220178
|
requirements.txt
ADDED
|
@@ -0,0 +1,12 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
flask
|
| 2 |
+
ultralytics
|
| 3 |
+
opencv-python
|
| 4 |
+
numpy
|
| 5 |
+
pillow
|
| 6 |
+
werkzeug
|
| 7 |
+
flask-cors
|
| 8 |
+
groq
|
| 9 |
+
python-dotenv
|
| 10 |
+
mediapipe
|
| 11 |
+
supabase
|
| 12 |
+
inference_sdk
|
skin_type_classification85.pth
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:e6b7b020c59b3c210ab9ac0b0368e3e549432310651a5a55289bf13f15cf2cf3
|
| 3 |
+
size 102571904
|
yolov11x1.1-trained.pt
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:0add40f1749007685bb0bb4b2348aeefa6ac4c9692b3528ec2139ba684f12cb4
|
| 3 |
+
size 124952045
|