Khunndev commited on
Commit
fa700aa
Β·
1 Parent(s): dd117cd

feat: Implement concurrency limits, queue management, and performance optimizations for robust API handling.

Browse files
Files changed (4) hide show
  1. Dockerfile +10 -7
  2. README.md +28 -6
  3. main.py +226 -72
  4. model.py +24 -2
Dockerfile CHANGED
@@ -8,17 +8,17 @@ ENV PYTHONUNBUFFERED=1 \
8
  PYTHONDONTWRITEBYTECODE=1 \
9
  PIP_NO_CACHE_DIR=1 \
10
  PIP_DISABLE_PIP_VERSION_CHECK=1 \
11
- OMP_NUM_THREADS=1 \
12
- MKL_NUM_THREADS=1 \
13
- TORCH_NUM_THREADS=1 \
14
  MPLCONFIGDIR=/home/appuser/.config/matplotlib \
15
  YOLO_CONFIG_DIR=/home/appuser/.config/Ultralytics
16
 
17
  # Create non-root user, /app directory, and config directories all at once
18
  RUN useradd -m appuser && \
19
  mkdir -p /app /home/appuser/.config/matplotlib \
20
- /home/appuser/.config/Ultralytics \
21
- /home/appuser/.local && \
22
  chown -R appuser:appuser /app /home/appuser
23
 
24
  # Set the working directory
@@ -55,5 +55,8 @@ COPY --chown=appuser:appuser . .
55
  # Switch to non-root user for runtime
56
  USER appuser
57
 
58
- # Run with workers optimized for CPU
59
- CMD ["uvicorn", "main:app", "--host", "0.0.0.0", "--port", "7860", "--workers", "1"]
 
 
 
 
8
  PYTHONDONTWRITEBYTECODE=1 \
9
  PIP_NO_CACHE_DIR=1 \
10
  PIP_DISABLE_PIP_VERSION_CHECK=1 \
11
+ OMP_NUM_THREADS=2 \
12
+ MKL_NUM_THREADS=2 \
13
+ TORCH_NUM_THREADS=2 \
14
  MPLCONFIGDIR=/home/appuser/.config/matplotlib \
15
  YOLO_CONFIG_DIR=/home/appuser/.config/Ultralytics
16
 
17
  # Create non-root user, /app directory, and config directories all at once
18
  RUN useradd -m appuser && \
19
  mkdir -p /app /home/appuser/.config/matplotlib \
20
+ /home/appuser/.config/Ultralytics \
21
+ /home/appuser/.local && \
22
  chown -R appuser:appuser /app /home/appuser
23
 
24
  # Set the working directory
 
55
  # Switch to non-root user for runtime
56
  USER appuser
57
 
58
+ # Expose port for Hugging Face Spaces
59
+ EXPOSE 7860
60
+
61
+ # Run with 2 workers for better concurrency, with keep-alive for connection reuse
62
+ CMD ["uvicorn", "main:app", "--host", "0.0.0.0", "--port", "7860", "--workers", "2", "--timeout-keep-alive", "30", "--limit-concurrency", "20"]
README.md CHANGED
@@ -1,11 +1,33 @@
1
  ---
2
- title: Pipecounting
3
- emoji: 🐒
4
- colorFrom: pink
5
- colorTo: yellow
6
  sdk: docker
 
7
  pinned: false
8
- license: mit
9
  ---
10
 
11
- Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
  ---
2
+ title: Pipe Count
3
+ emoji: πŸ”§
4
+ colorFrom: blue
5
+ colorTo: green
6
  sdk: docker
7
+ app_port: 7860
8
  pinned: false
 
9
  ---
10
 
11
+ # Pipe Counting API
12
+
13
+ Upload an image of pipes and the API will detect and count them using YOLOv5.
14
+
15
+ ## Features
16
+
17
+ - **Object Detection**: Counts pipes in images using YOLOv5 custom model
18
+ - **Concurrent Support**: Handles multiple users with queue management
19
+ - **Health Endpoint**: `/health` - Check API status and queue info
20
+
21
+ ## API Endpoints
22
+
23
+ | Endpoint | Method | Description |
24
+ |----------|--------|-------------|
25
+ | `/` | GET | Web interface |
26
+ | `/detectImage` | POST | Upload image for pipe counting |
27
+ | `/health` | GET | Health check with queue status |
28
+
29
+ ## Usage
30
+
31
+ ```bash
32
+ curl -X POST -F "file=@image.jpg" https://your-space.hf.space/detectImage --output result.jpg
33
+ ```
main.py CHANGED
@@ -1,5 +1,5 @@
1
  from model import get_yolov5
2
- from fastapi import FastAPI, File, UploadFile, HTTPException, BackgroundTasks
3
  from fastapi.middleware.cors import CORSMiddleware
4
  from fastapi.responses import FileResponse, Response, JSONResponse
5
  from fastapi.staticfiles import StaticFiles
@@ -10,7 +10,8 @@ import numpy as np
10
  from io import BytesIO
11
  from typing import Tuple, List, Dict, Any, Optional
12
  import time
13
- import concurrent.futures
 
14
  from functools import lru_cache
15
 
16
  # Constants
@@ -26,12 +27,30 @@ MAX_IMAGE_WIDTH = 2000 # Allow larger images
26
  JPEG_QUALITY = 100 # Maximum quality
27
  CACHE_SIZE = 32
28
 
 
 
 
 
 
29
  # Simple, high-contrast colors
30
  PRIMARY_COLOR = (0, 0, 255) # Red
31
  TEXT_COLOR = (255, 255, 255) # White
32
  BACKGROUND_COLOR = (0, 0, 0) # Black
33
  HEADER_TEXT_COLOR = (255, 255, 255) # White
34
 
 
 
 
 
 
 
 
 
 
 
 
 
 
35
  class ImageProcessor:
36
  def __init__(self):
37
  self.font_face = cv2.FONT_HERSHEY_SIMPLEX # Clear, simple font
@@ -47,7 +66,7 @@ class ImageProcessor:
47
  raise ValueError("Failed to decode image")
48
  return image
49
  except Exception as e:
50
- raise HTTPException(status_code=400, detail=f"Invalid image data: {str(e)}")
51
 
52
  @staticmethod
53
  def resize_for_performance(image: np.ndarray) -> np.ndarray:
@@ -146,16 +165,98 @@ class ImageProcessor:
146
 
147
  return top_bar
148
 
149
- def log_with_datetime(message: str) -> None:
150
- """Log message with timestamp"""
 
 
 
 
 
 
 
 
 
 
 
 
 
151
  current_time = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
152
- print(f"[{current_time}] {message}")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
153
 
154
  # Initialize FastAPI app
155
  app = FastAPI(
156
  title="PIPE COUNTING API",
157
- description="Upload PIPE image and the API will respond with number of pipes detected",
158
- version="0.0.3",
159
  )
160
 
161
  # Configure CORS
@@ -166,12 +267,58 @@ app.add_middleware(
166
  allow_headers=["*"],
167
  )
168
 
169
- # Initialize model
170
- model_pipe = get_yolov5(0.6)
171
 
172
  # Static files path
173
  static_path = Path(__file__).resolve().parent / "static"
174
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
175
  @app.get("/{filename:path}")
176
  async def serve_file(filename: str):
177
  """Serve static files"""
@@ -182,77 +329,84 @@ async def serve_file(filename: str):
182
  return FileResponse(file_path)
183
  raise HTTPException(status_code=404, detail="File not found")
184
 
 
185
  @app.post("/detectImage")
186
  async def detect_image(file: UploadFile):
187
- """Process uploaded image and detect pipes"""
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
188
  try:
189
- start_time = time.time()
190
-
191
- # Read and validate image
192
  image_data = await file.read()
 
 
193
  if not image_data:
194
  raise HTTPException(status_code=400, detail="Empty file")
195
 
196
- # Process image
197
- log_with_datetime("Processing image...")
198
- processor = ImageProcessor()
199
-
200
- # Load and prepare image
201
- original_img = processor.load_image(image_data)
202
- original_img = processor.resize_for_performance(original_img)
203
-
204
- # Make a clean copy to preserve the original
205
- display_img = original_img.copy()
206
-
207
- # Run inference
208
- results = model_pipe(original_img, size=INFERENCE_SIZE)
209
- detections = results.pandas().xyxy[0].to_dict('records')
210
-
211
- # Sort detections from top-left to bottom-right
212
- sorted_detections = processor.sort_detections_by_position(detections)
213
-
214
- total_count = len(sorted_detections)
215
- log_with_datetime(f"Total pipe count: {total_count}")
216
-
217
- # Draw simple markers on each detection
218
- for idx, detection in enumerate(sorted_detections):
219
- # Get center of detection
220
- center = (
221
- int((detection['xmin'] + detection['xmax']) / 2),
222
- int((detection['ymin'] + detection['ymax']) / 2)
223
- )
224
-
225
- # Calculate text size based on detection size
226
- box_size = min(
227
- detection['xmax'] - detection['xmin'],
228
- detection['ymax'] - detection['ymin']
229
- )
230
- font_scale = box_size / FONT_SCALE_DIVISOR
231
-
232
- # Draw marker
233
- processor.draw_simple_marker(display_img, center, str(idx + 1), font_scale)
234
-
235
- # Add top bar with count
236
- top_bar = processor.create_simple_top_bar(
237
- display_img.shape[1],
238
- display_img.shape[0],
239
- total_count
240
  )
241
- combined_img = np.vstack((top_bar, display_img))
242
-
243
- # Convert to high-quality JPEG
244
- encode_param = [int(cv2.IMWRITE_JPEG_QUALITY), JPEG_QUALITY]
245
- _, img_bytes = cv2.imencode('.jpg', combined_img, encode_param)
246
-
247
- # Log performance
248
- total_time = time.time() - start_time
249
- log_with_datetime(f"Total processing time: {total_time:.3f} seconds")
250
-
251
- return Response(content=img_bytes.tobytes(), media_type="image/jpeg")
252
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
253
  except HTTPException:
254
  raise
 
 
 
255
  except Exception as e:
256
- log_with_datetime(f"Error processing image: {str(e)}")
257
- raise HTTPException(status_code=500,
258
- detail="An error occurred processing the image")
 
 
 
1
  from model import get_yolov5
2
+ from fastapi import FastAPI, File, UploadFile, HTTPException, BackgroundTasks, Request
3
  from fastapi.middleware.cors import CORSMiddleware
4
  from fastapi.responses import FileResponse, Response, JSONResponse
5
  from fastapi.staticfiles import StaticFiles
 
10
  from io import BytesIO
11
  from typing import Tuple, List, Dict, Any, Optional
12
  import time
13
+ import asyncio
14
+ from concurrent.futures import ThreadPoolExecutor
15
  from functools import lru_cache
16
 
17
  # Constants
 
27
  JPEG_QUALITY = 100 # Maximum quality
28
  CACHE_SIZE = 32
29
 
30
+ # Concurrency settings - optimized for free tier (2 vCPU)
31
+ MAX_CONCURRENT_INFERENCES = 2 # Limit concurrent model runs
32
+ MAX_QUEUE_SIZE = 10 # Reject if queue exceeds this
33
+ REQUEST_TIMEOUT_SECONDS = 60 # Timeout for each request
34
+
35
  # Simple, high-contrast colors
36
  PRIMARY_COLOR = (0, 0, 255) # Red
37
  TEXT_COLOR = (255, 255, 255) # White
38
  BACKGROUND_COLOR = (0, 0, 0) # Black
39
  HEADER_TEXT_COLOR = (255, 255, 255) # White
40
 
41
+ # Thread pool for CPU-bound operations
42
+ executor = ThreadPoolExecutor(max_workers=MAX_CONCURRENT_INFERENCES)
43
+
44
+ # Semaphore to limit concurrent inferences
45
+ inference_semaphore: Optional[asyncio.Semaphore] = None
46
+
47
+ # Queue status tracking
48
+ queue_status = {
49
+ "current_requests": 0,
50
+ "total_processed": 0,
51
+ "total_rejected": 0
52
+ }
53
+
54
  class ImageProcessor:
55
  def __init__(self):
56
  self.font_face = cv2.FONT_HERSHEY_SIMPLEX # Clear, simple font
 
66
  raise ValueError("Failed to decode image")
67
  return image
68
  except Exception as e:
69
+ raise ValueError(f"Invalid image data: {str(e)}")
70
 
71
  @staticmethod
72
  def resize_for_performance(image: np.ndarray) -> np.ndarray:
 
165
 
166
  return top_bar
167
 
168
+
169
+ # ANSI color codes for console output
170
+ class Colors:
171
+ RESET = "\033[0m"
172
+ BOLD = "\033[1m"
173
+ GREEN = "\033[92m"
174
+ YELLOW = "\033[93m"
175
+ RED = "\033[91m"
176
+ BLUE = "\033[94m"
177
+ CYAN = "\033[96m"
178
+ MAGENTA = "\033[95m"
179
+
180
+
181
+ def log_with_datetime(message: str, level: str = "INFO") -> None:
182
+ """Log message with timestamp and colored level"""
183
  current_time = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
184
+
185
+ level_colors = {
186
+ "INFO": Colors.GREEN,
187
+ "WARN": Colors.YELLOW,
188
+ "ERROR": Colors.RED,
189
+ "DEBUG": Colors.CYAN,
190
+ "REQUEST": Colors.BLUE,
191
+ "SUCCESS": Colors.MAGENTA,
192
+ }
193
+
194
+ color = level_colors.get(level, Colors.RESET)
195
+ print(f"{Colors.BOLD}[{current_time}]{Colors.RESET} {color}[{level}]{Colors.RESET} {message}")
196
+
197
+
198
+ def process_image_sync(image_data: bytes, model) -> bytes:
199
+ """
200
+ Synchronous image processing function - runs in thread pool.
201
+ This keeps the CPU-bound work off the async event loop.
202
+ """
203
+ processor = ImageProcessor()
204
+
205
+ # Load and prepare image
206
+ original_img = processor.load_image(image_data)
207
+ original_img = processor.resize_for_performance(original_img)
208
+
209
+ # Make a clean copy to preserve the original
210
+ display_img = original_img.copy()
211
+
212
+ # Run inference
213
+ results = model(original_img, size=INFERENCE_SIZE)
214
+ detections = results.pandas().xyxy[0].to_dict('records')
215
+
216
+ # Sort detections from top-left to bottom-right
217
+ sorted_detections = processor.sort_detections_by_position(detections)
218
+
219
+ total_count = len(sorted_detections)
220
+ log_with_datetime(f"Total pipe count: {total_count}")
221
+
222
+ # Draw simple markers on each detection
223
+ for idx, detection in enumerate(sorted_detections):
224
+ # Get center of detection
225
+ center = (
226
+ int((detection['xmin'] + detection['xmax']) / 2),
227
+ int((detection['ymin'] + detection['ymax']) / 2)
228
+ )
229
+
230
+ # Calculate text size based on detection size
231
+ box_size = min(
232
+ detection['xmax'] - detection['xmin'],
233
+ detection['ymax'] - detection['ymin']
234
+ )
235
+ font_scale = box_size / FONT_SCALE_DIVISOR
236
+
237
+ # Draw marker
238
+ processor.draw_simple_marker(display_img, center, str(idx + 1), font_scale)
239
+
240
+ # Add top bar with count
241
+ top_bar = processor.create_simple_top_bar(
242
+ display_img.shape[1],
243
+ display_img.shape[0],
244
+ total_count
245
+ )
246
+ combined_img = np.vstack((top_bar, display_img))
247
+
248
+ # Convert to high-quality JPEG
249
+ encode_param = [int(cv2.IMWRITE_JPEG_QUALITY), JPEG_QUALITY]
250
+ _, img_bytes = cv2.imencode('.jpg', combined_img, encode_param)
251
+
252
+ return img_bytes.tobytes()
253
+
254
 
255
  # Initialize FastAPI app
256
  app = FastAPI(
257
  title="PIPE COUNTING API",
258
+ description="Upload PIPE image and the API will respond with number of pipes detected. Supports concurrent requests with queue management.",
259
+ version="0.0.4",
260
  )
261
 
262
  # Configure CORS
 
267
  allow_headers=["*"],
268
  )
269
 
270
+ # Initialize model (global, loaded once)
271
+ model_pipe = None
272
 
273
  # Static files path
274
  static_path = Path(__file__).resolve().parent / "static"
275
 
276
+
277
+ @app.on_event("startup")
278
+ async def startup_event():
279
+ """Initialize resources on startup"""
280
+ global inference_semaphore, model_pipe
281
+
282
+ print(f"\n{Colors.BOLD}{'='*60}{Colors.RESET}")
283
+ print(f"{Colors.BOLD}{Colors.CYAN} πŸ”§ PIPE COUNTING API - Starting Up{Colors.RESET}")
284
+ print(f"{Colors.BOLD}{'='*60}{Colors.RESET}\n")
285
+
286
+ # Initialize semaphore for concurrency control
287
+ inference_semaphore = asyncio.Semaphore(MAX_CONCURRENT_INFERENCES)
288
+ log_with_datetime(f"Semaphore initialized (max concurrent: {MAX_CONCURRENT_INFERENCES})")
289
+ log_with_datetime(f"Max queue size: {MAX_QUEUE_SIZE}")
290
+ log_with_datetime(f"Request timeout: {REQUEST_TIMEOUT_SECONDS}s")
291
+
292
+ # Load model
293
+ log_with_datetime("Loading YOLOv5 model...")
294
+ model_pipe = get_yolov5(0.6)
295
+ log_with_datetime("Model loaded successfully!", "SUCCESS")
296
+
297
+ # Warmup model with dummy inference
298
+ log_with_datetime("Warming up model with dummy inference...")
299
+ dummy_img = np.zeros((640, 640, 3), dtype=np.uint8)
300
+ model_pipe(dummy_img, size=640)
301
+ log_with_datetime("Model warmup complete!", "SUCCESS")
302
+
303
+ print(f"\n{Colors.BOLD}{Colors.GREEN} βœ… API Ready - Listening on port 7860{Colors.RESET}")
304
+ print(f"{Colors.BOLD}{'='*60}{Colors.RESET}\n")
305
+
306
+
307
+ @app.get("/health")
308
+ async def health_check():
309
+ """Health check endpoint with queue status"""
310
+ return JSONResponse({
311
+ "status": "ok",
312
+ "queue": {
313
+ "current_requests": queue_status["current_requests"],
314
+ "max_concurrent": MAX_CONCURRENT_INFERENCES,
315
+ "max_queue_size": MAX_QUEUE_SIZE,
316
+ "total_processed": queue_status["total_processed"],
317
+ "total_rejected": queue_status["total_rejected"]
318
+ }
319
+ })
320
+
321
+
322
  @app.get("/{filename:path}")
323
  async def serve_file(filename: str):
324
  """Serve static files"""
 
329
  return FileResponse(file_path)
330
  raise HTTPException(status_code=404, detail="File not found")
331
 
332
+
333
  @app.post("/detectImage")
334
  async def detect_image(file: UploadFile):
335
+ """
336
+ Process uploaded image and detect pipes.
337
+ Uses semaphore to limit concurrent inferences and prevent overload.
338
+ """
339
+ global queue_status
340
+
341
+ # Check if queue is full
342
+ if queue_status["current_requests"] >= MAX_QUEUE_SIZE:
343
+ queue_status["total_rejected"] += 1
344
+ log_with_datetime(f"Request rejected - queue full ({queue_status['current_requests']}/{MAX_QUEUE_SIZE})")
345
+ raise HTTPException(
346
+ status_code=503,
347
+ detail=f"Server busy. Please try again in a few seconds. Queue: {queue_status['current_requests']}/{MAX_QUEUE_SIZE}"
348
+ )
349
+
350
+ # Track request
351
+ queue_status["current_requests"] += 1
352
+ request_id = queue_status["total_processed"] + queue_status["total_rejected"] + queue_status["current_requests"]
353
+ start_time = time.time()
354
+
355
  try:
356
+ # Read image data
 
 
357
  image_data = await file.read()
358
+ file_size_kb = len(image_data) / 1024
359
+
360
  if not image_data:
361
  raise HTTPException(status_code=400, detail="Empty file")
362
 
363
+ log_with_datetime(
364
+ f"πŸ“₯ Request #{request_id} | File: {file.filename or 'unknown'} ({file_size_kb:.1f}KB) | Queue: {queue_status['current_requests']}/{MAX_QUEUE_SIZE}",
365
+ "REQUEST"
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
366
  )
 
 
 
 
 
 
 
 
 
 
 
367
 
368
+ # Acquire semaphore (limits concurrent model inferences)
369
+ async with inference_semaphore:
370
+ try:
371
+ # Run CPU-bound inference in thread pool with timeout
372
+ loop = asyncio.get_event_loop()
373
+ result = await asyncio.wait_for(
374
+ loop.run_in_executor(executor, process_image_sync, image_data, model_pipe),
375
+ timeout=REQUEST_TIMEOUT_SECONDS
376
+ )
377
+
378
+ # Log performance
379
+ total_time = time.time() - start_time
380
+ queue_status["total_processed"] += 1
381
+ log_with_datetime(
382
+ f"βœ… Request #{request_id} completed | Time: {total_time:.2f}s | Total processed: {queue_status['total_processed']}",
383
+ "SUCCESS"
384
+ )
385
+
386
+ return Response(
387
+ content=result,
388
+ media_type="image/jpeg",
389
+ headers={
390
+ "X-Processing-Time": f"{total_time:.3f}s",
391
+ "X-Queue-Position": "0"
392
+ }
393
+ )
394
+
395
+ except asyncio.TimeoutError:
396
+ log_with_datetime(f"⏱️ Request #{request_id} timeout after {REQUEST_TIMEOUT_SECONDS}s", "ERROR")
397
+ raise HTTPException(
398
+ status_code=504,
399
+ detail=f"Request timeout after {REQUEST_TIMEOUT_SECONDS} seconds"
400
+ )
401
+
402
  except HTTPException:
403
  raise
404
+ except ValueError as e:
405
+ log_with_datetime(f"❌ Request #{request_id} invalid image: {str(e)}", "ERROR")
406
+ raise HTTPException(status_code=400, detail=str(e))
407
  except Exception as e:
408
+ log_with_datetime(f"❌ Request #{request_id} error: {str(e)}", "ERROR")
409
+ raise HTTPException(status_code=500, detail="An error occurred processing the image")
410
+ finally:
411
+ # Always decrease counter
412
+ queue_status["current_requests"] -= 1
model.py CHANGED
@@ -1,11 +1,27 @@
1
  import torch
2
  import os
 
 
 
 
 
 
 
 
 
3
 
4
  def get_yolov5(confident_val):
5
- """Initialize YOLOv5 model with CPU optimizations"""
6
  # Force CPU mode
7
  os.environ['CUDA_VISIBLE_DEVICES'] = ''
8
- torch.set_num_threads(1) # Limit to single thread for better CPU performance
 
 
 
 
 
 
 
9
 
10
  # Load model with optimization flags
11
  model = torch.hub.load('./yolov5', 'custom', path='./countmodel.pt', source='local', force_reload=False)
@@ -18,4 +34,10 @@ def get_yolov5(confident_val):
18
  # Enable inference optimizations
19
  model.eval() # Set to evaluation mode
20
 
 
 
 
 
 
21
  return model
 
 
1
  import torch
2
  import os
3
+ import numpy as np
4
+
5
+ # ANSI color codes
6
+ class Colors:
7
+ RESET = "\033[0m"
8
+ BOLD = "\033[1m"
9
+ GREEN = "\033[92m"
10
+ CYAN = "\033[96m"
11
+ YELLOW = "\033[93m"
12
 
13
  def get_yolov5(confident_val):
14
+ """Initialize YOLOv5 model with optimized thread settings"""
15
  # Force CPU mode
16
  os.environ['CUDA_VISIBLE_DEVICES'] = ''
17
+
18
+ # Use multiple threads for better throughput (auto-scale based on CPU)
19
+ num_threads = min(os.cpu_count() or 2, 4) # Cap at 4 threads
20
+ torch.set_num_threads(num_threads)
21
+ torch.set_num_interop_threads(num_threads)
22
+
23
+ print(f"{Colors.CYAN}[MODEL]{Colors.RESET} πŸ”„ Loading YOLOv5 with {Colors.BOLD}{num_threads} threads{Colors.RESET}")
24
+ print(f"{Colors.CYAN}[MODEL]{Colors.RESET} πŸ“Š Confidence threshold: {confident_val}")
25
 
26
  # Load model with optimization flags
27
  model = torch.hub.load('./yolov5', 'custom', path='./countmodel.pt', source='local', force_reload=False)
 
34
  # Enable inference optimizations
35
  model.eval() # Set to evaluation mode
36
 
37
+ # Enable inference mode for better performance
38
+ torch.inference_mode()
39
+
40
+ print(f"{Colors.GREEN}[MODEL]{Colors.RESET} βœ… Model loaded successfully!")
41
+ print(f"{Colors.CYAN}[MODEL]{Colors.RESET} πŸ“ˆ Max detections: {model.max_det}")
42
  return model
43
+