Load a model from a Python file by importing it and instantiating the class.
(model_path: str, class_name: str, **kwargs)
| 102 | # --------------------------------------------------------------------------- |
| 103 | |
| 104 | def load_model_from_file(model_path: str, class_name: str, **kwargs) -> nn.Module: |
| 105 | """Load a model from a Python file by importing it and instantiating the class.""" |
| 106 | model_path = os.path.abspath(model_path) |
| 107 | if not os.path.exists(model_path): |
| 108 | raise FileNotFoundError(f"Model file not found: {model_path}") |
| 109 | |
| 110 | spec = importlib.util.spec_from_file_location("user_model", model_path) |
| 111 | if spec is None or spec.loader is None: |
| 112 | raise ImportError(f"Cannot import model from: {model_path}") |
| 113 | |
| 114 | mod = importlib.util.module_from_spec(spec) |
| 115 | spec.loader.exec_module(mod) |
| 116 | |
| 117 | if not hasattr(mod, class_name): |
| 118 | available = [n for n in dir(mod) if not n.startswith("_")] |
| 119 | raise AttributeError( |
| 120 | f"Class '{class_name}' not found in {model_path}. " |
| 121 | f"Available names: {available}" |
| 122 | ) |
| 123 | |
| 124 | cls = getattr(mod, class_name) |
| 125 | model = cls(**kwargs) |
| 126 | return model |
| 127 | |
| 128 | |
| 129 | def load_model_from_module(module_name: str, class_name: str, |