Spaces:
Sleeping
Sleeping
Download server.py from ramganeshm/pill-detection-backend: direct link, hf CLI and curl.
- Browser
- Download file 9.13 kB
-
https://huggingface.co/spaces/ramganeshm/pill-detection-backend/resolve/main/server.py
- Command line
-
hf download hf://spaces/ramganeshm/pill-detection-backend/server.py
-
curl -L -o server.py https://huggingface.co/spaces/ramganeshm/pill-detection-backend/resolve/main/server.py
9.13 kB
| """ | |
| RT-DETR Pill Detection Cloud API Service (Hugging Face Spaces) | |
| Provides high-performance live inference for automated pill detection and counting. | |
| Powers the Vercel-hosted frontend web application. | |
| """ | |
| import os | |
| import io | |
| import time | |
| import json | |
| from pathlib import Path | |
| from typing import List, Dict, Any, Optional | |
| from fastapi import FastAPI, UploadFile, File, Form, Query, HTTPException, status | |
| from fastapi.middleware.cors import CORSMiddleware | |
| from fastapi.responses import JSONResponse, PlainTextResponse | |
| from PIL import Image | |
| import numpy as np | |
| BASE_DIR = Path(__file__).resolve().parent | |
| CHECKPOINT_PATH = BASE_DIR / "best.pt" | |
| KAGGLE_METRICS_FILE = BASE_DIR / "kaggle_evaluation_results.json" | |
| MAX_UPLOAD_SIZE = 20 * 1024 * 1024 # 20 MB | |
| MAX_IMAGE_DIMENSION = 4096 | |
| ALLOWED_IMAGE_FORMATS = {"PNG", "JPEG", "JPG", "WEBP"} | |
| MODEL_AVAILABLE = False | |
| try: | |
| import torch | |
| from ultralytics import RTDETR | |
| MODEL_AVAILABLE = True | |
| except ImportError as e: | |
| print(f"Warning: ultralytics or torch import failed: {e}") | |
| app = FastAPI( | |
| title="Pill Detection RT-DETR API", | |
| description="Live AI Inference Service for Dense Medical Pill Detection and Counting (RT-DETR-L)", | |
| version="1.0.0" | |
| ) | |
| # CORS: browsers reject Access-Control-Allow-Origin: * when credentials=True | |
| app.add_middleware( | |
| CORSMiddleware, | |
| allow_origins=["*"], | |
| allow_origin_regex=r"https://.*\.vercel\.app", | |
| allow_credentials=False, | |
| allow_methods=["*"], | |
| allow_headers=["*"], | |
| ) | |
| MODELS = {} | |
| def get_model(): | |
| global MODELS | |
| if not MODEL_AVAILABLE or not CHECKPOINT_PATH.exists(): | |
| return None | |
| key = str(CHECKPOINT_PATH) | |
| if key not in MODELS: | |
| print(f"Loading RT-DETR-L weights from {CHECKPOINT_PATH}...") | |
| MODELS[key] = RTDETR(str(CHECKPOINT_PATH)) | |
| print("Model loaded successfully.") | |
| return MODELS[key] | |
| def root(): | |
| """Root probe + link to docs (HF Space landing).""" | |
| return { | |
| "service": "rt_detr_pill_detection_api", | |
| "status": "ok", | |
| "docs": "/docs", | |
| "endpoints": ["/api/health", "/api/status", "/api/predict", "/agents.md"], | |
| } | |
| def agents_md(): | |
| agents_path = BASE_DIR / "agents.md" | |
| if agents_path.exists(): | |
| return PlainTextResponse(agents_path.read_text(encoding="utf-8")) | |
| return {"detail": "agents.md not found"} | |
| def health_check() -> Dict[str, Any]: | |
| return { | |
| "status": "healthy", | |
| "service": "rt_detr_pill_detection_api", | |
| "checkpoint_exists": CHECKPOINT_PATH.exists(), | |
| "model_loaded": len(MODELS) > 0 | |
| } | |
| def get_status() -> Dict[str, Any]: | |
| has_cuda = False | |
| if MODEL_AVAILABLE: | |
| try: | |
| has_cuda = torch.cuda.is_available() | |
| except Exception: | |
| pass | |
| model = get_model() | |
| benchmark_metrics = None | |
| gpu_benchmark = None | |
| counting_audit = None | |
| if KAGGLE_METRICS_FILE.exists(): | |
| try: | |
| with open(KAGGLE_METRICS_FILE, "r", encoding="utf-8") as f: | |
| b_data = json.load(f) | |
| benchmark_metrics = b_data.get("test_evaluation_metrics") | |
| gpu_benchmark = b_data.get("latency_benchmark") | |
| counting_audit = b_data.get("counting_audit") | |
| except Exception: | |
| pass | |
| return { | |
| "status": "online", | |
| "pipeline": "Pure End-to-End RT-DETR (Native Set Prediction)", | |
| "model_architecture": "RT-DETR-L (Real-Time Detection Transformer)", | |
| "active_checkpoint": str(CHECKPOINT_PATH.name), | |
| "dataset_source": "alexanderyyy/pills-detection-dataset (10,559 images, 140,000+ pills)", | |
| "model_loaded": model is not None, | |
| "device": "CUDA (GPU)" if has_cuda else "Cloud CPU (2 vCPU, 16 GB RAM)", | |
| "cuda_available": has_cuda, | |
| "classes": {0: "pill"}, | |
| "test_split_metrics": benchmark_metrics, | |
| "latency_benchmark": gpu_benchmark, | |
| "counting_audit": counting_audit | |
| } | |
| async def predict_image( | |
| file: UploadFile = File(...), | |
| conf: Optional[float] = Query(None), | |
| confidence_threshold: Optional[float] = Form(None) | |
| ): | |
| t_start = time.perf_counter() | |
| # Default to calibrated optimal confidence (0.50) | |
| effective_conf = conf if conf is not None else (confidence_threshold if confidence_threshold is not None else 0.50) | |
| effective_conf = max(0.01, min(0.99, float(effective_conf))) | |
| model = get_model() | |
| if model is None: | |
| raise HTTPException( | |
| status_code=status.HTTP_503_SERVICE_UNAVAILABLE, | |
| detail="RT-DETR model is not initialized or weights file not found." | |
| ) | |
| # 1. Enforce file size limit | |
| contents = await file.read() | |
| if len(contents) > MAX_UPLOAD_SIZE: | |
| raise HTTPException( | |
| status_code=status.HTTP_413_REQUEST_ENTITY_TOO_LARGE, | |
| detail=f"File size exceeds maximum allowed size of {MAX_UPLOAD_SIZE // (1024**2)}MB." | |
| ) | |
| # 2. Image decoding & validation | |
| try: | |
| pil_img = Image.open(io.BytesIO(contents)) | |
| img_format = (pil_img.format or "").upper() | |
| if img_format not in ALLOWED_IMAGE_FORMATS and not file.filename.lower().endswith(('.jpg', '.jpeg', '.png', '.webp')): | |
| raise HTTPException( | |
| status_code=status.HTTP_400_BAD_REQUEST, | |
| detail=f"Unsupported format '{img_format}'. Supported formats: PNG, JPG, JPEG, WEBP." | |
| ) | |
| pil_img = pil_img.convert("RGB") | |
| w, h = pil_img.size | |
| if w > MAX_IMAGE_DIMENSION or h > MAX_IMAGE_DIMENSION: | |
| raise HTTPException( | |
| status_code=status.HTTP_400_BAD_REQUEST, | |
| detail=f"Image dimensions ({w}x{h}) exceed maximum allowed dimension of {MAX_IMAGE_DIMENSION}px." | |
| ) | |
| except HTTPException: | |
| raise | |
| except Exception as img_err: | |
| raise HTTPException( | |
| status_code=status.HTTP_400_BAD_REQUEST, | |
| detail=f"Invalid or corrupted image: {str(img_err)}" | |
| ) | |
| t_pre_end = time.perf_counter() | |
| preprocess_ms = round((t_pre_end - t_start) * 1000.0, 2) | |
| # 3. Model Forward Inference | |
| t_infer_start = time.perf_counter() | |
| try: | |
| results = model.predict(pil_img, conf=effective_conf, device="cpu", verbose=False) | |
| except Exception as infer_err: | |
| raise HTTPException( | |
| status_code=status.HTTP_500_INTERNAL_SERVER_ERROR, | |
| detail=f"Inference failed: {str(infer_err)}" | |
| ) | |
| t_infer_end = time.perf_counter() | |
| infer_ms = round((t_infer_end - t_infer_start) * 1000.0, 2) | |
| # 4. Post-processing and set prediction extraction | |
| t_post_start = time.perf_counter() | |
| accepted_predictions = [] | |
| if results and len(results) > 0: | |
| res = results[0] | |
| for i, b in enumerate(res.boxes): | |
| xyxy = b.xyxy[0].tolist() | |
| conf_val = float(b.conf[0]) | |
| cls_id = int(b.cls[0]) | |
| x1, y1, x2, y2 = xyxy | |
| x1_norm = max(0.0, min(1.0, x1 / float(w))) | |
| y1_norm = max(0.0, min(1.0, y1 / float(h))) | |
| x2_norm = max(0.0, min(1.0, x2 / float(w))) | |
| y2_norm = max(0.0, min(1.0, y2 / float(h))) | |
| tier = "high" if conf_val >= 0.70 else ("medium" if conf_val >= 0.40 else "low") | |
| accepted_predictions.append({ | |
| "id": f"pred_{i}", | |
| "rank": i + 1, | |
| "confidence": round(conf_val, 4), | |
| "tier": tier, | |
| "needs_review": tier == "low", | |
| "box_xyxy": [round(x1, 2), round(y1, 2), round(x2, 2), round(y2, 2)], | |
| "box_normalized": [round(x1_norm, 4), round(y1_norm, 4), round(x2_norm, 4), round(y2_norm, 4)] | |
| }) | |
| high_count = sum(1 for p in accepted_predictions if p["tier"] == "high") | |
| med_count = sum(1 for p in accepted_predictions if p["tier"] == "medium") | |
| low_count = sum(1 for p in accepted_predictions if p["tier"] == "low") | |
| t_post_end = time.perf_counter() | |
| post_ms = round((t_post_end - t_post_start) * 1000.0, 2) | |
| total_ms = round((time.perf_counter() - t_start) * 1000.0, 2) | |
| return { | |
| "success": True, | |
| "is_live_inference": True, | |
| "pipeline": "Pure End-to-End RT-DETR (Native Set Prediction)", | |
| "filename": file.filename, | |
| "width": w, | |
| "height": h, | |
| "image_resolution": f"{w} × {h} px", | |
| "predicted_count": len(accepted_predictions), | |
| "confidence_threshold": effective_conf, | |
| "latency_breakdown": { | |
| "preprocess_ms": preprocess_ms, | |
| "inference_ms": infer_ms, | |
| "postprocess_ms": post_ms, | |
| "total_ms": total_ms | |
| }, | |
| "predictions": accepted_predictions, | |
| "confidence_summary": { | |
| "high": high_count, | |
| "medium": med_count, | |
| "low": low_count, | |
| "review_required": low_count > 0 | |
| } | |
| } | |
| if __name__ == "__main__": | |
| import uvicorn | |
| port = int(os.environ.get("PORT", 7860)) | |
| uvicorn.run(app, host="0.0.0.0", port=port) | |