File size: 1,622 Bytes
77da9e2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""
Service Factory - Centralized DetectionService Management

This module provides a singleton pattern for DetectionService to avoid
code duplication across api/endpoints.py and ui/detection_wrapper.py.

IMPORTANT: The service instance is thread-safe for reading but NOT for
writing. Do NOT modify service attributes (enable_clip, enable_ocr, etc.)
as this can cause race conditions in multi-threaded environments.

Instead, pass parameters directly to service.analyze() method.
"""

from typing import Optional
from detection.service import DetectionService


# Shared detection service instance (lazy loaded)
_detection_service: Optional[DetectionService] = None


def get_detection_service() -> DetectionService:
    """
    Get or create the shared detection service instance
    
    This function implements a singleton pattern to ensure only one
    DetectionService instance is created and reused across the application.
    
    Thread Safety:
        - Reading from the service is thread-safe
        - DO NOT modify service attributes from multiple threads
        - Pass parameters to analyze() instead of modifying service flags
    
    Returns:
        Shared DetectionService instance
    """
    global _detection_service
    if _detection_service is None:
        _detection_service = DetectionService()
    return _detection_service


def reset_detection_service():
    """
    Reset the shared detection service instance
    
    Useful for testing or when you need to reload the model with
    different initialization parameters.
    """
    global _detection_service
    _detection_service = None