odontify-api / main.py
estrologic's picture
Upload 2 files
22cf9ad verified
Raw History Blame Contribute Delete
11.5 kB
"""
Odontify – Dental AI Pipeline | FastAPI endpoint
Repo: estrologic/odontify_pipeline_yolo_resnet50
Solo se dibujan boxes en dientes donde ResNet50 detecta caries (mild/moderate/severe).
Los dientes 'healthy' se detectan pero NO se anotan.
"""
import base64
import io
import logging
import tempfile
from pathlib import Path
from typing import Optional
import cv2
import numpy as np
import torch
import torch.nn as nn
import torchvision.models as models
import torchvision.transforms as T
from fastapi import FastAPI, File, UploadFile, HTTPException
from fastapi.responses import JSONResponse
from huggingface_hub import hf_hub_download
from ultralytics import YOLO
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)
# ── Constantes ────────────────────────────────────────────────────────
REPO_ID = "estrologic/odontify_pipeline_yolo_resnet50"
CARIES_CLASSES = ["healthy", "mild", "moderate", "severe"]
CARIES_SIZE = 224
CONF_THRESHOLD = 0.25
IOU_THRESHOLD = 0.45
IMG_SIZE = 512
DETECTOR_FILES = {
"T": "T_best.pt",
"B": "B_best.pt",
"F": "F_best.pt",
"L": "L_best.pt",
"R": "R_best.pt",
}
VIEW_FDI = {
"T": [11,12,13,14,15,16,17,18,21,22,23,24,25,26,27,28],
"B": [31,32,33,34,35,36,37,38,41,42,43,44,45,46,47,48],
"F": [11,12,13,14,15,16,17,18,21,22,23,24,25,26,27,28,
31,32,33,34,35,36,37,38,41,42,43,44,45,46,47,48],
"L": [11,12,21,22,23,24,25,26,27,28,
31,32,33,34,35,36,37,38,41,42],
"R": [11,12,13,14,15,16,17,18,21,22,
31,32,41,42,43,44,45,46,47,48],
}
# Solo colores para hallazgos positivos
SEVERITY_COLORS_BGR = {
"mild" : (50, 200, 255),
"moderate": (0, 140, 255),
"severe" : (50, 50, 220),
}
# ── Pipeline ──────────────────────────────────────────────────────────
class OdontifyPipeline:
def __init__(self):
self.device = "cuda" if torch.cuda.is_available() else "cpu"
logger.info(f"Dispositivo: {self.device}")
self.caries_transform = T.Compose([
T.ToPILImage(),
T.Resize((CARIES_SIZE, CARIES_SIZE)),
T.ToTensor(),
T.Normalize(mean=[0.485, 0.456, 0.406],
std= [0.229, 0.224, 0.225]),
])
self._load_models()
def _dl(self, filename: str) -> str:
logger.info(f" Descargando {filename} ...")
return hf_hub_download(repo_id=REPO_ID, filename=filename)
def _load_models(self):
logger.info("Cargando modelos desde Hugging Face...")
# Stage 1
self.view_model = YOLO(self._dl("view_best.pt"))
# Stage 2 – solo guarda paths, instancia al usar
self.det_paths = {v: self._dl(f) for v, f in DETECTOR_FILES.items()}
# Stage 3 – ResNet50 con detecciΓ³n automΓ‘tica de cabeza fc
ckpt = torch.load(self._dl("resnet50_v6_4class_best.pth"),
map_location=self.device)
if isinstance(ckpt, dict) and "model_state_dict" in ckpt:
sd = ckpt["model_state_dict"]
elif isinstance(ckpt, dict) and "state_dict" in ckpt:
sd = ckpt["state_dict"]
else:
sd = ckpt
sd = {k.replace("module.", ""): v for k, v in sd.items()}
inf = models.resnet50(weights=None).fc.in_features
net = models.resnet50(weights=None)
if "fc.weight" in sd:
net.fc = nn.Linear(inf, sd["fc.weight"].shape[0])
else:
net.fc = nn.Sequential(
nn.Linear(inf, sd["fc.0.weight"].shape[0]),
nn.BatchNorm1d(sd["fc.0.weight"].shape[0]),
nn.ReLU(),
nn.Dropout(0.5),
nn.Linear(sd["fc.0.weight"].shape[0], sd["fc.4.weight"].shape[0]),
)
net.load_state_dict(sd, strict=True)
self.caries_model = net.to(self.device).eval()
logger.info("βœ… Todos los modelos cargados.")
# ── Etapa 1 ───────────────────────────────────────────────────────
def _classify_view(self, img_path: str) -> tuple[str, float]:
res = self.view_model(img_path, imgsz=IMG_SIZE, verbose=False)[0]
return res.names[res.probs.top1], float(res.probs.top1conf)
# ── Etapa 2 ───────────────────────────────────────────────────────
def _detect_teeth(self, img_path: str, view: str) -> list[dict]:
res = YOLO(self.det_paths[view])(
img_path, imgsz=IMG_SIZE,
conf=CONF_THRESHOLD, iou=IOU_THRESHOLD, verbose=False
)[0]
fdi_sorted = sorted(VIEW_FDI[view])
teeth = []
if res.boxes is None:
return teeth
for box in res.boxes:
x1, y1, x2, y2 = map(int, box.xyxy[0].tolist())
local_cls = int(box.cls[0])
if local_cls >= len(fdi_sorted):
continue
teeth.append({
"fdi": fdi_sorted[local_cls],
"x1": x1, "y1": y1, "x2": x2, "y2": y2,
"det_conf": round(float(box.conf[0]), 3),
})
return teeth
# ── Etapa 3 ───────────────────────────────────────────────────────
def _classify_caries(self, crop_bgr: np.ndarray) -> tuple[str, float]:
if crop_bgr is None or crop_bgr.size == 0:
return "unknown", 0.0
rgb = cv2.cvtColor(crop_bgr, cv2.COLOR_BGR2RGB)
tensor = self.caries_transform(rgb).unsqueeze(0).to(self.device)
with torch.no_grad():
probs = torch.softmax(self.caries_model(tensor), dim=1)[0]
idx = probs.argmax().item()
return CARIES_CLASSES[idx], round(float(probs[idx]), 3)
# ── Run completo ──────────────────────────────────────────────────
def run(self, img_bytes: bytes) -> tuple[bytes, dict]:
arr = np.frombuffer(img_bytes, np.uint8)
img_bgr = cv2.imdecode(arr, cv2.IMREAD_COLOR)
if img_bgr is None:
raise ValueError("No se pudo decodificar la imagen")
h, w = img_bgr.shape[:2]
# YOLO necesita path en disco
with tempfile.NamedTemporaryFile(suffix=".jpg", delete=False) as tmp:
cv2.imwrite(tmp.name, img_bgr)
tmp_path = tmp.name
try:
# Stage 1
view, view_conf = self._classify_view(tmp_path)
# Stage 2
teeth = self._detect_teeth(tmp_path, view)
finally:
Path(tmp_path).unlink(missing_ok=True)
# Stage 3 + anotaciΓ³n
annotated = img_bgr.copy()
findings = []
with_caries = 0
for tooth in teeth:
x1, y1, x2, y2 = tooth["x1"], tooth["y1"], tooth["x2"], tooth["y2"]
crop = img_bgr[max(0,y1):min(h,y2), max(0,x1):min(w,x2)]
severity, conf = self._classify_caries(crop)
findings.append({
"fdi" : tooth["fdi"],
"severity" : severity,
"confidence": conf,
"bbox" : [x1, y1, x2, y2],
})
# βœ… Box solo si hay caries
if severity not in SEVERITY_COLORS_BGR:
continue
with_caries += 1
color = SEVERITY_COLORS_BGR[severity]
cv2.rectangle(annotated, (x1, y1), (x2, y2), color, 2)
label = f"FDI {tooth['fdi']} | {severity} {conf:.0%}"
(lw, lh), _ = cv2.getTextSize(label, cv2.FONT_HERSHEY_SIMPLEX, 0.45, 1)
y_bg = max(0, y1 - lh - 8)
cv2.rectangle(annotated, (x1, y_bg), (x1 + lw + 4, y1), color, -1)
cv2.putText(annotated, label, (x1 + 2, max(lh, y1 - 4)),
cv2.FONT_HERSHEY_SIMPLEX, 0.45, (0, 0, 0), 1, cv2.LINE_AA)
# Header
header = (f"Vista: {view} ({view_conf:.0%}) | "
f"Dientes: {len(teeth)} | Con caries: {with_caries}")
cv2.putText(annotated, header, (10, 28),
cv2.FONT_HERSHEY_SIMPLEX, 0.7, (255, 255, 255), 2, cv2.LINE_AA)
# Leyenda
for i, (sev, color) in enumerate(SEVERITY_COLORS_BGR.items()):
y_leg = h - 15 - i * 22
cv2.rectangle(annotated, (10, y_leg - 12), (26, y_leg + 2), color, -1)
cv2.putText(annotated, sev, (32, y_leg),
cv2.FONT_HERSHEY_SIMPLEX, 0.5, (255, 255, 255), 1, cv2.LINE_AA)
_, buf = cv2.imencode(".jpg", annotated, [cv2.IMWRITE_JPEG_QUALITY, 92])
summary = {s: sum(1 for f in findings if f["severity"] == s)
for s in CARIES_CLASSES}
report = {
"view" : view,
"view_confidence" : round(view_conf, 3),
"total_teeth_detected": len(teeth),
"teeth_with_caries" : with_caries,
"summary" : summary,
"findings" : findings,
}
return buf.tobytes(), report
# ── FastAPI ───────────────────────────────────────────────────────────
app = FastAPI(
title="Odontify Dental API",
description=(
"Pipeline de IA para anΓ‘lisis dental intraoral (3 etapas).\n\n"
"**POST /analyze** β†’ imagen anotada (base64 JPEG) + JSON con hallazgos FDI.\n\n"
"Solo se anotan dientes con caries (mild / moderate / severe)."
),
version="1.0.0",
)
pipeline: Optional[OdontifyPipeline] = None
@app.on_event("startup")
async def startup():
global pipeline
pipeline = OdontifyPipeline()
@app.get("/")
def root():
return {"status": "ok", "message": "Odontify Dental API 🦷"}
@app.get("/health")
def health():
return {"status": "healthy", "models_loaded": pipeline is not None}
@app.post("/analyze")
async def analyze(file: UploadFile = File(...)):
"""
Recibe imagen intraoral (JPG / PNG).
Retorna:
- **image_base64**: imagen anotada en base64 (JPEG). Solo dientes con caries tienen box.
- **report**: vista, FDI de cada diente, severidad de caries y confianza.
"""
if pipeline is None:
raise HTTPException(503, "Modelos aΓΊn cargando, intenta en unos segundos")
if not file.content_type.startswith("image/"):
raise HTTPException(400, f"Se esperaba imagen, recibido: {file.content_type}")
raw = await file.read()
if not raw:
raise HTTPException(400, "Archivo vacΓ­o")
try:
img_out, report = pipeline.run(raw)
except ValueError as e:
raise HTTPException(400, str(e))
except Exception as e:
logger.exception("Error en pipeline")
raise HTTPException(500, f"Error interno: {e}")
return JSONResponse({
"image_base64": base64.b64encode(img_out).decode(),
"image_format" : "JPEG",
"report" : report,
})