astrbot_plugin_imagestudio/backend/services/dashboard_service.py

103 行
3.3 KiB
Python

"""Dashboard summary service."""
from __future__ import annotations
from pathlib import Path
from typing import Any
from core.config_service import ConfigService, ImageStudioConfig
from database.db_helper import Database, REPO_ROOT
class DashboardService:
def __init__(
self,
database: Database,
config_service: ConfigService | None = None,
):
self.database = database
self.config_service = config_service or ConfigService()
def get_summary(self) -> dict[str, Any]:
config = self.config_service.load()
return {
"plugin_status": "running",
"today_generation_count": 0,
"active_profiles": self._count_active_profiles(),
"queue": {
"pending": 0,
"running": 0,
"failed": 0,
"dead_letter": 0,
},
"storage": self._storage_summary(config),
"recent_jobs": [],
"recent_images": self._recent_images(),
}
def _count_active_profiles(self) -> int:
conn = self.database.connect()
try:
row = conn.execute(
"SELECT COUNT(*) AS total FROM character_profiles WHERE status = ?",
("active",),
).fetchone()
finally:
conn.close()
return int(row["total"] if row else 0)
def _recent_images(self) -> list[dict[str, Any]]:
conn = self.database.connect()
try:
rows = conn.execute(
"""
SELECT image_id, node_id, workflow_id, profile_id, thumbnail_uri, image_uri, created_at
FROM generation_images
WHERE is_archived = 0
ORDER BY created_at DESC
LIMIT 10
"""
).fetchall()
finally:
conn.close()
return [
{
"image_id": row["image_id"],
"node_id": row["node_id"],
"workflow_id": row["workflow_id"],
"profile_id": row["profile_id"],
"thumbnail_uri": row["thumbnail_uri"],
"image_uri": row["image_uri"],
"created_at": str(row["created_at"]),
}
for row in rows
]
def _storage_summary(self, config: ImageStudioConfig) -> dict[str, int]:
images_bytes = _directory_size(_resolve_data_path(config.storage.images_path))
thumbnails_bytes = _directory_size(_resolve_data_path(config.storage.thumbnails_path))
materials_bytes = _directory_size(_resolve_data_path(config.storage.materials_path))
temp_bytes = _directory_size(_resolve_data_path(config.storage.temp_path))
return {
"total_bytes": images_bytes + thumbnails_bytes + materials_bytes + temp_bytes,
"images_bytes": images_bytes + thumbnails_bytes,
"materials_bytes": materials_bytes,
"temp_bytes": temp_bytes,
}
def _resolve_data_path(path: str) -> Path:
resolved = Path(path)
if not resolved.is_absolute():
resolved = REPO_ROOT / resolved
return resolved
def _directory_size(path: Path) -> int:
if not path.exists():
return 0
total = 0
for child in path.rglob("*"):
if child.is_file():
total += child.stat().st_size
return total