added resources module to get models and metadata

This commit is contained in:
donny committed 2026-01-03 17:43:10 -07:00
1 parent 6711e006c1
commit 7d2b95df19
3 files changed
+368

No files matched your search

+20
View File
@@ -2,6 +2,7 @@ from server import PromptServer
from .progress import add_progress_hook
from .routes import SetupRoutes
from .workflows import *
from . import resources
from io import BytesIO
import json
@@ -45,5 +46,24 @@ add_progress_hook(my_progress_callback)
# Register API routes
SetupRoutes(PromptServer.instance)
# Optional: Index all new models at startup (set to True to enable)
AUTO_INDEX_ON_STARTUP = True
if AUTO_INDEX_ON_STARTUP:
import threading
def index_on_startup():
print("[ImageLab] Starting background indexing of new models...")
try:
indexed = resources.index_all_new_models()
if indexed:
print(f"[ImageLab] Indexed models: {indexed}")
else:
print("[ImageLab] No new models to index")
except Exception as e:
print(f"[ImageLab] Error during startup indexing: {e}")
# Run in background thread to not block startup
threading.Thread(target=index_on_startup, daemon=True).start()
NODE_CLASS_MAPPINGS = {}
NODE_DISPLAY_NAME_MAPPINGS = {}
+255
View File
@@ -0,0 +1,255 @@
"""
Resource management for external API.
Provides access to models, metadata, and indexing capabilities.
"""
import os
import json
import hashlib
import requests
from typing import Dict, List, Optional
import folder_paths
# Resources directory for storing index files
RESOURCES_DIR = os.path.join(os.path.dirname(__file__), 'resources')
os.makedirs(RESOURCES_DIR, exist_ok=True)
def calculate_sha256(filepath: str) -> str:
"""Calculate SHA256 hash of a file."""
sha256_hash = hashlib.sha256()
with open(filepath, "rb") as f:
for byte_block in iter(lambda: f.read(8192), b""):
sha256_hash.update(byte_block)
return sha256_hash.hexdigest()
def get_index(filename: str) -> Dict:
"""Get existing index data for a model file."""
# Use full filename (with extension) + .index
index_path = os.path.join(RESOURCES_DIR, f"{filename}.index")
if os.path.exists(index_path):
try:
with open(index_path, 'r') as f:
return json.load(f)
except json.JSONDecodeError:
pass
return {
'filename': filename,
'hash': None,
'civitai': None,
'imagelab': {}
}
def save_index(filename: str, data: Dict):
"""Save index data for a model file."""
# Use full filename (with extension) + .index
index_path = os.path.join(RESOURCES_DIR, f"{filename}.index")
with open(index_path, 'w') as f:
json.dump(data, f, indent=2)
def get_civitai_metadata(hash: str) -> Optional[Dict]:
"""Fetch metadata from CivitAI by hash."""
try:
response = requests.get(
f"https://civitai.com/api/v1/model-versions/by-hash/{hash}",
timeout=5
)
if response.status_code == 200:
return response.json()
except Exception as e:
print(f"[Resources] Error fetching CivitAI metadata: {e}")
return None
def index_model(filepath: str, filename: str) -> Dict:
"""
Index a model file - calculate hash and fetch metadata.
Returns the index data.
"""
print(f"[Resources] Indexing: {filename}")
index = get_index(filename)
# Calculate hash if not present
if not index.get('hash'):
print(f"[Resources] Calculating SHA256 hash...")
try:
index['hash'] = calculate_sha256(filepath)
except Exception as e:
print(f"[Resources] Error calculating hash: {e}")
return index
# Fetch CivitAI metadata if not present
if index.get('hash') and not index.get('civitai'):
print(f"[Resources] Fetching CivitAI metadata...")
index['civitai'] = get_civitai_metadata(index['hash'])
save_index(filename, index)
return index
def get_models_by_type(model_type: str) -> List[Dict]:
"""
Get all models of a specific type with basic info (no indexing).
Args:
model_type: Type of model (checkpoints, loras, vae, etc.)
"""
models = []
if model_type not in folder_paths.folder_names_and_paths:
return models
# Get files using folder_paths API
files = folder_paths.get_filename_list(model_type)
for filename in files:
models.append({
'label': os.path.splitext(filename)[0],
'apiName': filename,
'indexed': os.path.exists(os.path.join(RESOURCES_DIR, f"{filename}.index"))
})
return models
def index_model_by_name(model_type: str, filename: str) -> Dict:
"""
Index a specific model file by name.
Args:
model_type: Type of model (checkpoints, loras, etc.)
filename: The filename to index
Returns:
Dict with hash and metadata
"""
if model_type not in folder_paths.folder_names_and_paths:
raise ValueError(f"Invalid model type: {model_type}")
filepath = folder_paths.get_full_path(model_type, filename)
if not filepath:
raise FileNotFoundError(f"Model file not found: {filename}")
# Index the model
index = index_model(filepath, filename)
return {
'filename': filename,
'hash': index.get('hash'),
'civitai': index.get('civitai'),
'imagelab': index.get('imagelab', {})
}
def index_all_new_models() -> Dict[str, int]:
"""
Index all models that don't have an index file yet.
Returns a count of indexed models per type.
"""
model_types = [
'checkpoints', 'loras', 'vae', 'embeddings', 'upscale_models',
'controlnet', 'clip', 'clip_vision', 'diffusion_models'
]
indexed_counts = {}
for model_type in model_types:
if model_type not in folder_paths.folder_names_and_paths:
continue
count = 0
files = folder_paths.get_filename_list(model_type)
for filename in files:
index_path = os.path.join(RESOURCES_DIR, f"{filename}.index")
# Only index if no index file exists
if not os.path.exists(index_path):
try:
filepath = folder_paths.get_full_path(model_type, filename)
if filepath:
index_model(filepath, filename)
count += 1
except Exception as e:
print(f"[Resources] Error indexing {filename}: {e}")
if count > 0:
indexed_counts[model_type] = count
return indexed_counts
def get_all_models() -> Dict[str, List[Dict]]:
"""
Get all available models grouped by type (no indexing).
"""
model_types = [
'checkpoints',
'loras',
'vae',
'embeddings',
'upscale_models',
'controlnet',
'clip',
'clip_vision',
'diffusion_models',
'unet',
'gligen',
'photomaker',
'style_models'
]
resources = {}
for model_type in model_types:
try:
models = get_models_by_type(model_type, skip_indexing=skip_indexing)
if models: # Only include if models exist
resources[model_type] = models
except Exception as e:
print(f"[Resources] Error loading {model_type}: {e}")
return resources
def get_samplers() -> List[Dict]:
"""Get available samplers."""
import comfy.samplers
return [
{
'label': sampler,
'apiName': sampler,
'metadata': None
}
for sampler in comfy.samplers.KSampler.SAMPLERS
]
def get_schedulers() -> List[Dict]:
"""Get available schedulers."""
import comfy.samplers
return [
{
'label': scheduler,
'apiName': scheduler,
'metadata': None
}
for scheduler in comfy.samplers.KSampler.SCHEDULERS
]
def get_upscale_methods() -> List[Dict]:
"""Get available upscale methods."""
import nodes
return [
{
'label': method,
'apiName': method,
'metadata': None
}
for method in nodes.LatentUpscale.upscale_methods
]
+93
View File
@@ -5,6 +5,7 @@ from aiohttp import web
from server import PromptServer
from .workflows import get_workflow, get_workflow_metadata, list_workflows
from . import resources
def SetupRoutes(server: PromptServer):
"""Register API routes with the ComfyUI server."""
@@ -71,6 +72,98 @@ def SetupRoutes(server: PromptServer):
'error': f"Workflow execution failed: {str(e)}"
}, status=500)
@server.instance.routes.get("/imagelab/resources")
async def get_all_resources(request):
"""Get all available resources (models, samplers, etc.) - fast, no indexing"""
try:
models = resources.get_all_models()
return web.json_response({
'success': True,
'resources': {
**models,
'samplers': resources.get_samplers(),
'schedulers': resources.get_schedulers(),
'upscale_methods': resources.get_upscale_methods()
}
})
except Exception as e:
return web.json_response({
'success': False,
'error': str(e)
}, status=500)
@server.instance.routes.get("/imagelab/resources/{resource_type}")
async def get_resource_by_type(request):
"""Get resources of a specific type - fast, no indexing"""
resource_type = request.match_info['resource_type']
try:
# Handle special resource types
if resource_type == 'samplers':
result = resources.get_samplers()
elif resource_type == 'schedulers':
result = resources.get_schedulers()
elif resource_type == 'upscale_methods':
result = resources.get_upscale_methods()
else:
# Try to get as a model type
result = resources.get_models_by_type(resource_type)
return web.json_response({
'success': True,
'resource_type': resource_type,
'items': result
})
except Exception as e:
return web.json_response({
'success': False,
'error': str(e)
}, status=500)
@server.instance.routes.post("/imagelab/resources/{resource_type}/index/{filename}")
async def index_model_file(request):
"""Index a specific model file - calculate hash and fetch metadata"""
resource_type = request.match_info['resource_type']
filename = request.match_info['filename']
try:
metadata = resources.index_model_by_name(resource_type, filename)
return web.json_response({
'success': True,
'resource_type': resource_type,
'filename': filename,
'metadata': metadata
})
except FileNotFoundError as e:
return web.json_response({
'success': False,
'error': str(e)
}, status=404)
except Exception as e:
return web.json_response({
'success': False,
'error': str(e)
}, status=500)
@server.instance.routes.post("/imagelab/resources/index-all")
async def index_all_models(request):
"""Index all models that don't have index files yet"""
try:
indexed_counts = resources.index_all_new_models()
return web.json_response({
'success': True,
'message': 'Indexing complete',
'indexed': indexed_counts
})
except Exception as e:
return web.json_response({
'success': False,
'error': str(e)
}, status=500)
@server.instance.routes.get("/imagelab/hello")
async def get_hello(request):
"""Test endpoint."""