edge detection

#1
by SHREYUC - opened
Files changed (6) hide show
  1. Dockerfile +56 -73
  2. README.md +6 -55
  3. main.py +80 -306
  4. model.py +2 -24
  5. static/images/credit.png +0 -0
  6. static/index.html +1 -1
Dockerfile CHANGED
@@ -1,73 +1,56 @@
1
- # Use lighter Python image optimized for production
2
- FROM python:3.10-slim
3
-
4
- LABEL maintainer="Yuwarath Suktrakool <yuwarasu@scg.com>"
5
-
6
- # Set environment variables for optimization and configuration paths
7
- ENV PYTHONUNBUFFERED=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
- # App configuration (can be overridden at runtime)
18
- ENV MAX_CONCURRENT=2 \
19
- MAX_QUEUE_SIZE=10 \
20
- REQUEST_TIMEOUT=60 \
21
- CONFIDENCE_THRESHOLD=0.6 \
22
- JPEG_QUALITY=85
23
-
24
- # Create non-root user, /app directory, and config directories all at once
25
- RUN useradd -m appuser && \
26
- mkdir -p /app /home/appuser/.config/matplotlib \
27
- /home/appuser/.config/Ultralytics \
28
- /home/appuser/.local && \
29
- chown -R appuser:appuser /app /home/appuser
30
-
31
- # Set the working directory
32
- WORKDIR /app
33
-
34
- # Install system dependencies (as root)
35
- RUN apt-get update && \
36
- apt-get install -y --no-install-recommends \
37
- ffmpeg libsm6 libxext6 git curl \
38
- && rm -rf /var/lib/apt/lists/*
39
-
40
- # Copy requirements first and set ownership to leverage Docker cache
41
- COPY --chown=appuser:appuser requirements.txt .
42
-
43
- # Install Python dependencies (as root)
44
- RUN pip install --no-cache-dir -r requirements.txt
45
-
46
- # --- Switch to appuser to create files ---
47
- # By running git clone as 'appuser', the files will already have the correct owner
48
- USER appuser
49
-
50
- # Clone YOLOv5 as appuser and remove .git to reduce size
51
- RUN git clone --depth 1 https://github.com/ultralytics/yolov5.git && \
52
- rm -rf yolov5/.git
53
-
54
- # --- Switch back to root to copy remaining files ---
55
- # This is necessary because the build context files (from your computer) are owned by root
56
- USER root
57
-
58
- # Copy application code and set ownership
59
- # This REPLACES your old 'COPY . .' and the failing 'RUN chown...'
60
- COPY --chown=appuser:appuser . .
61
-
62
- # Switch to non-root user for runtime
63
- USER appuser
64
-
65
- # Expose port for Hugging Face Spaces
66
- EXPOSE 7860
67
-
68
- # Health check - verify API is responding
69
- HEALTHCHECK --interval=30s --timeout=10s --start-period=60s --retries=3 \
70
- CMD curl -f http://localhost:7860/health || exit 1
71
-
72
- # Run with 2 workers for better concurrency, with keep-alive for connection reuse
73
- CMD ["uvicorn", "main:app", "--host", "0.0.0.0", "--port", "7860", "--workers", "2", "--timeout-keep-alive", "30", "--limit-concurrency", "20"]
 
1
+ # Use lighter Python image optimized for production
2
+ FROM python:3.10-slim
3
+
4
+ LABEL maintainer="Yuwarath Suktrakool <yuwarasu@scg.com>"
5
+
6
+ # Set environment variables for optimization and configuration paths
7
+ 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
18
+ RUN useradd -m appuser && \
19
+ mkdir -p /app && \
20
+ chown appuser:appuser /app
21
+
22
+ # Set the working directory
23
+ WORKDIR /app
24
+
25
+ # Create and set permissions for config directories
26
+ RUN mkdir -p /home/appuser/.config/matplotlib && \
27
+ mkdir -p /home/appuser/.config/Ultralytics && \
28
+ mkdir -p /home/appuser/.local && \
29
+ chown -R appuser:appuser /home/appuser
30
+
31
+ # Install system dependencies
32
+ RUN apt-get update && \
33
+ apt-get install -y --no-install-recommends \
34
+ ffmpeg libsm6 libxext6 git \
35
+ && rm -rf /var/lib/apt/lists/*
36
+
37
+ # Clone YOLOv5 and remove .git to reduce size
38
+ RUN git clone --depth 1 https://github.com/ultralytics/yolov5.git && \
39
+ rm -rf yolov5/.git
40
+
41
+ # Copy requirements first to leverage Docker cache
42
+ COPY requirements.txt .
43
+
44
+ # Install Python dependencies
45
+ RUN pip install --no-cache-dir -r requirements.txt && \
46
+ chown -R appuser:appuser /app
47
+
48
+ # Copy application code
49
+ COPY . .
50
+ RUN chown -R appuser:appuser /app
51
+
52
+ # Switch to non-root user
53
+ USER appuser
54
+
55
+ # Run with workers optimized for CPU
56
+ CMD ["uvicorn", "main:app", "--host", "0.0.0.0", "--port", "7860", "--workers", "1"]
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
README.md CHANGED
@@ -1,60 +1,11 @@
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
- - **JSON API**: Get count and coordinates without image rendering
20
- - **Health Monitoring**: Check API status and queue info
21
-
22
- ## API Endpoints
23
-
24
- | Endpoint | Method | Description |
25
- |----------|--------|-------------|
26
- | `/` | GET | Web interface |
27
- | `/detectImage` | POST | Upload image, get annotated result |
28
- | `/detect/json` | POST | Upload image, get JSON response |
29
- | `/health` | GET | Health check with config info |
30
-
31
- ## Usage
32
-
33
- **Get annotated image:**
34
- ```bash
35
- curl -X POST -F "file=@image.jpg" https://your-space.hf.space/detectImage -o result.jpg
36
- ```
37
-
38
- **Get JSON response (faster):**
39
- ```bash
40
- curl -X POST -F "file=@image.jpg" https://your-space.hf.space/detect/json
41
- ```
42
-
43
- **Response:**
44
- ```json
45
- {
46
- "count": 42,
47
- "detections": [{"id": 1, "x": 150, "y": 200, "confidence": 0.95}, ...],
48
- "processing_time_ms": 2340
49
- }
50
- ```
51
-
52
- ## Configuration (Environment Variables)
53
-
54
- | Variable | Default | Description |
55
- |----------|---------|-------------|
56
- | `MAX_CONCURRENT` | 2 | Max concurrent inferences |
57
- | `MAX_QUEUE_SIZE` | 10 | Max queued requests |
58
- | `REQUEST_TIMEOUT` | 60 | Timeout in seconds |
59
- | `CONFIDENCE_THRESHOLD` | 0.6 | Detection confidence |
60
- | `JPEG_QUALITY` | 85 | Output image quality |
 
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
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
main.py CHANGED
@@ -1,5 +1,5 @@
1
  from model import get_yolov5
2
- from fastapi import FastAPI, File, UploadFile, HTTPException, BackgroundTasks, Request, Query
3
  from fastapi.middleware.cors import CORSMiddleware
4
  from fastapi.responses import FileResponse, Response, JSONResponse
5
  from fastapi.staticfiles import StaticFiles
@@ -10,49 +10,28 @@ import numpy as np
10
  from io import BytesIO
11
  from typing import Tuple, List, Dict, Any, Optional
12
  import time
13
- import asyncio
14
- import os
15
- from concurrent.futures import ThreadPoolExecutor
16
  from functools import lru_cache
17
 
18
- # Constants (can be overridden by environment variables)
19
- MIN_IMAGE_HEIGHT = int(os.getenv("MIN_IMAGE_HEIGHT", "1500")) # Reduced for faster processing
20
- INFERENCE_SIZE = int(os.getenv("INFERENCE_SIZE", "1024"))
21
  FONT_SCALE_DIVISOR = 100 # Larger text
22
  TOP_BAR_HEIGHT_PERCENT = 0.1
23
  MIN_TOP_BAR_HEIGHT = 50
24
- CIRCLE_RADIUS_MULTIPLIER = 30
25
- BORDER_THICKNESS = 3
26
- FONT_THICKNESS = 2
27
- MAX_IMAGE_WIDTH = int(os.getenv("MAX_IMAGE_WIDTH", "1500")) # Reduced for faster processing
28
- JPEG_QUALITY = int(os.getenv("JPEG_QUALITY", "85")) # Reduced for faster transfer (85 is visually identical)
29
  CACHE_SIZE = 32
30
 
31
- # Concurrency settings - configurable via environment (optimized for HF free tier)
32
- MAX_CONCURRENT_INFERENCES = int(os.getenv("MAX_CONCURRENT", "2"))
33
- MAX_QUEUE_SIZE = int(os.getenv("MAX_QUEUE_SIZE", "10"))
34
- REQUEST_TIMEOUT_SECONDS = int(os.getenv("REQUEST_TIMEOUT", "60"))
35
- CONFIDENCE_THRESHOLD = float(os.getenv("CONFIDENCE_THRESHOLD", "0.6"))
36
-
37
  # Simple, high-contrast colors
38
  PRIMARY_COLOR = (0, 0, 255) # Red
39
  TEXT_COLOR = (255, 255, 255) # White
40
  BACKGROUND_COLOR = (0, 0, 0) # Black
41
  HEADER_TEXT_COLOR = (255, 255, 255) # White
42
 
43
- # Thread pool for CPU-bound operations
44
- executor = ThreadPoolExecutor(max_workers=MAX_CONCURRENT_INFERENCES)
45
-
46
- # Semaphore to limit concurrent inferences
47
- inference_semaphore: Optional[asyncio.Semaphore] = None
48
-
49
- # Queue status tracking
50
- queue_status = {
51
- "current_requests": 0,
52
- "total_processed": 0,
53
- "total_rejected": 0
54
- }
55
-
56
  class ImageProcessor:
57
  def __init__(self):
58
  self.font_face = cv2.FONT_HERSHEY_SIMPLEX # Clear, simple font
@@ -68,7 +47,7 @@ class ImageProcessor:
68
  raise ValueError("Failed to decode image")
69
  return image
70
  except Exception as e:
71
- raise ValueError(f"Invalid image data: {str(e)}")
72
 
73
  @staticmethod
74
  def resize_for_performance(image: np.ndarray) -> np.ndarray:
@@ -167,98 +146,16 @@ class ImageProcessor:
167
 
168
  return top_bar
169
 
170
-
171
- # ANSI color codes for console output
172
- class Colors:
173
- RESET = "\033[0m"
174
- BOLD = "\033[1m"
175
- GREEN = "\033[92m"
176
- YELLOW = "\033[93m"
177
- RED = "\033[91m"
178
- BLUE = "\033[94m"
179
- CYAN = "\033[96m"
180
- MAGENTA = "\033[95m"
181
-
182
-
183
- def log_with_datetime(message: str, level: str = "INFO") -> None:
184
- """Log message with timestamp and colored level"""
185
  current_time = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
186
-
187
- level_colors = {
188
- "INFO": Colors.GREEN,
189
- "WARN": Colors.YELLOW,
190
- "ERROR": Colors.RED,
191
- "DEBUG": Colors.CYAN,
192
- "REQUEST": Colors.BLUE,
193
- "SUCCESS": Colors.MAGENTA,
194
- }
195
-
196
- color = level_colors.get(level, Colors.RESET)
197
- print(f"{Colors.BOLD}[{current_time}]{Colors.RESET} {color}[{level}]{Colors.RESET} {message}")
198
-
199
-
200
- def process_image_sync(image_data: bytes, model) -> bytes:
201
- """
202
- Synchronous image processing function - runs in thread pool.
203
- This keeps the CPU-bound work off the async event loop.
204
- """
205
- processor = ImageProcessor()
206
-
207
- # Load and prepare image
208
- original_img = processor.load_image(image_data)
209
- original_img = processor.resize_for_performance(original_img)
210
-
211
- # Make a clean copy to preserve the original
212
- display_img = original_img.copy()
213
-
214
- # Run inference
215
- results = model(original_img, size=INFERENCE_SIZE)
216
- detections = results.pandas().xyxy[0].to_dict('records')
217
-
218
- # Sort detections from top-left to bottom-right
219
- sorted_detections = processor.sort_detections_by_position(detections)
220
-
221
- total_count = len(sorted_detections)
222
- log_with_datetime(f"Total pipe count: {total_count}")
223
-
224
- # Draw simple markers on each detection
225
- for idx, detection in enumerate(sorted_detections):
226
- # Get center of detection
227
- center = (
228
- int((detection['xmin'] + detection['xmax']) / 2),
229
- int((detection['ymin'] + detection['ymax']) / 2)
230
- )
231
-
232
- # Calculate text size based on detection size
233
- box_size = min(
234
- detection['xmax'] - detection['xmin'],
235
- detection['ymax'] - detection['ymin']
236
- )
237
- font_scale = box_size / FONT_SCALE_DIVISOR
238
-
239
- # Draw marker
240
- processor.draw_simple_marker(display_img, center, str(idx + 1), font_scale)
241
-
242
- # Add top bar with count
243
- top_bar = processor.create_simple_top_bar(
244
- display_img.shape[1],
245
- display_img.shape[0],
246
- total_count
247
- )
248
- combined_img = np.vstack((top_bar, display_img))
249
-
250
- # Convert to high-quality JPEG
251
- encode_param = [int(cv2.IMWRITE_JPEG_QUALITY), JPEG_QUALITY]
252
- _, img_bytes = cv2.imencode('.jpg', combined_img, encode_param)
253
-
254
- return img_bytes.tobytes()
255
-
256
 
257
  # Initialize FastAPI app
258
  app = FastAPI(
259
  title="PIPE COUNTING API",
260
- description="Upload PIPE image and the API will respond with number of pipes detected. Supports concurrent requests with queue management.",
261
- version="0.0.4",
262
  )
263
 
264
  # Configure CORS
@@ -269,128 +166,12 @@ app.add_middleware(
269
  allow_headers=["*"],
270
  )
271
 
272
- # Initialize model (global, loaded once)
273
- model_pipe = None
274
 
275
  # Static files path
276
  static_path = Path(__file__).resolve().parent / "static"
277
 
278
-
279
- @app.on_event("startup")
280
- async def startup_event():
281
- """Initialize resources on startup"""
282
- global inference_semaphore, model_pipe
283
-
284
- print(f"\n{Colors.BOLD}{'='*60}{Colors.RESET}")
285
- print(f"{Colors.BOLD}{Colors.CYAN} 🔧 PIPE COUNTING API - Starting Up{Colors.RESET}")
286
- print(f"{Colors.BOLD}{'='*60}{Colors.RESET}\n")
287
-
288
- # Initialize semaphore for concurrency control
289
- inference_semaphore = asyncio.Semaphore(MAX_CONCURRENT_INFERENCES)
290
- log_with_datetime(f"Semaphore initialized (max concurrent: {MAX_CONCURRENT_INFERENCES})")
291
- log_with_datetime(f"Max queue size: {MAX_QUEUE_SIZE}")
292
- log_with_datetime(f"Request timeout: {REQUEST_TIMEOUT_SECONDS}s")
293
-
294
- # Load model
295
- log_with_datetime(f"Loading YOLOv5 model (confidence: {CONFIDENCE_THRESHOLD})...")
296
- model_pipe = get_yolov5(CONFIDENCE_THRESHOLD)
297
- log_with_datetime("Model loaded successfully!", "SUCCESS")
298
-
299
- # Warmup model with dummy inference
300
- log_with_datetime("Warming up model with dummy inference...")
301
- dummy_img = np.zeros((640, 640, 3), dtype=np.uint8)
302
- model_pipe(dummy_img, size=640)
303
- log_with_datetime("Model warmup complete!", "SUCCESS")
304
-
305
- print(f"\n{Colors.BOLD}{Colors.GREEN} ✅ API Ready - Listening on port 7860{Colors.RESET}")
306
- print(f"{Colors.BOLD}{'='*60}{Colors.RESET}\n")
307
-
308
-
309
- @app.get("/health")
310
- async def health_check():
311
- """Health check endpoint with queue status and configuration"""
312
- return JSONResponse({
313
- "status": "ok",
314
- "version": "0.0.5",
315
- "queue": {
316
- "current_requests": queue_status["current_requests"],
317
- "max_concurrent": MAX_CONCURRENT_INFERENCES,
318
- "max_queue_size": MAX_QUEUE_SIZE,
319
- "total_processed": queue_status["total_processed"],
320
- "total_rejected": queue_status["total_rejected"]
321
- },
322
- "config": {
323
- "confidence_threshold": CONFIDENCE_THRESHOLD,
324
- "inference_size": INFERENCE_SIZE,
325
- "jpeg_quality": JPEG_QUALITY,
326
- "timeout_seconds": REQUEST_TIMEOUT_SECONDS
327
- }
328
- })
329
-
330
-
331
- @app.post("/detect/json")
332
- async def detect_image_json(file: UploadFile):
333
- """
334
- Detect pipes and return JSON with count and detection coordinates.
335
- Faster than /detectImage as it doesn't render the annotated image.
336
- """
337
- global queue_status
338
-
339
- if queue_status["current_requests"] >= MAX_QUEUE_SIZE:
340
- queue_status["total_rejected"] += 1
341
- raise HTTPException(status_code=503, detail="Server busy")
342
-
343
- queue_status["current_requests"] += 1
344
- start_time = time.time()
345
-
346
- try:
347
- image_data = await file.read()
348
- if not image_data:
349
- raise HTTPException(status_code=400, detail="Empty file")
350
-
351
- async with inference_semaphore:
352
- loop = asyncio.get_event_loop()
353
-
354
- def run_detection(data: bytes):
355
- processor = ImageProcessor()
356
- img = processor.load_image(data)
357
- img = processor.resize_for_performance(img)
358
- results = model_pipe(img, size=INFERENCE_SIZE)
359
- detections = results.pandas().xyxy[0].to_dict('records')
360
- sorted_dets = processor.sort_detections_by_position(detections)
361
- return [
362
- {
363
- "id": i + 1,
364
- "x": int((d['xmin'] + d['xmax']) / 2),
365
- "y": int((d['ymin'] + d['ymax']) / 2),
366
- "confidence": round(d.get('confidence', 0), 3)
367
- }
368
- for i, d in enumerate(sorted_dets)
369
- ]
370
-
371
- detections = await asyncio.wait_for(
372
- loop.run_in_executor(executor, run_detection, image_data),
373
- timeout=REQUEST_TIMEOUT_SECONDS
374
- )
375
-
376
- total_time = time.time() - start_time
377
- queue_status["total_processed"] += 1
378
-
379
- return JSONResponse({
380
- "count": len(detections),
381
- "detections": detections,
382
- "processing_time_ms": int(total_time * 1000)
383
- })
384
-
385
- except asyncio.TimeoutError:
386
- raise HTTPException(status_code=504, detail="Request timeout")
387
- except Exception as e:
388
- log_with_datetime(f"JSON detect error: {str(e)}", "ERROR")
389
- raise HTTPException(status_code=500, detail="Processing error")
390
- finally:
391
- queue_status["current_requests"] -= 1
392
-
393
-
394
  @app.get("/{filename:path}")
395
  async def serve_file(filename: str):
396
  """Serve static files"""
@@ -401,84 +182,77 @@ async def serve_file(filename: str):
401
  return FileResponse(file_path)
402
  raise HTTPException(status_code=404, detail="File not found")
403
 
404
-
405
  @app.post("/detectImage")
406
  async def detect_image(file: UploadFile):
407
- """
408
- Process uploaded image and detect pipes.
409
- Uses semaphore to limit concurrent inferences and prevent overload.
410
- """
411
- global queue_status
412
-
413
- # Check if queue is full
414
- if queue_status["current_requests"] >= MAX_QUEUE_SIZE:
415
- queue_status["total_rejected"] += 1
416
- log_with_datetime(f"Request rejected - queue full ({queue_status['current_requests']}/{MAX_QUEUE_SIZE})")
417
- raise HTTPException(
418
- status_code=503,
419
- detail=f"Server busy. Please try again in a few seconds. Queue: {queue_status['current_requests']}/{MAX_QUEUE_SIZE}"
420
- )
421
-
422
- # Track request
423
- queue_status["current_requests"] += 1
424
- request_id = queue_status["total_processed"] + queue_status["total_rejected"] + queue_status["current_requests"]
425
- start_time = time.time()
426
-
427
  try:
428
- # Read image data
429
- image_data = await file.read()
430
- file_size_kb = len(image_data) / 1024
431
 
 
 
432
  if not image_data:
433
  raise HTTPException(status_code=400, detail="Empty file")
434
 
435
- log_with_datetime(
436
- f"📥 Request #{request_id} | File: {file.filename or 'unknown'} ({file_size_kb:.1f}KB) | Queue: {queue_status['current_requests']}/{MAX_QUEUE_SIZE}",
437
- "REQUEST"
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
438
  )
 
 
 
 
 
 
 
 
 
 
 
439
 
440
- # Acquire semaphore (limits concurrent model inferences)
441
- async with inference_semaphore:
442
- try:
443
- # Run CPU-bound inference in thread pool with timeout
444
- loop = asyncio.get_event_loop()
445
- result = await asyncio.wait_for(
446
- loop.run_in_executor(executor, process_image_sync, image_data, model_pipe),
447
- timeout=REQUEST_TIMEOUT_SECONDS
448
- )
449
-
450
- # Log performance
451
- total_time = time.time() - start_time
452
- queue_status["total_processed"] += 1
453
- log_with_datetime(
454
- f"✅ Request #{request_id} completed | Time: {total_time:.2f}s | Total processed: {queue_status['total_processed']}",
455
- "SUCCESS"
456
- )
457
-
458
- return Response(
459
- content=result,
460
- media_type="image/jpeg",
461
- headers={
462
- "X-Processing-Time": f"{total_time:.3f}s",
463
- "X-Queue-Position": "0"
464
- }
465
- )
466
-
467
- except asyncio.TimeoutError:
468
- log_with_datetime(f"⏱️ Request #{request_id} timeout after {REQUEST_TIMEOUT_SECONDS}s", "ERROR")
469
- raise HTTPException(
470
- status_code=504,
471
- detail=f"Request timeout after {REQUEST_TIMEOUT_SECONDS} seconds"
472
- )
473
-
474
  except HTTPException:
475
  raise
476
- except ValueError as e:
477
- log_with_datetime(f"❌ Request #{request_id} invalid image: {str(e)}", "ERROR")
478
- raise HTTPException(status_code=400, detail=str(e))
479
  except Exception as e:
480
- log_with_datetime(f"❌ Request #{request_id} error: {str(e)}", "ERROR")
481
- raise HTTPException(status_code=500, detail="An error occurred processing the image")
482
- finally:
483
- # Always decrease counter
484
- queue_status["current_requests"] -= 1
 
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
  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
17
+ MIN_IMAGE_HEIGHT = 2000
18
+ INFERENCE_SIZE = 1024
19
  FONT_SCALE_DIVISOR = 100 # Larger text
20
  TOP_BAR_HEIGHT_PERCENT = 0.1
21
  MIN_TOP_BAR_HEIGHT = 50
22
+ CIRCLE_RADIUS_MULTIPLIER = 30 # Smaller circles to avoid covering too much
23
+ BORDER_THICKNESS = 3 # Thicker borders for better visibility
24
+ FONT_THICKNESS = 2 # Bold text
25
+ 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
  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
 
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
  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
  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")
 
 
model.py CHANGED
@@ -1,27 +1,11 @@
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,10 +18,4 @@ def get_yolov5(confident_val):
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
-
 
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
  # Enable inference optimizations
19
  model.eval() # Set to evaluation mode
20
 
 
 
 
 
 
21
  return model
 
static/images/credit.png CHANGED
static/index.html CHANGED
@@ -1 +1 @@
1
- <!DOCTYPE html><html lang="en"><head><meta charset="utf-8"><title>NPI Pipe Counting</title><meta http-equiv="X-UA-Compatible" content="IE=edge"><meta name="description" content="NPI Pipe Counting โปรแกรมนับจำนวนท่อPVCจากรูปภาพ"><meta name="viewport" content="width=device-width,initial-scale=1"><meta name="mobile-web-app-capable" content="yes"><meta name="apple-mobile-web-app-title" content="NPI Pipe Counting"><meta name="apple-mobile-web-app-status-bar-style" content="#e4e4e4"><meta name="apple-mobile-web-app-capable" content="yes"><meta name="application-name" content="NPI Pipe Counting"><meta name="msapplication-TileColor" content="#e4e4e4"><meta name="msapplication-TileImage" content="/images/touch/mstile-150x150.png"><meta name="theme-color" content="#fff"><link rel="apple-touch-icon" href="/images/touch/apple-touch-icon.jpg"><link rel="icon" type="image/png" href="/images/touch/favicon-32x32.png" sizes="32x32"><link rel="icon" type="image/png" href="/images/touch/favicon-16x16.png" sizes="16x16"><link rel="shortcut icon" href="/images/touch/favicon.ico"><link rel="manifest" href="/manifest.json"><link href="styles.css" rel="stylesheet"><style>.version-footer{position:fixed;bottom:5px;left:50%;transform:translateX(-50%);color:rgba(255,255,255,0.6);font-size:11px;z-index:100;font-family:monospace;background:rgba(0,0,0,0.3);padding:2px 8px;border-radius:3px}</style></head><body><div class="app__layout"><div class="choose"><img src="/images/choose.svg"></div><div class="result"><img src="/images/result.svg"></div><div class="loading"><img src="/images/loading.svg"></div><!-- Header --><header class="app__header"><span class="app__header-icon" onclick="alert('โปรแกรมนับจำนวนท่อPVCจากรูปภาพ\nบริษัท นวพลาสติก อุตสาหกรรม จำกัด\nสร้างโดย Digital Infrastructure\nเวอร์ชั่น 1.0 12-ตุลาคม-2023');"><svg fill="#FFFFFF" height="27" viewBox="0 0 24 24" width="27" xmlns="http://www.w3.org/2000/svg"><path d="M0 0h24v24H0z" fill="none"/><path d="M11 17h2v-6h-2v6zm1-15C6.48 2 2 6.48 2 12s4.48 10 10 10 10-4.48 10-10S17.52 2 12 2zm0 18c-4.41 0-8-3.59-8-8s3.59-8 8-8 8 3.59 8 8-3.59 8-8 8zM11 9h2V7h-2v2z"/></svg></span></header><!-- <img id="image" src="/images/bg.png"> --><main class="app__layout-content"></main></div><div class="app__overlay"><div class="app__overlay-frame"></div><!-- Scanner animation --><div class="custom-scanner"></div><div class="app__help-text"></div></div><input type="file" id="fileInput" style="display: none;" accept="image/*"><div class="app__counting"></div><div class="app__select-photos"></div><div class="app__select-camera"></div><div class="credit"></div><div class="version-footer" id="version-footer">Loading...</div><script async src="https://cdn.jsdelivr.net/npm/pwacompat@2.0.6/pwacompat.min.js" integrity="sha384-GOaSLecPIMCJksN83HLuYf9FToOiQ2Df0+0ntv7ey8zjUHESXhthwvq9hXAZTifA" crossorigin="anonymous"></script><script type="text/javascript" src="main.c04e0f549281cfe61f09.bundle.js"></script><script>fetch('/health').then(r=>r.json()).then(d=>{document.getElementById('version-footer').textContent='v'+d.version+' | Queue: '+d.queue.current_requests+'/'+d.queue.max_queue_size}).catch(()=>{document.getElementById('version-footer').textContent='v0.0.5'})</script></body></html>
 
1
+ <!DOCTYPE html><html lang="en"><head><meta charset="utf-8"><title>NPI Pipe Counting</title><meta http-equiv="X-UA-Compatible" content="IE=edge"><meta name="description" content="NPI Pipe Counting โปรแกรมนับจำนวนท่อPVCจากรูปภาพ"><meta name="viewport" content="width=device-width,initial-scale=1"><meta name="mobile-web-app-capable" content="yes"><meta name="apple-mobile-web-app-title" content="NPI Pipe Counting"><meta name="apple-mobile-web-app-status-bar-style" content="#e4e4e4"><meta name="apple-mobile-web-app-capable" content="yes"><meta name="application-name" content="NPI Pipe Counting"><meta name="msapplication-TileColor" content="#e4e4e4"><meta name="msapplication-TileImage" content="/images/touch/mstile-150x150.png"><meta name="theme-color" content="#fff"><link rel="apple-touch-icon" href="/images/touch/apple-touch-icon.jpg"><link rel="icon" type="image/png" href="/images/touch/favicon-32x32.png" sizes="32x32"><link rel="icon" type="image/png" href="/images/touch/favicon-16x16.png" sizes="16x16"><link rel="shortcut icon" href="/images/touch/favicon.ico"><link rel="manifest" href="/manifest.json"><link href="styles.css" rel="stylesheet"></head><body><div class="app__layout"><div class="choose"><img src="/images/choose.svg"></div><div class="result"><img src="/images/result.svg"></div><div class="loading"><img src="/images/loading.svg"></div><!-- Header --><header class="app__header"><span class="app__header-icon" onclick="alert('โปรแกรมนับจำนวนท่อPVCจากรูปภาพ\nบริษัท น��พลาสติก อุตสาหกรรม จำกัด\nสร้างโดย Digital Infrastructure\nเวอร์ชั่น 1.0 12-ตุลาคม-2023');"><svg fill="#FFFFFF" height="27" viewBox="0 0 24 24" width="27" xmlns="http://www.w3.org/2000/svg"><path d="M0 0h24v24H0z" fill="none"/><path d="M11 17h2v-6h-2v6zm1-15C6.48 2 2 6.48 2 12s4.48 10 10 10 10-4.48 10-10S17.52 2 12 2zm0 18c-4.41 0-8-3.59-8-8s3.59-8 8-8 8 3.59 8 8-3.59 8-8 8zM11 9h2V7h-2v2z"/></svg></span></header><!-- <img id="image" src="/images/bg.png"> --><main class="app__layout-content"></main></div><div class="app__overlay"><div class="app__overlay-frame"></div><!-- Scanner animation --><div class="custom-scanner"></div><div class="app__help-text"></div></div><input type="file" id="fileInput" style="display: none;" accept="image/*"><div class="app__counting"></div><div class="app__select-photos"></div><div class="app__select-camera"></div><div class="credit"></div><script async src="https://cdn.jsdelivr.net/npm/pwacompat@2.0.6/pwacompat.min.js" integrity="sha384-GOaSLecPIMCJksN83HLuYf9FToOiQ2Df0+0ntv7ey8zjUHESXhthwvq9hXAZTifA" crossorigin="anonymous"></script><script type="text/javascript" src="main.c04e0f549281cfe61f09.bundle.js"></script></body></html>