settings.py (2165B)
1 # File: settings.py 2 # Created Date: Tuesday May 14th 2024 3 # Author: Steven Atkinson (steven@atkinson.mn) 4 5 import json 6 from enum import Enum 7 from functools import partial 8 from pathlib import Path 9 from typing import Optional 10 11 _THIS_DIR = Path(__file__).parent.resolve() 12 _SETTINGS_JSON_PATH = Path(_THIS_DIR, "settings.json") 13 _LAST_PATHS_KEY = "last_paths" 14 15 16 class PathKey(Enum): 17 INPUT_FILE = "input_file" 18 OUTPUT_FILE = "output_file" 19 TRAINING_DESTINATION = "training_destination" 20 21 22 def get_last_path(path_key: PathKey) -> Optional[Path]: 23 s = _get_settings() 24 if _LAST_PATHS_KEY not in s: 25 return None 26 last_path = s[_LAST_PATHS_KEY].get(path_key.value) 27 if last_path is None: 28 return None 29 assert isinstance(last_path, str) 30 return Path(last_path) 31 32 33 def set_last_path(path_key: PathKey, path: Path): 34 s = _get_settings() 35 if _LAST_PATHS_KEY not in s: 36 s[_LAST_PATHS_KEY] = {} 37 s[_LAST_PATHS_KEY][path_key.value] = str(path) 38 _write_settings(s) 39 40 41 def _get_settings() -> dict: 42 """ 43 Make sure that ./settings.json exists; if it does, then read it. If not, empty dict. 44 """ 45 if not _SETTINGS_JSON_PATH.exists(): 46 return dict() 47 else: 48 with open(_SETTINGS_JSON_PATH, "r") as fp: 49 return json.load(fp) 50 51 52 class _WriteSettings(object): 53 def __init__(self): 54 self._oserror = False 55 56 def __call__(self, *args, **kwargs): 57 if self._oserror: 58 return 59 # Try-catch for Issue 448 60 try: 61 return _write_settings_unsafe(*args, **kwargs) 62 except OSError as e: 63 if "Read-only filesystem" in str(e): 64 print( 65 "Failed to write settings--NAM appears to be installed to a " 66 "read-only filesystem. This is discouraged; consider installing to " 67 "a location with user-level access." 68 ) 69 self._oserror = True 70 else: 71 raise e 72 73 74 _write_settings = _WriteSettings() 75 76 77 def _write_settings_unsafe(obj: dict): 78 with open(_SETTINGS_JSON_PATH, "w") as fp: 79 json.dump(obj, fp, indent=4)