File size: 1,339 Bytes
1378843
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
import hashlib
import os
from pathlib import Path
from typing import Any


class Unspecified:
    pass


UNSPECIFIED = Unspecified()
FALSISH_STRINGS = {"", "0", "false", "n", "no", "off", "disabled"}


def env_str(name: str, default: str | Unspecified = UNSPECIFIED) -> str:
    value = os.environ.get(name)
    if value is None:
        if isinstance(default, Unspecified):
            raise ValueError(f"environment variable {name} is not set")
        return default
    return value


def env_bool(name: str, default: bool | Unspecified = UNSPECIFIED) -> bool:
    value = os.environ.get(name)
    if value is None:
        if isinstance(default, Unspecified):
            raise ValueError(f"environment variable {name} is not set")
        return default
    return value.lower() not in FALSISH_STRINGS


def data_dir(name: str) -> Path:
    rv = Path(env_str("DATA_DIR", "/var/tts-service")) / name
    if not rv.exists():
        os.makedirs(rv)
    return Path(rv)


def cache_path(*keys: Any, extension: str | None = None) -> Path:
    key = "\0".join(str(k) for k in keys)
    hash = hashlib.md5(key.encode()).hexdigest()
    dir_path = data_dir("cache") / hash[0:2]
    if not dir_path.exists():
        os.makedirs(dir_path)
    name = f"{hash[2:]}"
    if extension:
        name += f".{extension}"
    return dir_path / name