Coverage for utils / utils.py: 100.00%
48 statements
« prev ^ index » next coverage.py v7.13.0, created at 2025-12-22 10:24 +0000
« prev ^ index » next coverage.py v7.13.0, created at 2025-12-22 10:24 +0000
1import os
2import json
3import torch
4import numpy as np
5import random
7def inherit_docstring(cls):
8 """
9 Inherit docstrings from base classes to methods without docstrings.
11 This decorator automatically applies the docstring from a base class method
12 to a derived class method if the derived method doesn't have its own docstring.
14 Args:
15 cls: The class to enhance with inherited docstrings
17 Returns:
18 cls: The enhanced class
19 """
20 for name, func in vars(cls).items():
21 if not callable(func) or func.__doc__ is not None:
22 continue
24 # Look for same method in base classes
25 for base in cls.__bases__:
26 base_func = getattr(base, name, None)
27 if base_func and getattr(base_func, "__doc__", None):
28 func.__doc__ = base_func.__doc__
29 break
31 return cls
34def load_config_file(path: str) -> dict:
35 """Load a JSON configuration file from the specified path and return it as a dictionary."""
36 try:
37 with open(path, 'r') as f:
38 config_dict = json.load(f)
39 return config_dict
41 except FileNotFoundError:
42 print(f"Error: The file '{path}' does not exist.")
43 return None
44 except json.JSONDecodeError as e:
45 print(f"Error decoding JSON in '{path}': {e}")
46 # Handle other potential JSON decoding errors here
47 return None
48 except Exception as e:
49 print(f"An unexpected error occurred: {e}")
50 # Handle other unexpected errors here
51 return None
54def load_json_as_list(input_file: str) -> list:
55 """Load a JSON file as a list of dictionaries."""
56 res = []
57 with open(input_file, 'r') as f:
58 lines = f.readlines()
59 for line in lines:
60 d = json.loads(line)
61 res.append(d)
62 return res
65def create_directory_for_file(file_path) -> None:
66 """Create the directory for the specified file path if it does not already exist."""
67 directory = os.path.dirname(file_path)
68 if not os.path.exists(directory):
69 os.makedirs(directory)
72def set_random_seed(seed: int):
73 """Set random seeds for reproducibility."""
75 torch.manual_seed(seed + 0)
76 torch.cuda.manual_seed(seed + 1)
77 torch.cuda.manual_seed_all(seed + 2)
78 np.random.seed((seed + 3) % 2**32)
79 torch.cuda.manual_seed_all(seed + 4)
80 random.seed(seed + 5)