Compare commits
@@ -1,11 +1,24 @@
|
||||
# ComfyUI-Workflow-Studio
|
||||
|
||||
A comprehensive workflow management and generation UI plugin for [ComfyUI](https://github.com/comfyanonymous/ComfyUI).
|
||||
A comprehensive workflow, asset management, and generation UI plugin for [ComfyUI](https://github.com/comfyanonymous/ComfyUI).
|
||||
|
||||
Browse, organize, and execute workflows directly from a dedicated studio interface — without switching between windows or manually editing JSON.
|
||||
**📁 Management** — organize all your assets in one studio
|
||||
- Workflow, model, image, and prompt management
|
||||
- AI-powered prompt writing assistance, translation, and tag generation
|
||||
- File drop & Gallery-linked metadata viewing — inspect and reuse generation settings instantly
|
||||
|
||||
**⚡ GenerateUI** — a productivity-focused generation tab connected to every other tab
|
||||
- Batch generation across models, samplers, prompts, and workflows
|
||||
- Image Feeder for continuous folder-based generation
|
||||
|
||||
**📚 Workflow Studio Library** — a multi-function side panel for smooth ComfyUI integration
|
||||
- Drag & drop models, nodes, prompts, and workflows straight onto the canvas
|
||||
- **Send to Canvas**: click "Send to Canvas" (Workflow tab) or "Copy & Send Canvas" (Gallery tab) to send the workflow directly to the ComfyUI canvas — UI and API formats both supported
|
||||
- View metadata from images / JSON, then drop the detected models and prompts onto the canvas
|
||||
- Built-in AI tools (translation and more)
|
||||
|
||||

|
||||

|
||||

|
||||
|
||||
## Screenshots
|
||||
|
||||
@@ -17,13 +30,21 @@ Browse, organize, and execute workflows directly from a dedicated studio interfa
|
||||
|:---:|:---:|
|
||||
|  |  |
|
||||
|
||||
| Top Bar | WS Library |
|
||||
| GenUI LoRA Stack | GenUI Batch |
|
||||
|:---:|:---:|
|
||||
|  |  |
|
||||
|  |  |
|
||||
|
||||
| Library Information | Customize |
|
||||
| Models Multi-select Menu | Top Bar |
|
||||
|:---:|:---:|
|
||||
|  |  |
|
||||
|  |  |
|
||||
|
||||
| WS Library | Library Information |
|
||||
|:---:|:---:|
|
||||
|  |  |
|
||||
|
||||
| Customize | |
|
||||
|:---:|:---:|
|
||||
|  | |
|
||||
|
||||
---
|
||||
|
||||
@@ -37,7 +58,7 @@ Browse, organize, and execute workflows directly from a dedicated studio interfa
|
||||
- **Side panel tabs** — Thumbnail preview, JSON viewer with syntax highlighting, and Group management
|
||||
- **Badge management** — add, rename, delete badges with custom colors shared with the Models tab (⚙ Badge button)
|
||||
- **AI summary** — generate workflow descriptions using Ollama
|
||||
- **Import / Export** — import workflows from files or clipboard, open in ComfyUI directly
|
||||
- **Import / Export** — import workflows from files or clipboard; **Send to Canvas** button sends the selected workflow directly to the ComfyUI canvas (UI and API formats both supported)
|
||||
- **Default view setting** — persist your preferred view mode (Thumbnail / Table)
|
||||
|
||||
### Canvas Snapshot (v0.1.2)
|
||||
@@ -48,6 +69,7 @@ Browse, organize, and execute workflows directly from a dedicated studio interfa
|
||||
|
||||
### GenerateUI Tab (v0.3.5)
|
||||
- **5-tab layout** — Input / Model / Settings / Feeder / Batch tabs; Input, Model, and Settings each include a Raw JSON column on the right for instant preview and direct editing
|
||||
- **Save button** — located at the right end of the subtab row; opens a filename dialog (default: current workflow name) and saves the current workflow as a `.json` file to the Workflow tab via the import API
|
||||
- **Input tab** — Prompt (top) and Image drag-and-drop (bottom) in the left column; Raw JSON (540px) in the right column
|
||||
- **Model tab** — Checkpoint, VAE, LoRA, ControlNet, UNET, TextEncoder selectors with filter; Raw JSON on the right
|
||||
- **Settings tab** — KSampler and Latent Image side by side at 50% width each; Raw JSON on the right
|
||||
@@ -62,8 +84,10 @@ Browse, organize, and execute workflows directly from a dedicated studio interfa
|
||||
- **UI-to-API conversion** — automatic conversion supporting subgraphs (nested workflows), COMBO types, and display-only node exclusion; improved analysis covers SDXL multi-hop CONDITIONING chains, CLIPTextEncodeSDXL, SDXLPromptStyler, KSamplerAdvanced, and more
|
||||
- **Eagle integration** — auto-save generated images to [Eagle](https://eagle.cool/) with metadata
|
||||
|
||||
### Feeder subtab (v0.3.5)
|
||||
Requires the **[comfyui-image-feeder](https://github.com/ketle-man/comfyui-image-feeder)** custom node.
|
||||
### Feeder subtab (v0.3.5 / v0.3.42)
|
||||
Two independent modes selectable via **[Image Loop] / [Gallery]** toggle buttons at the top of the left pane (persisted in `localStorage`).
|
||||
|
||||
**Image Loop mode** — requires the **[comfyui-image-feeder](https://github.com/ketle-man/comfyui-image-feeder)** custom node.
|
||||
- **ImageFeeder node control** — select the target node from a dropdown auto-populated from the loaded workflow; edit all node parameters (Directory, Sort Mode, Index, Start/End Index, Batch Size, Seed, Use Selection) and Apply to the workflow
|
||||
- **Image library** — 3-pane layout: folder tree (left) browsing `user/default/image-loop-data/`, image grid with checkbox selection (center), preview panel with resolution and file size (right)
|
||||
- **Selection management** — check individual images; All / None buttons for the current folder; selected files are reflected in `selected_files` on Apply
|
||||
@@ -75,6 +99,13 @@ Requires the **[comfyui-image-feeder](https://github.com/ketle-man/comfyui-image
|
||||
- **Index sync** — after each generation the node returns `next_index` via WebSocket (`image_loop_node_sync`); the Index field updates automatically
|
||||
- **Seed** — Run loop uses the right-pane seed setting (Random / Fixed / Increment / Decrement); the node's own Seed field only affects random sort order
|
||||
|
||||
**Gallery mode** (v0.3.42) — no external plugin required; uses the built-in **WFS_GalleryFeeder** custom node.
|
||||
- **WFS_GalleryFeeder node** — reads images directly from a Gallery group and outputs them one at a time; inputs: `group_name`, `index`, `sort_mode` (filename_asc / filename_desc / random), `seed`
|
||||
- **Node & group selector** — pick the WFS_GalleryFeeder node from the loaded workflow and choose which Gallery group to feed images from; `__Feeder__` group is auto-created on first open
|
||||
- **Image grid** — center pane shows all images in the selected group; click any image to update the Index to that position
|
||||
- **After Gen modes** — Loop (wrap at end and continue indefinitely), Increment (stop automatically when last image is reached), Fixed (always use the same index)
|
||||
- **Run / Stop controls** — left pane Run / Stop buttons manage the generation loop; After Gen combo (loop / increment / fixed), ▶ Run, and ■ Stop widgets are also available directly on the WFS_GalleryFeeder node in the ComfyUI canvas (`gallery_feeder_extension.js`)
|
||||
|
||||
### Prompt Tab
|
||||
- **3-column layout** — AI Assistant (left), Presets/Preset Manager tab-panel (center), Wildcard support (right)
|
||||
- **AI chat assistant** — powered by [Ollama](https://ollama.com/), generate and refine prompts interactively
|
||||
@@ -116,20 +147,24 @@ Requires the **[comfyui-image-feeder](https://github.com/ketle-man/comfyui-image
|
||||
- **Wildcard Integration** — link the WFS wildcard directory to ComfyUI-Impact-Pack's `wildcards/` directory (directory junction on Windows, symlink on other OS); existing WFS wildcard files are automatically migrated; requires [ComfyUI-Impact-Pack](https://github.com/ltdrdata/ComfyUI-Impact-Pack)
|
||||
- **Language** — English / Japanese / Chinese
|
||||
|
||||
### Gallery Tab (v0.3.1)
|
||||
### Gallery Tab (v0.3.44)
|
||||
- **Image browser** — browse ComfyUI output images (Thumbnail / Table views) with server-side scanning optimized for 6,000+ image libraries
|
||||
- **Thumbnail / Table views** — switch view modes; Favorites column shown leftmost in Table view
|
||||
- **Folder management** — create subfolders ("+ New") or delete the selected folder with all contents ("Del") from the folder tree header
|
||||
- **File operations** — move or delete individual images from the detail panel's Info tab; bulk Move To... and Delete from the multi-select bar
|
||||
- **Multi-select** — Ctrl+click to select multiple images; Bulk Bar appears for batch operations (group, favorite, move, delete)
|
||||
- **File operations** — move or delete individual images from the detail panel's Info tab; bulk Move To... and Delete File from the multi-select bar
|
||||
- **Multi-select** — Ctrl+click to select multiple images; Bulk Bar appears for batch operations: select group → "Add to Group" / "Remove from Group"; Favorite All / Unfavorite All; Compare (2–4 images); Move To...; Delete File
|
||||
- **Image Compare** — select 2–4 images with Ctrl+click, then click "Compare" in the Bulk Bar to open a side-by-side lightbox; grid adapts to the number of selected images
|
||||
- **Prompt search** — text search covers filename, tags, memo, and prompt text (A1111 `parameters` field cached on first detail panel open)
|
||||
- **Server-side filtering** — filter by group, favorites, or tags with fast server-side set lookup (no full rescan)
|
||||
- **Group management** — create, rename, delete groups and assign/remove images using the same 4-section panel as Models tab
|
||||
- **Group management** — create, rename, delete groups and assign/remove images using the same 4-section panel as Models tab; **`__Feeder__`** is a reserved group (🔒 prefix) that cannot be renamed or deleted; used by the Feeder Gallery mode to define the generation queue; **FC** button in the toolbar clears all members without deleting the group
|
||||
- **Thumbnail F button** — cyan overlay button (top-left of each image card) toggles the image's membership in the `__Feeder__` group; cyan and always-visible when the image is in the group; visible on hover only when inactive
|
||||
- **Favorites** — star images inline without reopening the detail panel
|
||||
- **Detail panel** — view filename, path, tags, groups, and metadata in a slide-out panel
|
||||
- **Workflow viewer** — Metadata tab displays workflow JSON from PNG embedded data (`prompt` / `workflow` keys) or from workflow saved by the Generate UI tab
|
||||
- **Workflow viewer** — Metadata tab displays workflow JSON from PNG embedded data (`prompt` / `workflow` keys) or from workflow saved by the Generate UI tab; **Copy & Send Canvas** button copies the JSON to the clipboard and sends the workflow directly to the ComfyUI canvas (UI and API formats both supported)
|
||||
- **Load GenUI button** — loads the embedded ComfyUI workflow from the selected image directly into the GenerateUI tab; shows a warning toast if no workflow is embedded or the format is unsupported; Metadata button is styled green, Load GenUI button uses the primary accent color
|
||||
- **Workflow auto-save** — images generated from the Generate UI tab have their workflow automatically saved to gallery metadata
|
||||
- **Output folder configurable** — set the scanned output folder from Settings tab
|
||||
- **Performance** — folder-level mtime cache (30s TTL) for fast incremental refresh; tree expansion state preserved across folder operations
|
||||
- **Performance** — server-side 256px JPEG thumbnail generation with disk cache (`data/thumb_cache/`); infinite-scroll paging (50 images per page, IntersectionObserver); folder-level mtime cache (60s TTL); bulk operations use single-request API endpoints
|
||||
|
||||
### Nodes Tab (v0.1.7)
|
||||
- **Node Browser** — browse all installed ComfyUI nodes from `/object_info` API with Card/Table views
|
||||
@@ -141,29 +176,46 @@ Requires the **[comfyui-image-feeder](https://github.com/ketle-man/comfyui-image
|
||||
|
||||
### Models Tab (v0.2.3)
|
||||
- **Model Browser** — browse all installed ComfyUI models (Checkpoint, LoRA, VAE, ControlNet, UNET, TextEncoder, Hypernetwork, Embedding) with sub-tab switching
|
||||
- **Thumbnail / Table views** — switch between view modes with pagination (24 items per page)
|
||||
- **Thumbnail / Table views** — switch between view modes with pagination (24 items per page); Table view includes **Type** and **Base Model** columns sourced from cached CivitAI data, displayed between the Subdirectory and Extension columns; Enable/Disable column labeled **E/D**
|
||||
- **Table column sort** — click any column header to sort ascending (▲), click again for descending (▼), click a third time to clear; active column highlighted in accent color
|
||||
- **Search & Filter** — full-text search, filter by tags, groups, and favorites
|
||||
- **User-defined badges** — assign free-label badges to models; badge colors shared with the Workflow tab palette
|
||||
- **Side panel tabs** — Info (file path display with click-to-copy, tags, memo), Groups management, CivitAI integration
|
||||
- **Side panel tabs** — opens to CivitAI tab by default when a model is selected; Info (file path display with click-to-copy, tags, memo), Groups management, CivitAI integration
|
||||
- **CivitAI integration** — fetch model metadata by SHA256 hash; side panel shows **Type** (badge), **Base Model**, **Hash** (BLAKE3/SHA256, click to copy), trained words, tags, and model page link; model link opens in the site selected in Settings (civitai.com or civitai.red)
|
||||
- **CivitAI panel — Info / Sample sub-tabs** — Info tab shows model details (name, type, base model, hash, trigger words, tags, description); Sample tab shows all sample images (count shown in tab label); clicking any image opens the full-size version in a new tab
|
||||
- **CivitAI panel states** — three distinct states: not yet checked (fetch button), checked but not found on CivitAI (re-check button with notice), and found (full info display); clicking the CivitAI tab always refreshes to the latest state
|
||||
- **Batch CivitAI fetch** — one-click batch fetch using `POST /model-versions/by-hash` (up to 100 models per request) with SSE progress streaming; previews are auto-saved for models without one
|
||||
- **Detail modal** — preview image, CivitAI info, thumbnail change via file upload
|
||||
- **Detail modal** — preview image, CivitAI info, thumbnail change via file upload; **Delete** button permanently removes the model file and all associated sidecar files (preview images, `.json`, `.civitai.info`, `.metadata.json`, `.cm-info.json`)
|
||||
- **GenUI Model button** — apply the selected model directly to the corresponding node in GenerateUI's current workflow (Checkpoint, LoRA, VAE, ControlNet, UNET, TextEncoder)
|
||||
- **Group management** — create, rename, delete groups and assign/remove models; groups are scoped per model type (checkpoint groups only appear in the Checkpoint tab)
|
||||
- **Group management** — create, rename, delete groups and assign/remove models; groups are scoped per model type (checkpoint groups only appear in the Checkpoint tab); Checkpoint and LoRA tabs include **B (Batch)** and **S (Stack)** quick-assign buttons per card/row for one-click group membership toggle without grid re-render
|
||||
- **Table view memo** — memo column displayed in table view for quick reference
|
||||
- **Preview images** — auto-detect `{model_stem}.preview.png` next to model files
|
||||
- **Enable / Disable models** — hide models from ComfyUI by renaming the file extension (`.disabled` suffix); toggle per card (⏸ button), per group (Enable All / Disable All), or filter by status (All / Enabled / Disabled)
|
||||
- **Multi-select & bulk operations** — enter selection mode to check multiple models; bulk action bar supports: **Deselect All** (clear all without exiting select mode), **★ Favorite / ☆ Unfavorite** (toggle favorites for all selected), **Add / Remove from Group**, **Create & Add** (new group), **+Badge / −Badge** (apply or remove a badge from all selected), and permanent **Delete Files** (model file + preview images + sidecar files such as `.json` / `.info`)
|
||||
- **Multi-select & bulk operations** — click the green **Select** button to enter selection mode and check multiple models; the bulk action bar is organized in three rows:
|
||||
- **Group row** — select an existing group and **Add** / **Remove**, or type a new name and **Create & Add**
|
||||
- **Badge row** — select a badge and **+Badge** / **−Badge** to apply or remove from all selected
|
||||
- **File row** — select a destination subfolder (or type a new folder name and create it) then **Move** to relocate the model file with all sidecar files; **Delete Files** (right end) permanently removes selected models and all associated files
|
||||
|
||||
### Tagger Tab (v0.3.38)
|
||||
- **3 sub-tabs** — Single / Batch / DB for single-image tagging, folder batch processing, and tag database management
|
||||
- **Model support** — WD Tagger (ONNX, NCHW/NHWC auto-detect), SwinV2 (ONNX), DeepDanbooru (.h5, requires TensorFlow); place each model in its own subfolder under `ComfyUI/models/tagger/<model-name>/` containing the `.onnx` + `selected_tags.csv` (or `.h5` + label file)
|
||||
- **Threshold sliders** — General threshold (default 0.35) and Character threshold for `character:` prefix tags (default 0.85); sliders update the display value in real time
|
||||
- **Ollama VLM** — optional vision model alongside WD Tagger; set API URL and select model (↻ to refresh list); results from both models are merged into one comma-separated tag string
|
||||
- **Single tab** — drag & drop an image onto the preview area or click Upload; Gallery detail panel **Tagger** button opens the selected image directly here
|
||||
- **Single output options** — (1) **GenUI:P** — appends tags to the GenerateUI tab's positive prompt and immediately applies to the loaded workflow; (2) **Send to Prompt** — appends tags to the Prompt tab's positive textarea; (3) **Save to Gallery** — saves tags to Gallery image metadata (requires image opened from Gallery); (4) **Write to File** — embeds tags into JPEG EXIF (`ImageDescription`) or PNG `tEXt` chunk (`Tags` key), other formats get a `.tags.json` sidecar; (5) **Save to DB** — stores in internal SQLite database
|
||||
- **Batch tab** — enter a folder path, configure WD Tagger and Ollama settings; output options: **Save to DB** (default on), **Write to File** (EXIF/PNG metadata), **Write .txt** (creates `<filename>.txt` alongside each image with all tags); real-time progress bar and log; Stop cancels after the current image
|
||||
- **DB tab** — searchable SQLite database of all tagged images; click a row to open the edit panel and modify WD Tags / VLM Tags; Save updates the record, Delete removes it; Export CSV downloads all records
|
||||
- **Dependencies** — install into ComfyUI's embedded Python: `python_embedded\python.exe -m pip install -r requirements.txt`; for GPU inference use `onnxruntime-gpu`; TensorFlow (DeepDanbooru) is optional and commented out in `requirements.txt`
|
||||
|
||||
### AI TOOL Tab (v0.3.14)
|
||||
- **3-pane layout** — Translation (40%) | TOOLS (40%) | Settings (20%); all panes always visible simultaneously; no sub-tab switching required
|
||||
- **4-pane layout** — Translation | Chat | TOOLS | Settings; all panes always visible simultaneously; no sub-tab switching required
|
||||
- **Translation pane** — translate text between Japanese, English, Chinese, or a custom Free language using Ollama or LM Studio; language selectors with ⇄ swap button (swaps both language selectors and text content); selections saved automatically
|
||||
- **Chat pane** (v0.3.40) — multi-turn conversation with the LLM; full conversation history sent each turn for context; Enter to send, Shift+Enter for a newline; Clear button resets history; Ollama uses `/api/chat`, LM Studio uses `/v1/chat/completions`
|
||||
- **TOOLS pane (VLM)** — drop an image into the 110px drop zone, select a task (Describe Image / Create Prompt / Create Tags), and click Run to analyze with a vision model; result shown in the output area with a Copy button
|
||||
- **TOOLS pane (Wildcards)** (v0.3.40) — select "Create wildcards" from the task dropdown; enter a category name and count; click Run to generate plain-text wildcard entries one per line (no markdown, no numbering); result can be copied directly into wildcard `.txt` files
|
||||
- **Settings pane** — choose backend (Ollama / LM Studio), set the API URL, test connection, select a model (with refresh button), and configure Free language names for translation source and destination
|
||||
- **Settings shared** — settings saved to `localStorage` under `wfm_ai_settings`; shared with the Library panel's AI TOOL tab so configuration is consistent across both interfaces
|
||||
- **Backend support** — Ollama (`/api/generate` for text, `/api/tags` for model list); LM Studio OpenAI-compatible API (`/v1/chat/completions`, `/v1/models`); VLM images sent as base64 (`images:[]` for Ollama, `image_url` content block for LM Studio)
|
||||
- **Backend support** — Ollama (`/api/generate` for text, `/api/chat` for conversations, `/api/tags` for model list); LM Studio OpenAI-compatible API (`/v1/chat/completions`, `/v1/models`); VLM images sent as base64 (`images:[]` for Ollama, `image_url` content block for LM Studio)
|
||||
- **URL security** — backend URL validated via `new URL()` to enforce `http://` or `https://` scheme
|
||||
|
||||
### Workflow Studio Library (ComfyUI Side Panel) (v0.3.9)
|
||||
@@ -172,25 +224,27 @@ Requires the **[comfyui-image-feeder](https://github.com/ketle-man/comfyui-image
|
||||
- **N — Nodes tab** — browse favorite nodes (All / ★ Favorites / Groups / Sets / 📂 Category / 🧩 Package sub-tabs), ★ star shown for favorites in All view
|
||||
- **Category sub-tab** — dropdown to filter nodes by top-level category
|
||||
- **Package sub-tab** — dropdown to filter nodes by custom node package name
|
||||
- **M — Models tab** — browse installed models (All / ★ Favorites / Groups / By Type sub-tabs)
|
||||
- **P — Prompts tab** — browse prompt presets with All / Favorites / Categories sub-tabs
|
||||
- **I — Information tab** — drop a ComfyUI-generated PNG/WebP or workflow JSON in the side panel to view its metadata; supports `UnetLoaderGGUF` and `QuadrupleCLIPLoader` node types; preview area fixed at 110px
|
||||
- **A — AI TOOL tab** — 3-pane layout (Translation | TOOLS | Settings) always visible; Translation and TOOLS (VLM) powered by Ollama or LM Studio; settings (backend, URL, model) shared with the SPA AI TOOL tab via `localStorage`
|
||||
- **M — Models tab** — browse installed models (All / ★ Favorites / Groups / By Type sub-tabs); LoRA groups show an **All N LoRAs** item — drag to canvas to place a `Lora Loader (LoraManager)` node with all LoRAs pre-loaded
|
||||
- **P — Prompts tab** — browse prompt presets with All / ★ Favorites / Categories sub-tabs; **Groups sub-tab** (row 2) — view presets by group (shared with the Batch tab's `wfm_prompt_preset_groups`)
|
||||
- **I — Information tab** — drop a ComfyUI-generated PNG/WebP or workflow JSON in the side panel to view its metadata; detects LoRAs from `LoraLoader`, `LoraLoaderModelOnly`, and `Lora Loader (LoraManager)` nodes (API format supported); supports `UnetLoaderGGUF` and `QuadrupleCLIPLoader` node types; preview area fixed at 110px
|
||||
- **A — AI TOOL tab** — Translation, Chat, TOOLS, and Settings sub-tabs powered by Ollama or LM Studio; Chat supports multi-turn conversations (full history sent each turn); TOOLS includes VLM image analysis and wildcard generation; settings (backend, URL, model) shared with the SPA AI TOOL tab via `localStorage`
|
||||
- **model sub-tab** — Checkpoint, VAE, Diffusion Model, and Text Encoder; drag items to canvas to place the corresponding loader node (Checkpoint → `CheckpointLoaderSimple`, VAE → `VAELoader`, Diffusion Model → `UNETLoader`, Text Encoder → `CLIPLoader`); double-click also places at canvas center
|
||||
- **lora sub-tab** — LoRA names with `strength_model / strength_clip` values; drag individual LoRA to place `LoraLoader`; **Multiple LORA** section (appears for 1+ LoRAs) drags all LoRAs into a single `Lora Loader (LoraManager)` node
|
||||
- **lora sub-tab** — detects LoRAs from `LoraLoader`, `LoraLoaderModelOnly`, and `Lora Loader (LoraManager)` nodes (API format `inputs.loras.__value__` supported); shows `strength_model / strength_clip` values; drag individual LoRA to place `LoraLoader`; **Multiple LORA** section (appears for 1+ LoRAs) drags all LoRAs into a single `Lora Loader (LoraManager)` node with LoRA syntax pre-filled
|
||||
- **Prompts sub-tab** — POS / NEG badge list; drag a prompt to place `CLIPTextEncode` with text pre-filled; click any entry to view full text + Copy button
|
||||
- **Drag & drop workflows** — drag a workflow onto the canvas to load it
|
||||
- **Drag & drop nodes** — drag nodes/node sets onto the canvas to place them
|
||||
- **Drag & drop prompts** — drag a preset onto the canvas to create a WFS_PromptText node with positive/negative prompts
|
||||
- **Send to Canvas** — clicking "Send to Canvas" (Workflow tab toolbar / detail modal) or "Copy & Send Canvas" (Gallery tab JSON panel) sends the workflow directly to the ComfyUI canvas via `window.opener` (UI and API formats both supported); if Workflow Studio was opened from a bookmark instead of the ComfyUI toolbar, UI-format workflows fall back to title drag (panel title highlights blue with a green ● — drag it onto the canvas to load)
|
||||
- **Copy prompts** — copy individual positive (P) or negative (N) prompts from sidebar items
|
||||
- **Double-click** — load workflows or place nodes without dragging
|
||||
- **Search** — search within each sub-tab to quickly find items
|
||||
- **⚙ Theme settings** — customize panel background, sub-header background, text, border, and secondary text colors; saved to localStorage and applied on every open
|
||||
|
||||
### Help & Support Tab (v0.1.3)
|
||||
- **Sidebar navigation** — 2-column layout: left sidebar (14 topics) + right content pane; click any topic to switch the displayed content
|
||||
- **Support** — fixed at the bottom of the sidebar; shows GitHub and Ko-fi links in the right pane
|
||||
- **Feature list** — overview of all features organized by tab
|
||||
- **Tips** — quick tips for drag & drop import, favorites, and default workflow
|
||||
- **Support links** — GitHub repository and Ko-fi donation page
|
||||
- **Keyboard Shortcuts** and **Troubleshooting** sections included
|
||||
|
||||
---
|
||||
|
||||
@@ -279,6 +333,123 @@ Click the **camera icon** (next to the W button) in ComfyUI's top bar to capture
|
||||
|
||||
## Changelog
|
||||
|
||||
### v0.3.44
|
||||
- **Gallery tab — server-side thumbnail generation** — `GET /wfm/gallery/image/thumb?path=...&w=256` endpoint generates 256px JPEG thumbnails via Pillow and caches them to `data/thumb_cache/` keyed by `md5(path:mtime:width)`; GIF served as-is to preserve animation; falls back to the original file if Pillow is unavailable; thumbnail view and table view both switched from `/image/serve` to `/image/thumb`
|
||||
- **Gallery tab — infinite-scroll paging** — thumbnail view renders 50 images initially; an IntersectionObserver sentinel (rootMargin 300px) appends the next page on scroll; sentinel is disconnected and removed when all images are rendered; paging resets on every `renderImages()` call (folder change, filter, sort)
|
||||
- **Gallery tab — bulk API endpoints** — `POST /wfm/gallery/bulk/favorite` and `POST /wfm/gallery/bulk/group` handle favorite set and group add/remove for any number of images in a single request; replaced N-parallel individual fetches in `bulkSetFavorite()` and `bulkAddToGroup()`
|
||||
- **Gallery tab — image compare mode** — Ctrl+click 2–4 images, then click "Compare" in the Bulk Bar to open a side-by-side lightbox; CSS grid adapts to the image count via `--compare-cols` custom property; close button is `position:fixed` at the top-right corner to avoid `overflow:auto` clipping
|
||||
- **Gallery tab — "Remove from Group" bulk button** — new button in the Bulk Bar (right of "Add to Group"); uses the same group selector dropdown; calls `POST /wfm/gallery/bulk/group` with `action:"remove"`
|
||||
- **Gallery tab — bulk bar UI labels** — dropdown placeholder "Add to Group..." → "Select Group"; "Add" button → "Add to Group"; "Delete" button → "Delete File" (distinguishes file deletion from group removal)
|
||||
- **Gallery tab — prompt search** — text search now covers A1111 `parameters` text embedded in PNG/JPEG metadata; prompt text is extracted on first detail-panel open and stored as `prompt_cache` in `metadata.json`; subsequent `list_images` searches include `prompt_cache` without re-reading image files
|
||||
- **Help tab — Gallery mode i18n** — Feeder subtab Gallery mode section (h4, description, 6 bullet points) now translated to Japanese and Chinese via `i18n.js`
|
||||
- **Help tab — font size ×1.5** — nav items, headings, body text, link cards, and support card text all scaled up in `main.css`
|
||||
- **Help tab — search box** — live search input above the nav sidebar filters matching pages and auto-clicks the first result; placeholder text localized (EN/JA/ZH)
|
||||
|
||||
### v0.3.43
|
||||
- **Send to Canvas — direct canvas load via `window.opener`** — clicking "Send to Canvas" (Workflow tab) or "Copy & Send Canvas" (Gallery tab) now sends the workflow directly to the ComfyUI canvas without requiring a title drag; uses `window.opener.wfmReceiveWorkflow()` registered by `node_sets_menu.js` via `app.handleFile()`; both UI and API formats are supported; fallback to localStorage + title drag when `window.opener` is unavailable (e.g. opened from a bookmark), UI-format only
|
||||
- **Workflow Studio Library — API-format DnD enabled** — API-format workflows in the W (Workflows) sub-tab are no longer grayed out; drag & drop and double-click now work for all formats via `app.handleFile()`
|
||||
|
||||
### v0.3.42
|
||||
- **Feeder tab — Gallery mode** — new [Image Loop] / [Gallery] toggle in the Feeder tab; Gallery mode drives a WFS_GalleryFeeder node without any external plugin: node selector, group select, sort mode / index / seed, After Gen (Loop / Increment / Fixed), Run / Stop; center pane shows the selected group's images — click any image to jump to that index; `__Feeder__` group is auto-created on first open
|
||||
- **WFS_GalleryFeeder custom node** — new ComfyUI node (Workflow Studio category) that reads images from a Gallery group and outputs one `IMAGE` at a time; inputs: `group_name`, `index`, `sort_mode` (filename_asc / filename_desc / random), `seed`; skips missing files; `IS_CHANGED` ensures re-execution on every queue
|
||||
- **WFS_GalleryFeeder — ComfyUI canvas controls** — `gallery_feeder_extension.js` adds After Gen combo (loop / increment / fixed), ▶ Run button, and ■ Stop button as non-serialized widgets directly on the node in the ComfyUI canvas; manages per-node loop state with `waitForExecution()` Promise pattern; `onRemoved` hook auto-stops the loop on node deletion
|
||||
- **Gallery tab — thumbnail F button** — cyan overlay button (top-left of each image card) toggles `__Feeder__` group membership; active state is always visible in cyan, inactive shows only on hover; initial state derived from `img.groups` returned by `list_images()`
|
||||
- **Gallery tab — `__Feeder__` reserved group** — shown with 🔒 prefix in group dropdowns; rename and delete blocked server-side (403) and client-side (buttons disabled); **FC** toolbar button clears all group members without deleting the group
|
||||
- **Security: XSS fixes in `gallery-tab.js`** — tag names, filenames, and server error messages now escaped via `escapeHtml()` before insertion into `innerHTML` (tag badge list, detail panel `alt` attributes, lightbox footer, folder tree errors, grid errors); `util.js` `escapeHtml` updated to also escape single quotes (`'` → `'`)
|
||||
- **Security: path validation in `gallery_service.py`** — `save_image_meta`, `toggle_favorite`, `add_to_group`, `remove_from_group` now call `_check_path_allowed()` before any file operation; previously these four methods were missing the guard that other write methods already had
|
||||
- **Security: `_init_allowed_root()` in `gallery_routes.py`** — `_allowed_root` is now initialized at module load from saved `gallery_output_dir` (falls back to ComfyUI default output dir); prevents `list_folder_tree` from overriding `_allowed_root` via a crafted `?root=` request, and also fixes serve_image returning 404 in Feeder Gallery mode before the Gallery tab is opened
|
||||
- **Bug fix: WFS_GalleryFeeder seed validation error** — seed `max` changed from `0x7FFFFFFF` to `0xffffffffffffffff` (matching KSampler); `applySeedToWorkflow()` was writing values exceeding the old max, causing `value_bigger_than_max` validation failures
|
||||
|
||||
### v0.3.41
|
||||
- **Generate UI — ImpactWildcardEncode / ImpactWildcardProcessor prompt detection** — fixed: wildcard text inputs from comfy-impact-pack nodes were not shown in the Prompt tab of Generate UI
|
||||
- `CLIPTextEncodeEditPlus` node (used as the text encoder in these workflows) now correctly propagates positive/negative roles upstream to ImpactWildcard nodes via BFS
|
||||
- `CLIPTextEncodeEditPlus` with an empty `text_edit` field is no longer added to `prompt_nodes` ahead of the upstream ImpactWildcard node, preventing a blank text area
|
||||
- `widgets[0]` is now always written to `wildcard_text` in the API conversion step, regardless of `object_info` widget-order differences between impact-pack versions
|
||||
- Static fallback mapping added for `ImpactWildcardProcessor` and `ImpactWildcardEncode` so detection works even when the ComfyUI server is offline
|
||||
|
||||
### v0.3.40
|
||||
- **AI TOOL tab — Chat pane** — new pane (between Translation and TOOLS) for multi-turn conversation with the LLM; full conversation history sent each turn for context; Enter to send, Shift+Enter for newline; Clear button resets history; Ollama uses `/api/chat`, LM Studio uses `/v1/chat/completions`
|
||||
- **AI TOOL tab — Wildcard generation** — new "Create wildcards" task in the TOOLS pane dropdown; enter a category name and count, click Run to generate plain-text entries one per line (no markdown, no numbering); output can be pasted directly into wildcard `.txt` files
|
||||
- **Library A tab — Chat and Wildcards** — both features added to the side panel's A tab: Chat as a new sub-tab (Translation → Chat → TOOLS → Settings), wildcard generation as a new option in the TOOLS sub-tab dropdown
|
||||
- **Help updated** — AI TOOL tab help card updated to 6 items (Chat and Wildcards added); Library panel sidepanel-16 updated; EN/JA/ZH
|
||||
|
||||
### v0.3.39
|
||||
- **Workflow tab — Send to Canvas button** — replaced "Open in ComfyUI" (toolbar and detail modal) with "Send to Canvas"; stores the selected workflow in `localStorage` for title-drag to the canvas without opening a new browser tab
|
||||
- **Gallery tab — Copy & Send Canvas button** — renamed "Copy Workflow" to "Copy & Send Canvas"; copies the embedded workflow JSON to the clipboard and simultaneously stores it for title-drag
|
||||
- **Workflow Studio Library — title drag** — after "Send to Canvas" or "Copy & Send Canvas" is clicked, the "Workflow Studio Library" panel title turns blue with a green ● indicator; drag the title onto the ComfyUI canvas to load the workflow; title resets automatically after loading
|
||||
|
||||
### v0.3.38
|
||||
- **Tagger tab** — new tab for automatic image tagging; supports WD Tagger (ONNX), SwinV2, DeepDanbooru (.h5), and Ollama VLM; 3 sub-tabs: Single (drag & drop / upload, 5 output targets), Batch (folder processing with real-time progress), DB (searchable SQLite database with CSV export)
|
||||
- **Tagger single — GenUI:P button** — new button (left of "Send to Prompt") that appends generated tags to the GenerateUI positive prompt and immediately applies them to the loaded workflow; shows a warning if no workflow is loaded in GenerateUI
|
||||
- **Tagger batch — Write .txt output** — new output option that creates `<filename>.txt` alongside each processed image containing all generated tags (comma-separated)
|
||||
- **Gallery detail panel — Tagger button** — new action button in the Gallery detail panel opens the selected image directly in the Tagger tab for instant single-image tagging
|
||||
- **Gallery detail panel layout** — tabs (Info / JSON / Groups) and action buttons (Metadata / Load GenUI / Tagger) are now on separate rows, preventing button overflow on narrow panels
|
||||
- **Gallery — Save to Gallery tags fix** — tags saved from the Tagger tab were stored as a string instead of an array, causing `forEach is not a function` errors on the next Gallery refresh; now correctly stored as a string array
|
||||
- **GenerateUI — ZIT/Lumina2 workflow prompt fix** — `ConditioningZeroOut` removed from the CONDITIONING passthrough set; previously it propagated the "negative" role upstream through the shared CLIPTextEncode node, marking it as "unknown" and hiding the positive prompt in the GenerateUI Input tab; ZIT (Z-Image Turbo) workflows now correctly show the positive prompt
|
||||
- **Workflow analyzer — lumina2 model type** — CLIPLoader `type: "lumina2"` is now correctly classified as Z-IMAGE in the workflow type detector
|
||||
|
||||
### v0.3.37
|
||||
- **Models tab — Select All button** — new button added to the right of "Deselect All" in the multi-select action bar; selects all models currently visible after applying the active search / filter / group filters
|
||||
- **Gallery tab — Select All button** — new button added to the right of "Deselect All" in the bulk action bar; selects all images in the current folder view
|
||||
- **Gallery bulk bar — i18n** — all bulk action bar buttons and the selection count were hard-coded English strings; they now use the `t()` translation system (EN / JA / ZH) so the bar respects the selected UI language
|
||||
|
||||
### v0.3.36
|
||||
- **GenerateUI Save — overwrite protection** — saving now checks for an existing file and asks for confirmation before overwriting; if the target file is in UI format, a dedicated warning explains that saving in API format will lose the node layout
|
||||
- **GenerateUI Save — Raw JSON sync** — unapplied Raw JSON edits are now included in the save (parsed and synced back to the editor); invalid JSON aborts the save with an error instead of silently saving stale content
|
||||
- **GenerateUI Save — hardening** — filename is set via DOM (no HTML-attribute injection), image extensions (`.png` etc.) are stripped from the default name, and a double-submit guard prevents duplicate POSTs
|
||||
- **Help i18n fixed** — v0.3.35 help text updates (Save button, table sort, JSON tab rename) were being overwritten at startup by stale i18n strings and never displayed; all help keys synced in EN / JA / ZH and new entries registered in the help ID map
|
||||
- **Toast i18n** — ~115 hard-coded English toasts replaced with translated messages (~60 new shared keys in EN / JA / ZH); Settings labels for Text Size / RAW JSON Colors that displayed raw key names are now properly defined
|
||||
- **Refactoring** — new shared `util.js` (`escapeHtml` unified across 5 files — the Metadata tab copy was missing `"` escaping; `readJsonStorage` / `getSettings` replace 15 direct `localStorage` parses); Models table sort now precomputes sort keys (faster on large libraries); Gallery action buttons moved off the tab-button class, removing all `!important` CSS overrides
|
||||
- **README refreshed** — intro rewritten around the three pillars (Management / GenerateUI / Library side panel); new screenshots: GenUI LoRA Stack, GenUI Batch, Models Multi-select Menu; WS Library image updated
|
||||
|
||||
### v0.3.35
|
||||
- **Models tab — Table column sort** — click any column header to sort ascending (▲), click again for descending (▼), click a third time to clear; active column name highlighted in accent color; Enable/Disable column header now labeled **E/D**
|
||||
- **Gallery tab — Load GenUI button** — new button to the right of the Metadata button in the detail panel; loads the embedded ComfyUI workflow from the selected image directly into the GenerateUI tab; warning toast shown if no workflow is embedded or the format is unsupported; Metadata button restyled green, Load GenUI uses primary accent color
|
||||
- **GenerateUI tab — Save button** — new button at the right end of the subtab row; opens a filename dialog (default: current workflow name) and saves the current workflow as a `.json` file to the Workflow tab via the import API; workflow name label updates to the saved filename on success
|
||||
|
||||
### v0.3.33
|
||||
- **LoRA pane — workflow load no longer overwrites LoraManager** — removed the auto-apply block that replaced `inputs.loras` / `inputs.text` with Stack group contents on every workflow load; Stack is now applied only when the Apply button is pressed
|
||||
- **LoRA pane — 🔄 button no longer resets to Single tab** — active tab state is saved before `innerHTML` rebuild and restored afterwards; staying on Stack tab after refresh
|
||||
- **Models tab — Stack group hidden for non-LoRA types** — when switching to Checkpoint or other non-LoRA types, the Stack group is now excluded from the group filter dropdown and side-panel group management (LoRA-only concept)
|
||||
- **CLIPTextEncodeEditPlus widget mapping fix** — `convertUiToApi` no longer advances `wIdx` for UI slot inputs that have an actual link, preventing index misalignment when `object_info` lists optional STRING inputs (e.g. `text1`) before widget inputs (e.g. `text_edit`); fixes `+af` appearing as the positive prompt instead of the edit text
|
||||
- **Stack Apply — trigger words now applied correctly on first press** — trigger words (`currentAllTriggers` / `currentActiveTriggers`) are now recomputed at click time from the latest `_stackActive` + `metadata` + `civitaiCache`; previously used a stale snapshot captured at render time, causing trigger words to be missing on the first Apply and to linger after disabling a model
|
||||
|
||||
### v0.3.32
|
||||
- **Lora Loader (LoraManager) LoRA detection** — I tab and Metadata tab now correctly detect LoRAs from `Lora Loader (LoraManager)` nodes in API format (`inputs.loras.__value__`); `strength`/`clipStrength` stored as strings (e.g. `"0.20"`) are now parsed correctly
|
||||
- **LoraManager node placement — LoRA syntax** — placing a `Lora Loader (LoraManager)` node via drag now also updates the `text` widget with `<lora:name:strength>` syntax (previously only the `loras` array widget was set)
|
||||
- **M tab Groups — LoRA → LoraManager drop** — LoRA groups in the Library M tab show an **All N LoRAs** item; drag to canvas places a `Lora Loader (LoraManager)` node with all group LoRAs; double-click also places at canvas center
|
||||
- **P tab — Groups sub-tab** — new Groups sub-tab (row 2) in the Library P tab; groups are read from `localStorage["wfm_prompt_preset_groups"]` (shared with Batch); expanding a group shows draggable preset items
|
||||
|
||||
### v0.3.31
|
||||
- **LoRA pane — Single/Stack tabs** — LoRA pane split into two tabs: Single (filter, model dropdown, M/C strength, target node, Apply, P, LORA SYNTAX, TRIGGER WORDS) and Stack (target node, Apply, P, Toggle-all, global strength adjuster, LORA SYNTAX, TRIGGER WORDS, model list); each tab has independent strength settings
|
||||
- **GenUI Model — LoRA improvements** — now correctly handles `Lora Loader (LoraManager)` nodes (previously failed to find the node); on apply: switches to Single tab, disables all Stack models, and updates LORA SYNTAX / TRIGGER WORDS in the Single tab panel
|
||||
|
||||
### v0.3.30
|
||||
- **LoRA Stack trigger words fix** — inactive stack models no longer show their trigger words in the Trigger words display; both initial render and per-model toggle/toggle-all now filter to active models only
|
||||
- **Help troubleshooting** — added entry for "No such file or directory" error when running LoRA Stack (comfyui-lora-manager compatibility issue)
|
||||
|
||||
### v0.3.29
|
||||
- **LoRA section unified** — single LoRA and Stack sections merged into one pane; Apply button handles both cases (stack models present → apply all active + prompt sync; no stack → apply selected single LoRA + prompt sync); Ctrl+Apply removed, now plain Apply by default
|
||||
- **LoRA prompt sync** — Apply inserts `<lora:stem:M:C>` syntax and CivitAI trigger words into the Positive prompt; re-applying updates the prompt by diff (removes stale tokens, re-adds active ones); works for both single LoRA and Stack
|
||||
- **P button** — placed to the right of Apply; immediately writes the current Positive prompt textarea to the target workflow node without switching tabs
|
||||
- **LoRA UI layout fixes** — "Stack" label moved from ID row to Strength row left of the toggle-all checkbox; ID dropdown expanded to `flex:1` (no max-width cap); M/C input width 54 px → 60 px to prevent value truncation
|
||||
- **Models tab — CivitAI default** — side panel opens to the CivitAI tab by default when a model is selected
|
||||
- **Help tab — sidebar navigation** — redesigned as 2-column layout: left sidebar (14 topics + Support fixed at bottom) + right content pane; content switches on click
|
||||
- **Input tab — Prompt/Image tabs + taller textboxes** — Prompt and Image split into inner tabs; Positive prompt rows 4 → 8, Negative prompt rows 3 → 6
|
||||
- **Reset Workflow button** — added to the GenerateUI toolbar; re-reads the loaded workflow file from disk and reloads the editor
|
||||
- **LoRA Stack trigger words** — CivitAI trigger words for active stack models appended to Positive prompt on Apply; diff-updated on re-apply
|
||||
- **Feeder subtab UI** — (root) folder selected automatically on tab open; PREVIEW pane moved to the far right of the layout; preview auto-updates to the current processing image during a RUN
|
||||
- **Batch tab — Sampler / Scheduler** — left pane gains Sampler and Scheduler tabs (lists fetched from ComfyUI); Batch Queue gains two new columns; batch runs each value through KSampler sequentially
|
||||
- **Lora Loader (LoraManager) support** — workflow analysis, single Apply, Stack Apply, and Batch all write `inputs.loras.__value__` array + `inputs.text` syntax for LoraManager nodes
|
||||
- **Stack enable/disable** — per-model checkbox and Toggle All checkbox; disabled models excluded from syntax/prompt; LoraManager apply preserves them as `active: false`
|
||||
- **Global strength adjuster** — `[−][step][+]` controls for Model and CLIP strength applied to all stack models at once
|
||||
- **model-and-prompt-from-metadata node support** — `CLIPTextEncodeEditPlus`, `ImageMetadataCheckpointLoader`, `ImageMetadataPromptLoader`, `ImageMetadataLoRALoader` added to workflow analysis
|
||||
- **Models thumbnail bug fixes** — preview endpoint now sends `Cache-Control: no-cache`; files under 100 bytes skipped; `.disabled` model files included in preview change lookup
|
||||
|
||||
### v0.3.23
|
||||
- **Bug fix: workflow batch 404** — `_runBatchGenerate()` workflow case was fetching `/api/wfm/workflows/{filename}` (non-existent route); corrected to `/api/wfm/workflows/raw?filename={filename}`
|
||||
- **Bug fix: rename double-submit** — `addEventListener("blur", commitRename)` was accumulating on the persistent `#wfm-modal-title-input` element each time the modal opened; subsequent renames fired the handler twice, sending two rename requests back-to-back (first succeeds, second returns 409 or 404); fixed by storing the listener reference on `titleInput._commitRename` and calling `removeEventListener` before re-registering
|
||||
|
||||
### v0.3.22
|
||||
- **Card view removed** — Workflow tab and Models tab no longer offer Card view; Thumbnail and Table remain; if `"card"` was previously stored in localStorage it falls back to Thumbnail automatically
|
||||
- **Batch type selector** — replaced the Checkpoint Batch toggle with per-type checkboxes on the Batch Queue column headers (Checkpoint / Lora / Prompt / Workflow); radio behavior ensures only one type is active at a time; the Batch panel below Generate repurposed as a status display showing the active type, amber progress bar, and Pause/Resume / Stop controls
|
||||
@@ -523,7 +694,8 @@ ComfyUI-Workflow-Studio/
|
||||
│ ├── wfm.py # Main class & route registration
|
||||
│ ├── config.py # Path configuration
|
||||
│ ├── nodes/
|
||||
│ │ └── prompt_text.py # WFS_PromptText custom node (positive/negative prompt)
|
||||
│ │ ├── prompt_text.py # WFS_PromptText custom node (positive/negative prompt)
|
||||
│ │ └── gallery_feeder_node.py # WFS_GalleryFeeder custom node (gallery group → IMAGE)
|
||||
│ ├── routes/
|
||||
│ │ ├── workflow_routes.py # Workflow CRUD & analysis API
|
||||
│ │ ├── nodes_routes.py # Nodes metadata & node sets API
|
||||
@@ -550,21 +722,25 @@ ComfyUI-Workflow-Studio/
|
||||
│ ├── app.js # App initialization & routing
|
||||
│ ├── workflow-tab.js # Workflow browser
|
||||
│ ├── generate-tab.js # Generation UI
|
||||
│ ├── feeder-tab.js # Feeder subtab (ImageFeeder node control + image library)
|
||||
│ ├── feeder-tab.js # Feeder subtab (Image Loop + Gallery modes)
|
||||
│ ├── gallery-tab.js # Gallery tab (image browser, groups, metadata)
|
||||
│ ├── tagger-tab.js # Tagger tab (WD Tagger, DeepDanbooru, Ollama VLM)
|
||||
│ ├── prompt-tab.js # AI assistant & presets
|
||||
│ ├── metadata-tab.js # Metadata extraction & display (PNG/WebP/JSON)
|
||||
│ ├── settings-tab.js # Settings panel
|
||||
│ ├── comfyui-client.js # ComfyUI WebSocket/API client
|
||||
│ ├── nodes-tab.js # Node browser & node sets
|
||||
│ ├── models-tab.js # Model browser & CivitAI integration
|
||||
│ ├── ai-tab.js # AI TOOL tab (Translation | TOOLS/VLM | Settings — Ollama / LM Studio)
|
||||
│ ├── ai-tab.js # AI TOOL tab (Translation | Chat | TOOLS/VLM | Settings)
|
||||
│ ├── comfyui-workflow.js # UI-to-API format conversion
|
||||
│ ├── comfyui-editor.js # Dynamic parameter editor
|
||||
│ ├── json-highlight.js # JSON syntax highlighting
|
||||
│ ├── util.js # Shared utilities (escapeHtml, readJsonStorage, getSettings)
|
||||
│ └── i18n.js # Internationalization
|
||||
├── web/comfyui/
|
||||
│ ├── top_menu_extension.js # ComfyUI menu bar integration
|
||||
│ └── node_sets_menu.js # Workflow Studio Library side panel
|
||||
│ ├── node_sets_menu.js # Workflow Studio Library side panel
|
||||
│ └── gallery_feeder_extension.js # WFS_GalleryFeeder canvas widgets (After Gen / Run / Stop)
|
||||
└── data/ # Fallback data dir (used when ComfyUI user/default/ is not found)
|
||||
```
|
||||
|
||||
@@ -580,6 +756,9 @@ MIT License
|
||||
|
||||
- [ComfyUI](https://github.com/comfyanonymous/ComfyUI) by comfyanonymous
|
||||
- [ComfyUI-Custom-Scripts](https://github.com/pythongosssss/ComfyUI-Custom-Scripts) by pythongosssss — Canvas snapshot and PNG workflow embedding implementation reference
|
||||
- [ComfyUI-Lora-Manager](https://github.com/willchil/ComfyUI-Lora-Manager) — Plugin architecture and UI pattern reference
|
||||
- [ComfyUI-Lora-Manager](https://github.com/willmiao/ComfyUI-Lora-Manager) — Plugin architecture and UI pattern reference
|
||||
- [Ollama](https://ollama.com/) for local LLM inference
|
||||
- [Eagle](https://eagle.cool/) for image management
|
||||
- [Pillow (PIL Fork)](https://python-pillow.org/) — server-side thumbnail generation (`data/thumb_cache/`)
|
||||
- [ComfyUI-Gallery](https://github.com/PanicTitan/ComfyUI-Gallery) by PanicTitan — thumbnail grid UX reference
|
||||
- [infinite-image-browsing](https://github.com/zanllp/sd-webui-infinite-image-browsing) by zanllp — thumbnail caching and index strategy reference
|
||||
|
||||
+4
-3
@@ -9,15 +9,16 @@ WorkflowStudio.add_routes()
|
||||
|
||||
# Register custom nodes (isolated loading)
|
||||
_NODE_MODULES = {
|
||||
"WFS_PromptText": (".py.nodes.prompt_text", "WFS_PromptText"),
|
||||
"WFS_PromptText": (".py.nodes.prompt_text", "WFS_PromptText", "Prompt Text (WFS)"),
|
||||
"WFS_GalleryFeeder": (".py.nodes.gallery_feeder_node", "WFS_GalleryFeeder", "Gallery Feeder (WFS)"),
|
||||
}
|
||||
|
||||
for _name, (_mod_path, _cls_name) in _NODE_MODULES.items():
|
||||
for _name, (_mod_path, _cls_name, _display_name) in _NODE_MODULES.items():
|
||||
try:
|
||||
import importlib
|
||||
_mod = importlib.import_module(_mod_path, package=__name__)
|
||||
NODE_CLASS_MAPPINGS[_name] = getattr(_mod, _cls_name)
|
||||
NODE_DISPLAY_NAME_MAPPINGS[_name] = "Prompt Text (WFS)"
|
||||
NODE_DISPLAY_NAME_MAPPINGS[_name] = _display_name
|
||||
except Exception as _e:
|
||||
print(f"[WARNING] Workflow Studio: Failed to load '{_name}': {_e}")
|
||||
|
||||
|
||||
Binary file not shown.
|
After Width: | Height: | Size: 193 KiB |
Binary file not shown.
|
After Width: | Height: | Size: 16 KiB |
Binary file not shown.
|
Before Width: | Height: | Size: 16 KiB After Width: | Height: | Size: 64 KiB |
Binary file not shown.
|
After Width: | Height: | Size: 48 KiB |
@@ -69,3 +69,8 @@ NODE_SETS_FILE = DATA_DIR / "node_sets.json"
|
||||
PROMPTS_FILE = DATA_DIR / "prompts.json"
|
||||
MODEL_METADATA_FILE = DATA_DIR / "model_metadata.json"
|
||||
WILDCARD_DIR = DATA_DIR / "wildcard"
|
||||
|
||||
# Tagger
|
||||
TAGGER_DB_FILE = DATA_DIR / "tagger.db"
|
||||
TAGGER_SETTINGS_FILE = DATA_DIR / "tagger_settings.json"
|
||||
TAGGER_MODELS_DIR = _COMFYUI_ROOT / "models" / "tagger"
|
||||
|
||||
@@ -0,0 +1,95 @@
|
||||
"""WFS_GalleryFeeder – Feeds images from a gallery group into a workflow."""
|
||||
import json
|
||||
import random
|
||||
import logging
|
||||
from pathlib import Path
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
# Feeder専用グループ名(gallery_metadata.json 内で予約される)
|
||||
FEEDER_GROUP = "__Feeder__"
|
||||
|
||||
|
||||
class WFS_GalleryFeeder:
|
||||
"""Gallery グループ内の画像をインデックス順に1枚ずつ出力するノード。"""
|
||||
|
||||
@classmethod
|
||||
def INPUT_TYPES(cls):
|
||||
return {
|
||||
"required": {
|
||||
"group_name": ("STRING", {"default": FEEDER_GROUP}),
|
||||
"index": ("INT", {"default": 0, "min": 0, "max": 99999}),
|
||||
"sort_mode": (["filename_asc", "filename_desc", "random"],),
|
||||
"seed": ("INT", {"default": 0, "min": 0, "max": 0xffffffffffffffff}),
|
||||
},
|
||||
}
|
||||
|
||||
RETURN_TYPES = ("IMAGE",)
|
||||
RETURN_NAMES = ("image",)
|
||||
FUNCTION = "execute"
|
||||
CATEGORY = "Workflow Studio"
|
||||
OUTPUT_NODE = False
|
||||
|
||||
@classmethod
|
||||
def IS_CHANGED(cls, **kwargs):
|
||||
# 毎回実行させる(インデックスが変わるため)
|
||||
return float("NaN")
|
||||
|
||||
def execute(self, group_name: str, index: int, sort_mode: str, seed: int):
|
||||
import torch
|
||||
import numpy as np
|
||||
from PIL import Image as PILImage
|
||||
|
||||
paths = self._get_sorted_paths(group_name, sort_mode, seed)
|
||||
if not paths:
|
||||
logger.warning("WFS_GalleryFeeder: group '%s' is empty or not found", group_name)
|
||||
return (torch.zeros(1, 64, 64, 3),)
|
||||
|
||||
img_path = paths[index % len(paths)]
|
||||
try:
|
||||
img = PILImage.open(img_path).convert("RGB")
|
||||
except Exception as e:
|
||||
logger.error("WFS_GalleryFeeder: failed to load '%s': %s", img_path, e)
|
||||
return (torch.zeros(1, 64, 64, 3),)
|
||||
|
||||
arr = np.array(img, dtype=np.float32) / 255.0
|
||||
tensor = torch.from_numpy(arr).unsqueeze(0)
|
||||
return (tensor,)
|
||||
|
||||
# ── 内部ヘルパー ──────────────────────────────────────────────
|
||||
|
||||
def _get_sorted_paths(self, group_name: str, sort_mode: str, seed: int) -> list[str]:
|
||||
metadata_file = self._find_metadata_file()
|
||||
if not metadata_file.exists():
|
||||
return []
|
||||
try:
|
||||
with open(metadata_file, "r", encoding="utf-8") as f:
|
||||
data = json.load(f)
|
||||
except Exception as e:
|
||||
logger.error("WFS_GalleryFeeder: metadata read error: %s", e)
|
||||
return []
|
||||
|
||||
paths = [
|
||||
key for key, meta in data.get("images", {}).items()
|
||||
if group_name in meta.get("groups", []) and Path(key).exists()
|
||||
]
|
||||
|
||||
if sort_mode == "filename_asc":
|
||||
paths.sort(key=lambda p: Path(p).name.lower())
|
||||
elif sort_mode == "filename_desc":
|
||||
paths.sort(key=lambda p: Path(p).name.lower(), reverse=True)
|
||||
elif sort_mode == "random":
|
||||
rng = random.Random(seed)
|
||||
rng.shuffle(paths)
|
||||
|
||||
return paths
|
||||
|
||||
@staticmethod
|
||||
def _find_metadata_file() -> Path:
|
||||
# py/nodes/ -> py/ -> plugin root -> ComfyUI/custom_nodes/ -> ComfyUI root
|
||||
plugin_root = Path(__file__).resolve().parent.parent.parent
|
||||
comfyui_root = plugin_root.parent.parent
|
||||
user_default = comfyui_root / "user" / "default"
|
||||
if user_default.is_dir():
|
||||
return user_default / "Workflow-Studio" / "gallery_metadata.json"
|
||||
return plugin_root / "data" / "gallery_metadata.json"
|
||||
@@ -15,21 +15,56 @@ logger = logging.getLogger(__name__)
|
||||
_service = GalleryService(DATA_DIR)
|
||||
|
||||
|
||||
def _init_allowed_root() -> None:
|
||||
"""起動時に保存済みの出力ディレクトリで _allowed_root を初期化する。
|
||||
Gallery タブを開く前に Feeder タブの Gallery モードが serve_image を呼んでも
|
||||
404 にならないようにするために必要。"""
|
||||
try:
|
||||
settings_file = DATA_DIR / "settings.json"
|
||||
if settings_file.exists():
|
||||
with open(settings_file, "r", encoding="utf-8") as f:
|
||||
settings = json.load(f)
|
||||
saved_root = settings.get("gallery_output_dir", "").strip()
|
||||
if saved_root and Path(saved_root).is_dir():
|
||||
_service.update_output_root(saved_root)
|
||||
return
|
||||
except Exception as e:
|
||||
logger.warning("GalleryRoutes: failed to load saved gallery root: %s", e)
|
||||
|
||||
# フォールバック: ComfyUI のデフォルト output フォルダ
|
||||
try:
|
||||
import folder_paths # type: ignore
|
||||
output_dir = folder_paths.get_output_directory()
|
||||
if output_dir and Path(output_dir).is_dir():
|
||||
_service.update_output_root(output_dir)
|
||||
except Exception as e:
|
||||
logger.warning("GalleryRoutes: failed to get ComfyUI output dir: %s", e)
|
||||
|
||||
|
||||
_init_allowed_root()
|
||||
|
||||
|
||||
def setup_routes(app: web.Application):
|
||||
app.router.add_get("/wfm/gallery/folders", list_folders)
|
||||
app.router.add_get("/wfm/gallery/images", list_images)
|
||||
app.router.add_get("/wfm/gallery/image/meta", get_image_meta)
|
||||
app.router.add_get("/wfm/gallery/image/workflow", get_image_workflow)
|
||||
app.router.add_get("/wfm/gallery/image/serve", serve_image)
|
||||
app.router.add_get("/wfm/gallery/image/thumb", serve_thumb)
|
||||
app.router.add_post("/wfm/gallery/image/meta", save_image_meta)
|
||||
app.router.add_post("/wfm/gallery/image/favorite", toggle_favorite)
|
||||
app.router.add_get("/wfm/gallery/groups", list_groups)
|
||||
app.router.add_post("/wfm/gallery/groups", create_group)
|
||||
app.router.add_put("/wfm/gallery/groups/{name}", rename_group)
|
||||
app.router.add_delete("/wfm/gallery/groups/{name}", delete_group)
|
||||
app.router.add_post("/wfm/gallery/groups/ensure", ensure_group)
|
||||
app.router.add_post("/wfm/gallery/groups/{name}/add", add_to_group)
|
||||
app.router.add_post("/wfm/gallery/groups/{name}/remove", remove_from_group)
|
||||
app.router.add_post("/wfm/gallery/groups/{name}/clear", clear_group_images)
|
||||
app.router.add_get("/wfm/gallery/groups/{name}/images", list_group_images)
|
||||
# バルク操作
|
||||
app.router.add_post("/wfm/gallery/bulk/favorite", bulk_favorite)
|
||||
app.router.add_post("/wfm/gallery/bulk/group", bulk_group)
|
||||
# フォルダ・ファイル操作
|
||||
app.router.add_post("/wfm/gallery/folder", create_folder_route)
|
||||
app.router.add_delete("/wfm/gallery/folder", delete_folder_route)
|
||||
@@ -127,6 +162,70 @@ async def serve_image(request: web.Request) -> web.Response:
|
||||
})
|
||||
|
||||
|
||||
async def serve_thumb(request: web.Request) -> web.Response:
|
||||
"""サムネイル配信。Pillowで縮小したJPEGをディスクキャッシュして返す。"""
|
||||
path = request.rel_url.query.get("path", "")
|
||||
if not path:
|
||||
return web.Response(status=400)
|
||||
try:
|
||||
width = int(request.rel_url.query.get("w", "256"))
|
||||
width = max(32, min(512, width))
|
||||
except ValueError:
|
||||
width = 256
|
||||
|
||||
thumb_path = _service.serve_thumbnail(path, width)
|
||||
if thumb_path is None:
|
||||
return web.Response(status=404)
|
||||
|
||||
ext = thumb_path.suffix.lower()
|
||||
if ext in (".jpg", ".jpeg"):
|
||||
content_type = "image/jpeg"
|
||||
elif ext == ".gif":
|
||||
content_type = "image/gif"
|
||||
else:
|
||||
content_type = mimetypes.guess_type(str(thumb_path))[0] or "image/jpeg"
|
||||
|
||||
return web.FileResponse(thumb_path, headers={
|
||||
"Content-Type": content_type,
|
||||
"Cache-Control": "max-age=86400",
|
||||
})
|
||||
|
||||
|
||||
# ──────────────────────────────────────────────────────────────
|
||||
# バルク操作
|
||||
# ──────────────────────────────────────────────────────────────
|
||||
|
||||
async def bulk_favorite(request: web.Request) -> web.Response:
|
||||
"""POST /wfm/gallery/bulk/favorite — 複数画像のお気に入りを一括設定"""
|
||||
try:
|
||||
body = await request.json()
|
||||
paths = body.get("paths", [])
|
||||
value = bool(body.get("value", True))
|
||||
if not paths:
|
||||
return web.json_response({"error": "paths required"}, status=400)
|
||||
result = _service.bulk_set_favorite(paths, value)
|
||||
return web.json_response(result)
|
||||
except Exception as e:
|
||||
return web.json_response({"error": str(e)}, status=500)
|
||||
|
||||
|
||||
async def bulk_group(request: web.Request) -> web.Response:
|
||||
"""POST /wfm/gallery/bulk/group — 複数画像のグループ追加/削除を一括処理"""
|
||||
try:
|
||||
body = await request.json()
|
||||
paths = body.get("paths", [])
|
||||
group = body.get("group", "").strip()
|
||||
action = body.get("action", "add") # "add" or "remove"
|
||||
if not paths or not group:
|
||||
return web.json_response({"error": "paths and group required"}, status=400)
|
||||
if action not in ("add", "remove"):
|
||||
return web.json_response({"error": "action must be 'add' or 'remove'"}, status=400)
|
||||
result = _service.bulk_group_op(paths, group, action)
|
||||
return web.json_response(result)
|
||||
except Exception as e:
|
||||
return web.json_response({"error": str(e)}, status=500)
|
||||
|
||||
|
||||
async def save_image_meta(request: web.Request) -> web.Response:
|
||||
try:
|
||||
body = await request.json()
|
||||
@@ -174,10 +273,15 @@ async def create_group(request: web.Request) -> web.Response:
|
||||
return web.json_response({"error": str(e)}, status=500)
|
||||
|
||||
|
||||
_RESERVED_GROUPS = {"__Feeder__"}
|
||||
|
||||
|
||||
async def rename_group(request: web.Request) -> web.Response:
|
||||
"""PUT /wfm/gallery/groups/{name} - グループ名変更"""
|
||||
try:
|
||||
old_name = request.match_info.get("name", "")
|
||||
if old_name in _RESERVED_GROUPS:
|
||||
return web.json_response({"error": f"Group '{old_name}' is reserved and cannot be renamed"}, status=403)
|
||||
body = await request.json()
|
||||
new_name = body.get("new_name", "").strip()
|
||||
if not old_name or not new_name:
|
||||
@@ -192,6 +296,8 @@ async def rename_group(request: web.Request) -> web.Response:
|
||||
|
||||
async def delete_group(request: web.Request) -> web.Response:
|
||||
name = request.match_info.get("name", "")
|
||||
if name in _RESERVED_GROUPS:
|
||||
return web.json_response({"error": f"Group '{name}' is reserved and cannot be deleted"}, status=403)
|
||||
ok = _service.delete_group(name)
|
||||
return web.json_response({"ok": ok})
|
||||
|
||||
@@ -224,6 +330,28 @@ async def list_group_images(request: web.Request) -> web.Response:
|
||||
return web.json_response({"images": images})
|
||||
|
||||
|
||||
async def clear_group_images(request: web.Request) -> web.Response:
|
||||
"""POST /wfm/gallery/groups/{name}/clear - グループ内の全画像を除外"""
|
||||
name = request.match_info.get("name", "")
|
||||
if not name:
|
||||
return web.json_response({"error": "name required"}, status=400)
|
||||
ok = _service.clear_group(name)
|
||||
return web.json_response({"ok": ok})
|
||||
|
||||
|
||||
async def ensure_group(request: web.Request) -> web.Response:
|
||||
"""POST /wfm/gallery/groups/ensure - グループが存在しない場合のみ作成"""
|
||||
try:
|
||||
body = await request.json()
|
||||
name = body.get("name", "").strip()
|
||||
if not name:
|
||||
return web.json_response({"error": "name required"}, status=400)
|
||||
_service.ensure_group(name)
|
||||
return web.json_response({"ok": True})
|
||||
except Exception as e:
|
||||
return web.json_response({"error": str(e)}, status=500)
|
||||
|
||||
|
||||
# ──────────────────────────────────────────────────────────────
|
||||
# フォルダ・ファイル操作
|
||||
# ──────────────────────────────────────────────────────────────
|
||||
|
||||
@@ -31,6 +31,8 @@ def setup_routes(app: web.Application):
|
||||
app.router.add_post("/api/wfm/models/toggle", handle_toggle_model)
|
||||
app.router.add_post("/api/wfm/models/group-toggle", handle_toggle_group)
|
||||
app.router.add_post("/api/wfm/models/delete", handle_delete_models)
|
||||
app.router.add_get("/api/wfm/models/subdirs", handle_get_subdirs)
|
||||
app.router.add_post("/api/wfm/models/move", handle_move_models)
|
||||
|
||||
|
||||
# ── Model Metadata ─────────────────────────────────────────
|
||||
@@ -344,7 +346,7 @@ async def handle_get_preview(request: web.Request) -> web.Response:
|
||||
return web.FileResponse(
|
||||
preview_path,
|
||||
headers={"Content-Type": content_type or "image/png",
|
||||
"Cache-Control": "public, max-age=3600"},
|
||||
"Cache-Control": "no-cache"},
|
||||
)
|
||||
except Exception as e:
|
||||
logger.error("Error serving model preview: %s", e)
|
||||
@@ -383,7 +385,7 @@ async def handle_change_preview(request: web.Request) -> web.Response:
|
||||
if image_data is None:
|
||||
return web.json_response({"error": "file required"}, status=400)
|
||||
|
||||
# Resolve model file path
|
||||
# Resolve model file path (also check .disabled variants)
|
||||
from ..services.models_service import _get_model_dirs
|
||||
dirs = _get_model_dirs(model_type)
|
||||
model_path = None
|
||||
@@ -392,6 +394,11 @@ async def handle_change_preview(request: web.Request) -> web.Response:
|
||||
if candidate.is_file():
|
||||
model_path = candidate
|
||||
break
|
||||
# disabled モデルも対象にする
|
||||
disabled_candidate = d / (model_name + ".disabled")
|
||||
if disabled_candidate.is_file():
|
||||
model_path = disabled_candidate
|
||||
break
|
||||
|
||||
if not model_path:
|
||||
return web.json_response({"error": "Model file not found"}, status=404)
|
||||
@@ -566,3 +573,46 @@ async def handle_delete_models(request: web.Request) -> web.Response:
|
||||
except Exception as e:
|
||||
logger.error("Error in delete_models: %s", e)
|
||||
return web.json_response({"error": str(e)}, status=500)
|
||||
|
||||
|
||||
_VALID_MODEL_TYPES = frozenset(
|
||||
["checkpoint", "lora", "vae", "controlnet", "unet", "textencoder", "hypernetwork", "embedding"]
|
||||
)
|
||||
|
||||
|
||||
async def handle_get_subdirs(request: web.Request) -> web.Response:
|
||||
"""GET /api/wfm/models/subdirs?type=checkpoint
|
||||
Returns list of root-level subdirectory names for the given model type.
|
||||
"""
|
||||
try:
|
||||
model_type = request.rel_url.query.get("type", "")
|
||||
if model_type not in _VALID_MODEL_TYPES:
|
||||
return web.json_response({"error": "Invalid model type"}, status=400)
|
||||
result = await asyncio.to_thread(_service.get_subdirs, model_type)
|
||||
return web.json_response(result)
|
||||
except Exception as e:
|
||||
return web.json_response({"error": str(e)}, status=500)
|
||||
|
||||
|
||||
async def handle_move_models(request: web.Request) -> web.Response:
|
||||
"""POST /api/wfm/models/move
|
||||
|
||||
Body: { "model_type": "checkpoint", "model_names": [...], "dest": "sdxl" }
|
||||
dest: "" = root, or a root-level subfolder name (no path separators, no "..").
|
||||
"""
|
||||
try:
|
||||
body = await request.json()
|
||||
model_type = body.get("model_type", "")
|
||||
model_names = body.get("model_names", [])
|
||||
dest_subdir = body.get("dest", "")
|
||||
if model_type not in _VALID_MODEL_TYPES:
|
||||
return web.json_response({"error": "Invalid model type"}, status=400)
|
||||
if not isinstance(model_names, list) or not model_names:
|
||||
return web.json_response({"error": "model_names must be a non-empty list"}, status=400)
|
||||
if not isinstance(dest_subdir, str):
|
||||
return web.json_response({"error": "dest must be a string"}, status=400)
|
||||
result = await asyncio.to_thread(_service.move_models, model_type, model_names, dest_subdir)
|
||||
return web.json_response(result)
|
||||
except Exception as e:
|
||||
logger.error("Error in move_models: %s", e)
|
||||
return web.json_response({"error": str(e)}, status=500)
|
||||
|
||||
@@ -0,0 +1,214 @@
|
||||
"""Tagger API routes."""
|
||||
|
||||
import asyncio
|
||||
import logging
|
||||
|
||||
from aiohttp import web
|
||||
|
||||
from ..config import TAGGER_DB_FILE, TAGGER_MODELS_DIR, TAGGER_SETTINGS_FILE
|
||||
from ..services.tagger_db_service import TaggerDbService
|
||||
from ..services.tagger_service import TaggerService
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
_svc = TaggerService(TAGGER_MODELS_DIR, TAGGER_SETTINGS_FILE)
|
||||
_db = TaggerDbService(TAGGER_DB_FILE)
|
||||
|
||||
|
||||
def setup_routes(app: web.Application):
|
||||
app.router.add_get("/wfm/tagger/models", handle_models)
|
||||
app.router.add_post("/wfm/tagger/predict", handle_predict)
|
||||
app.router.add_get("/wfm/tagger/ollama/models", handle_ollama_models)
|
||||
app.router.add_post("/wfm/tagger/ollama/predict", handle_ollama_predict)
|
||||
app.router.add_post("/wfm/tagger/batch/start", handle_batch_start)
|
||||
app.router.add_get("/wfm/tagger/batch/status", handle_batch_status)
|
||||
app.router.add_post("/wfm/tagger/batch/stop", handle_batch_stop)
|
||||
app.router.add_get("/wfm/tagger/db/list", handle_db_list)
|
||||
app.router.add_get("/wfm/tagger/db/search", handle_db_search)
|
||||
app.router.add_put("/wfm/tagger/db/{id}", handle_db_update)
|
||||
app.router.add_delete("/wfm/tagger/db/{id}", handle_db_delete)
|
||||
app.router.add_get("/wfm/tagger/db/export", handle_db_export)
|
||||
app.router.add_post("/wfm/tagger/db/save", handle_db_save)
|
||||
app.router.add_post("/wfm/tagger/write_meta", handle_write_meta)
|
||||
app.router.add_get("/wfm/tagger/settings", handle_settings_get)
|
||||
app.router.add_post("/wfm/tagger/settings", handle_settings_save)
|
||||
|
||||
|
||||
async def handle_models(request: web.Request) -> web.Response:
|
||||
try:
|
||||
models = await asyncio.to_thread(_svc.list_models)
|
||||
return web.json_response({"models": models})
|
||||
except Exception as e:
|
||||
logger.error("handle_models: %s", e)
|
||||
return web.json_response({"error": str(e)}, status=500)
|
||||
|
||||
|
||||
async def handle_predict(request: web.Request) -> web.Response:
|
||||
try:
|
||||
body = await request.json()
|
||||
b64 = body.get("image_b64", "")
|
||||
model = body.get("model", "")
|
||||
if not b64 or not model:
|
||||
return web.json_response({"error": "image_b64 and model required"}, status=400)
|
||||
result = await asyncio.to_thread(
|
||||
_svc.predict, b64, model,
|
||||
float(body.get("threshold", 0.35)),
|
||||
float(body.get("char_threshold", 0.85)),
|
||||
)
|
||||
return web.json_response(result)
|
||||
except Exception as e:
|
||||
logger.error("handle_predict: %s", e)
|
||||
return web.json_response({"error": str(e)}, status=500)
|
||||
|
||||
|
||||
async def handle_ollama_models(request: web.Request) -> web.Response:
|
||||
api_url = request.rel_url.query.get("api_url", "http://127.0.0.1:11434")
|
||||
try:
|
||||
models = await asyncio.to_thread(_svc.ollama_models, api_url)
|
||||
return web.json_response({"models": models})
|
||||
except Exception as e:
|
||||
return web.json_response({"error": str(e)}, status=500)
|
||||
|
||||
|
||||
async def handle_ollama_predict(request: web.Request) -> web.Response:
|
||||
try:
|
||||
body = await request.json()
|
||||
result = await asyncio.to_thread(
|
||||
_svc.ollama_predict,
|
||||
body.get("image_b64", ""),
|
||||
body.get("api_url", "http://127.0.0.1:11434"),
|
||||
body.get("model", ""),
|
||||
body.get("prompt", ""),
|
||||
int(body.get("max_tags", 40)),
|
||||
)
|
||||
return web.json_response(result)
|
||||
except Exception as e:
|
||||
return web.json_response({"error": str(e)}, status=500)
|
||||
|
||||
|
||||
async def handle_batch_start(request: web.Request) -> web.Response:
|
||||
try:
|
||||
body = await request.json()
|
||||
result = await asyncio.to_thread(
|
||||
_svc.batch_start,
|
||||
body.get("folder", ""),
|
||||
body.get("model", ""),
|
||||
float(body.get("threshold", 0.35)),
|
||||
float(body.get("char_threshold", 0.85)),
|
||||
bool(body.get("use_ollama", False)),
|
||||
body.get("ollama_api", "http://127.0.0.1:11434"),
|
||||
body.get("ollama_model", ""),
|
||||
body.get("ollama_prompt", ""),
|
||||
int(body.get("ollama_max_tags", 40)),
|
||||
bool(body.get("save_db", True)),
|
||||
bool(body.get("write_file", False)),
|
||||
bool(body.get("write_txt", False)),
|
||||
_db,
|
||||
)
|
||||
return web.json_response(result)
|
||||
except Exception as e:
|
||||
return web.json_response({"error": str(e)}, status=500)
|
||||
|
||||
|
||||
async def handle_batch_status(request: web.Request) -> web.Response:
|
||||
return web.json_response(_svc.batch_status())
|
||||
|
||||
|
||||
async def handle_batch_stop(request: web.Request) -> web.Response:
|
||||
_svc.batch_stop()
|
||||
return web.json_response({"ok": True})
|
||||
|
||||
|
||||
async def handle_db_list(request: web.Request) -> web.Response:
|
||||
try:
|
||||
limit = int(request.rel_url.query.get("limit", 100))
|
||||
offset = int(request.rel_url.query.get("offset", 0))
|
||||
rows = await asyncio.to_thread(_db.list, limit, offset)
|
||||
total = await asyncio.to_thread(_db.total)
|
||||
return web.json_response({"rows": rows, "total": total})
|
||||
except Exception as e:
|
||||
return web.json_response({"error": str(e)}, status=500)
|
||||
|
||||
|
||||
async def handle_db_search(request: web.Request) -> web.Response:
|
||||
try:
|
||||
q = request.rel_url.query.get("q", "")
|
||||
rows = await asyncio.to_thread(_db.search, q)
|
||||
return web.json_response({"rows": rows})
|
||||
except Exception as e:
|
||||
return web.json_response({"error": str(e)}, status=500)
|
||||
|
||||
|
||||
async def handle_db_update(request: web.Request) -> web.Response:
|
||||
try:
|
||||
row_id = int(request.match_info["id"])
|
||||
body = await request.json()
|
||||
await asyncio.to_thread(
|
||||
_db.update, row_id,
|
||||
body.get("interrogator_tags", ""),
|
||||
body.get("vlm_tags", ""),
|
||||
)
|
||||
return web.json_response({"ok": True})
|
||||
except Exception as e:
|
||||
return web.json_response({"error": str(e)}, status=500)
|
||||
|
||||
|
||||
async def handle_db_delete(request: web.Request) -> web.Response:
|
||||
try:
|
||||
row_id = int(request.match_info["id"])
|
||||
await asyncio.to_thread(_db.delete, row_id)
|
||||
return web.json_response({"ok": True})
|
||||
except Exception as e:
|
||||
return web.json_response({"error": str(e)}, status=500)
|
||||
|
||||
|
||||
async def handle_db_export(request: web.Request) -> web.Response:
|
||||
try:
|
||||
csv_data = await asyncio.to_thread(_db.export_csv)
|
||||
return web.Response(
|
||||
body=csv_data.encode("utf-8"),
|
||||
content_type="text/csv",
|
||||
headers={"Content-Disposition": "attachment; filename=tagger_tags.csv"},
|
||||
)
|
||||
except Exception as e:
|
||||
return web.json_response({"error": str(e)}, status=500)
|
||||
|
||||
|
||||
async def handle_db_save(request: web.Request) -> web.Response:
|
||||
try:
|
||||
body = await request.json()
|
||||
row_id = await asyncio.to_thread(
|
||||
_db.save,
|
||||
body.get("filename", ""),
|
||||
body.get("interrogator_tags", ""),
|
||||
body.get("vlm_tags", ""),
|
||||
)
|
||||
return web.json_response({"ok": True, "id": row_id})
|
||||
except Exception as e:
|
||||
return web.json_response({"error": str(e)}, status=500)
|
||||
|
||||
|
||||
async def handle_write_meta(request: web.Request) -> web.Response:
|
||||
try:
|
||||
body = await request.json()
|
||||
result = await asyncio.to_thread(
|
||||
_svc.write_meta_to_file,
|
||||
body.get("path", ""),
|
||||
body.get("tags", ""),
|
||||
)
|
||||
return web.json_response(result)
|
||||
except Exception as e:
|
||||
return web.json_response({"error": str(e)}, status=500)
|
||||
|
||||
|
||||
async def handle_settings_get(request: web.Request) -> web.Response:
|
||||
return web.json_response(_svc.load_settings())
|
||||
|
||||
|
||||
async def handle_settings_save(request: web.Request) -> web.Response:
|
||||
try:
|
||||
body = await request.json()
|
||||
await asyncio.to_thread(_svc.save_settings, body)
|
||||
return web.json_response({"ok": True})
|
||||
except Exception as e:
|
||||
return web.json_response({"error": str(e)}, status=500)
|
||||
@@ -124,6 +124,19 @@ class GalleryMetadataStore:
|
||||
if group_name in meta.get("groups", [])
|
||||
}
|
||||
|
||||
def clear_group(self, group_name: str) -> bool:
|
||||
"""グループ内の全画像を除外する(グループ自体は残す)"""
|
||||
for meta in self._data["images"].values():
|
||||
if group_name in meta.get("groups", []):
|
||||
meta["groups"] = [g for g in meta["groups"] if g != group_name]
|
||||
return self._save_to_disk()
|
||||
|
||||
def ensure_group(self, name: str) -> bool:
|
||||
"""グループが存在しない場合のみ作成する"""
|
||||
if any(g["name"] == name for g in self._data.get("groups", [])):
|
||||
return True
|
||||
return self.create_group(name)
|
||||
|
||||
def delete(self, image_path: str) -> bool:
|
||||
"""画像のメタデータエントリを削除する"""
|
||||
key = self._normalize_path(image_path)
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
"""
|
||||
Gallery Service - outputフォルダの画像管理、メタデータ閲覧
|
||||
"""
|
||||
import hashlib
|
||||
import json
|
||||
import logging
|
||||
import mimetypes
|
||||
@@ -26,7 +27,7 @@ _PNG_CHUNK_MAX = 32 * 1024 * 1024
|
||||
_JPEG_READ_MAX = 64 * 1024 * 1024
|
||||
|
||||
# フォルダキャッシュのTTL秒(フォルダmtimeが同じでも念のため)
|
||||
_CACHE_TTL = 30.0
|
||||
_CACHE_TTL = 60.0
|
||||
|
||||
|
||||
class _FolderCache:
|
||||
@@ -81,8 +82,7 @@ class GalleryService:
|
||||
def _check_path_allowed(self, path: Path) -> bool:
|
||||
"""パスが許可ルート配下かチェック(パストラバーサル防止)"""
|
||||
if self._allowed_root is None:
|
||||
resolved = path.resolve()
|
||||
return resolved == path.resolve()
|
||||
return False
|
||||
try:
|
||||
path.resolve().relative_to(self._allowed_root)
|
||||
return True
|
||||
@@ -218,13 +218,14 @@ class GalleryService:
|
||||
"groups": meta.get("groups", []),
|
||||
}
|
||||
|
||||
# 検索フィルタ
|
||||
# 検索フィルタ(ファイル名・メモ・タグ・キャッシュ済みプロンプト)
|
||||
if search:
|
||||
s = search.lower()
|
||||
if not (
|
||||
s in name.lower()
|
||||
or s in item["memo"].lower()
|
||||
or any(s in t.lower() for t in tags)
|
||||
or s in meta.get("prompt_cache", "").lower()
|
||||
):
|
||||
continue
|
||||
|
||||
@@ -263,6 +264,14 @@ class GalleryService:
|
||||
|
||||
saved = self.metadata_store.get(str(path))
|
||||
|
||||
# workflow キーを除く文字列フィールドをプロンプトキャッシュとして保存(検索用)
|
||||
prompt_text = " ".join(
|
||||
str(v) for k, v in embedded.items()
|
||||
if k != "workflow" and isinstance(v, str) and len(v) < 50_000
|
||||
).strip()
|
||||
if prompt_text and prompt_text != saved.get("prompt_cache", ""):
|
||||
self.metadata_store.save(str(path), {"prompt_cache": prompt_text})
|
||||
|
||||
stat = path.stat()
|
||||
return {
|
||||
"filename": path.name,
|
||||
@@ -385,14 +394,42 @@ class GalleryService:
|
||||
# ──────────────────────────────────────────────────────────────
|
||||
|
||||
def save_image_meta(self, image_path: str, data: dict) -> bool:
|
||||
if not self._check_path_allowed(Path(image_path).resolve()):
|
||||
return False
|
||||
return self.metadata_store.save(image_path, data)
|
||||
|
||||
def toggle_favorite(self, image_path: str) -> bool:
|
||||
if not self._check_path_allowed(Path(image_path).resolve()):
|
||||
return False
|
||||
meta = self.metadata_store.get(image_path)
|
||||
new_val = not meta.get("favorite", False)
|
||||
self.metadata_store.save(image_path, {"favorite": new_val})
|
||||
return new_val
|
||||
|
||||
def bulk_set_favorite(self, paths: list[str], value: bool) -> dict:
|
||||
"""複数画像のお気に入りを一括設定する"""
|
||||
ok = fail = 0
|
||||
for p in paths:
|
||||
if not self._check_path_allowed(Path(p).resolve()):
|
||||
fail += 1
|
||||
continue
|
||||
if self.metadata_store.save(p, {"favorite": value}):
|
||||
ok += 1
|
||||
else:
|
||||
fail += 1
|
||||
return {"ok": ok, "fail": fail}
|
||||
|
||||
def bulk_group_op(self, paths: list[str], group_name: str, action: str = "add") -> dict:
|
||||
"""複数画像のグループ追加 / 削除を一括処理する。action は "add" または "remove"。"""
|
||||
ok = fail = 0
|
||||
for p in paths:
|
||||
success = self.add_to_group(p, group_name) if action == "add" else self.remove_from_group(p, group_name)
|
||||
if success:
|
||||
ok += 1
|
||||
else:
|
||||
fail += 1
|
||||
return {"ok": ok, "fail": fail}
|
||||
|
||||
# ──────────────────────────────────────────────────────────────
|
||||
# グループ管理
|
||||
# ──────────────────────────────────────────────────────────────
|
||||
@@ -410,6 +447,8 @@ class GalleryService:
|
||||
return self.metadata_store.delete_group(name)
|
||||
|
||||
def add_to_group(self, image_path: str, group_name: str) -> bool:
|
||||
if not self._check_path_allowed(Path(image_path).resolve()):
|
||||
return False
|
||||
meta = self.metadata_store.get(image_path)
|
||||
groups = meta.get("groups", [])
|
||||
if group_name not in groups:
|
||||
@@ -418,6 +457,8 @@ class GalleryService:
|
||||
return True
|
||||
|
||||
def remove_from_group(self, image_path: str, group_name: str) -> bool:
|
||||
if not self._check_path_allowed(Path(image_path).resolve()):
|
||||
return False
|
||||
meta = self.metadata_store.get(image_path)
|
||||
groups = [g for g in meta.get("groups", []) if g != group_name]
|
||||
return self.metadata_store.save(image_path, {"groups": groups})
|
||||
@@ -425,6 +466,12 @@ class GalleryService:
|
||||
def list_images_in_group(self, group_name: str) -> list[str]:
|
||||
return self.metadata_store.list_images_in_group(group_name)
|
||||
|
||||
def clear_group(self, group_name: str) -> bool:
|
||||
return self.metadata_store.clear_group(group_name)
|
||||
|
||||
def ensure_group(self, name: str) -> bool:
|
||||
return self.metadata_store.ensure_group(name)
|
||||
|
||||
# ──────────────────────────────────────────────────────────────
|
||||
# 画像配信
|
||||
# ──────────────────────────────────────────────────────────────
|
||||
@@ -540,3 +587,46 @@ class GalleryService:
|
||||
logger.warning("serve_image: path not allowed: %s", p)
|
||||
return None
|
||||
return p
|
||||
|
||||
def serve_thumbnail(self, image_path: str, width: int = 256) -> Path | None:
|
||||
"""縮小サムネイルのPathを返す。
|
||||
ディスクキャッシュがあればそれを返し、なければPillowで生成して保存する。
|
||||
GIFはアニメーション保持のため元ファイルをそのまま返す。
|
||||
Pillowが使えない場合は元ファイルにフォールバック。
|
||||
"""
|
||||
p = Path(image_path).resolve()
|
||||
if not p.is_file():
|
||||
return None
|
||||
if p.suffix.lower() not in IMAGE_EXTENSIONS:
|
||||
return None
|
||||
if not self._check_path_allowed(p):
|
||||
logger.warning("serve_thumbnail: path not allowed: %s", p)
|
||||
return None
|
||||
|
||||
# GIF はアニメーション保持のためそのまま返す
|
||||
if p.suffix.lower() == ".gif":
|
||||
return p
|
||||
|
||||
try:
|
||||
mtime = int(p.stat().st_mtime * 1000)
|
||||
except OSError:
|
||||
return None
|
||||
|
||||
cache_key = hashlib.md5(f"{p}:{mtime}:{width}".encode()).hexdigest()
|
||||
cache_dir = self.data_dir / "thumb_cache"
|
||||
cache_dir.mkdir(exist_ok=True)
|
||||
thumb_path = cache_dir / f"{cache_key}.jpg"
|
||||
|
||||
if thumb_path.exists():
|
||||
return thumb_path
|
||||
|
||||
try:
|
||||
from PIL import Image
|
||||
with Image.open(p) as img:
|
||||
img = img.convert("RGB")
|
||||
img.thumbnail((width, width), Image.LANCZOS)
|
||||
img.save(thumb_path, "JPEG", quality=85, optimize=True)
|
||||
return thumb_path
|
||||
except Exception as e:
|
||||
logger.warning("serve_thumbnail: failed for %s: %s", p, e)
|
||||
return p # フォールバック: 元ファイル
|
||||
|
||||
@@ -2,6 +2,7 @@
|
||||
|
||||
import json
|
||||
import logging
|
||||
import shutil
|
||||
from datetime import datetime, timezone
|
||||
from pathlib import Path
|
||||
|
||||
@@ -17,7 +18,7 @@ _PREVIEW_EXTENSIONS = [".preview.png", ".preview.jpg", ".preview.jpeg", ".previe
|
||||
_SIDECAR_EXTENSIONS = [
|
||||
".preview.png", ".preview.jpg", ".preview.jpeg", ".preview.webp",
|
||||
".png", ".jpg", ".jpeg", ".webp",
|
||||
".json", ".civitai.info", ".info",
|
||||
".metadata.json", ".cm-info.json", ".json", ".civitai.info", ".info",
|
||||
]
|
||||
|
||||
_DISABLED_SUFFIX = ".disabled"
|
||||
@@ -219,7 +220,7 @@ class ModelsService:
|
||||
|
||||
for ext in _PREVIEW_EXTENSIONS:
|
||||
preview = parent / (stem + ext)
|
||||
if preview.is_file():
|
||||
if preview.is_file() and preview.stat().st_size >= 100:
|
||||
logger.debug("Preview found: %s", preview)
|
||||
return preview
|
||||
|
||||
@@ -274,3 +275,126 @@ class ModelsService:
|
||||
self._save_metadata(data)
|
||||
|
||||
return {"deleted": deleted}
|
||||
|
||||
def get_subdirs(self, model_type):
|
||||
"""Return sorted list of root-level subdirectory names for a model type."""
|
||||
dirs = _get_model_dirs(model_type)
|
||||
subdirs = set()
|
||||
for d in dirs:
|
||||
if not d.is_dir():
|
||||
continue
|
||||
for item in d.iterdir():
|
||||
if item.is_dir():
|
||||
subdirs.add(item.name)
|
||||
return sorted(subdirs)
|
||||
|
||||
def move_models(self, model_type, model_names, dest_subdir):
|
||||
"""Move model files + sidecar files to dest_subdir (root-level subfolder name).
|
||||
|
||||
dest_subdir: "" = model root, "sdxl" = <root>/sdxl/
|
||||
Creates the destination directory if it does not exist.
|
||||
Updates metadata keys to reflect new paths.
|
||||
Returns {"moved": [{"from": ..., "to": ...}], "errors": [...]}
|
||||
"""
|
||||
# Validate dest_subdir: must be a plain folder name (no separators, no "..", not absolute)
|
||||
if dest_subdir:
|
||||
if ".." in dest_subdir:
|
||||
return {"moved": [], "errors": [{"model": "*", "error": "Invalid destination: '..' not allowed"}]}
|
||||
if "/" in dest_subdir or "\\" in dest_subdir:
|
||||
return {"moved": [], "errors": [{"model": "*", "error": "Invalid destination: must be a single folder name"}]}
|
||||
if Path(dest_subdir).is_absolute():
|
||||
return {"moved": [], "errors": [{"model": "*", "error": "Invalid destination: absolute paths not allowed"}]}
|
||||
|
||||
moved = []
|
||||
errors = []
|
||||
model_dirs = _get_model_dirs(model_type)
|
||||
|
||||
meta_data = self._load_metadata()
|
||||
meta_changed = False
|
||||
|
||||
for model_name in model_names:
|
||||
if ".." in model_name:
|
||||
errors.append({"model": model_name, "error": "Invalid model name"})
|
||||
continue
|
||||
|
||||
path, _is_enabled = self.find_model_file(model_type, model_name)
|
||||
if path is None:
|
||||
errors.append({"model": model_name, "error": f"Model not found: {model_name}"})
|
||||
continue
|
||||
|
||||
try:
|
||||
# Determine which root dir this model lives in
|
||||
root_dir = None
|
||||
for d in model_dirs:
|
||||
try:
|
||||
path.relative_to(d)
|
||||
root_dir = d
|
||||
break
|
||||
except ValueError:
|
||||
pass
|
||||
if root_dir is None:
|
||||
errors.append({"model": model_name, "error": "Cannot determine root directory"})
|
||||
continue
|
||||
|
||||
# Destination directory — verify it stays within root_dir after resolution
|
||||
dest_dir = root_dir / dest_subdir if dest_subdir else root_dir
|
||||
try:
|
||||
dest_dir.resolve().relative_to(root_dir.resolve())
|
||||
except ValueError:
|
||||
errors.append({"model": model_name, "error": "Destination is outside model root"})
|
||||
continue
|
||||
dest_dir.mkdir(parents=True, exist_ok=True)
|
||||
|
||||
# Original filename without .disabled suffix
|
||||
orig_name = path.name
|
||||
if orig_name.endswith(_DISABLED_SUFFIX):
|
||||
orig_name = orig_name[: -len(_DISABLED_SUFFIX)]
|
||||
stem = Path(orig_name).stem
|
||||
|
||||
new_path = dest_dir / path.name
|
||||
if new_path.resolve() == path.resolve():
|
||||
errors.append({"model": model_name, "error": "Already in destination"})
|
||||
continue
|
||||
|
||||
# Refuse to overwrite an existing file
|
||||
if new_path.exists():
|
||||
errors.append({"model": model_name, "error": f"Destination already exists: {path.name}"})
|
||||
continue
|
||||
|
||||
# Move the model file
|
||||
shutil.move(str(path), str(new_path))
|
||||
logger.info("Moved model: %s → %s", path, new_path)
|
||||
|
||||
# Move all sidecar files (skip if destination already exists)
|
||||
for ext in _SIDECAR_EXTENSIONS:
|
||||
sidecar = path.parent / (stem + ext)
|
||||
if sidecar.is_file():
|
||||
sidecar_dest = dest_dir / (stem + ext)
|
||||
if sidecar_dest.exists():
|
||||
logger.warning("Sidecar destination exists, skipping: %s", sidecar_dest)
|
||||
continue
|
||||
try:
|
||||
shutil.move(str(sidecar), str(sidecar_dest))
|
||||
except Exception as se:
|
||||
logger.warning("Could not move sidecar %s: %s", sidecar, se)
|
||||
|
||||
# Compute new logical model name (relative to root, forward slashes)
|
||||
new_rel = str(new_path.relative_to(root_dir)).replace("\\", "/")
|
||||
if new_rel.endswith(_DISABLED_SUFFIX):
|
||||
new_rel = new_rel[: -len(_DISABLED_SUFFIX)]
|
||||
|
||||
# Update metadata key
|
||||
if model_name in meta_data:
|
||||
meta_data[new_rel] = meta_data.pop(model_name)
|
||||
meta_changed = True
|
||||
|
||||
moved.append({"from": model_name, "to": new_rel})
|
||||
|
||||
except Exception as e:
|
||||
logger.error("Error moving model %s: %s", model_name, e)
|
||||
errors.append({"model": model_name, "error": str(e)})
|
||||
|
||||
if meta_changed:
|
||||
self._save_metadata(meta_data)
|
||||
|
||||
return {"moved": moved, "errors": errors}
|
||||
|
||||
@@ -0,0 +1,108 @@
|
||||
"""Tagger タグ DB サービス(SQLite)。"""
|
||||
|
||||
import csv
|
||||
import io
|
||||
import logging
|
||||
import sqlite3
|
||||
from pathlib import Path
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
class TaggerDbService:
|
||||
def __init__(self, db_file: Path):
|
||||
self.db_file = db_file
|
||||
self._init_db()
|
||||
|
||||
def _conn(self) -> sqlite3.Connection:
|
||||
return sqlite3.connect(str(self.db_file))
|
||||
|
||||
def _init_db(self):
|
||||
self.db_file.parent.mkdir(parents=True, exist_ok=True)
|
||||
with self._conn() as conn:
|
||||
conn.execute("""
|
||||
CREATE TABLE IF NOT EXISTS images (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
filename TEXT,
|
||||
interrogator_tags TEXT,
|
||||
vlm_tags TEXT,
|
||||
all_tags TEXT,
|
||||
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
|
||||
)
|
||||
""")
|
||||
for sql in [
|
||||
"CREATE INDEX IF NOT EXISTS idx_all_tags ON images(all_tags)",
|
||||
"CREATE INDEX IF NOT EXISTS idx_filename ON images(filename)",
|
||||
"CREATE INDEX IF NOT EXISTS idx_created_at ON images(created_at DESC)",
|
||||
]:
|
||||
conn.execute(sql)
|
||||
conn.commit()
|
||||
|
||||
def save(self, filename: str, interrogator_tags: str, vlm_tags: str) -> int:
|
||||
all_tags = ", ".join(filter(None, [interrogator_tags, vlm_tags]))
|
||||
with self._conn() as conn:
|
||||
cur = conn.execute(
|
||||
"INSERT INTO images (filename, interrogator_tags, vlm_tags, all_tags) VALUES (?, ?, ?, ?)",
|
||||
(filename, interrogator_tags, vlm_tags, all_tags),
|
||||
)
|
||||
conn.commit()
|
||||
return cur.lastrowid
|
||||
|
||||
def list(self, limit: int = 100, offset: int = 0) -> list:
|
||||
with self._conn() as conn:
|
||||
rows = conn.execute(
|
||||
"SELECT id, filename, interrogator_tags, vlm_tags, all_tags, created_at "
|
||||
"FROM images ORDER BY id DESC LIMIT ? OFFSET ?",
|
||||
(limit, offset),
|
||||
).fetchall()
|
||||
return [self._row(r) for r in rows]
|
||||
|
||||
def total(self) -> int:
|
||||
with self._conn() as conn:
|
||||
return conn.execute("SELECT COUNT(*) FROM images").fetchone()[0]
|
||||
|
||||
def search(self, q: str) -> list:
|
||||
pattern = f"%{q}%"
|
||||
with self._conn() as conn:
|
||||
rows = conn.execute(
|
||||
"SELECT id, filename, interrogator_tags, vlm_tags, all_tags, created_at "
|
||||
"FROM images WHERE all_tags LIKE ? OR filename LIKE ? ORDER BY id DESC LIMIT 200",
|
||||
(pattern, pattern),
|
||||
).fetchall()
|
||||
return [self._row(r) for r in rows]
|
||||
|
||||
def update(self, row_id: int, interrogator_tags: str, vlm_tags: str):
|
||||
all_tags = ", ".join(filter(None, [interrogator_tags, vlm_tags]))
|
||||
with self._conn() as conn:
|
||||
conn.execute(
|
||||
"UPDATE images SET interrogator_tags=?, vlm_tags=?, all_tags=? WHERE id=?",
|
||||
(interrogator_tags, vlm_tags, all_tags, row_id),
|
||||
)
|
||||
conn.commit()
|
||||
|
||||
def delete(self, row_id: int):
|
||||
with self._conn() as conn:
|
||||
conn.execute("DELETE FROM images WHERE id=?", (row_id,))
|
||||
conn.commit()
|
||||
|
||||
def export_csv(self) -> str:
|
||||
with self._conn() as conn:
|
||||
rows = conn.execute(
|
||||
"SELECT id, filename, interrogator_tags, vlm_tags, all_tags, created_at FROM images ORDER BY id"
|
||||
).fetchall()
|
||||
buf = io.StringIO()
|
||||
writer = csv.writer(buf)
|
||||
writer.writerow(["id", "filename", "interrogator_tags", "vlm_tags", "all_tags", "created_at"])
|
||||
writer.writerows(rows)
|
||||
return buf.getvalue()
|
||||
|
||||
@staticmethod
|
||||
def _row(r) -> dict:
|
||||
return {
|
||||
"id": r[0],
|
||||
"filename": r[1] or "",
|
||||
"interrogator_tags": r[2] or "",
|
||||
"vlm_tags": r[3] or "",
|
||||
"all_tags": r[4] or "",
|
||||
"created_at": r[5] or "",
|
||||
}
|
||||
@@ -0,0 +1,402 @@
|
||||
"""WD Tagger / DeepDanbooru / Ollama VLM 推論サービス。"""
|
||||
|
||||
import base64
|
||||
import csv
|
||||
import io
|
||||
import json
|
||||
import logging
|
||||
import tempfile
|
||||
import threading
|
||||
import urllib.request
|
||||
from pathlib import Path
|
||||
from typing import Optional
|
||||
|
||||
import numpy as np
|
||||
from PIL import Image, ImageOps, PngImagePlugin
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
_model_lock = threading.Lock()
|
||||
|
||||
|
||||
class TaggerService:
|
||||
def __init__(self, models_dir: Path, settings_file: Path):
|
||||
self.models_dir = models_dir
|
||||
self.settings_file = settings_file
|
||||
self._cache: dict = {}
|
||||
self._batch_state: dict = {
|
||||
"running": False, "total": 0, "done": 0, "log": [], "stop": False,
|
||||
}
|
||||
|
||||
# ── 設定 ──────────────────────────────────────────────────
|
||||
|
||||
def load_settings(self) -> dict:
|
||||
if self.settings_file.exists():
|
||||
try:
|
||||
with open(self.settings_file, "r", encoding="utf-8") as f:
|
||||
return json.load(f)
|
||||
except Exception:
|
||||
pass
|
||||
return {}
|
||||
|
||||
def save_settings(self, data: dict):
|
||||
self.settings_file.parent.mkdir(parents=True, exist_ok=True)
|
||||
with open(self.settings_file, "w", encoding="utf-8") as f:
|
||||
json.dump(data, f, ensure_ascii=False, indent=2)
|
||||
|
||||
def _effective_models_dir(self) -> Path:
|
||||
custom = self.load_settings().get("models_dir", "").strip()
|
||||
if custom:
|
||||
p = Path(custom)
|
||||
if p.is_dir():
|
||||
return p
|
||||
return self.models_dir
|
||||
|
||||
# ── モデル一覧 ─────────────────────────────────────────────
|
||||
|
||||
def list_models(self) -> list:
|
||||
mdir = self._effective_models_dir()
|
||||
models = []
|
||||
if not mdir.is_dir():
|
||||
return models
|
||||
for item in sorted(mdir.iterdir()):
|
||||
if not item.is_dir():
|
||||
continue
|
||||
exts = {f.suffix.lower() for f in item.iterdir() if f.is_file()}
|
||||
if ".onnx" in exts:
|
||||
models.append({"name": item.name, "type": "onnx"})
|
||||
elif ".h5" in exts:
|
||||
models.append({"name": item.name, "type": "deepdanbooru"})
|
||||
return models
|
||||
|
||||
# ── モデルロード ──────────────────────────────────────────
|
||||
|
||||
@staticmethod
|
||||
def _validate_model_name(name: str) -> bool:
|
||||
"""パストラバーサル防止: セパレータ・NUL・相対参照を拒否"""
|
||||
return bool(name) and "/" not in name and "\\" not in name and "\x00" not in name and name not in (".", "..")
|
||||
|
||||
def _load_model(self, model_name: str) -> Optional[dict]:
|
||||
if not self._validate_model_name(model_name):
|
||||
logger.error("Invalid model name rejected: %r", model_name)
|
||||
return None
|
||||
if model_name in self._cache:
|
||||
return self._cache[model_name]
|
||||
with _model_lock:
|
||||
if model_name in self._cache:
|
||||
return self._cache[model_name]
|
||||
mdir = self._effective_models_dir()
|
||||
model_dir = mdir / model_name
|
||||
if not model_dir.is_dir():
|
||||
logger.error("Model dir not found: %s", model_dir)
|
||||
return None
|
||||
files = list(model_dir.iterdir())
|
||||
onnx = next((f for f in files if f.suffix == ".onnx"), None)
|
||||
h5 = next((f for f in files if f.suffix == ".h5"), None)
|
||||
if onnx:
|
||||
return self._load_onnx(model_name, onnx, model_dir)
|
||||
if h5:
|
||||
return self._load_deepdanbooru(model_name, h5, model_dir)
|
||||
logger.error("No .onnx or .h5 in %s", model_dir)
|
||||
return None
|
||||
|
||||
def _load_onnx(self, name: str, onnx_file: Path, model_dir: Path) -> Optional[dict]:
|
||||
try:
|
||||
import onnxruntime as ort
|
||||
providers = []
|
||||
try:
|
||||
import torch
|
||||
if torch.cuda.is_available():
|
||||
providers.append("CUDAExecutionProvider")
|
||||
except ImportError:
|
||||
pass
|
||||
providers.append("CPUExecutionProvider")
|
||||
session = ort.InferenceSession(str(onnx_file), providers=providers)
|
||||
labels = self._load_labels(model_dir)
|
||||
data = {
|
||||
"session": session,
|
||||
"labels": labels,
|
||||
"input_name": session.get_inputs()[0].name,
|
||||
"input_shape": session.get_inputs()[0].shape,
|
||||
"type": "onnx",
|
||||
}
|
||||
self._cache[name] = data
|
||||
logger.info("ONNX loaded: %s (%d labels)", name, len(labels))
|
||||
return data
|
||||
except ImportError:
|
||||
logger.error("onnxruntime not installed")
|
||||
return None
|
||||
except Exception as e:
|
||||
logger.error("ONNX load error %s: %s", name, e)
|
||||
return None
|
||||
|
||||
def _load_deepdanbooru(self, name: str, h5_file: Path, model_dir: Path) -> Optional[dict]:
|
||||
try:
|
||||
import tensorflow as tf
|
||||
except ImportError:
|
||||
logger.warning("TensorFlow not installed — DeepDanbooru unavailable")
|
||||
return None
|
||||
try:
|
||||
model = tf.keras.models.load_model(str(h5_file))
|
||||
labels = self._load_labels(model_dir)
|
||||
data = {"session": model, "labels": labels, "type": "deepdanbooru"}
|
||||
self._cache[name] = data
|
||||
logger.info("DeepDanbooru loaded: %s (%d labels)", name, len(labels))
|
||||
return data
|
||||
except Exception as e:
|
||||
logger.error("DeepDanbooru load error %s: %s", name, e)
|
||||
return None
|
||||
|
||||
def _load_labels(self, model_dir: Path) -> list:
|
||||
for fname in ("selected_tags.csv", "tags.csv", "tags.txt", "tags-general.txt"):
|
||||
p = model_dir / fname
|
||||
if not p.exists():
|
||||
continue
|
||||
try:
|
||||
if p.suffix == ".csv":
|
||||
with open(p, "r", encoding="utf-8-sig", newline="") as f:
|
||||
reader = csv.reader(f)
|
||||
next(reader, None)
|
||||
return [row[1] for row in reader if len(row) > 1]
|
||||
else:
|
||||
with open(p, "r", encoding="utf-8") as f:
|
||||
return [ln.strip() for ln in f if ln.strip()]
|
||||
except Exception as e:
|
||||
logger.warning("Label load failed %s: %s", p, e)
|
||||
return []
|
||||
|
||||
# ── 推論(WD Tagger / DeepDanbooru) ────────────────────
|
||||
|
||||
def predict(self, image_b64: str, model_name: str, threshold: float = 0.35, char_threshold: float = 0.85) -> dict:
|
||||
img = self._decode_b64(image_b64)
|
||||
data = self._load_model(model_name)
|
||||
if data is None:
|
||||
return {"error": f"Model '{model_name}' could not be loaded"}
|
||||
try:
|
||||
if data["type"] == "deepdanbooru":
|
||||
tags = self._predict_dd(img, data, threshold, char_threshold)
|
||||
else:
|
||||
tags = self._predict_onnx(img, data, threshold, char_threshold)
|
||||
return {"tags": ", ".join(tags), "count": len(tags)}
|
||||
except Exception as e:
|
||||
logger.error("predict error: %s", e)
|
||||
return {"error": str(e)}
|
||||
|
||||
def _predict_onnx(self, img: Image.Image, data: dict, thr: float, char_thr: float) -> list:
|
||||
shape = data["input_shape"]
|
||||
fmt = "NHWC"
|
||||
size = (224, 224)
|
||||
if len(shape) == 4:
|
||||
if shape[1] == 3 and isinstance(shape[2], int) and shape[2] > 0:
|
||||
fmt = "NCHW"
|
||||
size = (int(shape[3]), int(shape[2]))
|
||||
elif shape[3] == 3 and isinstance(shape[1], int) and shape[1] > 0:
|
||||
fmt = "NHWC"
|
||||
size = (int(shape[2]), int(shape[1]))
|
||||
|
||||
img = ImageOps.exif_transpose(img)
|
||||
if img.mode != "RGB":
|
||||
img = img.convert("RGB")
|
||||
arr = np.array(img.resize(size, Image.Resampling.LANCZOS), dtype=np.float32) / 255.0
|
||||
if fmt == "NCHW":
|
||||
arr = arr.transpose((2, 0, 1))
|
||||
arr = np.expand_dims(arr, 0)
|
||||
preds = data["session"].run(None, {data["input_name"]: arr})[0][0]
|
||||
return self._filter_tags(preds, data["labels"], thr, char_thr)
|
||||
|
||||
def _predict_dd(self, img: Image.Image, data: dict, thr: float, char_thr: float) -> list:
|
||||
img = ImageOps.exif_transpose(img)
|
||||
if img.mode != "RGB":
|
||||
img = img.convert("RGB")
|
||||
arr = np.array(img.resize((512, 512), Image.Resampling.LANCZOS), dtype=np.float32) / 255.0
|
||||
arr = np.expand_dims(arr, 0)
|
||||
preds = data["session"].predict(arr)[0]
|
||||
return self._filter_tags(preds, data["labels"], thr, char_thr)
|
||||
|
||||
def _filter_tags(self, preds, labels: list, thr: float, char_thr: float) -> list:
|
||||
tags = []
|
||||
for i, score in enumerate(preds):
|
||||
if i >= len(labels):
|
||||
break
|
||||
label = labels[i]
|
||||
if float(score) >= (char_thr if label.startswith("character:") else thr):
|
||||
tags.append(label.replace("character:", ""))
|
||||
return tags
|
||||
|
||||
# ── Ollama VLM ────────────────────────────────────────────
|
||||
|
||||
def ollama_models(self, api_url: str) -> list:
|
||||
try:
|
||||
req = urllib.request.Request(api_url.rstrip("/") + "/api/tags")
|
||||
with urllib.request.urlopen(req, timeout=5) as resp:
|
||||
data = json.loads(resp.read().decode("utf-8"))
|
||||
return sorted(m["name"] for m in data.get("models", []))
|
||||
except Exception as e:
|
||||
logger.error("ollama_models: %s", e)
|
||||
return []
|
||||
|
||||
def ollama_predict(self, image_b64: str, api_url: str, model: str, prompt: str, max_tags: int = 40) -> dict:
|
||||
payload = json.dumps({
|
||||
"model": model,
|
||||
"messages": [{"role": "user", "content": prompt, "images": [image_b64]}],
|
||||
"stream": False,
|
||||
"options": {"temperature": 0.7, "num_ctx": 4096},
|
||||
}).encode("utf-8")
|
||||
try:
|
||||
req = urllib.request.Request(
|
||||
api_url.rstrip("/") + "/api/chat",
|
||||
data=payload,
|
||||
headers={"Content-Type": "application/json"},
|
||||
method="POST",
|
||||
)
|
||||
with urllib.request.urlopen(req, timeout=180) as resp:
|
||||
data = json.loads(resp.read().decode("utf-8"))
|
||||
content = data.get("message", {}).get("content", "")
|
||||
tags = [t.strip() for t in content.split(",") if t.strip()][:max_tags]
|
||||
return {"tags": ", ".join(tags), "count": len(tags)}
|
||||
except Exception as e:
|
||||
logger.error("ollama_predict: %s", e)
|
||||
return {"error": str(e)}
|
||||
|
||||
# ── ファイルメタデータ書込 ────────────────────────────────
|
||||
|
||||
_ALLOWED_WRITE_EXTS = {".jpg", ".jpeg", ".png", ".webp", ".bmp", ".gif"}
|
||||
|
||||
def write_meta_to_file(self, image_path: str, tags: str) -> dict:
|
||||
path = Path(image_path).resolve()
|
||||
if path.suffix.lower() not in self._ALLOWED_WRITE_EXTS:
|
||||
return {"error": "Unsupported file type"}
|
||||
if not path.is_file():
|
||||
return {"error": f"File not found: {image_path}"}
|
||||
try:
|
||||
import piexif
|
||||
except ImportError:
|
||||
piexif = None
|
||||
try:
|
||||
with Image.open(path) as img:
|
||||
img.load()
|
||||
ext = path.suffix.lower()
|
||||
if ext in (".jpg", ".jpeg") and piexif:
|
||||
self._write_jpeg(img, path, tags, piexif)
|
||||
elif ext == ".png":
|
||||
self._write_png(img, path, tags)
|
||||
else:
|
||||
self._write_sidecar(path, tags)
|
||||
return {"ok": True}
|
||||
except Exception as e:
|
||||
logger.error("write_meta: %s", e)
|
||||
return {"error": str(e)}
|
||||
|
||||
def _write_jpeg(self, img: Image.Image, path: Path, tags: str, piexif):
|
||||
exif_data = img.info.get("exif")
|
||||
if exif_data:
|
||||
try:
|
||||
exif_dict = piexif.load(exif_data)
|
||||
except Exception:
|
||||
exif_dict = {"0th": {}, "Exif": {}, "1st": {}, "GPS": {}, "Interop": {}}
|
||||
else:
|
||||
exif_dict = {"0th": {}, "Exif": {}, "1st": {}, "GPS": {}, "Interop": {}}
|
||||
exif_dict["0th"][piexif.ImageIFD.ImageDescription] = tags.encode("utf-8")
|
||||
exif_bytes = piexif.dump(exif_dict)
|
||||
with tempfile.NamedTemporaryFile(delete=False, suffix=path.suffix) as tmp:
|
||||
tmp_path = Path(tmp.name)
|
||||
img.save(str(tmp_path), "JPEG", quality=95, exif=exif_bytes)
|
||||
tmp_path.replace(path)
|
||||
|
||||
def _write_png(self, img: Image.Image, path: Path, tags: str):
|
||||
meta = PngImagePlugin.PngInfo()
|
||||
for k, v in img.info.items():
|
||||
if isinstance(k, str) and isinstance(v, str):
|
||||
meta.add_text(k, v)
|
||||
meta.add_text("Tags", tags)
|
||||
with tempfile.NamedTemporaryFile(delete=False, suffix=".png") as tmp:
|
||||
tmp_path = Path(tmp.name)
|
||||
img.save(str(tmp_path), "PNG", pnginfo=meta)
|
||||
tmp_path.replace(path)
|
||||
|
||||
def _write_sidecar(self, path: Path, tags: str):
|
||||
sidecar = path.with_suffix(".tags.json")
|
||||
with open(sidecar, "w", encoding="utf-8") as f:
|
||||
json.dump({"tags": tags}, f, ensure_ascii=False, indent=2)
|
||||
|
||||
# ── バッチ処理 ────────────────────────────────────────────
|
||||
|
||||
def batch_status(self) -> dict:
|
||||
s = self._batch_state
|
||||
return {
|
||||
"running": s["running"],
|
||||
"total": s["total"],
|
||||
"done": s["done"],
|
||||
"log": s["log"][-50:],
|
||||
}
|
||||
|
||||
def batch_stop(self):
|
||||
self._batch_state["stop"] = True
|
||||
|
||||
def batch_start(self, folder: str, model_name: str, threshold: float, char_threshold: float,
|
||||
use_ollama: bool, ollama_api: str, ollama_model: str, ollama_prompt: str,
|
||||
ollama_max_tags: int, save_db: bool, write_file: bool, write_txt: bool, db_service) -> dict:
|
||||
if self._batch_state["running"]:
|
||||
return {"error": "Batch already running"}
|
||||
folder_path = Path(folder)
|
||||
if not folder_path.is_dir():
|
||||
return {"error": f"Folder not found: {folder}"}
|
||||
|
||||
exts = {".jpg", ".jpeg", ".png", ".webp", ".bmp", ".gif"}
|
||||
files = sorted(f for f in folder_path.iterdir() if f.is_file() and f.suffix.lower() in exts)
|
||||
if not files:
|
||||
return {"error": "No image files found"}
|
||||
|
||||
self._batch_state = {
|
||||
"running": True, "total": len(files), "done": 0, "log": [], "stop": False,
|
||||
}
|
||||
|
||||
def _run():
|
||||
for fpath in files:
|
||||
if self._batch_state["stop"]:
|
||||
self._batch_state["log"].append("Stopped.")
|
||||
break
|
||||
try:
|
||||
with Image.open(fpath) as img:
|
||||
img.load()
|
||||
buf = io.BytesIO()
|
||||
img.save(buf, format="PNG")
|
||||
b64 = base64.b64encode(buf.getvalue()).decode("utf-8")
|
||||
|
||||
interrogator_tags = ""
|
||||
if model_name:
|
||||
res = self.predict(b64, model_name, threshold, char_threshold)
|
||||
interrogator_tags = res.get("tags", "")
|
||||
|
||||
vlm_tags = ""
|
||||
if use_ollama and ollama_model:
|
||||
res2 = self.ollama_predict(b64, ollama_api, ollama_model, ollama_prompt, ollama_max_tags)
|
||||
vlm_tags = res2.get("tags", "")
|
||||
|
||||
all_tags = ", ".join(filter(None, [interrogator_tags, vlm_tags]))
|
||||
|
||||
if save_db:
|
||||
db_service.save(str(fpath), interrogator_tags, vlm_tags)
|
||||
if write_file and all_tags:
|
||||
self.write_meta_to_file(str(fpath), all_tags)
|
||||
if write_txt and all_tags:
|
||||
txt_path = fpath.with_suffix(".txt")
|
||||
with open(txt_path, "w", encoding="utf-8") as f:
|
||||
f.write(all_tags)
|
||||
|
||||
n = len([t for t in all_tags.split(",") if t.strip()])
|
||||
self._batch_state["log"].append(f"✓ {fpath.name}: {n} tags")
|
||||
except Exception as e:
|
||||
self._batch_state["log"].append(f"✗ {fpath.name}: {e}")
|
||||
self._batch_state["done"] += 1
|
||||
|
||||
self._batch_state["running"] = False
|
||||
|
||||
threading.Thread(target=_run, daemon=True).start()
|
||||
return {"ok": True, "total": len(files)}
|
||||
|
||||
# ── ユーティリティ ────────────────────────────────────────
|
||||
|
||||
@staticmethod
|
||||
def _decode_b64(b64: str) -> Image.Image:
|
||||
return Image.open(io.BytesIO(base64.b64decode(b64)))
|
||||
@@ -18,6 +18,7 @@ _CLIP_TYPE_TO_MODEL = {
|
||||
"wan": "Wan",
|
||||
"cosmos": "Cosmos",
|
||||
"lumina": "Lumina",
|
||||
"lumina2": "Z-IMAGE",
|
||||
}
|
||||
|
||||
|
||||
|
||||
@@ -61,7 +61,7 @@ class WorkflowStudio:
|
||||
app.router.add_get("/wfm", serve_index_page)
|
||||
|
||||
# API routes
|
||||
from .routes import workflow_routes, settings_routes, ollama_routes, eagle_routes, nodes_routes, prompts_routes, models_routes, gallery_routes, wildcard_routes
|
||||
from .routes import workflow_routes, settings_routes, ollama_routes, eagle_routes, nodes_routes, prompts_routes, models_routes, gallery_routes, wildcard_routes, tagger_routes
|
||||
|
||||
workflow_routes.setup_routes(app)
|
||||
settings_routes.setup_routes(app)
|
||||
@@ -72,5 +72,6 @@ class WorkflowStudio:
|
||||
models_routes.setup_routes(app)
|
||||
gallery_routes.setup_routes(app)
|
||||
wildcard_routes.setup_routes(app)
|
||||
tagger_routes.setup_routes(app)
|
||||
|
||||
logger.info("Workflow Studio: Routes registered successfully")
|
||||
|
||||
+2
-2
@@ -1,7 +1,7 @@
|
||||
[project]
|
||||
name = "comfyui-workflow-studio"
|
||||
description = "A comprehensive workflow management and generation UI plugin for ComfyUI. Browse, organize, and execute workflows from a dedicated studio interface."
|
||||
version = "0.3.22"
|
||||
description = "A comprehensive workflow, asset management, and generation UI plugin for ComfyUI. Manage workflows, models, images, and prompts; batch generation and Image Feeder in the GenerateUI tab; library side panel with canvas drag & drop and AI tools."
|
||||
version = "0.3.44"
|
||||
license = "MIT"
|
||||
requires-python = ">= 3.10"
|
||||
dependencies = ["jinja2"]
|
||||
|
||||
@@ -0,0 +1,21 @@
|
||||
# ComfyUI-Workflow-Studio - Tagger tab dependencies
|
||||
#
|
||||
# numpy and Pillow are already bundled with ComfyUI and do not need to be installed.
|
||||
# torch is managed by ComfyUI and must NOT be pinned here.
|
||||
#
|
||||
# Install into ComfyUI's embedded Python:
|
||||
# python_embeded\python.exe -m pip install -r requirements.txt
|
||||
#
|
||||
# For GPU-accelerated ONNX inference, install onnxruntime-gpu instead of onnxruntime:
|
||||
# python_embeded\python.exe -m pip install onnxruntime-gpu
|
||||
|
||||
# -- Required for WD Tagger / SwinV2 ONNX inference --
|
||||
onnxruntime>=1.16
|
||||
|
||||
# -- Required for JPEG EXIF tag writing --
|
||||
piexif>=1.1.3
|
||||
|
||||
# -- Optional: DeepDanbooru (.h5 model) support --
|
||||
# Omit if you do not use DeepDanbooru models.
|
||||
# TensorFlow is large (~600MB) and conflicts with some CUDA setups.
|
||||
# tensorflow>=2.10
|
||||
@@ -219,6 +219,43 @@
|
||||
color: #fbbf24;
|
||||
}
|
||||
|
||||
/* Feederグループボタン(サムネイルカード左上) */
|
||||
.wfm-gallery-thumb-feeder-btn {
|
||||
position: absolute;
|
||||
top: 4px;
|
||||
left: 4px;
|
||||
background: rgba(0,0,0,0.5);
|
||||
border: none;
|
||||
border-radius: 50%;
|
||||
width: 24px;
|
||||
height: 24px;
|
||||
font-size: 11px;
|
||||
font-weight: bold;
|
||||
line-height: 1;
|
||||
padding: 0;
|
||||
cursor: pointer;
|
||||
color: rgba(255,255,255,0.6);
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
opacity: 0;
|
||||
transition: opacity 0.15s, color 0.15s;
|
||||
}
|
||||
|
||||
.wfm-gallery-thumb-card:hover .wfm-gallery-thumb-feeder-btn {
|
||||
opacity: 1;
|
||||
}
|
||||
|
||||
.wfm-gallery-thumb-feeder-btn.active {
|
||||
color: #38bdf8;
|
||||
opacity: 1;
|
||||
}
|
||||
|
||||
.wfm-gallery-thumb-feeder-btn:hover {
|
||||
background: rgba(0,0,0,0.75);
|
||||
color: #38bdf8;
|
||||
}
|
||||
|
||||
/* テーブルビューのお気に入りボタン */
|
||||
.wfm-gallery-table-fav-btn {
|
||||
background: none;
|
||||
@@ -602,6 +639,109 @@
|
||||
background: rgba(255,255,255,0.2);
|
||||
}
|
||||
|
||||
/* ── 画像比較ライトボックス ──────────────────────────────────── */
|
||||
|
||||
.wfm-lightbox-compare .wfm-lightbox-compare-inner {
|
||||
position: relative;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
align-items: center;
|
||||
max-width: 96vw;
|
||||
max-height: 92vh;
|
||||
overflow: auto;
|
||||
}
|
||||
|
||||
.wfm-lightbox-compare-grid {
|
||||
display: grid;
|
||||
grid-template-columns: repeat(var(--compare-cols, 2), 1fr);
|
||||
gap: 12px;
|
||||
padding: 16px;
|
||||
}
|
||||
|
||||
.wfm-lightbox-compare-item {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
align-items: center;
|
||||
gap: 6px;
|
||||
}
|
||||
|
||||
.wfm-lightbox-compare-img {
|
||||
max-width: calc(92vw / var(--compare-cols, 2) - 12px);
|
||||
max-height: 78vh;
|
||||
object-fit: contain;
|
||||
border-radius: 4px;
|
||||
cursor: default;
|
||||
}
|
||||
|
||||
.wfm-lightbox-compare-label {
|
||||
color: rgba(255,255,255,0.75);
|
||||
font-size: 12px;
|
||||
text-align: center;
|
||||
max-width: 100%;
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
.wfm-lightbox-compare-close {
|
||||
position: fixed;
|
||||
top: 16px;
|
||||
right: 16px;
|
||||
z-index: 10001;
|
||||
}
|
||||
|
||||
/* ── 詳細パネル アクションボタン行 ───────────────────────────── */
|
||||
|
||||
.wfm-gallery-detail-action-row {
|
||||
display: flex;
|
||||
gap: 6px;
|
||||
padding: 4px 8px;
|
||||
border-bottom: 1px solid var(--wfm-border);
|
||||
flex-shrink: 0;
|
||||
flex-wrap: wrap;
|
||||
}
|
||||
|
||||
/* ── 詳細パネル アクションボタン ─────────────────────────────── */
|
||||
|
||||
.wfm-gallery-action-btn {
|
||||
padding: 4px 10px;
|
||||
border-radius: 4px;
|
||||
border: 1px solid;
|
||||
cursor: pointer;
|
||||
font-size: 12px;
|
||||
white-space: nowrap;
|
||||
align-self: center;
|
||||
margin: 2px 3px;
|
||||
color: #fff;
|
||||
}
|
||||
|
||||
.wfm-gallery-action-btn-green {
|
||||
background: var(--wfm-success, #22c55e);
|
||||
border-color: var(--wfm-success, #22c55e);
|
||||
}
|
||||
.wfm-gallery-action-btn-green:hover {
|
||||
background: #16a34a;
|
||||
border-color: #16a34a;
|
||||
}
|
||||
|
||||
.wfm-gallery-action-btn-primary {
|
||||
background: var(--wfm-primary);
|
||||
border-color: var(--wfm-primary);
|
||||
}
|
||||
.wfm-gallery-action-btn-primary:hover {
|
||||
background: var(--wfm-primary-hover);
|
||||
border-color: var(--wfm-primary-hover);
|
||||
}
|
||||
|
||||
.wfm-gallery-action-btn-tagger {
|
||||
background: var(--wfm-accent, #7c5cfc);
|
||||
border-color: var(--wfm-accent, #7c5cfc);
|
||||
}
|
||||
.wfm-gallery-action-btn-tagger:hover {
|
||||
background: #6a4de0;
|
||||
border-color: #6a4de0;
|
||||
}
|
||||
|
||||
/* ── ファイル操作ボタン (詳細パネル) ─────────────────────────── */
|
||||
|
||||
.wfm-gallery-file-actions {
|
||||
|
||||
+695
-25
@@ -581,6 +581,301 @@ body {
|
||||
padding: 12px 14px;
|
||||
}
|
||||
|
||||
/* Narrow variant for Model tab left pane */
|
||||
.wfm-gen-params-col--narrow {
|
||||
flex: 1;
|
||||
}
|
||||
|
||||
/* Center pane: LoRA-only (Model tab) */
|
||||
.wfm-gen-lora-col {
|
||||
flex: 1;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
overflow: hidden;
|
||||
border-right: 1px solid var(--wfm-border);
|
||||
}
|
||||
|
||||
.wfm-gen-lora-col-header {
|
||||
padding: 8px 14px;
|
||||
font-size: 12px;
|
||||
font-weight: 600;
|
||||
color: var(--wfm-text-secondary);
|
||||
text-transform: uppercase;
|
||||
letter-spacing: 0.06em;
|
||||
border-bottom: 1px solid var(--wfm-border);
|
||||
flex-shrink: 0;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
}
|
||||
|
||||
.wfm-lora-refresh-btn {
|
||||
margin-left: auto;
|
||||
font-size: 13px;
|
||||
line-height: 1;
|
||||
padding: 2px 5px;
|
||||
opacity: 0.7;
|
||||
text-transform: none;
|
||||
letter-spacing: 0;
|
||||
}
|
||||
.wfm-lora-refresh-btn:hover { opacity: 1; }
|
||||
|
||||
.wfm-gen-lora-col-body {
|
||||
flex: 1;
|
||||
overflow-y: auto;
|
||||
padding: 0;
|
||||
}
|
||||
|
||||
/* ── LoRA pane tabs ─────────────────────────────────────── */
|
||||
.wfm-lora-tab-header {
|
||||
display: flex;
|
||||
border-bottom: 1px solid var(--wfm-border);
|
||||
gap: 0;
|
||||
padding: 0 8px;
|
||||
flex-shrink: 0;
|
||||
}
|
||||
|
||||
.wfm-lora-tab-btn {
|
||||
padding: 6px 14px;
|
||||
font-size: 12px;
|
||||
font-weight: 500;
|
||||
color: var(--wfm-text-secondary);
|
||||
background: none;
|
||||
border: none;
|
||||
border-bottom: 2px solid transparent;
|
||||
cursor: pointer;
|
||||
margin-bottom: -1px;
|
||||
text-transform: none;
|
||||
letter-spacing: 0;
|
||||
transition: color 0.15s, border-color 0.15s;
|
||||
}
|
||||
|
||||
.wfm-lora-tab-btn:hover { color: var(--wfm-text); }
|
||||
|
||||
.wfm-lora-tab-btn.active {
|
||||
color: var(--wfm-accent);
|
||||
border-bottom-color: var(--wfm-accent);
|
||||
}
|
||||
|
||||
.wfm-lora-tab-content {
|
||||
padding: 10px 12px;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 6px;
|
||||
}
|
||||
|
||||
/* ── LoRA pane sections ──────────────────────────────────── */
|
||||
.wfm-lora-unified {
|
||||
padding: 10px 12px;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 6px;
|
||||
}
|
||||
|
||||
.wfm-lora-strength-combined {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 0;
|
||||
flex-wrap: wrap;
|
||||
padding: 2px 0;
|
||||
}
|
||||
|
||||
.wfm-lora-strength-single {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 5px;
|
||||
font-size: 12px;
|
||||
color: var(--wfm-text-secondary);
|
||||
padding-right: 10px;
|
||||
margin-right: 10px;
|
||||
border-right: 1px solid var(--wfm-border);
|
||||
}
|
||||
|
||||
.wfm-lora-strength-single input {
|
||||
width: 60px !important;
|
||||
}
|
||||
|
||||
.wfm-lora-stack-header {
|
||||
display: flex;
|
||||
gap: 6px;
|
||||
align-items: center;
|
||||
}
|
||||
|
||||
.wfm-lora-p-btn {
|
||||
background: rgba(74, 158, 255, 0.12) !important;
|
||||
border-color: rgba(74, 158, 255, 0.35) !important;
|
||||
color: var(--wfm-primary) !important;
|
||||
font-weight: 700;
|
||||
flex-shrink: 0;
|
||||
}
|
||||
|
||||
.wfm-lora-stack-label {
|
||||
font-size: 12px;
|
||||
font-weight: 700;
|
||||
color: var(--wfm-text-secondary);
|
||||
white-space: nowrap;
|
||||
padding-right: 2px;
|
||||
}
|
||||
|
||||
.wfm-lora-stack-info-block {
|
||||
background: var(--wfm-bg-secondary);
|
||||
border: 1px solid var(--wfm-border);
|
||||
border-radius: var(--wfm-radius-sm);
|
||||
padding: 8px 10px;
|
||||
}
|
||||
|
||||
.wfm-lora-stack-info-label {
|
||||
font-size: 10px;
|
||||
font-weight: 600;
|
||||
color: var(--wfm-text-secondary);
|
||||
text-transform: uppercase;
|
||||
letter-spacing: 0.05em;
|
||||
margin-bottom: 4px;
|
||||
}
|
||||
|
||||
.wfm-lora-stack-syntax {
|
||||
font-size: 11px;
|
||||
font-family: monospace;
|
||||
color: var(--wfm-text);
|
||||
word-break: break-all;
|
||||
white-space: pre-wrap;
|
||||
line-height: 1.5;
|
||||
}
|
||||
|
||||
.wfm-lora-stack-triggers {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
gap: 4px;
|
||||
}
|
||||
|
||||
.wfm-lora-trigger-word {
|
||||
font-size: 11px;
|
||||
background: rgba(74, 158, 255, 0.12);
|
||||
color: var(--wfm-primary);
|
||||
border: 1px solid rgba(74, 158, 255, 0.25);
|
||||
border-radius: 3px;
|
||||
padding: 1px 6px;
|
||||
}
|
||||
|
||||
.wfm-lora-stack-models {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 0;
|
||||
}
|
||||
|
||||
.wfm-lora-stack-models-header {
|
||||
display: grid;
|
||||
grid-template-columns: 16px 1fr 64px 64px;
|
||||
gap: 4px;
|
||||
padding: 0 0 4px;
|
||||
font-size: 11px;
|
||||
color: var(--wfm-text-secondary);
|
||||
border-bottom: 1px solid var(--wfm-border);
|
||||
margin-bottom: 4px;
|
||||
text-align: right;
|
||||
}
|
||||
|
||||
.wfm-lora-stack-models-header span:nth-child(2) {
|
||||
text-align: left;
|
||||
}
|
||||
|
||||
.wfm-lora-stack-model-row {
|
||||
display: grid;
|
||||
grid-template-columns: 16px 1fr auto;
|
||||
gap: 6px;
|
||||
align-items: center;
|
||||
padding: 4px 0;
|
||||
border-bottom: 1px solid var(--wfm-border);
|
||||
}
|
||||
|
||||
.wfm-lora-stack-model-row:last-child {
|
||||
border-bottom: none;
|
||||
}
|
||||
|
||||
.wfm-lora-stack-model-row--off .wfm-lora-stack-model-name {
|
||||
opacity: 0.4;
|
||||
text-decoration: line-through;
|
||||
}
|
||||
|
||||
.wfm-lora-stack-model-row--off .wfm-lora-stack-strengths input {
|
||||
opacity: 0.35;
|
||||
}
|
||||
|
||||
.wfm-lora-stack-model-name {
|
||||
font-size: 12px;
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
.wfm-lora-stack-strengths {
|
||||
display: flex;
|
||||
gap: 4px;
|
||||
}
|
||||
|
||||
.wfm-lora-stack-strengths input[type="number"] {
|
||||
padding: 4px 4px !important;
|
||||
text-align: center;
|
||||
}
|
||||
|
||||
.wfm-lora-stack-strengths input[type="number"]::-webkit-outer-spin-button,
|
||||
.wfm-lora-stack-strengths input[type="number"]::-webkit-inner-spin-button {
|
||||
-webkit-appearance: none;
|
||||
margin: 0;
|
||||
}
|
||||
|
||||
.wfm-lora-stack-strengths input[type="number"] {
|
||||
-moz-appearance: textfield;
|
||||
appearance: textfield;
|
||||
}
|
||||
|
||||
/* Global strength adjustment row */
|
||||
.wfm-lora-stack-global-adj {
|
||||
display: grid;
|
||||
grid-template-columns: 16px 1fr auto;
|
||||
gap: 6px;
|
||||
align-items: center;
|
||||
padding: 5px 0;
|
||||
border-bottom: 1px solid var(--wfm-border);
|
||||
margin-bottom: 4px;
|
||||
}
|
||||
|
||||
.wfm-lora-stack-global-adj-label {
|
||||
font-size: 11px;
|
||||
color: var(--wfm-text-secondary);
|
||||
font-weight: 600;
|
||||
}
|
||||
|
||||
.wfm-lora-stack-global-adj-groups {
|
||||
display: flex;
|
||||
gap: 8px;
|
||||
align-items: center;
|
||||
}
|
||||
|
||||
.wfm-lora-stack-global-adj-group {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 3px;
|
||||
}
|
||||
|
||||
.wfm-lora-stack-global-adj-group > span {
|
||||
font-size: 11px;
|
||||
color: var(--wfm-text-secondary);
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
.wfm-lora-stack-adj-step {
|
||||
width: 50px !important;
|
||||
padding: 2px 4px !important;
|
||||
text-align: center;
|
||||
}
|
||||
|
||||
.wfm-btn-xs {
|
||||
padding: 1px 6px;
|
||||
font-size: 13px;
|
||||
line-height: 1.4;
|
||||
min-width: 22px;
|
||||
}
|
||||
|
||||
/* Stacked sections inside params col (Input: Prompt on top, Image below) */
|
||||
.wfm-gen-params-section {
|
||||
flex: 1;
|
||||
@@ -593,6 +888,44 @@ body {
|
||||
border-top: 1px solid var(--wfm-border);
|
||||
}
|
||||
|
||||
/* Input tab inner tabs (Prompt / Image) */
|
||||
.wfm-input-inner-tabnav {
|
||||
display: flex;
|
||||
gap: 2px;
|
||||
padding: 6px 14px 0;
|
||||
border-bottom: 1px solid var(--wfm-border);
|
||||
flex-shrink: 0;
|
||||
}
|
||||
|
||||
.wfm-input-inner-tab {
|
||||
padding: 4px 14px;
|
||||
font-size: 12px;
|
||||
font-weight: 500;
|
||||
background: none;
|
||||
border: none;
|
||||
border-bottom: 2px solid transparent;
|
||||
color: var(--wfm-text-secondary);
|
||||
cursor: pointer;
|
||||
margin-bottom: -1px;
|
||||
transition: color 0.15s, border-color 0.15s;
|
||||
}
|
||||
|
||||
.wfm-input-inner-tab:hover {
|
||||
color: var(--wfm-text);
|
||||
}
|
||||
|
||||
.wfm-input-inner-tab.active {
|
||||
color: var(--wfm-primary);
|
||||
border-bottom-color: var(--wfm-primary);
|
||||
}
|
||||
|
||||
.wfm-input-inner-panel {
|
||||
flex: 1;
|
||||
overflow-y: auto;
|
||||
padding: 10px 14px;
|
||||
min-height: 0;
|
||||
}
|
||||
|
||||
/* Right sub-column: Raw JSON */
|
||||
.wfm-gen-rawjson-col {
|
||||
width: 540px;
|
||||
@@ -1081,6 +1414,41 @@ body {
|
||||
opacity: 0.7;
|
||||
}
|
||||
|
||||
/* ============================================
|
||||
Stack Button (Lora multi-apply)
|
||||
============================================ */
|
||||
|
||||
.wfm-stack-btn {
|
||||
position: absolute;
|
||||
bottom: 6px;
|
||||
left: 6px;
|
||||
background: none;
|
||||
border: none;
|
||||
color: var(--wfm-text-secondary);
|
||||
font-size: 11px;
|
||||
font-weight: bold;
|
||||
cursor: pointer;
|
||||
line-height: 1;
|
||||
opacity: 0.5;
|
||||
transition: opacity 0.15s, color 0.15s;
|
||||
padding: 0 2px;
|
||||
}
|
||||
|
||||
.wfm-stack-btn:hover {
|
||||
opacity: 1;
|
||||
}
|
||||
|
||||
.wfm-stack-btn.active {
|
||||
color: #60d0a0;
|
||||
opacity: 1;
|
||||
}
|
||||
|
||||
.wfm-table-row .wfm-stack-btn,
|
||||
.wfm-models-table-row .wfm-stack-btn {
|
||||
position: static;
|
||||
opacity: 0.7;
|
||||
}
|
||||
|
||||
|
||||
.wfm-tag {
|
||||
font-size: 10px;
|
||||
@@ -2616,25 +2984,100 @@ body {
|
||||
Help & Support Tab
|
||||
============================================ */
|
||||
|
||||
.wfm-help-container {
|
||||
max-width: 800px;
|
||||
margin: 0 auto;
|
||||
padding: 24px 20px;
|
||||
overflow-y: auto;
|
||||
/* Help Tab — sidebar layout */
|
||||
.wfm-help-layout {
|
||||
display: flex;
|
||||
height: 100%;
|
||||
overflow: hidden;
|
||||
}
|
||||
|
||||
.wfm-help-section {
|
||||
margin-bottom: 32px;
|
||||
.wfm-help-sidebar {
|
||||
width: 220px;
|
||||
flex-shrink: 0;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
border-right: 1px solid var(--wfm-border);
|
||||
overflow: hidden;
|
||||
}
|
||||
|
||||
.wfm-help-section-title {
|
||||
font-size: 18px;
|
||||
font-weight: 700;
|
||||
.wfm-help-nav {
|
||||
flex: 1;
|
||||
overflow-y: auto;
|
||||
padding: 8px 0;
|
||||
}
|
||||
|
||||
.wfm-help-search-wrap {
|
||||
padding: 8px 8px 4px;
|
||||
}
|
||||
|
||||
.wfm-help-search {
|
||||
width: 100%;
|
||||
box-sizing: border-box;
|
||||
background: var(--wfm-bg);
|
||||
border: 1px solid var(--wfm-border);
|
||||
color: var(--wfm-text);
|
||||
margin-bottom: 16px;
|
||||
padding-bottom: 8px;
|
||||
border-bottom: 2px solid var(--wfm-primary);
|
||||
border-radius: 4px;
|
||||
padding: 5px 8px;
|
||||
font-size: 16px;
|
||||
outline: none;
|
||||
}
|
||||
|
||||
.wfm-help-search:focus {
|
||||
border-color: var(--wfm-primary);
|
||||
}
|
||||
|
||||
.wfm-help-nav-item.search-hidden {
|
||||
display: none;
|
||||
}
|
||||
|
||||
.wfm-help-nav-item {
|
||||
display: block;
|
||||
width: 100%;
|
||||
text-align: left;
|
||||
padding: 7px 14px;
|
||||
font-size: 18px;
|
||||
background: none;
|
||||
border: none;
|
||||
border-left: 2px solid transparent;
|
||||
color: var(--wfm-text-secondary);
|
||||
cursor: pointer;
|
||||
transition: color 0.15s, background 0.15s;
|
||||
white-space: nowrap;
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
}
|
||||
|
||||
.wfm-help-nav-item:hover {
|
||||
color: var(--wfm-text);
|
||||
background: var(--wfm-hover);
|
||||
}
|
||||
|
||||
.wfm-help-nav-item.active {
|
||||
color: var(--wfm-primary);
|
||||
background: var(--wfm-hover);
|
||||
border-left-color: var(--wfm-primary);
|
||||
font-weight: 600;
|
||||
}
|
||||
|
||||
.wfm-help-sidebar-support {
|
||||
border-top: 1px solid var(--wfm-border);
|
||||
padding: 6px 0;
|
||||
}
|
||||
|
||||
.wfm-help-content {
|
||||
flex: 1;
|
||||
overflow-y: auto;
|
||||
padding: 20px 24px;
|
||||
min-width: 0;
|
||||
}
|
||||
|
||||
.wfm-help-page {
|
||||
display: none;
|
||||
max-width: 760px;
|
||||
}
|
||||
|
||||
.wfm-help-page.active {
|
||||
display: block;
|
||||
}
|
||||
|
||||
.wfm-help-card {
|
||||
@@ -2646,19 +3089,28 @@ body {
|
||||
}
|
||||
|
||||
.wfm-help-card h3 {
|
||||
font-size: 14px;
|
||||
font-size: 21px;
|
||||
font-weight: 600;
|
||||
color: var(--wfm-primary);
|
||||
margin-bottom: 8px;
|
||||
}
|
||||
|
||||
.wfm-help-card h4 {
|
||||
font-size: 18px;
|
||||
}
|
||||
|
||||
.wfm-help-card p {
|
||||
font-size: 20px;
|
||||
line-height: 1.7;
|
||||
}
|
||||
|
||||
.wfm-help-card ul {
|
||||
margin: 0;
|
||||
padding-left: 20px;
|
||||
}
|
||||
|
||||
.wfm-help-card li {
|
||||
font-size: 13px;
|
||||
font-size: 20px;
|
||||
color: var(--wfm-text-secondary);
|
||||
line-height: 1.8;
|
||||
}
|
||||
@@ -2669,7 +3121,7 @@ body {
|
||||
}
|
||||
|
||||
.wfm-help-support-card > p {
|
||||
font-size: 14px;
|
||||
font-size: 21px;
|
||||
color: var(--wfm-text-secondary);
|
||||
margin-bottom: 20px;
|
||||
}
|
||||
@@ -2716,18 +3168,18 @@ body {
|
||||
}
|
||||
|
||||
.wfm-help-link-title {
|
||||
font-size: 15px;
|
||||
font-size: 23px;
|
||||
font-weight: 600;
|
||||
}
|
||||
|
||||
.wfm-help-link-desc {
|
||||
font-size: 12px;
|
||||
font-size: 18px;
|
||||
color: var(--wfm-text-secondary);
|
||||
margin-top: 2px;
|
||||
}
|
||||
|
||||
.wfm-help-thanks {
|
||||
font-size: 13px;
|
||||
font-size: 20px;
|
||||
color: var(--wfm-text-secondary);
|
||||
font-style: italic;
|
||||
}
|
||||
@@ -3683,6 +4135,14 @@ body {
|
||||
width: 30px;
|
||||
}
|
||||
|
||||
.wfm-table-th-filename,
|
||||
.wfm-table-td-filename {
|
||||
max-width: 160px;
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
.wfm-table-th-subdir,
|
||||
.wfm-table-td-subdir {
|
||||
width: 80px;
|
||||
@@ -3692,6 +4152,26 @@ body {
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
.wfm-table-th-civtype,
|
||||
.wfm-table-td-civtype {
|
||||
width: 70px;
|
||||
max-width: 70px;
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
white-space: nowrap;
|
||||
font-size: 0.85em;
|
||||
}
|
||||
|
||||
.wfm-table-th-basemodel,
|
||||
.wfm-table-td-basemodel {
|
||||
width: 110px;
|
||||
max-width: 110px;
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
white-space: nowrap;
|
||||
font-size: 0.85em;
|
||||
}
|
||||
|
||||
.wfm-table-th-ext,
|
||||
.wfm-table-td-ext {
|
||||
width: 60px;
|
||||
@@ -3807,6 +4287,17 @@ body {
|
||||
}
|
||||
|
||||
|
||||
/* Table sort header */
|
||||
.wfm-table-th-sortable {
|
||||
cursor: pointer;
|
||||
-webkit-user-select: none;
|
||||
user-select: none;
|
||||
white-space: nowrap;
|
||||
}
|
||||
.wfm-table-th-sortable:hover {
|
||||
color: var(--wfm-accent, #6366f1);
|
||||
}
|
||||
|
||||
/* Table view toggle cell */
|
||||
.wfm-table-td-toggle {
|
||||
text-align: center;
|
||||
@@ -3823,6 +4314,11 @@ body {
|
||||
width: 30px;
|
||||
}
|
||||
|
||||
.wfm-table-td-stack {
|
||||
text-align: center;
|
||||
width: 30px;
|
||||
}
|
||||
|
||||
/* Disabled badge in card title */
|
||||
.wfm-badge-disabled {
|
||||
background: rgba(255, 107, 107, 0.2);
|
||||
@@ -3873,13 +4369,45 @@ body {
|
||||
}
|
||||
.wfm-bulk-bar {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 8px;
|
||||
flex-direction: column;
|
||||
gap: 4px;
|
||||
padding: 6px 12px;
|
||||
background: rgba(108, 142, 245, 0.12);
|
||||
border-bottom: 1px solid rgba(108, 142, 245, 0.3);
|
||||
}
|
||||
.wfm-bulk-header {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 6px;
|
||||
flex-wrap: wrap;
|
||||
}
|
||||
.wfm-bulk-rows {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 3px;
|
||||
}
|
||||
.wfm-bulk-row {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 4px;
|
||||
}
|
||||
.wfm-bulk-row-label {
|
||||
font-size: 12px;
|
||||
color: var(--wfm-text-secondary);
|
||||
width: 44px;
|
||||
flex-shrink: 0;
|
||||
text-align: right;
|
||||
}
|
||||
.wfm-bulk-select {
|
||||
width: 330px !important;
|
||||
max-width: 330px !important;
|
||||
font-size: 12px !important;
|
||||
padding: 2px 4px !important;
|
||||
}
|
||||
.wfm-bulk-input {
|
||||
width: 110px !important;
|
||||
font-size: 12px;
|
||||
}
|
||||
.wfm-bulk-count {
|
||||
font-size: 13px;
|
||||
color: #a0a8c0;
|
||||
@@ -3890,6 +4418,21 @@ body {
|
||||
height: 18px;
|
||||
background: rgba(255, 255, 255, 0.15);
|
||||
margin: 0 4px;
|
||||
flex-shrink: 0;
|
||||
}
|
||||
.wfm-btn-success {
|
||||
background: #22c55e;
|
||||
color: #fff;
|
||||
border-color: #16a34a;
|
||||
}
|
||||
.wfm-btn-success:hover {
|
||||
background: #16a34a;
|
||||
border-color: #15803d;
|
||||
}
|
||||
.wfm-btn-success.active {
|
||||
background: #16a34a;
|
||||
border-color: #15803d;
|
||||
box-shadow: 0 0 0 2px rgba(34, 197, 94, 0.4);
|
||||
}
|
||||
|
||||
/* ── Batch Tab ──────────────────────────────────────────────────── */
|
||||
@@ -3909,7 +4452,36 @@ body {
|
||||
.wfm-batch-pane:last-child { border-right: none; }
|
||||
.wfm-batch-left { width: 240px; flex-shrink: 0; }
|
||||
.wfm-batch-center { flex: 1; }
|
||||
.wfm-batch-right { flex: 1.2; min-width: 320px; flex-shrink: 0; }
|
||||
.wfm-batch-right { flex: 1.5; min-width: 380px; flex-shrink: 0; }
|
||||
.wfm-batch-left-tab-nav {
|
||||
display: flex;
|
||||
border-bottom: 1px solid var(--wfm-border);
|
||||
flex-shrink: 0;
|
||||
}
|
||||
.wfm-batch-left-tab {
|
||||
flex: 1;
|
||||
padding: 5px 4px;
|
||||
font-size: 10px;
|
||||
background: transparent;
|
||||
border: none;
|
||||
color: var(--wfm-text-secondary);
|
||||
cursor: pointer;
|
||||
border-bottom: 2px solid transparent;
|
||||
margin-bottom: -1px;
|
||||
transition: color 0.15s;
|
||||
white-space: nowrap;
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
}
|
||||
.wfm-batch-left-tab:hover { color: var(--wfm-text-primary); background: var(--wfm-surface); }
|
||||
.wfm-batch-left-tab.active { color: var(--wfm-primary); border-bottom-color: var(--wfm-primary); }
|
||||
.wfm-batch-left-content {
|
||||
display: none;
|
||||
flex-direction: column;
|
||||
flex: 1;
|
||||
overflow: hidden;
|
||||
}
|
||||
.wfm-batch-left-content.active { display: flex; }
|
||||
.wfm-batch-pane-header {
|
||||
font-size: 11px;
|
||||
font-weight: 600;
|
||||
@@ -4577,7 +5149,7 @@ body {
|
||||
display: flex;
|
||||
}
|
||||
|
||||
/* 3-pane layout */
|
||||
/* 4-pane layout */
|
||||
.wfm-ai-pane {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
@@ -4585,8 +5157,9 @@ body {
|
||||
min-width: 0;
|
||||
}
|
||||
|
||||
.wfm-ai-pane-translate { flex: 4; }
|
||||
.wfm-ai-pane-tools { flex: 4; }
|
||||
.wfm-ai-pane-translate { flex: 3; }
|
||||
.wfm-ai-pane-chat { flex: 4; }
|
||||
.wfm-ai-pane-tools { flex: 3; }
|
||||
.wfm-ai-pane-settings { flex: 2; }
|
||||
|
||||
.wfm-ai-pane-header {
|
||||
@@ -4761,6 +5334,25 @@ body {
|
||||
margin-left: 4px;
|
||||
}
|
||||
|
||||
/* Wildcard inputs */
|
||||
.wfm-ai-wc-inputs {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 6px;
|
||||
flex-shrink: 0;
|
||||
}
|
||||
|
||||
.wfm-ai-wc-row {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 8px;
|
||||
}
|
||||
|
||||
.wfm-ai-wc-count {
|
||||
width: 70px;
|
||||
flex-shrink: 0;
|
||||
}
|
||||
|
||||
/* VLM Tab */
|
||||
.wfm-ai-vlm-container {
|
||||
display: flex;
|
||||
@@ -4830,3 +5422,81 @@ body {
|
||||
align-self: flex-end;
|
||||
flex-shrink: 0;
|
||||
}
|
||||
|
||||
/* Chat pane */
|
||||
.wfm-ai-chat-container {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
flex: 1;
|
||||
overflow: hidden;
|
||||
min-height: 0;
|
||||
padding: 8px;
|
||||
gap: 8px;
|
||||
}
|
||||
|
||||
.wfm-ai-chat-messages {
|
||||
flex: 1;
|
||||
overflow-y: auto;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 8px;
|
||||
min-height: 0;
|
||||
padding: 4px;
|
||||
}
|
||||
|
||||
.wfm-ai-chat-msg {
|
||||
max-width: 90%;
|
||||
padding: 8px 10px;
|
||||
border-radius: 8px;
|
||||
font-size: 13px;
|
||||
line-height: 1.5;
|
||||
word-break: break-word;
|
||||
white-space: pre-wrap;
|
||||
}
|
||||
|
||||
.wfm-ai-chat-msg-user {
|
||||
align-self: flex-end;
|
||||
background: var(--wfm-primary);
|
||||
color: #fff;
|
||||
}
|
||||
|
||||
.wfm-ai-chat-msg-assistant {
|
||||
align-self: flex-start;
|
||||
background: var(--wfm-surface);
|
||||
border: 1px solid var(--wfm-border);
|
||||
color: var(--wfm-text);
|
||||
}
|
||||
|
||||
.wfm-ai-chat-input-area {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 6px;
|
||||
flex-shrink: 0;
|
||||
}
|
||||
|
||||
.wfm-ai-chat-input {
|
||||
width: 100%;
|
||||
min-height: 60px;
|
||||
max-height: 120px;
|
||||
padding: 8px 10px;
|
||||
background: var(--wfm-bg);
|
||||
border: 1px solid var(--wfm-border);
|
||||
border-radius: var(--wfm-radius-sm);
|
||||
color: var(--wfm-text);
|
||||
font-size: 13px;
|
||||
font-family: inherit;
|
||||
resize: none;
|
||||
line-height: 1.5;
|
||||
box-sizing: border-box;
|
||||
}
|
||||
|
||||
.wfm-ai-chat-input:focus {
|
||||
outline: none;
|
||||
border-color: var(--wfm-primary);
|
||||
}
|
||||
|
||||
.wfm-ai-chat-actions {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 6px;
|
||||
}
|
||||
|
||||
@@ -0,0 +1,294 @@
|
||||
/* ============================================================
|
||||
Tagger Tab Styles
|
||||
============================================================ */
|
||||
|
||||
/* ── サブタブナビ ────────────────────────────────────────────── */
|
||||
|
||||
.wfm-tagger-subtab-nav {
|
||||
display: flex;
|
||||
gap: 0;
|
||||
border-bottom: 1px solid var(--wfm-border);
|
||||
background: var(--wfm-bg-secondary);
|
||||
flex-shrink: 0;
|
||||
}
|
||||
|
||||
.wfm-tagger-subtab-btn {
|
||||
padding: 8px 20px;
|
||||
font-size: 13px;
|
||||
font-weight: 500;
|
||||
background: transparent;
|
||||
border: none;
|
||||
border-bottom: 2px solid transparent;
|
||||
color: var(--wfm-text-secondary);
|
||||
cursor: pointer;
|
||||
transition: color 0.15s, border-color 0.15s;
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
.wfm-tagger-subtab-btn:hover {
|
||||
color: var(--wfm-text);
|
||||
}
|
||||
|
||||
.wfm-tagger-subtab-btn.active {
|
||||
color: var(--wfm-primary);
|
||||
border-bottom-color: var(--wfm-primary);
|
||||
}
|
||||
|
||||
/* ── サブタブ共通 ────────────────────────────────────────────── */
|
||||
|
||||
.wfm-tagger-subtab {
|
||||
flex: 1;
|
||||
overflow-y: auto;
|
||||
padding: 12px;
|
||||
}
|
||||
|
||||
/* ── セクション ─────────────────────────────────────────────── */
|
||||
|
||||
.wfm-tagger-section {
|
||||
background: var(--wfm-surface);
|
||||
border: 1px solid var(--wfm-border);
|
||||
border-radius: var(--wfm-radius);
|
||||
padding: 10px 12px;
|
||||
margin-bottom: 10px;
|
||||
}
|
||||
|
||||
.wfm-tagger-section-header {
|
||||
font-size: 12px;
|
||||
font-weight: 600;
|
||||
color: var(--wfm-text-secondary);
|
||||
text-transform: uppercase;
|
||||
letter-spacing: 0.05em;
|
||||
margin-bottom: 8px;
|
||||
}
|
||||
|
||||
/* ── フォームレイアウト ─────────────────────────────────────── */
|
||||
|
||||
.wfm-tagger-form-row {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 8px;
|
||||
margin-bottom: 6px;
|
||||
}
|
||||
|
||||
.wfm-tagger-form-row:last-child {
|
||||
margin-bottom: 0;
|
||||
}
|
||||
|
||||
.wfm-tagger-label {
|
||||
font-size: 12px;
|
||||
color: var(--wfm-text-secondary);
|
||||
min-width: 80px;
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
.wfm-tagger-select {
|
||||
flex: 1;
|
||||
min-width: 0;
|
||||
}
|
||||
|
||||
/* ── スライダー ─────────────────────────────────────────────── */
|
||||
|
||||
.wfm-tagger-slider {
|
||||
flex: 1;
|
||||
min-width: 0;
|
||||
accent-color: var(--wfm-primary);
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
.wfm-tagger-slider-val {
|
||||
font-size: 12px;
|
||||
color: var(--wfm-text-secondary);
|
||||
min-width: 36px;
|
||||
text-align: right;
|
||||
}
|
||||
|
||||
/* ── Single サブタブ ─────────────────────────────────────────── */
|
||||
|
||||
.wfm-tagger-single-layout {
|
||||
display: flex;
|
||||
gap: 12px;
|
||||
height: calc(100vh - var(--wfm-header-height, 96px) - 80px);
|
||||
min-height: 0;
|
||||
}
|
||||
|
||||
.wfm-tagger-image-pane {
|
||||
width: 300px;
|
||||
min-width: 240px;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 8px;
|
||||
flex-shrink: 0;
|
||||
}
|
||||
|
||||
.wfm-tagger-image-sources {
|
||||
display: flex;
|
||||
gap: 6px;
|
||||
flex-wrap: wrap;
|
||||
}
|
||||
|
||||
.wfm-tagger-preview-wrap {
|
||||
flex: 1;
|
||||
min-height: 0;
|
||||
background: var(--wfm-surface);
|
||||
border: 2px dashed var(--wfm-border);
|
||||
border-radius: var(--wfm-radius);
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
overflow: hidden;
|
||||
position: relative;
|
||||
transition: border-color 0.15s, background 0.15s;
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
.wfm-tagger-preview-wrap.drag-over {
|
||||
border-color: var(--wfm-primary);
|
||||
background: rgba(74, 158, 255, 0.08);
|
||||
}
|
||||
|
||||
.wfm-tagger-image-name {
|
||||
font-size: 11px;
|
||||
color: var(--wfm-text-secondary);
|
||||
text-align: center;
|
||||
word-break: break-all;
|
||||
min-height: 16px;
|
||||
}
|
||||
|
||||
.wfm-tagger-controls-pane {
|
||||
flex: 1;
|
||||
min-width: 0;
|
||||
overflow-y: auto;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 0;
|
||||
}
|
||||
|
||||
.wfm-tagger-result-actions {
|
||||
display: flex;
|
||||
gap: 6px;
|
||||
margin-top: 6px;
|
||||
flex-wrap: wrap;
|
||||
}
|
||||
|
||||
/* ── Batch サブタブ ──────────────────────────────────────────── */
|
||||
|
||||
.wfm-tagger-batch-layout {
|
||||
max-width: 900px;
|
||||
}
|
||||
|
||||
.wfm-tagger-batch-cols {
|
||||
display: grid;
|
||||
grid-template-columns: 1fr 1fr;
|
||||
gap: 10px;
|
||||
}
|
||||
|
||||
.wfm-tagger-progress-bar-wrap {
|
||||
height: 6px;
|
||||
background: var(--wfm-border);
|
||||
border-radius: 3px;
|
||||
overflow: hidden;
|
||||
}
|
||||
|
||||
.wfm-tagger-progress-bar {
|
||||
height: 100%;
|
||||
background: var(--wfm-primary);
|
||||
border-radius: 3px;
|
||||
transition: width 0.3s ease;
|
||||
}
|
||||
|
||||
/* ── DB サブタブ ─────────────────────────────────────────────── */
|
||||
|
||||
.wfm-tagger-db-layout {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
height: calc(100vh - var(--wfm-header-height, 96px) - 80px);
|
||||
min-height: 0;
|
||||
}
|
||||
|
||||
.wfm-tagger-db-toolbar {
|
||||
display: flex;
|
||||
gap: 6px;
|
||||
align-items: center;
|
||||
margin-bottom: 10px;
|
||||
flex-shrink: 0;
|
||||
}
|
||||
|
||||
.wfm-tagger-db-table-wrap {
|
||||
flex: 1;
|
||||
overflow: auto;
|
||||
border: 1px solid var(--wfm-border);
|
||||
border-radius: var(--wfm-radius);
|
||||
min-height: 0;
|
||||
}
|
||||
|
||||
.wfm-tagger-db-table {
|
||||
width: 100%;
|
||||
border-collapse: collapse;
|
||||
font-size: 12px;
|
||||
}
|
||||
|
||||
.wfm-tagger-db-table th,
|
||||
.wfm-tagger-db-table td {
|
||||
padding: 6px 10px;
|
||||
text-align: left;
|
||||
border-bottom: 1px solid var(--wfm-border);
|
||||
white-space: nowrap;
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
max-width: 220px;
|
||||
}
|
||||
|
||||
.wfm-tagger-db-table th {
|
||||
background: var(--wfm-bg-secondary);
|
||||
color: var(--wfm-text-secondary);
|
||||
font-weight: 600;
|
||||
text-transform: uppercase;
|
||||
font-size: 11px;
|
||||
letter-spacing: 0.04em;
|
||||
position: sticky;
|
||||
top: 0;
|
||||
z-index: 1;
|
||||
}
|
||||
|
||||
.wfm-tagger-db-table tbody tr {
|
||||
cursor: pointer;
|
||||
transition: background 0.1s;
|
||||
}
|
||||
|
||||
.wfm-tagger-db-table tbody tr:hover {
|
||||
background: var(--wfm-surface-hover);
|
||||
}
|
||||
|
||||
.wfm-tagger-db-table tbody tr.selected {
|
||||
background: rgba(74, 158, 255, 0.15);
|
||||
}
|
||||
|
||||
.wfm-tagger-db-edit-panel {
|
||||
flex-shrink: 0;
|
||||
margin-top: 10px;
|
||||
background: var(--wfm-surface);
|
||||
border: 1px solid var(--wfm-border);
|
||||
border-radius: var(--wfm-radius);
|
||||
padding: 10px 12px;
|
||||
}
|
||||
|
||||
/* ── ユーティリティ ─────────────────────────────────────────── */
|
||||
|
||||
#wfm-tab-tagger {
|
||||
display: none;
|
||||
flex-direction: column;
|
||||
height: calc(100vh - var(--wfm-header-height, 56px));
|
||||
overflow: hidden;
|
||||
}
|
||||
|
||||
#wfm-tab-tagger.active {
|
||||
display: flex;
|
||||
}
|
||||
|
||||
.wfm-placeholder {
|
||||
color: var(--wfm-text-secondary);
|
||||
font-size: 13px;
|
||||
text-align: center;
|
||||
padding: 20px;
|
||||
pointer-events: none;
|
||||
}
|
||||
+154
-12
@@ -5,6 +5,7 @@
|
||||
|
||||
import { showToast } from "./app.js";
|
||||
import { t } from "./i18n.js";
|
||||
import { readJsonStorage } from "./util.js";
|
||||
|
||||
const SETTINGS_KEY = "wfm_ai_settings";
|
||||
|
||||
@@ -19,11 +20,7 @@ const LANG_NAMES = {
|
||||
// ============================================
|
||||
|
||||
function loadAiSettings() {
|
||||
try {
|
||||
return JSON.parse(localStorage.getItem(SETTINGS_KEY) || "{}");
|
||||
} catch {
|
||||
return {};
|
||||
}
|
||||
return readJsonStorage(SETTINGS_KEY);
|
||||
}
|
||||
|
||||
function saveAiSettings(patch) {
|
||||
@@ -367,6 +364,111 @@ function initSettingsTab() {
|
||||
}
|
||||
}
|
||||
|
||||
// ============================================
|
||||
// Chat tab
|
||||
// ============================================
|
||||
|
||||
async function callChat(url, backend, model, messages) {
|
||||
if (backend === "ollama") {
|
||||
const res = await fetch(`${url}/api/chat`, {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify({ model, messages, stream: false }),
|
||||
});
|
||||
if (!res.ok) throw new Error(`HTTP ${res.status}`);
|
||||
return (await res.json()).message?.content || "";
|
||||
} else {
|
||||
const res = await fetch(`${url}/v1/chat/completions`, {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify({ model, messages, stream: false }),
|
||||
});
|
||||
if (!res.ok) throw new Error(`HTTP ${res.status}`);
|
||||
return (await res.json()).choices?.[0]?.message?.content || "";
|
||||
}
|
||||
}
|
||||
|
||||
function appendChatBubble(messagesEl, role, content) {
|
||||
const div = document.createElement("div");
|
||||
div.className = `wfm-ai-chat-msg wfm-ai-chat-msg-${role}`;
|
||||
div.textContent = content;
|
||||
messagesEl.appendChild(div);
|
||||
messagesEl.scrollTop = messagesEl.scrollHeight;
|
||||
return div;
|
||||
}
|
||||
|
||||
function initChatTab() {
|
||||
const messagesEl = document.getElementById("wfm-ai-chat-messages");
|
||||
const inputEl = document.getElementById("wfm-ai-chat-input");
|
||||
const sendBtn = document.getElementById("wfm-ai-chat-send-btn");
|
||||
const clearBtn = document.getElementById("wfm-ai-chat-clear-btn");
|
||||
const statusEl = document.getElementById("wfm-ai-chat-status");
|
||||
|
||||
if (!messagesEl || !inputEl || !sendBtn) return;
|
||||
|
||||
let chatHistory = [];
|
||||
|
||||
async function sendMessage() {
|
||||
const text = inputEl.value.trim();
|
||||
if (!text) return;
|
||||
|
||||
const settings = loadAiSettings();
|
||||
const { backend = "ollama", backendUrl, model } = settings;
|
||||
const url = backendUrl || (backend === "ollama" ? "http://localhost:11434" : "http://localhost:1234");
|
||||
|
||||
if (!isValidBackendUrl(url)) {
|
||||
showToast(t("aiToastInvalidUrl"), "error");
|
||||
return;
|
||||
}
|
||||
if (!model) {
|
||||
showToast(t("aiToastNoModel"), "error");
|
||||
return;
|
||||
}
|
||||
|
||||
inputEl.value = "";
|
||||
inputEl.style.height = "";
|
||||
chatHistory.push({ role: "user", content: text });
|
||||
appendChatBubble(messagesEl, "user", text);
|
||||
|
||||
sendBtn.disabled = true;
|
||||
statusEl.textContent = t("aiStatusChatting");
|
||||
statusEl.className = "wfm-ai-trans-status wfm-ai-status-working";
|
||||
|
||||
try {
|
||||
const reply = await callChat(url, backend, model, chatHistory);
|
||||
chatHistory.push({ role: "assistant", content: reply });
|
||||
appendChatBubble(messagesEl, "assistant", reply);
|
||||
statusEl.textContent = "";
|
||||
statusEl.className = "wfm-ai-trans-status";
|
||||
} catch (err) {
|
||||
chatHistory.pop();
|
||||
if (messagesEl.lastChild) messagesEl.removeChild(messagesEl.lastChild);
|
||||
inputEl.value = text;
|
||||
statusEl.textContent = `${t("aiStatusConnectFail")}${err.message}`;
|
||||
statusEl.className = "wfm-ai-trans-status wfm-ai-status-error";
|
||||
showToast(t("aiToastChatFailed") + err.message, "error");
|
||||
} finally {
|
||||
sendBtn.disabled = false;
|
||||
}
|
||||
}
|
||||
|
||||
sendBtn.addEventListener("click", sendMessage);
|
||||
|
||||
inputEl.addEventListener("keydown", (e) => {
|
||||
if (e.key === "Enter" && !e.shiftKey) {
|
||||
e.preventDefault();
|
||||
sendMessage();
|
||||
}
|
||||
});
|
||||
|
||||
clearBtn.addEventListener("click", () => {
|
||||
chatHistory = [];
|
||||
messagesEl.innerHTML = "";
|
||||
statusEl.textContent = "";
|
||||
statusEl.className = "wfm-ai-trans-status";
|
||||
});
|
||||
}
|
||||
|
||||
// ============================================
|
||||
// VLM tab
|
||||
// ============================================
|
||||
@@ -381,11 +483,22 @@ function initVlmTab() {
|
||||
const statusEl = document.getElementById("wfm-ai-vlm-status");
|
||||
const resultEl = document.getElementById("wfm-ai-vlm-result");
|
||||
const copyBtn = document.getElementById("wfm-ai-vlm-copy");
|
||||
const wcInputs = document.getElementById("wfm-ai-wc-inputs");
|
||||
const wcNameEl = document.getElementById("wfm-ai-wc-name");
|
||||
const wcCountEl = document.getElementById("wfm-ai-wc-count");
|
||||
|
||||
if (!dropEl) return;
|
||||
|
||||
let vlmImage = null; // { base64, mimeType }
|
||||
|
||||
function updateTaskUI() {
|
||||
const isWildcard = taskSel?.value === "wildcard";
|
||||
dropEl.style.display = isWildcard ? "none" : "";
|
||||
if (wcInputs) wcInputs.style.display = isWildcard ? "" : "none";
|
||||
}
|
||||
taskSel?.addEventListener("change", updateTaskUI);
|
||||
updateTaskUI();
|
||||
|
||||
const loadImage = async (file) => {
|
||||
if (!file || !file.type.startsWith("image/")) return;
|
||||
vlmImage = await fileToBase64(file);
|
||||
@@ -405,19 +518,47 @@ function initVlmTab() {
|
||||
});
|
||||
|
||||
runBtn.addEventListener("click", async () => {
|
||||
if (!vlmImage) { showToast(t("aiToastNoImage"), "error"); return; }
|
||||
|
||||
const task = taskSel?.value || "describe";
|
||||
const settings = loadAiSettings();
|
||||
const { backend = "ollama", backendUrl, model } = settings;
|
||||
const url = backendUrl || (backend === "ollama" ? "http://localhost:11434" : "http://localhost:1234");
|
||||
|
||||
if (!isValidBackendUrl(url)) {
|
||||
showToast(t("aiToastInvalidUrl"), "error");
|
||||
return;
|
||||
}
|
||||
if (!isValidBackendUrl(url)) { showToast(t("aiToastInvalidUrl"), "error"); return; }
|
||||
if (!model) { showToast(t("aiToastNoModel"), "error"); return; }
|
||||
|
||||
const task = taskSel?.value || "describe";
|
||||
if (task === "wildcard") {
|
||||
const name = wcNameEl?.value.trim() || "";
|
||||
const count = Math.max(1, parseInt(wcCountEl?.value) || 20);
|
||||
if (!name) { showToast(t("aiToastWcNoName"), "error"); return; }
|
||||
|
||||
runBtn.disabled = true;
|
||||
statusEl.textContent = t("aiStatusRunning");
|
||||
statusEl.className = "wfm-ai-trans-status wfm-ai-status-working";
|
||||
resultEl.value = "";
|
||||
|
||||
const prompt = `Generate ${count} wildcard entries for the category "${name}". Output only plain text in English, one entry per line, no numbers, no markdown, no asterisks, no bold, nothing else.`;
|
||||
|
||||
try {
|
||||
const result = await callLLM(url, backend, model, prompt);
|
||||
resultEl.value = result.trim()
|
||||
.split("\n")
|
||||
.map(l => l.replace(/\*\*/g, "").replace(/^\*\s*/, "").replace(/^\d+\.\s*/, "").trim())
|
||||
.filter(l => l.length > 0)
|
||||
.join("\n");
|
||||
statusEl.textContent = t("aiStatusDone");
|
||||
statusEl.className = "wfm-ai-trans-status wfm-ai-status-ok";
|
||||
} catch (err) {
|
||||
statusEl.textContent = `${t("aiStatusConnectFail")}${err.message}`;
|
||||
statusEl.className = "wfm-ai-trans-status wfm-ai-status-error";
|
||||
showToast(t("aiToastVlmFailed") + err.message, "error");
|
||||
} finally {
|
||||
runBtn.disabled = false;
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
if (!vlmImage) { showToast(t("aiToastNoImage"), "error"); return; }
|
||||
|
||||
runBtn.disabled = true;
|
||||
statusEl.textContent = t("aiStatusRunning");
|
||||
statusEl.className = "wfm-ai-trans-status wfm-ai-status-working";
|
||||
@@ -450,6 +591,7 @@ function initVlmTab() {
|
||||
|
||||
export function initAiTab() {
|
||||
initTranslateTab();
|
||||
initChatTab();
|
||||
initVlmTab();
|
||||
initSettingsTab();
|
||||
}
|
||||
|
||||
+98
-11
@@ -4,6 +4,7 @@
|
||||
*/
|
||||
|
||||
import { initI18n, t } from "./i18n.js";
|
||||
import { getSettings } from "./util.js";
|
||||
|
||||
// Initialize i18n before anything else
|
||||
initI18n();
|
||||
@@ -90,7 +91,7 @@ function initTabs() {
|
||||
|
||||
function applyI18nToHtml() {
|
||||
// Tab labels
|
||||
const tabMap = { workflow: "tabWorkflow", nodes: "tabNodes", models: "tabModels", generate: "tabGenerate", prompt: "tabPrompt", metadata: "tabMetadata", gallery: "tabGallery", settings: "tabSettings", help: "tabHelp", ai: "tabAi" };
|
||||
const tabMap = { workflow: "tabWorkflow", nodes: "tabNodes", models: "tabModels", generate: "tabGenerate", prompt: "tabPrompt", metadata: "tabMetadata", gallery: "tabGallery", settings: "tabSettings", help: "tabHelp", ai: "tabAi", tagger: "tabTagger" };
|
||||
document.querySelectorAll(".wfm-tab").forEach((tab) => {
|
||||
const key = tabMap[tab.dataset.tab];
|
||||
if (key) tab.textContent = t(key);
|
||||
@@ -114,7 +115,7 @@ function applyI18nToHtml() {
|
||||
|
||||
const listOpenComfyBtn = document.getElementById("wfm-list-open-comfyui-btn");
|
||||
if (listOpenComfyBtn) {
|
||||
listOpenComfyBtn.textContent = t("openInComfyUI");
|
||||
listOpenComfyBtn.textContent = t("sendToCanvas");
|
||||
if (listOpenComfyBtn.disabled) listOpenComfyBtn.title = t("selectCardFirst");
|
||||
}
|
||||
|
||||
@@ -195,6 +196,29 @@ function applyI18nToHtml() {
|
||||
if (btn.dataset.detailTab === "meta") btn.textContent = t("gallerySideMetadata");
|
||||
if (btn.dataset.detailTab === "group") btn.textContent = t("modelsSideGroup");
|
||||
});
|
||||
const galleryBulkDeselect = document.getElementById("wfm-gallery-bulk-deselect");
|
||||
if (galleryBulkDeselect) galleryBulkDeselect.textContent = t("galleryBulkDeselectAll");
|
||||
const galleryBulkSelectAll = document.getElementById("wfm-gallery-bulk-select-all");
|
||||
if (galleryBulkSelectAll) galleryBulkSelectAll.textContent = t("galleryBulkSelectAll");
|
||||
const galleryBulkGroupSelect = document.getElementById("wfm-gallery-bulk-group-select");
|
||||
if (galleryBulkGroupSelect) {
|
||||
const opt = galleryBulkGroupSelect.querySelector("option[value='']");
|
||||
if (opt) opt.textContent = t("galleryBulkAddToGroup");
|
||||
}
|
||||
const galleryBulkGroupAdd = document.getElementById("wfm-gallery-bulk-group-add");
|
||||
if (galleryBulkGroupAdd) galleryBulkGroupAdd.textContent = t("galleryBulkAdd");
|
||||
const galleryBulkGroupRemove = document.getElementById("wfm-gallery-bulk-group-remove");
|
||||
if (galleryBulkGroupRemove) galleryBulkGroupRemove.textContent = t("galleryBulkGroupRemove");
|
||||
const galleryBulkFav = document.getElementById("wfm-gallery-bulk-fav");
|
||||
if (galleryBulkFav) galleryBulkFav.textContent = t("galleryBulkFavAll");
|
||||
const galleryBulkUnfav = document.getElementById("wfm-gallery-bulk-unfav");
|
||||
if (galleryBulkUnfav) galleryBulkUnfav.textContent = t("galleryBulkUnfavAll");
|
||||
const galleryBulkMove = document.getElementById("wfm-gallery-bulk-move");
|
||||
if (galleryBulkMove) galleryBulkMove.textContent = t("galleryBulkMoveTo");
|
||||
const galleryBulkDelete = document.getElementById("wfm-gallery-bulk-delete");
|
||||
if (galleryBulkDelete) galleryBulkDelete.textContent = t("galleryBulkDelete");
|
||||
const galleryOpenTaggerBtn = document.getElementById("wfm-gallery-open-tagger-btn");
|
||||
if (galleryOpenTaggerBtn) galleryOpenTaggerBtn.textContent = t("tabTagger");
|
||||
|
||||
// Prompt tab
|
||||
const assistantHeader = document.querySelector(".wfm-prompt-split-left .wfm-prompt-split-header");
|
||||
@@ -328,13 +352,21 @@ function applyI18nToHtml() {
|
||||
"wfm-help-gen-8": "helpGen8", "wfm-help-gen-9": "helpGen9", "wfm-help-gen-10": "helpGen10",
|
||||
"wfm-help-gen-11": "helpGen11", "wfm-help-gen-12": "helpGen12",
|
||||
"wfm-help-gen-13": "helpGen13", "wfm-help-gen-14": "helpGen14",
|
||||
"wfm-help-gen-15": "helpGen15",
|
||||
"wfm-help-feeder-title": "helpFeederTitle",
|
||||
"wfm-help-feeder-desc": "helpFeederDesc",
|
||||
"wfm-help-feeder-imgloop-title": "helpFeederImgloopTitle",
|
||||
"wfm-help-feeder-imgloop-desc": "helpFeederImgloopDesc",
|
||||
"wfm-help-feeder-1": "helpFeeder1", "wfm-help-feeder-2": "helpFeeder2",
|
||||
"wfm-help-feeder-3": "helpFeeder3", "wfm-help-feeder-4": "helpFeeder4",
|
||||
"wfm-help-feeder-5": "helpFeeder5", "wfm-help-feeder-6": "helpFeeder6",
|
||||
"wfm-help-feeder-7": "helpFeeder7", "wfm-help-feeder-8": "helpFeeder8",
|
||||
"wfm-help-feeder-9": "helpFeeder9",
|
||||
"wfm-help-feeder-gal-title": "helpFeederGalTitle",
|
||||
"wfm-help-feeder-gal-desc": "helpFeederGalDesc",
|
||||
"wfm-help-feeder-gal-1": "helpFeederGal1", "wfm-help-feeder-gal-2": "helpFeederGal2",
|
||||
"wfm-help-feeder-gal-3": "helpFeederGal3", "wfm-help-feeder-gal-4": "helpFeederGal4",
|
||||
"wfm-help-feeder-gal-5": "helpFeederGal5", "wfm-help-feeder-gal-6": "helpFeederGal6",
|
||||
"wfm-help-prompt-1": "helpPrompt1", "wfm-help-prompt-2": "helpPrompt2",
|
||||
"wfm-help-prompt-3": "helpPrompt3", "wfm-help-prompt-4": "helpPrompt4",
|
||||
"wfm-help-prompt-5": "helpPrompt5", "wfm-help-prompt-6": "helpPrompt6",
|
||||
@@ -355,14 +387,21 @@ function applyI18nToHtml() {
|
||||
"wfm-help-models-5": "helpModels5", "wfm-help-models-6": "helpModels6",
|
||||
"wfm-help-models-7": "helpModels7", "wfm-help-models-8": "helpModels8",
|
||||
"wfm-help-models-9": "helpModels9", "wfm-help-models-10": "helpModels10",
|
||||
"wfm-help-models-11": "helpModels11",
|
||||
"wfm-help-models-11": "helpModels11", "wfm-help-models-12": "helpModels12",
|
||||
"wfm-help-gallery-title": "helpGalleryTitle",
|
||||
"wfm-help-gallery-1": "helpGallery1", "wfm-help-gallery-2": "helpGallery2",
|
||||
"wfm-help-gallery-3": "helpGallery3", "wfm-help-gallery-4": "helpGallery4",
|
||||
"wfm-help-gallery-5": "helpGallery5", "wfm-help-gallery-6": "helpGallery6",
|
||||
"wfm-help-gallery-7": "helpGallery7", "wfm-help-gallery-8": "helpGallery8",
|
||||
"wfm-help-gallery-9": "helpGallery9", "wfm-help-gallery-10": "helpGallery10",
|
||||
"wfm-help-gallery-11": "helpGallery11",
|
||||
"wfm-help-gallery-11": "helpGallery11", "wfm-help-gallery-12": "helpGallery12",
|
||||
"wfm-help-gallery-13": "helpGallery13", "wfm-help-gallery-14": "helpGallery14",
|
||||
"wfm-help-tagger-title": "helpTaggerTitle",
|
||||
"wfm-help-tagger-1": "helpTagger1", "wfm-help-tagger-2": "helpTagger2",
|
||||
"wfm-help-tagger-3": "helpTagger3", "wfm-help-tagger-4": "helpTagger4",
|
||||
"wfm-help-tagger-5": "helpTagger5", "wfm-help-tagger-6": "helpTagger6",
|
||||
"wfm-help-tagger-7": "helpTagger7", "wfm-help-tagger-8": "helpTagger8",
|
||||
"wfm-help-tagger-9": "helpTagger9",
|
||||
"wfm-help-sidepanel-title": "helpSidepanelTitle",
|
||||
"wfm-help-sidepanel-1": "helpSidepanel1", "wfm-help-sidepanel-2": "helpSidepanel2",
|
||||
"wfm-help-sidepanel-3": "helpSidepanel3", "wfm-help-sidepanel-4": "helpSidepanel4",
|
||||
@@ -373,6 +412,7 @@ function applyI18nToHtml() {
|
||||
"wfm-help-sidepanel-13": "helpSidepanel13",
|
||||
"wfm-help-sidepanel-14": "helpSidepanel14", "wfm-help-sidepanel-15": "helpSidepanel15",
|
||||
"wfm-help-sidepanel-16": "helpSidepanel16",
|
||||
"wfm-help-sidepanel-17": "helpSidepanel17",
|
||||
"wfm-help-ai-title": "helpAiTitle",
|
||||
"wfm-help-ai-1": "helpAi1", "wfm-help-ai-2": "helpAi2", "wfm-help-ai-3": "helpAi3",
|
||||
"wfm-help-ai-4": "helpAi4", "wfm-help-ai-5": "helpAi5", "wfm-help-ai-6": "helpAi6",
|
||||
@@ -382,6 +422,8 @@ function applyI18nToHtml() {
|
||||
"wfm-help-trouble-title": "helpTroubleTitle",
|
||||
"wfm-help-trouble-1": "helpTrouble1", "wfm-help-trouble-2": "helpTrouble2",
|
||||
"wfm-help-trouble-3": "helpTrouble3", "wfm-help-trouble-4": "helpTrouble4",
|
||||
"wfm-help-trouble-5": "helpTrouble5", "wfm-help-trouble-6": "helpTrouble6",
|
||||
"wfm-help-trouble-7": "helpTrouble7",
|
||||
"wfm-help-support-title": "helpSupportTitle",
|
||||
"wfm-help-support-desc": "helpSupportDesc",
|
||||
"wfm-help-github-desc": "helpGithubDesc",
|
||||
@@ -392,6 +434,41 @@ function applyI18nToHtml() {
|
||||
const el = document.getElementById(id);
|
||||
if (el) el.textContent = t(key);
|
||||
}
|
||||
|
||||
// Search box placeholder
|
||||
const helpSearch = document.getElementById("wfm-help-search");
|
||||
if (helpSearch) {
|
||||
helpSearch.placeholder = t("helpSearchPlaceholder");
|
||||
helpSearch.addEventListener("input", _onHelpSearch);
|
||||
}
|
||||
}
|
||||
|
||||
function _onHelpSearch(e) {
|
||||
const q = e.target.value.trim().toLowerCase();
|
||||
const navItems = document.querySelectorAll("[data-help-page]");
|
||||
if (!q) {
|
||||
navItems.forEach(btn => btn.classList.remove("search-hidden"));
|
||||
return;
|
||||
}
|
||||
|
||||
const matchedPages = new Set();
|
||||
document.querySelectorAll(".wfm-help-page").forEach(page => {
|
||||
const pageId = page.id.replace("wfm-help-page-", "");
|
||||
if (page.textContent.toLowerCase().includes(q)) matchedPages.add(pageId);
|
||||
});
|
||||
|
||||
let firstBtn = null;
|
||||
navItems.forEach(btn => {
|
||||
const pageId = btn.dataset.helpPage;
|
||||
if (matchedPages.has(pageId)) {
|
||||
btn.classList.remove("search-hidden");
|
||||
if (!firstBtn) firstBtn = btn;
|
||||
} else {
|
||||
btn.classList.add("search-hidden");
|
||||
}
|
||||
});
|
||||
|
||||
if (firstBtn && !firstBtn.classList.contains("active")) firstBtn.click();
|
||||
}
|
||||
|
||||
// ============================================
|
||||
@@ -434,26 +511,35 @@ import { initModelsTab } from "./models-tab.js";
|
||||
import { initGalleryTab } from "./gallery-tab.js";
|
||||
import { initMetadataTab } from "./metadata-tab.js";
|
||||
import { initAiTab } from "./ai-tab.js";
|
||||
import { initTaggerTab } from "./tagger-tab.js";
|
||||
|
||||
// Apply saved theme immediately to prevent flash of default theme
|
||||
applyTheme(getSavedTheme());
|
||||
|
||||
// Apply saved textarea font size
|
||||
// Apply saved textarea font size & JSON highlight colors
|
||||
try {
|
||||
const _s = JSON.parse(localStorage.getItem("wfm_settings") || "{}");
|
||||
const _s = getSettings();
|
||||
if (_s.textareaFontSize) applyTextareaFontSize(_s.textareaFontSize);
|
||||
} catch {}
|
||||
|
||||
// Apply saved JSON highlight colors
|
||||
try {
|
||||
const _s = JSON.parse(localStorage.getItem("wfm_settings") || "{}");
|
||||
applyJsonColors(_s.jsonColors);
|
||||
} catch {}
|
||||
|
||||
function initHelpTab() {
|
||||
document.querySelectorAll(".wfm-help-nav-item").forEach((btn) => {
|
||||
btn.addEventListener("click", () => {
|
||||
const page = btn.dataset.helpPage;
|
||||
document.querySelectorAll(".wfm-help-nav-item").forEach((b) => b.classList.remove("active"));
|
||||
btn.classList.add("active");
|
||||
document.querySelectorAll(".wfm-help-page").forEach((p) => p.classList.remove("active"));
|
||||
document.getElementById(`wfm-help-page-${page}`)?.classList.add("active");
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
document.addEventListener("DOMContentLoaded", () => {
|
||||
applyI18nToHtml();
|
||||
initTabs();
|
||||
initModal();
|
||||
initHelpTab();
|
||||
initSettingsTab(); // Settings first (applies saved URL)
|
||||
initWorkflowTab();
|
||||
initNodesTab();
|
||||
@@ -463,6 +549,7 @@ document.addEventListener("DOMContentLoaded", () => {
|
||||
initMetadataTab();
|
||||
initGalleryTab();
|
||||
initAiTab();
|
||||
initTaggerTab();
|
||||
|
||||
console.log("Workflow Studio: App initialized");
|
||||
});
|
||||
|
||||
@@ -168,14 +168,16 @@ export const comfyUI = {
|
||||
},
|
||||
|
||||
// Generation
|
||||
async queuePrompt(workflow) {
|
||||
async queuePrompt(workflow, extraData = null) {
|
||||
const body = {
|
||||
prompt: workflow,
|
||||
client_id: this.clientId,
|
||||
};
|
||||
if (extraData) body.extra_data = extraData;
|
||||
const res = await fetch(`${this.baseUrl}/prompt`, {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify({
|
||||
prompt: workflow,
|
||||
client_id: this.clientId,
|
||||
}),
|
||||
body: JSON.stringify(body),
|
||||
});
|
||||
if (!res.ok) {
|
||||
const err = await res.json().catch(() => ({}));
|
||||
@@ -275,8 +277,8 @@ export const comfyUI = {
|
||||
throw new Error("Failed to connect WebSocket");
|
||||
}
|
||||
|
||||
// Queue prompt
|
||||
const result = await this.queuePrompt(workflow);
|
||||
// Queue prompt — pass workflow as extra_pnginfo so SaveImage embeds it in PNG metadata
|
||||
const result = await this.queuePrompt(workflow, { extra_pnginfo: { workflow } });
|
||||
this.currentPromptId = result.prompt_id;
|
||||
|
||||
// Track progress
|
||||
|
||||
+521
-17
@@ -5,6 +5,105 @@
|
||||
import { comfyUI } from "./comfyui-client.js";
|
||||
import { syncJsonHighlight } from "./json-highlight.js";
|
||||
|
||||
// ── LoRA pane stack state ─────────────────────────────────
|
||||
// { modelFullPath: { m: number, c: number } }
|
||||
let _stackStrengths = {};
|
||||
// { modelFullPath: boolean } — true = active (default)
|
||||
let _stackActive = {};
|
||||
|
||||
function _loraBasename(fullPath) {
|
||||
const name = (fullPath || "").replace(/\\/g, "/").split("/").pop() || fullPath;
|
||||
return name.replace(/\.[^.]+$/, "");
|
||||
}
|
||||
|
||||
function _buildLoraSyntax(stackModels) {
|
||||
return stackModels
|
||||
.filter((m) => _stackActive[m] !== false)
|
||||
.map((m) => {
|
||||
const stem = _loraBasename(m);
|
||||
const str = (_stackStrengths[m]?.m ?? 1.0).toFixed(2).replace(/\.?0+$/, "") || "1";
|
||||
return `<lora:${stem}:${str}>`;
|
||||
})
|
||||
.join(", ");
|
||||
}
|
||||
|
||||
function _buildLoraManagerSyntax(stackModels) {
|
||||
return stackModels
|
||||
.filter((m) => _stackActive[m] !== false)
|
||||
.map((m) => {
|
||||
const stem = _loraBasename(m);
|
||||
const strM = (_stackStrengths[m]?.m ?? 1.0).toFixed(2).replace(/\.?0+$/, "") || "1";
|
||||
const strC = (_stackStrengths[m]?.c ?? 1.0).toFixed(2).replace(/\.?0+$/, "") || "1";
|
||||
return `<lora:${stem}:${strM}:${strC}>`;
|
||||
})
|
||||
.join(" ");
|
||||
}
|
||||
|
||||
function _applyLoraToNode(nodeId, loraPath, strModel, strClip, isLoraManager) {
|
||||
if (isLoraManager) {
|
||||
const stem = _loraBasename(loraPath);
|
||||
comfyUI.currentWorkflow[nodeId].inputs.loras = {
|
||||
__value__: [{ name: stem, strength: strModel, active: true, expanded: false, clipStrength: strClip, locked: false }],
|
||||
};
|
||||
comfyUI.currentWorkflow[nodeId].inputs.text = `<lora:${stem}:${strModel}:${strClip}>`;
|
||||
} else {
|
||||
comfyUI.currentWorkflow[nodeId].inputs.lora_name = loraPath;
|
||||
comfyUI.currentWorkflow[nodeId].inputs.strength_model = strModel;
|
||||
comfyUI.currentWorkflow[nodeId].inputs.strength_clip = strClip;
|
||||
}
|
||||
}
|
||||
|
||||
function _refreshLoraPaneDynamic(stackModels, metadata, civitaiCache) {
|
||||
const syntaxEl = document.getElementById("wfm-lora-stack-syntax");
|
||||
if (syntaxEl) syntaxEl.textContent = _buildLoraSyntax(stackModels) || "—";
|
||||
|
||||
const triggersEl = document.getElementById("wfm-lora-stack-triggers");
|
||||
if (triggersEl && metadata && civitaiCache) {
|
||||
const activeWords = [];
|
||||
stackModels.forEach((m) => {
|
||||
if (_stackActive[m] === false) return;
|
||||
const sha = (metadata[m] || {}).sha256;
|
||||
const civInfo = sha && civitaiCache[sha];
|
||||
if (civInfo?.trainedWords?.length) activeWords.push(...civInfo.trainedWords);
|
||||
});
|
||||
triggersEl.innerHTML = activeWords.length
|
||||
? activeWords.map((w) => `<span class="wfm-lora-trigger-word">${w}</span>`).join(" ")
|
||||
: `<span style="color:var(--wfm-text-secondary);font-size:12px;">—</span>`;
|
||||
}
|
||||
}
|
||||
|
||||
function _refreshLoraSingleDynamic(metadata, civitaiCache) {
|
||||
const modelName = document.getElementById("wfm-lora-select")?.value;
|
||||
const syntaxEl = document.getElementById("wfm-lora-single-syntax");
|
||||
const triggersEl = document.getElementById("wfm-lora-single-triggers");
|
||||
if (!modelName) {
|
||||
if (syntaxEl) syntaxEl.textContent = "—";
|
||||
if (triggersEl) triggersEl.innerHTML = `<span style="color:var(--wfm-text-secondary);font-size:12px;">—</span>`;
|
||||
return;
|
||||
}
|
||||
const stem = _loraBasename(modelName);
|
||||
const strM = parseFloat(document.getElementById("wfm-lora-str-model")?.value) || 1.0;
|
||||
const strC = parseFloat(document.getElementById("wfm-lora-str-clip")?.value) || 1.0;
|
||||
if (syntaxEl) syntaxEl.textContent = `<lora:${stem}:${strM}:${strC}>`;
|
||||
if (triggersEl) {
|
||||
const sha = (metadata[modelName] || {}).sha256;
|
||||
const civInfo = sha && civitaiCache[sha];
|
||||
const words = civInfo?.trainedWords || [];
|
||||
triggersEl.innerHTML = words.length
|
||||
? words.map(w => `<span class="wfm-lora-trigger-word">${w}</span>`).join(" ")
|
||||
: `<span style="color:var(--wfm-text-secondary);font-size:12px;">—</span>`;
|
||||
}
|
||||
}
|
||||
|
||||
function _syncStackToggleAll(stackModels) {
|
||||
const cb = document.getElementById("wfm-lora-stack-toggle-all");
|
||||
if (!cb) return;
|
||||
const allOn = stackModels.every((m) => _stackActive[m] !== false);
|
||||
const allOff = stackModels.every((m) => _stackActive[m] === false);
|
||||
cb.checked = allOn;
|
||||
cb.indeterminate = !allOn && !allOff;
|
||||
}
|
||||
|
||||
/** Sync comfyUI.currentWorkflow to Raw JSON textarea + highlight */
|
||||
function _syncRawJson() {
|
||||
const rawTextarea = document.getElementById("wfm-gen-raw-json");
|
||||
@@ -60,6 +159,7 @@ export const comfyEditor = {
|
||||
this.renderPromptTab(analysis, "wfm-gen-prompt-fields");
|
||||
this.renderImageTab(analysis, "wfm-gen-image-fields");
|
||||
this.renderModelTab(analysis, "wfm-gen-model-fields");
|
||||
this.renderLoraPane(analysis, "wfm-gen-lora-fields"); // async, fires independently
|
||||
this.renderSettingsTab(analysis, "wfm-gen-settings-fields");
|
||||
_syncRawJson();
|
||||
},
|
||||
@@ -82,7 +182,7 @@ export const comfyEditor = {
|
||||
</select>
|
||||
<button class="wfm-btn wfm-btn-sm" id="wfm-prompt-pos-apply">Apply</button>
|
||||
</div>
|
||||
<textarea class="wfm-textarea" id="wfm-prompt-pos-text" rows="4">${positiveNodes[0]?.text || ""}</textarea>
|
||||
<textarea class="wfm-textarea" id="wfm-prompt-pos-text" rows="8">${positiveNodes[0]?.text || ""}</textarea>
|
||||
</div>
|
||||
<div class="wfm-form-group">
|
||||
<label>Negative Prompt</label>
|
||||
@@ -93,7 +193,7 @@ export const comfyEditor = {
|
||||
</select>
|
||||
<button class="wfm-btn wfm-btn-sm" id="wfm-prompt-neg-apply">Apply</button>
|
||||
</div>
|
||||
<textarea class="wfm-textarea" id="wfm-prompt-neg-text" rows="3">${negativeNodes[0]?.text || ""}</textarea>
|
||||
<textarea class="wfm-textarea" id="wfm-prompt-neg-text" rows="6">${negativeNodes[0]?.text || ""}</textarea>
|
||||
</div>
|
||||
`;
|
||||
|
||||
@@ -127,7 +227,6 @@ export const comfyEditor = {
|
||||
const sections = [
|
||||
{ label: "Checkpoint", key: "checkpoints", nodes: analysis.checkpoint_nodes, inputKey: "ckpt_name" },
|
||||
{ label: "VAE", key: "vaes", nodes: analysis.vae_nodes, inputKey: "vae_name" },
|
||||
{ label: "LoRA", key: "loras", nodes: analysis.lora_nodes, inputKey: "lora_name" },
|
||||
{ label: "Diffusion Model", key: "diffusionModels", nodes: analysis.diffusion_model_nodes, inputKey: "unet_name" },
|
||||
{ label: "Text Encoder", key: "textEncoders", nodes: analysis.text_encoder_nodes, inputKey: "clip_name1" },
|
||||
{ label: "ControlNet", key: "controlNets", nodes: analysis.controlnet_nodes, inputKey: "control_net_name" },
|
||||
@@ -152,13 +251,6 @@ export const comfyEditor = {
|
||||
<select class="wfm-select" id="wfm-model-${s.key}-target" style="flex:1;">${targetOpts}</select>
|
||||
<button class="wfm-btn wfm-btn-sm wfm-model-apply" data-key="${s.key}" data-input="${s.inputKey}">Apply</button>
|
||||
</div>
|
||||
${s.key === "loras" ? `
|
||||
<div style="display:flex;gap:8px;margin-top:6px;align-items:center;">
|
||||
<label style="font-size:12px;">Strength M:</label>
|
||||
<input type="number" class="wfm-input" id="wfm-lora-str-model" value="1.0" step="0.1" min="0" max="2" style="width:70px;">
|
||||
<label style="font-size:12px;">C:</label>
|
||||
<input type="number" class="wfm-input" id="wfm-lora-str-clip" value="1.0" step="0.1" min="0" max="2" style="width:70px;">
|
||||
</div>` : ""}
|
||||
</div>
|
||||
`;
|
||||
})
|
||||
@@ -192,19 +284,400 @@ export const comfyEditor = {
|
||||
const nodeId = targetSelect.value;
|
||||
if (nodeId && comfyUI.currentWorkflow?.[nodeId]) {
|
||||
comfyUI.currentWorkflow[nodeId].inputs[inputKey] = value;
|
||||
// Apply LoRA strengths
|
||||
if (key === "loras") {
|
||||
const strModel = parseFloat(document.getElementById("wfm-lora-str-model")?.value) || 1.0;
|
||||
const strClip = parseFloat(document.getElementById("wfm-lora-str-clip")?.value) || 1.0;
|
||||
comfyUI.currentWorkflow[nodeId].inputs.strength_model = strModel;
|
||||
comfyUI.currentWorkflow[nodeId].inputs.strength_clip = strClip;
|
||||
}
|
||||
_syncRawJson();
|
||||
}
|
||||
});
|
||||
});
|
||||
},
|
||||
|
||||
async renderLoraPane(analysis, containerId) {
|
||||
const el = document.getElementById(containerId);
|
||||
if (!el) return;
|
||||
|
||||
const loraNodes = analysis.lora_nodes || [];
|
||||
const loras = this.models.loras || [];
|
||||
const defaultStackTarget = (loraNodes.find((n) => n.is_lora_manager) || loraNodes[0])?.id;
|
||||
const nodeOpts = loraNodes
|
||||
.map((n) => `<option value="${n.id}">ID:${n.id} (${n.title})</option>`)
|
||||
.join("");
|
||||
const stackTargetOpts = loraNodes
|
||||
.map((n) => `<option value="${n.id}" ${String(n.id) === String(defaultStackTarget) ? "selected" : ""}>ID:${n.id} (${n.title})</option>`)
|
||||
.join("");
|
||||
const currentVal = loraNodes[0]?.lora_name || "";
|
||||
|
||||
// Fetch Stack group, metadata, CivitAI cache in parallel
|
||||
let stackModels = [];
|
||||
let metadata = {};
|
||||
let civitaiCache = {};
|
||||
try {
|
||||
const [grpRes, metaRes, civRes] = await Promise.all([
|
||||
fetch("/api/wfm/models/groups?type=lora"),
|
||||
fetch("/api/wfm/models/metadata"),
|
||||
fetch("/api/wfm/models/civitai/cache"),
|
||||
]);
|
||||
const groups = grpRes.ok ? await grpRes.json() : {};
|
||||
stackModels = groups["Stack"] || [];
|
||||
metadata = metaRes.ok ? await metaRes.json() : {};
|
||||
civitaiCache = civRes.ok ? await civRes.json() : {};
|
||||
} catch { /* ignore */ }
|
||||
|
||||
stackModels.forEach((m) => {
|
||||
if (!_stackStrengths[m]) _stackStrengths[m] = { m: 1.0, c: 1.0 };
|
||||
if (_stackActive[m] === undefined) _stackActive[m] = true;
|
||||
});
|
||||
|
||||
// Build Stack trigger words
|
||||
const activeTriggerWords = [];
|
||||
const allStackTriggers = [];
|
||||
stackModels.forEach((m) => {
|
||||
const sha = (metadata[m] || {}).sha256;
|
||||
const civInfo = sha && civitaiCache[sha];
|
||||
if (civInfo?.trainedWords?.length) {
|
||||
allStackTriggers.push(...civInfo.trainedWords);
|
||||
if (_stackActive[m] !== false) activeTriggerWords.push(...civInfo.trainedWords);
|
||||
}
|
||||
});
|
||||
const stackTriggerHtml = activeTriggerWords.length
|
||||
? activeTriggerWords.map((w) => `<span class="wfm-lora-trigger-word">${w}</span>`).join(" ")
|
||||
: `<span style="color:var(--wfm-text-secondary);font-size:12px;">—</span>`;
|
||||
const stackLoraSyntax = _buildLoraSyntax(stackModels);
|
||||
const allActive = stackModels.every((m) => _stackActive[m] !== false);
|
||||
const anyActive = stackModels.some((m) => _stackActive[m] !== false);
|
||||
|
||||
const stackModelRows = stackModels.map((m) => {
|
||||
const stem = _loraBasename(m);
|
||||
const str = _stackStrengths[m] || { m: 1.0, c: 1.0 };
|
||||
const active = _stackActive[m] !== false;
|
||||
return `
|
||||
<div class="wfm-lora-stack-model-row${active ? "" : " wfm-lora-stack-model-row--off"}" data-model="${m.replace(/"/g, """)}">
|
||||
<input type="checkbox" class="wfm-lora-stack-active-cb" ${active ? "checked" : ""} title="Enable/Disable">
|
||||
<span class="wfm-lora-stack-model-name" title="${m}">${stem}</span>
|
||||
<div class="wfm-lora-stack-strengths">
|
||||
<input type="number" class="wfm-input wfm-lora-stack-str-m" value="${str.m}" step="0.05" min="0" max="2" style="width:64px;" ${active ? "" : "disabled"}>
|
||||
<input type="number" class="wfm-input wfm-lora-stack-str-c" value="${str.c}" step="0.05" min="0" max="2" style="width:64px;" ${active ? "" : "disabled"}>
|
||||
</div>
|
||||
</div>`;
|
||||
}).join("");
|
||||
|
||||
const _prevActiveTab = el.querySelector(".wfm-lora-tab-btn.active")?.dataset?.tab || "single";
|
||||
|
||||
el.innerHTML = `
|
||||
<div class="wfm-lora-tab-header">
|
||||
<button class="wfm-lora-tab-btn active" data-tab="single">Single</button>
|
||||
<button class="wfm-lora-tab-btn" data-tab="stack">Stack</button>
|
||||
</div>
|
||||
|
||||
<!-- Single tab -->
|
||||
<div class="wfm-lora-tab-content" id="wfm-lora-panel-single">
|
||||
<input type="text" class="wfm-input" id="wfm-lora-filter" placeholder="Filter...">
|
||||
<select class="wfm-select" id="wfm-lora-select">
|
||||
${loras.map((m) => `<option value="${m}" ${m === currentVal ? "selected" : ""}>${m}</option>`).join("")}
|
||||
</select>
|
||||
<div class="wfm-lora-strength-single">
|
||||
<span>M</span>
|
||||
<input type="number" class="wfm-input" id="wfm-lora-str-model" value="1.0" step="0.05" min="0" max="2">
|
||||
<span>C</span>
|
||||
<input type="number" class="wfm-input" id="wfm-lora-str-clip" value="1.0" step="0.05" min="0" max="2">
|
||||
</div>
|
||||
<div class="wfm-lora-stack-header">
|
||||
<select class="wfm-select" id="wfm-lora-single-target" style="flex:1;min-width:0;">${nodeOpts}</select>
|
||||
<button class="wfm-btn wfm-btn-sm" id="wfm-lora-single-apply" title="Apply LoRA to node and sync to Positive prompt">Apply</button>
|
||||
<button class="wfm-btn wfm-btn-sm wfm-lora-p-btn" id="wfm-lora-single-pos-apply" title="Apply Positive prompt to workflow">P</button>
|
||||
</div>
|
||||
<div class="wfm-lora-stack-info-block">
|
||||
<div class="wfm-lora-stack-info-label">Lora syntax</div>
|
||||
<div id="wfm-lora-single-syntax" class="wfm-lora-stack-syntax">—</div>
|
||||
</div>
|
||||
<div class="wfm-lora-stack-info-block">
|
||||
<div class="wfm-lora-stack-info-label">Trigger words</div>
|
||||
<div id="wfm-lora-single-triggers" class="wfm-lora-stack-triggers"><span style="color:var(--wfm-text-secondary);font-size:12px;">—</span></div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Stack tab -->
|
||||
<div class="wfm-lora-tab-content" id="wfm-lora-panel-stack" style="display:none;">
|
||||
<div class="wfm-lora-stack-header">
|
||||
<select class="wfm-select" id="wfm-lora-stack-target" style="flex:1;min-width:0;">${stackTargetOpts}</select>
|
||||
<button class="wfm-btn wfm-btn-sm" id="wfm-lora-stack-apply" title="Apply Stack to node and sync to Positive prompt">Apply</button>
|
||||
<button class="wfm-btn wfm-btn-sm wfm-lora-p-btn" id="wfm-lora-pos-apply" title="Apply Positive prompt to workflow">P</button>
|
||||
</div>
|
||||
<div class="wfm-lora-strength-combined">
|
||||
<span class="wfm-lora-stack-label" style="margin-right:4px;flex-shrink:0;">Stack</span>
|
||||
<input type="checkbox" id="wfm-lora-stack-toggle-all" ${allActive ? "checked" : ""} title="Toggle all stack models" style="flex-shrink:0;margin-right:8px;">
|
||||
${stackModels.length > 0 ? `
|
||||
<div class="wfm-lora-stack-global-adj-groups">
|
||||
<div class="wfm-lora-stack-global-adj-group">
|
||||
<span>Str M</span>
|
||||
<button class="wfm-btn wfm-btn-xs" id="wfm-stack-adj-m-dec">−</button>
|
||||
<input type="number" id="wfm-stack-adj-step-m" class="wfm-input wfm-lora-stack-adj-step" value="0.05" step="0.05" min="0.01" max="2.0">
|
||||
<button class="wfm-btn wfm-btn-xs" id="wfm-stack-adj-m-inc">+</button>
|
||||
</div>
|
||||
<div class="wfm-lora-stack-global-adj-group">
|
||||
<span>C</span>
|
||||
<button class="wfm-btn wfm-btn-xs" id="wfm-stack-adj-c-dec">−</button>
|
||||
<input type="number" id="wfm-stack-adj-step-c" class="wfm-input wfm-lora-stack-adj-step" value="0.05" step="0.05" min="0.01" max="2.0">
|
||||
<button class="wfm-btn wfm-btn-xs" id="wfm-stack-adj-c-inc">+</button>
|
||||
</div>
|
||||
</div>
|
||||
` : ""}
|
||||
</div>
|
||||
<div class="wfm-lora-stack-info-block">
|
||||
<div class="wfm-lora-stack-info-label">Lora syntax</div>
|
||||
<div id="wfm-lora-stack-syntax" class="wfm-lora-stack-syntax">—</div>
|
||||
</div>
|
||||
<div class="wfm-lora-stack-info-block">
|
||||
<div class="wfm-lora-stack-info-label">Trigger words</div>
|
||||
<div id="wfm-lora-stack-triggers" class="wfm-lora-stack-triggers">${stackTriggerHtml}</div>
|
||||
</div>
|
||||
<div class="wfm-lora-stack-models">
|
||||
${stackModelRows || `<p class="wfm-placeholder">No models in Stack group</p>`}
|
||||
</div>
|
||||
</div>
|
||||
`;
|
||||
|
||||
// Fix: overwrite textContent to avoid HTML parsing of <lora:...> syntax
|
||||
const _synEl = document.getElementById("wfm-lora-stack-syntax");
|
||||
if (_synEl) _synEl.textContent = stackLoraSyntax || "—";
|
||||
|
||||
// ── Tab switching ────────────────────────────────────
|
||||
el.querySelectorAll(".wfm-lora-tab-btn").forEach((btn) => {
|
||||
btn.addEventListener("click", () => {
|
||||
el.querySelectorAll(".wfm-lora-tab-btn").forEach(b => b.classList.remove("active"));
|
||||
btn.classList.add("active");
|
||||
const tab = btn.dataset.tab;
|
||||
document.getElementById("wfm-lora-panel-single").style.display = tab === "single" ? "" : "none";
|
||||
document.getElementById("wfm-lora-panel-stack").style.display = tab === "stack" ? "" : "none";
|
||||
});
|
||||
});
|
||||
|
||||
// Restore previously active tab after re-render
|
||||
if (_prevActiveTab === "stack") {
|
||||
el.querySelector('[data-tab="single"]')?.classList.remove("active");
|
||||
el.querySelector('[data-tab="stack"]')?.classList.add("active");
|
||||
document.getElementById("wfm-lora-panel-single").style.display = "none";
|
||||
document.getElementById("wfm-lora-panel-stack").style.display = "";
|
||||
}
|
||||
|
||||
// ── Single: filter ───────────────────────────────────
|
||||
document.getElementById("wfm-lora-filter")?.addEventListener("input", (e) => {
|
||||
const filter = e.target.value.toLowerCase();
|
||||
const select = document.getElementById("wfm-lora-select");
|
||||
if (!select) return;
|
||||
select.innerHTML = loras
|
||||
.filter((m) => m.toLowerCase().includes(filter))
|
||||
.map((m) => `<option value="${m}">${m}</option>`)
|
||||
.join("");
|
||||
_refreshLoraSingleDynamic(metadata, civitaiCache);
|
||||
});
|
||||
|
||||
// ── Single: update SYNTAX/TRIGGERS on model or strength change ──
|
||||
document.getElementById("wfm-lora-select")?.addEventListener("change", () => _refreshLoraSingleDynamic(metadata, civitaiCache));
|
||||
document.getElementById("wfm-lora-str-model")?.addEventListener("input", () => _refreshLoraSingleDynamic(metadata, civitaiCache));
|
||||
document.getElementById("wfm-lora-str-clip")?.addEventListener("input", () => _refreshLoraSingleDynamic(metadata, civitaiCache));
|
||||
|
||||
// ── Single: Apply button ─────────────────────────────
|
||||
document.getElementById("wfm-lora-single-apply")?.addEventListener("click", () => {
|
||||
const nodeId = document.getElementById("wfm-lora-single-target")?.value;
|
||||
const select = document.getElementById("wfm-lora-select");
|
||||
if (!nodeId || !comfyUI.currentWorkflow?.[nodeId] || !select?.value) return;
|
||||
|
||||
const node = loraNodes.find((n) => String(n.id) === String(nodeId));
|
||||
const strModel = parseFloat(document.getElementById("wfm-lora-str-model")?.value) || 1.0;
|
||||
const strClip = parseFloat(document.getElementById("wfm-lora-str-clip")?.value) || 1.0;
|
||||
_applyLoraToNode(nodeId, select.value, strModel, strClip, node?.is_lora_manager);
|
||||
_syncRawJson();
|
||||
|
||||
// Sync to Positive prompt
|
||||
const posTextarea = document.getElementById("wfm-prompt-pos-text");
|
||||
if (!posTextarea) return;
|
||||
const stem = _loraBasename(select.value);
|
||||
const loraSyntax = `<lora:${stem}:${strModel}:${strClip}>`;
|
||||
const sha = (metadata[select.value] || {}).sha256;
|
||||
const civInfo = sha && civitaiCache[sha];
|
||||
const triggerWords = civInfo?.trainedWords || [];
|
||||
|
||||
let cleaned = posTextarea.value;
|
||||
const escapedStem = stem.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
|
||||
cleaned = cleaned.replace(new RegExp(`,?\\s*<lora:${escapedStem}:[^>]*>`, "gi"), "");
|
||||
if (triggerWords.length > 0) {
|
||||
const wordSet = new Set(triggerWords.map(w => w.trim().toLowerCase()));
|
||||
cleaned = cleaned.split(",").map(p => p.trim()).filter(p => p && !wordSet.has(p.toLowerCase())).join(", ");
|
||||
}
|
||||
cleaned = cleaned.replace(/,\s*$/, "").trim();
|
||||
const append = triggerWords.length > 0 ? `${loraSyntax}, ${triggerWords.join(", ")}` : loraSyntax;
|
||||
posTextarea.value = cleaned ? `${cleaned}, ${append}` : append;
|
||||
|
||||
const posNodeId = document.getElementById("wfm-prompt-pos-target")?.value;
|
||||
if (posNodeId && comfyUI.currentWorkflow?.[posNodeId]) {
|
||||
const promptNode = comfyUI.currentAnalysis?.prompt_nodes?.find(n => String(n.id) === String(posNodeId));
|
||||
comfyUI.currentWorkflow[posNodeId].inputs[promptNode?.textKey || "text"] = posTextarea.value;
|
||||
_syncRawJson();
|
||||
}
|
||||
});
|
||||
|
||||
// ── Single: P button ─────────────────────────────────
|
||||
document.getElementById("wfm-lora-single-pos-apply")?.addEventListener("click", () => {
|
||||
const nodeId = document.getElementById("wfm-prompt-pos-target")?.value;
|
||||
const text = document.getElementById("wfm-prompt-pos-text")?.value;
|
||||
if (nodeId && comfyUI.currentWorkflow?.[nodeId]) {
|
||||
const promptNode = comfyUI.currentAnalysis?.prompt_nodes?.find(n => String(n.id) === String(nodeId));
|
||||
comfyUI.currentWorkflow[nodeId].inputs[promptNode?.textKey || "text"] = text;
|
||||
_syncRawJson();
|
||||
}
|
||||
});
|
||||
|
||||
// ── Stack: per-model strength + toggle ───────────────
|
||||
el.querySelectorAll(".wfm-lora-stack-model-row").forEach((row) => {
|
||||
const modelName = row.dataset.model;
|
||||
const inputM = row.querySelector(".wfm-lora-stack-str-m");
|
||||
const inputC = row.querySelector(".wfm-lora-stack-str-c");
|
||||
const cbActive = row.querySelector(".wfm-lora-stack-active-cb");
|
||||
|
||||
const onStrChange = () => {
|
||||
_stackStrengths[modelName] = { m: parseFloat(inputM.value) || 1.0, c: parseFloat(inputC.value) || 1.0 };
|
||||
_refreshLoraPaneDynamic(stackModels, metadata, civitaiCache);
|
||||
};
|
||||
inputM?.addEventListener("input", onStrChange);
|
||||
inputC?.addEventListener("input", onStrChange);
|
||||
|
||||
cbActive?.addEventListener("change", () => {
|
||||
const on = cbActive.checked;
|
||||
_stackActive[modelName] = on;
|
||||
row.classList.toggle("wfm-lora-stack-model-row--off", !on);
|
||||
if (inputM) inputM.disabled = !on;
|
||||
if (inputC) inputC.disabled = !on;
|
||||
_syncStackToggleAll(stackModels);
|
||||
_refreshLoraPaneDynamic(stackModels, metadata, civitaiCache);
|
||||
});
|
||||
});
|
||||
|
||||
// ── Stack: toggle-all checkbox ───────────────────────
|
||||
const toggleAllCb = document.getElementById("wfm-lora-stack-toggle-all");
|
||||
if (toggleAllCb) {
|
||||
toggleAllCb.indeterminate = !allActive && anyActive;
|
||||
toggleAllCb.addEventListener("change", () => {
|
||||
const on = toggleAllCb.checked;
|
||||
stackModels.forEach((m) => { _stackActive[m] = on; });
|
||||
el.querySelectorAll(".wfm-lora-stack-model-row").forEach((row) => {
|
||||
const cb = row.querySelector(".wfm-lora-stack-active-cb");
|
||||
const inM = row.querySelector(".wfm-lora-stack-str-m");
|
||||
const inC = row.querySelector(".wfm-lora-stack-str-c");
|
||||
if (cb) cb.checked = on;
|
||||
if (inM) inM.disabled = !on;
|
||||
if (inC) inC.disabled = !on;
|
||||
row.classList.toggle("wfm-lora-stack-model-row--off", !on);
|
||||
});
|
||||
_refreshLoraPaneDynamic(stackModels, metadata, civitaiCache);
|
||||
});
|
||||
}
|
||||
|
||||
// ── Stack: global strength adjustment ────────────────
|
||||
if (stackModels.length > 0) {
|
||||
const adjApply = (key, sign) => {
|
||||
const delta = sign * (parseFloat(document.getElementById(`wfm-stack-adj-step-${key}`)?.value) || 0.05);
|
||||
stackModels.forEach((m) => {
|
||||
const str = _stackStrengths[m] || { m: 1.0, c: 1.0 };
|
||||
str[key] = Math.max(0, Math.round((str[key] + delta) * 1000) / 1000);
|
||||
_stackStrengths[m] = str;
|
||||
});
|
||||
el.querySelectorAll(".wfm-lora-stack-model-row").forEach((row) => {
|
||||
const str = _stackStrengths[row.dataset.model];
|
||||
if (!str) return;
|
||||
const inp = row.querySelector(`.wfm-lora-stack-str-${key}`);
|
||||
if (inp) inp.value = str[key];
|
||||
});
|
||||
_refreshLoraPaneDynamic(stackModels, metadata, civitaiCache);
|
||||
};
|
||||
document.getElementById("wfm-stack-adj-m-inc")?.addEventListener("click", () => adjApply("m", 1));
|
||||
document.getElementById("wfm-stack-adj-m-dec")?.addEventListener("click", () => adjApply("m", -1));
|
||||
document.getElementById("wfm-stack-adj-c-inc")?.addEventListener("click", () => adjApply("c", 1));
|
||||
document.getElementById("wfm-stack-adj-c-dec")?.addEventListener("click", () => adjApply("c", -1));
|
||||
}
|
||||
|
||||
// ── Stack: Apply button ──────────────────────────────
|
||||
document.getElementById("wfm-lora-stack-apply")?.addEventListener("click", () => {
|
||||
const nodeId = document.getElementById("wfm-lora-stack-target")?.value;
|
||||
if (!nodeId || !comfyUI.currentWorkflow?.[nodeId]) return;
|
||||
|
||||
const node = loraNodes.find((n) => String(n.id) === String(nodeId));
|
||||
if (node?.is_lora_manager) {
|
||||
const loraValue = stackModels.map((m) => {
|
||||
const stem = _loraBasename(m);
|
||||
const str = _stackStrengths[m] || { m: 1.0, c: 1.0 };
|
||||
const active = _stackActive[m] !== false;
|
||||
return { name: stem, strength: str.m, active, expanded: false, clipStrength: str.c, locked: false };
|
||||
});
|
||||
comfyUI.currentWorkflow[nodeId].inputs.loras = { __value__: loraValue };
|
||||
comfyUI.currentWorkflow[nodeId].inputs.text = _buildLoraManagerSyntax(stackModels);
|
||||
} else {
|
||||
const first = stackModels[0];
|
||||
if (first) {
|
||||
comfyUI.currentWorkflow[nodeId].inputs.lora_name = first;
|
||||
comfyUI.currentWorkflow[nodeId].inputs.strength_model = _stackStrengths[first]?.m ?? 1.0;
|
||||
comfyUI.currentWorkflow[nodeId].inputs.strength_clip = _stackStrengths[first]?.c ?? 1.0;
|
||||
}
|
||||
}
|
||||
_syncRawJson();
|
||||
|
||||
// Sync Stack LORA SYNTAX + TRIGGER WORDS to Positive prompt
|
||||
const posTextarea = document.getElementById("wfm-prompt-pos-text");
|
||||
if (!posTextarea) return;
|
||||
const effectiveSyntax = _buildLoraSyntax(stackModels);
|
||||
|
||||
// Recompute trigger words at apply-time using the current _stackActive state
|
||||
const currentAllTriggers = [];
|
||||
const currentActiveTriggers = [];
|
||||
stackModels.forEach((m) => {
|
||||
const sha = (metadata[m] || {}).sha256;
|
||||
const civInfo = sha && civitaiCache[sha];
|
||||
if (civInfo?.trainedWords?.length) {
|
||||
currentAllTriggers.push(...civInfo.trainedWords);
|
||||
if (_stackActive[m] !== false) currentActiveTriggers.push(...civInfo.trainedWords);
|
||||
}
|
||||
});
|
||||
|
||||
let cleaned = posTextarea.value;
|
||||
for (const m of stackModels) {
|
||||
const stem = _loraBasename(m).replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
|
||||
cleaned = cleaned.replace(new RegExp(`,?\\s*<lora:${stem}:[^>]*>`, "gi"), "");
|
||||
}
|
||||
if (currentAllTriggers.length > 0) {
|
||||
const wordSet = new Set(currentAllTriggers.map(w => w.trim().toLowerCase()));
|
||||
cleaned = cleaned.split(",").map(p => p.trim()).filter(p => p && !wordSet.has(p.toLowerCase())).join(", ");
|
||||
}
|
||||
cleaned = cleaned.replace(/,\s*$/, "").trim();
|
||||
if (effectiveSyntax) {
|
||||
const append = currentActiveTriggers.length > 0
|
||||
? `${effectiveSyntax}, ${currentActiveTriggers.join(", ")}`
|
||||
: effectiveSyntax;
|
||||
posTextarea.value = cleaned ? `${cleaned}, ${append}` : append;
|
||||
} else {
|
||||
posTextarea.value = cleaned;
|
||||
}
|
||||
|
||||
const posNodeId = document.getElementById("wfm-prompt-pos-target")?.value;
|
||||
if (posNodeId && comfyUI.currentWorkflow?.[posNodeId]) {
|
||||
const promptNode = comfyUI.currentAnalysis?.prompt_nodes?.find(n => String(n.id) === String(posNodeId));
|
||||
comfyUI.currentWorkflow[posNodeId].inputs[promptNode?.textKey || "text"] = posTextarea.value;
|
||||
_syncRawJson();
|
||||
}
|
||||
});
|
||||
|
||||
// ── Stack: P button ──────────────────────────────────
|
||||
document.getElementById("wfm-lora-pos-apply")?.addEventListener("click", () => {
|
||||
const nodeId = document.getElementById("wfm-prompt-pos-target")?.value;
|
||||
const text = document.getElementById("wfm-prompt-pos-text")?.value;
|
||||
if (nodeId && comfyUI.currentWorkflow?.[nodeId]) {
|
||||
const promptNode = comfyUI.currentAnalysis?.prompt_nodes?.find(n => String(n.id) === String(nodeId));
|
||||
comfyUI.currentWorkflow[nodeId].inputs[promptNode?.textKey || "text"] = text;
|
||||
_syncRawJson();
|
||||
}
|
||||
});
|
||||
|
||||
// Initial single tab display
|
||||
_refreshLoraSingleDynamic(metadata, civitaiCache);
|
||||
},
|
||||
|
||||
renderSettingsTab(analysis, containerId) {
|
||||
const el = document.getElementById(containerId);
|
||||
if (!el) return;
|
||||
@@ -424,6 +897,37 @@ export const comfyEditor = {
|
||||
comfyUI.currentWorkflow[negTarget].inputs[negTextKey] = negText;
|
||||
}
|
||||
},
|
||||
|
||||
disableAllStack(containerId = "wfm-gen-lora-fields") {
|
||||
for (const k of Object.keys(_stackActive)) {
|
||||
_stackActive[k] = false;
|
||||
}
|
||||
const toggleAll = document.getElementById("wfm-lora-stack-toggle-all");
|
||||
if (toggleAll) toggleAll.checked = false;
|
||||
const container = document.getElementById(containerId);
|
||||
if (!container) return;
|
||||
container.querySelectorAll(".wfm-lora-stack-model-row").forEach((row) => {
|
||||
row.classList.add("wfm-lora-stack-model-row--off");
|
||||
const cb = row.querySelector(".wfm-lora-stack-active-cb");
|
||||
const inM = row.querySelector(".wfm-lora-stack-str-m");
|
||||
const inC = row.querySelector(".wfm-lora-stack-str-c");
|
||||
if (cb) cb.checked = false;
|
||||
if (inM) inM.disabled = true;
|
||||
if (inC) inC.disabled = true;
|
||||
});
|
||||
},
|
||||
|
||||
switchLoraSingleTab() {
|
||||
const container = document.getElementById("wfm-gen-lora-fields");
|
||||
if (!container) return;
|
||||
container.querySelectorAll(".wfm-lora-tab-btn").forEach(b => b.classList.remove("active"));
|
||||
const singleBtn = container.querySelector(".wfm-lora-tab-btn[data-tab='single']");
|
||||
if (singleBtn) singleBtn.classList.add("active");
|
||||
const singlePanel = document.getElementById("wfm-lora-panel-single");
|
||||
const stackPanel = document.getElementById("wfm-lora-panel-stack");
|
||||
if (singlePanel) singlePanel.style.display = "";
|
||||
if (stackPanel) stackPanel.style.display = "none";
|
||||
},
|
||||
};
|
||||
|
||||
function _nodeOptions(nodes) {
|
||||
|
||||
@@ -295,10 +295,15 @@ export const comfyWorkflow = {
|
||||
const nodeLinks = linkMap[node.id] || {};
|
||||
const inputDefs = node.inputs || [];
|
||||
const linkedInputNames = new Set();
|
||||
// UI slot inputs with an actual link don't have a widget value entry in
|
||||
// widgets_values (modern ComfyUI format). Track these separately so the
|
||||
// widget-mapping loop won't advance wIdx for them.
|
||||
const linkedSlotNames = new Set();
|
||||
inputDefs.forEach((inp, idx) => {
|
||||
if (nodeLinks[idx]) {
|
||||
inputs[inp.name] = nodeLinks[idx];
|
||||
linkedInputNames.add(inp.name);
|
||||
linkedSlotNames.add(inp.name);
|
||||
}
|
||||
});
|
||||
|
||||
@@ -336,13 +341,15 @@ export const comfyWorkflow = {
|
||||
const expectedType = widgetTypes[nIdx];
|
||||
// Skip if this input is already linked
|
||||
if (linkedInputNames.has(name)) {
|
||||
// Still consume widget value(s) since widgets_values
|
||||
// includes entries for linked inputs too
|
||||
wIdx++;
|
||||
// Also skip control_after_generate if present
|
||||
if (wIdx < widgets.length && _isExtraWidgetValue(widgets[wIdx], expectedType)) {
|
||||
if (!linkedSlotNames.has(name)) {
|
||||
// Not a UI slot input — old-style linked input that still
|
||||
// occupies a slot in widgets_values; consume it.
|
||||
wIdx++;
|
||||
if (wIdx < widgets.length && _isExtraWidgetValue(widgets[wIdx], expectedType)) {
|
||||
wIdx++;
|
||||
}
|
||||
}
|
||||
// UI slot inputs with a real link have no widget value entry — don't advance wIdx.
|
||||
continue;
|
||||
}
|
||||
// Check if current widget value matches expected type
|
||||
@@ -392,6 +399,14 @@ export const comfyWorkflow = {
|
||||
} // end else (non-LoraManager path)
|
||||
}
|
||||
|
||||
// ImpactWildcardEncode / ImpactWildcardProcessor: widgets[0] is always wildcard_text.
|
||||
// Always overwrite: object_info ordering may misalign when widget order differs between
|
||||
// impact-pack versions; widgets[0] is stable across all known versions.
|
||||
if ((node.type === "ImpactWildcardEncode" || node.type === "ImpactWildcardProcessor")
|
||||
&& widgets.length > 0) {
|
||||
inputs["wildcard_text"] = widgets[0];
|
||||
}
|
||||
|
||||
api[nodeId] = {
|
||||
class_type: node.type,
|
||||
inputs,
|
||||
@@ -513,7 +528,10 @@ export const comfyWorkflow = {
|
||||
// Nodes that pass CONDITIONING through without changing positive/negative role
|
||||
const COND_PASSTHROUGH = new Set([
|
||||
"ConditioningCombine", "ConditioningConcat", "ConditioningAverage",
|
||||
"ConditioningZeroOut", "ConditioningSetTimestepRange",
|
||||
"ConditioningSetTimestepRange",
|
||||
// ConditioningZeroOut is intentionally excluded: it discards upstream text entirely
|
||||
// (used as a no-text negative in ZIT/Lumina2 workflows). Propagating the negative
|
||||
// role upstream would incorrectly mark the shared positive CLIPTextEncode as "unknown".
|
||||
"ControlNetApply", "ControlNetApplyAdvanced",
|
||||
"IPAdapterApply", "IPAdapterApplyFaceID",
|
||||
"StyleModelApply",
|
||||
@@ -561,6 +579,16 @@ export const comfyWorkflow = {
|
||||
if (isNeg) samplerNegativeRef[tv[0]] = true;
|
||||
}
|
||||
}
|
||||
// CLIPTextEncodeEditPlus — propagate role to its STRING inputs (text1, text2)
|
||||
if (ct === "CLIPTextEncodeEditPlus") {
|
||||
for (const key of ["text1", "text2"]) {
|
||||
const tv = inputs[key];
|
||||
if (Array.isArray(tv)) {
|
||||
if (isPos) samplerPositiveRef[tv[0]] = true;
|
||||
if (isNeg) samplerNegativeRef[tv[0]] = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -591,6 +619,23 @@ export const comfyWorkflow = {
|
||||
});
|
||||
}
|
||||
|
||||
// ImageMetadataPromptLoader — checkpoint + positive/negative prompts in one node
|
||||
if (ct === "ImageMetadataPromptLoader") {
|
||||
result.checkpoint_nodes.push({ id, type: ct, title, ckpt_name: inputs.ckpt_name });
|
||||
if (typeof inputs.positive_text === "string") {
|
||||
result.prompt_nodes.push({
|
||||
id, type: ct, title: `${title} [positive]`, role: "positive",
|
||||
text: inputs.positive_text, textKey: "positive_text",
|
||||
});
|
||||
}
|
||||
if (typeof inputs.negative_text === "string") {
|
||||
result.prompt_nodes.push({
|
||||
id, type: ct, title: `${title} [negative]`, role: "negative",
|
||||
text: inputs.negative_text, textKey: "negative_text",
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
// --- Prompt nodes ---
|
||||
|
||||
if (ct === "CLIPTextEncode") {
|
||||
@@ -618,6 +663,19 @@ export const comfyWorkflow = {
|
||||
}
|
||||
}
|
||||
|
||||
// CLIPTextEncodeEditPlus — text_edit is the locally editable override; text1 is always a link.
|
||||
// Skip when text_edit is empty: it means upstream nodes (ImpactWildcardEncode etc.) supply
|
||||
// the actual prompt text and the edit field is just an optional local override.
|
||||
if (ct === "CLIPTextEncodeEditPlus") {
|
||||
const textVal = inputs.text_edit;
|
||||
if (typeof textVal === "string" && textVal !== "") {
|
||||
result.prompt_nodes.push({
|
||||
id, type: ct, title, role: getRole(),
|
||||
text: textVal, textKey: "text_edit",
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
// Qwen-based image+text encoder
|
||||
if (ct === "TextEncodeQwenImageEditPlus") {
|
||||
result.prompt_nodes.push({
|
||||
@@ -696,6 +754,26 @@ export const comfyWorkflow = {
|
||||
}
|
||||
}
|
||||
|
||||
// Lora Loader (LoraManager) — loras stored in inputs.loras.__value__
|
||||
if (ct === "Lora Loader (LoraManager)") {
|
||||
result.lora_nodes.push({ id, type: ct, title, is_lora_manager: true });
|
||||
}
|
||||
|
||||
// ImageMetadataLoRALoader — up to 3 LoRA slots; skip "None" entries
|
||||
if (ct === "ImageMetadataLoRALoader") {
|
||||
for (let i = 1; i <= 3; i++) {
|
||||
const loraName = inputs[`lora_${i}`];
|
||||
if (typeof loraName === "string" && loraName !== "None") {
|
||||
result.lora_nodes.push({
|
||||
id, type: ct, title,
|
||||
lora_name: loraName,
|
||||
strength_model: inputs[`strength_model_${i}`] ?? 1.0,
|
||||
strength_clip: inputs[`strength_clip_${i}`] ?? 1.0,
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// --- VAE nodes ---
|
||||
if (ct === "VAELoader") {
|
||||
result.vae_nodes.push({ id, type: ct, title, vae_name: inputs.vae_name });
|
||||
@@ -781,6 +859,10 @@ function _getWidgetMapping(nodeType) {
|
||||
CheckpointLoaderSimple: ["ckpt_name"],
|
||||
KSampler: ["seed", "steps", "cfg", "sampler_name", "scheduler", "denoise"],
|
||||
CLIPTextEncode: ["text"],
|
||||
CLIPTextEncodeEditPlus: ["text_edit", "mode"],
|
||||
ImageMetadataCheckpointLoader: ["ckpt_name", "vae_name", "_metadata_json"],
|
||||
ImageMetadataPromptLoader: ["ckpt_name", "vae_name", "positive_text", "negative_text", "_metadata_json"],
|
||||
ImageMetadataLoRALoader: ["lora_1", "strength_model_1", "strength_clip_1", "lora_2", "strength_model_2", "strength_clip_2", "lora_3", "strength_model_3", "strength_clip_3"],
|
||||
EmptyLatentImage: ["width", "height", "batch_size"],
|
||||
LoraLoader: ["lora_name", "strength_model", "strength_clip"],
|
||||
VAELoader: ["vae_name"],
|
||||
@@ -792,6 +874,10 @@ function _getWidgetMapping(nodeType) {
|
||||
CLIPLoader: ["clip_name", "type", "device"],
|
||||
FluxGuidance: ["guidance"],
|
||||
CFGNorm: ["strength"],
|
||||
// Impact Pack wildcard nodes — only map wildcard_text (index 0); remaining widgets
|
||||
// vary between versions and include frontend-only extras, so we leave them unmapped.
|
||||
ImpactWildcardProcessor: ["wildcard_text"],
|
||||
ImpactWildcardEncode: ["wildcard_text"],
|
||||
};
|
||||
return mappings[nodeType] || null;
|
||||
}
|
||||
|
||||
+387
-38
@@ -1,17 +1,29 @@
|
||||
/**
|
||||
* Feeder Tab - ImageFeeder node control with embedded image library
|
||||
* Feeder Tab - ImageFeeder node control (Image Loop mode)
|
||||
* + WFS_GalleryFeeder node control (Gallery mode)
|
||||
*/
|
||||
|
||||
import { comfyUI } from "./comfyui-client.js";
|
||||
import { showToast } from "./app.js";
|
||||
import { t } from "./i18n.js";
|
||||
import { FEEDER_GROUP, ensureFeederGroup } from "./gallery-tab.js";
|
||||
|
||||
// ── Module State ──────────────────────────────────────────────────
|
||||
const _s = {
|
||||
dir: "", // current folder relative path
|
||||
images: [], // filenames in current folder
|
||||
selected: new Set(),// selected filenames (across all interactions)
|
||||
dir: "", // current folder relative path (loop mode)
|
||||
images: [], // filenames in current folder (loop mode)
|
||||
selected: new Set(),// selected filenames (loop mode)
|
||||
presets: {}, // {presetName: {directory, selected_files}}
|
||||
running: false, // feeder run loop active
|
||||
mode: localStorage.getItem("wfm_feeder_mode") || "loop", // "loop" | "gallery"
|
||||
};
|
||||
|
||||
// Gallery mode state
|
||||
const _gs = {
|
||||
groups: [], // [{name}]
|
||||
group: FEEDER_GROUP, // selected group name
|
||||
images: [], // absolute paths in selected group
|
||||
idx: 0, // current index
|
||||
};
|
||||
|
||||
// ── Node helpers ──────────────────────────────────────────────────
|
||||
@@ -24,12 +36,40 @@ function _feederNodes() {
|
||||
.map(([id, n]) => ({ id, title: n._meta?.title || `ImageFeeder` }));
|
||||
}
|
||||
|
||||
function _galFeederNodes() {
|
||||
const wf = comfyUI.currentWorkflow;
|
||||
if (!wf) return [];
|
||||
return Object.entries(wf)
|
||||
.filter(([, n]) => n?.class_type === "WFS_GalleryFeeder")
|
||||
.map(([id, n]) => ({ id, title: n._meta?.title || `GalleryFeeder` }));
|
||||
}
|
||||
|
||||
export function refreshFeederNodeList() {
|
||||
const sel = document.getElementById("wfm-feeder-node-sel");
|
||||
if (_s.mode === "gallery") {
|
||||
_refreshGalNodeList();
|
||||
} else {
|
||||
const sel = document.getElementById("wfm-feeder-node-sel");
|
||||
if (!sel) return;
|
||||
const nodes = _feederNodes();
|
||||
if (nodes.length === 0) {
|
||||
sel.innerHTML = `<option value="">-- No ImageFeeder node --</option>`;
|
||||
return;
|
||||
}
|
||||
const prevVal = sel.value;
|
||||
sel.innerHTML = nodes.map(n =>
|
||||
`<option value="${n.id}">${n.title} (ID:${n.id})</option>`
|
||||
).join("");
|
||||
if (prevVal && nodes.find(n => n.id === prevVal)) sel.value = prevVal;
|
||||
_loadFromNode(sel.value || nodes[0].id);
|
||||
}
|
||||
}
|
||||
|
||||
function _refreshGalNodeList() {
|
||||
const sel = document.getElementById("wfm-feeder-gal-node-sel");
|
||||
if (!sel) return;
|
||||
const nodes = _feederNodes();
|
||||
const nodes = _galFeederNodes();
|
||||
if (nodes.length === 0) {
|
||||
sel.innerHTML = `<option value="">-- No ImageFeeder node --</option>`;
|
||||
sel.innerHTML = `<option value="">-- No WFS_GalleryFeeder node --</option>`;
|
||||
return;
|
||||
}
|
||||
const prevVal = sel.value;
|
||||
@@ -37,7 +77,7 @@ export function refreshFeederNodeList() {
|
||||
`<option value="${n.id}">${n.title} (ID:${n.id})</option>`
|
||||
).join("");
|
||||
if (prevVal && nodes.find(n => n.id === prevVal)) sel.value = prevVal;
|
||||
_loadFromNode(sel.value || nodes[0].id);
|
||||
_loadFromGalNode(sel.value || nodes[0].id);
|
||||
}
|
||||
|
||||
function _loadFromNode(nodeId) {
|
||||
@@ -54,7 +94,6 @@ function _loadFromNode(nodeId) {
|
||||
_setVal("wfm-feeder-seed", inp.seed ?? 0);
|
||||
_setCheck("wfm-feeder-use-sel", inp.use_selection ?? true);
|
||||
|
||||
// Restore selected_files
|
||||
_s.selected.clear();
|
||||
try {
|
||||
const arr = JSON.parse(inp.selected_files || "[]");
|
||||
@@ -72,15 +111,44 @@ function _loadFromNode(nodeId) {
|
||||
_updateStatus();
|
||||
}
|
||||
|
||||
function _loadFromGalNode(nodeId) {
|
||||
const wf = comfyUI.currentWorkflow;
|
||||
if (!wf?.[nodeId]) return;
|
||||
const inp = wf[nodeId].inputs || {};
|
||||
|
||||
const group = inp.group_name || FEEDER_GROUP;
|
||||
_setVal("wfm-feeder-gal-sort", inp.sort_mode || "filename_asc");
|
||||
_setVal("wfm-feeder-gal-index", inp.index ?? 0);
|
||||
_setVal("wfm-feeder-gal-seed", inp.seed ?? 0);
|
||||
_gs.idx = inp.index ?? 0;
|
||||
|
||||
if (_gs.group !== group) {
|
||||
_gs.group = group;
|
||||
_setGalGroupSelect(group);
|
||||
_loadGalImages(group);
|
||||
}
|
||||
}
|
||||
|
||||
function _applyToWorkflow() {
|
||||
const nodeId = document.getElementById("wfm-feeder-node-sel")?.value;
|
||||
const wf = comfyUI.currentWorkflow;
|
||||
if (!nodeId || !wf?.[nodeId]) {
|
||||
showToast("No ImageFeeder node selected", "error");
|
||||
showToast(t("feederNoNode"), "error");
|
||||
return;
|
||||
}
|
||||
_applyToNode(nodeId);
|
||||
showToast("Applied to workflow", "success");
|
||||
showToast(t("appliedToWorkflow"), "success");
|
||||
}
|
||||
|
||||
function _applyGalToWorkflow() {
|
||||
const nodeId = document.getElementById("wfm-feeder-gal-node-sel")?.value;
|
||||
const wf = comfyUI.currentWorkflow;
|
||||
if (!nodeId || !wf?.[nodeId]) {
|
||||
showToast(t("feederGalNoNode"), "error");
|
||||
return;
|
||||
}
|
||||
_applyToGalNode(nodeId);
|
||||
showToast(t("appliedToWorkflow"), "success");
|
||||
}
|
||||
|
||||
// ── Run Loop ──────────────────────────────────────────────────────
|
||||
@@ -92,6 +160,13 @@ function _setRunUI(running) {
|
||||
if (stopBtn) stopBtn.disabled = !running;
|
||||
}
|
||||
|
||||
function _setGalRunUI(running) {
|
||||
const runBtn = document.getElementById("wfm-feeder-gal-run-btn");
|
||||
const stopBtn = document.getElementById("wfm-feeder-gal-stop-btn");
|
||||
if (runBtn) runBtn.disabled = running;
|
||||
if (stopBtn) stopBtn.disabled = !running;
|
||||
}
|
||||
|
||||
function _applyToNode(nodeId) {
|
||||
const wf = comfyUI.currentWorkflow;
|
||||
const inp = wf[nodeId].inputs;
|
||||
@@ -106,20 +181,28 @@ function _applyToNode(nodeId) {
|
||||
inp.selected_files = JSON.stringify([..._s.selected]);
|
||||
}
|
||||
|
||||
function _applyToGalNode(nodeId) {
|
||||
const wf = comfyUI.currentWorkflow;
|
||||
const inp = wf[nodeId].inputs;
|
||||
inp.group_name = _gs.group;
|
||||
inp.index = _gs.idx;
|
||||
inp.sort_mode = document.getElementById("wfm-feeder-gal-sort")?.value || "filename_asc";
|
||||
inp.seed = parseInt(document.getElementById("wfm-feeder-gal-seed")?.value) || 0;
|
||||
}
|
||||
|
||||
async function _startRun() {
|
||||
if (_s.running) return;
|
||||
if (!comfyUI.currentWorkflow) { showToast("No workflow loaded", "error"); return; }
|
||||
if (!comfyUI.connected) { showToast("Not connected to ComfyUI", "error"); return; }
|
||||
if (!comfyUI.currentWorkflow) { showToast(t("noWorkflowLoaded"), "error"); return; }
|
||||
if (!comfyUI.connected) { showToast(t("notConnectedToComfyUI"), "error"); return; }
|
||||
|
||||
const nodeId = document.getElementById("wfm-feeder-node-sel")?.value;
|
||||
if (!nodeId || !comfyUI.currentWorkflow[nodeId]) {
|
||||
showToast("No ImageFeeder node selected", "error");
|
||||
showToast(t("feederNoNode"), "error");
|
||||
return;
|
||||
}
|
||||
|
||||
// WebSocket を先に接続してノード sync メッセージを受け取れるようにする
|
||||
const wsOk = await comfyUI.connectWebSocket();
|
||||
if (!wsOk) { showToast("WebSocket connection failed", "error"); return; }
|
||||
if (!wsOk) { showToast(t("wsConnectionFailed"), "error"); return; }
|
||||
|
||||
_s.running = true;
|
||||
_setRunUI(true);
|
||||
@@ -128,13 +211,16 @@ async function _startRun() {
|
||||
const progressText = document.getElementById("wfm-gen-progress-text");
|
||||
const resultImg = document.getElementById("wfm-gen-result-img");
|
||||
|
||||
// image_loop_node_sync メッセージを捕捉するリスナー
|
||||
let _lastSync = null;
|
||||
const _syncHandler = (ev) => {
|
||||
try {
|
||||
const msg = JSON.parse(ev.data);
|
||||
if (msg.type === "image_loop_node_sync" && String(msg.data?.node_id) === String(nodeId)) {
|
||||
_lastSync = msg.data;
|
||||
if (msg.data.thumbnail_path) {
|
||||
const p = msg.data.thumbnail_path;
|
||||
_showPreview(p, p.split("/").pop());
|
||||
}
|
||||
}
|
||||
} catch {}
|
||||
};
|
||||
@@ -152,7 +238,6 @@ async function _startRun() {
|
||||
if (progressBar) progressBar.style.width = "0%";
|
||||
if (progressText) progressText.textContent = `#${++count} 0%`;
|
||||
|
||||
// 右ペインのseed設定を使用(KSamplerに適用される)
|
||||
const seedMode = document.getElementById("wfm-gen-seed-mode")?.value || "random";
|
||||
const seedValue = parseInt(document.getElementById("wfm-gen-seed-value")?.value) || -1;
|
||||
|
||||
@@ -168,7 +253,6 @@ async function _startRun() {
|
||||
}
|
||||
);
|
||||
|
||||
// 右ペインのseed表示を更新(通常の生成と同じ挙動)
|
||||
const seedEl = document.getElementById("wfm-gen-seed-value");
|
||||
if (seedEl) seedEl.value = seed;
|
||||
|
||||
@@ -182,7 +266,6 @@ async function _startRun() {
|
||||
|
||||
if (!_s.running) break;
|
||||
|
||||
// control after generate: ノードから返された next_index を反映
|
||||
const control = document.getElementById("wfm-feeder-control-after")?.value || "loop";
|
||||
if (control === "fixed") {
|
||||
// index を変えない
|
||||
@@ -191,14 +274,13 @@ async function _startRun() {
|
||||
if (indexEl) indexEl.value = _lastSync.next_index;
|
||||
if (control === "increment" && !_lastSync.has_next) {
|
||||
_s.running = false;
|
||||
showToast(`Feeder complete (${count} generated)`, "success");
|
||||
showToast(t("feederComplete", count), "success");
|
||||
break;
|
||||
}
|
||||
// loop: has_next=false でも次は index=0 からなので続行
|
||||
}
|
||||
}
|
||||
} catch (err) {
|
||||
if (_s.running) showToast("Feeder run error: " + err.message, "error");
|
||||
if (_s.running) showToast(t("feederRunError", err.message), "error");
|
||||
} finally {
|
||||
comfyUI.socket?.removeEventListener("message", _syncHandler);
|
||||
_s.running = false;
|
||||
@@ -211,10 +293,107 @@ async function _stopRun() {
|
||||
_s.running = false;
|
||||
try { await comfyUI.interrupt(); } catch {}
|
||||
_setRunUI(false);
|
||||
showToast("Feeder stopped", "info");
|
||||
showToast(t("feederStopped"), "info");
|
||||
}
|
||||
|
||||
// ── Folder Tree ───────────────────────────────────────────────────
|
||||
// ── Gallery Mode Run Loop ─────────────────────────────────────────
|
||||
|
||||
async function _startGalRun() {
|
||||
if (_s.running) return;
|
||||
if (!comfyUI.currentWorkflow) { showToast(t("noWorkflowLoaded"), "error"); return; }
|
||||
if (!comfyUI.connected) { showToast(t("notConnectedToComfyUI"), "error"); return; }
|
||||
|
||||
const nodeId = document.getElementById("wfm-feeder-gal-node-sel")?.value;
|
||||
if (!nodeId || !comfyUI.currentWorkflow[nodeId]) {
|
||||
showToast(t("feederGalNoNode"), "error");
|
||||
return;
|
||||
}
|
||||
if (_gs.images.length === 0) {
|
||||
showToast(t("feederGalEmptyGroup"), "error");
|
||||
return;
|
||||
}
|
||||
|
||||
const wsOk = await comfyUI.connectWebSocket();
|
||||
if (!wsOk) { showToast(t("wsConnectionFailed"), "error"); return; }
|
||||
|
||||
_s.running = true;
|
||||
_setGalRunUI(true);
|
||||
|
||||
const progressBar = document.getElementById("wfm-gen-progress-bar");
|
||||
const progressText = document.getElementById("wfm-gen-progress-text");
|
||||
const resultImg = document.getElementById("wfm-gen-result-img");
|
||||
const indexEl = document.getElementById("wfm-feeder-gal-index");
|
||||
|
||||
const total = _gs.images.length;
|
||||
let count = 0;
|
||||
try {
|
||||
while (_s.running) {
|
||||
_applyToGalNode(nodeId);
|
||||
|
||||
if (progressBar) progressBar.style.width = "0%";
|
||||
if (progressText) progressText.textContent = `#${++count} [${_gs.idx + 1}/${total}] 0%`;
|
||||
|
||||
const seedMode = document.getElementById("wfm-gen-seed-mode")?.value || "random";
|
||||
const seedValue = parseInt(document.getElementById("wfm-gen-seed-value")?.value) || -1;
|
||||
|
||||
const { images, seed } = await comfyUI.generate(
|
||||
{ ...comfyUI.currentWorkflow },
|
||||
{
|
||||
seedMode,
|
||||
seedValue,
|
||||
onProgress: (pct) => {
|
||||
if (progressBar) progressBar.style.width = `${(pct * 100).toFixed(1)}%`;
|
||||
if (progressText) progressText.textContent = `#${count} [${_gs.idx + 1}/${total}] ${(pct * 100).toFixed(0)}%`;
|
||||
},
|
||||
}
|
||||
);
|
||||
|
||||
const seedEl = document.getElementById("wfm-gen-seed-value");
|
||||
if (seedEl) seedEl.value = seed;
|
||||
|
||||
if (progressBar) progressBar.style.width = "100%";
|
||||
|
||||
if (images.length > 0 && resultImg) {
|
||||
const blob = await comfyUI.getImageBlob(images[0]);
|
||||
resultImg.src = URL.createObjectURL(blob);
|
||||
resultImg.style.display = "block";
|
||||
}
|
||||
|
||||
if (!_s.running) break;
|
||||
|
||||
const control = document.getElementById("wfm-feeder-gal-control-after")?.value || "loop";
|
||||
const nextIdx = (_gs.idx + 1) % total;
|
||||
const isLast = _gs.idx === total - 1;
|
||||
|
||||
if (control === "fixed") {
|
||||
// idx を変えない
|
||||
} else if (control === "increment" && isLast) {
|
||||
_s.running = false;
|
||||
showToast(t("feederComplete", count), "success");
|
||||
break;
|
||||
} else {
|
||||
_gs.idx = nextIdx;
|
||||
if (indexEl) indexEl.value = _gs.idx;
|
||||
_highlightGalCard(_gs.images[_gs.idx]);
|
||||
}
|
||||
}
|
||||
} catch (err) {
|
||||
if (_s.running) showToast(t("feederRunError", err.message), "error");
|
||||
} finally {
|
||||
_s.running = false;
|
||||
_setGalRunUI(false);
|
||||
if (progressText) progressText.textContent = `Done (${count} generated)`;
|
||||
}
|
||||
}
|
||||
|
||||
async function _stopGalRun() {
|
||||
_s.running = false;
|
||||
try { await comfyUI.interrupt(); } catch {}
|
||||
_setGalRunUI(false);
|
||||
showToast(t("feederStopped"), "info");
|
||||
}
|
||||
|
||||
// ── Folder Tree (loop mode) ───────────────────────────────────────
|
||||
|
||||
async function _loadTree() {
|
||||
const container = document.getElementById("wfm-feeder-tree");
|
||||
@@ -271,7 +450,7 @@ function _highlightTreeRow(path) {
|
||||
});
|
||||
}
|
||||
|
||||
// ── Image Grid ────────────────────────────────────────────────────
|
||||
// ── Image Grid (loop mode) ────────────────────────────────────────
|
||||
|
||||
async function _loadImages(dir) {
|
||||
const grid = document.getElementById("wfm-feeder-grid");
|
||||
@@ -362,8 +541,6 @@ function _deselectAll() {
|
||||
_updateStatus();
|
||||
}
|
||||
|
||||
// ── Status Bar ───────────────────────────────────────────────────
|
||||
|
||||
function _updateStatus() {
|
||||
const el = document.getElementById("wfm-feeder-status");
|
||||
if (!el) return;
|
||||
@@ -371,6 +548,104 @@ function _updateStatus() {
|
||||
el.textContent = `📂 ${_s.dir || "(root)"} | ${inCurrent} / ${_s.images.length} selected`;
|
||||
}
|
||||
|
||||
// ── Gallery Mode: Group & Image Grid ─────────────────────────────
|
||||
|
||||
async function _loadGalGroups() {
|
||||
try {
|
||||
const res = await fetch("/wfm/gallery/groups");
|
||||
if (!res.ok) throw new Error(res.status);
|
||||
const data = await res.json();
|
||||
_gs.groups = data.groups || [];
|
||||
_renderGalGroupSelect();
|
||||
} catch (err) {
|
||||
console.warn("[Feeder] loadGalGroups failed:", err);
|
||||
}
|
||||
}
|
||||
|
||||
function _renderGalGroupSelect() {
|
||||
const sel = document.getElementById("wfm-feeder-gal-group");
|
||||
if (!sel) return;
|
||||
sel.innerHTML = _gs.groups
|
||||
.map(g => `<option value="${g.name}"${g.name === _gs.group ? " selected" : ""}>${g.name}</option>`)
|
||||
.join("");
|
||||
if (!_gs.groups.find(g => g.name === _gs.group) && _gs.groups.length > 0) {
|
||||
_gs.group = _gs.groups[0].name;
|
||||
}
|
||||
}
|
||||
|
||||
function _setGalGroupSelect(group) {
|
||||
const sel = document.getElementById("wfm-feeder-gal-group");
|
||||
if (sel) sel.value = group;
|
||||
}
|
||||
|
||||
async function _loadGalImages(group) {
|
||||
const grid = document.getElementById("wfm-feeder-gal-grid");
|
||||
const statusEl = document.getElementById("wfm-feeder-gal-status");
|
||||
if (!grid) return;
|
||||
grid.innerHTML = `<div class="wfm-feeder-grid-msg">Loading...</div>`;
|
||||
try {
|
||||
const res = await fetch(`/wfm/gallery/groups/${encodeURIComponent(group)}/images`);
|
||||
if (!res.ok) throw new Error(res.status);
|
||||
const data = await res.json();
|
||||
_gs.images = data.images || [];
|
||||
_gs.idx = 0;
|
||||
const idxEl = document.getElementById("wfm-feeder-gal-index");
|
||||
if (idxEl) idxEl.value = 0;
|
||||
_renderGalGrid();
|
||||
if (statusEl) statusEl.textContent = `${_gs.images.length} image(s) in "${group}"`;
|
||||
} catch (err) {
|
||||
_gs.images = [];
|
||||
grid.innerHTML = `<div class="wfm-feeder-grid-msg" style="color:var(--wfm-danger)">Load failed: ${err.message}</div>`;
|
||||
if (statusEl) statusEl.textContent = "";
|
||||
}
|
||||
}
|
||||
|
||||
function _renderGalGrid() {
|
||||
const grid = document.getElementById("wfm-feeder-gal-grid");
|
||||
if (!grid) return;
|
||||
if (_gs.images.length === 0) {
|
||||
grid.innerHTML = `<div class="wfm-feeder-grid-msg">No images in this group</div>`;
|
||||
return;
|
||||
}
|
||||
grid.innerHTML = "";
|
||||
_gs.images.forEach((absPath, i) => grid.appendChild(_makeGalCard(absPath, i)));
|
||||
}
|
||||
|
||||
function _makeGalCard(absPath, idx) {
|
||||
const fname = absPath.replace(/\\/g, "/").split("/").pop();
|
||||
const card = document.createElement("div");
|
||||
card.className = "wfm-feeder-card" + (idx === _gs.idx ? " selected" : "");
|
||||
card.dataset.path = absPath;
|
||||
card.dataset.idx = idx;
|
||||
|
||||
const img = document.createElement("img");
|
||||
img.className = "wfm-feeder-card-img";
|
||||
img.loading = "lazy";
|
||||
img.src = `/wfm/gallery/image/serve?path=${encodeURIComponent(absPath)}`;
|
||||
img.onerror = () => { img.style.display = "none"; card.style.minHeight = "110px"; };
|
||||
|
||||
const name = document.createElement("div");
|
||||
name.className = "wfm-feeder-card-name";
|
||||
name.textContent = fname;
|
||||
name.title = fname;
|
||||
|
||||
card.append(img, name);
|
||||
card.addEventListener("click", () => {
|
||||
_gs.idx = idx;
|
||||
const idxEl = document.getElementById("wfm-feeder-gal-index");
|
||||
if (idxEl) idxEl.value = idx;
|
||||
_highlightGalCard(absPath);
|
||||
_showGalPreview(absPath, fname);
|
||||
});
|
||||
return card;
|
||||
}
|
||||
|
||||
function _highlightGalCard(absPath) {
|
||||
document.querySelectorAll("#wfm-feeder-gal-grid .wfm-feeder-card").forEach(c => {
|
||||
c.classList.toggle("selected", c.dataset.path === absPath);
|
||||
});
|
||||
}
|
||||
|
||||
// ── Preview Panel ────────────────────────────────────────────────
|
||||
|
||||
async function _showPreview(relPath, fname) {
|
||||
@@ -395,7 +670,20 @@ async function _showPreview(relPath, fname) {
|
||||
} catch { if (infoEl) infoEl.textContent = ""; }
|
||||
}
|
||||
|
||||
// ── Presets ──────────────────────────────────────────────────────
|
||||
async function _showGalPreview(absPath, fname) {
|
||||
const imgEl = document.getElementById("wfm-feeder-preview-img");
|
||||
const nameEl = document.getElementById("wfm-feeder-preview-name");
|
||||
const infoEl = document.getElementById("wfm-feeder-preview-info");
|
||||
|
||||
if (imgEl) {
|
||||
imgEl.src = `/wfm/gallery/image/serve?path=${encodeURIComponent(absPath)}`;
|
||||
imgEl.style.display = "block";
|
||||
}
|
||||
if (nameEl) nameEl.textContent = fname;
|
||||
if (infoEl) infoEl.textContent = "";
|
||||
}
|
||||
|
||||
// ── Presets (loop mode) ───────────────────────────────────────────
|
||||
|
||||
async function _loadPresets() {
|
||||
try {
|
||||
@@ -416,7 +704,7 @@ function _renderPresets() {
|
||||
|
||||
async function _savePreset() {
|
||||
const name = document.getElementById("wfm-feeder-preset-name")?.value.trim();
|
||||
if (!name) { showToast("Enter a preset name", "error"); return; }
|
||||
if (!name) { showToast(t("enterPresetName"), "error"); return; }
|
||||
const sel = _s.images.filter(f => _s.selected.has(f));
|
||||
try {
|
||||
const res = await fetch("/image_feeder/presets", {
|
||||
@@ -425,20 +713,20 @@ async function _savePreset() {
|
||||
body: JSON.stringify({ name, directory: _s.dir, selected_files: sel }),
|
||||
});
|
||||
if (res.ok) {
|
||||
showToast(`Preset saved: ${name}`, "success");
|
||||
showToast(t("presetSavedName", name), "success");
|
||||
const nameInput = document.getElementById("wfm-feeder-preset-name");
|
||||
if (nameInput) nameInput.value = "";
|
||||
await _loadPresets();
|
||||
const selEl = document.getElementById("wfm-feeder-preset-sel");
|
||||
if (selEl) selEl.value = name;
|
||||
} else { showToast("Save failed", "error"); }
|
||||
} catch (err) { showToast("Save error: " + err.message, "error"); }
|
||||
} else { showToast(t("saveFailed"), "error"); }
|
||||
} catch (err) { showToast(t("saveFailed", err.message), "error"); }
|
||||
}
|
||||
|
||||
async function _applyPreset() {
|
||||
const selEl = document.getElementById("wfm-feeder-preset-sel");
|
||||
const name = selEl?.value;
|
||||
if (!name || !_s.presets[name]) { showToast("Select a preset first", "error"); return; }
|
||||
if (!name || !_s.presets[name]) { showToast(t("selectPresetFirst"), "error"); return; }
|
||||
const preset = _s.presets[name];
|
||||
const dir = preset.directory || "";
|
||||
|
||||
@@ -453,7 +741,7 @@ async function _applyPreset() {
|
||||
}
|
||||
_refreshGridCbs();
|
||||
_updateStatus();
|
||||
showToast(`Preset loaded: ${name}`, "success");
|
||||
showToast(t("presetLoaded", name), "success");
|
||||
}
|
||||
|
||||
async function _deletePreset() {
|
||||
@@ -461,9 +749,37 @@ async function _deletePreset() {
|
||||
if (!name) return;
|
||||
try {
|
||||
await fetch(`/image_feeder/presets/${encodeURIComponent(name)}`, { method: "DELETE" });
|
||||
showToast(`Preset deleted: ${name}`, "info");
|
||||
showToast(t("presetDeleted", name), "info");
|
||||
await _loadPresets();
|
||||
} catch (err) { showToast("Delete error", "error"); }
|
||||
} catch (err) { showToast(t("deleteFailed"), "error"); }
|
||||
}
|
||||
|
||||
// ── Mode Switch ───────────────────────────────────────────────────
|
||||
|
||||
function _setMode(mode) {
|
||||
_s.mode = mode;
|
||||
localStorage.setItem("wfm_feeder_mode", mode);
|
||||
|
||||
const loopBtn = document.getElementById("wfm-feeder-mode-loop");
|
||||
const galBtn = document.getElementById("wfm-feeder-mode-gallery");
|
||||
const loopSec = document.getElementById("wfm-feeder-loop-section");
|
||||
const galSec = document.getElementById("wfm-feeder-gal-section");
|
||||
const loopLib = document.getElementById("wfm-feeder-loop-library");
|
||||
const galLib = document.getElementById("wfm-feeder-gal-library");
|
||||
|
||||
const isGallery = mode === "gallery";
|
||||
|
||||
if (loopBtn) loopBtn.classList.toggle("wfm-btn-primary", !isGallery);
|
||||
if (galBtn) galBtn.classList.toggle("wfm-btn-primary", isGallery);
|
||||
if (loopSec) loopSec.style.display = isGallery ? "none" : "";
|
||||
if (galSec) galSec.style.display = isGallery ? "" : "none";
|
||||
if (loopLib) loopLib.style.display = isGallery ? "none" : "";
|
||||
if (galLib) galLib.style.display = isGallery ? "" : "none";
|
||||
|
||||
if (isGallery) {
|
||||
_loadGalGroups().then(() => _loadGalImages(_gs.group));
|
||||
_refreshGalNodeList();
|
||||
}
|
||||
}
|
||||
|
||||
// ── Helpers ───────────────────────────────────────────────────────
|
||||
@@ -480,6 +796,11 @@ function _setCheck(id, val) {
|
||||
// ── Init ─────────────────────────────────────────────────────────
|
||||
|
||||
export async function initFeederTab() {
|
||||
// Mode toggle
|
||||
document.getElementById("wfm-feeder-mode-loop")?.addEventListener("click", () => _setMode("loop"));
|
||||
document.getElementById("wfm-feeder-mode-gallery")?.addEventListener("click", () => _setMode("gallery"));
|
||||
|
||||
// ── Image Loop mode events ──
|
||||
document.getElementById("wfm-feeder-node-sel")?.addEventListener("change", e => {
|
||||
_loadFromNode(e.target.value);
|
||||
});
|
||||
@@ -506,5 +827,33 @@ export async function initFeederTab() {
|
||||
document.getElementById("wfm-feeder-run-btn")?.addEventListener("click", _startRun);
|
||||
document.getElementById("wfm-feeder-stop-btn")?.addEventListener("click", _stopRun);
|
||||
|
||||
await Promise.all([_loadTree(), _loadPresets()]);
|
||||
// ── Gallery mode events ──
|
||||
document.getElementById("wfm-feeder-gal-node-sel")?.addEventListener("change", e => {
|
||||
_loadFromGalNode(e.target.value);
|
||||
});
|
||||
|
||||
document.getElementById("wfm-feeder-gal-apply-btn")?.addEventListener("click", _applyGalToWorkflow);
|
||||
|
||||
document.getElementById("wfm-feeder-gal-group")?.addEventListener("change", e => {
|
||||
_gs.group = e.target.value;
|
||||
_gs.idx = 0;
|
||||
_loadGalImages(_gs.group);
|
||||
});
|
||||
|
||||
document.getElementById("wfm-feeder-gal-index")?.addEventListener("change", e => {
|
||||
_gs.idx = Math.max(0, parseInt(e.target.value) || 0);
|
||||
if (_gs.images[_gs.idx]) _highlightGalCard(_gs.images[_gs.idx]);
|
||||
});
|
||||
|
||||
document.getElementById("wfm-feeder-gal-run-btn")?.addEventListener("click", _startGalRun);
|
||||
document.getElementById("wfm-feeder-gal-stop-btn")?.addEventListener("click", _stopGalRun);
|
||||
|
||||
// 初期化
|
||||
await ensureFeederGroup();
|
||||
_setMode(_s.mode);
|
||||
|
||||
if (_s.mode === "loop") {
|
||||
await Promise.all([_loadTree(), _loadPresets()]);
|
||||
_selectDir("");
|
||||
}
|
||||
}
|
||||
|
||||
+414
-101
@@ -5,6 +5,10 @@
|
||||
|
||||
import { showToast } from "./app.js";
|
||||
import { t } from "./i18n.js";
|
||||
import { loadFileIntoMetadataTab } from "./metadata-tab.js";
|
||||
import { loadWorkflowIntoEditor } from "./generate-tab.js";
|
||||
import { escapeHtml } from "./util.js";
|
||||
import { comfyWorkflow } from "./comfyui-workflow.js";
|
||||
|
||||
// ── 定数 ─────────────────────────────────────────────────────
|
||||
|
||||
@@ -14,20 +18,33 @@ const API = {
|
||||
imageMeta: (path) => `/wfm/gallery/image/meta?path=${encodeURIComponent(path)}`,
|
||||
imageWorkflow: (path) => `/wfm/gallery/image/workflow?path=${encodeURIComponent(path)}`,
|
||||
serveImage: (path) => `/wfm/gallery/image/serve?path=${encodeURIComponent(path)}`,
|
||||
thumb: (path, w = 256) => `/wfm/gallery/image/thumb?path=${encodeURIComponent(path)}&w=${w}`,
|
||||
bulkFavorite: "/wfm/gallery/bulk/favorite",
|
||||
bulkGroup: "/wfm/gallery/bulk/group",
|
||||
saveImageMeta: `/wfm/gallery/image/meta`,
|
||||
toggleFavorite: `/wfm/gallery/image/favorite`,
|
||||
groups: `/wfm/gallery/groups`,
|
||||
groupCreate: `/wfm/gallery/groups`,
|
||||
groupEnsure: `/wfm/gallery/groups/ensure`,
|
||||
groupRename: (name) => `/wfm/gallery/groups/${encodeURIComponent(name)}`,
|
||||
groupDelete: (name) => `/wfm/gallery/groups/${encodeURIComponent(name)}`,
|
||||
groupAdd: (name) => `/wfm/gallery/groups/${encodeURIComponent(name)}/add`,
|
||||
groupRemove: (name) => `/wfm/gallery/groups/${encodeURIComponent(name)}/remove`,
|
||||
groupClear: (name) => `/wfm/gallery/groups/${encodeURIComponent(name)}/clear`,
|
||||
groupImages: (name) => `/wfm/gallery/groups/${encodeURIComponent(name)}/images`,
|
||||
folderCreate: `/wfm/gallery/folder`,
|
||||
folderDelete: `/wfm/gallery/folder`,
|
||||
imagesDelete: `/wfm/gallery/images/delete`,
|
||||
imagesMove: `/wfm/gallery/images/move`,
|
||||
};
|
||||
|
||||
export const FEEDER_GROUP = "__Feeder__";
|
||||
|
||||
// ── ページング ────────────────────────────────────────────────
|
||||
const PAGE_SIZE = 50;
|
||||
let _renderedCount = 0;
|
||||
let _scrollObserver = null;
|
||||
|
||||
// ── 状態 ─────────────────────────────────────────────────────
|
||||
|
||||
const state = {
|
||||
@@ -65,6 +82,18 @@ function formatDate(mtime) {
|
||||
return new Date(mtime * 1000).toLocaleString();
|
||||
}
|
||||
|
||||
async function openImageInMetadataTab(img) {
|
||||
try {
|
||||
const res = await fetch(API.serveImage(img.path));
|
||||
if (!res.ok) throw new Error(`HTTP ${res.status}`);
|
||||
const blob = await res.blob();
|
||||
const file = new File([blob], img.filename, { type: blob.type || "image/png" });
|
||||
await loadFileIntoMetadataTab(file);
|
||||
} catch (e) {
|
||||
showToast(t("errorWithMsg", e.message), "error");
|
||||
}
|
||||
}
|
||||
|
||||
// ── フォルダツリー ────────────────────────────────────────────
|
||||
|
||||
function _getExpandedPaths() {
|
||||
@@ -116,7 +145,7 @@ async function loadFolderTree() {
|
||||
try {
|
||||
const data = await apiFetch(API.folders(state.outputRoot));
|
||||
if (data.error) {
|
||||
tree.innerHTML = `<p class="wfm-placeholder">${data.error}</p>`;
|
||||
tree.innerHTML = `<p class="wfm-placeholder">${escapeHtml(data.error)}</p>`;
|
||||
return;
|
||||
}
|
||||
state.folderTree = data;
|
||||
@@ -132,7 +161,7 @@ async function loadFolderTree() {
|
||||
_restoreTreeState(expandedPaths, state.currentFolder);
|
||||
}
|
||||
} catch (e) {
|
||||
tree.innerHTML = `<p class="wfm-placeholder">Error: ${e.message}</p>`;
|
||||
tree.innerHTML = `<p class="wfm-placeholder">Error: ${escapeHtml(e.message)}</p>`;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -240,7 +269,7 @@ async function loadImages() {
|
||||
renderImages();
|
||||
updateTagFilter(state.images);
|
||||
} catch (e) {
|
||||
grid.innerHTML = `<p class="wfm-placeholder">Error: ${e.message}</p>`;
|
||||
grid.innerHTML = `<p class="wfm-placeholder">Error: ${escapeHtml(e.message)}</p>`;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -248,6 +277,9 @@ function renderImages() {
|
||||
const grid = document.getElementById("wfm-gallery-grid");
|
||||
grid.className = `wfm-gallery-grid wfm-gallery-view-${state.viewMode}`;
|
||||
|
||||
_disconnectScrollObserver();
|
||||
_renderedCount = 0;
|
||||
|
||||
if (state.images.length === 0) {
|
||||
grid.innerHTML = `<p class="wfm-placeholder">No images found.</p>`;
|
||||
return;
|
||||
@@ -256,15 +288,53 @@ function renderImages() {
|
||||
grid.innerHTML = "";
|
||||
|
||||
if (state.viewMode === "thumb") {
|
||||
state.images.forEach(img => {
|
||||
const card = createThumbCard(img);
|
||||
grid.appendChild(card);
|
||||
});
|
||||
_appendNextPage(grid);
|
||||
if (_renderedCount < state.images.length) {
|
||||
_attachScrollSentinel(grid);
|
||||
}
|
||||
} else {
|
||||
grid.appendChild(createTable(state.images));
|
||||
}
|
||||
}
|
||||
|
||||
function _appendNextPage(grid) {
|
||||
const end = Math.min(_renderedCount + PAGE_SIZE, state.images.length);
|
||||
const fragment = document.createDocumentFragment();
|
||||
for (let i = _renderedCount; i < end; i++) {
|
||||
fragment.appendChild(createThumbCard(state.images[i]));
|
||||
}
|
||||
grid.appendChild(fragment);
|
||||
_renderedCount = end;
|
||||
}
|
||||
|
||||
function _disconnectScrollObserver() {
|
||||
if (_scrollObserver) {
|
||||
_scrollObserver.disconnect();
|
||||
_scrollObserver = null;
|
||||
}
|
||||
document.getElementById("wfm-gallery-scroll-sentinel")?.remove();
|
||||
}
|
||||
|
||||
function _attachScrollSentinel(grid) {
|
||||
const sentinel = document.createElement("div");
|
||||
sentinel.id = "wfm-gallery-scroll-sentinel";
|
||||
sentinel.style.cssText = "height:1px;width:100%;grid-column:1/-1";
|
||||
grid.appendChild(sentinel);
|
||||
|
||||
_scrollObserver = new IntersectionObserver((entries) => {
|
||||
if (!entries[0].isIntersecting) return;
|
||||
_appendNextPage(grid);
|
||||
if (_renderedCount >= state.images.length) {
|
||||
_disconnectScrollObserver();
|
||||
} else {
|
||||
// sentinel を末尾に移動
|
||||
grid.appendChild(sentinel);
|
||||
}
|
||||
}, { rootMargin: "300px" });
|
||||
|
||||
_scrollObserver.observe(sentinel);
|
||||
}
|
||||
|
||||
function createThumbCard(img) {
|
||||
const card = document.createElement("div");
|
||||
card.className = "wfm-gallery-thumb-card";
|
||||
@@ -280,7 +350,7 @@ function createThumbCard(img) {
|
||||
const imgEl = document.createElement("img");
|
||||
imgEl.className = "wfm-gallery-thumb-img";
|
||||
imgEl.loading = "lazy";
|
||||
imgEl.src = API.serveImage(img.path);
|
||||
imgEl.src = API.thumb(img.path);
|
||||
imgEl.alt = img.filename;
|
||||
imgEl.onerror = () => {
|
||||
imgEl.style.display = "none";
|
||||
@@ -302,8 +372,25 @@ function createThumbCard(img) {
|
||||
});
|
||||
card.appendChild(favBtn);
|
||||
|
||||
// クリック: 詳細表示 / Ctrl+クリック: 複数選択
|
||||
// Feederグループトグルボタン(カード左上)
|
||||
const inFeeder = (img.groups || []).includes(FEEDER_GROUP);
|
||||
const feederBtn = document.createElement("button");
|
||||
feederBtn.className = `wfm-gallery-thumb-feeder-btn${inFeeder ? " active" : ""}`;
|
||||
feederBtn.title = inFeeder ? "Remove from Feeder" : "Add to Feeder";
|
||||
feederBtn.textContent = "F";
|
||||
feederBtn.addEventListener("click", async (e) => {
|
||||
e.stopPropagation();
|
||||
await toggleFeederGroupInPlace(img, feederBtn);
|
||||
});
|
||||
card.appendChild(feederBtn);
|
||||
|
||||
// クリック: 詳細表示 / Ctrl+クリック: 複数選択 / Alt+クリック: Metadataタブで開く
|
||||
card.addEventListener("click", (e) => {
|
||||
if (e.altKey) {
|
||||
e.preventDefault();
|
||||
openImageInMetadataTab(img);
|
||||
return;
|
||||
}
|
||||
if (e.ctrlKey || e.metaKey) {
|
||||
// 複数選択トグル
|
||||
if (state.selectedImages.has(img.path)) {
|
||||
@@ -371,7 +458,7 @@ function createTable(images) {
|
||||
tdFav.appendChild(favBtn);
|
||||
|
||||
const tdThumb = document.createElement("td");
|
||||
tdThumb.innerHTML = `<img src="${API.serveImage(img.path)}" class="wfm-gallery-table-thumb" loading="lazy" alt="">`;
|
||||
tdThumb.innerHTML = `<img src="${API.thumb(img.path, 128)}" class="wfm-gallery-table-thumb" loading="lazy" alt="">`;
|
||||
|
||||
const tdName = document.createElement("td");
|
||||
tdName.className = "wfm-gallery-table-name";
|
||||
@@ -385,7 +472,7 @@ function createTable(images) {
|
||||
tdDate.textContent = formatDate(img.mtime);
|
||||
|
||||
const tdTags = document.createElement("td");
|
||||
tdTags.innerHTML = (img.tags || []).map(tag => `<span class="wfm-gallery-tag-badge">${tag}</span>`).join("");
|
||||
tdTags.innerHTML = (img.tags || []).map(tag => `<span class="wfm-gallery-tag-badge">${escapeHtml(tag)}</span>`).join("");
|
||||
|
||||
tr.appendChild(tdFav);
|
||||
tr.appendChild(tdThumb);
|
||||
@@ -394,8 +481,13 @@ function createTable(images) {
|
||||
tr.appendChild(tdDate);
|
||||
tr.appendChild(tdTags);
|
||||
|
||||
// クリック: 詳細表示 / Ctrl+クリック: 複数選択
|
||||
// クリック: 詳細表示 / Ctrl+クリック: 複数選択 / Alt+クリック: Metadataタブで開く
|
||||
tr.addEventListener("click", (e) => {
|
||||
if (e.altKey) {
|
||||
e.preventDefault();
|
||||
openImageInMetadataTab(img);
|
||||
return;
|
||||
}
|
||||
if (e.ctrlKey || e.metaKey) {
|
||||
if (state.selectedImages.has(img.path)) {
|
||||
state.selectedImages.delete(img.path);
|
||||
@@ -430,10 +522,17 @@ function updateBulkBar() {
|
||||
const count = state.selectedImages.size;
|
||||
if (count > 0) {
|
||||
bar.style.display = "";
|
||||
countEl.textContent = `${count} selected`;
|
||||
countEl.textContent = `${count} ${t("galleryBulkSelected")}`;
|
||||
} else {
|
||||
bar.style.display = "none";
|
||||
}
|
||||
// Compare ボタンは 2〜4 枚選択時のみ表示
|
||||
const compareBtn = document.getElementById("wfm-gallery-bulk-compare");
|
||||
if (compareBtn) {
|
||||
const show = count >= 2 && count <= 4;
|
||||
compareBtn.style.display = show ? "" : "none";
|
||||
compareBtn.textContent = t("galleryBulkCompare");
|
||||
}
|
||||
}
|
||||
|
||||
// ── お気に入りトグル(インプレース更新) ─────────────────────────
|
||||
@@ -456,7 +555,40 @@ async function toggleFavoriteInPlace(img, btn) {
|
||||
state.selectedImage.favorite = data.favorite;
|
||||
}
|
||||
} catch (e) {
|
||||
showToast(`Error: ${e.message}`, "error");
|
||||
showToast(t("errorWithMsg", e.message), "error");
|
||||
}
|
||||
}
|
||||
|
||||
async function toggleFeederGroupInPlace(img, btn) {
|
||||
const inFeeder = (img.groups || []).includes(FEEDER_GROUP);
|
||||
try {
|
||||
if (inFeeder) {
|
||||
await fetch(API.groupRemove(FEEDER_GROUP), {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify({ path: img.path }),
|
||||
});
|
||||
img.groups = (img.groups || []).filter(g => g !== FEEDER_GROUP);
|
||||
showToast(t("removedFromFeeder"), "success");
|
||||
} else {
|
||||
await fetch(API.groupAdd(FEEDER_GROUP), {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify({ path: img.path }),
|
||||
});
|
||||
img.groups = [...(img.groups || []), FEEDER_GROUP];
|
||||
showToast(t("addedToFeeder"), "success");
|
||||
}
|
||||
const cached = state.images.find(i => i.path === img.path);
|
||||
if (cached) cached.groups = img.groups;
|
||||
const nowInFeeder = img.groups.includes(FEEDER_GROUP);
|
||||
btn.classList.toggle("active", nowInFeeder);
|
||||
btn.title = nowInFeeder ? "Remove from Feeder" : "Add to Feeder";
|
||||
if (state.selectedImage && state.selectedImage.path === img.path) {
|
||||
state.selectedImage.groups = img.groups;
|
||||
}
|
||||
} catch (e) {
|
||||
showToast(t("errorWithMsg", e.message), "error");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -479,6 +611,13 @@ function updateTagFilter(images) {
|
||||
|
||||
// ── 詳細パネル ────────────────────────────────────────────────
|
||||
|
||||
function _updateCopyCanvasBtn() {
|
||||
const btn = document.getElementById("wfm-gallery-copy-workflow-btn");
|
||||
if (!btn) return;
|
||||
btn.disabled = !state.embeddedWorkflow;
|
||||
btn.title = "";
|
||||
}
|
||||
|
||||
async function loadImageDetail(img) {
|
||||
// ファイル操作ボタンを有効化
|
||||
const moveBtn = document.getElementById("wfm-gallery-img-move-btn");
|
||||
@@ -488,7 +627,7 @@ async function loadImageDetail(img) {
|
||||
|
||||
// プレビュー
|
||||
const preview = document.getElementById("wfm-gallery-detail-preview");
|
||||
preview.innerHTML = `<img src="${API.serveImage(img.path)}" class="wfm-gallery-detail-img" alt="${img.filename}" title="Double-click to enlarge">`;
|
||||
preview.innerHTML = `<img src="${API.serveImage(img.path)}" class="wfm-gallery-detail-img" alt="${escapeHtml(img.filename)}" title="Double-click to enlarge">`;
|
||||
preview.querySelector("img").addEventListener("dblclick", () => openLightbox(img));
|
||||
|
||||
// ファイル名
|
||||
@@ -513,8 +652,10 @@ async function loadImageDetail(img) {
|
||||
]);
|
||||
state.embeddedWorkflow = wfRes.has_workflow ? wfRes.workflow : null;
|
||||
renderWorkflowJson(state.embeddedWorkflow);
|
||||
_updateCopyCanvasBtn();
|
||||
} catch (e) {
|
||||
renderWorkflowJson(null);
|
||||
_updateCopyCanvasBtn();
|
||||
}
|
||||
|
||||
// グループタブ更新
|
||||
@@ -527,7 +668,7 @@ function renderTagsDisplay(tags) {
|
||||
tags.forEach(tag => {
|
||||
const span = document.createElement("span");
|
||||
span.className = "wfm-gallery-tag-badge wfm-gallery-tag-removable";
|
||||
span.innerHTML = `${tag} <button class="wfm-gallery-tag-remove" data-tag="${tag}" title="Remove">×</button>`;
|
||||
span.innerHTML = `${escapeHtml(tag)} <button class="wfm-gallery-tag-remove" data-tag="${escapeHtml(tag)}" title="Remove">×</button>`;
|
||||
span.querySelector("button").addEventListener("click", () => removeTag(tag));
|
||||
container.appendChild(span);
|
||||
});
|
||||
@@ -582,7 +723,7 @@ async function saveMetaField(fields) {
|
||||
const idx = state.images.findIndex(i => i.path === state.selectedImage.path);
|
||||
if (idx >= 0) Object.assign(state.images[idx], fields);
|
||||
} catch (e) {
|
||||
showToast(`Save failed: ${e.message}`, "error");
|
||||
showToast(t("saveFailed", e.message), "error");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -602,6 +743,34 @@ async function loadGroups() {
|
||||
}
|
||||
}
|
||||
|
||||
/** Feederグループ(__Feeder__)が存在しない場合に作成する */
|
||||
export async function ensureFeederGroup() {
|
||||
try {
|
||||
await fetch(API.groupEnsure, {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify({ name: FEEDER_GROUP }),
|
||||
});
|
||||
await loadGroups();
|
||||
} catch (e) {
|
||||
console.warn("[Gallery] ensureFeederGroup error:", e);
|
||||
}
|
||||
}
|
||||
|
||||
/** Feederグループ内の全画像を除外する(FC ボタン) */
|
||||
async function clearFeederGroup() {
|
||||
try {
|
||||
await fetch(API.groupClear(FEEDER_GROUP), { method: "POST" });
|
||||
showToast(t("feederGroupCleared"), "success");
|
||||
// グループフィルタが __Feeder__ ならリロード
|
||||
if (state.groupFilter === FEEDER_GROUP) {
|
||||
await loadImages();
|
||||
}
|
||||
} catch (e) {
|
||||
showToast(t("errorWithMsg", e.message), "error");
|
||||
}
|
||||
}
|
||||
|
||||
/** ツールバーのグループフィルタと一括バーのセレクトを更新 */
|
||||
function _updateGroupSelects() {
|
||||
// ツールバー: グループフィルタ
|
||||
@@ -622,7 +791,7 @@ function _updateGroupSelects() {
|
||||
const bulkSel = document.getElementById("wfm-gallery-bulk-group-select");
|
||||
if (bulkSel) {
|
||||
const current = bulkSel.value;
|
||||
bulkSel.innerHTML = `<option value="">Add to Group...</option>`;
|
||||
bulkSel.innerHTML = `<option value="">${t("galleryBulkAddToGroup")}</option>`;
|
||||
state.groups.forEach(g => {
|
||||
const opt = document.createElement("option");
|
||||
opt.value = g.name;
|
||||
@@ -680,12 +849,15 @@ function renderDetailGroup(img) {
|
||||
<select id="wfm-gallery-grp-manage-sel" class="wfm-select" style="flex:1;font-size:12px;padding:3px 6px;">
|
||||
${allGroups.length === 0
|
||||
? `<option value="">${t("modelsNoGroupAvailable")}</option>`
|
||||
: allGroups.map(g => `<option value="${escapeHtml(g)}">${escapeHtml(g)}</option>`).join("")}
|
||||
: allGroups.map(g => {
|
||||
const label = g === FEEDER_GROUP ? `🔒 ${escapeHtml(g)}` : escapeHtml(g);
|
||||
return `<option value="${escapeHtml(g)}">${label}</option>`;
|
||||
}).join("")}
|
||||
</select>
|
||||
<button class="wfm-btn wfm-btn-sm" id="wfm-gallery-grp-rename-btn"
|
||||
${allGroups.length === 0 ? "disabled" : ""} title="${t("modelsRename")}">✎</button>
|
||||
${allGroups.length === 0 || allGroups[0] === FEEDER_GROUP ? "disabled" : ""} title="${t("modelsRename")}">✎</button>
|
||||
<button class="wfm-btn wfm-btn-sm wfm-btn-danger" id="wfm-gallery-grp-delete-btn"
|
||||
${allGroups.length === 0 ? "disabled" : ""} title="${t("modelsDelete")}">×</button>
|
||||
${allGroups.length === 0 || allGroups[0] === FEEDER_GROUP ? "disabled" : ""} title="${t("modelsDelete")}">×</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
@@ -705,9 +877,9 @@ function renderDetailGroup(img) {
|
||||
const cached = state.images.find(i => i.path === img.path);
|
||||
if (cached) cached.groups = img.groups;
|
||||
renderDetailGroup(img);
|
||||
showToast(`Removed from "${g}"`, "success");
|
||||
showToast(t("removedFromGroupName", g), "success");
|
||||
} catch (e) {
|
||||
showToast(`Error: ${e.message}`, "error");
|
||||
showToast(t("errorWithMsg", e.message), "error");
|
||||
}
|
||||
});
|
||||
});
|
||||
@@ -727,9 +899,9 @@ function renderDetailGroup(img) {
|
||||
const cached = state.images.find(i => i.path === img.path);
|
||||
if (cached) cached.groups = img.groups;
|
||||
renderDetailGroup(img);
|
||||
showToast(`Added to "${g}"`, "success");
|
||||
showToast(t("addedToGroupName", g), "success");
|
||||
} catch (e) {
|
||||
showToast(`Error: ${e.message}`, "error");
|
||||
showToast(t("errorWithMsg", e.message), "error");
|
||||
}
|
||||
});
|
||||
|
||||
@@ -739,7 +911,7 @@ function renderDetailGroup(img) {
|
||||
const name = input?.value.trim();
|
||||
if (!name) return;
|
||||
if (state.groups.some(g => g.name === name)) {
|
||||
showToast("Group already exists", "warning");
|
||||
showToast(t("groupExists"), "warning");
|
||||
return;
|
||||
}
|
||||
try {
|
||||
@@ -759,12 +931,21 @@ function renderDetailGroup(img) {
|
||||
if (cached) cached.groups = img.groups;
|
||||
input.value = "";
|
||||
await loadGroups(); // セレクト類を更新
|
||||
showToast(`Group "${name}" created`, "success");
|
||||
showToast(t("groupCreated", name), "success");
|
||||
} catch (e) {
|
||||
showToast(`Error: ${e.message}`, "error");
|
||||
showToast(t("errorWithMsg", e.message), "error");
|
||||
}
|
||||
});
|
||||
|
||||
// 管理セレクト変更時: __Feeder__ は rename/delete を無効化
|
||||
el.querySelector("#wfm-gallery-grp-manage-sel")?.addEventListener("change", (e) => {
|
||||
const isReserved = e.target.value === FEEDER_GROUP;
|
||||
const renameBtn = el.querySelector("#wfm-gallery-grp-rename-btn");
|
||||
const deleteBtn = el.querySelector("#wfm-gallery-grp-delete-btn");
|
||||
if (renameBtn) renameBtn.disabled = isReserved;
|
||||
if (deleteBtn) deleteBtn.disabled = isReserved;
|
||||
});
|
||||
|
||||
// グループ名変更
|
||||
el.querySelector("#wfm-gallery-grp-rename-btn")?.addEventListener("click", async () => {
|
||||
const sel = el.querySelector("#wfm-gallery-grp-manage-sel");
|
||||
@@ -773,7 +954,7 @@ function renderDetailGroup(img) {
|
||||
const newName = prompt(`Rename group "${oldName}" to:`, oldName);
|
||||
if (!newName || newName === oldName) return;
|
||||
if (state.groups.some(g => g.name === newName)) {
|
||||
showToast("Group name already exists", "warning");
|
||||
showToast(t("groupNameExists"), "warning");
|
||||
return;
|
||||
}
|
||||
try {
|
||||
@@ -796,9 +977,9 @@ function renderDetailGroup(img) {
|
||||
state.groupFilter = newName;
|
||||
}
|
||||
await loadGroups();
|
||||
showToast(`Renamed to "${newName}"`, "success");
|
||||
showToast(t("renamedTo", newName), "success");
|
||||
} catch (e) {
|
||||
showToast(`Error: ${e.message}`, "error");
|
||||
showToast(t("errorWithMsg", e.message), "error");
|
||||
}
|
||||
});
|
||||
|
||||
@@ -819,26 +1000,19 @@ function renderDetailGroup(img) {
|
||||
if (filterSel) filterSel.value = "";
|
||||
}
|
||||
await loadGroups();
|
||||
showToast(`Group "${name}" deleted`, "success");
|
||||
showToast(t("groupDeleted", name), "success");
|
||||
} catch (e) {
|
||||
showToast(`Error: ${e.message}`, "error");
|
||||
showToast(t("errorWithMsg", e.message), "error");
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
function escapeHtml(str) {
|
||||
return String(str)
|
||||
.replace(/&/g, "&")
|
||||
.replace(/</g, "<")
|
||||
.replace(/>/g, ">")
|
||||
.replace(/"/g, """);
|
||||
}
|
||||
|
||||
// ── フォルダ作成・削除 ────────────────────────────────────────
|
||||
|
||||
async function createFolder() {
|
||||
if (!state.currentFolder) {
|
||||
showToast("Please select a parent folder first", "error");
|
||||
showToast(t("selectParentFolderFirst"), "error");
|
||||
return;
|
||||
}
|
||||
const name = prompt("New folder name:");
|
||||
@@ -851,13 +1025,13 @@ async function createFolder() {
|
||||
});
|
||||
const data = await res.json();
|
||||
if (!data.ok) {
|
||||
showToast(`Error: ${data.error}`, "error");
|
||||
showToast(t("errorWithMsg", data.error), "error");
|
||||
return;
|
||||
}
|
||||
showToast(`Folder "${name.trim()}" created`, "success");
|
||||
showToast(t("folderCreated", name.trim()), "success");
|
||||
await loadFolderTree();
|
||||
} catch (e) {
|
||||
showToast(`Error: ${e.message}`, "error");
|
||||
showToast(t("errorWithMsg", e.message), "error");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -872,16 +1046,16 @@ async function deleteFolder() {
|
||||
});
|
||||
const data = await res.json();
|
||||
if (!data.ok) {
|
||||
showToast(`Error: ${data.error}`, "error");
|
||||
showToast(t("errorWithMsg", data.error), "error");
|
||||
return;
|
||||
}
|
||||
showToast("Folder deleted", "success");
|
||||
showToast(t("folderDeleted"), "success");
|
||||
state.currentFolder = "";
|
||||
state.images = [];
|
||||
document.getElementById("wfm-gallery-grid").innerHTML = `<p class="wfm-placeholder">Select a folder to browse images.</p>`;
|
||||
await loadFolderTree();
|
||||
} catch (e) {
|
||||
showToast(`Error: ${e.message}`, "error");
|
||||
showToast(t("errorWithMsg", e.message), "error");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -896,7 +1070,7 @@ async function performDeleteImages(paths) {
|
||||
});
|
||||
const data = await res.json();
|
||||
if (data.deleted && data.deleted.length > 0) {
|
||||
showToast(`Deleted ${data.deleted.length} image(s)`, "success");
|
||||
showToast(t("deletedNImages", data.deleted.length), "success");
|
||||
// 削除された画像をstateから除去
|
||||
const deletedSet = new Set(data.deleted);
|
||||
state.images = state.images.filter(img => !deletedSet.has(img.path));
|
||||
@@ -916,10 +1090,10 @@ async function performDeleteImages(paths) {
|
||||
loadFolderTree();
|
||||
}
|
||||
if (data.errors && data.errors.length > 0) {
|
||||
showToast(`Errors: ${data.errors.join(", ")}`, "error");
|
||||
showToast(t("errorsList", data.errors.join(", ")), "error");
|
||||
}
|
||||
} catch (e) {
|
||||
showToast(`Error: ${e.message}`, "error");
|
||||
showToast(t("errorWithMsg", e.message), "error");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -932,7 +1106,7 @@ async function performMoveImages(paths, destFolder) {
|
||||
});
|
||||
const data = await res.json();
|
||||
if (data.moved && data.moved.length > 0) {
|
||||
showToast(`Moved ${data.moved.length} image(s)`, "success");
|
||||
showToast(t("movedNImages", data.moved.length), "success");
|
||||
const movedSet = new Set(data.moved.map(m => m.from));
|
||||
state.images = state.images.filter(img => !movedSet.has(img.path));
|
||||
state.selectedImages = new Set([...state.selectedImages].filter(p => !movedSet.has(p)));
|
||||
@@ -950,13 +1124,13 @@ async function performMoveImages(paths, destFolder) {
|
||||
loadFolderTree();
|
||||
}
|
||||
if (data.errors && data.errors.length > 0) {
|
||||
showToast(`Errors: ${data.errors.join(", ")}`, "error");
|
||||
showToast(t("errorsList", data.errors.join(", ")), "error");
|
||||
}
|
||||
if (data.error) {
|
||||
showToast(`Error: ${data.error}`, "error");
|
||||
showToast(t("errorWithMsg", data.error), "error");
|
||||
}
|
||||
} catch (e) {
|
||||
showToast(`Error: ${e.message}`, "error");
|
||||
showToast(t("errorWithMsg", e.message), "error");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -978,7 +1152,7 @@ function openMoveModal(paths) {
|
||||
const destinations = allFolders.filter(f => f.abs_path !== state.currentFolder);
|
||||
|
||||
if (destinations.length === 0) {
|
||||
showToast("No other folders available. Create a subfolder first.", "error");
|
||||
showToast(t("noOtherFolders"), "error");
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -1014,46 +1188,76 @@ function openMoveModal(paths) {
|
||||
async function bulkAddToGroup(groupName) {
|
||||
if (!groupName || state.selectedImages.size === 0) return;
|
||||
const paths = [...state.selectedImages];
|
||||
let success = 0;
|
||||
for (const path of paths) {
|
||||
try {
|
||||
await fetch(API.groupAdd(groupName), {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify({ path }),
|
||||
try {
|
||||
const res = await fetch(API.bulkGroup, {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify({ paths, group: groupName, action: "add" }),
|
||||
});
|
||||
const data = await res.json();
|
||||
if (data.ok > 0) {
|
||||
paths.forEach(path => {
|
||||
const img = state.images.find(im => im.path === path);
|
||||
if (img) {
|
||||
if (!img.groups) img.groups = [];
|
||||
if (!img.groups.includes(groupName)) img.groups.push(groupName);
|
||||
}
|
||||
});
|
||||
// キャッシュ更新
|
||||
const img = state.images.find(i => i.path === path);
|
||||
if (img) {
|
||||
if (!img.groups) img.groups = [];
|
||||
if (!img.groups.includes(groupName)) img.groups.push(groupName);
|
||||
}
|
||||
success++;
|
||||
} catch (e) { /* continue */ }
|
||||
}
|
||||
showToast(t("addedNImagesToGroup", data.ok, groupName), "success");
|
||||
} catch (e) {
|
||||
showToast(t("errorWithMsg", e.message), "error");
|
||||
}
|
||||
}
|
||||
|
||||
async function bulkRemoveFromGroup(groupName) {
|
||||
if (!groupName || state.selectedImages.size === 0) return;
|
||||
const paths = [...state.selectedImages];
|
||||
try {
|
||||
const res = await fetch(API.bulkGroup, {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify({ paths, group: groupName, action: "remove" }),
|
||||
});
|
||||
const data = await res.json();
|
||||
if (data.ok > 0) {
|
||||
paths.forEach(path => {
|
||||
const img = state.images.find(im => im.path === path);
|
||||
if (img && img.groups) {
|
||||
img.groups = img.groups.filter(g => g !== groupName);
|
||||
}
|
||||
});
|
||||
}
|
||||
showToast(t("removedNImagesFromGroup", data.ok, groupName), "success");
|
||||
} catch (e) {
|
||||
showToast(t("errorWithMsg", e.message), "error");
|
||||
}
|
||||
showToast(`Added ${success} image(s) to "${groupName}"`, "success");
|
||||
}
|
||||
|
||||
async function bulkSetFavorite(favoriteValue) {
|
||||
if (state.selectedImages.size === 0) return;
|
||||
const paths = [...state.selectedImages];
|
||||
let success = 0;
|
||||
for (const path of paths) {
|
||||
try {
|
||||
const img = state.images.find(i => i.path === path);
|
||||
if (!img || img.favorite === favoriteValue) continue;
|
||||
await fetch(API.toggleFavorite, {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify({ path }),
|
||||
const paths = [...state.selectedImages].filter(path => {
|
||||
const img = state.images.find(i => i.path === path);
|
||||
return img && img.favorite !== favoriteValue;
|
||||
});
|
||||
if (paths.length === 0) return;
|
||||
try {
|
||||
const res = await fetch(API.bulkFavorite, {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify({ paths, value: favoriteValue }),
|
||||
});
|
||||
const data = await res.json();
|
||||
if (data.ok > 0) {
|
||||
paths.forEach(path => {
|
||||
const img = state.images.find(im => im.path === path);
|
||||
if (img) img.favorite = favoriteValue;
|
||||
});
|
||||
img.favorite = favoriteValue;
|
||||
success++;
|
||||
} catch (e) { /* continue */ }
|
||||
}
|
||||
if (success > 0) {
|
||||
showToast(`${favoriteValue ? "Favorited" : "Unfavorited"} ${success} image(s)`, "success");
|
||||
renderImages(); // お気に入り状態が変わったのでビュー更新
|
||||
showToast(favoriteValue ? t("favoritedNImages", data.ok) : t("unfavoritedNImages", data.ok), "success");
|
||||
renderImages();
|
||||
}
|
||||
} catch (e) {
|
||||
showToast(t("errorWithMsg", e.message), "error");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1064,8 +1268,8 @@ function openLightbox(img) {
|
||||
overlay.className = "wfm-gallery-lightbox";
|
||||
overlay.innerHTML = `
|
||||
<div class="wfm-gallery-lightbox-inner">
|
||||
<img src="${API.serveImage(img.path)}" class="wfm-gallery-lightbox-img" alt="${img.filename}">
|
||||
<div class="wfm-gallery-lightbox-footer">${img.filename}</div>
|
||||
<img src="${API.serveImage(img.path)}" class="wfm-gallery-lightbox-img" alt="${escapeHtml(img.filename)}">
|
||||
<div class="wfm-gallery-lightbox-footer">${escapeHtml(img.filename)}</div>
|
||||
<button class="wfm-gallery-lightbox-close">×</button>
|
||||
</div>
|
||||
`;
|
||||
@@ -1077,6 +1281,36 @@ function openLightbox(img) {
|
||||
document.body.appendChild(overlay);
|
||||
}
|
||||
|
||||
// ── 画像比較ライトボックス ─────────────────────────────────────
|
||||
|
||||
function openCompare(paths) {
|
||||
const imgs = paths.map(p => state.images.find(im => im.path === p)).filter(Boolean);
|
||||
if (imgs.length < 2) return;
|
||||
|
||||
const overlay = document.createElement("div");
|
||||
overlay.className = "wfm-gallery-lightbox wfm-lightbox-compare";
|
||||
|
||||
const itemsHtml = imgs.map(img => `
|
||||
<div class="wfm-lightbox-compare-item">
|
||||
<img src="${API.serveImage(img.path)}" class="wfm-lightbox-compare-img" alt="${escapeHtml(img.filename)}" loading="lazy">
|
||||
<div class="wfm-lightbox-compare-label">${escapeHtml(img.filename)}</div>
|
||||
</div>
|
||||
`).join("");
|
||||
|
||||
overlay.innerHTML = `
|
||||
<div class="wfm-lightbox-compare-inner">
|
||||
<div class="wfm-lightbox-compare-grid" style="--compare-cols:${imgs.length}">${itemsHtml}</div>
|
||||
</div>
|
||||
<button class="wfm-gallery-lightbox-close wfm-lightbox-compare-close">×</button>
|
||||
`;
|
||||
overlay.addEventListener("click", (e) => {
|
||||
if (e.target === overlay || e.target.classList.contains("wfm-gallery-lightbox-close")) {
|
||||
overlay.remove();
|
||||
}
|
||||
});
|
||||
document.body.appendChild(overlay);
|
||||
}
|
||||
|
||||
// ── outputパス取得 ────────────────────────────────────────────
|
||||
|
||||
async function detectOutputPath() {
|
||||
@@ -1166,6 +1400,9 @@ function bindEvents() {
|
||||
loadImages();
|
||||
});
|
||||
|
||||
// FC ボタン: Feeder グループをクリア
|
||||
document.getElementById("wfm-gallery-fc-btn")?.addEventListener("click", clearFeederGroup);
|
||||
|
||||
// ビュー切替
|
||||
document.querySelectorAll("[data-gallery-view]").forEach(btn => {
|
||||
btn.addEventListener("click", () => {
|
||||
@@ -1196,18 +1433,36 @@ function bindEvents() {
|
||||
// メモ保存
|
||||
document.getElementById("wfm-gallery-memo-save-btn")?.addEventListener("click", () => {
|
||||
const memo = document.getElementById("wfm-gallery-memo").value;
|
||||
saveMetaField({ memo }).then(() => showToast("Memo saved", "success"));
|
||||
saveMetaField({ memo }).then(() => showToast(t("memoSaved"), "success"));
|
||||
});
|
||||
|
||||
// ワークフローコピー
|
||||
document.getElementById("wfm-gallery-copy-workflow-btn")?.addEventListener("click", () => {
|
||||
// ワークフローコピー&キャンバスへ送る
|
||||
document.getElementById("wfm-gallery-copy-workflow-btn")?.addEventListener("click", async () => {
|
||||
if (!state.embeddedWorkflow) {
|
||||
showToast("No embedded workflow found.", "error");
|
||||
showToast(t("galleryNoEmbeddedWorkflow"), "error");
|
||||
return;
|
||||
}
|
||||
navigator.clipboard.writeText(JSON.stringify(state.embeddedWorkflow, null, 2))
|
||||
.then(() => showToast("Workflow copied to clipboard!", "success"))
|
||||
.catch(() => showToast("Copy failed", "error"));
|
||||
try {
|
||||
// window.opener経由でComfyUIキャンバスに直接ロード(推奨)
|
||||
if (window.opener && typeof window.opener.wfmReceiveWorkflow === "function") {
|
||||
window.opener.wfmReceiveWorkflow(state.embeddedWorkflow);
|
||||
await navigator.clipboard.writeText(JSON.stringify(state.embeddedWorkflow, null, 2)).catch(() => {});
|
||||
showToast(t("workflowSentToCanvas"), "success");
|
||||
return;
|
||||
}
|
||||
// フォールバック: localStorage + タイトルドラッグ(UI形式のみ)
|
||||
const fmt = comfyWorkflow.detectFormat(state.embeddedWorkflow);
|
||||
if (fmt === "api") {
|
||||
showToast(t("apiFormatCanvasNoOpener"), "error");
|
||||
return;
|
||||
}
|
||||
const jsonStr = JSON.stringify(state.embeddedWorkflow, null, 2);
|
||||
await navigator.clipboard.writeText(jsonStr).catch(() => {});
|
||||
localStorage.setItem("wfm_pending_workflow", jsonStr);
|
||||
showToast(t("workflowSentToCanvas"), "success");
|
||||
} catch (err) {
|
||||
showToast(t("errorWithMsg", err.message), "error");
|
||||
}
|
||||
});
|
||||
|
||||
// 一括操作バー
|
||||
@@ -1218,12 +1473,27 @@ function bindEvents() {
|
||||
document.querySelectorAll(".multi-selected").forEach(el => el.classList.remove("multi-selected"));
|
||||
});
|
||||
|
||||
document.getElementById("wfm-gallery-bulk-select-all")?.addEventListener("click", () => {
|
||||
state.images.forEach(img => state.selectedImages.add(img.path));
|
||||
renderImages();
|
||||
updateBulkBar();
|
||||
});
|
||||
|
||||
document.getElementById("wfm-gallery-bulk-group-add")?.addEventListener("click", () => {
|
||||
const sel = document.getElementById("wfm-gallery-bulk-group-select");
|
||||
if (sel && sel.value) {
|
||||
bulkAddToGroup(sel.value);
|
||||
} else {
|
||||
showToast("Please select a group", "error");
|
||||
showToast(t("selectGroupFirst"), "error");
|
||||
}
|
||||
});
|
||||
|
||||
document.getElementById("wfm-gallery-bulk-group-remove")?.addEventListener("click", () => {
|
||||
const sel = document.getElementById("wfm-gallery-bulk-group-select");
|
||||
if (sel && sel.value) {
|
||||
bulkRemoveFromGroup(sel.value);
|
||||
} else {
|
||||
showToast(t("selectGroupFirst"), "error");
|
||||
}
|
||||
});
|
||||
|
||||
@@ -1235,6 +1505,11 @@ function bindEvents() {
|
||||
bulkSetFavorite(false);
|
||||
});
|
||||
|
||||
document.getElementById("wfm-gallery-bulk-compare")?.addEventListener("click", () => {
|
||||
if (state.selectedImages.size < 2) return;
|
||||
openCompare([...state.selectedImages]);
|
||||
});
|
||||
|
||||
document.getElementById("wfm-gallery-bulk-move")?.addEventListener("click", () => {
|
||||
if (state.selectedImages.size === 0) return;
|
||||
openMoveModal([...state.selectedImages]);
|
||||
@@ -1263,10 +1538,48 @@ function bindEvents() {
|
||||
performDeleteImages([state.selectedImage.path]);
|
||||
});
|
||||
|
||||
// 詳細タブ切り替え
|
||||
document.querySelectorAll(".wfm-gallery-detail-tab-btn").forEach(btn => {
|
||||
// MetadataタブボタンをJSONに改名(テンプレートとの二重保証)
|
||||
const metaTabBtn = document.querySelector('.wfm-gallery-detail-tab-btn[data-detail-tab="meta"]');
|
||||
if (metaTabBtn) metaTabBtn.textContent = "JSON";
|
||||
|
||||
// Metadataボタン: 選択画像をMetadataタブで開く
|
||||
document.getElementById("wfm-gallery-open-metadata-btn")?.addEventListener("click", () => {
|
||||
if (!state.selectedImage) {
|
||||
showToast(t("gallerySelectImageFirst"), "error");
|
||||
return;
|
||||
}
|
||||
openImageInMetadataTab(state.selectedImage);
|
||||
});
|
||||
|
||||
document.getElementById("wfm-gallery-open-tagger-btn")?.addEventListener("click", async () => {
|
||||
if (!state.selectedImage) {
|
||||
showToast(t("gallerySelectImageFirst"), "error");
|
||||
return;
|
||||
}
|
||||
const { openImageInTaggerTab } = await import("./tagger-tab.js");
|
||||
openImageInTaggerTab(state.selectedImage);
|
||||
});
|
||||
|
||||
// Load in GenerateUI ボタン: 埋め込みワークフローをGenerateUIタブに読み込む
|
||||
document.getElementById("wfm-gallery-load-genui-btn")?.addEventListener("click", async () => {
|
||||
if (!state.selectedImage) {
|
||||
showToast(t("gallerySelectImageFirst"), "error");
|
||||
return;
|
||||
}
|
||||
if (!state.embeddedWorkflow) {
|
||||
showToast(t("galleryNoEmbeddedWorkflow"), "warning");
|
||||
return;
|
||||
}
|
||||
const loaded = await loadWorkflowIntoEditor(state.embeddedWorkflow, state.selectedImage.filename);
|
||||
if (loaded !== false) {
|
||||
document.querySelector('.wfm-tab[data-tab="generate"]')?.click();
|
||||
}
|
||||
});
|
||||
|
||||
// 詳細タブ切り替え(data-detail-tab を持つボタンのみ対象。Metadata / Load GenUI はアクションボタン)
|
||||
document.querySelectorAll(".wfm-gallery-detail-tab-btn[data-detail-tab]").forEach(btn => {
|
||||
btn.addEventListener("click", () => {
|
||||
document.querySelectorAll(".wfm-gallery-detail-tab-btn").forEach(b => b.classList.remove("active"));
|
||||
document.querySelectorAll(".wfm-gallery-detail-tab-btn[data-detail-tab]").forEach(b => b.classList.remove("active"));
|
||||
btn.classList.add("active");
|
||||
const tabId = btn.dataset.detailTab;
|
||||
document.querySelectorAll(".wfm-gallery-detail-tab-content").forEach(c => c.style.display = "none");
|
||||
|
||||
+384
-43
@@ -2,28 +2,25 @@
|
||||
* GenerateUI Tab - Workflow execution with parameter editing
|
||||
*/
|
||||
|
||||
import { showToast } from "./app.js";
|
||||
import { showToast, openModal, closeModal } from "./app.js";
|
||||
import { comfyUI } from "./comfyui-client.js";
|
||||
import { comfyWorkflow } from "./comfyui-workflow.js";
|
||||
import { comfyEditor } from "./comfyui-editor.js";
|
||||
import { t } from "./i18n.js";
|
||||
import { syncJsonHighlight, syncScroll } from "./json-highlight.js";
|
||||
import { initFeederTab, refreshFeederNodeList } from "./feeder-tab.js";
|
||||
import { getSettings, readJsonStorage } from "./util.js";
|
||||
|
||||
// ============================================
|
||||
// Eagle Auto-Save
|
||||
// ============================================
|
||||
|
||||
function getEagleSettings() {
|
||||
try {
|
||||
const s = JSON.parse(localStorage.getItem("wfm_settings") || "{}");
|
||||
return {
|
||||
url: s.eagleUrl || "http://localhost:41595",
|
||||
autoSave: !!s.eagleAutoSave,
|
||||
};
|
||||
} catch {
|
||||
return { url: "http://localhost:41595", autoSave: false };
|
||||
}
|
||||
const s = getSettings();
|
||||
return {
|
||||
url: s.eagleUrl || "http://localhost:41595",
|
||||
autoSave: !!s.eagleAutoSave,
|
||||
};
|
||||
}
|
||||
|
||||
async function saveToEagle(imageUrl, name, tags = []) {
|
||||
@@ -103,6 +100,120 @@ function updateStatus(connected) {
|
||||
}
|
||||
}
|
||||
|
||||
// ============================================
|
||||
// Workflow Save
|
||||
// ============================================
|
||||
|
||||
async function saveCurrentWorkflow() {
|
||||
if (!comfyUI.currentWorkflow) {
|
||||
showToast(t("noWorkflowLoaded"), "warning");
|
||||
return;
|
||||
}
|
||||
|
||||
const currentFilename = document.getElementById("wfm-gen-wf-name")?.dataset?.filename || "";
|
||||
const defaultStem = currentFilename.replace(/\.(json|png|jpg|jpeg|webp|gif)$/i, "") || "workflow";
|
||||
|
||||
const html = `
|
||||
<div style="display:flex;flex-direction:column;gap:14px;min-width:300px;">
|
||||
<div>
|
||||
<label style="font-size:12px;color:var(--wfm-text-secondary);display:block;margin-bottom:4px;">${t("filenameLabel")}</label>
|
||||
<div style="display:flex;align-items:center;gap:6px;">
|
||||
<input type="text" id="wfm-save-wf-name" class="wfm-input" style="flex:1;" placeholder="workflow name">
|
||||
<span style="color:var(--wfm-text-secondary);font-size:13px;">.json</span>
|
||||
</div>
|
||||
</div>
|
||||
<div style="display:flex;gap:8px;justify-content:flex-end;">
|
||||
<button class="wfm-btn wfm-btn-sm" id="wfm-save-wf-cancel-btn">${t("cancel")}</button>
|
||||
<button class="wfm-btn wfm-btn-sm wfm-btn-primary" id="wfm-save-wf-confirm-btn">${t("save")}</button>
|
||||
</div>
|
||||
</div>`;
|
||||
|
||||
openModal(t("saveWorkflowTitle"), html);
|
||||
|
||||
// 属性値に埋め込まず DOM 経由で初期値を設定(ファイル名中の引用符等によるHTML注入防止)
|
||||
const input = document.getElementById("wfm-save-wf-name");
|
||||
if (input) input.value = defaultStem;
|
||||
setTimeout(() => {
|
||||
if (input) { input.focus(); input.select(); }
|
||||
}, 50);
|
||||
|
||||
document.getElementById("wfm-save-wf-cancel-btn")?.addEventListener("click", () => closeModal());
|
||||
|
||||
let saving = false;
|
||||
const doSave = async () => {
|
||||
if (saving) return;
|
||||
const stem = input?.value?.trim();
|
||||
if (!stem) {
|
||||
showToast(t("pleaseEnterFilename"), "warning");
|
||||
return;
|
||||
}
|
||||
const filename = stem.endsWith(".json") ? stem : `${stem}.json`;
|
||||
saving = true;
|
||||
try {
|
||||
// Raw JSON に未適用の編集があれば保存対象に反映する
|
||||
let workflow = comfyUI.currentWorkflow;
|
||||
const rawText = document.getElementById("wfm-gen-raw-json")?.value ?? "";
|
||||
if (rawText.trim() && rawText !== JSON.stringify(workflow, null, 2)) {
|
||||
try {
|
||||
workflow = JSON.parse(rawText);
|
||||
} catch {
|
||||
showToast(t("rawJsonUnappliedInvalid"), "error");
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
// 上書き確認(保存先がUI形式ならAPI形式化でレイアウトが失われる旨を警告)
|
||||
try {
|
||||
const listRes = await fetch("/api/wfm/workflows");
|
||||
const listData = await listRes.json();
|
||||
const existing = (Array.isArray(listData) ? listData : []).find(w => w.filename === filename);
|
||||
if (existing) {
|
||||
const msg = existing.analysis?.format === "ui"
|
||||
? t("uiFormatOverwriteWarn")
|
||||
: t("overwriteConfirm", filename);
|
||||
if (!confirm(msg)) return;
|
||||
}
|
||||
} catch { /* 一覧取得失敗時は確認をスキップして保存を続行 */ }
|
||||
|
||||
const blob = new Blob(
|
||||
[JSON.stringify(workflow, null, 2)],
|
||||
{ type: "application/json" }
|
||||
);
|
||||
const file = new File([blob], filename, { type: "application/json" });
|
||||
const fd = new FormData();
|
||||
fd.append("files", file);
|
||||
const res = await fetch("/api/wfm/workflows/import", { method: "POST", body: fd });
|
||||
const data = await res.json();
|
||||
const ng = (data.results || []).filter(r => r.status === "error");
|
||||
if (ng.length) {
|
||||
showToast(t("saveFailed", ng[0].message || "unknown error"), "error");
|
||||
return;
|
||||
}
|
||||
closeModal();
|
||||
if (workflow !== comfyUI.currentWorkflow) {
|
||||
// Raw JSON の編集を保存した場合はエディタにも反映して同期する
|
||||
await loadWorkflowIntoEditor(workflow, filename);
|
||||
} else {
|
||||
const nameEl = document.getElementById("wfm-gen-wf-name");
|
||||
if (nameEl) {
|
||||
nameEl.textContent = filename;
|
||||
nameEl.dataset.filename = filename;
|
||||
}
|
||||
}
|
||||
showToast(t("savedAs", filename), "success");
|
||||
} catch (err) {
|
||||
showToast(t("saveFailed", err.message), "error");
|
||||
} finally {
|
||||
saving = false;
|
||||
}
|
||||
};
|
||||
|
||||
document.getElementById("wfm-save-wf-confirm-btn")?.addEventListener("click", doSave);
|
||||
input?.addEventListener("keydown", (e) => {
|
||||
if (e.key === "Enter") doSave();
|
||||
});
|
||||
}
|
||||
|
||||
// ============================================
|
||||
// Workflow Loading
|
||||
// ============================================
|
||||
@@ -117,7 +228,7 @@ export async function loadWorkflowIntoEditor(workflow, filename) {
|
||||
} else if (format === "ui") {
|
||||
apiWorkflow = await comfyWorkflow.convertUiToApi(workflow);
|
||||
} else if (format === "unknown") {
|
||||
showToast("Unknown workflow format", "error");
|
||||
showToast(t("unknownWorkflowFormat"), "error");
|
||||
return false;
|
||||
}
|
||||
|
||||
@@ -140,6 +251,7 @@ export async function loadWorkflowIntoEditor(workflow, filename) {
|
||||
const nameEl = document.getElementById("wfm-gen-wf-name");
|
||||
if (nameEl) {
|
||||
nameEl.textContent = filename || "Loaded Workflow";
|
||||
nameEl.dataset.filename = filename || "";
|
||||
}
|
||||
|
||||
// Enable generate button
|
||||
@@ -148,7 +260,7 @@ export async function loadWorkflowIntoEditor(workflow, filename) {
|
||||
|
||||
refreshFeederNodeList();
|
||||
|
||||
showToast(`Workflow loaded: ${filename || ""}`, "success");
|
||||
showToast(t("workflowLoadedName", filename || ""), "success");
|
||||
return true;
|
||||
}
|
||||
|
||||
@@ -157,7 +269,7 @@ export async function loadWorkflowIntoEditor(workflow, filename) {
|
||||
// ============================================
|
||||
|
||||
const _ckptBatch = { aborted: false, paused: false, _resumeResolve: null };
|
||||
let _activeBatchType = null; // "checkpoint" | "lora" | "prompt" | "workflow" | null
|
||||
let _activeBatchType = null; // "checkpoint" | "lora" | "prompt" | "workflow" | "sampler" | "scheduler" | null
|
||||
|
||||
async function _waitIfPaused() {
|
||||
if (!_ckptBatch.paused) return;
|
||||
@@ -175,7 +287,7 @@ function _setPauseBtnState(paused) {
|
||||
function _updateBatchTypeLabel(running = false) {
|
||||
const el = document.getElementById("wfm-batch-type-label");
|
||||
if (!el) return;
|
||||
const labels = { checkpoint: "Checkpoint", lora: "Lora", prompt: "Prompt", workflow: "Workflow" };
|
||||
const labels = { checkpoint: "Checkpoint", lora: "Lora", prompt: "Prompt", workflow: "Workflow", sampler: "Sampler", scheduler: "Scheduler" };
|
||||
if (_activeBatchType) {
|
||||
el.textContent = labels[_activeBatchType];
|
||||
el.style.color = running ? "var(--wfm-primary)" : "";
|
||||
@@ -211,6 +323,10 @@ const _batchGroupState = {
|
||||
wfPartialSelections: {},
|
||||
};
|
||||
|
||||
// Sampler / Scheduler 選択状態
|
||||
const _samplerSelected = new Set();
|
||||
const _schedulerSelected = new Set();
|
||||
|
||||
// 汎用: groupsData/selectedGroups/partialSelectionsからメンバーSetを返す
|
||||
function _getItemsFromGroupState(groupsData, selectedGroups, partialSelections) {
|
||||
const result = new Set();
|
||||
@@ -327,6 +443,20 @@ function _renderBatchPreview() {
|
||||
(f) => f.replace(/\.json$/i, "").replace(/\\/g, "/").split("/").pop(),
|
||||
"workflow", "workflows"
|
||||
);
|
||||
// Sampler
|
||||
_renderQueueColumn(
|
||||
"wfm-batch-sampler-count", "wfm-batch-sampler-list",
|
||||
[..._samplerSelected].sort(),
|
||||
(s) => s,
|
||||
"sampler", "samplers"
|
||||
);
|
||||
// Scheduler
|
||||
_renderQueueColumn(
|
||||
"wfm-batch-scheduler-count", "wfm-batch-scheduler-list",
|
||||
[..._schedulerSelected].sort(),
|
||||
(s) => s,
|
||||
"scheduler", "schedulers"
|
||||
);
|
||||
}
|
||||
|
||||
// モデルパスリストをフォルダ → [modelPath, ...] のMapに変換
|
||||
@@ -787,9 +917,7 @@ async function _loadPromptGroupsForBatch() {
|
||||
const res = await fetch("/api/wfm/prompts");
|
||||
_batchGroupState.promptPresets = res.ok ? await res.json() : [];
|
||||
} catch { _batchGroupState.promptPresets = []; }
|
||||
try {
|
||||
_batchGroupState.promptGroups = JSON.parse(localStorage.getItem("wfm_prompt_preset_groups") || "{}");
|
||||
} catch { _batchGroupState.promptGroups = {}; }
|
||||
_batchGroupState.promptGroups = readJsonStorage("wfm_prompt_preset_groups");
|
||||
|
||||
const validIds = new Set(_batchGroupState.promptPresets.map((p) => p.id));
|
||||
for (const g of Object.keys(_batchGroupState.promptGroups)) {
|
||||
@@ -825,9 +953,7 @@ function _renderBatchPromptGroupList() {
|
||||
// Workflow グループ
|
||||
// ============================================
|
||||
function _loadWorkflowGroupsForBatch() {
|
||||
try {
|
||||
_batchGroupState.wfGroups = JSON.parse(localStorage.getItem("wfm_groups") || "{}");
|
||||
} catch { _batchGroupState.wfGroups = {}; }
|
||||
_batchGroupState.wfGroups = readJsonStorage("wfm_groups");
|
||||
|
||||
const currentNames = new Set(Object.keys(_batchGroupState.wfGroups));
|
||||
for (const name of _batchGroupState.wfSelectedGroups) {
|
||||
@@ -853,8 +979,122 @@ function _renderBatchWfGroupList() {
|
||||
);
|
||||
}
|
||||
|
||||
// ============================================
|
||||
// Sampler / Scheduler リスト
|
||||
// ============================================
|
||||
function _buildSimpleGroupList(listEl, items, selectedSet, emptyMsg) {
|
||||
if (!listEl) return;
|
||||
if (items.length === 0) {
|
||||
listEl.innerHTML = `<div style="padding:8px 10px;font-size:11px;color:var(--wfm-text-secondary);">${emptyMsg}</div>`;
|
||||
return;
|
||||
}
|
||||
listEl.innerHTML = "";
|
||||
|
||||
const group = document.createElement("div");
|
||||
group.className = "wfm-ckpt-folder-group open";
|
||||
|
||||
const header = document.createElement("div");
|
||||
header.className = "wfm-ckpt-folder-header";
|
||||
|
||||
const folderCb = document.createElement("input");
|
||||
folderCb.type = "checkbox";
|
||||
const selCount = () => items.filter((x) => selectedSet.has(x)).length;
|
||||
const updateFolderCb = () => {
|
||||
const n = selCount();
|
||||
folderCb.checked = items.length > 0 && n === items.length;
|
||||
folderCb.indeterminate = n > 0 && n < items.length;
|
||||
};
|
||||
updateFolderCb();
|
||||
|
||||
const toggle = document.createElement("span");
|
||||
toggle.className = "wfm-ckpt-folder-toggle";
|
||||
toggle.textContent = "▶";
|
||||
|
||||
const nameSpan = document.createElement("span");
|
||||
nameSpan.className = "wfm-ckpt-folder-name";
|
||||
nameSpan.textContent = "(root)";
|
||||
|
||||
const countSpan = document.createElement("span");
|
||||
countSpan.className = "wfm-ckpt-folder-count";
|
||||
countSpan.textContent = items.length;
|
||||
|
||||
const filesDiv = document.createElement("div");
|
||||
filesDiv.className = "wfm-ckpt-folder-files";
|
||||
|
||||
for (const s of items) {
|
||||
const label = document.createElement("label");
|
||||
label.className = "wfm-ckpt-item wfm-ckpt-item--indented";
|
||||
const cb = document.createElement("input");
|
||||
cb.type = "checkbox";
|
||||
cb.value = s;
|
||||
cb.checked = selectedSet.has(s);
|
||||
cb.addEventListener("change", () => {
|
||||
if (cb.checked) selectedSet.add(s);
|
||||
else selectedSet.delete(s);
|
||||
updateFolderCb();
|
||||
_renderBatchPreview();
|
||||
});
|
||||
const span = document.createElement("span");
|
||||
span.className = "wfm-ckpt-item-label";
|
||||
span.textContent = s;
|
||||
label.appendChild(cb);
|
||||
label.appendChild(span);
|
||||
filesDiv.appendChild(label);
|
||||
}
|
||||
|
||||
folderCb.addEventListener("change", () => {
|
||||
folderCb.indeterminate = false;
|
||||
items.forEach((s) => { if (folderCb.checked) selectedSet.add(s); else selectedSet.delete(s); });
|
||||
filesDiv.querySelectorAll("input[type=checkbox]").forEach((c) => { c.checked = folderCb.checked; });
|
||||
_renderBatchPreview();
|
||||
});
|
||||
|
||||
[toggle, nameSpan].forEach((el) => {
|
||||
el.addEventListener("click", () => group.classList.toggle("open"));
|
||||
});
|
||||
|
||||
header.appendChild(folderCb);
|
||||
header.appendChild(toggle);
|
||||
header.appendChild(nameSpan);
|
||||
header.appendChild(countSpan);
|
||||
group.appendChild(header);
|
||||
group.appendChild(filesDiv);
|
||||
listEl.appendChild(group);
|
||||
}
|
||||
|
||||
function _rebuildSamplerList() {
|
||||
_buildSimpleGroupList(
|
||||
document.getElementById("wfm-sampler-list"),
|
||||
comfyEditor.models.samplers || [],
|
||||
_samplerSelected,
|
||||
"No samplers (connect to ComfyUI first)"
|
||||
);
|
||||
}
|
||||
|
||||
function _rebuildSchedulerList() {
|
||||
_buildSimpleGroupList(
|
||||
document.getElementById("wfm-scheduler-list"),
|
||||
comfyEditor.models.schedulers || [],
|
||||
_schedulerSelected,
|
||||
"No schedulers (connect to ComfyUI first)"
|
||||
);
|
||||
}
|
||||
|
||||
function initBatchTab() {
|
||||
// 内部タブ切り替え(タブ表示時に対応するグループを読み込む)
|
||||
// 左ペイン タブ切り替え
|
||||
document.querySelectorAll(".wfm-batch-left-tab").forEach((btn) => {
|
||||
btn.addEventListener("click", () => {
|
||||
document.querySelectorAll(".wfm-batch-left-tab").forEach((b) => b.classList.remove("active"));
|
||||
btn.classList.add("active");
|
||||
const tabId = btn.dataset.leftTab;
|
||||
document.querySelectorAll(".wfm-batch-left-content").forEach((c) => c.classList.remove("active"));
|
||||
document.getElementById(`wfm-batch-left-${tabId}`)?.classList.add("active");
|
||||
if (tabId === "sampler") _rebuildSamplerList();
|
||||
else if (tabId === "scheduler") _rebuildSchedulerList();
|
||||
});
|
||||
});
|
||||
|
||||
// 中央ペイン 内部タブ切り替え
|
||||
document.querySelectorAll(".wfm-batch-inner-tab").forEach((btn) => {
|
||||
btn.addEventListener("click", () => {
|
||||
document.querySelectorAll(".wfm-batch-inner-tab").forEach((b) => b.classList.remove("active"));
|
||||
@@ -869,10 +1109,10 @@ function initBatchTab() {
|
||||
});
|
||||
});
|
||||
|
||||
// 検索フィルター(左ペイン)
|
||||
// 検索フィルター(左ペイン Checkpoint)
|
||||
document.getElementById("wfm-ckpt-search")?.addEventListener("input", _rebuildCkptList);
|
||||
|
||||
// 全選択 / 全解除(左ペイン)
|
||||
// 全選択 / 全解除(左ペイン Checkpoint)
|
||||
document.getElementById("wfm-ckpt-select-all")?.addEventListener("click", () => {
|
||||
_ckptState.mode = "all";
|
||||
_ckptState.selected.clear();
|
||||
@@ -886,6 +1126,30 @@ function initBatchTab() {
|
||||
_renderBatchPreview();
|
||||
});
|
||||
|
||||
// 全選択 / 全解除(左ペイン Sampler)
|
||||
document.getElementById("wfm-sampler-select-all")?.addEventListener("click", () => {
|
||||
(comfyEditor.models.samplers || []).forEach((s) => _samplerSelected.add(s));
|
||||
_rebuildSamplerList();
|
||||
_renderBatchPreview();
|
||||
});
|
||||
document.getElementById("wfm-sampler-deselect-all")?.addEventListener("click", () => {
|
||||
_samplerSelected.clear();
|
||||
_rebuildSamplerList();
|
||||
_renderBatchPreview();
|
||||
});
|
||||
|
||||
// 全選択 / 全解除(左ペイン Scheduler)
|
||||
document.getElementById("wfm-scheduler-select-all")?.addEventListener("click", () => {
|
||||
(comfyEditor.models.schedulers || []).forEach((s) => _schedulerSelected.add(s));
|
||||
_rebuildSchedulerList();
|
||||
_renderBatchPreview();
|
||||
});
|
||||
document.getElementById("wfm-scheduler-deselect-all")?.addEventListener("click", () => {
|
||||
_schedulerSelected.clear();
|
||||
_rebuildSchedulerList();
|
||||
_renderBatchPreview();
|
||||
});
|
||||
|
||||
// Batch タブが表示されたときに全グループを読み込む
|
||||
document.querySelector('[data-subtab="batch"]')?.addEventListener("click", () => {
|
||||
_rebuildCkptList();
|
||||
@@ -1000,7 +1264,7 @@ async function _coreGenerate(silent = false) {
|
||||
saveGeneratedImagesMeta(images, { ...comfyUI.currentWorkflow }).catch(() => {});
|
||||
}
|
||||
|
||||
if (!silent) showToast("Generation complete", "success");
|
||||
if (!silent) showToast(t("generationComplete"), "success");
|
||||
}
|
||||
|
||||
// ============================================
|
||||
@@ -1048,7 +1312,7 @@ async function _runBatchLoop(items, applyFn, labelFn = (x) => String(x)) {
|
||||
} catch (err) {
|
||||
if (_ckptBatch.aborted) break;
|
||||
failed++;
|
||||
showToast(`[${i + 1}/${items.length}] Failed: ${err.message}`, "error");
|
||||
showToast(t("batchItemFailed", i + 1, items.length, err.message), "error");
|
||||
}
|
||||
}
|
||||
} finally {
|
||||
@@ -1066,7 +1330,7 @@ async function _runBatchLoop(items, applyFn, labelFn = (x) => String(x)) {
|
||||
if (batchCurrentName) batchCurrentName.textContent = _ckptBatch.aborted ? "Stopped" : "Done";
|
||||
|
||||
if (_ckptBatch.aborted) {
|
||||
showToast(`Batch stopped — ${completed} completed, ${failed} failed`, "info");
|
||||
showToast(t("batchStopped", completed, failed), "info");
|
||||
} else {
|
||||
showToast(
|
||||
`Batch complete: ${completed}/${items.length}${failed > 0 ? ` (${failed} failed)` : ""}`,
|
||||
@@ -1080,9 +1344,9 @@ async function _runBatchGenerate() {
|
||||
switch (_activeBatchType) {
|
||||
case "checkpoint": {
|
||||
const ckptNodes = comfyUI.currentAnalysis?.checkpoint_nodes || [];
|
||||
if (ckptNodes.length === 0) { showToast("No checkpoint node found in workflow", "error"); return; }
|
||||
if (ckptNodes.length === 0) { showToast(t("modelsGenUINoNode", "checkpoint"), "error"); return; }
|
||||
const list = _getSelectedCheckpoints();
|
||||
if (list.length === 0) { showToast("No checkpoints selected", "error"); return; }
|
||||
if (list.length === 0) { showToast(t("batchNoneSelected", "checkpoints"), "error"); return; }
|
||||
await _runBatchLoop(list, (model) => {
|
||||
for (const node of ckptNodes) {
|
||||
if (comfyUI.currentWorkflow?.[node.id])
|
||||
@@ -1093,13 +1357,21 @@ async function _runBatchGenerate() {
|
||||
}
|
||||
case "lora": {
|
||||
const loraNodes = comfyUI.currentAnalysis?.lora_nodes || [];
|
||||
if (loraNodes.length === 0) { showToast("No LoRA node found in workflow", "error"); return; }
|
||||
if (loraNodes.length === 0) { showToast(t("modelsGenUINoNode", "LoRA"), "error"); return; }
|
||||
const list = [..._getSelectedLoraGroupItems()];
|
||||
if (list.length === 0) { showToast("No LoRAs selected", "error"); return; }
|
||||
if (list.length === 0) { showToast(t("batchNoneSelected", "LoRAs"), "error"); return; }
|
||||
await _runBatchLoop(list, (loraName) => {
|
||||
for (const node of loraNodes) {
|
||||
if (comfyUI.currentWorkflow?.[node.id])
|
||||
if (!comfyUI.currentWorkflow?.[node.id]) continue;
|
||||
if (node.is_lora_manager) {
|
||||
const stem = loraName.replace(/\\/g, "/").split("/").pop().replace(/\.[^.]+$/, "");
|
||||
comfyUI.currentWorkflow[node.id].inputs.loras = {
|
||||
__value__: [{ name: stem, strength: 1.0, active: true, expanded: false, clipStrength: 1.0, locked: false }],
|
||||
};
|
||||
comfyUI.currentWorkflow[node.id].inputs.text = `<lora:${stem}:1:1>`;
|
||||
} else {
|
||||
comfyUI.currentWorkflow[node.id].inputs.lora_name = loraName;
|
||||
}
|
||||
}
|
||||
}, (name) => name.replace(/\.[^.]+$/, ""));
|
||||
break;
|
||||
@@ -1108,11 +1380,11 @@ async function _runBatchGenerate() {
|
||||
const positiveNodes = (comfyUI.currentAnalysis?.prompt_nodes || []).filter((n) => n.role === "positive");
|
||||
const negativeNodes = (comfyUI.currentAnalysis?.prompt_nodes || []).filter((n) => n.role === "negative");
|
||||
if (positiveNodes.length === 0 && negativeNodes.length === 0) {
|
||||
showToast("No prompt node found in workflow", "error"); return;
|
||||
showToast(t("modelsGenUINoNode", "prompt"), "error"); return;
|
||||
}
|
||||
// _getSelectedPromptGroupItems() はすでにプリセットオブジェクトの配列を返す
|
||||
const list = _getSelectedPromptGroupItems();
|
||||
if (list.length === 0) { showToast("No prompts selected", "error"); return; }
|
||||
if (list.length === 0) { showToast(t("batchNoneSelected", "prompts"), "error"); return; }
|
||||
await _runBatchLoop(list, (preset) => {
|
||||
for (const node of positiveNodes) {
|
||||
if (comfyUI.currentWorkflow?.[node.id])
|
||||
@@ -1127,12 +1399,12 @@ async function _runBatchGenerate() {
|
||||
}
|
||||
case "workflow": {
|
||||
const list = [..._getSelectedWfGroupItems()];
|
||||
if (list.length === 0) { showToast("No workflows selected", "error"); return; }
|
||||
if (list.length === 0) { showToast(t("batchNoneSelected", "workflows"), "error"); return; }
|
||||
const savedWorkflow = comfyUI.currentWorkflow ? JSON.stringify(comfyUI.currentWorkflow) : null;
|
||||
const savedFilename = document.getElementById("wfm-gen-workflow-name")?.textContent || "";
|
||||
try {
|
||||
await _runBatchLoop(list, async (filename) => {
|
||||
const resp = await fetch(`/api/wfm/workflows/${encodeURIComponent(filename)}`);
|
||||
const resp = await fetch(`/api/wfm/workflows/raw?filename=${encodeURIComponent(filename)}`);
|
||||
if (!resp.ok) throw new Error(`Failed to load: ${filename}`);
|
||||
const data = await resp.json();
|
||||
await loadWorkflowIntoEditor(data, filename);
|
||||
@@ -1144,6 +1416,32 @@ async function _runBatchGenerate() {
|
||||
}
|
||||
break;
|
||||
}
|
||||
case "sampler": {
|
||||
const samplerNodes = comfyUI.currentAnalysis?.sampler_nodes || [];
|
||||
if (samplerNodes.length === 0) { showToast(t("modelsGenUINoNode", "KSampler"), "error"); return; }
|
||||
const list = [..._samplerSelected].sort();
|
||||
if (list.length === 0) { showToast(t("batchNoneSelected", "samplers"), "error"); return; }
|
||||
await _runBatchLoop(list, (samplerName) => {
|
||||
for (const node of samplerNodes) {
|
||||
if (comfyUI.currentWorkflow?.[node.id])
|
||||
comfyUI.currentWorkflow[node.id].inputs.sampler_name = samplerName;
|
||||
}
|
||||
});
|
||||
break;
|
||||
}
|
||||
case "scheduler": {
|
||||
const samplerNodes = comfyUI.currentAnalysis?.sampler_nodes || [];
|
||||
if (samplerNodes.length === 0) { showToast(t("modelsGenUINoNode", "KSampler"), "error"); return; }
|
||||
const list = [..._schedulerSelected].sort();
|
||||
if (list.length === 0) { showToast(t("batchNoneSelected", "schedulers"), "error"); return; }
|
||||
await _runBatchLoop(list, (schedulerName) => {
|
||||
for (const node of samplerNodes) {
|
||||
if (comfyUI.currentWorkflow?.[node.id])
|
||||
comfyUI.currentWorkflow[node.id].inputs.scheduler = schedulerName;
|
||||
}
|
||||
});
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1153,7 +1451,7 @@ async function _runBatchGenerate() {
|
||||
|
||||
async function handleGenerate() {
|
||||
if (!comfyUI.currentWorkflow) {
|
||||
showToast("No workflow loaded", "error");
|
||||
showToast(t("noWorkflowLoaded"), "error");
|
||||
return;
|
||||
}
|
||||
if (comfyUI.generating) return;
|
||||
@@ -1180,7 +1478,7 @@ async function handleGenerate() {
|
||||
} catch (err) {
|
||||
const progressText = document.getElementById("wfm-gen-progress-text");
|
||||
if (progressText) progressText.textContent = "Error";
|
||||
showToast("Generation error: " + err.message, "error");
|
||||
showToast(t("generationError", err.message), "error");
|
||||
}
|
||||
}
|
||||
} finally {
|
||||
@@ -1203,9 +1501,9 @@ export async function initGenerateTab() {
|
||||
updateStatus(connected);
|
||||
if (connected) {
|
||||
await comfyEditor.loadModelLists();
|
||||
showToast("Connected to ComfyUI", "success");
|
||||
showToast(t("connectedToComfyUI"), "success");
|
||||
} else {
|
||||
showToast("Failed to connect", "error");
|
||||
showToast(t("failedToConnect"), "error");
|
||||
}
|
||||
});
|
||||
|
||||
@@ -1215,10 +1513,31 @@ export async function initGenerateTab() {
|
||||
if (comfyUI.currentAnalysis) {
|
||||
comfyEditor.renderAll(comfyUI.currentAnalysis, comfyUI.currentWorkflow);
|
||||
}
|
||||
showToast("Model lists refreshed", "success");
|
||||
showToast(t("modelListsRefreshed"), "success");
|
||||
_rebuildSamplerList();
|
||||
_rebuildSchedulerList();
|
||||
_renderBatchPreview();
|
||||
});
|
||||
|
||||
// Save workflow button
|
||||
document.getElementById("wfm-gen-save-btn")?.addEventListener("click", () => saveCurrentWorkflow());
|
||||
|
||||
document.getElementById("wfm-gen-reset-workflow-btn")?.addEventListener("click", async () => {
|
||||
const filename = document.getElementById("wfm-gen-wf-name")?.dataset?.filename;
|
||||
if (!filename || !filename.endsWith(".json")) {
|
||||
showToast(t("noFileWorkflowLoaded"), "warning");
|
||||
return;
|
||||
}
|
||||
try {
|
||||
const resp = await fetch(`/api/wfm/workflows/raw?filename=${encodeURIComponent(filename)}`);
|
||||
if (!resp.ok) throw new Error(resp.status);
|
||||
const data = await resp.json();
|
||||
await loadWorkflowIntoEditor(data, filename);
|
||||
} catch (err) {
|
||||
showToast(t("resetFailed", err.message), "error");
|
||||
}
|
||||
});
|
||||
|
||||
// Generate button
|
||||
document.getElementById("wfm-gen-generate-btn")?.addEventListener("click", handleGenerate);
|
||||
|
||||
@@ -1232,7 +1551,7 @@ export async function initGenerateTab() {
|
||||
_ckptBatch._resumeResolve = null;
|
||||
}
|
||||
await comfyUI.interrupt();
|
||||
showToast("Interrupted", "info");
|
||||
showToast(t("interrupted"), "info");
|
||||
});
|
||||
|
||||
// Move shared Raw JSON widget into the active tab's rawjson-col
|
||||
@@ -1259,6 +1578,28 @@ export async function initGenerateTab() {
|
||||
document.querySelectorAll(".wfm-gen-subtab-content").forEach((c) => c.classList.remove("active"));
|
||||
document.getElementById(`wfm-gen-subtab-${target}`)?.classList.add("active");
|
||||
moveRawJsonToTab(target);
|
||||
// Re-render LoRA pane when switching to model tab so Stack group changes are reflected
|
||||
if (target === "model" && comfyUI.currentAnalysis) {
|
||||
comfyEditor.renderLoraPane(comfyUI.currentAnalysis, "wfm-gen-lora-fields");
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
// Stack refresh button in LoRA column header
|
||||
document.getElementById("wfm-lora-stack-refresh")?.addEventListener("click", () => {
|
||||
if (comfyUI.currentAnalysis) {
|
||||
comfyEditor.renderLoraPane(comfyUI.currentAnalysis, "wfm-gen-lora-fields");
|
||||
}
|
||||
});
|
||||
|
||||
// Input inner tab (Prompt / Image)
|
||||
document.querySelectorAll(".wfm-input-inner-tab").forEach((btn) => {
|
||||
btn.addEventListener("click", () => {
|
||||
const target = btn.dataset.inputTab;
|
||||
document.querySelectorAll(".wfm-input-inner-tab").forEach((b) => b.classList.remove("active"));
|
||||
btn.classList.add("active");
|
||||
document.querySelectorAll(".wfm-input-inner-panel").forEach((p) => p.style.display = "none");
|
||||
document.getElementById(`wfm-input-panel-${target}`)?.style.setProperty("display", "");
|
||||
});
|
||||
});
|
||||
|
||||
@@ -1273,7 +1614,7 @@ export async function initGenerateTab() {
|
||||
const wf = JSON.parse(textarea.value);
|
||||
await loadWorkflowIntoEditor(wf, "Raw JSON");
|
||||
} catch (err) {
|
||||
showToast("Invalid JSON: " + err.message, "error");
|
||||
showToast(t("invalidJsonMsg", err.message), "error");
|
||||
}
|
||||
});
|
||||
|
||||
@@ -1428,7 +1769,7 @@ export async function initGenerateTab() {
|
||||
// Auto-load default workflow (doesn't require ComfyUI connection)
|
||||
if (!comfyUI.currentWorkflow) {
|
||||
try {
|
||||
const settings = JSON.parse(localStorage.getItem("wfm_settings") || "{}");
|
||||
const settings = getSettings();
|
||||
if (settings.defaultWorkflow && settings.defaultWorkflowData) {
|
||||
await loadWorkflowIntoEditor(settings.defaultWorkflowData, settings.defaultWorkflow);
|
||||
console.log("Workflow Studio: Auto-loaded default workflow:", settings.defaultWorkflow);
|
||||
|
||||
+702
-83
File diff suppressed because it is too large
Load Diff
@@ -5,6 +5,7 @@
|
||||
*/
|
||||
|
||||
import { t } from "./i18n.js";
|
||||
import { escapeHtml } from "./util.js";
|
||||
|
||||
// ── File size limit ───────────────────────────────────────────
|
||||
const MAX_FILE_SIZE = 50 * 1024 * 1024;
|
||||
@@ -154,7 +155,9 @@ function extractLoRAs(wf) {
|
||||
function add(name, sm, sc) {
|
||||
if (!name || typeof name !== "string" || name === "None" || seen.has(name)) return;
|
||||
seen.add(name);
|
||||
results.push({ name, strength_model: typeof sm === "number" ? sm : 1.0, strength_clip: typeof sc === "number" ? sc : 1.0 });
|
||||
const smNum = parseFloat(sm);
|
||||
const scNum = parseFloat(sc);
|
||||
results.push({ name, strength_model: isNaN(smNum) ? 1.0 : smNum, strength_clip: isNaN(scNum) ? 1.0 : scNum });
|
||||
}
|
||||
if (Array.isArray(wf.nodes)) {
|
||||
for (const n of collectAllNodes(wf)) {
|
||||
@@ -170,6 +173,11 @@ function extractLoRAs(wf) {
|
||||
const ct = n.class_type ?? "";
|
||||
if (ct === "LoraLoader") add(n.inputs?.lora_name, n.inputs?.strength_model, n.inputs?.strength_clip);
|
||||
else if (ct === "LoraLoaderModelOnly") add(n.inputs?.lora_name, n.inputs?.strength, 1.0);
|
||||
else if (ct === "Lora Loader (LoraManager)") {
|
||||
const lorasData = n.inputs?.loras;
|
||||
const list = lorasData?.__value__ ?? (Array.isArray(lorasData) ? lorasData : null);
|
||||
if (list) for (const l of list) { if (l?.active !== false) add(l?.name, l?.strength ?? 1.0, l?.clipStrength ?? l?.strength ?? 1.0); }
|
||||
}
|
||||
}
|
||||
}
|
||||
return results;
|
||||
@@ -497,7 +505,6 @@ async function extractAllMetadata(file) {
|
||||
}
|
||||
|
||||
// ── UI helpers ────────────────────────────────────────────────
|
||||
function escapeHtml(s) { return String(s).replace(/&/g, "&").replace(/</g, "<").replace(/>/g, ">"); }
|
||||
|
||||
function buildModelItem(label) {
|
||||
const el = document.createElement("div");
|
||||
@@ -543,6 +550,15 @@ function renderSection(sectionEl, listEl, items, buildFn) {
|
||||
for (const item of items) listEl.appendChild(buildFn(item));
|
||||
}
|
||||
|
||||
// ── External API ──────────────────────────────────────────────
|
||||
let _externalHandleFile = null;
|
||||
|
||||
export async function loadFileIntoMetadataTab(file) {
|
||||
document.querySelector('.wfm-tab[data-tab="metadata"]')?.click();
|
||||
await new Promise(r => setTimeout(r, 0));
|
||||
if (_externalHandleFile) await _externalHandleFile(file);
|
||||
}
|
||||
|
||||
// ── Tab initialization ────────────────────────────────────────
|
||||
export function initMetadataTab() {
|
||||
const dropZone = document.getElementById("wfm-meta-drop");
|
||||
@@ -736,6 +752,8 @@ export function initMetadataTab() {
|
||||
if (setTextareaValue("wfm-preset-neg", text)) flashBtn(this);
|
||||
});
|
||||
|
||||
_externalHandleFile = handleFile;
|
||||
|
||||
// Drag & Drop
|
||||
dropZone.addEventListener("dragover", e => { e.preventDefault(); e.stopPropagation(); dropZone.classList.add("drag-over"); });
|
||||
dropZone.addEventListener("dragleave", e => { e.stopPropagation(); dropZone.classList.remove("drag-over"); });
|
||||
|
||||
+392
-73
@@ -7,10 +7,12 @@ import { showToast, openModal, closeModal } from "./app.js";
|
||||
import { t } from "./i18n.js";
|
||||
import { comfyUI } from "./comfyui-client.js";
|
||||
import { comfyEditor } from "./comfyui-editor.js";
|
||||
import { escapeHtml, readJsonStorage } from "./util.js";
|
||||
|
||||
// ── Constants ─────────────────────────────────────────────
|
||||
const RESERVED_GROUPS = ["Batch"];
|
||||
const RESERVED_GROUPS = ["Batch", "Stack"];
|
||||
const BATCH_MODEL_TYPES = ["checkpoint", "lora"];
|
||||
const STACK_MODEL_TYPES = ["lora"];
|
||||
|
||||
// ── State ─────────────────────────────────────────────────
|
||||
|
||||
@@ -30,6 +32,7 @@ const state = {
|
||||
allModelGroups: {}, // { type: { groupName: [models] } } — all types
|
||||
civitaiCache: {},
|
||||
disabledModels: {}, // { type: Set<modelName> }
|
||||
subdirs: [],
|
||||
selectMode: false,
|
||||
selectedModels: new Set(),
|
||||
searchText: "",
|
||||
@@ -45,6 +48,8 @@ const state = {
|
||||
selectedModel: null,
|
||||
loaded: {},
|
||||
currentPage: 0,
|
||||
sortColumn: null, // "fav" | "filename" | "subdir" | "civtype" | "basemodel" | "ext" | "tags" | "memo" | "enabled"
|
||||
sortDir: "asc", // "asc" | "desc"
|
||||
};
|
||||
|
||||
|
||||
@@ -91,25 +96,81 @@ function applyToGenUI(modelName, modelType) {
|
||||
return;
|
||||
}
|
||||
|
||||
const { key, inputKey } = mapping;
|
||||
let selectEl = null;
|
||||
|
||||
// Find the first matching node in the current workflow
|
||||
const nodeId = Object.keys(comfyUI.currentWorkflow).find((id) => {
|
||||
const node = comfyUI.currentWorkflow[id];
|
||||
return node.inputs && inputKey in node.inputs;
|
||||
});
|
||||
if (modelType === "lora") {
|
||||
// Use lora_nodes from analysis to correctly handle Lora Loader (LoraManager)
|
||||
const loraNodes = comfyUI.currentAnalysis?.lora_nodes || [];
|
||||
let nodeId = null;
|
||||
let isLoraManager = false;
|
||||
|
||||
if (!nodeId) {
|
||||
showToast(t("modelsGenUINoNode", TYPE_LABELS[modelType] || modelType), "warning");
|
||||
return;
|
||||
if (loraNodes.length > 0) {
|
||||
const targetNode = loraNodes[0];
|
||||
nodeId = targetNode.id;
|
||||
isLoraManager = !!targetNode.is_lora_manager;
|
||||
} else {
|
||||
// Fallback: find a standard LoraLoader node by lora_name input
|
||||
nodeId = Object.keys(comfyUI.currentWorkflow).find((id) => {
|
||||
const node = comfyUI.currentWorkflow[id];
|
||||
return node.inputs && "lora_name" in node.inputs;
|
||||
});
|
||||
}
|
||||
|
||||
if (!nodeId || !comfyUI.currentWorkflow[nodeId]) {
|
||||
showToast(t("modelsGenUINoNode", TYPE_LABELS[modelType] || modelType), "warning");
|
||||
return;
|
||||
}
|
||||
|
||||
const stem = modelName.replace(/\\/g, "/").split("/").pop().replace(/\.[^.]+$/, "");
|
||||
|
||||
if (isLoraManager) {
|
||||
comfyUI.currentWorkflow[nodeId].inputs.loras = {
|
||||
__value__: [{ name: stem, strength: 1.0, active: true, expanded: false, clipStrength: 1.0, locked: false }],
|
||||
};
|
||||
comfyUI.currentWorkflow[nodeId].inputs.text = `<lora:${stem}:1:1>`;
|
||||
} else {
|
||||
comfyUI.currentWorkflow[nodeId].inputs.lora_name = modelName;
|
||||
}
|
||||
|
||||
// Disable all Stack models and switch to Single tab
|
||||
comfyEditor.disableAllStack("wfm-gen-lora-fields");
|
||||
comfyEditor.switchLoraSingleTab();
|
||||
|
||||
// Update Single tab LORA SYNTAX and TRIGGER WORDS displays
|
||||
const loraSyntax = `<lora:${stem}:1:1>`;
|
||||
const sha = (state.modelMetadata[modelName] || {}).sha256;
|
||||
const civInfo = sha && state.civitaiCache[sha];
|
||||
const triggerWords = civInfo?.trainedWords || [];
|
||||
|
||||
const singleSyntaxEl = document.getElementById("wfm-lora-single-syntax");
|
||||
if (singleSyntaxEl) singleSyntaxEl.textContent = loraSyntax;
|
||||
|
||||
const singleTriggersEl = document.getElementById("wfm-lora-single-triggers");
|
||||
if (singleTriggersEl) {
|
||||
singleTriggersEl.innerHTML = triggerWords.length
|
||||
? triggerWords.map(w => `<span class="wfm-lora-trigger-word">${w}</span>`).join(" ")
|
||||
: `<span style="color:var(--wfm-text-secondary);font-size:12px;">—</span>`;
|
||||
}
|
||||
|
||||
selectEl = document.getElementById("wfm-lora-select");
|
||||
} else {
|
||||
const { key, inputKey } = mapping;
|
||||
|
||||
const nodeId = Object.keys(comfyUI.currentWorkflow).find((id) => {
|
||||
const node = comfyUI.currentWorkflow[id];
|
||||
return node.inputs && inputKey in node.inputs;
|
||||
});
|
||||
|
||||
if (!nodeId) {
|
||||
showToast(t("modelsGenUINoNode", TYPE_LABELS[modelType] || modelType), "warning");
|
||||
return;
|
||||
}
|
||||
|
||||
comfyUI.currentWorkflow[nodeId].inputs[inputKey] = modelName;
|
||||
selectEl = document.getElementById(`wfm-model-${key}`);
|
||||
}
|
||||
|
||||
comfyUI.currentWorkflow[nodeId].inputs[inputKey] = modelName;
|
||||
|
||||
// Sync GenUI select element if visible
|
||||
const selectEl = document.getElementById(`wfm-model-${key}`);
|
||||
if (selectEl) {
|
||||
// Add option if not present (subdir paths may not be in list)
|
||||
if (![...selectEl.options].some(o => o.value === modelName)) {
|
||||
const opt = document.createElement("option");
|
||||
opt.value = modelName;
|
||||
@@ -119,7 +180,6 @@ function applyToGenUI(modelName, modelType) {
|
||||
selectEl.value = modelName;
|
||||
}
|
||||
|
||||
// Sync raw JSON display
|
||||
const rawTextarea = document.getElementById("wfm-gen-raw-json");
|
||||
if (rawTextarea) {
|
||||
rawTextarea.value = JSON.stringify(comfyUI.currentWorkflow, null, 2);
|
||||
@@ -131,9 +191,7 @@ function applyToGenUI(modelName, modelType) {
|
||||
// User-defined badge colors (stored in metadata per model)
|
||||
// Global badge palette: label → color, stored in localStorage
|
||||
function getBadgePalette() {
|
||||
try {
|
||||
return JSON.parse(localStorage.getItem("wfm_models_badge_palette") || "{}");
|
||||
} catch { return {}; }
|
||||
return readJsonStorage("wfm_models_badge_palette");
|
||||
}
|
||||
|
||||
function saveBadgePalette(palette) {
|
||||
@@ -142,13 +200,6 @@ function saveBadgePalette(palette) {
|
||||
|
||||
// ── Helpers ───────────────────────────────────────────────
|
||||
|
||||
function escapeHtml(s) {
|
||||
return String(s)
|
||||
.replace(/&/g, "&")
|
||||
.replace(/</g, "<")
|
||||
.replace(/>/g, ">")
|
||||
.replace(/"/g, """);
|
||||
}
|
||||
|
||||
function parseModelPath(fullName) {
|
||||
const lastSlash = Math.max(fullName.lastIndexOf("/"), fullName.lastIndexOf("\\"));
|
||||
@@ -263,6 +314,12 @@ function clearSelection() {
|
||||
renderBulkActionBar();
|
||||
}
|
||||
|
||||
function selectAll() {
|
||||
filterModels().forEach(m => state.selectedModels.add(m));
|
||||
renderModelGrid();
|
||||
renderBulkActionBar();
|
||||
}
|
||||
|
||||
function renderBulkActionBar() {
|
||||
const bar = document.getElementById("wfm-models-bulk-bar");
|
||||
if (!bar) return;
|
||||
@@ -286,28 +343,48 @@ function renderBulkActionBar() {
|
||||
|
||||
bar.style.display = "flex";
|
||||
bar.innerHTML = `
|
||||
<span class="wfm-bulk-count">${count} ${t("modelSelected")}</span>
|
||||
<button class="wfm-btn wfm-btn-sm" id="wfm-bulk-deselect-all-btn">${t("modelBulkDeselectAll")}</button>
|
||||
<span class="wfm-bulk-sep">|</span>
|
||||
<button class="wfm-btn wfm-btn-sm" id="wfm-bulk-fav-add-btn" title="${t("modelBulkFavAdd")}">${t("modelBulkFavAdd")}</button>
|
||||
<button class="wfm-btn wfm-btn-sm" id="wfm-bulk-fav-remove-btn" title="${t("modelBulkFavRemove")}">${t("modelBulkFavRemove")}</button>
|
||||
<span class="wfm-bulk-sep">|</span>
|
||||
<select id="wfm-bulk-group-select" class="wfm-select" style="font-size:12px;">${groupOptions}</select>
|
||||
<button class="wfm-btn wfm-btn-sm wfm-btn-primary" id="wfm-bulk-add-btn"${noGroups ? " disabled" : ""}>${t("modelBulkAddGroup")}</button>
|
||||
<button class="wfm-btn wfm-btn-sm wfm-btn-danger" id="wfm-bulk-remove-btn"${noGroups ? " disabled" : ""}>${t("modelBulkRemoveGroup")}</button>
|
||||
<span class="wfm-bulk-sep">|</span>
|
||||
<input type="text" id="wfm-bulk-new-group-input" class="wfm-search-input" style="width:120px;font-size:12px;" placeholder="${t("modelsGroupName")}">
|
||||
<button class="wfm-btn wfm-btn-sm" id="wfm-bulk-create-add-btn">${t("modelBulkCreateAdd")}</button>
|
||||
<span class="wfm-bulk-sep">|</span>
|
||||
<select id="wfm-bulk-badge-select" class="wfm-select" style="font-size:12px;">${badgeOptions}</select>
|
||||
<button class="wfm-btn wfm-btn-sm wfm-btn-primary" id="wfm-bulk-badge-apply-btn"${noBadges ? " disabled" : ""}>${t("modelBulkBadgeApply")}</button>
|
||||
<button class="wfm-btn wfm-btn-sm wfm-btn-danger" id="wfm-bulk-badge-remove-btn"${noBadges ? " disabled" : ""}>${t("modelBulkBadgeRemove")}</button>
|
||||
<span class="wfm-bulk-sep">|</span>
|
||||
<button class="wfm-btn wfm-btn-sm" id="wfm-bulk-clear-btn" title="Clear selection">×</button>
|
||||
<button class="wfm-btn wfm-btn-sm wfm-btn-danger" id="wfm-bulk-delete-btn" style="margin-left:4px;">${t("modelBulkDelete")}</button>
|
||||
<div class="wfm-bulk-header">
|
||||
<span class="wfm-bulk-count">${count} ${t("modelSelected")}</span>
|
||||
<button class="wfm-btn wfm-btn-sm" id="wfm-bulk-deselect-all-btn">${t("modelBulkDeselectAll")}</button>
|
||||
<button class="wfm-btn wfm-btn-sm" id="wfm-bulk-select-all-btn">${t("modelBulkSelectAll")}</button>
|
||||
<span class="wfm-bulk-sep"></span>
|
||||
<button class="wfm-btn wfm-btn-sm" id="wfm-bulk-fav-add-btn">${t("modelBulkFavAdd")}</button>
|
||||
<button class="wfm-btn wfm-btn-sm" id="wfm-bulk-fav-remove-btn">${t("modelBulkFavRemove")}</button>
|
||||
</div>
|
||||
<div class="wfm-bulk-rows">
|
||||
<div class="wfm-bulk-row">
|
||||
<span class="wfm-bulk-row-label">Group:</span>
|
||||
<select id="wfm-bulk-group-select" class="wfm-select wfm-bulk-select">${groupOptions}</select>
|
||||
<button class="wfm-btn wfm-btn-sm wfm-btn-primary" id="wfm-bulk-add-btn"${noGroups ? " disabled" : ""}>${t("modelBulkAddGroup")}</button>
|
||||
<button class="wfm-btn wfm-btn-sm wfm-btn-danger" id="wfm-bulk-remove-btn"${noGroups ? " disabled" : ""}>${t("modelBulkRemoveGroup")}</button>
|
||||
<span class="wfm-bulk-sep"></span>
|
||||
<input type="text" id="wfm-bulk-new-group-input" class="wfm-search-input wfm-bulk-input" placeholder="${t("modelsGroupName")}">
|
||||
<button class="wfm-btn wfm-btn-sm" id="wfm-bulk-create-add-btn">${t("modelBulkCreateAdd")}</button>
|
||||
</div>
|
||||
<div class="wfm-bulk-row">
|
||||
<span class="wfm-bulk-row-label">Badge:</span>
|
||||
<select id="wfm-bulk-badge-select" class="wfm-select wfm-bulk-select">${badgeOptions}</select>
|
||||
<button class="wfm-btn wfm-btn-sm wfm-btn-primary" id="wfm-bulk-badge-apply-btn"${noBadges ? " disabled" : ""}>${t("modelBulkBadgeApply")}</button>
|
||||
<button class="wfm-btn wfm-btn-sm wfm-btn-danger" id="wfm-bulk-badge-remove-btn"${noBadges ? " disabled" : ""}>${t("modelBulkBadgeRemove")}</button>
|
||||
</div>
|
||||
<div class="wfm-bulk-row">
|
||||
<span class="wfm-bulk-row-label">File:</span>
|
||||
<select id="wfm-bulk-move-select" class="wfm-select wfm-bulk-select">
|
||||
<option value="">${t("modelBulkMoveRoot")}</option>
|
||||
${state.subdirs.map((d) => `<option value="${escapeHtml(d)}">${escapeHtml(d)}</option>`).join("")}
|
||||
</select>
|
||||
<button class="wfm-btn wfm-btn-sm" id="wfm-bulk-move-btn">${t("modelBulkMoveBtn")}</button>
|
||||
<span class="wfm-bulk-sep"></span>
|
||||
<input type="text" id="wfm-bulk-new-dir-input" class="wfm-search-input wfm-bulk-input" placeholder="${t("modelBulkMoveNewFolder")}">
|
||||
<button class="wfm-btn wfm-btn-sm" id="wfm-bulk-mkdir-move-btn">${t("modelBulkMoveCreateMove")}</button>
|
||||
<span style="flex:1"></span>
|
||||
<button class="wfm-btn wfm-btn-sm wfm-btn-danger" id="wfm-bulk-delete-btn">${t("modelBulkDelete")}</button>
|
||||
</div>
|
||||
</div>
|
||||
`;
|
||||
|
||||
document.getElementById("wfm-bulk-deselect-all-btn")?.addEventListener("click", clearSelection);
|
||||
document.getElementById("wfm-bulk-select-all-btn")?.addEventListener("click", selectAll);
|
||||
document.getElementById("wfm-bulk-fav-add-btn")?.addEventListener("click", () => bulkSetFavorite(true));
|
||||
document.getElementById("wfm-bulk-fav-remove-btn")?.addEventListener("click", () => bulkSetFavorite(false));
|
||||
document.getElementById("wfm-bulk-add-btn")?.addEventListener("click", () => {
|
||||
@@ -333,7 +410,16 @@ function renderBulkActionBar() {
|
||||
const label = document.getElementById("wfm-bulk-badge-select")?.value;
|
||||
if (label) bulkApplyBadge(label, false);
|
||||
});
|
||||
document.getElementById("wfm-bulk-clear-btn")?.addEventListener("click", clearSelection);
|
||||
document.getElementById("wfm-bulk-move-btn")?.addEventListener("click", () => {
|
||||
const dest = document.getElementById("wfm-bulk-move-select")?.value || "";
|
||||
bulkMoveModels(dest);
|
||||
});
|
||||
document.getElementById("wfm-bulk-mkdir-move-btn")?.addEventListener("click", () => {
|
||||
const input = document.getElementById("wfm-bulk-new-dir-input");
|
||||
const name = input?.value.trim();
|
||||
if (!name) return;
|
||||
bulkMoveModels(name);
|
||||
});
|
||||
document.getElementById("wfm-bulk-delete-btn")?.addEventListener("click", bulkDeleteModels);
|
||||
}
|
||||
|
||||
@@ -438,6 +524,58 @@ async function bulkDeleteModels() {
|
||||
}
|
||||
}
|
||||
|
||||
async function fetchSubdirs() {
|
||||
try {
|
||||
const res = await fetch(`/api/wfm/models/subdirs?type=${encodeURIComponent(state.activeModelType)}`);
|
||||
state.subdirs = res.ok ? await res.json() : [];
|
||||
} catch { state.subdirs = []; }
|
||||
}
|
||||
|
||||
async function bulkMoveModels(destSubdir) {
|
||||
const model_names = [...state.selectedModels];
|
||||
if (model_names.length === 0) return;
|
||||
try {
|
||||
const res = await fetch("/api/wfm/models/move", {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify({ model_type: state.activeModelType, model_names, dest: destSubdir }),
|
||||
});
|
||||
const data = await res.json();
|
||||
const okCount = data.moved?.length || 0;
|
||||
const errCount = data.errors?.length || 0;
|
||||
|
||||
if (okCount > 0) {
|
||||
data.moved.forEach(({ from, to }) => {
|
||||
const list = state.modelsByType[state.activeModelType];
|
||||
const idx = list.indexOf(from);
|
||||
if (idx !== -1) list[idx] = to;
|
||||
if (state.modelMetadata[from]) {
|
||||
state.modelMetadata[to] = state.modelMetadata[from];
|
||||
delete state.modelMetadata[from];
|
||||
}
|
||||
const ds = state.disabledModels[state.activeModelType];
|
||||
if (ds && ds.has(from)) { ds.delete(from); ds.add(to); }
|
||||
state.selectedModels.delete(from);
|
||||
});
|
||||
if (state.selectedModel && data.moved.some((m) => m.from === state.selectedModel)) {
|
||||
state.selectedModel = null;
|
||||
const titleEl = document.getElementById("wfm-models-panel-title");
|
||||
if (titleEl) titleEl.textContent = "";
|
||||
}
|
||||
showToast(`${okCount} ${t("modelBulkMoveDone")}`, "success");
|
||||
await fetchSubdirs();
|
||||
renderDirFilter();
|
||||
renderModelGrid();
|
||||
renderBulkActionBar();
|
||||
}
|
||||
if (errCount > 0) {
|
||||
showToast(`${t("modelBulkMoveError")}: ${data.errors[0].error}`, "error");
|
||||
}
|
||||
} catch (err) {
|
||||
showToast(`${t("modelBulkMoveError")}: ${err.message}`, "error");
|
||||
}
|
||||
}
|
||||
|
||||
// ── Enable / Disable helpers ──────────────────────────────
|
||||
|
||||
function isModelDisabled(modelName) {
|
||||
@@ -532,7 +670,7 @@ async function saveModelMetadata(modelName, updates) {
|
||||
}
|
||||
return data;
|
||||
} catch (err) {
|
||||
showToast("Error saving metadata: " + err.message, "error");
|
||||
showToast(t("saveFailed", err.message), "error");
|
||||
return null;
|
||||
}
|
||||
}
|
||||
@@ -601,7 +739,47 @@ function filterModels() {
|
||||
});
|
||||
}
|
||||
|
||||
return models;
|
||||
return sortModels(models);
|
||||
}
|
||||
|
||||
function sortKeyOf(modelName) {
|
||||
const meta = state.modelMetadata[modelName] || {};
|
||||
switch (state.sortColumn) {
|
||||
case "fav":
|
||||
return meta.favorite ? 1 : 0;
|
||||
case "filename":
|
||||
return parseModelPath(modelName).name.toLowerCase();
|
||||
case "subdir":
|
||||
return parseModelPath(modelName).dir.toLowerCase();
|
||||
case "civtype": {
|
||||
const civ = meta.sha256 && state.civitaiCache[meta.sha256];
|
||||
return (civ?.type || "").toLowerCase();
|
||||
}
|
||||
case "basemodel": {
|
||||
const civ = meta.sha256 && state.civitaiCache[meta.sha256];
|
||||
return (civ?.baseModel || "").toLowerCase();
|
||||
}
|
||||
case "ext":
|
||||
return getExtension(parseModelPath(modelName).name).toLowerCase();
|
||||
case "tags":
|
||||
return (meta.tags || []).join(", ").toLowerCase();
|
||||
case "memo":
|
||||
return (meta.memo || "").toLowerCase();
|
||||
case "enabled":
|
||||
return isModelDisabled(modelName) ? 1 : 0;
|
||||
default:
|
||||
return 0;
|
||||
}
|
||||
}
|
||||
|
||||
function sortModels(models) {
|
||||
if (!state.sortColumn) return models;
|
||||
// ソートキーを1モデル1回だけ計算(比較ごとのparseModelPath等の再計算を回避)
|
||||
const dir = state.sortDir === "asc" ? 1 : -1;
|
||||
return models
|
||||
.map((m) => [sortKeyOf(m), m])
|
||||
.sort((a, b) => (a[0] < b[0] ? -dir : a[0] > b[0] ? dir : 0))
|
||||
.map((pair) => pair[1]);
|
||||
}
|
||||
|
||||
function getAllTags() {
|
||||
@@ -846,8 +1024,12 @@ function renderThumbView(grid, models) {
|
||||
const tagsHtml = (meta.tags || []).map((tag) => `<span class="wfm-badge wfm-badge-sm">${escapeHtml(tag)}</span>`).join("");
|
||||
const favStar = meta.favorite ? "\u2605" : "\u2606";
|
||||
const favClass = meta.favorite ? "wfm-fav-btn active" : "wfm-fav-btn";
|
||||
const inBatch = isInBatch(modelName);
|
||||
const showBatchBtn = ["checkpoint", "lora"].includes(state.activeModelType);
|
||||
const showStackBtn = state.activeModelType === "lora";
|
||||
const inBatch = showBatchBtn && isInBatch(modelName);
|
||||
const inStack = showStackBtn && isInStack(modelName);
|
||||
const batchClass = inBatch ? "wfm-batch-btn active" : "wfm-batch-btn";
|
||||
const stackClass = inStack ? "wfm-stack-btn active" : "wfm-stack-btn";
|
||||
|
||||
const card = document.createElement("div");
|
||||
card.className = "wfm-card";
|
||||
@@ -865,7 +1047,8 @@ function renderThumbView(grid, models) {
|
||||
<div class="wfm-card-title" title="${escapeHtml(modelName)}">${escapeHtml(getStem(name))}</div>
|
||||
<div class="wfm-card-meta">${userBadges} ${tagsHtml}</div>
|
||||
</div>
|
||||
<button class="${batchClass}" title="${t("modelsBatch")}">B</button>
|
||||
${showBatchBtn ? `<button class="${batchClass}" title="${t("modelsBatch")}">B</button>` : ""}
|
||||
${showStackBtn ? `<button class="${stackClass}" title="Stack (Lora multi-apply)">S</button>` : ""}
|
||||
<button class="${favClass}" title="${t("modelsFavorite")}">${favStar}</button>
|
||||
<button class="wfm-toggle-btn${disabled ? " wfm-toggle-disabled" : ""}" title="${disabled ? t("modelEnable") : t("modelDisable")}">${disabled ? "▶" : "⏸"}</button>`;
|
||||
|
||||
@@ -874,9 +1057,19 @@ function renderThumbView(grid, models) {
|
||||
const placeholder = card.querySelector(".wfm-card-thumb-placeholder");
|
||||
loadPreviewImage(img, placeholder, modelName);
|
||||
|
||||
card.querySelector(".wfm-batch-btn").addEventListener("click", (e) => {
|
||||
card.querySelector(".wfm-batch-btn")?.addEventListener("click", async (e) => {
|
||||
e.stopPropagation();
|
||||
toggleBatch(modelName);
|
||||
await toggleBatch(modelName);
|
||||
if (state.showBatchOnly) {
|
||||
renderModelGrid();
|
||||
} else {
|
||||
e.currentTarget.classList.toggle("active", isInBatch(modelName));
|
||||
}
|
||||
});
|
||||
card.querySelector(".wfm-stack-btn")?.addEventListener("click", async (e) => {
|
||||
e.stopPropagation();
|
||||
await toggleStack(modelName);
|
||||
e.currentTarget.classList.toggle("active", isInStack(modelName));
|
||||
});
|
||||
card.querySelector(".wfm-fav-btn").addEventListener("click", (e) => {
|
||||
e.stopPropagation();
|
||||
@@ -893,7 +1086,7 @@ function renderThumbView(grid, models) {
|
||||
checkEl.className = "wfm-select-check" + (isChecked ? " checked" : "");
|
||||
card.appendChild(checkEl);
|
||||
card.addEventListener("click", (e) => {
|
||||
if (e.target.closest(".wfm-batch-btn, .wfm-fav-btn, .wfm-toggle-btn")) return;
|
||||
if (e.target.closest(".wfm-batch-btn, .wfm-stack-btn, .wfm-fav-btn, .wfm-toggle-btn")) return;
|
||||
toggleModelSelection(modelName);
|
||||
});
|
||||
} else {
|
||||
@@ -907,16 +1100,31 @@ function renderThumbView(grid, models) {
|
||||
|
||||
// ── Table View ────────────────────────────────────────────
|
||||
|
||||
function thSortHtml(label, col, extraClass = "", extraStyle = "") {
|
||||
const isActive = state.sortColumn === col;
|
||||
const arrow = isActive ? (state.sortDir === "asc" ? " ▲" : " ▼") : "";
|
||||
const activeStyle = isActive ? "color:var(--wfm-accent,#6366f1);" : "";
|
||||
const cls = ["wfm-table-th-sortable", extraClass].filter(Boolean).join(" ");
|
||||
return `<th class="${cls}" data-sort-col="${col}" style="${activeStyle}${extraStyle}">${label}${arrow}</th>`;
|
||||
}
|
||||
|
||||
function renderTableView(grid, models) {
|
||||
const showBatchBtn = ["checkpoint", "lora"].includes(state.activeModelType);
|
||||
const showStackBtn = state.activeModelType === "lora";
|
||||
const rows = models
|
||||
.map((modelName) => {
|
||||
const meta = state.modelMetadata[modelName] || {};
|
||||
const { dir, name } = parseModelPath(modelName);
|
||||
const ext = getExtension(name);
|
||||
const sha256 = meta.sha256;
|
||||
const civitai = sha256 && state.civitaiCache[sha256];
|
||||
const civitaiType = civitai ? (civitai.type || "") : "";
|
||||
const civitaiBaseModel = civitai ? (civitai.baseModel || "") : "";
|
||||
const disabled = isModelDisabled(modelName);
|
||||
const isChecked = state.selectMode && state.selectedModels.has(modelName);
|
||||
const favIcon = meta.favorite ? "★" : "☆";
|
||||
const batchIcon = isInBatch(modelName) ? `<button class="wfm-batch-btn active" title="${t("modelsBatch")}">B</button>` : `<button class="wfm-batch-btn" title="${t("modelsBatch")}">B</button>`;
|
||||
const batchIcon = !showBatchBtn ? "" : isInBatch(modelName) ? `<button class="wfm-batch-btn active" title="${t("modelsBatch")}">B</button>` : `<button class="wfm-batch-btn" title="${t("modelsBatch")}">B</button>`;
|
||||
const stackIcon = isInStack(modelName) ? `<button class="wfm-stack-btn active" title="Stack (Lora multi-apply)">S</button>` : `<button class="wfm-stack-btn" title="Stack (Lora multi-apply)">S</button>`;
|
||||
const tagsStr = (meta.tags || []).join(", ");
|
||||
const memo = meta.memo || "";
|
||||
const toggleLabel = disabled ? t("modelEnable") : t("modelDisable");
|
||||
@@ -928,13 +1136,16 @@ function renderTableView(grid, models) {
|
||||
${checkCell}
|
||||
<td class="wfm-models-table-fav" title="Favorite">${favIcon}</td>
|
||||
<td class="wfm-table-td-thumb"><img class="wfm-table-thumb" style="display:none" /></td>
|
||||
<td title="${escapeHtml(modelName)}">${escapeHtml(name)}</td>
|
||||
<td class="wfm-table-td-filename" title="${escapeHtml(modelName)}">${escapeHtml(name)}</td>
|
||||
<td class="wfm-table-td-subdir">${escapeHtml(dir)}</td>
|
||||
<td class="wfm-table-td-civtype" title="${escapeHtml(civitaiType)}">${escapeHtml(civitaiType)}</td>
|
||||
<td class="wfm-table-td-basemodel" title="${escapeHtml(civitaiBaseModel)}">${escapeHtml(civitaiBaseModel)}</td>
|
||||
<td class="wfm-table-td-ext">${escapeHtml(ext)}</td>
|
||||
<td>${escapeHtml(tagsStr)}</td>
|
||||
<td class="wfm-table-td-memo" title="${escapeHtml(memo)}">${escapeHtml(memo)}</td>
|
||||
<td class="wfm-table-td-toggle"><button class="wfm-toggle-btn${disabled ? " wfm-toggle-disabled" : ""}" title="${toggleLabel}">${toggleIcon}</button></td>
|
||||
<td class="wfm-table-td-batch">${batchIcon}</td>
|
||||
${showBatchBtn ? `<td class="wfm-table-td-batch">${batchIcon}</td>` : ""}
|
||||
${showStackBtn ? `<td class="wfm-table-td-stack">${stackIcon}</td>` : ""}
|
||||
</tr>`;
|
||||
})
|
||||
.join("");
|
||||
@@ -942,15 +1153,18 @@ function renderTableView(grid, models) {
|
||||
const checkTh = state.selectMode ? `<th style="width:24px;"></th>` : "";
|
||||
grid.innerHTML = `<table class="wfm-models-table"><thead><tr>
|
||||
${checkTh}
|
||||
<th style="width:30px;">★</th>
|
||||
${thSortHtml("★", "fav", "", "width:30px;text-align:center;")}
|
||||
<th style="width:40px;"></th>
|
||||
<th>${t("modelsFileName")}</th>
|
||||
<th class="wfm-table-th-subdir">${t("modelsSubdir")}</th>
|
||||
<th class="wfm-table-th-ext">${t("modelsExt")}</th>
|
||||
<th>${t("modelsTags")}</th>
|
||||
<th>${t("modelsMemo")}</th>
|
||||
<th style="width:50px;"></th>
|
||||
<th style="width:30px;">B</th>
|
||||
${thSortHtml(t("modelsFileName"), "filename", "wfm-table-th-filename")}
|
||||
${thSortHtml(t("modelsSubdir"), "subdir", "wfm-table-th-subdir")}
|
||||
${thSortHtml(t("civitaiType"), "civtype", "wfm-table-th-civtype")}
|
||||
${thSortHtml(t("civitaiBaseModel"), "basemodel", "wfm-table-th-basemodel")}
|
||||
${thSortHtml(t("modelsExt"), "ext", "wfm-table-th-ext")}
|
||||
${thSortHtml(t("modelsTags"), "tags")}
|
||||
${thSortHtml(t("modelsMemo"), "memo")}
|
||||
${thSortHtml("E/D", "enabled", "", "width:50px;text-align:center;")}
|
||||
${showBatchBtn ? `<th style="width:30px;">B</th>` : ""}
|
||||
${showStackBtn ? `<th style="width:30px;">S</th>` : ""}
|
||||
</tr></thead><tbody>${rows}</tbody></table>`;
|
||||
|
||||
grid.querySelectorAll(".wfm-models-table-row").forEach((row) => {
|
||||
@@ -960,7 +1174,7 @@ function renderTableView(grid, models) {
|
||||
|
||||
if (state.selectMode) {
|
||||
row.addEventListener("click", (e) => {
|
||||
if (e.target.closest(".wfm-models-table-fav, .wfm-toggle-btn, .wfm-batch-btn")) return;
|
||||
if (e.target.closest(".wfm-models-table-fav, .wfm-toggle-btn, .wfm-batch-btn, .wfm-stack-btn")) return;
|
||||
toggleModelSelection(mn);
|
||||
});
|
||||
} else {
|
||||
@@ -975,9 +1189,37 @@ function renderTableView(grid, models) {
|
||||
e.stopPropagation();
|
||||
toggleModelEnable(mn);
|
||||
});
|
||||
row.querySelector(".wfm-batch-btn").addEventListener("click", (e) => {
|
||||
row.querySelector(".wfm-batch-btn")?.addEventListener("click", async (e) => {
|
||||
e.stopPropagation();
|
||||
toggleBatch(mn);
|
||||
await toggleBatch(mn);
|
||||
if (state.showBatchOnly) {
|
||||
renderModelGrid();
|
||||
} else {
|
||||
e.currentTarget.classList.toggle("active", isInBatch(mn));
|
||||
}
|
||||
});
|
||||
row.querySelector(".wfm-stack-btn")?.addEventListener("click", async (e) => {
|
||||
e.stopPropagation();
|
||||
await toggleStack(mn);
|
||||
e.currentTarget.classList.toggle("active", isInStack(mn));
|
||||
});
|
||||
});
|
||||
|
||||
grid.querySelectorAll(".wfm-table-th-sortable").forEach((th) => {
|
||||
th.addEventListener("click", () => {
|
||||
const col = th.dataset.sortCol;
|
||||
if (state.sortColumn === col) {
|
||||
if (state.sortDir === "asc") {
|
||||
state.sortDir = "desc";
|
||||
} else {
|
||||
state.sortColumn = null;
|
||||
state.sortDir = "asc";
|
||||
}
|
||||
} else {
|
||||
state.sortColumn = col;
|
||||
state.sortDir = "asc";
|
||||
}
|
||||
renderModelGrid();
|
||||
});
|
||||
});
|
||||
}
|
||||
@@ -999,7 +1241,6 @@ async function toggleBatch(modelName) {
|
||||
state.modelGroups["Batch"] = batch;
|
||||
state.allModelGroups[state.activeModelType] = state.modelGroups;
|
||||
await saveModelGroups(state.modelGroups);
|
||||
renderModelGrid();
|
||||
}
|
||||
|
||||
async function clearBatchGroup() {
|
||||
@@ -1014,6 +1255,31 @@ async function clearBatchGroup() {
|
||||
showToast(t("modelsBatchClear"), "success");
|
||||
}
|
||||
|
||||
function isInStack(modelName) {
|
||||
return (state.modelGroups["Stack"] || []).includes(modelName);
|
||||
}
|
||||
|
||||
async function toggleStack(modelName) {
|
||||
const stack = state.modelGroups["Stack"] || [];
|
||||
const idx = stack.indexOf(modelName);
|
||||
if (idx >= 0) {
|
||||
stack.splice(idx, 1);
|
||||
} else {
|
||||
stack.push(modelName);
|
||||
}
|
||||
state.modelGroups["Stack"] = stack;
|
||||
state.allModelGroups[state.activeModelType] = state.modelGroups;
|
||||
await saveModelGroups(state.modelGroups);
|
||||
}
|
||||
|
||||
async function clearStackGroup() {
|
||||
state.modelGroups["Stack"] = [];
|
||||
state.allModelGroups[state.activeModelType] = state.modelGroups;
|
||||
await saveModelGroups(state.modelGroups);
|
||||
renderModelGrid();
|
||||
showToast(t("stackCleared"), "success");
|
||||
}
|
||||
|
||||
// ── Favorite toggle ───────────────────────────────────────
|
||||
|
||||
async function toggleFavorite(modelName) {
|
||||
@@ -1082,6 +1348,7 @@ function openDetailModal(modelName) {
|
||||
${GENUI_TYPE_MAP[state.activeModelType]
|
||||
? `<button class="wfm-btn wfm-btn-sm" id="wfm-modal-genui-model" title="${t("modelsGenUITitle")}">${t("modelsGenUIBtn")}</button>`
|
||||
: ""}
|
||||
<button class="wfm-btn wfm-btn-sm wfm-btn-danger" id="wfm-modal-model-delete" style="margin-left:auto;">${t("modelsDelete")}</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>`;
|
||||
@@ -1136,6 +1403,41 @@ function openDetailModal(modelName) {
|
||||
applyToGenUI(modelName, state.activeModelType);
|
||||
});
|
||||
|
||||
// Delete model button
|
||||
document.getElementById("wfm-modal-model-delete")?.addEventListener("click", async () => {
|
||||
const confirmMsg = t("modelBulkDeleteConfirm").replace("{count}", "1");
|
||||
if (!confirm(confirmMsg)) return;
|
||||
try {
|
||||
const res = await fetch("/api/wfm/models/delete", {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify({ model_type: state.activeModelType, model_names: [modelName] }),
|
||||
});
|
||||
const data = await res.json();
|
||||
if (data.errors?.length > 0) {
|
||||
showToast(`${t("modelBulkDeleteError")}: ${data.errors[0].error}`, "error");
|
||||
return;
|
||||
}
|
||||
showToast(`${getStem(name)} ${t("modelBulkDeleteDone")}`, "success");
|
||||
closeModal();
|
||||
const list = state.modelsByType[state.activeModelType];
|
||||
const idx = list.indexOf(modelName);
|
||||
if (idx !== -1) list.splice(idx, 1);
|
||||
delete state.modelMetadata[modelName];
|
||||
const ds = state.disabledModels[state.activeModelType];
|
||||
if (ds) ds.delete(modelName);
|
||||
state.selectedModels.delete(modelName);
|
||||
if (state.selectedModel === modelName) {
|
||||
state.selectedModel = null;
|
||||
const titleEl = document.getElementById("wfm-models-panel-title");
|
||||
if (titleEl) titleEl.textContent = "";
|
||||
}
|
||||
renderModelGrid();
|
||||
} catch (err) {
|
||||
showToast(`${t("modelBulkDeleteError")}: ${err.message}`, "error");
|
||||
}
|
||||
});
|
||||
|
||||
// Change thumbnail
|
||||
const changeBtn = document.getElementById("wfm-modal-change-thumb");
|
||||
const thumbFile = document.getElementById("wfm-modal-thumb-file");
|
||||
@@ -1187,12 +1489,12 @@ function showSidePanel(modelName) {
|
||||
const { name } = parseModelPath(modelName);
|
||||
document.getElementById("wfm-models-panel-title").textContent = name;
|
||||
|
||||
// Reset to Info tab
|
||||
// Reset to CivitAI tab
|
||||
document.querySelectorAll(".wfm-models-side-tab-btn").forEach((b) => b.classList.remove("active"));
|
||||
document.querySelector('.wfm-models-side-tab-btn[data-side-tab="info"]')?.classList.add("active");
|
||||
document.querySelector('.wfm-models-side-tab-btn[data-side-tab="civitai"]')?.classList.add("active");
|
||||
document.querySelectorAll(".wfm-models-side-content").forEach((c) => (c.style.display = "none"));
|
||||
const infoEl = document.getElementById("wfm-models-side-info");
|
||||
if (infoEl) infoEl.style.display = "block";
|
||||
const civitaiEl = document.getElementById("wfm-models-side-civitai");
|
||||
if (civitaiEl) civitaiEl.style.display = "block";
|
||||
|
||||
renderSideInfo(modelName);
|
||||
renderSideGroup(modelName);
|
||||
@@ -1729,11 +2031,17 @@ async function loadModelsForCurrentType() {
|
||||
state.modelGroups["Batch"] = [];
|
||||
await saveModelGroups(state.modelGroups);
|
||||
}
|
||||
if (STACK_MODEL_TYPES.includes(type) && !state.modelGroups["Stack"]) {
|
||||
state.modelGroups["Stack"] = [];
|
||||
await saveModelGroups(state.modelGroups);
|
||||
}
|
||||
if (!STACK_MODEL_TYPES.includes(type)) delete state.modelGroups["Stack"];
|
||||
state.allModelGroups[type] = state.modelGroups;
|
||||
renderTagFilter();
|
||||
renderDirFilter();
|
||||
renderGroupFilter();
|
||||
renderModelGrid();
|
||||
fetchSubdirs();
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -1752,6 +2060,11 @@ async function loadModelsForCurrentType() {
|
||||
groups["Batch"] = [];
|
||||
await saveModelGroups(groups);
|
||||
}
|
||||
if (STACK_MODEL_TYPES.includes(type) && !groups["Stack"]) {
|
||||
groups["Stack"] = [];
|
||||
await saveModelGroups(groups);
|
||||
}
|
||||
if (!STACK_MODEL_TYPES.includes(type)) delete groups["Stack"];
|
||||
state.modelGroups = groups;
|
||||
state.allModelGroups[type] = groups;
|
||||
|
||||
@@ -1766,10 +2079,11 @@ async function loadModelsForCurrentType() {
|
||||
renderDirFilter();
|
||||
renderGroupFilter();
|
||||
renderModelGrid();
|
||||
fetchSubdirs();
|
||||
} catch (err) {
|
||||
console.error("Failed to load models:", err);
|
||||
if (placeholder) placeholder.textContent = t("modelsLoadError");
|
||||
showToast("Error: " + err.message, "error");
|
||||
showToast(t("errorWithMsg", err.message), "error");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -2006,6 +2320,11 @@ export function initModelsTab() {
|
||||
clearBatchGroup();
|
||||
});
|
||||
|
||||
// Stack clear
|
||||
document.getElementById("wfm-models-stack-clear-btn")?.addEventListener("click", () => {
|
||||
clearStackGroup();
|
||||
});
|
||||
|
||||
// View mode (thumb / card / table)
|
||||
document.querySelectorAll("[data-models-view]").forEach((btn) => {
|
||||
if (btn.dataset.modelsView === state.viewMode) {
|
||||
|
||||
@@ -5,6 +5,7 @@
|
||||
import { showToast } from "./app.js";
|
||||
import { comfyUI } from "./comfyui-client.js";
|
||||
import { t } from "./i18n.js";
|
||||
import { escapeHtml } from "./util.js";
|
||||
|
||||
// ── State ─────────────────────────────────────────────────
|
||||
|
||||
@@ -50,9 +51,6 @@ function categoryBadgeHtml(cat) {
|
||||
return `<span class="wfm-badge wfm-badge-category">${cat}</span>`;
|
||||
}
|
||||
|
||||
function escapeHtml(s) {
|
||||
return String(s).replace(/&/g, "&").replace(/</g, "<").replace(/>/g, ">").replace(/"/g, """);
|
||||
}
|
||||
|
||||
// ── API ───────────────────────────────────────────────────
|
||||
|
||||
@@ -586,7 +584,7 @@ function renderSideGroups(node) {
|
||||
const name = input?.value?.trim();
|
||||
if (!name) return;
|
||||
if (state.nodeGroups[name]) {
|
||||
showToast("Group already exists", "warning");
|
||||
showToast(t("groupExists"), "warning");
|
||||
return;
|
||||
}
|
||||
state.nodeGroups[name] = [node.name];
|
||||
@@ -604,7 +602,7 @@ function renderSideGroups(node) {
|
||||
const newName = prompt(`Rename group "${oldName}" to:`, oldName);
|
||||
if (!newName || newName === oldName) return;
|
||||
if (state.nodeGroups[newName] !== undefined) {
|
||||
showToast("Group name already exists", "warning");
|
||||
showToast(t("groupNameExists"), "warning");
|
||||
return;
|
||||
}
|
||||
state.nodeGroups[newName] = state.nodeGroups[oldName];
|
||||
@@ -613,7 +611,7 @@ function renderSideGroups(node) {
|
||||
if (state.groupFilter === oldName) state.groupFilter = newName;
|
||||
renderSideGroups(node);
|
||||
renderFilters();
|
||||
showToast(`Renamed to "${newName}"`, "success");
|
||||
showToast(t("renamedTo", newName), "success");
|
||||
});
|
||||
|
||||
// グループ削除
|
||||
@@ -627,7 +625,7 @@ function renderSideGroups(node) {
|
||||
if (state.groupFilter === name) state.groupFilter = "";
|
||||
renderSideGroups(node);
|
||||
renderFilters();
|
||||
showToast(`Group "${name}" deleted`, "success");
|
||||
showToast(t("groupDeleted", name), "success");
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
+18
-19
@@ -4,6 +4,7 @@
|
||||
|
||||
import { showToast } from "./app.js";
|
||||
import { t } from "./i18n.js";
|
||||
import { readJsonStorage } from "./util.js";
|
||||
|
||||
// ============================================
|
||||
// State
|
||||
@@ -115,9 +116,7 @@ async function loadAllPresets() {
|
||||
promptPresets = await fetchPresets();
|
||||
|
||||
// Load groups from localStorage
|
||||
try {
|
||||
pmGroups = JSON.parse(localStorage.getItem(PM_GROUPS_KEY) || "{}");
|
||||
} catch { pmGroups = {}; }
|
||||
pmGroups = readJsonStorage(PM_GROUPS_KEY);
|
||||
|
||||
// Clean stale entries from groups (preserve reserved groups even if empty)
|
||||
const validIds = new Set(promptPresets.map(p => p.id));
|
||||
@@ -1050,43 +1049,43 @@ export function initPromptTab() {
|
||||
if (!name || !name.trim()) return;
|
||||
const key = name.trim();
|
||||
if (pmGroups[key]) {
|
||||
showToast("Group already exists", "error");
|
||||
showToast(t("groupExists"), "error");
|
||||
return;
|
||||
}
|
||||
pmGroups[key] = [];
|
||||
saveGroups();
|
||||
renderPresetManager();
|
||||
showToast(`Group "${key}" created`, "success");
|
||||
showToast(t("groupCreated", key), "success");
|
||||
});
|
||||
|
||||
document.getElementById("wfm-preset-add-to-group-btn")?.addEventListener("click", () => {
|
||||
const groupSelect = document.getElementById("wfm-preset-group-select");
|
||||
const groupName = groupSelect?.value;
|
||||
if (!groupName) {
|
||||
showToast("Select a group first", "error");
|
||||
showToast(t("selectGroupFirst"), "error");
|
||||
return;
|
||||
}
|
||||
const id = presetSelect?.value;
|
||||
if (!id) {
|
||||
showToast("Select a preset first", "error");
|
||||
showToast(t("selectPresetFirst"), "error");
|
||||
return;
|
||||
}
|
||||
if (!pmGroups[groupName]) pmGroups[groupName] = [];
|
||||
if (pmGroups[groupName].includes(id)) {
|
||||
showToast("Already in this group", "info");
|
||||
showToast(t("alreadyInGroup"), "info");
|
||||
return;
|
||||
}
|
||||
pmGroups[groupName].push(id);
|
||||
saveGroups();
|
||||
renderPresetManager();
|
||||
showToast("Added to group", "success");
|
||||
showToast(t("addedToGroup"), "success");
|
||||
});
|
||||
|
||||
document.getElementById("wfm-preset-del-group-btn")?.addEventListener("click", () => {
|
||||
const groupSelect = document.getElementById("wfm-preset-group-select");
|
||||
const groupName = groupSelect?.value;
|
||||
if (!groupName) {
|
||||
showToast("Select a group first", "error");
|
||||
showToast(t("selectGroupFirst"), "error");
|
||||
return;
|
||||
}
|
||||
if (PROMPT_RESERVED_GROUPS.includes(groupName)) {
|
||||
@@ -1097,7 +1096,7 @@ export function initPromptTab() {
|
||||
delete pmGroups[groupName];
|
||||
saveGroups();
|
||||
renderPresetManager();
|
||||
showToast(`Group "${groupName}" deleted`, "success");
|
||||
showToast(t("groupDeleted", groupName), "success");
|
||||
});
|
||||
|
||||
// --- Preset Manager ---
|
||||
@@ -1160,7 +1159,7 @@ export function initPromptTab() {
|
||||
const n = prompt("Number of items to pick (n):", "2");
|
||||
if (n === null) return;
|
||||
const num = parseInt(n, 10);
|
||||
if (isNaN(num) || num < 1) { showToast("Enter a positive integer", "error"); return; }
|
||||
if (isNaN(num) || num < 1) { showToast(t("enterPositiveInt"), "error"); return; }
|
||||
const template = "{" + num + "$$|}";
|
||||
const start = ta.selectionStart;
|
||||
wcInsertAtCursor(ta, template);
|
||||
@@ -1198,7 +1197,7 @@ export function initPromptTab() {
|
||||
if (!src || !dst) return;
|
||||
dst.value = src.value;
|
||||
dst.dispatchEvent(new Event("input", { bubbles: true }));
|
||||
showToast("Sent to Positive Prompt", "success");
|
||||
showToast(t("sentToPositive"), "success");
|
||||
});
|
||||
|
||||
document.getElementById("wfm-wc-to-neg-btn")?.addEventListener("click", () => {
|
||||
@@ -1207,7 +1206,7 @@ export function initPromptTab() {
|
||||
if (!src || !dst) return;
|
||||
dst.value = src.value;
|
||||
dst.dispatchEvent(new Event("input", { bubbles: true }));
|
||||
showToast("Sent to Negative Prompt", "success");
|
||||
showToast(t("sentToNegative"), "success");
|
||||
});
|
||||
|
||||
document.getElementById("wfm-wc-clear-btn")?.addEventListener("click", () => {
|
||||
@@ -1235,22 +1234,22 @@ export function initPromptTab() {
|
||||
const ext = extSelect?.value || "txt";
|
||||
const content = contentTA?.value || "";
|
||||
|
||||
if (!rawName) { showToast("Enter a filename", "error"); return; }
|
||||
if (!rawName) { showToast(t("pleaseEnterFilename"), "error"); return; }
|
||||
// Validate each path component (allow letters, numbers, -, _, ., space)
|
||||
const nameParts = rawName.split("/");
|
||||
if (nameParts.some(p => !p || !/^[\w\-. ]+$/.test(p))) {
|
||||
showToast("Invalid path. Use folder/name format, each part: letters, numbers, -, _, . only", "error");
|
||||
showToast(t("invalidPathFormat"), "error");
|
||||
return;
|
||||
}
|
||||
const name = rawName;
|
||||
const filename = `${name}.${ext}`;
|
||||
const saved = await wcSaveFile(filename, content);
|
||||
if (saved) {
|
||||
showToast(`Saved: ${filename}`, "success");
|
||||
showToast(t("savedAs", filename), "success");
|
||||
wcCloseEditor();
|
||||
wcRefreshFiles();
|
||||
} else {
|
||||
showToast("Failed to save file", "error");
|
||||
showToast(t("saveFailed"), "error");
|
||||
}
|
||||
});
|
||||
|
||||
@@ -1259,7 +1258,7 @@ export function initPromptTab() {
|
||||
if (!wcEditingFilename) return;
|
||||
if (!confirm(`Delete "${wcEditingFilename}"?`)) return;
|
||||
await wcDeleteFile(wcEditingFilename);
|
||||
showToast(`Deleted: ${wcEditingFilename}`, "success");
|
||||
showToast(t("deletedName", wcEditingFilename), "success");
|
||||
wcCloseEditor();
|
||||
wcRefreshFiles();
|
||||
});
|
||||
|
||||
@@ -6,6 +6,8 @@ import { showToast } from "./app.js";
|
||||
import { comfyUI } from "./comfyui-client.js";
|
||||
import { t, getLang, getSummaryLang, setLang, setSummaryLang, getLanguageOptions, getSummaryLanguageOptions } from "./i18n.js";
|
||||
|
||||
import { getSettings, readJsonStorage } from "./util.js";
|
||||
|
||||
const SETTINGS_KEY = "wfm_settings";
|
||||
|
||||
function rgbToHex(rgb) {
|
||||
@@ -15,11 +17,7 @@ function rgbToHex(rgb) {
|
||||
}
|
||||
|
||||
function loadLocalSettings() {
|
||||
try {
|
||||
return JSON.parse(localStorage.getItem(SETTINGS_KEY) || "{}");
|
||||
} catch {
|
||||
return {};
|
||||
}
|
||||
return readJsonStorage(SETTINGS_KEY);
|
||||
}
|
||||
|
||||
function saveLocalSettings(patch) {
|
||||
@@ -960,7 +958,7 @@ export async function initSettingsTab() {
|
||||
setLang(lang);
|
||||
saveLocalSettings({ ...loadLocalSettings(), uiLang: lang });
|
||||
// Re-render the entire page to apply new language
|
||||
showToast("Language changed. Reloading...", "success");
|
||||
showToast(t("languageChanged"), "success");
|
||||
setTimeout(() => location.reload(), 500);
|
||||
});
|
||||
|
||||
@@ -1176,7 +1174,7 @@ export async function initSettingsTab() {
|
||||
|
||||
// Clear default workflow
|
||||
document.getElementById("wfm-settings-clear-wf")?.addEventListener("click", () => {
|
||||
const s = JSON.parse(localStorage.getItem("wfm_settings") || "{}");
|
||||
const s = getSettings();
|
||||
delete s.defaultWorkflow;
|
||||
delete s.defaultWorkflowData;
|
||||
localStorage.setItem("wfm_settings", JSON.stringify(s));
|
||||
|
||||
@@ -0,0 +1,667 @@
|
||||
/**
|
||||
* Tagger Tab
|
||||
* Handles WD Tagger / DeepDanbooru + Ollama VLM single/batch tagging.
|
||||
*/
|
||||
|
||||
import { t } from "./i18n.js";
|
||||
import { showToast } from "./app.js";
|
||||
|
||||
// ── 状態 ────────────────────────────────────────────────────────
|
||||
|
||||
const state = {
|
||||
/** @type {string|null} 現在の画像 base64 (data URI prefix を除く) */
|
||||
imageB64: null,
|
||||
/** @type {string} 元のファイルパス (Galleryから来た場合) */
|
||||
imagePath: "",
|
||||
/** @type {string} 表示名 */
|
||||
imageName: "",
|
||||
/** @type {NodeJS.Timeout|null} バッチポーリングタイマー */
|
||||
batchPollTimer: null,
|
||||
/** @type {number|null} DB編集中の行ID */
|
||||
dbEditId: null,
|
||||
};
|
||||
|
||||
// ── 初期化 ──────────────────────────────────────────────────────
|
||||
|
||||
export function initTaggerTab() {
|
||||
_applyI18n();
|
||||
_setupSubtabs();
|
||||
_setupSliders();
|
||||
_setupOllamaToggle();
|
||||
_setupSingleActions();
|
||||
_setupBatchActions();
|
||||
_setupDbActions();
|
||||
_loadModels();
|
||||
_loadSettings();
|
||||
}
|
||||
|
||||
/** GalleryタブからTaggerタブへ画像を渡す */
|
||||
export function openImageInTaggerTab(img) {
|
||||
// タブを切り替え
|
||||
document.querySelectorAll(".wfm-tab").forEach(b => b.classList.remove("active"));
|
||||
document.querySelectorAll(".wfm-tab-content").forEach(s => s.classList.remove("active"));
|
||||
const btn = document.querySelector('.wfm-tab[data-tab="tagger"]');
|
||||
const sec = document.getElementById("wfm-tab-tagger");
|
||||
if (btn) btn.classList.add("active");
|
||||
if (sec) sec.classList.add("active");
|
||||
|
||||
// 画像を読み込む (Gallery APIから取得)
|
||||
if (!img?.path) return;
|
||||
const url = `/wfm/gallery/image/serve?path=${encodeURIComponent(img.path)}`;
|
||||
fetch(url)
|
||||
.then(r => {
|
||||
if (!r.ok) throw new Error(`HTTP ${r.status}`);
|
||||
return r.blob();
|
||||
})
|
||||
.then(blob => {
|
||||
const reader = new FileReader();
|
||||
reader.onload = e => {
|
||||
_setPreviewFromDataUrl(e.target.result, img.filename || img.path.split(/[\\/]/).pop());
|
||||
state.imagePath = img.path;
|
||||
};
|
||||
reader.readAsDataURL(blob);
|
||||
})
|
||||
.catch(() => showToast(t("taggerNoImage"), "error"));
|
||||
}
|
||||
|
||||
// ── i18n ─────────────────────────────────────────────────────────
|
||||
|
||||
function _applyI18n() {
|
||||
const map = {
|
||||
"wfm-tagger-from-gallery-btn": "taggerFromGallery",
|
||||
"wfm-tagger-upload-label": "taggerUpload",
|
||||
"wfm-tagger-threshold-label": "taggerThreshold",
|
||||
"wfm-tagger-char-threshold-label": "taggerCharThreshold",
|
||||
"wfm-tagger-generate-btn": "taggerGenerateTags",
|
||||
"wfm-tagger-ollama-header-label": "taggerOllamaEnable",
|
||||
"wfm-tagger-ollama-url-label": "taggerOllamaUrl",
|
||||
"wfm-tagger-ollama-model-label": "taggerOllamaModel",
|
||||
"wfm-tagger-ollama-prompt-label": "taggerOllamaPrompt",
|
||||
"wfm-tagger-ollama-max-label": "taggerOllamaMaxTags",
|
||||
"wfm-tagger-result-header": "taggerResult",
|
||||
"wfm-tagger-send-genui-btn": "taggerSendToGenUI",
|
||||
"wfm-tagger-send-prompt-btn": "taggerSendToPrompt",
|
||||
"wfm-tagger-save-gallery-btn": "taggerSaveToGallery",
|
||||
"wfm-tagger-write-file-btn": "taggerWriteToFile",
|
||||
"wfm-tagger-save-db-btn": "taggerSaveToDB",
|
||||
"wfm-tagger-batch-folder-header": "taggerBatchFolder",
|
||||
"wfm-tagger-batch-threshold-label": "taggerThreshold",
|
||||
"wfm-tagger-batch-char-threshold-label": "taggerCharThreshold",
|
||||
"wfm-tagger-batch-url-label": "taggerOllamaUrl",
|
||||
"wfm-tagger-batch-model-label": "taggerOllamaModel",
|
||||
"wfm-tagger-batch-prompt-label": "taggerOllamaPrompt",
|
||||
"wfm-tagger-batch-output-header": "taggerBatchOutput",
|
||||
"wfm-tagger-batch-save-db-label": "taggerSaveToDB",
|
||||
"wfm-tagger-batch-write-file-label": "taggerWriteToFile",
|
||||
"wfm-tagger-batch-write-txt-label": "taggerBatchWriteTxt",
|
||||
"wfm-tagger-batch-start-btn": "taggerBatchStart",
|
||||
"wfm-tagger-batch-stop-btn": "taggerBatchStop",
|
||||
"wfm-tagger-db-search-btn": "taggerDbSearch",
|
||||
"wfm-tagger-db-show-all-btn": "taggerDbShowAll",
|
||||
"wfm-tagger-db-export-btn": "taggerDbExport",
|
||||
"wfm-tagger-db-th-file": "taggerDbFile",
|
||||
"wfm-tagger-db-th-interrogator": "taggerDbInterrogator",
|
||||
"wfm-tagger-db-th-vlm": "taggerDbVlm",
|
||||
"wfm-tagger-db-th-date": "taggerDbDate",
|
||||
"wfm-tagger-db-edit-interr-label": "taggerDbInterrogator",
|
||||
"wfm-tagger-db-edit-vlm-label": "taggerDbVlm",
|
||||
"wfm-tagger-db-save-btn": "taggerDbSave",
|
||||
"wfm-tagger-db-delete-btn": "taggerDbDelete",
|
||||
};
|
||||
for (const [id, key] of Object.entries(map)) {
|
||||
const el = document.getElementById(id);
|
||||
if (el) el.textContent = t(key);
|
||||
}
|
||||
|
||||
// サブタブボタン
|
||||
const subtabKeys = ["taggerSingleTab", "taggerBatchTab", "taggerDbTab"];
|
||||
document.querySelectorAll(".wfm-tagger-subtab-btn").forEach((btn, i) => {
|
||||
btn.textContent = t(subtabKeys[i] || "");
|
||||
});
|
||||
|
||||
// プレースホルダー
|
||||
const ph = document.getElementById("wfm-tagger-preview-placeholder");
|
||||
if (ph) ph.textContent = t("taggerNoImage");
|
||||
}
|
||||
|
||||
// ── サブタブ切り替え ─────────────────────────────────────────────
|
||||
|
||||
function _setupSubtabs() {
|
||||
document.querySelectorAll(".wfm-tagger-subtab-btn").forEach(btn => {
|
||||
btn.addEventListener("click", () => {
|
||||
document.querySelectorAll(".wfm-tagger-subtab-btn").forEach(b => b.classList.remove("active"));
|
||||
btn.classList.add("active");
|
||||
const tab = btn.dataset.taggerTab;
|
||||
document.querySelectorAll(".wfm-tagger-subtab").forEach(s => {
|
||||
s.style.display = s.id === `wfm-tagger-${tab}` ? "" : "none";
|
||||
});
|
||||
if (tab === "db") _dbLoad();
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
// ── スライダー ───────────────────────────────────────────────────
|
||||
|
||||
function _setupSliders() {
|
||||
[
|
||||
["wfm-tagger-threshold", "wfm-tagger-threshold-val"],
|
||||
["wfm-tagger-char-threshold", "wfm-tagger-char-threshold-val"],
|
||||
["wfm-tagger-batch-threshold", "wfm-tagger-batch-threshold-val"],
|
||||
["wfm-tagger-batch-char-threshold", "wfm-tagger-batch-char-threshold-val"],
|
||||
].forEach(([sliderId, valId]) => {
|
||||
const slider = document.getElementById(sliderId);
|
||||
const val = document.getElementById(valId);
|
||||
if (!slider || !val) return;
|
||||
val.textContent = slider.value;
|
||||
slider.addEventListener("input", () => { val.textContent = slider.value; });
|
||||
});
|
||||
}
|
||||
|
||||
// ── Ollama トグル ────────────────────────────────────────────────
|
||||
|
||||
function _setupOllamaToggle() {
|
||||
const chk = document.getElementById("wfm-tagger-ollama-enable");
|
||||
const wrap = document.getElementById("wfm-tagger-ollama-settings");
|
||||
if (chk && wrap) {
|
||||
chk.addEventListener("change", () => {
|
||||
wrap.style.display = chk.checked ? "" : "none";
|
||||
});
|
||||
wrap.style.display = chk.checked ? "" : "none";
|
||||
}
|
||||
}
|
||||
|
||||
// ── モデル一覧ロード ─────────────────────────────────────────────
|
||||
|
||||
async function _loadModels() {
|
||||
try {
|
||||
const res = await fetch("/wfm/tagger/models");
|
||||
const data = await res.json();
|
||||
const models = data.models || [];
|
||||
["wfm-tagger-model", "wfm-tagger-batch-model"].forEach(selId => {
|
||||
const sel = document.getElementById(selId);
|
||||
if (!sel) return;
|
||||
sel.innerHTML = `<option value="">${t("taggerNoModel")}</option>` +
|
||||
models.map(m => `<option value="${m.name}">[${m.type}] ${m.name}</option>`).join("");
|
||||
});
|
||||
} catch (e) {
|
||||
console.warn("tagger: _loadModels error", e);
|
||||
}
|
||||
}
|
||||
|
||||
// ── Ollamaモデル一覧ロード ───────────────────────────────────────
|
||||
|
||||
async function _loadOllamaModels(urlId, selId) {
|
||||
const urlEl = document.getElementById(urlId);
|
||||
const selEl = document.getElementById(selId);
|
||||
if (!urlEl || !selEl) return;
|
||||
const api = urlEl.value || "http://127.0.0.1:11434";
|
||||
try {
|
||||
const res = await fetch(`/wfm/tagger/ollama/models?api_url=${encodeURIComponent(api)}`);
|
||||
const data = await res.json();
|
||||
const models = data.models || [];
|
||||
if (models.length === 0) {
|
||||
selEl.innerHTML = `<option value="">(${t("taggerNoModel")})</option>`;
|
||||
} else {
|
||||
selEl.innerHTML = models.map(m => `<option value="${m}">${m}</option>`).join("");
|
||||
}
|
||||
} catch {
|
||||
selEl.innerHTML = `<option value="">(${t("taggerNoModel")})</option>`;
|
||||
}
|
||||
}
|
||||
|
||||
// ── 設定の読み込み/保存 ─────────────────────────────────────────
|
||||
|
||||
async function _loadSettings() {
|
||||
try {
|
||||
const res = await fetch("/wfm/tagger/settings");
|
||||
const data = await res.json();
|
||||
if (data.ollama_url) {
|
||||
const el = document.getElementById("wfm-tagger-ollama-url");
|
||||
if (el) el.value = data.ollama_url;
|
||||
}
|
||||
if (data.batch_ollama_url) {
|
||||
const el = document.getElementById("wfm-tagger-batch-ollama-url");
|
||||
if (el) el.value = data.batch_ollama_url;
|
||||
}
|
||||
} catch {
|
||||
// 初回は無視
|
||||
}
|
||||
}
|
||||
|
||||
async function _saveSettings() {
|
||||
try {
|
||||
await fetch("/wfm/tagger/settings", {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify({
|
||||
ollama_url: document.getElementById("wfm-tagger-ollama-url")?.value || "",
|
||||
batch_ollama_url: document.getElementById("wfm-tagger-batch-ollama-url")?.value || "",
|
||||
}),
|
||||
});
|
||||
} catch {
|
||||
// サイレントに失敗
|
||||
}
|
||||
}
|
||||
|
||||
// ── Single サブタブ ─────────────────────────────────────────────
|
||||
|
||||
function _setupSingleActions() {
|
||||
// ファイルアップロード
|
||||
document.getElementById("wfm-tagger-upload")?.addEventListener("change", e => {
|
||||
const file = e.target.files?.[0];
|
||||
if (!file) return;
|
||||
_loadImageFile(file);
|
||||
e.target.value = "";
|
||||
});
|
||||
|
||||
// ドラッグ&ドロップ
|
||||
const dropZone = document.getElementById("wfm-tagger-drop-zone");
|
||||
if (dropZone) {
|
||||
dropZone.addEventListener("dragover", e => {
|
||||
e.preventDefault();
|
||||
dropZone.classList.add("drag-over");
|
||||
});
|
||||
dropZone.addEventListener("dragleave", e => {
|
||||
if (!dropZone.contains(e.relatedTarget)) {
|
||||
dropZone.classList.remove("drag-over");
|
||||
}
|
||||
});
|
||||
dropZone.addEventListener("drop", e => {
|
||||
e.preventDefault();
|
||||
dropZone.classList.remove("drag-over");
|
||||
const file = e.dataTransfer.files?.[0];
|
||||
if (file && file.type.startsWith("image/")) {
|
||||
_loadImageFile(file);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
// タグ生成
|
||||
document.getElementById("wfm-tagger-generate-btn")?.addEventListener("click", _generateTags);
|
||||
|
||||
// Ollamaリフレッシュ
|
||||
document.getElementById("wfm-tagger-ollama-refresh-btn")?.addEventListener("click", () => {
|
||||
_loadOllamaModels("wfm-tagger-ollama-url", "wfm-tagger-ollama-model");
|
||||
});
|
||||
|
||||
// 結果アクション
|
||||
document.getElementById("wfm-tagger-send-genui-btn")?.addEventListener("click", _sendToGenUI);
|
||||
document.getElementById("wfm-tagger-send-prompt-btn")?.addEventListener("click", _sendToPrompt);
|
||||
document.getElementById("wfm-tagger-save-gallery-btn")?.addEventListener("click", _saveToGallery);
|
||||
document.getElementById("wfm-tagger-write-file-btn")?.addEventListener("click", _writeToFile);
|
||||
document.getElementById("wfm-tagger-save-db-btn")?.addEventListener("click", _saveToDb);
|
||||
}
|
||||
|
||||
function _loadImageFile(file) {
|
||||
const reader = new FileReader();
|
||||
reader.onload = e => {
|
||||
_setPreviewFromDataUrl(e.target.result, file.name);
|
||||
state.imagePath = "";
|
||||
};
|
||||
reader.readAsDataURL(file);
|
||||
}
|
||||
|
||||
function _setPreviewFromDataUrl(dataUrl, name) {
|
||||
state.imageB64 = dataUrl.replace(/^data:[^;]+;base64,/, "");
|
||||
state.imageName = name;
|
||||
const img = document.getElementById("wfm-tagger-preview");
|
||||
const ph = document.getElementById("wfm-tagger-preview-placeholder");
|
||||
const nameEl = document.getElementById("wfm-tagger-image-name");
|
||||
if (img) { img.src = dataUrl; img.style.display = ""; }
|
||||
if (ph) ph.style.display = "none";
|
||||
if (nameEl) nameEl.textContent = name;
|
||||
}
|
||||
|
||||
async function _generateTags() {
|
||||
if (!state.imageB64) {
|
||||
showToast(t("taggerNoImage"), "warning");
|
||||
return;
|
||||
}
|
||||
const model = document.getElementById("wfm-tagger-model")?.value || "";
|
||||
const threshold = parseFloat(document.getElementById("wfm-tagger-threshold")?.value || "0.35");
|
||||
const charThreshold = parseFloat(document.getElementById("wfm-tagger-char-threshold")?.value || "0.85");
|
||||
const useOllama = document.getElementById("wfm-tagger-ollama-enable")?.checked || false;
|
||||
const ollamaUrl = document.getElementById("wfm-tagger-ollama-url")?.value || "http://127.0.0.1:11434";
|
||||
const ollamaModel = document.getElementById("wfm-tagger-ollama-model")?.value || "";
|
||||
const ollamaPrompt = document.getElementById("wfm-tagger-ollama-prompt")?.value || "";
|
||||
const maxTags = parseInt(document.getElementById("wfm-tagger-ollama-max-tags")?.value || "40");
|
||||
|
||||
const generateBtn = document.getElementById("wfm-tagger-generate-btn");
|
||||
if (generateBtn) { generateBtn.disabled = true; generateBtn.textContent = "..."; }
|
||||
|
||||
try {
|
||||
let tags = "";
|
||||
|
||||
if (model) {
|
||||
const res = await fetch("/wfm/tagger/predict", {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify({ image_b64: state.imageB64, model, threshold, char_threshold: charThreshold }),
|
||||
});
|
||||
const data = await res.json();
|
||||
if (data.error) throw new Error(data.error);
|
||||
tags = data.tags || "";
|
||||
}
|
||||
|
||||
if (useOllama && ollamaModel) {
|
||||
const res2 = await fetch("/wfm/tagger/ollama/predict", {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify({
|
||||
image_b64: state.imageB64, api_url: ollamaUrl,
|
||||
model: ollamaModel, prompt: ollamaPrompt, max_tags: maxTags,
|
||||
}),
|
||||
});
|
||||
const data2 = await res2.json();
|
||||
if (data2.error) throw new Error(data2.error);
|
||||
const vlm = data2.tags || "";
|
||||
tags = [tags, vlm].filter(Boolean).join(", ");
|
||||
}
|
||||
|
||||
if (!tags) { showToast(t("taggerNoTags"), "warning"); return; }
|
||||
document.getElementById("wfm-tagger-result").value = tags;
|
||||
showToast(t("taggerDone"), "success");
|
||||
_saveSettings();
|
||||
} catch (e) {
|
||||
showToast(e.message, "error");
|
||||
} finally {
|
||||
if (generateBtn) { generateBtn.disabled = false; generateBtn.textContent = t("taggerGenerateTags"); }
|
||||
}
|
||||
}
|
||||
|
||||
function _sendToGenUI() {
|
||||
const tags = document.getElementById("wfm-tagger-result")?.value || "";
|
||||
if (!tags) { showToast(t("taggerNoTags"), "warning"); return; }
|
||||
const ta = document.getElementById("wfm-prompt-pos-text");
|
||||
if (!ta) { showToast(t("taggerNoGenUI"), "warning"); return; }
|
||||
const cur = ta.value;
|
||||
ta.value = cur ? `${cur}, ${tags}` : tags;
|
||||
ta.dispatchEvent(new Event("input", { bubbles: true }));
|
||||
document.getElementById("wfm-prompt-pos-apply")?.click();
|
||||
showToast(t("taggerSentToGenUI"), "success");
|
||||
}
|
||||
|
||||
function _sendToPrompt() {
|
||||
const tags = document.getElementById("wfm-tagger-result")?.value || "";
|
||||
if (!tags) { showToast(t("taggerNoTags"), "warning"); return; }
|
||||
const ta = document.getElementById("wfm-preset-pos");
|
||||
if (!ta) { showToast(t("taggerNoGalleryImage"), "warning"); return; }
|
||||
const cur = ta.value;
|
||||
ta.value = cur ? `${cur}, ${tags}` : tags;
|
||||
ta.dispatchEvent(new Event("input", { bubbles: true }));
|
||||
showToast(t("taggerSentToPrompt"), "success");
|
||||
}
|
||||
|
||||
async function _saveToGallery() {
|
||||
const tags = document.getElementById("wfm-tagger-result")?.value || "";
|
||||
if (!tags || !state.imagePath) {
|
||||
showToast(t("taggerNoGalleryImage"), "warning");
|
||||
return;
|
||||
}
|
||||
try {
|
||||
const tagsArray = tags.split(",").map(s => s.trim()).filter(Boolean);
|
||||
const res = await fetch("/wfm/gallery/image/meta", {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify({ path: state.imagePath, tags: tagsArray }),
|
||||
});
|
||||
const data = await res.json();
|
||||
if (data.error) throw new Error(data.error);
|
||||
showToast(t("taggerSavedToGallery"), "success");
|
||||
} catch (e) {
|
||||
showToast(e.message, "error");
|
||||
}
|
||||
}
|
||||
|
||||
async function _writeToFile() {
|
||||
const tags = document.getElementById("wfm-tagger-result")?.value || "";
|
||||
if (!tags || !state.imagePath) {
|
||||
showToast(t("taggerNoGalleryImage"), "warning");
|
||||
return;
|
||||
}
|
||||
try {
|
||||
const res = await fetch("/wfm/tagger/write_meta", {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify({ path: state.imagePath, tags }),
|
||||
});
|
||||
const data = await res.json();
|
||||
if (data.error) throw new Error(data.error);
|
||||
showToast(t("taggerWrittenToFile"), "success");
|
||||
} catch (e) {
|
||||
showToast(e.message, "error");
|
||||
}
|
||||
}
|
||||
|
||||
async function _saveToDb() {
|
||||
const tags = document.getElementById("wfm-tagger-result")?.value || "";
|
||||
if (!tags) { showToast(t("taggerNoTags"), "warning"); return; }
|
||||
try {
|
||||
const res = await fetch("/wfm/tagger/db/save", {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify({ filename: state.imageName, interrogator_tags: tags, vlm_tags: "" }),
|
||||
});
|
||||
const data = await res.json();
|
||||
if (data.error) throw new Error(data.error);
|
||||
showToast(t("taggerSavedToDB"), "success");
|
||||
} catch (e) {
|
||||
showToast(e.message, "error");
|
||||
}
|
||||
}
|
||||
|
||||
// ── Batch サブタブ ───────────────────────────────────────────────
|
||||
|
||||
function _setupBatchActions() {
|
||||
document.getElementById("wfm-tagger-batch-ollama-refresh-btn")?.addEventListener("click", () => {
|
||||
_loadOllamaModels("wfm-tagger-batch-ollama-url", "wfm-tagger-batch-ollama-model");
|
||||
});
|
||||
|
||||
document.getElementById("wfm-tagger-batch-start-btn")?.addEventListener("click", _batchStart);
|
||||
document.getElementById("wfm-tagger-batch-stop-btn")?.addEventListener("click", _batchStop);
|
||||
}
|
||||
|
||||
async function _batchStart() {
|
||||
const folder = document.getElementById("wfm-tagger-batch-folder")?.value || "";
|
||||
if (!folder) { showToast(t("taggerBatchFolder"), "warning"); return; }
|
||||
|
||||
const body = {
|
||||
folder,
|
||||
model: document.getElementById("wfm-tagger-batch-model")?.value || "",
|
||||
threshold: parseFloat(document.getElementById("wfm-tagger-batch-threshold")?.value || "0.35"),
|
||||
char_threshold: parseFloat(document.getElementById("wfm-tagger-batch-char-threshold")?.value || "0.85"),
|
||||
use_ollama: document.getElementById("wfm-tagger-batch-ollama-enable")?.checked || false,
|
||||
ollama_api: document.getElementById("wfm-tagger-batch-ollama-url")?.value || "http://127.0.0.1:11434",
|
||||
ollama_model: document.getElementById("wfm-tagger-batch-ollama-model")?.value || "",
|
||||
ollama_prompt: document.getElementById("wfm-tagger-batch-ollama-prompt")?.value || "",
|
||||
save_db: document.getElementById("wfm-tagger-batch-save-db")?.checked ?? true,
|
||||
write_file: document.getElementById("wfm-tagger-batch-write-file")?.checked || false,
|
||||
write_txt: document.getElementById("wfm-tagger-batch-write-txt")?.checked || false,
|
||||
};
|
||||
|
||||
try {
|
||||
const res = await fetch("/wfm/tagger/batch/start", {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify(body),
|
||||
});
|
||||
const data = await res.json();
|
||||
if (data.error) throw new Error(data.error);
|
||||
|
||||
document.getElementById("wfm-tagger-batch-start-btn").disabled = true;
|
||||
document.getElementById("wfm-tagger-batch-stop-btn").disabled = false;
|
||||
document.getElementById("wfm-tagger-batch-log").value = "";
|
||||
_startBatchPoll();
|
||||
} catch (e) {
|
||||
showToast(e.message, "error");
|
||||
}
|
||||
}
|
||||
|
||||
async function _batchStop() {
|
||||
await fetch("/wfm/tagger/batch/stop", { method: "POST" });
|
||||
}
|
||||
|
||||
function _startBatchPoll() {
|
||||
if (state.batchPollTimer) clearInterval(state.batchPollTimer);
|
||||
state.batchPollTimer = setInterval(_pollBatch, 1000);
|
||||
}
|
||||
|
||||
async function _pollBatch() {
|
||||
try {
|
||||
const res = await fetch("/wfm/tagger/batch/status");
|
||||
const data = await res.json();
|
||||
|
||||
const total = data.total || 0;
|
||||
const done = data.done || 0;
|
||||
const pct = total > 0 ? Math.round((done / total) * 100) : 0;
|
||||
|
||||
const bar = document.getElementById("wfm-tagger-batch-progress-bar");
|
||||
const txt = document.getElementById("wfm-tagger-batch-progress-text");
|
||||
if (bar) bar.style.width = pct + "%";
|
||||
if (txt) txt.textContent = `${done} / ${total} (${pct}%)`;
|
||||
|
||||
const logEl = document.getElementById("wfm-tagger-batch-log");
|
||||
if (logEl && data.log?.length) {
|
||||
logEl.value = data.log.join("\n");
|
||||
logEl.scrollTop = logEl.scrollHeight;
|
||||
}
|
||||
|
||||
if (!data.running) {
|
||||
clearInterval(state.batchPollTimer);
|
||||
state.batchPollTimer = null;
|
||||
document.getElementById("wfm-tagger-batch-start-btn").disabled = false;
|
||||
document.getElementById("wfm-tagger-batch-stop-btn").disabled = true;
|
||||
showToast(t("taggerDone"), "success");
|
||||
}
|
||||
} catch {
|
||||
// 無視
|
||||
}
|
||||
}
|
||||
|
||||
// ── DB サブタブ ──────────────────────────────────────────────────
|
||||
|
||||
function _setupDbActions() {
|
||||
document.getElementById("wfm-tagger-db-search-btn")?.addEventListener("click", _dbSearch);
|
||||
document.getElementById("wfm-tagger-db-show-all-btn")?.addEventListener("click", _dbLoad);
|
||||
document.getElementById("wfm-tagger-db-export-btn")?.addEventListener("click", _dbExport);
|
||||
document.getElementById("wfm-tagger-db-search-input")?.addEventListener("keydown", e => {
|
||||
if (e.key === "Enter") _dbSearch();
|
||||
});
|
||||
document.getElementById("wfm-tagger-db-save-btn")?.addEventListener("click", _dbSave);
|
||||
document.getElementById("wfm-tagger-db-delete-btn")?.addEventListener("click", _dbDelete);
|
||||
}
|
||||
|
||||
async function _dbLoad() {
|
||||
try {
|
||||
const res = await fetch("/wfm/tagger/db/list?limit=200&offset=0");
|
||||
const data = await res.json();
|
||||
_renderDbTable(data.rows || []);
|
||||
} catch (e) {
|
||||
showToast(e.message, "error");
|
||||
}
|
||||
}
|
||||
|
||||
async function _dbSearch() {
|
||||
const q = document.getElementById("wfm-tagger-db-search-input")?.value || "";
|
||||
if (!q) { _dbLoad(); return; }
|
||||
try {
|
||||
const res = await fetch(`/wfm/tagger/db/search?q=${encodeURIComponent(q)}`);
|
||||
const data = await res.json();
|
||||
_renderDbTable(data.rows || []);
|
||||
} catch (e) {
|
||||
showToast(e.message, "error");
|
||||
}
|
||||
}
|
||||
|
||||
function _renderDbTable(rows) {
|
||||
const tbody = document.getElementById("wfm-tagger-db-tbody");
|
||||
if (!tbody) return;
|
||||
if (!rows.length) {
|
||||
tbody.innerHTML = `<tr><td colspan="5" style="text-align:center;padding:20px;color:var(--wfm-text-secondary)">${t("taggerDbEmpty")}</td></tr>`;
|
||||
return;
|
||||
}
|
||||
tbody.innerHTML = rows.map(row => `
|
||||
<tr data-id="${row.id}" title="${_esc(row.all_tags)}">
|
||||
<td>${row.id}</td>
|
||||
<td>${_esc(row.filename)}</td>
|
||||
<td>${_esc(_truncate(row.interrogator_tags, 60))}</td>
|
||||
<td>${_esc(_truncate(row.vlm_tags, 60))}</td>
|
||||
<td>${_esc(row.created_at?.split("T")[0] || row.created_at || "")}</td>
|
||||
</tr>
|
||||
`).join("");
|
||||
|
||||
tbody.querySelectorAll("tr").forEach(tr => {
|
||||
tr.addEventListener("click", () => {
|
||||
tbody.querySelectorAll("tr").forEach(r => r.classList.remove("selected"));
|
||||
tr.classList.add("selected");
|
||||
const row = rows.find(r => r.id === parseInt(tr.dataset.id));
|
||||
if (row) _openDbEdit(row);
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
function _openDbEdit(row) {
|
||||
state.dbEditId = row.id;
|
||||
const panel = document.getElementById("wfm-tagger-db-edit-panel");
|
||||
const header = document.getElementById("wfm-tagger-db-edit-header");
|
||||
const interrEl = document.getElementById("wfm-tagger-db-edit-interrogator");
|
||||
const vlmEl = document.getElementById("wfm-tagger-db-edit-vlm");
|
||||
if (!panel) return;
|
||||
if (header) header.textContent = `ID: ${row.id} ${row.filename}`;
|
||||
if (interrEl) interrEl.value = row.interrogator_tags;
|
||||
if (vlmEl) vlmEl.value = row.vlm_tags;
|
||||
panel.style.display = "";
|
||||
}
|
||||
|
||||
async function _dbSave() {
|
||||
if (state.dbEditId == null) return;
|
||||
const interrogator_tags = document.getElementById("wfm-tagger-db-edit-interrogator")?.value || "";
|
||||
const vlm_tags = document.getElementById("wfm-tagger-db-edit-vlm")?.value || "";
|
||||
try {
|
||||
const res = await fetch(`/wfm/tagger/db/${state.dbEditId}`, {
|
||||
method: "PUT",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify({ interrogator_tags, vlm_tags }),
|
||||
});
|
||||
const data = await res.json();
|
||||
if (data.error) throw new Error(data.error);
|
||||
showToast(t("taggerDbSaved"), "success");
|
||||
_dbLoad();
|
||||
} catch (e) {
|
||||
showToast(e.message, "error");
|
||||
}
|
||||
}
|
||||
|
||||
async function _dbDelete() {
|
||||
if (state.dbEditId == null) return;
|
||||
if (!confirm(`Delete DB record #${state.dbEditId}?`)) return;
|
||||
try {
|
||||
const res = await fetch(`/wfm/tagger/db/${state.dbEditId}`, { method: "DELETE" });
|
||||
const data = await res.json();
|
||||
if (data.error) throw new Error(data.error);
|
||||
document.getElementById("wfm-tagger-db-edit-panel").style.display = "none";
|
||||
state.dbEditId = null;
|
||||
showToast(t("taggerDbDeleted"), "success");
|
||||
_dbLoad();
|
||||
} catch (e) {
|
||||
showToast(e.message, "error");
|
||||
}
|
||||
}
|
||||
|
||||
function _dbExport() {
|
||||
const a = document.createElement("a");
|
||||
a.href = "/wfm/tagger/db/export";
|
||||
a.download = "tagger_tags.csv";
|
||||
a.click();
|
||||
}
|
||||
|
||||
// ── ユーティリティ ───────────────────────────────────────────────
|
||||
|
||||
function _esc(str) {
|
||||
return String(str || "").replace(/&/g, "&").replace(/</g, "<").replace(/>/g, ">").replace(/"/g, """);
|
||||
}
|
||||
|
||||
function _truncate(str, len) {
|
||||
if (!str) return "";
|
||||
return str.length > len ? str.slice(0, len) + "…" : str;
|
||||
}
|
||||
@@ -0,0 +1,28 @@
|
||||
/**
|
||||
* Shared utilities
|
||||
*/
|
||||
|
||||
// HTMLエスケープ(属性値・テキストコンテンツ両方で安全に使える)
|
||||
export function escapeHtml(s) {
|
||||
return String(s)
|
||||
.replace(/&/g, "&")
|
||||
.replace(/</g, "<")
|
||||
.replace(/>/g, ">")
|
||||
.replace(/"/g, """)
|
||||
.replace(/'/g, "'");
|
||||
}
|
||||
|
||||
// localStorage からJSONを安全に読む(不正JSON・未設定時はfallback)
|
||||
export function readJsonStorage(key, fallback = {}) {
|
||||
try {
|
||||
const raw = localStorage.getItem(key);
|
||||
return raw ? JSON.parse(raw) : fallback;
|
||||
} catch {
|
||||
return fallback;
|
||||
}
|
||||
}
|
||||
|
||||
// プラグイン共通設定 (wfm_settings)
|
||||
export function getSettings() {
|
||||
return readJsonStorage("wfm_settings");
|
||||
}
|
||||
+46
-30
@@ -10,6 +10,7 @@ import { loadWorkflowIntoEditor } from "./generate-tab.js";
|
||||
import { t, getSummaryPrompt } from "./i18n.js";
|
||||
import { highlightJSON } from "./json-highlight.js";
|
||||
import { openBadgeEditModal } from "./models-tab.js";
|
||||
import { escapeHtml, getSettings, readJsonStorage } from "./util.js";
|
||||
|
||||
// ============================================
|
||||
// Constants
|
||||
@@ -33,26 +34,39 @@ const state = {
|
||||
|
||||
|
||||
function getBadgePalette() {
|
||||
try { return JSON.parse(localStorage.getItem("wfm_models_badge_palette") || "{}"); }
|
||||
catch { return {}; }
|
||||
return readJsonStorage("wfm_models_badge_palette");
|
||||
}
|
||||
|
||||
function saveBadgePalette(palette) {
|
||||
localStorage.setItem("wfm_models_badge_palette", JSON.stringify(palette));
|
||||
}
|
||||
|
||||
function escapeHtml(s) {
|
||||
return String(s)
|
||||
.replace(/&/g, "&")
|
||||
.replace(/</g, "<")
|
||||
.replace(/>/g, ">")
|
||||
.replace(/"/g, """);
|
||||
}
|
||||
|
||||
// ============================================
|
||||
// Open in ComfyUI
|
||||
// Open in ComfyUI / Send to Canvas
|
||||
// ============================================
|
||||
|
||||
function sendToCanvas(workflowData) {
|
||||
try {
|
||||
// window.opener経由でComfyUIキャンバスに直接ロード(推奨)
|
||||
if (window.opener && typeof window.opener.wfmReceiveWorkflow === "function") {
|
||||
window.opener.wfmReceiveWorkflow(workflowData);
|
||||
showToast(t("workflowSentToCanvas"), "success");
|
||||
return;
|
||||
}
|
||||
// フォールバック: localStorage + タイトルドラッグ(UI形式のみ)
|
||||
const fmt = comfyWorkflow.detectFormat(workflowData);
|
||||
if (fmt === "api") {
|
||||
showToast(t("apiFormatCanvasNoOpener"), "error");
|
||||
return;
|
||||
}
|
||||
localStorage.setItem("wfm_pending_workflow", JSON.stringify(workflowData));
|
||||
showToast(t("workflowSentToCanvas"), "success");
|
||||
} catch (err) {
|
||||
showToast(t("errorWithMsg", err.message), "error");
|
||||
}
|
||||
}
|
||||
|
||||
function openInComfyUI(workflowData) {
|
||||
// Open ComfyUI frontend in a new tab and load the workflow.
|
||||
// Same-origin, so we can access the child window's app object.
|
||||
@@ -94,7 +108,7 @@ const groups = {
|
||||
|
||||
load() {
|
||||
try {
|
||||
this._data = JSON.parse(localStorage.getItem("wfm_groups") || "{}");
|
||||
this._data = readJsonStorage("wfm_groups");
|
||||
} catch {
|
||||
this._data = {};
|
||||
}
|
||||
@@ -501,7 +515,7 @@ async function toggleFavorite(wf, btnEl) {
|
||||
btnEl.textContent = newVal ? "\u2605" : "\u2606";
|
||||
btnEl.classList.toggle("active", newVal);
|
||||
} catch (err) {
|
||||
showToast("Error: " + err.message, "error");
|
||||
showToast(t("errorWithMsg", err.message), "error");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -677,7 +691,7 @@ function renderSideGroup(wf) {
|
||||
groups.remove(filename, btn.dataset.group);
|
||||
renderSideGroup(wf);
|
||||
_refreshGroupFilter();
|
||||
showToast(`Removed from "${btn.dataset.group}"`, "success");
|
||||
showToast(t("removedFromGroupName", btn.dataset.group), "success");
|
||||
});
|
||||
});
|
||||
|
||||
@@ -687,7 +701,7 @@ function renderSideGroup(wf) {
|
||||
if (!g) return;
|
||||
groups.assign(filename, g);
|
||||
renderSideGroup(wf);
|
||||
showToast(`Added to "${g}"`, "success");
|
||||
showToast(t("addedToGroupName", g), "success");
|
||||
});
|
||||
|
||||
// グループ作成(作成後に現在のWFに追加)
|
||||
@@ -696,14 +710,14 @@ function renderSideGroup(wf) {
|
||||
const name = input?.value.trim();
|
||||
if (!name) return;
|
||||
if (!groups.createGroup(name)) {
|
||||
showToast(`"${name}" already exists`, "warning");
|
||||
showToast(t("nameAlreadyExists", name), "warning");
|
||||
return;
|
||||
}
|
||||
groups.assign(filename, name);
|
||||
input.value = "";
|
||||
renderSideGroup(wf);
|
||||
_refreshGroupFilter();
|
||||
showToast(`Group "${name}" created`, "success");
|
||||
showToast(t("groupCreated", name), "success");
|
||||
});
|
||||
|
||||
// グループ名変更
|
||||
@@ -717,13 +731,13 @@ function renderSideGroup(wf) {
|
||||
const newName = prompt(`Rename group "${oldName}" to:`, oldName);
|
||||
if (!newName || newName === oldName) return;
|
||||
if (!groups.renameGroup(oldName, newName)) {
|
||||
showToast("Rename failed", "error");
|
||||
showToast(t("renameFailed"), "error");
|
||||
return;
|
||||
}
|
||||
if (state.groupFilter === oldName) state.groupFilter = newName;
|
||||
renderSideGroup(wf);
|
||||
_refreshGroupFilter();
|
||||
showToast(`Renamed to "${newName}"`, "success");
|
||||
showToast(t("renamedTo", newName), "success");
|
||||
});
|
||||
|
||||
// グループ削除
|
||||
@@ -743,7 +757,7 @@ function renderSideGroup(wf) {
|
||||
}
|
||||
renderSideGroup(wf);
|
||||
_refreshGroupFilter();
|
||||
showToast(`Group "${name}" deleted`, "success");
|
||||
showToast(t("groupDeleted", name), "success");
|
||||
});
|
||||
|
||||
_refreshGroupFilter();
|
||||
@@ -865,7 +879,7 @@ function openDetailModal(wf) {
|
||||
</section>
|
||||
<div class="wfm-modal-actions">
|
||||
<button class="wfm-btn wfm-btn-primary" id="wfm-detail-load">${t("loadInGenerate")}</button>
|
||||
<button class="wfm-btn wfm-btn-sm" id="wfm-detail-open-comfyui">${t("openInComfyUI")}</button>
|
||||
<button class="wfm-btn wfm-btn-sm" id="wfm-detail-open-comfyui">${t("sendToCanvas")}</button>
|
||||
<button class="wfm-btn wfm-btn-sm" id="wfm-detail-set-default">${t("setAsDefault")}</button>
|
||||
<button class="wfm-btn wfm-btn-sm" id="wfm-detail-change-thumb">${t("changeThumbnail")}</button>
|
||||
<input type="file" id="wfm-detail-thumb-file" accept="image/png,image/webp,image/jpeg" style="display:none">
|
||||
@@ -903,7 +917,7 @@ function openDetailModal(wf) {
|
||||
favBtn.classList.toggle("active", newVal);
|
||||
renderGrid();
|
||||
} catch (err) {
|
||||
showToast("Error: " + err.message, "error");
|
||||
showToast(t("errorWithMsg", err.message), "error");
|
||||
}
|
||||
});
|
||||
titleEl.parentNode.insertBefore(favBtn, titleEl);
|
||||
@@ -946,6 +960,8 @@ function openDetailModal(wf) {
|
||||
showToast(t("renameError") + ": " + err.message, "error");
|
||||
}
|
||||
};
|
||||
if (titleInput._commitRename) titleInput.removeEventListener("blur", titleInput._commitRename);
|
||||
titleInput._commitRename = commitRename;
|
||||
titleInput.addEventListener("blur", commitRename);
|
||||
titleInput.addEventListener("keydown", (e) => {
|
||||
if (e.key === "Enter") { e.preventDefault(); titleInput.blur(); }
|
||||
@@ -1013,11 +1029,11 @@ function openDetailModal(wf) {
|
||||
}
|
||||
});
|
||||
|
||||
// Open in ComfyUI
|
||||
// Send to Canvas
|
||||
document.getElementById("wfm-detail-open-comfyui")?.addEventListener("click", async () => {
|
||||
try {
|
||||
const wfData = await getRawWorkflow(wf.filename);
|
||||
openInComfyUI(wfData);
|
||||
sendToCanvas(wfData);
|
||||
} catch (err) {
|
||||
showToast(t("loadError") + ": " + err.message, "error");
|
||||
}
|
||||
@@ -1034,7 +1050,7 @@ function openDetailModal(wf) {
|
||||
apiData = await comfyWorkflow.convertUiToApi(wfData);
|
||||
}
|
||||
// Save to localStorage
|
||||
const settings = JSON.parse(localStorage.getItem("wfm_settings") || "{}");
|
||||
const settings = getSettings();
|
||||
settings.defaultWorkflow = wf.filename;
|
||||
settings.defaultWorkflowData = apiData;
|
||||
localStorage.setItem("wfm_settings", JSON.stringify(settings));
|
||||
@@ -1184,7 +1200,7 @@ export function initWorkflowTab() {
|
||||
showToast(msg, ng.length ? "error" : "success");
|
||||
await loadWorkflows();
|
||||
} catch (err) {
|
||||
showToast("Import error: " + err.message, "error");
|
||||
showToast(t("importErrorMsg", err.message), "error");
|
||||
}
|
||||
e.target.value = "";
|
||||
});
|
||||
@@ -1227,10 +1243,10 @@ export function initWorkflowTab() {
|
||||
const data = await importFiles(files);
|
||||
const ok =
|
||||
data.results?.filter((r) => r.status === "success").length ?? 0;
|
||||
showToast(`${ok} file(s) imported via drag & drop`, "success");
|
||||
showToast(t("importedViaDrop", ok), "success");
|
||||
await loadWorkflows();
|
||||
} catch (err) {
|
||||
showToast("Import error: " + err.message, "error");
|
||||
showToast(t("importErrorMsg", err.message), "error");
|
||||
}
|
||||
});
|
||||
}
|
||||
@@ -1290,12 +1306,12 @@ export function initWorkflowTab() {
|
||||
}
|
||||
});
|
||||
|
||||
// Toolbar: Open in ComfyUI button
|
||||
// Toolbar: Send to Canvas button
|
||||
document.getElementById("wfm-list-open-comfyui-btn")?.addEventListener("click", async () => {
|
||||
if (!state.selectedWf) return;
|
||||
try {
|
||||
const wfData = await getRawWorkflow(state.selectedWf.filename);
|
||||
openInComfyUI(wfData);
|
||||
sendToCanvas(wfData);
|
||||
} catch (err) {
|
||||
showToast(t("loadError") + ": " + err.message, "error");
|
||||
}
|
||||
@@ -1304,7 +1320,7 @@ export function initWorkflowTab() {
|
||||
// Toolbar: Refresh button
|
||||
document.getElementById("wfm-refresh-btn")?.addEventListener("click", async () => {
|
||||
await loadWorkflows();
|
||||
showToast("Refreshed", "success");
|
||||
showToast(t("refreshed"), "success");
|
||||
});
|
||||
|
||||
// Toolbar: ⚙ settings button (view settings panel)
|
||||
|
||||
+728
-264
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,178 @@
|
||||
/**
|
||||
* WFS_GalleryFeeder – ComfyUI canvas extension
|
||||
* Adds "After Gen", Run, and Stop controls directly on the node widget area.
|
||||
*/
|
||||
import { app } from "../../scripts/app.js";
|
||||
|
||||
const FEEDER_GROUP = "__Feeder__";
|
||||
|
||||
// Per-node runtime state (keyed by node.id)
|
||||
const _ns = new Map();
|
||||
|
||||
// ── Helpers ───────────────────────────────────────────────────────────
|
||||
|
||||
async function fetchGroupImages(groupName) {
|
||||
try {
|
||||
const res = await fetch(`/wfm/gallery/groups/${encodeURIComponent(groupName)}/images`);
|
||||
if (!res.ok) return [];
|
||||
return (await res.json()).images || [];
|
||||
} catch { return []; }
|
||||
}
|
||||
|
||||
function getOrCreate(nodeId) {
|
||||
if (!_ns.has(nodeId)) {
|
||||
_ns.set(nodeId, { running: false, stopFlag: false, idx: 0, images: [] });
|
||||
}
|
||||
return _ns.get(nodeId);
|
||||
}
|
||||
|
||||
function getInputWidget(node, name) {
|
||||
return node.widgets?.find(w => w.name === name);
|
||||
}
|
||||
|
||||
function setWidgetValue(node, name, value) {
|
||||
const w = getInputWidget(node, name);
|
||||
if (!w) return;
|
||||
w.value = value;
|
||||
if (w.callback) w.callback(value);
|
||||
app.canvas?.setDirty(true, true);
|
||||
}
|
||||
|
||||
/** Resolves when the current prompt finishes (executing=null, interrupted), rejects on error. */
|
||||
function waitForExecution() {
|
||||
return new Promise((resolve, reject) => {
|
||||
const cleanup = () => {
|
||||
app.api.removeEventListener("executing", onExecuting);
|
||||
app.api.removeEventListener("execution_error", onError);
|
||||
app.api.removeEventListener("execution_interrupted", onInterrupted);
|
||||
};
|
||||
const onExecuting = ({ detail }) => { if (detail === null) { cleanup(); resolve(); } };
|
||||
const onError = ({ detail }) => { cleanup(); reject(new Error(detail?.exception_message || "Execution error")); };
|
||||
const onInterrupted = () => { cleanup(); resolve(); }; // treat interrupt as "done"
|
||||
|
||||
app.api.addEventListener("executing", onExecuting);
|
||||
app.api.addEventListener("execution_error", onError);
|
||||
app.api.addEventListener("execution_interrupted", onInterrupted);
|
||||
});
|
||||
}
|
||||
|
||||
function updateRunBtn(node) {
|
||||
const st = getOrCreate(node.id);
|
||||
if (node._wfsRunWidget) node._wfsRunWidget.name = st.running ? "⏳ Running..." : "▶ Run";
|
||||
app.canvas?.setDirty(true, true);
|
||||
}
|
||||
|
||||
function wfsToast(msg, severity = "warn") {
|
||||
try {
|
||||
const tm = app.extensionManager?.toast;
|
||||
if (tm?.add) { tm.add({ severity, summary: "Gallery Feeder", detail: msg, life: 4000 }); return; }
|
||||
} catch {}
|
||||
console[severity === "error" ? "error" : "warn"]("[WFS_GalleryFeeder]", msg);
|
||||
}
|
||||
|
||||
// ── Run / Stop ────────────────────────────────────────────────────────
|
||||
|
||||
async function startLoop(node) {
|
||||
const st = getOrCreate(node.id);
|
||||
if (st.running) return;
|
||||
|
||||
// Re-fetch images for the current group each Run
|
||||
const groupName = getInputWidget(node, "group_name")?.value || FEEDER_GROUP;
|
||||
const images = await fetchGroupImages(groupName);
|
||||
if (images.length === 0) {
|
||||
wfsToast(`No images in group "${groupName}"`, "warn");
|
||||
return;
|
||||
}
|
||||
|
||||
st.running = true;
|
||||
st.stopFlag = false;
|
||||
st.images = images;
|
||||
st.idx = Math.max(0, Math.min(
|
||||
parseInt(getInputWidget(node, "index")?.value) || 0,
|
||||
images.length - 1
|
||||
));
|
||||
|
||||
updateRunBtn(node);
|
||||
|
||||
// Queue first generation with current index
|
||||
setWidgetValue(node, "index", st.idx);
|
||||
app.queuePrompt(0, 1);
|
||||
|
||||
while (st.running && !st.stopFlag) {
|
||||
try {
|
||||
await waitForExecution();
|
||||
} catch (err) {
|
||||
if (st.running) wfsToast(err.message, "error");
|
||||
break;
|
||||
}
|
||||
|
||||
if (!st.running || st.stopFlag) break;
|
||||
|
||||
const afterGen = node._wfsAfterGenWidget?.value || "loop";
|
||||
const total = st.images.length;
|
||||
|
||||
// Increment mode: stop after the last image
|
||||
if (afterGen === "increment" && st.idx >= total - 1) break;
|
||||
|
||||
if (afterGen !== "fixed") {
|
||||
st.idx = (st.idx + 1) % total;
|
||||
setWidgetValue(node, "index", st.idx);
|
||||
}
|
||||
|
||||
app.queuePrompt(0, 1);
|
||||
}
|
||||
|
||||
st.running = false;
|
||||
updateRunBtn(node);
|
||||
}
|
||||
|
||||
function stopLoop(node) {
|
||||
const st = getOrCreate(node.id);
|
||||
if (!st.running) return;
|
||||
st.stopFlag = true;
|
||||
st.running = false;
|
||||
try { app.api.interrupt(); } catch {}
|
||||
updateRunBtn(node);
|
||||
}
|
||||
|
||||
// ── Extension registration ────────────────────────────────────────────
|
||||
|
||||
app.registerExtension({
|
||||
name: "WorkflowStudio.GalleryFeeder",
|
||||
|
||||
async beforeRegisterNodeDef(nodeType, nodeData) {
|
||||
if (nodeData.name !== "WFS_GalleryFeeder") return;
|
||||
|
||||
const origCreated = nodeType.prototype.onNodeCreated;
|
||||
nodeType.prototype.onNodeCreated = function () {
|
||||
origCreated?.call(this);
|
||||
const node = this;
|
||||
|
||||
// ── After Gen selector ────────────────────────────────────
|
||||
// serialize:false → not included in widgets_values / prompt inputs
|
||||
const afterGenW = node.addWidget("combo", "wfs_after_gen", "loop", () => {}, {
|
||||
values: ["loop", "increment", "fixed"],
|
||||
serialize: false,
|
||||
});
|
||||
node._wfsAfterGenWidget = afterGenW;
|
||||
|
||||
// ── Run button ────────────────────────────────────────────
|
||||
const runW = node.addWidget("button", "▶ Run", null, () => startLoop(node));
|
||||
runW.serialize = false;
|
||||
node._wfsRunWidget = runW;
|
||||
|
||||
// ── Stop button ───────────────────────────────────────────
|
||||
const stopW = node.addWidget("button", "■ Stop", null, () => stopLoop(node));
|
||||
stopW.serialize = false;
|
||||
node._wfsStopWidget = stopW;
|
||||
};
|
||||
|
||||
// Clean up when node is removed from graph
|
||||
const origRemoved = nodeType.prototype.onRemoved;
|
||||
nodeType.prototype.onRemoved = function () {
|
||||
stopLoop(this);
|
||||
_ns.delete(this.id);
|
||||
origRemoved?.call(this);
|
||||
};
|
||||
},
|
||||
});
|
||||
+445
-11
@@ -43,9 +43,11 @@ const state = {
|
||||
wfLoaded: false,
|
||||
// Prompts sub-tabs
|
||||
promptSubTab: "prompt-all", // "prompt-all" | "prompt-favorites" | "prompt-categories"
|
||||
promptSubTab2: null, // "prompt-groups" | null
|
||||
promptList: [], // full prompt array from API
|
||||
promptFavorites: [], // favorite === true
|
||||
promptCategories: [], // unique category strings
|
||||
promptGroups: {}, // { groupName: [promptId, ...] } from localStorage
|
||||
promptLoaded: false,
|
||||
// Models sub-tabs
|
||||
modelSubTab: "model-all", // "model-all" | "model-favorites" | "model-groups"
|
||||
@@ -59,7 +61,7 @@ const state = {
|
||||
infoSubTab: "info-model", // "info-model" | "info-lora" | "info-prompt"
|
||||
infoMeta: null, // parsed metadata from dropped file
|
||||
// AI tab
|
||||
aiSubTab: "ai-translate", // "ai-translate" | "ai-vlm" | "ai-settings"
|
||||
aiSubTab: "ai-translate", // "ai-translate" | "ai-chat" | "ai-vlm" | "ai-settings"
|
||||
};
|
||||
|
||||
// ============================================
|
||||
@@ -143,6 +145,15 @@ const loadPromptData = async () => {
|
||||
if (c) catSet.add(c);
|
||||
}
|
||||
state.promptCategories = [...catSet].sort();
|
||||
|
||||
try {
|
||||
state.promptGroups = JSON.parse(localStorage.getItem("wfm_prompt_preset_groups") || "{}");
|
||||
} catch { state.promptGroups = {}; }
|
||||
const validIds = new Set(prompts.map(p => p.id));
|
||||
for (const g of Object.keys(state.promptGroups)) {
|
||||
state.promptGroups[g] = (state.promptGroups[g] || []).filter(id => validIds.has(id));
|
||||
}
|
||||
|
||||
state.promptLoaded = true;
|
||||
};
|
||||
|
||||
@@ -230,6 +241,52 @@ const fetchWorkflowRaw = async (filename) => {
|
||||
} catch { return null; }
|
||||
};
|
||||
|
||||
// Returns true if the JSON is in ComfyUI API format (dict of nodeId→{class_type, inputs})
|
||||
// rather than the UI format (has nodes[] and links[] arrays).
|
||||
const isApiWorkflowFormat = (data) => {
|
||||
if (!data || typeof data !== "object" || Array.isArray(data)) return false;
|
||||
if (Array.isArray(data.nodes)) return false;
|
||||
const keys = Object.keys(data);
|
||||
return keys.length > 0 && keys.every((k) => data[k]?.class_type);
|
||||
};
|
||||
|
||||
// Minimal API→UI conversion so app.loadGraphData() can handle API-format workflows.
|
||||
// Nodes are arranged in a grid; link types use "*" since object_info is not queried here.
|
||||
const convertApiToUiWorkflow = (api) => {
|
||||
const nodes = [];
|
||||
const links = [];
|
||||
let linkId = 1;
|
||||
const sortedIds = Object.keys(api).sort((a, b) => Number(a) - Number(b));
|
||||
sortedIds.forEach((id, idx) => {
|
||||
const node = api[id];
|
||||
const col = idx % 5;
|
||||
const row = Math.floor(idx / 5);
|
||||
const uiNode = {
|
||||
id: Number(id),
|
||||
type: node.class_type,
|
||||
title: node._meta?.title || node.class_type,
|
||||
pos: [col * 300 + 50, row * 250 + 50],
|
||||
size: [250, 200],
|
||||
inputs: [],
|
||||
outputs: [],
|
||||
widgets_values: [],
|
||||
mode: 0,
|
||||
};
|
||||
for (const [key, val] of Object.entries(node.inputs || {})) {
|
||||
if (Array.isArray(val) && val.length === 2 && typeof val[0] === "string" && typeof val[1] === "number") {
|
||||
uiNode.inputs.push({ name: key, type: "*", link: linkId });
|
||||
links.push([linkId, Number(val[0]), val[1], Number(id), uiNode.inputs.length - 1, "*"]);
|
||||
linkId++;
|
||||
} else {
|
||||
uiNode.widgets_values.push(val);
|
||||
}
|
||||
}
|
||||
nodes.push(uiNode);
|
||||
});
|
||||
const maxNodeId = Math.max(0, ...sortedIds.map(Number));
|
||||
return { nodes, links, groups: [], config: {}, extra: {}, version: 0.4, last_node_id: maxNodeId, last_link_id: linkId };
|
||||
};
|
||||
|
||||
const loadWfData = async () => {
|
||||
const workflows = await fetchWorkflows();
|
||||
state.wfList = workflows.filter(w => w.filename !== ".index.json");
|
||||
@@ -478,9 +535,21 @@ const placeLoraMgrNode = (loras, pos) => {
|
||||
node.pos = pos || centerPos;
|
||||
graph.add(node);
|
||||
if (node.widgets) {
|
||||
const loraList = loras.map(l => ({ name: l.name, strength: l.strength_model ?? 1.0, clipStrength: l.strength_clip ?? l.strength_model ?? 1.0, active: true }));
|
||||
const loraList = loras.map(l => ({ name: l.name, strength: l.strength_model ?? l.strength ?? 1.0, clipStrength: l.strength_clip ?? l.strength_model ?? l.strength ?? 1.0, active: true }));
|
||||
const w = node.widgets.find(ww => Array.isArray(ww.value) || ww.name === "loras");
|
||||
if (w) { w.value = loraList; if (w.callback) w.callback(loraList); }
|
||||
const textW = node.widgets.find(ww => ww.name === "text");
|
||||
if (textW) {
|
||||
textW.value = loraList
|
||||
.filter(l => l.active !== false)
|
||||
.map(l => {
|
||||
const s = parseFloat(l.strength) || 1.0;
|
||||
const c = parseFloat(l.clipStrength) || s;
|
||||
return s === c ? `<lora:${l.name}:${s}>` : `<lora:${l.name}:${s}:${c}>`;
|
||||
})
|
||||
.join(" ");
|
||||
if (textW.callback) textW.callback(textW.value);
|
||||
}
|
||||
}
|
||||
app.canvas.setDirty(true, true);
|
||||
showToast(`Placed: Lora Loader (${loras.length} loras)`, "success");
|
||||
@@ -490,6 +559,30 @@ const placeLoraMgrNode = (loras, pos) => {
|
||||
// Workflow canvas loading
|
||||
// ============================================
|
||||
|
||||
/**
|
||||
* Load workflow JSON onto the ComfyUI canvas.
|
||||
* Delegates to app.handleFile() so ComfyUI's native path handles both UI and API
|
||||
* formats (identical to dragging a file from Explorer). Falls back to
|
||||
* convertApiToUiWorkflow() + loadGraphData() if handleFile is unavailable.
|
||||
*/
|
||||
const loadDataOnCanvas = async (data) => {
|
||||
if (typeof app?.handleFile === "function") {
|
||||
const blob = new Blob([JSON.stringify(data)], { type: "application/json" });
|
||||
const file = new File([blob], "workflow.json", { type: "application/json" });
|
||||
await app.handleFile(file);
|
||||
} else {
|
||||
if (isApiWorkflowFormat(data)) data = convertApiToUiWorkflow(data);
|
||||
await app.loadGraphData(data);
|
||||
}
|
||||
};
|
||||
|
||||
// ============================================
|
||||
// Cross-window receiver for SPA Send-to-Canvas
|
||||
// ============================================
|
||||
window.wfmReceiveWorkflow = async (data) => {
|
||||
await loadDataOnCanvas(data);
|
||||
};
|
||||
|
||||
const loadWorkflowOnCanvas = async (filename) => {
|
||||
const displayName = filename.replace(/\.json$/i, "");
|
||||
showToast(`Loading "${displayName}"...`, "info");
|
||||
@@ -499,7 +592,7 @@ const loadWorkflowOnCanvas = async (filename) => {
|
||||
return;
|
||||
}
|
||||
try {
|
||||
await app.loadGraphData(data);
|
||||
await loadDataOnCanvas(data);
|
||||
showToast(`Loaded: ${displayName}`, "success");
|
||||
} catch (err) {
|
||||
showToast("Failed to load: " + err.message, "error");
|
||||
@@ -525,7 +618,8 @@ const installCanvasDropHandler = () => {
|
||||
e.dataTransfer.types.includes("application/x-wfm-prompt") ||
|
||||
e.dataTransfer.types.includes("application/x-wfm-model") ||
|
||||
e.dataTransfer.types.includes("application/x-wfm-lora-multi") ||
|
||||
e.dataTransfer.types.includes("application/x-wfm-clip-text")) {
|
||||
e.dataTransfer.types.includes("application/x-wfm-clip-text") ||
|
||||
e.dataTransfer.types.includes("application/x-wfm-pending")) {
|
||||
e.preventDefault();
|
||||
e.dataTransfer.dropEffect = "copy";
|
||||
}
|
||||
@@ -572,6 +666,31 @@ const installCanvasDropHandler = () => {
|
||||
return;
|
||||
}
|
||||
|
||||
// Handle pending workflow drop (from Gallery / Workflow tab "Send to Canvas")
|
||||
const pendingRaw = e.dataTransfer.getData("application/x-wfm-pending");
|
||||
if (pendingRaw) {
|
||||
e.preventDefault();
|
||||
(async () => {
|
||||
try {
|
||||
const wfData = JSON.parse(pendingRaw);
|
||||
await loadDataOnCanvas(wfData);
|
||||
localStorage.removeItem("wfm_pending_workflow");
|
||||
if (panelEl) {
|
||||
const titleEl = panelEl.querySelector(".wfm-nlp-title");
|
||||
if (titleEl) {
|
||||
titleEl.draggable = false;
|
||||
titleEl.classList.remove("wfm-nlp-title-pending");
|
||||
titleEl.title = "Workflow Studio Library";
|
||||
}
|
||||
}
|
||||
showToast("Workflow loaded on canvas", "success");
|
||||
} catch (err) {
|
||||
showToast("Failed to load workflow: " + err.message, "error");
|
||||
}
|
||||
})();
|
||||
return;
|
||||
}
|
||||
|
||||
// Handle workflow drop
|
||||
const wfRaw = e.dataTransfer.getData("application/x-wfm-workflow");
|
||||
if (wfRaw) {
|
||||
@@ -740,6 +859,28 @@ const createPanel = () => {
|
||||
});
|
||||
});
|
||||
|
||||
// Pending workflow drag-to-canvas
|
||||
const titleEl = panel.querySelector(".wfm-nlp-title");
|
||||
const updateTitlePendingState = () => {
|
||||
const hasPending = !!localStorage.getItem("wfm_pending_workflow");
|
||||
titleEl.draggable = hasPending;
|
||||
titleEl.classList.toggle("wfm-nlp-title-pending", hasPending);
|
||||
titleEl.title = hasPending
|
||||
? "Drag to canvas to load workflow"
|
||||
: "Workflow Studio Library";
|
||||
};
|
||||
updateTitlePendingState();
|
||||
panel.addEventListener("mouseenter", updateTitlePendingState);
|
||||
window.addEventListener("storage", (e) => {
|
||||
if (e.key === "wfm_pending_workflow") updateTitlePendingState();
|
||||
});
|
||||
titleEl.addEventListener("dragstart", (e) => {
|
||||
const pendingRaw = localStorage.getItem("wfm_pending_workflow");
|
||||
if (!pendingRaw) { e.preventDefault(); return; }
|
||||
e.dataTransfer.effectAllowed = "copy";
|
||||
e.dataTransfer.setData("application/x-wfm-pending", pendingRaw);
|
||||
});
|
||||
|
||||
// Close
|
||||
panel.querySelector(".wfm-nlp-close").addEventListener("click", () => togglePanel());
|
||||
|
||||
@@ -810,6 +951,7 @@ const rebuildSubTabs = () => {
|
||||
if (state.topTab === "ai") {
|
||||
const row1Tabs = [
|
||||
{ key: "ai-translate", label: "Translation" },
|
||||
{ key: "ai-chat", label: "Chat" },
|
||||
{ key: "ai-vlm", label: "TOOLS" },
|
||||
{ key: "ai-settings", label: "Settings" },
|
||||
];
|
||||
@@ -892,8 +1034,11 @@ const rebuildSubTabs = () => {
|
||||
{ key: "prompt-favorites", label: "\u2605 Favorites" },
|
||||
{ key: "prompt-categories", label: "\ud83d\udcc1 Categories" },
|
||||
];
|
||||
const row2Tabs = [
|
||||
{ key: "prompt-groups", label: "\ud83d\udcc1 Groups" },
|
||||
];
|
||||
|
||||
const activeKey = state.promptSubTab;
|
||||
const activeKey = state.promptSubTab2 || state.promptSubTab;
|
||||
|
||||
for (const t of row1Tabs) {
|
||||
const btn = document.createElement("button");
|
||||
@@ -902,13 +1047,26 @@ const rebuildSubTabs = () => {
|
||||
btn.textContent = t.label;
|
||||
btn.addEventListener("click", () => {
|
||||
state.promptSubTab = t.key;
|
||||
state.promptSubTab2 = null;
|
||||
updateAllActive();
|
||||
btn.classList.add("active");
|
||||
renderContent();
|
||||
});
|
||||
row1.appendChild(btn);
|
||||
}
|
||||
// No row2 tabs for prompts
|
||||
for (const t of row2Tabs) {
|
||||
const btn = document.createElement("button");
|
||||
btn.className = "wfm-nlp-tab wfm-nlp-sub-tab" + (activeKey === t.key ? " active" : "");
|
||||
btn.dataset.subtab = t.key;
|
||||
btn.textContent = t.label;
|
||||
btn.addEventListener("click", () => {
|
||||
state.promptSubTab2 = t.key;
|
||||
updateAllActive();
|
||||
btn.classList.add("active");
|
||||
renderContent();
|
||||
});
|
||||
row2.appendChild(btn);
|
||||
}
|
||||
} else if (state.topTab === "workflows") {
|
||||
const row1Tabs = [
|
||||
{ key: "wf-all", label: "All" },
|
||||
@@ -1040,10 +1198,12 @@ const renderContent = () => {
|
||||
content.innerHTML = `<div class="wfm-nlp-empty">Loading...</div>`;
|
||||
return;
|
||||
}
|
||||
switch (state.promptSubTab) {
|
||||
const promptKey = state.promptSubTab2 || state.promptSubTab;
|
||||
switch (promptKey) {
|
||||
case "prompt-all": renderPromptAll(content); break;
|
||||
case "prompt-favorites": renderPromptFavorites(content); break;
|
||||
case "prompt-categories": renderPromptCategories(content); break;
|
||||
case "prompt-groups": renderPromptGroups(content); break;
|
||||
}
|
||||
} else if (state.topTab === "workflows") {
|
||||
if (!state.wfLoaded) {
|
||||
@@ -1529,6 +1689,32 @@ const renderModelGroups = async (container) => {
|
||||
const item = createModelItem(name, type);
|
||||
listEl.appendChild(item);
|
||||
}
|
||||
|
||||
if (modelType === "lora" && filtered.length >= 1) {
|
||||
const sep = document.createElement("div");
|
||||
sep.className = "wfm-nlp-info-section-title";
|
||||
sep.style.marginTop = "6px";
|
||||
listEl.appendChild(sep);
|
||||
|
||||
const multiItem = document.createElement("div");
|
||||
multiItem.className = "wfm-nlp-item wfm-nlp-model-item";
|
||||
multiItem.draggable = true;
|
||||
multiItem.title = `Drag to canvas to place Lora Loader (LoraManager) with all ${filtered.length} loras`;
|
||||
multiItem.innerHTML = `<div class="wfm-nlp-item-row"><div class="wfm-nlp-item-body"><div class="wfm-nlp-item-label">All ${filtered.length} LoRAs</div><div class="wfm-nlp-item-sub">→ Lora Loader (LoraManager)</div></div></div>`;
|
||||
const buildLoraList = () => filtered.map(n => {
|
||||
const stem = n.replace(/\\/g, "/").split("/").pop().replace(/\.[^.]+$/, "");
|
||||
return { name: stem, strength: 1.0, clipStrength: 1.0, active: true };
|
||||
});
|
||||
multiItem.addEventListener("dragstart", (e) => {
|
||||
e.dataTransfer.effectAllowed = "copy";
|
||||
e.dataTransfer.setData("application/x-wfm-lora-multi", JSON.stringify({ loras: buildLoraList() }));
|
||||
multiItem.classList.add("dragging");
|
||||
});
|
||||
multiItem.addEventListener("dragend", () => multiItem.classList.remove("dragging"));
|
||||
multiItem.addEventListener("dblclick", (e) => { e.stopPropagation(); placeLoraMgrNode(buildLoraList()); });
|
||||
listEl.appendChild(multiItem);
|
||||
}
|
||||
|
||||
section.appendChild(listEl);
|
||||
container.appendChild(section);
|
||||
}
|
||||
@@ -1722,6 +1908,55 @@ const renderPromptCategories = (container) => {
|
||||
}
|
||||
};
|
||||
|
||||
const renderPromptGroups = (container) => {
|
||||
container.innerHTML = "";
|
||||
const groupNames = Object.keys(state.promptGroups).sort();
|
||||
|
||||
if (groupNames.length === 0) {
|
||||
container.innerHTML = `<div class="wfm-nlp-empty">
|
||||
No groups.<br><small>Create groups in Workflow Studio</small>
|
||||
</div>`;
|
||||
return;
|
||||
}
|
||||
|
||||
const promptMap = new Map(state.promptList.map(p => [p.id, p]));
|
||||
let hasAny = false;
|
||||
|
||||
for (const groupName of groupNames) {
|
||||
const ids = state.promptGroups[groupName] || [];
|
||||
const prompts = ids.map(id => promptMap.get(id)).filter(Boolean);
|
||||
const filtered = prompts.filter(matchesPromptSearch);
|
||||
if (state.searchText && filtered.length === 0) continue;
|
||||
|
||||
hasAny = true;
|
||||
const section = document.createElement("div");
|
||||
section.className = "wfm-nlp-group-section";
|
||||
|
||||
const header = document.createElement("div");
|
||||
header.className = "wfm-nlp-group-header collapsed";
|
||||
header.innerHTML = `<span>${esc(groupName)}</span> <span class="wfm-nlp-badge">${filtered.length}</span>`;
|
||||
header.addEventListener("click", () => {
|
||||
const list = section.querySelector(".wfm-nlp-group-list");
|
||||
list.style.display = list.style.display === "none" ? "block" : "none";
|
||||
header.classList.toggle("collapsed");
|
||||
});
|
||||
section.appendChild(header);
|
||||
|
||||
const list = document.createElement("div");
|
||||
list.className = "wfm-nlp-group-list";
|
||||
list.style.display = "none";
|
||||
for (const p of filtered) {
|
||||
list.appendChild(createDraggablePromptItem(p));
|
||||
}
|
||||
section.appendChild(list);
|
||||
container.appendChild(section);
|
||||
}
|
||||
|
||||
if (!hasAny) {
|
||||
container.innerHTML = `<div class="wfm-nlp-empty">No matches.</div>`;
|
||||
}
|
||||
};
|
||||
|
||||
// ============================================
|
||||
// Render – Node sub-tabs (existing)
|
||||
// ============================================
|
||||
@@ -2217,7 +2452,9 @@ function _extractLoRAs(wf) {
|
||||
function add(name, sm, sc) {
|
||||
if (!name || typeof name !== "string" || name === "None" || seen.has(name)) return;
|
||||
seen.add(name);
|
||||
results.push({ name, strength_model: typeof sm === "number" ? sm : 1.0, strength_clip: typeof sc === "number" ? sc : 1.0 });
|
||||
const smNum = parseFloat(sm);
|
||||
const scNum = parseFloat(sc);
|
||||
results.push({ name, strength_model: isNaN(smNum) ? 1.0 : smNum, strength_clip: isNaN(scNum) ? 1.0 : scNum });
|
||||
}
|
||||
if (Array.isArray(wf.nodes)) {
|
||||
for (const n of _collectAllNodes(wf)) {
|
||||
@@ -2233,6 +2470,11 @@ function _extractLoRAs(wf) {
|
||||
const ct = n.class_type ?? "";
|
||||
if (ct === "LoraLoader") add(n.inputs?.lora_name, n.inputs?.strength_model, n.inputs?.strength_clip);
|
||||
else if (ct === "LoraLoaderModelOnly") add(n.inputs?.lora_name, n.inputs?.strength, 1.0);
|
||||
else if (ct === "Lora Loader (LoraManager)") {
|
||||
const lorasData = n.inputs?.loras;
|
||||
const list = lorasData?.__value__ ?? (Array.isArray(lorasData) ? lorasData : null);
|
||||
if (list) for (const l of list) { if (l?.active !== false) add(l?.name, l?.strength ?? 1.0, l?.clipStrength ?? l?.strength ?? 1.0); }
|
||||
}
|
||||
}
|
||||
}
|
||||
return results;
|
||||
@@ -2836,6 +3078,24 @@ async function aiCallVLM(url, backend, model, prompt, base64Image, mimeType) {
|
||||
}
|
||||
}
|
||||
|
||||
async function aiCallChat(url, backend, model, messages) {
|
||||
if (backend === "ollama") {
|
||||
const r = await fetch(`${url}/api/chat`, {
|
||||
method: "POST", headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify({ model, messages, stream: false }),
|
||||
});
|
||||
if (!r.ok) throw new Error(`HTTP ${r.status}`);
|
||||
return (await r.json()).message?.content || "";
|
||||
} else {
|
||||
const r = await fetch(`${url}/v1/chat/completions`, {
|
||||
method: "POST", headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify({ model, messages, stream: false }),
|
||||
});
|
||||
if (!r.ok) throw new Error(`HTTP ${r.status}`);
|
||||
return (await r.json()).choices?.[0]?.message?.content || "";
|
||||
}
|
||||
}
|
||||
|
||||
async function aiFetchModels(url, backend) {
|
||||
if (backend === "ollama") {
|
||||
const r = await fetch(`${url}/api/tags`);
|
||||
@@ -2877,6 +3137,16 @@ const renderAiTab = (container) => {
|
||||
</div>
|
||||
<textarea id="wfm-nlp-ai-output" class="wfm-nlp-ai-textarea wfm-nlp-ai-output" placeholder="Translation result..." readonly></textarea>
|
||||
</div>
|
||||
<!-- Chat sub -->
|
||||
<div id="wfm-nlp-ai-chat" class="wfm-nlp-ai-pane" style="display:none;">
|
||||
<div class="wfm-nlp-ai-chat-msgs" id="wfm-nlp-ai-chat-msgs"></div>
|
||||
<textarea id="wfm-nlp-ai-chat-input" class="wfm-nlp-ai-textarea wfm-nlp-ai-chat-input" placeholder="Type a message..."></textarea>
|
||||
<div class="wfm-nlp-ai-actions">
|
||||
<button id="wfm-nlp-ai-chat-send" class="wfm-nlp-ai-btn wfm-nlp-ai-btn-primary">Send</button>
|
||||
<button id="wfm-nlp-ai-chat-clear" class="wfm-nlp-ai-btn">Clear</button>
|
||||
<span id="wfm-nlp-ai-chat-status" class="wfm-nlp-ai-status"></span>
|
||||
</div>
|
||||
</div>
|
||||
<!-- TOOLS sub -->
|
||||
<div id="wfm-nlp-ai-vlm" class="wfm-nlp-ai-pane" style="display:none;">
|
||||
<div class="wfm-nlp-ai-vlm-drop" id="wfm-nlp-ai-vlm-drop">
|
||||
@@ -2884,11 +3154,22 @@ const renderAiTab = (container) => {
|
||||
<span id="wfm-nlp-ai-vlm-label" class="wfm-nlp-ai-vlm-label">Drop PNG / JPG / WebP</span>
|
||||
<input type="file" id="wfm-nlp-ai-vlm-file" accept="image/png,image/jpeg,image/webp" style="display:none;">
|
||||
</div>
|
||||
<div id="wfm-nlp-ai-wc-inputs" style="display:none;flex-direction:column;gap:5px;">
|
||||
<div class="wfm-nlp-ai-row">
|
||||
<span class="wfm-nlp-ai-lbl">Name</span>
|
||||
<input type="text" id="wfm-nlp-ai-wc-name" class="wfm-nlp-ai-input" style="flex:1;" placeholder="e.g. sports">
|
||||
</div>
|
||||
<div class="wfm-nlp-ai-row">
|
||||
<span class="wfm-nlp-ai-lbl">Count</span>
|
||||
<input type="number" id="wfm-nlp-ai-wc-count" class="wfm-nlp-ai-input wfm-nlp-ai-wc-count" value="20" min="1" max="200">
|
||||
</div>
|
||||
</div>
|
||||
<div class="wfm-nlp-ai-row">
|
||||
<select id="wfm-nlp-ai-vlm-task" class="wfm-nlp-ai-sel" style="flex:1;">
|
||||
<option value="describe">Describe image</option>
|
||||
<option value="prompt">Create prompt</option>
|
||||
<option value="tags">Create tags</option>
|
||||
<option value="wildcard">Create wildcards</option>
|
||||
</select>
|
||||
<button id="wfm-nlp-ai-vlm-run" class="wfm-nlp-ai-btn wfm-nlp-ai-btn-primary">Run</button>
|
||||
</div>
|
||||
@@ -2946,7 +3227,7 @@ const renderAiTab = (container) => {
|
||||
|
||||
const renderAiSubContent = () => {
|
||||
if (!panelEl) return;
|
||||
const panes = { "ai-translate": "wfm-nlp-ai-translate", "ai-vlm": "wfm-nlp-ai-vlm", "ai-settings": "wfm-nlp-ai-settings" };
|
||||
const panes = { "ai-translate": "wfm-nlp-ai-translate", "ai-chat": "wfm-nlp-ai-chat", "ai-vlm": "wfm-nlp-ai-vlm", "ai-settings": "wfm-nlp-ai-settings" };
|
||||
for (const [key, id] of Object.entries(panes)) {
|
||||
const el = panelEl.querySelector(`#${id}`);
|
||||
if (el) el.style.display = state.aiSubTab === key ? "flex" : "none";
|
||||
@@ -3101,6 +3382,67 @@ const setupAiHandlers = (container) => {
|
||||
// Auto-load models if settings exist
|
||||
if (cfg.backendUrl && cfg.backend) refreshModels().catch(() => {});
|
||||
|
||||
// ---- Chat handlers ----
|
||||
let chatHistory = [];
|
||||
const chatMsgsEl = container.querySelector("#wfm-nlp-ai-chat-msgs");
|
||||
const chatInputEl = container.querySelector("#wfm-nlp-ai-chat-input");
|
||||
const chatSendBtn = container.querySelector("#wfm-nlp-ai-chat-send");
|
||||
const chatClearBtn= container.querySelector("#wfm-nlp-ai-chat-clear");
|
||||
const chatStatusEl= container.querySelector("#wfm-nlp-ai-chat-status");
|
||||
|
||||
const appendChatBubble = (role, content) => {
|
||||
const div = document.createElement("div");
|
||||
div.className = `wfm-nlp-ai-chat-msg wfm-nlp-ai-chat-msg-${role}`;
|
||||
div.textContent = content;
|
||||
chatMsgsEl.appendChild(div);
|
||||
chatMsgsEl.scrollTop = chatMsgsEl.scrollHeight;
|
||||
};
|
||||
|
||||
const sendChatMessage = async () => {
|
||||
const text = chatInputEl?.value?.trim();
|
||||
if (!text) return;
|
||||
const c = loadAiCfg();
|
||||
const backend = c.backend || "ollama";
|
||||
const url = c.backendUrl || (backend === "ollama" ? "http://localhost:11434" : "http://localhost:1234");
|
||||
const model = c.model;
|
||||
if (!isValidAiUrl(url)) { showToast("URLは http:// または https:// で始まる必要があります", "error"); return; }
|
||||
if (!model) { showToast("Please select a model in Settings", "error"); return; }
|
||||
|
||||
chatInputEl.value = "";
|
||||
chatHistory.push({ role: "user", content: text });
|
||||
appendChatBubble("user", text);
|
||||
|
||||
chatSendBtn.disabled = true;
|
||||
chatStatusEl.textContent = "Thinking...";
|
||||
chatStatusEl.className = "wfm-nlp-ai-status wfm-nlp-ai-working";
|
||||
|
||||
try {
|
||||
const reply = await aiCallChat(url, backend, model, chatHistory);
|
||||
chatHistory.push({ role: "assistant", content: reply });
|
||||
appendChatBubble("assistant", reply);
|
||||
chatStatusEl.textContent = "";
|
||||
chatStatusEl.className = "wfm-nlp-ai-status";
|
||||
} catch (err) {
|
||||
chatHistory.pop();
|
||||
if (chatMsgsEl.lastChild) chatMsgsEl.removeChild(chatMsgsEl.lastChild);
|
||||
chatInputEl.value = text;
|
||||
chatStatusEl.textContent = `エラー: ${err.message}`;
|
||||
chatStatusEl.className = "wfm-nlp-ai-status wfm-nlp-ai-err";
|
||||
} finally {
|
||||
chatSendBtn.disabled = false;
|
||||
}
|
||||
};
|
||||
|
||||
chatSendBtn?.addEventListener("click", sendChatMessage);
|
||||
chatInputEl?.addEventListener("keydown", e => {
|
||||
if (e.key === "Enter" && !e.shiftKey) { e.preventDefault(); sendChatMessage(); }
|
||||
});
|
||||
chatClearBtn?.addEventListener("click", () => {
|
||||
chatHistory = [];
|
||||
if (chatMsgsEl) chatMsgsEl.innerHTML = "";
|
||||
if (chatStatusEl) { chatStatusEl.textContent = ""; chatStatusEl.className = "wfm-nlp-ai-status"; }
|
||||
});
|
||||
|
||||
// ---- VLM handlers ----
|
||||
let vlmImage = null; // { base64, mimeType }
|
||||
|
||||
@@ -3108,10 +3450,22 @@ const setupAiHandlers = (container) => {
|
||||
const vlmPreview = container.querySelector("#wfm-nlp-ai-vlm-preview");
|
||||
const vlmLabel = container.querySelector("#wfm-nlp-ai-vlm-label");
|
||||
const vlmFile = container.querySelector("#wfm-nlp-ai-vlm-file");
|
||||
const vlmTaskSel = container.querySelector("#wfm-nlp-ai-vlm-task");
|
||||
const vlmRunBtn = container.querySelector("#wfm-nlp-ai-vlm-run");
|
||||
const vlmStatus = container.querySelector("#wfm-nlp-ai-vlm-status");
|
||||
const vlmResult = container.querySelector("#wfm-nlp-ai-vlm-result");
|
||||
const vlmCopy = container.querySelector("#wfm-nlp-ai-vlm-copy");
|
||||
const wcInputs = container.querySelector("#wfm-nlp-ai-wc-inputs");
|
||||
const wcNameEl = container.querySelector("#wfm-nlp-ai-wc-name");
|
||||
const wcCountEl = container.querySelector("#wfm-nlp-ai-wc-count");
|
||||
|
||||
const updateVlmTaskUI = () => {
|
||||
const isWc = vlmTaskSel?.value === "wildcard";
|
||||
if (vlmDrop) vlmDrop.style.display = isWc ? "none" : "";
|
||||
if (wcInputs) wcInputs.style.display = isWc ? "flex" : "none";
|
||||
};
|
||||
vlmTaskSel?.addEventListener("change", updateVlmTaskUI);
|
||||
updateVlmTaskUI();
|
||||
|
||||
const loadVlmImage = async (file) => {
|
||||
if (!file || !file.type.startsWith("image/")) return;
|
||||
@@ -3140,7 +3494,7 @@ const setupAiHandlers = (container) => {
|
||||
};
|
||||
|
||||
vlmRunBtn?.addEventListener("click", async () => {
|
||||
if (!vlmImage) { showToast("Please drop an image", "error"); return; }
|
||||
const task = vlmTaskSel?.value || "describe";
|
||||
const c = loadAiCfg();
|
||||
const backend = c.backend || "ollama";
|
||||
const url = c.backendUrl || (backend === "ollama" ? "http://localhost:11434" : "http://localhost:1234");
|
||||
@@ -3148,7 +3502,37 @@ const setupAiHandlers = (container) => {
|
||||
if (!isValidAiUrl(url)) { showToast("URLは http:// または https:// で始まる必要があります", "error"); return; }
|
||||
if (!model) { showToast("Please select a model in Settings", "error"); return; }
|
||||
|
||||
const task = container.querySelector("#wfm-nlp-ai-vlm-task")?.value || "describe";
|
||||
if (task === "wildcard") {
|
||||
const name = wcNameEl?.value?.trim() || "";
|
||||
const count = Math.max(1, parseInt(wcCountEl?.value) || 20);
|
||||
if (!name) { showToast("Please enter a wildcard name", "error"); return; }
|
||||
|
||||
vlmRunBtn.disabled = true;
|
||||
vlmStatus.textContent = "Running...";
|
||||
vlmStatus.className = "wfm-nlp-ai-status wfm-nlp-ai-working";
|
||||
vlmResult.value = "";
|
||||
|
||||
const prompt = `Generate ${count} wildcard entries for the category "${name}". Output only plain text in English, one entry per line, no numbers, no markdown, no asterisks, no bold, nothing else.`;
|
||||
try {
|
||||
const result = await aiCallLLM(url, backend, model, prompt);
|
||||
vlmResult.value = result.trim()
|
||||
.split("\n")
|
||||
.map(l => l.replace(/\*\*/g, "").replace(/^\*\s*/, "").replace(/^\d+\.\s*/, "").trim())
|
||||
.filter(l => l.length > 0)
|
||||
.join("\n");
|
||||
vlmStatus.textContent = "完了";
|
||||
vlmStatus.className = "wfm-nlp-ai-status wfm-nlp-ai-ok";
|
||||
} catch (err) {
|
||||
vlmStatus.textContent = `エラー: ${err.message}`;
|
||||
vlmStatus.className = "wfm-nlp-ai-status wfm-nlp-ai-err";
|
||||
} finally {
|
||||
vlmRunBtn.disabled = false;
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
if (!vlmImage) { showToast("Please drop an image", "error"); return; }
|
||||
|
||||
vlmRunBtn.disabled = true;
|
||||
vlmStatus.textContent = "Running...";
|
||||
vlmStatus.className = "wfm-nlp-ai-status wfm-nlp-ai-working";
|
||||
@@ -3304,6 +3688,16 @@ const injectStyles = () => {
|
||||
font-size: 14px;
|
||||
flex: 1;
|
||||
}
|
||||
.wfm-nlp-title-pending {
|
||||
cursor: grab;
|
||||
color: #66aaff;
|
||||
}
|
||||
.wfm-nlp-title-pending::after {
|
||||
content: " ●";
|
||||
font-size: 7px;
|
||||
color: #4caf50;
|
||||
vertical-align: super;
|
||||
}
|
||||
.wfm-nlp-close {
|
||||
background: none;
|
||||
border: none;
|
||||
@@ -4005,6 +4399,46 @@ const injectStyles = () => {
|
||||
color: var(--descrip-text, #999);
|
||||
pointer-events: none;
|
||||
}
|
||||
/* Chat */
|
||||
.wfm-nlp-ai-chat-msgs {
|
||||
flex: 1;
|
||||
overflow-y: auto;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 6px;
|
||||
min-height: 0;
|
||||
padding: 2px;
|
||||
}
|
||||
.wfm-nlp-ai-chat-msg {
|
||||
max-width: 92%;
|
||||
padding: 6px 8px;
|
||||
border-radius: 6px;
|
||||
font-size: 11px;
|
||||
line-height: 1.5;
|
||||
word-break: break-word;
|
||||
white-space: pre-wrap;
|
||||
}
|
||||
.wfm-nlp-ai-chat-msg-user {
|
||||
align-self: flex-end;
|
||||
background: var(--p-button-background, #4a9eff);
|
||||
color: #fff;
|
||||
}
|
||||
.wfm-nlp-ai-chat-msg-assistant {
|
||||
align-self: flex-start;
|
||||
background: var(--comfy-input-bg, #2a2a2a);
|
||||
border: 1px solid var(--border-color, #4e4e4e);
|
||||
color: var(--input-text, #ddd);
|
||||
}
|
||||
.wfm-nlp-ai-chat-input {
|
||||
min-height: 50px;
|
||||
max-height: 100px;
|
||||
flex: none;
|
||||
flex-shrink: 0;
|
||||
}
|
||||
/* Wildcard count */
|
||||
.wfm-nlp-ai-wc-count {
|
||||
width: 60px;
|
||||
}
|
||||
`;
|
||||
document.head.appendChild(style);
|
||||
};
|
||||
|
||||
Reference in New Issue
Block a user