CoolFace
Apppublic

singularity7/Muggier

sourceHugging Facecc-by-nc-4.0updated 3y agoView on Hugging Face
0likes
temp_utils.py57 linesDownload Raw Back to common_utils
1# Copyright (c) Meta Platforms, Inc. and affiliates.2# All rights reserved.3#4# This source code is licensed under the license found in the5# LICENSE file in the root directory of this source tree.6 7import os8import tempfile9 10 11class TempDirMixin:12    """Mixin to provide easy access to temp dir.13    """14 15    temp_dir_ = None16 17    @classmethod18    def get_base_temp_dir(cls):19        # If AUDIOCRAFT_TEST_DIR is set, use it instead of temporary directory.20        # this is handy for debugging.21        key = "AUDIOCRAFT_TEST_DIR"22        if key in os.environ:23            return os.environ[key]24        if cls.temp_dir_ is None:25            cls.temp_dir_ = tempfile.TemporaryDirectory()26        return cls.temp_dir_.name27 28    @classmethod29    def tearDownClass(cls):30        if cls.temp_dir_ is not None:31            try:32                cls.temp_dir_.cleanup()33                cls.temp_dir_ = None34            except PermissionError:35                # On Windows there is a know issue with `shutil.rmtree`,36                # which fails intermittently.37                # https://github.com/python/cpython/issues/7416838                # Following the above thread, we ignore it.39                pass40        super().tearDownClass()41 42    @property43    def id(self):44        return self.__class__.__name__45 46    def get_temp_path(self, *paths):47        temp_dir = os.path.join(self.get_base_temp_dir(), self.id)48        path = os.path.join(temp_dir, *paths)49        os.makedirs(os.path.dirname(path), exist_ok=True)50        return path51 52    def get_temp_dir(self, *paths):53        temp_dir = os.path.join(self.get_base_temp_dir(), self.id)54        path = os.path.join(temp_dir, *paths)55        os.makedirs(path, exist_ok=True)56        return path57