file_handler.py 2.12 KB
Newer Older
1
2
3
4
5
# Copyright (c) Microsoft Corporation.
# Licensed under the MIT License.

"""Utilities for file."""

6
import itertools
7
8
9
from pathlib import Path
from datetime import datetime

10
import yaml
11
from omegaconf import OmegaConf
12

13
14
15
16
17
18
19
20
21
22
23
24
25
from superbench.common.utils import logger


def rotate_dir(target_dir):
    """Rotate directory if it is not empty.

    Args:
        target_dir (str): Target directory path.
    """
    try:
        if target_dir.is_dir() and any(target_dir.iterdir()):
            logger.warning('Directory %s is not empty.', str(target_dir))
            for i in itertools.count(start=1):
26
                backup_dir = target_dir.with_name(f'{target_dir.name}.bak{i}')
27
28
29
30
31
32
33
                if not backup_dir.is_dir():
                    target_dir.rename(backup_dir)
                    break
    except Exception:
        logger.exception('Failed to rotate directory %s.', str(target_dir))
        raise

34

35
36
def create_sb_output_dir(output_dir=None):
    """Create output directory.
37

38
39
40
41
    Create output directory on filesystem, generate a new name based on current time if not provided.

    Args:
        output_dir (str): Output directory. Defaults to None.
42
43

    Returns:
44
        str: Given or generated output directory.
45
    """
46
47
48
    if not output_dir:
        output_dir = str(Path('outputs', datetime.now().strftime('%Y-%m-%d_%H-%M-%S')))
    output_path = Path(output_dir).expanduser().resolve()
49
50
51
52
53
    try:
        output_path.mkdir(mode=0o755, parents=True, exist_ok=True)
    except Exception:
        logger.exception('Failed to create directory %s.', str(output_path))
        raise
54
    return output_dir
55
56


57
def get_sb_config(config_file):
58
59
60
61
62
63
64
65
    """Read SuperBench config yaml.

    Read config file, use default config if None is provided.

    Args:
        config_file (str): config file path.

    Returns:
66
        OmegaConf: Config object, None if file does not exist.
67
    """
68
69
    default_config_file = Path(__file__).parent / '../../config/default.yaml'
    p = Path(config_file) if config_file else default_config_file
70
71
    if not p.is_file():
        return None
72
73
    with p.open() as fp:
        return OmegaConf.create(yaml.load(fp, Loader=yaml.SafeLoader))