* Fix DB threading, recent ordering, restore size, and scan timestamps * Fix subfolders API missing include_ancestors param * refactor: move api code into promptmanager_core package * chore: ignore local config, tracking state, and db backups * Fix: fall back to original source when thumbnail img fails to load * fix(core): apply code review fixes, optimizations, and schema compliance - Fix KeyError in image_monitor _get_fallback_prompt dictionary handling - Add secondary LoRA hash stripping in image_monitor prompt lookup - Protect dual PromptManager workflows from metadata overwrite in patched_save_images - Support WebP, JPEG, and GIF metadata extraction via image.info - Add default values for prepend_text and append_text in INPUT_TYPES - Add **kwargs to encode_prompt, process_text, search, and IS_CHANGED - Declare explicit RETURN_NAMES across PromptManager and PromptManagerText - Add close() proxy to PromptDatabase and fix Windows SQLite connection locks - Normalize database and subfolder paths for cross-platform consistency - Update test suite teardown handlers and mock targets across 17 test modules - Add comprehensive CHANGELOG.md and issue.txt tracking documentation * Close test databases before unlinking temp files The usage and image-linking tests unlinked their temp database while the persistent SQLite connection was still open, so Windows raised WinError 32 from tearDown (POSIX allows unlinking an open file, so upstream CI never saw it). Close the database first and ignore a transient lock, matching tests/test_database.py. * Ignore local tracking state and prebackfill database backup * style: restore black formatting after 3.6.0 merge The fork-only default:" additions to prepend_text/append_text dropped the trailing commas, which black reformats. This is the entire cause of Tests #4 on main: black --check failed with 'would reformat prompt_manager.py' while every other job (test matrix, coverage, comfyui, js-test) passed. No behaviour change. * feat(images): collect AVIF as a media type (#652) The EXIF reader from #650 reads the prompt and workflow records ComfyUI's SaveImageAdvanced writes into an AVIF, but no file-type list named .avif, so neither the scan nor the monitor ever handed it one. Every list now names .avif: the scan and its deletion allowlist, the monitor's default and fallback, the gallery and thumbnail walks, serving and Inspect, auto-tagging's listing and its path check, the capture store, the preview source order and the diagnostics count. Pillow's floor here is >= 10.1.0 (ComfyUI's) and Pillow opens AVIF only from 11.0, and only when built with an AVIF decoder. utils/media_formats.collectable asks PIL.features.check("avif") at every collection point, so a Pillow without AVIF skips the file quietly and behaves exactly as before #652; the tests pin both answers on the gallery walk, the monitor, auto-tagging, the capture store and the scan. gallery.monitoring.extensions is saved per install and overrides the default, so a list saved before #652 gains .avif last on load, keeping every entry the install chose; an empty list stays empty, and a value that is not a list keeps the current one. The fixture is tests/fixtures/media/comfyui_avif.avif: a 1 KB still written by ComfyUI's own _save_avif (tools/make_avif_fixture.py regenerates it) carrying a PromptManager graph. The scan stores and links its prompt and pair; the monitor links the same positive prompt from the file's own EXIF. The local browser-only Inspect reader is unchanged: the bundled front-end reader does not parse AVIF, so the chooser still offers what it can read. Library Inspect reads an AVIF through the server, where Pillow answers. * chore: drop two local ignore rules that are not part of AVIF support (#652) --------- Co-authored-by: LacklusterOpsec <LacklusterOpsec@users.noreply.github.com> Co-authored-by: Vito Sansevero <vito.sansevero@gmail.com>
485 lines
18 KiB
Python
485 lines
18 KiB
Python
"""Diagnostic utilities for troubleshooting the PromptManager gallery system.
|
|
|
|
This module provides comprehensive diagnostic tools to help identify and resolve
|
|
issues with the PromptManager system, particularly the gallery and image monitoring
|
|
functionality. It performs systematic checks of all system components and provides
|
|
clear feedback on potential problems.
|
|
|
|
The diagnostic system checks:
|
|
- Database connectivity and schema integrity
|
|
- Image table structure and data
|
|
- File system permissions and access
|
|
- ComfyUI output directory detection
|
|
- Required Python dependencies
|
|
- System integration points
|
|
|
|
Typical usage:
|
|
from utils.diagnostics import GalleryDiagnostics, run_diagnostics
|
|
|
|
# Run full diagnostic suite
|
|
results = run_diagnostics()
|
|
|
|
# Or create custom diagnostic instance
|
|
diagnostics = GalleryDiagnostics("custom_db.db")
|
|
database_status = diagnostics.check_database()
|
|
|
|
The diagnostics provide:
|
|
- Clear pass/fail status for each component
|
|
- Detailed error messages and remediation suggestions
|
|
- Statistics and system information
|
|
- Test utilities for verifying functionality
|
|
"""
|
|
|
|
import os
|
|
import sqlite3
|
|
from contextlib import closing
|
|
from pathlib import Path
|
|
from typing import Dict, Any
|
|
|
|
from .logging_config import get_logger
|
|
from .media_folders import in_skipped_folder
|
|
|
|
try:
|
|
from ..database.workflow_documents import DocumentReader, resolve_image_row
|
|
except ImportError: # loaded as a top-level ``utils`` package
|
|
from database.workflow_documents import DocumentReader, resolve_image_row
|
|
|
|
|
|
class GalleryDiagnostics:
|
|
"""Diagnostics for the gallery system.
|
|
|
|
This class provides comprehensive diagnostic capabilities for the PromptManager
|
|
gallery system. It systematically checks all components and dependencies to
|
|
identify potential issues and provide actionable feedback.
|
|
|
|
The diagnostics cover:
|
|
- Database structure and connectivity
|
|
- Image tracking table integrity
|
|
- File system access and permissions
|
|
- ComfyUI integration points
|
|
- Python dependency availability
|
|
|
|
Each diagnostic method returns a standardized result dictionary with:
|
|
- status: 'ok', 'warning', or 'error'
|
|
- message: Descriptive message (for warnings/errors)
|
|
- Additional data specific to the diagnostic
|
|
"""
|
|
|
|
def __init__(self, db_path: str = None):
|
|
"""Initialize the diagnostics system.
|
|
|
|
Args:
|
|
db_path: Path to the SQLite database file to diagnose.
|
|
If None, the library's database (see
|
|
``utils.library_location``).
|
|
"""
|
|
if db_path is None:
|
|
db_path = self._resolve_db_path()
|
|
self.db_path = db_path
|
|
self.logger = get_logger("prompt_manager.diagnostics")
|
|
|
|
@staticmethod
|
|
def _resolve_db_path() -> str:
|
|
"""The library's database: the same resolver as PromptDatabase."""
|
|
try:
|
|
from ..database.operations import resolve_library_location
|
|
except ImportError:
|
|
from database.operations import resolve_library_location
|
|
return resolve_library_location().db_path
|
|
|
|
def run_full_diagnostic(self) -> Dict[str, Any]:
|
|
"""Run a complete diagnostic check.
|
|
|
|
Executes all diagnostic checks in sequence and provides a comprehensive
|
|
report of system status. Logs detailed information during the process.
|
|
|
|
Returns:
|
|
Dictionary mapping diagnostic categories to their results:
|
|
- database: Database connectivity and structure check
|
|
- images_table: Image tracking table specific check
|
|
- file_system: File system access and permissions check
|
|
- comfyui_output: ComfyUI output directory detection
|
|
- dependencies: Python dependency availability check
|
|
"""
|
|
self.logger.info("\n" + "=" * 60)
|
|
self.logger.info("[DIAG] PROMPTMANAGER GALLERY DIAGNOSTICS")
|
|
self.logger.info("=" * 60)
|
|
|
|
results = {
|
|
"database": self.check_database(),
|
|
"images_table": self.check_images_table(),
|
|
"file_system": self.check_file_system(),
|
|
"comfyui_output": self.check_comfyui_output(),
|
|
"dependencies": self.check_dependencies(),
|
|
}
|
|
|
|
self.logger.info("\n" + "=" * 60)
|
|
self.logger.info("[SUMMARY] DIAGNOSTIC SUMMARY")
|
|
self.logger.info("=" * 60)
|
|
|
|
for category, result in results.items():
|
|
status = "[PASS] PASS" if result["status"] == "ok" else "[FAIL] FAIL"
|
|
self.logger.info(f"{category.upper():<20} {status}")
|
|
if result["status"] != "ok":
|
|
self.logger.warning(f" Issue: {result['message']}")
|
|
|
|
self.logger.info("\n" + "=" * 60)
|
|
return results
|
|
|
|
def check_database(self) -> Dict[str, Any]:
|
|
"""Check database connection and structure.
|
|
|
|
Verifies that the database file exists, is accessible, and contains
|
|
the expected prompt table structure.
|
|
|
|
Returns:
|
|
Dictionary containing:
|
|
- status: 'ok' or 'error'
|
|
- message: Error description (if status is 'error')
|
|
- prompt_count: Number of prompts in database (if successful)
|
|
- has_images_table: Whether generated_images table exists (if successful)
|
|
"""
|
|
self.logger.info("\n[DB] Checking Database...")
|
|
|
|
try:
|
|
if not os.path.exists(self.db_path):
|
|
return {
|
|
"status": "error",
|
|
"message": f"Database file not found: {self.db_path}",
|
|
}
|
|
|
|
with closing(sqlite3.connect(self.db_path)) as conn:
|
|
conn.row_factory = sqlite3.Row
|
|
|
|
# Check prompts table
|
|
cursor = conn.execute("SELECT COUNT(*) as count FROM prompts")
|
|
prompt_count = cursor.fetchone()["count"]
|
|
self.logger.info(f" [NOTE] Prompts in database: {prompt_count}")
|
|
|
|
# Check if generated_images table exists
|
|
cursor = conn.execute("""
|
|
SELECT name FROM sqlite_master
|
|
WHERE type='table' AND name='generated_images'
|
|
""")
|
|
|
|
has_images_table = cursor.fetchone() is not None
|
|
self.logger.info(f" [IMG] Images table exists: {has_images_table}")
|
|
|
|
return {
|
|
"status": "ok",
|
|
"prompt_count": prompt_count,
|
|
"has_images_table": has_images_table,
|
|
}
|
|
|
|
except Exception as e:
|
|
return {"status": "error", "message": f"Database error: {str(e)}"}
|
|
|
|
def check_images_table(self) -> Dict[str, Any]:
|
|
"""Check the generated_images table specifically.
|
|
|
|
Examines the generated_images table structure and content to verify
|
|
the gallery system can function properly.
|
|
|
|
Returns:
|
|
Dictionary containing:
|
|
- status: 'ok' or 'error'
|
|
- message: Error description (if table missing or inaccessible)
|
|
- image_count: Number of images in table (if successful)
|
|
- recent_images: List of recent image records (if successful)
|
|
"""
|
|
self.logger.info("\n[IMG] Checking Images Table...")
|
|
|
|
try:
|
|
with closing(sqlite3.connect(self.db_path)) as conn:
|
|
conn.row_factory = sqlite3.Row
|
|
|
|
# Check if table exists
|
|
cursor = conn.execute("""
|
|
SELECT name FROM sqlite_master
|
|
WHERE type='table' AND name='generated_images'
|
|
""")
|
|
|
|
if not cursor.fetchone():
|
|
return {
|
|
"status": "error",
|
|
"message": (
|
|
"generated_images table does not exist - "
|
|
"run the updated code to create it"
|
|
),
|
|
}
|
|
|
|
# Check image records
|
|
cursor = conn.execute("SELECT COUNT(*) as count FROM generated_images")
|
|
image_count = cursor.fetchone()["count"]
|
|
self.logger.info(f" [STATS] Images in database: {image_count}")
|
|
|
|
# Get recent images
|
|
cursor = conn.execute("""
|
|
SELECT gi.*, p.text
|
|
FROM generated_images gi
|
|
LEFT JOIN prompts p ON gi.prompt_id = p.id
|
|
ORDER BY gi.generation_time DESC
|
|
LIMIT 5
|
|
""")
|
|
reader = DocumentReader(conn)
|
|
recent_images = [resolve_image_row(reader, row) for row in cursor]
|
|
|
|
self.logger.info(f" [TIME] Recent images: {len(recent_images)}")
|
|
for img in recent_images:
|
|
self.logger.info(
|
|
f" - {img['filename']} -> Prompt {img['prompt_id']}"
|
|
)
|
|
|
|
return {
|
|
"status": "ok",
|
|
"image_count": image_count,
|
|
"recent_images": recent_images,
|
|
}
|
|
|
|
except Exception as e:
|
|
return {"status": "error", "message": f"Images table error: {str(e)}"}
|
|
|
|
def check_file_system(self) -> Dict[str, Any]:
|
|
"""Check file system and permissions.
|
|
|
|
Verifies that the application has appropriate file system access
|
|
for reading images and writing database files.
|
|
|
|
Returns:
|
|
Dictionary containing:
|
|
- status: 'ok' or 'error'
|
|
- message: Error description (if issues detected)
|
|
- current_dir: Current working directory path
|
|
- can_write: Whether write access is available
|
|
"""
|
|
self.logger.info("\n[DIR] Checking File System...")
|
|
|
|
try:
|
|
# Check current directory
|
|
current_dir = os.getcwd()
|
|
self.logger.info(f" [FOLDER] Current directory: {current_dir}")
|
|
|
|
# Check if we can write to current directory
|
|
test_file = "test_write.tmp"
|
|
try:
|
|
with open(test_file, "w") as f:
|
|
f.write("test")
|
|
os.remove(test_file)
|
|
can_write = True
|
|
except (IOError, OSError):
|
|
can_write = False
|
|
|
|
self.logger.info(f" [EDIT] Can write to directory: {can_write}")
|
|
|
|
return {"status": "ok", "current_dir": current_dir, "can_write": can_write}
|
|
|
|
except Exception as e:
|
|
return {"status": "error", "message": f"File system error: {str(e)}"}
|
|
|
|
def check_comfyui_output(self) -> Dict[str, Any]:
|
|
"""Check ComfyUI output directories.
|
|
|
|
Attempts to locate ComfyUI output directories where generated images
|
|
would be stored. Checks both common locations and ComfyUI's configured paths.
|
|
|
|
Returns:
|
|
Dictionary containing:
|
|
- status: 'ok' if directories found, 'warning' if none found
|
|
- message: Warning message (if no directories found)
|
|
- output_dirs: List of detected output directory paths
|
|
"""
|
|
self.logger.info("\n[STYLE] Checking ComfyUI Output...")
|
|
|
|
output_dirs = []
|
|
|
|
def _add_dir(abs_path, source):
|
|
if abs_path not in output_dirs:
|
|
output_dirs.append(abs_path)
|
|
self.logger.info(f" [DIR] {source}: {abs_path}")
|
|
try:
|
|
image_files = []
|
|
for ext in [".png", ".jpg", ".jpeg", ".webp", ".avif"]:
|
|
image_files.extend(
|
|
found
|
|
for found in Path(abs_path).rglob(f"*{ext}")
|
|
if not in_skipped_folder(
|
|
found.relative_to(abs_path).parts[:-1]
|
|
)
|
|
)
|
|
self.logger.info(f" [IMG] Images found: {len(image_files)}")
|
|
except Exception as e:
|
|
self.logger.error(f" [FAIL] Error scanning: {e}")
|
|
|
|
# Check user-configured gallery directories from config.json
|
|
try:
|
|
from py.config import GalleryConfig
|
|
|
|
for cfg_dir in GalleryConfig.MONITORING_DIRECTORIES:
|
|
abs_path = os.path.abspath(cfg_dir)
|
|
if os.path.exists(abs_path):
|
|
_add_dir(abs_path, "Configured directory")
|
|
except Exception as e:
|
|
self.logger.debug(f" [NOTE] Could not load gallery config: {e}")
|
|
|
|
# Check ComfyUI's own output directory (respects --output-directory)
|
|
try:
|
|
import folder_paths
|
|
|
|
comfyui_output = folder_paths.get_output_directory()
|
|
if comfyui_output and os.path.exists(comfyui_output):
|
|
_add_dir(os.path.abspath(comfyui_output), "ComfyUI output dir")
|
|
except ImportError:
|
|
self.logger.warning(" [WARN] ComfyUI folder_paths not available")
|
|
|
|
# Fallback: check common relative paths
|
|
if not output_dirs:
|
|
for dir_path in [
|
|
"output",
|
|
"../output",
|
|
"../../output",
|
|
"ComfyUI/output",
|
|
"../ComfyUI/output",
|
|
"../../ComfyUI/output",
|
|
]:
|
|
abs_path = os.path.abspath(dir_path)
|
|
if os.path.exists(abs_path):
|
|
_add_dir(abs_path, "Found output dir")
|
|
|
|
return {
|
|
"status": "ok" if output_dirs else "warning",
|
|
"message": "No output directories found" if not output_dirs else None,
|
|
"output_dirs": output_dirs,
|
|
}
|
|
|
|
def check_dependencies(self) -> Dict[str, Any]:
|
|
"""Check required dependencies.
|
|
|
|
Verifies that all required Python packages are available for the
|
|
PromptManager system to function properly.
|
|
|
|
Returns:
|
|
Dictionary containing:
|
|
- status: 'ok' if all dependencies available, 'error' if any missing
|
|
- message: Error description (if dependencies missing)
|
|
- dependencies: Dictionary mapping package names to availability status
|
|
"""
|
|
self.logger.info("\n[PKG] Checking Dependencies...")
|
|
|
|
dependencies = {"watchdog": False, "PIL": False, "sqlite3": False}
|
|
|
|
# Check watchdog
|
|
try:
|
|
import watchdog
|
|
|
|
dependencies["watchdog"] = True
|
|
version = getattr(watchdog, "__version__", "unknown version")
|
|
self.logger.info(f" [PASS] watchdog: {version}")
|
|
except ImportError:
|
|
self.logger.error(" [FAIL] watchdog: NOT INSTALLED")
|
|
|
|
# Check PIL
|
|
try:
|
|
from PIL import Image # noqa: F401 - availability probe
|
|
|
|
dependencies["PIL"] = True
|
|
self.logger.info(" [PASS] PIL (Pillow): Available")
|
|
except ImportError:
|
|
self.logger.error(" [FAIL] PIL (Pillow): NOT AVAILABLE")
|
|
|
|
# sqlite3 is imported at the top of this module, so it is always here.
|
|
dependencies["sqlite3"] = True
|
|
self.logger.info(f" [PASS] sqlite3: {sqlite3.sqlite_version}")
|
|
|
|
all_deps_ok = all(dependencies.values())
|
|
|
|
return {
|
|
"status": "ok" if all_deps_ok else "error",
|
|
"message": "Missing dependencies" if not all_deps_ok else None,
|
|
"dependencies": dependencies,
|
|
}
|
|
|
|
def create_test_image_link(
|
|
self, prompt_id: int, test_image_path: str = None
|
|
) -> Dict[str, Any]:
|
|
"""Create a test image link to verify the system works.
|
|
|
|
Creates a test entry in the generated_images table to verify that
|
|
the image linking functionality is working correctly.
|
|
|
|
Args:
|
|
prompt_id: ID of an existing prompt to link the test image to
|
|
test_image_path: Optional path for the test image (uses fake path if None)
|
|
|
|
Returns:
|
|
Dictionary containing:
|
|
- status: 'ok' if test link created successfully, 'error' otherwise
|
|
- message: Success or error message
|
|
- image_id: ID of created test image record (if successful)
|
|
"""
|
|
self.logger.info(f"\n[TEST] Creating test image link for prompt {prompt_id}...")
|
|
|
|
try:
|
|
# Import database operations
|
|
import sys
|
|
import os
|
|
|
|
sys.path.insert(
|
|
0, os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
|
|
)
|
|
from database.operations import PromptDatabase
|
|
|
|
db = PromptDatabase()
|
|
|
|
# Create a fake image path if none provided
|
|
if not test_image_path:
|
|
test_image_path = "/fake/test/image.png"
|
|
|
|
# Create test metadata
|
|
test_metadata = {
|
|
"file_info": {
|
|
"size": 1024000,
|
|
"dimensions": [512, 512],
|
|
"format": "PNG",
|
|
},
|
|
"workflow": {"test": True},
|
|
"prompt": {"test_prompt": "This is a test"},
|
|
}
|
|
|
|
# Link the test image
|
|
image_id = db.link_image_to_prompt(
|
|
prompt_id=str(prompt_id),
|
|
image_path=test_image_path,
|
|
metadata=test_metadata,
|
|
)
|
|
|
|
self.logger.info(f" [PASS] Test image linked with ID: {image_id}")
|
|
|
|
return {
|
|
"status": "ok",
|
|
"image_id": image_id,
|
|
"message": f"Test image linked successfully with ID {image_id}",
|
|
}
|
|
|
|
except Exception as e:
|
|
return {
|
|
"status": "error",
|
|
"message": f"Failed to create test link: {str(e)}",
|
|
}
|
|
|
|
|
|
def run_diagnostics() -> Dict[str, Any]:
|
|
"""Run diagnostics from command line.
|
|
|
|
Convenience function to create a GalleryDiagnostics instance and run
|
|
the full diagnostic suite with default settings.
|
|
|
|
Returns:
|
|
Complete diagnostic results dictionary
|
|
"""
|
|
diagnostics = GalleryDiagnostics()
|
|
return diagnostics.run_full_diagnostic()
|
|
|
|
|
|
if __name__ == "__main__":
|
|
run_diagnostics()
|