Spaces:
Running
Running
Download main.py from npisb/pipecountapp: direct link, hf CLI and curl.
- Browser
- Download file 10 kB
-
https://huggingface.co/spaces/npisb/pipecountapp/resolve/refs%2Fpr%2F2/main.py
- Command line
-
hf download hf://spaces/npisb/pipecountapp@refs/pr/2/main.py
-
curl -L -o main.py https://huggingface.co/spaces/npisb/pipecountapp/resolve/refs%2Fpr%2F2/main.py
10 kB
| from model import get_yolov5 | |
| from fastapi import FastAPI, File, UploadFile, HTTPException, BackgroundTasks | |
| 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 concurrent.futures | |
| from functools import lru_cache | |
| # Constants | |
| MIN_IMAGE_HEIGHT = 2000 | |
| INFERENCE_SIZE = 1024 | |
| FONT_SCALE_DIVISOR = 100 # Larger text | |
| TOP_BAR_HEIGHT_PERCENT = 0.1 | |
| MIN_TOP_BAR_HEIGHT = 50 | |
| CIRCLE_RADIUS_MULTIPLIER = 30 # Smaller circles to avoid covering too much | |
| BORDER_THICKNESS = 3 # Thicker borders for better visibility | |
| FONT_THICKNESS = 2 # Bold text | |
| MAX_IMAGE_WIDTH = 2000 # Allow larger images | |
| JPEG_QUALITY = 100 # Maximum quality | |
| CACHE_SIZE = 32 | |
| # 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 | |
| class ImageProcessor: | |
| def __init__(self): | |
| self.font_face = cv2.FONT_HERSHEY_SIMPLEX # Clear, simple font | |
| self.text_heights = {} | |
| 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 HTTPException(status_code=400, detail=f"Invalid image data: {str(e)}") | |
| 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 | |
| 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 | |
| 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 | |
| def log_with_datetime(message: str) -> None: | |
| """Log message with timestamp""" | |
| current_time = datetime.now().strftime("%Y-%m-%d %H:%M:%S") | |
| print(f"[{current_time}] {message}") | |
| # Initialize FastAPI app | |
| app = FastAPI( | |
| title="PIPE COUNTING API", | |
| description="Upload PIPE image and the API will respond with number of pipes detected", | |
| version="0.0.3", | |
| ) | |
| # Configure CORS | |
| app.add_middleware( | |
| CORSMiddleware, | |
| allow_origins=["*"], | |
| allow_methods=["*"], | |
| allow_headers=["*"], | |
| ) | |
| # Initialize model | |
| model_pipe = get_yolov5(0.6) | |
| # Static files path | |
| static_path = Path(__file__).resolve().parent / "static" | |
| 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") | |
| async def detect_image(file: UploadFile): | |
| """Process uploaded image and detect pipes""" | |
| try: | |
| start_time = time.time() | |
| # Read and validate image | |
| image_data = await file.read() | |
| if not image_data: | |
| raise HTTPException(status_code=400, detail="Empty file") | |
| # Process image | |
| log_with_datetime("Processing image...") | |
| 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_pipe(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) | |
| # Log performance | |
| total_time = time.time() - start_time | |
| log_with_datetime(f"Total processing time: {total_time:.3f} seconds") | |
| return Response(content=img_bytes.tobytes(), media_type="image/jpeg") | |
| except HTTPException: | |
| raise | |
| except Exception as e: | |
| log_with_datetime(f"Error processing image: {str(e)}") | |
| raise HTTPException(status_code=500, | |
| detail="An error occurred processing the image") |