Spaces:
Runtime error
Runtime error
File size: 1,733 Bytes
1378843 b3385db 1378843 b3385db |
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 51 52 53 54 55 56 57 58 59 60 61 62 63 64 |
import hashlib
import os
from pathlib import Path
from typing import Any, cast
import pandoc
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
def html_to_markdown(html: str) -> str:
doc = pandoc.read(html, format="html")
md = pandoc.write(doc, format="markdown-smart", options=["--wrap=none"])
return cast(str, md)
def markdown_to_text(md: str) -> str:
doc = pandoc.read(md, format="markdown")
txt = pandoc.write(doc, format="plain-smart", options=["--wrap=none"])
return cast(str, txt)
|