MogensR commited on
Commit
a7a451b
·
1 Parent(s): d394724

Update utils/__init__.py

Browse files
Files changed (1) hide show
  1. utils/__init__.py +58 -68
utils/__init__.py CHANGED
@@ -1,79 +1,69 @@
1
  """
2
- Fixed utils/__init__.py - Prevents recursion in __getattr__
 
3
  """
4
 
5
  from __future__ import annotations
6
 
7
- import importlib
8
- import sys
9
- from types import ModuleType
10
- from typing import Any, Iterable
11
 
12
- __all__ = ["__getattr__", "__dir__"]
13
 
14
- _swapped: bool = False
15
- _real_utils: ModuleType | None = None
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
16
 
17
- def _swap_with_utils() -> ModuleType:
18
- global _swapped, _real_utils
19
-
20
- # Return cached module if already swapped
21
- if _swapped and _real_utils is not None:
22
- return _real_utils
23
-
24
- # Prevent recursion by checking if we're already in the process
25
- if _swapped:
26
- # If we're here, something went wrong - return a dummy module
27
- dummy = ModuleType("utils_dummy")
28
- return dummy
29
-
30
- try:
31
- _swapped = True # Set this BEFORE importing to prevent recursion
32
- _real_utils = importlib.import_module("utils")
33
-
34
- # Replace utilities in sys.modules
35
- sys.modules["utilities"] = _real_utils
36
-
37
- # Alias submodules
38
- for modname, module in list(sys.modules.items()):
39
- if modname.startswith("utils.") and isinstance(module, ModuleType):
40
- suffix = modname.partition(".")[2]
41
- sys.modules[f"utilities.{suffix}"] = module
42
-
43
- return _real_utils
44
-
45
- except Exception as e:
46
- # Reset state on failure
47
- _swapped = False
48
- _real_utils = None
49
- # Create a minimal fallback module to prevent further errors
50
- fallback = ModuleType("utils_fallback")
51
- fallback.__dict__.update({
52
- 'device': ModuleType('device'),
53
- 'logging': ModuleType('logging'),
54
- 'config': ModuleType('config')
55
- })
56
- return fallback
57
 
58
- def __getattr__(name: str) -> Any:
59
- # Prevent infinite recursion by checking if we're already trying to get this attribute
60
- if hasattr(__getattr__, '_in_progress'):
61
- raise AttributeError(f"Recursion detected while getting attribute '{name}'")
62
-
63
  try:
64
- __getattr__._in_progress = True
65
- real = _swap_with_utils()
66
- if hasattr(real, name):
67
- return getattr(real, name)
68
- else:
69
- raise AttributeError(f"module 'utilities' has no attribute '{name}'")
70
- finally:
71
- if hasattr(__getattr__, '_in_progress'):
72
- delattr(__getattr__, '_in_progress')
73
 
74
- def __dir__() -> Iterable[str]:
75
- try:
76
- real = _swap_with_utils()
77
- return dir(real)
78
- except Exception:
79
- return ["__getattr__", "__dir__"]
 
 
 
 
 
 
 
 
 
 
1
  """
2
+ Fixed utils/__init__.py - Properly imports existing functions from utils modules
3
+ Replaces the recursive lazy-loading approach with direct imports
4
  """
5
 
6
  from __future__ import annotations
7
 
8
+ import logging
9
+ from typing import Any
 
 
10
 
11
+ logger = logging.getLogger(__name__)
12
 
13
+ # Import all required functions from their actual locations in the utils package
14
+ try:
15
+ from .cv_processing import (
16
+ segment_person_hq,
17
+ refine_mask_hq,
18
+ replace_background_hq,
19
+ PROFESSIONAL_BACKGROUNDS
20
+ )
21
+ logger.debug("Successfully imported cv_processing functions")
22
+ except ImportError as e:
23
+ logger.error(f"Failed to import cv_processing functions: {e}")
24
+ # Provide fallback implementations
25
+ def segment_person_hq(*args, **kwargs):
26
+ raise NotImplementedError("segment_person_hq not available")
27
+ def refine_mask_hq(*args, **kwargs):
28
+ raise NotImplementedError("refine_mask_hq not available")
29
+ def replace_background_hq(*args, **kwargs):
30
+ raise NotImplementedError("replace_background_hq not available")
31
+ PROFESSIONAL_BACKGROUNDS = {}
32
 
33
+ try:
34
+ from .utils import (
35
+ validate_video_file,
36
+ )
37
+ logger.debug("Successfully imported utils functions")
38
+ except ImportError as e:
39
+ logger.error(f"Failed to import utils functions: {e}")
40
+ def validate_video_file(*args, **kwargs):
41
+ raise NotImplementedError("validate_video_file not available")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
42
 
43
+ try:
44
+ from .cv_processing import create_professional_background
45
+ logger.debug("Successfully imported create_professional_background")
46
+ except ImportError:
 
47
  try:
48
+ from .utils import create_professional_background
49
+ logger.debug("Successfully imported create_professional_background from utils")
50
+ except ImportError as e:
51
+ logger.error(f"Failed to import create_professional_background: {e}")
52
+ def create_professional_background(*args, **kwargs):
53
+ raise NotImplementedError("create_professional_background not available")
 
 
 
54
 
55
+ # Export all functions for backward compatibility
56
+ __all__ = [
57
+ "segment_person_hq",
58
+ "refine_mask_hq",
59
+ "replace_background_hq",
60
+ "create_professional_background",
61
+ "PROFESSIONAL_BACKGROUNDS",
62
+ "validate_video_file"
63
+ ]
64
+
65
+ # For backward compatibility with utilities import
66
+ import sys
67
+ sys.modules["utilities"] = sys.modules[__name__]
68
+
69
+ logger.info("Utils module initialized successfully")