Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
16690fd3b4 | ||
|
|
fee7e788b0 | ||
|
|
8f00a3588a | ||
|
|
f1fb075397 | ||
|
|
17ba97cb22 | ||
|
|
a792220746 | ||
|
|
3fd286e862 | ||
|
|
eca57fc076 | ||
|
|
880a9c8f07 | ||
|
|
421a7aafb5 | ||
|
|
9ff083c82c | ||
|
|
7a98647b13 | ||
|
|
7dc532b81a | ||
|
|
f27d26868a | ||
|
|
604e18ee5d | ||
|
|
6531b8f79f | ||
|
|
60b9f0a402 | ||
|
|
170649aff4 | ||
|
|
8f6ae5e538 | ||
|
|
8aa34dfcb0 | ||
|
|
5326e961b6 | ||
|
|
e0bfe04f33 | ||
|
|
bd723bf2d2 | ||
|
|
056aac445e | ||
|
|
17ae04e7ff | ||
|
|
5157a0a003 | ||
|
|
3a5e102913 | ||
|
|
9bfccda0ee | ||
|
|
d64f80bb33 | ||
|
|
1482e15222 | ||
|
|
deba83af77 | ||
|
|
cc7ca295bb | ||
|
|
58bcca2b63 | ||
|
|
799063846a | ||
|
|
7ac3ba4ced | ||
|
|
efb321c8f4 | ||
|
|
b4c8ce900a | ||
|
|
943114abc2 | ||
|
|
c3b1cede93 | ||
|
|
ff9710b15d | ||
|
|
8d72f656f3 | ||
|
|
e71637f049 | ||
|
|
35d373f783 | ||
|
|
f991799d14 | ||
|
|
37bbebaa2b | ||
|
|
edba569d7a | ||
|
|
a462577ca9 | ||
|
|
4b104963fe | ||
|
|
6fcfc975d6 | ||
|
|
48919edeb4 | ||
|
|
e157ef6ed8 | ||
|
|
9645564f67 | ||
|
|
8b2b1b694c | ||
|
|
3f831ef4ab | ||
|
|
45d4da6b73 | ||
|
|
b42620f7a2 | ||
|
|
59c77a427f | ||
|
|
078ff7124b | ||
|
|
0b55205910 | ||
|
|
77a8fe1857 | ||
|
|
d5e5cda937 | ||
|
|
316fa76c62 | ||
|
|
20a14a330d | ||
|
|
52f0e9460c | ||
|
|
d9a05b372f | ||
|
|
f036e7de9e | ||
|
|
ff3e76a20a | ||
|
|
b62f3611da | ||
|
|
58115b743d | ||
|
|
e22279a1a1 | ||
|
|
ae1170a2a8 | ||
|
|
0766ed6d9f | ||
|
|
30fdf3a16f | ||
|
|
60b862b28c | ||
|
|
c89e727e91 | ||
|
|
020eef004e | ||
|
|
b8c8db3375 | ||
|
|
e1d208e14f | ||
|
|
350078359f | ||
|
|
19117cc7cc | ||
|
|
9372658ff6 | ||
|
|
c4de258502 | ||
|
|
0d54b121ff | ||
|
|
541f878f84 | ||
|
|
1ac8cad26b | ||
|
|
4ad4d02783 | ||
|
|
4bed753bed | ||
|
|
082374e0d4 | ||
|
|
a1c4f29acb | ||
|
|
3e7a9750ee | ||
|
|
450e51c102 | ||
|
|
1be5b0db1c | ||
|
|
e9d5ced6a8 | ||
|
|
8596706a25 | ||
|
|
1e37209c0c | ||
|
|
9aef067c9f | ||
|
|
85fcad23f3 | ||
|
|
7961e00bd7 | ||
|
|
06983dc783 | ||
|
|
2e85fcb22f | ||
|
|
943ee858a5 | ||
|
|
138ece0dec | ||
|
|
a9a0817eb8 | ||
|
|
8eae6ff9f3 | ||
|
|
1480f6a179 | ||
|
|
a8f04936a2 | ||
|
|
927ea93c82 |
@@ -0,0 +1,28 @@
|
||||
name: Publish to Comfy registry
|
||||
on:
|
||||
workflow_dispatch:
|
||||
push:
|
||||
branches:
|
||||
- main
|
||||
- master
|
||||
paths:
|
||||
- "pyproject.toml"
|
||||
|
||||
permissions:
|
||||
issues: write
|
||||
|
||||
jobs:
|
||||
publish-node:
|
||||
name: Publish Custom Node to registry
|
||||
runs-on: ubuntu-latest
|
||||
if: ${{ github.repository_owner == 'tmode-1960' }}
|
||||
steps:
|
||||
- name: Check out code
|
||||
uses: actions/checkout@v4
|
||||
with:
|
||||
submodules: true
|
||||
- name: Publish Custom Node
|
||||
uses: Comfy-Org/publish-node-action@v1
|
||||
with:
|
||||
## Add your own personal access token to your Github Repository secrets and reference it here.
|
||||
personal_access_token: ${{ secrets.REGISTRY_ACCESS_TOKEN }}
|
||||
@@ -0,0 +1 @@
|
||||
__pycache__
|
||||
@@ -1,28 +1,103 @@
|
||||
# TA-ComfyUI-Nodes-Pack
|
||||
A collection of various useful ComfyUI custom nodes
|
||||
|
||||
|
||||
## 1. Model Loaders
|
||||
1. ta_load_diffusion_model_with_name
|
||||
2. ta_load_checkpoint_model_with_name
|
||||
3. ta_load_gguf_model_with_name
|
||||
# TA-ComfyUI-Nodes-Pack
|
||||
|
||||
_These are model loaders with an additional output that displays the model name so that it can be used in the further workflow._
|
||||
Custom nodes for [ComfyUI](https://github.com/comfyanonymous/ComfyUI) by **thomo.ART**.
|
||||
|
||||
.png)
|
||||
> ⚠️ **Breaking Change – Version 2.x is not compatible with 1.x nodes.**
|
||||
> Workflows built with version 1.x must be rebuilt. Node names, inputs, and outputs have changed significantly.
|
||||
|
||||
___
|
||||
|
||||
## 2. Extension for EBU-LMStudio
|
||||
#### (https://github.com/burnsbert/ComfyUI-EBU-LMStudio)
|
||||
|
||||
1. ***ta_lmstudio_load_on_run (text2prompt & image2prompt)*** \
|
||||
Loads the LLM Model in the LM Studio server when you click RUN
|
||||
2. ***ta_lmstudio_model_selector (ext2prompt & image2prompt)*** \
|
||||
Selection field for all models installed in LM Studio. Vision models are marked with (V).
|
||||
3. ***ta_ebu_lmstudio_vision_node (image2prompt)*** \
|
||||
Settings for Image2Prompt Generation
|
||||
|
||||
_These are extensions for the EBU-LMStudio custom node._
|
||||

|
||||
|
||||
.png) 
|
||||
---
|
||||
|
||||
## Overview
|
||||
|
||||
A collection of nodes designed for use in thomo.ART workflows, focused on flexible multi-model image generation with LLM/VLM integration, structured prompt routing, and clean workflow management.
|
||||
|
||||
The full documentation is available via the built-in **Help button** in each node (opens in your browser at `http://localhost:8188/ta-nodes/wiki/index.html`).
|
||||
|
||||
---
|
||||
|
||||
## Nodes
|
||||
|
||||
### 🧠 TA Unified Model Switcher
|
||||
Switch between multiple models without changing the workflow. Uses a dropdown to select the active model – all others are skipped via lazy evaluation. Model list is configured via a browser-based editor.
|
||||
|
||||
### 🗂️ TA Model Preset
|
||||
Load MODEL, CLIP, and VAE from a named preset. Supports Diffusion Models (`[D]`), GGUF (`[G]`), and Checkpoints (`[C]`). Presets are managed via a browser-based editor.
|
||||
|
||||
### 📦 TA Load Model (with Name)
|
||||
Combined loader for all three model types. Auto-detects the type from the filename prefix and outputs a `TA_MODEL_NAME` string for use with the Filename Generator.
|
||||
|
||||
### 🤖 TA Smart LLM
|
||||
Text-to-prompt and image-to-prompt via LM Studio or Ollama. Automatically detects vision-capable models. Supports VRAM management and model caching.
|
||||
|
||||
### 🔀 TA Prompt Hub
|
||||
Central prompt collector. Passes through positive prompt, negative prompt, additional prompt, and LoRA trigger words. Combines non-empty parts into a single `combined_prompt` output.
|
||||
|
||||
### 🗂️ TA Prompt Controller
|
||||
Routes between a manually typed prompt and a generated prompt (e.g. from TA Smart LLM). Five modes: Manual Only, Generated Only, two Combine orders, and Clear/Empty.
|
||||
|
||||
### 🎛️ TA Sampler Preset & ⚡ TA KSampler
|
||||
Designed as a pair. TA Sampler Preset loads sampling parameters (steps, CFG, sampler, scheduler, start/end step) from a JSON file via browser editor. TA KSampler accepts sampler and scheduler as plain strings and provides live latent preview per step.
|
||||
|
||||
### 🧹 TA Cleanup Switch
|
||||
Combined VRAM and RAM cleanup in one switchable node. Replaces a three-node cleanup chain. Passes any signal through unchanged. Can be fully disabled with zero overhead.
|
||||
|
||||
### 🌊 TA Flux Guidance Gate
|
||||
Automatically applies Flux Guidance to conditioning when the active sampler preset is FLUX-based (detected via the preset name). Passes conditioning through unchanged for all other presets.
|
||||
|
||||
### 🔧 TA SageAttention Toggler
|
||||
Patches a model with SageAttention and/or PyTorch FP16 matmul acceleration. Supports all five SageAttention kernel variants. Both patches are independent and toggleable.
|
||||
|
||||
### 📁 TA Filename Generator
|
||||
Generates structured output file paths from folder, subfolder (supports strftime date codes), prefix, workflow version, model name, and timestamp. Returns both a base path and an upscaled variant path.
|
||||
|
||||
### 💾 TA Save Image Optional
|
||||
Saves images as JPEG or WebP with configurable quality. Includes an enable toggle and optional companion `.txt` files with prompts and timestamp.
|
||||
|
||||
### 💾 TA Save Image With Prompt
|
||||
Extends ComfyUI's built-in SaveImage with optional companion `.txt` files containing prompts and timestamp. Always saves as PNG.
|
||||
|
||||
### 🎬 TA SeedVR2 Gate
|
||||
Enable/disable gate for the SeedVR2 upscaler pipeline using lazy evaluation. When disabled, all upstream nodes (including the ~14 GB model loaders) are skipped entirely.
|
||||
|
||||
### 💬 TA Discord Link
|
||||
Displays a clickable Discord invite link directly inside the ComfyUI graph. URL and button label are configurable via a browser-based editor.
|
||||
|
||||
---
|
||||
|
||||
## Installation
|
||||
|
||||
### Via ComfyUI Manager
|
||||
Search for `TA-ComfyUI-Nodes-Pack` in the ComfyUI Manager and install.
|
||||
|
||||
### Manual
|
||||
```bash
|
||||
cd ComfyUI/custom_nodes
|
||||
git clone https://github.com/thomoart/TA-ComfyUI-Nodes-Pack
|
||||
```
|
||||
|
||||
Restart ComfyUI after installation.
|
||||
|
||||
---
|
||||
|
||||
## Documentation
|
||||
|
||||
Full node documentation (DE/EN) is built into the pack and accessible directly from ComfyUI via the **🔗 TA Help Link** node or at:
|
||||
|
||||
```
|
||||
http://localhost:8188/ta-nodes/wiki/index.html
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## License
|
||||
|
||||
- **Node Pack:** Apache 2.0
|
||||
- **Workflows:** CC-BY-NC-SA 4.0
|
||||
|
||||
---
|
||||
|
||||
## Links
|
||||
|
||||
[](https://ko-fi.com/thomoart)
|
||||
|
||||
+76
-56
@@ -1,64 +1,84 @@
|
||||
"""
|
||||
TA Nodes Pack - Custom Nodes for ComfyUI
|
||||
Contains nodes for loading various model types with names and text processing
|
||||
Plus LM Studio Vision Integration for Image-to-Prompt
|
||||
Plus LM Studio Load On Run for controlled model loading
|
||||
TA ComfyUI Nodes Pack
|
||||
© Thomas Möhrling (thomo.ART)
|
||||
Erstelldatum: 2026-03-02
|
||||
Änderungsdatum: 2026-03-13
|
||||
Version: v4.0 - TADiscordLink hinzugefügt
|
||||
"""
|
||||
|
||||
# Import base loader nodes
|
||||
from .ta_load_checkpoint_model_with_name import TALoadCheckpointModelWithName
|
||||
from .ta_load_diffusion_model_with_name import TALoadDiffusionModelWithName
|
||||
from .ta_load_gguf_model_with_name import TALoadGGUFModelWithName
|
||||
print("\n" + "="*60)
|
||||
print(" ⚠️ TA-ComfyUI-Nodes-Pack v2.0 — BREAKING CHANGE!")
|
||||
print(" v1.x Workflows sind NICHT kompatibel mit v2.x.")
|
||||
print(" Bitte README lesen vor dem Update!")
|
||||
print(" https://github.com/tmode-1960/TA-ComfyUI-Nodes-Pack")
|
||||
print("="*60 + "\n")
|
||||
|
||||
# Import LM Studio Vision Nodes
|
||||
from .ta_ebu_lmstudio_vision_node import (
|
||||
NODE_CLASS_MAPPINGS as LMSTUDIO_VISION_MAPPINGS,
|
||||
NODE_DISPLAY_NAME_MAPPINGS as LMSTUDIO_VISION_DISPLAY
|
||||
)
|
||||
from .ta_smart_llm import NODE_CLASS_MAPPINGS, NODE_DISPLAY_NAME_MAPPINGS
|
||||
from .ta_llm_prompt_selector import TA_LLM_PromptSelector
|
||||
from .ta_unified_model_switcher import TAUnifiedModelSwitcher
|
||||
from .ta_save_image_optional import TASaveImageOptional
|
||||
from .ta_save_image_with_prompt import TASaveImageWithPrompt
|
||||
from .ta_sageattention_toggler import TASageAttentionToggler
|
||||
from .ta_filename_generator import TAFilenameGenerator
|
||||
from .ta_prompt_controller import TAPromptController
|
||||
from .ta_prompt_hub import TAPromptHub
|
||||
from .ta_load_model_with_name import TALoadModelWithName
|
||||
from .ta_sampler_preset import TASamplerPreset
|
||||
from .ta_ksampler import TAKSampler
|
||||
from .ta_latent_preview import TALatentPreview
|
||||
from .ta_seedvr2_gate import TASeedVR2Gate
|
||||
from .ta_flux_guidance_gate import TAFluxGuidanceGate
|
||||
from .ta_model_presets import TAModelPreset
|
||||
from .ta_directory_captioning import TACaptioning
|
||||
from .ta_cleanup_switch import TACleanupSwitch
|
||||
from .ta_help_link import TAHelpLink
|
||||
from .ta_discord_link import TADiscordLink
|
||||
|
||||
# Import LM Studio Load On Run Node
|
||||
from .ta_lmstudio_load_on_run import (
|
||||
NODE_CLASS_MAPPINGS as LOAD_ON_RUN_MAPPINGS,
|
||||
NODE_DISPLAY_NAME_MAPPINGS as LOAD_ON_RUN_DISPLAY
|
||||
)
|
||||
# Erweiterte Mappings (alt + neu)
|
||||
NODE_CLASS_MAPPINGS.update({
|
||||
"TA_LLM_PromptSelector": TA_LLM_PromptSelector,
|
||||
"TAUnifiedModelSwitcher": TAUnifiedModelSwitcher,
|
||||
"TASaveImageOptional": TASaveImageOptional,
|
||||
"TASaveImageWithPrompt": TASaveImageWithPrompt,
|
||||
"TASageAttentionToggler": TASageAttentionToggler,
|
||||
"TAFilenameGenerator": TAFilenameGenerator,
|
||||
"TAPromptController": TAPromptController,
|
||||
"TAPromptHub": TAPromptHub,
|
||||
"TALoadModelWithName": TALoadModelWithName,
|
||||
"TASamplerPreset": TASamplerPreset,
|
||||
"TAKSampler": TAKSampler,
|
||||
"TALatentPreview": TALatentPreview,
|
||||
"TASeedVR2Gate": TASeedVR2Gate,
|
||||
"TAFluxGuidanceGate": TAFluxGuidanceGate,
|
||||
"TAModelPreset": TAModelPreset,
|
||||
"TACaptioning": TACaptioning,
|
||||
"TACleanupSwitch": TACleanupSwitch,
|
||||
"TAHelpLink": TAHelpLink,
|
||||
"TADiscordLink": TADiscordLink,
|
||||
})
|
||||
|
||||
# Import LM Studio Model Selector Nodes
|
||||
from .ta_lmstudio_model_selector import (
|
||||
NODE_CLASS_MAPPINGS as MODEL_SELECTOR_MAPPINGS,
|
||||
NODE_DISPLAY_NAME_MAPPINGS as MODEL_SELECTOR_DISPLAY
|
||||
)
|
||||
NODE_DISPLAY_NAME_MAPPINGS.update({
|
||||
"TA_LLM_PromptSelector": "🎯 TA LLM Prompt Selector",
|
||||
"TAUnifiedModelSwitcher": "🧠 TA Unified Model Switcher",
|
||||
"TASaveImageOptional": "💾 TA Save Image Optional",
|
||||
"TASaveImageWithPrompt": "📝 TA Save Image With Prompt",
|
||||
"TASageAttentionToggler": "🔧 TA SageAttention Toggler",
|
||||
"TAFilenameGenerator": "📁 TA Filename Generator",
|
||||
"TAPromptController": "🗂️ TA Prompt Controller",
|
||||
"TAPromptHub": "🔀 TA Prompt Hub",
|
||||
"TALoadModelWithName": "📦 TA Load Model (with Name)",
|
||||
"TASamplerPreset": "🎛️ TA Sampler Preset",
|
||||
"TAKSampler": "⚡ TA KSampler",
|
||||
"TALatentPreview": "🖼️ TA Latent Preview",
|
||||
"TASeedVR2Gate": "🚦 TA SeedVR2 Gate",
|
||||
"TAFluxGuidanceGate": "🌊 TA Flux Guidance Gate",
|
||||
"TAModelPreset": "🗂️ TA Model Presets",
|
||||
"TACaptioning": "📷 TA Directory Captioning",
|
||||
"TACleanupSwitch": "🧹 TA Cleanup Switch",
|
||||
"TAHelpLink": "🔗 TA Help Link",
|
||||
"TADiscordLink": "💬 TA Discord Link",
|
||||
})
|
||||
|
||||
# Node class mappings - Base loaders
|
||||
NODE_CLASS_MAPPINGS = {
|
||||
"TALoadCheckpointModelWithName": TALoadCheckpointModelWithName,
|
||||
"TALoadDiffusionModelWithName": TALoadDiffusionModelWithName,
|
||||
"TALoadGGUFModelWithName": TALoadGGUFModelWithName,
|
||||
}
|
||||
WEB_DIRECTORY = "./web/js"
|
||||
|
||||
# Add LM Studio Vision Nodes
|
||||
NODE_CLASS_MAPPINGS.update(LMSTUDIO_VISION_MAPPINGS)
|
||||
|
||||
# Add LM Studio Load On Run Node
|
||||
NODE_CLASS_MAPPINGS.update(LOAD_ON_RUN_MAPPINGS)
|
||||
|
||||
# Add LM Studio Model Selector Nodes
|
||||
NODE_CLASS_MAPPINGS.update(MODEL_SELECTOR_MAPPINGS)
|
||||
|
||||
# Display names for the UI - Base loaders
|
||||
NODE_DISPLAY_NAME_MAPPINGS = {
|
||||
"TALoadCheckpointModelWithName": "TA Load Checkpoint Model (with Name)",
|
||||
"TALoadDiffusionModelWithName": "TA Load Diffusion Model (with Name)",
|
||||
"TALoadGGUFModelWithName": "TA Load GGUF Model (with Name)",
|
||||
}
|
||||
|
||||
# Add LM Studio Vision display names
|
||||
NODE_DISPLAY_NAME_MAPPINGS.update(LMSTUDIO_VISION_DISPLAY)
|
||||
|
||||
# Add LM Studio Load On Run display names
|
||||
NODE_DISPLAY_NAME_MAPPINGS.update(LOAD_ON_RUN_DISPLAY)
|
||||
|
||||
# Add LM Studio Model Selector display names
|
||||
NODE_DISPLAY_NAME_MAPPINGS.update(MODEL_SELECTOR_DISPLAY)
|
||||
|
||||
# Export for ComfyUI
|
||||
__all__ = ['NODE_CLASS_MAPPINGS', 'NODE_DISPLAY_NAME_MAPPINGS']
|
||||
__all__ = ['NODE_CLASS_MAPPINGS', 'NODE_DISPLAY_NAME_MAPPINGS']
|
||||
@@ -0,0 +1,8 @@
|
||||
{
|
||||
"name": "TA-ComfyUI-Nodes-Pack",
|
||||
"author": "tmode-1960",
|
||||
"description": "Some useful nodes for ComfyUI (Model Loader, LM Studio, Ollama and more)",
|
||||
"version": "2.0.0",
|
||||
"repository": "https://github.com/tmode-1960/TA-ComfyUI-Nodes-Pack",
|
||||
"license": "Apache 2.0"
|
||||
}
|
||||
File diff suppressed because one or more lines are too long
Binary file not shown.
|
Before Width: | Height: | Size: 31 KiB |
Binary file not shown.
|
Before Width: | Height: | Size: 20 KiB |
Binary file not shown.
|
Before Width: | Height: | Size: 37 KiB |
Binary file not shown.
|
After Width: | Height: | Size: 1.2 MiB |
@@ -0,0 +1,31 @@
|
||||
[project]
|
||||
name = "TA-ComfyUI-Nodes-Pack"
|
||||
version = "2.0.0"
|
||||
description = "Some useful nodes for ComfyUI (Model Loader, LM Studio, Ollama and more))"
|
||||
readme = "README.md"
|
||||
requires-python = ">=3.8"
|
||||
license = {text = "MIT"}
|
||||
authors = [
|
||||
{name = "tmode-1960", email = "info@thomo.art"}
|
||||
]
|
||||
keywords = ["comfyui", "nodes", "custom-nodes"]
|
||||
|
||||
dependencies = [
|
||||
# Hier können Sie erforderliche Python-Pakete auflisten
|
||||
# z.B. "numpy>=1.20.0",
|
||||
]
|
||||
|
||||
[project.urls]
|
||||
Homepage = "https://github.com/tmode-1960/TA-ComfyUI-Nodes-Pack"
|
||||
Repository = "https://github.com/tmode-1960/TA-ComfyUI-Nodes-Pack"
|
||||
Issues = "https://github.com/tmode-1960/TA-ComfyUI-Nodes-Pack/issues"
|
||||
|
||||
[build-system]
|
||||
requires = ["setuptools>=45", "wheel"]
|
||||
build-backend = "setuptools.build_meta"
|
||||
|
||||
# ComfyUI Registry Konfiguration
|
||||
[tool.comfy]
|
||||
PublisherId = "tmode-1960"
|
||||
DisplayName = "TA ComfyUI Nodes Pack"
|
||||
Icon = "" # Optional: URL zu einem Icon
|
||||
@@ -0,0 +1,158 @@
|
||||
"""
|
||||
================================================================================
|
||||
Node Name : TACleanupSwitch
|
||||
Created : 2026-03-12
|
||||
Modified : 2026-03-12
|
||||
Copyright : © 2026, Thomas Möhrling (thomo.ART)
|
||||
Version : 1.2
|
||||
--------------------------------------------------------------------------------
|
||||
Part of ComfyUI-TA-Nodes-Pack
|
||||
License : Apache 2.0
|
||||
Description:
|
||||
Combined VRAM/RAM cleanup node with an enable toggle.
|
||||
Replaces the three-node chain (Clear Cache All → VRAM-Cleanup → RAM-Cleanup)
|
||||
with a single switchable node. When enabled=False, all cleanup operations
|
||||
are skipped entirely. Passes through any input signal unchanged.
|
||||
|
||||
VRAM cleanup : unload_all_models() + soft_empty_cache() +
|
||||
PromptServer free_memory flag + gc.collect()
|
||||
RAM cleanup : SetSystemFileCacheSize + EmptyWorkingSet (all processes) +
|
||||
SetProcessWorkingSetSize + retry loop with sleep
|
||||
================================================================================
|
||||
"""
|
||||
|
||||
import gc
|
||||
import time
|
||||
import platform
|
||||
import ctypes
|
||||
from ctypes import wintypes
|
||||
import psutil
|
||||
from server import PromptServer
|
||||
import comfy.model_management
|
||||
|
||||
|
||||
class AnyType(str):
|
||||
def __eq__(self, _) -> bool:
|
||||
return True
|
||||
def __ne__(self, __value: object) -> bool:
|
||||
return False
|
||||
|
||||
any_type = AnyType("*")
|
||||
|
||||
|
||||
class TACleanupSwitch:
|
||||
"""
|
||||
Switchable combined VRAM/RAM cleanup node.
|
||||
When enabled=True, runs full VRAM + RAM cleanup identical to LAOGOU nodes.
|
||||
When enabled=False, does nothing at all (no overhead).
|
||||
"""
|
||||
|
||||
CATEGORY = "TA-Nodes"
|
||||
FUNCTION = "execute"
|
||||
OUTPUT_NODE = True
|
||||
RETURN_TYPES = (any_type,)
|
||||
RETURN_NAMES = ("signal",)
|
||||
|
||||
@classmethod
|
||||
def INPUT_TYPES(cls):
|
||||
return {
|
||||
"required": {
|
||||
"enabled": ("BOOLEAN", {"default": True, "label_on": "✅ ON", "label_off": "❌ OFF"}),
|
||||
"offload_model": ("BOOLEAN", {"default": True}),
|
||||
"offload_cache": ("BOOLEAN", {"default": True}),
|
||||
"retry_times": ("INT", {"default": 3, "min": 1, "max": 10, "step": 1}),
|
||||
},
|
||||
"optional": {
|
||||
"signal": (any_type, {}),
|
||||
},
|
||||
}
|
||||
|
||||
@classmethod
|
||||
def IS_CHANGED(cls, **kwargs):
|
||||
return float(time.time())
|
||||
|
||||
def execute(self, enabled, offload_model, offload_cache, retry_times, signal=None):
|
||||
|
||||
if not enabled:
|
||||
return (signal,)
|
||||
|
||||
system = platform.system()
|
||||
|
||||
# ── VRAM Cleanup ──────────────────────────────────────────────────────
|
||||
try:
|
||||
if offload_model:
|
||||
comfy.model_management.unload_all_models()
|
||||
|
||||
if offload_cache:
|
||||
gc.collect()
|
||||
comfy.model_management.soft_empty_cache()
|
||||
PromptServer.instance.prompt_queue.set_flag("free_memory", True)
|
||||
|
||||
print(f"🧹 VRAM cleanup done [offload_model: {offload_model}, offload_cache: {offload_cache}]")
|
||||
|
||||
except Exception as e:
|
||||
print(f"❌ VRAM cleanup failed: {str(e)}")
|
||||
|
||||
# ── RAM Cleanup ───────────────────────────────────────────────────────
|
||||
try:
|
||||
mem_before = psutil.virtual_memory()
|
||||
before_pct = mem_before.percent
|
||||
before_avail_mb = mem_before.available / (1024 * 1024)
|
||||
|
||||
for _ in range(retry_times):
|
||||
|
||||
# 1) File cache
|
||||
try:
|
||||
if system == "Windows":
|
||||
ctypes.windll.kernel32.SetSystemFileCacheSize(-1, -1, 0)
|
||||
elif system == "Linux":
|
||||
libc = ctypes.CDLL("libc.so.6")
|
||||
libc.malloc_trim(0)
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
# 2) EmptyWorkingSet on all processes
|
||||
if system == "Windows":
|
||||
for proc in psutil.process_iter(['pid']):
|
||||
try:
|
||||
handle = ctypes.windll.kernel32.OpenProcess(
|
||||
wintypes.DWORD(0x001F0FFF),
|
||||
wintypes.BOOL(False),
|
||||
wintypes.DWORD(proc.info['pid'])
|
||||
)
|
||||
ctypes.windll.psapi.EmptyWorkingSet(handle)
|
||||
ctypes.windll.kernel32.CloseHandle(handle)
|
||||
except Exception:
|
||||
continue
|
||||
|
||||
# 3) Working set trim
|
||||
try:
|
||||
if system == "Windows":
|
||||
ctypes.windll.kernel32.SetProcessWorkingSetSize(-1, -1, -1)
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
time.sleep(1)
|
||||
|
||||
mem_after = psutil.virtual_memory()
|
||||
after_pct = mem_after.percent
|
||||
after_avail_mb = mem_after.available / (1024 * 1024)
|
||||
freed_mb = after_avail_mb - before_avail_mb
|
||||
print(f"🧹 RAM cleanup done [{before_pct:.1f}% → {after_pct:.1f}%, freed: {freed_mb:.0f} MB]")
|
||||
|
||||
except Exception as e:
|
||||
print(f"❌ RAM cleanup failed: {str(e)}")
|
||||
|
||||
return (signal,)
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Node registration
|
||||
# ---------------------------------------------------------------------------
|
||||
NODE_CLASS_MAPPINGS = {
|
||||
"TACleanupSwitch": TACleanupSwitch,
|
||||
}
|
||||
|
||||
NODE_DISPLAY_NAME_MAPPINGS = {
|
||||
"TACleanupSwitch": "🧹 TA Cleanup Switch",
|
||||
}
|
||||
@@ -0,0 +1,445 @@
|
||||
"""
|
||||
================================================================================
|
||||
Node Name : TA Directory Captioning
|
||||
Created : 2025
|
||||
Modified : 2026-03-11
|
||||
Copyright : © 2026, Thomas Möhrling (thomo.ART)
|
||||
Version : 2.0
|
||||
--------------------------------------------------------------------------------
|
||||
Part of ComfyUI-TA-Nodes-Pack
|
||||
License : Apache 2.0
|
||||
|
||||
Description:
|
||||
Iterates through a directory, sends images to LM Studio or Ollama Vision
|
||||
Models and saves the generated captions as .txt files alongside each image.
|
||||
Uses TASmartLLM model detection logic (LMStudio + Ollama, Vision tagging).
|
||||
================================================================================
|
||||
"""
|
||||
|
||||
import os
|
||||
import base64
|
||||
import requests
|
||||
import time
|
||||
from PIL import Image, ImageOps
|
||||
from io import BytesIO
|
||||
|
||||
# Import TASmartLLM for model list, vision detection and tag logic.
|
||||
# Falls back to a minimal inline implementation if ta_smart_llm is not available.
|
||||
try:
|
||||
from .ta_smart_llm import TASmartLLM, is_vision_model, tag_model, strip_vision_tag
|
||||
_SMART_LLM_AVAILABLE = True
|
||||
except ImportError:
|
||||
print("[TA-Captioning] WARN: ta_smart_llm not found. Using fallback model list.")
|
||||
_SMART_LLM_AVAILABLE = False
|
||||
|
||||
VISION_KEYWORDS = ["llava", "vision", "-vl-", "_vl_", "vl-", "vl_",
|
||||
"moondream", "minicpm-v", "internvl", "qwen-vl"]
|
||||
VISION_MANUAL = set()
|
||||
|
||||
def is_vision_model(model_id: str) -> bool:
|
||||
lower = model_id.lower()
|
||||
return any(kw in lower for kw in VISION_KEYWORDS) or lower in VISION_MANUAL
|
||||
|
||||
def tag_model(full_name: str) -> str:
|
||||
model_id = '/'.join(full_name.split('/')[1:])
|
||||
if is_vision_model(model_id):
|
||||
return f"{full_name} [Vision]"
|
||||
return full_name
|
||||
|
||||
def strip_vision_tag(model: str) -> str:
|
||||
return model.replace(" [Vision]", "")
|
||||
|
||||
class TASmartLLM:
|
||||
@classmethod
|
||||
def get_models(cls):
|
||||
models = []
|
||||
try:
|
||||
r = requests.get("http://127.0.0.1:1234/v1/models", timeout=2)
|
||||
if r.status_code == 200:
|
||||
for m in r.json()['data']:
|
||||
models.append(tag_model(f"LMStudio/{m['id']}"))
|
||||
except:
|
||||
pass
|
||||
try:
|
||||
r = requests.get("http://127.0.0.1:11434/api/tags", timeout=2)
|
||||
if r.status_code == 200:
|
||||
for m in r.json()['models']:
|
||||
models.append(tag_model(f"Ollama/{m['name']}"))
|
||||
except:
|
||||
pass
|
||||
return models if models else ["No Backend"]
|
||||
|
||||
|
||||
# --- Helper function: normalize image and encode to Base64 ---
|
||||
|
||||
def encode_image_from_path(image_path: str, max_size: int = 1024) -> str:
|
||||
"""
|
||||
Converts an image file to a Base64-encoded PNG string suitable for API submission.
|
||||
|
||||
Normalization steps applied:
|
||||
- EXIF rotation correction (prevents incorrectly oriented images)
|
||||
- Color space conversion to RGB (removes RGBA channels and palette modes)
|
||||
- Resolution scaling to max_size px on the longest side (prevents HTTP 400 on large images)
|
||||
- Metadata stripping (clean PNG without embedded ComfyUI workflow chunks)
|
||||
|
||||
Args:
|
||||
image_path (str): Absolute path to the source image file.
|
||||
max_size (int): Maximum pixel size for the longest side. Defaults to 1024.
|
||||
|
||||
Returns:
|
||||
str: Base64-encoded PNG string, or None if encoding failed.
|
||||
"""
|
||||
try:
|
||||
with open(image_path, "rb") as f:
|
||||
img_bytes = f.read()
|
||||
|
||||
pil_image = Image.open(BytesIO(img_bytes))
|
||||
pil_image = ImageOps.exif_transpose(pil_image)
|
||||
pil_image = pil_image.convert("RGB")
|
||||
pil_image.thumbnail((max_size, max_size), Image.LANCZOS)
|
||||
|
||||
buffer = BytesIO()
|
||||
pil_image.save(buffer, format="PNG", optimize=False)
|
||||
|
||||
return base64.b64encode(buffer.getvalue()).decode('utf-8')
|
||||
|
||||
except Exception as e:
|
||||
print(f"[TA-Captioning] Error encoding {image_path}: {e}")
|
||||
return None
|
||||
|
||||
|
||||
# --- Custom Node Class ---
|
||||
|
||||
class TACaptioning:
|
||||
"""
|
||||
ComfyUI node that batch-captions all images in a given directory using a
|
||||
vision-capable LLM served by LM Studio or Ollama.
|
||||
|
||||
For each image file (.png / .jpg / .jpeg / .webp) found in the target
|
||||
directory, the node:
|
||||
1. Encodes the image as a Base64 PNG (with normalization).
|
||||
2. Sends it together with the user-defined prompt to the selected model.
|
||||
3. Writes the generated caption text to a .txt file with the same base name.
|
||||
|
||||
Existing caption files are skipped unless overwrite_existing is enabled.
|
||||
A summary status string is returned and printed to the console after the run.
|
||||
"""
|
||||
|
||||
@classmethod
|
||||
def INPUT_TYPES(cls):
|
||||
"""
|
||||
Defines all input widgets shown in the ComfyUI node UI.
|
||||
|
||||
Fetches the current model list from TASmartLLM (queries LM Studio and
|
||||
Ollama at node load time) and pre-selects the first vision-tagged model
|
||||
as the default.
|
||||
|
||||
Returns:
|
||||
dict: ComfyUI INPUT_TYPES dictionary with all required inputs.
|
||||
"""
|
||||
models = TASmartLLM.get_models()
|
||||
|
||||
vision_models = [m for m in models if "[Vision]" in m]
|
||||
default_model = vision_models[0] if vision_models else (models[0] if models else "No Backend")
|
||||
|
||||
return {
|
||||
"required": {
|
||||
"directory_path": ("STRING", {
|
||||
"default": "C:/Images/to_caption",
|
||||
"multiline": False
|
||||
}),
|
||||
"model": (models, {
|
||||
"default": default_model
|
||||
}),
|
||||
"server_url": ("STRING", {
|
||||
"default": "http://127.0.0.1:1234",
|
||||
"multiline": False,
|
||||
"tooltip": "LMStudio: http://127.0.0.1:1234 | Ollama: http://127.0.0.1:11434"
|
||||
}),
|
||||
"prompt": ("STRING", {
|
||||
"default": (
|
||||
"Describe this image in one continuous sentence or short paragraph. "
|
||||
"No labels, no bullet points, no line breaks. "
|
||||
"Focus on: subject, style, colors, lighting, composition, background. "
|
||||
"No filler phrases, no interpretation. Respond in English."
|
||||
),
|
||||
"multiline": True
|
||||
}),
|
||||
"system_prompt": ("STRING", {
|
||||
"default": "You are a precise image captioning assistant for AI training datasets. Describe only what is visible. Be factual, concise, and always respond in English.",
|
||||
"multiline": True
|
||||
}),
|
||||
"temperature": ("FLOAT", {
|
||||
"default": 0.2, "min": 0.0, "max": 2.0, "step": 0.1
|
||||
}),
|
||||
"max_tokens": ("INT", {
|
||||
"default": 150, "min": 1, "max": 131072
|
||||
}),
|
||||
"max_image_size": ("INT", {
|
||||
"default": 1024, "min": 256, "max": 4096, "step": 128,
|
||||
"tooltip": "Longest side in pixels. Larger images are downscaled (prevents HTTP 400)."
|
||||
}),
|
||||
"overwrite_existing": ("BOOLEAN", {
|
||||
"default": False,
|
||||
"label_on": "Overwrite",
|
||||
"label_off": "Skip existing"
|
||||
}),
|
||||
}
|
||||
}
|
||||
|
||||
RETURN_TYPES = ("STRING",)
|
||||
RETURN_NAMES = ("status",)
|
||||
FUNCTION = "caption_directory"
|
||||
CATEGORY = "TA-Nodes/LMStudio"
|
||||
|
||||
@classmethod
|
||||
def IS_CHANGED(cls, *args, **kwargs):
|
||||
"""Forces re-execution on every queue run by returning the current timestamp."""
|
||||
return time.time()
|
||||
|
||||
# ------------------------------------------------------------------ #
|
||||
# Backend request dispatch #
|
||||
# ------------------------------------------------------------------ #
|
||||
|
||||
def _send_request(self, server_url, backend, model_name, prompt, system_prompt,
|
||||
image_base64, temperature, max_tokens) -> str:
|
||||
"""
|
||||
Dispatches the captioning request to the appropriate backend handler.
|
||||
|
||||
Detects the backend from the model prefix ('LMStudio' or 'Ollama') and
|
||||
routes to the matching private method.
|
||||
|
||||
Args:
|
||||
server_url (str): Base URL of the inference server.
|
||||
backend (str): Backend identifier, e.g. 'LMStudio' or 'Ollama'.
|
||||
model_name (str): Model identifier without the backend prefix.
|
||||
prompt (str): User prompt sent with the image.
|
||||
system_prompt (str): System-level instruction for the model.
|
||||
image_base64 (str): Base64-encoded PNG image string.
|
||||
temperature (float): Sampling temperature for generation.
|
||||
max_tokens (int): Maximum number of tokens to generate.
|
||||
|
||||
Returns:
|
||||
str: Generated caption text from the model.
|
||||
"""
|
||||
if "LMStudio" in backend:
|
||||
return self._send_lmstudio_request(
|
||||
server_url, model_name, prompt, system_prompt,
|
||||
image_base64, temperature, max_tokens
|
||||
)
|
||||
else:
|
||||
return self._send_ollama_request(
|
||||
server_url, model_name, prompt, system_prompt, image_base64
|
||||
)
|
||||
|
||||
def _send_lmstudio_request(self, server_url, model_name, prompt, system_prompt,
|
||||
image_base64, temperature, max_tokens) -> str:
|
||||
"""
|
||||
Sends a vision chat completion request to an LM Studio server.
|
||||
|
||||
Uses the OpenAI-compatible /v1/chat/completions endpoint. The image is
|
||||
passed as a base64 data URI inside the user message content array.
|
||||
|
||||
Args:
|
||||
server_url (str): Base URL of the LM Studio server.
|
||||
model_name (str): Model identifier as returned by the LM Studio API.
|
||||
prompt (str): User prompt text.
|
||||
system_prompt (str): System message for the chat.
|
||||
image_base64 (str): Base64-encoded PNG image string.
|
||||
temperature (float): Sampling temperature.
|
||||
max_tokens (int): Maximum tokens to generate.
|
||||
|
||||
Returns:
|
||||
str: Stripped caption text from the model response.
|
||||
|
||||
Raises:
|
||||
Exception: On connection errors or non-2xx HTTP responses.
|
||||
"""
|
||||
url = f"{server_url}/v1/chat/completions"
|
||||
payload = {
|
||||
"model": model_name,
|
||||
"messages": [
|
||||
{"role": "system", "content": system_prompt},
|
||||
{"role": "user", "content": [
|
||||
{"type": "text", "text": prompt},
|
||||
{"type": "image_url", "image_url": {"url": f"data:image/png;base64,{image_base64}"}}
|
||||
]}
|
||||
],
|
||||
"temperature": temperature,
|
||||
"max_tokens": max_tokens,
|
||||
"stream": False
|
||||
}
|
||||
try:
|
||||
r = requests.post(url, json=payload, timeout=1200)
|
||||
r.raise_for_status()
|
||||
return r.json()['choices'][0]['message']['content'].strip()
|
||||
except requests.exceptions.ConnectionError:
|
||||
raise Exception("Connection Error: LM Studio server not reachable.")
|
||||
except requests.exceptions.HTTPError as e:
|
||||
raise Exception(f"LMStudio API HTTP Error {e.response.status_code}: {e.response.text}")
|
||||
except Exception as e:
|
||||
raise Exception(f"LMStudio request failed: {str(e)}")
|
||||
|
||||
def _send_ollama_request(self, server_url, model_name, prompt, system_prompt,
|
||||
image_base64) -> str:
|
||||
"""
|
||||
Sends a vision generation request to an Ollama server.
|
||||
|
||||
Uses the Ollama /api/generate endpoint. System prompt and user prompt are
|
||||
concatenated as a single prompt string; the image is passed in the
|
||||
'images' field as a Base64 string.
|
||||
|
||||
Args:
|
||||
server_url (str): Base URL of the Ollama server.
|
||||
model_name (str): Model name as listed by Ollama.
|
||||
prompt (str): User prompt text.
|
||||
system_prompt (str): Prepended to the prompt as instructions.
|
||||
image_base64 (str): Base64-encoded PNG image string.
|
||||
|
||||
Returns:
|
||||
str: Stripped caption text from the model response.
|
||||
|
||||
Raises:
|
||||
Exception: On connection errors or non-2xx HTTP responses.
|
||||
"""
|
||||
url = f"{server_url}/api/generate"
|
||||
payload = {
|
||||
"model": model_name,
|
||||
"prompt": f"{system_prompt}\n\n{prompt}".strip(),
|
||||
"images": [image_base64],
|
||||
"stream": False
|
||||
}
|
||||
try:
|
||||
r = requests.post(url, json=payload, timeout=1200)
|
||||
r.raise_for_status()
|
||||
return r.json()['response'].strip()
|
||||
except requests.exceptions.ConnectionError:
|
||||
raise Exception("Connection Error: Ollama server not reachable.")
|
||||
except requests.exceptions.HTTPError as e:
|
||||
raise Exception(f"Ollama API HTTP Error {e.response.status_code}: {e.response.text}")
|
||||
except Exception as e:
|
||||
raise Exception(f"Ollama request failed: {str(e)}")
|
||||
|
||||
# ------------------------------------------------------------------ #
|
||||
# Main execution function #
|
||||
# ------------------------------------------------------------------ #
|
||||
|
||||
def caption_directory(self, directory_path, model, server_url, prompt, system_prompt,
|
||||
temperature, max_tokens, max_image_size, overwrite_existing):
|
||||
"""
|
||||
Main node execution function. Iterates all images in the target directory
|
||||
and generates a caption .txt file for each one.
|
||||
|
||||
Workflow per image:
|
||||
1. Check if a caption file already exists (skip if overwrite_existing is False).
|
||||
2. Encode the image to a normalized Base64 PNG via encode_image_from_path().
|
||||
3. Send the encoded image and prompts to the selected backend.
|
||||
4. Write the returned caption to a .txt file with the same base name.
|
||||
|
||||
The model string is parsed to extract the backend prefix ('LMStudio' or
|
||||
'Ollama') and the actual model name. If Ollama is detected but the provided
|
||||
server_url does not contain port 11434, the URL is automatically corrected.
|
||||
|
||||
Args:
|
||||
directory_path (str): Absolute path to the directory containing images.
|
||||
model (str): Selected model string including backend prefix and
|
||||
optional [Vision] tag, e.g. 'LMStudio/model-id [Vision]'.
|
||||
server_url (str): Base URL of the inference server.
|
||||
prompt (str): User prompt for the vision model.
|
||||
system_prompt (str): System-level instruction for the model.
|
||||
temperature (float): Sampling temperature for generation.
|
||||
max_tokens (int): Maximum number of tokens to generate per caption.
|
||||
max_image_size (int): Maximum pixel size for the longest image dimension.
|
||||
overwrite_existing (bool): If False, skips images that already have a .txt file.
|
||||
|
||||
Returns:
|
||||
tuple[str]: Single-element tuple with a summary status string, e.g.:
|
||||
"Done. 12 captions created, 3 skipped, 0 errors. (Total images: 15)"
|
||||
"""
|
||||
clean_model = strip_vision_tag(model)
|
||||
parts = clean_model.split('/', 1)
|
||||
backend = parts[0]
|
||||
model_name = parts[1] if len(parts) > 1 else clean_model
|
||||
|
||||
if "Ollama" in backend and "11434" not in server_url:
|
||||
effective_url = "http://127.0.0.1:11434"
|
||||
print(f"[TA-Captioning] Ollama detected – using {effective_url} instead of {server_url}")
|
||||
else:
|
||||
effective_url = server_url.rstrip("/")
|
||||
|
||||
if not os.path.isdir(directory_path):
|
||||
return (f"ERROR: Directory not found: {directory_path}",)
|
||||
|
||||
image_files = [
|
||||
f for f in os.listdir(directory_path)
|
||||
if f.lower().endswith(('.png', '.jpg', '.jpeg', '.webp'))
|
||||
]
|
||||
|
||||
if not image_files:
|
||||
return (f"NO IMAGES found in: {directory_path}",)
|
||||
|
||||
print(f"\n{'='*60}")
|
||||
print(f"[TA-Captioning] Starting captioning for {len(image_files)} images...")
|
||||
print(f"[TA-Captioning] Backend : {backend}")
|
||||
print(f"[TA-Captioning] Model : {model_name}")
|
||||
print(f"[TA-Captioning] Server : {effective_url}")
|
||||
print(f"[TA-Captioning] Max img size : {max_image_size}px")
|
||||
print(f"[TA-Captioning] Temperature : {temperature}")
|
||||
print(f"[TA-Captioning] Max tokens : {max_tokens}")
|
||||
print(f"[TA-Captioning] Overwrite : {overwrite_existing}")
|
||||
print(f"{'='*60}\n")
|
||||
|
||||
captioned_count = 0
|
||||
skipped_count = 0
|
||||
error_count = 0
|
||||
|
||||
for filename in image_files:
|
||||
image_path = os.path.join(directory_path, filename)
|
||||
base_name = os.path.splitext(filename)[0]
|
||||
caption_path = os.path.join(directory_path, base_name + ".txt")
|
||||
|
||||
if not overwrite_existing and os.path.exists(caption_path):
|
||||
print(f"ℹ️ '{filename}' already captioned – skipping.")
|
||||
skipped_count += 1
|
||||
continue
|
||||
|
||||
print(f"⏳ Processing: {filename}...")
|
||||
|
||||
image_base64 = encode_image_from_path(image_path, max_size=max_image_size)
|
||||
if not image_base64:
|
||||
print(f"❌ Could not encode '{filename}' – skipping.")
|
||||
error_count += 1
|
||||
continue
|
||||
|
||||
try:
|
||||
caption = self._send_request(
|
||||
effective_url, backend, model_name,
|
||||
prompt, system_prompt,
|
||||
image_base64, temperature, max_tokens
|
||||
)
|
||||
|
||||
with open(caption_path, "w", encoding="utf-8") as f:
|
||||
f.write(caption)
|
||||
|
||||
print(f"✅ Saved caption for '{filename}'.")
|
||||
captioned_count += 1
|
||||
|
||||
except Exception as e:
|
||||
print(f"❌ Error processing '{filename}': {e}")
|
||||
error_count += 1
|
||||
|
||||
status_msg = (
|
||||
f"Done. {captioned_count} captions created, "
|
||||
f"{skipped_count} skipped, {error_count} errors. "
|
||||
f"(Total images: {len(image_files)})"
|
||||
)
|
||||
print(f"\n[TA-Captioning] {status_msg}\n")
|
||||
return (status_msg,)
|
||||
|
||||
|
||||
# ------------------------------------------------------------------ #
|
||||
# ComfyUI node registration #
|
||||
# ------------------------------------------------------------------ #
|
||||
|
||||
NODE_CLASS_MAPPINGS = {"TACaptioning": TACaptioning}
|
||||
NODE_DISPLAY_NAME_MAPPINGS = {"TACaptioning": "TA Directory Captioning"}
|
||||
@@ -0,0 +1,4 @@
|
||||
{
|
||||
"discord_url": "https://discord.gg/f7S3zjGWbW",
|
||||
"label": "Join Bocodemy on Discord"
|
||||
}
|
||||
@@ -0,0 +1,185 @@
|
||||
"""
|
||||
================================================================================
|
||||
Node Name : TA Discord Link
|
||||
Created : 2026-03-13
|
||||
Modified : 2026-03-13
|
||||
Copyright : © 2026, Thomas Möhrling (thomo.ART)
|
||||
Version : 2.0
|
||||
--------------------------------------------------------------------------------
|
||||
Part of ComfyUI-TA-Nodes-Pack
|
||||
License : Apache 2.0
|
||||
|
||||
Description:
|
||||
A purely informational node that displays a clickable Discord invite link
|
||||
directly inside the ComfyUI graph. No inputs, no outputs.
|
||||
|
||||
The invite URL is stored in ta_discord_link.json and can be edited via
|
||||
the browser-based editor at:
|
||||
http://localhost:8188/ta_discord_link/ui
|
||||
|
||||
The matching JS widget extension reads the URL from
|
||||
GET /ta_discord_link/config and renders a styled Discord button.
|
||||
================================================================================
|
||||
"""
|
||||
|
||||
import os
|
||||
import json
|
||||
from aiohttp import web
|
||||
from server import PromptServer
|
||||
|
||||
# ──────────────────────────────────────────────
|
||||
# Paths
|
||||
# ──────────────────────────────────────────────
|
||||
_THIS_DIR = os.path.dirname(os.path.abspath(__file__))
|
||||
_CFG_FILE = os.path.join(_THIS_DIR, "ta_discord_link.json")
|
||||
_HTML_PATH = os.path.join(_THIS_DIR, "web", "js", "ta_discord_link_ui.html")
|
||||
|
||||
_DEFAULT_CFG = {
|
||||
"discord_url": "https://discord.gg/YOUR_INVITE_CODE",
|
||||
"label": "Join us on Discord",
|
||||
}
|
||||
|
||||
|
||||
# ──────────────────────────────────────────────
|
||||
# Config helpers
|
||||
# ──────────────────────────────────────────────
|
||||
def _load_cfg() -> dict:
|
||||
"""
|
||||
Loads ta_discord_link.json and returns its contents.
|
||||
|
||||
Creates the file with defaults if it does not exist. Returns _DEFAULT_CFG
|
||||
on any read or parse error without modifying the file.
|
||||
|
||||
Returns:
|
||||
dict: Config dict with 'discord_url' and 'label' keys.
|
||||
"""
|
||||
if not os.path.exists(_CFG_FILE):
|
||||
try:
|
||||
with open(_CFG_FILE, "w", encoding="utf-8") as f:
|
||||
json.dump(_DEFAULT_CFG, f, indent=2, ensure_ascii=False)
|
||||
print("[TADiscordLink] ta_discord_link.json created with defaults.")
|
||||
except Exception as e:
|
||||
print(f"[TADiscordLink] Could not create config file: {e}")
|
||||
return dict(_DEFAULT_CFG)
|
||||
|
||||
try:
|
||||
with open(_CFG_FILE, "r", encoding="utf-8") as f:
|
||||
data = json.load(f)
|
||||
if isinstance(data, dict):
|
||||
return {**_DEFAULT_CFG, **data} # fill missing keys with defaults
|
||||
return dict(_DEFAULT_CFG)
|
||||
except Exception as e:
|
||||
print(f"[TADiscordLink] Error reading config: {e}")
|
||||
return dict(_DEFAULT_CFG)
|
||||
|
||||
|
||||
def _save_cfg(cfg: dict) -> None:
|
||||
"""
|
||||
Persists the given config dict to ta_discord_link.json.
|
||||
|
||||
Args:
|
||||
cfg (dict): Config dict to write.
|
||||
"""
|
||||
with open(_CFG_FILE, "w", encoding="utf-8") as f:
|
||||
json.dump(cfg, f, indent=2, ensure_ascii=False)
|
||||
|
||||
|
||||
# ──────────────────────────────────────────────
|
||||
# Web Endpoints
|
||||
# ──────────────────────────────────────────────
|
||||
@PromptServer.instance.routes.get("/ta_discord_link/ui")
|
||||
async def ta_discord_link_ui(request):
|
||||
"""
|
||||
Serves the browser-based Discord link editor HTML page.
|
||||
|
||||
Route: GET /ta_discord_link/ui
|
||||
|
||||
Returns:
|
||||
web.Response: HTML page, or 404 if the HTML file is missing.
|
||||
"""
|
||||
if not os.path.exists(_HTML_PATH):
|
||||
return web.Response(text="HTML editor file not found.", status=404)
|
||||
with open(_HTML_PATH, "r", encoding="utf-8") as f:
|
||||
return web.Response(text=f.read(), content_type="text/html")
|
||||
|
||||
|
||||
@PromptServer.instance.routes.get("/ta_discord_link/config")
|
||||
async def ta_discord_link_config(request):
|
||||
"""
|
||||
Returns the current Discord link config as JSON.
|
||||
|
||||
Route: GET /ta_discord_link/config
|
||||
|
||||
Returns:
|
||||
web.Response: JSON response with 'discord_url' and 'label'.
|
||||
"""
|
||||
return web.json_response(_load_cfg())
|
||||
|
||||
|
||||
@PromptServer.instance.routes.post("/ta_discord_link/save")
|
||||
async def ta_discord_link_save(request):
|
||||
"""
|
||||
Accepts a JSON body with 'discord_url' (required) and 'label' (optional)
|
||||
and persists them to ta_discord_link.json.
|
||||
|
||||
Route: POST /ta_discord_link/save
|
||||
Body: {'discord_url': str, 'label': str}
|
||||
|
||||
Returns:
|
||||
web.Response: JSON {'ok': True} on success or {'ok': False, 'error': str}.
|
||||
"""
|
||||
try:
|
||||
body = await request.json()
|
||||
url = body.get("discord_url", "").strip()
|
||||
if not url:
|
||||
return web.json_response({"ok": False, "error": "discord_url must not be empty."})
|
||||
cfg = {
|
||||
"discord_url": url,
|
||||
"label": body.get("label", _DEFAULT_CFG["label"]).strip() or _DEFAULT_CFG["label"],
|
||||
}
|
||||
_save_cfg(cfg)
|
||||
print(f"[TADiscordLink] Config saved: {url}")
|
||||
return web.json_response({"ok": True})
|
||||
except Exception as e:
|
||||
return web.json_response({"ok": False, "error": str(e)})
|
||||
|
||||
|
||||
# ──────────────────────────────────────────────
|
||||
# Node
|
||||
# ──────────────────────────────────────────────
|
||||
class TADiscordLink:
|
||||
"""
|
||||
Renders a clickable Discord invite link inside the ComfyUI node graph.
|
||||
|
||||
This node has no functional inputs or outputs. The invite URL and button
|
||||
label are stored in ta_discord_link.json and can be changed via the
|
||||
browser editor at http://localhost:8188/ta_discord_link/ui.
|
||||
The JS widget fetches the current config via GET /ta_discord_link/config
|
||||
and renders a styled Discord button directly in the graph.
|
||||
"""
|
||||
|
||||
CATEGORY = "thomo.ART/utils"
|
||||
FUNCTION = "run"
|
||||
OUTPUT_NODE = True
|
||||
|
||||
@classmethod
|
||||
def INPUT_TYPES(cls):
|
||||
return {"required": {}}
|
||||
|
||||
RETURN_TYPES = ()
|
||||
|
||||
def run(self):
|
||||
"""No-op execution — all rendering is handled on the JS side."""
|
||||
return {}
|
||||
|
||||
|
||||
# ──────────────────────────────────────────────
|
||||
# Registration
|
||||
# ──────────────────────────────────────────────
|
||||
NODE_CLASS_MAPPINGS = {
|
||||
"TADiscordLink": TADiscordLink,
|
||||
}
|
||||
|
||||
NODE_DISPLAY_NAME_MAPPINGS = {
|
||||
"TADiscordLink": "TA Discord Link",
|
||||
}
|
||||
@@ -1,327 +0,0 @@
|
||||
"""
|
||||
TA-EBU-LMStudio Vision Node for Image-to-Prompt
|
||||
Part of ComfyUI-TA-Nodes-Pack
|
||||
Extends LM Studio with Vision Language Model Support for Image-to-Prompt
|
||||
"""
|
||||
|
||||
import torch
|
||||
import numpy as np
|
||||
from PIL import Image
|
||||
import io
|
||||
import base64
|
||||
import requests
|
||||
import time
|
||||
import sys
|
||||
|
||||
|
||||
class TAEbuLMStudioVisionRequest:
|
||||
"""
|
||||
TA Node for Image-to-Prompt with LM Studio Vision Language Models
|
||||
Uses VLMs like LLaVA, Qwen2-VL, Pixtral for image descriptions
|
||||
"""
|
||||
|
||||
@classmethod
|
||||
def INPUT_TYPES(cls):
|
||||
return {
|
||||
"required": {
|
||||
"image": ("IMAGE",),
|
||||
"prompt": ("STRING", {
|
||||
"default": "Describe this image in detail.",
|
||||
"multiline": True
|
||||
}),
|
||||
"model_name": ("STRING", {
|
||||
"default": "llava-v1.5",
|
||||
"multiline": False
|
||||
}),
|
||||
"temperature": ("FLOAT", {
|
||||
"default": 0.7,
|
||||
"min": 0.0,
|
||||
"max": 2.0,
|
||||
"step": 0.1
|
||||
}),
|
||||
"max_tokens": ("INT", {
|
||||
"default": 500,
|
||||
"min": 1,
|
||||
"max": 4096
|
||||
}),
|
||||
"server_url": ("STRING", {
|
||||
"default": "http://localhost:1234",
|
||||
"multiline": False
|
||||
}),
|
||||
},
|
||||
"optional": {
|
||||
"system_prompt": ("STRING", {
|
||||
"default": "You are a helpful AI assistant that describes images accurately.",
|
||||
"multiline": True
|
||||
}),
|
||||
}
|
||||
}
|
||||
|
||||
RETURN_TYPES = ("STRING",)
|
||||
RETURN_NAMES = ("generated_prompt",)
|
||||
FUNCTION = "generate_prompt"
|
||||
CATEGORY = "TA-Nodes/LMStudio"
|
||||
|
||||
def tensor_to_base64(self, image_tensor):
|
||||
"""
|
||||
Converts ComfyUI Image Tensor to Base64 String
|
||||
ComfyUI Format: [batch, height, width, channels] with values 0-1
|
||||
"""
|
||||
# Take the first image from the batch
|
||||
if len(image_tensor.shape) == 4:
|
||||
image_tensor = image_tensor[0]
|
||||
|
||||
# Convert from [H, W, C] to numpy array
|
||||
image_np = image_tensor.cpu().numpy()
|
||||
|
||||
# Convert from 0-1 to 0-255
|
||||
image_np = (image_np * 255).astype(np.uint8)
|
||||
|
||||
# Create PIL Image
|
||||
pil_image = Image.fromarray(image_np)
|
||||
|
||||
# Convert to Base64
|
||||
buffer = io.BytesIO()
|
||||
pil_image.save(buffer, format="PNG")
|
||||
img_base64 = base64.b64encode(buffer.getvalue()).decode('utf-8')
|
||||
|
||||
return img_base64
|
||||
|
||||
def generate_prompt(self, image, prompt, model_name, temperature, max_tokens,
|
||||
server_url, system_prompt=None):
|
||||
"""
|
||||
Sends image and prompt to LM Studio Vision Model
|
||||
Uses OpenAI-compatible API with Base64-encoded images
|
||||
"""
|
||||
try:
|
||||
start_time = time.time()
|
||||
|
||||
print(f"[TA-Vision] Converting image to base64...")
|
||||
image_base64 = self.tensor_to_base64(image)
|
||||
|
||||
# Build the API request in OpenAI-compatible format
|
||||
url = f"{server_url}/v1/chat/completions"
|
||||
|
||||
messages = []
|
||||
|
||||
# Optional: Add system prompt
|
||||
if system_prompt:
|
||||
messages.append({
|
||||
"role": "system",
|
||||
"content": system_prompt
|
||||
})
|
||||
|
||||
# User message with image
|
||||
# Format: OpenAI-compatible with base64 image_url
|
||||
messages.append({
|
||||
"role": "user",
|
||||
"content": [
|
||||
{
|
||||
"type": "text",
|
||||
"text": prompt
|
||||
},
|
||||
{
|
||||
"type": "image_url",
|
||||
"image_url": {
|
||||
"url": f"data:image/png;base64,{image_base64}"
|
||||
}
|
||||
}
|
||||
]
|
||||
})
|
||||
|
||||
payload = {
|
||||
"model": model_name,
|
||||
"messages": messages,
|
||||
"temperature": temperature,
|
||||
"max_tokens": max_tokens,
|
||||
"stream": False
|
||||
}
|
||||
|
||||
print(f"[TA-Vision] Sending request to LM Studio ({model_name})...")
|
||||
print(f"[TA-Vision] Prompt: {prompt}")
|
||||
|
||||
# Send request
|
||||
response = requests.post(url, json=payload, timeout=120)
|
||||
|
||||
if response.status_code == 200:
|
||||
result = response.json()
|
||||
generated_text = result['choices'][0]['message']['content']
|
||||
|
||||
end_time = time.time()
|
||||
elapsed_time = end_time - start_time
|
||||
|
||||
print(f"\n{'='*60}")
|
||||
print(f"[TA-Vision] Generated Prompt:")
|
||||
print(f"{generated_text}")
|
||||
print(f"{'='*60}")
|
||||
print(f"[TA-Vision] Generation time: {elapsed_time:.2f} seconds\n")
|
||||
|
||||
return (generated_text,)
|
||||
else:
|
||||
error_message = f"Error {response.status_code}: {response.text}"
|
||||
print(f"[TA-Vision] {error_message}", file=sys.stderr)
|
||||
|
||||
# Helpful error messages
|
||||
if response.status_code == 404:
|
||||
error_message += "\n\n[TA-Vision] HINT: Is the Vision model loaded in LM Studio?"
|
||||
elif "does not support images" in response.text:
|
||||
error_message += "\n\n[TA-Vision] HINT: The loaded model does not support images. Please load a Vision model (e.g. llava-v1.5, qwen2-vl, pixtral)."
|
||||
|
||||
return (error_message,)
|
||||
|
||||
except requests.exceptions.ConnectionError:
|
||||
error_message = "[TA-Vision] Connection Error: LM Studio Server not reachable. Is LM Studio running and the server active?"
|
||||
print(error_message, file=sys.stderr)
|
||||
return (error_message,)
|
||||
except Exception as e:
|
||||
error_message = f"[TA-Vision] Error: {str(e)}"
|
||||
print(error_message, file=sys.stderr)
|
||||
return (error_message,)
|
||||
|
||||
|
||||
class TAEbuLMStudioLoadModel:
|
||||
"""
|
||||
TA Node for loading LM Studio models via CLI
|
||||
Compatible with text and vision models
|
||||
"""
|
||||
|
||||
@classmethod
|
||||
def INPUT_TYPES(cls):
|
||||
return {
|
||||
"required": {
|
||||
"model_search_string": ("STRING", {
|
||||
"default": "llava",
|
||||
"multiline": False
|
||||
}),
|
||||
"context_length": ("INT", {
|
||||
"default": 8192,
|
||||
"min": 512,
|
||||
"max": 131072
|
||||
}),
|
||||
},
|
||||
"optional": {
|
||||
"input_string": ("STRING", {
|
||||
"default": "",
|
||||
"multiline": False
|
||||
}),
|
||||
}
|
||||
}
|
||||
|
||||
RETURN_TYPES = ("STRING", "STRING")
|
||||
RETURN_NAMES = ("output_string", "loaded_model")
|
||||
FUNCTION = "load_model"
|
||||
CATEGORY = "TA-Nodes/LMStudio"
|
||||
|
||||
def load_model(self, model_search_string, context_length, input_string=""):
|
||||
"""
|
||||
Loads a model in LM Studio via lms CLI
|
||||
"""
|
||||
try:
|
||||
import subprocess
|
||||
|
||||
print(f"[TA-LMStudio] Searching for model: {model_search_string}")
|
||||
|
||||
# Search for model
|
||||
search_cmd = ['lms', 'ls', '--detailed']
|
||||
result = subprocess.run(search_cmd, capture_output=True, text=True, check=True)
|
||||
|
||||
# Find matching model
|
||||
search_parts = model_search_string.lower().split()
|
||||
search_pattern = '.*'.join(search_parts)
|
||||
|
||||
import re
|
||||
matched_models = []
|
||||
|
||||
for line in result.stdout.split("\n"):
|
||||
line = line.strip()
|
||||
if line.startswith('/'):
|
||||
model_path = line.split()[0].lstrip("/")
|
||||
if re.search(search_pattern, model_path.lower()):
|
||||
matched_models.append(model_path)
|
||||
|
||||
if not matched_models:
|
||||
error_msg = f"[TA-LMStudio] No models found matching '{model_search_string}'"
|
||||
print(error_msg)
|
||||
return (input_string, error_msg)
|
||||
|
||||
model_path = matched_models[0]
|
||||
print(f"[TA-LMStudio] Loading model: {model_path}")
|
||||
|
||||
# Load model
|
||||
load_cmd = ['lms', 'load', model_path, '-y', f'--context-length={context_length}', '--gpu=1']
|
||||
load_result = subprocess.run(load_cmd, capture_output=True, text=True, check=True)
|
||||
|
||||
if load_result.returncode == 0:
|
||||
print(f"[TA-LMStudio] Model loaded successfully: {model_path}")
|
||||
return (input_string, model_path)
|
||||
else:
|
||||
error_msg = f"[TA-LMStudio] Failed to load model: {model_path}"
|
||||
print(error_msg)
|
||||
return (input_string, error_msg)
|
||||
|
||||
except Exception as e:
|
||||
error_msg = f"[TA-LMStudio] Error: {str(e)}"
|
||||
print(error_msg, file=sys.stderr)
|
||||
return (input_string, error_msg)
|
||||
|
||||
|
||||
class TAEbuLMStudioUnload:
|
||||
"""
|
||||
TA Node for unloading all LM Studio models
|
||||
Useful for VRAM management between tasks
|
||||
"""
|
||||
|
||||
@classmethod
|
||||
def INPUT_TYPES(cls):
|
||||
return {
|
||||
"optional": {
|
||||
"input_string": ("STRING", {
|
||||
"default": "",
|
||||
"multiline": False
|
||||
}),
|
||||
}
|
||||
}
|
||||
|
||||
RETURN_TYPES = ("STRING",)
|
||||
RETURN_NAMES = ("output_string",)
|
||||
FUNCTION = "unload_models"
|
||||
CATEGORY = "TA-Nodes/LMStudio"
|
||||
|
||||
def unload_models(self, input_string=""):
|
||||
"""
|
||||
Unloads all loaded models in LM Studio
|
||||
"""
|
||||
try:
|
||||
import subprocess
|
||||
|
||||
print(f"[TA-LMStudio] Unloading all models...")
|
||||
|
||||
unload_cmd = ['lms', 'unload', '--all', '-y']
|
||||
result = subprocess.run(unload_cmd, capture_output=True, text=True, check=True)
|
||||
|
||||
if result.returncode == 0:
|
||||
print(f"[TA-LMStudio] All models unloaded successfully")
|
||||
return (input_string,)
|
||||
else:
|
||||
error_msg = "[TA-LMStudio] Failed to unload models"
|
||||
print(error_msg)
|
||||
return (error_msg,)
|
||||
|
||||
except Exception as e:
|
||||
error_msg = f"[TA-LMStudio] Error: {str(e)}"
|
||||
print(error_msg, file=sys.stderr)
|
||||
return (error_msg,)
|
||||
|
||||
|
||||
# Node Registration
|
||||
NODE_CLASS_MAPPINGS = {
|
||||
"TAEbuLMStudioVisionRequest": TAEbuLMStudioVisionRequest,
|
||||
"TAEbuLMStudioLoadModel": TAEbuLMStudioLoadModel,
|
||||
"TAEbuLMStudioUnload": TAEbuLMStudioUnload,
|
||||
}
|
||||
|
||||
NODE_DISPLAY_NAME_MAPPINGS = {
|
||||
"TAEbuLMStudioVisionRequest": "TA LMStudio Vision (Image-to-Prompt)",
|
||||
"TAEbuLMStudioLoadModel": "TA LMStudio Load Model",
|
||||
"TAEbuLMStudioUnload": "TA LMStudio Unload All",
|
||||
}
|
||||
@@ -0,0 +1,182 @@
|
||||
"""
|
||||
================================================================================
|
||||
Node Name : TA Filename Generator
|
||||
Created : 2025
|
||||
Modified : 2026-03-11
|
||||
Copyright : © 2026, Thomas Möhrling (thomo.ART)
|
||||
Version : 2.0
|
||||
--------------------------------------------------------------------------------
|
||||
Part of ComfyUI-TA-Nodes-Pack
|
||||
License : Apache 2.0
|
||||
|
||||
Description:
|
||||
Generates structured output file paths by combining an optional folder,
|
||||
an optional subfolder (which supports strftime date-format codes),
|
||||
a name prefix, workflow version, model name, and a formatted date string.
|
||||
Returns both a base filename and an upscaled variant.
|
||||
================================================================================
|
||||
"""
|
||||
|
||||
import datetime
|
||||
import os
|
||||
|
||||
# List of date format options for the 'date_format' combo widget.
|
||||
date_format_options = [
|
||||
"%Y%m%d%H%M",
|
||||
"%Y%m%d%H%M%S",
|
||||
"%Y%m%d",
|
||||
"%Y-%m-%d-%H_%M_%S",
|
||||
"%Y-%m-%d-%H_%M",
|
||||
"%Y-%m-%d",
|
||||
"%Y-%m-%d %H_%M_%S",
|
||||
"%Y-%m-%d %H_%M",
|
||||
"%H%M",
|
||||
"%H%M%S",
|
||||
"%H_%M",
|
||||
"%H_%M_%S"
|
||||
]
|
||||
|
||||
|
||||
class TAFilenameGenerator:
|
||||
"""
|
||||
Custom ComfyUI node that replicates the filename-generation subgraph logic
|
||||
from thomo.ART workflows.
|
||||
|
||||
Combines an optional output folder, an optional subfolder (which can contain
|
||||
strftime date-format codes such as %Y-%m-%d), a name prefix, workflow version,
|
||||
model name, and a formatted date string into a full file path.
|
||||
Returns both a base filename path and an upscaled variant path.
|
||||
"""
|
||||
|
||||
@classmethod
|
||||
def INPUT_TYPES(s):
|
||||
"""
|
||||
Defines all input widgets shown in the ComfyUI node UI.
|
||||
|
||||
All inputs are optional. The 'subfolder' field accepts plain text as well
|
||||
as strftime date-format codes (e.g. %Y-%m-%d), which are resolved at
|
||||
execution time. The 'date_format' combo controls the timestamp appended
|
||||
to the filename itself.
|
||||
|
||||
Returns:
|
||||
dict: ComfyUI INPUT_TYPES dictionary with all optional inputs.
|
||||
"""
|
||||
return {
|
||||
"required": {},
|
||||
"optional": {
|
||||
"model_name": ("TA_MODEL_NAME",),
|
||||
"output_folder": ("STRING", {"default": "TA-Outputs"}),
|
||||
# The 'subfolder' field accepts plain strings as well as
|
||||
# strftime date-format codes, which are resolved internally.
|
||||
"subfolder": ("STRING", {"default": ""}),
|
||||
"name_prefix": ("STRING", {"default": "TA"}),
|
||||
"wf_version": ("STRING", {"default": "v2.50"}),
|
||||
"upscaled_suffix": ("STRING", {"default": "UPSCALED"}),
|
||||
"delimiter": ("STRING", {"default": "-"}),
|
||||
"date_format": (date_format_options, ),
|
||||
}
|
||||
}
|
||||
|
||||
RETURN_TYPES = ("STRING", "STRING")
|
||||
RETURN_NAMES = ("filename", "filename_up")
|
||||
|
||||
FUNCTION = "generate_filenames"
|
||||
CATEGORY = "TA Nodes/utils"
|
||||
|
||||
def generate_filenames(self, output_folder="TA-Outputs", subfolder="", name_prefix="TA", wf_version="v2.50", upscaled_suffix="UPSCALED", delimiter="-", date_format="%Y%m%d%H%M", model_name=None):
|
||||
"""
|
||||
Builds and returns two OS-normalized file path strings: a base filename
|
||||
and an upscaled variant.
|
||||
|
||||
Processing steps:
|
||||
1. Capture the current datetime.
|
||||
2. Format the date string for the filename using the selected date_format.
|
||||
3. Process the subfolder string through strftime to resolve any embedded
|
||||
date-format codes (e.g. '%Y-%m-%d' → '2026-03-11'). Plain text is
|
||||
passed through unchanged. Invalid codes fall back to the literal string.
|
||||
4. Assemble the base filename from [prefix, wf_version, model_name, date].
|
||||
5. Assemble the upscaled filename by appending the upscaled_suffix.
|
||||
6. Strip and clean the folder path components.
|
||||
7. Join all parts with os.path.join (empty subfolder is ignored).
|
||||
8. Normalize the final paths for the current OS (forward/back slashes).
|
||||
|
||||
Args:
|
||||
output_folder (str): Root output folder name. Default: 'TA-Outputs'.
|
||||
subfolder (str): Optional subfolder name; supports strftime codes.
|
||||
name_prefix (str): Short prefix string prepended to the filename.
|
||||
wf_version (str): Workflow version tag, e.g. 'v2.50'.
|
||||
upscaled_suffix (str): Suffix appended to the upscaled filename variant.
|
||||
delimiter (str): Character used to join filename parts. Default: '-'.
|
||||
date_format (str): strftime format string for the timestamp component.
|
||||
model_name (str|None): Model name string from a TA_MODEL_NAME input.
|
||||
Falls back to 'model' if None.
|
||||
|
||||
Returns:
|
||||
tuple[str, str]: (base_filepath, upscaled_filepath), both OS-normalized.
|
||||
"""
|
||||
if model_name is None:
|
||||
model_name = "model"
|
||||
|
||||
# 1. Get the current time.
|
||||
now = datetime.datetime.now()
|
||||
|
||||
# 2. Format the date string for the filename (from the combo widget).
|
||||
try:
|
||||
date_string = now.strftime(date_format)
|
||||
except Exception as e:
|
||||
print(f"[TA-Nodes] Error formatting filename date: {e}")
|
||||
date_string = "DATE_ERROR"
|
||||
|
||||
# 3. Process the 'subfolder' string.
|
||||
# strftime resolves %-codes and leaves plain characters unchanged.
|
||||
try:
|
||||
processed_subfolder = now.strftime(subfolder)
|
||||
except ValueError as e:
|
||||
# If an invalid code (e.g. %q) is entered, use the literal string.
|
||||
print(f"[TA-Nodes] Warning: Invalid date format in subfolder '{subfolder}'. Using literal name.")
|
||||
processed_subfolder = subfolder
|
||||
|
||||
# 4. Build the base filename WITHOUT folder path.
|
||||
parts_base = [
|
||||
name_prefix,
|
||||
wf_version,
|
||||
model_name,
|
||||
date_string
|
||||
]
|
||||
base_filename_only = delimiter.join(filter(None, parts_base))
|
||||
|
||||
# 5. Build the upscaled filename WITHOUT folder path.
|
||||
parts_upscaled_only = [
|
||||
base_filename_only,
|
||||
upscaled_suffix
|
||||
]
|
||||
upscaled_filename_only = delimiter.join(filter(None, parts_upscaled_only))
|
||||
|
||||
# 6. Strip and clean the folder path components.
|
||||
clean_output_folder = output_folder.strip().strip('/\\')
|
||||
# Use the processed (date-resolved) subfolder name.
|
||||
clean_subfolder = processed_subfolder.strip().strip('/\\')
|
||||
|
||||
# 7. Build the final path using os.path.join.
|
||||
# Empty strings (e.g. when subfolder is blank) are handled correctly.
|
||||
final_filename = os.path.join(clean_output_folder, clean_subfolder, base_filename_only)
|
||||
final_upscaled_filename = os.path.join(clean_output_folder, clean_subfolder, upscaled_filename_only)
|
||||
|
||||
# 8. Normalize the path for the current operating system.
|
||||
final_filename = os.path.normpath(final_filename)
|
||||
final_upscaled_filename = os.path.normpath(final_upscaled_filename)
|
||||
|
||||
# 9. Return both results.
|
||||
return (final_filename, final_upscaled_filename)
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------------
|
||||
# NODE MAPPINGS
|
||||
# ---------------------------------------------------------------------------------
|
||||
NODE_CLASS_MAPPINGS = {
|
||||
"TAFilenameGenerator": TAFilenameGenerator
|
||||
}
|
||||
|
||||
NODE_DISPLAY_NAME_MAPPINGS = {
|
||||
"TAFilenameGenerator": "TA Filename Generator"
|
||||
}
|
||||
@@ -0,0 +1,111 @@
|
||||
"""
|
||||
================================================================================
|
||||
Node Name : TA Flux Guidance Gate
|
||||
Created : 2026-03-10
|
||||
Modified : 2026-03-11
|
||||
Copyright : © 2026, Thomas Möhrling (thomo.ART)
|
||||
Version : 2.0
|
||||
--------------------------------------------------------------------------------
|
||||
Part of ComfyUI-TA-Nodes-Pack
|
||||
License : Apache 2.0
|
||||
|
||||
Description:
|
||||
Conditionally applies Flux Guidance to a conditioning tensor based on the
|
||||
active sampler preset. Guidance is only applied when the preset name
|
||||
contains 'FLUX'; otherwise the conditioning is passed through unchanged.
|
||||
================================================================================
|
||||
"""
|
||||
|
||||
import node_helpers
|
||||
|
||||
|
||||
class TAFluxGuidanceGate:
|
||||
"""
|
||||
Gates Flux Guidance based on the active sampler preset name.
|
||||
|
||||
Passes the conditioning through node_helpers.conditioning_set_values with
|
||||
the specified guidance value only when the connected preset_info string
|
||||
contains 'FLUX' (case-insensitive). For all other presets the conditioning
|
||||
tensor is returned unmodified, avoiding unintended guidance injection into
|
||||
non-Flux samplers.
|
||||
"""
|
||||
|
||||
CATEGORY = "TA Nodes/Sampling"
|
||||
FUNCTION = "apply"
|
||||
RETURN_TYPES = ("CONDITIONING",)
|
||||
RETURN_NAMES = ("conditioning",)
|
||||
|
||||
@classmethod
|
||||
def INPUT_TYPES(cls):
|
||||
"""
|
||||
Defines all input widgets shown in the ComfyUI node UI.
|
||||
|
||||
Inputs:
|
||||
conditioning: The conditioning tensor to be passed through or modified.
|
||||
guidance: The Flux guidance scale value applied when a FLUX preset
|
||||
is active. Has no effect for non-Flux presets.
|
||||
preset_info: The 'info' string output from a TA Sampler Preset node.
|
||||
Used to detect whether the active preset is FLUX-based.
|
||||
|
||||
Returns:
|
||||
dict: ComfyUI INPUT_TYPES dictionary with all required inputs.
|
||||
"""
|
||||
return {
|
||||
"required": {
|
||||
"conditioning": ("CONDITIONING",),
|
||||
"guidance": ("FLOAT", {
|
||||
"default": 3.5, "min": 0.0, "max": 100.0, "step": 0.1,
|
||||
"tooltip": "Flux Guidance scale – only applied when a FLUX preset is active.",
|
||||
}),
|
||||
"preset_info": ("STRING", {
|
||||
"default": "",
|
||||
"tooltip": "Connect the 'info' output of a TA Sampler Preset node.",
|
||||
"forceInput": True,
|
||||
}),
|
||||
},
|
||||
}
|
||||
|
||||
def apply(self, conditioning, guidance, preset_info):
|
||||
"""
|
||||
Applies or bypasses Flux Guidance depending on the active sampler preset.
|
||||
|
||||
Checks whether the preset_info string contains 'FLUX' (case-insensitive).
|
||||
If a FLUX preset is detected, the guidance value is injected into the
|
||||
conditioning tensor via node_helpers.conditioning_set_values. Otherwise
|
||||
the conditioning is returned unmodified.
|
||||
|
||||
Args:
|
||||
conditioning: The input conditioning tensor.
|
||||
guidance (float): Flux guidance scale to apply for FLUX presets.
|
||||
preset_info (str): Info string from a TA Sampler Preset node; used
|
||||
to determine whether the active preset is FLUX-based.
|
||||
|
||||
Returns:
|
||||
tuple: Single-element tuple containing the (modified or unmodified)
|
||||
conditioning tensor.
|
||||
"""
|
||||
is_flux = "FLUX" in preset_info.upper()
|
||||
|
||||
if is_flux:
|
||||
print(f"[TAFluxGuidanceGate] FLUX preset detected – applying guidance={guidance}.")
|
||||
result = node_helpers.conditioning_set_values(
|
||||
conditioning, {"guidance": guidance}
|
||||
)
|
||||
else:
|
||||
print(f"[TAFluxGuidanceGate] No FLUX preset – passing conditioning through unchanged.")
|
||||
result = conditioning
|
||||
|
||||
return (result,)
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Node Registration
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
NODE_CLASS_MAPPINGS = {
|
||||
"TAFluxGuidanceGate": TAFluxGuidanceGate,
|
||||
}
|
||||
|
||||
NODE_DISPLAY_NAME_MAPPINGS = {
|
||||
"TAFluxGuidanceGate": "🌊 TA Flux Guidance Gate",
|
||||
}
|
||||
@@ -0,0 +1,77 @@
|
||||
"""
|
||||
================================================================================
|
||||
Node Name : TA Help Link
|
||||
Created : 2026-03-12
|
||||
Modified : 2026-03-12
|
||||
Copyright : © 2026, Thomas Möhrling (thomo.ART)
|
||||
Version : 1.2
|
||||
--------------------------------------------------------------------------------
|
||||
Part of ComfyUI-TA-Nodes-Pack
|
||||
License : Apache 2.0
|
||||
Description:
|
||||
Decorative utility node that displays a clickable button inside the
|
||||
ComfyUI workflow canvas. Label and page are configurable via the
|
||||
Properties panel (right-click → Properties). Clicking the button
|
||||
opens a local wiki page served via a registered ComfyUI route.
|
||||
|
||||
Route : GET /ta-nodes/wiki/{filename}
|
||||
Wiki : wiki/index.html (Markdown viewer)
|
||||
Pages : wiki/*.md
|
||||
|
||||
No inputs or outputs - purely decorative/informational.
|
||||
================================================================================
|
||||
"""
|
||||
|
||||
import os
|
||||
from aiohttp import web
|
||||
from server import PromptServer
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Static file route: /ta-nodes/wiki/<filename>
|
||||
# Serves any file from the wiki/ subdirectory next to this module.
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
WIKI_DIR = os.path.join(os.path.dirname(__file__), "web", "wiki")
|
||||
|
||||
|
||||
@PromptServer.instance.routes.get("/ta-nodes/wiki/{filename}")
|
||||
async def serve_wiki_file(request):
|
||||
filename = request.match_info["filename"]
|
||||
|
||||
# Basic path traversal guard
|
||||
if ".." in filename or "/" in filename or "\\" in filename:
|
||||
raise web.HTTPForbidden()
|
||||
|
||||
filepath = os.path.join(WIKI_DIR, filename)
|
||||
if not os.path.isfile(filepath):
|
||||
raise web.HTTPNotFound()
|
||||
|
||||
return web.FileResponse(filepath)
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Node definition
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
class TAHelpLink:
|
||||
|
||||
@classmethod
|
||||
def INPUT_TYPES(cls):
|
||||
return {"required": {}}
|
||||
|
||||
RETURN_TYPES = ()
|
||||
FUNCTION = "noop"
|
||||
OUTPUT_NODE = True
|
||||
CATEGORY = "thomo.ART/utils"
|
||||
|
||||
def noop(self):
|
||||
return {}
|
||||
|
||||
|
||||
NODE_CLASS_MAPPINGS = {
|
||||
"TAHelpLink": TAHelpLink,
|
||||
}
|
||||
|
||||
NODE_DISPLAY_NAME_MAPPINGS = {
|
||||
"TAHelpLink": "TA Help Link",
|
||||
}
|
||||
+361
@@ -0,0 +1,361 @@
|
||||
"""
|
||||
================================================================================
|
||||
Node Name : TA KSampler
|
||||
Created : 2026-03-07
|
||||
Modified : 2026-03-14
|
||||
Copyright : © 2026, Thomas Möhrling (thomo.ART)
|
||||
Version : 2.1
|
||||
--------------------------------------------------------------------------------
|
||||
Part of ComfyUI-TA-Nodes-Pack
|
||||
License : Apache 2.0
|
||||
|
||||
Description:
|
||||
Advanced KSampler node that accepts sampler_name and scheduler as plain
|
||||
STRING inputs, making it directly connectable to the TA Sampler Preset node.
|
||||
Provides per-step live latent2rgb preview via pbar.update_absolute(),
|
||||
identical in behaviour to ComfyUI's built-in KSampler preview.
|
||||
================================================================================
|
||||
"""
|
||||
|
||||
import struct
|
||||
import torch
|
||||
import numpy as np
|
||||
from PIL import Image
|
||||
|
||||
import comfy.sample
|
||||
import comfy.samplers
|
||||
import comfy.utils
|
||||
import latent_preview
|
||||
|
||||
|
||||
# ── latent2rgb conversion factors (ComfyUI Latent2RGBPreviewer, 4+16 channel) ─
|
||||
_FACTORS_RAW = [
|
||||
[ 0.3512, 0.2946, 0.3430],
|
||||
[ 0.3037, 0.2151, 0.2835],
|
||||
[ 0.3172, 0.2827, 0.3164],
|
||||
[ 0.2775, 0.2775, 0.3310],
|
||||
[-0.0472, 0.0621, 0.0905],
|
||||
[-0.1543, -0.0937, -0.1290],
|
||||
[-0.0598, -0.0478, -0.0453],
|
||||
[ 0.0440, 0.0839, 0.0759],
|
||||
[-0.1225, 0.0110, 0.0543],
|
||||
[ 0.0507, 0.0873, 0.0775],
|
||||
[-0.0219, 0.0022, 0.0046],
|
||||
[-0.0275, 0.0270, 0.0206],
|
||||
[-0.0315, -0.0072, -0.0001],
|
||||
[ 0.0077, 0.0091, 0.0076],
|
||||
[-0.0218, -0.0125, -0.0162],
|
||||
[ 0.0124, 0.0052, 0.0074],
|
||||
]
|
||||
_BIAS = [0.5006, 0.4229, 0.4572]
|
||||
|
||||
|
||||
def _latent_to_pil(latent_tensor: torch.Tensor) -> Image.Image:
|
||||
"""
|
||||
Converts a single latent frame tensor to a PIL RGB image.
|
||||
|
||||
Applies the ComfyUI latent2rgb matrix (_FACTORS_RAW) and bias (_BIAS) to
|
||||
project the latent channels into RGB colour space. The result is upscaled
|
||||
to at least 512 px on the longest side using Lanczos resampling if the
|
||||
raw decoded image is smaller.
|
||||
|
||||
Handles both standard (C, H, W) latents and FLUX.2 Klein packed 2D latents
|
||||
delivered as (H*W, C) by reshaping them to (C, H, W) before conversion.
|
||||
|
||||
Args:
|
||||
latent_tensor (torch.Tensor): Single latent frame, either (C, H, W)
|
||||
or packed (H*W, C) as from FLUX.2 Klein.
|
||||
|
||||
Returns:
|
||||
Image.Image: RGB PIL image, upscaled to at least 512 px on the longest side.
|
||||
"""
|
||||
s = latent_tensor.cpu().float()
|
||||
|
||||
# Guard: must be (C, H, W) at this point
|
||||
if s.dim() != 3:
|
||||
raise ValueError(f"_latent_to_pil expects 3D tensor (C, H, W), got shape {tuple(s.shape)}")
|
||||
|
||||
c = s.shape[0]
|
||||
|
||||
factors = torch.tensor(_FACTORS_RAW[:c], dtype=torch.float32) # (C, 3)
|
||||
bias = torch.tensor(_BIAS, dtype=torch.float32) # (3,)
|
||||
|
||||
# (C, H, W) → (H, W, C) → (H, W, 3)
|
||||
rgb = (s.permute(1, 2, 0) @ factors + bias).clamp(0.0, 1.0)
|
||||
arr = (rgb.numpy() * 255).astype(np.uint8)
|
||||
img = Image.fromarray(arr, "RGB")
|
||||
|
||||
# Upscale to at least 512 px on the longest side (Lanczos)
|
||||
w, h = img.size
|
||||
target = 512
|
||||
if max(w, h) < target:
|
||||
scale = target / max(w, h)
|
||||
img = img.resize((int(w * scale), int(h * scale)), Image.LANCZOS)
|
||||
|
||||
return img
|
||||
|
||||
|
||||
def _make_step_callback(model, steps: int):
|
||||
"""
|
||||
Builds a sampling callback that sends a latent2rgb preview to the ComfyUI
|
||||
frontend after every denoising step via pbar.update_absolute().
|
||||
|
||||
Behaviour is identical to latent_preview.prepare_callback(). Supports both
|
||||
standard 4D latents (B, C, H, W) and 5D video/Qwen latents (B, C, F, H, W)
|
||||
by normalising the tensor to (C, H, W) before conversion.
|
||||
|
||||
Preview errors are caught silently so they never interrupt the sampling
|
||||
process; the progress bar still advances even if the preview fails.
|
||||
|
||||
Args:
|
||||
model: The ComfyUI model object (used for ProgressBar context).
|
||||
steps (int): Total number of sampling steps; used to initialise the
|
||||
progress bar.
|
||||
|
||||
Returns:
|
||||
callable: A callback function with the signature
|
||||
callback(step, x0, x, total_steps).
|
||||
"""
|
||||
pbar = comfy.utils.ProgressBar(steps)
|
||||
|
||||
# Read the preview format from ComfyUI CLI settings (JPEG / PNG).
|
||||
preview_format = "JPEG"
|
||||
try:
|
||||
from comfy.cli_args import args as _cli_args
|
||||
fmt = getattr(_cli_args, "preview_format", "JPEG")
|
||||
if fmt in ("JPEG", "PNG"):
|
||||
preview_format = fmt
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
preview_failed = [False] # mutable flag accessible inside closure
|
||||
|
||||
def callback(step, x0, x, total_steps):
|
||||
# x0: denoised latent after this step, shape (B, C, H, W)
|
||||
if preview_failed[0]:
|
||||
pbar.update_absolute(step + 1, total_steps, None)
|
||||
return
|
||||
try:
|
||||
# Normalise shape to (C, H, W):
|
||||
# Standard 4D: (B, C, H, W) → x0[0] e.g. FLUX Dev
|
||||
# Video / Qwen 5D: (B, C, F, H, W) → x0[0, :, 0, :, :]
|
||||
# FLUX.2 Klein 3D: (B, tokens, C) → depatchify to (C, H, W)
|
||||
if x0.dim() == 5:
|
||||
frame = x0[0, :, 0, :, :] # (C, H, W)
|
||||
elif x0.dim() == 4:
|
||||
frame = x0[0] # (C, H, W)
|
||||
elif x0.dim() == 3:
|
||||
seq = x0[0] # (tokens, C)
|
||||
tokens, c = seq.shape
|
||||
found = False
|
||||
for h in range(int(tokens ** 0.5) + 1, 0, -1):
|
||||
if tokens % h == 0:
|
||||
w = tokens // h
|
||||
if 0.25 <= h / w <= 4.0:
|
||||
frame = seq.reshape(h, w, c).permute(2, 0, 1) # (C, H, W)
|
||||
found = True
|
||||
break
|
||||
if not found:
|
||||
pbar.update_absolute(step + 1, total_steps, None)
|
||||
return
|
||||
else:
|
||||
frame = x0 # fallback
|
||||
preview_img = _latent_to_pil(frame)
|
||||
pbar.update_absolute(step + 1, total_steps, ("JPEG", preview_img, None))
|
||||
except Exception as e:
|
||||
# On first failure: log once and disable preview for remaining steps.
|
||||
print(f"[TAKSampler] Preview not supported for this model "
|
||||
f"(step {step+1}: {type(e).__name__}: {e}) — disabling preview.")
|
||||
preview_failed[0] = True
|
||||
pbar.update_absolute(step + 1, total_steps, None)
|
||||
|
||||
return callback
|
||||
|
||||
|
||||
class TAKSampler:
|
||||
"""
|
||||
Advanced KSampler that accepts sampler_name and scheduler as plain STRING
|
||||
inputs instead of COMBO dropdowns, making it directly connectable to the
|
||||
TA Sampler Preset node.
|
||||
|
||||
Provides per-step live latent2rgb preview via pbar.update_absolute(),
|
||||
identical in behaviour to ComfyUI's built-in KSampler preview. Preview can
|
||||
be toggled on/off via the 'preview' boolean input.
|
||||
"""
|
||||
|
||||
CATEGORY = "TA Nodes/Sampling"
|
||||
FUNCTION = "sample"
|
||||
RETURN_TYPES = ("LATENT",)
|
||||
RETURN_NAMES = ("latent",)
|
||||
|
||||
@classmethod
|
||||
def INPUT_TYPES(cls):
|
||||
"""
|
||||
Defines all input widgets shown in the ComfyUI node UI.
|
||||
|
||||
Returns:
|
||||
dict: ComfyUI INPUT_TYPES dictionary with all required inputs.
|
||||
"""
|
||||
return {
|
||||
"required": {
|
||||
"model": ("MODEL",),
|
||||
"add_noise": (["enable", "disable"], {"default": "enable"}),
|
||||
"noise_seed": ("INT", {
|
||||
"default": 0, "min": 0, "max": 0xffffffffffffffff,
|
||||
"control_after_generate": True,
|
||||
}),
|
||||
"steps": ("INT", {"default": 20, "min": 1, "max": 200}),
|
||||
"cfg": ("FLOAT", {"default": 7.0, "min": 0.0, "max": 30.0, "step": 0.1}),
|
||||
"sampler_name": ("STRING", {
|
||||
"default": "euler",
|
||||
"tooltip": "e.g. euler, euler_ancestral, dpmpp_2m, dpmpp_sde …",
|
||||
}),
|
||||
"scheduler": ("STRING", {
|
||||
"default": "normal",
|
||||
"tooltip": "e.g. normal, karras, exponential, simple, beta …",
|
||||
}),
|
||||
"positive": ("CONDITIONING",),
|
||||
"negative": ("CONDITIONING",),
|
||||
"latent_image": ("LATENT",),
|
||||
"start_at_step": ("INT", {"default": 0, "min": 0, "max": 10000}),
|
||||
"end_at_step": ("INT", {"default": 9999, "min": 0, "max": 99999}),
|
||||
"return_with_leftover_noise": (["disable", "enable"], {"default": "disable"}),
|
||||
"preview": ("BOOLEAN", {"default": True, "label_on": "true", "label_off": "false"}),
|
||||
},
|
||||
}
|
||||
|
||||
def sample(
|
||||
self,
|
||||
model,
|
||||
add_noise,
|
||||
noise_seed,
|
||||
steps,
|
||||
cfg,
|
||||
sampler_name,
|
||||
scheduler,
|
||||
positive,
|
||||
negative,
|
||||
latent_image,
|
||||
start_at_step,
|
||||
end_at_step,
|
||||
return_with_leftover_noise,
|
||||
preview,
|
||||
):
|
||||
"""
|
||||
Executes the sampling process and returns the resulting latent tensor.
|
||||
|
||||
Validates the sampler_name and scheduler strings against ComfyUI's
|
||||
registered values, falling back to safe defaults ('euler' / 'normal')
|
||||
if an unknown value is provided. Builds the noise tensor, optional noise
|
||||
mask, and step callback, then delegates to comfy.sample.sample().
|
||||
|
||||
Args:
|
||||
model: ComfyUI MODEL object.
|
||||
add_noise (str): 'enable' to add noise; 'disable' for a
|
||||
zero noise tensor (useful for img2img).
|
||||
noise_seed (int): RNG seed for reproducible noise generation.
|
||||
steps (int): Total number of denoising steps.
|
||||
cfg (float): Classifier-free guidance scale.
|
||||
sampler_name (str): Name of the sampler algorithm, e.g. 'euler'.
|
||||
Falls back to 'euler' if not recognised.
|
||||
scheduler (str): Name of the noise scheduler, e.g. 'karras'.
|
||||
Falls back to 'normal' if not recognised.
|
||||
positive: Positive CONDITIONING tensor.
|
||||
negative: Negative CONDITIONING tensor.
|
||||
latent_image (dict): Input LATENT dict containing 'samples' and
|
||||
optionally 'batch_index' and 'noise_mask'.
|
||||
start_at_step (int): Step index at which to begin sampling
|
||||
(0 = from the start).
|
||||
end_at_step (int): Step index at which to stop sampling
|
||||
(9999 = run to completion).
|
||||
return_with_leftover_noise (str):
|
||||
'enable' to keep residual noise in the
|
||||
output; 'disable' for a fully denoised result.
|
||||
preview (bool): If True, sends latent2rgb previews to the
|
||||
ComfyUI frontend after each step. If False,
|
||||
falls back to the standard ComfyUI callback.
|
||||
|
||||
Returns:
|
||||
tuple: Single-element tuple containing the output LATENT dict with
|
||||
the sampled 'samples' tensor.
|
||||
"""
|
||||
# ── Validation ─────────────────────────────────────────────────────
|
||||
available_samplers = comfy.samplers.KSampler.SAMPLERS
|
||||
available_schedulers = comfy.samplers.KSampler.SCHEDULERS
|
||||
|
||||
if sampler_name not in available_samplers:
|
||||
print(f"[TAKSampler] ⚠️ Unknown sampler_name '{sampler_name}', "
|
||||
f"using 'euler'. Available: {available_samplers}")
|
||||
sampler_name = "euler"
|
||||
|
||||
if scheduler not in available_schedulers:
|
||||
print(f"[TAKSampler] ⚠️ Unknown scheduler '{scheduler}', "
|
||||
f"using 'normal'. Available: {available_schedulers}")
|
||||
scheduler = "normal"
|
||||
|
||||
# ── Flags ──────────────────────────────────────────────────────────
|
||||
disable_noise = (add_noise == "disable")
|
||||
force_full_denoise = (return_with_leftover_noise == "disable")
|
||||
start_step = start_at_step if start_at_step > 0 else None
|
||||
last_step = end_at_step if end_at_step < 9999 else None
|
||||
|
||||
# ── Prepare latent ─────────────────────────────────────────────────
|
||||
latent = latent_image.copy()
|
||||
latent_data = latent["samples"]
|
||||
latent_data = comfy.sample.fix_empty_latent_channels(model, latent_data)
|
||||
|
||||
# ── Noise ──────────────────────────────────────────────────────────
|
||||
if disable_noise:
|
||||
noise = torch.zeros(
|
||||
latent_data.size(),
|
||||
dtype=latent_data.dtype,
|
||||
layout=latent_data.layout,
|
||||
device="cpu",
|
||||
)
|
||||
else:
|
||||
batch_inds = latent.get("batch_index", None)
|
||||
noise = comfy.sample.prepare_noise(latent_data, noise_seed, batch_inds)
|
||||
|
||||
noise_mask = latent.get("noise_mask", None)
|
||||
|
||||
# ── Callback with live preview ──────────────────────────────────────
|
||||
callback = _make_step_callback(model, steps) if preview else latent_preview.prepare_callback(model, steps)
|
||||
disable_pbar = not comfy.utils.PROGRESS_BAR_ENABLED
|
||||
|
||||
# ── Sampling ───────────────────────────────────────────────────────
|
||||
samples = comfy.sample.sample(
|
||||
model,
|
||||
noise,
|
||||
steps,
|
||||
cfg,
|
||||
sampler_name,
|
||||
scheduler,
|
||||
positive,
|
||||
negative,
|
||||
latent_data,
|
||||
denoise = 1.0,
|
||||
disable_noise = disable_noise,
|
||||
start_step = start_step,
|
||||
last_step = last_step,
|
||||
force_full_denoise = force_full_denoise,
|
||||
noise_mask = noise_mask,
|
||||
callback = callback,
|
||||
disable_pbar = disable_pbar,
|
||||
seed = noise_seed,
|
||||
)
|
||||
|
||||
latent["samples"] = samples
|
||||
return (latent,)
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Node Registration
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
NODE_CLASS_MAPPINGS = {
|
||||
"TAKSampler": TAKSampler,
|
||||
}
|
||||
|
||||
NODE_DISPLAY_NAME_MAPPINGS = {
|
||||
"TAKSampler": "⚡ TA KSampler",
|
||||
}
|
||||
@@ -0,0 +1,174 @@
|
||||
"""
|
||||
================================================================================
|
||||
Node Name : TA Latent Preview
|
||||
Created : 2026-03-07
|
||||
Modified : 2026-03-11
|
||||
Copyright : © 2026, Thomas Möhrling (thomo.ART)
|
||||
Version : 2.0
|
||||
--------------------------------------------------------------------------------
|
||||
Part of ComfyUI-TA-Nodes-Pack
|
||||
License : Apache 2.0
|
||||
|
||||
Description:
|
||||
Displays a LATENT tensor as a preview image directly inside the node using
|
||||
the latent2rgb projection. Requires no VAE and no TAESD — runs on any
|
||||
hardware. Output format is identical to ComfyUI's built-in PreviewImage node.
|
||||
================================================================================
|
||||
"""
|
||||
|
||||
import os
|
||||
import uuid
|
||||
import torch
|
||||
import numpy as np
|
||||
from PIL import Image
|
||||
import folder_paths
|
||||
|
||||
|
||||
# latent2rgb weights (ComfyUI LatentToRGB, supports 4- and 16-channel latents)
|
||||
LATENT_RGB_FACTORS = [
|
||||
# R G B
|
||||
[ 0.3512, 0.2946, 0.3430],
|
||||
[ 0.3037, 0.2151, 0.2835],
|
||||
[ 0.3172, 0.2827, 0.3164],
|
||||
[ 0.2775, 0.2775, 0.3310],
|
||||
[-0.0472, 0.0621, 0.0905],
|
||||
[-0.1543, -0.0937, -0.1290],
|
||||
[-0.0598, -0.0478, -0.0453],
|
||||
[ 0.0440, 0.0839, 0.0759],
|
||||
[-0.1225, 0.0110, 0.0543],
|
||||
[ 0.0507, 0.0873, 0.0775],
|
||||
[-0.0219, 0.0022, 0.0046],
|
||||
[-0.0275, 0.0270, 0.0206],
|
||||
[-0.0315, -0.0072, -0.0001],
|
||||
[ 0.0077, 0.0091, 0.0076],
|
||||
[-0.0218, -0.0125, -0.0162],
|
||||
[ 0.0124, 0.0052, 0.0074],
|
||||
]
|
||||
|
||||
BIAS = [0.5006, 0.4229, 0.4572]
|
||||
|
||||
|
||||
def latent_to_pil(latent_samples: torch.Tensor) -> list:
|
||||
"""
|
||||
Converts a batch of latent tensors to a list of PIL RGB images using the
|
||||
latent2rgb projection matrix.
|
||||
|
||||
Applies LATENT_RGB_FACTORS and BIAS to project each latent frame from
|
||||
latent space into approximate RGB colour space without requiring a VAE.
|
||||
Supports both 4-channel (standard SD/SDXL) and 16-channel (SD3 / Flux)
|
||||
latents by slicing the factor matrix to match the channel count.
|
||||
|
||||
Args:
|
||||
latent_samples (torch.Tensor): Latent batch tensor with shape (B, C, H, W).
|
||||
|
||||
Returns:
|
||||
list[Image.Image]: List of B PIL RGB images, one per batch entry.
|
||||
"""
|
||||
s = latent_samples.cpu().float()
|
||||
b, c, h, w = s.shape
|
||||
|
||||
factors = torch.tensor(LATENT_RGB_FACTORS[:c], dtype=torch.float32) # (C, 3)
|
||||
bias = torch.tensor(BIAS, dtype=torch.float32) # (3,)
|
||||
|
||||
s = s.permute(0, 2, 3, 1) # (B, H, W, C)
|
||||
rgb = (s @ factors + bias).clamp(0.0, 1.0) # (B, H, W, 3)
|
||||
|
||||
images = []
|
||||
for i in range(b):
|
||||
arr = (rgb[i].numpy() * 255).astype(np.uint8)
|
||||
images.append(Image.fromarray(arr, "RGB"))
|
||||
return images
|
||||
|
||||
|
||||
class TALatentPreview:
|
||||
"""
|
||||
Displays a LATENT tensor as a preview image directly inside the ComfyUI node.
|
||||
|
||||
Uses the latent2rgb projection matrix — no VAE decoder and no TAESD model
|
||||
are required, so the node runs on any hardware configuration. The UI output
|
||||
format (temp PNG files with filename/subfolder/type dict) is identical to
|
||||
ComfyUI's built-in PreviewImage node, ensuring full frontend compatibility.
|
||||
|
||||
Also outputs the projected RGB data as a standard IMAGE tensor (B, H, W, 3)
|
||||
in float [0..1] range for optional use in downstream workflow nodes.
|
||||
"""
|
||||
|
||||
CATEGORY = "TA Nodes/Sampling"
|
||||
FUNCTION = "preview"
|
||||
RETURN_TYPES = ("IMAGE",)
|
||||
RETURN_NAMES = ("image",)
|
||||
OUTPUT_NODE = True
|
||||
|
||||
@classmethod
|
||||
def INPUT_TYPES(cls):
|
||||
"""
|
||||
Defines all input widgets shown in the ComfyUI node UI.
|
||||
|
||||
Returns:
|
||||
dict: ComfyUI INPUT_TYPES dictionary with the required LATENT input.
|
||||
"""
|
||||
return {
|
||||
"required": {
|
||||
"latent": ("LATENT",),
|
||||
},
|
||||
}
|
||||
|
||||
def preview(self, latent):
|
||||
"""
|
||||
Projects the input latent tensor to RGB, saves preview PNGs to the
|
||||
ComfyUI temp directory, and returns both UI image references and an
|
||||
IMAGE tensor for downstream nodes.
|
||||
|
||||
For each image in the batch a uniquely named PNG is written to the
|
||||
ComfyUI temp directory and registered in the 'ui' return dict so the
|
||||
frontend can display it inside the node. The same RGB projection is
|
||||
also returned as a float IMAGE tensor (B, H, W, 3) via 'result'.
|
||||
|
||||
Args:
|
||||
latent (dict): ComfyUI LATENT dict containing a 'samples' key with
|
||||
a tensor of shape (B, C, H, W).
|
||||
|
||||
Returns:
|
||||
dict: ComfyUI combined UI + result dict:
|
||||
- 'ui': {'images': [{'filename', 'subfolder', 'type'}, ...]}
|
||||
- 'result': tuple containing the IMAGE tensor (B, H, W, 3) float [0..1].
|
||||
"""
|
||||
samples = latent["samples"] # (B, C, H, W)
|
||||
pil_imgs = latent_to_pil(samples)
|
||||
|
||||
temp_dir = folder_paths.get_temp_directory()
|
||||
os.makedirs(temp_dir, exist_ok=True)
|
||||
|
||||
ui_images = []
|
||||
for img in pil_imgs:
|
||||
filename = f"ta_latent_preview_{uuid.uuid4().hex[:12]}.png"
|
||||
filepath = os.path.join(temp_dir, filename)
|
||||
img.save(filepath, compress_level=1)
|
||||
ui_images.append({
|
||||
"filename": filename,
|
||||
"subfolder": "",
|
||||
"type": "temp",
|
||||
})
|
||||
|
||||
# IMAGE tensor for downstream workflow nodes: (B, H, W, 3) float [0..1]
|
||||
s = samples.cpu().float()
|
||||
b, c, h, w = s.shape
|
||||
factors = torch.tensor(LATENT_RGB_FACTORS[:c], dtype=torch.float32)
|
||||
bias = torch.tensor(BIAS, dtype=torch.float32)
|
||||
rgb = (s.permute(0, 2, 3, 1) @ factors + bias).clamp(0.0, 1.0)
|
||||
|
||||
return {"ui": {"images": ui_images}, "result": (rgb,)}
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Node Registration
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
NODE_CLASS_MAPPINGS = {
|
||||
"TALatentPreview": TALatentPreview,
|
||||
}
|
||||
|
||||
NODE_DISPLAY_NAME_MAPPINGS = {
|
||||
"TALatentPreview": "🖼️ TA Latent Preview",
|
||||
}
|
||||
@@ -0,0 +1,90 @@
|
||||
"""
|
||||
================================================================================
|
||||
Node Name : TA LLM Prompt Selector
|
||||
Created : 2025
|
||||
Modified : 2026-03-11
|
||||
Copyright : © 2026, Thomas Möhrling (thomo.ART)
|
||||
Version : 2.0
|
||||
--------------------------------------------------------------------------------
|
||||
Part of ComfyUI-TA-Nodes-Pack
|
||||
License : Apache 2.0
|
||||
|
||||
Description:
|
||||
Selects between a text-to-image prompt and an image-to-image prompt based
|
||||
on the current LLM status. When the LLM is active and a text2prompt string
|
||||
is present, text2prompt is forwarded; otherwise image2prompt is used.
|
||||
================================================================================
|
||||
"""
|
||||
|
||||
import comfy
|
||||
|
||||
|
||||
class TA_LLM_PromptSelector:
|
||||
"""
|
||||
Automatically selects the appropriate prompt string based on LLM status.
|
||||
|
||||
Routes to text2prompt when the LLM backend is active (llm_status is not
|
||||
'DISABLED') and text2prompt contains a non-empty string. Falls back to
|
||||
image2prompt in all other cases (LLM disabled, or no text prompt provided).
|
||||
"""
|
||||
|
||||
@classmethod
|
||||
def INPUT_TYPES(cls):
|
||||
"""
|
||||
Defines all input widgets shown in the ComfyUI node UI.
|
||||
|
||||
Inputs:
|
||||
llm_status: Status string from an upstream LLM node. The value
|
||||
'DISABLED' (or an empty string) indicates the LLM is
|
||||
inactive; any other non-empty value is treated as active.
|
||||
text2prompt: Prompt string generated by the LLM (text-to-image path).
|
||||
image2prompt: Fallback prompt string used when the LLM is inactive or
|
||||
text2prompt is empty (image-to-image path).
|
||||
|
||||
Returns:
|
||||
dict: ComfyUI INPUT_TYPES dictionary with all required inputs.
|
||||
"""
|
||||
return {
|
||||
"required": {
|
||||
"llm_status": ("STRING", {
|
||||
"default": "DISABLED",
|
||||
"multiline": False
|
||||
}),
|
||||
"text2prompt": ("STRING", {
|
||||
"multiline": True,
|
||||
"default": ""
|
||||
}),
|
||||
"image2prompt": ("STRING", {
|
||||
"multiline": True,
|
||||
"default": ""
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
RETURN_TYPES = ("STRING",)
|
||||
FUNCTION = "select_prompt"
|
||||
CATEGORY = "ThomasAI"
|
||||
|
||||
def select_prompt(self, llm_status, text2prompt, image2prompt):
|
||||
"""
|
||||
Returns the appropriate prompt string based on LLM status and input content.
|
||||
|
||||
Selection logic:
|
||||
- If llm_status is a non-empty string other than 'DISABLED' AND
|
||||
text2prompt is non-empty → return text2prompt.
|
||||
- Otherwise → return image2prompt.
|
||||
|
||||
Args:
|
||||
llm_status (str): Status indicator from an upstream LLM node.
|
||||
'DISABLED' or empty string means the LLM is off.
|
||||
text2prompt (str): LLM-generated prompt for the text-to-image path.
|
||||
image2prompt (str): Fallback prompt for the image-to-image path.
|
||||
|
||||
Returns:
|
||||
tuple[str]: Single-element tuple containing the selected prompt string.
|
||||
"""
|
||||
# Auto-select logic: use text2prompt if LLM is active and prompt is present,
|
||||
# otherwise fall back to image2prompt.
|
||||
if llm_status and llm_status.strip() != "DISABLED" and text2prompt.strip():
|
||||
return (text2prompt,)
|
||||
return (image2prompt,)
|
||||
@@ -1,405 +0,0 @@
|
||||
"""
|
||||
TA LMStudio Load On Run Node - With Vision Model Marking
|
||||
Marks vision models with (V) in the dropdown
|
||||
"""
|
||||
|
||||
import subprocess
|
||||
import time
|
||||
import re
|
||||
|
||||
|
||||
class TALMStudioLoadOnRun:
|
||||
"""
|
||||
Node with vision model marking
|
||||
"""
|
||||
|
||||
_model_paths = {}
|
||||
_vision_keywords = [
|
||||
# Explicit vision keywords
|
||||
'vision', 'llava', 'pixtral', 'minicpm-v', 'cogvlm', 'internvl',
|
||||
'molmo', 'aria', 'phi-3-vision', 'phi-3.5-vision',
|
||||
# Qwen: ONLY VL variants are vision
|
||||
'qwen-vl', 'qwen2-vl', 'qwen2.5-vl', 'qwen3-vl', 'qwq-vl',
|
||||
# Llama: ONLY 3.1 and 3.2 have vision
|
||||
'llama-3.1', 'llama-3.2', 'llama3.1', 'llama3.2',
|
||||
# Gemma: ONLY Gemma 3 (Gemini-based) has vision
|
||||
'gemma-3', 'paligemma',
|
||||
# Other known vision models
|
||||
'fuyu', 'kosmos', 'idefics', 'otter', 'flamingo', 'blip',
|
||||
'deepseek-vl', 'yi-vl', 'mplug', 'sphinx', 'video-llama',
|
||||
]
|
||||
|
||||
@classmethod
|
||||
def INPUT_TYPES(cls):
|
||||
models = cls.get_available_models()
|
||||
|
||||
return {
|
||||
"required": {
|
||||
"model": (models, {
|
||||
"default": models[0] if models else "llava-v1.5"
|
||||
}),
|
||||
"context_length": ("INT", {
|
||||
"default": 8192,
|
||||
"min": 512,
|
||||
"max": 131072,
|
||||
"step": 512
|
||||
}),
|
||||
"wait_time": ("INT", {
|
||||
"default": 8,
|
||||
"min": 1,
|
||||
"max": 30,
|
||||
"step": 1,
|
||||
"display": "number",
|
||||
"tooltip": "Seconds to wait after loading (8-10s recommended for large models)"
|
||||
}),
|
||||
"skip_unload": ("BOOLEAN", {
|
||||
"default": False,
|
||||
"label_on": "Skip unload",
|
||||
"label_off": "Try unload",
|
||||
"tooltip": "Skip unload if it keeps failing"
|
||||
}),
|
||||
},
|
||||
}
|
||||
|
||||
RETURN_TYPES = ("STRING", "STRING")
|
||||
RETURN_NAMES = ("model_name", "status")
|
||||
FUNCTION = "load_and_return"
|
||||
CATEGORY = "TA-Nodes/LMStudio"
|
||||
|
||||
@classmethod
|
||||
def is_valid_model(cls, model_name):
|
||||
"""
|
||||
Checks if an entry is a real model
|
||||
Filters meta entries like EMBEDDING, LLM, You, etc.
|
||||
"""
|
||||
if not model_name or len(model_name) < 3:
|
||||
return False
|
||||
|
||||
# Filter: Known meta entries (case-insensitive)
|
||||
blocked_entries = [
|
||||
'embedding', 'llm', 'you', 'default', 'none',
|
||||
'text-embedding', 'all-minilm', 'bge-', 'e5-'
|
||||
]
|
||||
|
||||
model_lower = model_name.lower()
|
||||
for blocked in blocked_entries:
|
||||
if model_lower == blocked or model_lower.startswith(blocked):
|
||||
return False
|
||||
|
||||
# Filter: Only uppercase letters (probably a category)
|
||||
if model_name.isupper() and len(model_name) < 15:
|
||||
return False
|
||||
|
||||
return True
|
||||
|
||||
@classmethod
|
||||
def is_vision_model(cls, model_name):
|
||||
"""
|
||||
Checks if a model is a vision model
|
||||
Based on known vision model keywords
|
||||
"""
|
||||
model_lower = model_name.lower()
|
||||
|
||||
for keyword in cls._vision_keywords:
|
||||
if keyword in model_lower:
|
||||
return True
|
||||
|
||||
return False
|
||||
|
||||
@classmethod
|
||||
def get_available_models(cls):
|
||||
"""Gets ALL available models and marks vision models"""
|
||||
cls._model_paths = {}
|
||||
|
||||
try:
|
||||
result = subprocess.run(
|
||||
['lms', 'ls', '--detailed'],
|
||||
capture_output=True,
|
||||
text=True,
|
||||
timeout=10,
|
||||
encoding='utf-8',
|
||||
errors='replace'
|
||||
)
|
||||
|
||||
if result.returncode == 0:
|
||||
models = []
|
||||
lines = result.stdout.split('\n')
|
||||
|
||||
for line in lines:
|
||||
line = line.strip()
|
||||
|
||||
if not line or 'Downloaded models' in line or line.startswith('-'):
|
||||
continue
|
||||
|
||||
parts = line.split()
|
||||
if not parts:
|
||||
continue
|
||||
|
||||
full_path = parts[0]
|
||||
if full_path.startswith('/'):
|
||||
full_path = full_path.lstrip('/')
|
||||
|
||||
# Create display name
|
||||
if '/' in full_path:
|
||||
path_parts = full_path.split('/')
|
||||
if len(path_parts) >= 2:
|
||||
display_name = '/'.join(path_parts[-2:])
|
||||
else:
|
||||
display_name = path_parts[-1]
|
||||
else:
|
||||
display_name = full_path
|
||||
|
||||
# FILTER: Skip meta entries
|
||||
if not cls.is_valid_model(display_name):
|
||||
continue
|
||||
|
||||
# CHECK IF VISION MODEL
|
||||
if cls.is_vision_model(display_name):
|
||||
# Add (V) for vision models
|
||||
display_name_marked = f"{display_name} (V)"
|
||||
else:
|
||||
display_name_marked = display_name
|
||||
|
||||
# Store both: marked name → full path
|
||||
cls._model_paths[display_name_marked] = full_path
|
||||
models.append(display_name_marked)
|
||||
|
||||
if models:
|
||||
# Sort: Vision models first, then alphabetically
|
||||
vision_models = [m for m in models if '(V)' in m]
|
||||
text_models = [m for m in models if '(V)' not in m]
|
||||
|
||||
vision_models.sort()
|
||||
text_models.sort()
|
||||
|
||||
# Vision models first
|
||||
sorted_models = vision_models + text_models
|
||||
|
||||
return sorted_models
|
||||
else:
|
||||
return cls.get_default_models()
|
||||
else:
|
||||
return cls.get_default_models()
|
||||
|
||||
except Exception as e:
|
||||
print(f"[TA-LoadOnRun] Error listing models: {e}")
|
||||
return cls.get_default_models()
|
||||
|
||||
@classmethod
|
||||
def get_default_models(cls):
|
||||
defaults = [
|
||||
"llava-v1.5-7b (V)",
|
||||
"qwen2-vl-7b-instruct (V)",
|
||||
"pixtral-12b (V)",
|
||||
"google/gemma-3-27b (V)",
|
||||
"llama-3.1-unhinged-vision-8b (V)",
|
||||
]
|
||||
for model in defaults:
|
||||
if model not in cls._model_paths:
|
||||
# Remove (V) for the path
|
||||
model_path = model.replace(" (V)", "")
|
||||
cls._model_paths[model] = model_path
|
||||
return defaults
|
||||
|
||||
def try_unload(self):
|
||||
"""Attempts to unload, tolerates errors"""
|
||||
print("[TA-LoadOnRun] Attempting to unload models...")
|
||||
|
||||
try:
|
||||
result = subprocess.run(
|
||||
['lms', 'unload', '--all', '-y'],
|
||||
capture_output=True,
|
||||
text=True,
|
||||
timeout=10,
|
||||
encoding='utf-8',
|
||||
errors='replace'
|
||||
)
|
||||
|
||||
output = (result.stdout + result.stderr).lower()
|
||||
|
||||
if 'no models to unload' in output or 'no models loaded' in output:
|
||||
print(f"[TA-LoadOnRun] ✓ Already unloaded")
|
||||
return True
|
||||
elif result.returncode == 0:
|
||||
print(f"[TA-LoadOnRun] ✓ Unload successful")
|
||||
time.sleep(2)
|
||||
return True
|
||||
else:
|
||||
print(f"[TA-LoadOnRun] ⚠ Unload returned code {result.returncode}")
|
||||
return False
|
||||
|
||||
except subprocess.TimeoutExpired:
|
||||
print(f"[TA-LoadOnRun] ⚠ Unload timeout - continuing anyway")
|
||||
return False
|
||||
except Exception as e:
|
||||
print(f"[TA-LoadOnRun] ⚠ Unload error: {e} - continuing anyway")
|
||||
return False
|
||||
|
||||
def is_model_loaded(self, model_name):
|
||||
"""Checks if model is loaded"""
|
||||
try:
|
||||
result = subprocess.run(
|
||||
['lms', 'ps'],
|
||||
capture_output=True,
|
||||
text=True,
|
||||
timeout=5,
|
||||
encoding='utf-8',
|
||||
errors='replace'
|
||||
)
|
||||
|
||||
if result.returncode == 0:
|
||||
output = result.stdout
|
||||
# Remove (V) from name for comparison
|
||||
clean_name = model_name.replace(" (V)", "")
|
||||
full_path = self._model_paths.get(model_name, clean_name)
|
||||
|
||||
if clean_name in output or full_path in output:
|
||||
return True
|
||||
|
||||
name_parts = clean_name.replace('/', ' ').split()
|
||||
for part in name_parts:
|
||||
if len(part) > 4 and part in output:
|
||||
return True
|
||||
|
||||
return False
|
||||
return False
|
||||
except:
|
||||
return False
|
||||
|
||||
def wait_for_model_ready(self, model_name, max_wait=20):
|
||||
"""Waits until model is ready"""
|
||||
print(f"[TA-LoadOnRun] Verifying model is ready...")
|
||||
|
||||
for i in range(max_wait):
|
||||
if self.is_model_loaded(model_name):
|
||||
print(f"[TA-LoadOnRun] ✓ Model verified after {i+1}s")
|
||||
return True
|
||||
|
||||
if i == 0 or (i+1) % 5 == 0:
|
||||
print(f"[TA-LoadOnRun] Checking... ({i+1}/{max_wait}s)")
|
||||
|
||||
time.sleep(1)
|
||||
|
||||
print(f"[TA-LoadOnRun] ⚠ Could not verify model after {max_wait}s")
|
||||
return False
|
||||
|
||||
def load_model(self, display_name, context_length, wait_time, skip_unload):
|
||||
"""Loads the model"""
|
||||
# Remove (V) for the actual load command
|
||||
clean_name = display_name.replace(" (V)", "")
|
||||
full_path = self._model_paths.get(display_name, clean_name)
|
||||
|
||||
print(f"[TA-LoadOnRun] === LOADING MODEL ===")
|
||||
print(f"[TA-LoadOnRun] Display: {display_name}")
|
||||
print(f"[TA-LoadOnRun] Path: {full_path}")
|
||||
print(f"[TA-LoadOnRun] Wait time: {wait_time}s")
|
||||
|
||||
try:
|
||||
# Try to unload (optional)
|
||||
if not skip_unload:
|
||||
unload_ok = self.try_unload()
|
||||
if unload_ok:
|
||||
time.sleep(2)
|
||||
else:
|
||||
print(f"[TA-LoadOnRun] Continuing despite unload issues...")
|
||||
time.sleep(1)
|
||||
else:
|
||||
print(f"[TA-LoadOnRun] Skipping unload (skip_unload=True)")
|
||||
|
||||
# Load model
|
||||
load_cmd = [
|
||||
'lms', 'load', full_path, '-y',
|
||||
f'--context-length={context_length}',
|
||||
'--gpu=1'
|
||||
]
|
||||
|
||||
print(f"[TA-LoadOnRun] Loading: {' '.join(load_cmd)}")
|
||||
|
||||
result = subprocess.run(
|
||||
load_cmd,
|
||||
capture_output=True,
|
||||
text=True,
|
||||
timeout=120,
|
||||
encoding='utf-8',
|
||||
errors='replace'
|
||||
)
|
||||
|
||||
print(f"[TA-LoadOnRun] Return code: {result.returncode}")
|
||||
|
||||
if result.returncode == 0:
|
||||
print(f"[TA-LoadOnRun] ✓ Load command completed")
|
||||
|
||||
# Warning for too short wait_time
|
||||
if wait_time < 3:
|
||||
print(f"[TA-LoadOnRun] ⚠ WARNING: wait_time={wait_time}s is too short!")
|
||||
print(f"[TA-LoadOnRun] ⚠ Recommended: 8-10s for reliable loading")
|
||||
|
||||
print(f"[TA-LoadOnRun] Waiting {wait_time}s for initialization...")
|
||||
time.sleep(wait_time)
|
||||
|
||||
# Verify
|
||||
if self.wait_for_model_ready(display_name, max_wait=15):
|
||||
print(f"[TA-LoadOnRun] ✓✓✓ MODEL READY! ✓✓✓")
|
||||
return True, "Loaded and ready"
|
||||
else:
|
||||
print(f"[TA-LoadOnRun] ⚠ Load completed but verification failed")
|
||||
print(f"[TA-LoadOnRun] ⚠ Model might still work, trying anyway...")
|
||||
return True, "Loaded (not verified)"
|
||||
else:
|
||||
print(f"[TA-LoadOnRun] ✗ Load failed with code {result.returncode}")
|
||||
if result.stderr:
|
||||
print(f"[TA-LoadOnRun] Error: {result.stderr[:300]}")
|
||||
return False, f"Load failed (code {result.returncode})"
|
||||
|
||||
except subprocess.TimeoutExpired:
|
||||
print("[TA-LoadOnRun] ✗ Load timeout (>120s)")
|
||||
return False, "Timeout"
|
||||
except Exception as e:
|
||||
print(f"[TA-LoadOnRun] ✗ Error: {e}")
|
||||
return False, f"Error: {str(e)}"
|
||||
|
||||
def load_and_return(self, model, context_length, wait_time, skip_unload):
|
||||
"""Executed on RUN"""
|
||||
|
||||
# Warning for too short wait_time
|
||||
if wait_time < 3:
|
||||
print(f"\n{'!'*60}")
|
||||
print(f"[TA-LoadOnRun] ⚠⚠⚠ WARNING ⚠⚠⚠")
|
||||
print(f"[TA-LoadOnRun] wait_time={wait_time}s is TOO SHORT!")
|
||||
print(f"[TA-LoadOnRun] This may cause 'Model not loaded' errors!")
|
||||
print(f"[TA-LoadOnRun] RECOMMENDED: Set wait_time to 8-10s")
|
||||
print(f"{'!'*60}\n")
|
||||
|
||||
# API name (remove (V))
|
||||
clean_model = model.replace(" (V)", "")
|
||||
if '/' in clean_model:
|
||||
api_name = clean_model.split('/')[-1]
|
||||
else:
|
||||
api_name = clean_model
|
||||
|
||||
print(f"\n{'='*60}")
|
||||
print(f"[TA-LoadOnRun] ===== WORKFLOW EXECUTION =====")
|
||||
print(f"[TA-LoadOnRun] Model: {model}")
|
||||
print(f"[TA-LoadOnRun] Wait time: {wait_time}s")
|
||||
print(f"[TA-LoadOnRun] Skip unload: {skip_unload}")
|
||||
print(f"{'='*60}\n")
|
||||
|
||||
# Load model
|
||||
success, status = self.load_model(model, context_length, wait_time, skip_unload)
|
||||
|
||||
if success:
|
||||
print(f"\n[TA-LoadOnRun] ✓ READY FOR VISION NODE\n")
|
||||
else:
|
||||
print(f"\n[TA-LoadOnRun] ✗ LOAD FAILED\n")
|
||||
|
||||
return (api_name, status)
|
||||
|
||||
|
||||
# Node Registration
|
||||
NODE_CLASS_MAPPINGS = {
|
||||
"TALMStudioLoadOnRun": TALMStudioLoadOnRun,
|
||||
}
|
||||
|
||||
NODE_DISPLAY_NAME_MAPPINGS = {
|
||||
"TALMStudioLoadOnRun": "TA LMStudio Load (On Run)",
|
||||
}
|
||||
@@ -1,192 +0,0 @@
|
||||
"""
|
||||
TA LMStudio Model Selector Node
|
||||
Shows available LM Studio models in a dropdown for selection
|
||||
"""
|
||||
|
||||
import subprocess
|
||||
|
||||
|
||||
class TALMStudioModelSelector:
|
||||
"""
|
||||
Node for selecting LM Studio models from a dropdown
|
||||
Lists all installed models
|
||||
"""
|
||||
|
||||
@classmethod
|
||||
def INPUT_TYPES(cls):
|
||||
models = cls.get_available_models()
|
||||
|
||||
return {
|
||||
"required": {
|
||||
"model": (models, {
|
||||
"default": models[0] if models else "llava-v1.5"
|
||||
}),
|
||||
},
|
||||
"optional": {
|
||||
"refresh": ("BOOLEAN", {
|
||||
"default": False,
|
||||
}),
|
||||
}
|
||||
}
|
||||
|
||||
RETURN_TYPES = ("STRING",)
|
||||
RETURN_NAMES = ("model_name",)
|
||||
FUNCTION = "select_model"
|
||||
CATEGORY = "TA-Nodes/LMStudio"
|
||||
|
||||
@classmethod
|
||||
def get_available_models(cls):
|
||||
"""
|
||||
Retrieves list of all available LM Studio models
|
||||
"""
|
||||
try:
|
||||
result = subprocess.run(
|
||||
['lms', 'ls', '--detailed'],
|
||||
capture_output=True,
|
||||
text=True,
|
||||
timeout=5
|
||||
)
|
||||
|
||||
if result.returncode == 0:
|
||||
models = []
|
||||
for line in result.stdout.split('\n'):
|
||||
line = line.strip()
|
||||
if line.startswith('/'):
|
||||
model_path = line.split()[0].lstrip('/')
|
||||
model_name = model_path.split('/')[-1] if '/' in model_path else model_path
|
||||
models.append(model_name)
|
||||
|
||||
if models:
|
||||
models.sort(key=str.lower) # Case-insensitive alphabetisch sortieren
|
||||
print(f"[TA-ModelSelector] Found {len(models)} models")
|
||||
return models
|
||||
else:
|
||||
print("[TA-ModelSelector] No models found, using defaults")
|
||||
return cls.get_default_models()
|
||||
else:
|
||||
print("[TA-ModelSelector] lms command failed, using defaults")
|
||||
return cls.get_default_models()
|
||||
|
||||
except FileNotFoundError:
|
||||
print("[TA-ModelSelector] lms CLI not found, using defaults")
|
||||
return cls.get_default_models()
|
||||
except Exception as e:
|
||||
print(f"[TA-ModelSelector] Error: {e}, using defaults")
|
||||
return cls.get_default_models()
|
||||
|
||||
@classmethod
|
||||
def get_default_models(cls):
|
||||
"""
|
||||
Fallback: Standard vision models
|
||||
"""
|
||||
models = [
|
||||
"llava-v1.5",
|
||||
"qwen2-vl-7b-instruct",
|
||||
"pixtral-12b",
|
||||
"minicpm-v-2.6",
|
||||
"gemma-3-27b-it",
|
||||
]
|
||||
models.sort(key=str.lower) # Case-insensitive alphabetisch sortieren
|
||||
return models
|
||||
|
||||
@classmethod
|
||||
def IS_CHANGED(cls, model, refresh=False):
|
||||
if refresh:
|
||||
return float("nan")
|
||||
return model
|
||||
|
||||
def select_model(self, model, refresh=False):
|
||||
print(f"[TA-ModelSelector] Selected model: {model}")
|
||||
return (model,)
|
||||
|
||||
|
||||
class TALMStudioLoadedModels:
|
||||
"""
|
||||
Node that displays CURRENTLY LOADED models in LM Studio
|
||||
"""
|
||||
|
||||
@classmethod
|
||||
def INPUT_TYPES(cls):
|
||||
loaded = cls.get_loaded_models()
|
||||
|
||||
return {
|
||||
"required": {
|
||||
"model": (loaded, {
|
||||
"default": loaded[0] if loaded else "no-model-loaded"
|
||||
}),
|
||||
},
|
||||
"optional": {
|
||||
"refresh": ("BOOLEAN", {
|
||||
"default": False
|
||||
}),
|
||||
}
|
||||
}
|
||||
|
||||
RETURN_TYPES = ("STRING",)
|
||||
RETURN_NAMES = ("model_name",)
|
||||
FUNCTION = "select_model"
|
||||
CATEGORY = "TA-Nodes/LMStudio"
|
||||
|
||||
@classmethod
|
||||
def get_loaded_models(cls):
|
||||
"""
|
||||
Retrieves list of CURRENTLY LOADED models
|
||||
"""
|
||||
try:
|
||||
result = subprocess.run(
|
||||
['lms', 'ps'],
|
||||
capture_output=True,
|
||||
text=True,
|
||||
timeout=5
|
||||
)
|
||||
|
||||
if result.returncode == 0:
|
||||
models = []
|
||||
lines = result.stdout.split('\n')
|
||||
|
||||
for line in lines:
|
||||
line = line.strip()
|
||||
if not line or 'Currently loaded' in line or line.startswith('-'):
|
||||
continue
|
||||
|
||||
parts = line.split()
|
||||
if parts:
|
||||
model_name = parts[0]
|
||||
models.append(model_name)
|
||||
|
||||
if models:
|
||||
models.sort(key=str.lower) # Case-insensitive alphabetisch sortieren
|
||||
print(f"[TA-LoadedModels] Currently loaded: {', '.join(models)}")
|
||||
return models
|
||||
else:
|
||||
return ["no-model-loaded"]
|
||||
else:
|
||||
return ["lms-error"]
|
||||
|
||||
except Exception as e:
|
||||
print(f"[TA-LoadedModels] Error: {e}")
|
||||
return ["error-checking-models"]
|
||||
|
||||
@classmethod
|
||||
def IS_CHANGED(cls, model, refresh=False):
|
||||
if refresh:
|
||||
return float("nan")
|
||||
return model
|
||||
|
||||
def select_model(self, model, refresh=False):
|
||||
if model == "no-model-loaded":
|
||||
print("[TA-LoadedModels] WARNING: No model is currently loaded in LM Studio!")
|
||||
else:
|
||||
print(f"[TA-LoadedModels] Using loaded model: {model}")
|
||||
return (model,)
|
||||
|
||||
|
||||
NODE_CLASS_MAPPINGS = {
|
||||
"TALMStudioModelSelector": TALMStudioModelSelector,
|
||||
"TALMStudioLoadedModels": TALMStudioLoadedModels,
|
||||
}
|
||||
|
||||
NODE_DISPLAY_NAME_MAPPINGS = {
|
||||
"TALMStudioModelSelector": "TA LMStudio Model Selector (All Models)",
|
||||
"TALMStudioLoadedModels": "TA LMStudio Model Selector (Loaded Only)",
|
||||
}
|
||||
@@ -1,56 +0,0 @@
|
||||
import folder_paths
|
||||
import comfy.sd
|
||||
import os
|
||||
import torch
|
||||
|
||||
class TALoadCheckpointModelWithName:
|
||||
"""
|
||||
Loads a checkpoint model and additionally outputs the model name
|
||||
Compatible with PyTorch 2.8+
|
||||
"""
|
||||
|
||||
@classmethod
|
||||
def INPUT_TYPES(cls):
|
||||
return {
|
||||
"required": {
|
||||
"ckpt_name": (folder_paths.get_filename_list("checkpoints"),),
|
||||
}
|
||||
}
|
||||
|
||||
RETURN_TYPES = ("MODEL", "CLIP", "VAE", "STRING")
|
||||
RETURN_NAMES = ("model", "clip", "vae", "model_name")
|
||||
FUNCTION = "load_checkpoint"
|
||||
CATEGORY = "TA Nodes/loaders"
|
||||
|
||||
def load_checkpoint(self, ckpt_name):
|
||||
# Load the checkpoint
|
||||
ckpt_path = folder_paths.get_full_path("checkpoints", ckpt_name)
|
||||
|
||||
# PyTorch 2.8+ compatible loading with context manager
|
||||
with torch.inference_mode():
|
||||
out = comfy.sd.load_checkpoint_guess_config(
|
||||
ckpt_path,
|
||||
output_vae=True,
|
||||
output_clip=True,
|
||||
embedding_directory=folder_paths.get_folder_paths("embeddings")
|
||||
)
|
||||
|
||||
# Extract Model, CLIP and VAE
|
||||
model = out[0]
|
||||
clip = out[1]
|
||||
vae = out[2]
|
||||
|
||||
# Extract only the filename without path and extension
|
||||
model_name_only = os.path.splitext(os.path.basename(ckpt_name))[0]
|
||||
|
||||
# Return the cleaned model name as well
|
||||
return (model, clip, vae, model_name_only)
|
||||
|
||||
|
||||
NODE_CLASS_MAPPINGS = {
|
||||
"TALoadCheckpointModelWithName": TALoadCheckpointModelWithName
|
||||
}
|
||||
|
||||
NODE_DISPLAY_NAME_MAPPINGS = {
|
||||
"TALoadCheckpointModelWithName": "TA Load Checkpoint Model (with Name)"
|
||||
}
|
||||
@@ -1,58 +0,0 @@
|
||||
import folder_paths
|
||||
import comfy.sd
|
||||
import os
|
||||
import torch
|
||||
|
||||
class TALoadDiffusionModelWithName:
|
||||
"""
|
||||
Loads a diffusion model (UNet) and additionally outputs the model name
|
||||
Compatible with PyTorch 2.8+
|
||||
"""
|
||||
|
||||
@classmethod
|
||||
def INPUT_TYPES(cls):
|
||||
return {
|
||||
"required": {
|
||||
"unet_name": (folder_paths.get_filename_list("diffusion_models"),),
|
||||
"weight_dtype": (["default", "fp8_e4m3fn", "fp8_e5m2"], {"default": "default"}),
|
||||
}
|
||||
}
|
||||
|
||||
RETURN_TYPES = ("MODEL", "STRING")
|
||||
RETURN_NAMES = ("model", "model_name")
|
||||
FUNCTION = "load_unet"
|
||||
CATEGORY = "TA Nodes/loaders"
|
||||
|
||||
def load_unet(self, unet_name, weight_dtype):
|
||||
# Load the diffusion model (UNet)
|
||||
unet_path = folder_paths.get_full_path("diffusion_models", unet_name)
|
||||
|
||||
# Determine model_options based on weight_dtype
|
||||
model_options = {}
|
||||
if weight_dtype == "fp8_e4m3fn":
|
||||
model_options["weight_dtype"] = torch.float8_e4m3fn
|
||||
elif weight_dtype == "fp8_e5m2":
|
||||
model_options["weight_dtype"] = torch.float8_e5m2
|
||||
# "default" means no special options
|
||||
|
||||
# PyTorch 2.8+ compatible loading with context manager
|
||||
with torch.inference_mode():
|
||||
if model_options:
|
||||
model = comfy.sd.load_diffusion_model(unet_path, model_options=model_options)
|
||||
else:
|
||||
model = comfy.sd.load_diffusion_model(unet_path)
|
||||
|
||||
# Extract only the filename without path and extension
|
||||
model_name_only = os.path.splitext(os.path.basename(unet_name))[0]
|
||||
|
||||
# Return model and cleaned name
|
||||
return (model, model_name_only)
|
||||
|
||||
|
||||
NODE_CLASS_MAPPINGS = {
|
||||
"TALoadDiffusionModelWithName": TALoadDiffusionModelWithName
|
||||
}
|
||||
|
||||
NODE_DISPLAY_NAME_MAPPINGS = {
|
||||
"TALoadDiffusionModelWithName": "TA Load Diffusion Model (with Name)"
|
||||
}
|
||||
@@ -1,157 +0,0 @@
|
||||
import folder_paths
|
||||
import comfy.sd
|
||||
import os
|
||||
import logging
|
||||
import sys
|
||||
import traceback
|
||||
import io
|
||||
from contextlib import redirect_stderr, redirect_stdout
|
||||
|
||||
class TALoadGGUFModelWithName:
|
||||
"""
|
||||
Loads a GGUF model and additionally outputs the model name
|
||||
Silent version without debug output
|
||||
"""
|
||||
|
||||
@classmethod
|
||||
def INPUT_TYPES(cls):
|
||||
# Search for GGUF files in various directories
|
||||
unet_names = []
|
||||
|
||||
# Primary: unet_gguf directory
|
||||
try:
|
||||
unet_names = folder_paths.get_filename_list("unet_gguf")
|
||||
except:
|
||||
pass
|
||||
|
||||
# Fallback: unet directory with .gguf filter
|
||||
if not unet_names:
|
||||
try:
|
||||
all_files = folder_paths.get_filename_list("unet")
|
||||
unet_names = [x for x in all_files if x.endswith(".gguf")]
|
||||
except:
|
||||
pass
|
||||
|
||||
# Second fallback: diffusion_models with .gguf filter
|
||||
if not unet_names:
|
||||
try:
|
||||
all_files = folder_paths.get_filename_list("diffusion_models")
|
||||
unet_names = [x for x in all_files if x.endswith(".gguf")]
|
||||
except:
|
||||
pass
|
||||
|
||||
return {
|
||||
"required": {
|
||||
"unet_name": (unet_names if unet_names else ["No GGUF files found"],),
|
||||
}
|
||||
}
|
||||
|
||||
RETURN_TYPES = ("MODEL", "STRING")
|
||||
RETURN_NAMES = ("model", "model_name")
|
||||
FUNCTION = "load_unet"
|
||||
CATEGORY = "TA Nodes/loaders"
|
||||
TITLE = "TA Load GGUF Model (with Name)"
|
||||
|
||||
def load_unet(self, unet_name):
|
||||
# Try to find the file in various directories
|
||||
unet_path = None
|
||||
for folder_type in ["unet_gguf", "unet", "diffusion_models"]:
|
||||
try:
|
||||
potential_path = folder_paths.get_full_path(folder_type, unet_name)
|
||||
if potential_path and os.path.exists(potential_path):
|
||||
unet_path = potential_path
|
||||
break
|
||||
except:
|
||||
continue
|
||||
|
||||
if unet_path is None:
|
||||
raise FileNotFoundError(f"Could not find {unet_name} in any model directory")
|
||||
|
||||
gguf_node_path = os.path.join(folder_paths.base_path, "custom_nodes", "ComfyUI-GGUF")
|
||||
model = None
|
||||
|
||||
# Method 1: Directly import the GGUF nodes.py (without output)
|
||||
try:
|
||||
if gguf_node_path not in sys.path:
|
||||
sys.path.insert(0, gguf_node_path)
|
||||
|
||||
# Suppress all output during import
|
||||
with redirect_stdout(io.StringIO()), redirect_stderr(io.StringIO()):
|
||||
try:
|
||||
from nodes import UnetLoaderGGUF
|
||||
loader = UnetLoaderGGUF()
|
||||
result = loader.load_unet(unet_name)
|
||||
model = result[0]
|
||||
except ImportError:
|
||||
# Alternative import method
|
||||
import importlib.util
|
||||
nodes_path = os.path.join(gguf_node_path, "nodes.py")
|
||||
if os.path.exists(nodes_path):
|
||||
spec = importlib.util.spec_from_file_location("gguf_nodes", nodes_path)
|
||||
gguf_nodes = importlib.util.module_from_spec(spec)
|
||||
spec.loader.exec_module(gguf_nodes)
|
||||
|
||||
if hasattr(gguf_nodes, 'UnetLoaderGGUF'):
|
||||
loader = gguf_nodes.UnetLoaderGGUF()
|
||||
result = loader.load_unet(unet_name)
|
||||
model = result[0]
|
||||
except:
|
||||
pass
|
||||
|
||||
# Method 2: Use the registered node (without output)
|
||||
if model is None:
|
||||
try:
|
||||
with redirect_stdout(io.StringIO()), redirect_stderr(io.StringIO()):
|
||||
from nodes import NODE_CLASS_MAPPINGS
|
||||
|
||||
if "UnetLoaderGGUF" in NODE_CLASS_MAPPINGS:
|
||||
loader_class = NODE_CLASS_MAPPINGS["UnetLoaderGGUF"]
|
||||
loader = loader_class()
|
||||
result = loader.load_unet(unet_name)
|
||||
model = result[0]
|
||||
except:
|
||||
pass
|
||||
|
||||
# Method 3: Try to import GGUF-specific modules (without output)
|
||||
if model is None:
|
||||
try:
|
||||
with redirect_stdout(io.StringIO()), redirect_stderr(io.StringIO()):
|
||||
sys.path.insert(0, gguf_node_path)
|
||||
|
||||
from gguf import GGUFReader
|
||||
from ops import GGMLOps, GGMLLayer, GGMLTensor
|
||||
from loader import gguf_sd_loader
|
||||
|
||||
ops = GGMLOps()
|
||||
sd = gguf_sd_loader(unet_path)
|
||||
|
||||
model = comfy.sd.load_diffusion_model_state_dict(
|
||||
sd, model_options={"custom_operations": ops}
|
||||
)
|
||||
except:
|
||||
pass
|
||||
|
||||
# If everything fails
|
||||
if model is None:
|
||||
error_msg = (
|
||||
f"Could not load GGUF model: {unet_name}\n\n"
|
||||
f"Please check:\n"
|
||||
f"1. ComfyUI-GGUF is properly installed\n"
|
||||
f"2. All dependencies are installed (gguf package)\n"
|
||||
f"3. The GGUF file is not corrupted"
|
||||
)
|
||||
raise RuntimeError(error_msg)
|
||||
|
||||
# Extract only the filename without path and extension
|
||||
model_name_only = os.path.splitext(os.path.basename(unet_name))[0]
|
||||
|
||||
return (model, model_name_only)
|
||||
|
||||
|
||||
NODE_CLASS_MAPPINGS = {
|
||||
"TALoadGGUFModelWithName": TALoadGGUFModelWithName
|
||||
}
|
||||
|
||||
NODE_DISPLAY_NAME_MAPPINGS = {
|
||||
"TALoadGGUFModelWithName": "TA Load GGUF Model (with Name)"
|
||||
}
|
||||
@@ -0,0 +1,307 @@
|
||||
"""
|
||||
================================================================================
|
||||
Node Name : TA Load Model (with Name)
|
||||
Created : 2025
|
||||
Modified : 2026-03-11
|
||||
Copyright : © 2026, Thomas Möhrling (thomo.ART)
|
||||
Version : 2.0
|
||||
--------------------------------------------------------------------------------
|
||||
Part of ComfyUI-TA-Nodes-Pack
|
||||
License : Apache 2.0
|
||||
|
||||
Description:
|
||||
Combined model loader for Diffusion Models, GGUF UNet models, and
|
||||
Checkpoints. Automatically detects the model type from the [D] / [G] / [C]
|
||||
prefix in the filename and routes to the appropriate loader. Returns the
|
||||
model, optional CLIP and VAE (checkpoints only), and the bare model name
|
||||
string as a TA_MODEL_NAME output.
|
||||
================================================================================
|
||||
"""
|
||||
|
||||
import folder_paths
|
||||
import comfy.sd
|
||||
import os
|
||||
import sys
|
||||
import io
|
||||
import torch
|
||||
from contextlib import redirect_stderr, redirect_stdout
|
||||
|
||||
|
||||
def _scan_models() -> list:
|
||||
"""
|
||||
Scans diffusion_models, unet/unet_gguf, and checkpoints directories and
|
||||
returns a sorted list of all discovered model filenames with type prefixes:
|
||||
|
||||
[D] diffusion_models (non-GGUF)
|
||||
[G] GGUF (unet_gguf / unet folder, .gguf extension)
|
||||
[C] checkpoints
|
||||
|
||||
The prefixes are used by TALoadModelWithName.load_model() to select the
|
||||
correct loading strategy without requiring separate node inputs.
|
||||
|
||||
Returns:
|
||||
list[str]: Sorted list of prefixed model name strings, e.g.
|
||||
['[C] v1-5-pruned.safetensors', '[D] flux1-dev.safetensors',
|
||||
'[G] flux1-Q4_K_S.gguf']. Returns ['No models found'] if
|
||||
no models are detected in any of the scanned directories.
|
||||
"""
|
||||
entries = []
|
||||
|
||||
# Diffusion models (non-GGUF)
|
||||
try:
|
||||
for name in folder_paths.get_filename_list("diffusion_models"):
|
||||
if not name.lower().endswith(".gguf"):
|
||||
entries.append(f"[D] {name}")
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
# GGUF: scan models/unet directly (folder_paths filters out .gguf files)
|
||||
try:
|
||||
unet_dirs = folder_paths.get_folder_paths("unet")
|
||||
for unet_dir in unet_dirs:
|
||||
if not os.path.isdir(unet_dir):
|
||||
continue
|
||||
for root, _, files in os.walk(unet_dir):
|
||||
for fname in files:
|
||||
if fname.lower().endswith(".gguf"):
|
||||
# Store path relative to the unet_dir as the model name
|
||||
rel = os.path.relpath(os.path.join(root, fname), unet_dir)
|
||||
entries.append(f"[G] {rel}")
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
# Checkpoints
|
||||
try:
|
||||
for name in folder_paths.get_filename_list("checkpoints"):
|
||||
entries.append(f"[C] {name}")
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
return sorted(entries) if entries else ["No models found"]
|
||||
|
||||
|
||||
def _load_gguf(unet_name: str):
|
||||
"""
|
||||
Loads a GGUF UNet model via the ComfyUI-GGUF custom node package.
|
||||
|
||||
Attempts three loading strategies in order, falling back to the next if
|
||||
the previous raises an exception:
|
||||
|
||||
1. Import UnetLoaderGGUF directly from the ComfyUI-GGUF nodes module.
|
||||
2. Look up 'UnetLoaderGGUF' in ComfyUI's global NODE_CLASS_MAPPINGS.
|
||||
3. Load the GGUF state dict manually via GGMLOps and gguf_sd_loader,
|
||||
then pass it to comfy.sd.load_diffusion_model_state_dict().
|
||||
|
||||
All stdout/stderr output from the GGUF loaders is suppressed to keep the
|
||||
ComfyUI console clean.
|
||||
|
||||
Args:
|
||||
unet_name (str): Relative path to the GGUF file within the unet folder,
|
||||
e.g. 'flux1-Q4_K_S.gguf'.
|
||||
|
||||
Returns:
|
||||
MODEL: Loaded ComfyUI model object.
|
||||
|
||||
Raises:
|
||||
FileNotFoundError: If the GGUF file cannot be located in any unet directory.
|
||||
RuntimeError: If all three loading strategies fail.
|
||||
"""
|
||||
gguf_node_path = os.path.join(
|
||||
folder_paths.base_path, "custom_nodes", "ComfyUI-GGUF"
|
||||
)
|
||||
model = None
|
||||
|
||||
# Resolve the absolute path to the GGUF file
|
||||
unet_path = None
|
||||
try:
|
||||
unet_dirs = folder_paths.get_folder_paths("unet")
|
||||
for unet_dir in unet_dirs:
|
||||
candidate = os.path.join(unet_dir, unet_name)
|
||||
if os.path.exists(candidate):
|
||||
unet_path = candidate
|
||||
break
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
if unet_path is None:
|
||||
raise FileNotFoundError(f"GGUF file not found: {unet_name}")
|
||||
|
||||
# Strategy 1: UnetLoaderGGUF from the ComfyUI-GGUF nodes module
|
||||
try:
|
||||
if gguf_node_path not in sys.path:
|
||||
sys.path.insert(0, gguf_node_path)
|
||||
with redirect_stdout(io.StringIO()), redirect_stderr(io.StringIO()):
|
||||
try:
|
||||
from nodes import UnetLoaderGGUF
|
||||
model = UnetLoaderGGUF().load_unet(unet_name)[0]
|
||||
except ImportError:
|
||||
import importlib.util
|
||||
nodes_path = os.path.join(gguf_node_path, "nodes.py")
|
||||
if os.path.exists(nodes_path):
|
||||
spec = importlib.util.spec_from_file_location("gguf_nodes", nodes_path)
|
||||
gguf_nodes = importlib.util.module_from_spec(spec)
|
||||
spec.loader.exec_module(gguf_nodes)
|
||||
if hasattr(gguf_nodes, "UnetLoaderGGUF"):
|
||||
model = gguf_nodes.UnetLoaderGGUF().load_unet(unet_name)[0]
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
# Strategy 2: NODE_CLASS_MAPPINGS lookup
|
||||
if model is None:
|
||||
try:
|
||||
with redirect_stdout(io.StringIO()), redirect_stderr(io.StringIO()):
|
||||
from nodes import NODE_CLASS_MAPPINGS
|
||||
if "UnetLoaderGGUF" in NODE_CLASS_MAPPINGS:
|
||||
model = NODE_CLASS_MAPPINGS["UnetLoaderGGUF"]().load_unet(unet_name)[0]
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
# Strategy 3: Direct GGUF module loading via absolute path
|
||||
if model is None:
|
||||
try:
|
||||
with redirect_stdout(io.StringIO()), redirect_stderr(io.StringIO()):
|
||||
from ops import GGMLOps
|
||||
from loader import gguf_sd_loader
|
||||
sd = gguf_sd_loader(unet_path)
|
||||
model = comfy.sd.load_diffusion_model_state_dict(
|
||||
sd, model_options={"custom_operations": GGMLOps()}
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
if model is None:
|
||||
raise RuntimeError(
|
||||
f"Could not load GGUF model: {unet_name}\n"
|
||||
"Check that ComfyUI-GGUF is installed and the gguf package is available."
|
||||
)
|
||||
return model
|
||||
|
||||
|
||||
class TALoadModelWithName:
|
||||
"""
|
||||
Combined model loader for Diffusion Models, GGUF UNet models, and Checkpoints.
|
||||
|
||||
Automatically detects the model type from the [D] / [G] / [C] prefix in the
|
||||
selected model_file string and routes to the appropriate loading strategy:
|
||||
|
||||
[D] comfy.sd.load_diffusion_model() – standard diffusion model
|
||||
[G] _load_gguf() – GGUF quantised UNet
|
||||
[C] comfy.sd.load_checkpoint_guess_config() – full checkpoint
|
||||
|
||||
Outputs:
|
||||
model – always present for all model types
|
||||
clip – populated for checkpoints only, None otherwise
|
||||
vae – populated for checkpoints only, None otherwise
|
||||
model_name – bare filename without path or extension (TA_MODEL_NAME type)
|
||||
"""
|
||||
|
||||
@classmethod
|
||||
def INPUT_TYPES(cls):
|
||||
"""
|
||||
Defines all input widgets shown in the ComfyUI node UI.
|
||||
|
||||
Returns:
|
||||
dict: ComfyUI INPUT_TYPES dictionary with all required inputs.
|
||||
"""
|
||||
return {
|
||||
"required": {
|
||||
"model_file": (_scan_models(),),
|
||||
"weight_dtype": (
|
||||
["auto", "fp8_e4m3fn", "fp8_e5m2"],
|
||||
{"default": "auto",
|
||||
"tooltip": "Relevant for Diffusion Models only. "
|
||||
"Auto = ComfyUI decides based on the model."},
|
||||
),
|
||||
}
|
||||
}
|
||||
|
||||
RETURN_TYPES = ("MODEL", "CLIP", "VAE", "TA_MODEL_NAME")
|
||||
RETURN_NAMES = ("model", "clip", "vae", "model_name")
|
||||
FUNCTION = "load_model"
|
||||
CATEGORY = "TA Nodes/loaders"
|
||||
|
||||
def load_model(self, model_file: str, weight_dtype: str):
|
||||
"""
|
||||
Loads the selected model file and returns its components.
|
||||
|
||||
Parses the [D] / [G] / [C] prefix to determine the model type, then
|
||||
delegates to the appropriate ComfyUI loader. For diffusion models the
|
||||
weight_dtype option is applied when set to fp8_e4m3fn or fp8_e5m2.
|
||||
CLIP and VAE outputs are only populated for checkpoint models.
|
||||
|
||||
Args:
|
||||
model_file (str): Prefixed model name string as produced by
|
||||
_scan_models(), e.g. '[D] flux1-dev.safetensors'.
|
||||
weight_dtype (str): Weight precision override for diffusion models.
|
||||
One of 'auto', 'fp8_e4m3fn', or 'fp8_e5m2'.
|
||||
|
||||
Returns:
|
||||
tuple: (model, clip, vae, model_name_only) where:
|
||||
- model : loaded ComfyUI MODEL object
|
||||
- clip : CLIP object (checkpoints) or None
|
||||
- vae : VAE object (checkpoints) or None
|
||||
- model_name_only : bare filename string without path/extension
|
||||
|
||||
Raises:
|
||||
ValueError: If model_file does not start with a recognised prefix.
|
||||
"""
|
||||
# Separate prefix from actual filename
|
||||
if model_file.startswith("[D] "):
|
||||
kind = "diffusion"
|
||||
name = model_file[4:]
|
||||
elif model_file.startswith("[G] "):
|
||||
kind = "gguf"
|
||||
name = model_file[4:]
|
||||
elif model_file.startswith("[C] "):
|
||||
kind = "checkpoint"
|
||||
name = model_file[4:]
|
||||
else:
|
||||
raise ValueError(f"[TALoadModelWithName] Unknown format: '{model_file}'")
|
||||
|
||||
model = clip = vae = None
|
||||
|
||||
# --- Diffusion Model ---
|
||||
if kind == "diffusion":
|
||||
unet_path = folder_paths.get_full_path("diffusion_models", name)
|
||||
model_options = {}
|
||||
if weight_dtype == "fp8_e4m3fn":
|
||||
model_options["weight_dtype"] = torch.float8_e4m3fn
|
||||
elif weight_dtype == "fp8_e5m2":
|
||||
model_options["weight_dtype"] = torch.float8_e5m2
|
||||
|
||||
with torch.inference_mode():
|
||||
if model_options:
|
||||
model = comfy.sd.load_diffusion_model(unet_path, model_options=model_options)
|
||||
else:
|
||||
model = comfy.sd.load_diffusion_model(unet_path)
|
||||
|
||||
# --- GGUF ---
|
||||
elif kind == "gguf":
|
||||
model = _load_gguf(name)
|
||||
|
||||
# --- Checkpoint ---
|
||||
elif kind == "checkpoint":
|
||||
ckpt_path = folder_paths.get_full_path("checkpoints", name)
|
||||
with torch.inference_mode():
|
||||
out = comfy.sd.load_checkpoint_guess_config(
|
||||
ckpt_path,
|
||||
output_vae=True,
|
||||
output_clip=True,
|
||||
embedding_directory=folder_paths.get_folder_paths("embeddings"),
|
||||
)
|
||||
model = out[0]
|
||||
clip = out[1]
|
||||
vae = out[2]
|
||||
|
||||
model_name_only = os.path.splitext(os.path.basename(name))[0]
|
||||
print(f"[TALoadModelWithName] Loaded: [{kind.upper()}] '{model_name_only}'")
|
||||
return (model, clip, vae, model_name_only)
|
||||
|
||||
|
||||
NODE_CLASS_MAPPINGS = {
|
||||
"TALoadModelWithName": TALoadModelWithName
|
||||
}
|
||||
|
||||
NODE_DISPLAY_NAME_MAPPINGS = {
|
||||
"TALoadModelWithName": "TA Load Model (with Name)"
|
||||
}
|
||||
@@ -0,0 +1,6 @@
|
||||
{
|
||||
"choices": [
|
||||
"Model-Presets",
|
||||
"Model-Loader 1"
|
||||
]
|
||||
}
|
||||
@@ -0,0 +1,52 @@
|
||||
[
|
||||
{
|
||||
"name": "ZImage (BF16)",
|
||||
"model_file": "[D] ZIMAGE/z_image_turbo_bf16.safetensors",
|
||||
"clip_name_1": "ZIMAGE/qwen_3_4b_bf16.safetensors",
|
||||
"clip_name_2": "",
|
||||
"clip_type": "lumina2",
|
||||
"clip_device": "default",
|
||||
"vae_name": "ZIMAGE/zImage_vae.safetensors",
|
||||
"shift": "3.10"
|
||||
},
|
||||
{
|
||||
"name": "Qwen Diffusion",
|
||||
"model_file": "[D] QWEN/qwen_image_fp8_e4m3fn.safetensors",
|
||||
"clip_name_1": "QWEN/qwen_2.5_vl_7b_fp8_scaled.safetensors",
|
||||
"clip_name_2": "",
|
||||
"clip_type": "qwen_image",
|
||||
"clip_device": "default",
|
||||
"vae_name": "QWEN/qwen_image_vae.safetensors",
|
||||
"shift": "",
|
||||
"weight_dtype": "fp8_e4m3fn"
|
||||
},
|
||||
{
|
||||
"name": "FLUX Dev (FP8)",
|
||||
"model_file": "[D] FLUX/flux1-dev-fp8.safetensors",
|
||||
"clip_name_1": "FLUX/t5xxl_fp8_e4m3fn.safetensors",
|
||||
"clip_name_2": "FLUX/clip_l.safetensors",
|
||||
"clip_type": "flux",
|
||||
"clip_device": "default",
|
||||
"vae_name": "FLUX/FLUX_VAE.safetensors"
|
||||
},
|
||||
{
|
||||
"name": "SDXL (Juggernaut)",
|
||||
"model_file": "[C] SDXL/juggernautXL_ragnarokBy.safetensors",
|
||||
"clip_name_1": "",
|
||||
"clip_name_2": "",
|
||||
"clip_type": "auto",
|
||||
"clip_device": "default",
|
||||
"vae_name": ""
|
||||
},
|
||||
{
|
||||
"name": "ACE",
|
||||
"model_file": "[D] ACE/acestep_v1.5_merge_sft_turbo_ta_0.5.safetensors",
|
||||
"clip_name_1": "ACE/qwen_0.6b_ace15.safetensors",
|
||||
"clip_name_2": "ACE/qwen_4b_ace15.safetensors",
|
||||
"clip_type": "ace",
|
||||
"clip_device": "default",
|
||||
"vae_name": "ACE/ace_1.5_vae.safetensors",
|
||||
"weight_dtype": "auto",
|
||||
"shift": ""
|
||||
}
|
||||
]
|
||||
@@ -0,0 +1,702 @@
|
||||
"""
|
||||
================================================================================
|
||||
Node Name : TA Model Presets
|
||||
Created : 2025
|
||||
Modified : 2026-03-11
|
||||
Copyright : © 2026, Thomas Möhrling (thomo.ART)
|
||||
Version : 2.0
|
||||
--------------------------------------------------------------------------------
|
||||
Part of ComfyUI-TA-Nodes-Pack
|
||||
License : Apache 2.0
|
||||
|
||||
Description:
|
||||
Preset-based model loader. Loads Model, CLIP (single or dual for FLUX/SDXL)
|
||||
and VAE from a named preset defined in ta_model_presets.json. Supports
|
||||
Diffusion Models [D], GGUF UNet models [G], and full Checkpoints [C].
|
||||
Includes a browser-based preset editor at:
|
||||
http://localhost:8188/ta_model_presets/ui
|
||||
================================================================================
|
||||
"""
|
||||
|
||||
import folder_paths
|
||||
import comfy.sd
|
||||
import comfy.utils
|
||||
import os
|
||||
import sys
|
||||
import io
|
||||
import json
|
||||
import torch
|
||||
from contextlib import redirect_stderr, redirect_stdout
|
||||
from aiohttp import web
|
||||
from server import PromptServer
|
||||
|
||||
# ──────────────────────────────────────────────
|
||||
# Paths
|
||||
# ──────────────────────────────────────────────
|
||||
_THIS_DIR = os.path.dirname(os.path.abspath(__file__))
|
||||
_PRESETS_FILE = os.path.join(_THIS_DIR, "ta_model_presets.json")
|
||||
_HTML_PATH = os.path.join(_THIS_DIR, "web", "js", "ta_model_presets_ui.html")
|
||||
|
||||
_DEFAULT_PRESETS = [
|
||||
{
|
||||
"name": "ZImage (BF16)",
|
||||
"model_file": "[D] ZIMAGE/z_image_turbo_bf16.safetensors",
|
||||
"clip_name_1": "ZIMAGE/qwen_3_4b_bf16.safetensors",
|
||||
"clip_name_2": "",
|
||||
"clip_type": "lumina2",
|
||||
"clip_device": "default",
|
||||
"vae_name": "ZIMAGE/zImage_vae.safetensors",
|
||||
"shift": 3.0,
|
||||
"weight_dtype": "auto"
|
||||
},
|
||||
{
|
||||
"name": "FLUX Dev (FP8)",
|
||||
"model_file": "[D] FLUX/flux1-dev-fp8.safetensors",
|
||||
"clip_name_1": "FLUX/t5xxl_fp8_e4m3fn.safetensors",
|
||||
"clip_name_2": "FLUX/clip_l.safetensors",
|
||||
"clip_type": "flux",
|
||||
"clip_device": "default",
|
||||
"vae_name": "FLUX/FLUX_VAE.safetensors",
|
||||
"shift": "",
|
||||
"weight_dtype": "fp8_e4m3fn"
|
||||
},
|
||||
{
|
||||
"name": "SDXL Checkpoint",
|
||||
"model_file": "[C] SDXL/sdxl_base.safetensors",
|
||||
"clip_name_1": "",
|
||||
"clip_name_2": "",
|
||||
"clip_type": "auto",
|
||||
"clip_device": "default",
|
||||
"vae_name": "",
|
||||
"shift": "",
|
||||
"weight_dtype": "auto"
|
||||
}
|
||||
]
|
||||
|
||||
# Map clip_type string → ComfyUI internal CLIPType enum constant.
|
||||
# Built dynamically from the CLIPType enum so it stays current across ComfyUI versions.
|
||||
def _build_clip_type_map() -> dict:
|
||||
"""
|
||||
Builds a mapping from lowercase clip_type name strings to ComfyUI CLIPType
|
||||
enum members. 'auto' is mapped to None (caller decides the default).
|
||||
Common aliases (sdxl, sd1) are added for the stable_diffusion enum member
|
||||
if present, so preset files can use short names without breaking.
|
||||
|
||||
Returns:
|
||||
dict: Mapping of {str: CLIPType | None}.
|
||||
"""
|
||||
mapping = {"auto": None}
|
||||
try:
|
||||
for member in comfy.sd.CLIPType:
|
||||
key = member.name.lower()
|
||||
mapping[key] = member
|
||||
except Exception:
|
||||
pass
|
||||
# Aliases for common short names
|
||||
if "stable_diffusion" in mapping:
|
||||
mapping.setdefault("sdxl", mapping["stable_diffusion"])
|
||||
mapping.setdefault("sd1", mapping["stable_diffusion"])
|
||||
return mapping
|
||||
|
||||
_CLIP_TYPE_MAP = _build_clip_type_map()
|
||||
|
||||
|
||||
def _get_clip_type_names() -> list:
|
||||
"""
|
||||
Returns all available CLIPType names as lowercase strings, prefixed with
|
||||
'auto'. Used to populate the clip_type dropdown in the browser editor.
|
||||
|
||||
Returns:
|
||||
list[str]: List of clip type name strings, e.g. ['auto', 'flux', 'stable_diffusion', ...].
|
||||
"""
|
||||
names = ["auto"]
|
||||
try:
|
||||
for member in comfy.sd.CLIPType:
|
||||
names.append(member.name.lower())
|
||||
except Exception:
|
||||
pass
|
||||
return names
|
||||
|
||||
|
||||
def _normalize(path: str) -> str:
|
||||
"""
|
||||
Normalizes path separators to forward slashes for cross-platform consistency.
|
||||
|
||||
Args:
|
||||
path (str): File path string, potentially containing backslashes (Windows).
|
||||
|
||||
Returns:
|
||||
str: Path string with all backslashes replaced by forward slashes.
|
||||
"""
|
||||
return path.replace("\\", "/")
|
||||
|
||||
|
||||
# ──────────────────────────────────────────────
|
||||
# JSON helpers
|
||||
# ──────────────────────────────────────────────
|
||||
def _ensure_presets_file() -> list:
|
||||
"""
|
||||
Ensures ta_model_presets.json exists and returns its contents as a list.
|
||||
|
||||
If the file does not exist it is created with _DEFAULT_PRESETS. If the file
|
||||
exists but is empty, invalid JSON, or not a list, _DEFAULT_PRESETS is
|
||||
returned as a safe fallback without modifying the file.
|
||||
|
||||
Returns:
|
||||
list[dict]: List of preset dictionaries loaded from file, or
|
||||
_DEFAULT_PRESETS on any error.
|
||||
"""
|
||||
if not os.path.exists(_PRESETS_FILE):
|
||||
try:
|
||||
with open(_PRESETS_FILE, "w", encoding="utf-8") as f:
|
||||
json.dump(_DEFAULT_PRESETS, f, indent=2, ensure_ascii=False)
|
||||
print(f"[TAModelPreset] ta_model_presets.json created with {len(_DEFAULT_PRESETS)} example presets.")
|
||||
except Exception as e:
|
||||
print(f"[TAModelPreset] Could not create ta_model_presets.json: {e}")
|
||||
return _DEFAULT_PRESETS
|
||||
|
||||
try:
|
||||
with open(_PRESETS_FILE, "r", encoding="utf-8") as f:
|
||||
data = json.load(f)
|
||||
if isinstance(data, list) and data:
|
||||
return data
|
||||
return _DEFAULT_PRESETS
|
||||
except Exception as e:
|
||||
print(f"[TAModelPreset] Error reading ta_model_presets.json: {e}")
|
||||
return _DEFAULT_PRESETS
|
||||
|
||||
|
||||
def _save_presets(presets: list) -> None:
|
||||
"""
|
||||
Serializes the given list of preset dicts to ta_model_presets.json.
|
||||
|
||||
Args:
|
||||
presets (list[dict]): List of preset dictionaries to persist.
|
||||
"""
|
||||
with open(_PRESETS_FILE, "w", encoding="utf-8") as f:
|
||||
json.dump(presets, f, indent=2, ensure_ascii=False)
|
||||
|
||||
|
||||
def _preset_names() -> list:
|
||||
"""
|
||||
Returns the 'name' field of every preset in the presets file as a list.
|
||||
Falls back to 'Preset N' for entries without a name field.
|
||||
|
||||
Returns:
|
||||
list[str]: Ordered list of preset name strings.
|
||||
"""
|
||||
return [p.get("name", f"Preset {i}") for i, p in enumerate(_ensure_presets_file())]
|
||||
|
||||
|
||||
def _get_preset_by_name(name: str) -> dict | None:
|
||||
"""
|
||||
Looks up a preset dict by its 'name' field.
|
||||
|
||||
Args:
|
||||
name (str): Preset name to search for.
|
||||
|
||||
Returns:
|
||||
dict | None: Matching preset dict, or None if not found.
|
||||
"""
|
||||
for p in _ensure_presets_file():
|
||||
if p.get("name") == name:
|
||||
return p
|
||||
return None
|
||||
|
||||
|
||||
# ──────────────────────────────────────────────
|
||||
# Scan helpers – always forward slashes
|
||||
# ──────────────────────────────────────────────
|
||||
def _scan_model_files() -> list:
|
||||
"""
|
||||
Scans diffusion_models, unet (GGUF), and checkpoints directories and
|
||||
returns a sorted list of all discovered model filenames with type prefixes:
|
||||
|
||||
[D] diffusion_models (non-GGUF)
|
||||
[G] GGUF (.gguf files in the unet folder)
|
||||
[C] checkpoints
|
||||
|
||||
All paths use forward slashes for cross-platform consistency.
|
||||
|
||||
Returns:
|
||||
list[str]: Sorted list of prefixed model name strings.
|
||||
"""
|
||||
entries = []
|
||||
try:
|
||||
for name in folder_paths.get_filename_list("diffusion_models"):
|
||||
if not name.lower().endswith(".gguf"):
|
||||
entries.append(f"[D] {_normalize(name)}")
|
||||
except Exception:
|
||||
pass
|
||||
try:
|
||||
unet_dirs = folder_paths.get_folder_paths("unet")
|
||||
for unet_dir in unet_dirs:
|
||||
if not os.path.isdir(unet_dir):
|
||||
continue
|
||||
for root, _, files in os.walk(unet_dir):
|
||||
for fname in files:
|
||||
if fname.lower().endswith(".gguf"):
|
||||
rel = os.path.relpath(os.path.join(root, fname), unet_dir)
|
||||
entries.append(f"[G] {_normalize(rel)}")
|
||||
except Exception:
|
||||
pass
|
||||
try:
|
||||
for name in folder_paths.get_filename_list("checkpoints"):
|
||||
entries.append(f"[C] {_normalize(name)}")
|
||||
except Exception:
|
||||
pass
|
||||
return sorted(entries)
|
||||
|
||||
|
||||
def _scan_clip_files() -> list:
|
||||
"""
|
||||
Scans the 'clip' and 'text_encoders' model directories and returns a
|
||||
sorted, deduplicated list of all found CLIP/text encoder filenames.
|
||||
All paths use forward slashes.
|
||||
|
||||
Returns:
|
||||
list[str]: Sorted list of CLIP model filename strings.
|
||||
"""
|
||||
entries = []
|
||||
for folder in ["clip", "text_encoders"]:
|
||||
try:
|
||||
entries += [_normalize(n) for n in folder_paths.get_filename_list(folder)]
|
||||
except Exception:
|
||||
pass
|
||||
return sorted(set(entries))
|
||||
|
||||
|
||||
def _scan_vae_files() -> list:
|
||||
"""
|
||||
Scans the 'vae' model directory and returns a sorted list of all found
|
||||
VAE filenames. All paths use forward slashes.
|
||||
|
||||
Returns:
|
||||
list[str]: Sorted list of VAE filename strings, or [] on error.
|
||||
"""
|
||||
try:
|
||||
return sorted(_normalize(n) for n in folder_paths.get_filename_list("vae"))
|
||||
except Exception:
|
||||
return []
|
||||
|
||||
|
||||
# ──────────────────────────────────────────────
|
||||
# Web Endpoints
|
||||
# ──────────────────────────────────────────────
|
||||
@PromptServer.instance.routes.get("/ta_model_presets/ui")
|
||||
async def ta_presets_ui(request):
|
||||
"""
|
||||
Serves the browser-based preset editor HTML page.
|
||||
|
||||
Route: GET /ta_model_presets/ui
|
||||
|
||||
Returns:
|
||||
web.Response: HTML page content, or a 404 response if the HTML file
|
||||
is not found at the expected path.
|
||||
"""
|
||||
if not os.path.exists(_HTML_PATH):
|
||||
return web.Response(text="HTML file not found.", status=404)
|
||||
with open(_HTML_PATH, "r", encoding="utf-8") as f:
|
||||
return web.Response(text=f.read(), content_type="text/html")
|
||||
|
||||
|
||||
@PromptServer.instance.routes.get("/ta_model_presets/list")
|
||||
async def ta_presets_list(request):
|
||||
"""
|
||||
Returns the full list of currently saved presets as JSON.
|
||||
|
||||
Route: GET /ta_model_presets/list
|
||||
|
||||
Returns:
|
||||
web.Response: JSON response with {'presets': [...]}.
|
||||
"""
|
||||
return web.json_response({"presets": _ensure_presets_file()})
|
||||
|
||||
|
||||
@PromptServer.instance.routes.get("/ta_model_presets/options")
|
||||
async def ta_presets_options(request):
|
||||
"""
|
||||
Returns all available model, CLIP, VAE, and clip_type options as JSON.
|
||||
Used by the browser editor to populate its dropdown menus.
|
||||
|
||||
Route: GET /ta_model_presets/options
|
||||
|
||||
Returns:
|
||||
web.Response: JSON response with {'models': [...], 'clips': [...],
|
||||
'vaes': [...], 'clip_types': [...]}.
|
||||
"""
|
||||
return web.json_response({
|
||||
"models": _scan_model_files(),
|
||||
"clips": _scan_clip_files(),
|
||||
"vaes": _scan_vae_files(),
|
||||
"clip_types": _get_clip_type_names(),
|
||||
})
|
||||
|
||||
|
||||
@PromptServer.instance.routes.post("/ta_model_presets/save")
|
||||
async def ta_presets_save(request):
|
||||
"""
|
||||
Accepts a JSON body with a 'presets' list and persists it to
|
||||
ta_model_presets.json. Entries without a non-empty 'name' field are
|
||||
filtered out before saving.
|
||||
|
||||
Route: POST /ta_model_presets/save
|
||||
Body: {'presets': [{...}, ...]}
|
||||
|
||||
Returns:
|
||||
web.Response: JSON response with {'ok': True} on success, or
|
||||
{'ok': False, 'error': str} on validation failure or exception.
|
||||
"""
|
||||
try:
|
||||
body = await request.json()
|
||||
presets = body.get("presets", [])
|
||||
presets = [p for p in presets if isinstance(p, dict) and p.get("name", "").strip()]
|
||||
if not presets:
|
||||
return web.json_response({"ok": False, "error": "No valid presets provided."})
|
||||
_save_presets(presets)
|
||||
print(f"[TAModelPreset] {len(presets)} preset(s) saved.")
|
||||
return web.json_response({"ok": True})
|
||||
except Exception as e:
|
||||
return web.json_response({"ok": False, "error": str(e)})
|
||||
|
||||
|
||||
# ──────────────────────────────────────────────
|
||||
# ModelSamplingAuraFlow Patch
|
||||
# ──────────────────────────────────────────────
|
||||
def _apply_auraflow_patch(model, shift: float):
|
||||
"""
|
||||
Applies the ModelSamplingAuraFlow patch to a model, equivalent to using
|
||||
the ComfyUI node of the same name. Used to set the sigma shift value for
|
||||
AuraFlow-based architectures (e.g. Z-Image-Turbo).
|
||||
|
||||
Looks up 'ModelSamplingAuraFlow' in NODE_CLASS_MAPPINGS and calls its
|
||||
patch_aura() method. If the node is not registered or the call fails,
|
||||
the original model is returned unmodified.
|
||||
|
||||
Args:
|
||||
model: ComfyUI MODEL object to patch.
|
||||
shift (float): Sigma shift value to apply.
|
||||
|
||||
Returns:
|
||||
MODEL: Patched model, or the original model if the patch could not
|
||||
be applied.
|
||||
"""
|
||||
try:
|
||||
from nodes import NODE_CLASS_MAPPINGS
|
||||
if "ModelSamplingAuraFlow" in NODE_CLASS_MAPPINGS:
|
||||
result = NODE_CLASS_MAPPINGS["ModelSamplingAuraFlow"]().patch_aura(model, shift)
|
||||
print(f"[TAModelPreset] ModelSamplingAuraFlow applied (shift={shift})")
|
||||
return result[0]
|
||||
else:
|
||||
print("[TAModelPreset] ModelSamplingAuraFlow not in NODE_CLASS_MAPPINGS – model unchanged")
|
||||
return model
|
||||
except Exception as e:
|
||||
print(f"[TAModelPreset] ModelSamplingAuraFlow error: {e} – model unchanged")
|
||||
return model
|
||||
|
||||
|
||||
# ──────────────────────────────────────────────
|
||||
# GGUF Loader
|
||||
# ──────────────────────────────────────────────
|
||||
def _load_gguf(unet_name: str):
|
||||
"""
|
||||
Loads a GGUF UNet model via the ComfyUI-GGUF custom node package.
|
||||
|
||||
Attempts three loading strategies in order, falling back to the next if
|
||||
the previous raises an exception:
|
||||
|
||||
1. Import UnetLoaderGGUF directly from the ComfyUI-GGUF nodes module.
|
||||
2. Look up 'UnetLoaderGGUF' in ComfyUI's global NODE_CLASS_MAPPINGS.
|
||||
3. Load the GGUF state dict manually via GGMLOps and gguf_sd_loader,
|
||||
then pass it to comfy.sd.load_diffusion_model_state_dict().
|
||||
|
||||
All stdout/stderr output from the GGUF loaders is suppressed.
|
||||
|
||||
Args:
|
||||
unet_name (str): Relative path to the GGUF file within the unet folder.
|
||||
|
||||
Returns:
|
||||
MODEL: Loaded ComfyUI model object.
|
||||
|
||||
Raises:
|
||||
FileNotFoundError: If the GGUF file cannot be located in any unet directory.
|
||||
RuntimeError: If all three loading strategies fail.
|
||||
"""
|
||||
gguf_node_path = os.path.join(
|
||||
folder_paths.base_path, "custom_nodes", "ComfyUI-GGUF"
|
||||
)
|
||||
model = None
|
||||
unet_path = None
|
||||
|
||||
try:
|
||||
unet_dirs = folder_paths.get_folder_paths("unet")
|
||||
for unet_dir in unet_dirs:
|
||||
candidate = os.path.join(unet_dir, unet_name)
|
||||
if os.path.exists(candidate):
|
||||
unet_path = candidate
|
||||
break
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
if unet_path is None:
|
||||
raise FileNotFoundError(f"GGUF file not found: {unet_name}")
|
||||
|
||||
# Strategy 1: UnetLoaderGGUF from the ComfyUI-GGUF nodes module
|
||||
try:
|
||||
if gguf_node_path not in sys.path:
|
||||
sys.path.insert(0, gguf_node_path)
|
||||
with redirect_stdout(io.StringIO()), redirect_stderr(io.StringIO()):
|
||||
try:
|
||||
from nodes import UnetLoaderGGUF
|
||||
model = UnetLoaderGGUF().load_unet(unet_name)[0]
|
||||
except ImportError:
|
||||
import importlib.util
|
||||
nodes_path = os.path.join(gguf_node_path, "nodes.py")
|
||||
if os.path.exists(nodes_path):
|
||||
spec = importlib.util.spec_from_file_location("gguf_nodes", nodes_path)
|
||||
gguf_nodes = importlib.util.module_from_spec(spec)
|
||||
spec.loader.exec_module(gguf_nodes)
|
||||
if hasattr(gguf_nodes, "UnetLoaderGGUF"):
|
||||
model = gguf_nodes.UnetLoaderGGUF().load_unet(unet_name)[0]
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
# Strategy 2: NODE_CLASS_MAPPINGS lookup
|
||||
if model is None:
|
||||
try:
|
||||
with redirect_stdout(io.StringIO()), redirect_stderr(io.StringIO()):
|
||||
from nodes import NODE_CLASS_MAPPINGS
|
||||
if "UnetLoaderGGUF" in NODE_CLASS_MAPPINGS:
|
||||
model = NODE_CLASS_MAPPINGS["UnetLoaderGGUF"]().load_unet(unet_name)[0]
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
# Strategy 3: Direct GGUF module loading via absolute path
|
||||
if model is None:
|
||||
try:
|
||||
with redirect_stdout(io.StringIO()), redirect_stderr(io.StringIO()):
|
||||
from ops import GGMLOps
|
||||
from loader import gguf_sd_loader
|
||||
sd = gguf_sd_loader(unet_path)
|
||||
model = comfy.sd.load_diffusion_model_state_dict(
|
||||
sd, model_options={"custom_operations": GGMLOps()}
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
if model is None:
|
||||
raise RuntimeError(
|
||||
f"Could not load GGUF model: {unet_name}\n"
|
||||
"Check that ComfyUI-GGUF is installed and the gguf package is available."
|
||||
)
|
||||
return model
|
||||
|
||||
|
||||
# ──────────────────────────────────────────────
|
||||
# CLIP Loader helper – uses ComfyUI's native CLIPLoader
|
||||
# ──────────────────────────────────────────────
|
||||
def _load_clip(clip_name_1: str, clip_name_2: str, clip_type: str):
|
||||
"""
|
||||
Loads a CLIP model using ComfyUI's native CLIPLoader or DualCLIPLoader node.
|
||||
|
||||
Selects the loader based on whether clip_name_2 is provided:
|
||||
- Single CLIP: CLIPLoader with clip_type (defaults to 'stable_diffusion'
|
||||
when 'auto' is specified).
|
||||
- Dual CLIP: DualCLIPLoader with clip_type (defaults to 'flux' when
|
||||
'auto' is specified).
|
||||
|
||||
Args:
|
||||
clip_name_1 (str): Primary CLIP / text encoder filename.
|
||||
clip_name_2 (str): Secondary CLIP filename for dual-CLIP setups (e.g. FLUX).
|
||||
Pass an empty string for single-CLIP models.
|
||||
clip_type (str): CLIP type string, e.g. 'flux', 'stable_diffusion', 'auto'.
|
||||
|
||||
Returns:
|
||||
CLIP | None: Loaded ComfyUI CLIP object, or None if the loader node is
|
||||
not available or an exception occurs.
|
||||
"""
|
||||
try:
|
||||
from nodes import NODE_CLASS_MAPPINGS as _NCM
|
||||
|
||||
ct = _CLIP_TYPE_MAP.get(clip_type.lower())
|
||||
|
||||
if clip_name_2:
|
||||
# Dual CLIP → DualCLIPLoader
|
||||
if "DualCLIPLoader" in _NCM:
|
||||
clip_type_name = clip_type.lower() if clip_type.lower() != "auto" else "flux"
|
||||
return _NCM["DualCLIPLoader"]().load_clip(clip_name_1, clip_name_2, clip_type_name)[0]
|
||||
else:
|
||||
print("[TAModelPreset] DualCLIPLoader not found")
|
||||
return None
|
||||
else:
|
||||
# Single CLIP → CLIPLoader
|
||||
if "CLIPLoader" in _NCM:
|
||||
clip_type_name = clip_type.lower() if clip_type.lower() != "auto" else "stable_diffusion"
|
||||
return _NCM["CLIPLoader"]().load_clip(clip_name_1, clip_type_name)[0]
|
||||
else:
|
||||
print("[TAModelPreset] CLIPLoader not found")
|
||||
return None
|
||||
except Exception as e:
|
||||
print(f"[TAModelPreset] CLIP load error: {e}")
|
||||
return None
|
||||
|
||||
|
||||
# ──────────────────────────────────────────────
|
||||
# Node
|
||||
# ──────────────────────────────────────────────
|
||||
class TAModelPreset:
|
||||
"""
|
||||
Preset-based model loader node for ComfyUI.
|
||||
|
||||
Loads Model, CLIP (single or dual for FLUX/SDXL), and VAE from a named
|
||||
preset defined in ta_model_presets.json. Supports Diffusion Models [D],
|
||||
GGUF UNet models [G], and full Checkpoints [C]. Optionally applies the
|
||||
ModelSamplingAuraFlow shift patch when a 'shift' value is set in the preset.
|
||||
|
||||
Browser-based preset editor: http://localhost:8188/ta_model_presets/ui
|
||||
"""
|
||||
|
||||
@classmethod
|
||||
def INPUT_TYPES(cls):
|
||||
"""
|
||||
Defines all input widgets shown in the ComfyUI node UI.
|
||||
|
||||
Reads the current preset names from ta_model_presets.json at node load
|
||||
time to populate the preset dropdown.
|
||||
|
||||
Returns:
|
||||
dict: ComfyUI INPUT_TYPES dictionary with the required preset input.
|
||||
"""
|
||||
names = _preset_names()
|
||||
return {
|
||||
"required": {
|
||||
"preset": (names, {
|
||||
"tooltip": "Editor: http://localhost:8188/ta_model_presets/ui"
|
||||
}),
|
||||
}
|
||||
}
|
||||
|
||||
RETURN_TYPES = ("MODEL", "CLIP", "VAE", "TA_MODEL_NAME")
|
||||
RETURN_NAMES = ("model", "clip", "vae", "model_name")
|
||||
FUNCTION = "load_preset"
|
||||
CATEGORY = "TA Nodes/loaders"
|
||||
|
||||
def load_preset(self, preset: str):
|
||||
"""
|
||||
Loads all model components defined by the selected preset.
|
||||
|
||||
Reads the preset from ta_model_presets.json, parses the [D]/[G]/[C]
|
||||
model_file prefix to select the loading strategy, then loads the model,
|
||||
CLIP (if not provided by a checkpoint), and VAE (if not provided by a
|
||||
checkpoint). Optionally applies the ModelSamplingAuraFlow shift patch
|
||||
if the preset includes a non-empty 'shift' value.
|
||||
|
||||
Args:
|
||||
preset (str): Name of the preset to load, as listed in the dropdown.
|
||||
|
||||
Returns:
|
||||
tuple: (model, clip, vae, model_name_only) where:
|
||||
- model : loaded ComfyUI MODEL object
|
||||
- clip : CLIP object or None
|
||||
- vae : VAE object or None
|
||||
- model_name_only : bare filename string without path/extension
|
||||
|
||||
Raises:
|
||||
ValueError: If the preset name is not found or model_file has an
|
||||
unrecognised prefix format.
|
||||
"""
|
||||
p = _get_preset_by_name(preset)
|
||||
if p is None:
|
||||
raise ValueError(f"[TAModelPreset] Preset '{preset}' not found.")
|
||||
|
||||
model_file = _normalize(p.get("model_file", ""))
|
||||
clip_name_1 = _normalize(p.get("clip_name_1", p.get("clip_name", "")))
|
||||
clip_name_2 = _normalize(p.get("clip_name_2", ""))
|
||||
vae_name = _normalize(p.get("vae_name", ""))
|
||||
clip_type = p.get("clip_type", "auto")
|
||||
clip_device = p.get("clip_device", "default")
|
||||
weight_dtype = p.get("weight_dtype", "auto")
|
||||
|
||||
if model_file.startswith("[D] "):
|
||||
kind = "diffusion"
|
||||
mname = model_file[4:]
|
||||
elif model_file.startswith("[G] "):
|
||||
kind = "gguf"
|
||||
mname = model_file[4:]
|
||||
elif model_file.startswith("[C] "):
|
||||
kind = "checkpoint"
|
||||
mname = model_file[4:]
|
||||
else:
|
||||
raise ValueError(f"[TAModelPreset] Unknown model_file format: '{model_file}'")
|
||||
|
||||
model = clip = vae = None
|
||||
|
||||
# ── Load model ──
|
||||
if kind == "diffusion":
|
||||
unet_path = folder_paths.get_full_path("diffusion_models", mname)
|
||||
model_options = {}
|
||||
if weight_dtype == "fp8_e4m3fn":
|
||||
model_options["weight_dtype"] = torch.float8_e4m3fn
|
||||
elif weight_dtype == "fp8_e5m2":
|
||||
model_options["weight_dtype"] = torch.float8_e5m2
|
||||
with torch.inference_mode():
|
||||
if model_options:
|
||||
model = comfy.sd.load_diffusion_model(unet_path, model_options=model_options)
|
||||
else:
|
||||
model = comfy.sd.load_diffusion_model(unet_path)
|
||||
|
||||
elif kind == "gguf":
|
||||
model = _load_gguf(mname)
|
||||
|
||||
elif kind == "checkpoint":
|
||||
# CLIP and VAE are bundled inside the checkpoint
|
||||
ckpt_path = folder_paths.get_full_path("checkpoints", mname)
|
||||
with torch.inference_mode():
|
||||
out = comfy.sd.load_checkpoint_guess_config(
|
||||
ckpt_path,
|
||||
output_vae=True,
|
||||
output_clip=True,
|
||||
embedding_directory=folder_paths.get_folder_paths("embeddings"),
|
||||
)
|
||||
model = out[0]
|
||||
clip = out[1]
|
||||
vae = out[2]
|
||||
|
||||
# ── Load CLIP (only if not already provided by a checkpoint) ──
|
||||
if clip is None and clip_name_1:
|
||||
clip = _load_clip(clip_name_1, clip_name_2, clip_type)
|
||||
|
||||
# ── Load VAE (only if not already provided by a checkpoint) ──
|
||||
if vae is None and vae_name:
|
||||
try:
|
||||
from nodes import NODE_CLASS_MAPPINGS as _NCM
|
||||
if "VAELoader" in _NCM:
|
||||
vae = _NCM["VAELoader"]().load_vae(vae_name)[0]
|
||||
else:
|
||||
print(f"[TAModelPreset] VAELoader not found")
|
||||
except Exception as e:
|
||||
print(f"[TAModelPreset] VAE load error: {e}")
|
||||
|
||||
model_name_only = os.path.splitext(os.path.basename(mname))[0]
|
||||
dual = " (Dual CLIP)" if clip_name_2 else ""
|
||||
|
||||
# ── ModelSamplingAuraFlow patch (optional) ──
|
||||
shift_raw = p.get("shift", "")
|
||||
if shift_raw != "" and shift_raw is not None:
|
||||
try:
|
||||
shift = float(shift_raw)
|
||||
model = _apply_auraflow_patch(model, shift)
|
||||
except (ValueError, TypeError):
|
||||
pass
|
||||
|
||||
print(f"[TAModelPreset] Loaded: Preset='{preset}' [{kind.upper()}]{dual} '{model_name_only}'")
|
||||
return (model, clip, vae, model_name_only)
|
||||
|
||||
|
||||
NODE_CLASS_MAPPINGS = {
|
||||
"TAModelPreset": TAModelPreset,
|
||||
}
|
||||
|
||||
NODE_DISPLAY_NAME_MAPPINGS = {
|
||||
"TAModelPreset": "TA Model Presets",
|
||||
}
|
||||
@@ -0,0 +1,143 @@
|
||||
"""
|
||||
================================================================================
|
||||
Node Name : TA Prompt Controller (Switch)
|
||||
Created : 2025
|
||||
Modified : 2026-03-11
|
||||
Copyright : © 2026, Thomas Möhrling (thomo.ART)
|
||||
Version : 2.0
|
||||
--------------------------------------------------------------------------------
|
||||
Part of ComfyUI-TA-Nodes-Pack
|
||||
License : Apache 2.0
|
||||
|
||||
Description:
|
||||
Controls the flow between a manually typed prompt and a generated prompt
|
||||
(e.g. from a VLM or LLM node). Supports five modes: pass-through of either
|
||||
source, two combine orders, or an empty output. Intended as a central
|
||||
prompt routing node in TA workflows.
|
||||
================================================================================
|
||||
"""
|
||||
|
||||
|
||||
class TAPromptController:
|
||||
"""
|
||||
Manages the flow between a generated prompt (e.g. from VLM/LLM) and manual
|
||||
input. Allows switching between sources or combining them in either order.
|
||||
|
||||
Five modes are available:
|
||||
- Manual Only: Returns manual_prompt unchanged.
|
||||
- Generated Only: Returns generated_prompt unchanged.
|
||||
- Combine: Manual + Generated: Joins manual then generated with delimiter.
|
||||
- Combine: Generated + Manual: Joins generated then manual with delimiter.
|
||||
- Clear / Empty: Returns an empty string regardless of inputs.
|
||||
|
||||
In Combine modes, if only one input is non-empty that value is returned
|
||||
without the delimiter.
|
||||
"""
|
||||
|
||||
@classmethod
|
||||
def INPUT_TYPES(cls):
|
||||
"""
|
||||
Defines all input widgets shown in the ComfyUI node UI.
|
||||
|
||||
Inputs:
|
||||
manual_prompt: Free-text prompt typed directly in the node widget.
|
||||
Supports dynamic prompts syntax.
|
||||
mode: Selects the output routing / combination strategy.
|
||||
delimiter: Separator string inserted between prompts in Combine
|
||||
modes. Defaults to ', '.
|
||||
generated_prompt: Optional STRING input from an upstream LLM/VLM node.
|
||||
Defaults to an empty string if not connected.
|
||||
|
||||
Returns:
|
||||
dict: ComfyUI INPUT_TYPES dictionary with required and optional inputs.
|
||||
"""
|
||||
return {
|
||||
"required": {
|
||||
"manual_prompt": ("STRING", {
|
||||
"default": "",
|
||||
"multiline": True,
|
||||
"dynamicPrompts": True,
|
||||
"placeholder": "Type here or convert to input..."
|
||||
}),
|
||||
"mode": ([
|
||||
"Manual Only",
|
||||
"Generated Only",
|
||||
"Combine: Manual + Generated",
|
||||
"Combine: Generated + Manual",
|
||||
"Clear / Empty"
|
||||
], {
|
||||
"default": "Manual Only"
|
||||
}),
|
||||
"delimiter": ("STRING", {
|
||||
"default": ", ",
|
||||
"multiline": False
|
||||
}),
|
||||
},
|
||||
"optional": {
|
||||
"generated_prompt": ("STRING", {
|
||||
"forceInput": True,
|
||||
"default": ""
|
||||
}),
|
||||
}
|
||||
}
|
||||
|
||||
RETURN_TYPES = ("STRING",)
|
||||
RETURN_NAMES = ("final_prompt",)
|
||||
FUNCTION = "process_prompt"
|
||||
CATEGORY = "TA Nodes/text"
|
||||
|
||||
def process_prompt(self, manual_prompt, mode, delimiter, generated_prompt=""):
|
||||
"""
|
||||
Routes or combines the input prompts according to the selected mode.
|
||||
|
||||
None values for either prompt input are treated as empty strings.
|
||||
In Combine modes the delimiter is only inserted when both inputs are
|
||||
non-empty; a single non-empty input is returned as-is.
|
||||
|
||||
Args:
|
||||
manual_prompt (str): Manually typed prompt string.
|
||||
mode (str): One of the five routing mode strings.
|
||||
delimiter (str): Separator inserted between prompts in Combine modes.
|
||||
generated_prompt (str): Prompt string from an upstream LLM/VLM node.
|
||||
Defaults to '' if not connected.
|
||||
|
||||
Returns:
|
||||
tuple[str]: Single-element tuple containing the final prompt string.
|
||||
"""
|
||||
if manual_prompt is None: manual_prompt = ""
|
||||
if generated_prompt is None: generated_prompt = ""
|
||||
|
||||
result = ""
|
||||
|
||||
if mode == "Manual Only":
|
||||
result = manual_prompt
|
||||
|
||||
elif mode == "Generated Only":
|
||||
result = generated_prompt
|
||||
|
||||
elif mode == "Combine: Manual + Generated":
|
||||
if manual_prompt and generated_prompt:
|
||||
result = f"{manual_prompt}{delimiter}{generated_prompt}"
|
||||
else:
|
||||
result = manual_prompt or generated_prompt
|
||||
|
||||
elif mode == "Combine: Generated + Manual":
|
||||
if manual_prompt and generated_prompt:
|
||||
result = f"{generated_prompt}{delimiter}{manual_prompt}"
|
||||
else:
|
||||
result = generated_prompt or manual_prompt
|
||||
|
||||
elif mode == "Clear / Empty":
|
||||
result = ""
|
||||
|
||||
return (result,)
|
||||
|
||||
|
||||
# Node Registration
|
||||
NODE_CLASS_MAPPINGS = {
|
||||
"TAPromptController": TAPromptController
|
||||
}
|
||||
|
||||
NODE_DISPLAY_NAME_MAPPINGS = {
|
||||
"TAPromptController": "TA Prompt Controller (Switch)"
|
||||
}
|
||||
@@ -0,0 +1,124 @@
|
||||
"""
|
||||
================================================================================
|
||||
Node Name : TA Prompt Hub
|
||||
Created : 2025
|
||||
Modified : 2026-03-11
|
||||
Copyright : © 2026, Thomas Möhrling (thomo.ART)
|
||||
Version : 2.0
|
||||
--------------------------------------------------------------------------------
|
||||
Part of ComfyUI-TA-Nodes-Pack
|
||||
License : Apache 2.0
|
||||
|
||||
Description:
|
||||
Central prompt collector node that gathers all prompt inputs in one place.
|
||||
Pure pass-through with no routing logic — use TAPromptController for mode
|
||||
switching. Also provides a combined_prompt output that joins positive_prompt,
|
||||
additional_prompt, and lora_trigger_words with ', ' (empty parts omitted).
|
||||
================================================================================
|
||||
"""
|
||||
|
||||
|
||||
class TAPromptHub:
|
||||
"""
|
||||
Central prompt collector — gathers all prompt inputs in one node.
|
||||
No logic, pure pass-through. Use TAPromptController for mode switching.
|
||||
|
||||
Outputs:
|
||||
positive_prompt – pass-through
|
||||
additional_prompt – pass-through
|
||||
negative_prompt – pass-through
|
||||
lora_trigger_words – optional input, pass-through
|
||||
combined_prompt – positive_prompt + additional_prompt + lora_trigger_words
|
||||
"""
|
||||
|
||||
@classmethod
|
||||
def INPUT_TYPES(cls):
|
||||
"""
|
||||
Defines all input widgets shown in the ComfyUI node UI.
|
||||
|
||||
Inputs:
|
||||
positive_prompt: Main positive prompt text. Supports dynamic prompts.
|
||||
additional_prompt: Secondary positive prompt, intended for style or
|
||||
scene additions without LoRA trigger words.
|
||||
negative_prompt: Negative prompt text. Supports dynamic prompts.
|
||||
lora_trigger_words: Optional STRING input from an upstream LoRA node.
|
||||
Defaults to '' if not connected.
|
||||
|
||||
Returns:
|
||||
dict: ComfyUI INPUT_TYPES dictionary with required and optional inputs.
|
||||
"""
|
||||
return {
|
||||
"required": {
|
||||
"positive_prompt": ("STRING", {
|
||||
"default": "",
|
||||
"multiline": True,
|
||||
"dynamicPrompts": True,
|
||||
"placeholder": "Positive prompt..."
|
||||
}),
|
||||
"additional_prompt": ("STRING", {
|
||||
"default": "",
|
||||
"multiline": True,
|
||||
"dynamicPrompts": True,
|
||||
"placeholder": "Additional positive prompt (no LoRA trigger words)..."
|
||||
}),
|
||||
"negative_prompt": ("STRING", {
|
||||
"default": "",
|
||||
"multiline": True,
|
||||
"dynamicPrompts": True,
|
||||
"placeholder": "Negative prompt..."
|
||||
}),
|
||||
},
|
||||
"optional": {
|
||||
"lora_trigger_words": ("STRING", {
|
||||
"forceInput": True,
|
||||
"default": ""
|
||||
}),
|
||||
}
|
||||
}
|
||||
|
||||
RETURN_TYPES = ("STRING", "STRING", "STRING", "STRING", "STRING")
|
||||
RETURN_NAMES = ("positive_prompt", "additional_prompt", "negative_prompt", "lora_trigger_words", "combined_prompt")
|
||||
FUNCTION = "collect_prompts"
|
||||
CATEGORY = "TA Nodes/text"
|
||||
|
||||
def collect_prompts(self, positive_prompt, additional_prompt, negative_prompt, lora_trigger_words=""):
|
||||
"""
|
||||
Passes all prompt inputs through unchanged and builds a combined prompt.
|
||||
|
||||
None values for any input are normalized to empty strings. The
|
||||
combined_prompt output joins positive_prompt, additional_prompt, and
|
||||
lora_trigger_words with ', ', skipping any parts that are empty or
|
||||
whitespace-only.
|
||||
|
||||
Args:
|
||||
positive_prompt (str): Main positive prompt string.
|
||||
additional_prompt (str): Secondary positive prompt string.
|
||||
negative_prompt (str): Negative prompt string.
|
||||
lora_trigger_words (str): LoRA trigger word string from an upstream
|
||||
node. Defaults to '' if not connected.
|
||||
|
||||
Returns:
|
||||
tuple[str, str, str, str, str]:
|
||||
(positive_prompt, additional_prompt, negative_prompt,
|
||||
lora_trigger_words, combined_prompt)
|
||||
"""
|
||||
if positive_prompt is None: positive_prompt = ""
|
||||
if additional_prompt is None: additional_prompt = ""
|
||||
if negative_prompt is None: negative_prompt = ""
|
||||
if lora_trigger_words is None: lora_trigger_words = ""
|
||||
|
||||
# combined_prompt: join positive + additional + lora_trigger_words (non-empty parts only)
|
||||
parts = [p for p in [positive_prompt, additional_prompt, lora_trigger_words] if p.strip()]
|
||||
combined_prompt = ", ".join(parts)
|
||||
|
||||
return (positive_prompt, additional_prompt, negative_prompt, lora_trigger_words, combined_prompt)
|
||||
|
||||
|
||||
# Node Registration
|
||||
NODE_CLASS_MAPPINGS = {
|
||||
"TAPromptHub": TAPromptHub
|
||||
}
|
||||
|
||||
NODE_DISPLAY_NAME_MAPPINGS = {
|
||||
"TAPromptHub": "🔀 TA Prompt Hub"
|
||||
}
|
||||
@@ -0,0 +1,223 @@
|
||||
"""
|
||||
================================================================================
|
||||
Node Name : TA SageAttention Toggler
|
||||
Created : 2025
|
||||
Modified : 2026-03-11
|
||||
Copyright : © 2026, Thomas Möhrling (thomo.ART)
|
||||
Version : 2.0
|
||||
--------------------------------------------------------------------------------
|
||||
Part of ComfyUI-TA-Nodes-Pack
|
||||
License : Apache 2.0
|
||||
|
||||
Description:
|
||||
Patches a ComfyUI MODEL with SageAttention and/or PyTorch FP16 matmul
|
||||
acceleration. Exposes all five SageAttention modes available in
|
||||
ComfyUI-KJNodes: auto, qk_int8_pv_fp16_cuda, qk_int8_pv_fp16_triton,
|
||||
qk_int8_pv_fp8_cuda, and qk_fp8_pv_fp8_cuda.
|
||||
================================================================================
|
||||
"""
|
||||
|
||||
import torch
|
||||
import logging
|
||||
from comfy.model_management import soft_empty_cache
|
||||
|
||||
logging.basicConfig(level=logging.INFO)
|
||||
logger = logging.getLogger("TA_SageAttentionToggler")
|
||||
|
||||
# Node mappings correctly reference the class
|
||||
NODE_CLASS_MAPPINGS = {"TASageAttentionToggler": "TASageAttentionToggler"}
|
||||
NODE_DISPLAY_NAME_MAPPINGS = {"TASageAttentionToggler": "🔧 TA SageAttention Toggler"}
|
||||
|
||||
|
||||
class TASageAttentionToggler:
|
||||
"""
|
||||
Applies SageAttention and/or PyTorch FP16 matmul patches to a MODEL.
|
||||
|
||||
SageAttention replaces the standard attention function with a quantised
|
||||
CUDA/Triton kernel for faster inference. The FP16 matmul patch enables
|
||||
torch.backends.cuda.matmul.allow_fp16_accumulation for additional
|
||||
throughput on supported hardware (requires PyTorch Nightly 2.7+).
|
||||
|
||||
Both patches are independent and can be enabled or disabled individually.
|
||||
"""
|
||||
|
||||
@classmethod
|
||||
def INPUT_TYPES(cls):
|
||||
"""
|
||||
Defines all input widgets shown in the ComfyUI node UI.
|
||||
|
||||
Inputs:
|
||||
model: The ComfyUI MODEL to patch.
|
||||
sage_enable: Toggle to apply the SageAttention patch.
|
||||
torch_enable: Toggle to apply the FP16 matmul patch.
|
||||
sage_mode: Selects the SageAttention kernel variant.
|
||||
'auto' uses the default sageattn() entry point;
|
||||
the other options select specific quantisation
|
||||
configurations (CUDA or Triton backends).
|
||||
|
||||
Returns:
|
||||
dict: ComfyUI INPUT_TYPES dictionary with all required inputs.
|
||||
"""
|
||||
return {
|
||||
"required": {
|
||||
"model": ("MODEL",),
|
||||
"sage_enable": ("BOOLEAN", {"default": True, "label_on": "✅ Sage ON", "label_off": "❌ OFF"}),
|
||||
"torch_enable": ("BOOLEAN", {"default": True, "label_on": "✅ Torch ON", "label_off": "❌ OFF"}),
|
||||
"sage_mode": ([
|
||||
"auto",
|
||||
"sageattn_qk_int8_pv_fp16_cuda",
|
||||
"sageattn_qk_int8_pv_fp16_triton",
|
||||
"sageattn_qk_int8_pv_fp8_cuda",
|
||||
"sageattn_qk_fp8_pv_fp8_cuda"
|
||||
], {"default": "auto"}),
|
||||
}
|
||||
}
|
||||
|
||||
RETURN_TYPES = ("MODEL",)
|
||||
FUNCTION = "apply_patches"
|
||||
CATEGORY = "TA Smart LLM"
|
||||
|
||||
def apply_patches(self, model, sage_enable, torch_enable, sage_mode):
|
||||
"""
|
||||
Applies the selected patches to the model and returns the patched result.
|
||||
|
||||
Each patch is applied independently based on its toggle. If sage_enable
|
||||
is True, _apply_sage_patch() is called first; if torch_enable is True,
|
||||
_apply_torch_patch() is called afterwards. Both patches modify the model
|
||||
object in-place and also return it for chaining.
|
||||
|
||||
Args:
|
||||
model: ComfyUI MODEL object to patch.
|
||||
sage_enable (bool): Whether to apply the SageAttention patch.
|
||||
torch_enable (bool): Whether to apply the FP16 matmul patch.
|
||||
sage_mode (str): SageAttention kernel variant to use.
|
||||
|
||||
Returns:
|
||||
tuple: Single-element tuple containing the patched MODEL object.
|
||||
"""
|
||||
logger.info(f"🚀 [TA] SageToggler START | Sage:{sage_enable} | Torch:{torch_enable} | Mode:{sage_mode}")
|
||||
patched_model = model
|
||||
|
||||
if sage_enable:
|
||||
patched_model = self._apply_sage_patch(patched_model, sage_mode)
|
||||
|
||||
if torch_enable:
|
||||
patched_model = self._apply_torch_patch(patched_model)
|
||||
|
||||
logger.info("✅ [TA] Patches applied!")
|
||||
return (patched_model, )
|
||||
|
||||
def _apply_sage_patch(self, model, sage_mode):
|
||||
"""
|
||||
Patches the model with the specified SageAttention kernel.
|
||||
|
||||
Imports the requested sageattention function and wraps it in a lambda
|
||||
that matches ComfyUI's attention call signature (q, k, v, is_causal,
|
||||
attn_mask, tensor_layout). The wrapped function is stored as
|
||||
model.sage_func and model.sage_active is set to True on success.
|
||||
|
||||
If the sageattention package is not installed, model.sage_active is set
|
||||
to False and an installation hint is logged; the model is returned
|
||||
unmodified.
|
||||
|
||||
Args:
|
||||
model: ComfyUI MODEL object to patch.
|
||||
sage_mode (str): One of the five supported sage_mode strings.
|
||||
|
||||
Returns:
|
||||
MODEL: The model with sage_func and sage_active attributes set.
|
||||
|
||||
Raises:
|
||||
ValueError: If sage_mode is not one of the recognised mode strings.
|
||||
"""
|
||||
logger.info(f"🔥 SageAttention PATCH: {sage_mode}")
|
||||
|
||||
try:
|
||||
from sageattention import sageattn
|
||||
|
||||
if sage_mode == "auto":
|
||||
sage_func = lambda q, k, v, is_causal=False, attn_mask=None, tensor_layout="NHD": \
|
||||
sageattn(q, k, v, is_causal=is_causal, attn_mask=attn_mask, tensor_layout=tensor_layout)
|
||||
|
||||
elif sage_mode == "sageattn_qk_int8_pv_fp16_cuda":
|
||||
from sageattention import sageattn_qk_int8_pv_fp16_cuda
|
||||
sage_func = lambda q, k, v, is_causal=False, attn_mask=None, tensor_layout="NHD": \
|
||||
sageattn_qk_int8_pv_fp16_cuda(q, k, v, is_causal=is_causal, attn_mask=attn_mask,
|
||||
pv_accum_dtype="fp32", tensor_layout=tensor_layout)
|
||||
|
||||
elif sage_mode == "sageattn_qk_int8_pv_fp16_triton":
|
||||
from sageattention import sageattn_qk_int8_pv_fp16_triton
|
||||
sage_func = lambda q, k, v, is_causal=False, attn_mask=None, tensor_layout="NHD": \
|
||||
sageattn_qk_int8_pv_fp16_triton(q, k, v, is_causal=is_causal, attn_mask=attn_mask,
|
||||
tensor_layout=tensor_layout)
|
||||
|
||||
elif sage_mode == "sageattn_qk_int8_pv_fp8_cuda":
|
||||
from sageattention import sageattn_qk_int8_pv_fp8_cuda
|
||||
sage_func = lambda q, k, v, is_causal=False, attn_mask=None, tensor_layout="NHD": \
|
||||
sageattn_qk_int8_pv_fp8_cuda(q, k, v, is_causal=is_causal, attn_mask=attn_mask,
|
||||
pv_accum_dtype="fp32+fp32", tensor_layout=tensor_layout)
|
||||
|
||||
elif sage_mode == "sageattn_qk_fp8_pv_fp8_cuda":
|
||||
from sageattention import sageattn_qk_fp8_pv_fp8_cuda
|
||||
sage_func = lambda q, k, v, is_causal=False, attn_mask=None, tensor_layout="NHD": \
|
||||
sageattn_qk_fp8_pv_fp8_cuda(q, k, v, is_causal=is_causal, attn_mask=attn_mask,
|
||||
tensor_layout=tensor_layout)
|
||||
|
||||
else:
|
||||
raise ValueError(f"Unknown sage_mode: {sage_mode}")
|
||||
|
||||
logger.info(f"✅ {sage_mode} loaded successfully!")
|
||||
model.sage_func = sage_func
|
||||
model.sage_active = True
|
||||
|
||||
except ImportError as e:
|
||||
logger.error(f"❌ SageAttention import error: {e}")
|
||||
logger.info("💡 Install with: pip install sageattention-nightly")
|
||||
model.sage_active = False
|
||||
|
||||
return model
|
||||
|
||||
def _apply_torch_patch(self, model):
|
||||
"""
|
||||
Enables PyTorch FP16 matmul accumulation on the CUDA backend.
|
||||
|
||||
Sets torch.backends.cuda.matmul.allow_fp16_accumulation to True if the
|
||||
attribute is available (requires PyTorch Nightly 2.7+). The previous
|
||||
value is logged for reference. Registers _restore_torch as a callback
|
||||
on model._torch_callbacks if that attribute exists, and sets
|
||||
model.torch_patched = True.
|
||||
|
||||
Args:
|
||||
model: ComfyUI MODEL object to patch.
|
||||
|
||||
Returns:
|
||||
MODEL: The model with torch_patched set to True.
|
||||
"""
|
||||
logger.info("🔥 Torch Backend PATCH")
|
||||
|
||||
original_fp16 = None
|
||||
if hasattr(torch.backends.cuda.matmul, 'allow_fp16_accumulation'):
|
||||
original_fp16 = torch.backends.cuda.matmul.allow_fp16_accumulation
|
||||
torch.backends.cuda.matmul.allow_fp16_accumulation = True
|
||||
logger.info(f"✅ FP16 Matmul enabled (previously: {original_fp16})")
|
||||
else:
|
||||
logger.warning("⚠️ PyTorch Nightly 2.7+ required for FP16 Matmul")
|
||||
|
||||
if hasattr(model, '_torch_callbacks'):
|
||||
model._torch_callbacks.append(self._restore_torch)
|
||||
|
||||
model.torch_patched = True
|
||||
return model
|
||||
|
||||
def _restore_torch(self):
|
||||
"""
|
||||
Restores the PyTorch FP16 matmul accumulation setting to False and
|
||||
flushes the VRAM cache via soft_empty_cache().
|
||||
|
||||
Intended to be registered as a teardown callback on the model so that
|
||||
the global torch backend setting is not left enabled after sampling.
|
||||
"""
|
||||
if hasattr(torch.backends.cuda.matmul, 'allow_fp16_accumulation'):
|
||||
torch.backends.cuda.matmul.allow_fp16_accumulation = False
|
||||
logger.info("🔄 Torch Backend restored")
|
||||
soft_empty_cache()
|
||||
@@ -0,0 +1,381 @@
|
||||
"""
|
||||
================================================================================
|
||||
Node Name : TA Sampler Preset
|
||||
Created : 2026-03-07
|
||||
Modified : 2026-03-14
|
||||
Copyright : © 2026, Thomas Möhrling (thomo.ART)
|
||||
Version : 2.2
|
||||
--------------------------------------------------------------------------------
|
||||
Part of ComfyUI-TA-Nodes-Pack
|
||||
License : Apache 2.0
|
||||
|
||||
Description:
|
||||
Loads sampler presets from ta_sampler_presets.json on every execution.
|
||||
All outputs are directly connectable to TA KSampler. Includes a
|
||||
browser-based preset editor at:
|
||||
http://localhost:8188/ta_sampler_presets/ui
|
||||
================================================================================
|
||||
"""
|
||||
|
||||
import os
|
||||
import json
|
||||
from aiohttp import web
|
||||
from server import PromptServer
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Paths
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
_DIR = os.path.dirname(os.path.abspath(__file__))
|
||||
_JSON_PATH = os.path.join(_DIR, "ta_sampler_presets.json")
|
||||
_HTML_PATH = os.path.join(_DIR, "web", "js", "ta_sampler_presets_ui.html")
|
||||
|
||||
_DEFAULT_PRESETS = {
|
||||
"Z-Image Turbo": {
|
||||
"steps": 9, "cfg": 1.0,
|
||||
"start_at_step": 0, "end_at_step": 9999,
|
||||
"sampler_name": "euler", "scheduler": "beta",
|
||||
},
|
||||
}
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# JSON Helpers
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
def _load_presets() -> dict:
|
||||
"""
|
||||
Loads presets from ta_sampler_presets.json. If the file does not exist it
|
||||
is created with _DEFAULT_PRESETS. Returns _DEFAULT_PRESETS as a fallback
|
||||
if the file cannot be read or parsed.
|
||||
|
||||
Returns:
|
||||
dict: Mapping of preset name strings to preset parameter dicts.
|
||||
"""
|
||||
if not os.path.exists(_JSON_PATH):
|
||||
_save_presets(_DEFAULT_PRESETS)
|
||||
return _DEFAULT_PRESETS.copy()
|
||||
try:
|
||||
with open(_JSON_PATH, "r", encoding="utf-8") as f:
|
||||
return json.load(f)
|
||||
except Exception as e:
|
||||
print(f"[TASamplerPreset] Error loading JSON: {e}")
|
||||
return _DEFAULT_PRESETS.copy()
|
||||
|
||||
|
||||
def _save_presets(presets: dict) -> None:
|
||||
"""
|
||||
Serializes the given presets dict to ta_sampler_presets.json.
|
||||
|
||||
Args:
|
||||
presets (dict): Mapping of preset name strings to preset parameter dicts.
|
||||
"""
|
||||
try:
|
||||
with open(_JSON_PATH, "w", encoding="utf-8") as f:
|
||||
json.dump(presets, f, indent=4, ensure_ascii=False)
|
||||
except Exception as e:
|
||||
print(f"[TASamplerPreset] Error saving JSON: {e}")
|
||||
|
||||
|
||||
def _preset_names() -> list:
|
||||
"""
|
||||
Returns an ordered list of all preset name strings from the presets file.
|
||||
Falls back to ['(empty)'] if no presets are found.
|
||||
|
||||
Returns:
|
||||
list[str]: List of preset name strings.
|
||||
"""
|
||||
return list(_load_presets().keys()) or ["(empty)"]
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Web Endpoints
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
@PromptServer.instance.routes.get("/ta_sampler_presets/ui")
|
||||
async def ta_presets_ui(request):
|
||||
"""
|
||||
Serves the browser-based sampler preset editor HTML page.
|
||||
|
||||
Route: GET /ta_sampler_presets/ui
|
||||
|
||||
Returns:
|
||||
web.Response: HTML page content, or a 404 response if the HTML file
|
||||
is not found at the expected path.
|
||||
"""
|
||||
if not os.path.exists(_HTML_PATH):
|
||||
return web.Response(text="HTML file not found.", status=404)
|
||||
with open(_HTML_PATH, "r", encoding="utf-8") as f:
|
||||
return web.Response(text=f.read(), content_type="text/html")
|
||||
|
||||
|
||||
@PromptServer.instance.routes.get("/ta_sampler_presets/options")
|
||||
async def ta_presets_options(request):
|
||||
"""
|
||||
Returns all available sampler and scheduler names as JSON.
|
||||
Used by the browser editor to populate its dropdown menus.
|
||||
|
||||
Route: GET /ta_sampler_presets/options
|
||||
|
||||
Returns:
|
||||
web.Response: JSON response with {'samplers': [...], 'schedulers': [...]}.
|
||||
"""
|
||||
import comfy.samplers
|
||||
return web.json_response({
|
||||
"samplers": comfy.samplers.KSampler.SAMPLERS,
|
||||
"schedulers": comfy.samplers.KSampler.SCHEDULERS,
|
||||
})
|
||||
|
||||
|
||||
@PromptServer.instance.routes.get("/ta_sampler_presets/list")
|
||||
async def ta_presets_list(request):
|
||||
"""
|
||||
Returns the full presets dictionary as JSON.
|
||||
|
||||
Route: GET /ta_sampler_presets/list
|
||||
|
||||
Returns:
|
||||
web.Response: JSON response containing all presets as a dict.
|
||||
"""
|
||||
return web.json_response(_load_presets())
|
||||
|
||||
|
||||
@PromptServer.instance.routes.post("/ta_sampler_presets/get")
|
||||
async def ta_presets_get(request):
|
||||
"""
|
||||
Returns the parameter dict for a single named preset.
|
||||
|
||||
Route: POST /ta_sampler_presets/get
|
||||
Body: {'preset': '<name>'}
|
||||
|
||||
Returns:
|
||||
web.Response: JSON response with the preset's parameter dict,
|
||||
or a 404 error if the preset name is not found.
|
||||
"""
|
||||
try:
|
||||
body = await request.json()
|
||||
name = body.get("preset", "")
|
||||
presets = _load_presets()
|
||||
if name not in presets:
|
||||
return web.json_response({"error": f"Preset '{name}' not found."}, status=404)
|
||||
return web.json_response(presets[name])
|
||||
except Exception as e:
|
||||
return web.json_response({"error": str(e)}, status=500)
|
||||
|
||||
|
||||
@PromptServer.instance.routes.post("/ta_sampler_presets/save")
|
||||
async def ta_presets_save(request):
|
||||
"""
|
||||
Creates or updates a named preset and persists it to ta_sampler_presets.json.
|
||||
All parameter values are type-cast to their expected types before saving.
|
||||
|
||||
Route: POST /ta_sampler_presets/save
|
||||
Body: {'name': '<name>', 'data': {steps, cfg, start_at_step, end_at_step,
|
||||
sampler_name, scheduler}}
|
||||
|
||||
Returns:
|
||||
web.Response: JSON response with {'ok': True} on success, or
|
||||
{'ok': False, 'error': str} on validation failure or exception.
|
||||
"""
|
||||
try:
|
||||
body = await request.json()
|
||||
name = body.get("name", "").strip()
|
||||
data = body.get("data", {})
|
||||
if not name:
|
||||
return web.json_response({"ok": False, "error": "No preset name provided."})
|
||||
presets = _load_presets()
|
||||
presets[name] = {
|
||||
"steps": int(data.get("steps", 20)),
|
||||
"cfg": float(data.get("cfg", 7.0)),
|
||||
"start_at_step": int(data.get("start_at_step", 0)),
|
||||
"end_at_step": int(data.get("end_at_step", 9999)),
|
||||
"sampler_name": str(data.get("sampler_name", "euler")),
|
||||
"scheduler": str(data.get("scheduler", "normal")),
|
||||
}
|
||||
_save_presets(presets)
|
||||
print(f"[TASamplerPreset] Preset '{name}' saved.")
|
||||
return web.json_response({"ok": True})
|
||||
except Exception as e:
|
||||
return web.json_response({"ok": False, "error": str(e)})
|
||||
|
||||
|
||||
@PromptServer.instance.routes.post("/ta_sampler_presets/delete")
|
||||
async def ta_presets_delete(request):
|
||||
"""
|
||||
Deletes a named preset from ta_sampler_presets.json.
|
||||
|
||||
Route: POST /ta_sampler_presets/delete
|
||||
Body: {'name': '<name>'}
|
||||
|
||||
Returns:
|
||||
web.Response: JSON response with {'ok': True} on success, or
|
||||
{'ok': False, 'error': str} if the preset is not found
|
||||
or an exception occurs.
|
||||
"""
|
||||
try:
|
||||
body = await request.json()
|
||||
name = body.get("name", "").strip()
|
||||
presets = _load_presets()
|
||||
if name not in presets:
|
||||
return web.json_response({"ok": False, "error": f"Preset '{name}' not found."})
|
||||
del presets[name]
|
||||
_save_presets(presets)
|
||||
print(f"[TASamplerPreset] Preset '{name}' deleted.")
|
||||
return web.json_response({"ok": True})
|
||||
except Exception as e:
|
||||
return web.json_response({"ok": False, "error": str(e)})
|
||||
|
||||
|
||||
@PromptServer.instance.routes.post("/ta_sampler_presets/reorder")
|
||||
async def ta_presets_reorder(request):
|
||||
"""
|
||||
Rewrites ta_sampler_presets.json with keys in the given order.
|
||||
|
||||
Route: POST /ta_sampler_presets/reorder
|
||||
Body: {'order': ['Name1', 'Name2', ...]}
|
||||
|
||||
Returns:
|
||||
web.Response: JSON response with {'ok': True} on success, or
|
||||
{'ok': False, 'error': str} on exception.
|
||||
"""
|
||||
try:
|
||||
body = await request.json()
|
||||
order = body.get("order", [])
|
||||
presets = _load_presets()
|
||||
reordered = {name: presets[name] for name in order if name in presets}
|
||||
# Safety net: append any presets not included in order
|
||||
for name, data in presets.items():
|
||||
if name not in reordered:
|
||||
reordered[name] = data
|
||||
_save_presets(reordered)
|
||||
print(f"[TASamplerPreset] Reordered: {list(reordered.keys())}")
|
||||
return web.json_response({"ok": True})
|
||||
except Exception as e:
|
||||
return web.json_response({"ok": False, "error": str(e)})
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Node: TASamplerPreset
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
class TASamplerPreset:
|
||||
"""
|
||||
Loads sampler presets from ta_sampler_presets.json on every execution.
|
||||
|
||||
All seven outputs (steps, cfg, sampler_name, scheduler, start_at_step,
|
||||
end_at_step, info) are directly connectable to TA KSampler inputs.
|
||||
The 'info' output provides a formatted summary string that can also be
|
||||
used by TAFluxGuidanceGate to detect FLUX presets.
|
||||
|
||||
Browser-based preset editor: http://localhost:8188/ta_sampler_presets/ui
|
||||
"""
|
||||
|
||||
CATEGORY = "TA Nodes/Sampling"
|
||||
FUNCTION = "get_preset"
|
||||
RETURN_TYPES = ("INT", "FLOAT", "STRING", "STRING", "INT", "INT", "STRING",)
|
||||
RETURN_NAMES = ("steps", "cfg", "sampler_name", "scheduler", "start_at_step", "end_at_step", "info",)
|
||||
|
||||
@classmethod
|
||||
def IS_CHANGED(cls, preset: str):
|
||||
"""
|
||||
Returns the last-modified timestamp of ta_sampler_presets.json.
|
||||
|
||||
ComfyUI calls this before every execution. If the return value differs
|
||||
from the previous call, ComfyUI re-evaluates INPUT_TYPES and re-renders
|
||||
the node — causing the preset dropdown to reflect any changes made in
|
||||
the browser editor without requiring a ComfyUI restart.
|
||||
|
||||
Args:
|
||||
preset (str): Currently selected preset name (unused).
|
||||
|
||||
Returns:
|
||||
float: mtime of the JSON file, or 0.0 if the file does not exist.
|
||||
"""
|
||||
try:
|
||||
return os.path.getmtime(_JSON_PATH)
|
||||
except OSError:
|
||||
return 0.0
|
||||
|
||||
@classmethod
|
||||
def INPUT_TYPES(cls):
|
||||
"""
|
||||
Defines all input widgets shown in the ComfyUI node UI.
|
||||
|
||||
Reads the current preset names from ta_sampler_presets.json at node
|
||||
load time to populate the preset dropdown.
|
||||
|
||||
Returns:
|
||||
dict: ComfyUI INPUT_TYPES dictionary with the required preset input.
|
||||
"""
|
||||
return {
|
||||
"required": {
|
||||
"preset": (_preset_names(), {
|
||||
"default": _preset_names()[0],
|
||||
"tooltip": "Select preset. Editor: http://localhost:8188/ta_sampler_presets/ui",
|
||||
}),
|
||||
},
|
||||
}
|
||||
|
||||
def get_preset(self, preset: str):
|
||||
"""
|
||||
Loads the selected preset from ta_sampler_presets.json and returns all
|
||||
its parameters as individual typed outputs.
|
||||
|
||||
If the requested preset name is not found in the file (e.g. after a
|
||||
rename), the first available preset is used as a fallback and a warning
|
||||
is printed to the console.
|
||||
|
||||
The 'info' output is a formatted multi-line string summarising all
|
||||
preset parameters. It is also used by TAFluxGuidanceGate — if the
|
||||
preset name contains 'FLUX', guidance is applied automatically.
|
||||
|
||||
Args:
|
||||
preset (str): Name of the preset to load, as shown in the dropdown.
|
||||
|
||||
Returns:
|
||||
tuple: (steps, cfg, sampler_name, scheduler, start_at_step,
|
||||
end_at_step, info) with types (int, float, str, str, int,
|
||||
int, str).
|
||||
"""
|
||||
presets = _load_presets()
|
||||
|
||||
if preset not in presets:
|
||||
print(f"[TASamplerPreset] Preset '{preset}' not found, using first available.")
|
||||
preset = list(presets.keys())[0]
|
||||
|
||||
p = presets[preset]
|
||||
info = (f"[{preset}]\n"
|
||||
f"steps : {p['steps']}\n"
|
||||
f"cfg : {p['cfg']}\n"
|
||||
f"sampler : {p['sampler_name']}\n"
|
||||
f"scheduler : {p['scheduler']}\n"
|
||||
f"start_at_step: {p['start_at_step']}\n"
|
||||
f"end_at_step : {p['end_at_step']}")
|
||||
|
||||
print(f"[TASamplerPreset] preset='{preset}' "
|
||||
f"steps={p['steps']} cfg={p['cfg']} "
|
||||
f"sampler={p['sampler_name']} scheduler={p['scheduler']} "
|
||||
f"start={p['start_at_step']} end={p['end_at_step']}")
|
||||
|
||||
return (
|
||||
int(p["steps"]),
|
||||
float(p["cfg"]),
|
||||
str(p["sampler_name"]),
|
||||
str(p["scheduler"]),
|
||||
int(p["start_at_step"]),
|
||||
int(p["end_at_step"]),
|
||||
info,
|
||||
)
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Node Registration
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
NODE_CLASS_MAPPINGS = {
|
||||
"TASamplerPreset": TASamplerPreset,
|
||||
}
|
||||
|
||||
NODE_DISPLAY_NAME_MAPPINGS = {
|
||||
"TASamplerPreset": "🎛️ TA Sampler Preset",
|
||||
}
|
||||
@@ -0,0 +1,58 @@
|
||||
{
|
||||
"Z-Image Turbo": {
|
||||
"steps": 9,
|
||||
"cfg": 1.0,
|
||||
"start_at_step": 0,
|
||||
"end_at_step": 9999,
|
||||
"sampler_name": "euler",
|
||||
"scheduler": "beta"
|
||||
},
|
||||
"FLUX": {
|
||||
"steps": 35,
|
||||
"cfg": 1.0,
|
||||
"start_at_step": 0,
|
||||
"end_at_step": 9999,
|
||||
"sampler_name": "deis",
|
||||
"scheduler": "beta"
|
||||
},
|
||||
"FLUX.1-DEV Turbo": {
|
||||
"steps": 8,
|
||||
"cfg": 7.0,
|
||||
"start_at_step": 0,
|
||||
"end_at_step": 9999,
|
||||
"sampler_name": "euler",
|
||||
"scheduler": "normal"
|
||||
},
|
||||
"QWEN": {
|
||||
"steps": 20,
|
||||
"cfg": 2.5,
|
||||
"start_at_step": 0,
|
||||
"end_at_step": 9999,
|
||||
"sampler_name": "dpmpp_2m",
|
||||
"scheduler": "sgm_uniform"
|
||||
},
|
||||
"QWEN Lightning": {
|
||||
"steps": 8,
|
||||
"cfg": 1.0,
|
||||
"start_at_step": 0,
|
||||
"end_at_step": 9999,
|
||||
"sampler_name": "dpmpp_2m",
|
||||
"scheduler": "sgm_uniform"
|
||||
},
|
||||
"SDXL": {
|
||||
"steps": 25,
|
||||
"cfg": 7.0,
|
||||
"start_at_step": 0,
|
||||
"end_at_step": 9999,
|
||||
"sampler_name": "dpmpp_2m",
|
||||
"scheduler": "karras"
|
||||
},
|
||||
"SD1.5": {
|
||||
"steps": 20,
|
||||
"cfg": 7.0,
|
||||
"start_at_step": 0,
|
||||
"end_at_step": 9999,
|
||||
"sampler_name": "euler_ancestral",
|
||||
"scheduler": "normal"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,192 @@
|
||||
"""
|
||||
================================================================================
|
||||
Node Name : TA Save Image Optional
|
||||
Created : 2025
|
||||
Modified : 2026-03-12
|
||||
Copyright : © 2026, Thomas Möhrling (thomo.ART)
|
||||
Version : 2.1
|
||||
--------------------------------------------------------------------------------
|
||||
Part of ComfyUI-TA-Nodes-Pack
|
||||
License : Apache 2.0
|
||||
|
||||
Description:
|
||||
Optional image saver that extends ComfyUI's built-in SaveImage node.
|
||||
Supports JPEG and WebP output formats with configurable quality, an
|
||||
enable/disable toggle, and optional companion .txt files containing the
|
||||
positive and negative prompts alongside a timestamp and filename reference.
|
||||
================================================================================
|
||||
"""
|
||||
|
||||
import os
|
||||
import datetime
|
||||
import torch
|
||||
import numpy as np
|
||||
from PIL import Image
|
||||
from nodes import SaveImage
|
||||
import folder_paths
|
||||
|
||||
|
||||
class TASaveImageOptional(SaveImage):
|
||||
"""
|
||||
Extended image saver node with optional saving, format selection, and
|
||||
prompt logging.
|
||||
|
||||
Inherits from ComfyUI's SaveImage to reuse its output directory and path
|
||||
resolution logic. Adds a boolean enable toggle so the node can be disabled
|
||||
without disconnecting it from the workflow. When enabled, images are saved
|
||||
as JPEG or WebP with the specified quality. Optionally writes a companion
|
||||
.txt file per image containing the positive/negative prompts, timestamp,
|
||||
and filename for documentation and dataset purposes.
|
||||
"""
|
||||
|
||||
def __init__(self):
|
||||
super().__init__()
|
||||
|
||||
@classmethod
|
||||
def INPUT_TYPES(s):
|
||||
"""
|
||||
Defines all input widgets shown in the ComfyUI node UI.
|
||||
|
||||
Inputs:
|
||||
images: IMAGE tensor batch to save.
|
||||
filename_prefix: Base filename string. Any image extension suffix
|
||||
(.jpg, .jpeg, .webp, .png) is stripped automatically
|
||||
before path construction.
|
||||
enabled: Master toggle. When False the node is bypassed and
|
||||
the input images are passed through unchanged.
|
||||
save_txt: When 'enabled', writes a .txt companion file per
|
||||
image with prompts, timestamp, and filename.
|
||||
positive_prompt: Positive prompt string to include in the .txt file.
|
||||
negative_prompt: Negative prompt string to include in the .txt file.
|
||||
save_format: Output image format: 'jpg' or 'webp'.
|
||||
jpeg_quality: Compression quality level (applies to both JPEG
|
||||
and WebP). Selectable from 70–100.
|
||||
|
||||
Returns:
|
||||
dict: ComfyUI INPUT_TYPES dictionary with required and optional inputs.
|
||||
"""
|
||||
return {
|
||||
"required": {
|
||||
"images": ("IMAGE",),
|
||||
"filename_prefix": ("STRING", {"default": "ComfyUI"}),
|
||||
"enabled": ("BOOLEAN", {"default": True, "label_on": "✅ Save ON", "label_off": "❌ OFF"}),
|
||||
"save_txt": (["enabled", "disabled"], {"default": "enabled"}),
|
||||
"positive_prompt": ("STRING", {"forceInput": True}),
|
||||
"negative_prompt": ("STRING", {"forceInput": True}),
|
||||
},
|
||||
"optional": {
|
||||
"save_format": (["jpg", "webp"], {"default": "jpg"}),
|
||||
"jpeg_quality": (["70", "80", "90", "95", "100"], {"default": "95"}),
|
||||
}
|
||||
}
|
||||
|
||||
RETURN_TYPES = ("IMAGE",)
|
||||
RETURN_NAMES = ("IMAGE",)
|
||||
FUNCTION = "ta_save_images"
|
||||
OUTPUT_NODE = True
|
||||
CATEGORY = "TA Nodes/utils"
|
||||
|
||||
def ta_save_images(self, images, filename_prefix, enabled, save_txt, positive_prompt, negative_prompt,
|
||||
save_format="jpg", jpeg_quality="95", **kwargs):
|
||||
"""
|
||||
Saves images to disk in the selected format and optionally writes
|
||||
companion .txt prompt files.
|
||||
|
||||
When enabled is False the method returns immediately, passing the input
|
||||
images through without writing any files.
|
||||
|
||||
For each image in the batch:
|
||||
1. Converts the float IMAGE tensor to a uint8 numpy array.
|
||||
2. Saves the image as JPEG or WebP using the specified quality.
|
||||
3. Optionally writes a .txt file with timestamp, filename, and prompts.
|
||||
|
||||
File naming follows ComfyUI's standard counter convention:
|
||||
<filename_prefix>_<counter:05>_.<ext>
|
||||
|
||||
Any image extension suffix in filename_prefix is stripped before path
|
||||
construction to prevent double extensions.
|
||||
|
||||
Args:
|
||||
images: Batch IMAGE tensor (B, H, W, 3) float [0..1].
|
||||
filename_prefix (str): Base filename; extension suffixes are stripped.
|
||||
enabled (bool): Master toggle. False = pass-through, no I/O.
|
||||
save_txt (str): 'enabled' to write .txt companion files.
|
||||
positive_prompt (str): Positive prompt string for .txt output.
|
||||
negative_prompt (str): Negative prompt string for .txt output.
|
||||
save_format (str): 'jpg' or 'webp'. Defaults to 'jpg'.
|
||||
jpeg_quality (str): Quality level string '70'–'100'. Defaults to '95'.
|
||||
**kwargs: Absorbs any additional ComfyUI-injected inputs.
|
||||
|
||||
Returns:
|
||||
dict: ComfyUI result dict {'result': (images,)} containing the
|
||||
original input IMAGE tensor for downstream nodes.
|
||||
"""
|
||||
if not enabled:
|
||||
return {"result": (images,)}
|
||||
|
||||
quality = int(jpeg_quality)
|
||||
if save_format == "webp":
|
||||
ext = ".webp"
|
||||
else:
|
||||
ext = ".jpg"
|
||||
|
||||
# Strip any image extension suffix from filename_prefix if present
|
||||
for suffix in [".jpg", ".jpeg", ".webp", ".png"]:
|
||||
if filename_prefix.lower().endswith(suffix):
|
||||
filename_prefix = filename_prefix[:-len(suffix)]
|
||||
break
|
||||
|
||||
full_output_folder, filename, counter, subfolder, filename_prefix = \
|
||||
folder_paths.get_save_image_path(
|
||||
filename_prefix,
|
||||
self.output_dir,
|
||||
images[0].shape[1],
|
||||
images[0].shape[0]
|
||||
)
|
||||
|
||||
current_counter = counter - len(images)
|
||||
|
||||
for i, img in enumerate(images):
|
||||
img = ((img.cpu() * 255).clip(0, 255).cpu().numpy()).astype(np.uint8)
|
||||
pil_img = Image.fromarray(img)
|
||||
file_base = f"{filename}_{current_counter:05}_"
|
||||
save_path = os.path.join(full_output_folder, f"{file_base}{ext}")
|
||||
|
||||
if save_format == "webp":
|
||||
pil_img.save(save_path, format="WEBP", quality=quality)
|
||||
else:
|
||||
pil_img.save(save_path, format="JPEG", quality=quality)
|
||||
current_counter += 1
|
||||
|
||||
if save_txt == "enabled":
|
||||
now = datetime.datetime.now()
|
||||
date_time_str = now.strftime("%Y-%m-%d %H:%M:%S")
|
||||
current_counter = counter - len(images)
|
||||
for i in range(len(images)):
|
||||
file_base = f"{filename}_{current_counter:05}_"
|
||||
txt_file = f"{file_base}.txt"
|
||||
output_text = (
|
||||
f"DATE / TIME: {date_time_str}\n"
|
||||
f"FILE: {file_base}{ext}\n"
|
||||
f"{'='*30}\n"
|
||||
f"POSITIVE PROMPT:\n{positive_prompt}\n\n"
|
||||
f"NEGATIVE PROMPT:\n{negative_prompt}\n"
|
||||
f"{'='*30}\n"
|
||||
)
|
||||
try:
|
||||
file_path = os.path.join(full_output_folder, txt_file)
|
||||
with open(file_path, "w", encoding="utf-8") as f:
|
||||
f.write(output_text)
|
||||
except Exception as e:
|
||||
print(f"[TA-Nodes] Error writing TXT file: {e}")
|
||||
current_counter += 1
|
||||
|
||||
return {"result": (images,)}
|
||||
|
||||
|
||||
NODE_CLASS_MAPPINGS = {
|
||||
"TASaveImageOptional": TASaveImageOptional
|
||||
}
|
||||
NODE_DISPLAY_NAME_MAPPINGS = {
|
||||
"TASaveImageOptional": "TA Save Image Optional v2.1"
|
||||
}
|
||||
@@ -0,0 +1,162 @@
|
||||
"""
|
||||
================================================================================
|
||||
Node Name : TA Save Image With Prompt
|
||||
Created : 2025
|
||||
Modified : 2026-03-11
|
||||
Copyright : © 2026, Thomas Möhring (thomo.ART)
|
||||
Version : 2.0
|
||||
--------------------------------------------------------------------------------
|
||||
Part of ComfyUI-TA-Nodes-Pack
|
||||
License : Apache 2.0
|
||||
|
||||
|
||||
Description:
|
||||
Image saver that extends ComfyUI's built-in SaveImage node.
|
||||
Reuses the original saving logic and adds optional companion .txt files
|
||||
containing the positive and negative prompts alongside a timestamp and
|
||||
filename reference. The images are passed through for further workflow use.
|
||||
================================================================================
|
||||
"""
|
||||
|
||||
import os
|
||||
import datetime
|
||||
import json
|
||||
from PIL import Image
|
||||
import numpy as np
|
||||
|
||||
# Import of the original SaveImage class
|
||||
from nodes import SaveImage
|
||||
import folder_paths
|
||||
|
||||
|
||||
class TASaveImageWithPrompt(SaveImage):
|
||||
"""
|
||||
Extended image saver node that reuses ComfyUI's SaveImage saving logic.
|
||||
|
||||
Inherits from ComfyUI's SaveImage class to leverage its output directory
|
||||
resolution, filename counter logic, and UI preview generation. After
|
||||
calling the original save_images() method, optionally writes a companion
|
||||
.txt file per image containing the positive/negative prompts, timestamp,
|
||||
and filename for documentation and dataset preparation purposes.
|
||||
|
||||
The input images are always returned unchanged for downstream workflow nodes.
|
||||
"""
|
||||
|
||||
def __init__(self):
|
||||
super().__init__()
|
||||
|
||||
@classmethod
|
||||
def INPUT_TYPES(s):
|
||||
"""
|
||||
Defines all input widgets shown in the ComfyUI node UI.
|
||||
|
||||
Inputs:
|
||||
images: IMAGE tensor batch from upstream nodes.
|
||||
filename_prefix: Base filename string passed to the original SaveImage.
|
||||
positive_prompt: Positive prompt string to include in the .txt file.
|
||||
negative_prompt: Negative prompt string to include in the .txt file.
|
||||
save_txt: When 'enabled', writes a .txt companion file per image with
|
||||
prompts, timestamp, and filename reference.
|
||||
|
||||
Returns:
|
||||
dict: ComfyUI INPUT_TYPES dictionary with required inputs.
|
||||
"""
|
||||
# Get the original input definitions
|
||||
types = SaveImage.INPUT_TYPES()
|
||||
# Add our prompt-related inputs
|
||||
types["required"].update({
|
||||
"positive_prompt": ("STRING", {"forceInput": True}),
|
||||
"negative_prompt": ("STRING", {"forceInput": True}),
|
||||
"save_txt": (["enabled", "disabled"], {"default": "enabled"}),
|
||||
})
|
||||
return types
|
||||
|
||||
# --- CHANGE: define return type ---
|
||||
RETURN_TYPES = ("IMAGE",)
|
||||
RETURN_NAMES = ("IMAGE",)
|
||||
# -----------------------------------
|
||||
|
||||
FUNCTION = "ta_save_images"
|
||||
OUTPUT_NODE = True
|
||||
CATEGORY = "TA Nodes/utils"
|
||||
|
||||
def ta_save_images(self, images, filename_prefix, positive_prompt, negative_prompt, save_txt, **kwargs):
|
||||
"""
|
||||
Saves images using the original SaveImage logic and optionally writes
|
||||
companion .txt prompt files.
|
||||
|
||||
Workflow:
|
||||
1. Calls self.save_images() from the base SaveImage class to perform
|
||||
the actual PNG saving and generate UI preview information.
|
||||
2. If save_txt is 'enabled', reconstructs the exact filenames using
|
||||
folder_paths.get_save_image_path() and writes a .txt file for each
|
||||
image containing timestamp, filename, and prompts.
|
||||
|
||||
File naming follows ComfyUI's standard counter convention:
|
||||
<filename_prefix>_<00001>_.png + <filename>_<00001>_.txt
|
||||
|
||||
Args:
|
||||
images: Batch IMAGE tensor (B, H, W, 3) float [0..1].
|
||||
filename_prefix (str): Base filename passed to SaveImage.
|
||||
positive_prompt (str): Positive prompt string for .txt output.
|
||||
negative_prompt (str): Negative prompt string for .txt output.
|
||||
save_txt (str): 'enabled' to write .txt companion files.
|
||||
**kwargs: Absorbs any additional ComfyUI-injected inputs.
|
||||
|
||||
Returns:
|
||||
dict: ComfyUI result dict with 'ui' (from SaveImage) and 'result'
|
||||
tuple containing the original input IMAGE tensor.
|
||||
"""
|
||||
# 1. Call the original method (saves images and generates metadata)
|
||||
snap_res = self.save_images(images=images, filename_prefix=filename_prefix, **kwargs)
|
||||
|
||||
# 2. TXT logic
|
||||
if save_txt == "enabled":
|
||||
full_output_folder, filename, counter, subfolder, filename_prefix = \
|
||||
folder_paths.get_save_image_path(
|
||||
filename_prefix,
|
||||
self.output_dir,
|
||||
images[0].shape[1],
|
||||
images[0].shape[0]
|
||||
)
|
||||
|
||||
now = datetime.datetime.now()
|
||||
date_time_str = now.strftime("%Y-%m-%d %H:%M:%S")
|
||||
|
||||
# Recalculate counter to the state BEFORE saving
|
||||
current_counter = counter - len(images)
|
||||
|
||||
for i in range(len(images)):
|
||||
file_base = f"{filename}_{current_counter:05}_"
|
||||
txt_file = f"{file_base}.txt"
|
||||
|
||||
output_text = (
|
||||
f"DATE / TIME: {date_time_str}\n"
|
||||
f"FILE: {file_base}.png\n"
|
||||
f"{'='*30}\n"
|
||||
f"POSITIVE PROMPT:\n{positive_prompt}\n\n"
|
||||
f"NEGATIVE PROMPT:\n{negative_prompt}\n"
|
||||
f"{'='*30}\n"
|
||||
)
|
||||
|
||||
try:
|
||||
file_path = os.path.join(full_output_folder, txt_file)
|
||||
with open(file_path, "w", encoding="utf-8") as f:
|
||||
f.write(output_text)
|
||||
except Exception as e:
|
||||
print(f"[TA-Nodes] Error while writing TXT: {e}")
|
||||
|
||||
current_counter += 1
|
||||
|
||||
# --- CHANGE: return images together with original UI results ---
|
||||
# snap_res contains UI preview info; we pass 'images' as workflow output.
|
||||
return {"ui": snap_res["ui"], "result": (images,)}
|
||||
|
||||
|
||||
NODE_CLASS_MAPPINGS = {
|
||||
"TASaveImageWithPrompt": TASaveImageWithPrompt
|
||||
}
|
||||
|
||||
NODE_DISPLAY_NAME_MAPPINGS = {
|
||||
"TASaveImageWithPrompt": "TA Save Image With Prompt v2.0"
|
||||
}
|
||||
@@ -0,0 +1,116 @@
|
||||
"""
|
||||
================================================================================
|
||||
Node Name : TA SeedVR2 Gate
|
||||
Created : 2025
|
||||
Modified : 2026-03-11
|
||||
Copyright : © 2026, Thomas Möhrling (thomo.ART)
|
||||
Version : 2.0
|
||||
--------------------------------------------------------------------------------
|
||||
Part of ComfyUI-TA-Nodes-Pack
|
||||
License : Apache 2.0
|
||||
|
||||
|
||||
Description:
|
||||
Enable/disable gate for SeedVR2 upscaler pipeline.
|
||||
When disabled, all upstream nodes (SeedVR2LoadDiTModel, SeedVR2LoadVAEModel,
|
||||
image source) are skipped entirely due to lazy evaluation. When enabled,
|
||||
inputs pass through unchanged for normal workflow execution.
|
||||
================================================================================
|
||||
"""
|
||||
|
||||
from comfy_execution.graph import ExecutionBlocker
|
||||
|
||||
|
||||
class TASeedVR2Gate:
|
||||
"""
|
||||
Gate node for SeedVR2 upscaler pipeline using ComfyUI lazy evaluation.
|
||||
|
||||
Controls execution of expensive upstream nodes like model loaders and image
|
||||
preparation. When enabled=False, optional inputs are never requested or
|
||||
executed, preventing unnecessary computation. When enabled=True, all inputs
|
||||
are passed through normally to downstream nodes.
|
||||
|
||||
Uses check_lazy_status() to conditionally request lazy inputs and gate()
|
||||
to either return the real inputs or ExecutionBlocker placeholders.
|
||||
"""
|
||||
|
||||
@classmethod
|
||||
def INPUT_TYPES(cls):
|
||||
"""
|
||||
Defines all input widgets shown in the ComfyUI node UI.
|
||||
|
||||
Inputs:
|
||||
enabled: Master toggle. False = bypass upstream execution entirely.
|
||||
image: (optional/lazy) IMAGE tensor from upstream source.
|
||||
dit: (optional/lazy) SEEDVR2_DIT model tensor.
|
||||
vae: (optional/lazy) SEEDVR2_VAE model tensor.
|
||||
|
||||
Returns:
|
||||
dict: ComfyUI INPUT_TYPES dictionary with required and optional inputs.
|
||||
"""
|
||||
return {
|
||||
"required": {
|
||||
"enabled": ("BOOLEAN", {"default": False}),
|
||||
},
|
||||
"optional": {
|
||||
"image": ("IMAGE", {"lazy": True}),
|
||||
"dit": ("SEEDVR2_DIT", {"lazy": True}),
|
||||
"vae": ("SEEDVR2_VAE", {"lazy": True}),
|
||||
}
|
||||
}
|
||||
|
||||
RETURN_TYPES = ("IMAGE", "SEEDVR2_DIT", "SEEDVR2_VAE")
|
||||
RETURN_NAMES = ("image", "dit", "vae")
|
||||
FUNCTION = "gate"
|
||||
CATEGORY = "TA Nodes"
|
||||
|
||||
def check_lazy_status(self, enabled, image=None, dit=None, vae=None):
|
||||
"""
|
||||
Determines which lazy inputs to request based on the enabled state.
|
||||
|
||||
Called by ComfyUI during graph planning. Returns input names only when
|
||||
enabled=True, causing upstream nodes to execute. When enabled=False,
|
||||
returns empty list to skip all upstream execution entirely.
|
||||
|
||||
Args:
|
||||
enabled (bool): Gate toggle state.
|
||||
image, dit, vae: Ignored; placeholders for lazy inputs.
|
||||
|
||||
Returns:
|
||||
list: List of input names to request, or empty list to skip.
|
||||
"""
|
||||
# Only request the inputs if the gate is enabled.
|
||||
# When enabled=False, ComfyUI skips all upstream nodes entirely.
|
||||
if enabled:
|
||||
return ["image", "dit", "vae"]
|
||||
return []
|
||||
|
||||
def gate(self, enabled, image=None, dit=None, vae=None):
|
||||
"""
|
||||
Passes inputs through when enabled, or returns blockers when disabled.
|
||||
|
||||
Main execution method. Returns real inputs for normal workflow flow or
|
||||
ExecutionBlocker placeholders that prevent downstream execution.
|
||||
|
||||
Args:
|
||||
enabled (bool): Gate toggle state.
|
||||
image: IMAGE tensor (lazy).
|
||||
dit: SEEDVR2_DIT model (lazy).
|
||||
vae: SEEDVR2_VAE model (lazy).
|
||||
|
||||
Returns:
|
||||
tuple: (image, dit, vae) or (blocker, blocker, blocker).
|
||||
"""
|
||||
if not enabled:
|
||||
blocker = ExecutionBlocker(None)
|
||||
return (blocker, blocker, blocker)
|
||||
return (image, dit, vae)
|
||||
|
||||
|
||||
NODE_CLASS_MAPPINGS = {
|
||||
"TASeedVR2Gate": TASeedVR2Gate,
|
||||
}
|
||||
|
||||
NODE_DISPLAY_NAME_MAPPINGS = {
|
||||
"TASeedVR2Gate": "TA SeedVR2 Gate v2.0"
|
||||
}
|
||||
+366
@@ -0,0 +1,366 @@
|
||||
"""
|
||||
================================================================================
|
||||
Node Name : TA Smart LLM
|
||||
Created : 2025
|
||||
Modified : 2026-03-13
|
||||
Copyright : © 2026, Thomas Möhrling (thomo.ART)
|
||||
Version : 2.2
|
||||
--------------------------------------------------------------------------------
|
||||
Part of ComfyUI-TA-Nodes-Pack
|
||||
License : Apache 2.0
|
||||
|
||||
|
||||
Description:
|
||||
Smart LLM integration for LM Studio and Ollama backends with VRAM management.
|
||||
Auto-detects vision models (tags with [Vision]), supports image input for
|
||||
multimodal prompts, optional pre/post model unloading, and model caching.
|
||||
Returns generated prompt text and execution status.
|
||||
================================================================================
|
||||
"""
|
||||
|
||||
import requests
|
||||
import torch
|
||||
import base64
|
||||
import json
|
||||
import os
|
||||
import subprocess
|
||||
from io import BytesIO
|
||||
from PIL import Image
|
||||
import time
|
||||
|
||||
CACHE_FILE = os.path.join(os.path.dirname(os.path.abspath(__file__)), "ta_smart_llm_models.json")
|
||||
|
||||
# Keywords for automatic vision model detection (lowercase)
|
||||
VISION_KEYWORDS = ["llava", "vision", "-vl-", "_vl_", "vl-", "vl_", "moondream", "minicpm-v", "internvl", "qwen-vl"]
|
||||
|
||||
# Manual additions (exact model names without backend prefix, lowercase)
|
||||
# Example: VISION_MANUAL = {"my-vision-model-7b", "another-model-13b"}
|
||||
VISION_MANUAL = set()
|
||||
|
||||
|
||||
def is_vision_model(model_id: str) -> bool:
|
||||
lower = model_id.lower()
|
||||
if any(kw in lower for kw in VISION_KEYWORDS):
|
||||
return True
|
||||
if lower in VISION_MANUAL:
|
||||
return True
|
||||
return False
|
||||
|
||||
|
||||
def tag_model(full_name: str) -> str:
|
||||
"""
|
||||
Adds [Vision] suffix if the model supports image input.
|
||||
"""
|
||||
model_id = '/'.join(full_name.split('/')[1:])
|
||||
if is_vision_model(model_id):
|
||||
return f"{full_name} [Vision]"
|
||||
return full_name
|
||||
|
||||
|
||||
def strip_vision_tag(model: str) -> str:
|
||||
"""
|
||||
Removes [Vision] tag for the API request.
|
||||
"""
|
||||
return model.replace(" [Vision]", "")
|
||||
|
||||
|
||||
class TASmartLLM:
|
||||
"""
|
||||
ComfyUI node for LLM prompt generation via LM Studio or Ollama.
|
||||
|
||||
Features:
|
||||
- Auto-discovery and caching of available models from both backends
|
||||
- Automatic vision model detection and image support
|
||||
- Optional VRAM cleanup before LLM inference (unloads ComfyUI image models)
|
||||
- Optional LLM unloading after generation to free GPU memory
|
||||
- Retry logic for transient API errors
|
||||
- Status feedback for workflow debugging
|
||||
"""
|
||||
|
||||
@classmethod
|
||||
def _load_cached_models(cls):
|
||||
try:
|
||||
with open(CACHE_FILE, "r") as f:
|
||||
return set(json.load(f))
|
||||
except:
|
||||
return set()
|
||||
|
||||
@classmethod
|
||||
def _save_cached_models(cls, models):
|
||||
try:
|
||||
with open(CACHE_FILE, "w") as f:
|
||||
json.dump(sorted(models), f)
|
||||
except:
|
||||
pass
|
||||
|
||||
@classmethod
|
||||
def get_models(cls):
|
||||
"""
|
||||
Discovers and caches available models from LM Studio (port 1234) and
|
||||
Ollama (port 11434). Tags vision-capable models with [Vision] suffix.
|
||||
|
||||
Per-backend logic:
|
||||
- If a backend responds, its models replace the cached entries for
|
||||
that backend (additions and deletions are reflected immediately).
|
||||
- If a backend is offline, its cached entries are kept unchanged so
|
||||
that saved workflows remain valid without breaking validation.
|
||||
"""
|
||||
known = cls._load_cached_models()
|
||||
|
||||
# Split cache by backend
|
||||
known_lmstudio = {m for m in known if m.startswith("LMStudio/")}
|
||||
known_ollama = {m for m in known if m.startswith("Ollama/")}
|
||||
|
||||
# Query LM Studio — replace cache if reachable
|
||||
try:
|
||||
r = requests.get("http://127.0.0.1:1234/v1/models", timeout=2)
|
||||
if r.status_code == 200:
|
||||
known_lmstudio = {f"LMStudio/{m['id']}" for m in r.json()['data']}
|
||||
except:
|
||||
pass # offline — keep existing cache
|
||||
|
||||
# Query Ollama — replace cache if reachable
|
||||
try:
|
||||
r = requests.get("http://127.0.0.1:11434/api/tags", timeout=2)
|
||||
if r.status_code == 200:
|
||||
known_ollama = {f"Ollama/{m['name']}" for m in r.json()['models']}
|
||||
except:
|
||||
pass # offline — keep existing cache
|
||||
|
||||
all_models = known_lmstudio | known_ollama
|
||||
cls._save_cached_models(all_models)
|
||||
|
||||
tagged = [tag_model(m) for m in sorted(all_models)]
|
||||
return tagged if tagged else ["No Backend"]
|
||||
|
||||
@classmethod
|
||||
def INPUT_TYPES(cls):
|
||||
"""
|
||||
Defines all input widgets shown in the ComfyUI node UI.
|
||||
|
||||
Required Inputs:
|
||||
llm_enable: Master toggle to enable/disable the entire node.
|
||||
model: Dropdown of discovered models (LMStudio/Ollama, vision-tagged).
|
||||
user_prompt: Main user input prompt (multiline).
|
||||
system_prompt: System instruction for the LLM.
|
||||
unload_image_models_first: Unload ComfyUI image models before inference.
|
||||
unload_llm_after: Unload LLM model from backend after generation.
|
||||
|
||||
Optional Inputs:
|
||||
image: IMAGE tensor for vision models (auto-detected).
|
||||
|
||||
Returns:
|
||||
dict: ComfyUI INPUT_TYPES dictionary.
|
||||
"""
|
||||
models = cls.get_models()
|
||||
return {
|
||||
"required": {
|
||||
"llm_enable": ("BOOLEAN", {"default": True, "label_on": "✅ LLM ON", "label_off": "❌ OFF"}),
|
||||
"model": (models, {"default": models[0] if models else "No Backend"}),
|
||||
"user_prompt": ("STRING", {"multiline": True, "default": ""}),
|
||||
"system_prompt": ("STRING", {"multiline": True, "default": "You are an expert SD prompt generator."}),
|
||||
"unload_image_models_first": ("BOOLEAN", {"default": False}),
|
||||
"unload_llm_after": ("BOOLEAN", {"default": False}),
|
||||
},
|
||||
"optional": {
|
||||
"image": ("IMAGE",)
|
||||
}
|
||||
}
|
||||
|
||||
RETURN_TYPES = ("STRING", "STRING")
|
||||
RETURN_NAMES = ("prompt", "status")
|
||||
FUNCTION = "generate"
|
||||
CATEGORY = "TA Tools"
|
||||
|
||||
@classmethod
|
||||
def IS_CHANGED(cls, *args, **kwargs):
|
||||
return time.time()
|
||||
|
||||
def _backend_reachable(self, backend, port):
|
||||
"""
|
||||
Checks if LM Studio or Ollama backend is responding.
|
||||
"""
|
||||
try:
|
||||
url = f"http://127.0.0.1:{port}/v1/models" if "LMStudio" in backend else f"http://127.0.0.1:{port}/api/tags"
|
||||
return requests.get(url, timeout=2).status_code == 200
|
||||
except:
|
||||
return False
|
||||
|
||||
def _unload_comfyui_models(self):
|
||||
"""
|
||||
Unloads all ComfyUI image models from VRAM to free GPU memory.
|
||||
"""
|
||||
try:
|
||||
import comfy.model_management as mm
|
||||
mm.unload_all_models()
|
||||
mm.soft_empty_cache()
|
||||
except Exception as e:
|
||||
print(f"[TA Smart LLM] Warning: Could not unload image models: {e}")
|
||||
|
||||
def _unload_lmstudio_llm(self):
|
||||
"""
|
||||
Unloads the active LM Studio model via lms CLI tool.
|
||||
"""
|
||||
try:
|
||||
subprocess.run(["lms", "unload", "--all"], timeout=15, capture_output=True)
|
||||
print(f"[TA Smart LLM] LM Studio model unloaded successfully.")
|
||||
except Exception as e:
|
||||
print(f"[TA Smart LLM] Warning: Could not unload LM Studio model: {e}")
|
||||
|
||||
def _unload_ollama_llm(self, model_name):
|
||||
"""
|
||||
Unloads an Ollama model by calling it with keep_alive=0.
|
||||
"""
|
||||
try:
|
||||
requests.post("http://127.0.0.1:11434/api/generate", json={
|
||||
"model": model_name,
|
||||
"keep_alive": 0
|
||||
}, timeout=10)
|
||||
print(f"[TA Smart LLM] Ollama model unloaded successfully: {model_name}")
|
||||
except Exception as e:
|
||||
print(f"[TA Smart LLM] Warning: Could not unload Ollama model: {e}")
|
||||
|
||||
def _build_image_b64(self, image):
|
||||
"""
|
||||
Converts IMAGE tensor to base64 PNG for vision model input.
|
||||
"""
|
||||
img_array = (255 * image[0].cpu().numpy()).astype('uint8')
|
||||
img = Image.fromarray(img_array)
|
||||
buffer = BytesIO()
|
||||
img.save(buffer, 'PNG')
|
||||
return base64.b64encode(buffer.getvalue()).decode('utf-8')
|
||||
|
||||
def _flush_lmstudio_context(self, url, model_name):
|
||||
"""
|
||||
Sends a minimal request to clear LM Studio chat context.
|
||||
"""
|
||||
try:
|
||||
requests.post(url, json={
|
||||
"model": model_name,
|
||||
"messages": [{"role": "user", "content": "."}],
|
||||
"max_tokens": 1
|
||||
}, timeout=10)
|
||||
except:
|
||||
pass
|
||||
time.sleep(0.5)
|
||||
|
||||
def _post_with_retry(self, url, payload, is_lmstudio, max_retries=3, retry_delay=1.5):
|
||||
"""
|
||||
Posts to LLM API with retry logic for transient errors.
|
||||
"""
|
||||
last_error = None
|
||||
for attempt in range(1, max_retries + 1):
|
||||
try:
|
||||
r = requests.post(url, json=payload, timeout=120)
|
||||
r.raise_for_status()
|
||||
return r.json()['choices'][0]['message']['content'] if is_lmstudio else r.json()['response']
|
||||
except requests.exceptions.HTTPError as e:
|
||||
last_error = e
|
||||
if e.response is not None and e.response.status_code in (400, 500, 502, 503) and attempt < max_retries:
|
||||
time.sleep(retry_delay)
|
||||
continue
|
||||
raise
|
||||
except requests.exceptions.RequestException as e:
|
||||
last_error = e
|
||||
if attempt < max_retries:
|
||||
time.sleep(retry_delay)
|
||||
continue
|
||||
raise
|
||||
raise last_error
|
||||
|
||||
def generate(self, llm_enable, model, user_prompt, system_prompt,
|
||||
unload_image_models_first=False, unload_llm_after=False,
|
||||
image=None):
|
||||
"""
|
||||
Main generation method. Queries the selected LLM and returns prompt + status.
|
||||
|
||||
Workflow:
|
||||
1. Skip if disabled or backend unreachable.
|
||||
2. Optionally unload ComfyUI models for VRAM.
|
||||
3. Build payload (text + optional image b64).
|
||||
4. Send request to LM Studio/Ollama with retries.
|
||||
5. Optionally unload LLM model after.
|
||||
|
||||
Args:
|
||||
llm_enable (bool): Master enable toggle.
|
||||
model (str): Selected model (tagged).
|
||||
user_prompt (str): User input.
|
||||
system_prompt (str): System instruction.
|
||||
unload_image_models_first (bool): Free VRAM before.
|
||||
unload_llm_after (bool): Free VRAM after.
|
||||
image: Optional IMAGE for vision models.
|
||||
|
||||
Returns:
|
||||
tuple: (generated_prompt: str, status: str)
|
||||
"""
|
||||
if not llm_enable:
|
||||
return ("", "DISABLED")
|
||||
|
||||
clean_model = strip_vision_tag(model)
|
||||
backend = clean_model.split('/')[0]
|
||||
model_name = '/'.join(clean_model.split('/')[1:])
|
||||
port = 1234 if "LMStudio" in backend else 11434
|
||||
|
||||
if not self._backend_reachable(backend, port):
|
||||
return ("", f"SKIPPED - {backend} not reachable")
|
||||
|
||||
print(f"[TA Smart LLM] Loading model: {clean_model}")
|
||||
|
||||
# Unload ComfyUI image models before LLM request
|
||||
if unload_image_models_first:
|
||||
self._unload_comfyui_models()
|
||||
|
||||
full_prompt = user_prompt.strip()
|
||||
|
||||
img_b64 = self._build_image_b64(image) if image is not None else None
|
||||
|
||||
try:
|
||||
if "LMStudio" in backend:
|
||||
url = f"http://127.0.0.1:{port}/v1/chat/completions"
|
||||
if img_b64:
|
||||
self._flush_lmstudio_context(url, model_name)
|
||||
user_content = [
|
||||
{"type": "text", "text": full_prompt},
|
||||
{"type": "image_url", "image_url": {"url": f"data:image/png;base64,{img_b64}"}}
|
||||
]
|
||||
else:
|
||||
user_content = full_prompt
|
||||
payload = {
|
||||
"model": model_name,
|
||||
"messages": [
|
||||
{"role": "system", "content": system_prompt},
|
||||
{"role": "user", "content": user_content}
|
||||
],
|
||||
"max_tokens": 1024
|
||||
}
|
||||
|
||||
result = self._post_with_retry(url, payload, is_lmstudio=True)
|
||||
|
||||
# Unload LM Studio model after request
|
||||
if unload_llm_after:
|
||||
self._unload_lmstudio_llm()
|
||||
|
||||
else: # Ollama
|
||||
url = f"http://127.0.0.1:{port}/api/generate"
|
||||
payload = {
|
||||
"model": model_name,
|
||||
"prompt": f"{system_prompt}\n\n{full_prompt}".strip(),
|
||||
"stream": False
|
||||
}
|
||||
|
||||
if img_b64:
|
||||
payload["images"] = [img_b64]
|
||||
result = self._post_with_retry(url, payload, is_lmstudio=False)
|
||||
|
||||
# Unload Ollama model after request
|
||||
if unload_llm_after:
|
||||
self._unload_ollama_llm(model_name)
|
||||
|
||||
return (result.strip(), f"{clean_model} ✅")
|
||||
|
||||
except Exception as e:
|
||||
return (f"ERROR: {str(e)}", clean_model)
|
||||
|
||||
|
||||
NODE_CLASS_MAPPINGS = {"TASmartLLM": TASmartLLM}
|
||||
NODE_DISPLAY_NAME_MAPPINGS = {"TASmartLLM": "TA Smart LLM v2.2"}
|
||||
@@ -0,0 +1 @@
|
||||
["LMStudio/cognitivecomputations_dolphin-mistral-24b-venice-edition", "LMStudio/cydonia-24b-v4.1", "LMStudio/deepseek-coder-v2-lite-16b", "LMStudio/gemma-3-27b-it-qat", "LMStudio/huihui-qwen3-vl-8b-instruct-abliterated", "LMStudio/llama-3.1-unhinged-vision-8b", "LMStudio/llama-3.2-1b-instruct", "LMStudio/llava-v1.5-7b-llamafile", "LMStudio/mistral-catmacaroni-slerp-uncensored-7b", "LMStudio/mistral-small-3.1-draft-0.5b", "LMStudio/mistralai/devstral-small-2-2512", "LMStudio/mistralai/ministral-3-14b-reasoning", "LMStudio/qwen2.5-0.5b-instruct", "LMStudio/qwen2.5-0.5b-song-lyrics-generation", "LMStudio/qwen3-30b-a3b-thinking-2507-claude-4.5-sonnet-high-reasoning-distill", "LMStudio/qwen3-4b-thinking-2507", "LMStudio/qwen3-coder-30b-a3b-instruct", "LMStudio/qwen3-vl-8b-instruct", "LMStudio/text-embedding-nomic-embed-text-v1.5", "LMStudio/wizardlm-1.0-uncensored-llama2-13b", "LMStudio/xortron2025"]
|
||||
@@ -0,0 +1,285 @@
|
||||
"""
|
||||
================================================================================
|
||||
Node Name : TA Unified Model Switcher
|
||||
Created : 2025
|
||||
Modified : 2026-03-11
|
||||
Copyright : © 2026, Thomas Möhrling (thomo.ART)
|
||||
Version : 2.0
|
||||
--------------------------------------------------------------------------------
|
||||
Part of ComfyUI-TA-Nodes-Pack
|
||||
License : Apache 2.0
|
||||
|
||||
|
||||
Description:
|
||||
Unified model switcher with dynamic slots (up to 3) and browser-based editor.
|
||||
Uses ta_model_choices.json for dropdown options. Lazy evaluation loads only
|
||||
the selected model's MODEL/CLIP/VAE. Web UI at http://localhost:8188/ta_model_choices/ui
|
||||
for editing choices without code changes.
|
||||
================================================================================
|
||||
"""
|
||||
|
||||
import os
|
||||
import json
|
||||
from aiohttp import web
|
||||
from server import PromptServer
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Paths
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
_DIR = os.path.dirname(os.path.abspath(__file__))
|
||||
_JSON_PATH = os.path.join(_DIR, "ta_model_choices.json")
|
||||
_HTML_PATH = os.path.join(_DIR, "web", "js", "ta_model_choices_ui.html")
|
||||
|
||||
_DEFAULT_CHOICES = [
|
||||
"Z-Image Diffusion",
|
||||
"Z-Image GGUF",
|
||||
"Qwen Diffusion",
|
||||
"FLUX Diffusion",
|
||||
"Checkpoint",
|
||||
]
|
||||
|
||||
|
||||
def _load_choices() -> list:
|
||||
"""
|
||||
Loads model choices from ta_model_choices.json, falls back to defaults.
|
||||
"""
|
||||
if not os.path.exists(_JSON_PATH):
|
||||
_save_choices(_DEFAULT_CHOICES.copy())
|
||||
return _DEFAULT_CHOICES.copy()
|
||||
try:
|
||||
with open(_JSON_PATH, "r", encoding="utf-8") as f:
|
||||
data = json.load(f)
|
||||
return data.get("choices", _DEFAULT_CHOICES.copy())
|
||||
except Exception as e:
|
||||
print(f"[TAUnifiedModelSwitcher] Error loading JSON: {e}")
|
||||
return _DEFAULT_CHOICES.copy()
|
||||
|
||||
|
||||
def _save_choices(choices: list) -> None:
|
||||
"""
|
||||
Saves model choices to ta_model_choices.json.
|
||||
"""
|
||||
try:
|
||||
with open(_JSON_PATH, "w", encoding="utf-8") as f:
|
||||
json.dump({"choices": choices}, f, indent=4, ensure_ascii=False)
|
||||
except Exception as e:
|
||||
print(f"[TAUnifiedModelSwitcher] Error saving JSON: {e}")
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Web Endpoints
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
@PromptServer.instance.routes.get("/ta_model_choices/ui")
|
||||
async def ta_choices_ui(request):
|
||||
"""
|
||||
Serves the browser-based model choices editor HTML.
|
||||
"""
|
||||
if not os.path.exists(_HTML_PATH):
|
||||
return web.Response(text="HTML not found.", status=404)
|
||||
with open(_HTML_PATH, "r", encoding="utf-8") as f:
|
||||
return web.Response(text=f.read(), content_type="text/html")
|
||||
|
||||
|
||||
@PromptServer.instance.routes.get("/ta_model_choices/list")
|
||||
async def ta_choices_list(request):
|
||||
"""
|
||||
API endpoint to retrieve current model choices.
|
||||
"""
|
||||
return web.json_response({"choices": _load_choices()})
|
||||
|
||||
|
||||
@PromptServer.instance.routes.post("/ta_model_choices/save")
|
||||
async def ta_choices_save(request):
|
||||
"""
|
||||
API endpoint to save updated model choices.
|
||||
"""
|
||||
try:
|
||||
body = await request.json()
|
||||
choices = body.get("choices", [])
|
||||
choices = [str(c).strip() for c in choices if str(c).strip()]
|
||||
if not choices:
|
||||
return web.json_response({"ok": False, "error": "List cannot be empty."})
|
||||
_save_choices(choices)
|
||||
print(f"[TAUnifiedModelSwitcher] Choices saved: {choices}")
|
||||
return web.json_response({"ok": True})
|
||||
except Exception as e:
|
||||
return web.json_response({"ok": False, "error": str(e)})
|
||||
|
||||
|
||||
def _build_slot_map() -> dict:
|
||||
"""
|
||||
Dynamically generates SLOT_MAP from JSON choices.
|
||||
List position = slot number (1-based).
|
||||
"""
|
||||
choices = _load_choices()
|
||||
return {
|
||||
choice: [f"model_{i+1}", f"clip_{i+1}", f"vae_{i+1}", f"model_name_{i+1}"]
|
||||
for i, choice in enumerate(choices)
|
||||
}
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Node
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
class TAUnifiedModelSwitcher:
|
||||
"""
|
||||
Unified Model Switcher node supporting up to 3 dynamic slots.
|
||||
|
||||
Features:
|
||||
- model_choice: Dropdown populated from ta_model_choices.json
|
||||
- Optional lazy inputs for each slot: model/clip/vae/model_name
|
||||
- Lazy evaluation: only active slot's upstream nodes execute
|
||||
- Dynamic SLOT_MAP generated from JSON choices
|
||||
- Browser editor: http://localhost:8188/ta_model_choices/ui
|
||||
|
||||
Usage: Connect model loader groups to slots 1-3. Select via dropdown.
|
||||
"""
|
||||
|
||||
@classmethod
|
||||
def INPUT_TYPES(cls):
|
||||
"""
|
||||
Defines all input widgets shown in the ComfyUI node UI.
|
||||
|
||||
Required Inputs:
|
||||
model_choice: Dropdown of choices from JSON (editable via web UI).
|
||||
|
||||
Optional Inputs (lazy):
|
||||
model_1/clip_1/vae_1/model_name_1: Slot 1 inputs
|
||||
model_2/clip_2/vae_2/model_name_2: Slot 2 inputs
|
||||
model_3/clip_3/vae_3/model_name_3: Slot 3 inputs
|
||||
|
||||
Returns:
|
||||
dict: ComfyUI INPUT_TYPES dictionary.
|
||||
"""
|
||||
choices = _load_choices()
|
||||
return {
|
||||
"required": {
|
||||
"model_choice": (choices, {
|
||||
"default": choices[0],
|
||||
"tooltip": "Editor: http://localhost:8188/ta_model_choices/ui",
|
||||
}),
|
||||
},
|
||||
"optional": {
|
||||
"model_1": ("MODEL", {"lazy": True}),
|
||||
"clip_1": ("CLIP", {"lazy": True}),
|
||||
"vae_1": ("VAE", {"lazy": True}),
|
||||
"model_name_1": ("TA_MODEL_NAME", {"lazy": True}),
|
||||
|
||||
"model_2": ("MODEL", {"lazy": True}),
|
||||
"clip_2": ("CLIP", {"lazy": True}),
|
||||
"vae_2": ("VAE", {"lazy": True}),
|
||||
"model_name_2": ("TA_MODEL_NAME", {"lazy": True}),
|
||||
|
||||
"model_3": ("MODEL", {"lazy": True}),
|
||||
"clip_3": ("CLIP", {"lazy": True}),
|
||||
"vae_3": ("VAE", {"lazy": True}),
|
||||
"model_name_3": ("TA_MODEL_NAME", {"lazy": True}),
|
||||
}
|
||||
}
|
||||
|
||||
RETURN_TYPES = ("MODEL", "CLIP", "VAE", "TA_MODEL_NAME")
|
||||
RETURN_NAMES = ("model", "clip", "vae", "active_model")
|
||||
FUNCTION = "select"
|
||||
CATEGORY = "TA Nodes/loaders"
|
||||
|
||||
@classmethod
|
||||
def IS_CHANGED(cls, model_choice, **kwargs):
|
||||
"""
|
||||
Triggers re-execution when model_choice changes.
|
||||
"""
|
||||
return model_choice
|
||||
|
||||
def check_lazy_status(self, model_choice, **kwargs):
|
||||
"""
|
||||
Determines which lazy inputs to request for the selected slot.
|
||||
|
||||
Called during graph planning. Returns only the inputs for the active
|
||||
slot, enabling lazy evaluation.
|
||||
|
||||
Args:
|
||||
model_choice (str): Selected choice from dropdown.
|
||||
|
||||
Returns:
|
||||
list: Input names for the active slot.
|
||||
"""
|
||||
slot_map = _build_slot_map()
|
||||
needed = slot_map.get(model_choice)
|
||||
if needed:
|
||||
print(f"[TAUnifiedModelSwitcher] Loading slot: '{model_choice}' → {needed}")
|
||||
return needed
|
||||
all_inputs = []
|
||||
for v in slot_map.values():
|
||||
all_inputs.extend(v)
|
||||
return all_inputs
|
||||
|
||||
def select(
|
||||
self,
|
||||
model_choice,
|
||||
model_1=None, clip_1=None, vae_1=None, model_name_1=None,
|
||||
model_2=None, clip_2=None, vae_2=None, model_name_2=None,
|
||||
model_3=None, clip_3=None, vae_3=None, model_name_3=None,
|
||||
):
|
||||
"""
|
||||
Selects and returns MODEL/CLIP/VAE from the active slot.
|
||||
|
||||
Validates connections and slot index. Falls back to model_choice as
|
||||
name if model_name input is missing.
|
||||
|
||||
Args:
|
||||
model_choice (str): Selected slot identifier.
|
||||
model_1..model_name_3: All slot inputs (lazy).
|
||||
|
||||
Returns:
|
||||
tuple: (MODEL, CLIP, VAE, active_model_name)
|
||||
|
||||
Raises:
|
||||
ValueError: Invalid choice, missing connections, or slot overflow.
|
||||
"""
|
||||
all_models = [model_1, model_2, model_3]
|
||||
all_clips = [clip_1, clip_2, clip_3]
|
||||
all_vaes = [vae_1, vae_2, vae_3]
|
||||
all_names = [model_name_1, model_name_2, model_name_3]
|
||||
|
||||
slot_map = _build_slot_map()
|
||||
if model_choice not in slot_map:
|
||||
raise ValueError(
|
||||
f"[TAUnifiedModelSwitcher] Unknown model_choice: '{model_choice}'\n"
|
||||
f"Available options: {list(slot_map.keys())}"
|
||||
)
|
||||
|
||||
slot_inputs = slot_map[model_choice]
|
||||
idx = int(slot_inputs[0].split("_")[1]) - 1
|
||||
|
||||
if idx >= 3:
|
||||
raise ValueError(
|
||||
f"[TAUnifiedModelSwitcher] Slot index {idx+1} exceeds maximum (3)."
|
||||
)
|
||||
|
||||
model = all_models[idx]
|
||||
clip = all_clips[idx]
|
||||
vae = all_vaes[idx]
|
||||
name = all_names[idx]
|
||||
|
||||
if model is None or clip is None or vae is None:
|
||||
raise ValueError(
|
||||
f"[TAUnifiedModelSwitcher] Slot '{model_choice}' (#{idx+1}) not connected "
|
||||
f"(model={model is not None}, clip={clip is not None}, vae={vae is not None})."
|
||||
)
|
||||
|
||||
if name is None:
|
||||
name = model_choice
|
||||
|
||||
print(f"[TAUnifiedModelSwitcher] Active: '{model_choice}' → '{name}'")
|
||||
return (model, clip, vae, name)
|
||||
|
||||
|
||||
NODE_CLASS_MAPPINGS = {
|
||||
"TAUnifiedModelSwitcher": TAUnifiedModelSwitcher
|
||||
}
|
||||
|
||||
NODE_DISPLAY_NAME_MAPPINGS = {
|
||||
"TAUnifiedModelSwitcher": "🧠 TA Unified Model Switcher v2.0"
|
||||
}
|
||||
Vendored
+69
File diff suppressed because one or more lines are too long
@@ -0,0 +1,147 @@
|
||||
/**
|
||||
* TADiscordLink — ComfyUI JS Widget Extension
|
||||
* © 2026, Thomas Möhrling (thomo.ART)
|
||||
* Version: 2.0
|
||||
*
|
||||
* Fetches the Discord invite URL from GET /ta_discord_link/config and renders
|
||||
* a styled Discord button inside the TADiscordLink node. Opens the server in
|
||||
* a new browser tab on click.
|
||||
*
|
||||
* The URL and label can be edited at http://localhost:8188/ta_discord_link/ui
|
||||
*/
|
||||
|
||||
import { app } from "../../scripts/app.js";
|
||||
|
||||
const DISCORD_PURPLE = "#5865F2";
|
||||
const DISCORD_PURPLE_HOVER = "#4752C4";
|
||||
|
||||
const DISCORD_SVG = `<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24"
|
||||
width="18" height="18" fill="white"
|
||||
style="margin-right:6px;flex-shrink:0;">
|
||||
<path d="M20.317 4.37a19.791 19.791 0 0 0-4.885-1.515.074.074 0 0 0-.079.037
|
||||
c-.21.375-.444.864-.608 1.25a18.27 18.27 0 0 0-5.487 0
|
||||
12.64 12.64 0 0 0-.617-1.25.077.077 0 0 0-.079-.037
|
||||
A19.736 19.736 0 0 0 3.677 4.37a.07.07 0 0 0-.032.027
|
||||
C.533 9.046-.32 13.58.099 18.057a.082.082 0 0 0 .031.057
|
||||
19.9 19.9 0 0 0 5.993 3.03.078.078 0 0 0 .084-.028
|
||||
14.09 14.09 0 0 0 1.226-1.994.076.076 0 0 0-.041-.106
|
||||
13.107 13.107 0 0 1-1.872-.892.077.077 0 0 1-.008-.128
|
||||
10.2 10.2 0 0 0 .372-.292.074.074 0 0 1 .077-.01
|
||||
c3.928 1.793 8.18 1.793 12.062 0a.074.074 0 0 1 .078.01
|
||||
c.12.098.246.198.373.292a.077.077 0 0 1-.006.127
|
||||
12.299 12.299 0 0 1-1.873.892.077.077 0 0 0-.041.107
|
||||
c.36.698.772 1.362 1.225 1.993a.076.076 0 0 0 .084.028
|
||||
19.839 19.839 0 0 0 6.002-3.03.077.077 0 0 0 .032-.054
|
||||
c.5-5.177-.838-9.674-3.549-13.66a.061.061 0 0 0-.031-.03z
|
||||
M8.02 15.33c-1.183 0-2.157-1.085-2.157-2.419
|
||||
0-1.333.956-2.419 2.157-2.419
|
||||
1.21 0 2.176 1.096 2.157 2.42
|
||||
0 1.333-.956 2.418-2.157 2.418z
|
||||
m7.975 0c-1.183 0-2.157-1.085-2.157-2.419
|
||||
0-1.333.955-2.419 2.157-2.419
|
||||
1.21 0 2.176 1.096 2.157 2.42
|
||||
0 1.333-.946 2.418-2.157 2.418z"/>
|
||||
</svg>`;
|
||||
|
||||
/** Fetch config once per page load and cache it. */
|
||||
let _configCache = null;
|
||||
async function _getConfig() {
|
||||
if (_configCache) return _configCache;
|
||||
try {
|
||||
const res = await fetch("/ta_discord_link/config");
|
||||
if (res.ok) _configCache = await res.json();
|
||||
} catch (e) {
|
||||
console.warn("[TADiscordLink] Could not fetch config:", e);
|
||||
}
|
||||
return _configCache ?? { discord_url: "#", label: "Join us on Discord" };
|
||||
}
|
||||
|
||||
app.registerExtension({
|
||||
name: "thomo.ART.TADiscordLink",
|
||||
|
||||
async beforeRegisterNodeDef(nodeType, nodeData) {
|
||||
if (nodeData.name !== "TADiscordLink") return;
|
||||
|
||||
const onNodeCreated = nodeType.prototype.onNodeCreated;
|
||||
|
||||
nodeType.prototype.onNodeCreated = function () {
|
||||
onNodeCreated?.apply(this, arguments);
|
||||
|
||||
this.size = [280, 90];
|
||||
this.resizable = false;
|
||||
|
||||
// ── Wrapper div (needed for DOM widget sizing) ────────────────
|
||||
const wrapper = document.createElement("div");
|
||||
Object.assign(wrapper.style, {
|
||||
display: "flex",
|
||||
flexDirection: "column",
|
||||
gap: "6px",
|
||||
width: "100%",
|
||||
boxSizing: "border-box",
|
||||
});
|
||||
|
||||
// ── Discord button ────────────────────────────────────────────
|
||||
const btn = document.createElement("a");
|
||||
btn.target = "_blank";
|
||||
btn.rel = "noopener noreferrer";
|
||||
btn.href = "#"; // replaced after config loads
|
||||
|
||||
Object.assign(btn.style, {
|
||||
display: "inline-flex",
|
||||
alignItems: "center",
|
||||
justifyContent: "center",
|
||||
width: "100%",
|
||||
padding: "8px 14px",
|
||||
background: DISCORD_PURPLE,
|
||||
color: "white",
|
||||
fontFamily: "'gg sans', 'Noto Sans', sans-serif",
|
||||
fontSize: "14px",
|
||||
fontWeight: "600",
|
||||
borderRadius: "6px",
|
||||
textDecoration: "none",
|
||||
cursor: "pointer",
|
||||
boxSizing: "border-box",
|
||||
transition: "background 0.15s ease",
|
||||
userSelect: "none",
|
||||
});
|
||||
|
||||
btn.innerHTML = DISCORD_SVG + "Join us on Discord";
|
||||
|
||||
btn.addEventListener("mouseenter", () => { btn.style.background = DISCORD_PURPLE_HOVER; });
|
||||
btn.addEventListener("mouseleave", () => { btn.style.background = DISCORD_PURPLE; });
|
||||
// Prevent LiteGraph from swallowing the click
|
||||
btn.addEventListener("pointerdown", (e) => e.stopPropagation());
|
||||
|
||||
// ── Edit-link ─────────────────────────────────────────────────
|
||||
const editLink = document.createElement("a");
|
||||
editLink.href = "/ta_discord_link/ui";
|
||||
editLink.target = "_blank";
|
||||
editLink.rel = "noopener noreferrer";
|
||||
editLink.textContent = "⚙ Edit link…";
|
||||
Object.assign(editLink.style, {
|
||||
fontSize: "11px",
|
||||
color: "#aaa",
|
||||
textDecoration: "none",
|
||||
textAlign: "center",
|
||||
display: "block",
|
||||
});
|
||||
editLink.addEventListener("mouseenter", () => { editLink.style.color = "#fff"; });
|
||||
editLink.addEventListener("mouseleave", () => { editLink.style.color = "#aaa"; });
|
||||
editLink.addEventListener("pointerdown", (e) => e.stopPropagation());
|
||||
|
||||
wrapper.appendChild(btn);
|
||||
wrapper.appendChild(editLink);
|
||||
|
||||
this.addDOMWidget("discord_widget", "div", wrapper, {
|
||||
getValue: () => "",
|
||||
setValue: () => {},
|
||||
});
|
||||
|
||||
// ── Load config and update button ─────────────────────────────
|
||||
_getConfig().then(cfg => {
|
||||
btn.href = cfg.discord_url ?? "#";
|
||||
btn.innerHTML = DISCORD_SVG + (cfg.label ?? "Join us on Discord");
|
||||
});
|
||||
};
|
||||
},
|
||||
});
|
||||
@@ -0,0 +1,265 @@
|
||||
<!DOCTYPE html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="UTF-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||||
<title>TA Discord Link — Editor</title>
|
||||
<style>
|
||||
:root {
|
||||
--bg: #1e1e2e;
|
||||
--surface: #2a2a3e;
|
||||
--border: #3a3a5a;
|
||||
--accent: #5865F2;
|
||||
--accent-h: #4752C4;
|
||||
--text: #cdd6f4;
|
||||
--muted: #7f849c;
|
||||
--success: #a6e3a1;
|
||||
--error: #f38ba8;
|
||||
--radius: 8px;
|
||||
}
|
||||
|
||||
*, *::before, *::after { box-sizing: border-box; margin: 0; padding: 0; }
|
||||
|
||||
body {
|
||||
background: var(--bg);
|
||||
color: var(--text);
|
||||
font-family: 'Segoe UI', 'gg sans', 'Noto Sans', sans-serif;
|
||||
font-size: 14px;
|
||||
min-height: 100vh;
|
||||
display: flex;
|
||||
align-items: flex-start;
|
||||
justify-content: center;
|
||||
padding: 40px 16px;
|
||||
}
|
||||
|
||||
.card {
|
||||
background: var(--surface);
|
||||
border: 1px solid var(--border);
|
||||
border-radius: var(--radius);
|
||||
width: 100%;
|
||||
max-width: 520px;
|
||||
padding: 28px 32px;
|
||||
}
|
||||
|
||||
/* ── Header ── */
|
||||
.header {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 12px;
|
||||
margin-bottom: 28px;
|
||||
}
|
||||
.header svg { flex-shrink: 0; }
|
||||
.header h1 { font-size: 18px; font-weight: 700; }
|
||||
.header p { font-size: 12px; color: var(--muted); margin-top: 2px; }
|
||||
|
||||
/* ── Form ── */
|
||||
label {
|
||||
display: block;
|
||||
font-size: 12px;
|
||||
font-weight: 600;
|
||||
color: var(--muted);
|
||||
text-transform: uppercase;
|
||||
letter-spacing: .05em;
|
||||
margin-bottom: 6px;
|
||||
}
|
||||
|
||||
input[type="text"], input[type="url"] {
|
||||
width: 100%;
|
||||
padding: 9px 12px;
|
||||
background: var(--bg);
|
||||
border: 1px solid var(--border);
|
||||
border-radius: 6px;
|
||||
color: var(--text);
|
||||
font-size: 13px;
|
||||
outline: none;
|
||||
transition: border-color 0.15s;
|
||||
}
|
||||
input:focus { border-color: var(--accent); }
|
||||
|
||||
.field { margin-bottom: 18px; }
|
||||
.hint { font-size: 11px; color: var(--muted); margin-top: 5px; }
|
||||
|
||||
/* ── Preview ── */
|
||||
.preview-label {
|
||||
font-size: 12px;
|
||||
font-weight: 600;
|
||||
color: var(--muted);
|
||||
text-transform: uppercase;
|
||||
letter-spacing: .05em;
|
||||
margin-bottom: 8px;
|
||||
}
|
||||
.preview-wrap {
|
||||
background: var(--bg);
|
||||
border: 1px solid var(--border);
|
||||
border-radius: 6px;
|
||||
padding: 14px;
|
||||
margin-bottom: 22px;
|
||||
}
|
||||
#preview-btn {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
width: 100%;
|
||||
padding: 8px 14px;
|
||||
background: var(--accent);
|
||||
color: white;
|
||||
font-family: inherit;
|
||||
font-size: 14px;
|
||||
font-weight: 600;
|
||||
border-radius: 6px;
|
||||
text-decoration: none;
|
||||
cursor: pointer;
|
||||
transition: background 0.15s;
|
||||
user-select: none;
|
||||
}
|
||||
#preview-btn:hover { background: var(--accent-h); }
|
||||
|
||||
/* ── Save button ── */
|
||||
#save-btn {
|
||||
width: 100%;
|
||||
padding: 10px;
|
||||
background: var(--accent);
|
||||
color: white;
|
||||
border: none;
|
||||
border-radius: 6px;
|
||||
font-size: 14px;
|
||||
font-weight: 600;
|
||||
cursor: pointer;
|
||||
transition: background 0.15s;
|
||||
}
|
||||
#save-btn:hover { background: var(--accent-h); }
|
||||
#save-btn:disabled { opacity: 0.5; cursor: not-allowed; }
|
||||
|
||||
/* ── Toast ── */
|
||||
#toast {
|
||||
margin-top: 14px;
|
||||
padding: 9px 12px;
|
||||
border-radius: 6px;
|
||||
font-size: 13px;
|
||||
font-weight: 500;
|
||||
text-align: center;
|
||||
display: none;
|
||||
}
|
||||
#toast.ok { background: #1e3a2f; color: var(--success); border: 1px solid var(--success); }
|
||||
#toast.err { background: #3a1e26; color: var(--error); border: 1px solid var(--error); }
|
||||
|
||||
/* ── Discord logo SVG ── */
|
||||
.discord-icon {
|
||||
margin-right: 7px;
|
||||
flex-shrink: 0;
|
||||
}
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
<div class="card">
|
||||
|
||||
<!-- Header -->
|
||||
<div class="header">
|
||||
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" width="32" height="32" fill="#5865F2">
|
||||
<path d="M20.317 4.37a19.791 19.791 0 0 0-4.885-1.515.074.074 0 0 0-.079.037c-.21.375-.444.864-.608 1.25a18.27 18.27 0 0 0-5.487 0 12.64 12.64 0 0 0-.617-1.25.077.077 0 0 0-.079-.037A19.736 19.736 0 0 0 3.677 4.37a.07.07 0 0 0-.032.027C.533 9.046-.32 13.58.099 18.057a.082.082 0 0 0 .031.057 19.9 19.9 0 0 0 5.993 3.03.078.078 0 0 0 .084-.028 14.09 14.09 0 0 0 1.226-1.994.076.076 0 0 0-.041-.106 13.107 13.107 0 0 1-1.872-.892.077.077 0 0 1-.008-.128 10.2 10.2 0 0 0 .372-.292.074.074 0 0 1 .077-.01c3.928 1.793 8.18 1.793 12.062 0a.074.074 0 0 1 .078.01c.12.098.246.198.373.292a.077.077 0 0 1-.006.127 12.299 12.299 0 0 1-1.873.892.077.077 0 0 0-.041.107c.36.698.772 1.362 1.225 1.993a.076.076 0 0 0 .084.028 19.839 19.839 0 0 0 6.002-3.03.077.077 0 0 0 .032-.054c.5-5.177-.838-9.674-3.549-13.66a.061.061 0 0 0-.031-.03zM8.02 15.33c-1.183 0-2.157-1.085-2.157-2.419 0-1.333.956-2.419 2.157-2.419 1.21 0 2.176 1.096 2.157 2.42 0 1.333-.956 2.418-2.157 2.418zm7.975 0c-1.183 0-2.157-1.085-2.157-2.419 0-1.333.955-2.419 2.157-2.419 1.21 0 2.176 1.096 2.157 2.42 0 1.333-.946 2.418-2.157 2.418z"/>
|
||||
</svg>
|
||||
<div>
|
||||
<h1>TA Discord Link</h1>
|
||||
<p>thomo.ART Node Pack — Link Editor</p>
|
||||
<p style="font-size:11px;color:var(--muted);margin-top:3px;">© 2026, Thomas Möhrling (thomo.ART)</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- URL field -->
|
||||
<div class="field">
|
||||
<label for="url-input">Discord Invite URL</label>
|
||||
<input type="url" id="url-input" placeholder="https://discord.gg/…" spellcheck="false" autocomplete="off">
|
||||
<p class="hint">Your Discord invite link — e.g. https://discord.gg/abcXYZ123</p>
|
||||
</div>
|
||||
|
||||
<!-- Label field -->
|
||||
<div class="field">
|
||||
<label for="label-input">Button Label</label>
|
||||
<input type="text" id="label-input" placeholder="Join us on Discord" maxlength="60">
|
||||
<p class="hint">Text shown on the button inside the ComfyUI node.</p>
|
||||
</div>
|
||||
|
||||
<!-- Live preview -->
|
||||
<div class="preview-label">Preview</div>
|
||||
<div class="preview-wrap">
|
||||
<a id="preview-btn" href="#" target="_blank" rel="noopener noreferrer">
|
||||
<svg class="discord-icon" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" width="18" height="18" fill="white">
|
||||
<path d="M20.317 4.37a19.791 19.791 0 0 0-4.885-1.515.074.074 0 0 0-.079.037c-.21.375-.444.864-.608 1.25a18.27 18.27 0 0 0-5.487 0 12.64 12.64 0 0 0-.617-1.25.077.077 0 0 0-.079-.037A19.736 19.736 0 0 0 3.677 4.37a.07.07 0 0 0-.032.027C.533 9.046-.32 13.58.099 18.057a.082.082 0 0 0 .031.057 19.9 19.9 0 0 0 5.993 3.03.078.078 0 0 0 .084-.028 14.09 14.09 0 0 0 1.226-1.994.076.076 0 0 0-.041-.106 13.107 13.107 0 0 1-1.872-.892.077.077 0 0 1-.008-.128 10.2 10.2 0 0 0 .372-.292.074.074 0 0 1 .077-.01c3.928 1.793 8.18 1.793 12.062 0a.074.074 0 0 1 .078.01c.12.098.246.198.373.292a.077.077 0 0 1-.006.127 12.299 12.299 0 0 1-1.873.892.077.077 0 0 0-.041.107c.36.698.772 1.362 1.225 1.993a.076.076 0 0 0 .084.028 19.839 19.839 0 0 0 6.002-3.03.077.077 0 0 0 .032-.054c.5-5.177-.838-9.674-3.549-13.66a.061.061 0 0 0-.031-.03zM8.02 15.33c-1.183 0-2.157-1.085-2.157-2.419 0-1.333.956-2.419 2.157-2.419 1.21 0 2.176 1.096 2.157 2.42 0 1.333-.956 2.418-2.157 2.418zm7.975 0c-1.183 0-2.157-1.085-2.157-2.419 0-1.333.955-2.419 2.157-2.419 1.21 0 2.176 1.096 2.157 2.42 0 1.333-.946 2.418-2.157 2.418z"/>
|
||||
</svg>
|
||||
<span id="preview-label-text">Join us on Discord</span>
|
||||
</a>
|
||||
</div>
|
||||
|
||||
<!-- Save -->
|
||||
<button id="save-btn">Save</button>
|
||||
<div id="toast"></div>
|
||||
|
||||
</div>
|
||||
|
||||
<script>
|
||||
const urlInput = document.getElementById("url-input");
|
||||
const labelInput = document.getElementById("label-input");
|
||||
const previewBtn = document.getElementById("preview-btn");
|
||||
const previewTxt = document.getElementById("preview-label-text");
|
||||
const saveBtn = document.getElementById("save-btn");
|
||||
const toast = document.getElementById("toast");
|
||||
|
||||
// ── Live preview sync ──────────────────────────────────────────────────────
|
||||
urlInput.addEventListener("input", () => { previewBtn.href = urlInput.value || "#"; });
|
||||
labelInput.addEventListener("input", () => { previewTxt.textContent = labelInput.value || "Join us on Discord"; });
|
||||
|
||||
// ── Load current config ────────────────────────────────────────────────────
|
||||
async function loadConfig() {
|
||||
try {
|
||||
const res = await fetch("/ta_discord_link/config");
|
||||
const data = await res.json();
|
||||
urlInput.value = data.discord_url ?? "";
|
||||
labelInput.value = data.label ?? "";
|
||||
previewBtn.href = data.discord_url ?? "#";
|
||||
previewTxt.textContent = data.label ?? "Join us on Discord";
|
||||
} catch (e) {
|
||||
showToast("Could not load current config.", false);
|
||||
}
|
||||
}
|
||||
|
||||
// ── Save ───────────────────────────────────────────────────────────────────
|
||||
saveBtn.addEventListener("click", async () => {
|
||||
const url = urlInput.value.trim();
|
||||
const label = labelInput.value.trim();
|
||||
|
||||
if (!url) {
|
||||
showToast("Please enter a Discord invite URL.", false);
|
||||
return;
|
||||
}
|
||||
|
||||
saveBtn.disabled = true;
|
||||
try {
|
||||
const res = await fetch("/ta_discord_link/save", {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify({ discord_url: url, label }),
|
||||
});
|
||||
const data = await res.json();
|
||||
if (data.ok) {
|
||||
showToast("✓ Saved! Reload ComfyUI to update the node button.", true);
|
||||
} else {
|
||||
showToast("Error: " + (data.error ?? "Unknown error"), false);
|
||||
}
|
||||
} catch (e) {
|
||||
showToast("Save failed: " + e.message, false);
|
||||
} finally {
|
||||
saveBtn.disabled = false;
|
||||
}
|
||||
});
|
||||
|
||||
function showToast(msg, ok) {
|
||||
toast.textContent = msg;
|
||||
toast.className = ok ? "ok" : "err";
|
||||
toast.style.display = "block";
|
||||
setTimeout(() => { toast.style.display = "none"; }, 4000);
|
||||
}
|
||||
|
||||
loadConfig();
|
||||
</script>
|
||||
</body>
|
||||
</html>
|
||||
@@ -0,0 +1,124 @@
|
||||
/**
|
||||
* TAHelpLink - Frontend Extension
|
||||
* Renders a clickable button inside the node that opens a local wiki page.
|
||||
* Label and page are configured via the Properties panel (right-click → Properties).
|
||||
*
|
||||
* Wiki viewer : wiki/index.html → served at /ta-nodes/wiki/index.html
|
||||
* Markdown : wiki/<page>.md → served at /ta-nodes/wiki/<page>.md
|
||||
* Renderer : web/js/marked.min.js
|
||||
* → manuell herunterladen von https://github.com/markedjs/marked/releases
|
||||
*
|
||||
* Part of the TA Nodes Pack by thomo.ART
|
||||
*/
|
||||
|
||||
import { app } from "../../scripts/app.js";
|
||||
|
||||
const BUTTON_HEIGHT = 30;
|
||||
const BUTTON_PADDING = 10;
|
||||
const NODE_WIDTH = 180;
|
||||
const NODE_HEIGHT = 58;
|
||||
|
||||
const WIKI_BASE = `${location.origin}/ta-nodes/wiki`;
|
||||
// Note: marked.min.js served via /extensions/TA-ComfyUI-Nodes-Pack/marked.min.js
|
||||
|
||||
/**
|
||||
* Resolve the final URL.
|
||||
* - Full http(s):// URL → used as-is
|
||||
* - Filename (e.g. "help.md") → routed through /ta-nodes/wiki/index.html?page=...
|
||||
*/
|
||||
function resolveUrl(page) {
|
||||
if (!page) return null;
|
||||
if (/^https?:\/\//i.test(page)) return page;
|
||||
return `${WIKI_BASE}/index.html?page=${encodeURIComponent(page)}`;
|
||||
}
|
||||
|
||||
app.registerExtension({
|
||||
name: "thomo.TAHelpLink",
|
||||
|
||||
async beforeRegisterNodeDef(nodeType, nodeData) {
|
||||
if (nodeData.name !== "TAHelpLink") return;
|
||||
|
||||
// Initialise properties with defaults on node creation
|
||||
const origOnNodeCreated = nodeType.prototype.onNodeCreated;
|
||||
nodeType.prototype.onNodeCreated = function () {
|
||||
if (origOnNodeCreated) origOnNodeCreated.apply(this, arguments);
|
||||
|
||||
if (!this.properties) this.properties = {};
|
||||
if (this.properties.label === undefined) this.properties.label = "📖 Help";
|
||||
if (this.properties.page === undefined) this.properties.page = "help.md";
|
||||
|
||||
this.size = [NODE_WIDTH, NODE_HEIGHT];
|
||||
this.resizable = false;
|
||||
};
|
||||
|
||||
// Draw the button
|
||||
nodeType.prototype.onDrawForeground = function (ctx) {
|
||||
if (this.flags?.collapsed) return;
|
||||
|
||||
const x = BUTTON_PADDING;
|
||||
const w = this.size[0] - BUTTON_PADDING * 2;
|
||||
const y = (this.size[1] - BUTTON_HEIGHT) / 2;
|
||||
const label = this.properties?.label || "📖 Help";
|
||||
const hov = this._helpLinkHovered;
|
||||
|
||||
// Background
|
||||
ctx.fillStyle = hov ? "#3a7bd5" : "#2a5db0";
|
||||
ctx.beginPath();
|
||||
ctx.roundRect(x, y, w, BUTTON_HEIGHT, 6);
|
||||
ctx.fill();
|
||||
|
||||
// Border
|
||||
ctx.strokeStyle = hov ? "#5a9bf5" : "#4a7dd0";
|
||||
ctx.lineWidth = 1;
|
||||
ctx.stroke();
|
||||
|
||||
// Label
|
||||
ctx.fillStyle = "#ffffff";
|
||||
ctx.font = "bold 13px Arial";
|
||||
ctx.textAlign = "center";
|
||||
ctx.textBaseline = "middle";
|
||||
ctx.fillText(label, x + w / 2, y + BUTTON_HEIGHT / 2);
|
||||
|
||||
this._btnBounds = { x, y, w, h: BUTTON_HEIGHT };
|
||||
};
|
||||
|
||||
// Fixed size
|
||||
nodeType.prototype.computeSize = function () {
|
||||
return [NODE_WIDTH, NODE_HEIGHT];
|
||||
};
|
||||
|
||||
// Hover
|
||||
nodeType.prototype.onMouseMove = function (e, pos) {
|
||||
const b = this._btnBounds;
|
||||
if (!b) return;
|
||||
const hov = pos[0] >= b.x && pos[0] <= b.x + b.w &&
|
||||
pos[1] >= b.y && pos[1] <= b.y + b.h;
|
||||
if (hov !== this._helpLinkHovered) {
|
||||
this._helpLinkHovered = hov;
|
||||
app.canvas.setDirty(true);
|
||||
}
|
||||
app.canvas.canvas.style.cursor = hov ? "pointer" : "";
|
||||
};
|
||||
|
||||
nodeType.prototype.onMouseLeave = function () {
|
||||
if (this._helpLinkHovered) {
|
||||
this._helpLinkHovered = false;
|
||||
app.canvas.canvas.style.cursor = "";
|
||||
app.canvas.setDirty(true);
|
||||
}
|
||||
};
|
||||
|
||||
// Click → open wiki
|
||||
nodeType.prototype.onMouseDown = function (e, pos) {
|
||||
const b = this._btnBounds;
|
||||
if (!b) return;
|
||||
const clicked = pos[0] >= b.x && pos[0] <= b.x + b.w &&
|
||||
pos[1] >= b.y && pos[1] <= b.y + b.h;
|
||||
if (clicked) {
|
||||
const url = resolveUrl(this.properties?.page);
|
||||
if (url) window.open(url, "_blank", "noopener,noreferrer");
|
||||
return true;
|
||||
}
|
||||
};
|
||||
},
|
||||
});
|
||||
@@ -0,0 +1,28 @@
|
||||
/**
|
||||
* TA Mini Model Switcher - Editor Button
|
||||
* =======================================
|
||||
* Fügt dem TA Mini Model Switcher Node einen Button hinzu
|
||||
* der den Browser-Editor öffnet.
|
||||
*
|
||||
* Author: TA Nodes Pack
|
||||
*/
|
||||
|
||||
import { app } from "../../scripts/app.js";
|
||||
|
||||
app.registerExtension({
|
||||
name: "TA.ModelChoicesEditorButton",
|
||||
|
||||
async beforeRegisterNodeDef(nodeType, nodeData) {
|
||||
if (nodeData.name !== "TAUnifiedModelSwitcher") return;
|
||||
|
||||
const onNodeCreated = nodeType.prototype.onNodeCreated;
|
||||
|
||||
nodeType.prototype.onNodeCreated = function () {
|
||||
if (onNodeCreated) onNodeCreated.apply(this, arguments);
|
||||
|
||||
this.addWidget("button", "✏️ Model Choices Editor öffnen", null, () => {
|
||||
window.open("http://localhost:8188/ta_model_choices/ui", "_blank");
|
||||
});
|
||||
};
|
||||
},
|
||||
});
|
||||
@@ -0,0 +1,235 @@
|
||||
<!DOCTYPE html>
|
||||
<html lang="de">
|
||||
<head>
|
||||
<meta charset="UTF-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||||
<title>TA Model Choices Editor</title>
|
||||
<style>
|
||||
* { box-sizing: border-box; margin: 0; padding: 0; }
|
||||
|
||||
body {
|
||||
font-family: "Segoe UI", sans-serif;
|
||||
background: #1a1a2e;
|
||||
color: #e0e0e0;
|
||||
padding: 24px;
|
||||
min-height: 100vh;
|
||||
}
|
||||
|
||||
h1 {
|
||||
font-size: 1.6rem;
|
||||
color: #a78bfa;
|
||||
margin-bottom: 6px;
|
||||
}
|
||||
|
||||
.subtitle {
|
||||
color: #666;
|
||||
font-size: 0.85rem;
|
||||
margin-bottom: 28px;
|
||||
}
|
||||
|
||||
.card {
|
||||
background: #1e1e38;
|
||||
border: 1px solid #3d3d6e;
|
||||
border-radius: 8px;
|
||||
padding: 20px 24px;
|
||||
margin-bottom: 24px;
|
||||
max-width: 540px;
|
||||
}
|
||||
|
||||
.card h2 {
|
||||
font-size: 1rem;
|
||||
color: #a78bfa;
|
||||
margin-bottom: 16px;
|
||||
}
|
||||
|
||||
/* ── Liste ── */
|
||||
#choices-list {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 8px;
|
||||
margin-bottom: 16px;
|
||||
}
|
||||
|
||||
.choice-row {
|
||||
display: flex;
|
||||
gap: 8px;
|
||||
align-items: center;
|
||||
}
|
||||
|
||||
.choice-row input {
|
||||
flex: 1;
|
||||
background: #16162a;
|
||||
border: 1px solid #3d3d6e;
|
||||
color: #e0e0e0;
|
||||
padding: 7px 10px;
|
||||
border-radius: 4px;
|
||||
font-size: 0.9rem;
|
||||
}
|
||||
|
||||
.choice-row input:focus {
|
||||
outline: none;
|
||||
border-color: #a78bfa;
|
||||
}
|
||||
|
||||
.drag-handle {
|
||||
cursor: grab;
|
||||
color: #555;
|
||||
font-size: 1.1rem;
|
||||
padding: 0 4px;
|
||||
user-select: none;
|
||||
}
|
||||
.drag-handle:active { cursor: grabbing; }
|
||||
|
||||
/* ── Buttons ── */
|
||||
.btn {
|
||||
border: none;
|
||||
border-radius: 5px;
|
||||
padding: 6px 14px;
|
||||
cursor: pointer;
|
||||
font-size: 0.82rem;
|
||||
font-weight: 600;
|
||||
transition: opacity 0.15s;
|
||||
}
|
||||
.btn:hover { opacity: 0.82; }
|
||||
|
||||
.btn-delete { background: #dc2626; color: #fff; padding: 5px 10px; }
|
||||
.btn-add { background: #059669; color: #fff; font-size: 0.9rem; padding: 8px 20px; }
|
||||
.btn-save { background: #7c3aed; color: #fff; font-size: 0.9rem; padding: 8px 20px; }
|
||||
|
||||
.actions {
|
||||
display: flex;
|
||||
gap: 10px;
|
||||
flex-wrap: wrap;
|
||||
}
|
||||
|
||||
/* ── Toast ── */
|
||||
#toast {
|
||||
position: fixed;
|
||||
bottom: 28px;
|
||||
right: 28px;
|
||||
background: #059669;
|
||||
color: #fff;
|
||||
padding: 12px 20px;
|
||||
border-radius: 8px;
|
||||
font-size: 0.9rem;
|
||||
opacity: 0;
|
||||
transition: opacity 0.3s;
|
||||
pointer-events: none;
|
||||
}
|
||||
#toast.error { background: #dc2626; }
|
||||
#toast.show { opacity: 1; }
|
||||
|
||||
.hint {
|
||||
font-size: 0.78rem;
|
||||
color: #555;
|
||||
margin-top: 10px;
|
||||
}
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
|
||||
<h1>🔀 TA Model Choices Editor</h1>
|
||||
<p class="subtitle">Einträge werden in ta_model_choices.json gespeichert · ComfyUI neu starten damit das Dropdown aktualisiert wird</p>
|
||||
<p class="subtitle">© 2026, Thomas Möhrling (thomo.ART)</p>
|
||||
|
||||
<div class="card">
|
||||
<h2>📋 Model Choices</h2>
|
||||
<div id="choices-list"></div>
|
||||
<div class="actions">
|
||||
<button class="btn btn-add" onclick="addChoice()">➕ Eintrag hinzufügen</button>
|
||||
<button class="btn btn-save" onclick="saveChoices()">💾 Speichern</button>
|
||||
</div>
|
||||
<p class="hint">⬆⬇ Einträge per Drag & Drop sortieren · Nach dem Speichern ComfyUI neu starten</p>
|
||||
</div>
|
||||
|
||||
<div id="toast"></div>
|
||||
|
||||
<script>
|
||||
let _dragSrc = null;
|
||||
|
||||
// ── Toast ──────────────────────────────────────────────────────────────
|
||||
function showToast(msg, isError = false) {
|
||||
const t = document.getElementById("toast");
|
||||
t.textContent = msg;
|
||||
t.className = "show" + (isError ? " error" : "");
|
||||
clearTimeout(t._timer);
|
||||
t._timer = setTimeout(() => t.className = "", 3000);
|
||||
}
|
||||
|
||||
// ── Zeile erzeugen ─────────────────────────────────────────────────────
|
||||
function makeRow(value = "") {
|
||||
const row = document.createElement("div");
|
||||
row.className = "choice-row";
|
||||
row.draggable = true;
|
||||
row.innerHTML = `
|
||||
<span class="drag-handle" title="Verschieben">⠿</span>
|
||||
<input type="text" value="${escHtml(value)}" placeholder="z.B. FLUX Diffusion">
|
||||
<button class="btn btn-delete" onclick="this.closest('.choice-row').remove()">🗑️</button>
|
||||
`;
|
||||
|
||||
// Drag & Drop
|
||||
row.addEventListener("dragstart", e => {
|
||||
_dragSrc = row;
|
||||
e.dataTransfer.effectAllowed = "move";
|
||||
setTimeout(() => row.style.opacity = "0.4", 0);
|
||||
});
|
||||
row.addEventListener("dragend", () => row.style.opacity = "1");
|
||||
row.addEventListener("dragover", e => { e.preventDefault(); e.dataTransfer.dropEffect = "move"; });
|
||||
row.addEventListener("drop", e => {
|
||||
e.preventDefault();
|
||||
if (_dragSrc && _dragSrc !== row) {
|
||||
const list = document.getElementById("choices-list");
|
||||
const rows = [...list.children];
|
||||
const srcIdx = rows.indexOf(_dragSrc);
|
||||
const destIdx = rows.indexOf(row);
|
||||
if (srcIdx < destIdx) row.after(_dragSrc);
|
||||
else row.before(_dragSrc);
|
||||
}
|
||||
});
|
||||
|
||||
return row;
|
||||
}
|
||||
|
||||
// ── Eintrag hinzufügen ─────────────────────────────────────────────────
|
||||
function addChoice() {
|
||||
document.getElementById("choices-list").appendChild(makeRow());
|
||||
}
|
||||
|
||||
// ── Liste laden ────────────────────────────────────────────────────────
|
||||
async function loadChoices() {
|
||||
const res = await fetch("/ta_model_choices/list").then(r => r.json());
|
||||
const list = document.getElementById("choices-list");
|
||||
list.innerHTML = "";
|
||||
(res.choices || []).forEach(c => list.appendChild(makeRow(c)));
|
||||
}
|
||||
|
||||
// ── Speichern ──────────────────────────────────────────────────────────
|
||||
async function saveChoices() {
|
||||
const inputs = document.querySelectorAll("#choices-list .choice-row input");
|
||||
const choices = [...inputs].map(i => i.value.trim()).filter(Boolean);
|
||||
|
||||
if (choices.length === 0) {
|
||||
showToast("⚠️ Mindestens ein Eintrag wird benötigt.", true);
|
||||
return;
|
||||
}
|
||||
|
||||
const res = await fetch("/ta_model_choices/save", {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify({ choices }),
|
||||
}).then(r => r.json());
|
||||
|
||||
if (res.ok) showToast("✅ Gespeichert! Bitte ComfyUI neu starten.");
|
||||
else showToast(`❌ Fehler: ${res.error}`, true);
|
||||
}
|
||||
|
||||
function escHtml(str) {
|
||||
return String(str)
|
||||
.replace(/&/g,"&").replace(/</g,"<")
|
||||
.replace(/>/g,">").replace(/"/g,""");
|
||||
}
|
||||
|
||||
loadChoices();
|
||||
</script>
|
||||
</body>
|
||||
</html>
|
||||
@@ -0,0 +1,28 @@
|
||||
/**
|
||||
* TA Model Preset - Editor Button
|
||||
* ================================
|
||||
* Fügt dem TA Model Preset Node einen Button hinzu
|
||||
* der den Browser-Editor öffnet.
|
||||
*
|
||||
* Author: TA Nodes Pack
|
||||
*/
|
||||
|
||||
import { app } from "../../scripts/app.js";
|
||||
|
||||
app.registerExtension({
|
||||
name: "TA.ModelPresetEditorButton",
|
||||
|
||||
async beforeRegisterNodeDef(nodeType, nodeData) {
|
||||
if (nodeData.name !== "TAModelPreset") return;
|
||||
|
||||
const onNodeCreated = nodeType.prototype.onNodeCreated;
|
||||
|
||||
nodeType.prototype.onNodeCreated = function () {
|
||||
if (onNodeCreated) onNodeCreated.apply(this, arguments);
|
||||
|
||||
this.addWidget("button", "✏️ Model Preset Editor öffnen", null, () => {
|
||||
window.open("http://localhost:8188/ta_model_presets/ui", "_blank");
|
||||
});
|
||||
};
|
||||
},
|
||||
});
|
||||
@@ -0,0 +1,480 @@
|
||||
<!DOCTYPE html>
|
||||
<html lang="de">
|
||||
<head>
|
||||
<meta charset="UTF-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||||
<title>TA Model Preset Editor</title>
|
||||
<style>
|
||||
* { box-sizing: border-box; margin: 0; padding: 0; }
|
||||
|
||||
body {
|
||||
font-family: "Segoe UI", sans-serif;
|
||||
background: #1a1a2e;
|
||||
color: #e0e0e0;
|
||||
padding: 24px;
|
||||
min-height: 100vh;
|
||||
}
|
||||
|
||||
h1 {
|
||||
font-size: 1.6rem;
|
||||
color: #a78bfa;
|
||||
margin-bottom: 6px;
|
||||
}
|
||||
|
||||
.subtitle {
|
||||
color: #666;
|
||||
font-size: 0.85rem;
|
||||
margin-bottom: 28px;
|
||||
}
|
||||
|
||||
.card {
|
||||
background: #1e1e38;
|
||||
border: 1px solid #3d3d6e;
|
||||
border-radius: 8px;
|
||||
padding: 20px 24px;
|
||||
margin-bottom: 24px;
|
||||
max-width: 720px;
|
||||
}
|
||||
|
||||
.card h2 {
|
||||
font-size: 1rem;
|
||||
color: #a78bfa;
|
||||
margin-bottom: 16px;
|
||||
}
|
||||
|
||||
#preset-list {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 10px;
|
||||
margin-bottom: 16px;
|
||||
}
|
||||
|
||||
.preset-row {
|
||||
background: #16162a;
|
||||
border: 1px solid #3d3d6e;
|
||||
border-radius: 6px;
|
||||
overflow: hidden;
|
||||
}
|
||||
.preset-row.dragging { opacity: 0.4; }
|
||||
.preset-row.drag-over { border-color: #a78bfa; }
|
||||
|
||||
.row-header {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 8px;
|
||||
padding: 8px 12px;
|
||||
cursor: pointer;
|
||||
user-select: none;
|
||||
background: #1e1e38;
|
||||
}
|
||||
.row-header:hover { background: #25254a; }
|
||||
|
||||
.drag-handle {
|
||||
cursor: grab;
|
||||
color: #555;
|
||||
font-size: 1.1rem;
|
||||
padding: 0 4px;
|
||||
user-select: none;
|
||||
}
|
||||
.drag-handle:active { cursor: grabbing; }
|
||||
|
||||
.preset-title {
|
||||
flex: 1;
|
||||
font-size: 0.9rem;
|
||||
font-weight: 600;
|
||||
color: #e0e0e0;
|
||||
}
|
||||
|
||||
.preset-badge {
|
||||
font-size: 0.72rem;
|
||||
padding: 2px 7px;
|
||||
border-radius: 4px;
|
||||
background: #16162a;
|
||||
color: #a78bfa;
|
||||
border: 1px solid #3d3d6e;
|
||||
font-family: monospace;
|
||||
}
|
||||
|
||||
.chevron {
|
||||
color: #555;
|
||||
font-size: 0.75rem;
|
||||
transition: transform 0.2s;
|
||||
}
|
||||
.preset-row.open .chevron { transform: rotate(180deg); }
|
||||
|
||||
.row-body {
|
||||
display: none;
|
||||
padding: 14px 12px;
|
||||
border-top: 1px solid #3d3d6e;
|
||||
}
|
||||
.preset-row.open .row-body { display: block; }
|
||||
|
||||
.form-grid {
|
||||
display: grid;
|
||||
grid-template-columns: 1fr 1fr;
|
||||
gap: 10px;
|
||||
}
|
||||
.form-full { grid-column: 1 / -1; }
|
||||
|
||||
.field label {
|
||||
display: block;
|
||||
font-size: 0.75rem;
|
||||
color: #666;
|
||||
text-transform: uppercase;
|
||||
letter-spacing: 0.05em;
|
||||
margin-bottom: 4px;
|
||||
}
|
||||
|
||||
.field select,
|
||||
.field input[type="text"] {
|
||||
width: 100%;
|
||||
background: #16162a;
|
||||
border: 1px solid #3d3d6e;
|
||||
color: #e0e0e0;
|
||||
padding: 7px 10px;
|
||||
border-radius: 4px;
|
||||
font-size: 0.85rem;
|
||||
font-family: monospace;
|
||||
outline: none;
|
||||
appearance: none;
|
||||
}
|
||||
.field select:focus,
|
||||
.field input[type="text"]:focus { border-color: #a78bfa; }
|
||||
.field select option { background: #1e1e38; }
|
||||
|
||||
.clip2-field { display: none; }
|
||||
.clip2-field.visible { display: block; }
|
||||
|
||||
.row-footer {
|
||||
display: flex;
|
||||
justify-content: flex-end;
|
||||
margin-top: 12px;
|
||||
padding-top: 10px;
|
||||
border-top: 1px solid #3d3d6e;
|
||||
}
|
||||
|
||||
.btn {
|
||||
border: none;
|
||||
border-radius: 5px;
|
||||
padding: 6px 14px;
|
||||
cursor: pointer;
|
||||
font-size: 0.82rem;
|
||||
font-weight: 600;
|
||||
transition: opacity 0.15s;
|
||||
}
|
||||
.btn:hover { opacity: 0.82; }
|
||||
|
||||
.btn-delete { background: #dc2626; color: #fff; padding: 5px 10px; }
|
||||
.btn-add { background: #059669; color: #fff; font-size: 0.9rem; padding: 8px 20px; }
|
||||
.btn-save { background: #7c3aed; color: #fff; font-size: 0.9rem; padding: 8px 20px; }
|
||||
|
||||
.actions { display: flex; gap: 10px; flex-wrap: wrap; }
|
||||
|
||||
#toast {
|
||||
position: fixed;
|
||||
bottom: 28px; right: 28px;
|
||||
background: #059669;
|
||||
color: #fff;
|
||||
padding: 12px 20px;
|
||||
border-radius: 8px;
|
||||
font-size: 0.9rem;
|
||||
opacity: 0;
|
||||
transition: opacity 0.3s;
|
||||
pointer-events: none;
|
||||
}
|
||||
#toast.error { background: #dc2626; }
|
||||
#toast.show { opacity: 1; }
|
||||
|
||||
.hint {
|
||||
font-size: 0.78rem;
|
||||
color: #555;
|
||||
margin-top: 10px;
|
||||
}
|
||||
|
||||
.empty {
|
||||
text-align: center;
|
||||
padding: 32px;
|
||||
color: #555;
|
||||
font-size: 0.9rem;
|
||||
}
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
|
||||
<h1>🗂️ TA Model Preset Editor</h1>
|
||||
<p class="subtitle">Presets werden in ta_model_presets.json gespeichert · ComfyUI neu starten damit das Dropdown aktualisiert wird</p>
|
||||
<p class="subtitle">© 2026, Thomas Möhrling (thomo.ART)</p>
|
||||
|
||||
<div class="card">
|
||||
<h2>📋 Model Presets</h2>
|
||||
<div id="preset-list"></div>
|
||||
<div class="actions">
|
||||
<button class="btn btn-add" onclick="addPreset()">➕ Preset hinzufügen</button>
|
||||
<button class="btn btn-save" onclick="saveAll()">💾 Speichern</button>
|
||||
</div>
|
||||
<p class="hint">⬆⬇ Presets per Drag & Drop sortieren · Nach dem Speichern ComfyUI neu starten</p>
|
||||
</div>
|
||||
|
||||
<div id="toast"></div>
|
||||
|
||||
<script>
|
||||
let presets = [];
|
||||
let modelFiles = [];
|
||||
let clipFiles = [];
|
||||
let vaeFiles = [];
|
||||
let clipTypes = ["auto"];
|
||||
let _dragSrc = null;
|
||||
|
||||
const CLIP_DEVICES = ["default","cpu","gpu"];
|
||||
|
||||
// Typen die Dual-CLIP brauchen
|
||||
const DUAL_CLIP_TYPES = ["flux", "sdxl", "flux2", "ace"];
|
||||
|
||||
function needsDualClip(clipType) {
|
||||
return DUAL_CLIP_TYPES.includes((clipType || "").toLowerCase());
|
||||
}
|
||||
|
||||
async function init() {
|
||||
await Promise.all([loadOptions(), loadPresets()]);
|
||||
render();
|
||||
}
|
||||
|
||||
async function loadOptions() {
|
||||
try {
|
||||
const d = await fetch("/ta_model_presets/options").then(r => r.json());
|
||||
modelFiles = d.models || [];
|
||||
clipFiles = d.clips || [];
|
||||
vaeFiles = d.vaes || [];
|
||||
clipTypes = d.clip_types || ["auto"];
|
||||
} catch(e) { console.warn("Optionen nicht geladen:", e); }
|
||||
}
|
||||
|
||||
async function loadPresets() {
|
||||
try {
|
||||
const d = await fetch("/ta_model_presets/list").then(r => r.json());
|
||||
presets = d.presets || [];
|
||||
} catch(e) { showToast("Fehler beim Laden", true); }
|
||||
}
|
||||
|
||||
function render() {
|
||||
const list = document.getElementById("preset-list");
|
||||
if (!presets.length) {
|
||||
list.innerHTML = `<div class="empty">Keine Presets vorhanden. Klicke auf „Preset hinzufügen".</div>`;
|
||||
return;
|
||||
}
|
||||
list.innerHTML = "";
|
||||
presets.forEach((p, i) => list.appendChild(makeRow(p, i)));
|
||||
}
|
||||
|
||||
function clip2Label(clipType) {
|
||||
const t = (clipType || "").toLowerCase();
|
||||
if (t === "flux") return `CLIP 2 <span style="color:#a78bfa;font-size:0.7rem;">(FLUX: T5-XXL)</span>`;
|
||||
if (t === "sdxl") return `CLIP 2 <span style="color:#a78bfa;font-size:0.7rem;">(SDXL: clip_g)</span>`;
|
||||
if (t === "flux2") return `CLIP 2 <span style="color:#a78bfa;font-size:0.7rem;">(FLUX.2)</span>`;
|
||||
if (t === "ace") return `CLIP 2 <span style="color:#a78bfa;font-size:0.7rem;">(ACE: 2. Text Encoder)</span>`;
|
||||
return "CLIP 2";
|
||||
}
|
||||
|
||||
function makeRow(p, i) {
|
||||
const row = document.createElement("div");
|
||||
row.className = "preset-row";
|
||||
row.draggable = true;
|
||||
|
||||
const kind = p.model_file?.startsWith("[G]") ? "GGUF"
|
||||
: p.model_file?.startsWith("[C]") ? "CKPT"
|
||||
: p.model_file?.startsWith("[D]") ? "DIFF" : "–";
|
||||
|
||||
const dual = needsDualClip(p.clip_type);
|
||||
|
||||
row.innerHTML = `
|
||||
<div class="row-header" onclick="toggleRow(${i})">
|
||||
<span class="drag-handle" onclick="event.stopPropagation()">⠿</span>
|
||||
<span class="preset-title">${escHtml(p.name || "Unbenannt")}</span>
|
||||
<span class="preset-badge">${kind}</span>
|
||||
<span class="chevron">▼</span>
|
||||
</div>
|
||||
<div class="row-body">
|
||||
<div class="form-grid">
|
||||
<div class="field form-full">
|
||||
<label>Preset Name</label>
|
||||
<input type="text" value="${escHtml(p.name||'')}"
|
||||
oninput="update(${i},'name',this.value)"
|
||||
placeholder="z.B. ZImage BF16">
|
||||
</div>
|
||||
<div class="field form-full">
|
||||
<label>Model File</label>
|
||||
${buildSelect("model_file", i, modelFiles, p.model_file||'')}
|
||||
</div>
|
||||
<div class="field form-full">
|
||||
<label>CLIP 1</label>
|
||||
${buildSelect("clip_name_1", i, clipFiles, p.clip_name_1 || p.clip_name || '')}
|
||||
</div>
|
||||
<div class="field form-full clip2-field${dual ? ' visible' : ''}" id="clip2-${i}">
|
||||
<label>${clip2Label(p.clip_type)}</label>
|
||||
${buildSelect("clip_name_2", i, clipFiles, p.clip_name_2||'')}
|
||||
</div>
|
||||
<div class="field">
|
||||
<label>CLIP Type</label>
|
||||
${buildSelectSimple("clip_type", i, clipTypes, p.clip_type||'auto')}
|
||||
</div>
|
||||
<div class="field">
|
||||
<label>CLIP Device</label>
|
||||
${buildSelectSimple("clip_device", i, CLIP_DEVICES, p.clip_device||'default')}
|
||||
</div>
|
||||
<div class="field form-full">
|
||||
<label>VAE</label>
|
||||
${buildSelect("vae_name", i, vaeFiles, p.vae_name||'')}
|
||||
</div>
|
||||
<div class="field">
|
||||
<label>Weight dtype <span style="color:#a78bfa;font-size:0.7rem;">(nur Diffusion Models)</span></label>
|
||||
${buildSelectSimple("weight_dtype", i, ["auto","fp8_e4m3fn","fp8_e5m2"], p.weight_dtype||'auto')}
|
||||
</div>
|
||||
<div class="field">
|
||||
<label>Shift <span style="color:#a78bfa;font-size:0.7rem;">(ModelSamplingAuraFlow – leer = deaktiviert)</span></label>
|
||||
<input type="text" value="${escHtml(p.shift !== undefined ? String(p.shift) : '')}"
|
||||
oninput="update(${i},'shift',this.value)"
|
||||
placeholder="z.B. 3.0 – leer lassen für FLUX/SDXL">
|
||||
</div>
|
||||
</div>
|
||||
<div class="row-footer">
|
||||
<button class="btn btn-delete" onclick="removePreset(${i})">🗑️ Entfernen</button>
|
||||
</div>
|
||||
</div>`;
|
||||
|
||||
// Drag & Drop
|
||||
row.addEventListener("dragstart", e => {
|
||||
_dragSrc = i;
|
||||
e.dataTransfer.effectAllowed = "move";
|
||||
setTimeout(() => row.classList.add("dragging"), 0);
|
||||
});
|
||||
row.addEventListener("dragend", () => row.classList.remove("dragging"));
|
||||
row.addEventListener("dragover", e => { e.preventDefault(); row.classList.add("drag-over"); });
|
||||
row.addEventListener("dragleave",() => row.classList.remove("drag-over"));
|
||||
row.addEventListener("drop", e => {
|
||||
e.preventDefault();
|
||||
row.classList.remove("drag-over");
|
||||
if (_dragSrc !== null && _dragSrc !== i) {
|
||||
const moved = presets.splice(_dragSrc, 1)[0];
|
||||
presets.splice(i, 0, moved);
|
||||
render();
|
||||
}
|
||||
});
|
||||
|
||||
return row;
|
||||
}
|
||||
|
||||
function buildSelect(field, idx, options, current) {
|
||||
if (!options.length) {
|
||||
return `<input type="text" value="${escHtml(current)}"
|
||||
oninput="update(${idx},'${field}',this.value)"
|
||||
placeholder="Dateiname eingeben">`;
|
||||
}
|
||||
const hasMatch = options.includes(current);
|
||||
let html = `<select onchange="update(${idx},'${field}',this.value)">`;
|
||||
if (!current) {
|
||||
html += `<option value="">– auswählen –</option>`;
|
||||
} else if (!hasMatch) {
|
||||
html += `<option value="${escHtml(current)}" selected>${escHtml(current)}</option>`;
|
||||
html += `<option disabled>──────────</option>`;
|
||||
}
|
||||
options.forEach(o => {
|
||||
html += `<option value="${escHtml(o)}" ${o===current?'selected':''}>${escHtml(o)}</option>`;
|
||||
});
|
||||
return html + `</select>`;
|
||||
}
|
||||
|
||||
function buildSelectSimple(field, idx, options, current) {
|
||||
const isClipType = field === "clip_type";
|
||||
const handler = isClipType
|
||||
? `onClipTypeChange(${idx},this.value)`
|
||||
: `update(${idx},'${field}',this.value)`;
|
||||
let html = `<select onchange="${handler}">`;
|
||||
options.forEach(o => {
|
||||
html += `<option value="${o}" ${o===current?'selected':''}>${o}</option>`;
|
||||
});
|
||||
return html + `</select>`;
|
||||
}
|
||||
|
||||
function onClipTypeChange(i, value) {
|
||||
update(i, 'clip_type', value);
|
||||
const clip2 = document.getElementById(`clip2-${i}`);
|
||||
if (clip2) {
|
||||
const dual = needsDualClip(value);
|
||||
clip2.classList.toggle("visible", dual);
|
||||
// Label aktualisieren
|
||||
const label = clip2.querySelector("label");
|
||||
if (label) label.innerHTML = clip2Label(value);
|
||||
}
|
||||
}
|
||||
|
||||
function toggleRow(i) {
|
||||
document.querySelectorAll(".preset-row")[i].classList.toggle("open");
|
||||
}
|
||||
|
||||
function update(i, field, value) {
|
||||
presets[i][field] = value;
|
||||
const rows = document.querySelectorAll(".preset-row");
|
||||
if (field === "name") {
|
||||
const el = rows[i].querySelector(".preset-title");
|
||||
if (el) el.textContent = value || "Unbenannt";
|
||||
}
|
||||
if (field === "model_file") {
|
||||
const badge = rows[i].querySelector(".preset-badge");
|
||||
if (badge) badge.textContent = value.startsWith("[G]") ? "GGUF"
|
||||
: value.startsWith("[C]") ? "CKPT"
|
||||
: value.startsWith("[D]") ? "DIFF" : "–";
|
||||
}
|
||||
}
|
||||
|
||||
function addPreset() {
|
||||
presets.push({
|
||||
name: `Preset ${presets.length + 1}`,
|
||||
model_file: "", clip_name_1: "", clip_name_2: "",
|
||||
clip_type: "auto", clip_device: "default", vae_name: "",
|
||||
weight_dtype: "auto", shift: ""
|
||||
});
|
||||
render();
|
||||
setTimeout(() => {
|
||||
const rows = document.querySelectorAll(".preset-row");
|
||||
if (rows.length) {
|
||||
rows[rows.length-1].classList.add("open");
|
||||
rows[rows.length-1].scrollIntoView({ behavior: "smooth", block: "center" });
|
||||
}
|
||||
}, 50);
|
||||
}
|
||||
|
||||
function removePreset(i) {
|
||||
if (!confirm(`Preset "${presets[i].name}" wirklich entfernen?`)) return;
|
||||
presets.splice(i, 1);
|
||||
render();
|
||||
}
|
||||
|
||||
async function saveAll() {
|
||||
const res = await fetch("/ta_model_presets/save", {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify({ presets })
|
||||
}).then(r => r.json());
|
||||
|
||||
if (res.ok) showToast("✅ Gespeichert! Bitte ComfyUI neu starten.");
|
||||
else showToast(`❌ Fehler: ${res.error}`, true);
|
||||
}
|
||||
|
||||
function showToast(msg, isError = false) {
|
||||
const t = document.getElementById("toast");
|
||||
t.textContent = msg;
|
||||
t.className = "show" + (isError ? " error" : "");
|
||||
clearTimeout(t._timer);
|
||||
t._timer = setTimeout(() => t.className = "", 3000);
|
||||
}
|
||||
|
||||
function escHtml(str) {
|
||||
return String(str)
|
||||
.replace(/&/g,"&").replace(/</g,"<")
|
||||
.replace(/>/g,">").replace(/"/g,""");
|
||||
}
|
||||
|
||||
init();
|
||||
</script>
|
||||
</body>
|
||||
</html>
|
||||
@@ -0,0 +1,28 @@
|
||||
/**
|
||||
* TA Sampler Preset - Editor Button
|
||||
* ===================================
|
||||
* Fügt dem TA Sampler Preset Node einen Button hinzu
|
||||
* der den Browser-Editor öffnet.
|
||||
*
|
||||
* Author: TA Nodes Pack
|
||||
*/
|
||||
|
||||
import { app } from "../../scripts/app.js";
|
||||
|
||||
app.registerExtension({
|
||||
name: "TA.SamplerPresetEditorButton",
|
||||
|
||||
async beforeRegisterNodeDef(nodeType, nodeData) {
|
||||
if (nodeData.name !== "TASamplerPreset") return;
|
||||
|
||||
const onNodeCreated = nodeType.prototype.onNodeCreated;
|
||||
|
||||
nodeType.prototype.onNodeCreated = function () {
|
||||
if (onNodeCreated) onNodeCreated.apply(this, arguments);
|
||||
|
||||
this.addWidget("button", "✏️ Preset Editor öffnen", null, () => {
|
||||
window.open("http://localhost:8188/ta_sampler_presets/ui", "_blank");
|
||||
});
|
||||
};
|
||||
},
|
||||
});
|
||||
@@ -0,0 +1,455 @@
|
||||
<!DOCTYPE html>
|
||||
<html lang="de">
|
||||
<head>
|
||||
<meta charset="UTF-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||||
<title>TA Sampler Preset Editor</title>
|
||||
<style>
|
||||
* { box-sizing: border-box; margin: 0; padding: 0; }
|
||||
|
||||
body {
|
||||
font-family: "Segoe UI", sans-serif;
|
||||
background: #1a1a2e;
|
||||
color: #e0e0e0;
|
||||
padding: 24px;
|
||||
min-height: 100vh;
|
||||
}
|
||||
|
||||
h1 {
|
||||
font-size: 1.6rem;
|
||||
color: #a78bfa;
|
||||
margin-bottom: 6px;
|
||||
}
|
||||
|
||||
.subtitle {
|
||||
color: #666;
|
||||
font-size: 0.85rem;
|
||||
margin-bottom: 28px;
|
||||
}
|
||||
|
||||
/* ── Tabelle ── */
|
||||
.table-wrap {
|
||||
overflow-x: auto;
|
||||
margin-bottom: 32px;
|
||||
}
|
||||
|
||||
table {
|
||||
width: 100%;
|
||||
border-collapse: collapse;
|
||||
font-size: 0.9rem;
|
||||
}
|
||||
|
||||
th {
|
||||
background: #2d2d4e;
|
||||
color: #a78bfa;
|
||||
padding: 10px 14px;
|
||||
text-align: left;
|
||||
border-bottom: 2px solid #3d3d6e;
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
td {
|
||||
padding: 9px 14px;
|
||||
border-bottom: 1px solid #2a2a4a;
|
||||
vertical-align: middle;
|
||||
}
|
||||
|
||||
tr:hover td { background: #22223a; }
|
||||
|
||||
td input[type="number"],
|
||||
td input[type="text"] {
|
||||
background: #16162a;
|
||||
border: 1px solid #3d3d6e;
|
||||
color: #e0e0e0;
|
||||
padding: 4px 8px;
|
||||
border-radius: 4px;
|
||||
width: 100%;
|
||||
font-size: 0.85rem;
|
||||
}
|
||||
|
||||
td input:focus {
|
||||
outline: none;
|
||||
border-color: #a78bfa;
|
||||
}
|
||||
|
||||
.col-drag { width: 36px; text-align: center; padding: 0 4px; }
|
||||
.col-name { min-width: 140px; }
|
||||
.col-num { width: 100px; }
|
||||
.col-str { min-width: 130px; }
|
||||
.col-act { width: 120px; text-align: center; }
|
||||
|
||||
/* ── Drag & Drop ── */
|
||||
.drag-handle {
|
||||
cursor: grab;
|
||||
color: #555;
|
||||
font-size: 1.2rem;
|
||||
user-select: none;
|
||||
display: block;
|
||||
text-align: center;
|
||||
}
|
||||
.drag-handle:active { cursor: grabbing; }
|
||||
|
||||
tr.drag-over td { background: #2d2d5e !important; outline: 2px dashed #a78bfa; outline-offset: -2px; }
|
||||
tr.dragging { opacity: 0.4; }
|
||||
|
||||
/* ── Buttons ── */
|
||||
.btn {
|
||||
border: none;
|
||||
border-radius: 5px;
|
||||
padding: 6px 14px;
|
||||
cursor: pointer;
|
||||
font-size: 0.82rem;
|
||||
font-weight: 600;
|
||||
transition: opacity 0.15s;
|
||||
}
|
||||
.btn:hover { opacity: 0.82; }
|
||||
|
||||
.btn-save { background: #7c3aed; color: #fff; }
|
||||
.btn-delete { background: #dc2626; color: #fff; }
|
||||
.btn-add { background: #059669; color: #fff; font-size: 0.9rem; padding: 8px 20px; }
|
||||
.btn-reload { background: #2563eb; color: #fff; font-size: 0.9rem; padding: 8px 20px; }
|
||||
|
||||
/* ── Neues Preset ── */
|
||||
.new-preset {
|
||||
background: #1e1e38;
|
||||
border: 1px solid #3d3d6e;
|
||||
border-radius: 8px;
|
||||
padding: 20px 24px;
|
||||
margin-bottom: 24px;
|
||||
}
|
||||
|
||||
.new-preset h2 {
|
||||
font-size: 1rem;
|
||||
color: #a78bfa;
|
||||
margin-bottom: 16px;
|
||||
}
|
||||
|
||||
.form-grid {
|
||||
display: grid;
|
||||
grid-template-columns: repeat(auto-fill, minmax(180px, 1fr));
|
||||
gap: 12px;
|
||||
margin-bottom: 16px;
|
||||
}
|
||||
|
||||
.form-field label {
|
||||
display: block;
|
||||
font-size: 0.78rem;
|
||||
color: #888;
|
||||
margin-bottom: 4px;
|
||||
}
|
||||
|
||||
.form-field input {
|
||||
background: #16162a;
|
||||
border: 1px solid #3d3d6e;
|
||||
color: #e0e0e0;
|
||||
padding: 6px 10px;
|
||||
border-radius: 4px;
|
||||
width: 100%;
|
||||
font-size: 0.88rem;
|
||||
}
|
||||
|
||||
.form-field input:focus {
|
||||
outline: none;
|
||||
border-color: #a78bfa;
|
||||
}
|
||||
|
||||
.form-actions { display: flex; gap: 10px; align-items: center; }
|
||||
|
||||
/* ── Status Toast ── */
|
||||
#toast {
|
||||
position: fixed;
|
||||
bottom: 28px;
|
||||
right: 28px;
|
||||
background: #059669;
|
||||
color: #fff;
|
||||
padding: 12px 20px;
|
||||
border-radius: 8px;
|
||||
font-size: 0.9rem;
|
||||
opacity: 0;
|
||||
transition: opacity 0.3s;
|
||||
pointer-events: none;
|
||||
max-width: 340px;
|
||||
}
|
||||
#toast.error { background: #dc2626; }
|
||||
#toast.show { opacity: 1; }
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
|
||||
<h1>🎛️ TA Sampler Preset Editor</h1>
|
||||
<p class="subtitle">Presets werden in ta_sampler_presets.json gespeichert · Änderungen gelten beim nächsten ComfyUI-Run sofort</p>
|
||||
<p class="subtitle">© 2026, Thomas Möhrling (thomo.ART)</p>
|
||||
|
||||
<!-- Preset-Tabelle -->
|
||||
<div class="table-wrap">
|
||||
<table id="preset-table">
|
||||
<thead>
|
||||
<tr>
|
||||
<th class="col-drag"></th>
|
||||
<th class="col-name">Name</th>
|
||||
<th class="col-num">Steps</th>
|
||||
<th class="col-num">CFG</th>
|
||||
<th class="col-num">Start</th>
|
||||
<th class="col-num">End</th>
|
||||
<th class="col-str">Sampler</th>
|
||||
<th class="col-str">Scheduler</th>
|
||||
<th class="col-act">Aktionen</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody id="preset-tbody">
|
||||
<tr><td colspan="9" style="text-align:center;color:#666;padding:20px;">Lade Presets…</td></tr>
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
|
||||
<!-- Neues Preset anlegen -->
|
||||
<div class="new-preset">
|
||||
<h2>➕ Neues Preset anlegen</h2>
|
||||
<div class="form-grid">
|
||||
<div class="form-field">
|
||||
<label>Name</label>
|
||||
<input type="text" id="new-name" placeholder="z.B. FLUX Schnell">
|
||||
</div>
|
||||
<div class="form-field">
|
||||
<label>Steps</label>
|
||||
<input type="number" id="new-steps" value="20" min="1" max="200">
|
||||
</div>
|
||||
<div class="form-field">
|
||||
<label>CFG</label>
|
||||
<input type="number" id="new-cfg" value="7.0" min="0" max="30" step="0.1">
|
||||
</div>
|
||||
<div class="form-field">
|
||||
<label>Start At Step</label>
|
||||
<input type="number" id="new-start" value="0" min="0" max="200">
|
||||
</div>
|
||||
<div class="form-field">
|
||||
<label>End At Step</label>
|
||||
<input type="number" id="new-end" value="9999" min="0" max="99999">
|
||||
</div>
|
||||
<div class="form-field">
|
||||
<label>Sampler Name</label>
|
||||
<select id="new-sampler"></select>
|
||||
</div>
|
||||
<div class="form-field">
|
||||
<label>Scheduler</label>
|
||||
<select id="new-scheduler"></select>
|
||||
</div>
|
||||
</div>
|
||||
<div class="form-actions">
|
||||
<button class="btn btn-add" onclick="addPreset()">✅ Preset anlegen</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div id="toast"></div>
|
||||
|
||||
<script>
|
||||
const API = {
|
||||
list: () => fetch("/ta_sampler_presets/list").then(r => r.json()),
|
||||
save: (name, data) => fetch("/ta_sampler_presets/save", {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify({ name, data })
|
||||
}).then(r => r.json()),
|
||||
delete: (name) => fetch("/ta_sampler_presets/delete", {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify({ name })
|
||||
}).then(r => r.json()),
|
||||
reorder: (order) => fetch("/ta_sampler_presets/reorder", {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify({ order })
|
||||
}).then(r => r.json()),
|
||||
};
|
||||
|
||||
// ── Drag & Drop State ─────────────────────────────────────────────────
|
||||
let _dragSrc = null;
|
||||
|
||||
// ── Toast ──────────────────────────────────────────────────────────────
|
||||
function showToast(msg, isError = false) {
|
||||
const t = document.getElementById("toast");
|
||||
t.textContent = msg;
|
||||
t.className = "show" + (isError ? " error" : "");
|
||||
clearTimeout(t._timer);
|
||||
t._timer = setTimeout(() => t.className = "", 3000);
|
||||
}
|
||||
|
||||
// ── Tabelle rendern ────────────────────────────────────────────────────
|
||||
async function loadPresets() {
|
||||
const presets = await API.list();
|
||||
const tbody = document.getElementById("preset-tbody");
|
||||
tbody.innerHTML = "";
|
||||
|
||||
if (!presets || Object.keys(presets).length === 0) {
|
||||
tbody.innerHTML = '<tr><td colspan="9" style="text-align:center;color:#666;padding:20px;">Keine Presets vorhanden.</td></tr>';
|
||||
return;
|
||||
}
|
||||
|
||||
for (const [name, p] of Object.entries(presets)) {
|
||||
const tr = document.createElement("tr");
|
||||
tr.dataset.name = name;
|
||||
tr.draggable = true;
|
||||
tr.innerHTML = `
|
||||
<td class="col-drag"><span class="drag-handle" title="Verschieben">⠿</span></td>
|
||||
<td class="col-name"><strong>${escHtml(name)}</strong></td>
|
||||
<td class="col-num"><input type="number" value="${p.steps}" min="1" max="200" data-field="steps"></td>
|
||||
<td class="col-num"><input type="number" value="${p.cfg}" min="0" max="30" step="0.1" data-field="cfg"></td>
|
||||
<td class="col-num"><input type="number" value="${p.start_at_step}" min="0" max="200" data-field="start_at_step"></td>
|
||||
<td class="col-num"><input type="number" value="${p.end_at_step}" min="0" max="99999" data-field="end_at_step"></td>
|
||||
<td class="col-str">${makeSelect(p.sampler_name, window._samplers, "sampler_name")}</td>
|
||||
<td class="col-str">${makeSelect(p.scheduler, window._schedulers, "scheduler")}</td>
|
||||
<td class="col-act">
|
||||
<button class="btn btn-save" onclick="savePreset(this)">💾 Speichern</button>
|
||||
<br><br>
|
||||
<button class="btn btn-delete" onclick="deletePreset(this)">🗑️ Löschen</button>
|
||||
</td>
|
||||
`;
|
||||
|
||||
// ── Drag Events ──
|
||||
tr.addEventListener("dragstart", e => {
|
||||
_dragSrc = tr;
|
||||
e.dataTransfer.effectAllowed = "move";
|
||||
setTimeout(() => tr.classList.add("dragging"), 0);
|
||||
});
|
||||
tr.addEventListener("dragend", () => {
|
||||
tr.classList.remove("dragging");
|
||||
document.querySelectorAll("#preset-tbody tr").forEach(r => r.classList.remove("drag-over"));
|
||||
});
|
||||
tr.addEventListener("dragover", e => {
|
||||
e.preventDefault();
|
||||
e.dataTransfer.dropEffect = "move";
|
||||
if (_dragSrc && _dragSrc !== tr) {
|
||||
document.querySelectorAll("#preset-tbody tr").forEach(r => r.classList.remove("drag-over"));
|
||||
tr.classList.add("drag-over");
|
||||
}
|
||||
});
|
||||
tr.addEventListener("dragleave", () => tr.classList.remove("drag-over"));
|
||||
tr.addEventListener("drop", async e => {
|
||||
e.preventDefault();
|
||||
tr.classList.remove("drag-over");
|
||||
if (!_dragSrc || _dragSrc === tr) return;
|
||||
|
||||
const rows = [...document.querySelectorAll("#preset-tbody tr")];
|
||||
const srcIdx = rows.indexOf(_dragSrc);
|
||||
const destIdx = rows.indexOf(tr);
|
||||
if (srcIdx < destIdx) tr.after(_dragSrc);
|
||||
else tr.before(_dragSrc);
|
||||
|
||||
// Neue Reihenfolge an Backend senden
|
||||
const order = [...document.querySelectorAll("#preset-tbody tr[data-name]")]
|
||||
.map(r => r.dataset.name);
|
||||
const res = await API.reorder(order);
|
||||
if (res.ok) showToast("↕️ Reihenfolge gespeichert.");
|
||||
else showToast(`❌ Fehler: ${res.error}`, true);
|
||||
});
|
||||
|
||||
tbody.appendChild(tr);
|
||||
}
|
||||
}
|
||||
|
||||
// ── Preset speichern ───────────────────────────────────────────────────
|
||||
async function savePreset(btn) {
|
||||
const tr = btn.closest("tr");
|
||||
const name = tr.dataset.name;
|
||||
const data = {};
|
||||
tr.querySelectorAll("[data-field]").forEach(el => {
|
||||
const f = el.dataset.field;
|
||||
data[f] = (f === "steps" || f === "start_at_step" || f === "end_at_step")
|
||||
? parseInt(el.value)
|
||||
: f === "cfg"
|
||||
? parseFloat(el.value)
|
||||
: el.value.trim();
|
||||
});
|
||||
const res = await API.save(name, data);
|
||||
if (res.ok) showToast(`✅ Preset '${name}' gespeichert.`);
|
||||
else showToast(`❌ Fehler: ${res.error}`, true);
|
||||
}
|
||||
|
||||
// ── Preset löschen ─────────────────────────────────────────────────────
|
||||
async function deletePreset(btn) {
|
||||
const tr = btn.closest("tr");
|
||||
const name = tr.dataset.name;
|
||||
if (!confirm(`Preset '${name}' wirklich löschen?`)) return;
|
||||
const res = await API.delete(name);
|
||||
if (res.ok) { showToast(`🗑️ Preset '${name}' gelöscht.`); await loadPresets(); }
|
||||
else showToast(`❌ Fehler: ${res.error}`, true);
|
||||
}
|
||||
|
||||
// ── Neues Preset anlegen ───────────────────────────────────────────────
|
||||
async function addPreset() {
|
||||
const name = document.getElementById("new-name").value.trim();
|
||||
if (!name) { showToast("⚠️ Bitte einen Namen eingeben.", true); return; }
|
||||
|
||||
const data = {
|
||||
steps: parseInt(document.getElementById("new-steps").value),
|
||||
cfg: parseFloat(document.getElementById("new-cfg").value),
|
||||
start_at_step: parseInt(document.getElementById("new-start").value),
|
||||
end_at_step: parseInt(document.getElementById("new-end").value),
|
||||
sampler_name: document.getElementById("new-sampler").value,
|
||||
scheduler: document.getElementById("new-scheduler").value,
|
||||
};
|
||||
|
||||
const res = await API.save(name, data);
|
||||
if (res.ok) {
|
||||
showToast(`✅ Preset '${name}' angelegt.`);
|
||||
document.getElementById("new-name").value = "";
|
||||
await loadPresets();
|
||||
} else {
|
||||
showToast(`❌ Fehler: ${res.error}`, true);
|
||||
}
|
||||
}
|
||||
|
||||
// ── Select-HTML erzeugen ───────────────────────────────────────────────
|
||||
function makeSelect(selected, options, field) {
|
||||
const opts = options.map(o =>
|
||||
`<option value="${escHtml(o)}"${o === selected ? " selected" : ""}>${escHtml(o)}</option>`
|
||||
).join("");
|
||||
return `<select data-field="${field}" style="background:#16162a;border:1px solid #3d3d6e;color:#e0e0e0;padding:4px 6px;border-radius:4px;width:100%;font-size:0.85rem;">${opts}</select>`;
|
||||
}
|
||||
|
||||
// ── Dropdowns für neues Preset befüllen ───────────────────────────────
|
||||
function fillNewPresetDropdowns() {
|
||||
const samplerSel = document.getElementById("new-sampler");
|
||||
const schedulerSel = document.getElementById("new-scheduler");
|
||||
|
||||
window._samplers.forEach(s => {
|
||||
const opt = document.createElement("option");
|
||||
opt.value = s; opt.textContent = s;
|
||||
if (s === "euler") opt.selected = true;
|
||||
samplerSel.appendChild(opt);
|
||||
});
|
||||
|
||||
window._schedulers.forEach(s => {
|
||||
const opt = document.createElement("option");
|
||||
opt.value = s; opt.textContent = s;
|
||||
if (s === "normal") opt.selected = true;
|
||||
schedulerSel.appendChild(opt);
|
||||
});
|
||||
|
||||
// Style
|
||||
[samplerSel, schedulerSel].forEach(el => {
|
||||
el.style.cssText = "background:#16162a;border:1px solid #3d3d6e;color:#e0e0e0;padding:6px 8px;border-radius:4px;width:100%;font-size:0.88rem;";
|
||||
});
|
||||
}
|
||||
|
||||
function escHtml(str) {
|
||||
return String(str)
|
||||
.replace(/&/g,"&").replace(/</g,"<")
|
||||
.replace(/>/g,">").replace(/"/g,""");
|
||||
}
|
||||
|
||||
// ── Init ──────────────────────────────────────────────────────────────
|
||||
async function init() {
|
||||
// Sampler + Scheduler laden
|
||||
const opts = await fetch("/ta_sampler_presets/options").then(r => r.json());
|
||||
window._samplers = opts.samplers || [];
|
||||
window._schedulers = opts.schedulers || [];
|
||||
|
||||
fillNewPresetDropdowns();
|
||||
await loadPresets();
|
||||
}
|
||||
|
||||
init();
|
||||
</script>
|
||||
</body>
|
||||
</html>
|
||||
+1968
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,262 @@
|
||||
<!DOCTYPE html>
|
||||
<html lang="de">
|
||||
<head>
|
||||
<meta charset="UTF-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
||||
<title>TA Nodes Pack – Wiki</title>
|
||||
<script src="/extensions/TA-ComfyUI-Nodes-Pack/marked.min.js"></script>
|
||||
<style>
|
||||
* {
|
||||
box-sizing: border-box;
|
||||
margin: 0;
|
||||
padding: 0;
|
||||
}
|
||||
|
||||
body {
|
||||
background-color: #1a1a2e;
|
||||
color: #e0e0e0;
|
||||
font-family: "Segoe UI", Arial, sans-serif;
|
||||
font-size: 15px;
|
||||
line-height: 1.7;
|
||||
margin: 0;
|
||||
}
|
||||
|
||||
/* ── Header ── */
|
||||
#header {
|
||||
background: #16213e;
|
||||
border-bottom: 1px solid #2a3a5e;
|
||||
padding: 14px 40px 12px 40px;
|
||||
}
|
||||
|
||||
#header .title {
|
||||
font-size: 1.25em;
|
||||
font-weight: 700;
|
||||
color: #e0e0e0;
|
||||
margin-bottom: 3px;
|
||||
}
|
||||
|
||||
#header .subtitle {
|
||||
font-size: 0.82em;
|
||||
color: #7a8aaa;
|
||||
}
|
||||
|
||||
#header .subtitle span {
|
||||
margin: 0 6px;
|
||||
opacity: 0.4;
|
||||
}
|
||||
|
||||
#header .copyright {
|
||||
font-size: 0.78em;
|
||||
color: #555e7a;
|
||||
margin-top: 4px;
|
||||
}
|
||||
|
||||
/* ── Content ── */
|
||||
#content {
|
||||
padding: 36px 40px;
|
||||
max-width: 860px;
|
||||
margin: 0 auto;
|
||||
}
|
||||
|
||||
#content h1 {
|
||||
color: #5a9bf5;
|
||||
font-size: 1.9em;
|
||||
margin-bottom: 0.4em;
|
||||
border-bottom: 2px solid #2a5db0;
|
||||
padding-bottom: 0.3em;
|
||||
}
|
||||
|
||||
#content h2 {
|
||||
color: #7ab3f7;
|
||||
font-size: 1.4em;
|
||||
margin-top: 1.6em;
|
||||
margin-bottom: 0.4em;
|
||||
border-bottom: 1px solid #2a3a5e;
|
||||
padding-bottom: 0.2em;
|
||||
}
|
||||
|
||||
#content h3 {
|
||||
color: #a0c4ff;
|
||||
font-size: 1.1em;
|
||||
margin-top: 1.2em;
|
||||
margin-bottom: 0.3em;
|
||||
}
|
||||
|
||||
#content p {
|
||||
margin-bottom: 0.9em;
|
||||
}
|
||||
|
||||
#content ul, #content ol {
|
||||
margin: 0.5em 0 0.9em 1.6em;
|
||||
}
|
||||
|
||||
#content li {
|
||||
margin-bottom: 0.3em;
|
||||
}
|
||||
|
||||
#content code {
|
||||
background: #0d1b2a;
|
||||
color: #7dd3fc;
|
||||
padding: 0.15em 0.45em;
|
||||
border-radius: 4px;
|
||||
font-family: "Cascadia Code", "Consolas", monospace;
|
||||
font-size: 0.9em;
|
||||
}
|
||||
|
||||
#content pre {
|
||||
background: #0d1b2a;
|
||||
border: 1px solid #2a3a5e;
|
||||
border-radius: 6px;
|
||||
padding: 1em;
|
||||
overflow-x: auto;
|
||||
margin-bottom: 1em;
|
||||
}
|
||||
|
||||
#content pre code {
|
||||
background: none;
|
||||
padding: 0;
|
||||
color: #a5d6f8;
|
||||
}
|
||||
|
||||
#content blockquote {
|
||||
border-left: 4px solid #2a5db0;
|
||||
padding-left: 1em;
|
||||
color: #a0a0b0;
|
||||
margin: 0.8em 0;
|
||||
}
|
||||
|
||||
#content table {
|
||||
border-collapse: collapse;
|
||||
width: 100%;
|
||||
margin-bottom: 1em;
|
||||
}
|
||||
|
||||
#content th {
|
||||
background: #2a5db0;
|
||||
color: #fff;
|
||||
padding: 0.5em 0.8em;
|
||||
text-align: left;
|
||||
}
|
||||
|
||||
#content td {
|
||||
border: 1px solid #2a3a5e;
|
||||
padding: 0.45em 0.8em;
|
||||
}
|
||||
|
||||
#content tr:nth-child(even) td {
|
||||
background: #1e2a40;
|
||||
}
|
||||
|
||||
#content a {
|
||||
color: #5a9bf5;
|
||||
text-decoration: none;
|
||||
}
|
||||
|
||||
#content a:hover {
|
||||
text-decoration: underline;
|
||||
}
|
||||
|
||||
#content hr {
|
||||
border: none;
|
||||
border-top: 1px solid #2a3a5e;
|
||||
margin: 1.5em 0;
|
||||
}
|
||||
|
||||
#error {
|
||||
display: none;
|
||||
color: #f87171;
|
||||
background: #2a1a1a;
|
||||
border: 1px solid #7f1d1d;
|
||||
border-radius: 6px;
|
||||
padding: 1em;
|
||||
margin: 1em 40px;
|
||||
}
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
|
||||
<div id="header">
|
||||
<div class="title">📖 TA Nodes Pack – Dokumentation</div>
|
||||
<div class="subtitle">
|
||||
Wiki für alle Nodes des TA-ComfyUI-Nodes-Pack
|
||||
<span>·</span>
|
||||
Markdown-Dateien in <code>web/wiki/</code>
|
||||
</div>
|
||||
<div class="copyright">© 2026, Thomas Möhrling (thomo.ART)</div>
|
||||
</div>
|
||||
|
||||
<div id="error"></div>
|
||||
<div id="content"></div>
|
||||
|
||||
<script>
|
||||
const params = new URLSearchParams(location.search);
|
||||
const page = params.get("page") || "help.md";
|
||||
|
||||
if (!/^[\w\-]+\.md$/i.test(page)) {
|
||||
document.getElementById("error").style.display = "block";
|
||||
document.getElementById("error").textContent = "Ungültiger Seitenname.";
|
||||
} else {
|
||||
fetch(`/ta-nodes/wiki/${page}?v=${Date.now()}`)
|
||||
.then(r => {
|
||||
if (!r.ok) throw new Error(`HTTP ${r.status}`);
|
||||
return r.text();
|
||||
})
|
||||
.then(md => renderChunked(md))
|
||||
.catch(err => {
|
||||
const el = document.getElementById("error");
|
||||
el.style.display = "block";
|
||||
el.textContent = `Fehler beim Laden von "${page}": ${err.message}`;
|
||||
});
|
||||
}
|
||||
|
||||
// Split markdown on top-level section boundaries (--- separator lines),
|
||||
// render each chunk in a separate requestAnimationFrame so the browser
|
||||
// stays responsive and doesn't drop list items on large documents.
|
||||
function renderChunked(md) {
|
||||
const content = document.getElementById("content");
|
||||
content.innerHTML = "";
|
||||
|
||||
// Split on lines that are exactly "---" (our section separators).
|
||||
// Keep the separator so marked renders the <hr> correctly.
|
||||
// Split only on double-separator lines ("---\n---") which are
|
||||
// our explicit section boundaries, never inside tables/code.
|
||||
const chunks = md.split(/(?=^---\n---$)/m);
|
||||
|
||||
let i = 0;
|
||||
function renderNext() {
|
||||
if (i >= chunks.length) {
|
||||
// After all chunks are rendered, fix anchor links so
|
||||
// clicking a TOC entry scrolls to the right section.
|
||||
fixAnchors();
|
||||
return;
|
||||
}
|
||||
const div = document.createElement("div");
|
||||
div.innerHTML = marked.parse(chunks[i]);
|
||||
content.appendChild(div);
|
||||
i++;
|
||||
requestAnimationFrame(renderNext);
|
||||
}
|
||||
requestAnimationFrame(renderNext);
|
||||
}
|
||||
|
||||
// marked.js generates anchors from heading text (slugified).
|
||||
// Our headings contain <a id="..."> tags which marked wraps inside
|
||||
// the heading, so the id ends up on the inner <a> not the heading.
|
||||
// This function hoists every id from an inner <a> up to its parent
|
||||
// heading element so that in-page hash navigation works correctly.
|
||||
function fixAnchors() {
|
||||
document.querySelectorAll("h1 a[id], h2 a[id], h3 a[id]").forEach(a => {
|
||||
const heading = a.closest("h1, h2, h3");
|
||||
if (heading && !heading.id) {
|
||||
heading.id = a.id;
|
||||
}
|
||||
});
|
||||
// If the URL already has a hash, scroll to it now that IDs are set.
|
||||
if (location.hash) {
|
||||
const target = document.getElementById(location.hash.slice(1));
|
||||
if (target) target.scrollIntoView();
|
||||
}
|
||||
}
|
||||
</script>
|
||||
</body>
|
||||
</html>
|
||||
Reference in New Issue
Block a user