pytorch-lightning

Форк
0
76 строк · 2.5 Кб
1
# Copyright The Lightning AI team.
2
#
3
# Licensed under the Apache License, Version 2.0 (the "License");
4
# you may not use this file except in compliance with the License.
5
# You may obtain a copy of the License at
6
#
7
#     http://www.apache.org/licenses/LICENSE-2.0
8
#
9
# Unless required by applicable law or agreed to in writing, software
10
# distributed under the License is distributed on an "AS IS" BASIS,
11
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
# See the License for the specific language governing permissions and
13
# limitations under the License.
14

15
import pathlib
16
from dataclasses import asdict, dataclass, field
17
from typing import Union
18

19
import yaml
20

21
from lightning.app.utilities.name_generator import get_unique_name
22

23
_APP_CONFIG_FILENAME = ".lightning"
24

25

26
@dataclass
27
class AppConfig:
28
    """The AppConfig holds configuration metadata for the application.
29

30
    Args:
31
        name: Optional name of the application. If not provided, auto-generates a new name.
32

33
    """
34

35
    name: str = field(default_factory=get_unique_name)
36

37
    def save_to_file(self, path: Union[str, pathlib.Path]) -> None:
38
        """Save the configuration to the given file in YAML format."""
39
        path = pathlib.Path(path)
40
        with open(path, "w") as file:
41
            yaml.dump(asdict(self), file)
42

43
    def save_to_dir(self, directory: Union[str, pathlib.Path]) -> None:
44
        """Save the configuration to a file '.lightning' to the given folder in YAML format."""
45
        self.save_to_file(_get_config_file(directory))
46

47
    @classmethod
48
    def load_from_file(cls, path: Union[str, pathlib.Path]) -> "AppConfig":
49
        """Load the configuration from the given file."""
50
        with open(path) as file:
51
            config = yaml.safe_load(file)
52
        return cls(**config)
53

54
    @classmethod
55
    def load_from_dir(cls, directory: Union[str, pathlib.Path]) -> "AppConfig":
56
        """Load the configuration from the given folder.
57

58
        Args:
59
            directory: Path to a folder which contains the '.lightning' config file to load.
60

61
        """
62
        return cls.load_from_file(pathlib.Path(directory, _APP_CONFIG_FILENAME))
63

64

65
def _get_config_file(source_path: Union[str, pathlib.Path]) -> pathlib.Path:
66
    """Get the Lightning app config file '.lightning' at the given source path.
67

68
    Args:
69
        source_path: A path to a folder or a file.
70

71
    """
72
    source_path = pathlib.Path(source_path).absolute()
73
    if source_path.is_file():
74
        source_path = source_path.parent
75

76
    return pathlib.Path(source_path / _APP_CONFIG_FILENAME)
77

Использование cookies

Мы используем файлы cookie в соответствии с Политикой конфиденциальности и Политикой использования cookies.

Нажимая кнопку «Принимаю», Вы даете АО «СберТех» согласие на обработку Ваших персональных данных в целях совершенствования нашего веб-сайта и Сервиса GitVerse, а также повышения удобства их использования.

Запретить использование cookies Вы можете самостоятельно в настройках Вашего браузера.