yolov13_fastapi_api.py 9.16 KB
Newer Older
chenzk's avatar
v1.0  
chenzk committed
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
#!/usr/bin/env python3
"""
YOLOv13 FastAPI REST API Example

A scalable FastAPI server demonstrating real-time object detection capabilities
using YOLOv13 and other YOLO models. This implementation can be easily extended
to support any YOLO model variant for production deployment.

Key Features:
- Real-time object detection via REST API
- Multi-model support (YOLOv13, YOLOv8, and other variants)
- Configurable inference parameters (confidence, IoU thresholds)
- Production-ready error handling and validation
- Performance monitoring and benchmarking

Performance Highlights:
- YOLOv13n: ~0.146s inference time (6.9 FPS theoretical)
- Scalable to any YOLO model family
- Optimized for real-time applications

For a complete production implementation with advanced features, see:
https://github.com/MohibShaikh/yolov13-fastapi-complete

Usage:
    pip install fastapi uvicorn ultralytics python-multipart
    python yolov13_fastapi_api.py
    
    # Test real-time detection:
    curl -X POST "http://localhost:8000/detect" \
         -F "image=@path/to/image.jpg" \
         -F "model=yolov13n"

Author: MohibShaikh
"""

import time
import logging
from typing import List, Dict, Any, Optional
from pathlib import Path

import cv2
import numpy as np
from fastapi import FastAPI, File, UploadFile, Form, HTTPException
from fastapi.responses import JSONResponse
from pydantic import BaseModel
import uvicorn

# Configure logging
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)

# Initialize FastAPI app
app = FastAPI(
    title="YOLOv13 Real-Time Detection API",
    description="Scalable real-time object detection supporting multiple YOLO models",
    version="1.0.0"
)

# Global model cache
models = {}

class DetectionResult(BaseModel):
    """Detection result model"""
    success: bool
    model_used: str
    inference_time: float
    detections: List[Dict[str, Any]]
    num_detections: int
    image_info: Dict[str, int]

def load_model(model_name: str):
    """Load and cache YOLO model"""
    if model_name not in models:
        try:
            from ultralytics import YOLO
            logger.info(f"Loading {model_name} model...")
            models[model_name] = YOLO(f"{model_name}.pt")
            logger.info(f"Model {model_name} loaded successfully")
        except Exception as e:
            logger.error(f"Failed to load {model_name}: {e}")
            raise HTTPException(status_code=500, detail=f"Model loading failed: {e}")
    
    return models[model_name]

def process_image(image_data: bytes) -> np.ndarray:
    """Convert uploaded image to OpenCV format"""
    try:
        # Convert bytes to numpy array
        nparr = np.frombuffer(image_data, np.uint8)
        # Decode image
        image = cv2.imdecode(nparr, cv2.IMREAD_COLOR)
        
        if image is None:
            raise ValueError("Invalid image format")
        
        return image
    except Exception as e:
        raise HTTPException(status_code=400, detail=f"Image processing failed: {e}")

@app.get("/")
async def root():
    """Root endpoint with API information"""
    return {
        "message": "YOLOv13 Real-Time Object Detection API",
        "description": "Scalable multi-model detection server",
        "capabilities": {
            "real_time_detection": "Sub-second inference times",
            "multi_model_support": "YOLOv13, YOLOv8, and other variants",
            "configurable_parameters": "Confidence and IoU thresholds",
            "production_ready": "Error handling and validation"
        },
        "performance": {
            "yolov13n_fps": "~6.9 FPS theoretical",
            "inference_time": "~0.146s average"
        },
        "endpoints": {
            "/detect": "POST - Real-time object detection",
            "/models": "GET - Available models",
            "/performance": "GET - Performance metrics",
            "/docs": "GET - API documentation"
        }
    }

@app.get("/models")
async def get_models():
    """Get available YOLO models for real-time detection"""
    available_models = ["yolov13n", "yolov13s", "yolov13m", "yolov13l", "yolov13x", 
                       "yolov8n", "yolov8s", "yolov8m", "yolov8l", "yolov8x"]
    
    return {
        "available_models": available_models,
        "loaded_models": list(models.keys()),
        "recommended_for_realtime": "yolov13n",
        "model_info": {
            "nano_models": ["yolov13n", "yolov8n"],
            "small_models": ["yolov13s", "yolov8s"],
            "medium_models": ["yolov13m", "yolov8m"],
            "large_models": ["yolov13l", "yolov8l"],
            "extra_large": ["yolov13x", "yolov8x"]
        },
        "scaling_note": "All models supported - choose based on speed/accuracy requirements"
    }

@app.post("/detect", response_model=DetectionResult)
async def detect_objects(
    image: UploadFile = File(..., description="Image file for real-time object detection"),
    model: str = Form("yolov13n", description="YOLO model to use (any variant supported)"),
    conf: float = Form(0.25, ge=0.0, le=1.0, description="Confidence threshold"),
    iou: float = Form(0.45, ge=0.0, le=1.0, description="IoU threshold")
):
    """
    Real-time object detection using configurable YOLO models
    
    This endpoint demonstrates scalable real-time detection capabilities.
    Supports all YOLO model variants - choose based on your speed/accuracy requirements.
    
    Returns detection results with bounding boxes, confidence scores, and performance metrics.
    """
    
    # Validate model name
    valid_models = ["yolov13n", "yolov13s", "yolov13m", "yolov13l", "yolov13x",
                   "yolov8n", "yolov8s", "yolov8m", "yolov8l", "yolov8x"]
    
    if model not in valid_models:
        raise HTTPException(
            status_code=400, 
            detail=f"Invalid model. Choose from: {', '.join(valid_models)}"
        )
    
    # Validate image
    if not image.content_type or not image.content_type.startswith('image/'):
        raise HTTPException(status_code=400, detail="File must be an image")
    
    try:
        # Read and process image
        image_data = await image.read()
        img = process_image(image_data)
        
        # Load model
        yolo_model = load_model(model)
        
        # Run inference with timing
        start_time = time.time()
        results = yolo_model(img, conf=conf, iou=iou, verbose=False)
        inference_time = time.time() - start_time
        
        # Process results
        detections = []
        if len(results) > 0 and results[0].boxes is not None:
            boxes = results[0].boxes
            
            for i in range(len(boxes)):
                box = boxes[i]
                detection = {
                    "bbox": box.xyxy[0].cpu().numpy().tolist(),  # [x1, y1, x2, y2]
                    "confidence": float(box.conf[0]),
                    "class_id": int(box.cls[0]),
                    "class_name": yolo_model.names[int(box.cls[0])]
                }
                detections.append(detection)
        
        # Return results
        return DetectionResult(
            success=True,
            model_used=model,
            inference_time=round(inference_time, 3),
            detections=detections,
            num_detections=len(detections),
            image_info={
                "width": img.shape[1],
                "height": img.shape[0],
                "channels": img.shape[2]
            }
        )
        
    except HTTPException:
        raise
    except Exception as e:
        logger.error(f"Detection failed: {e}")
        raise HTTPException(status_code=500, detail=f"Detection failed: {str(e)}")

@app.get("/performance")
async def get_performance_metrics():
    """Get real-time performance metrics and scaling information"""
    return {
        "real_time_capabilities": {
            "yolov13n": {
                "inference_time": "~0.146s",
                "fps_theoretical": 6.9,
                "use_case": "Real-time applications",
                "model_tier": "Nano (fastest)"
            },
            "performance_scaling": {
                "nano_models": "Best for real-time (6-7 FPS)",
                "small_models": "Balanced speed/accuracy",
                "medium_models": "Higher accuracy, ~3-4 FPS", 
                "large_models": "Maximum accuracy, ~1-2 FPS"
            }
        },
        "deployment_guidelines": {
            "real_time_streaming": "Use nano models (yolov13n, yolov8n)",
            "batch_processing": "Use larger models for better accuracy",
            "edge_devices": "Nano models recommended",
            "server_deployment": "Any model size supported"
        },
        "scalability": {
            "supported_models": "All YOLO variants",
            "model_switching": "Runtime model selection",
            "configuration": "Adjustable confidence and IoU thresholds",
            "extensibility": "Easy to add new YOLO models"
        }
    }

if __name__ == "__main__":
    print("Starting YOLOv13 Real-Time Detection Server...")
    print("Multi-model support: YOLOv13, YOLOv8, and other variants")
    print("Real-time capability: ~6.9 FPS with YOLOv13n")
    print("API Docs: http://localhost:8000/docs")
    
    uvicorn.run(
        app,
        host="0.0.0.0", 
        port=8000,
        log_level="info"
    )