| 5 | |
| 6 | |
| 7 | class Settings: |
| 8 | def __init__(self): |
| 9 | self.settings_file_path = self.get_settings_directory_path() + 'settings.json' |
| 10 | os.makedirs(os.path.dirname(self.settings_file_path), exist_ok=True) |
| 11 | self.settings = self.load_settings_from_file() |
| 12 | |
| 13 | def get_settings_directory_path(self): |
| 14 | return str(Path.home()) + '/.open-interface/' |
| 15 | |
| 16 | def get_dict(self) -> dict[str, str]: |
| 17 | return self.settings |
| 18 | |
| 19 | def _read_settings_file(self) -> dict[str, str]: |
| 20 | if os.path.exists(self.settings_file_path): |
| 21 | with open(self.settings_file_path, 'r') as file: |
| 22 | try: |
| 23 | return json.load(file) |
| 24 | except Exception: |
| 25 | return {} |
| 26 | return {} |
| 27 | |
| 28 | def save_settings_to_file(self, settings_dict) -> None: |
| 29 | settings: dict[str, str] = self._read_settings_file() |
| 30 | |
| 31 | for setting_name in settings_dict: |
| 32 | setting_val = settings_dict[setting_name] |
| 33 | if setting_val is not None: |
| 34 | if setting_name == "api_key": |
| 35 | api_key = settings_dict["api_key"] |
| 36 | |
| 37 | # TODO: Now we have two keys OPENAI_API_KEY and GEMINI_API_KEY |
| 38 | os.environ["OPENAI_API_KEY"] = api_key # Set environment variable |
| 39 | |
| 40 | encoded_api_key = base64.b64encode(api_key.encode()).decode() |
| 41 | settings['api_key'] = encoded_api_key |
| 42 | else: |
| 43 | settings[setting_name] = setting_val |
| 44 | |
| 45 | with open(self.settings_file_path, 'w+') as file: |
| 46 | json.dump(settings, file, indent=4) |
| 47 | |
| 48 | def load_settings_from_file(self) -> dict[str, str]: |
| 49 | """ |
| 50 | if os.path.exists(self.settings_file_path): |
| 51 | with open(self.settings_file_path, 'r') as file: |
| 52 | try: |
| 53 | settings = json.load(file) |
| 54 | except: |
| 55 | return {} |
| 56 | |
| 57 | # Decode the API key |
| 58 | if 'api_key' in settings: |
| 59 | decoded_api_key = base64.b64decode(settings['api_key']).decode() |
| 60 | settings['api_key'] = decoded_api_key |
| 61 | |
| 62 | return settings |
| 63 | else: |
| 64 | return {} |