Aghode91 commited on
Commit
bd77c31
·
1 Parent(s): de4c265
Dockerfile ADDED
@@ -0,0 +1,17 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 transforms.py .
10
+ COPY mobilenetv2.py .
11
+ COPY predict.py .
12
+ COPY app.py .
13
+ COPY models ./models
14
+
15
+ EXPOSE 8000
16
+
17
+ CMD ["uvicorn", "app:app", "--host", "0.0.0.0", "--port", "8000"]
app.py ADDED
@@ -0,0 +1,47 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ from mobilenetv2 import CLASS_NAMES
16
+
17
+ app = FastAPI(title="Acne Prediction API")
18
+
19
+ MODEL_PATH = Path(__file__).resolve().parent / "models" / "mobilenetv2_baseline_acne_normal.pt"
20
+ DEVICE = "cuda" if torch.cuda.is_available() else "cpu"
21
+
22
+ model, _metadata = load_model(str(MODEL_PATH), device=DEVICE)
23
+
24
+
25
+ @app.get("/health")
26
+ def health() -> Dict[str, str]:
27
+ return {"status": "ok"}
28
+
29
+
30
+ @app.post("/predict")
31
+ async def predict(file: UploadFile = File(...)):
32
+ try:
33
+ contents = await file.read()
34
+ pil_image = Image.open(BytesIO(contents)).convert("RGB")
35
+ result = predict_image(model, pil_image, device=DEVICE, use_face_detection=True, class_names=CLASS_NAMES)
36
+ return {
37
+ "model": "acne_classifier",
38
+ "prediction": result["class"],
39
+ "confidence": result["confidence"],
40
+ "scores": result["scores"]
41
+ }
42
+ except Exception as e:
43
+ raise HTTPException(status_code=400, detail=f"Inference error: {e}")
44
+
45
+
46
+ if __name__ == "__main__":
47
+ uvicorn.run("app:app", host="0.0.0.0", port=8000, reload=False)
mobilenetv2.py ADDED
@@ -0,0 +1,36 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch.nn as nn
2
+ from torchvision import models
3
+
4
+
5
+ CLASS_NAMES = ["acne", "normal"]
6
+ NUM_CLASSES = len(CLASS_NAMES)
7
+
8
+
9
+ def build_model(num_classes: int = NUM_CLASSES, freeze_backbone: bool = True) -> nn.Module:
10
+ """
11
+ Charge MobileNetV2 pré-entraîné sur ImageNet et adapte la tête de classification.
12
+
13
+ Args:
14
+ num_classes: Nombre de classes en sortie (3 par défaut).
15
+ freeze_backbone: Si True, gèle toutes les couches sauf le classifier.
16
+ Mettre False pour le fine-tuning ou le chargement d'un checkpoint.
17
+
18
+ Returns:
19
+ Modèle PyTorch prêt à être envoyé sur device.
20
+ """
21
+ weights = models.MobileNet_V2_Weights.DEFAULT
22
+ model = models.mobilenet_v2(weights=weights)
23
+
24
+ in_features: int = int(model.classifier[1].in_features) # type: ignore[arg-type]
25
+
26
+ if freeze_backbone:
27
+ for param in model.parameters():
28
+ param.requires_grad = False
29
+
30
+ # Remplacement de la tête avec Dropout pour réduire l'overfitting
31
+ model.classifier = nn.Sequential(
32
+ nn.Dropout(p=0.4),
33
+ nn.Linear(in_features, num_classes),
34
+ )
35
+
36
+ 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_baseline_acne_normal.pt ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:6ec27902855e1ab3d4980f1ff133bcf17923f6c7457d137df1bdaad1e94010e9
3
+ size 9177941
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 acne.transforms import get_inference_transforms
39
+ from acne.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
+
54
+ num_classes: int = int(metadata.get("num_classes", NUM_CLASSES))
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
+ # 1. Conversion en format OpenCV (BGR)
67
+ if isinstance(image_input, (str, Path)):
68
+ image_bgr = cv2.imread(str(image_input))
69
+ else:
70
+ # Conversion PIL -> OpenCV BGR
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
+ # 3. Resize final et retour en PIL RGB
106
+ resized = cv2.resize(image_bgr, (640, 640))
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", 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,43 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import cv2
2
+ import numpy as np
3
+ from PIL import Image
4
+ from torchvision import transforms
5
+
6
+
7
+ # Normalisation
8
+
9
+ IMAGENET_MEAN = [0.4996, 0.4011, 0.3593]
10
+ IMAGENET_STD = [0.3475, 0.3008, 0.2851]
11
+
12
+
13
+ # ── Pipelines ─────────────────────────────────────────────────────────────────
14
+
15
+ def get_train_transforms() -> transforms.Compose:
16
+ """Pipeline entraînement : augmentation + normalisation."""
17
+ return transforms.Compose([
18
+ transforms.Resize(640),
19
+ transforms.CenterCrop(640),
20
+ transforms.RandomHorizontalFlip(p=0.5),
21
+ transforms.RandomRotation(15),
22
+ transforms.ColorJitter(brightness=0.3, contrast=0.3, saturation=0.2),
23
+ transforms.ToTensor(),
24
+ transforms.Normalize(IMAGENET_MEAN, IMAGENET_STD),
25
+ ])
26
+
27
+
28
+ def get_val_transforms() -> transforms.Compose:
29
+ """Pipeline validation/test : normalisation, sans augmentation."""
30
+ return transforms.Compose([
31
+ transforms.Resize((640,640)),
32
+ transforms.ToTensor(),
33
+ transforms.Normalize(IMAGENET_MEAN, IMAGENET_STD),
34
+ ])
35
+
36
+
37
+ def get_inference_transforms() -> transforms.Compose:
38
+ """
39
+ Pipeline inférence (identique à val).
40
+ Exposé séparément pour être importé proprement dans 04_predict.py et app.py
41
+ sans dépendre du reste du module de training.
42
+ """
43
+ return get_val_transforms()