Spaces:
Sleeping
Sleeping
adding files
Browse files- Dockerfile +18 -0
- app.py +45 -0
- mobilenetv2.py +27 -0
- models/blaze_face_full_range.tflite +3 -0
- models/blaze_face_short_range.tflite +3 -0
- models/mobilenetv2_generated_dataset_oily_dry_normal_v1.pt +3 -0
- predict.py +157 -0
- requirements.txt +10 -0
- transforms.py +10 -0
Dockerfile
ADDED
|
@@ -0,0 +1,18 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
FROM python:3.11-slim
|
| 2 |
+
|
| 3 |
+
WORKDIR /app
|
| 4 |
+
|
| 5 |
+
RUN apt-get update && apt-get install -y libgl1 libglib2.0-0 && rm -rf /var/lib/apt/lists/*
|
| 6 |
+
COPY requirements.txt .
|
| 7 |
+
RUN pip install --no-cache-dir -r requirements.txt
|
| 8 |
+
|
| 9 |
+
COPY models/blaze_face_short_range.tflite ./models/blaze_face_short_range.tflite
|
| 10 |
+
COPY transforms.py .
|
| 11 |
+
COPY mobilenetv2.py .
|
| 12 |
+
COPY predict.py .
|
| 13 |
+
COPY app.py .
|
| 14 |
+
COPY models ./models
|
| 15 |
+
|
| 16 |
+
EXPOSE 8000
|
| 17 |
+
|
| 18 |
+
CMD ["uvicorn", "app:app", "--host", "0.0.0.0", "--port", "8000"]
|
app.py
ADDED
|
@@ -0,0 +1,45 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import sys
|
| 2 |
+
from io import BytesIO
|
| 3 |
+
from pathlib import Path
|
| 4 |
+
from typing import Dict
|
| 5 |
+
|
| 6 |
+
import torch
|
| 7 |
+
import uvicorn
|
| 8 |
+
from fastapi import FastAPI, File, HTTPException, UploadFile
|
| 9 |
+
from PIL import Image
|
| 10 |
+
|
| 11 |
+
# Garantit que les modules locaux (predict, transforms, mobilenetv2) sont trouvables
|
| 12 |
+
sys.path.insert(0, str(Path(__file__).resolve().parent))
|
| 13 |
+
|
| 14 |
+
from predict import load_model, predict_image # noqa: E402
|
| 15 |
+
|
| 16 |
+
app = FastAPI(title="Oily Prediction API")
|
| 17 |
+
|
| 18 |
+
MODEL_PATH = Path(__file__).resolve().parent / "models" / "mobilenetv2_generated_dataset_oily_dry_normal_v1.pt"
|
| 19 |
+
DEVICE = "cuda" if torch.cuda.is_available() else "cpu"
|
| 20 |
+
|
| 21 |
+
model, _metadata = load_model(str(MODEL_PATH), device=DEVICE)
|
| 22 |
+
|
| 23 |
+
|
| 24 |
+
@app.get("/health")
|
| 25 |
+
def health() -> Dict[str, str]:
|
| 26 |
+
return {"status": "ok"}
|
| 27 |
+
|
| 28 |
+
|
| 29 |
+
@app.post("/predict")
|
| 30 |
+
async def predict(file: UploadFile = File(...)):
|
| 31 |
+
try:
|
| 32 |
+
contents = await file.read()
|
| 33 |
+
pil_image = Image.open(BytesIO(contents)).convert("RGB")
|
| 34 |
+
result = predict_image(model, pil_image, device=DEVICE, use_face_detection=True)
|
| 35 |
+
return {
|
| 36 |
+
"model": "oily",
|
| 37 |
+
"prediction": result["class"],
|
| 38 |
+
"confidence": result["confidence"],
|
| 39 |
+
}
|
| 40 |
+
except Exception as e:
|
| 41 |
+
raise HTTPException(status_code=400, detail=f"Inference error: {e}")
|
| 42 |
+
|
| 43 |
+
|
| 44 |
+
if __name__ == "__main__":
|
| 45 |
+
uvicorn.run("app:app", host="0.0.0.0", port=8000, reload=False)
|
mobilenetv2.py
ADDED
|
@@ -0,0 +1,27 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import torch.nn as nn
|
| 2 |
+
from torchvision import models
|
| 3 |
+
|
| 4 |
+
|
| 5 |
+
CLASS_NAMES = ["dry", "normal", "oily"]
|
| 6 |
+
NUM_CLASSES = len(CLASS_NAMES)
|
| 7 |
+
|
| 8 |
+
def build_model(num_classes: int = NUM_CLASSES, freeze_backbone: bool = True) -> nn.Module:
|
| 9 |
+
model = models.mobilenet_v2(weights=None)
|
| 10 |
+
|
| 11 |
+
# On identifie la couche linéaire d'origine
|
| 12 |
+
classifier_block = model.classifier[1]
|
| 13 |
+
if isinstance(classifier_block, nn.Linear):
|
| 14 |
+
num_features = classifier_block.in_features
|
| 15 |
+
else:
|
| 16 |
+
num_features = 1280
|
| 17 |
+
|
| 18 |
+
if freeze_backbone:
|
| 19 |
+
for param in model.parameters():
|
| 20 |
+
param.requires_grad = False
|
| 21 |
+
|
| 22 |
+
model.classifier[1] = nn.Sequential(
|
| 23 |
+
nn.Dropout(p=0.3),
|
| 24 |
+
nn.Linear(num_features, num_classes),
|
| 25 |
+
)
|
| 26 |
+
|
| 27 |
+
return model
|
models/blaze_face_full_range.tflite
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:3698b18f063835bc609069ef052228fbe86d9c9a6dc8dcb7c7c2d69aed2b181b
|
| 3 |
+
size 1083786
|
models/blaze_face_short_range.tflite
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:b4578f35940bf5a1a655214a1cce5cab13eba73c1297cd78e1a04c2380b0152f
|
| 3 |
+
size 229746
|
models/mobilenetv2_generated_dataset_oily_dry_normal_v1.pt
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:a653b77e383f6b4b9edd9a91462cff13594d3d0de7ab262a509fb42435dc43ac
|
| 3 |
+
size 9200309
|
predict.py
ADDED
|
@@ -0,0 +1,157 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import argparse
|
| 2 |
+
import sys
|
| 3 |
+
import os
|
| 4 |
+
from pathlib import Path
|
| 5 |
+
from typing import Optional, Union
|
| 6 |
+
|
| 7 |
+
import cv2
|
| 8 |
+
import mediapipe as mp
|
| 9 |
+
import numpy as np
|
| 10 |
+
import torch
|
| 11 |
+
from mediapipe.tasks import python
|
| 12 |
+
from mediapipe.tasks.python import vision as mp_vision
|
| 13 |
+
from PIL import Image
|
| 14 |
+
|
| 15 |
+
# --- GESTION DES CHEMINS (Correctif Docker) ---
|
| 16 |
+
# Dans Docker, le fichier est dans /app/predict.py
|
| 17 |
+
# parent = /app
|
| 18 |
+
CURRENT_DIR = Path(__file__).resolve().parent
|
| 19 |
+
|
| 20 |
+
# On définit ROOT avec sécurité pour Docker
|
| 21 |
+
try:
|
| 22 |
+
if os.path.exists("/app"):
|
| 23 |
+
ROOT = Path("/app")
|
| 24 |
+
else:
|
| 25 |
+
ROOT = CURRENT_DIR.parents[1] # Remonte de oily/ vers skinmatch/
|
| 26 |
+
except IndexError:
|
| 27 |
+
ROOT = CURRENT_DIR
|
| 28 |
+
|
| 29 |
+
# Ajout au sys.path pour que Python trouve les modules 'oily'
|
| 30 |
+
if str(CURRENT_DIR) not in sys.path:
|
| 31 |
+
sys.path.insert(0, str(CURRENT_DIR))
|
| 32 |
+
|
| 33 |
+
# On ajuste les imports pour Docker (si oily est le dossier courant)
|
| 34 |
+
try:
|
| 35 |
+
from transforms import get_inference_transforms
|
| 36 |
+
from mobilenetv2 import build_model, CLASS_NAMES, NUM_CLASSES
|
| 37 |
+
except ImportError:
|
| 38 |
+
from oily.transforms import get_inference_transforms
|
| 39 |
+
from oily.mobilenetv2 import build_model, CLASS_NAMES, NUM_CLASSES
|
| 40 |
+
|
| 41 |
+
# Chemin vers le modèle de détection de visage
|
| 42 |
+
# Note : Assure-toi que ce fichier .tflite est bien copié dans ton image Docker !
|
| 43 |
+
BLAZEFACE_MODEL = CURRENT_DIR / "models" / "blaze_face_short_range.tflite"
|
| 44 |
+
|
| 45 |
+
def load_model(model_path: str, device: Optional[str] = None) -> tuple[torch.nn.Module, dict]:
|
| 46 |
+
resolved_device: str = device if device is not None else (
|
| 47 |
+
"cuda" if torch.cuda.is_available() else "cpu"
|
| 48 |
+
)
|
| 49 |
+
|
| 50 |
+
# Ajout de weights_only=True par sécurité (bonne pratique PyTorch récente)
|
| 51 |
+
checkpoint: dict = torch.load(model_path, map_location=resolved_device, weights_only=False)
|
| 52 |
+
metadata: dict = checkpoint.get("metadata", {})
|
| 53 |
+
num_classes: int = int(metadata.get("num_classes", NUM_CLASSES))
|
| 54 |
+
|
| 55 |
+
# On reconstruit le modèle
|
| 56 |
+
model = build_model(num_classes=num_classes, freeze_backbone=False)
|
| 57 |
+
model.load_state_dict(checkpoint["model_state_dict"])
|
| 58 |
+
model = model.to(resolved_device)
|
| 59 |
+
model.eval()
|
| 60 |
+
|
| 61 |
+
print(f"Modèle chargé depuis : {model_path}")
|
| 62 |
+
return model, metadata
|
| 63 |
+
|
| 64 |
+
|
| 65 |
+
def preprocess_image(image_input: Union[str, Path, Image.Image], use_face_detection: bool = True) -> Image.Image:
|
| 66 |
+
# Conversion en format OpenCV (RGB)
|
| 67 |
+
if isinstance(image_input, (str, Path)):
|
| 68 |
+
image_bgr = cv2.imread(str(image_input))
|
| 69 |
+
else:
|
| 70 |
+
# Conversion PIL -> OpenCV RGB
|
| 71 |
+
image_bgr = cv2.cvtColor(np.array(image_input), cv2.COLOR_RGB2BGR)
|
| 72 |
+
|
| 73 |
+
if image_bgr is None:
|
| 74 |
+
raise ValueError("Impossible de charger l'image.")
|
| 75 |
+
|
| 76 |
+
h, w = image_bgr.shape[:2]
|
| 77 |
+
|
| 78 |
+
# 2. Détection de visage (Fallback si le modèle .tflite manque)
|
| 79 |
+
if use_face_detection and BLAZEFACE_MODEL.exists():
|
| 80 |
+
try:
|
| 81 |
+
base_options = python.BaseOptions(model_asset_path=str(BLAZEFACE_MODEL))
|
| 82 |
+
options = mp_vision.FaceDetectorOptions(
|
| 83 |
+
base_options=base_options,
|
| 84 |
+
running_mode=mp_vision.RunningMode.IMAGE,
|
| 85 |
+
)
|
| 86 |
+
with mp_vision.FaceDetector.create_from_options(options) as detector:
|
| 87 |
+
# Conversion pour Mediapipe
|
| 88 |
+
mp_image = mp.Image(image_format=mp.ImageFormat.SRGB, data=cv2.cvtColor(image_bgr, cv2.COLOR_BGR2RGB))
|
| 89 |
+
result = detector.detect(mp_image)
|
| 90 |
+
|
| 91 |
+
if result.detections:
|
| 92 |
+
bbox = result.detections[0].bounding_box
|
| 93 |
+
margin = 0.2
|
| 94 |
+
x = max(0, int(bbox.origin_x - bbox.width * margin))
|
| 95 |
+
y = max(0, int(bbox.origin_y - bbox.height * margin))
|
| 96 |
+
w_crop = int(bbox.width * (1 + margin * 2))
|
| 97 |
+
h_crop = int(bbox.height * (1 + margin * 2))
|
| 98 |
+
|
| 99 |
+
crop = image_bgr[y:y+h_crop, x:x+w_crop]
|
| 100 |
+
if crop.size > 0:
|
| 101 |
+
image_bgr = crop
|
| 102 |
+
except Exception as e:
|
| 103 |
+
print(f"Face detection failed: {e}. Using original image.")
|
| 104 |
+
|
| 105 |
+
# Resize final et retour en PIL RGB
|
| 106 |
+
resized = cv2.resize(image_bgr, (224, 224), interpolation=cv2.INTER_CUBIC)
|
| 107 |
+
return Image.fromarray(cv2.cvtColor(resized, cv2.COLOR_BGR2RGB))
|
| 108 |
+
|
| 109 |
+
|
| 110 |
+
def predict_image(
|
| 111 |
+
model: torch.nn.Module,
|
| 112 |
+
image_input: Union[str, Path, Image.Image],
|
| 113 |
+
device: Optional[str] = None,
|
| 114 |
+
use_face_detection: bool = True,
|
| 115 |
+
class_names: Optional[list[str]] = None,
|
| 116 |
+
) -> dict:
|
| 117 |
+
resolved_device: str = device if device is not None else str(next(model.parameters()).device)
|
| 118 |
+
resolved_classes: list[str] = class_names if class_names is not None else CLASS_NAMES
|
| 119 |
+
|
| 120 |
+
# 1. Prétraitement
|
| 121 |
+
pil_image = preprocess_image(image_input, use_face_detection)
|
| 122 |
+
|
| 123 |
+
# 2. Transforms (Normalisation ImageNet)
|
| 124 |
+
transform = get_inference_transforms()
|
| 125 |
+
tensor = transform(pil_image).unsqueeze(0).to(resolved_device)
|
| 126 |
+
|
| 127 |
+
# 3. Inférence
|
| 128 |
+
with torch.no_grad():
|
| 129 |
+
logits = model(tensor)
|
| 130 |
+
probs = torch.softmax(logits, dim=1).squeeze(0)
|
| 131 |
+
|
| 132 |
+
# 4. Formatage
|
| 133 |
+
predicted_idx = int(probs.argmax().item())
|
| 134 |
+
confidence = float(probs[predicted_idx].item())
|
| 135 |
+
|
| 136 |
+
scores = {
|
| 137 |
+
cls: round(float(probs[i].item()), 4)
|
| 138 |
+
for i, cls in enumerate(resolved_classes)
|
| 139 |
+
}
|
| 140 |
+
|
| 141 |
+
return {
|
| 142 |
+
"class": resolved_classes[predicted_idx],
|
| 143 |
+
"confidence": round(confidence, 4),
|
| 144 |
+
"scores": scores,
|
| 145 |
+
}
|
| 146 |
+
|
| 147 |
+
# --- Bloc main inchangé mais sécurisé ---
|
| 148 |
+
if __name__ == "__main__":
|
| 149 |
+
parser = argparse.ArgumentParser()
|
| 150 |
+
parser.add_argument("--model", type=str, required=True)
|
| 151 |
+
parser.add_argument("--image", type=str, required=True)
|
| 152 |
+
args = parser.parse_args()
|
| 153 |
+
|
| 154 |
+
model, meta = load_model(args.model)
|
| 155 |
+
names = meta.get("class_names", meta.get("class_names", CLASS_NAMES))
|
| 156 |
+
res = predict_image(model, args.image, class_names=names)
|
| 157 |
+
print(res)
|
requirements.txt
ADDED
|
@@ -0,0 +1,10 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
fastapi
|
| 2 |
+
uvicorn[standard]
|
| 3 |
+
python-multipart
|
| 4 |
+
pandas
|
| 5 |
+
pillow
|
| 6 |
+
opencv-python-headless
|
| 7 |
+
mediapipe
|
| 8 |
+
--extra-index-url https://download.pytorch.org/whl/cpu
|
| 9 |
+
torch
|
| 10 |
+
torchvision
|
transforms.py
ADDED
|
@@ -0,0 +1,10 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from torchvision import transforms
|
| 2 |
+
from torchvision.transforms import InterpolationMode
|
| 3 |
+
|
| 4 |
+
|
| 5 |
+
def get_inference_transforms() -> transforms.Compose:
|
| 6 |
+
return transforms.Compose([
|
| 7 |
+
transforms.Resize((224, 224), interpolation=InterpolationMode.BICUBIC),
|
| 8 |
+
transforms.ToTensor(),
|
| 9 |
+
transforms.Normalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225]),
|
| 10 |
+
])
|