Spaces:
Sleeping
Sleeping
Upload 2 files
Browse files- Dockerfile +21 -0
- main.py +255 -0
Dockerfile
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
FROM python:3.10-slim
|
| 2 |
+
|
| 3 |
+
ENV PYTHONDONTWRITEBYTECODE=1 \
|
| 4 |
+
PYTHONUNBUFFERED=1 \
|
| 5 |
+
PIP_NO_CACHE_DIR=1 \
|
| 6 |
+
TF_NUM_INTRAOP_THREADS=1 \
|
| 7 |
+
TF_NUM_INTEROP_THREADS=1 \
|
| 8 |
+
OMP_NUM_THREADS=1 \
|
| 9 |
+
TF_CPP_MIN_LOG_LEVEL=2
|
| 10 |
+
|
| 11 |
+
WORKDIR /app
|
| 12 |
+
|
| 13 |
+
COPY requirements.txt /app/requirements.txt
|
| 14 |
+
RUN python -m pip install --upgrade pip setuptools wheel && \
|
| 15 |
+
pip install -r requirements.txt
|
| 16 |
+
|
| 17 |
+
COPY main.py /app/main.py
|
| 18 |
+
COPY Models /app/Models
|
| 19 |
+
|
| 20 |
+
EXPOSE 7860
|
| 21 |
+
CMD ["python","-m","uvicorn","main:app","--host","0.0.0.0","--port","7860","--workers","1"]
|
main.py
ADDED
|
@@ -0,0 +1,255 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os, io, json, logging
|
| 2 |
+
from typing import List, Dict, Any
|
| 3 |
+
|
| 4 |
+
import numpy as np
|
| 5 |
+
from fastapi import FastAPI, UploadFile, File, HTTPException, Request
|
| 6 |
+
from fastapi.middleware.cors import CORSMiddleware
|
| 7 |
+
from fastapi.responses import JSONResponse
|
| 8 |
+
from PIL import Image
|
| 9 |
+
import tensorflow as tf
|
| 10 |
+
|
| 11 |
+
# optional gatekeep
|
| 12 |
+
try:
|
| 13 |
+
import cv2
|
| 14 |
+
HAS_OPENCV = True
|
| 15 |
+
except Exception:
|
| 16 |
+
HAS_OPENCV = False
|
| 17 |
+
|
| 18 |
+
# HF Hub (สำหรับดึง derm-foundation)
|
| 19 |
+
from huggingface_hub import snapshot_download
|
| 20 |
+
|
| 21 |
+
logging.basicConfig(level=logging.INFO)
|
| 22 |
+
logger = logging.getLogger("skinclassify")
|
| 23 |
+
|
| 24 |
+
# ---------------------- Config ----------------------
|
| 25 |
+
DERM_MODEL_ID = os.getenv("DERM_MODEL_ID", "google/derm-foundation")
|
| 26 |
+
DERM_LOCAL_DIR = os.getenv("DERM_LOCAL_DIR", "") # path ไปยัง SavedModel ถ้ามีออฟไลน์
|
| 27 |
+
HEAD_PATH = os.getenv("HEAD_PATH", "Models/mlp_best.keras")
|
| 28 |
+
THRESHOLDS_PATH = os.getenv("THRESHOLDS_PATH", "Models/mlp_thresholds.npy")
|
| 29 |
+
MU_PATH = os.getenv("MU_PATH", "Models/mu.npy")
|
| 30 |
+
SD_PATH = os.getenv("SD_PATH", "Models/sd.npy")
|
| 31 |
+
LABELS_PATH = os.getenv("LABELS_PATH", "Models/class_names.json")
|
| 32 |
+
NPZ_PATH = os.getenv("NPZ_PATH", "") # ถ้าอยากโหลด mu/sd/class_names จากไฟล์เดียว
|
| 33 |
+
|
| 34 |
+
TOPK = int(os.getenv("TOPK", "5"))
|
| 35 |
+
|
| 36 |
+
# Gate keep params
|
| 37 |
+
MIN_W, MIN_H = int(os.getenv("MIN_W", "128")), int(os.getenv("MIN_H", "128"))
|
| 38 |
+
MIN_ASPECT, MAX_ASPECT = float(os.getenv("MIN_ASPECT", "0.5")), float(os.getenv("MAX_ASPECT", "2.0"))
|
| 39 |
+
MIN_BRIGHT, MAX_BRIGHT = float(os.getenv("MIN_BRIGHT", "20")), float(os.getenv("MAX_BRIGHT", "235"))
|
| 40 |
+
MIN_SKIN_RATIO = float(os.getenv("MIN_SKIN_RATIO", "0.15"))
|
| 41 |
+
MIN_SHARPNESS = float(os.getenv("MIN_SHARPNESS", "30.0"))
|
| 42 |
+
|
| 43 |
+
# Performance (กัน OOM บน free space)
|
| 44 |
+
os.environ.setdefault("TF_NUM_INTRAOP_THREADS", "1")
|
| 45 |
+
os.environ.setdefault("TF_NUM_INTEROP_THREADS", "1")
|
| 46 |
+
os.environ.setdefault("OMP_NUM_THREADS", "1")
|
| 47 |
+
os.environ.setdefault("TF_CPP_MIN_LOG_LEVEL", "2")
|
| 48 |
+
|
| 49 |
+
# Upload size (กัน DoS)
|
| 50 |
+
MAX_UPLOAD = int(os.getenv("MAX_UPLOAD", str(6 * 1024 * 1024))) # 6MB
|
| 51 |
+
|
| 52 |
+
DF_SIZE = (448, 448)
|
| 53 |
+
|
| 54 |
+
app = FastAPI(title="SkinClassify API (Derm-Foundation)", version="2.0.0")
|
| 55 |
+
app.add_middleware(
|
| 56 |
+
CORSMiddleware,
|
| 57 |
+
allow_origins=os.getenv("ALLOW_ORIGINS", "*").split(","),
|
| 58 |
+
allow_credentials=True,
|
| 59 |
+
allow_methods=["*"],
|
| 60 |
+
allow_headers=["*"],
|
| 61 |
+
)
|
| 62 |
+
|
| 63 |
+
# ---------------------- Load labels ----------------------
|
| 64 |
+
def _load_json(path):
|
| 65 |
+
with open(path, "r", encoding="utf-8") as f:
|
| 66 |
+
return json.load(f)
|
| 67 |
+
|
| 68 |
+
if os.path.exists(LABELS_PATH):
|
| 69 |
+
CLASS_NAMES: List[str] = _load_json(LABELS_PATH)
|
| 70 |
+
logger.info(f"Loaded class_names from {LABELS_PATH}")
|
| 71 |
+
elif NPZ_PATH and os.path.exists(NPZ_PATH):
|
| 72 |
+
arr = np.load(NPZ_PATH, allow_pickle=True)
|
| 73 |
+
if "class_names" in arr:
|
| 74 |
+
CLASS_NAMES = list(arr["class_names"])
|
| 75 |
+
logger.info(f"Loaded class_names from {NPZ_PATH}:class_names")
|
| 76 |
+
else:
|
| 77 |
+
raise RuntimeError("No LABELS_PATH and class_names not found in NPZ")
|
| 78 |
+
else:
|
| 79 |
+
raise RuntimeError("LABELS_PATH not found and NPZ_PATH not provided.")
|
| 80 |
+
C = len(CLASS_NAMES)
|
| 81 |
+
|
| 82 |
+
# ---------------------- Load head ----------------------
|
| 83 |
+
logger.info(f"Loading head from {HEAD_PATH}")
|
| 84 |
+
head = tf.keras.models.load_model(HEAD_PATH, compile=False)
|
| 85 |
+
|
| 86 |
+
# ---------------------- Load mu/sd ----------------------
|
| 87 |
+
def _load_mu_sd():
|
| 88 |
+
if os.path.exists(MU_PATH) and os.path.exists(SD_PATH):
|
| 89 |
+
mu_ = np.load(MU_PATH).astype("float32")
|
| 90 |
+
sd_ = np.load(SD_PATH).astype("float32")
|
| 91 |
+
return mu_, sd_
|
| 92 |
+
if NPZ_PATH and os.path.exists(NPZ_PATH):
|
| 93 |
+
arr = np.load(NPZ_PATH, allow_pickle=True)
|
| 94 |
+
mu_ = arr["mu"].astype("float32")
|
| 95 |
+
sd_ = arr["sd"].astype("float32")
|
| 96 |
+
return mu_, sd_
|
| 97 |
+
raise RuntimeError("mu/sd not found (MU_PATH/SD_PATH or NPZ_PATH).")
|
| 98 |
+
|
| 99 |
+
mu, sd = _load_mu_sd()
|
| 100 |
+
logger.info("Loaded mu/sd")
|
| 101 |
+
|
| 102 |
+
# ---------------------- Load thresholds ----------------------
|
| 103 |
+
if os.path.exists(THRESHOLDS_PATH):
|
| 104 |
+
best_th = np.load(THRESHOLDS_PATH).astype("float32")
|
| 105 |
+
if best_th.shape[0] != C:
|
| 106 |
+
raise RuntimeError(f"thresholds size {best_th.shape[0]} != #classes {C}")
|
| 107 |
+
else:
|
| 108 |
+
logger.warning("THRESHOLDS_PATH not found -> default 0.5 for all classes")
|
| 109 |
+
best_th = np.full(C, 0.5, dtype="float32")
|
| 110 |
+
|
| 111 |
+
# ---------------------- Wrap head with standardization ----------------------
|
| 112 |
+
inp = tf.keras.Input(shape=(mu.shape[-1],), name="embedding")
|
| 113 |
+
x = tf.keras.layers.Lambda(lambda e: (e - mu) / (sd + 1e-6), name="standardize")(inp)
|
| 114 |
+
out = head(x)
|
| 115 |
+
clf = tf.keras.Model(inp, out, name="head_with_norm")
|
| 116 |
+
|
| 117 |
+
# ---------------------- Load derm-foundation ----------------------
|
| 118 |
+
# ใช้ snapshot_download + tf.saved_model.load (ถูกกับโมเดลของ Google)
|
| 119 |
+
logger.info("Loading Derm Foundation (first time may take a while)...")
|
| 120 |
+
try:
|
| 121 |
+
if DERM_LOCAL_DIR and os.path.isdir(DERM_LOCAL_DIR) and os.path.exists(os.path.join(DERM_LOCAL_DIR, "saved_model.pb")):
|
| 122 |
+
derm_dir = DERM_LOCAL_DIR
|
| 123 |
+
logger.info(f"Loaded Derm Foundation from local: {DERM_LOCAL_DIR}")
|
| 124 |
+
else:
|
| 125 |
+
logger.info(f"Downloading derm-foundation from hub: {DERM_MODEL_ID}")
|
| 126 |
+
derm_dir = snapshot_download(
|
| 127 |
+
repo_id=DERM_MODEL_ID,
|
| 128 |
+
repo_type="model",
|
| 129 |
+
allow_patterns=["saved_model.pb", "variables/*"],
|
| 130 |
+
)
|
| 131 |
+
logger.info(f"Derm Foundation downloaded to: {derm_dir}")
|
| 132 |
+
|
| 133 |
+
derm = tf.saved_model.load(derm_dir)
|
| 134 |
+
infer = derm.signatures["serving_default"] # call with key 'inputs'
|
| 135 |
+
except Exception as e:
|
| 136 |
+
raise RuntimeError(
|
| 137 |
+
f"Failed to load derm-foundation: {e}. "
|
| 138 |
+
"Make sure you accepted the model terms on Hugging Face, "
|
| 139 |
+
"or set DERM_LOCAL_DIR to a local SavedModel path."
|
| 140 |
+
)
|
| 141 |
+
|
| 142 |
+
# ---------------------- Utils ----------------------
|
| 143 |
+
def pil_to_png_bytes_448(pil_img: Image.Image) -> bytes:
|
| 144 |
+
pil_img = pil_img.convert("RGB").resize(DF_SIZE)
|
| 145 |
+
arr = np.array(pil_img, dtype=np.uint8)
|
| 146 |
+
return tf.io.encode_png(arr).numpy()
|
| 147 |
+
|
| 148 |
+
def _brightness(np_img_rgb: np.ndarray) -> float:
|
| 149 |
+
r,g,b = np_img_rgb[...,0], np_img_rgb[...,1], np_img_rgb[...,2]
|
| 150 |
+
y = 0.2126*r + 0.7152*g + 0.0722*b
|
| 151 |
+
return float(y.mean())
|
| 152 |
+
|
| 153 |
+
def _sharpness(np_img_rgb: np.ndarray) -> float:
|
| 154 |
+
if not HAS_OPENCV:
|
| 155 |
+
return 100.0
|
| 156 |
+
gray = cv2.cvtColor(np_img_rgb, cv2.COLOR_RGB2GRAY)
|
| 157 |
+
return float(cv2.Laplacian(gray, cv2.CV_64F).var())
|
| 158 |
+
|
| 159 |
+
def _skin_ratio(np_img_rgb: np.ndarray) -> float:
|
| 160 |
+
img = Image.fromarray(np_img_rgb).convert("YCbCr")
|
| 161 |
+
ycbcr = np.array(img)
|
| 162 |
+
Cb = ycbcr[...,1]; Cr = ycbcr[...,2]
|
| 163 |
+
mask = (Cb >= 77) & (Cb <= 127) & (Cr >= 133) & (Cr <= 173)
|
| 164 |
+
return float(mask.mean())
|
| 165 |
+
|
| 166 |
+
def gatekeep_image(img_bytes: bytes) -> Dict[str, Any]:
|
| 167 |
+
try:
|
| 168 |
+
img = Image.open(io.BytesIO(img_bytes)).convert("RGB")
|
| 169 |
+
except Exception:
|
| 170 |
+
return {"ok": False, "reasons": ["invalid_image"], "metrics": {}}
|
| 171 |
+
w,h = img.size
|
| 172 |
+
metrics = {"width": w, "height": h}
|
| 173 |
+
reasons = []
|
| 174 |
+
if w < MIN_W or h < MIN_H:
|
| 175 |
+
reasons.append("too_small")
|
| 176 |
+
aspect = w / h
|
| 177 |
+
metrics["aspect"] = float(aspect)
|
| 178 |
+
if not (MIN_ASPECT <= aspect <= MAX_ASPECT):
|
| 179 |
+
reasons.append("weird_aspect")
|
| 180 |
+
np_img = np.array(img)
|
| 181 |
+
bright = _brightness(np_img)
|
| 182 |
+
metrics["brightness"] = bright
|
| 183 |
+
if bright < MIN_BRIGHT: reasons.append("too_dark")
|
| 184 |
+
if bright > MAX_BRIGHT: reasons.append("too_bright")
|
| 185 |
+
if HAS_OPENCV:
|
| 186 |
+
sharp = _sharpness(np_img)
|
| 187 |
+
metrics["sharpness"] = sharp
|
| 188 |
+
if sharp < MIN_SHARPNESS: reasons.append("too_blurry")
|
| 189 |
+
ratio = _skin_ratio(np_img)
|
| 190 |
+
metrics["skin_ratio"] = ratio
|
| 191 |
+
if ratio < MIN_SKIN_RATIO: reasons.append("not_skin_like")
|
| 192 |
+
return {"ok": len(reasons)==0, "reasons": reasons, "metrics": metrics}
|
| 193 |
+
|
| 194 |
+
def predict_probs(img_bytes: bytes) -> np.ndarray:
|
| 195 |
+
pil = Image.open(io.BytesIO(img_bytes)).convert("RGB").resize(DF_SIZE)
|
| 196 |
+
by = pil_to_png_bytes_448(pil)
|
| 197 |
+
ex = tf.train.Example(features=tf.train.Features(
|
| 198 |
+
feature={'image/encoded': tf.train.Feature(bytes_list=tf.train.BytesList(value=[by]))}
|
| 199 |
+
)).SerializeToString()
|
| 200 |
+
out = infer(inputs=tf.constant([ex]))
|
| 201 |
+
# ปกติคีย์จะชื่อ "embedding"
|
| 202 |
+
if "embedding" not in out:
|
| 203 |
+
raise RuntimeError(f"Unexpected derm-foundation outputs: {list(out.keys())}")
|
| 204 |
+
emb = out["embedding"].numpy().astype("float32") # (1, 6144)
|
| 205 |
+
probs = clf.predict(emb, verbose=0)[0]
|
| 206 |
+
return probs
|
| 207 |
+
|
| 208 |
+
# ---------------------- Endpoints ----------------------
|
| 209 |
+
@app.get("/health")
|
| 210 |
+
def health():
|
| 211 |
+
return {
|
| 212 |
+
"ok": True,
|
| 213 |
+
"classes": len(CLASS_NAMES),
|
| 214 |
+
"derm": DERM_MODEL_ID or DERM_LOCAL_DIR,
|
| 215 |
+
"has_opencv": HAS_OPENCV
|
| 216 |
+
}
|
| 217 |
+
|
| 218 |
+
@app.post("/predict")
|
| 219 |
+
async def predict(request: Request, file: UploadFile = File(...)):
|
| 220 |
+
# limit content-length
|
| 221 |
+
cl = request.headers.get("content-length")
|
| 222 |
+
if cl and int(cl) > MAX_UPLOAD:
|
| 223 |
+
raise HTTPException(413, "File too large")
|
| 224 |
+
img_bytes = await file.read()
|
| 225 |
+
if len(img_bytes) > MAX_UPLOAD:
|
| 226 |
+
raise HTTPException(413, "File too large")
|
| 227 |
+
|
| 228 |
+
gate = gatekeep_image(img_bytes)
|
| 229 |
+
if not gate["ok"]:
|
| 230 |
+
return JSONResponse(status_code=200, content={"ok": False, "reason": "gate_reject", "gate": gate})
|
| 231 |
+
|
| 232 |
+
probs = predict_probs(img_bytes)
|
| 233 |
+
order = np.argsort(probs)[::-1]
|
| 234 |
+
top = [{"label": CLASS_NAMES[i], "prob": float(probs[i])} for i in order[:TOPK]]
|
| 235 |
+
|
| 236 |
+
preds = (probs >= best_th).astype(np.int32)
|
| 237 |
+
positives = [{"label": CLASS_NAMES[i], "prob": float(probs[i])} for i in range(C) if preds[i] == 1]
|
| 238 |
+
|
| 239 |
+
return {
|
| 240 |
+
"ok": True,
|
| 241 |
+
"gate": gate,
|
| 242 |
+
"result": {
|
| 243 |
+
"type": "multilabel",
|
| 244 |
+
"thresholds_used": {CLASS_NAMES[i]: float(best_th[i]) for i in range(C)},
|
| 245 |
+
"positives": positives,
|
| 246 |
+
"topk": top,
|
| 247 |
+
"probs": {CLASS_NAMES[i]: float(probs[i]) for i in range(C)}
|
| 248 |
+
}
|
| 249 |
+
}
|
| 250 |
+
|
| 251 |
+
# สำหรับรันนอก Docker (เช่นทดสอบ local)
|
| 252 |
+
if __name__ == "__main__":
|
| 253 |
+
import uvicorn
|
| 254 |
+
port = int(os.getenv("PORT", "7860"))
|
| 255 |
+
uvicorn.run(app, host="0.0.0.0", port=port, workers=1)
|