From ddf132bd78b2e4e05174fe787d58d9b2827dc9c1 Mon Sep 17 00:00:00 2001 From: Will Miao <13051207myq@gmail.com> Date: Thu, 29 May 2025 14:36:13 +0800 Subject: [PATCH] Add cache management feature: implement clear cache API and modal confirmation --- py/routes/misc_routes.py | 53 +++++++++++++++++++++++++++ py/services/model_scanner.py | 2 +- static/js/managers/ModalManager.js | 14 ++++++- static/js/managers/SettingsManager.js | 31 ++++++++++++++++ templates/components/modals.html | 38 +++++++++++++++++++ 5 files changed, 136 insertions(+), 2 deletions(-) diff --git a/py/routes/misc_routes.py b/py/routes/misc_routes.py index 23c0d7e8..c7ea6f0b 100644 --- a/py/routes/misc_routes.py +++ b/py/routes/misc_routes.py @@ -4,6 +4,7 @@ import asyncio import json import time import aiohttp +import shutil from server import PromptServer # type: ignore from aiohttp import web from ..services.settings_manager import settings @@ -39,6 +40,9 @@ class MiscRoutes: def setup_routes(app): """Register miscellaneous routes""" app.router.add_post('/api/settings', MiscRoutes.update_settings) + + # Add new route for clearing cache + app.router.add_post('/api/clear-cache', MiscRoutes.clear_cache) # Usage stats routes app.router.add_post('/api/update-usage-stats', MiscRoutes.update_usage_stats) @@ -53,6 +57,55 @@ class MiscRoutes: # Lora code update endpoint app.router.add_post('/api/update-lora-code', MiscRoutes.update_lora_code) + @staticmethod + async def clear_cache(request): + """Clear all cache files from the cache folder""" + try: + # Get the cache folder path (relative to project directory) + project_dir = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) + cache_folder = os.path.join(project_dir, 'cache') + + # Check if cache folder exists + if not os.path.exists(cache_folder): + logger.info("Cache folder does not exist, nothing to clear") + return web.json_response({'success': True, 'message': 'No cache folder found'}) + + # Get list of cache files before deleting for reporting + cache_files = [f for f in os.listdir(cache_folder) if os.path.isfile(os.path.join(cache_folder, f))] + deleted_files = [] + + # Delete each .msgpack file in the cache folder + for filename in cache_files: + if filename.endswith('.msgpack'): + file_path = os.path.join(cache_folder, filename) + try: + os.remove(file_path) + deleted_files.append(filename) + logger.info(f"Deleted cache file: {filename}") + except Exception as e: + logger.error(f"Failed to delete {filename}: {e}") + return web.json_response({ + 'success': False, + 'error': f"Failed to delete {filename}: {str(e)}" + }, status=500) + + # If we want to completely remove the cache folder too (optional, + # but we'll keep the folder structure in place here) + # shutil.rmtree(cache_folder) + + return web.json_response({ + 'success': True, + 'message': f"Successfully cleared {len(deleted_files)} cache files", + 'deleted_files': deleted_files + }) + + except Exception as e: + logger.error(f"Error clearing cache files: {e}", exc_info=True) + return web.json_response({ + 'success': False, + 'error': str(e) + }, status=500) + @staticmethod async def update_settings(request): """Update application settings""" diff --git a/py/services/model_scanner.py b/py/services/model_scanner.py index 7acd0f72..b2adc9a4 100644 --- a/py/services/model_scanner.py +++ b/py/services/model_scanner.py @@ -103,7 +103,7 @@ class ModelScanner: else: os.rename(temp_path, cache_path) - logger.info(f"Saved {self.model_type} cache with {len(self._cache.raw_data)} models to {cache_path}") + logger.debug(f"Saved {self.model_type} cache with {len(self._cache.raw_data)} models to {cache_path}") return True except Exception as e: logger.error(f"Error saving {self.model_type} cache to disk: {e}") diff --git a/static/js/managers/ModalManager.js b/static/js/managers/ModalManager.js index 3b21c78f..4ab8cd2c 100644 --- a/static/js/managers/ModalManager.js +++ b/static/js/managers/ModalManager.js @@ -170,6 +170,18 @@ export class ModalManager { }); } + // Add clearCacheModal registration + const clearCacheModal = document.getElementById('clearCacheModal'); + if (clearCacheModal) { + this.registerModal('clearCacheModal', { + element: clearCacheModal, + onClose: () => { + this.getModal('clearCacheModal').element.classList.remove('show'); + document.body.classList.remove('modal-open'); + } + }); + } + // Set up event listeners for modal toggles const supportToggle = document.getElementById('supportToggleBtn'); if (supportToggle) { @@ -233,7 +245,7 @@ export class ModalManager { // Store current scroll position before showing modal this.scrollPosition = window.scrollY; - if (id === 'deleteModal' || id === 'excludeModal' || id === 'duplicateDeleteModal') { + if (id === 'deleteModal' || id === 'excludeModal' || id === 'duplicateDeleteModal' || id === 'clearCacheModal') { modal.element.classList.add('show'); } else { modal.element.style.display = 'block'; diff --git a/static/js/managers/SettingsManager.js b/static/js/managers/SettingsManager.js index f0c7c240..db09d81d 100644 --- a/static/js/managers/SettingsManager.js +++ b/static/js/managers/SettingsManager.js @@ -341,6 +341,37 @@ export class SettingsManager { } } + confirmClearCache() { + // Show confirmation modal + modalManager.showModal('clearCacheModal'); + } + + async executeClearCache() { + try { + // Call the API endpoint to clear cache files + const response = await fetch('/api/clear-cache', { + method: 'POST', + headers: { + 'Content-Type': 'application/json', + } + }); + + const result = await response.json(); + + if (result.success) { + showToast('Cache files have been cleared successfully. Cache will rebuild on next action.', 'success'); + } else { + showToast(`Failed to clear cache: ${result.error}`, 'error'); + } + + // Close the confirmation modal + modalManager.closeModal('clearCacheModal'); + } catch (error) { + showToast(`Error clearing cache: ${error.message}`, 'error'); + modalManager.closeModal('clearCacheModal'); + } + } + async reloadContent() { if (this.currentPage === 'loras') { // Reload the loras without updating folders diff --git a/templates/components/modals.html b/templates/components/modals.html index 142ff8e4..71e4f298 100644 --- a/templates/components/modals.html +++ b/templates/components/modals.html @@ -39,6 +39,21 @@ + +