/ common / utils / path_utils.py
path_utils.py
 1  """
 2  Common utilities shared across modules.
 3  
 4  This module provides reusable components to avoid code duplication:
 5  - Path utilities for project root resolution
 6  - GELU reference implementations
 7  - Model loading utilities
 8  """
 9  
10  from __future__ import annotations
11  
12  from pathlib import Path
13  
14  
15  def get_project_root() -> Path:
16      """
17      Get the project root directory.
18  
19      Returns:
20          Path to the project root directory.
21  
22      Example:
23          >>> from common.utils import get_project_root
24          >>> root = get_project_root()
25          >>> (root / "README.md").exists()
26          True
27      """
28      # Walk up from this file to find the project root
29      current = Path(__file__).resolve()
30      while current.parent != current:
31          # Check for markers that indicate project root
32          if (current / "pyproject.toml").exists() or (current / "setup.py").exists():
33              return current
34          current = current.parent
35      # Fallback: assume 4 levels up from this file
36      return Path(__file__).resolve().parents[3]
37  
38  
39  def ensure_project_root_in_path() -> None:
40      """
41      Ensure the project root is in sys.path for imports.
42  
43      This function is used to enable imports from the project root
44      without requiring package installation during development.
45  
46      Example:
47          >>> from common.utils import ensure_project_root_in_path
48          >>> ensure_project_root_in_path()
49          >>> # Now can import from any module
50      """
51      import sys
52  
53      root = get_project_root()
54      root_str = str(root)
55      if root_str not in sys.path:
56          sys.path.insert(0, root_str)