Skip to content

Commit

Permalink
refactor(config): move configuration logic to util/settings.py for be…
Browse files Browse the repository at this point in the history
…tter modularity

refactor(main.py): update imports and usage to reflect new module structure
feat(util): add replicate_api.py to encapsulate API interactions
refactor(util): create settings.py to handle configuration management
  • Loading branch information
rtuszik committed Oct 6, 2024
1 parent cc24e6d commit 1858b81
Show file tree
Hide file tree
Showing 5 changed files with 92 additions and 88 deletions.
80 changes: 0 additions & 80 deletions src/config.py

This file was deleted.

15 changes: 8 additions & 7 deletions src/main.py
Original file line number Diff line number Diff line change
@@ -1,10 +1,9 @@
import sys

from config import get_api_key
from gui import create_gui
from loguru import logger
from nicegui import ui
from replicate_api import ImageGenerator
import util
from gui import ImageGeneratorGUI

logger.add(
sys.stderr, format="{time} {level} {message}", filter="my_module", level="INFO"
Expand All @@ -19,10 +18,10 @@


logger.info("Initializing ImageGenerator")
generator = ImageGenerator()
generator = util.Replicate_API()


api_key = get_api_key()
api_key = util.Settings.get_api_key()
if api_key:
generator.set_api_key(api_key)
else:
Expand All @@ -33,8 +32,10 @@

@ui.page("/")
async def main_page():
await create_gui(generator)
logger.info("NiceGUI server is running")
logger.debug("Creating GUI")
gui = ImageGeneratorGUI(generator)
gui.setup_ui()
logger.debug("GUI created")


logger.info("Starting NiceGUI server")
Expand Down
3 changes: 3 additions & 0 deletions src/util/__init__.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
# from .settings import Settings
from .replicate_api import Replicate_API
from .settings import Settings
2 changes: 1 addition & 1 deletion src/replicate_api.py → src/util/replicate_api.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@
load_dotenv()


class ImageGenerator:
class Replicate_API:
def __init__(self):
self.replicate_model = None
self.api_key = None
Expand Down
80 changes: 80 additions & 0 deletions src/util/settings.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,80 @@
import configparser
import os
from typing import Any, Type

from loguru import logger

DOCKERIZED = os.environ.get("DOCKER_CONTAINER", "False").lower() == "true"
CONFIG_DIR = "/app/settings" if DOCKERIZED else "."
DEFAULT_CONFIG_FILE = os.path.join(CONFIG_DIR, "settings.ini")
USER_CONFIG_FILE = os.path.join(CONFIG_DIR, "settings.user.ini")

logger.info(
f"Configuration files: DEFAULT={DEFAULT_CONFIG_FILE}, USER={USER_CONFIG_FILE}"
)

config = configparser.ConfigParser()
config.read([DEFAULT_CONFIG_FILE, USER_CONFIG_FILE])
logger.info("Configuration files loaded")


class Settings:
def get_api_key():
api_key = os.environ.get("REPLICATE_API_KEY") or config.get(
"secrets", "REPLICATE_API_KEY", fallback=None
)
if api_key:
logger.info("API key retrieved successfully")
else:
logger.warning("No API key found")
return api_key

def get_setting(
section: str, key: str, fallback: Any = None, value_type: Type[Any] = str
) -> Any:
logger.info(
f"Attempting to get setting: section={section}, key={key}, fallback={fallback}, value_type={value_type}"
)
try:
value = config.get(section, key)
logger.debug(f"Raw value retrieved: {value}")
if value_type is int:
result = int(value)
elif value_type is float:
result = float(value)
elif value_type is bool:
result = value.lower() in ("true", "yes", "1", "on")
else:
result = value
logger.info(f"Setting retrieved successfully: {result}")
return result
except (configparser.NoSectionError, configparser.NoOptionError) as e:
logger.warning(
f"Setting not found: {str(e)}. Using fallback value: {fallback}"
)
return fallback
except ValueError as e:
logger.error(
f"Error converting setting value: {str(e)}. Using fallback value: {fallback}"
)
return fallback

def set_setting(section, key, value):
logger.info(f"Setting value: section={section}, key={key}, value={value}")
if not config.has_section(section):
logger.info(f"Creating new section: {section}")
config.add_section(section)
config.set(section, key, str(value))
logger.info("Value set successfully")

def save_settings():
logger.info(f"Saving settings to {USER_CONFIG_FILE}")
try:
with open(USER_CONFIG_FILE, "w") as configfile:
config.write(configfile)
logger.info("Settings saved successfully")
except IOError as e:
logger.error(f"Error saving settings: {str(e)}")


logger.info("Config module initialized")

0 comments on commit 1858b81

Please sign in to comment.