refactor(settings): lazily initialize manager

This commit is contained in:
pixelpaws
2025-10-08 08:56:57 +08:00
parent 3118f3b43c
commit c53fa8692b
31 changed files with 299 additions and 172 deletions

View File

@@ -18,7 +18,7 @@ from ..utils.metadata_manager import MetadataManager
from .example_images_processor import ExampleImagesProcessor
from .example_images_metadata import MetadataUpdater
from ..services.downloader import get_downloader
from ..services.settings_manager import settings
from ..services.settings_manager import get_settings_manager
class ExampleImagesDownloadError(RuntimeError):
@@ -107,7 +107,7 @@ class DownloadManager:
self._state_lock = state_lock or asyncio.Lock()
def _resolve_output_dir(self, library_name: str | None = None) -> str:
base_path = settings.get('example_images_path')
base_path = get_settings_manager().get('example_images_path')
if not base_path:
return ''
return ensure_library_root_exists(library_name)
@@ -126,7 +126,8 @@ class DownloadManager:
model_types = data.get('model_types', ['lora', 'checkpoint'])
delay = float(data.get('delay', 0.2))
base_path = settings.get('example_images_path')
settings_manager = get_settings_manager()
base_path = settings_manager.get('example_images_path')
if not base_path:
error_msg = 'Example images path not configured in settings'
@@ -138,7 +139,7 @@ class DownloadManager:
}
raise DownloadConfigurationError(error_msg)
active_library = settings.get_active_library_name()
active_library = get_settings_manager().get_active_library_name()
output_dir = self._resolve_output_dir(active_library)
if not output_dir:
raise DownloadConfigurationError('Example images path not configured in settings')
@@ -151,7 +152,7 @@ class DownloadManager:
progress_file = os.path.join(output_dir, '.download_progress.json')
progress_source = progress_file
if uses_library_scoped_folders():
legacy_root = settings.get('example_images_path') or ''
legacy_root = get_settings_manager().get('example_images_path') or ''
legacy_progress = os.path.join(legacy_root, '.download_progress.json') if legacy_root else ''
if legacy_progress and os.path.exists(legacy_progress) and not os.path.exists(progress_file):
try:
@@ -555,11 +556,12 @@ class DownloadManager:
if not model_hashes:
raise DownloadConfigurationError('Missing model_hashes parameter')
base_path = settings.get('example_images_path')
settings_manager = get_settings_manager()
base_path = settings_manager.get('example_images_path')
if not base_path:
raise DownloadConfigurationError('Example images path not configured in settings')
active_library = settings.get_active_library_name()
active_library = settings_manager.get_active_library_name()
output_dir = self._resolve_output_dir(active_library)
if not output_dir:
raise DownloadConfigurationError('Example images path not configured in settings')

View File

@@ -3,7 +3,7 @@ import os
import sys
import subprocess
from aiohttp import web
from ..services.settings_manager import settings
from ..services.settings_manager import get_settings_manager
from ..utils.example_images_paths import (
get_model_folder,
get_model_relative_path,
@@ -37,7 +37,8 @@ class ExampleImagesFileManager:
}, status=400)
# Get example images path from settings
example_images_path = settings.get('example_images_path')
settings_manager = get_settings_manager()
example_images_path = settings_manager.get('example_images_path')
if not example_images_path:
return web.json_response({
'success': False,
@@ -109,7 +110,8 @@ class ExampleImagesFileManager:
}, status=400)
# Get example images path from settings
example_images_path = settings.get('example_images_path')
settings_manager = get_settings_manager()
example_images_path = settings_manager.get('example_images_path')
if not example_images_path:
return web.json_response({
'success': False,
@@ -183,7 +185,8 @@ class ExampleImagesFileManager:
}, status=400)
# Get example images path from settings
example_images_path = settings.get('example_images_path')
settings_manager = get_settings_manager()
example_images_path = settings_manager.get('example_images_path')
if not example_images_path:
return web.json_response({
'has_images': False

View File

@@ -6,7 +6,7 @@ from ..recipes.constants import GEN_PARAM_KEYS
from ..services.metadata_service import get_default_metadata_provider, get_metadata_provider
from ..services.metadata_sync_service import MetadataSyncService
from ..services.preview_asset_service import PreviewAssetService
from ..services.settings_manager import settings
from ..services.settings_manager import get_settings_manager
from ..services.downloader import get_downloader
from ..utils.constants import SUPPORTED_MEDIA_EXTENSIONS
from ..utils.exif_utils import ExifUtils
@@ -20,13 +20,22 @@ _preview_service = PreviewAssetService(
exif_utils=ExifUtils,
)
_metadata_sync_service = MetadataSyncService(
metadata_manager=MetadataManager,
preview_service=_preview_service,
settings=settings,
default_metadata_provider_factory=get_default_metadata_provider,
metadata_provider_selector=get_metadata_provider,
)
_METADATA_SYNC_SERVICE: MetadataSyncService | None = None
def _get_metadata_sync_service() -> MetadataSyncService:
"""Return the shared metadata sync service, initialising it lazily."""
global _METADATA_SYNC_SERVICE
if _METADATA_SYNC_SERVICE is None:
_METADATA_SYNC_SERVICE = MetadataSyncService(
metadata_manager=MetadataManager,
preview_service=_preview_service,
settings=get_settings_manager(),
default_metadata_provider_factory=get_default_metadata_provider,
metadata_provider_selector=get_metadata_provider,
)
return _METADATA_SYNC_SERVICE
class MetadataUpdater:
@@ -71,7 +80,7 @@ class MetadataUpdater:
async def update_cache_func(old_path, new_path, metadata):
return await scanner.update_single_model_cache(old_path, new_path, metadata)
success, error = await _metadata_sync_service.fetch_and_update_model(
success, error = await _get_metadata_sync_service().fetch_and_update_model(
sha256=model_hash,
file_path=file_path,
model_data=model_data,

View File

@@ -3,7 +3,7 @@ import logging
import os
import re
import json
from ..services.settings_manager import settings
from ..services.settings_manager import get_settings_manager
from ..services.service_registry import ServiceRegistry
from ..utils.example_images_paths import iter_library_roots
from ..utils.metadata_manager import MetadataManager
@@ -20,7 +20,7 @@ class ExampleImagesMigration:
@staticmethod
async def check_and_run_migrations():
"""Check if migrations are needed and run them in background"""
root = settings.get('example_images_path')
root = get_settings_manager().get('example_images_path')
if not root or not os.path.exists(root):
logger.debug("No example images path configured or path doesn't exist, skipping migrations")
return

View File

@@ -8,7 +8,7 @@ import re
import shutil
from typing import Iterable, List, Optional, Tuple
from ..services.settings_manager import settings
from ..services.settings_manager import get_settings_manager
_HEX_PATTERN = re.compile(r"[a-fA-F0-9]{64}")
@@ -18,7 +18,8 @@ logger = logging.getLogger(__name__)
def _get_configured_libraries() -> List[str]:
"""Return configured library names if multi-library support is enabled."""
libraries = settings.get("libraries")
settings_manager = get_settings_manager()
libraries = settings_manager.get("libraries")
if isinstance(libraries, dict) and libraries:
return list(libraries.keys())
return []
@@ -27,7 +28,8 @@ def _get_configured_libraries() -> List[str]:
def get_example_images_root() -> str:
"""Return the root directory configured for example images."""
root = settings.get("example_images_path") or ""
settings_manager = get_settings_manager()
root = settings_manager.get("example_images_path") or ""
return os.path.abspath(root) if root else ""
@@ -41,7 +43,8 @@ def uses_library_scoped_folders() -> bool:
def sanitize_library_name(library_name: Optional[str]) -> str:
"""Return a filesystem safe library name."""
name = library_name or settings.get_active_library_name() or "default"
settings_manager = get_settings_manager()
name = library_name or settings_manager.get_active_library_name() or "default"
safe_name = re.sub(r"[^A-Za-z0-9_.-]", "_", name)
return safe_name or "default"
@@ -161,11 +164,13 @@ def iter_library_roots() -> Iterable[Tuple[str, str]]:
results.append((library, get_library_root(library)))
else:
# Fall back to the active library to avoid skipping migrations/cleanup
active = settings.get_active_library_name() or "default"
settings_manager = get_settings_manager()
active = settings_manager.get_active_library_name() or "default"
results.append((active, get_library_root(active)))
return results
active = settings.get_active_library_name() or "default"
settings_manager = get_settings_manager()
active = settings_manager.get_active_library_name() or "default"
return [(active, root)]

View File

@@ -6,7 +6,7 @@ import string
from aiohttp import web
from ..utils.constants import SUPPORTED_MEDIA_EXTENSIONS
from ..services.service_registry import ServiceRegistry
from ..services.settings_manager import settings
from ..services.settings_manager import get_settings_manager
from ..utils.example_images_paths import get_model_folder, get_model_relative_path
from .example_images_metadata import MetadataUpdater
from ..utils.metadata_manager import MetadataManager
@@ -318,7 +318,7 @@ class ExampleImagesProcessor:
try:
# Get example images path
example_images_path = settings.get('example_images_path')
example_images_path = get_settings_manager().get('example_images_path')
if not example_images_path:
raise ExampleImagesValidationError('No example images path configured')
@@ -442,7 +442,7 @@ class ExampleImagesProcessor:
}, status=400)
# Get example images path
example_images_path = settings.get('example_images_path')
example_images_path = get_settings_manager().get('example_images_path')
if not example_images_path:
return web.json_response({
'success': False,

View File

@@ -3,7 +3,7 @@ import os
from typing import Dict
from ..services.service_registry import ServiceRegistry
from ..config import config
from ..services.settings_manager import settings
from ..services.settings_manager import get_settings_manager
from .constants import CIVITAI_MODEL_TAGS
import asyncio
@@ -143,7 +143,8 @@ def calculate_relative_path_for_model(model_data: Dict, model_type: str = 'lora'
Relative path string (empty string for flat structure)
"""
# Get path template from settings for specific model type
path_template = settings.get_download_path_template(model_type)
settings_manager = get_settings_manager()
path_template = settings_manager.get_download_path_template(model_type)
# If template is empty, return empty path (flat structure)
if not path_template:
@@ -166,7 +167,7 @@ def calculate_relative_path_for_model(model_data: Dict, model_type: str = 'lora'
model_tags = model_data.get('tags', [])
# Apply mapping if available
base_model_mappings = settings.get('base_model_path_mappings', {})
base_model_mappings = settings_manager.get('base_model_path_mappings', {})
mapped_base_model = base_model_mappings.get(base_model, base_model)
# Find the first Civitai model tag that exists in model_tags