Compare commits

...
38 Commits
Author SHA1 Message Date
ketle-manandClaude Sonnet 4.6 7181f4e20a feat: add Chat pane and Wildcard generation to AI TOOL tab (v0.3.40)
- AI TOOL tab: 3-pane layout expanded to 4-pane (Translation | Chat | TOOLS | Settings)
- Chat pane: multi-turn LLM conversation with history; Enter to send, Shift+Enter for newline; Clear resets history; Ollama /api/chat, LM Studio /v1/chat/completions
- TOOLS pane: new "Create wildcards" task — enter category name and count, generates plain-text entries one per line (no markdown, no numbering)
- Both features added to the Library side panel A tab (Chat sub-tab + wildcard dropdown option)
- i18n: aiStatusChatting / aiToastChatFailed / aiToastWcNoName added in EN/JA/ZH
- Help: AI TOOL tab card updated to 6 items; helpSidepanel16 updated in EN/JA/ZH

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-06-19 14:43:03 +09:00
ketle-manandClaude Sonnet 4.6 735e8ba876 feat: Send to Canvas button + Library title drag-to-canvas (v0.3.39)
- Workflow tab: replaced "Open in ComfyUI" with "Send to Canvas" (toolbar
  and detail modal); stores workflow JSON in localStorage for title-drag
- Gallery tab: renamed "Copy Workflow" to "Copy & Send Canvas"; copies to
  clipboard and stores for title-drag simultaneously
- Workflow Studio Library: panel title turns blue with green indicator when
  a pending workflow is stored; drag title onto canvas to load via
  app.loadGraphData(); title resets automatically after loading
- i18n: sendToCanvas / copyAndSendCanvas / workflowSentToCanvas (EN/JA/ZH)
- Help: helpWf6, helpGallery8 updated; helpSidepanel17 added (EN/JA/ZH)

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-06-18 21:33:13 +09:00
ketle-manandClaude Sonnet 4.6 c5a2662bef feat: add Tagger tab + GenUI:P button + ZIT workflow fix (v0.3.38)
### Tagger tab (new)
- WD Tagger (ONNX/NCHW/NHWC), SwinV2, DeepDanbooru (.h5/TF optional), Ollama VLM
- Single subtab: drag & drop / upload, 5 output targets (GenUI:P / Prompt / Gallery / File / DB)
- Batch subtab: folder processing, Save DB / Write to File / Write .txt output options
- DB subtab: searchable SQLite, row edit, CSV export
- Backend: tagger_service.py, tagger_db_service.py, tagger_routes.py (17 endpoints)
- Security: model name validation, extension allowlist, path traversal fix in gallery_service

### Tagger single — GenUI:P button
- Appends generated tags to GenerateUI positive prompt and applies to loaded workflow immediately

### GenerateUI — ZIT/Lumina2 workflow prompt fix
- Remove ConditioningZeroOut from COND_PASSTHROUGH; shared CLIPTextEncode now correctly
  gets role "positive" instead of "unknown" in ZIT workflows
- workflow_analyzer: add lumina2 → Z-IMAGE to _CLIP_TYPE_TO_MODEL

### Gallery detail panel
- Split tab row (Info/JSON/Groups) and action row (Metadata/Load GenUI/Tagger) to separate rows
- Add Tagger button (purple) to open selected image in Tagger tab
- Fix Save to Gallery: tags now stored as array (was string, broke forEach on refresh)

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-06-15 15:04:42 +09:00
ketle-manandClaude Sonnet 4.6 127d85d913 feat: Select All button for Models & Gallery bulk bars, Gallery bulk bar i18n (v0.3.37)
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-06-15 09:22:04 +09:00
ketle-manandClaude Fable 5 85ce2e05df fix: review fixes (Save safety, help i18n), util.js refactor, toast i18n, README refresh (v0.3.36)
- GenerateUI Save: overwrite confirmation with UI-format warning, Raw JSON
  sync, HTML-injection-safe filename input, double-submit guard
- Help i18n: v0.3.35 help updates were overwritten by stale i18n strings;
  synced helpGen2/helpModels2/helpGallery8/10 in 3 languages, registered
  missing helpIdMap entries, added helpGallery12/13
- Toast i18n: ~115 hard-coded English toasts replaced with t() (+~60 shared
  keys in EN/JA/ZH); fixed undefined Settings keys (textSize*/jsonColor*)
- Refactor: new shared util.js (escapeHtml unified across 5 files,
  readJsonStorage/getSettings replace 15 localStorage parses); sortModels
  precomputes sort keys; Gallery action buttons split from tab-button class
  (all !important CSS removed)
- README: intro rewritten around 3 pillars (Management / GenerateUI /
  Library side panel); new screenshots (LoRA Stack, Batch, Multi-select);
  WS Library image updated; pyproject description aligned

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-06-10 21:37:06 +09:00
ketle-manandClaude Sonnet 4.6 3190cc1443 feat: Models table sort, Gallery Load GenUI, GenerateUI Save button, help update (v0.3.35)
- Models tab: click column header to sort table (asc▲/desc▼/clear); active column highlighted in accent color; E/D label for Enable/Disable column
- Gallery tab: Load GenUI button loads embedded workflow into GenerateUI tab; Metadata button restyled green; warning toast if no workflow or unsupported format
- GenerateUI tab: Save button at right end of subtab row; filename dialog defaults to current workflow name; saves to Workflow tab via import API
- Help: Models tab note and Troubleshooting entry added for model loading error after move/delete (requires Hard Reset or ComfyUI restart)
- README and DEVLOG updated for v0.3.35

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-06-10 10:27:46 +09:00
ketle-manandClaude Sonnet 4.6 070e378314 feat: Models table Type/BaseModel columns, modal delete, bulk move, B/S fix, Gallery-Metadata link (v0.3.34)
- Table view: add CivitAI Type and Base Model columns between Subdirectory and Extension
- Detail modal: Delete button removes model file + all sidecar files
- Bulk action bar: file move operation (model + sidecars) with subfolder create; 3-row layout (Group/Badge/File); Select button green; dropdown width 330px; Delete Files moved to File row right end; X button removed
- B/S buttons (Checkpoint/LoRA table+card): targeted active-class toggle instead of full grid re-render; renderModelGrid only called when showBatchOnly filter is active
- Backend: GET /api/wfm/models/subdirs and POST /api/wfm/models/move with path traversal protection and _VALID_MODEL_TYPES whitelist
- Gallery: Alt+click or Metadata button opens selected image in Metadata tab via loadFileIntoMetadataTab()
- Help and DEVLOG updated

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-06-09 16:11:22 +09:00
ketle-manandClaude Sonnet 4.6 dbc9ff0820 fix: LoRA pane load overwrite, tab reset, Stack group visibility, CLIPTextEncodeEditPlus mapping, Stack Apply trigger words (v0.3.33)
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-06-09 00:49:21 +09:00
ketle-manandClaude Sonnet 4.6 3957ec7d21 feat: Lora Loader (LoraManager) detection, M-tab Groups drop, P-tab Groups subtab (v0.3.32)
- I/Metadata tabs: detect LoRAs from Lora Loader (LoraManager) nodes in both workflow and API formats (inputs.loras.__value__)
- Fix strength parsing: use parseFloat to handle string values like "0.20" from LoraManager
- placeLoraMgrNode: sync text widget with LoRA syntax (<lora:name:s:c>) after drop
- M tab Groups: add "All N LoRAs" drag/drop item to place Lora Loader (LoraManager) with full group
- P tab: add Groups subtab (row2) showing wfm_prompt_preset_groups from localStorage
- Help (i18n.js), README, DEVLOG updated for v0.3.32

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-06-08 22:11:02 +09:00
ketle-manandClaude Sonnet 4.6 0c7ca31c99 feat: split LoRA pane into Single/Stack tabs, fix GenUI Model LoRA handling (v0.3.31)
- renderLoraPane rewritten: Single tab (filter, dropdown, M/C strength, Apply, P,
  LORA SYNTAX, TRIGGER WORDS) and Stack tab (target, Apply, P, toggle-all,
  global adj, LORA SYNTAX, TRIGGER WORDS, model list) are now independent
- _refreshLoraSingleDynamic: auto-updates LORA SYNTAX/TRIGGER WORDS on model or
  strength change in Single tab
- comfyEditor.switchLoraSingleTab() / disableAllStack() added for external access
- applyToGenUI (models-tab): now handles Lora Loader (LoraManager) via lora_nodes;
  switches to Single tab, disables Stack, updates LORA SYNTAX/TRIGGER WORDS display
- i18n helpGen5 / helpModels8 updated (EN/JA/ZH)

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-06-08 18:47:13 +09:00
ketle-manandClaude Sonnet 4.6 ff9df1ad92 feat: LoRA stack trigger words fix, stack refresh button, help troubleshooting (v0.3.30)
- Fix trigger words display: inactive stack models no longer contribute trigger
  words; initial render and per-model toggle/toggle-all now filter to active only
- Add LoRA column header refresh button (🔄) for manual Stack group reload
  without switching away from the Model tab
- Add help troubleshooting entry for "No such file or directory" error when
  running LoRA Stack (comfyui-lora-manager compatibility issue)

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-06-08 17:00:29 +09:00
ketle-manandClaude Sonnet 4.6 c0fde1c42e feat: LoRA unified pane, Help sidebar, Feeder UI, Batch Sampler/Scheduler, LoraManager support (v0.3.29)
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-06-08 15:10:00 +09:00
ketle-manandClaude Sonnet 4.6 3886ad2b42 fix: workflow batch 404 and rename double-submit bug (v0.3.23)
- fix: workflow batch used non-existent route /api/wfm/workflows/{name};
  corrected to /api/wfm/workflows/raw?filename={name}
- fix: rename modal accumulated blur listeners on #wfm-modal-title-input
  across modal opens; subsequent renames sent two requests back-to-back
  (first succeeded, second hit 409/404); store listener ref on
  titleInput._commitRename and removeEventListener before re-registering

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-06-05 17:49:59 +09:00
ketle-manandClaude Sonnet 4.6 080d75b8c4 feat: remove card view, add 4-type batch selector UI (v0.3.22)
- Remove Card view from Workflow and Models tabs (Thumbnail/Table only);
  localStorage fallback: stored "card" value defaults to "thumb"
- Replace Checkpoint Batch toggle with per-column-header checkboxes in
  Batch Queue pane (Checkpoint/Lora/Prompt/Workflow, radio behavior);
  Batch panel below Generate repurposed as status display + Pause/Stop
- Add _runBatchLoop() generic loop + _runBatchGenerate() 4-type dispatcher:
  Checkpoint (file-tree + group), Lora (group), Prompt (preset objects →
  positive/negative nodes), Workflow (group, restores original after batch)
- Remove ~86 lines of card-view CSS; keep nodes-tab card view intact
- Update help strings (EN/JA/ZH): helpWf1, helpModels2, helpGen11/13/14
- Update README features and Changelog

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-06-05 16:22:29 +09:00
ketle-manandClaude Sonnet 4.6 eada3923c7 feat: CivitAI host setting, Info/Sample sub-tabs, URL fix, help i18n (v0.3.21)
- Settings tab: add civitai.com / civitai.red host selector; saved to
  settings.json and synced to localStorage for use across tabs
- CivitAI panel: split into Info / Sample sub-tabs; images moved to
  Sample tab with count in label; images open full-size in new tab
- URL fix: modelId=null entries now use /model-versions/{versionId}
  fallback (fixes all 324 existing cache entries client-side)
- Help: add helpGen12/13/14 (Batch tab panes) and helpSettings11/12/13
  (Text Size / RAW JSON Colors / CivitAI Host) with EN/JA/ZH; update
  helpGen3 (4-tab→5-tab) and helpGen11; fix JA/ZH English-mixed terms

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-31 22:47:21 +09:00
ketle-manandClaude Sonnet 4.6 ef0fccbd36 feat: CivitAI panel — Type/Hash display, image new-tab, URL fix, 3-state UI (v0.3.20)
- Add Type badge, Base Model row, Hash row (BLAKE3/SHA256) to CivitAI side panel
- Extract fileHashes (BLAKE3, SHA256, AutoV2 etc.) in _extract_info
- Sample images wrapped in <a target="_blank"> to open full-size in new tab
- Fix broken model page URL caused by batch POST API omitting model.id;
  fall back to top-level modelId field in _extract_info; also reconstruct
  URL client-side from modelId+versionId for existing cached data
- Add 3-state CivitAI tab UI: unchecked / checked-not-found / found
- CivitAI tab click now calls renderSideCivitai to always show latest state

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-31 20:35:45 +09:00
ketle-manandClaude Sonnet 4.6 9564aa8c6e feat: CivitAI batch speedup, retry backoff, API key, richer metadata (v0.3.19)
- civitai_service.py: replace per-model GET with POST /model-versions/by-hash
  batch endpoint (up to 100 hashes/request); batch_fetch now runs in 2 phases:
  Phase 1 hashes all files, Phase 2 POSTs uncached hashes in one shot —
  100-model fetch drops from ~50 s to a few seconds
- Add exponential backoff retry (1s/2s/4s, max 3 attempts) for HTTP
  429/500/502/503/504 in both fetch_by_hash and _batch_fetch_post
- Add CivitAI API key support: CIVITAI_API_KEY env var takes priority over
  settings.json civitai_api_key; Bearer token added to all requests
- settings_routes.py: exclude civitai_api_key from data export bundle
- _extract_info: add nsfwLevel, air (AIR URN), stats (downloadCount/thumbsUp),
  updatedAt, publishedAt, imageDetails (url/width/height/nsfwLevel per image),
  fileMeta (fp/size/format); images URL list kept for backward compatibility
- Normalize hash casing: lowercase for cache keys, uppercase for API calls
- models-tab.js: apply data.hashes from done SSE event directly to
  state.modelMetadata to fix CivitAI tab blank after batch fetch
- settings-tab.js + i18n.js (EN/JA/ZH): add CivitAI API Key settings section

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-31 18:44:05 +09:00
ketle-manandClaude Sonnet 4.6 7395fe2432 feat: add Batch tab to GenerateUI, expand Models bulk actions (v0.3.18)
- GenerateUI: new Batch subtab (5th tab) with 3-pane layout —
  left pane: file-tree checkpoint selector (initially all unchecked);
  center pane: group-based selection with inner tabs (Checkpoint/Lora/
  Prompt/Workflow); right pane: live Batch Queue preview combining both
  selections with duplicates removed
- Checkpoint selector removed from right panel dropdown; Batch tab
  is now the single entry point for checkpoint selection
- Group selection state refactored from flat selectedModels Set to
  selectedGroups + partialSelections so group membership changes in the
  Models tab are always reflected without stale entries
- Models: bulk action bar adds Deselect All, bulk Favorite/Unfavorite,
  bulk +Badge/-Badge; i18n keys added for all three (EN/JA/ZH)
- civitai_service.py: remove SSL CERT_NONE fallback (v0.3.17 patch,
  SSL verification is now never disabled)
- Help, README, DEVLOG updated to v0.3.18

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-31 13:55:48 +09:00
ketle-manandClaude Sonnet 4.6 49e2519f89 chore: bump pyproject.toml version to 0.3.17
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-30 18:20:09 +09:00
ketle-manandClaude Sonnet 4.6 5390f0c94d fix: SSL cert error on CivitAI + Lora Manager UI-to-API conversion
- civitai_service: add _make_ssl_context() that tries certifi first,
  falls back to system store, then CERT_NONE with warning; fixes
  CERTIFICATE_VERIFY_FAILED on Windows Portable Python environments
- comfyui-workflow: convertUiToApi() now detects nodes with
  properties.__lm_widget_ids (Lora Loader (LoraManager)) and maps
  widgets_values via that index, wrapping the loras array as
  {"__value__": [...]} for the API format

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-30 18:18:10 +09:00
ketle-manandClaude Sonnet 4.6 b20f46dc93 feat: show CivitAI image as preview fallback when no local file exists
When the backend preview download fails (server-side network restriction etc.),
loadPreviewImage() now falls back to civitaiCache[sha256].images[0] so the
card and side panel always show the CivitAI image after fetching.
fetchCivitaiForModel() also refreshes the grid and side panel regardless of
preview_saved, using the CivitAI URL directly when no local file was saved.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-20 18:32:20 +09:00
ketle-manandClaude Sonnet 4.6 14c538eb55 docs: v0.3.15 README and DEVLOG update
- README: version badge 0.3.14 → 0.3.15, Sample Workflows section,
  CivitAI auto-preview note, Create Tags in TOOLS pane, v0.3.15 changelog
- DEVLOG: add 2026-05-20 v0.3.15 entry covering all three changes

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-20 17:35:51 +09:00
ketle-manandClaude Sonnet 4.6 ef0017a0fc docs: update help text for CivitAI auto-preview and Create Tags
- helpModels5 (EN/JA/ZH): note that preview is auto-downloaded when missing
- helpAi3 (EN/JA/ZH): add Create Tags / タグ作成 / 标签生成 to TOOLS task list

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-20 17:33:37 +09:00
ketle-manandClaude Sonnet 4.6 19e77a00db feat: add Create tags option to TOOLS pane VLM task selector
Add "Create tags" task to the VLM dropdown in both the SPA AI TOOL tab
and the Library panel A tab. Sends a prompt that asks the VLM to output
comma-separated English tags describing the image.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-20 17:31:38 +09:00
ketle-manandClaude Sonnet 4.6 826988cc0b feat: auto-save CivitAI preview image for models without preview
When fetching CivitAI info (individual or batch), if the model has no
preview image, automatically download the first CivitAI image and save
it as {model_stem}.preview.png next to the model file.

- civitai_service.py: add download_image() static method
- models_routes.py: auto-download preview in handle_civitai_fetch and
  handle_civitai_batch; batch summary includes preview_saved count
- models-tab.js: refresh side panel and grid on preview_saved=true;
  batch done toast shows "+N preview" when previews were saved

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-20 17:16:16 +09:00
ketle-manandClaude Sonnet 4.6 28bfbcda6b docs: add Sample Workflows section to README
Explains that workflows/ contains sample workflows and that some may
require additional custom nodes installable via ComfyUI Manager or git clone.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-20 16:54:18 +09:00
ketle-manandClaude Sonnet 4.6 6eef19e656 feat: add sample workflow files for distribution
Add workflows/ directory with 13 sample workflows (JSON + PNG thumbnails)
covering SD1.5, SDXL, DWPose, face detailer, and image editing presets.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-20 16:46:51 +09:00
ketle-manandClaude Sonnet 4.6 646721a5f4 docs: update DEVLOG for AI TOOL tab English label fixes
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-20 10:54:47 +09:00
ketle-manandClaude Sonnet 4.6 4c44215f70 fix: English-only static labels for AI TOOL tab (SPA + Library panel)
- Replace all Japanese-hardcoded labels in templates/index.html AI TOOL section with English
- Replace all Japanese-hardcoded labels in node_sets_menu.js AI tab (HTML + JS toast/status strings)
- Rename VLM subtab to TOOLS in Library panel subtab list

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-20 10:52:20 +09:00
ketle-manandClaude Sonnet 4.6 66f46af8b6 v0.3.14: AI TOOL tab 3-pane layout + RAW JSON color customization
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-20 10:34:17 +09:00
ketle-manandClaude Sonnet 4.6 95266a20b8 v0.3.13: AI tab (Translation, VLM, Settings) for SPA and Library panel
- Add A tab to SPA (templates/index.html) with Translation, VLM, Settings sub-tabs
- Add new static/js/ai-tab.js module (Ollama / LM Studio backends, full i18n via t())
- Add A tab to Workflow Studio Library side panel (node_sets_menu.js)
- Settings shared between SPA and Library panel via localStorage (wfm_ai_settings)
- URL security: validate backend URL with new URL() before any network call
- Rename ollamaSettings to 'Ollama Settings (Prompt Tab)' in EN/JA/ZH to distinguish from AI tab
- Add AI tab help card and helpSidepanel16 to Help tab (index.html + i18n.js + app.js)
- Update docs/6_ws_library.png, README.md (v0.3.13), DEVLOG.md

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-19 14:42:40 +09:00
ketle-manandClaude Sonnet 4.6 d54234b18d v0.3.12: Raw JSON search, workflow analyzer extended model detection, README screenshots refresh
- GenerateUI: always-visible search bar in Raw JSON panel (match count, ↑/↓ nav, Escape/✕ clear, orange/yellow highlights, scroll sync)
- workflow_analyzer: CLIPLoader type-field detection (_CLIP_TYPE_TO_MODEL), subgraph node scanning, UnetLoaderGGUF support, NewBie/Ovis/HiDream/Wan/Cosmos/Lumina added
- README: screenshots replaced with 8 feature-focused images; v0.3.12 changelog

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-18 13:46:59 +09:00
ketle-manandClaude Sonnet 4.6 4298fd9ea2 v0.3.11: Metadata tab extended loader support + Settings text size slider
- metadata-tab.js: add UnetLoaderGGUF/UNETLoaderGGUF as Diffusion Model
  and QuadrupleCLIPLoader as Text Encoder (was already in node_sets_menu.js
  for the I tab; now consistent across both Metadata tab and side panel)
- settings-tab.js: add applyTextareaFontSize() + Text Size section (10-28px
  slider that applies to all 8 prompt/chat textareas at once)
- app.js: apply saved textareaFontSize on page load alongside theme
- templates/index.html: update help text for Metadata and Settings tabs
- README/DEVLOG: v0.3.11 documentation

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-17 16:03:10 +09:00
ketle-manandClaude Sonnet 4.6 b8b4a65881 v0.3.10: Information tab drag-to-canvas, extended node type support, bug fixes
- Add drag & drop from I tab (model/lora/Prompts) to ComfyUI canvas
  - model sub-tab: places CheckpointLoaderSimple / VAELoader / UNETLoader / CLIPLoader
  - lora sub-tab: drag individual LoRA → LoraLoader; Multiple LORA section → Lora Loader (LoraManager)
  - Prompts sub-tab: drag prompt → CLIPTextEncode with text pre-filled
  - Double-click also places nodes at canvas center
- Add UnetLoaderGGUF / UNETLoaderGGUF detection as Diffusion Model
- Add QuadrupleCLIPLoader (HiDream, 4-CLIP workflows) detection as Text Encoder
- Fix CLIPLoader widget name in MODEL_NODE_MAP (clip_name1 → clip_name)
- Fix Information tab preview area height (fixed 110px, prevents list compression)
- Update help (index.html, app.js, i18n.js EN/JA/ZH) with new drag features
- Update README and DEVLOG for v0.3.10

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-17 12:25:37 +09:00
ketle-manandClaude Sonnet 4.6 0015638874 v0.3.9: side panel I tab + top bar icon fix
- Add Information (I) tab to ComfyUI side panel: drop PNG/WebP/JSON to
  inspect model, LoRA, and prompt metadata without leaving the canvas;
  sub-tabs: model / lora / Prompts with full-text preview and Copy button
- Shorten side panel tab labels to W / N / P / M / I with full name on hover
- Fix top bar icons invisible in newer ComfyUI: remove early-return guard
  that skipped SVG injection when Iconify had already converted the MDI
  class to an inline SVG; replace MutationObserver with simple rAF retry
- Update README, DEVLOG, help text (EN/JA/ZH), and index.html for v0.3.9

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-16 13:48:37 +09:00
ketle-manandClaude Sonnet 4.6 a48d9c1437 v0.3.8: Metadata tab - data9 workflow support and unclassified prompt text type
- Extended extractPromptsFromNodeSet to resolve link sources from any STRING-output
  node (ComfySwitchNode, PrimitiveStringMultiline, etc.) without type restriction
- Added fallback for SamplerCustomAdvanced (no positive/negative inputs): return
  textMap contents as texts[] instead of null
- Extended step4 PrimitiveStringMultiline and step7 final fallback to search
  subgraph nodes via collectAllNodes
- Added "text" prompt type (no POS/NEG badge) for cases where polarity cannot be
  determined; buildPromptItem and handleFile updated accordingly
- Added metaPromptText i18n key (EN/JA/ZH)
- Updated README (v0.3.8, feature description) and DEVLOG

Supported in data9: flux2_fp8, flux2_klein_4b_distilled, ernie_image,
qwen_image_edit_2511, wan2_2_14B_animate

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-16 00:32:49 +09:00
ketle-manandClaude Sonnet 4.6 48303e1452 docs: update README and DEVLOG for v0.3.7
README:
- Bump version badge to 0.3.7
- Update Metadata Tab feature section: subgraph support, expanded
  format list, updated prompt extraction description
- Add v0.3.7 changelog entry

DEVLOG:
- Append i18n/HTML text update notes to v0.3.7 entry

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-15 23:05:56 +09:00
ketle-manandClaude Sonnet 4.6 b0171add24 docs: update Metadata tab format note and help text (EN/JA/ZH)
- metaFormatTodo: replace "more formats planned" with note that
  Flux.2 / Qwen-Image / Z-Image subgraph workflows are now supported
- helpMetadata5: list Flux.2 / Qwen-Image / Z-Image explicitly
- Update static fallback text in index.html accordingly

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-15 23:03:17 +09:00
85 changed files with 29049 additions and 1065 deletions
+15
View File
@@ -185,3 +185,18 @@ os.environ["HF_HOME"] = "D:\\hf_cache"
5. `INPUT_TYPES` 変更時は `widgets_values` も同時更新
6. 削除した依存への参照が残っていないか grep で確認
7. ComfyUI完全再起動 → ワークフロー読み込み → エンドツーエンド実行確認
---
## リリース手順
コミット・プッシュ・GitHub リリース(`gh release create`)を行う際は、**必ず以下の順序**で実施する。
1. `pyproject.toml` の `version` を新バージョン番号に更新してステージングに含める
2. `README.md` のバージョンバッジを更新(`![Version](https://img.shields.io/badge/version-X.Y.Z-green)`)
3. `README.md` の Changelog に新バージョンのエントリを追加
4. `DEVLOG.md` の先頭に変更詳細エントリを追加
5. 上記すべてを同一コミットにまとめてプッシュ
6. `gh release create vX.Y.Z` でリリースを作成
`pyproject.toml` のバージョン変更が GitHub Actions のトリガー(`paths: pyproject.toml`)になっており、ComfyUI Registry への自動公開もここで行われる。バージョン更新を忘れると Registry に反映されない。
+2032
View File
File diff suppressed because it is too large Load Diff
+301 -46
View File
@@ -1,52 +1,65 @@
# 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) — the panel title highlights blue; drag it onto the canvas to load the workflow
- View metadata from images / JSON, then drop the detected models and prompts onto the canvas
- Built-in AI tools (translation and more)
![Workflow Studio](https://img.shields.io/badge/ComfyUI-Custom_Node-blue)
![Version](https://img.shields.io/badge/version-0.3.6-green)
![Version](https://img.shields.io/badge/version-0.3.40-green)
## Screenshots
| Workflow Tab | GenerateUI Tab |
| Workflow Tab | Models Tab |
|:---:|:---:|
| ![Workflow](docs/screenshot_workflow.png) | ![GenerateUI](docs/screenshot_generate.png) |
| ![Workflow Tab](docs/1_workflowtab.png) | ![Models Tab](docs/2_modelstab.png) |
| Prompt Tab | Metadata Tab |
| Prompt Input Assistance | Gen UI Feeder |
|:---:|:---:|
| ![Prompt](docs/screenshot_prompt.png) | ![Metadata](docs/screenshot_metadata.png) |
| ![Prompt Input Assistance](docs/3_PromptInputAssistance.png) | ![Gen UI Feeder](docs/4_GenUI_feeder.png) |
| Settings Tab | Help & Support Tab |
| GenUI LoRA Stack | GenUI Batch |
|:---:|:---:|
| ![Settings](docs/screenshot_settings.png) | ![Help](docs/screenshot_help.png) |
| ![GenUI LoRA Stack](docs/9_GenUI_LoraStack.png) | ![GenUI Batch](docs/10_GenUI_Batch.png) |
| Nodes Tab | Models Tab |
| Models Multi-select Menu | Top Bar |
|:---:|:---:|
| ![Nodes](docs/screenshot_nodes.png) | ![Models](docs/screenshot_models.png) |
| ![Models Multi-select Menu](docs/11_multiple_select_menu.png) | ![Top Bar](docs/5_topbar.png) |
| Gallery Tab | Nodes Tab |
| WS Library | Library Information |
|:---:|:---:|
| ![Gallery](docs/screenshot_gallery.png) | ![Nodes](docs/screenshot_nodes.png) |
| ![WS Library](docs/6_ws_library.png) | ![Library Information](docs/7_library_Infomation.png) |
| Workflow Studio Library (ComfyUI) | ComfyUI Integration |
| Customize | |
|:---:|:---:|
| ![Workflow Studio Library](docs/screenshot_wf_node_library.png) | ![ComfyUI Top Bar](docs/screenshot_comfyui_topbar.png) |
| ![Customize](docs/8_Customize.png) | |
---
## Features
### Workflow Tab
- **Thumbnail / Card / Table views** — switch between view modes to browse your workflow library
- **Thumbnail / Table views** — switch between view modes to browse your workflow library
- **Thumbnail side panel** — preview workflow canvas snapshots in the side panel
- **Badge filtering** — filter by user-defined badges (free labels you assign to each workflow)
- **Search** — full-text search across workflow names and metadata
- **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
- **Default view setting** — persist your preferred view mode (Thumbnail / Card / Table)
- **Import / Export** — import workflows from files or clipboard; **Send to Canvas** button stores the selected workflow for title-drag onto the ComfyUI canvas
- **Default view setting** — persist your preferred view mode (Thumbnail / Table)
### Canvas Snapshot (v0.1.2)
- **One-click capture** — click the camera button in ComfyUI's top bar to snapshot the current workflow canvas
@@ -55,14 +68,19 @@ Browse, organize, and execute workflows directly from a dedicated studio interfa
- **Auto-import** — the captured workflow is automatically imported and appears in the Workflow tab
### GenerateUI Tab (v0.3.5)
- **4-tab layout** — Input / Model / Settings / Feeder tabs; Input, Model, and Settings each include a Raw JSON column on the right for instant preview and direct editing
- **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
- **Always-visible Raw JSON** — edit the API-format JSON directly from any tab with syntax highlighting; Apply button reloads the workflow
- **Always-visible Raw JSON** — edit the API-format JSON directly from any tab with syntax highlighting; Apply button reloads the workflow; built-in **search bar** (always shown) finds all matches as you type with count display (`3/12`); navigate with ↑/↓ buttons or Enter / Shift+Enter; Escape or ✕ clears; current match highlighted in orange, other matches in yellow
- **One-click generation** — queue prompts to ComfyUI without leaving the studio
- **Seed control** — randomize, lock, or manually set seeds; seed input and mode selector stacked vertically for readability
- **Checkpoint Batch** — enable via checkbox in the right panel to sequentially generate with every checkpoint model; select checkpoints by folder from the dropdown (check a folder to select all its files, expand with ▶ for individual file selection, supports any subfolder depth); Filter input to search; All / None buttons for quick selection; **Pause/Resume** suspends processing between models; Stop aborts after the current generation; amber progress bar tracks per-model progress
- **Batch type selector** — check one of the column header checkboxes in the Batch Queue pane (Checkpoint / Lora / Prompt / Workflow) to activate that batch type; only one type can be active at a time; the Batch panel below Generate shows the active type, progress, and Pause/Resume/Stop controls
- **Batch tab** (v0.3.18) — dedicated 3-pane layout for assembling the batch queue:
- **Left pane** — file-tree checkpoint selection; Filter input to search; All / None buttons; initial state is all unchecked
- **Center pane** — group-based selection with inner tabs (Checkpoint | Lora | Prompt | Workflow); Checkpoint/Lora groups come from the Models tab, Prompt groups from the Prompt tab, Workflow groups from the Workflow tab — check a group to add all its members, expand ▶ to select individually
- **Right pane (Batch Queue)** — shows items queued for each batch type; column headers (Checkpoint / Lora / Prompt / Workflow) each have a checkbox — check one to activate that batch type (radio behavior: only one at a time); count shown at top
- **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
@@ -92,15 +110,15 @@ Requires the **[comfyui-image-feeder](https://github.com/ketle-man/comfyui-image
- **Wildcard input toolbar** — one-click buttons to insert `{|}`, `{n$|}`, `__|__`, `<lora::1:LBW=;>` and other wildcard syntax; wraps selected text when applicable
- **Wildcard file manager** — create, view, and edit `.txt` / `.yaml` wildcard files stored in `user/default/Workflow-Studio/wildcard/`; click a filename in the file picker to insert `__filename__` at cursor
### Metadata Tab (v0.3.6)
### Metadata Tab (v0.3.8)
- **3-column layout** — Drop zone (left) | Model info (center) | LoRA + Prompt (right)
- **File drop** — drop a ComfyUI-generated PNG / WebP or workflow JSON onto the drop zone (or click to open a file picker); PNG/WebP images are shown as a preview
- **Model extraction** — automatically extracts Checkpoint, VAE, Diffusion Model, and Text Encoder names from the embedded workflow metadata
- **Model extraction** — automatically extracts Checkpoint, VAE, Diffusion Model, and Text Encoder names from the workflow; supports both standard and subgraph-based workflows (Flux.2 Dev/Klein, Qwen-Image-Edit/2511/Layered, Z-Image Base/Turbo, Ernie Image, WAN2.2); node types covered: UNETLoader, UnetLoaderGGUF, UNETLoaderGGUF (e.g. HiDream GGUF), CLIPLoader, DualCLIPLoader, TripleCLIPLoader, QuadrupleCLIPLoader (e.g. HiDream 4-CLIP)
- **LoRA extraction** — lists all LoRA models with `strength_model / strength_clip` values
- **Prompt extraction** — lists positive and negative prompts with POS/NEG badges; click any entry to view the full text below
- **Prompt extraction** — lists prompts with POS / NEG badges when positive/negative can be determined; when distinction is not possible (e.g. `SamplerCustomAdvanced`, intermediate nodes, cross-level connections), prompts are shown without a badge as plain **Text**; click any entry to view the full text below
- **Prompt actions** — Copy to clipboard, **GenUI:P/N** (set GenerateUI positive/negative prompt), **Prompt:P/N** (set Prompt tab preset positive/negative)
- **Format support** — ComfyUI (PNG/WebP/JSON), SD WebUI, SD Forge, Fooocus; support for additional model types beyond SD1.5/SDXL/Illustrious is planned
- **Format note** — supported formats are always shown in the left column; planned formats are noted in amber
- **Format support** — ComfyUI PNG/WebP/JSON (standard + Flux.2 / Qwen-Image / Z-Image / Ernie Image / WAN2.2 subgraph workflows), SD WebUI, SD Forge, Fooocus
- **Format note** — supported formats and covered model types are always shown in the left column
### Settings Tab
- **2-column layout** — left column for all settings; right column shows the Theme panel fixed in place (sticky)
@@ -111,8 +129,12 @@ Requires the **[comfyui-image-feeder](https://github.com/ketle-man/comfyui-image
- **Gallery output directory** — configure which output folder the Gallery tab scans for images
- **Eagle connection** — set Eagle API endpoint for auto-save
- **Ollama connection** — configure Ollama server URL
- **CivitAI Host** — choose which site opens when clicking a model link: `civitai.com` (SFW only) or `civitai.red` (unrestricted); saved to `settings.json` and synced to `localStorage` for the Models tab to use without extra fetches
- **CivitAI API Key** — optional Bearer token for authenticated CivitAI access; stored in `settings.json` (excluded from data exports); environment variable `CIVITAI_API_KEY` takes priority if set
- **Default workflow** — set a workflow to auto-load on startup
- **Data Management** — export all plugin data (settings, metadata, prompts, etc.) to a single JSON file; import to restore data (useful when migrating or reinstalling)
- **Data Management** — export all plugin data (settings, metadata, prompts, etc.) to a single JSON file; import to restore data (useful when migrating or reinstalling); API keys are excluded from exports for security
- **Text Size** — one slider (10–28 px) adjusts font size for all prompt and chat textareas at once: Generate UI positive/negative prompts, AI Assistant chat input, Preset prompts, Wildcard prompt and file editor, and Metadata prompt full preview; takes effect immediately and saved with Save Settings
- **RAW JSON Colors** — customize the 6 syntax highlight colors for the Raw JSON editor in Generate UI: Default Text (base), Name/Scheduler (yellow), Title (pink), Width/Height (green), Prompt/Text (cyan), Image/File (red); changes apply immediately on color pick; Reset Defaults restores the original scheme; saved to `localStorage` under `wfm_settings.jsonColors` and applied on startup
- **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
@@ -126,7 +148,8 @@ Requires the **[comfyui-image-feeder](https://github.com/ketle-man/comfyui-image
- **Group management** — create, rename, delete groups and assign/remove images using the same 4-section panel as Models tab
- **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 stores it for title-drag to the ComfyUI canvas
- **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
@@ -141,39 +164,75 @@ 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 / Card / 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
- **CivitAI integration** — fetch model metadata by SHA256 hash, view base model, trained words, tags, and model page link
- **Batch CivitAI fetch** — one-click batch fetch for all models of a type with SSE progress streaming
- **Detail modal** — preview image, CivitAI info, thumbnail change via file upload
- **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; **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 add/remove from groups and permanent file deletion (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
### Workflow Studio Library (ComfyUI Side Panel) (v0.2.5)
- **Workflows tab** — browse favorite workflows (All / ★ Favorites / Groups / By Badge sub-tabs), ★ star shown for favorites in All view
- **Nodes tab** — browse favorite nodes (All / ★ Favorites / Groups / Sets / 📂 Category / 🧩 Package sub-tabs), ★ star shown for favorites in All view
### 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)
- **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/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)
- **Tab layout (W / N / P / M / I / A)** — compact single-letter tabs with full name shown on hover
- **W — Workflows tab** — browse favorite workflows (All / ★ Favorites / Groups / By Badge sub-tabs), ★ star shown for favorites in All view
- **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
- **Models tab** — browse installed models (All / ★ Favorites / Groups / By Type sub-tabs)
- **Prompts tab** — browse prompt presets with All / Favorites / Categories sub-tabs
- **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** — 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
- **Title drag (Send to Canvas)** — after clicking "Send to Canvas" (Workflow tab toolbar / detail modal) or "Copy & Send Canvas" (Gallery tab JSON panel), the "Workflow Studio Library" title highlights blue with a green ● indicator; drag the title onto the canvas to load the stored workflow; title resets automatically after loading
- **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
---
@@ -194,6 +253,22 @@ Restart ComfyUI after installation.
---
## Sample Workflows
Sample workflows are included in the `workflows/` folder. You can open them directly in ComfyUI via drag & drop, or load them from the Workflow tab.
> **Note:** Some sample workflows require additional custom nodes.
> If a node is shown as missing (red/unknown) after loading, install the required custom nodes via **ComfyUI Manager** or by cloning the repository from GitHub into your `ComfyUI/custom_nodes/` directory.
>
> ```bash
> cd ComfyUI/custom_nodes
> git clone <repository-url>
> ```
>
> After installation, restart ComfyUI to activate the new nodes.
---
## Usage
### Launch
@@ -228,7 +303,8 @@ Click the **camera icon** (next to the W button) in ComfyUI's top bar to capture
### Optional
- **[Ollama](https://ollama.com/)** — for AI chat assistant and translation features
- **[Ollama](https://ollama.com/)** — for AI chat assistant, translation, and VLM features
- **[LM Studio](https://lmstudio.ai/)** — alternative backend for translation and VLM (OpenAI-compatible API)
- **[Eagle](https://eagle.cool/)** — for auto-saving generated images with metadata
---
@@ -245,11 +321,189 @@ Click the **camera icon** (next to the W button) in ComfyUI's top bar to capture
## Changelog
### 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
- **4-type batch generation** — `_runBatchGenerate()` dispatches to Checkpoint (file-tree + group selection), Lora (group selection), Prompt (preset group items applied to positive/negative nodes), and Workflow (group selection, restores original workflow after batch); all types use the same generic `_runBatchLoop()` with pause/abort support
- **Help updated** — EN / JA / ZH strings updated for `helpWf1`, `helpModels2`, `helpGen11`, `helpGen13`, `helpGen14`
### v0.3.21
- **CivitAI Host setting** — new dropdown in Settings tab (CivitAI section): choose `civitai.com` (SFW only) or `civitai.red` (unrestricted); selection is saved to `settings.json` and synced to `localStorage` so the Models tab uses it immediately without extra server calls
- **CivitAI panel — Info / Sample sub-tabs** — the CivitAI side panel is split into two sub-tabs; Info tab contains model details and actions; Sample tab shows all sample images (count displayed in label); images open full-size in a new browser tab on click
- **Bug fix: model page URL for existing cache** — `modelId: null` entries (the majority of the cache) previously generated broken links (`/models?modelVersionId=…`); both the Python service and the JS renderer now fall back to `/{host}/model-versions/{versionId}` which redirects correctly to the model page; all 324 existing cache entries are fixed immediately without re-fetching
- **Help updated** — Batch tab entries (gen-12 / gen-13 / gen-14) and Settings entries (settings-11 Text Size / settings-12 RAW JSON Colors / settings-13 CivitAI Host) are now fully localized in EN / JA / ZH; `helpGen3` updated to reflect 5-tab layout; `helpGen11` rewritten to describe the Batch toggle; JA/ZH translations no longer contain untranslated English terms (Filter, Pause/Resume, Stop)
### v0.3.20
- **CivitAI panel — Type / Base Model / Hash display** — side panel CivitAI tab now shows a Type badge (e.g. CHECKPOINT, LORA), Base Model row, and Hash row (BLAKE3 preferred, SHA256 fallback from CivitAI API or local metadata); click the hash to copy the full value to clipboard
- **CivitAI panel — images open in new tab** — sample images in the CivitAI tab are now wrapped in links; clicking an image opens the full-size version in a new browser tab
- **CivitAI panel — 3-state UI** — the panel now distinguishes between "not yet checked" (blue fetch button), "checked but not found on CivitAI" (re-check button with a notice), and "found" (full info); no more ambiguity after running batch fetch
- **CivitAI tab click refresh** — clicking the CivitAI tab in the side panel now re-renders its content, ensuring the latest fetch state is always shown without needing to reselect the model
- **Bug fix: model page URL broken after batch fetch** — the batch `POST /model-versions/by-hash` endpoint can omit `model.id` inside the version object; `_extract_info` now falls back to the top-level `modelId` field so the model page link is always correct; existing cached entries with a broken URL are also fixed client-side from `modelId` + `versionId`
- **CivitAI cache — `fileHashes` field added** — `_extract_info` now stores the primary file's full hash map (BLAKE3, SHA256, AutoV2, etc.) so the Hash row is populated for newly fetched or refreshed models
### v0.3.19
- **CivitAI batch fetch — major speedup** — switched from one-by-one `GET` requests (0.5 s delay each) to `POST /model-versions/by-hash` batch endpoint; up to 100 hashes per request, reducing 100-model fetch from ~50 s to a few seconds
- **Retry with exponential backoff** — `fetch_by_hash` and the new batch POST both retry on HTTP 429 / 500 / 502 / 503 / 504 with 1 s → 2 s → 4 s delays (max 3 attempts), as recommended in the CivitAI API docs
- **CivitAI API key support** — optional Bearer token can be set in Settings tab (CivitAI API Key section); environment variable `CIVITAI_API_KEY` takes priority over the stored key; API keys are excluded from data exports
- **Richer metadata** — `_extract_info` now captures `nsfwLevel` (numeric), `air` (AIR URN identifier), `stats` (download count, thumbs-up/down), `updatedAt`, `publishedAt`, image dimensions / per-image NSFW level (`imageDetails`), and primary file precision / format (`fileMeta`)
- **Hash consistency** — cache keys use lowercase hex; API requests send uppercase hex as required by the CivitAI spec
- **Bug fix: CivitAI tab blank after batch fetch** — the `done` SSE event now applies `data.hashes` directly to `state.modelMetadata` so the side-panel CivitAI tab renders correctly even when the subsequent `fetchModelMetadata()` call races ahead of the server flush
### v0.3.18
- **Batch tab** — new 5th subtab in GenerateUI with a dedicated 3-pane layout for assembling checkpoint batch queues; left pane: file-tree checkpoint selection (filter, All/None, initially unchecked); center pane: group-based selection with inner tabs (Checkpoint / Lora / Prompt / Workflow — Lora/Prompt/Workflow coming soon); right pane: live Batch Queue preview combining both pane selections with duplicates removed
- **Checkpoint selector moved** — the checkpoint dropdown is removed from the right panel; selection is now done exclusively in the Batch tab left and center panes; the right panel retains only the enable/disable toggle and progress display
- **Group selection fix** — batch group selection now stores selected group names (not raw model names), so changes to group membership in the Models tab are always reflected in the queue without stale entries
- **Models tab bulk operations expanded** — bulk action bar now includes: Deselect All (clear all selections without exiting select mode), ★ Favorite / ☆ Unfavorite, +Badge / −Badge (apply or remove a badge from all selected models); existing group and delete operations unchanged
### v0.3.17
- **CivitAI SSL fix** — resolved `CERTIFICATE_VERIFY_FAILED` errors when fetching model info on Windows Portable Python environments; uses `certifi` CA bundle when available, falls back to system store, and disables verification only as a last resort with a warning log
- **Lora Manager support** — `Lora Loader (LoraManager)` nodes (ComfyUI-Lora-Manager) are now correctly converted from UI format to API format in the GenerateUI tab; the `loras` widget array is wrapped to `{"__value__": [...]}` as required by the node, enabling generation with LoRA Manager workflows
### v0.3.16
- **CivitAI preview fallback** — model cards and the detail panel's Info tab now display the first CivitAI image directly when no local preview file exists; if the backend download fails (e.g. network restriction server-side), the browser fetches the image URL from the CivitAI cache as a fallback so the preview is always shown after fetching
### v0.3.15
- **Sample workflows** — added `workflows/` directory containing 13 sample workflows (SD1.5 / SDXL / DWPose / Face Detailer / Image Editing) with PNG thumbnails, bundled in the package
- **CivitAI auto-preview** — when fetching CivitAI info (individual or batch), the first CivitAI image is automatically downloaded and saved as `{model_stem}.preview.png` if no preview exists; batch summary reports the count of auto-saved previews
- **TOOLS pane — Create Tags** — new task option in the VLM dropdown (both SPA AI TOOL tab and Library A tab): generates a comma-separated list of descriptive English tags from the image
### v0.3.14
- **AI TOOL tab redesign** — tab renamed from "A" to "AI TOOL"; sub-tab navigation removed in favor of a permanent 3-pane layout (Translation 40% | TOOLS 40% | Settings 20%) — all panes always visible simultaneously; "VLM" pane renamed to "TOOLS"
- **Settings — RAW JSON Colors** — new accordion section with 6 color pickers to customize the syntax highlight colors for the Raw JSON editor in Generate UI: Default Text, Name/Scheduler, Title, Width/Height, Prompt/Text, Image/File; changes apply immediately on color pick; Reset Defaults restores the original scheme; saved to `localStorage` under `wfm_settings.jsonColors` and applied on startup
- **Help tab updated** — AI TOOL tab card rewritten; Settings card updated with RAW JSON Colors entry; Library panel sidepanel-16 entry updated
### v0.3.13
- **AI Tab (A)** — new tab added to both the SPA and the Workflow Studio Library side panel (rightmost tab)
- **Translation sub-tab** — translate text via Ollama or LM Studio between Japanese, English, Chinese, or a custom Free language; ⇄ swap button exchanges both language selectors and text content simultaneously; language selections persisted automatically
- **VLM sub-tab** — drop zone (110px, matching the I tab) accepts images via drag & drop or click; task selector (Describe Image / Create Prompt); Run button streams result into output area with Copy button; Ollama uses `images:[base64]` payload, LM Studio uses `image_url` content block
- **Settings sub-tab** — backend radio (Ollama / LM Studio), API URL input, connection test with live status, model selector with refresh, Free language name fields (source and destination); saved to `localStorage` key `wfm_ai_settings` and shared between SPA and Library panel
- **URL security** — backend URL validated via `new URL()` to enforce `http://` or `https://` scheme before any network call
- **Settings Tab — Ollama section renamed** — "Ollama 設定" → "Ollama 設定(プロンプトタブ)" to distinguish it from the new AI tab's settings
- **Help Tab updated** — added AI Tab (A) feature card and Library panel A tab entry; i18n support in EN/JA/ZH
### v0.3.12
- **GenerateUI — Raw JSON search** — always-visible search bar above the Raw JSON editor; finds all matches as you type with match count (`3/12`); navigate forward/back with ↑/↓ buttons, Enter / Shift+Enter, or Escape / ✕ to clear; current match highlighted in orange, other matches in yellow; search overlay syncs with editor scroll and stays updated while editing
- **Workflow analyzer — extended model type detection** — added CLIPLoader `type` field mapping to model family (`flux`, `hidream_i`, `wan`, `cosmos`, `lumina`, `ovis`, etc.) via `_CLIP_TYPE_TO_MODEL`; subgraph nodes (`definitions.subgraphs`) now scanned for model detection; `UnetLoaderGGUF` and similar loaders matched via `"UnetLoader" in ntype`; new families added: NewBie, Ovis, HiDream, Wan, Cosmos, Lumina; model-name detection refactored into reusable `_detect_model_type_from_name()`
- **Screenshots refreshed** — replaced tab-by-tab screenshots with 8 feature-focused images
### v0.3.11
- **Metadata Tab — extended loader support** — `metadata-tab.js` now recognizes `UnetLoaderGGUF` and `UNETLoaderGGUF` as Diffusion Model (e.g. HiDream GGUF workflows), and `QuadrupleCLIPLoader` as Text Encoder (e.g. HiDream 4-CLIP); previously these were detected only in the side panel I tab, not in the Metadata tab itself
- **Settings Tab — Text Size** — new slider (10–28 px) in the Settings tab adjusts font size for all prompt and chat text areas at once: Generate UI positive/negative prompts, AI Assistant chat input, Preset prompts, Wildcard text area and file editor, and Metadata prompt full preview; applied immediately on drag and persisted with Save Settings
### v0.3.10
- **Information tab — drag to canvas** — model, lora, and Prompts sub-tabs in the side panel I tab now support drag & drop onto the ComfyUI canvas; double-click also places nodes at canvas center
- model sub-tab: each item places the corresponding loader node (Checkpoint → `CheckpointLoaderSimple`, VAE → `VAELoader`, Diffusion Model → `UNETLoader`, Text Encoder → `CLIPLoader`)
- lora sub-tab: drag individual LoRA to place `LoraLoader`; **Multiple LORA** section (shown for 1+ LoRAs) places all LoRAs in a single `Lora Loader (LoraManager)` node
- Prompts sub-tab: drag a prompt to place `CLIPTextEncode` with the full text pre-filled
- **Extended node type support** — `UnetLoaderGGUF` / `UNETLoaderGGUF` now detected as Diffusion Model; `QuadrupleCLIPLoader` (HiDream and similar 4-CLIP workflows) now detected as Text Encoder
- **Bug fix: CLIPLoader widget name** — `textencoder` type in `MODEL_NODE_MAP` was incorrectly using `clip_name1` (DualCLIPLoader's widget) instead of `clip_name`; Text Encoder models now drop with the correct filename
- **Preview area fixed height** — Information tab drop zone fixed at 110px so model/prompt lists are no longer compressed when a large image is loaded
### v0.3.9
- **Side panel I tab** — new Information tab in the Workflow Studio Library side panel; drop a ComfyUI PNG/WebP/JSON directly in the panel to inspect models, LoRAs, and prompts without opening the Metadata tab; sub-tabs: model / lora / Prompts with full-text preview and Copy button
- **Side panel tab redesign** — tabs shortened to single letters (W / N / P / M / I) with full name shown on hover
- **Bug fix: top bar icons** — icons (Workflow Studio / camera / Node Sets) were invisible in newer ComfyUI versions because Iconify converted the MDI CSS class to an inline SVG before the custom SVG could be injected; fixed by removing the early-return guard and adopting the same simple `requestAnimationFrame` retry pattern used by lora-manager
### v0.3.8
- **Metadata Tab: extended subgraph support** — added extraction for Flux.2 Dev fp8 (`SamplerCustomAdvanced`), Flux.2 Klein 4B Distilled (image edit), Ernie Image, Qwen-Image-Edit 2511 (`TextEncodeQwenImageEditPlus`), and WAN2.2 14B Animate (top-level CLIPTextEncode + subgraph KSampler)
- **Prompt type: Text (no badge)** — when positive/negative polarity cannot be determined (indirect sampler connections, cross-level links, `PrimitiveStringMultiline` etc.), prompts are listed without a POS/NEG badge; action buttons still work normally
- **Prompt extraction improvements** — `extractPromptsFromNodeSet` now resolves link sources from any STRING-output node (e.g. `ComfySwitchNode`, `PrimitiveStringMultiline`) without type restriction; `PrimitiveStringMultiline` search and final text-encoder fallback both extended to include subgraph nodes via `collectAllNodes`
- **i18n** — added `metaPromptText` key (EN: "Text" / JA: "テキスト" / ZH: "文本")
### v0.3.7
- **Metadata Tab: subgraph workflow support** — Flux.2 (Dev fp8 / Klein), Qwen-Image-Edit (/ 2511 / Layered), and Z-Image (Base / Turbo) official templates now correctly extract models and prompts; these use ComfyUI's `definitions.subgraphs` format with `UNETLoader`, `CLIPLoader`, and `VAELoader` inside the subgraph
- **Prompt extraction improvements** — 7-stage fallback chain: ImageMetadataPromptLoader → WFS_PromptText → top-level CLIPTextEncode+KSampler → `PrimitiveStringMultiline` (flux2-klein) → subgraph CLIPTextEncode+KSampler → PromptStyler → all CLIPTextEncode text
- **MarkdownNote model fallback** — `extractMarkdownNoteModels()` parses `**section** → - [model](url)` patterns from MarkdownNote nodes as a supplemental model source
- **Format note updated** — "Flux.2 / Qwen-Image / Z-Image subgraph workflows supported" (EN/JA/ZH)
### v0.3.6
- **Metadata Tab** — new tab (between Prompt and Gallery) that extracts model and prompt information from ComfyUI-generated PNG/WebP images and workflow JSON files; 3-column layout: drop zone with image preview (left), Checkpoint/VAE/Diffusion Model/Text Encoder lists (center), LoRA list with strength values + Prompt list with full-text viewer (right)
- **Prompt action buttons** — Copy, GenUI:P/N (set GenerateUI prompts), Prompt:P/N (set Prompt tab preset prompts) directly from the extracted prompt text
- **SDXL Prompt Styler support** — improved prompt extraction resolves `PromptStyler → CLIPTextEncode` link chains in both LiteGraph and API workflow formats
- **Format support** — ComfyUI (PNG/WebP/JSON), SD WebUI, SD Forge, Fooocus; format note in the left column indicates planned support for additional model types
- **Format support** — ComfyUI (PNG/WebP/JSON), SD WebUI, SD Forge, Fooocus
### v0.3.5
- **Feeder subtab** — new subtab in GenerateUI for controlling [comfyui-image-feeder](https://github.com/ketle-man/comfyui-image-feeder) nodes; left pane: node selector + all ImageFeeder parameters + presets + Run/Stop controls; center pane: folder tree, image grid with checkbox selection, and preview panel
@@ -413,7 +667,7 @@ ComfyUI-Workflow-Studio/
│ ├── settings_service.py # Settings persistence
│ └── png_extractor.py # PNG metadata extraction
├── templates/
│ └── index.html # SPA template (Workflow/GenerateUI/Prompt/Metadata/Gallery/Nodes/Models/Settings/Help)
│ └── index.html # SPA template (Workflow/GenerateUI/Prompt/Metadata/Gallery/Nodes/Models/Settings/Help/AI)
├── static/
│ ├── favicon.svg # Browser tab icon (W+S Wave)
│ ├── css/main.css # Styles
@@ -428,6 +682,7 @@ ComfyUI-Workflow-Studio/
│ ├── 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)
│ ├── comfyui-workflow.js # UI-to-API format conversion
│ ├── comfyui-editor.js # Dynamic parameter editor
│ ├── json-highlight.js # JSON syntax highlighting
@@ -450,6 +705,6 @@ 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
Binary file not shown.

After

Width:  |  Height:  |  Size: 193 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 16 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 330 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.7 MiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 72 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 278 KiB

BIN
View File
Binary file not shown.

After

Width:  |  Height:  |  Size: 20 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 64 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 35 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 90 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 48 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 116 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 100 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 25 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 81 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 975 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 160 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 45 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 30 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 117 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 148 KiB

+5
View File
@@ -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"
+89 -2
View File
@@ -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 ─────────────────────────────────────────
@@ -150,10 +152,24 @@ async def handle_civitai_fetch(request: web.Request) -> web.Response:
"message": "Model not found on CivitAI"
})
# Auto-set preview if none exists and CivitAI has images
preview_saved = False
if info.get("images"):
has_preview = await asyncio.to_thread(_service.find_preview_image, model_type, model_name)
if not has_preview:
image_url = info["images"][0]
preview_path = file_path.parent / (file_path.stem + ".preview.png")
preview_saved = await asyncio.to_thread(
CivitaiService.download_image, image_url, preview_path
)
if preview_saved:
logger.info("Auto-saved preview for %s from CivitAI", model_name)
return web.json_response({
"status": "ok",
"sha256": sha256,
"civitai": info,
"preview_saved": preview_saved,
})
except Exception as e:
logger.error("CivitAI fetch error: %s", e)
@@ -269,6 +285,28 @@ async def handle_civitai_batch(request: web.Request) -> web.Response:
all_meta[mname]["sha256"] = sha
_service._save_metadata(all_meta)
# Auto-set previews for models without preview image
dirs = _get_model_dirs(model_type)
preview_saved_count = 0
for model_name, result in results.items():
civitai = result.get("civitai")
if not civitai or not civitai.get("images"):
continue
if _service.find_preview_image(model_type, model_name):
continue
model_file = None
for d in dirs:
p = d / model_name
if p.is_file():
model_file = p
break
if not model_file:
continue
preview_path = model_file.parent / (model_file.stem + ".preview.png")
if CivitaiService.download_image(civitai["images"][0], preview_path):
preview_saved_count += 1
logger.info("Auto-saved preview for %s from CivitAI", model_name)
# Send final result
summary = {
"total": len(model_files),
@@ -276,6 +314,7 @@ async def handle_civitai_batch(request: web.Request) -> web.Response:
"not_found": sum(1 for r in results.values() if r.get("sha256") and not r.get("civitai")),
"errors": sum(1 for r in results.values() if r.get("error")),
"hashes": {name: r.get("sha256") for name, r in results.items() if r.get("sha256")},
"preview_saved": preview_saved_count,
}
await response.write(send_sse("done", summary))
await response.write_eof()
@@ -307,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)
@@ -346,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
@@ -355,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)
@@ -529,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)
+9 -2
View File
@@ -179,13 +179,20 @@ def _load_data_file(filename: str):
return None
# エクスポートから除外するsettings.jsonのキー(APIキーなどの機密情報)
_SETTINGS_EXPORT_EXCLUDE = {"civitai_api_key"}
def _build_export_bundle() -> dict:
"""Collect all data files into a single export bundle."""
bundle = {"__version": 1, "__source": "ComfyUI-Workflow-Studio"}
for filename in _DATA_FILES:
data = _load_data_file(filename)
if data is not None:
bundle[filename] = data
if data is None:
continue
if filename == "settings.json" and isinstance(data, dict):
data = {k: v for k, v in data.items() if k not in _SETTINGS_EXPORT_EXCLUDE}
bundle[filename] = data
return bundle
+214
View File
@@ -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)
+289 -65
View File
@@ -3,6 +3,8 @@
import hashlib
import json
import logging
import ssl
import time
from pathlib import Path
from urllib.request import Request, urlopen
from urllib.error import URLError, HTTPError
@@ -11,9 +13,48 @@ from ..config import DATA_DIR
logger = logging.getLogger(__name__)
def _make_ssl_context():
"""Return an SSL context with CA verification.
1. certifi CA bundle (available in virtually all ComfyUI envs via torch→requests→certifi)
2. System default SSL context (OS certificate store)
Returns None if both fail — callers fall back to urlopen without context
(Python's own default, which also uses certifi when available).
SSL verification is never disabled to avoid MitM exposure.
"""
try:
import certifi
return ssl.create_default_context(cafile=certifi.where())
except Exception:
pass
try:
return ssl.create_default_context()
except Exception:
pass
logger.warning("CivitAI: could not build SSL context; falling back to urllib default")
return None
_SSL_CONTEXT = _make_ssl_context # lazy sentinel
def _get_ssl_context():
global _SSL_CONTEXT
if callable(_SSL_CONTEXT):
_SSL_CONTEXT = _make_ssl_context()
return _SSL_CONTEXT
CIVITAI_API_BASE = "https://civitai.com/api/v1"
CIVITAI_CACHE_FILE = DATA_DIR / "civitai_cache.json"
# HTTPステータスコード: 指数バックオフでリトライする対象
_RETRY_CODES = {429, 500, 502, 503, 504}
_MAX_RETRIES = 3
# POST /model-versions/by-hash は最大100件まで一括送信可能
_BATCH_CHUNK_SIZE = 100
class CivitaiService:
"""Fetch and cache CivitAI model metadata."""
@@ -21,6 +62,8 @@ class CivitaiService:
def __init__(self):
self._cache = None
# ── キャッシュ管理 ────────────────────────────────────────
def _load_cache(self):
if self._cache is not None:
return self._cache
@@ -42,12 +85,37 @@ class CivitaiService:
def get_cached(self, sha256_hash):
"""Return cached CivitAI data for a given hash, or None."""
cache = self._load_cache()
return cache.get(sha256_hash)
return cache.get(sha256_hash.lower())
def get_all_cached(self):
"""Return the full cache dict."""
return self._load_cache()
# ── APIキー / ヘッダー ────────────────────────────────────
@staticmethod
def _get_api_key():
"""Return CivitAI API key. Env var CIVITAI_API_KEY takes priority over settings.json."""
import os
env_key = os.environ.get("CIVITAI_API_KEY", "").strip()
if env_key:
return env_key
try:
from ..services.settings_service import SettingsService
return SettingsService().load().get("civitai_api_key", "").strip() or None
except Exception:
return None
def _build_headers(self):
"""Build request headers, optionally including Bearer token."""
headers = {"User-Agent": "ComfyUI-Workflow-Studio/1.0"}
api_key = self._get_api_key()
if api_key:
headers["Authorization"] = f"Bearer {api_key}"
return headers
# ── ハッシュ計算 ──────────────────────────────────────────
@staticmethod
def calculate_sha256(file_path, chunk_size=65536):
"""Calculate SHA256 hash of a file."""
@@ -61,43 +129,130 @@ class CivitaiService:
if not chunk:
break
h.update(chunk)
return h.hexdigest()
return h.hexdigest() # 小文字16進数
# ── 単体フェッチ (GET) ────────────────────────────────────
def fetch_by_hash(self, sha256_hash):
"""Fetch model version info from CivitAI by SHA256 hash.
"""Fetch model version info from CivitAI by SHA256 hash (GET).
429/5xx は指数バックオフでリトライ。
Returns dict with model info, or None if not found.
Caches successful results.
"""
# Check cache first
sha256_lower = sha256_hash.lower()
cache = self._load_cache()
if sha256_hash in cache:
return cache[sha256_hash]
if sha256_lower in cache:
return cache[sha256_lower]
url = f"{CIVITAI_API_BASE}/model-versions/by-hash/{sha256_hash}"
try:
req = Request(url, headers={"User-Agent": "ComfyUI-Workflow-Studio/1.0"})
with urlopen(req, timeout=15) as resp:
data = json.loads(resp.read().decode("utf-8"))
url = f"{CIVITAI_API_BASE}/model-versions/by-hash/{sha256_hash.upper()}"
if not data or "id" not in data:
for attempt in range(_MAX_RETRIES):
try:
req = Request(url, headers=self._build_headers())
with urlopen(req, timeout=15, context=_get_ssl_context()) as resp:
data = json.loads(resp.read().decode("utf-8"))
if not data or "id" not in data:
return None
info = self._extract_info(data)
cache[sha256_lower] = info
self._save_cache()
return info
except HTTPError as e:
if e.code == 404:
logger.debug("CivitAI: model not found for hash %s", sha256_hash[:16])
return None
if e.code in _RETRY_CODES and attempt < _MAX_RETRIES - 1:
wait = 2 ** attempt
logger.warning("CivitAI %s: retrying in %ss (attempt %d/%d)",
e.code, wait, attempt + 1, _MAX_RETRIES)
time.sleep(wait)
continue
logger.warning("CivitAI API error: %s %s", e.code, e.reason)
return None
except (URLError, Exception) as e:
if attempt < _MAX_RETRIES - 1:
wait = 2 ** attempt
logger.warning("CivitAI request failed: %s — retrying in %ss", e, wait)
time.sleep(wait)
continue
logger.warning("CivitAI request failed: %s", e)
return None
# Extract useful fields
info = self._extract_info(data)
cache[sha256_hash] = info
self._save_cache()
return info
return None
except HTTPError as e:
if e.code == 404:
logger.debug("CivitAI: model not found for hash %s", sha256_hash[:16])
return None
logger.warning("CivitAI API error: %s %s", e.code, e.reason)
return None
except (URLError, Exception) as e:
logger.warning("CivitAI request failed: %s", e)
return None
# ── 一括フェッチ (POST) ───────────────────────────────────
def _batch_fetch_post(self, sha256_hashes):
"""POST /model-versions/by-hash でハッシュリストを一括取得(最大100件/リクエスト)。
レスポンスの files[].hashes.SHA256 でリクエストのハッシュと照合する。
Returns: { sha256_lower: info_or_none }
"""
if not sha256_hashes:
return {}
url = f"{CIVITAI_API_BASE}/model-versions/by-hash"
results = {h.lower(): None for h in sha256_hashes}
cache = self._load_cache()
for chunk_start in range(0, len(sha256_hashes), _BATCH_CHUNK_SIZE):
chunk = sha256_hashes[chunk_start:chunk_start + _BATCH_CHUNK_SIZE]
chunk_lower = {h.lower() for h in chunk}
for attempt in range(_MAX_RETRIES):
try:
body = json.dumps([h.upper() for h in chunk]).encode("utf-8")
req = Request(
url,
data=body,
headers={**self._build_headers(), "Content-Type": "application/json"},
method="POST",
)
with urlopen(req, timeout=30, context=_get_ssl_context()) as resp:
versions = json.loads(resp.read().decode("utf-8"))
# 各バージョンを files[].hashes.SHA256 でリクエストのハッシュと照合
for version_data in versions:
info = self._extract_info(version_data)
matched = False
for f in version_data.get("files", []):
file_sha256 = f.get("hashes", {}).get("SHA256", "").lower()
if file_sha256 in chunk_lower:
cache[file_sha256] = info
results[file_sha256] = info
matched = True
break
if not matched:
# files にハッシュがない場合は versionId で照合を試みる
logger.debug("CivitAI: could not match version %s to a requested hash",
version_data.get("id"))
break # チャンク成功
except HTTPError as e:
if e.code in _RETRY_CODES and attempt < _MAX_RETRIES - 1:
wait = 2 ** attempt
logger.warning("CivitAI batch POST %s: retrying in %ss", e.code, wait)
time.sleep(wait)
continue
logger.warning("CivitAI batch POST error: %s %s", e.code, e.reason)
break
except (URLError, Exception) as e:
if attempt < _MAX_RETRIES - 1:
wait = 2 ** attempt
logger.warning("CivitAI batch POST failed: %s — retrying in %ss", e, wait)
time.sleep(wait)
continue
logger.warning("CivitAI batch POST failed: %s", e)
break
self._save_cache()
return results
# ── 情報抽出 ──────────────────────────────────────────────
@staticmethod
def _extract_info(data):
@@ -106,101 +261,170 @@ class CivitaiService:
images = data.get("images", [])
files = data.get("files", [])
# Get primary file info
primary_file = None
for f in files:
if f.get("primary"):
primary_file = f
break
# プライマリファイルを特定
primary_file = next((f for f in files if f.get("primary")), None)
if not primary_file and files:
primary_file = files[0]
# Get image URLs (first 5)
image_urls = []
# 画像情報(URL・寸法・NSFWレベル)を最大5件取得
image_list = []
for img in images[:5]:
url = img.get("url", "")
if url:
# Optimize for thumbnail
optimized = url.replace("/original=true", "/width=450,optimized=true")
image_urls.append(optimized)
img_url = img.get("url", "")
if not img_url:
continue
image_list.append({
"url": img_url,
"width": img.get("width"),
"height": img.get("height"),
"nsfwLevel": img.get("nsfwLevel", 0),
})
# プライマリファイルのメタ情報(精度・フォーマット)
file_meta = {}
file_hashes = {}
if primary_file:
pm = primary_file.get("metadata", {})
file_meta = {
"fp": pm.get("fp"),
"size": pm.get("size"),
"format": pm.get("format"),
}
# BLAKE3, SHA256, AutoV2 等のハッシュ
file_hashes = primary_file.get("hashes", {})
stats = data.get("stats", {})
# バッチ POST API は model オブジェクト内に id を含まない場合がある
# トップレベルの modelId をフォールバックとして使用する
model_id = model.get("id") or data.get("modelId")
version_id = data.get("id", "")
return {
"versionId": data.get("id"),
"modelId": model.get("id"),
"versionId": version_id,
"modelId": model_id,
"modelName": model.get("name", ""),
"versionName": data.get("name", ""),
"type": model.get("type", ""),
"description": data.get("description") or model.get("description", ""),
"tags": model.get("tags", []),
"nsfw": model.get("nsfw", False),
"nsfwLevel": data.get("nsfwLevel", 0),
"air": data.get("air", ""),
"creator": data.get("creator", {}).get("username", ""),
"images": image_urls,
# 後方互換のため URLリストを維持しつつ詳細情報も保存
"images": [img["url"] for img in image_list],
"imageDetails": image_list,
"trainedWords": data.get("trainedWords", []),
"baseModel": data.get("baseModel", ""),
"fileSize": primary_file.get("sizeKB", 0) if primary_file else 0,
"fileMeta": file_meta,
"fileHashes": file_hashes,
"downloadUrl": data.get("downloadUrl", ""),
"modelUrl": f"https://civitai.com/models/{model.get('id', '')}?modelVersionId={data.get('id', '')}",
"modelUrl": (
f"https://civitai.com/models/{model_id}?modelVersionId={version_id}"
if model_id else (
f"https://civitai.com/model-versions/{version_id}"
if version_id else ""
)
),
"stats": {
"downloadCount": stats.get("downloadCount", 0),
"thumbsUpCount": stats.get("thumbsUpCount", 0),
"thumbsDownCount": stats.get("thumbsDownCount", 0),
},
"updatedAt": data.get("updatedAt", ""),
"publishedAt": data.get("publishedAt", ""),
}
# ── バッチフェッチ ────────────────────────────────────────
def batch_fetch(self, model_files, progress_callback=None):
"""Batch fetch CivitAI info for multiple model files.
Phase 1: SHA256 計算("hashing")
Phase 2: POST で一括取得("fetching")— キャッシュ済みはスキップ
Args:
model_files: list of (model_name, file_path) tuples
progress_callback: fn(current, total, model_name, status) called per model
Returns: dict of { model_name: { sha256, civitai_info_or_none } }
"""
import time
results = {}
total = len(model_files)
cache = self._load_cache()
# Phase 1: ハッシュ計算
hashes_needed = [] # [(model_name, sha256_lower, original_index)]
for i, (model_name, file_path) in enumerate(model_files):
if progress_callback:
progress_callback(i, total, model_name, "hashing")
# Calculate hash
sha256 = self.calculate_sha256(file_path)
if not sha256:
results[model_name] = {"sha256": None, "civitai": None, "error": "hash_failed"}
continue
results[model_name] = {"sha256": sha256, "civitai": None}
# Check cache
if sha256 in cache:
results[model_name]["civitai"] = cache[sha256]
if progress_callback:
progress_callback(i, total, model_name, "cached")
progress_callback(i + 1, total, model_name, "not_found")
continue
# Fetch from API
sha256_lower = sha256.lower()
results[model_name] = {"sha256": sha256_lower, "civitai": None}
if sha256_lower in cache:
results[model_name]["civitai"] = cache[sha256_lower]
if progress_callback:
progress_callback(i + 1, total, model_name, "cached")
else:
hashes_needed.append((model_name, sha256_lower, i))
# Phase 2: POST で一括取得(未キャッシュ分)
if hashes_needed:
if progress_callback:
progress_callback(i, total, model_name, "fetching")
progress_callback(len(results), total, "", "fetching")
info = self.fetch_by_hash(sha256)
if info:
results[model_name]["civitai"] = info
# 同一ハッシュが複数モデルに対応する場合を考慮
sha256_to_entries: dict[str, list] = {}
for name, sha256_lower, idx in hashes_needed:
sha256_to_entries.setdefault(sha256_lower, []).append((name, idx))
if progress_callback:
status = "found" if info else "not_found"
progress_callback(i, total, model_name, status)
batch_results = self._batch_fetch_post(list(sha256_to_entries.keys()))
# Rate limit: small delay between API calls
time.sleep(0.5)
for sha256_lower, info in batch_results.items():
for name, idx in sha256_to_entries.get(sha256_lower, []):
results[name]["civitai"] = info
if progress_callback:
status = "found" if info else "not_found"
progress_callback(idx + 1, total, name, status)
if progress_callback:
progress_callback(total, total, "", "done")
return results
# ── 画像ダウンロード ──────────────────────────────────────
@staticmethod
def download_image(url, save_path, timeout=15):
"""Download an image from URL and save to save_path. Returns True on success."""
try:
req = Request(url, headers={"User-Agent": "ComfyUI-Workflow-Studio/1.0"})
with urlopen(req, timeout=timeout, context=_get_ssl_context()) as resp:
data = resp.read()
with open(save_path, "wb") as f:
f.write(data)
return True
except Exception as e:
logger.warning("Failed to download preview from %s: %s", url, e)
return False
# ── キャッシュ操作 ────────────────────────────────────────
def clear_cache(self, sha256_hash=None):
"""Clear cache for a specific hash or all."""
cache = self._load_cache()
if sha256_hash:
cache.pop(sha256_hash, None)
cache.pop(sha256_hash.lower(), None)
else:
cache.clear()
self._save_cache()
+1 -2
View File
@@ -81,8 +81,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
+126 -2
View File
@@ -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}
+108
View File
@@ -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 "",
}
+402
View File
@@ -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)))
+102 -20
View File
@@ -3,6 +3,24 @@
import os
import re
# CLIPLoader / DualCLIPLoader の type フィールド → モデル種別マッピング
_CLIP_TYPE_TO_MODEL = {
"flux": "Flux",
"flux2": "Flux2",
"newbie": "NewBie",
"ovis": "Ovis",
"qwen_image": "Qwen",
"sd3": "SD3",
"sd3.5": "SD3",
"hidream_i": "HiDream",
"hidream_e": "HiDream",
"hidream": "HiDream",
"wan": "Wan",
"cosmos": "Cosmos",
"lumina": "Lumina",
"lumina2": "Z-IMAGE",
}
def _model_name_from_ui_node(node):
"""Extract model filename from UI format node (lowercase)."""
@@ -11,16 +29,65 @@ def _model_name_from_ui_node(node):
return val.lower() if isinstance(val, str) else ""
def _clip_type_from_ui_node(node):
"""Extract CLIPLoader type string from widgets_values (lowercase)."""
ntype = node.get("type", "")
vals = node.get("widgets_values", [])
if ntype == "CLIPLoader" and len(vals) > 1:
return str(vals[1]).lower() if isinstance(vals[1], str) else ""
if ntype in ("DualCLIPLoader", "TripleCLIPLoader") and len(vals) > 2:
return str(vals[2]).lower() if isinstance(vals[2], str) else ""
return ""
def _model_name_from_api_node(node):
"""Extract model filename from API format node (lowercase)."""
inputs = node.get("inputs", {})
for key in ("ckpt_name", "unet_name", "model_name"):
for key in ("ckpt_name", "unet_name", "model_name", "clip_name1", "clip_name"):
val = inputs.get(key, "")
if isinstance(val, str) and val:
return val.lower()
return ""
def _collect_all_ui_nodes(workflow_data):
"""Yield all UI-format nodes including those inside definitions.subgraphs."""
for node in workflow_data.get("nodes", []):
yield node
defs = workflow_data.get("definitions", {})
if isinstance(defs, dict):
for sg in defs.get("subgraphs", []):
if isinstance(sg, dict):
for node in sg.get("nodes", []):
yield node
def _detect_model_type_from_name(mn_base, model_types):
"""Detect model type from a model filename (already lowercased basename)."""
if re.search(r"sd1[._-]?5|v1[._-]5", mn_base):
model_types.add("SD1.5")
elif re.search(r"sdxl|[._-]xl[._-]|[._-]xl$|xl[._-]", mn_base):
model_types.add("SDXL")
elif re.search(r"flux[-_.]?2", mn_base):
model_types.add("Flux2")
elif "flux" in mn_base:
model_types.add("Flux")
elif re.search(r"sd[._-]?3", mn_base):
model_types.add("SD3")
elif "qwen" in mn_base:
model_types.add("Qwen")
elif "zimage" in mn_base or "z-image" in mn_base or "zit" in mn_base:
model_types.add("Z-IMAGE")
elif "newbie" in mn_base:
model_types.add("NewBie")
elif "ovis" in mn_base:
model_types.add("Ovis")
elif "hidream" in mn_base:
model_types.add("HiDream")
elif "wan" in mn_base and re.search(r"wan[-_.]?\d|wan[-_]video", mn_base):
model_types.add("Wan")
def analyze_workflow(workflow_data, filename=""):
"""Analyze workflow JSON and return model types, input/output node counts."""
model_types = set()
@@ -36,23 +103,33 @@ def analyze_workflow(workflow_data, filename=""):
model_types.add("Qwen")
if "zimage" in fn or "z-image" in fn or "zit" in fn:
model_types.add("Z-IMAGE")
if "flux2" in fn:
if re.search(r"flux[-_.]?2", fn):
model_types.add("Flux2")
elif "flux" in fn:
model_types.add("Flux")
if "sd3" in fn:
model_types.add("SD3")
if "newbie" in fn:
model_types.add("NewBie")
if "ovis" in fn:
model_types.add("Ovis")
if "hidream" in fn:
model_types.add("HiDream")
if "wan" in fn and re.search(r"wan[-_.]?\d|wan[-_]video", fn):
model_types.add("Wan")
# Support both UI format (nodes array) and API format (node ID object)
raw_nodes = workflow_data.get("nodes", None)
if raw_nodes is not None:
# UI / app format: collect all nodes including subgraph definitions
node_iter = [
(
node.get("type", ""),
node.get("title", "").lower(),
_model_name_from_ui_node(node),
_clip_type_from_ui_node(node),
)
for node in raw_nodes
for node in _collect_all_ui_nodes(workflow_data)
]
else:
node_iter = []
@@ -62,33 +139,32 @@ def analyze_workflow(workflow_data, filename=""):
ntype = node.get("class_type", "")
title = node.get("_meta", {}).get("title", "").lower()
mn = _model_name_from_api_node(node)
node_iter.append((ntype, title, mn))
node_iter.append((ntype, title, mn, ""))
for ntype, title, mn in node_iter:
for ntype, title, mn, clip_type in node_iter:
if (
"CheckpointLoader" in ntype
or "UNETLoader" in ntype
or "UnetLoader" in ntype # UnetLoaderGGUF 等を含む
or "unet_name" in ntype
):
mn_base = os.path.basename(mn.replace("\\", "/"))
if re.search(r"sd1[._-]?5|v1[._-]5", mn_base):
model_types.add("SD1.5")
elif re.search(r"sdxl|[._-]xl[._-]|[._-]xl$|xl[._-]", mn_base):
model_types.add("SDXL")
elif "flux2" in mn_base:
model_types.add("Flux2")
elif "flux" in mn_base:
model_types.add("Flux")
elif re.search(r"sd[._-]?3", mn_base):
model_types.add("SD3")
elif "qwen" in mn_base:
model_types.add("Qwen")
elif "zimage" in mn_base or "z-image" in mn_base or "zit" in mn_base:
model_types.add("Z-IMAGE")
_detect_model_type_from_name(mn_base, model_types)
# CLIPLoader 系: type フィールドまたはファイル名からモデル種別を検出
# QuadrupleCLIPLoader 等、type フィールドを持たない新型ローダーにも対応
if "CLIPLoader" in ntype:
if clip_type:
detected = _CLIP_TYPE_TO_MODEL.get(clip_type)
if detected:
model_types.add(detected)
mn_base = os.path.basename(mn.replace("\\", "/"))
if mn_base:
_detect_model_type_from_name(mn_base, model_types)
if "sdxl" in title:
model_types.add("SDXL")
if "flux2" in title:
if re.search(r"flux[-_.]?2", title):
model_types.add("Flux2")
elif "flux" in title:
model_types.add("Flux")
@@ -98,6 +174,12 @@ def analyze_workflow(workflow_data, filename=""):
model_types.add("Qwen")
if "zimage" in title or "z-image" in title or "zit" in title:
model_types.add("Z-IMAGE")
if "newbie" in title:
model_types.add("NewBie")
if "ovis" in title:
model_types.add("Ovis")
if "hidream" in title:
model_types.add("HiDream")
if ntype == "CLIPTextEncode" or "prompt" in title:
inputs["prompts"] += 1
+2 -1
View File
@@ -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
View File
@@ -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.7"
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.40"
license = "MIT"
requires-python = ">= 3.10"
dependencies = ["jinja2"]
+21
View File
@@ -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
+52
View File
@@ -602,6 +602,58 @@
background: rgba(255,255,255,0.2);
}
/* ── 詳細パネル アクションボタン行 ───────────────────────────── */
.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 {
+1183 -75
View File
File diff suppressed because it is too large Load Diff
+294
View File
@@ -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;
}
+597
View File
@@ -0,0 +1,597 @@
/**
* AI Tab - Translation, VLM, Settings
* Supports Ollama and LM Studio as backends
*/
import { showToast } from "./app.js";
import { t } from "./i18n.js";
import { readJsonStorage } from "./util.js";
const SETTINGS_KEY = "wfm_ai_settings";
const LANG_NAMES = {
ja: "Japanese",
en: "English",
zh: "Chinese",
};
// ============================================
// Settings persistence
// ============================================
function loadAiSettings() {
return readJsonStorage(SETTINGS_KEY);
}
function saveAiSettings(patch) {
const data = { ...loadAiSettings(), ...patch };
localStorage.setItem(SETTINGS_KEY, JSON.stringify(data));
return data;
}
const VLM_PROMPTS = {
describe: "Describe this image in detail.",
prompt: "Create a detailed Stable Diffusion image generation prompt based on this image. Output only the prompt text, nothing else.",
tags: "Generate a list of descriptive tags for this image. Output only comma-separated tags in English, nothing else.",
};
function fileToBase64(file) {
return new Promise((resolve, reject) => {
const reader = new FileReader();
reader.onload = e => {
const b64 = e.target.result.split(",")[1];
resolve({ base64: b64, mimeType: file.type });
};
reader.onerror = reject;
reader.readAsDataURL(file);
});
}
async function callVLM(url, backend, model, prompt, base64Image, mimeType) {
if (backend === "ollama") {
const res = await fetch(`${url}/api/generate`, {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ model, prompt, images: [base64Image], stream: false }),
});
if (!res.ok) throw new Error(`HTTP ${res.status}`);
return (await res.json()).response || "";
} else {
const res = await fetch(`${url}/v1/chat/completions`, {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({
model,
messages: [{ role: "user", content: [
{ type: "text", text: prompt },
{ type: "image_url", image_url: { url: `data:${mimeType};base64,${base64Image}` } },
]}],
stream: false,
}),
});
if (!res.ok) throw new Error(`HTTP ${res.status}`);
return (await res.json()).choices?.[0]?.message?.content || "";
}
}
// ============================================
// URL validation
// ============================================
function isValidBackendUrl(url) {
try {
const u = new URL(url);
return u.protocol === "http:" || u.protocol === "https:";
} catch {
return false;
}
}
// ============================================
// API helpers
// ============================================
async function fetchModels(url, backend) {
if (backend === "ollama") {
const res = await fetch(`${url}/api/tags`);
if (!res.ok) throw new Error(`HTTP ${res.status}`);
const data = await res.json();
return (data.models || []).map((m) => m.name);
} else {
// LM Studio (OpenAI-compatible)
const res = await fetch(`${url}/v1/models`);
if (!res.ok) throw new Error(`HTTP ${res.status}`);
const data = await res.json();
return (data.data || []).map((m) => m.id);
}
}
async function testConnection(url, backend) {
const models = await fetchModels(url, backend);
return models.length;
}
async function callLLM(url, backend, model, prompt) {
if (backend === "ollama") {
const res = await fetch(`${url}/api/generate`, {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ model, prompt, stream: false }),
});
if (!res.ok) throw new Error(`HTTP ${res.status}`);
const data = await res.json();
return data.response || "";
} else {
// LM Studio (OpenAI-compatible)
const res = await fetch(`${url}/v1/chat/completions`, {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({
model,
messages: [{ role: "user", content: prompt }],
stream: false,
}),
});
if (!res.ok) throw new Error(`HTTP ${res.status}`);
const data = await res.json();
return data.choices?.[0]?.message?.content || "";
}
}
// ============================================
// Translation prompt builder
// ============================================
function buildTranslationPrompt(text, srcLang, dstLang, settings) {
const srcName = srcLang === "free" ? (settings.freeSrcLang || "Auto") : LANG_NAMES[srcLang];
const dstName = dstLang === "free" ? (settings.freeDstLang || "English") : LANG_NAMES[dstLang];
const fromPart = srcLang === "free" ? "" : `from ${srcName} `;
return `Translate the following text ${fromPart}to ${dstName}. Output only the translated text, nothing else.\n\n${text}`;
}
// ============================================
// Translation tab
// ============================================
function initTranslateTab() {
const srcLangSel = document.getElementById("wfm-ai-src-lang");
const dstLangSel = document.getElementById("wfm-ai-dst-lang");
const swapBtn = document.getElementById("wfm-ai-trans-swap-btn");
const inputEl = document.getElementById("wfm-ai-trans-input");
const outputEl = document.getElementById("wfm-ai-trans-output");
const transBtn = document.getElementById("wfm-ai-trans-btn");
const copyBtn = document.getElementById("wfm-ai-trans-copy-btn");
const statusEl = document.getElementById("wfm-ai-trans-status");
if (!transBtn) return;
// Restore saved language selections
const saved = loadAiSettings();
if (saved.srcLang && srcLangSel) srcLangSel.value = saved.srcLang;
if (saved.dstLang && dstLangSel) dstLangSel.value = saved.dstLang;
// Persist language selections
srcLangSel?.addEventListener("change", () => saveAiSettings({ srcLang: srcLangSel.value }));
dstLangSel?.addEventListener("change", () => saveAiSettings({ dstLang: dstLangSel.value }));
// Swap languages
swapBtn?.addEventListener("click", () => {
const tmp = srcLangSel.value;
srcLangSel.value = dstLangSel.value;
dstLangSel.value = tmp;
saveAiSettings({ srcLang: srcLangSel.value, dstLang: dstLangSel.value });
// Swap text content too
const tmpText = inputEl.value;
inputEl.value = outputEl.value;
outputEl.value = tmpText;
});
// Translate
transBtn.addEventListener("click", async () => {
const text = inputEl.value.trim();
if (!text) {
showToast(t("aiToastNoText"), "error");
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;
}
transBtn.disabled = true;
statusEl.textContent = t("aiStatusTranslating");
statusEl.className = "wfm-ai-trans-status wfm-ai-status-working";
outputEl.value = "";
try {
const prompt = buildTranslationPrompt(text, srcLangSel.value, dstLangSel.value, settings);
const result = await callLLM(url, backend, model, prompt);
outputEl.value = result.trim();
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("aiToastTransFailed") + err.message, "error");
} finally {
transBtn.disabled = false;
}
});
// Copy translated text
copyBtn?.addEventListener("click", () => {
const text = outputEl.value;
if (!text) {
showToast(t("aiToastNoCopyText"), "error");
return;
}
navigator.clipboard.writeText(text).then(() => {
showToast(t("aiToastCopied"), "success");
});
});
}
// ============================================
// Settings tab
// ============================================
async function refreshModels() {
const settings = loadAiSettings();
const backend = document.querySelector("input[name='wfm-ai-backend']:checked")?.value || "ollama";
const url = document.getElementById("wfm-ai-backend-url")?.value?.trim() || "";
const modelSel = document.getElementById("wfm-ai-model-select");
const refreshBtn = document.getElementById("wfm-ai-model-refresh-btn");
if (!modelSel) return;
if (refreshBtn) refreshBtn.disabled = true;
try {
const models = await fetchModels(url, backend);
modelSel.innerHTML = `<option value="">-- ${t("aiSettingsModelPlaceholder")} --</option>`;
models.forEach((name) => {
const opt = document.createElement("option");
opt.value = name;
opt.textContent = name;
if (name === settings.model) opt.selected = true;
modelSel.appendChild(opt);
});
if (models.length === 0) showToast(t("aiToastNoModels"), "error");
} catch (err) {
showToast(t("aiToastModelsFailed") + err.message, "error");
} finally {
if (refreshBtn) refreshBtn.disabled = false;
}
}
function initSettingsTab() {
const saved = loadAiSettings();
// Restore saved values
const backendRadios = document.querySelectorAll("input[name='wfm-ai-backend']");
backendRadios.forEach((r) => {
if (r.value === (saved.backend || "ollama")) r.checked = true;
});
const urlInput = document.getElementById("wfm-ai-backend-url");
if (urlInput && saved.backendUrl) urlInput.value = saved.backendUrl;
// Update URL placeholder when backend changes
backendRadios.forEach((r) => {
r.addEventListener("change", () => {
if (!urlInput) return;
const defaultUrl = r.value === "ollama" ? "http://localhost:11434" : "http://localhost:1234";
if (!saved.backendUrl) urlInput.value = defaultUrl;
});
});
// Connection test
document.getElementById("wfm-ai-test-btn")?.addEventListener("click", async () => {
const testBtn = document.getElementById("wfm-ai-test-btn");
const resultEl = document.getElementById("wfm-ai-test-result");
const backend = document.querySelector("input[name='wfm-ai-backend']:checked")?.value || "ollama";
const url = urlInput?.value?.trim() || "";
if (!isValidBackendUrl(url)) {
if (resultEl) {
resultEl.textContent = t("aiToastInvalidUrlInput");
resultEl.className = "wfm-ai-test-result wfm-ai-status-error";
}
return;
}
if (testBtn) testBtn.disabled = true;
if (resultEl) {
resultEl.textContent = t("aiStatusConnecting");
resultEl.className = "wfm-ai-test-result wfm-ai-status-working";
}
try {
const count = await testConnection(url, backend);
if (resultEl) {
resultEl.textContent = `${t("aiStatusConnectOk")} (${count} ${t("aiModels")})`;
resultEl.className = "wfm-ai-test-result wfm-ai-status-ok";
}
await refreshModels();
} catch (err) {
if (resultEl) {
resultEl.textContent = `${t("aiStatusConnectFail")}${err.message}`;
resultEl.className = "wfm-ai-test-result wfm-ai-status-error";
}
} finally {
if (testBtn) testBtn.disabled = false;
}
});
// Model refresh
document.getElementById("wfm-ai-model-refresh-btn")?.addEventListener("click", () => refreshModels());
// Free language inputs
const freeSrcInput = document.getElementById("wfm-ai-free-src-lang");
const freeDstInput = document.getElementById("wfm-ai-free-dst-lang");
if (freeSrcInput && saved.freeSrcLang) freeSrcInput.value = saved.freeSrcLang;
if (freeDstInput && saved.freeDstLang) freeDstInput.value = saved.freeDstLang;
// Save settings
document.getElementById("wfm-ai-settings-save-btn")?.addEventListener("click", () => {
const backend = document.querySelector("input[name='wfm-ai-backend']:checked")?.value || "ollama";
const url = urlInput?.value?.trim() || "";
const model = document.getElementById("wfm-ai-model-select")?.value || "";
const freeSrcLang = freeSrcInput?.value?.trim() || "";
const freeDstLang = freeDstInput?.value?.trim() || "";
if (url && !isValidBackendUrl(url)) {
showToast(t("aiToastInvalidUrl"), "error");
return;
}
saveAiSettings({ backend, backendUrl: url, model, freeSrcLang, freeDstLang });
showToast(t("aiToastSettingsSaved"), "success");
});
// Load models on init if settings exist
if (saved.backendUrl && saved.backend) {
refreshModels().catch(() => {});
}
}
// ============================================
// 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
// ============================================
function initVlmTab() {
const dropEl = document.getElementById("wfm-ai-vlm-drop");
const previewEl = document.getElementById("wfm-ai-vlm-preview");
const labelEl = document.getElementById("wfm-ai-vlm-label");
const fileInput = document.getElementById("wfm-ai-vlm-file");
const taskSel = document.getElementById("wfm-ai-vlm-task");
const runBtn = document.getElementById("wfm-ai-vlm-run");
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);
previewEl.src = `data:${vlmImage.mimeType};base64,${vlmImage.base64}`;
previewEl.style.display = "block";
labelEl.style.display = "none";
};
dropEl.addEventListener("click", () => fileInput.click());
fileInput.addEventListener("change", e => { if (e.target.files[0]) loadImage(e.target.files[0]); });
dropEl.addEventListener("dragover", e => { e.preventDefault(); dropEl.classList.add("drag-over"); });
dropEl.addEventListener("dragleave", () => dropEl.classList.remove("drag-over"));
dropEl.addEventListener("drop", e => {
e.preventDefault();
dropEl.classList.remove("drag-over");
if (e.dataTransfer.files[0]) loadImage(e.dataTransfer.files[0]);
});
runBtn.addEventListener("click", async () => {
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 (!model) { showToast(t("aiToastNoModel"), "error"); return; }
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";
resultEl.value = "";
try {
const result = await callVLM(url, backend, model, VLM_PROMPTS[task], vlmImage.base64, vlmImage.mimeType);
resultEl.value = result.trim();
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;
}
});
copyBtn.addEventListener("click", () => {
const text = resultEl.value;
if (!text) { showToast(t("aiToastNoCopyText"), "error"); return; }
navigator.clipboard.writeText(text).then(() => showToast(t("aiToastCopied"), "success"));
});
}
// ============================================
// Export
// ============================================
export function initAiTab() {
initTranslateTab();
initChatTab();
initVlmTab();
initSettingsTab();
}
+133 -6
View File
@@ -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" };
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,27 @@ 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 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");
@@ -224,6 +246,67 @@ function applyI18nToHtml() {
const presetCopyNegBtn = document.getElementById("wfm-preset-copy-neg-btn");
if (presetCopyNegBtn) presetCopyNegBtn.textContent = t("copyNegativePrompt");
// AI tab
document.querySelectorAll(".wfm-ai-subtab-btn").forEach(btn => {
if (btn.dataset.aiSubtab === "translate") btn.textContent = t("aiSubTabTranslate");
if (btn.dataset.aiSubtab === "vlm") btn.textContent = t("aiSubTabVlm");
if (btn.dataset.aiSubtab === "ai-settings") btn.textContent = t("aiSubTabSettings");
});
const aiLangMap = { ja: "aiLangJa", en: "aiLangEn", zh: "aiLangZh", free: "aiLangFree" };
[document.getElementById("wfm-ai-src-lang"), document.getElementById("wfm-ai-dst-lang")].forEach(sel => {
if (!sel) return;
sel.querySelectorAll("option").forEach(opt => {
const key = aiLangMap[opt.value];
if (key) opt.textContent = t(key);
});
});
const aiTransInput = document.getElementById("wfm-ai-trans-input");
if (aiTransInput) aiTransInput.placeholder = t("aiTransInputPlaceholder");
const aiTransOutput = document.getElementById("wfm-ai-trans-output");
if (aiTransOutput) aiTransOutput.placeholder = t("aiTransOutputPlaceholder");
const aiTransBtn = document.getElementById("wfm-ai-trans-btn");
if (aiTransBtn) aiTransBtn.textContent = t("aiTranslateBtn");
const aiTransCopyBtn = document.getElementById("wfm-ai-trans-copy-btn");
if (aiTransCopyBtn) aiTransCopyBtn.textContent = t("aiCopyBtn");
const aiVlmLabel = document.getElementById("wfm-ai-vlm-label");
if (aiVlmLabel) aiVlmLabel.textContent = t("aiVlmDropLabel");
const aiVlmTask = document.getElementById("wfm-ai-vlm-task");
if (aiVlmTask) {
aiVlmTask.querySelectorAll("option").forEach(opt => {
if (opt.value === "describe") opt.textContent = t("aiVlmDescribe");
if (opt.value === "prompt") opt.textContent = t("aiVlmPromptCreate");
});
}
const aiVlmRunBtn = document.getElementById("wfm-ai-vlm-run");
if (aiVlmRunBtn) aiVlmRunBtn.textContent = t("aiVlmRunBtn");
const aiVlmResult = document.getElementById("wfm-ai-vlm-result");
if (aiVlmResult) aiVlmResult.placeholder = t("aiVlmResultPlaceholder");
const aiVlmCopyBtn = document.getElementById("wfm-ai-vlm-copy");
if (aiVlmCopyBtn) aiVlmCopyBtn.textContent = t("aiCopyBtn");
const aiBackendTitle = document.getElementById("wfm-ai-settings-backend-title");
if (aiBackendTitle) aiBackendTitle.textContent = t("aiSettingsBackend");
const aiConnTitle = document.getElementById("wfm-ai-settings-conn-title");
if (aiConnTitle) aiConnTitle.textContent = t("aiSettingsConnection");
const aiTestBtn = document.getElementById("wfm-ai-test-btn");
if (aiTestBtn) aiTestBtn.textContent = t("aiSettingsTestBtn");
const aiModelTitle = document.getElementById("wfm-ai-settings-model-title");
if (aiModelTitle) aiModelTitle.textContent = t("aiSettingsModelSection");
const aiModelSel = document.getElementById("wfm-ai-model-select");
if (aiModelSel) {
const firstOpt = aiModelSel.querySelector("option[value='']");
if (firstOpt) firstOpt.textContent = t("aiSettingsModelPlaceholder");
}
const aiModelRefreshBtn = document.getElementById("wfm-ai-model-refresh-btn");
if (aiModelRefreshBtn) aiModelRefreshBtn.textContent = t("aiSettingsRefreshBtn");
const aiFreeLangTitle = document.getElementById("wfm-ai-settings-freelang-title");
if (aiFreeLangTitle) aiFreeLangTitle.textContent = t("aiSettingsFreeLang");
const aiFreeSrcLabel = document.getElementById("wfm-ai-free-src-label");
if (aiFreeSrcLabel) aiFreeSrcLabel.textContent = t("aiSettingsInputLang");
const aiFreeDstLabel = document.getElementById("wfm-ai-free-dst-label");
if (aiFreeDstLabel) aiFreeDstLabel.textContent = t("aiSettingsOutputLang");
const aiSaveBtn = document.getElementById("wfm-ai-settings-save-btn");
if (aiSaveBtn) aiSaveBtn.textContent = t("aiSettingsSaveBtn");
// Group panel labels
const propTitle = document.querySelector("#wfm-side-tab-group .wfm-group-section-title");
if (propTitle) propTitle.textContent = t("properties");
@@ -265,7 +348,9 @@ function applyI18nToHtml() {
"wfm-help-gen-3": "helpGen3", "wfm-help-gen-4": "helpGen4",
"wfm-help-gen-5": "helpGen5", "wfm-help-gen-6": "helpGen6", "wfm-help-gen-7": "helpGen7",
"wfm-help-gen-8": "helpGen8", "wfm-help-gen-9": "helpGen9", "wfm-help-gen-10": "helpGen10",
"wfm-help-gen-11": "helpGen11",
"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-1": "helpFeeder1", "wfm-help-feeder-2": "helpFeeder2",
@@ -283,6 +368,8 @@ function applyI18nToHtml() {
"wfm-help-settings-5": "helpSettings5", "wfm-help-settings-6": "helpSettings6",
"wfm-help-settings-7": "helpSettings7", "wfm-help-settings-8": "helpSettings8",
"wfm-help-settings-9": "helpSettings9", "wfm-help-settings-10": "helpSettings10",
"wfm-help-settings-11": "helpSettings11", "wfm-help-settings-12": "helpSettings12",
"wfm-help-settings-13": "helpSettings13",
"wfm-help-nodes-1": "helpNodes1", "wfm-help-nodes-2": "helpNodes2",
"wfm-help-nodes-3": "helpNodes3", "wfm-help-nodes-4": "helpNodes4",
"wfm-help-nodes-5": "helpNodes5", "wfm-help-nodes-6": "helpNodes6",
@@ -291,14 +378,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",
@@ -306,12 +400,21 @@ function applyI18nToHtml() {
"wfm-help-sidepanel-7": "helpSidepanel7", "wfm-help-sidepanel-8": "helpSidepanel8",
"wfm-help-sidepanel-9": "helpSidepanel9", "wfm-help-sidepanel-10": "helpSidepanel10",
"wfm-help-sidepanel-11": "helpSidepanel11", "wfm-help-sidepanel-12": "helpSidepanel12",
"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",
"wfm-help-shortcuts-title": "helpShortcutsTitle",
"wfm-help-shortcuts-1": "helpShortcuts1", "wfm-help-shortcuts-2": "helpShortcuts2",
"wfm-help-shortcuts-3": "helpShortcuts3", "wfm-help-shortcuts-4": "helpShortcuts4",
"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",
@@ -359,18 +462,40 @@ import { initWorkflowTab } from "./workflow-tab.js";
import { initNodesTab } from "./nodes-tab.js";
import { initGenerateTab } from "./generate-tab.js";
import { initPromptTab } from "./prompt-tab.js";
import { initSettingsTab, applyTheme, getSavedTheme } from "./settings-tab.js";
import { initSettingsTab, applyTheme, getSavedTheme, applyTextareaFontSize, applyJsonColors } from "./settings-tab.js";
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 & JSON highlight colors
try {
const _s = getSettings();
if (_s.textareaFontSize) applyTextareaFontSize(_s.textareaFontSize);
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();
@@ -379,6 +504,8 @@ document.addEventListener("DOMContentLoaded", () => {
initPromptTab();
initMetadataTab();
initGalleryTab();
initAiTab();
initTaggerTab();
console.log("Workflow Studio: App initialized");
});
+521 -17
View File
@@ -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, "&quot;")}">
<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) {
+84 -6
View File
@@ -295,16 +295,36 @@ 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);
}
});
// 2. Map widgets_values to widget input names using object_info
const widgets = node.widgets_values || [];
if (widgets.length > 0) {
// Lora Loader (LoraManager): use __lm_widget_ids from node properties
// widgets_values: [autocomplete_meta_obj, text_str, loras_array]
// API format: {__lm_autocomplete_meta_text: obj, text: str, loras: {__value__: arr}}
const lmWidgetIds = node.properties?.__lm_widget_ids;
if (lmWidgetIds && Array.isArray(lmWidgetIds)) {
lmWidgetIds.forEach((name, idx) => {
if (idx >= widgets.length || linkedInputNames.has(name)) return;
let val = widgets[idx];
if (name === "loras" && Array.isArray(val)) {
val = { "__value__": val };
}
inputs[name] = val;
});
} else {
const widgetNames = _getWidgetInputNames(objectInfo, node.type);
if (widgetNames.length > 0) {
@@ -321,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
@@ -374,6 +396,7 @@ export const comfyWorkflow = {
});
}
}
} // end else (non-LoraManager path)
}
api[nodeId] = {
@@ -497,7 +520,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",
@@ -575,6 +601,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") {
@@ -602,6 +645,17 @@ export const comfyWorkflow = {
}
}
// CLIPTextEncodeEditPlus — text_edit is the locally editable override; text1 is always a link
if (ct === "CLIPTextEncodeEditPlus") {
const textVal = inputs.text_edit;
if (typeof textVal === "string") {
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({
@@ -680,6 +734,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 });
@@ -765,6 +839,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"],
+23 -17
View File
@@ -4,6 +4,7 @@
import { comfyUI } from "./comfyui-client.js";
import { showToast } from "./app.js";
import { t } from "./i18n.js";
// ── Module State ──────────────────────────────────────────────────
const _s = {
@@ -76,11 +77,11 @@ 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");
}
// ── Run Loop ──────────────────────────────────────────────────────
@@ -108,18 +109,18 @@ function _applyToNode(nodeId) {
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);
@@ -135,6 +136,10 @@ async function _startRun() {
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 {}
};
@@ -191,14 +196,14 @@ 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,7 +216,7 @@ async function _stopRun() {
_s.running = false;
try { await comfyUI.interrupt(); } catch {}
_setRunUI(false);
showToast("Feeder stopped", "info");
showToast(t("feederStopped"), "info");
}
// ── Folder Tree ───────────────────────────────────────────────────
@@ -416,7 +421,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 +430,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 +458,7 @@ async function _applyPreset() {
}
_refreshGridCbs();
_updateStatus();
showToast(`Preset loaded: ${name}`, "success");
showToast(t("presetLoaded", name), "success");
}
async function _deletePreset() {
@@ -461,9 +466,9 @@ 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"); }
}
// ── Helpers ───────────────────────────────────────────────────────
@@ -507,4 +512,5 @@ export async function initFeederTab() {
document.getElementById("wfm-feeder-stop-btn")?.addEventListener("click", _stopRun);
await Promise.all([_loadTree(), _loadPresets()]);
_selectDir("");
}
+118 -52
View File
@@ -5,6 +5,9 @@
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";
// ── 定数 ─────────────────────────────────────────────────────
@@ -65,6 +68,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() {
@@ -302,8 +317,13 @@ function createThumbCard(img) {
});
card.appendChild(favBtn);
// クリック: 詳細表示 / Ctrl+クリック: 複数選択
// クリック: 詳細表示 / 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)) {
@@ -394,8 +414,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,7 +455,7 @@ 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";
}
@@ -456,7 +481,7 @@ async function toggleFavoriteInPlace(img, btn) {
state.selectedImage.favorite = data.favorite;
}
} catch (e) {
showToast(`Error: ${e.message}`, "error");
showToast(t("errorWithMsg", e.message), "error");
}
}
@@ -582,7 +607,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");
}
}
@@ -622,7 +647,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;
@@ -705,9 +730,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 +752,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 +764,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,9 +784,9 @@ 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");
}
});
@@ -773,7 +798,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 +821,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 +844,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, "&amp;")
.replace(/</g, "&lt;")
.replace(/>/g, "&gt;")
.replace(/"/g, "&quot;");
}
// ── フォルダ作成・削除 ────────────────────────────────────────
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 +869,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 +890,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 +914,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 +934,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 +950,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 +968,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 +996,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;
}
@@ -1031,7 +1049,7 @@ async function bulkAddToGroup(groupName) {
success++;
} catch (e) { /* continue */ }
}
showToast(`Added ${success} image(s) to "${groupName}"`, "success");
showToast(t("addedNImagesToGroup", success, groupName), "success");
}
async function bulkSetFavorite(favoriteValue) {
@@ -1052,7 +1070,7 @@ async function bulkSetFavorite(favoriteValue) {
} catch (e) { /* continue */ }
}
if (success > 0) {
showToast(`${favoriteValue ? "Favorited" : "Unfavorited"} ${success} image(s)`, "success");
showToast(favoriteValue ? t("favoritedNImages", success) : t("unfavoritedNImages", success), "success");
renderImages(); // お気に入り状態が変わったのでビュー更新
}
}
@@ -1196,18 +1214,22 @@ 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", () => {
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"));
const jsonStr = JSON.stringify(state.embeddedWorkflow, null, 2);
navigator.clipboard.writeText(jsonStr)
.then(() => {
localStorage.setItem("wfm_pending_workflow", jsonStr);
showToast(t("workflowSentToCanvas"), "success");
})
.catch(() => showToast(t("copyFailed"), "error"));
});
// 一括操作バー
@@ -1218,12 +1240,18 @@ 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");
}
});
@@ -1263,10 +1291,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");
+1124 -130
View File
File diff suppressed because it is too large Load Diff
+912 -56
View File
File diff suppressed because it is too large Load Diff
+53 -17
View File
@@ -5,6 +5,7 @@
*/
import { t } from "./i18n.js";
import { escapeHtml } from "./util.js";
// ── File size limit ───────────────────────────────────────────
const MAX_FILE_SIZE = 50 * 1024 * 1024;
@@ -122,8 +123,9 @@ function extractVAEs(wf) {
}
function extractDiffusionModels(wf) {
if (!wf || typeof wf !== "object") return [];
if (Array.isArray(wf.nodes)) return collectUnique(collectAllNodes(wf).filter(n => n.type === "UNETLoader").map(n => n.widgets_values?.[0]));
return collectUnique(Object.values(wf).filter(n => n?.class_type === "UNETLoader").map(n => n.inputs?.unet_name));
const UNET_TYPES = new Set(["UNETLoader", "UnetLoaderGGUF", "UNETLoaderGGUF"]);
if (Array.isArray(wf.nodes)) return collectUnique(collectAllNodes(wf).filter(n => UNET_TYPES.has(n.type)).map(n => n.widgets_values?.[0]));
return collectUnique(Object.values(wf).filter(n => UNET_TYPES.has(n?.class_type)).map(n => n.inputs?.unet_name));
}
function extractTextEncoders(wf) {
if (!wf || typeof wf !== "object") return [];
@@ -133,6 +135,7 @@ function extractTextEncoders(wf) {
if (n.type === "CLIPLoader") { if (n.widgets_values?.[0]) names.push(n.widgets_values[0]); }
else if (n.type === "DualCLIPLoader") { [0,1].forEach(i => { if (n.widgets_values?.[i]) names.push(n.widgets_values[i]); }); }
else if (n.type === "TripleCLIPLoader") { [0,1,2].forEach(i => { if (n.widgets_values?.[i]) names.push(n.widgets_values[i]); }); }
else if (n.type === "QuadrupleCLIPLoader") { [0,1,2,3].forEach(i => { if (n.widgets_values?.[i]) names.push(n.widgets_values[i]); }); }
}
} else {
for (const n of Object.values(wf)) {
@@ -141,6 +144,7 @@ function extractTextEncoders(wf) {
if (ct === "CLIPLoader") { if (n.inputs?.clip_name) names.push(n.inputs.clip_name); }
else if (ct === "DualCLIPLoader") { if (n.inputs?.clip_name1) names.push(n.inputs.clip_name1); if (n.inputs?.clip_name2) names.push(n.inputs.clip_name2); }
else if (ct === "TripleCLIPLoader") { ["clip_name1","clip_name2","clip_name3"].forEach(k => { if (n.inputs?.[k]) names.push(n.inputs[k]); }); }
else if (ct === "QuadrupleCLIPLoader") { ["clip_name1","clip_name2","clip_name3","clip_name4"].forEach(k => { if (n.inputs?.[k]) names.push(n.inputs[k]); }); }
}
}
return collectUnique(names);
@@ -151,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)) {
@@ -167,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;
@@ -205,16 +216,20 @@ function extractPromptsFromNodeSet(nodes, links) {
if (text && typeof text === "string") {
textMap.set(n.id, text);
} else if (Array.isArray(n.inputs)) {
const textInput = n.inputs.find(inp => inp.name === "text" || inp.name === "text_g");
const textInput = n.inputs.find(inp => inp.name === "text" || inp.name === "text_g" || inp.name === "prompt");
if (textInput?.link != null) {
const originId = linkOrigin.get(textInput.link);
const originSlot = linkSlot.get(textInput.link) ?? 0;
const srcNode = originId != null ? nodeMap.get(originId) : null;
if (srcNode) {
const srcType = srcNode.type ?? "";
if (isPromptStylerNode(srcType) || srcType === "WFS_PromptText") {
if (isPromptStylerNode(srcType)) {
const v = srcNode.widgets_values?.[originSlot];
if (v && typeof v === "string") textMap.set(n.id, v);
} else {
// WFS_PromptText, PrimitiveStringMultiline, ComfySwitchNode 等、任意の STRING 出力ノード
const v = srcNode.widgets_values?.[originSlot] ?? srcNode.widgets_values?.[0];
if (v && typeof v === "string") textMap.set(n.id, v);
}
}
}
@@ -236,7 +251,13 @@ function extractPromptsFromNodeSet(nodes, links) {
else if (name === "negative" || name.startsWith("negative")) neg.add(text);
}
}
if (!foundSampler || (pos.size === 0 && neg.size === 0)) return null;
if (!foundSampler) return null;
// SamplerCustomAdvanced などで positive/negative 直結がない場合、判別不能テキストとして返す
if (pos.size === 0 && neg.size === 0) {
const allTexts = [...textMap.values()].filter(t => t.trim());
if (allTexts.length > 0) return { positives: [], negatives: [], texts: allTexts };
return null;
}
return { positives: [...pos], negatives: [...neg] };
}
@@ -331,7 +352,7 @@ function extractPromptsAPI(wf) {
else if (key === "negative" || key.startsWith("negative")) neg.add(text);
}
}
if (!foundSampler || (pos.size === 0 && neg.size === 0)) { const all = [...textMap.values()]; return { positives: all, negatives: all }; }
if (!foundSampler || (pos.size === 0 && neg.size === 0)) { const all = [...textMap.values()].filter(t => t && t.trim()); return { positives: [], negatives: [], texts: all }; }
return { positives: [...pos], negatives: [...neg] };
}
@@ -359,14 +380,14 @@ function extractPromptsLiteGraph(wf) {
const topResult = extractPromptsFromNodeSet(nodes, links ?? []);
if (topResult) return topResult;
// 4. PrimitiveStringMultiline(flux2-klein など)
// 4. PrimitiveStringMultiline(flux2-klein / ernie など)- サブグラフ内も探す
const primTexts = [];
for (const n of nodes) {
for (const n of collectAllNodes(wf)) {
if (n.type !== "PrimitiveStringMultiline") continue;
const t = Array.isArray(n.widgets_values) ? n.widgets_values[0] : n.widgets_values;
if (t && typeof t === "string" && t.trim()) primTexts.push(t.trim());
}
if (primTexts.length > 0) return { positives: primTexts, negatives: [] };
if (primTexts.length > 0) return { positives: [], negatives: [], texts: primTexts };
// 5. サブグラフ内の CLIPTextEncode + KSampler(z-image / qwen / flux など)
for (const sg of wf.definitions?.subgraphs ?? []) {
@@ -388,14 +409,14 @@ function extractPromptsLiteGraph(wf) {
}
if (stylerPos.size > 0 || stylerNeg.size > 0) return { positives: [...stylerPos], negatives: [...stylerNeg] };
// 7. CLIPTextEncode 全テキスト(最終フォールバック)
// 7. テキストエンコーダー全テキスト(最終フォールバック)- サブグラフも含む・判別不能
const all = [];
for (const n of nodes) {
for (const n of collectAllNodes(wf)) {
if (!isTextEncoderNode(n.type ?? "")) continue;
const t = n.widgets_values?.[0];
if (t && typeof t === "string") all.push(t);
if (t && typeof t === "string" && t.trim()) all.push(t);
}
return { positives: all, negatives: all };
return { positives: [], negatives: [], texts: all };
}
// ── SD/Fooocus prompt extraction ──────────────────────────────
@@ -484,7 +505,6 @@ async function extractAllMetadata(file) {
}
// ── UI helpers ────────────────────────────────────────────────
function escapeHtml(s) { return String(s).replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;"); }
function buildModelItem(label) {
const el = document.createElement("div");
@@ -508,13 +528,17 @@ function buildPromptItem(label, type, full, fullArea, fullLabel, listEl) {
const el = document.createElement("div");
el.className = "wfm-meta-item wfm-meta-item-clickable";
const snippet = label.length > 60 ? label.slice(0, 60) + "…" : label;
const typeBadge = type === "positive" ? `<span class="wfm-meta-badge-pos">POS</span>` : `<span class="wfm-meta-badge-neg">NEG</span>`;
const typeBadge = type === "positive" ? `<span class="wfm-meta-badge-pos">POS</span>`
: type === "negative" ? `<span class="wfm-meta-badge-neg">NEG</span>`
: ``;
el.innerHTML = `${typeBadge}<span class="wfm-meta-item-name">${escapeHtml(snippet)}</span>`;
el.addEventListener("click", () => {
listEl.querySelectorAll(".wfm-meta-item-clickable").forEach(e => e.classList.remove("selected"));
el.classList.add("selected");
fullArea.value = full;
fullLabel.textContent = type === "positive" ? t("metaPromptPositive") : t("metaPromptNegative");
fullLabel.textContent = type === "positive" ? t("metaPromptPositive")
: type === "negative" ? t("metaPromptNegative")
: t("metaPromptText") || "Text";
});
return el;
}
@@ -526,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");
@@ -658,6 +691,7 @@ export function initMetadataTab() {
const allPrompts = [
...meta.positives.map(p => ({ type: "positive", text: p })),
...meta.negatives.map(p => ({ type: "negative", text: p })),
...(meta.texts ?? []).map(p => ({ type: "text", text: p })),
];
if (allPrompts.length > 0) {
promptSection.classList.remove("wfm-meta-section-empty");
@@ -718,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"); });
+689 -144
View File
File diff suppressed because it is too large Load Diff
+5 -7
View File
@@ -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, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;");
}
// ── 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");
});
}
+64 -27
View File
@@ -4,6 +4,7 @@
import { showToast } from "./app.js";
import { t } from "./i18n.js";
import { readJsonStorage } from "./util.js";
// ============================================
// State
@@ -21,6 +22,7 @@ let pmSearchText = "";
let pmSelectedId = null; // currently selected preset id
let pmGroups = {}; // { groupName: [presetId, ...] }
const PM_GROUPS_KEY = "wfm_prompt_preset_groups";
const PROMPT_RESERVED_GROUPS = ["Batch"];
// ============================================
// Preset API helpers
@@ -114,15 +116,17 @@ 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
// Clean stale entries from groups (preserve reserved groups even if empty)
const validIds = new Set(promptPresets.map(p => p.id));
for (const g of Object.keys(pmGroups)) {
pmGroups[g] = (pmGroups[g] || []).filter(id => validIds.has(id));
if (pmGroups[g].length === 0) delete pmGroups[g];
if (pmGroups[g].length === 0 && !PROMPT_RESERVED_GROUPS.includes(g)) delete pmGroups[g];
}
// Ensure reserved groups always exist
for (const g of PROMPT_RESERVED_GROUPS) {
if (!pmGroups[g]) pmGroups[g] = [];
}
saveGroups();
@@ -213,6 +217,25 @@ function matchesSearch(p) {
(p.tags || []).some(t => t.toLowerCase().includes(s));
}
function isInBatchPreset(id) {
return (pmGroups["Batch"] || []).includes(id);
}
function toggleBatchPreset(id) {
const batch = pmGroups["Batch"] || [];
const idx = batch.indexOf(id);
if (idx >= 0) { batch.splice(idx, 1); } else { batch.push(id); }
pmGroups["Batch"] = batch;
saveGroups();
}
function clearBatchPresets() {
pmGroups["Batch"] = [];
saveGroups();
renderPresetManager();
showToast(t("promptBatchClear"), "success");
}
function createPmItem(preset) {
const el = document.createElement("div");
el.className = "wfm-pm-item" + (pmSelectedId === preset.id ? " active" : "");
@@ -225,12 +248,15 @@ function createPmItem(preset) {
? `<span style="font-size:9px;color:var(--wfm-primary);margin-left:4px;">[${esc(preset.category)}]</span>`
: "";
const inBatch = isInBatchPreset(preset.id);
el.innerHTML = `
<div class="wfm-pm-item-body">
<div class="wfm-pm-item-name">${preset.favorite ? '<span style="color:#ffd700;">&#9733;</span> ' : ""}${esc(preset.name)}${catBadge}</div>
<div class="wfm-pm-item-sub">${esc(previewText)}</div>
</div>
<div class="wfm-pm-item-actions">
<button class="wfm-pm-action-btn pm-batch-btn${inBatch ? " batch-active" : ""}" title="Batch">B</button>
<button class="wfm-pm-action-btn pm-fav-btn${preset.favorite ? " fav-active" : ""}" title="Favorite">&#9733;</button>
<button class="wfm-pm-action-btn pm-del-btn" title="Delete" style="color:var(--wfm-danger);">&#10005;</button>
</div>
@@ -242,6 +268,13 @@ function createPmItem(preset) {
selectPresetInEditor(preset);
});
// Batch toggle
el.querySelector(".pm-batch-btn").addEventListener("click", (e) => {
e.stopPropagation();
toggleBatchPreset(preset.id);
renderPresetManager();
});
// Favorite toggle
el.querySelector(".pm-fav-btn").addEventListener("click", async (e) => {
e.stopPropagation();
@@ -977,18 +1010,14 @@ export function initPromptTab() {
});
if (created) {
promptPresets.push(created);
pmSelectedId = created.id;
showToast(t("presetSaved"), "success");
}
}
pmSelectedId = null;
renderPresetSelect();
renderPresetManager();
// Re-select
if (pmSelectedId && presetSelect) {
presetSelect.value = pmSelectedId;
}
if (presetSelect) presetSelect.value = "";
});
// Apply preset to GenerateUI
@@ -1020,50 +1049,54 @@ 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)) {
showToast(t("modelsGroupReserved"), "warning");
return;
}
if (!confirm(`Delete group "${groupName}"?`)) return;
delete pmGroups[groupName];
saveGroups();
renderPresetManager();
showToast(`Group "${groupName}" deleted`, "success");
showToast(t("groupDeleted", groupName), "success");
});
// --- Preset Manager ---
@@ -1081,6 +1114,10 @@ export function initPromptTab() {
renderPresetManager();
});
document.getElementById("wfm-pm-batch-clear-btn")?.addEventListener("click", () => {
clearBatchPresets();
});
// ── Center column tab switching ──────────────────────────
document.querySelectorAll(".wfm-prompt-center-tab").forEach(btn => {
btn.addEventListener("click", () => {
@@ -1122,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);
@@ -1160,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", () => {
@@ -1169,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", () => {
@@ -1197,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");
}
});
@@ -1221,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();
});
+190 -7
View File
@@ -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) {
@@ -314,6 +312,60 @@ function clearCustomOverrides() {
if (fontEl) fontEl.remove();
}
const TEXTAREA_FONT_SIZE_DEFAULT = 13;
const TEXTAREA_FONT_SIZE_STYLE_ID = "wfm-ta-font-size-style";
const TEXTAREA_FONT_SIZE_TARGETS = [
"#wfm-prompt-pos-text",
"#wfm-prompt-neg-text",
"#wfm-ollama-input",
"#wfm-preset-pos",
"#wfm-preset-neg",
"#wfm-wc-prompt",
"#wfm-wc-editor-content",
"#wfm-meta-prompt-full",
].join(",\n ");
export function applyTextareaFontSize(size) {
const px = Math.max(10, Math.min(28, parseInt(size) || TEXTAREA_FONT_SIZE_DEFAULT));
let el = document.getElementById(TEXTAREA_FONT_SIZE_STYLE_ID);
if (!el) {
el = document.createElement("style");
el.id = TEXTAREA_FONT_SIZE_STYLE_ID;
document.head.appendChild(el);
}
el.textContent = `${TEXTAREA_FONT_SIZE_TARGETS} { font-size: ${px}px !important; }`;
}
// JSON highlight color settings
const JSON_COLOR_STYLE_ID = "wfm-json-color-style";
const JSON_COLOR_DEFS = [
{ id: "base", label: () => t("jsonColorBase") || "通常テキスト", def: "#abb2bf" },
{ id: "yellow", label: () => t("jsonColorYellow") || "名前 / スケジューラ", def: "#e5c07b" },
{ id: "pink", label: () => t("jsonColorPink") || "タイトル", def: "#c678dd" },
{ id: "green", label: () => t("jsonColorGreen") || "Width / Height", def: "#98c379" },
{ id: "cyan", label: () => t("jsonColorCyan") || "プロンプト / テキスト", def: "#61afef" },
{ id: "red", label: () => t("jsonColorRed") || "画像 / ファイル", def: "#e06c75" },
];
export function applyJsonColors(colors) {
const vals = Object.fromEntries(JSON_COLOR_DEFS.map(d => [d.id, colors?.[d.id] || d.def]));
let el = document.getElementById(JSON_COLOR_STYLE_ID);
if (!el) {
el = document.createElement("style");
el.id = JSON_COLOR_STYLE_ID;
document.head.appendChild(el);
}
el.textContent = [
`.wfm-json-highlight { color: ${vals.base}; }`,
`.json-key-yellow, .json-val-yellow { color: ${vals.yellow}; }`,
`.json-key-pink, .json-val-pink { color: ${vals.pink}; }`,
`.json-key-green, .json-val-green { color: ${vals.green}; }`,
`.json-key-cyan, .json-val-cyan { color: ${vals.cyan}; }`,
`.json-key-red, .json-val-red { color: ${vals.red}; }`,
].join("\n");
}
export function applyTheme(themeId) {
if (themeId) {
document.documentElement.setAttribute("data-theme", themeId);
@@ -339,6 +391,11 @@ export async function initSettingsTab() {
const settings = loadLocalSettings();
const serverSettings = await loadServerSettings();
// Sync civitai_host to localStorage so other tabs can read it without an extra fetch
if (serverSettings.civitai_host) {
localStorage.setItem("wfm_civitai_host", serverSettings.civitai_host);
}
// Load current workflows dir info
let workflowsDirInfo = { current: "", default: "" };
try {
@@ -485,6 +542,41 @@ export async function initSettingsTab() {
</div>
</details>
<!-- Text Size -->
<details class="wfm-settings-section" open>
<summary class="wfm-settings-summary">${t("textSizeLabel") || "Text Size"}</summary>
<div class="wfm-form-group">
<label style="display:flex;align-items:center;justify-content:space-between;">
<span>${t("textSizeTextarea") || "Prompt / Chat Textarea"}</span>
<span id="wfm-ta-font-size-val" style="font-size:12px;color:var(--wfm-text-secondary);">${settings.textareaFontSize || TEXTAREA_FONT_SIZE_DEFAULT}px</span>
</label>
<input type="range" class="wfm-range" id="wfm-ta-font-size"
min="10" max="28" step="1"
value="${settings.textareaFontSize || TEXTAREA_FONT_SIZE_DEFAULT}"
style="width:100%;margin-top:4px;">
<small style="color:var(--wfm-text-secondary);font-size:11px;display:block;margin-top:4px;">
${t("textSizeHint") || "Applies to: Generate UI prompts, AI Assistant chat, Preset prompts, Wildcard textarea, Metadata prompt preview"}
</small>
</div>
</details>
<!-- RAW JSON Colors -->
<details class="wfm-settings-section" open>
<summary class="wfm-settings-summary">${t("jsonColorsSection") || "RAW JSON Colors"}</summary>
<div class="wfm-form-group">
<div class="wfm-color-grid" id="wfm-json-color-grid">
${JSON_COLOR_DEFS.map(d => {
const saved = settings.jsonColors?.[d.id] || d.def;
return `<div class="wfm-color-item">
<label>${d.label()}</label>
<input type="color" data-json-color="${d.id}" value="${saved}">
</div>`;
}).join("")}
</div>
<button class="wfm-btn wfm-btn-sm" id="wfm-json-color-reset" style="margin-top:8px;">${t("jsonColorReset") || "デフォルトに戻す"}</button>
</div>
</details>
<!-- Workflow Data Folder -->
<details class="wfm-settings-section">
<summary class="wfm-settings-summary">${t("workflowsDir")}</summary>
@@ -570,6 +662,36 @@ export async function initSettingsTab() {
</div>
</details>
<!-- CivitAI Settings -->
<details class="wfm-settings-section">
<summary class="wfm-settings-summary">${t("civitaiApiKeySetting")}</summary>
<div class="wfm-form-group">
<label style="display:flex;align-items:center;gap:4px;">
${t("civitaiHostSetting")}
<span title="${t("civitaiHostHint")}" style="cursor:help;color:var(--wfm-text-secondary);font-size:13px;">ℹ</span>
</label>
<select class="wfm-select" id="wfm-settings-civitai-host" style="width:100%;">
<option value="civitai.com" ${(serverSettings.civitai_host || "civitai.com") === "civitai.com" ? "selected" : ""}>${t("civitaiHostCom")}</option>
<option value="civitai.red" ${serverSettings.civitai_host === "civitai.red" ? "selected" : ""}>${t("civitaiHostRed")}</option>
</select>
</div>
<div class="wfm-form-group">
<small style="color:var(--wfm-text-secondary);font-size:11px;display:block;margin-bottom:8px;">
${t("civitaiApiKeyHint")}
</small>
<div style="display:flex;gap:8px;">
<input type="password" class="wfm-input" id="wfm-settings-civitai-api-key"
value="${serverSettings.civitai_api_key || ""}"
placeholder="${t("civitaiApiKeyPlaceholder")}"
style="flex:1;">
<button class="wfm-btn wfm-btn-primary wfm-btn-sm" id="wfm-settings-civitai-api-key-save">
${t("civitaiApiKeySave")}
</button>
</div>
<div id="wfm-settings-civitai-api-key-status" style="font-size:12px;margin-top:4px;"></div>
</div>
</details>
<!-- Default Workflow -->
<details class="wfm-settings-section">
<summary class="wfm-settings-summary">${t("defaultWorkflow")}</summary>
@@ -836,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);
});
@@ -982,6 +1104,36 @@ export async function initSettingsTab() {
}
});
// CivitAI host select
document.getElementById("wfm-settings-civitai-host")?.addEventListener("change", async (e) => {
const host = e.target.value;
try {
await saveServerSettings({ civitai_host: host });
serverSettings.civitai_host = host;
localStorage.setItem("wfm_civitai_host", host);
showToast(t("civitaiHostSaved"), "success");
} catch (err) {
showToast(`${t("saveError")}: ${err.message}`, "error");
}
});
// Save CivitAI API key
document.getElementById("wfm-settings-civitai-api-key-save")?.addEventListener("click", async () => {
const apiKey = document.getElementById("wfm-settings-civitai-api-key")?.value.trim() || "";
const statusEl = document.getElementById("wfm-settings-civitai-api-key-status");
try {
await saveServerSettings({ civitai_api_key: apiKey });
serverSettings.civitai_api_key = apiKey;
showToast(t("civitaiApiKeySaved"), "success");
if (statusEl) { statusEl.textContent = ""; }
} catch (err) {
if (statusEl) {
statusEl.textContent = `${t("saveError")}: ${err.message}`;
statusEl.style.color = "var(--wfm-danger)";
}
}
});
// Test ComfyUI URL
document.getElementById("wfm-settings-test-url")?.addEventListener("click", async () => {
const urlInput = document.getElementById("wfm-settings-comfyui-url");
@@ -1022,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));
@@ -1032,8 +1184,38 @@ export async function initSettingsTab() {
showToast(t("defaultWorkflowCleared"), "success");
});
// --- Textarea font size slider ---
document.getElementById("wfm-ta-font-size")?.addEventListener("input", (e) => {
const px = parseInt(e.target.value);
const valEl = document.getElementById("wfm-ta-font-size-val");
if (valEl) valEl.textContent = `${px}px`;
applyTextareaFontSize(px);
});
// --- JSON highlight color pickers ---
document.getElementById("wfm-json-color-grid")?.addEventListener("input", (e) => {
if (e.target.type !== "color") return;
const id = e.target.dataset.jsonColor;
const jsonColors = { ...(loadLocalSettings().jsonColors || {}), [id]: e.target.value };
saveLocalSettings({ jsonColors });
applyJsonColors(jsonColors);
});
document.getElementById("wfm-json-color-reset")?.addEventListener("click", () => {
const cur = loadLocalSettings();
delete cur.jsonColors;
localStorage.setItem(SETTINGS_KEY, JSON.stringify(cur));
applyJsonColors(undefined);
document.querySelectorAll("#wfm-json-color-grid input[type=color]").forEach(inp => {
const def = JSON_COLOR_DEFS.find(d => d.id === inp.dataset.jsonColor);
if (def) inp.value = def.def;
});
showToast(t("settingsSaved"), "success");
});
// Save (local settings)
document.getElementById("wfm-settings-save")?.addEventListener("click", () => {
const taFontSize = parseInt(document.getElementById("wfm-ta-font-size")?.value) || TEXTAREA_FONT_SIZE_DEFAULT;
const patch = {
comfyuiUrl: document.getElementById("wfm-settings-comfyui-url")?.value.trim() || "",
eagleUrl: document.getElementById("wfm-settings-eagle-url")?.value.trim() || "http://localhost:41595",
@@ -1041,6 +1223,7 @@ export async function initSettingsTab() {
uiLang: getLang(),
summaryLang: getSummaryLang(),
theme: document.documentElement.getAttribute("data-theme") || "",
textareaFontSize: taFontSize,
};
saveLocalSettings(patch);
+667
View File
@@ -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, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;");
}
function _truncate(str, len) {
if (!str) return "";
return str.length > len ? str.slice(0, len) + "…" : str;
}
+27
View File
@@ -0,0 +1,27 @@
/**
* Shared utilities
*/
// HTMLエスケープ(属性値で使うため " も必ずエスケープする)
export function escapeHtml(s) {
return String(s)
.replace(/&/g, "&amp;")
.replace(/</g, "&lt;")
.replace(/>/g, "&gt;")
.replace(/"/g, "&quot;");
}
// 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");
}
+119 -48
View File
@@ -10,6 +10,12 @@ 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
// ============================================
const WF_RESERVED_GROUPS = ["Batch"];
// ============================================
// State
@@ -19,34 +25,36 @@ const state = {
workflows: [],
activeBadge: "ALL",
searchText: "",
viewMode: localStorage.getItem("wfm_default_view") || "thumb", // thumb | card | table
viewMode: localStorage.getItem("wfm_default_view") === "table" ? "table" : "thumb",
selectedWf: null,
groupFilter: "", // empty = all groups
currentPage: 0,
showBatchOnly: false,
};
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, "&amp;")
.replace(/</g, "&lt;")
.replace(/>/g, "&gt;")
.replace(/"/g, "&quot;");
}
// ============================================
// Open in ComfyUI
// Open in ComfyUI / Send to Canvas
// ============================================
function sendToCanvas(workflowData) {
try {
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.
@@ -88,10 +96,15 @@ const groups = {
load() {
try {
this._data = JSON.parse(localStorage.getItem("wfm_groups") || "{}");
this._data = readJsonStorage("wfm_groups");
} catch {
this._data = {};
}
let needsSave = false;
for (const g of WF_RESERVED_GROUPS) {
if (!this._data[g]) { this._data[g] = []; needsSave = true; }
}
if (needsSave) this.save();
return this._data;
},
save() {
@@ -117,11 +130,14 @@ const groups = {
},
deleteGroup(name) {
if (WF_RESERVED_GROUPS.includes(name)) return false;
delete this.data[name];
this.save();
return true;
},
renameGroup(oldName, newName) {
if (WF_RESERVED_GROUPS.includes(oldName)) return false;
if (!newName || this.data[newName] || !this.data[oldName]) return false;
this.data[newName] = this.data[oldName];
delete this.data[oldName];
@@ -154,6 +170,32 @@ const groups = {
},
};
// ============================================
// Batch helpers
// ============================================
function isInBatch(filename) {
return (groups.data["Batch"] || []).includes(filename);
}
function toggleBatch(filename) {
const batch = groups.data["Batch"] || [];
const idx = batch.indexOf(filename);
if (idx >= 0) { batch.splice(idx, 1); } else { batch.push(filename); }
groups.data["Batch"] = batch;
groups.save();
renderGrid();
}
function clearBatch() {
groups.data["Batch"] = [];
groups.save();
state.showBatchOnly = false;
renderModelFilters();
renderGrid();
showToast(t("wfBatchClear"), "success");
}
// ============================================
// API
// ============================================
@@ -250,6 +292,7 @@ function renderModelFilters() {
container.innerHTML = `
<button class="wfm-filter-btn ${state.activeBadge === "ALL" ? "active" : ""}" data-filter="ALL">ALL</button>
<button class="wfm-filter-btn ${state.activeBadge === "FAVORITE" ? "active" : ""}" data-filter="FAVORITE">&#9733;</button>
<button class="wfm-filter-btn wfm-wf-batch-filter-btn${state.showBatchOnly ? " active" : ""}">B</button>
${badges.map((b) => {
const color = palette[b] || "";
const style = color ? ` style="background:${color};color:#fff;"` : "";
@@ -259,6 +302,13 @@ function renderModelFilters() {
container.querySelectorAll(".wfm-filter-btn").forEach((btn) => {
btn.addEventListener("click", () => {
if (btn.classList.contains("wfm-wf-batch-filter-btn")) {
state.showBatchOnly = !state.showBatchOnly;
state.currentPage = 0;
renderModelFilters();
renderGrid();
return;
}
state.activeBadge = btn.dataset.filter;
state.currentPage = 0;
renderModelFilters();
@@ -278,6 +328,11 @@ function filterWorkflows() {
return false;
}
// Batch filter
if (state.showBatchOnly) {
if (!(groups.data["Batch"] || []).includes(wf.filename)) return false;
}
// Group filter
if (state.groupFilter) {
const grpFiles = groups.data[state.groupFilter] || [];
@@ -333,30 +388,24 @@ function renderGrid() {
card.dataset.filename = wf.filename;
const hasThumb = !!wf.thumbnail;
const badges = wfBadgesHtml(wf);
const tags = (wf.metadata.tags || []).map((t) => `<span class="wfm-tag">#${t}</span>`).join("");
const favStar = wf.metadata.favorite ? "\u2605" : "\u2606";
const favClass = wf.metadata.favorite ? "wfm-fav-btn active" : "wfm-fav-btn";
if (state.viewMode === "thumb") {
card.innerHTML = `
<div class="wfm-card-thumb">${hasThumb ? `<img src="${wf.thumbnail}" loading="lazy" />` : `<span class="wfm-card-thumb-placeholder">${t("noImage")}</span>`}</div>
card.innerHTML = `
<div class="wfm-card-thumb">
${hasThumb ? `<img src="${wf.thumbnail}" loading="lazy" />` : `<span class="wfm-card-thumb-placeholder">${t("noImage")}</span>`}
<button class="wfm-batch-btn${isInBatch(wf.filename) ? ' active' : ''}" title="Batch">B</button>
</div>
<div class="wfm-card-body">
<div class="wfm-card-title" title="${wf.filename}">${wf.filename.replace(/\.json$/, "")}</div>
<div class="wfm-card-meta">${badges}</div>
</div>
<button class="${favClass}" title="${t("favorite")}">${favStar}</button>`;
} else {
// Card view: no thumbnail, more meta info
const io = `P:${wf.analysis.inputs?.prompts || 0} I:${wf.analysis.inputs?.images || 0} → ${wf.analysis.outputs?.images || 0}`;
card.innerHTML = `
<div class="wfm-card-body">
<div class="wfm-card-title" title="${wf.filename}">${wf.filename.replace(/\.json$/, "")}</div>
<div class="wfm-card-meta">${badges}</div>
<div class="wfm-card-io">${io}</div>
<div class="wfm-card-tags">${tags}</div>
</div>
<button class="${favClass}" title="${t("favorite")}">${favStar}</button>`;
}
card.querySelector(".wfm-batch-btn")?.addEventListener("click", (e) => {
e.stopPropagation();
toggleBatch(wf.filename);
});
card.querySelector(".wfm-fav-btn")?.addEventListener("click", (e) => {
e.stopPropagation();
@@ -390,6 +439,7 @@ function renderTableView(grid, filtered) {
<th style="width:60px;">${t("tags")}</th>
<th class="wfm-table-th-memo">${t("memo")}</th>
<th class="wfm-table-th-summary">${t("summary")}</th>
<th style="width:30px;"></th>
</tr></thead>`;
const tbody = document.createElement("tbody");
@@ -414,7 +464,13 @@ function renderTableView(grid, filtered) {
<td class="wfm-table-td-io">${io}</td>
<td>${tags}</td>
<td class="wfm-table-td-memo" title="${(wf.metadata.memo || "").replace(/"/g, "&quot;")}">${wf.metadata.memo || ""}</td>
<td class="wfm-table-td-summary" title="${(wf.metadata.summary || "").replace(/"/g, "&quot;")}">${wf.metadata.summary || ""}</td>`;
<td class="wfm-table-td-summary" title="${(wf.metadata.summary || "").replace(/"/g, "&quot;")}">${wf.metadata.summary || ""}</td>
<td class="wfm-table-td-batch"><button class="wfm-batch-btn${isInBatch(wf.filename) ? ' active' : ''}" title="Batch">B</button></td>`;
tr.querySelector(".wfm-batch-btn")?.addEventListener("click", (e) => {
e.stopPropagation();
toggleBatch(wf.filename);
});
tr.querySelector(".wfm-fav-btn")?.addEventListener("click", (e) => {
e.stopPropagation();
@@ -447,7 +503,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");
}
}
@@ -623,7 +679,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");
});
});
@@ -633,7 +689,7 @@ function renderSideGroup(wf) {
if (!g) return;
groups.assign(filename, g);
renderSideGroup(wf);
showToast(`Added to "${g}"`, "success");
showToast(t("addedToGroupName", g), "success");
});
// グループ作成(作成後に現在のWFに追加)
@@ -642,36 +698,44 @@ 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");
});
// グループ名変更
el.querySelector("#wfm-grp-rename-btn")?.addEventListener("click", () => {
const oldName = el.querySelector("#wfm-grp-manage-sel")?.value;
if (!oldName) return;
if (WF_RESERVED_GROUPS.includes(oldName)) {
showToast(t("modelsGroupReserved"), "warning");
return;
}
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");
});
// グループ削除
el.querySelector("#wfm-grp-delete-btn")?.addEventListener("click", () => {
const name = el.querySelector("#wfm-grp-manage-sel")?.value;
if (!name) return;
if (WF_RESERVED_GROUPS.includes(name)) {
showToast(t("modelsGroupReserved"), "warning");
return;
}
if (!confirm(`Delete group "${name}"?`)) return;
groups.deleteGroup(name);
if (state.groupFilter === name) {
@@ -681,7 +745,7 @@ function renderSideGroup(wf) {
}
renderSideGroup(wf);
_refreshGroupFilter();
showToast(`Group "${name}" deleted`, "success");
showToast(t("groupDeleted", name), "success");
});
_refreshGroupFilter();
@@ -803,7 +867,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">
@@ -841,7 +905,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);
@@ -884,6 +948,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(); }
@@ -951,11 +1017,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");
}
@@ -972,7 +1038,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));
@@ -1122,7 +1188,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 = "";
});
@@ -1165,10 +1231,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");
}
});
}
@@ -1228,12 +1294,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");
}
@@ -1242,7 +1308,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)
@@ -1271,6 +1337,11 @@ export function initWorkflowTab() {
openBadgeEditModal(() => renderGrid());
});
// Toolbar: BC (batch clear) button
document.getElementById("wfm-wf-batch-clear-btn")?.addEventListener("click", () => {
clearBatch();
});
// Initial load
loadWorkflows();
}
+845 -266
View File
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
+16 -33
View File
@@ -605,50 +605,33 @@ app.registerExtension({
};
injectStyles();
const applyButtonIcon = (button, className, getIconFn, extraStyles) => {
if (button.querySelector("svg")) return;
button.classList.add(className);
button.innerHTML = getIconFn();
button.style.borderRadius = "4px";
button.style.padding = "6px";
if (extraStyles) Object.assign(button.style, extraStyles);
const svg = button.querySelector("svg");
if (svg) {
svg.style.width = "20px";
svg.style.height = "20px";
}
};
const buttonConfigs = [
{ tooltip: BUTTON_TOOLTIP, className: "wfm-top-menu-button", getIcon: getWfmIcon, styles: { backgroundColor: "var(--primary-bg)" } },
{ tooltip: SNAPSHOT_TOOLTIP, className: "wfm-snapshot-button", getIcon: getSnapshotIcon, styles: null },
{ tooltip: NODE_SETS_TOOLTIP, className: "wfm-node-sets-btn", getIcon: getNodeSetsIcon, styles: null },
];
const replaceAllIcons = () => {
const replaceButtonIcons = () => {
let foundAny = false;
for (const cfg of buttonConfigs) {
document.querySelectorAll(`button[aria-label="${cfg.tooltip}"]`).forEach((btn) => {
applyButtonIcon(btn, cfg.className, cfg.getIcon, cfg.styles);
foundAny = true;
btn.classList.add(cfg.className);
btn.innerHTML = cfg.getIcon();
btn.style.borderRadius = "4px";
btn.style.padding = "6px";
if (cfg.styles) Object.assign(btn.style, cfg.styles);
const svg = btn.querySelector("svg");
if (svg) {
svg.style.width = "20px";
svg.style.height = "20px";
}
});
}
};
const waitAndObserve = () => {
const firstBtn = document.querySelector(`button[aria-label="${BUTTON_TOOLTIP}"]`);
if (!firstBtn) {
requestAnimationFrame(waitAndObserve);
return;
}
replaceAllIcons();
const container = firstBtn.closest(".actionbar-container") || firstBtn.parentElement;
if (container) {
new MutationObserver(() => replaceAllIcons()).observe(container, {
childList: true,
subtree: true,
});
if (!foundAny) {
requestAnimationFrame(replaceButtonIcons);
}
};
requestAnimationFrame(waitAndObserve);
requestAnimationFrame(replaceButtonIcons);
},
});
File diff suppressed because one or more lines are too long
Binary file not shown.

After

Width:  |  Height:  |  Size: 192 KiB

File diff suppressed because one or more lines are too long
Binary file not shown.

After

Width:  |  Height:  |  Size: 758 KiB

File diff suppressed because one or more lines are too long
Binary file not shown.

After

Width:  |  Height:  |  Size: 246 KiB

File diff suppressed because it is too large Load Diff
Binary file not shown.

After

Width:  |  Height:  |  Size: 316 KiB

+599
View File
@@ -0,0 +1,599 @@
{
"id": "f11699d9-4b62-47bd-b501-e49d609d9810",
"revision": 0,
"last_node_id": 10,
"last_link_id": 10,
"nodes": [
{
"id": 7,
"type": "CLIPTextEncode",
"pos": [
413,
389
],
"size": [
425.27801513671875,
180.6060791015625
],
"flags": {},
"order": 4,
"mode": 0,
"inputs": [
{
"localized_name": "clip",
"name": "clip",
"type": "CLIP",
"link": 5
},
{
"localized_name": "text",
"name": "text",
"type": "STRING",
"widget": {
"name": "text"
},
"link": null
}
],
"outputs": [
{
"localized_name": "CONDITIONING",
"name": "CONDITIONING",
"type": "CONDITIONING",
"slot_index": 0,
"links": [
6
]
}
],
"properties": {
"Node name for S&R": "CLIPTextEncode",
"ue_properties": {
"widget_ue_connectable": {},
"version": "7.8",
"input_ue_unconnectable": {}
}
},
"widgets_values": [
"text, watermark"
]
},
{
"id": 3,
"type": "KSampler",
"pos": [
863,
186
],
"size": [
315,
474
],
"flags": {},
"order": 5,
"mode": 0,
"inputs": [
{
"localized_name": "model",
"name": "model",
"type": "MODEL",
"link": 1
},
{
"localized_name": "positive",
"name": "positive",
"type": "CONDITIONING",
"link": 4
},
{
"localized_name": "negative",
"name": "negative",
"type": "CONDITIONING",
"link": 6
},
{
"localized_name": "latent_image",
"name": "latent_image",
"type": "LATENT",
"link": 2
},
{
"localized_name": "seed",
"name": "seed",
"type": "INT",
"widget": {
"name": "seed"
},
"link": null
},
{
"localized_name": "steps",
"name": "steps",
"type": "INT",
"widget": {
"name": "steps"
},
"link": null
},
{
"localized_name": "cfg",
"name": "cfg",
"type": "FLOAT",
"widget": {
"name": "cfg"
},
"link": null
},
{
"localized_name": "sampler_name",
"name": "sampler_name",
"type": "COMBO",
"widget": {
"name": "sampler_name"
},
"link": null
},
{
"localized_name": "scheduler",
"name": "scheduler",
"type": "COMBO",
"widget": {
"name": "scheduler"
},
"link": null
},
{
"localized_name": "denoise",
"name": "denoise",
"type": "FLOAT",
"widget": {
"name": "denoise"
},
"link": null
}
],
"outputs": [
{
"localized_name": "LATENT",
"name": "LATENT",
"type": "LATENT",
"slot_index": 0,
"links": [
7
]
}
],
"properties": {
"Node name for S&R": "KSampler",
"ue_properties": {
"widget_ue_connectable": {},
"version": "7.8",
"input_ue_unconnectable": {}
}
},
"widgets_values": [
378124453179007,
"randomize",
20,
8,
"euler",
"normal",
1
]
},
{
"id": 8,
"type": "VAEDecode",
"pos": [
1209,
188
],
"size": [
210,
46
],
"flags": {},
"order": 6,
"mode": 0,
"inputs": [
{
"localized_name": "samples",
"name": "samples",
"type": "LATENT",
"link": 7
},
{
"localized_name": "vae",
"name": "vae",
"type": "VAE",
"link": 10
}
],
"outputs": [
{
"localized_name": "IMAGE",
"name": "IMAGE",
"type": "IMAGE",
"slot_index": 0,
"links": [
9
]
}
],
"properties": {
"Node name for S&R": "VAEDecode",
"ue_properties": {
"widget_ue_connectable": {},
"version": "7.8",
"input_ue_unconnectable": {}
}
},
"widgets_values": []
},
{
"id": 9,
"type": "SaveImage",
"pos": [
1451,
189
],
"size": [
210,
270
],
"flags": {},
"order": 7,
"mode": 0,
"inputs": [
{
"localized_name": "images",
"name": "images",
"type": "IMAGE",
"link": 9
},
{
"localized_name": "filename_prefix",
"name": "filename_prefix",
"type": "STRING",
"widget": {
"name": "filename_prefix"
},
"link": null
}
],
"outputs": [],
"properties": {
"Node name for S&R": "SaveImage",
"ue_properties": {
"widget_ue_connectable": {},
"version": "7.8",
"input_ue_unconnectable": {}
}
},
"widgets_values": [
"ComfyUI"
]
},
{
"id": 5,
"type": "EmptyLatentImage",
"pos": [
473,
609
],
"size": [
315,
106
],
"flags": {},
"order": 0,
"mode": 0,
"inputs": [
{
"localized_name": "width",
"name": "width",
"type": "INT",
"widget": {
"name": "width"
},
"link": null
},
{
"localized_name": "height",
"name": "height",
"type": "INT",
"widget": {
"name": "height"
},
"link": null
},
{
"localized_name": "batch_size",
"name": "batch_size",
"type": "INT",
"widget": {
"name": "batch_size"
},
"link": null
}
],
"outputs": [
{
"localized_name": "LATENT",
"name": "LATENT",
"type": "LATENT",
"slot_index": 0,
"links": [
2
]
}
],
"properties": {
"Node name for S&R": "EmptyLatentImage",
"ue_properties": {
"widget_ue_connectable": {},
"version": "7.8",
"input_ue_unconnectable": {}
}
},
"widgets_values": [
1024,
1024,
1
]
},
{
"id": 4,
"type": "CheckpointLoaderSimple",
"pos": [
51.3,
182.49999999999997
],
"size": [
315,
98
],
"flags": {},
"order": 1,
"mode": 0,
"inputs": [
{
"localized_name": "ckpt_name",
"name": "ckpt_name",
"type": "COMBO",
"widget": {
"name": "ckpt_name"
},
"link": null
}
],
"outputs": [
{
"localized_name": "MODEL",
"name": "MODEL",
"type": "MODEL",
"slot_index": 0,
"links": [
1
]
},
{
"localized_name": "CLIP",
"name": "CLIP",
"type": "CLIP",
"slot_index": 1,
"links": [
3,
5
]
},
{
"localized_name": "VAE",
"name": "VAE",
"type": "VAE",
"slot_index": 2,
"links": []
}
],
"properties": {
"Node name for S&R": "CheckpointLoaderSimple",
"ue_properties": {
"widget_ue_connectable": {},
"version": "7.8",
"input_ue_unconnectable": {}
}
},
"widgets_values": [
"v1-5-pruned-emaonly-fp16.safetensors"
]
},
{
"id": 10,
"type": "VAELoader",
"pos": [
61.897062649999256,
347.8818042399999
],
"size": [
270,
58
],
"flags": {},
"order": 2,
"mode": 0,
"inputs": [
{
"localized_name": "vae_name",
"name": "vae_name",
"type": "COMBO",
"widget": {
"name": "vae_name"
},
"link": null
}
],
"outputs": [
{
"localized_name": "VAE",
"name": "VAE",
"type": "VAE",
"links": [
10
]
}
],
"properties": {
"ue_properties": {
"widget_ue_connectable": {},
"input_ue_unconnectable": {}
},
"Node name for S&R": "VAELoader"
},
"widgets_values": [
"vae-ft-mse-840000-ema-pruned.safetensors"
]
},
{
"id": 6,
"type": "CLIPTextEncode",
"pos": [
415,
186
],
"size": [
422.84503173828125,
164.31304931640625
],
"flags": {},
"order": 3,
"mode": 0,
"inputs": [
{
"localized_name": "clip",
"name": "clip",
"type": "CLIP",
"link": 3
},
{
"localized_name": "text",
"name": "text",
"type": "STRING",
"widget": {
"name": "text"
},
"link": null
}
],
"outputs": [
{
"localized_name": "CONDITIONING",
"name": "CONDITIONING",
"type": "CONDITIONING",
"slot_index": 0,
"links": [
4
]
}
],
"properties": {
"Node name for S&R": "CLIPTextEncode",
"ue_properties": {
"widget_ue_connectable": {},
"version": "7.8",
"input_ue_unconnectable": {}
}
},
"widgets_values": [
"flower"
]
}
],
"links": [
[
1,
4,
0,
3,
0,
"MODEL"
],
[
2,
5,
0,
3,
3,
"LATENT"
],
[
3,
4,
1,
6,
0,
"CLIP"
],
[
4,
6,
0,
3,
1,
"CONDITIONING"
],
[
5,
4,
1,
7,
0,
"CLIP"
],
[
6,
7,
0,
3,
2,
"CONDITIONING"
],
[
7,
3,
0,
8,
0,
"LATENT"
],
[
9,
8,
0,
9,
0,
"IMAGE"
],
[
10,
10,
0,
8,
1,
"VAE"
]
],
"groups": [],
"config": {},
"extra": {
"ds": {
"offset": [
0,
0
],
"scale": 1
},
"ue_links": [],
"links_added_by_ue": []
},
"version": 0.4
}
Binary file not shown.

After

Width:  |  Height:  |  Size: 167 KiB

File diff suppressed because one or more lines are too long
Binary file not shown.

After

Width:  |  Height:  |  Size: 309 KiB

File diff suppressed because one or more lines are too long
Binary file not shown.

After

Width:  |  Height:  |  Size: 741 KiB

File diff suppressed because it is too large Load Diff
Binary file not shown.

After

Width:  |  Height:  |  Size: 303 KiB

+887
View File
@@ -0,0 +1,887 @@
{
"id": "831a2929-0536-4715-a530-72a8b91c00fd",
"revision": 0,
"last_node_id": 13,
"last_link_id": 21,
"nodes": [
{
"id": 12,
"type": "CLIPTextEncodeEditPlus",
"pos": [
1364.9859298350216,
-408.28982585532515
],
"size": [
300,
257
],
"flags": {},
"order": 4,
"mode": 0,
"inputs": [
{
"localized_name": "clip",
"name": "clip",
"type": "CLIP",
"link": 16
},
{
"localized_name": "text1",
"name": "text1",
"type": "STRING",
"link": 18
},
{
"localized_name": "text2",
"name": "text2",
"shape": 7,
"type": "STRING",
"link": null
},
{
"localized_name": "text_edit",
"name": "text_edit",
"type": "STRING",
"widget": {
"name": "text_edit"
},
"link": null
},
{
"localized_name": "mode",
"name": "mode",
"type": "COMBO",
"widget": {
"name": "mode"
},
"link": null
}
],
"outputs": [
{
"localized_name": "conditioning",
"name": "conditioning",
"type": "CONDITIONING",
"links": [
17
]
},
{
"localized_name": "text",
"name": "text",
"type": "STRING",
"links": [
21
]
}
],
"properties": {
"ue_properties": {
"widget_ue_connectable": {},
"input_ue_unconnectable": {}
},
"Node name for S&R": "CLIPTextEncodeEditPlus"
},
"widgets_values": [
"blue flower",
"+af",
""
]
},
{
"id": 3,
"type": "KSampler",
"pos": [
1742.6139298350226,
-576.3158258553248
],
"size": [
315,
474
],
"flags": {},
"order": 5,
"mode": 0,
"inputs": [
{
"localized_name": "model",
"name": "model",
"type": "MODEL",
"link": 15
},
{
"localized_name": "positive",
"name": "positive",
"type": "CONDITIONING",
"link": 17
},
{
"localized_name": "negative",
"name": "negative",
"type": "CONDITIONING",
"link": 5
},
{
"localized_name": "latent_image",
"name": "latent_image",
"type": "LATENT",
"link": 6
},
{
"localized_name": "seed",
"name": "seed",
"type": "INT",
"widget": {
"name": "seed"
},
"link": null
},
{
"localized_name": "steps",
"name": "steps",
"type": "INT",
"widget": {
"name": "steps"
},
"link": null
},
{
"localized_name": "cfg",
"name": "cfg",
"type": "FLOAT",
"widget": {
"name": "cfg"
},
"link": null
},
{
"localized_name": "sampler_name",
"name": "sampler_name",
"type": "COMBO",
"widget": {
"name": "sampler_name"
},
"link": null
},
{
"localized_name": "scheduler",
"name": "scheduler",
"type": "COMBO",
"widget": {
"name": "scheduler"
},
"link": null
},
{
"localized_name": "denoise",
"name": "denoise",
"type": "FLOAT",
"widget": {
"name": "denoise"
},
"link": null
}
],
"outputs": [
{
"localized_name": "LATENT",
"name": "LATENT",
"type": "LATENT",
"slot_index": 0,
"links": [
7
]
}
],
"properties": {
"ue_properties": {
"widget_ue_connectable": {},
"version": "7.8",
"input_ue_unconnectable": {}
},
"Node name for S&R": "KSampler"
},
"widgets_values": [
1018108390999488,
"randomize",
20,
8,
"euler",
"normal",
1
]
},
{
"id": 4,
"type": "VAEDecode",
"pos": [
2086.446929835019,
-568.6398258553247
],
"size": [
210,
46
],
"flags": {},
"order": 7,
"mode": 0,
"inputs": [
{
"localized_name": "samples",
"name": "samples",
"type": "LATENT",
"link": 7
},
{
"localized_name": "vae",
"name": "vae",
"type": "VAE",
"link": 20
}
],
"outputs": [
{
"localized_name": "IMAGE",
"name": "IMAGE",
"type": "IMAGE",
"slot_index": 0,
"links": [
12
]
}
],
"properties": {
"ue_properties": {
"widget_ue_connectable": {},
"version": "7.8",
"input_ue_unconnectable": {}
},
"Node name for S&R": "VAEDecode"
},
"widgets_values": []
},
{
"id": 9,
"type": "SaveImage",
"pos": [
2326.33789983502,
-566.7928258553247
],
"size": [
210,
270
],
"flags": {},
"order": 8,
"mode": 0,
"inputs": [
{
"localized_name": "images",
"name": "images",
"type": "IMAGE",
"link": 12
},
{
"localized_name": "filename_prefix",
"name": "filename_prefix",
"type": "STRING",
"widget": {
"name": "filename_prefix"
},
"link": null
}
],
"outputs": [],
"properties": {
"ue_properties": {
"widget_ue_connectable": {},
"version": "7.8",
"input_ue_unconnectable": {}
},
"Node name for S&R": "SaveImage"
},
"widgets_values": [
"ComfyUI"
]
},
{
"id": 13,
"type": "ShowText|pysssss",
"pos": [
1363.0960298350246,
-578.3718258553248
],
"size": [
305.77,
111.08999999999992
],
"flags": {},
"order": 6,
"mode": 0,
"inputs": [
{
"localized_name": "text",
"name": "text",
"type": "STRING",
"link": 21
}
],
"outputs": [
{
"localized_name": "STRING",
"name": "STRING",
"shape": 6,
"type": "STRING",
"links": null
}
],
"properties": {
"ue_properties": {
"widget_ue_connectable": {},
"input_ue_unconnectable": {}
},
"Node name for S&R": "ShowText|pysssss"
},
"widgets_values": [
"girl,sentai,sentai,flower petal,full body,long hair,long legs,white boots and white gloves,<lora:9_Toshikazu:0.4> Toshikazu,<lora:9_Iggym:0.3> Iggym, painterly, realistic, sketch, traditional media, \\(medium\\)\n<lora:9_Landuo941:0.3> Landuo941\n<lora:Manga122:0.2>,<lora:MayuMurataIllustrious:0.3> Mayu Murata\n<lora:9_Navybluesparrow:0.4> Navybluesparrow\n<lora:9_RiyokoIkeda:0.2> Riyoko Ikeda\n<lora:9_ShumiiberryAlt:0.2> Shumiiberry,\n<lora:Shuiyuan:0.2> 5huny4n_5ty13 \n<lora:test_mix:0.2>,,blue flower"
]
},
{
"id": 5,
"type": "EmptyLatentImage",
"pos": [
992.022929835024,
79.15817414467442
],
"size": [
271.44000000000005,
106
],
"flags": {},
"order": 0,
"mode": 0,
"inputs": [
{
"localized_name": "width",
"name": "width",
"type": "INT",
"widget": {
"name": "width"
},
"link": null
},
{
"localized_name": "height",
"name": "height",
"type": "INT",
"widget": {
"name": "height"
},
"link": null
},
{
"localized_name": "batch_size",
"name": "batch_size",
"type": "INT",
"widget": {
"name": "batch_size"
},
"link": null
}
],
"outputs": [
{
"localized_name": "LATENT",
"name": "LATENT",
"type": "LATENT",
"slot_index": 0,
"links": [
6
]
}
],
"properties": {
"ue_properties": {
"widget_ue_connectable": {},
"version": "7.8",
"input_ue_unconnectable": {}
},
"Node name for S&R": "EmptyLatentImage"
},
"widgets_values": [
1024,
1024,
1
]
},
{
"id": 1,
"type": "ImageMetadataLoRALoader",
"pos": [
987.5885798350228,
-582.1963058553249
],
"size": [
286,
565
],
"flags": {},
"order": 2,
"mode": 0,
"inputs": [
{
"localized_name": "model",
"name": "model",
"type": "MODEL",
"link": 1
},
{
"localized_name": "clip",
"name": "clip",
"type": "CLIP",
"link": 2
},
{
"localized_name": "metadata",
"name": "metadata",
"shape": 7,
"type": "METADATA",
"link": 3
},
{
"localized_name": "lora_1",
"name": "lora_1",
"type": "COMBO",
"widget": {
"name": "lora_1"
},
"link": null
},
{
"localized_name": "strength_model_1",
"name": "strength_model_1",
"type": "FLOAT",
"widget": {
"name": "strength_model_1"
},
"link": null
},
{
"localized_name": "strength_clip_1",
"name": "strength_clip_1",
"type": "FLOAT",
"widget": {
"name": "strength_clip_1"
},
"link": null
},
{
"localized_name": "lora_2",
"name": "lora_2",
"type": "COMBO",
"widget": {
"name": "lora_2"
},
"link": null
},
{
"localized_name": "strength_model_2",
"name": "strength_model_2",
"type": "FLOAT",
"widget": {
"name": "strength_model_2"
},
"link": null
},
{
"localized_name": "strength_clip_2",
"name": "strength_clip_2",
"type": "FLOAT",
"widget": {
"name": "strength_clip_2"
},
"link": null
},
{
"localized_name": "lora_3",
"name": "lora_3",
"type": "COMBO",
"widget": {
"name": "lora_3"
},
"link": null
},
{
"localized_name": "strength_model_3",
"name": "strength_model_3",
"type": "FLOAT",
"widget": {
"name": "strength_model_3"
},
"link": null
},
{
"localized_name": "strength_clip_3",
"name": "strength_clip_3",
"type": "FLOAT",
"widget": {
"name": "strength_clip_3"
},
"link": null
}
],
"outputs": [
{
"localized_name": "model",
"name": "model",
"type": "MODEL",
"links": [
15
]
},
{
"localized_name": "clip",
"name": "clip",
"type": "CLIP",
"links": [
14,
16
]
}
],
"properties": {
"Node name for S&R": "ImageMetadataLoRALoader",
"ue_properties": {
"widget_ue_connectable": {},
"input_ue_unconnectable": {},
"version": "7.8"
}
},
"widgets_values": [
"temp\\Manga122.safetensors",
0.2,
0.2,
"temp\\MayuMurataIllustrious.safetensors",
0.3,
0.3,
"temp\\Shuiyuan.safetensors",
0.2,
0.2,
""
]
},
{
"id": 2,
"type": "ImageMetadataPromptLoader",
"pos": [
626.8189298350237,
-586.5118258553252
],
"size": [
286,
709
],
"flags": {},
"order": 1,
"mode": 0,
"inputs": [
{
"localized_name": "ckpt_name",
"name": "ckpt_name",
"type": "COMBO",
"widget": {
"name": "ckpt_name"
},
"link": null
},
{
"localized_name": "vae_name",
"name": "vae_name",
"type": "COMBO",
"widget": {
"name": "vae_name"
},
"link": null
},
{
"localized_name": "positive_text",
"name": "positive_text",
"type": "STRING",
"widget": {
"name": "positive_text"
},
"link": null
},
{
"localized_name": "negative_text",
"name": "negative_text",
"type": "STRING",
"widget": {
"name": "negative_text"
},
"link": null
},
{
"localized_name": "_metadata_json",
"name": "_metadata_json",
"type": "STRING",
"widget": {
"name": "_metadata_json"
},
"link": null
}
],
"outputs": [
{
"localized_name": "model",
"name": "model",
"type": "MODEL",
"links": [
1
]
},
{
"localized_name": "clip",
"name": "clip",
"type": "CLIP",
"links": [
2
]
},
{
"localized_name": "vae",
"name": "vae",
"type": "VAE",
"links": [
20
]
},
{
"localized_name": "positive",
"name": "positive",
"type": "CONDITIONING",
"links": null
},
{
"localized_name": "negative",
"name": "negative",
"type": "CONDITIONING",
"links": null
},
{
"localized_name": "positive_text",
"name": "positive_text",
"type": "STRING",
"links": [
18
]
},
{
"localized_name": "negative_text",
"name": "negative_text",
"type": "STRING",
"links": []
},
{
"localized_name": "metadata",
"name": "metadata",
"type": "METADATA",
"links": [
3
]
}
],
"properties": {
"Node name for S&R": "ImageMetadataPromptLoader",
"ue_properties": {
"widget_ue_connectable": {},
"input_ue_unconnectable": {},
"version": "7.8"
}
},
"widgets_values": [
"anime\\CHEYENNE_v24HyperIllustration.safetensors",
"SDXL-VAE-FP16-Fix.safetensors",
"girl,sentai,sentai,flower petal,full body,long hair,long legs,white boots and white gloves,<lora:9_Toshikazu:0.4> Toshikazu,<lora:9_Iggym:0.3> Iggym, painterly, realistic, sketch, traditional media, \\(medium\\)\n<lora:9_Landuo941:0.3> Landuo941\n<lora:Manga122:0.2>,<lora:MayuMurataIllustrious:0.3> Mayu Murata\n<lora:9_Navybluesparrow:0.4> Navybluesparrow\n<lora:9_RiyokoIkeda:0.2> Riyoko Ikeda\n<lora:9_ShumiiberryAlt:0.2> Shumiiberry,\n<lora:Shuiyuan:0.2> 5huny4n_5ty13 \n<lora:test_mix:0.2>,",
"helmet,mask",
"{\"loras\":[{\"name\":\"9_Toshikazu\",\"strength_model\":0.4,\"strength_clip\":0.4},{\"name\":\"9_Iggym\",\"strength_model\":0.3,\"strength_clip\":0.3},{\"name\":\"9_Landuo941\",\"strength_model\":0.3,\"strength_clip\":0.3},{\"name\":\"Manga122\",\"strength_model\":0.2,\"strength_clip\":0.2},{\"name\":\"MayuMurataIllustrious\",\"strength_model\":0.3,\"strength_clip\":0.3},{\"name\":\"9_Navybluesparrow\",\"strength_model\":0.4,\"strength_clip\":0.4},{\"name\":\"9_RiyokoIkeda\",\"strength_model\":0.2,\"strength_clip\":0.2},{\"name\":\"9_ShumiiberryAlt\",\"strength_model\":0.2,\"strength_clip\":0.2},{\"name\":\"Shuiyuan\",\"strength_model\":0.2,\"strength_clip\":0.2},{\"name\":\"test_mix\",\"strength_model\":0.2,\"strength_clip\":0.2}]}",
""
]
},
{
"id": 10,
"type": "CLIPTextEncode",
"pos": [
1360.6159298350235,
-96.8748258553254
],
"size": [
301.4950151367186,
88
],
"flags": {},
"order": 3,
"mode": 0,
"inputs": [
{
"localized_name": "clip",
"name": "clip",
"type": "CLIP",
"link": 14
},
{
"localized_name": "text",
"name": "text",
"type": "STRING",
"widget": {
"name": "text"
},
"link": null
}
],
"outputs": [
{
"localized_name": "CONDITIONING",
"name": "CONDITIONING",
"type": "CONDITIONING",
"slot_index": 0,
"links": [
5
]
}
],
"properties": {
"ue_properties": {
"widget_ue_connectable": {},
"version": "7.8",
"input_ue_unconnectable": {}
},
"Node name for S&R": "CLIPTextEncode"
},
"widgets_values": [
""
]
}
],
"links": [
[
1,
2,
0,
1,
0,
"MODEL"
],
[
2,
2,
1,
1,
1,
"CLIP"
],
[
3,
2,
7,
1,
2,
"METADATA"
],
[
5,
10,
0,
3,
2,
"CONDITIONING"
],
[
6,
5,
0,
3,
3,
"LATENT"
],
[
7,
3,
0,
4,
0,
"LATENT"
],
[
12,
4,
0,
9,
0,
"IMAGE"
],
[
14,
1,
1,
10,
0,
"CLIP"
],
[
15,
1,
0,
3,
0,
"MODEL"
],
[
16,
1,
1,
12,
0,
"CLIP"
],
[
17,
12,
0,
3,
1,
"CONDITIONING"
],
[
18,
2,
5,
12,
1,
"STRING"
],
[
20,
2,
2,
4,
1,
"VAE"
],
[
21,
12,
1,
13,
0,
"STRING"
]
],
"groups": [],
"config": {},
"extra": {
"ue_links": [],
"links_added_by_ue": []
},
"version": 0.4
}
Binary file not shown.

After

Width:  |  Height:  |  Size: 287 KiB

File diff suppressed because it is too large Load Diff
Binary file not shown.

After

Width:  |  Height:  |  Size: 510 KiB

+719
View File
@@ -0,0 +1,719 @@
{
"id": "03047124-7d5d-4eb4-b458-558d6dec9b5e",
"revision": 0,
"last_node_id": 28,
"last_link_id": 50,
"nodes": [
{
"id": 8,
"type": "VAEEncode",
"pos": [
551.8454158175873,
-685.9812381649755
],
"size": [
242.296875,
96
],
"flags": {},
"order": 5,
"mode": 0,
"inputs": [
{
"localized_name": "pixels",
"name": "pixels",
"type": "IMAGE",
"link": 49
},
{
"localized_name": "vae",
"name": "vae",
"type": "VAE",
"link": 34
}
],
"outputs": [
{
"localized_name": "LATENT",
"name": "LATENT",
"type": "LATENT",
"links": [
5
]
}
],
"properties": {
"Node name for S&R": "VAEEncode",
"ue_properties": {
"widget_ue_connectable": {},
"input_ue_unconnectable": {},
"version": "7.8"
}
},
"widgets_values": []
},
{
"id": 22,
"type": "VAELoader",
"pos": [
75.4452850000009,
-464.22850100000056
],
"size": [
270,
58
],
"flags": {},
"order": 0,
"mode": 0,
"inputs": [
{
"localized_name": "vae_name",
"name": "vae_name",
"type": "COMBO",
"widget": {
"name": "vae_name"
},
"link": null
}
],
"outputs": [
{
"localized_name": "VAE",
"name": "VAE",
"type": "VAE",
"links": [
34,
35
]
}
],
"properties": {
"Node name for S&R": "VAELoader",
"ue_properties": {
"widget_ue_connectable": {},
"input_ue_unconnectable": {},
"version": "7.8"
}
},
"widgets_values": [
"SDXL-VAE-FP16-Fix.safetensors"
]
},
{
"id": 5,
"type": "VAEDecode",
"pos": [
1312.282348239462,
-683.1137137997414
],
"size": [
254.390625,
96
],
"flags": {},
"order": 7,
"mode": 0,
"inputs": [
{
"localized_name": "samples",
"name": "samples",
"type": "LATENT",
"link": 11
},
{
"localized_name": "vae",
"name": "vae",
"type": "VAE",
"link": 35
}
],
"outputs": [
{
"localized_name": "IMAGE",
"name": "IMAGE",
"type": "IMAGE",
"links": [
50
]
}
],
"properties": {
"Node name for S&R": "VAEDecode",
"ue_properties": {
"widget_ue_connectable": {},
"input_ue_unconnectable": {},
"version": "7.8"
}
},
"widgets_values": []
},
{
"id": 7,
"type": "KSampler",
"pos": [
1000.0439480441502,
-674.780789922787
],
"size": [
270,
589.3125
],
"flags": {},
"order": 6,
"mode": 0,
"inputs": [
{
"localized_name": "model",
"name": "model",
"type": "MODEL",
"link": 36
},
{
"localized_name": "positive",
"name": "positive",
"type": "CONDITIONING",
"link": 37
},
{
"localized_name": "negative",
"name": "negative",
"type": "CONDITIONING",
"link": 10
},
{
"localized_name": "latent_image",
"name": "latent_image",
"type": "LATENT",
"link": 5
},
{
"localized_name": "seed",
"name": "seed",
"type": "INT",
"widget": {
"name": "seed"
},
"link": null
},
{
"localized_name": "steps",
"name": "steps",
"type": "INT",
"widget": {
"name": "steps"
},
"link": null
},
{
"localized_name": "cfg",
"name": "cfg",
"type": "FLOAT",
"widget": {
"name": "cfg"
},
"link": null
},
{
"localized_name": "sampler_name",
"name": "sampler_name",
"type": "COMBO",
"widget": {
"name": "sampler_name"
},
"link": null
},
{
"localized_name": "scheduler",
"name": "scheduler",
"type": "COMBO",
"widget": {
"name": "scheduler"
},
"link": null
},
{
"localized_name": "denoise",
"name": "denoise",
"type": "FLOAT",
"widget": {
"name": "denoise"
},
"link": null
}
],
"outputs": [
{
"localized_name": "LATENT",
"name": "LATENT",
"type": "LATENT",
"links": [
11
]
}
],
"properties": {
"Node name for S&R": "KSampler",
"ue_properties": {
"widget_ue_connectable": {},
"input_ue_unconnectable": {},
"version": "7.8"
}
},
"widgets_values": [
240074286219855,
"randomize",
30,
8,
"euler",
"karras",
0.7
]
},
{
"id": 24,
"type": "CLIPTextEncode",
"pos": [
528.6156850000002,
-509.49460100000033
],
"size": [
400,
200
],
"flags": {},
"order": 4,
"mode": 0,
"inputs": [
{
"localized_name": "clip",
"name": "clip",
"type": "CLIP",
"link": 38
},
{
"localized_name": "text",
"name": "text",
"type": "STRING",
"widget": {
"name": "text"
},
"link": null
}
],
"outputs": [
{
"localized_name": "CONDITIONING",
"name": "CONDITIONING",
"type": "CONDITIONING",
"links": [
37
]
}
],
"properties": {
"Node name for S&R": "CLIPTextEncode",
"ue_properties": {
"widget_ue_connectable": {},
"input_ue_unconnectable": {},
"version": "7.8"
}
},
"widgets_values": [
"flower,anime girl"
]
},
{
"id": 11,
"type": "CLIPTextEncode",
"pos": [
526.8870184488446,
-252.08752270664039
],
"size": [
400,
200
],
"flags": {
"collapsed": false
},
"order": 3,
"mode": 0,
"inputs": [
{
"localized_name": "clip",
"name": "clip",
"type": "CLIP",
"link": 9
},
{
"localized_name": "text",
"name": "text",
"type": "STRING",
"widget": {
"name": "text"
},
"link": null
}
],
"outputs": [
{
"localized_name": "CONDITIONING",
"name": "CONDITIONING",
"type": "CONDITIONING",
"links": [
10
]
}
],
"properties": {
"Node name for S&R": "CLIPTextEncode",
"ue_properties": {
"widget_ue_connectable": {},
"input_ue_unconnectable": {},
"version": "7.8"
}
},
"widgets_values": [
""
]
},
{
"id": 9,
"type": "CheckpointLoaderSimple",
"pos": [
70.30033916275676,
-694.6312926669282
],
"size": [
270,
154.65625
],
"flags": {},
"order": 1,
"mode": 0,
"inputs": [
{
"localized_name": "ckpt_name",
"name": "ckpt_name",
"type": "COMBO",
"widget": {
"name": "ckpt_name"
},
"link": null
}
],
"outputs": [
{
"localized_name": "MODEL",
"name": "MODEL",
"type": "MODEL",
"links": [
36
]
},
{
"localized_name": "CLIP",
"name": "CLIP",
"type": "CLIP",
"links": [
9,
38
]
},
{
"localized_name": "VAE",
"name": "VAE",
"type": "VAE",
"links": []
}
],
"properties": {
"Node name for S&R": "CheckpointLoaderSimple",
"ue_properties": {
"widget_ue_connectable": {},
"input_ue_unconnectable": {},
"version": "7.8"
}
},
"widgets_values": [
"anime\\IllustriousStyle_v22.safetensors"
]
},
{
"id": 28,
"type": "ImageFeeder",
"pos": [
76.77559983502367,
-338.79391585532534
],
"size": [
253.923,
319.923
],
"flags": {},
"order": 2,
"mode": 0,
"inputs": [
{
"localized_name": "directory",
"name": "directory",
"type": "STRING",
"widget": {
"name": "directory"
},
"link": null
},
{
"localized_name": "sort_mode",
"name": "sort_mode",
"type": "COMBO",
"widget": {
"name": "sort_mode"
},
"link": null
},
{
"localized_name": "index",
"name": "index",
"type": "INT",
"widget": {
"name": "index"
},
"link": null
},
{
"localized_name": "start_index",
"name": "start_index",
"type": "INT",
"widget": {
"name": "start_index"
},
"link": null
},
{
"localized_name": "end_index",
"name": "end_index",
"type": "INT",
"widget": {
"name": "end_index"
},
"link": null
},
{
"localized_name": "batch_size",
"name": "batch_size",
"type": "INT",
"widget": {
"name": "batch_size"
},
"link": null
},
{
"localized_name": "seed",
"name": "seed",
"type": "INT",
"widget": {
"name": "seed"
},
"link": null
},
{
"localized_name": "use_selection",
"name": "use_selection",
"type": "BOOLEAN",
"widget": {
"name": "use_selection"
},
"link": null
},
{
"localized_name": "selected_files",
"name": "selected_files",
"type": "STRING",
"widget": {
"name": "selected_files"
},
"link": null
}
],
"outputs": [
{
"localized_name": "IMAGE",
"name": "IMAGE",
"type": "IMAGE",
"links": [
49
]
}
],
"properties": {
"ue_properties": {
"widget_ue_connectable": {},
"input_ue_unconnectable": {}
},
"Node name for S&R": "ImageFeeder"
},
"widgets_values": [
"test",
"ascending",
0,
0,
0,
1,
908906407258686,
"randomize",
true,
"[\"00030-2656222951.png\",\"00063-2334831609.png\",\"02121-3711614362.png\"]",
""
]
},
{
"id": 4,
"type": "PreviewImage",
"pos": [
1603.3762031816507,
-693.7018206825535
],
"size": [
284.5062499999997,
301.77375000000023
],
"flags": {},
"order": 8,
"mode": 0,
"inputs": [
{
"localized_name": "images",
"name": "images",
"type": "IMAGE",
"link": 50
}
],
"outputs": [],
"properties": {
"Node name for S&R": "PreviewImage",
"ue_properties": {
"widget_ue_connectable": {},
"input_ue_unconnectable": {},
"version": "7.8"
}
},
"widgets_values": []
}
],
"links": [
[
5,
8,
0,
7,
3,
"LATENT"
],
[
9,
9,
1,
11,
0,
"CLIP"
],
[
10,
11,
0,
7,
2,
"CONDITIONING"
],
[
11,
7,
0,
5,
0,
"LATENT"
],
[
34,
22,
0,
8,
1,
"VAE"
],
[
35,
22,
0,
5,
1,
"VAE"
],
[
36,
9,
0,
7,
0,
"MODEL"
],
[
37,
24,
0,
7,
1,
"CONDITIONING"
],
[
38,
9,
1,
24,
0,
"CLIP"
],
[
49,
28,
0,
8,
0,
"IMAGE"
],
[
50,
5,
0,
4,
0,
"IMAGE"
]
],
"groups": [],
"config": {},
"extra": {
"ue_links": [],
"links_added_by_ue": [],
"linearData": {
"inputs": [
[
"9",
"ckpt_name"
],
[
"3",
"pose_editor_3d_widget"
],
[
"3",
"timer_interval"
]
],
"outputs": []
}
},
"version": 0.4
}
Binary file not shown.

After

Width:  |  Height:  |  Size: 258 KiB

+599
View File
@@ -0,0 +1,599 @@
{
"id": "f11699d9-4b62-47bd-b501-e49d609d9810",
"revision": 0,
"last_node_id": 10,
"last_link_id": 10,
"nodes": [
{
"id": 7,
"type": "CLIPTextEncode",
"pos": [
413,
389
],
"size": [
425.27801513671875,
180.6060791015625
],
"flags": {},
"order": 4,
"mode": 0,
"inputs": [
{
"localized_name": "clip",
"name": "clip",
"type": "CLIP",
"link": 5
},
{
"localized_name": "text",
"name": "text",
"type": "STRING",
"widget": {
"name": "text"
},
"link": null
}
],
"outputs": [
{
"localized_name": "CONDITIONING",
"name": "CONDITIONING",
"type": "CONDITIONING",
"slot_index": 0,
"links": [
6
]
}
],
"properties": {
"Node name for S&R": "CLIPTextEncode",
"ue_properties": {
"widget_ue_connectable": {},
"version": "7.8",
"input_ue_unconnectable": {}
}
},
"widgets_values": [
"text, watermark"
]
},
{
"id": 3,
"type": "KSampler",
"pos": [
863,
186
],
"size": [
315,
474
],
"flags": {},
"order": 5,
"mode": 0,
"inputs": [
{
"localized_name": "model",
"name": "model",
"type": "MODEL",
"link": 1
},
{
"localized_name": "positive",
"name": "positive",
"type": "CONDITIONING",
"link": 4
},
{
"localized_name": "negative",
"name": "negative",
"type": "CONDITIONING",
"link": 6
},
{
"localized_name": "latent_image",
"name": "latent_image",
"type": "LATENT",
"link": 2
},
{
"localized_name": "seed",
"name": "seed",
"type": "INT",
"widget": {
"name": "seed"
},
"link": null
},
{
"localized_name": "steps",
"name": "steps",
"type": "INT",
"widget": {
"name": "steps"
},
"link": null
},
{
"localized_name": "cfg",
"name": "cfg",
"type": "FLOAT",
"widget": {
"name": "cfg"
},
"link": null
},
{
"localized_name": "sampler_name",
"name": "sampler_name",
"type": "COMBO",
"widget": {
"name": "sampler_name"
},
"link": null
},
{
"localized_name": "scheduler",
"name": "scheduler",
"type": "COMBO",
"widget": {
"name": "scheduler"
},
"link": null
},
{
"localized_name": "denoise",
"name": "denoise",
"type": "FLOAT",
"widget": {
"name": "denoise"
},
"link": null
}
],
"outputs": [
{
"localized_name": "LATENT",
"name": "LATENT",
"type": "LATENT",
"slot_index": 0,
"links": [
7
]
}
],
"properties": {
"Node name for S&R": "KSampler",
"ue_properties": {
"widget_ue_connectable": {},
"version": "7.8",
"input_ue_unconnectable": {}
}
},
"widgets_values": [
636718080453780,
"randomize",
20,
8,
"euler",
"normal",
1
]
},
{
"id": 8,
"type": "VAEDecode",
"pos": [
1209,
188
],
"size": [
210,
46
],
"flags": {},
"order": 6,
"mode": 0,
"inputs": [
{
"localized_name": "samples",
"name": "samples",
"type": "LATENT",
"link": 7
},
{
"localized_name": "vae",
"name": "vae",
"type": "VAE",
"link": 10
}
],
"outputs": [
{
"localized_name": "IMAGE",
"name": "IMAGE",
"type": "IMAGE",
"slot_index": 0,
"links": [
9
]
}
],
"properties": {
"Node name for S&R": "VAEDecode",
"ue_properties": {
"widget_ue_connectable": {},
"version": "7.8",
"input_ue_unconnectable": {}
}
},
"widgets_values": []
},
{
"id": 9,
"type": "SaveImage",
"pos": [
1451,
189
],
"size": [
210,
270
],
"flags": {},
"order": 7,
"mode": 0,
"inputs": [
{
"localized_name": "images",
"name": "images",
"type": "IMAGE",
"link": 9
},
{
"localized_name": "filename_prefix",
"name": "filename_prefix",
"type": "STRING",
"widget": {
"name": "filename_prefix"
},
"link": null
}
],
"outputs": [],
"properties": {
"Node name for S&R": "SaveImage",
"ue_properties": {
"widget_ue_connectable": {},
"version": "7.8",
"input_ue_unconnectable": {}
}
},
"widgets_values": [
"ComfyUI"
]
},
{
"id": 5,
"type": "EmptyLatentImage",
"pos": [
473,
609
],
"size": [
315,
106
],
"flags": {},
"order": 0,
"mode": 0,
"inputs": [
{
"localized_name": "width",
"name": "width",
"type": "INT",
"widget": {
"name": "width"
},
"link": null
},
{
"localized_name": "height",
"name": "height",
"type": "INT",
"widget": {
"name": "height"
},
"link": null
},
{
"localized_name": "batch_size",
"name": "batch_size",
"type": "INT",
"widget": {
"name": "batch_size"
},
"link": null
}
],
"outputs": [
{
"localized_name": "LATENT",
"name": "LATENT",
"type": "LATENT",
"slot_index": 0,
"links": [
2
]
}
],
"properties": {
"Node name for S&R": "EmptyLatentImage",
"ue_properties": {
"widget_ue_connectable": {},
"version": "7.8",
"input_ue_unconnectable": {}
}
},
"widgets_values": [
1024,
1024,
1
]
},
{
"id": 6,
"type": "CLIPTextEncode",
"pos": [
415,
186
],
"size": [
422.84503173828125,
164.31304931640625
],
"flags": {},
"order": 3,
"mode": 0,
"inputs": [
{
"localized_name": "clip",
"name": "clip",
"type": "CLIP",
"link": 3
},
{
"localized_name": "text",
"name": "text",
"type": "STRING",
"widget": {
"name": "text"
},
"link": null
}
],
"outputs": [
{
"localized_name": "CONDITIONING",
"name": "CONDITIONING",
"type": "CONDITIONING",
"slot_index": 0,
"links": [
4
]
}
],
"properties": {
"Node name for S&R": "CLIPTextEncode",
"ue_properties": {
"widget_ue_connectable": {},
"version": "7.8",
"input_ue_unconnectable": {}
}
},
"widgets_values": [
"flower"
]
},
{
"id": 4,
"type": "CheckpointLoaderSimple",
"pos": [
51.3,
182.49999999999997
],
"size": [
315,
98
],
"flags": {},
"order": 1,
"mode": 0,
"inputs": [
{
"localized_name": "ckpt_name",
"name": "ckpt_name",
"type": "COMBO",
"widget": {
"name": "ckpt_name"
},
"link": null
}
],
"outputs": [
{
"localized_name": "MODEL",
"name": "MODEL",
"type": "MODEL",
"slot_index": 0,
"links": [
1
]
},
{
"localized_name": "CLIP",
"name": "CLIP",
"type": "CLIP",
"slot_index": 1,
"links": [
3,
5
]
},
{
"localized_name": "VAE",
"name": "VAE",
"type": "VAE",
"slot_index": 2,
"links": []
}
],
"properties": {
"Node name for S&R": "CheckpointLoaderSimple",
"ue_properties": {
"widget_ue_connectable": {},
"version": "7.8",
"input_ue_unconnectable": {}
}
},
"widgets_values": [
"anime\\artUniverse_sdxlV60.safetensors"
]
},
{
"id": 10,
"type": "VAELoader",
"pos": [
61.897062649999256,
347.8818042399999
],
"size": [
270,
58
],
"flags": {},
"order": 2,
"mode": 0,
"inputs": [
{
"localized_name": "vae_name",
"name": "vae_name",
"type": "COMBO",
"widget": {
"name": "vae_name"
},
"link": null
}
],
"outputs": [
{
"localized_name": "VAE",
"name": "VAE",
"type": "VAE",
"links": [
10
]
}
],
"properties": {
"ue_properties": {
"widget_ue_connectable": {},
"input_ue_unconnectable": {}
},
"Node name for S&R": "VAELoader"
},
"widgets_values": [
"sdxl_vae.safetensors"
]
}
],
"links": [
[
1,
4,
0,
3,
0,
"MODEL"
],
[
2,
5,
0,
3,
3,
"LATENT"
],
[
3,
4,
1,
6,
0,
"CLIP"
],
[
4,
6,
0,
3,
1,
"CONDITIONING"
],
[
5,
4,
1,
7,
0,
"CLIP"
],
[
6,
7,
0,
3,
2,
"CONDITIONING"
],
[
7,
3,
0,
8,
0,
"LATENT"
],
[
9,
8,
0,
9,
0,
"IMAGE"
],
[
10,
10,
0,
8,
1,
"VAE"
]
],
"groups": [],
"config": {},
"extra": {
"ds": {
"offset": [
0,
0
],
"scale": 1
},
"ue_links": [],
"links_added_by_ue": []
},
"version": 0.4
}
Binary file not shown.

After

Width:  |  Height:  |  Size: 168 KiB

File diff suppressed because it is too large Load Diff
Binary file not shown.

After

Width:  |  Height:  |  Size: 411 KiB