""" 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