Enhance LoraRoutes and templates for improved cache initialization handling

- Updated LoraRoutes to better check cache initialization status and handle loading states.
- Added logging for successful cache loading and error handling for cache retrieval failures.
- Enhanced base.html and loras.html templates to display a loading spinner and initialization notice during cache setup.
- Improved user experience by ensuring the loading notice is displayed appropriately based on initialization state.
This commit is contained in:
Will Miao
2025-03-28 15:04:35 +08:00
parent 85c3e33343
commit 5a8a402fdc
4 changed files with 91 additions and 26 deletions

View File

@@ -58,11 +58,13 @@ class LoraRoutes:
async def handle_loras_page(self, request: web.Request) -> web.Response: async def handle_loras_page(self, request: web.Request) -> web.Response:
"""Handle GET /loras request""" """Handle GET /loras request"""
try: try:
# 不等待缓存数据,直接检查缓存状态 # 检查缓存初始化状态,增强判断条件
is_initializing = ( is_initializing = (
self.scanner._cache is None and self.scanner._cache is None or
(self.scanner._initialization_task is not None and (self.scanner._initialization_task is not None and
not self.scanner._initialization_task.done()) not self.scanner._initialization_task.done()) or
(self.scanner._cache is not None and len(self.scanner._cache.raw_data) == 0 and
self.scanner._initialization_task is not None)
) )
if is_initializing: if is_initializing:
@@ -74,16 +76,31 @@ class LoraRoutes:
settings=settings, # Pass settings to template settings=settings, # Pass settings to template
request=request # Pass the request object to the template request=request # Pass the request object to the template
) )
logger.info("Loras page is initializing, returning loading page")
else: else:
# 正常流程 # 正常流程 - 但不要等待缓存刷新
cache = await self.scanner.get_cached_data() try:
template = self.template_env.get_template('loras.html') cache = await self.scanner.get_cached_data(force_refresh=False)
rendered = template.render( template = self.template_env.get_template('loras.html')
folders=cache.folders, rendered = template.render(
is_initializing=False, folders=cache.folders,
settings=settings, # Pass settings to template is_initializing=False,
request=request # Pass the request object to the template settings=settings, # Pass settings to template
) request=request # Pass the request object to the template
)
logger.info(f"Loras page loaded successfully with {len(cache.raw_data)} items")
except Exception as cache_error:
logger.error(f"Error loading cache data: {cache_error}")
# 如果获取缓存失败,也显示初始化页面
template = self.template_env.get_template('loras.html')
rendered = template.render(
folders=[],
is_initializing=True,
settings=settings,
request=request
)
logger.info("Cache error, returning initialization page")
return web.Response( return web.Response(
text=rendered, text=rendered,

View File

@@ -3,6 +3,7 @@ import os
import logging import logging
import asyncio import asyncio
import shutil import shutil
import time
from typing import List, Dict, Optional from typing import List, Dict, Optional
from dataclasses import dataclass from dataclasses import dataclass
from operator import itemgetter from operator import itemgetter
@@ -91,6 +92,7 @@ class LoraScanner:
async def _initialize_cache(self) -> None: async def _initialize_cache(self) -> None:
"""Initialize or refresh the cache""" """Initialize or refresh the cache"""
try: try:
start_time = time.time()
# Clear existing hash index # Clear existing hash index
self._hash_index.clear() self._hash_index.clear()
@@ -122,7 +124,7 @@ class LoraScanner:
await self._cache.resort() await self._cache.resort()
self._initialization_task = None self._initialization_task = None
logger.info("LoRA Manager: Cache initialization completed") logger.info(f"LoRA Manager: Cache initialization completed in {time.time() - start_time:.2f} seconds, found {len(raw_data)} loras")
except Exception as e: except Exception as e:
logger.error(f"LoRA Manager: Error initializing cache: {e}") logger.error(f"LoRA Manager: Error initializing cache: {e}")
self._cache = LoraCache( self._cache = LoraCache(

View File

@@ -37,6 +37,49 @@
<link rel="preconnect" href="https://civitai.com"> <link rel="preconnect" href="https://civitai.com">
<link rel="preconnect" href="https://cdnjs.cloudflare.com"> <link rel="preconnect" href="https://cdnjs.cloudflare.com">
<!-- Add styles for initialization notice -->
{% if is_initializing %}
<style>
.initialization-notice {
position: fixed;
top: 0;
left: 0;
width: 100%;
height: 100%;
background-color: rgba(0, 0, 0, 0.85);
z-index: 9999;
margin-top: 0;
border-radius: 0;
display: flex;
justify-content: center;
align-items: center;
color: white;
}
.notice-content {
background-color: rgba(30, 30, 30, 0.9);
border-radius: 10px;
padding: 30px;
text-align: center;
box-shadow: 0 0 20px rgba(0, 0, 0, 0.5);
max-width: 500px;
width: 80%;
}
.loading-spinner {
border: 5px solid rgba(255, 255, 255, 0.3);
border-radius: 50%;
border-top: 5px solid #fff;
width: 50px;
height: 50px;
margin: 0 auto 20px;
animation: spin 1s linear infinite;
}
@keyframes spin {
0% { transform: rotate(0deg); }
100% { transform: rotate(360deg); }
}
</style>
{% endif %}
<script> <script>
// 计算滚动条宽度并设置CSS变量 // 计算滚动条宽度并设置CSS变量
document.addEventListener('DOMContentLoaded', () => { document.addEventListener('DOMContentLoaded', () => {
@@ -52,6 +95,15 @@
</head> </head>
<body data-page="{% block page_id %}base{% endblock %}"> <body data-page="{% block page_id %}base{% endblock %}">
{% if is_initializing %}
<div class="initialization-notice">
<div class="notice-content">
<div class="loading-spinner"></div>
<h2>{% block init_title %}Initializing{% endblock %}</h2>
<p>{% block init_message %}Scanning and building cache. This may take a few minutes...{% endblock %}</p>
</div>
</div>
{% else %}
{% include 'components/header.html' %} {% include 'components/header.html' %}
<div class="page-content"> <div class="page-content">
@@ -61,22 +113,12 @@
{% block additional_components %}{% endblock %} {% block additional_components %}{% endblock %}
<div class="container"> <div class="container">
{% if is_initializing %}
<div class="initialization-notice">
<div class="notice-content">
<div class="loading-spinner"></div>
<h2>{% block init_title %}Initializing{% endblock %}</h2>
<p>{% block init_message %}Scanning and building cache. This may take a few minutes...{% endblock %}
</p>
</div>
</div>
{% else %}
{% block content %}{% endblock %} {% block content %}{% endblock %}
{% endif %}
</div> </div>
{% block overlay %}{% endblock %} {% block overlay %}{% endblock %}
</div> </div>
{% endif %}
{% block main_script %}{% endblock %} {% block main_script %}{% endblock %}
@@ -100,11 +142,11 @@
} }
// 启动状态检查 // 启动状态检查
checkInitStatus(); setTimeout(checkInitStatus, 1000); // 给页面完全加载的时间
</script> </script>
{% endif %} {% endif %}
{% block additional_scripts %}{% endblock %} {% block additional_scripts %}{% endblock %}
</body> </body>
</html> </html>

View File

@@ -4,7 +4,9 @@
{% block page_id %}loras{% endblock %} {% block page_id %}loras{% endblock %}
{% block preload %} {% block preload %}
{% if not is_initializing %}
<link rel="preload" href="/loras_static/js/loras.js" as="script" crossorigin="anonymous"> <link rel="preload" href="/loras_static/js/loras.js" as="script" crossorigin="anonymous">
{% endif %}
{% endblock %} {% endblock %}
{% block init_title %}Initializing LoRA Manager{% endblock %} {% block init_title %}Initializing LoRA Manager{% endblock %}
@@ -29,5 +31,7 @@
{% endblock %} {% endblock %}
{% block main_script %} {% block main_script %}
{% if not is_initializing %}
<script type="module" src="/loras_static/js/loras.js"></script> <script type="module" src="/loras_static/js/loras.js"></script>
{% endif %}
{% endblock %} {% endblock %}