pipecountapp / main.py
Khunndev
feat: Implement JSON detection endpoint, externalize configuration via environment variables, and enhance health checks.
2bfebd8
Raw History Blame Contribute Delete
18.8 kB
from model import get_yolov5
from fastapi import FastAPI, File, UploadFile, HTTPException, BackgroundTasks, Request, Query
from fastapi.middleware.cors import CORSMiddleware
from fastapi.responses import FileResponse, Response, JSONResponse
from fastapi.staticfiles import StaticFiles
from pathlib import Path
from datetime import datetime
import cv2
import numpy as np
from io import BytesIO
from typing import Tuple, List, Dict, Any, Optional
import time
import asyncio
import os
from concurrent.futures import ThreadPoolExecutor
from functools import lru_cache
# Constants (can be overridden by environment variables)
MIN_IMAGE_HEIGHT = int(os.getenv("MIN_IMAGE_HEIGHT", "1500")) # Reduced for faster processing
INFERENCE_SIZE = int(os.getenv("INFERENCE_SIZE", "1024"))
FONT_SCALE_DIVISOR = 100 # Larger text
TOP_BAR_HEIGHT_PERCENT = 0.1
MIN_TOP_BAR_HEIGHT = 50
CIRCLE_RADIUS_MULTIPLIER = 30
BORDER_THICKNESS = 3
FONT_THICKNESS = 2
MAX_IMAGE_WIDTH = int(os.getenv("MAX_IMAGE_WIDTH", "1500")) # Reduced for faster processing
JPEG_QUALITY = int(os.getenv("JPEG_QUALITY", "85")) # Reduced for faster transfer (85 is visually identical)
CACHE_SIZE = 32
# Concurrency settings - configurable via environment (optimized for HF free tier)
MAX_CONCURRENT_INFERENCES = int(os.getenv("MAX_CONCURRENT", "2"))
MAX_QUEUE_SIZE = int(os.getenv("MAX_QUEUE_SIZE", "10"))
REQUEST_TIMEOUT_SECONDS = int(os.getenv("REQUEST_TIMEOUT", "60"))
CONFIDENCE_THRESHOLD = float(os.getenv("CONFIDENCE_THRESHOLD", "0.6"))
# Simple, high-contrast colors
PRIMARY_COLOR = (0, 0, 255) # Red
TEXT_COLOR = (255, 255, 255) # White
BACKGROUND_COLOR = (0, 0, 0) # Black
HEADER_TEXT_COLOR = (255, 255, 255) # White
# Thread pool for CPU-bound operations
executor = ThreadPoolExecutor(max_workers=MAX_CONCURRENT_INFERENCES)
# Semaphore to limit concurrent inferences
inference_semaphore: Optional[asyncio.Semaphore] = None
# Queue status tracking
queue_status = {
"current_requests": 0,
"total_processed": 0,
"total_rejected": 0
}
class ImageProcessor:
def __init__(self):
self.font_face = cv2.FONT_HERSHEY_SIMPLEX # Clear, simple font
self.text_heights = {}
@staticmethod
def load_image(image_data: bytes) -> np.ndarray:
"""Load image from bytes data"""
try:
image_np = np.frombuffer(image_data, np.uint8)
image = cv2.imdecode(image_np, cv2.IMREAD_COLOR)
if image is None:
raise ValueError("Failed to decode image")
return image
except Exception as e:
raise ValueError(f"Invalid image data: {str(e)}")
@staticmethod
def resize_for_performance(image: np.ndarray) -> np.ndarray:
"""Resize image for optimal performance while maintaining quality"""
h, w = image.shape[:2]
# Only resize if really needed - preserve original image as much as possible
if h < MIN_IMAGE_HEIGHT:
scale = MIN_IMAGE_HEIGHT / h
new_h = MIN_IMAGE_HEIGHT
new_w = int(w * scale)
image = cv2.resize(image, (new_w, new_h), interpolation=cv2.INTER_AREA)
elif w > MAX_IMAGE_WIDTH:
scale = MAX_IMAGE_WIDTH / w
new_w = MAX_IMAGE_WIDTH
new_h = int(h * scale)
image = cv2.resize(image, (new_w, new_h), interpolation=cv2.INTER_AREA)
return image
@staticmethod
def sort_detections_by_position(detections: List[Dict[str, Any]]) -> List[Dict[str, Any]]:
"""Sort detections from top-left to bottom-right"""
# Calculate grid cells for sorting
grid_size = 10 # Number of virtual rows to consider
image_height = max([d['ymax'] for d in detections]) if detections else 1000
grid_height = image_height / grid_size
# Assign each detection to a grid row based on its y-center
for detection in detections:
y_center = (detection['ymin'] + detection['ymax']) / 2
detection['grid_row'] = int(y_center / grid_height)
# Group detections by grid row
rows = {}
for detection in detections:
row = detection['grid_row']
if row not in rows:
rows[row] = []
rows[row].append(detection)
# Sort each row by x-coordinate (left to right)
for row in rows:
rows[row].sort(key=lambda d: d['xmin'])
# Combine all rows in order (top to bottom)
sorted_detections = []
for row in sorted(rows.keys()):
sorted_detections.extend(rows[row])
return sorted_detections
@lru_cache(maxsize=CACHE_SIZE)
def get_text_size(self, text: str, font_scale: float) -> Tuple[int, int]:
"""Get and cache text size calculations"""
size, _ = cv2.getTextSize(text, self.font_face, font_scale, FONT_THICKNESS)
return size
def draw_simple_marker(self, image: np.ndarray, center: Tuple[int, int], text: str,
font_scale: float) -> None:
"""Draw simple, high-contrast circle with number"""
center_x, center_y = center
circle_radius = int(font_scale * CIRCLE_RADIUS_MULTIPLIER)
# Draw circle - thick, bright red border with no fill
cv2.circle(image, (center_x, center_y), circle_radius,
PRIMARY_COLOR, thickness=BORDER_THICKNESS, lineType=cv2.LINE_AA)
# Add white text with black outline for readability
text_size = self.get_text_size(text, font_scale)
text_x = center_x - text_size[0] // 2
text_y = center_y + text_size[1] // 2
# Text outline (black)
for dx, dy in [(-1,-1), (-1,1), (1,-1), (1,1)]:
cv2.putText(image, text, (text_x+dx, text_y+dy), self.font_face,
font_scale, (0,0,0), FONT_THICKNESS+1, lineType=cv2.LINE_AA)
# Main text (white)
cv2.putText(image, text, (text_x, text_y), self.font_face,
font_scale, TEXT_COLOR, FONT_THICKNESS, lineType=cv2.LINE_AA)
def create_simple_top_bar(self, width: int, height: int, total_count: int) -> np.ndarray:
"""Create simple top bar with total count display"""
top_bar_height = max(int(height * TOP_BAR_HEIGHT_PERCENT), MIN_TOP_BAR_HEIGHT)
font_scale = max(top_bar_height // 60, 1)
# Simple solid background
top_bar = np.zeros((top_bar_height, width, 3), dtype=np.uint8)
# Add text
count_text = f"Pipe Count: {total_count}"
cv2.putText(top_bar, count_text, (width//2 - 100, top_bar_height//2 + 10),
self.font_face, font_scale, HEADER_TEXT_COLOR,
FONT_THICKNESS, lineType=cv2.LINE_AA)
return top_bar
# ANSI color codes for console output
class Colors:
RESET = "\033[0m"
BOLD = "\033[1m"
GREEN = "\033[92m"
YELLOW = "\033[93m"
RED = "\033[91m"
BLUE = "\033[94m"
CYAN = "\033[96m"
MAGENTA = "\033[95m"
def log_with_datetime(message: str, level: str = "INFO") -> None:
"""Log message with timestamp and colored level"""
current_time = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
level_colors = {
"INFO": Colors.GREEN,
"WARN": Colors.YELLOW,
"ERROR": Colors.RED,
"DEBUG": Colors.CYAN,
"REQUEST": Colors.BLUE,
"SUCCESS": Colors.MAGENTA,
}
color = level_colors.get(level, Colors.RESET)
print(f"{Colors.BOLD}[{current_time}]{Colors.RESET} {color}[{level}]{Colors.RESET} {message}")
def process_image_sync(image_data: bytes, model) -> bytes:
"""
Synchronous image processing function - runs in thread pool.
This keeps the CPU-bound work off the async event loop.
"""
processor = ImageProcessor()
# Load and prepare image
original_img = processor.load_image(image_data)
original_img = processor.resize_for_performance(original_img)
# Make a clean copy to preserve the original
display_img = original_img.copy()
# Run inference
results = model(original_img, size=INFERENCE_SIZE)
detections = results.pandas().xyxy[0].to_dict('records')
# Sort detections from top-left to bottom-right
sorted_detections = processor.sort_detections_by_position(detections)
total_count = len(sorted_detections)
log_with_datetime(f"Total pipe count: {total_count}")
# Draw simple markers on each detection
for idx, detection in enumerate(sorted_detections):
# Get center of detection
center = (
int((detection['xmin'] + detection['xmax']) / 2),
int((detection['ymin'] + detection['ymax']) / 2)
)
# Calculate text size based on detection size
box_size = min(
detection['xmax'] - detection['xmin'],
detection['ymax'] - detection['ymin']
)
font_scale = box_size / FONT_SCALE_DIVISOR
# Draw marker
processor.draw_simple_marker(display_img, center, str(idx + 1), font_scale)
# Add top bar with count
top_bar = processor.create_simple_top_bar(
display_img.shape[1],
display_img.shape[0],
total_count
)
combined_img = np.vstack((top_bar, display_img))
# Convert to high-quality JPEG
encode_param = [int(cv2.IMWRITE_JPEG_QUALITY), JPEG_QUALITY]
_, img_bytes = cv2.imencode('.jpg', combined_img, encode_param)
return img_bytes.tobytes()
# Initialize FastAPI app
app = FastAPI(
title="PIPE COUNTING API",
description="Upload PIPE image and the API will respond with number of pipes detected. Supports concurrent requests with queue management.",
version="0.0.4",
)
# Configure CORS
app.add_middleware(
CORSMiddleware,
allow_origins=["*"],
allow_methods=["*"],
allow_headers=["*"],
)
# Initialize model (global, loaded once)
model_pipe = None
# Static files path
static_path = Path(__file__).resolve().parent / "static"
@app.on_event("startup")
async def startup_event():
"""Initialize resources on startup"""
global inference_semaphore, model_pipe
print(f"\n{Colors.BOLD}{'='*60}{Colors.RESET}")
print(f"{Colors.BOLD}{Colors.CYAN} 🔧 PIPE COUNTING API - Starting Up{Colors.RESET}")
print(f"{Colors.BOLD}{'='*60}{Colors.RESET}\n")
# Initialize semaphore for concurrency control
inference_semaphore = asyncio.Semaphore(MAX_CONCURRENT_INFERENCES)
log_with_datetime(f"Semaphore initialized (max concurrent: {MAX_CONCURRENT_INFERENCES})")
log_with_datetime(f"Max queue size: {MAX_QUEUE_SIZE}")
log_with_datetime(f"Request timeout: {REQUEST_TIMEOUT_SECONDS}s")
# Load model
log_with_datetime(f"Loading YOLOv5 model (confidence: {CONFIDENCE_THRESHOLD})...")
model_pipe = get_yolov5(CONFIDENCE_THRESHOLD)
log_with_datetime("Model loaded successfully!", "SUCCESS")
# Warmup model with dummy inference
log_with_datetime("Warming up model with dummy inference...")
dummy_img = np.zeros((640, 640, 3), dtype=np.uint8)
model_pipe(dummy_img, size=640)
log_with_datetime("Model warmup complete!", "SUCCESS")
print(f"\n{Colors.BOLD}{Colors.GREEN} ✅ API Ready - Listening on port 7860{Colors.RESET}")
print(f"{Colors.BOLD}{'='*60}{Colors.RESET}\n")
@app.get("/health")
async def health_check():
"""Health check endpoint with queue status and configuration"""
return JSONResponse({
"status": "ok",
"version": "0.0.5",
"queue": {
"current_requests": queue_status["current_requests"],
"max_concurrent": MAX_CONCURRENT_INFERENCES,
"max_queue_size": MAX_QUEUE_SIZE,
"total_processed": queue_status["total_processed"],
"total_rejected": queue_status["total_rejected"]
},
"config": {
"confidence_threshold": CONFIDENCE_THRESHOLD,
"inference_size": INFERENCE_SIZE,
"jpeg_quality": JPEG_QUALITY,
"timeout_seconds": REQUEST_TIMEOUT_SECONDS
}
})
@app.post("/detect/json")
async def detect_image_json(file: UploadFile):
"""
Detect pipes and return JSON with count and detection coordinates.
Faster than /detectImage as it doesn't render the annotated image.
"""
global queue_status
if queue_status["current_requests"] >= MAX_QUEUE_SIZE:
queue_status["total_rejected"] += 1
raise HTTPException(status_code=503, detail="Server busy")
queue_status["current_requests"] += 1
start_time = time.time()
try:
image_data = await file.read()
if not image_data:
raise HTTPException(status_code=400, detail="Empty file")
async with inference_semaphore:
loop = asyncio.get_event_loop()
def run_detection(data: bytes):
processor = ImageProcessor()
img = processor.load_image(data)
img = processor.resize_for_performance(img)
results = model_pipe(img, size=INFERENCE_SIZE)
detections = results.pandas().xyxy[0].to_dict('records')
sorted_dets = processor.sort_detections_by_position(detections)
return [
{
"id": i + 1,
"x": int((d['xmin'] + d['xmax']) / 2),
"y": int((d['ymin'] + d['ymax']) / 2),
"confidence": round(d.get('confidence', 0), 3)
}
for i, d in enumerate(sorted_dets)
]
detections = await asyncio.wait_for(
loop.run_in_executor(executor, run_detection, image_data),
timeout=REQUEST_TIMEOUT_SECONDS
)
total_time = time.time() - start_time
queue_status["total_processed"] += 1
return JSONResponse({
"count": len(detections),
"detections": detections,
"processing_time_ms": int(total_time * 1000)
})
except asyncio.TimeoutError:
raise HTTPException(status_code=504, detail="Request timeout")
except Exception as e:
log_with_datetime(f"JSON detect error: {str(e)}", "ERROR")
raise HTTPException(status_code=500, detail="Processing error")
finally:
queue_status["current_requests"] -= 1
@app.get("/{filename:path}")
async def serve_file(filename: str):
"""Serve static files"""
if not filename:
filename = "index.html"
file_path = static_path / filename
if file_path.is_file():
return FileResponse(file_path)
raise HTTPException(status_code=404, detail="File not found")
@app.post("/detectImage")
async def detect_image(file: UploadFile):
"""
Process uploaded image and detect pipes.
Uses semaphore to limit concurrent inferences and prevent overload.
"""
global queue_status
# Check if queue is full
if queue_status["current_requests"] >= MAX_QUEUE_SIZE:
queue_status["total_rejected"] += 1
log_with_datetime(f"Request rejected - queue full ({queue_status['current_requests']}/{MAX_QUEUE_SIZE})")
raise HTTPException(
status_code=503,
detail=f"Server busy. Please try again in a few seconds. Queue: {queue_status['current_requests']}/{MAX_QUEUE_SIZE}"
)
# Track request
queue_status["current_requests"] += 1
request_id = queue_status["total_processed"] + queue_status["total_rejected"] + queue_status["current_requests"]
start_time = time.time()
try:
# Read image data
image_data = await file.read()
file_size_kb = len(image_data) / 1024
if not image_data:
raise HTTPException(status_code=400, detail="Empty file")
log_with_datetime(
f"📥 Request #{request_id} | File: {file.filename or 'unknown'} ({file_size_kb:.1f}KB) | Queue: {queue_status['current_requests']}/{MAX_QUEUE_SIZE}",
"REQUEST"
)
# Acquire semaphore (limits concurrent model inferences)
async with inference_semaphore:
try:
# Run CPU-bound inference in thread pool with timeout
loop = asyncio.get_event_loop()
result = await asyncio.wait_for(
loop.run_in_executor(executor, process_image_sync, image_data, model_pipe),
timeout=REQUEST_TIMEOUT_SECONDS
)
# Log performance
total_time = time.time() - start_time
queue_status["total_processed"] += 1
log_with_datetime(
f"✅ Request #{request_id} completed | Time: {total_time:.2f}s | Total processed: {queue_status['total_processed']}",
"SUCCESS"
)
return Response(
content=result,
media_type="image/jpeg",
headers={
"X-Processing-Time": f"{total_time:.3f}s",
"X-Queue-Position": "0"
}
)
except asyncio.TimeoutError:
log_with_datetime(f"⏱️ Request #{request_id} timeout after {REQUEST_TIMEOUT_SECONDS}s", "ERROR")
raise HTTPException(
status_code=504,
detail=f"Request timeout after {REQUEST_TIMEOUT_SECONDS} seconds"
)
except HTTPException:
raise
except ValueError as e:
log_with_datetime(f"❌ Request #{request_id} invalid image: {str(e)}", "ERROR")
raise HTTPException(status_code=400, detail=str(e))
except Exception as e:
log_with_datetime(f"❌ Request #{request_id} error: {str(e)}", "ERROR")
raise HTTPException(status_code=500, detail="An error occurred processing the image")
finally:
# Always decrease counter
queue_status["current_requests"] -= 1