File size: 14,898 Bytes
9cc108e
3c33ae2
 
 
 
 
 
 
9cc108e
14e144e
3c33ae2
 
 
 
 
14e144e
3c33ae2
 
 
 
 
 
9cc108e
3c33ae2
 
14e144e
df82b88
3c33ae2
 
 
 
 
 
 
d7c5a41
3c33ae2
 
d7c5a41
3c33ae2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
deb0b65
3c33ae2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
aaee5da
3c33ae2
 
 
 
 
d7c5a41
3c33ae2
 
 
 
aaee5da
3c33ae2
 
d7c5a41
3c33ae2
 
 
 
 
9cc108e
3c33ae2
 
 
 
 
 
9cc108e
3c33ae2
 
 
 
 
 
 
 
 
 
 
 
 
deb0b65
3c33ae2
 
 
deb0b65
3c33ae2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
aaee5da
3c33ae2
 
 
d7c5a41
3c33ae2
 
d7c5a41
3c33ae2
 
 
d7c5a41
3c33ae2
 
14e144e
3c33ae2
 
 
 
9cc108e
3c33ae2
 
 
d7c5a41
3c33ae2
 
d7c5a41
3c33ae2
 
d7c5a41
3c33ae2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
aaee5da
3c33ae2
34dd9a6
3c33ae2
34dd9a6
 
3c33ae2
aaee5da
3c33ae2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
deb0b65
3c33ae2
 
 
 
 
 
 
 
 
 
 
 
 
 
deb0b65
3c33ae2
 
 
 
 
 
 
 
 
 
 
 
deb0b65
3c33ae2
 
 
deb0b65
3c33ae2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d7c5a41
3c33ae2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d7c5a41
3c33ae2
 
 
d7c5a41
3c33ae2
 
 
 
 
 
 
 
 
 
d7c5a41
3c33ae2
 
9cc108e
3c33ae2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d7c5a41
3c33ae2
 
 
 
 
 
 
d7c5a41
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
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
import os
from contextlib import asynccontextmanager

# ─── 1. MANDATORY BACKEND CONFIG (Must be at the very top) ───────────────────
os.environ["KERAS_BACKEND"] = "jax"
os.environ["JAX_PLATFORM_NAME"] = "cpu"
os.environ["HF_HOME"] = "/tmp/huggingface"

import base64
import logging
import numpy as np
import cv2
import requests
import tempfile
from typing import List, Dict, Any, Optional

import keras
from fastapi import FastAPI, File, UploadFile, HTTPException
from fastapi.responses import JSONResponse
from huggingface_hub import hf_hub_download
from tenacity import retry, stop_after_attempt, wait_exponential, retry_if_exception_type
from inference_sdk import InferenceHTTPClient

# ─── 2. LOGGING & CONFIG ─────────────────────────────────────────────────────
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')
logger = logging.getLogger(__name__)

API_KEY = os.getenv("ROBOFLOW_API_KEY")
WORKSPACE_NAME = "my-workspace-iy9ll"
WORKFLOW_ID = "find-teeth"
IMG_SIZE = 256
THRESHOLD = 0.05
MODEL_REPO = "sairamv1/TeethCariesDetection_CNNAutoencoder"
MODEL_FILENAME = "autoencoder.keras"

MODEL = None
roboflow_client = None

# ─── 3. RETRY-ENABLED MODEL DOWNLOAD ─────────────────────────────────────────
@retry(
    stop=stop_after_attempt(3),
    wait=wait_exponential(multiplier=1, min=2, max=10),
    retry=retry_if_exception_type((requests.RequestException, OSError))
)
def download_model() -> str:
    """Download model from HuggingFace Hub with retry logic."""
    logger.info(f"πŸš€ Downloading model from {MODEL_REPO}...")
    local_path = hf_hub_download(
        repo_id=MODEL_REPO,
        filename=MODEL_FILENAME,
        cache_dir="/tmp/huggingface"
    )
    logger.info(f"βœ… Model downloaded to {local_path}")
    return local_path

def init_roboflow_client():
    """Initialize Roboflow client if API key is available."""
    global roboflow_client
    if API_KEY:
        try:
            roboflow_client = InferenceHTTPClient(
                api_url="https://serverless.roboflow.com",
                api_key=API_KEY
            )
            logger.info("βœ… Roboflow client initialized")
        except Exception as e:
            logger.error(f"❌ Roboflow client initialization failed: {e}")
            roboflow_client = None
    else:
        logger.warning("⚠️ ROBOFLOW_API_KEY not set")

# ─── 4. LIFESPAN EVENT HANDLER ───────────────────────────────────────────────
@asynccontextmanager
async def lifespan(app: FastAPI):
    """Manage model loading at startup and cleanup at shutdown."""
    global MODEL
    try:
        local_model_path = download_model()
        logger.info("πŸ”„ Loading Keras model with JAX backend...")
        MODEL = keras.saving.load_model(local_model_path)
        logger.info(f"βœ… Model loaded successfully! Input shape: {MODEL.input_shape}")
        
        # Initialize Roboflow client
        init_roboflow_client()
    except Exception as e:
        logger.error(f"❌ Startup failed: {e}")
        MODEL = None
    
    yield
    logger.info("πŸ›‘ Shutting down...")

app = FastAPI(
    title="Teeth Caries Detection API",
    description="Dental anomaly detection using CNN Autoencoder",
    version="1.0.0",
    lifespan=lifespan
)

# ─── 5. ROBOFLOW API CALL ────────────────────────────────────────────────────
def call_roboflow_api(image_path: str) -> Dict:
    """Call Roboflow workflow using inference SDK."""
    if not roboflow_client:
        raise Exception("Roboflow client not initialized")
    
    result = roboflow_client.run_workflow(
        workspace_name=WORKSPACE_NAME,
        workflow_id=WORKFLOW_ID,
        images={"image": image_path},
        use_cache=False
    )
    return result

# ─── 6. ROUTES ───────────────────────────────────────────────────────────────
@app.get("/")
async def root():
    """Health check endpoint."""
    return {
        "status": "active",
        "model_ready": MODEL is not None,
        "backend": os.environ.get("KERAS_BACKEND"),
        "api_configured": API_KEY is not None,
        "roboflow_ready": roboflow_client is not None
    }

@app.get("/health")
async def health():
    """Detailed health check."""
    if MODEL is None:
        return JSONResponse(
            status_code=503,
            content={"status": "unhealthy", "reason": "Model not loaded"}
        )
    return {
        "status": "healthy",
        "model_input_shape": str(MODEL.input_shape),
        "roboflow_status": "ready" if roboflow_client else "not configured"
    }

@app.post("/analyze")
async def analyze(file: UploadFile = File(...)):
    """
    Analyze dental image for caries detection.
    
    Returns anomaly scores for each detected tooth.
    """
    if MODEL is None:
        raise HTTPException(status_code=503, detail="Model not initialized. Please retry later.")
    
    if not roboflow_client:
        raise HTTPException(status_code=500, detail="ROBOFLOW_API_KEY not configured")

    # ─── Read and validate image ─────────────────────────────────────────────
    try:
        contents = await file.read()
        if len(contents) == 0:
            raise HTTPException(status_code=400, detail="Empty file uploaded")
        
        nparr = np.frombuffer(contents, np.uint8)
        img = cv2.imdecode(nparr, cv2.IMREAD_COLOR)
        
        if img is None or img.size == 0:
            raise HTTPException(status_code=400, detail="Invalid image format or corrupted file")
        
        img_h, img_w = img.shape[:2]
        if img_h < 50 or img_w < 50:
            raise HTTPException(status_code=400, detail="Image too small (min 50x50 pixels)")
            
    except HTTPException:
        raise
    except Exception as e:
        logger.error(f"Image decode error: {e}")
        raise HTTPException(status_code=400, detail=f"Image processing failed: {str(e)}")

    # ─── Call Roboflow detection ─────────────────────────────────────────────
    tmp_path = None
    try:
        # Save to temp file for inference_sdk
        with tempfile.NamedTemporaryFile(suffix=".jpg", delete=False) as tmp:
            tmp.write(contents)
            tmp_path = tmp.name
        
        result_json = call_roboflow_api(tmp_path)
        
        # ─── DEBUG: Log what Roboflow returns ────────────────────────────────
        logger.info(f"πŸ” Response Type: {type(result_json)}")
        logger.info(f"πŸ” Response Keys: {result_json.keys() if isinstance(result_json, dict) else 'Not a dict'}")
        logger.info(f"πŸ” Full Response: {result_json}")
        
    except Exception as e:
        logger.error(f"Roboflow workflow error: {e}")
        raise HTTPException(status_code=502, detail=f"Detection service failed: {str(e)}")
    finally:
        # Clean up temp file
        if tmp_path and os.path.exists(tmp_path):
            os.remove(tmp_path)

        # ─── Parse detections ────────────────────────────────────────────────────
    predictions = []
    
    try:
        # Handle different response structures
        if isinstance(result_json, list) and len(result_json) > 0:
            # Response is a list
            first_item = result_json[0]
            logger.info(f"πŸ” First item type: {type(first_item)}")
            logger.info(f"πŸ” First item keys: {first_item.keys() if isinstance(first_item, dict) else 'Not dict'}")
            
            # FIXED: Check for "predictions" directly first!
            if isinstance(first_item, dict):
                if "predictions" in first_item:
                    predictions = first_item["predictions"]
                    logger.info(f"βœ… Found predictions directly in first_item")
                elif "outputs" in first_item:
                    outputs = first_item["outputs"]
                    logger.info(f"πŸ” Found outputs: {type(outputs)}")
                    if isinstance(outputs, dict):
                        predictions = outputs.get("predictions", [])
                        
        elif isinstance(result_json, dict):
            # Response is a dict
            logger.info(f"πŸ” Dict keys: {list(result_json.keys())}")
            
            # Try "predictions" first
            if "predictions" in result_json:
                predictions = result_json["predictions"]
            elif "outputs" in result_json:
                outputs = result_json["outputs"]
                if isinstance(outputs, list) and len(outputs) > 0:
                    output_data = outputs[0]
                elif isinstance(outputs, dict):
                    output_data = outputs
                else:
                    output_data = {}
                predictions = output_data.get("predictions", [])
        
        # Handle case where predictions might be a dict
        if isinstance(predictions, dict) and "predictions" in predictions:
            predictions = predictions["predictions"]
        
        logger.info(f"πŸ” Final predictions type: {type(predictions)}")
        logger.info(f"πŸ” Final predictions count: {len(predictions) if isinstance(predictions, list) else 0}")
        if isinstance(predictions, list) and len(predictions) > 0:
            logger.info(f"πŸ” First prediction keys: {predictions[0].keys()}")
            
    except Exception as e:
        logger.error(f"❌ Parsing error: {e}", exc_info=True)
        predictions = []
    
    if not predictions or (isinstance(predictions, list) and len(predictions) == 0):
        logger.warning("⚠️ No predictions found after parsing")
        return {
            "status": "success",
            "tooth_count": 0,
            "results": [],
            "message": "No teeth detected in image"
        }
    
    logger.info(f"βœ… Found {len(predictions)} teeth detections")


    # ─── Process crops ───────────────────────────────────────────────────────
    batch_images = []
    metadata = []

    for i, det in enumerate(predictions[:12]):
        try:
            xc, yc, w, h = det["x"], det["y"], det["width"], det["height"]
            x1 = max(0, int(xc - w/2))
            y1 = max(0, int(yc - h/2))
            x2 = min(img_w, int(xc + w/2))
            y2 = min(img_h, int(yc + h/2))
            
            if x2 <= x1 or y2 <= y1:
                continue
            
            crop = img[y1:y2, x1:x2]
            if crop.size == 0:
                continue

            # Preprocessing pipeline
            gray = cv2.cvtColor(crop, cv2.COLOR_BGR2GRAY)
            clahe = cv2.createCLAHE(clipLimit=2.0, tileGridSize=(8, 8))
            gray = clahe.apply(gray)
            
            # Aspect-ratio preserving resize with padding
            h_c, w_c = gray.shape
            scale = IMG_SIZE / max(h_c, w_c)
            nw, nh = int(w_c * scale), int(h_c * scale)
            resized = cv2.resize(gray, (nw, nh), interpolation=cv2.INTER_AREA)
            
            canvas = np.zeros((IMG_SIZE, IMG_SIZE), dtype=np.uint8)
            y_offset = (IMG_SIZE - nh) // 2
            x_offset = (IMG_SIZE - nw) // 2
            canvas[y_offset:y_offset + nh, x_offset:x_offset + nw] = resized
            
            final_img = (canvas.astype(np.float32) / 255.0)[..., np.newaxis]
            batch_images.append(final_img)
            metadata.append({"id": i, "box": [x1, y1, x2, y2]})
            
            logger.info(f"βœ… Processed tooth {i}: bbox=[{x1},{y1},{x2},{y2}]")
            
        except Exception as e:
            logger.warning(f"⚠️ Skipping detection {i} due to error: {e}")
            continue

    if not batch_images:
        return {
            "status": "success",
            "tooth_count": 0,
            "results": [],
            "message": "No valid tooth crops extracted"
        }

    logger.info(f"βœ… Prepared {len(batch_images)} tooth images for inference")

    # ─── Model inference ─────────────────────────────────────────────────────
    try:
        batch_array = np.array(batch_images)
        logger.info(f"πŸ”„ Running inference on batch shape: {batch_array.shape}")
        reconstructions = MODEL.predict(batch_array, verbose=0)
        errors = np.mean(np.abs(batch_array - reconstructions), axis=(1, 2, 3))
        logger.info(f"βœ… Inference complete. Scores: {errors}")
    except Exception as e:
        logger.error(f"❌ Inference error: {e}")
        raise HTTPException(status_code=500, detail="Model inference failed")

    # ─── Format results ──────────────────────────────────────────────────────
    results = []
    for idx, score in enumerate(errors):
        score_val = float(score)
        results.append({
            "tooth_index": metadata[idx]["id"],
            "anomaly_score": round(score_val, 4),
            "is_caries_detected": score_val > THRESHOLD,
            "bounding_box": metadata[idx]["box"],
            "confidence": "high" if score_val > THRESHOLD * 1.5 else "medium" if score_val > THRESHOLD else "low"
        })

    logger.info(f"πŸŽ‰ Analysis complete: {len(results)} teeth analyzed")
    
    return {
        "status": "success",
        "tooth_count": len(results),
        "detection_threshold": THRESHOLD,
        "results": results
    }

# ─── 7. ERROR HANDLER ────────────────────────────────────────────────────────
@app.exception_handler(Exception)
async def global_exception_handler(request, exc):
    logger.error(f"Unhandled exception: {exc}", exc_info=True)
    return JSONResponse(
        status_code=500,
        content={"detail": "Internal server error occurred"}
    )