Spaces:
Running
Running
File size: 18,759 Bytes
e07dafb 2bfebd8 e07dafb fa700aa 2bfebd8 fa700aa e07dafb 2bfebd8 e07dafb 2bfebd8 e07dafb 2bfebd8 fa700aa e07dafb fa700aa e07dafb fa700aa e07dafb fa700aa e07dafb fa700aa e07dafb fa700aa e07dafb fa700aa e07dafb fa700aa 2bfebd8 fa700aa 2bfebd8 fa700aa 2bfebd8 fa700aa 2bfebd8 fa700aa 2bfebd8 e07dafb fa700aa e07dafb fa700aa e07dafb fa700aa e07dafb fa700aa e07dafb fa700aa e07dafb fa700aa e07dafb fa700aa e07dafb fa700aa | 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 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 | 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 |