File size: 4,534 Bytes
bfae9aa
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
"""
API REST — Pipeline de Escoliose
Endpoint: POST /analyze

Uso:
    uvicorn server:app --host 0.0.0.0 --port 8000
"""

import time
import sys
from pathlib import Path

import numpy as np
import torch
import cv2
import requests
import albumentations as A
from albumentations.pytorch import ToTensorV2
from fastapi import FastAPI, HTTPException
from fastapi.middleware.cors import CORSMiddleware
from pydantic import BaseModel

sys.path.insert(0, str(Path(__file__).parent))
from models.hrnet import build_model
from data.dataset import IMAGE_SIZE

# ── Configuração ──────────────────────────────────────────────────────────────

CKPT_PATH = "results/scoliosis_hrnet/best.pth"

TRANSFORM = A.Compose([
    A.CLAHE(clip_limit=3.0, p=1.0),
    A.Resize(IMAGE_SIZE, IMAGE_SIZE),
    A.Normalize(mean=(0.485, 0.456, 0.406), std=(0.229, 0.224, 0.225)),
    ToTensorV2(),
])

# ── Carregar modelo uma vez no arranque ───────────────────────────────────────

device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
model  = build_model(arch="hrnet", num_outputs=3)
ckpt   = torch.load(CKPT_PATH, map_location=device, weights_only=False)
model.load_state_dict(ckpt["model"])
model  = model.to(device).eval()
print(f"[server] Modelo carregado em {device}")

# ── App ───────────────────────────────────────────────────────────────────────

app = FastAPI(title="Scoliosis Analysis API", version="1.0.0")

app.add_middleware(
    CORSMiddleware,
    allow_origins=["*"],
    allow_methods=["POST", "GET"],
    allow_headers=["*"],
)

# ── Schemas ───────────────────────────────────────────────────────────────────

class AnalyzeRequest(BaseModel):
    estudoId: str
    imageUrl: str

class CobbAngles(BaseModel):
    thoracic_proximal: float
    thoracic_main: float
    lumbar: float

class AnalyzeResponse(BaseModel):
    estudoId: str
    cobb_angles: CobbAngles
    max_angle: float
    classification: str
    processing_time_ms: float

# ── Helpers ───────────────────────────────────────────────────────────────────

def classify(angle: float) -> str:
    if angle < 10:  return "NORMAL"
    if angle < 25:  return "LEVE"
    if angle < 40:  return "MODERADA"
    return "GRAVE"


def download_image(url: str) -> np.ndarray:
    try:
        resp = requests.get(url, timeout=15)
        resp.raise_for_status()
    except requests.RequestException as e:
        raise HTTPException(status_code=400, detail=f"Erro ao descarregar imagem: {e}")

    arr = np.frombuffer(resp.content, np.uint8)
    img = cv2.imdecode(arr, cv2.IMREAD_GRAYSCALE)
    if img is None:
        raise HTTPException(status_code=400, detail="Não foi possível descodificar a imagem.")
    return cv2.cvtColor(img, cv2.COLOR_GRAY2RGB)


@torch.no_grad()
def run_inference(img: np.ndarray) -> list[float]:
    tensor = TRANSFORM(image=img)["image"].unsqueeze(0).to(device)
    return model(tensor)[0].cpu().tolist()

# ── Endpoints ─────────────────────────────────────────────────────────────────

@app.get("/health")
def health():
    return {"status": "ok", "device": str(device)}


@app.post("/analyze", response_model=AnalyzeResponse)
def analyze(body: AnalyzeRequest):
    t0 = time.perf_counter()

    img    = download_image(body.imageUrl)
    angles = run_inference(img)

    t1         = time.perf_counter()
    max_angle  = max(angles)

    return AnalyzeResponse(
        estudoId   = body.estudoId,
        cobb_angles = CobbAngles(
            thoracic_proximal = round(angles[0], 2),
            thoracic_main     = round(angles[1], 2),
            lumbar            = round(angles[2], 2),
        ),
        max_angle          = round(max_angle, 2),
        classification     = classify(max_angle),
        processing_time_ms = round((t1 - t0) * 1000, 1),
    )