Compare commits

...
9 Commits
Author SHA1 Message Date
ketle-manandClaude Sonnet 4.6 272de3d168 fix: ImpactWildcardEncode/Processor prompt not shown in Generate UI (v0.3.41)
- Add CLIPTextEncodeEditPlus BFS role propagation (text1/text2 inputs)
- Skip empty text_edit in CLIPTextEncodeEditPlus prompt_nodes to prevent
  blank textarea when upstream ImpactWildcard nodes supply the prompt
- Always overwrite wildcard_text from widgets[0] in convertUiToApi to
  guard against object_info widget-order differences between impact-pack versions
- Add static fallback mapping for ImpactWildcardProcessor/Encode

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-06-19 22:04:42 +09:00
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
38 changed files with 4624 additions and 377 deletions
+336
View File
@@ -1,5 +1,341 @@
# DEVLOG - ComfyUI-Workflow-Studio
## 2026-06-19: Generate UI — ImpactWildcardEncode/Processor プロンプト検出バグ修正(v0.3.41)
### 修正内容(`static/js/comfyui-workflow.js`)
**症状**:comfy-impact-pack の `ImpactWildcardEncode` / `ImpactWildcardProcessor` ノードを含むワークフローを Generate UI に読み込んだとき、Prompt タブにプロンプトが表示されない(ID は正しく表示されていた)。
**原因1: CLIPTextEncodeEditPlus 経由の BFS ロール伝播漏れ**
- これらのワークフローでは ImpactWildcard ノードの出力が `CLIPTextEncodeEditPlus` の `text2` 入力に接続され、CLIPTextEncodeEditPlus が KSampler の positive に繋がる構成。
- BFS 伝播で `CLIPTextEncodeEditPlus` の STRING 入力(text1, text2)に positive/negative ロールを伝播するコードが未実装だったため、上流の ImpactWildcard ノードのロールが `unknown` のままになっていた。
- **修正**: BFS ループに `CLIPTextEncodeEditPlus` の `text1` / `text2` への伝播を追加。
**原因2: CLIPTextEncodeEditPlus が空の text_edit で prompt_nodes の先頭に入り込む**
- CLIPTextEncodeEditPlus 自体も positive ロールとして検出され、`text_edit = ""` でノードIDが小さいため `positiveNodes[0]` になっていた。
- これによりテキストエリアに空文字が表示され、ImpactWildcard ノードのプロンプトが埋もれていた。
- **修正**: `text_edit` が空文字列の場合は `prompt_nodes` に追加しないよう条件を追加(`textVal !== ""`)。空の text_edit は「上流ノードからプロンプトが来る場合のデフォルト状態」であり、UI で表示する必要がない。
**原因3: object_info マッピングの不確実性**
- `convertUiToApi()` で impact-pack バージョンによる `object_info` のウィジェット順序差異が発生した場合、`wildcard_text` が正しくマッピングされない可能性があった。
- **修正1**: ポストプロセスで `widgets[0]` を常に `wildcard_text` として上書き(`!("wildcard_text" in inputs)` ガードを除去)。
- **修正2**: `_getWidgetMapping()` フォールバックに `ImpactWildcardProcessor: ["wildcard_text"]`、`ImpactWildcardEncode: ["wildcard_text"]` を追加(ComfyUI オフライン時の対応)。
---
## 2026-06-19: AI TOOL タブ Chat ペイン・ワイルドカード生成追加(v0.3.40)
### Chat ペイン(`templates/index.html`, `static/css/main.css`, `static/js/ai-tab.js`, `web/comfyui/node_sets_menu.js`)
- AI TOOL タブを 3ペイン → **4ペイン**(Translation | Chat | TOOLS | Settings)に変更
- Chat ペイン: LLM とのマルチターン会話;会話履歴を毎回送信;Enter で送信、Shift+Enter で改行;Clear ボタンで履歴リセット
- Ollama: `/api/chat` エンドポイント(`messages` 配列)、LM Studio: `/v1/chat/completions`(同形式)
- 送信失敗時は入力テキストを復元してリトライ可能
- サイドパネル Aタブにも Chat サブタブを追加(Translation → **Chat** → TOOLS → Settings の4タブ構成)
- CSS: `.wfm-ai-chat-*` / `.wfm-nlp-ai-chat-*` でユーザーバブル(右)・アシスタントバブル(左)スタイル追加
### ワイルドカード生成(`templates/index.html`, `static/css/main.css`, `static/js/ai-tab.js`, `web/comfyui/node_sets_menu.js`)
- TOOLS ペインのドロップダウンに「Create wildcards」オプションを追加
- タスク切替で UI を動的切り替え:VLM選択時→ドロップゾーン表示、Wildcard選択時→Name・Count入力フォームを表示
- プロンプト: `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.`
- 後処理: `**` / 行頭 `*` / 行頭数字(`\d+\.\s*`)を除去してプレーンテキストを保証
- SPA(`static/js/ai-tab.js`)とサイドパネル(`web/comfyui/node_sets_menu.js`)両方に実装
### ヘルプ・i18n(`static/js/i18n.js`, `static/js/app.js`, `templates/index.html`)
- AI TOOL タブヘルプを5項目→6項目に再構成(ai-3: Chat、ai-4: VLM、ai-5: Wildcards、ai-6: 設定)
- `helpSidepanel16` を EN/JA/ZH 更新(Chat・ワイルドカード機能を追記)
- `helpAi1`〜`helpAi6` を EN/JA/ZH 全更新
- 新 i18n キー追加(3言語): `aiStatusChatting`, `aiToastChatFailed`, `aiToastWcNoName`
---
## 2026-06-18: Send to Canvas機能追加(ワークフロータブ・ギャラリータブ→LibraryタイトルDnD)
### ワークフロータブ — Send to Canvas(`static/js/workflow-tab.js`, `static/js/app.js`, `templates/index.html`)
- ツールバーおよび詳細モーダルの **Open in ComfyUI** ボタンを **Send to Canvas** に変更
- `sendToCanvas(workflowData)`: ワークフローJSONを `localStorage["wfm_pending_workflow"]` に保存してトースト表示(新しいブラウザタブを開かない)
- `openInComfyUI()` 関数は後方互換のため残置
### ギャラリータブ — Copy & Send Canvas(`static/js/gallery-tab.js`, `templates/index.html`)
- **Copy Workflow** ボタンを **Copy & Send Canvas** にリネーム
- クリック時にクリップボードコピーと `localStorage["wfm_pending_workflow"]` への保存を同時実行
### Workflow Studio Library — タイトルドラッグ(`web/comfyui/node_sets_menu.js`)
- `createPanel()` 内でタイトル要素(`.wfm-nlp-title`)にドラッグロジックを追加
- `updateTitlePendingState()`: `localStorage` の `wfm_pending_workflow` 有無を検出して `draggable` 属性・CSS クラス・`title` 属性を動的切り替え
- `panel.mouseenter` / `window.storage` イベントで状態を自動更新(メインアプリ→ComfyUI切り替え後も検出)
- `dragstart`: pending JSON を `application/x-wfm-pending` MIME タイプにセット
- `installCanvasDropHandler()`: `application/x-wfm-pending` を dragover と drop の両ハンドラに追加
- drop 時に `JSON.parse` → `app.loadGraphData()` → localStorage削除 → タイトルリセット
- CSS: `.wfm-nlp-title-pending { color: #66aaff; cursor: grab }` + `::after` で緑●インジケーター表示
### i18n・ヘルプ(`static/js/i18n.js`, `static/js/app.js`, `templates/index.html`)
- `sendToCanvas` / `copyAndSendCanvas` / `workflowSentToCanvas` を EN/JA/ZH に追加
- ヘルプ: `helpWf6`(send to canvas)・`helpGallery8`(Copy & Send Canvas説明)を3言語更新
- ヘルプ: `helpSidepanel17` 新規追加(タイトルドラッグ機能説明)を3言語で追加、app.jsマッピング・index.html li要素も追加
---
## 2026-06-15: TaggerシングルGenUI:Pボタン追加+生成UIのZITワークフロープロンプト解析修正
### TaggerシングルGenUI:Pボタン(`templates/index.html`, `static/js/tagger-tab.js`, `static/js/i18n.js`)
- Single タブの結果アクション行に **GenUI:P** ボタンを追加(「プロンプトに送信」の左隣)
- クリックすると生成UIタブの `#wfm-prompt-pos-text`(ポジティブプロンプトtextarea)末尾にタグを追記し、`#wfm-prompt-pos-apply` を自動クリックしてワークフローへ即時反映
- 生成UIにワークフローが読み込まれていない場合は警告トーストを表示
- i18n: `taggerSendToGenUI` / `taggerSentToGenUI` / `taggerNoGenUI` を EN/JA/ZH に追加
- ヘルプ: `helpTagger6` を5項目に更新(GenUI:P を先頭に追加)
### 生成UIのZIT/Lumina2ワークフロープロンプト解析修正(`static/js/comfyui-workflow.js`, `py/services/workflow_analyzer.py`)
- `comfyui-workflow.js` の `COND_PASSTHROUGH` から `"ConditioningZeroOut"` を除外
- ZITワークフローでは KSampler.negative → ConditioningZeroOut → CLIPTextEncode という接続を持つが、ConditioningZeroOut は上流テキストを完全に破棄するため negative ロールを上流に伝播すべきでない
- 修正前: CLIPTextEncode が positive / negative 両ロール付与 → `getRole()` が "unknown" → Generate UI のプロンプト欄に表示されない
- 修正後: CLIPTextEncode は positive ロールのみ → 正常にポジティブプロンプトとして表示
- `workflow_analyzer.py` の `_CLIP_TYPE_TO_MODEL` に `"lumina2": "Z-IMAGE"` を追加
- CLIPLoader の `type` フィールドが `"lumina2"` のワークフローを Z-IMAGE として正確に分類
---
## 2026-06-15: Taggerバッチ.txt出力追加+Galleryタグ保存バグ修正
### Taggerバッチ.txt出力(`templates/index.html`, `static/js/tagger-tab.js`, `static/js/i18n.js`, `py/routes/tagger_routes.py`, `py/services/tagger_service.py`)
- バッチ出力オプションに **Write .txt** チェックボックスを追加
- 有効にすると処理した各画像と同一フォルダに `<ファイル名>.txt`(UTF-8)を生成、Interrogator + VLM タグのカンマ区切り文字列を書き込む
- `batch_start()` シグネチャに `write_txt: bool` パラメータを追加、ルート・フロントエンドも連動更新
- i18n: `taggerBatchWriteTxt` キーを EN/JA/ZH に追加
### Galleryタグ保存バグ修正(`static/js/tagger-tab.js`)
- `_saveToGallery()` がタグをカンマ区切り文字列のまま POST していたため、Gallery が `img.tags.forEach is not a function` エラーで更新不能になっていた
- 修正: 送信前に `tags.split(",").map(s => s.trim()).filter(Boolean)` で配列に変換
---
## 2026-06-15: Taggerタブ新規実装+ギャラリー詳細パネルUI改善+パストラバーサル修正
### Taggerタブ新規実装
#### バックエンド(`py/config.py`, `py/services/tagger_service.py`, `py/services/tagger_db_service.py`, `py/routes/tagger_routes.py`, `py/wfm.py`)
- `py/config.py`: `TAGGER_DB_FILE` / `TAGGER_SETTINGS_FILE` / `TAGGER_MODELS_DIR`(`ComfyUI/models/tagger/`)定数追加
- `TaggerService`: WD Tagger(ONNX)・SwinV2・DeepDanbooru(.h5 / TensorFlow optional)推論、Ollama VLM連携(`/api/chat`)、JPEGへのpiexif EXIF書込・PNGへのPngInfo書込・サイドカー.tags.json書込、スレッドベースバッチ処理(`batch_start` / `batch_stop` / `batch_status`)、設定の永続化
- `TaggerDbService`: SQLite(`tagger.db`)によるタグ保存・一覧・検索・更新・削除・CSV出力
- `tagger_routes.py`: `/wfm/tagger/` 配下に17エンドポイントを登録(models・predict・ollama/models・ollama/predict・batch/start/status/stop・db CRUD・write_meta・settings)、全CPU処理を `asyncio.to_thread()` でラップ
- `py/wfm.py`: `tagger_routes.setup_routes(app)` を追加
- `requirements.txt` 新規作成: `onnxruntime>=1.16`・`piexif>=1.1.3` を必須、TensorFlow をオプション(コメントアウト)として記載
#### フロントエンド(`templates/index.html`, `static/css/tagger-tab.css`, `static/js/tagger-tab.js`, `static/js/i18n.js`, `static/js/app.js`)
- `templates/index.html`: Taggerタブナビボタン追加、`<section id="wfm-tab-tagger">` を追加(Single / Batch / DBの3サブタブ構成)
- `static/css/tagger-tab.css` 新規作成: サブタブナビ・シングルレイアウト・プレビューエリア(破線ボーダー+ドラッグオーバーハイライト)・バッチ進行状況バー・DBテーブルのスタイル
- `static/js/tagger-tab.js` 新規作成:
- `initTaggerTab()`: i18n適用・サブタブ切り替え・スライダー連動・Ollamaトグル・各種イベント登録・モデル一覧ロード・設定読み込み
- `openImageInTaggerTab(img)`: Gallery→Taggerタブ遷移+画像ロード(`/wfm/gallery/image/serve` 経由でbase64変換)
- Single: ドラッグ&ドロップ・ファイルアップロード・タグ生成(WD Tagger+Ollama並行)・4出力先(Prompt送信・Gallery保存・ファイル書込・DB保存)
- Batch: バッチ開始/停止・1秒間隔ポーリングによるリアルタイム進行状況更新
- DB: 一覧表示・検索・行選択編集・保存・削除・CSV出力
- `static/js/i18n.js`: `tabTagger`・Taggerタブ関連キー約50件を EN/JA/ZH 3言語で追加
- `static/js/app.js`: `tabMap` に `tagger` 追加、`initTaggerTab()` インポート&呼び出し追加
### ギャラリー詳細パネルUI改善(`templates/index.html`, `static/css/gallery-tab.css`, `static/js/gallery-tab.js`, `static/js/app.js`)
- タブ行(Info / JSON / Groups)とアクションボタン行(Metadata / Load GenUI / Tagger)を分離: タブは `wfm-side-tab-nav`、ボタンは新設の `wfm-gallery-detail-action-row` へ移動
- `.wfm-gallery-detail-action-row` のCSSを `gallery-tab.css` に追加(`flex`・`flex-wrap`・`padding`)
- Galleryの詳細パネルに **Tagger** ボタン(`wfm-gallery-open-tagger-btn`、紫)追加: クリックで選択画像を `openImageInTaggerTab()` へ渡してTaggerタブへ遷移・画像ロード
- `.wfm-gallery-action-btn-tagger` スタイル(`gallery-tab.css`)追加
- `app.js` の `applyI18nToHtml()` でTaggerボタンのテキストを `t("tabTagger")` に設定
### セキュリティ修正: パストラバーサル対策(`py/services/tagger_service.py`, `py/services/gallery_service.py`)
- `TaggerService._validate_model_name()`: モデル名に `/` `\` `..` `\x00` が含まれる場合はロード拒否(`mdir / model_name` のパストラバーサルを防止)
- `TaggerService.write_meta_to_file()`: ユーザー指定パスを `resolve()` した上で許可拡張子(`.jpg/.jpeg/.png/.webp/.bmp/.gif`)のみ処理、それ以外はエラー返却
- `GalleryService._check_path_allowed()`: `_allowed_root is None` のときに tautology(`resolved == path.resolve()`、常にTrue)だった判定を `return False` に修正(`list_folder_tree` 呼び出し前に全パスが通る問題を解消)
### ヘルプ更新(`templates/index.html`, `static/js/i18n.js`, `static/js/app.js`)
- ヘルプナビに「Tagger Tab」追加
- Taggerタブのヘルプページ新設(9項目: モデル配置・Single操作・閾値・Ollama・出力先・Batch・DB・インストール手順)EN/JA/ZH
- Galleryタブヘルプに `helpGallery14`(Taggerボタン説明)を EN/JA/ZH で追加
- トラブルシューティングに `helpTrouble7`(Taggerモデル未表示時の対処)を EN/JA/ZH で追加
---
## 2026-06-15: 全選択ボタン追加+ギャラリーバルクバーi18n対応
### 変更内容
#### Modelsタブ: 複数選択バーに「全選択」ボタン追加(`static/js/models-tab.js`, `static/js/i18n.js`)
- `selectAll()` 関数を追加: `filterModels()` の結果(フィルター・検索適用後の表示中モデル)を `state.selectedModels` に一括追加して `renderModelGrid()` / `renderBulkActionBar()` を呼び出す
- `renderBulkActionBar()` のバーHTMLに `wfm-bulk-select-all-btn` を Deselect All ボタンの右隣に追加
- イベントリスナーを追加(`"wfm-bulk-select-all-btn"` → `selectAll`)
- i18n: `modelBulkSelectAll` を英語 "Select All" / 日本語 "全選択" / 中国語 "全选" で追加
#### Galleryタブ: 複数選択バーに「全選択」ボタン追加+全ボタンi18n対応(`templates/index.html`, `static/js/gallery-tab.js`, `static/js/app.js`, `static/js/i18n.js`)
- `wfm-gallery-bulk-select-all` ボタンを Deselect All ボタンの右隣に追加(`templates/index.html`)
- クリックリスナー: `state.images` の全パスを `state.selectedImages` に追加し `renderImages()` / `updateBulkBar()` を呼び出す
- バルクバーの全ボタン・セレクトのテキストを空にして `applyI18nToHtml()` 経由で `t()` 設定に変更(ハードコード英語文字列を排除)
- `updateBulkBar()` の選択件数表示を `t("galleryBulkSelected")` でi18n化(`"${count} selected"` → `"${count} ${t(...)}"` )
- グループセレクトの初期オプションを `t("galleryBulkAddToGroup")` でi18n化
- `app.js` の `applyI18nToHtml()` にギャラリーバルクバー全要素のi18n設定処理を追加
- i18n: 英語 / 日本語 / 中国語の3言語でギャラリーバルクバー用キー10個を新規追加: `galleryBulkSelected` / `galleryBulkDeselectAll` / `galleryBulkSelectAll` / `galleryBulkAddToGroup` / `galleryBulkAdd` / `galleryBulkFavAll` / `galleryBulkUnfavAll` / `galleryBulkMoveTo` / `galleryBulkDelete`
---
## 2026-06-10: v0.3.36 — コードレビュー修正+リファクタリング+README刷新
### コードレビュー修正(v0.3.35の不具合10件)
#### ヘルプi18n配線の修正(`static/js/i18n.js`, `static/js/app.js`, `templates/index.html`)
- **バグ**: `applyI18nToHtml()` が起動時に全言語でヘルプ文を上書きするため、v0.3.35でindex.htmlに追記したヘルプ更新(Saveボタン・ソート・JSONタブ改名)が一切表示されなかった
- `helpGen2` / `helpModels2` / `helpGallery8` / `helpGallery10` を3言語ともindex.htmlの新文言に同期
- `helpGallery12` / `helpGallery13` キーを3言語で新規追加(Metadata / Load GenUI ボタン説明)
- `helpIdMap` に `wfm-help-models-12` / `wfm-help-trouble-6` / `wfm-help-gallery-12` / `wfm-help-gallery-13` を登録
- index.html の「Thumbnail, Card, and Table」誤記を修正(カードビューはv0.3.22で廃止済み)
#### GenerateUI Save の安全化(`static/js/generate-tab.js`)
- **上書き確認**: 保存前に `GET /api/wfm/workflows` で既存ファイルを照会し、同名があれば confirm 表示。保存先が **UI形式**(`analysis.format === "ui"`)の場合はAPI形式上書きでノード配置が失われる旨の専用警告
- **Raw JSON同期**: Raw JSONテキストエリアに未Applyの編集があればパースして保存対象に反映し、保存後エディタへ同期。不正JSONはエラーで中断(従来は古い内容を黙って保存していた)
- **HTML注入防止**: ファイル名を `value="${...}"` 属性埋め込みからDOM経由の `input.value` 設定に変更
- **デフォルト名**: 拡張子除去を `.json` のみ→画像拡張子(.png/.jpg/.jpeg/.webp/.gif)にも拡大
- **二重送信ガード**: `saving` フラグでEnter連打・多重POSTを防止
#### その他
- `sortModels` を decorate-sort-undecorate 方式に変更(`sortKeyOf()` で1モデル1回だけキー計算。比較ごとの `parseModelPath` 再計算を解消)(`static/js/models-tab.js`)
- ギャラリーの Metadata / Load GenUI ボタンを `.wfm-gallery-detail-tab-btn` から専用の `.wfm-gallery-action-btn` に分離し、CSSの `!important` 16箇所を全廃(`templates/index.html`, `static/css/gallery-tab.css`)
- Save関連・ギャラリーの新規文字列をi18n化(`saveWorkflowTitle` / `savedAs` / `overwriteConfirm` / `gallerySelectImageFirst` 等を3言語追加)
### リファクタリング
#### util.js 新設(`static/js/util.js` 新規)
- `escapeHtml()`: 5ファイル(gallery / metadata / models / nodes / workflow)の重複定義を統一。metadata-tab版は `"` エスケープが抜けており属性値でHTML注入の恐れがあった(修正済み)
- `readJsonStorage(key, fallback)` / `getSettings()`: `JSON.parse(localStorage.getItem(...))` の直書き15箇所(8ファイル)を置換。try/catchの重複も削減
#### トーストi18n化(全タブJS, `static/js/i18n.js`)
- ハードコード英語トースト約115箇所をすべて `t()` 化(残り0件)
- 共通キー約60個を3言語(EN/JA/ZH)で追加: `errorWithMsg` / `groupCreated` / `presetSavedName` / `batchNoneSelected` / `generationComplete` など
- 既存キーとの衝突回避: 文字列型の既存 `importError` / `presetSaved` と重複したため、新関数型キーは `importErrorMsg` / `presetSavedName` に命名
- 既存バグ修正: Settings画面の `textSizeLabel` / `jsonColor*` 系11キーが未定義で生キー名が表示されていた(v0.3.14由来。`t() || "fallback"` はt()がキー名を返すため機能しない)→ 3言語で定義追加
- ZHブロックに欠落していた `copyPositivePrompt` / `copyNegativePrompt` / `copiedToClipboard` / `noTextToCopy` を追加
- 検証: 全 `t()` 呼び出しキーの定義確認・3言語のキー完全一致・重複キーなし・全JS構文チェック通過
### README刷新(`README.md`, `pyproject.toml`, `docs/`)
- 冒頭説明文を3本柱構成に書き換え: 📁 Management(ワークフロー/モデル/画像/プロンプト管理、AIプロンプト支援・翻訳・タグ生成、ファイルドロップ&ギャラリー連携メタデータ)/ ⚡ GenerateUI(全タブ連携、モデル・サンプラー等バッチ生成、Image Feeder)/ 📚 Workflow Studio Library(キャンバスドロップ、画像/JSONメタデータ表示&ドロップ、AIツール)
- スクリーンショット差し替え・追加: `6_ws_library.png` 差し替え、`9_GenUI_LoraStack.png`(GenUI LoRA Stack)・`10_GenUI_Batch.png`(GenUI Batch)・`11_multiple_select_menu.png`(Models Multi-select Menu)を新規追加し、生成UI系3枚が連続するよう表を再配置
- `pyproject.toml` の `description` をREADME新説明文と整合する内容に更新
---
## 2026-06-10: v0.3.35 — テーブルソート・Load GenUI・ワークフロー保存
### 変更内容
#### Modelsタブ テーブルビュー: 列ヘッダークリックでソート(`static/js/models-tab.js`, `static/css/main.css`)
- `state` に `sortColumn`(null または列キー)と `sortDir`(`"asc"` / `"desc"`)を追加
- `sortModels(models)` 関数を追加:ソート列に応じて ★・ファイル名・サブディレクトリ・Type・Base Model・拡張子・Tags・Memo・E/D の各キーで昇降順ソートを実行
- `filterModels()` の末尾で `sortModels()` を呼び出し、フィルタ後の全ビューに適用
- `thSortHtml(label, col, extraClass, extraStyle)` ヘルパーを追加:アクティブ列はアクセントカラー(`--wfm-accent`)に変色し ▲/▼ 矢印を表示
- `renderTableView` のヘッダーをすべて `thSortHtml` ベースに変更。クリックで asc → desc → 解除のサイクル
- Enable/Disable 列の空ヘッダーを **E/D** に変更
- `.wfm-table-th-sortable` CSS を追加(`cursor: pointer`、`-webkit-user-select: none`、`white-space: nowrap`、ホバー時アクセントカラー)
#### ギャラリータブ: Load GenUI ボタン追加(`templates/index.html`, `static/js/gallery-tab.js`, `static/css/gallery-tab.css`)
- 詳細パネルのタブナビに **Load GenUI**(青)ボタン(`wfm-gallery-load-genui-btn`)を Metadata ボタンの右隣に追加
- `gallery-tab.js` に `loadWorkflowIntoEditor` を `generate-tab.js` からインポート
- クリック時の動作:画像未選択 → warning トースト / ワークフロー未埋め込み → warning トースト / 非対応フォーマット → `loadWorkflowIntoEditor` 内でトースト表示 / 成功時 → GenerateUI タブへ自動切り替え
- **Metadata** ボタンに `wfm-gallery-action-btn-green` クラスを追加し緑色背景に変更
- `gallery-tab.css` に `.wfm-gallery-action-btn-green`(緑)・`.wfm-gallery-action-btn-primary`(`--wfm-primary` 青)スタイルを追加:`padding`・`border-radius`・`align-self: center`・`margin` を共通指定
#### GenerateUIタブ: Save ボタン追加(`templates/index.html`, `static/js/generate-tab.js`)
- `wfm-gen-subtab-nav` の右端(`margin-left:auto`)に **Save** ボタン(`wfm-gen-save-btn`、`wfm-btn-primary`)を設置
- `generate-tab.js` のインポートに `openModal`・`closeModal` を追加
- `saveCurrentWorkflow()` 関数を追加:
- ワークフロー未ロード時は warning トースト
- モーダルでファイル名を入力(デフォルト: 現在のワークフロー名)。Enter キーでも確定可能
- `comfyUI.currentWorkflow` を JSON シリアライズして `File` オブジェクトを生成、`POST /api/wfm/workflows/import` で Workflow タブに保存
- 保存成功後 `wfm-gen-wf-name` の表示・`dataset.filename` を新ファイル名に更新
- エラー時はトーストでメッセージ表示
#### ヘルプ更新(`templates/index.html`)
- GenerateUI Tab(`wfm-help-gen-2`):Save ボタンの説明を追加
- Gallery Tab(`wfm-help-gallery-8/10`):「Metadata tab」→「JSON tab」に表記修正;`wfm-help-gallery-12/13` として Metadata(緑)・Load GenUI(青)ボタンの説明を新規追加
- Models Tab(`wfm-help-models-2`):テーブルヘッダークリックソートと E/D 列の説明を追記
---
## 2026-06-09: v0.3.34 — Modelsタブ テーブルビュー強化・バルク操作改善
### 変更内容
#### テーブルビュー: Type / Base Model 列追加(`static/js/models-tab.js`, `static/css/main.css`)
- `renderTableView` にて Subdirectory と Extension 列の間に **Type** / **Base Model** 列を追加
- データは `state.civitaiCache[sha256]` から取得(追加API呼び出しなし)
- `.wfm-table-th-civtype` / `.wfm-table-td-civtype`(70px)、`.wfm-table-th-basemodel` / `.wfm-table-td-basemodel`(110px)を追加
- `.wfm-table-th-filename` / `.wfm-table-td-filename` の `max-width` を 160px に制限し、overflow ellipsis 適用
#### モーダル: Delete ボタン追加(`static/js/models-tab.js`)
- 詳細モーダルにモデル削除ボタンを設置
- `POST /api/wfm/models/delete` を呼び出してモデルファイル本体および全サイドカーファイル(`.preview.png`、`.json`、`.civitai.info`、`.metadata.json`、`.cm-info.json` など)を削除
- 削除後にローカルステート(`modelsByType`、`modelMetadata`、`disabledModels`、`selectedModels`)を差分更新して `renderModelGrid()` を呼び出す
#### バルクアクションバー: ファイル移動機能追加(`static/js/models-tab.js`, `static/css/main.css`)
- `fetchSubdirs()` 関数追加:`GET /api/wfm/models/subdirs?type=` でルート直下のサブフォルダ一覧を取得し `state.subdirs` にキャッシュ
- `bulkMoveModels(destSubdir)` 関数追加:`POST /api/wfm/models/move` で選択モデルをサブフォルダへ移動(サイドカーファイルも同時移動)。ローカルステートのキー(`modelsByType`、`modelMetadata`、`disabledModels`)を移動後の相対パスに更新
- 移動後に `fetchSubdirs()` → `renderDirFilter()` → `renderModelGrid()` → `renderBulkActionBar()` を連続実行
#### バルクアクションバー: UI再構成(`static/js/models-tab.js`, `static/css/main.css`)
- バーを **ヘッダー行**(件数表示・Deselect All・Favorite 操作)+**3行グリッド**(Group / Badge / File)に再構成
- **Group 行**:グループ選択ドロップダウン・Add / Remove ボタン・新規グループ名入力・Create & Add
- **Badge 行**:バッジ選択ドロップダウン・+Badge / −Badge ボタン
- **File 行**:移動先フォルダ選択ドロップダウン・Move ボタン・新規フォルダ名入力・Create & Move・Delete Files(行右端)
- Select ボタンを緑色(`.wfm-btn-success`)に変更(`templates/index.html`)
- X(Clear Selection)ボタンを削除。Deselect All のみを使用
- 各ドロップダウン幅を 110px → 330px に拡大
#### バックエンド: subdirs / move エンドポイント追加(`py/services/models_service.py`, `py/routes/models_routes.py`)
- `ModelsService.get_subdirs(model_type)` — ルート直下のディレクトリ名一覧を返す
- `ModelsService.move_models(model_type, model_names, dest_subdir)` — モデルと全サイドカーを `shutil.move` で移動。パストラバーサル防止(`..` チェック・セパレーター禁止・絶対パス禁止・`resolve().relative_to()` containment検証)・上書き防止を実装
- `GET /api/wfm/models/subdirs`、`POST /api/wfm/models/move` ルートを登録。`_VALID_MODEL_TYPES` frozenset でモデルタイプをホワイトリスト検証
- `_SIDECAR_EXTENSIONS` に `.metadata.json`、`.cm-info.json` を追加(delete / move 両操作に反映)
#### B/S ボタン: 行移動バグ修正(`static/js/models-tab.js`)
- `toggleBatch` / `toggleStack` から `renderModelGrid()` 呼び出しを削除
- テーブルビュー・カードビュー両方の B / S ボタンハンドラーを `async` に変更し、`await` 後にボタンの `active` クラスのみを差分更新(`classList.toggle`)
- `state.showBatchOnly` フィルター有効時(バッチから外すと行が消えるべき場合)のみ `renderModelGrid()` を呼び出す
#### ギャラリー → Metadata タブ連携(`static/js/gallery-tab.js`, `static/js/metadata-tab.js`)
- `metadata-tab.js` に `loadFileIntoMetadataTab(file)` をエクスポート:Metadata タブへ切り替えてファイルを読み込む外部 API
- `gallery-tab.js` に `openImageInMetadataTab(img)` を追加:画像を fetch してバイナリを Metadata タブに渡す
- ギャラリー画像カード(サムネイル・テーブル両ビュー)で **Alt+クリック** すると Metadata タブで開く
- 詳細パネルに **Metadata ボタン** を追加(`index.html` の `wfm-gallery-open-metadata-btn`):選択中の画像を Metadata タブで開く
- 詳細タブ切り替えロジックを修正(`data-detail-tab` を持つボタンのみ active/display を切り替え、Metadata ボタンを除外)
#### ヘルプ更新(`templates/index.html`)
- Models Tab ヘルプ(`wfm-help-models-2`、`-6`、`-7`、`-11`)を今回の変更に合わせて更新
---
## 2026-06-09: v0.3.33 — LoRAペイン・ワークフロー解析バグ修正
### 変更内容
#### LoRAペイン:ワークフロー読み込み時のLoraManager上書き防止(`static/js/comfyui-editor.js`)
- `renderLoraPane` 末尾にあった「Auto-apply Stack to LoraManager on load」ブロックを削除
- ワークフロー読み込み時にModelタブのStackグループ内容が `inputs.loras` / `inputs.text` を上書きし、RAW JSONが変わるバグを修正
- Apply ボタン押下時のみStackがLoraManagerに書き込まれる正しい動作に
#### LoRAペイン:🔄ボタン押下でSingleタブに戻るバグ修正(`static/js/comfyui-editor.js`)
- `renderLoraPane` 呼び出し前に現在のアクティブタブを `_prevActiveTab` に保存
- `el.innerHTML` 再構築後にタブ状態(activeクラス・display)を復元する処理を追加
- 🔄ボタン・モデルタブ切り替えによる再レンダリング後もStackタブに留まるよう修正
#### ModelsタブCheckpointへのStackグループ非表示(`static/js/models-tab.js`)
- `loadModelsForCurrentType` のグループロード後、`STACK_MODEL_TYPES`(lora のみ)に含まれないタイプでは `state.modelGroups["Stack"]` をメモリ上から削除
- Checkpointなどのタイプでグループフィルターおよびサイドパネルのグループ管理にStackが表示されなくなった
#### CLIPTextEncodeEditPlus ウィジェット値マッピング修正(`static/js/comfyui-workflow.js`)
- `convertUiToApi` でUIスロット入力にリンクが接続されている場合(`linkedSlotNames`)、`widgets_values` のインデックスを進めないよう変更
- 従来は `object_info` の STRING 型オプション入力(`text1` 等)がウィジェット名リストに含まれ、リンクあり判定でインデックスがズレていた
- `widgets_values: ["girl", "+af", ""]` で `text_edit="girl"` / `mode="+af"` が正しくマッピングされるよう修正
#### Stack Apply時のTrigger Words処理修正(`static/js/comfyui-editor.js`)
- Applyクリックハンドラー内でトリガーワードをレンダリング時のスナップショット変数から取得していたため、チェックボックス変更が反映されないバグを修正
- `currentAllTriggers` / `currentActiveTriggers` を Apply 時点で `_stackActive` + `metadata` + `civitaiCache` から動的に再計算するよう変更
- 修正前の不具合:1回目ApplyはLORA SYNTAXのみ(TRIGGER WORDSなし)、2回目で追加される / モデル無効でApply後もTRIGGER WORDSが残る
---
## 2026-06-08: v0.3.32 — Lora Loader (LoraManager) LoRA検出対応・ライブラリ機能拡張
### 変更内容
+111 -16
View File
@@ -1,11 +1,24 @@
# ComfyUI-Workflow-Studio
A comprehensive workflow management and generation UI plugin for [ComfyUI](https://github.com/comfyanonymous/ComfyUI).
A comprehensive workflow, asset management, and generation UI plugin for [ComfyUI](https://github.com/comfyanonymous/ComfyUI).
Browse, organize, and execute workflows directly from a dedicated studio interface — without switching between windows or manually editing JSON.
**📁 Management** — organize all your assets in one studio
- Workflow, model, image, and prompt management
- AI-powered prompt writing assistance, translation, and tag generation
- File drop & Gallery-linked metadata viewing — inspect and reuse generation settings instantly
**⚡ GenerateUI** — a productivity-focused generation tab connected to every other tab
- Batch generation across models, samplers, prompts, and workflows
- Image Feeder for continuous folder-based generation
**📚 Workflow Studio Library** — a multi-function side panel for smooth ComfyUI integration
- Drag & drop models, nodes, prompts, and workflows straight onto the canvas
- **Send to Canvas**: click "Send to Canvas" (Workflow tab) or "Copy & Send Canvas" (Gallery tab) — 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.32-green)
![Version](https://img.shields.io/badge/version-0.3.41-green)
## Screenshots
@@ -17,13 +30,21 @@ Browse, organize, and execute workflows directly from a dedicated studio interfa
|:---:|:---:|
| ![Prompt Input Assistance](docs/3_PromptInputAssistance.png) | ![Gen UI Feeder](docs/4_GenUI_feeder.png) |
| Top Bar | WS Library |
| GenUI LoRA Stack | GenUI Batch |
|:---:|:---:|
| ![Top Bar](docs/5_topbar.png) | ![WS Library](docs/6_ws_library.png) |
| ![GenUI LoRA Stack](docs/9_GenUI_LoraStack.png) | ![GenUI Batch](docs/10_GenUI_Batch.png) |
| Library Information | Customize |
| Models Multi-select Menu | Top Bar |
|:---:|:---:|
| ![Library Information](docs/7_library_Infomation.png) | ![Customize](docs/8_Customize.png) |
| ![Models Multi-select Menu](docs/11_multiple_select_menu.png) | ![Top Bar](docs/5_topbar.png) |
| WS Library | Library Information |
|:---:|:---:|
| ![WS Library](docs/6_ws_library.png) | ![Library Information](docs/7_library_Infomation.png) |
| Customize | |
|:---:|:---:|
| ![Customize](docs/8_Customize.png) | |
---
@@ -37,7 +58,7 @@ Browse, organize, and execute workflows directly from a dedicated studio interfa
- **Side panel tabs** — Thumbnail preview, JSON viewer with syntax highlighting, and Group management
- **Badge management** — add, rename, delete badges with custom colors shared with the Models tab (⚙ Badge button)
- **AI summary** — generate workflow descriptions using Ollama
- **Import / Export** — import workflows from files or clipboard, open in ComfyUI directly
- **Import / Export** — import workflows from files or clipboard; **Send to Canvas** button 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)
@@ -48,6 +69,7 @@ Browse, organize, and execute workflows directly from a dedicated studio interfa
### GenerateUI Tab (v0.3.5)
- **5-tab layout** — Input / Model / Settings / Feeder / Batch tabs; Input, Model, and Settings each include a Raw JSON column on the right for instant preview and direct editing
- **Save button** — located at the right end of the subtab row; opens a filename dialog (default: current workflow name) and saves the current workflow as a `.json` file to the Workflow tab via the import API
- **Input tab** — Prompt (top) and Image drag-and-drop (bottom) in the left column; Raw JSON (540px) in the right column
- **Model tab** — Checkpoint, VAE, LoRA, ControlNet, UNET, TextEncoder selectors with filter; Raw JSON on the right
- **Settings tab** — KSampler and Latent Image side by side at 50% width each; Raw JSON on the right
@@ -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,7 +164,8 @@ Requires the **[comfyui-image-feeder](https://github.com/ketle-man/comfyui-image
### Models Tab (v0.2.3)
- **Model Browser** — browse all installed ComfyUI models (Checkpoint, LoRA, VAE, ControlNet, UNET, TextEncoder, Hypernetwork, Embedding) with sub-tab switching
- **Thumbnail / Table views** — switch between view modes with pagination (24 items per page)
- **Thumbnail / Table views** — switch between view modes with pagination (24 items per page); Table view includes **Type** and **Base Model** columns sourced from cached CivitAI data, displayed between the Subdirectory and Extension columns; Enable/Disable column labeled **E/D**
- **Table column sort** — click any column header to sort ascending (▲), click again for descending (▼), click a third time to clear; active column highlighted in accent color
- **Search & Filter** — full-text search, filter by tags, groups, and favorites
- **User-defined badges** — assign free-label badges to models; badge colors shared with the Workflow tab palette
- **Side panel tabs** — 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
@@ -149,21 +173,37 @@ Requires the **[comfyui-image-feeder](https://github.com/ketle-man/comfyui-image
- **CivitAI panel — Info / Sample sub-tabs** — Info tab shows model details (name, type, base model, hash, trigger words, tags, description); Sample tab shows all sample images (count shown in tab label); clicking any image opens the full-size version in a new tab
- **CivitAI panel states** — three distinct states: not yet checked (fetch button), checked but not found on CivitAI (re-check button with notice), and found (full info display); clicking the CivitAI tab always refreshes to the latest state
- **Batch CivitAI fetch** — one-click batch fetch using `POST /model-versions/by-hash` (up to 100 models per request) with SSE progress streaming; previews are auto-saved for models without one
- **Detail modal** — preview image, CivitAI info, thumbnail change via file upload
- **Detail modal** — preview image, CivitAI info, thumbnail change via file upload; **Delete** button permanently removes the model file and all associated sidecar files (preview images, `.json`, `.civitai.info`, `.metadata.json`, `.cm-info.json`)
- **GenUI Model button** — apply the selected model directly to the corresponding node in GenerateUI's current workflow (Checkpoint, LoRA, VAE, ControlNet, UNET, TextEncoder)
- **Group management** — create, rename, delete groups and assign/remove models; groups are scoped per model type (checkpoint groups only appear in the Checkpoint tab)
- **Group management** — create, rename, delete groups and assign/remove models; groups are scoped per model type (checkpoint groups only appear in the Checkpoint tab); Checkpoint and LoRA tabs include **B (Batch)** and **S (Stack)** quick-assign buttons per card/row for one-click group membership toggle without grid re-render
- **Table view memo** — memo column displayed in table view for quick reference
- **Preview images** — auto-detect `{model_stem}.preview.png` next to model files
- **Enable / Disable models** — hide models from ComfyUI by renaming the file extension (`.disabled` suffix); toggle per card (⏸ button), per group (Enable All / Disable All), or filter by status (All / Enabled / Disabled)
- **Multi-select & bulk operations** — enter selection mode to check multiple models; bulk action bar supports: **Deselect All** (clear all without exiting select mode), **★ Favorite / ☆ Unfavorite** (toggle favorites for all selected), **Add / Remove from Group**, **Create & Add** (new group), **+Badge / −Badge** (apply or remove a badge from all selected), and permanent **Delete Files** (model file + preview images + sidecar files such as `.json` / `.info`)
- **Multi-select & bulk operations** — click the green **Select** button to enter selection mode and check multiple models; the bulk action bar is organized in three rows:
- **Group row** — select an existing group and **Add** / **Remove**, or type a new name and **Create & Add**
- **Badge row** — select a badge and **+Badge** / **−Badge** to apply or remove from all selected
- **File row** — select a destination subfolder (or type a new folder name and create it) then **Move** to relocate the model file with all sidecar files; **Delete Files** (right end) permanently removes selected models and all associated files
### Tagger Tab (v0.3.38)
- **3 sub-tabs** — Single / Batch / DB for single-image tagging, folder batch processing, and tag database management
- **Model support** — WD Tagger (ONNX, NCHW/NHWC auto-detect), SwinV2 (ONNX), DeepDanbooru (.h5, requires TensorFlow); place each model in its own subfolder under `ComfyUI/models/tagger/<model-name>/` containing the `.onnx` + `selected_tags.csv` (or `.h5` + label file)
- **Threshold sliders** — General threshold (default 0.35) and Character threshold for `character:` prefix tags (default 0.85); sliders update the display value in real time
- **Ollama VLM** — optional vision model alongside WD Tagger; set API URL and select model (↻ to refresh list); results from both models are merged into one comma-separated tag string
- **Single tab** — drag & drop an image onto the preview area or click Upload; Gallery detail panel **Tagger** button opens the selected image directly here
- **Single output options** — (1) **GenUI:P** — appends tags to the GenerateUI tab's positive prompt and immediately applies to the loaded workflow; (2) **Send to Prompt** — appends tags to the Prompt tab's positive textarea; (3) **Save to Gallery** — saves tags to Gallery image metadata (requires image opened from Gallery); (4) **Write to File** — embeds tags into JPEG EXIF (`ImageDescription`) or PNG `tEXt` chunk (`Tags` key), other formats get a `.tags.json` sidecar; (5) **Save to DB** — stores in internal SQLite database
- **Batch tab** — enter a folder path, configure WD Tagger and Ollama settings; output options: **Save to DB** (default on), **Write to File** (EXIF/PNG metadata), **Write .txt** (creates `<filename>.txt` alongside each image with all tags); real-time progress bar and log; Stop cancels after the current image
- **DB tab** — searchable SQLite database of all tagged images; click a row to open the edit panel and modify WD Tags / VLM Tags; Save updates the record, Delete removes it; Export CSV downloads all records
- **Dependencies** — install into ComfyUI's embedded Python: `python_embedded\python.exe -m pip install -r requirements.txt`; for GPU inference use `onnxruntime-gpu`; TensorFlow (DeepDanbooru) is optional and commented out in `requirements.txt`
### AI TOOL Tab (v0.3.14)
- **3-pane layout** — Translation (40%) | TOOLS (40%) | Settings (20%); all panes always visible simultaneously; no sub-tab switching required
- **4-pane layout** — Translation | Chat | TOOLS | Settings; all panes always visible simultaneously; no sub-tab switching required
- **Translation pane** — translate text between Japanese, English, Chinese, or a custom Free language using Ollama or LM Studio; language selectors with ⇄ swap button (swaps both language selectors and text content); selections saved automatically
- **Chat pane** (v0.3.40) — multi-turn conversation with the LLM; full conversation history sent each turn for context; Enter to send, Shift+Enter for a newline; Clear button resets history; Ollama uses `/api/chat`, LM Studio uses `/v1/chat/completions`
- **TOOLS pane (VLM)** — drop an image into the 110px drop zone, select a task (Describe Image / Create Prompt / Create Tags), and click Run to analyze with a vision model; result shown in the output area with a Copy button
- **TOOLS pane (Wildcards)** (v0.3.40) — select "Create wildcards" from the task dropdown; enter a category name and count; click Run to generate plain-text wildcard entries one per line (no markdown, no numbering); result can be copied directly into wildcard `.txt` files
- **Settings pane** — choose backend (Ollama / LM Studio), set the API URL, test connection, select a model (with refresh button), and configure Free language names for translation source and destination
- **Settings shared** — settings saved to `localStorage` under `wfm_ai_settings`; shared with the Library panel's AI TOOL tab so configuration is consistent across both interfaces
- **Backend support** — Ollama (`/api/generate` for text, `/api/tags` for model list); LM Studio OpenAI-compatible API (`/v1/chat/completions`, `/v1/models`); VLM images sent as base64 (`images:[]` for Ollama, `image_url` content block for LM Studio)
- **Backend support** — Ollama (`/api/generate` for text, `/api/chat` for conversations, `/api/tags` for model list); LM Studio OpenAI-compatible API (`/v1/chat/completions`, `/v1/models`); VLM images sent as base64 (`images:[]` for Ollama, `image_url` content block for LM Studio)
- **URL security** — backend URL validated via `new URL()` to enforce `http://` or `https://` scheme
### Workflow Studio Library (ComfyUI Side Panel) (v0.3.9)
@@ -175,13 +215,14 @@ Requires the **[comfyui-image-feeder](https://github.com/ketle-man/comfyui-image
- **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** — 3-pane layout (Translation | TOOLS | Settings) always visible; Translation and TOOLS (VLM) powered by Ollama or LM Studio; settings (backend, URL, model) shared with the SPA AI TOOL tab via `localStorage`
- **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
@@ -280,6 +321,60 @@ Click the **camera icon** (next to the W button) in ComfyUI's top bar to capture
## Changelog
### v0.3.41
- **Generate UI — ImpactWildcardEncode / ImpactWildcardProcessor prompt detection** — fixed: wildcard text inputs from comfy-impact-pack nodes were not shown in the Prompt tab of Generate UI
- `CLIPTextEncodeEditPlus` node (used as the text encoder in these workflows) now correctly propagates positive/negative roles upstream to ImpactWildcard nodes via BFS
- `CLIPTextEncodeEditPlus` with an empty `text_edit` field is no longer added to `prompt_nodes` ahead of the upstream ImpactWildcard node, preventing a blank text area
- `widgets[0]` is now always written to `wildcard_text` in the API conversion step, regardless of `object_info` widget-order differences between impact-pack versions
- Static fallback mapping added for `ImpactWildcardProcessor` and `ImpactWildcardEncode` so detection works even when the ComfyUI server is offline
### v0.3.40
- **AI TOOL tab — Chat pane** — new pane (between Translation and TOOLS) for multi-turn conversation with the LLM; full conversation history sent each turn for context; Enter to send, Shift+Enter for newline; Clear button resets history; Ollama uses `/api/chat`, LM Studio uses `/v1/chat/completions`
- **AI TOOL tab — Wildcard generation** — new "Create wildcards" task in the TOOLS pane dropdown; enter a category name and count, click Run to generate plain-text entries one per line (no markdown, no numbering); output can be pasted directly into wildcard `.txt` files
- **Library A tab — Chat and Wildcards** — both features added to the side panel's A tab: Chat as a new sub-tab (Translation → Chat → TOOLS → Settings), wildcard generation as a new option in the TOOLS sub-tab dropdown
- **Help updated** — AI TOOL tab help card updated to 6 items (Chat and Wildcards added); Library panel sidepanel-16 updated; EN/JA/ZH
### v0.3.39
- **Workflow tab — Send to Canvas button** — replaced "Open in ComfyUI" (toolbar and detail modal) with "Send to Canvas"; stores the selected workflow in `localStorage` for title-drag to the canvas without opening a new browser tab
- **Gallery tab — Copy & Send Canvas button** — renamed "Copy Workflow" to "Copy & Send Canvas"; copies the embedded workflow JSON to the clipboard and simultaneously stores it for title-drag
- **Workflow Studio Library — title drag** — after "Send to Canvas" or "Copy & Send Canvas" is clicked, the "Workflow Studio Library" panel title turns blue with a green ● indicator; drag the title onto the ComfyUI canvas to load the workflow; title resets automatically after loading
### v0.3.38
- **Tagger tab** — new tab for automatic image tagging; supports WD Tagger (ONNX), SwinV2, DeepDanbooru (.h5), and Ollama VLM; 3 sub-tabs: Single (drag & drop / upload, 5 output targets), Batch (folder processing with real-time progress), DB (searchable SQLite database with CSV export)
- **Tagger single — GenUI:P button** — new button (left of "Send to Prompt") that appends generated tags to the GenerateUI positive prompt and immediately applies them to the loaded workflow; shows a warning if no workflow is loaded in GenerateUI
- **Tagger batch — Write .txt output** — new output option that creates `<filename>.txt` alongside each processed image containing all generated tags (comma-separated)
- **Gallery detail panel — Tagger button** — new action button in the Gallery detail panel opens the selected image directly in the Tagger tab for instant single-image tagging
- **Gallery detail panel layout** — tabs (Info / JSON / Groups) and action buttons (Metadata / Load GenUI / Tagger) are now on separate rows, preventing button overflow on narrow panels
- **Gallery — Save to Gallery tags fix** — tags saved from the Tagger tab were stored as a string instead of an array, causing `forEach is not a function` errors on the next Gallery refresh; now correctly stored as a string array
- **GenerateUI — ZIT/Lumina2 workflow prompt fix** — `ConditioningZeroOut` removed from the CONDITIONING passthrough set; previously it propagated the "negative" role upstream through the shared CLIPTextEncode node, marking it as "unknown" and hiding the positive prompt in the GenerateUI Input tab; ZIT (Z-Image Turbo) workflows now correctly show the positive prompt
- **Workflow analyzer — lumina2 model type** — CLIPLoader `type: "lumina2"` is now correctly classified as Z-IMAGE in the workflow type detector
### v0.3.37
- **Models tab — Select All button** — new button added to the right of "Deselect All" in the multi-select action bar; selects all models currently visible after applying the active search / filter / group filters
- **Gallery tab — Select All button** — new button added to the right of "Deselect All" in the bulk action bar; selects all images in the current folder view
- **Gallery bulk bar — i18n** — all bulk action bar buttons and the selection count were hard-coded English strings; they now use the `t()` translation system (EN / JA / ZH) so the bar respects the selected UI language
### v0.3.36
- **GenerateUI Save — overwrite protection** — saving now checks for an existing file and asks for confirmation before overwriting; if the target file is in UI format, a dedicated warning explains that saving in API format will lose the node layout
- **GenerateUI Save — Raw JSON sync** — unapplied Raw JSON edits are now included in the save (parsed and synced back to the editor); invalid JSON aborts the save with an error instead of silently saving stale content
- **GenerateUI Save — hardening** — filename is set via DOM (no HTML-attribute injection), image extensions (`.png` etc.) are stripped from the default name, and a double-submit guard prevents duplicate POSTs
- **Help i18n fixed** — v0.3.35 help text updates (Save button, table sort, JSON tab rename) were being overwritten at startup by stale i18n strings and never displayed; all help keys synced in EN / JA / ZH and new entries registered in the help ID map
- **Toast i18n** — ~115 hard-coded English toasts replaced with translated messages (~60 new shared keys in EN / JA / ZH); Settings labels for Text Size / RAW JSON Colors that displayed raw key names are now properly defined
- **Refactoring** — new shared `util.js` (`escapeHtml` unified across 5 files — the Metadata tab copy was missing `"` escaping; `readJsonStorage` / `getSettings` replace 15 direct `localStorage` parses); Models table sort now precomputes sort keys (faster on large libraries); Gallery action buttons moved off the tab-button class, removing all `!important` CSS overrides
- **README refreshed** — intro rewritten around the three pillars (Management / GenerateUI / Library side panel); new screenshots: GenUI LoRA Stack, GenUI Batch, Models Multi-select Menu; WS Library image updated
### v0.3.35
- **Models tab — Table column sort** — click any column header to sort ascending (▲), click again for descending (▼), click a third time to clear; active column name highlighted in accent color; Enable/Disable column header now labeled **E/D**
- **Gallery tab — Load GenUI button** — new button to the right of the Metadata button in the detail panel; loads the embedded ComfyUI workflow from the selected image directly into the GenerateUI tab; warning toast shown if no workflow is embedded or the format is unsupported; Metadata button restyled green, Load GenUI uses primary accent color
- **GenerateUI tab — Save button** — new button at the right end of the subtab row; opens a filename dialog (default: current workflow name) and saves the current workflow as a `.json` file to the Workflow tab via the import API; workflow name label updates to the saved filename on success
### v0.3.33
- **LoRA pane — workflow load no longer overwrites LoraManager** — removed the auto-apply block that replaced `inputs.loras` / `inputs.text` with Stack group contents on every workflow load; Stack is now applied only when the Apply button is pressed
- **LoRA pane — 🔄 button no longer resets to Single tab** — active tab state is saved before `innerHTML` rebuild and restored afterwards; staying on Stack tab after refresh
- **Models tab — Stack group hidden for non-LoRA types** — when switching to Checkpoint or other non-LoRA types, the Stack group is now excluded from the group filter dropdown and side-panel group management (LoRA-only concept)
- **CLIPTextEncodeEditPlus widget mapping fix** — `convertUiToApi` no longer advances `wIdx` for UI slot inputs that have an actual link, preventing index misalignment when `object_info` lists optional STRING inputs (e.g. `text1`) before widget inputs (e.g. `text_edit`); fixes `+af` appearing as the positive prompt instead of the edit text
- **Stack Apply — trigger words now applied correctly on first press** — trigger words (`currentAllTriggers` / `currentActiveTriggers`) are now recomputed at click time from the latest `_stackActive` + `metadata` + `civitaiCache`; previously used a stale snapshot captured at render time, causing trigger words to be missing on the first Apply and to linger after disabling a model
### v0.3.32
- **Lora Loader (LoraManager) LoRA detection** — I tab and Metadata tab now correctly detect LoRAs from `Lora Loader (LoraManager)` nodes in API format (`inputs.loras.__value__`); `strength`/`clipStrength` stored as strings (e.g. `"0.20"`) are now parsed correctly
- **LoraManager node placement — LoRA syntax** — placing a `Lora Loader (LoraManager)` node via drag now also updates the `text` widget with `<lora:name:strength>` syntax (previously only the `loras` array widget was set)
Binary file not shown.

After

Width:  |  Height:  |  Size: 193 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 16 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 16 KiB

After

Width:  |  Height:  |  Size: 64 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 48 KiB

+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"
+45
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 ─────────────────────────────────────────
@@ -571,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)
+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)
+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
+125 -1
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"
@@ -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)))
+1
View File
@@ -18,6 +18,7 @@ _CLIP_TYPE_TO_MODEL = {
"wan": "Wan",
"cosmos": "Cosmos",
"lumina": "Lumina",
"lumina2": "Z-IMAGE",
}
+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.32"
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.41"
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 {
+189 -5
View File
@@ -4102,6 +4102,14 @@ body {
width: 30px;
}
.wfm-table-th-filename,
.wfm-table-td-filename {
max-width: 160px;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
.wfm-table-th-subdir,
.wfm-table-td-subdir {
width: 80px;
@@ -4111,6 +4119,26 @@ body {
white-space: nowrap;
}
.wfm-table-th-civtype,
.wfm-table-td-civtype {
width: 70px;
max-width: 70px;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
font-size: 0.85em;
}
.wfm-table-th-basemodel,
.wfm-table-td-basemodel {
width: 110px;
max-width: 110px;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
font-size: 0.85em;
}
.wfm-table-th-ext,
.wfm-table-td-ext {
width: 60px;
@@ -4226,6 +4254,17 @@ body {
}
/* Table sort header */
.wfm-table-th-sortable {
cursor: pointer;
-webkit-user-select: none;
user-select: none;
white-space: nowrap;
}
.wfm-table-th-sortable:hover {
color: var(--wfm-accent, #6366f1);
}
/* Table view toggle cell */
.wfm-table-td-toggle {
text-align: center;
@@ -4297,13 +4336,45 @@ body {
}
.wfm-bulk-bar {
display: flex;
align-items: center;
gap: 8px;
flex-direction: column;
gap: 4px;
padding: 6px 12px;
background: rgba(108, 142, 245, 0.12);
border-bottom: 1px solid rgba(108, 142, 245, 0.3);
}
.wfm-bulk-header {
display: flex;
align-items: center;
gap: 6px;
flex-wrap: wrap;
}
.wfm-bulk-rows {
display: flex;
flex-direction: column;
gap: 3px;
}
.wfm-bulk-row {
display: flex;
align-items: center;
gap: 4px;
}
.wfm-bulk-row-label {
font-size: 12px;
color: var(--wfm-text-secondary);
width: 44px;
flex-shrink: 0;
text-align: right;
}
.wfm-bulk-select {
width: 330px !important;
max-width: 330px !important;
font-size: 12px !important;
padding: 2px 4px !important;
}
.wfm-bulk-input {
width: 110px !important;
font-size: 12px;
}
.wfm-bulk-count {
font-size: 13px;
color: #a0a8c0;
@@ -4314,6 +4385,21 @@ body {
height: 18px;
background: rgba(255, 255, 255, 0.15);
margin: 0 4px;
flex-shrink: 0;
}
.wfm-btn-success {
background: #22c55e;
color: #fff;
border-color: #16a34a;
}
.wfm-btn-success:hover {
background: #16a34a;
border-color: #15803d;
}
.wfm-btn-success.active {
background: #16a34a;
border-color: #15803d;
box-shadow: 0 0 0 2px rgba(34, 197, 94, 0.4);
}
/* ── Batch Tab ──────────────────────────────────────────────────── */
@@ -5030,7 +5116,7 @@ body {
display: flex;
}
/* 3-pane layout */
/* 4-pane layout */
.wfm-ai-pane {
display: flex;
flex-direction: column;
@@ -5038,8 +5124,9 @@ body {
min-width: 0;
}
.wfm-ai-pane-translate { flex: 4; }
.wfm-ai-pane-tools { flex: 4; }
.wfm-ai-pane-translate { flex: 3; }
.wfm-ai-pane-chat { flex: 4; }
.wfm-ai-pane-tools { flex: 3; }
.wfm-ai-pane-settings { flex: 2; }
.wfm-ai-pane-header {
@@ -5214,6 +5301,25 @@ body {
margin-left: 4px;
}
/* Wildcard inputs */
.wfm-ai-wc-inputs {
display: flex;
flex-direction: column;
gap: 6px;
flex-shrink: 0;
}
.wfm-ai-wc-row {
display: flex;
align-items: center;
gap: 8px;
}
.wfm-ai-wc-count {
width: 70px;
flex-shrink: 0;
}
/* VLM Tab */
.wfm-ai-vlm-container {
display: flex;
@@ -5283,3 +5389,81 @@ body {
align-self: flex-end;
flex-shrink: 0;
}
/* Chat pane */
.wfm-ai-chat-container {
display: flex;
flex-direction: column;
flex: 1;
overflow: hidden;
min-height: 0;
padding: 8px;
gap: 8px;
}
.wfm-ai-chat-messages {
flex: 1;
overflow-y: auto;
display: flex;
flex-direction: column;
gap: 8px;
min-height: 0;
padding: 4px;
}
.wfm-ai-chat-msg {
max-width: 90%;
padding: 8px 10px;
border-radius: 8px;
font-size: 13px;
line-height: 1.5;
word-break: break-word;
white-space: pre-wrap;
}
.wfm-ai-chat-msg-user {
align-self: flex-end;
background: var(--wfm-primary);
color: #fff;
}
.wfm-ai-chat-msg-assistant {
align-self: flex-start;
background: var(--wfm-surface);
border: 1px solid var(--wfm-border);
color: var(--wfm-text);
}
.wfm-ai-chat-input-area {
display: flex;
flex-direction: column;
gap: 6px;
flex-shrink: 0;
}
.wfm-ai-chat-input {
width: 100%;
min-height: 60px;
max-height: 120px;
padding: 8px 10px;
background: var(--wfm-bg);
border: 1px solid var(--wfm-border);
border-radius: var(--wfm-radius-sm);
color: var(--wfm-text);
font-size: 13px;
font-family: inherit;
resize: none;
line-height: 1.5;
box-sizing: border-box;
}
.wfm-ai-chat-input:focus {
outline: none;
border-color: var(--wfm-primary);
}
.wfm-ai-chat-actions {
display: flex;
align-items: center;
gap: 6px;
}
+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;
}
+154 -12
View File
@@ -5,6 +5,7 @@
import { showToast } from "./app.js";
import { t } from "./i18n.js";
import { readJsonStorage } from "./util.js";
const SETTINGS_KEY = "wfm_ai_settings";
@@ -19,11 +20,7 @@ const LANG_NAMES = {
// ============================================
function loadAiSettings() {
try {
return JSON.parse(localStorage.getItem(SETTINGS_KEY) || "{}");
} catch {
return {};
}
return readJsonStorage(SETTINGS_KEY);
}
function saveAiSettings(patch) {
@@ -367,6 +364,111 @@ function initSettingsTab() {
}
}
// ============================================
// Chat tab
// ============================================
async function callChat(url, backend, model, messages) {
if (backend === "ollama") {
const res = await fetch(`${url}/api/chat`, {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ model, messages, stream: false }),
});
if (!res.ok) throw new Error(`HTTP ${res.status}`);
return (await res.json()).message?.content || "";
} else {
const res = await fetch(`${url}/v1/chat/completions`, {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ model, messages, stream: false }),
});
if (!res.ok) throw new Error(`HTTP ${res.status}`);
return (await res.json()).choices?.[0]?.message?.content || "";
}
}
function appendChatBubble(messagesEl, role, content) {
const div = document.createElement("div");
div.className = `wfm-ai-chat-msg wfm-ai-chat-msg-${role}`;
div.textContent = content;
messagesEl.appendChild(div);
messagesEl.scrollTop = messagesEl.scrollHeight;
return div;
}
function initChatTab() {
const messagesEl = document.getElementById("wfm-ai-chat-messages");
const inputEl = document.getElementById("wfm-ai-chat-input");
const sendBtn = document.getElementById("wfm-ai-chat-send-btn");
const clearBtn = document.getElementById("wfm-ai-chat-clear-btn");
const statusEl = document.getElementById("wfm-ai-chat-status");
if (!messagesEl || !inputEl || !sendBtn) return;
let chatHistory = [];
async function sendMessage() {
const text = inputEl.value.trim();
if (!text) return;
const settings = loadAiSettings();
const { backend = "ollama", backendUrl, model } = settings;
const url = backendUrl || (backend === "ollama" ? "http://localhost:11434" : "http://localhost:1234");
if (!isValidBackendUrl(url)) {
showToast(t("aiToastInvalidUrl"), "error");
return;
}
if (!model) {
showToast(t("aiToastNoModel"), "error");
return;
}
inputEl.value = "";
inputEl.style.height = "";
chatHistory.push({ role: "user", content: text });
appendChatBubble(messagesEl, "user", text);
sendBtn.disabled = true;
statusEl.textContent = t("aiStatusChatting");
statusEl.className = "wfm-ai-trans-status wfm-ai-status-working";
try {
const reply = await callChat(url, backend, model, chatHistory);
chatHistory.push({ role: "assistant", content: reply });
appendChatBubble(messagesEl, "assistant", reply);
statusEl.textContent = "";
statusEl.className = "wfm-ai-trans-status";
} catch (err) {
chatHistory.pop();
if (messagesEl.lastChild) messagesEl.removeChild(messagesEl.lastChild);
inputEl.value = text;
statusEl.textContent = `${t("aiStatusConnectFail")}${err.message}`;
statusEl.className = "wfm-ai-trans-status wfm-ai-status-error";
showToast(t("aiToastChatFailed") + err.message, "error");
} finally {
sendBtn.disabled = false;
}
}
sendBtn.addEventListener("click", sendMessage);
inputEl.addEventListener("keydown", (e) => {
if (e.key === "Enter" && !e.shiftKey) {
e.preventDefault();
sendMessage();
}
});
clearBtn.addEventListener("click", () => {
chatHistory = [];
messagesEl.innerHTML = "";
statusEl.textContent = "";
statusEl.className = "wfm-ai-trans-status";
});
}
// ============================================
// VLM tab
// ============================================
@@ -381,11 +483,22 @@ function initVlmTab() {
const statusEl = document.getElementById("wfm-ai-vlm-status");
const resultEl = document.getElementById("wfm-ai-vlm-result");
const copyBtn = document.getElementById("wfm-ai-vlm-copy");
const wcInputs = document.getElementById("wfm-ai-wc-inputs");
const wcNameEl = document.getElementById("wfm-ai-wc-name");
const wcCountEl = document.getElementById("wfm-ai-wc-count");
if (!dropEl) return;
let vlmImage = null; // { base64, mimeType }
function updateTaskUI() {
const isWildcard = taskSel?.value === "wildcard";
dropEl.style.display = isWildcard ? "none" : "";
if (wcInputs) wcInputs.style.display = isWildcard ? "" : "none";
}
taskSel?.addEventListener("change", updateTaskUI);
updateTaskUI();
const loadImage = async (file) => {
if (!file || !file.type.startsWith("image/")) return;
vlmImage = await fileToBase64(file);
@@ -405,19 +518,47 @@ function initVlmTab() {
});
runBtn.addEventListener("click", async () => {
if (!vlmImage) { showToast(t("aiToastNoImage"), "error"); return; }
const task = taskSel?.value || "describe";
const settings = loadAiSettings();
const { backend = "ollama", backendUrl, model } = settings;
const url = backendUrl || (backend === "ollama" ? "http://localhost:11434" : "http://localhost:1234");
if (!isValidBackendUrl(url)) {
showToast(t("aiToastInvalidUrl"), "error");
return;
}
if (!isValidBackendUrl(url)) { showToast(t("aiToastInvalidUrl"), "error"); return; }
if (!model) { showToast(t("aiToastNoModel"), "error"); return; }
const task = taskSel?.value || "describe";
if (task === "wildcard") {
const name = wcNameEl?.value.trim() || "";
const count = Math.max(1, parseInt(wcCountEl?.value) || 20);
if (!name) { showToast(t("aiToastWcNoName"), "error"); return; }
runBtn.disabled = true;
statusEl.textContent = t("aiStatusRunning");
statusEl.className = "wfm-ai-trans-status wfm-ai-status-working";
resultEl.value = "";
const prompt = `Generate ${count} wildcard entries for the category "${name}". Output only plain text in English, one entry per line, no numbers, no markdown, no asterisks, no bold, nothing else.`;
try {
const result = await callLLM(url, backend, model, prompt);
resultEl.value = result.trim()
.split("\n")
.map(l => l.replace(/\*\*/g, "").replace(/^\*\s*/, "").replace(/^\d+\.\s*/, "").trim())
.filter(l => l.length > 0)
.join("\n");
statusEl.textContent = t("aiStatusDone");
statusEl.className = "wfm-ai-trans-status wfm-ai-status-ok";
} catch (err) {
statusEl.textContent = `${t("aiStatusConnectFail")}${err.message}`;
statusEl.className = "wfm-ai-trans-status wfm-ai-status-error";
showToast(t("aiToastVlmFailed") + err.message, "error");
} finally {
runBtn.disabled = false;
}
return;
}
if (!vlmImage) { showToast(t("aiToastNoImage"), "error"); return; }
runBtn.disabled = true;
statusEl.textContent = t("aiStatusRunning");
statusEl.className = "wfm-ai-trans-status wfm-ai-status-working";
@@ -450,6 +591,7 @@ function initVlmTab() {
export function initAiTab() {
initTranslateTab();
initChatTab();
initVlmTab();
initSettingsTab();
}
+40 -12
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", ai: "tabAi" };
const tabMap = { workflow: "tabWorkflow", nodes: "tabNodes", models: "tabModels", generate: "tabGenerate", prompt: "tabPrompt", metadata: "tabMetadata", gallery: "tabGallery", settings: "tabSettings", help: "tabHelp", ai: "tabAi", tagger: "tabTagger" };
document.querySelectorAll(".wfm-tab").forEach((tab) => {
const key = tabMap[tab.dataset.tab];
if (key) tab.textContent = t(key);
@@ -114,7 +115,7 @@ function applyI18nToHtml() {
const listOpenComfyBtn = document.getElementById("wfm-list-open-comfyui-btn");
if (listOpenComfyBtn) {
listOpenComfyBtn.textContent = t("openInComfyUI");
listOpenComfyBtn.textContent = t("sendToCanvas");
if (listOpenComfyBtn.disabled) listOpenComfyBtn.title = t("selectCardFirst");
}
@@ -195,6 +196,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");
@@ -356,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",
@@ -374,6 +403,7 @@ function applyI18nToHtml() {
"wfm-help-sidepanel-13": "helpSidepanel13",
"wfm-help-sidepanel-14": "helpSidepanel14", "wfm-help-sidepanel-15": "helpSidepanel15",
"wfm-help-sidepanel-16": "helpSidepanel16",
"wfm-help-sidepanel-17": "helpSidepanel17",
"wfm-help-ai-title": "helpAiTitle",
"wfm-help-ai-1": "helpAi1", "wfm-help-ai-2": "helpAi2", "wfm-help-ai-3": "helpAi3",
"wfm-help-ai-4": "helpAi4", "wfm-help-ai-5": "helpAi5", "wfm-help-ai-6": "helpAi6",
@@ -383,7 +413,8 @@ function applyI18nToHtml() {
"wfm-help-trouble-title": "helpTroubleTitle",
"wfm-help-trouble-1": "helpTrouble1", "wfm-help-trouble-2": "helpTrouble2",
"wfm-help-trouble-3": "helpTrouble3", "wfm-help-trouble-4": "helpTrouble4",
"wfm-help-trouble-5": "helpTrouble5",
"wfm-help-trouble-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",
@@ -436,19 +467,15 @@ import { initModelsTab } from "./models-tab.js";
import { initGalleryTab } from "./gallery-tab.js";
import { initMetadataTab } from "./metadata-tab.js";
import { initAiTab } from "./ai-tab.js";
import { initTaggerTab } from "./tagger-tab.js";
// Apply saved theme immediately to prevent flash of default theme
applyTheme(getSavedTheme());
// Apply saved textarea font size
// Apply saved textarea font size & JSON highlight colors
try {
const _s = JSON.parse(localStorage.getItem("wfm_settings") || "{}");
const _s = getSettings();
if (_s.textareaFontSize) applyTextareaFontSize(_s.textareaFontSize);
} catch {}
// Apply saved JSON highlight colors
try {
const _s = JSON.parse(localStorage.getItem("wfm_settings") || "{}");
applyJsonColors(_s.jsonColors);
} catch {}
@@ -478,6 +505,7 @@ document.addEventListener("DOMContentLoaded", () => {
initMetadataTab();
initGalleryTab();
initAiTab();
initTaggerTab();
console.log("Workflow Studio: App initialized");
});
+26 -20
View File
@@ -359,6 +359,8 @@ export const comfyEditor = {
</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>
@@ -448,6 +450,14 @@ export const comfyEditor = {
});
});
// 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();
@@ -614,19 +624,31 @@ export const comfyEditor = {
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 (allStackTriggers.length > 0) {
const wordSet = new Set(allStackTriggers.map(w => w.trim().toLowerCase()));
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 = activeTriggerWords.length > 0
? `${effectiveSyntax}, ${activeTriggerWords.join(", ")}`
const append = currentActiveTriggers.length > 0
? `${effectiveSyntax}, ${currentActiveTriggers.join(", ")}`
: effectiveSyntax;
posTextarea.value = cleaned ? `${cleaned}, ${append}` : append;
} else {
@@ -652,22 +674,6 @@ export const comfyEditor = {
}
});
// ── Auto-apply Stack to LoraManager on load ──────────
if (defaultStackTarget && stackModels.length > 0 && comfyUI.currentWorkflow?.[defaultStackTarget]) {
const targetNode = loraNodes.find((n) => String(n.id) === String(defaultStackTarget));
if (targetNode?.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[defaultStackTarget].inputs.loras = { __value__: loraValue };
comfyUI.currentWorkflow[defaultStackTarget].inputs.text = _buildLoraManagerSyntax(stackModels);
_syncRawJson();
}
}
// Initial single tab display
_refreshLoraSingleDynamic(metadata, civitaiCache);
},
+42 -8
View File
@@ -295,10 +295,15 @@ export const comfyWorkflow = {
const nodeLinks = linkMap[node.id] || {};
const inputDefs = node.inputs || [];
const linkedInputNames = new Set();
// UI slot inputs with an actual link don't have a widget value entry in
// widgets_values (modern ComfyUI format). Track these separately so the
// widget-mapping loop won't advance wIdx for them.
const linkedSlotNames = new Set();
inputDefs.forEach((inp, idx) => {
if (nodeLinks[idx]) {
inputs[inp.name] = nodeLinks[idx];
linkedInputNames.add(inp.name);
linkedSlotNames.add(inp.name);
}
});
@@ -336,13 +341,15 @@ export const comfyWorkflow = {
const expectedType = widgetTypes[nIdx];
// Skip if this input is already linked
if (linkedInputNames.has(name)) {
// Still consume widget value(s) since widgets_values
// includes entries for linked inputs too
wIdx++;
// Also skip control_after_generate if present
if (wIdx < widgets.length && _isExtraWidgetValue(widgets[wIdx], expectedType)) {
if (!linkedSlotNames.has(name)) {
// Not a UI slot input — old-style linked input that still
// occupies a slot in widgets_values; consume it.
wIdx++;
if (wIdx < widgets.length && _isExtraWidgetValue(widgets[wIdx], expectedType)) {
wIdx++;
}
}
// UI slot inputs with a real link have no widget value entry — don't advance wIdx.
continue;
}
// Check if current widget value matches expected type
@@ -392,6 +399,14 @@ export const comfyWorkflow = {
} // end else (non-LoraManager path)
}
// ImpactWildcardEncode / ImpactWildcardProcessor: widgets[0] is always wildcard_text.
// Always overwrite: object_info ordering may misalign when widget order differs between
// impact-pack versions; widgets[0] is stable across all known versions.
if ((node.type === "ImpactWildcardEncode" || node.type === "ImpactWildcardProcessor")
&& widgets.length > 0) {
inputs["wildcard_text"] = widgets[0];
}
api[nodeId] = {
class_type: node.type,
inputs,
@@ -513,7 +528,10 @@ export const comfyWorkflow = {
// Nodes that pass CONDITIONING through without changing positive/negative role
const COND_PASSTHROUGH = new Set([
"ConditioningCombine", "ConditioningConcat", "ConditioningAverage",
"ConditioningZeroOut", "ConditioningSetTimestepRange",
"ConditioningSetTimestepRange",
// ConditioningZeroOut is intentionally excluded: it discards upstream text entirely
// (used as a no-text negative in ZIT/Lumina2 workflows). Propagating the negative
// role upstream would incorrectly mark the shared positive CLIPTextEncode as "unknown".
"ControlNetApply", "ControlNetApplyAdvanced",
"IPAdapterApply", "IPAdapterApplyFaceID",
"StyleModelApply",
@@ -561,6 +579,16 @@ export const comfyWorkflow = {
if (isNeg) samplerNegativeRef[tv[0]] = true;
}
}
// CLIPTextEncodeEditPlus — propagate role to its STRING inputs (text1, text2)
if (ct === "CLIPTextEncodeEditPlus") {
for (const key of ["text1", "text2"]) {
const tv = inputs[key];
if (Array.isArray(tv)) {
if (isPos) samplerPositiveRef[tv[0]] = true;
if (isNeg) samplerNegativeRef[tv[0]] = true;
}
}
}
}
}
@@ -635,10 +663,12 @@ export const comfyWorkflow = {
}
}
// CLIPTextEncodeEditPlus — text_edit is the locally editable override; text1 is always a link
// CLIPTextEncodeEditPlus — text_edit is the locally editable override; text1 is always a link.
// Skip when text_edit is empty: it means upstream nodes (ImpactWildcardEncode etc.) supply
// the actual prompt text and the edit field is just an optional local override.
if (ct === "CLIPTextEncodeEditPlus") {
const textVal = inputs.text_edit;
if (typeof textVal === "string") {
if (typeof textVal === "string" && textVal !== "") {
result.prompt_nodes.push({
id, type: ct, title, role: getRole(),
text: textVal, textKey: "text_edit",
@@ -844,6 +874,10 @@ function _getWidgetMapping(nodeType) {
CLIPLoader: ["clip_name", "type", "device"],
FluxGuidance: ["guidance"],
CFGNorm: ["strength"],
// Impact Pack wildcard nodes — only map wildcard_text (index 0); remaining widgets
// vary between versions and include frontend-only extras, so we leave them unmapped.
ImpactWildcardProcessor: ["wildcard_text"],
ImpactWildcardEncode: ["wildcard_text"],
};
return mappings[nodeType] || null;
}
+18 -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);
@@ -195,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;
@@ -215,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 ───────────────────────────────────────────────────
@@ -420,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", {
@@ -429,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 || "";
@@ -457,7 +458,7 @@ async function _applyPreset() {
}
_refreshGridCbs();
_updateStatus();
showToast(`Preset loaded: ${name}`, "success");
showToast(t("presetLoaded", name), "success");
}
async function _deletePreset() {
@@ -465,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 ───────────────────────────────────────────────────────
+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");
+152 -42
View File
@@ -2,28 +2,25 @@
* GenerateUI Tab - Workflow execution with parameter editing
*/
import { showToast } from "./app.js";
import { showToast, openModal, closeModal } from "./app.js";
import { comfyUI } from "./comfyui-client.js";
import { comfyWorkflow } from "./comfyui-workflow.js";
import { comfyEditor } from "./comfyui-editor.js";
import { t } from "./i18n.js";
import { syncJsonHighlight, syncScroll } from "./json-highlight.js";
import { initFeederTab, refreshFeederNodeList } from "./feeder-tab.js";
import { getSettings, readJsonStorage } from "./util.js";
// ============================================
// Eagle Auto-Save
// ============================================
function getEagleSettings() {
try {
const s = JSON.parse(localStorage.getItem("wfm_settings") || "{}");
return {
url: s.eagleUrl || "http://localhost:41595",
autoSave: !!s.eagleAutoSave,
};
} catch {
return { url: "http://localhost:41595", autoSave: false };
}
const s = getSettings();
return {
url: s.eagleUrl || "http://localhost:41595",
autoSave: !!s.eagleAutoSave,
};
}
async function saveToEagle(imageUrl, name, tags = []) {
@@ -103,6 +100,120 @@ function updateStatus(connected) {
}
}
// ============================================
// Workflow Save
// ============================================
async function saveCurrentWorkflow() {
if (!comfyUI.currentWorkflow) {
showToast(t("noWorkflowLoaded"), "warning");
return;
}
const currentFilename = document.getElementById("wfm-gen-wf-name")?.dataset?.filename || "";
const defaultStem = currentFilename.replace(/\.(json|png|jpg|jpeg|webp|gif)$/i, "") || "workflow";
const html = `
<div style="display:flex;flex-direction:column;gap:14px;min-width:300px;">
<div>
<label style="font-size:12px;color:var(--wfm-text-secondary);display:block;margin-bottom:4px;">${t("filenameLabel")}</label>
<div style="display:flex;align-items:center;gap:6px;">
<input type="text" id="wfm-save-wf-name" class="wfm-input" style="flex:1;" placeholder="workflow name">
<span style="color:var(--wfm-text-secondary);font-size:13px;">.json</span>
</div>
</div>
<div style="display:flex;gap:8px;justify-content:flex-end;">
<button class="wfm-btn wfm-btn-sm" id="wfm-save-wf-cancel-btn">${t("cancel")}</button>
<button class="wfm-btn wfm-btn-sm wfm-btn-primary" id="wfm-save-wf-confirm-btn">${t("save")}</button>
</div>
</div>`;
openModal(t("saveWorkflowTitle"), html);
// 属性値に埋め込まず DOM 経由で初期値を設定(ファイル名中の引用符等によるHTML注入防止)
const input = document.getElementById("wfm-save-wf-name");
if (input) input.value = defaultStem;
setTimeout(() => {
if (input) { input.focus(); input.select(); }
}, 50);
document.getElementById("wfm-save-wf-cancel-btn")?.addEventListener("click", () => closeModal());
let saving = false;
const doSave = async () => {
if (saving) return;
const stem = input?.value?.trim();
if (!stem) {
showToast(t("pleaseEnterFilename"), "warning");
return;
}
const filename = stem.endsWith(".json") ? stem : `${stem}.json`;
saving = true;
try {
// Raw JSON に未適用の編集があれば保存対象に反映する
let workflow = comfyUI.currentWorkflow;
const rawText = document.getElementById("wfm-gen-raw-json")?.value ?? "";
if (rawText.trim() && rawText !== JSON.stringify(workflow, null, 2)) {
try {
workflow = JSON.parse(rawText);
} catch {
showToast(t("rawJsonUnappliedInvalid"), "error");
return;
}
}
// 上書き確認(保存先がUI形式ならAPI形式化でレイアウトが失われる旨を警告)
try {
const listRes = await fetch("/api/wfm/workflows");
const listData = await listRes.json();
const existing = (Array.isArray(listData) ? listData : []).find(w => w.filename === filename);
if (existing) {
const msg = existing.analysis?.format === "ui"
? t("uiFormatOverwriteWarn")
: t("overwriteConfirm", filename);
if (!confirm(msg)) return;
}
} catch { /* 一覧取得失敗時は確認をスキップして保存を続行 */ }
const blob = new Blob(
[JSON.stringify(workflow, null, 2)],
{ type: "application/json" }
);
const file = new File([blob], filename, { type: "application/json" });
const fd = new FormData();
fd.append("files", file);
const res = await fetch("/api/wfm/workflows/import", { method: "POST", body: fd });
const data = await res.json();
const ng = (data.results || []).filter(r => r.status === "error");
if (ng.length) {
showToast(t("saveFailed", ng[0].message || "unknown error"), "error");
return;
}
closeModal();
if (workflow !== comfyUI.currentWorkflow) {
// Raw JSON の編集を保存した場合はエディタにも反映して同期する
await loadWorkflowIntoEditor(workflow, filename);
} else {
const nameEl = document.getElementById("wfm-gen-wf-name");
if (nameEl) {
nameEl.textContent = filename;
nameEl.dataset.filename = filename;
}
}
showToast(t("savedAs", filename), "success");
} catch (err) {
showToast(t("saveFailed", err.message), "error");
} finally {
saving = false;
}
};
document.getElementById("wfm-save-wf-confirm-btn")?.addEventListener("click", doSave);
input?.addEventListener("keydown", (e) => {
if (e.key === "Enter") doSave();
});
}
// ============================================
// Workflow Loading
// ============================================
@@ -117,7 +228,7 @@ export async function loadWorkflowIntoEditor(workflow, filename) {
} else if (format === "ui") {
apiWorkflow = await comfyWorkflow.convertUiToApi(workflow);
} else if (format === "unknown") {
showToast("Unknown workflow format", "error");
showToast(t("unknownWorkflowFormat"), "error");
return false;
}
@@ -149,7 +260,7 @@ export async function loadWorkflowIntoEditor(workflow, filename) {
refreshFeederNodeList();
showToast(`Workflow loaded: ${filename || ""}`, "success");
showToast(t("workflowLoadedName", filename || ""), "success");
return true;
}
@@ -806,9 +917,7 @@ async function _loadPromptGroupsForBatch() {
const res = await fetch("/api/wfm/prompts");
_batchGroupState.promptPresets = res.ok ? await res.json() : [];
} catch { _batchGroupState.promptPresets = []; }
try {
_batchGroupState.promptGroups = JSON.parse(localStorage.getItem("wfm_prompt_preset_groups") || "{}");
} catch { _batchGroupState.promptGroups = {}; }
_batchGroupState.promptGroups = readJsonStorage("wfm_prompt_preset_groups");
const validIds = new Set(_batchGroupState.promptPresets.map((p) => p.id));
for (const g of Object.keys(_batchGroupState.promptGroups)) {
@@ -844,9 +953,7 @@ function _renderBatchPromptGroupList() {
// Workflow グループ
// ============================================
function _loadWorkflowGroupsForBatch() {
try {
_batchGroupState.wfGroups = JSON.parse(localStorage.getItem("wfm_groups") || "{}");
} catch { _batchGroupState.wfGroups = {}; }
_batchGroupState.wfGroups = readJsonStorage("wfm_groups");
const currentNames = new Set(Object.keys(_batchGroupState.wfGroups));
for (const name of _batchGroupState.wfSelectedGroups) {
@@ -1157,7 +1264,7 @@ async function _coreGenerate(silent = false) {
saveGeneratedImagesMeta(images, { ...comfyUI.currentWorkflow }).catch(() => {});
}
if (!silent) showToast("Generation complete", "success");
if (!silent) showToast(t("generationComplete"), "success");
}
// ============================================
@@ -1205,7 +1312,7 @@ async function _runBatchLoop(items, applyFn, labelFn = (x) => String(x)) {
} catch (err) {
if (_ckptBatch.aborted) break;
failed++;
showToast(`[${i + 1}/${items.length}] Failed: ${err.message}`, "error");
showToast(t("batchItemFailed", i + 1, items.length, err.message), "error");
}
}
} finally {
@@ -1223,7 +1330,7 @@ async function _runBatchLoop(items, applyFn, labelFn = (x) => String(x)) {
if (batchCurrentName) batchCurrentName.textContent = _ckptBatch.aborted ? "Stopped" : "Done";
if (_ckptBatch.aborted) {
showToast(`Batch stopped — ${completed} completed, ${failed} failed`, "info");
showToast(t("batchStopped", completed, failed), "info");
} else {
showToast(
`Batch complete: ${completed}/${items.length}${failed > 0 ? ` (${failed} failed)` : ""}`,
@@ -1237,9 +1344,9 @@ async function _runBatchGenerate() {
switch (_activeBatchType) {
case "checkpoint": {
const ckptNodes = comfyUI.currentAnalysis?.checkpoint_nodes || [];
if (ckptNodes.length === 0) { showToast("No checkpoint node found in workflow", "error"); return; }
if (ckptNodes.length === 0) { showToast(t("modelsGenUINoNode", "checkpoint"), "error"); return; }
const list = _getSelectedCheckpoints();
if (list.length === 0) { showToast("No checkpoints selected", "error"); return; }
if (list.length === 0) { showToast(t("batchNoneSelected", "checkpoints"), "error"); return; }
await _runBatchLoop(list, (model) => {
for (const node of ckptNodes) {
if (comfyUI.currentWorkflow?.[node.id])
@@ -1250,9 +1357,9 @@ async function _runBatchGenerate() {
}
case "lora": {
const loraNodes = comfyUI.currentAnalysis?.lora_nodes || [];
if (loraNodes.length === 0) { showToast("No LoRA node found in workflow", "error"); return; }
if (loraNodes.length === 0) { showToast(t("modelsGenUINoNode", "LoRA"), "error"); return; }
const list = [..._getSelectedLoraGroupItems()];
if (list.length === 0) { showToast("No LoRAs selected", "error"); return; }
if (list.length === 0) { showToast(t("batchNoneSelected", "LoRAs"), "error"); return; }
await _runBatchLoop(list, (loraName) => {
for (const node of loraNodes) {
if (!comfyUI.currentWorkflow?.[node.id]) continue;
@@ -1273,11 +1380,11 @@ async function _runBatchGenerate() {
const positiveNodes = (comfyUI.currentAnalysis?.prompt_nodes || []).filter((n) => n.role === "positive");
const negativeNodes = (comfyUI.currentAnalysis?.prompt_nodes || []).filter((n) => n.role === "negative");
if (positiveNodes.length === 0 && negativeNodes.length === 0) {
showToast("No prompt node found in workflow", "error"); return;
showToast(t("modelsGenUINoNode", "prompt"), "error"); return;
}
// _getSelectedPromptGroupItems() はすでにプリセットオブジェクトの配列を返す
const list = _getSelectedPromptGroupItems();
if (list.length === 0) { showToast("No prompts selected", "error"); return; }
if (list.length === 0) { showToast(t("batchNoneSelected", "prompts"), "error"); return; }
await _runBatchLoop(list, (preset) => {
for (const node of positiveNodes) {
if (comfyUI.currentWorkflow?.[node.id])
@@ -1292,7 +1399,7 @@ async function _runBatchGenerate() {
}
case "workflow": {
const list = [..._getSelectedWfGroupItems()];
if (list.length === 0) { showToast("No workflows selected", "error"); return; }
if (list.length === 0) { showToast(t("batchNoneSelected", "workflows"), "error"); return; }
const savedWorkflow = comfyUI.currentWorkflow ? JSON.stringify(comfyUI.currentWorkflow) : null;
const savedFilename = document.getElementById("wfm-gen-workflow-name")?.textContent || "";
try {
@@ -1311,9 +1418,9 @@ async function _runBatchGenerate() {
}
case "sampler": {
const samplerNodes = comfyUI.currentAnalysis?.sampler_nodes || [];
if (samplerNodes.length === 0) { showToast("No KSampler node found in workflow", "error"); return; }
if (samplerNodes.length === 0) { showToast(t("modelsGenUINoNode", "KSampler"), "error"); return; }
const list = [..._samplerSelected].sort();
if (list.length === 0) { showToast("No samplers selected", "error"); return; }
if (list.length === 0) { showToast(t("batchNoneSelected", "samplers"), "error"); return; }
await _runBatchLoop(list, (samplerName) => {
for (const node of samplerNodes) {
if (comfyUI.currentWorkflow?.[node.id])
@@ -1324,9 +1431,9 @@ async function _runBatchGenerate() {
}
case "scheduler": {
const samplerNodes = comfyUI.currentAnalysis?.sampler_nodes || [];
if (samplerNodes.length === 0) { showToast("No KSampler node found in workflow", "error"); return; }
if (samplerNodes.length === 0) { showToast(t("modelsGenUINoNode", "KSampler"), "error"); return; }
const list = [..._schedulerSelected].sort();
if (list.length === 0) { showToast("No schedulers selected", "error"); return; }
if (list.length === 0) { showToast(t("batchNoneSelected", "schedulers"), "error"); return; }
await _runBatchLoop(list, (schedulerName) => {
for (const node of samplerNodes) {
if (comfyUI.currentWorkflow?.[node.id])
@@ -1344,7 +1451,7 @@ async function _runBatchGenerate() {
async function handleGenerate() {
if (!comfyUI.currentWorkflow) {
showToast("No workflow loaded", "error");
showToast(t("noWorkflowLoaded"), "error");
return;
}
if (comfyUI.generating) return;
@@ -1371,7 +1478,7 @@ async function handleGenerate() {
} catch (err) {
const progressText = document.getElementById("wfm-gen-progress-text");
if (progressText) progressText.textContent = "Error";
showToast("Generation error: " + err.message, "error");
showToast(t("generationError", err.message), "error");
}
}
} finally {
@@ -1394,9 +1501,9 @@ export async function initGenerateTab() {
updateStatus(connected);
if (connected) {
await comfyEditor.loadModelLists();
showToast("Connected to ComfyUI", "success");
showToast(t("connectedToComfyUI"), "success");
} else {
showToast("Failed to connect", "error");
showToast(t("failedToConnect"), "error");
}
});
@@ -1406,16 +1513,19 @@ export async function initGenerateTab() {
if (comfyUI.currentAnalysis) {
comfyEditor.renderAll(comfyUI.currentAnalysis, comfyUI.currentWorkflow);
}
showToast("Model lists refreshed", "success");
showToast(t("modelListsRefreshed"), "success");
_rebuildSamplerList();
_rebuildSchedulerList();
_renderBatchPreview();
});
// Save workflow button
document.getElementById("wfm-gen-save-btn")?.addEventListener("click", () => saveCurrentWorkflow());
document.getElementById("wfm-gen-reset-workflow-btn")?.addEventListener("click", async () => {
const filename = document.getElementById("wfm-gen-wf-name")?.dataset?.filename;
if (!filename || !filename.endsWith(".json")) {
showToast("No file-based workflow loaded", "warning");
showToast(t("noFileWorkflowLoaded"), "warning");
return;
}
try {
@@ -1424,7 +1534,7 @@ export async function initGenerateTab() {
const data = await resp.json();
await loadWorkflowIntoEditor(data, filename);
} catch (err) {
showToast("Reset failed: " + err.message, "error");
showToast(t("resetFailed", err.message), "error");
}
});
@@ -1441,7 +1551,7 @@ export async function initGenerateTab() {
_ckptBatch._resumeResolve = null;
}
await comfyUI.interrupt();
showToast("Interrupted", "info");
showToast(t("interrupted"), "info");
});
// Move shared Raw JSON widget into the active tab's rawjson-col
@@ -1504,7 +1614,7 @@ export async function initGenerateTab() {
const wf = JSON.parse(textarea.value);
await loadWorkflowIntoEditor(wf, "Raw JSON");
} catch (err) {
showToast("Invalid JSON: " + err.message, "error");
showToast(t("invalidJsonMsg", err.message), "error");
}
});
@@ -1659,7 +1769,7 @@ export async function initGenerateTab() {
// Auto-load default workflow (doesn't require ComfyUI connection)
if (!comfyUI.currentWorkflow) {
try {
const settings = JSON.parse(localStorage.getItem("wfm_settings") || "{}");
const settings = getSettings();
if (settings.defaultWorkflow && settings.defaultWorkflowData) {
await loadWorkflowIntoEditor(settings.defaultWorkflowData, settings.defaultWorkflow);
console.log("Workflow Studio: Auto-loaded default workflow:", settings.defaultWorkflow);
+591 -41
View File
@@ -3,6 +3,8 @@
* Provides UI text translations and summary prompt templates.
*/
import { getSettings } from "./util.js";
const LANGUAGES = {
en: {
// -- General --
@@ -84,6 +86,9 @@ const LANGUAGES = {
summaryPlaceholder: "Summary...",
openInComfyUI: "Open in ComfyUI",
openedInComfyUI: "Opened in ComfyUI",
sendToCanvas: "Send to Canvas",
copyAndSendCanvas: "Copy & Send Canvas",
workflowSentToCanvas: "Workflow ready — drag 'Workflow Studio Library' title to canvas",
comfyUILoadTimeout: "ComfyUI load timeout",
popupBlocked: "Popup blocked. Please allow popups for this site.",
setAsDefault: "Set as Default",
@@ -135,6 +140,93 @@ const LANGUAGES = {
increment: "Increment",
decrement: "Decrement",
// -- GenerateUI: workflow save --
saveWorkflowTitle: "Save Workflow",
filenameLabel: "Filename",
pleaseEnterFilename: "Please enter a filename",
saveFailed: (msg) => msg ? `Save failed: ${msg}` : "Save failed",
savedAs: (f) => `Saved: ${f}`,
overwriteConfirm: (f) => `"${f}" already exists. Overwrite?`,
uiFormatOverwriteWarn: "The original file is in UI format. Saving will overwrite it in API format, and the node layout will be lost. Continue?",
rawJsonUnappliedInvalid: "Raw JSON has unapplied edits but is not valid JSON. Apply or fix it before saving.",
// -- Toast messages (shared) --
errorWithMsg: (msg) => `Error: ${msg}`,
errorsList: (msgs) => `Errors: ${msgs}`,
copyFailed: "Copy failed",
workflowCopied: "Workflow copied to clipboard!",
memoSaved: "Memo saved",
refreshed: "Refreshed",
deleteFailed: (msg) => msg ? `Delete failed: ${msg}` : "Delete failed",
deletedName: (name) => `Deleted: ${name}`,
renameFailed: "Rename failed",
renamedTo: (name) => `Renamed to "${name}"`,
importErrorMsg: (msg) => `Import error: ${msg}`,
importedViaDrop: (n) => `${n} file(s) imported via drag & drop`,
nameAlreadyExists: (name) => `"${name}" already exists`,
languageChanged: "Language changed. Reloading...",
groupExists: "Group already exists",
groupNameExists: "Group name already exists",
groupCreated: (name) => `Group "${name}" created`,
groupDeleted: (name) => `Group "${name}" deleted`,
addedToGroup: "Added to group",
addedToGroupName: (g) => `Added to "${g}"`,
removedFromGroupName: (g) => `Removed from "${g}"`,
alreadyInGroup: "Already in this group",
selectGroupFirst: "Select a group first",
selectPresetFirst: "Select a preset first",
feederNoNode: "No ImageFeeder node selected",
appliedToWorkflow: "Applied to workflow",
notConnectedToComfyUI: "Not connected to ComfyUI",
wsConnectionFailed: "WebSocket connection failed",
feederRunError: (msg) => `Feeder run error: ${msg}`,
feederStopped: "Feeder stopped",
feederComplete: (n) => `Feeder complete (${n} generated)`,
presetSavedName: (name) => `Preset saved: ${name}`,
presetLoaded: (name) => `Preset loaded: ${name}`,
presetDeleted: (name) => `Preset deleted: ${name}`,
selectParentFolderFirst: "Please select a parent folder first",
folderDeleted: "Folder deleted",
folderCreated: (name) => `Folder "${name}" created`,
noOtherFolders: "No other folders available. Create a subfolder first.",
deletedNImages: (n) => `Deleted ${n} image(s)`,
movedNImages: (n) => `Moved ${n} image(s)`,
addedNImagesToGroup: (n, g) => `Added ${n} image(s) to "${g}"`,
favoritedNImages: (n) => `Favorited ${n} image(s)`,
unfavoritedNImages: (n) => `Unfavorited ${n} image(s)`,
unknownWorkflowFormat: "Unknown workflow format",
generationComplete: "Generation complete",
generationError: (msg) => `Generation error: ${msg}`,
batchNoneSelected: (what) => `No ${what} selected`,
batchItemFailed: (i, total, msg) => `[${i}/${total}] Failed: ${msg}`,
batchStopped: (completed, failed) => `Batch stopped — ${completed} completed, ${failed} failed`,
connectedToComfyUI: "Connected to ComfyUI",
failedToConnect: "Failed to connect",
modelListsRefreshed: "Model lists refreshed",
noFileWorkflowLoaded: "No file-based workflow loaded",
resetFailed: (msg) => `Reset failed: ${msg}`,
interrupted: "Interrupted",
invalidJsonMsg: (msg) => `Invalid JSON: ${msg}`,
workflowLoadedName: (name) => `Workflow loaded: ${name}`,
stackCleared: "Stack cleared",
enterPositiveInt: "Enter a positive integer",
sentToPositive: "Sent to Positive Prompt",
sentToNegative: "Sent to Negative Prompt",
invalidPathFormat: "Invalid path. Use folder/name format, each part: letters, numbers, -, _, . only",
// -- Settings: text size & JSON colors --
textSizeLabel: "Text Size",
textSizeTextarea: "Prompt / Chat Textarea",
textSizeHint: "Applies to: Generate UI prompts, AI Assistant chat, Preset prompts, Wildcard textarea, Metadata prompt preview",
jsonColorsSection: "RAW JSON Colors",
jsonColorBase: "Base text",
jsonColorYellow: "Names / Scheduler",
jsonColorPink: "Titles",
jsonColorGreen: "Width / Height",
jsonColorCyan: "Prompts / Text",
jsonColorRed: "Images / Files",
jsonColorReset: "Reset to defaults",
// -- Prompt tab --
tabPrompt: "Prompt",
you: "You",
@@ -300,7 +392,14 @@ const LANGUAGES = {
modelBulkDeleteConfirm: "Permanently delete {count} model file(s) and their preview images? This cannot be undone.",
modelBulkDeleteDone: "model file(s) deleted",
modelBulkDeleteError: "Failed to delete some models",
modelBulkMoveRoot: "(Root)",
modelBulkMoveBtn: "Move",
modelBulkMoveNewFolder: "New folder name",
modelBulkMoveCreateMove: "Create & Move",
modelBulkMoveDone: "model(s) moved",
modelBulkMoveError: "Failed to move some models",
modelBulkDeselectAll: "Deselect All",
modelBulkSelectAll: "Select All",
modelBulkFavAdd: "★ Favorite",
modelBulkFavRemove: "☆ Unfavorite",
modelBulkFavDone: "models favorited",
@@ -359,8 +458,71 @@ const LANGUAGES = {
galleryOutputDir: "Gallery Output Folder",
galleryOutputDirLabel: "Output Folder Path",
galleryOutputDirHint: "Set the ComfyUI output folder to browse in the Gallery tab. Leave blank to use ComfyUI's default output directory.",
gallerySelectImageFirst: "Please select an image first",
galleryNoEmbeddedWorkflow: "No ComfyUI workflow embedded in this image.",
galleryBulkSelected: "selected",
galleryBulkDeselectAll: "Deselect All",
galleryBulkSelectAll: "Select All",
galleryBulkAddToGroup: "Add to Group...",
galleryBulkAdd: "Add",
galleryBulkFavAll: "★ Favorite All",
galleryBulkUnfavAll: "☆ Unfavorite All",
galleryBulkMoveTo: "Move To...",
galleryBulkDelete: "Delete",
tabAi: "AI TOOL",
tabTagger: "Tagger",
// -- Tagger Tab --
taggerSingleTab: "Single",
taggerBatchTab: "Batch",
taggerDbTab: "DB",
taggerFromGallery: "From Gallery",
taggerUpload: "Upload",
taggerModel: "Model",
taggerThreshold: "Threshold",
taggerCharThreshold: "Char Thr.",
taggerGenerateTags: "Generate Tags",
taggerOllamaEnable: "Ollama VLM",
taggerOllamaUrl: "API URL",
taggerOllamaModel: "Model",
taggerOllamaPrompt: "Prompt",
taggerOllamaMaxTags: "Max Tags",
taggerResult: "Result Tags",
taggerSendToGenUI: "GenUI:P",
taggerSendToPrompt: "Send to Prompt",
taggerSaveToGallery: "Save to Gallery",
taggerWriteToFile: "Write to File",
taggerBatchWriteTxt: "Write .txt",
taggerSaveToDB: "Save to DB",
taggerBatchFolder: "Image Folder",
taggerBatchOutput: "Output Options",
taggerBatchStart: "Start Batch",
taggerBatchStop: "Stop",
taggerDbSearch: "Search",
taggerDbShowAll: "Show All",
taggerDbExport: "Export CSV",
taggerDbFile: "Filename",
taggerDbInterrogator: "WD Tags",
taggerDbVlm: "VLM Tags",
taggerDbDate: "Date",
taggerDbSave: "Save",
taggerDbDelete: "Delete",
taggerDbSaved: "Saved.",
taggerDbDeleted: "Deleted.",
taggerDbEmpty: "No records.",
taggerNoImage: "No image loaded",
taggerNoModel: "-- No model --",
taggerNoTags: "No tags generated",
taggerDone: "Done",
taggerSentToGenUI: "Sent to GenerateUI positive prompt",
taggerNoGenUI: "GenerateUI has no workflow loaded",
taggerSentToPrompt: "Sent to Prompt tab",
taggerSavedToGallery: "Saved to Gallery",
taggerNoGalleryImage: "No image path available",
taggerWrittenToFile: "Written to file",
taggerSavedToDB: "Saved to DB",
taggerSelectGalleryImage: "Select an image in the Gallery tab",
// -- AI Tab --
aiSubTabTranslate: "Translate",
@@ -405,6 +567,9 @@ const LANGUAGES = {
aiToastNoImage: "Please drop an image",
aiToastVlmFailed: "VLM failed: ",
aiModels: "models",
aiStatusChatting: "Thinking...",
aiToastChatFailed: "Chat failed: ",
aiToastWcNoName: "Please enter a wildcard name",
// -- Help & Support --
tabHelp: "Help",
@@ -418,10 +583,10 @@ const LANGUAGES = {
helpWf3: "Create, rename, delete groups and assign/remove workflows",
helpWf4: "Import JSON/PNG files via button or drag & drop",
helpWf5: "Side panel: thumbnail, JSON viewer (format badge: UI/API/App), clipboard copy, group management",
helpWf6: "Detail modal: rename, favorite, thumbnail change, badge assignment, tags, memo, AI summary, open in ComfyUI, load in GenerateUI, set as default, delete",
helpWf6: "Detail modal: rename, favorite, thumbnail change, badge assignment, tags, memo, AI summary, send to canvas, load in GenerateUI, set as default, delete",
helpWf7: "Badge management: add, rename, delete badges with custom colors shared with the Models tab (⚙ Badge button)",
helpGen1: "Connect/disconnect ComfyUI and check connection status",
helpGen2: "Load workflows from Workflow tab (App format .app.json not supported)",
helpGen2: "Load workflows from Workflow tab (App format .app.json not supported); Reset Workflow button re-reads the current workflow file from disk and reloads the editor; Save button (right end of the tab bar) saves the current workflow — including any edits made in the editor — as a new .json file to the Workflow tab; a filename dialog appears with the current workflow name as the default",
helpGen3: "5-tab layout — Input (Prompt + Image), Model, Settings, Feeder, Batch — Input/Model/Settings each include a Raw JSON column for instant preview and direct editing",
helpGen4: "Input tab: Prompt (top) and Image drag-and-drop (bottom) in the left column",
helpGen5: "Model tab: Checkpoint, VAE, LoRA (Single/Stack tabs), ControlNet, UNET, TextEncoder selectors with filter",
@@ -475,7 +640,7 @@ const LANGUAGES = {
helpNodes5: "Side panel: Details (class name, package, category, description, flags), I/O Spec (inputs/outputs with types and defaults), Groups management",
helpNodes6: "Node Sets: create reusable node collections with descriptions, tags, and link definitions between nodes",
helpModels1: "Browse installed models: Checkpoint, LoRA, VAE, ControlNet, UNET, TextEncoder, Hypernetwork, Embedding with sub-tab switching",
helpModels2: "Thumbnail and Table view modes with pagination",
helpModels2: "Thumbnail and Table view modes with pagination; Table view shows Type and Base Model columns sourced from CivitAI data alongside filename, subdirectory, and extension; column headers are clickable to sort — click once for ascending (▲), again for descending (▼), a third time to clear the sort; the E/D column sorts by enable/disable status",
helpModels3: "Search, tag filter, group filter, favorites filter, and status filter (All / Enabled only / Disabled only)",
helpModels4: "Side panel: Info (file path, tags, memo), Groups management, CivitAI integration",
helpModels5: "CivitAI integration: fetch model info by SHA256 hash, batch fetch per model type; preview image is automatically downloaded and saved if none exists",
@@ -485,6 +650,7 @@ const LANGUAGES = {
helpModels9: "User-defined badges: assign free-label badges with custom colors shared with the Workflow tab",
helpModels10: "Enable/Disable models: toggle visibility in ComfyUI by renaming file extension (.disabled suffix). Disable per model (⏸ button on each card) or per group (Enable All / Disable All in Group panel). Changes take effect after ComfyUI refresh.",
helpModels11: "Multi-select & bulk operations: click Select to enter selection mode, check multiple models, then use the bulk action bar to add/remove from groups or permanently delete files (model file + preview images + sidecar files such as .json/.info).",
helpModels12: "After moving or deleting models, ComfyUI may fail to load them because it caches the old file paths. Perform a Hard Reset from the ComfyUI menu (Queue → Hard Reset) or restart ComfyUI to refresh the model cache.",
helpGalleryTitle: "Gallery Tab",
helpGallery1: "Browse images in the ComfyUI output folder — set the folder path in Settings > Gallery Output Folder",
helpGallery2: "3-column layout: folder tree (left) | image grid (center) | detail panel (right)",
@@ -493,10 +659,26 @@ const LANGUAGES = {
helpGallery5: "Folder tree: click to load images, expand with ▶; '+ New' creates a subfolder inside the selected folder, 'Del' deletes it with all contents",
helpGallery6: "Multi-select with Ctrl+click — bulk operations: Add to Group, Favorite All, Unfavorite All, Move To..., Delete",
helpGallery7: "Detail panel — Info tab: filename, size, date, tags (add/remove), memo; 'Move To...' moves the image to another folder, 'Delete' removes it permanently",
helpGallery8: "Detail panel — Metadata tab: displays workflow JSON from PNG embedded data (prompt / workflow keys) or from metadata saved by the Generate UI tab; one-click clipboard copy",
helpGallery8: "Detail panel — JSON tab: displays workflow JSON from PNG embedded data (prompt / workflow keys) or from metadata saved by the Generate UI tab; 'Copy & Send Canvas' button copies to clipboard and stores the workflow for title-drag to canvas",
helpGallery9: "Detail panel — Groups tab: create, assign, remove, rename, and delete groups per image",
helpGallery10: "Workflow auto-save: images generated in the Generate UI tab automatically have their workflow saved to gallery metadata and shown in the Metadata tab",
helpGallery10: "Workflow auto-save: images generated in the Generate UI tab automatically have their workflow saved to gallery metadata and shown in the JSON tab",
helpGallery11: "Supports PNG (tEXt/iTXt), JPEG, WebP, GIF; workflow extraction reads ComfyUI prompt and workflow keys embedded in PNG metadata",
helpGallery12: "Metadata button (green, in the detail panel tab bar): opens the selected image in the Metadata tab for full embedded-data inspection; Alt+click on any image thumbnail has the same effect",
helpGallery13: "Load GenUI button (blue, in the detail panel tab bar): loads the embedded ComfyUI workflow from the selected image directly into the GenerateUI tab and switches to it; shows a warning toast if no workflow is embedded or the format is not supported",
helpGallery14: "Tagger button (purple, in the detail panel action row): opens the selected image directly in the Tagger tab's Single mode for instant tagging",
// -- Tagger Tab --
helpTaggerTitle: "Tagger Tab",
helpTagger1: "Automatic image tagging using WD Tagger (ONNX), SwinV2, DeepDanbooru (.h5), and Ollama VLM — 3 sub-tabs: Single / Batch / DB",
helpTagger2: "Model placement: put each model in its own subfolder under ComfyUI/models/tagger/<model-name>/; the folder must contain a .onnx file + selected_tags.csv (or .h5 + label file for DeepDanbooru)",
helpTagger3: "Single tab: drag & drop an image onto the preview area, or click Upload to pick a file; the Tagger button in the Gallery detail panel opens the selected image directly here",
helpTagger4: "Threshold slider: minimum confidence score for general tags (default 0.35); Character Threshold: separate threshold for character: prefix tags (default 0.85)",
helpTagger5: "Ollama VLM: enable the checkbox to run a vision model alongside WD Tagger; set API URL, select model (click ↻ to refresh), and customize the prompt; results from both models are merged",
helpTagger6: "Result tags can be sent to: (1) GenUI:P — appended to the GenerateUI tab's positive prompt textarea and applied to the loaded workflow immediately; (2) Send to Prompt — appended to the Prompt tab's positive textarea; (3) Save to Gallery — saved to Gallery image metadata (requires image opened from Gallery); (4) Write to File — embedded into JPEG EXIF (ImageDescription) or PNG tEXt (Tags key); (5) Save to DB — stored in the internal SQLite database",
helpTagger7: "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); click Start Batch to process all images in the folder; progress bar and log are updated in real time; Stop cancels after the current image",
helpTagger8: "DB tab: searchable 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 as a CSV file",
helpTagger9: "Install dependencies into ComfyUI's embedded Python: python_embeded\\python.exe -m pip install -r requirements.txt; for GPU ONNX inference install onnxruntime-gpu instead of onnxruntime; TensorFlow (for DeepDanbooru) is commented out by default due to size",
helpSidepanelTitle: "Workflow Studio Library (ComfyUI Side Panel)",
helpSidepanel1: "Open from the Workflow Studio Library button in the ComfyUI toolbar",
helpSidepanel2: "Workflows tab: All / ★ Favorites / Groups sub-tabs; ★ shown for favorites in All view",
@@ -513,13 +695,14 @@ const LANGUAGES = {
helpSidepanel13: "I tab (Information): drop a ComfyUI PNG/WebP/JSON to inspect model, LoRA, and prompt metadata in the side panel — sub-tabs: model / lora / Prompts; supports UnetLoaderGGUF, QuadrupleCLIPLoader, and Lora Loader (LoraManager) node types",
helpSidepanel14: "Information tab — drag items to canvas: model sub-tab places the loader node (Checkpoint → CheckpointLoaderSimple, VAE → VAELoader, Diffusion Model → UNETLoader, Text Encoder → CLIPLoader); double-click also places at canvas center",
helpSidepanel15: "Information tab — LoRA sub-tab: detects LoRAs from LoraLoader, LoraLoaderModelOnly, and Lora Loader (LoraManager) nodes (API format supported); drag individual LoRA to place LoraLoader; \"Multiple LORA\" section places all LoRAs in a single Lora Loader (LoraManager) node with LoRA syntax pre-filled; Prompts sub-tab: drag a prompt to place CLIPTextEncode node with text pre-filled; click prompt to view full text and copy",
helpSidepanel16: "A tab (AI Tools): Translation and VLM sub-tabs powered by Ollama or LM Studio; settings (backend, URL, model) are shared with the SPA AI tab via localStorage",
helpSidepanel16: "A tab (AI Tools): Translation, Chat, TOOLS, and Settings sub-tabs powered by Ollama or LM Studio; Chat supports multi-turn conversations; TOOLS includes VLM image analysis and wildcard generation; settings shared with the SPA AI TOOL tab via localStorage",
helpSidepanel17: "Title drag (Send to Canvas): after clicking 'Send to Canvas' (Workflow tab) or 'Copy & Send Canvas' (Gallery tab), the 'Workflow Studio Library' title turns blue with a green ● — drag it onto the canvas to load the workflow; title resets automatically after loading",
helpAiTitle: "AI Tab (A)",
helpAi1: "Translation sub-tab: translate text between Japanese, English, Chinese, or a custom Free language using Ollama or LM Studio",
helpAi2: "Language selectors for source and destination with ⇄ swap button; text content is also swapped; selections are saved automatically",
helpAi3: "TOOLS pane: drop an image into the drop zone and select a task — Describe Image, Create Prompt, or Create Tags — then click Run to analyze with a vision model",
helpAi4: "VLM result is displayed in the output area with a Copy button",
helpAi5: "Settings sub-tab: choose backend (Ollama / LM Studio), set the API URL, test connection, select model, and configure Free language names for translation",
helpAi1: "4-pane layout — Translation | Chat | TOOLS | Settings — all panes are always visible simultaneously",
helpAi2: "Translation pane: translate between Japanese, English, Chinese, or Free language; ⇄ swap button swaps both language selectors and text content; selections are saved automatically",
helpAi3: "Chat pane: multi-turn conversation with the LLM; Enter to send a message, Shift+Enter for a newline; Clear button resets the conversation history",
helpAi4: "TOOLS pane — VLM: drop an image (PNG/JPG/WebP) and select a task (Describe Image, Create Prompt, Create Tags), click Run; or select \"Create wildcards\", enter a category name and count to generate plain-text entries one per line",
helpAi5: "Settings pane: choose backend (Ollama / LM Studio), set API URL, test connection, select model, configure Free language names for translation",
helpAi6: "Settings are saved to localStorage and shared with the Library panel's A tab",
helpShortcutsTitle: "Keyboard Shortcuts",
helpShortcuts1: "Escape: Close modal/panel",
@@ -532,6 +715,8 @@ const LANGUAGES = {
helpTrouble3: "Workflows not showing: Click refresh button, check if loadable in ComfyUI, try restarting browser/ComfyUI",
helpTrouble4: "Image generation fails: Check if specified models exist in ComfyUI, verify connection, try restarting",
helpTrouble5: "LoRA Stack fails with 'No such file or directory' error: The LoRA may not be recognized by comfyui-lora-manager (known issue). Try a different LoRA or check if the file appears in Lora Manager's own UI",
helpTrouble6: "Model loading error after moving or deleting models: ComfyUI caches file paths and may still reference old locations. Perform a Hard Reset from the ComfyUI menu (Queue → Hard Reset) or restart ComfyUI to clear the cache.",
helpTrouble7: "Tagger tab shows no models: verify the model folder exists at ComfyUI/models/tagger/<model-name>/ and contains a .onnx or .h5 file; if onnxruntime is not installed, run: python_embeded\\python.exe -m pip install onnxruntime",
helpSupportTitle: "Support",
helpSupportDesc: "If you find this plugin useful, please consider supporting its development!",
helpGithubDesc: "Report issues, request features, and contribute",
@@ -755,6 +940,9 @@ const LANGUAGES = {
summaryPlaceholder: "要約...",
openInComfyUI: "ComfyUIで開く",
openedInComfyUI: "ComfyUIで開きました",
sendToCanvas: "キャンバスへ送る",
copyAndSendCanvas: "コピー&キャンバスへ送る",
workflowSentToCanvas: "ワークフロー準備完了 — タイトルをキャンバスへドラッグ",
comfyUILoadTimeout: "ComfyUIの読み込みがタイムアウトしました",
popupBlocked: "ポップアップがブロックされました。このサイトのポップアップを許可してください。",
setAsDefault: "デフォルトに設定",
@@ -806,6 +994,93 @@ const LANGUAGES = {
increment: "増加",
decrement: "減少",
// -- GenerateUI: workflow save --
saveWorkflowTitle: "ワークフローを保存",
filenameLabel: "ファイル名",
pleaseEnterFilename: "ファイル名を入力してください",
saveFailed: (msg) => msg ? `保存に失敗しました: ${msg}` : "保存に失敗しました",
savedAs: (f) => `保存しました: ${f}`,
overwriteConfirm: (f) => `「${f}」は既に存在します。上書きしますか?`,
uiFormatOverwriteWarn: "元のファイルはUI形式です。API形式で上書きするとノード配置などのグラフ情報が失われます。続行しますか?",
rawJsonUnappliedInvalid: "Raw JSONに未適用の編集がありますが、JSONとして不正です。適用または修正してから保存してください。",
// -- Toast messages (shared) --
errorWithMsg: (msg) => `エラー: ${msg}`,
errorsList: (msgs) => `エラー: ${msgs}`,
copyFailed: "コピーに失敗しました",
workflowCopied: "ワークフローをクリップボードにコピーしました",
memoSaved: "メモを保存しました",
refreshed: "更新しました",
deleteFailed: (msg) => msg ? `削除に失敗しました: ${msg}` : "削除に失敗しました",
deletedName: (name) => `削除しました: ${name}`,
renameFailed: "リネームに失敗しました",
renamedTo: (name) => `「${name}」にリネームしました`,
importErrorMsg: (msg) => `インポートエラー: ${msg}`,
importedViaDrop: (n) => `ドラッグ&ドロップで${n}件のファイルをインポートしました`,
nameAlreadyExists: (name) => `「${name}」は既に存在します`,
languageChanged: "言語を変更しました。再読み込みします...",
groupExists: "グループは既に存在します",
groupNameExists: "同名のグループが既に存在します",
groupCreated: (name) => `グループ「${name}」を作成しました`,
groupDeleted: (name) => `グループ「${name}」を削除しました`,
addedToGroup: "グループに追加しました",
addedToGroupName: (g) => `「${g}」に追加しました`,
removedFromGroupName: (g) => `「${g}」から削除しました`,
alreadyInGroup: "既にこのグループに含まれています",
selectGroupFirst: "先にグループを選択してください",
selectPresetFirst: "先にプリセットを選択してください",
feederNoNode: "ImageFeederノードが選択されていません",
appliedToWorkflow: "ワークフローに適用しました",
notConnectedToComfyUI: "ComfyUIに接続されていません",
wsConnectionFailed: "WebSocket接続に失敗しました",
feederRunError: (msg) => `Feeder実行エラー: ${msg}`,
feederStopped: "Feederを停止しました",
feederComplete: (n) => `Feeder完了(${n}枚生成)`,
presetSavedName: (name) => `プリセットを保存しました: ${name}`,
presetLoaded: (name) => `プリセットを読み込みました: ${name}`,
presetDeleted: (name) => `プリセットを削除しました: ${name}`,
selectParentFolderFirst: "先に親フォルダを選択してください",
folderDeleted: "フォルダを削除しました",
folderCreated: (name) => `フォルダ「${name}」を作成しました`,
noOtherFolders: "移動先フォルダがありません。先にサブフォルダを作成してください。",
deletedNImages: (n) => `${n}件の画像を削除しました`,
movedNImages: (n) => `${n}件の画像を移動しました`,
addedNImagesToGroup: (n, g) => `${n}件の画像を「${g}」に追加しました`,
favoritedNImages: (n) => `${n}件をお気に入りに追加しました`,
unfavoritedNImages: (n) => `${n}件をお気に入りから外しました`,
unknownWorkflowFormat: "不明なワークフロー形式です",
generationComplete: "生成が完了しました",
generationError: (msg) => `生成エラー: ${msg}`,
batchNoneSelected: (what) => `${what}が選択されていません`,
batchItemFailed: (i, total, msg) => `[${i}/${total}] 失敗: ${msg}`,
batchStopped: (completed, failed) => `バッチ停止 — 完了${completed}件、失敗${failed}件`,
connectedToComfyUI: "ComfyUIに接続しました",
failedToConnect: "接続に失敗しました",
modelListsRefreshed: "モデルリストを更新しました",
noFileWorkflowLoaded: "ファイルベースのワークフローが読み込まれていません",
resetFailed: (msg) => `リセットに失敗しました: ${msg}`,
interrupted: "中断しました",
invalidJsonMsg: (msg) => `不正なJSON: ${msg}`,
workflowLoadedName: (name) => `ワークフローを読み込みました: ${name}`,
stackCleared: "スタックをクリアしました",
enterPositiveInt: "正の整数を入力してください",
sentToPositive: "ポジティブプロンプトに送信しました",
sentToNegative: "ネガティブプロンプトに送信しました",
invalidPathFormat: "不正なパスです。folder/name形式で、各部分は英数字・-・_・.のみ使用できます",
// -- Settings: text size & JSON colors --
textSizeLabel: "文字サイズ",
textSizeTextarea: "プロンプト / チャット入力欄",
textSizeHint: "適用対象: 生成UIプロンプト、AIアシスタントチャット、プリセットプロンプト、ワイルドカード編集、Metadataプロンプトプレビュー",
jsonColorsSection: "RAW JSON 文字色",
jsonColorBase: "通常テキスト",
jsonColorYellow: "名前 / スケジューラ",
jsonColorPink: "タイトル",
jsonColorGreen: "Width / Height",
jsonColorCyan: "プロンプト / テキスト",
jsonColorRed: "画像 / ファイル",
jsonColorReset: "デフォルトに戻す",
// -- Prompt tab --
tabPrompt: "プロンプト",
you: "あなた",
@@ -971,7 +1246,14 @@ const LANGUAGES = {
modelBulkDeleteConfirm: "{count}件のモデルファイルとプレビュー画像を完全に削除しますか?この操作は取り消せません。",
modelBulkDeleteDone: "件のモデルファイルを削除しました",
modelBulkDeleteError: "一部のモデルの削除に失敗しました",
modelBulkMoveRoot: "(ルート)",
modelBulkMoveBtn: "移動",
modelBulkMoveNewFolder: "新規フォルダ名",
modelBulkMoveCreateMove: "作成して移動",
modelBulkMoveDone: "件のモデルを移動しました",
modelBulkMoveError: "一部のモデルの移動に失敗しました",
modelBulkDeselectAll: "選択解除",
modelBulkSelectAll: "全選択",
modelBulkFavAdd: "★ お気に入り追加",
modelBulkFavRemove: "☆ お気に入り解除",
modelBulkFavDone: "件をお気に入りに追加しました",
@@ -1030,8 +1312,71 @@ const LANGUAGES = {
galleryOutputDir: "ギャラリー Outputフォルダ",
galleryOutputDirLabel: "Outputフォルダのパス",
galleryOutputDirHint: "ギャラリータブで参照するComfyUIのoutputフォルダを設定します。空欄の場合はComfyUIのデフォルトoutputディレクトリを使用します。",
gallerySelectImageFirst: "先に画像を選択してください",
galleryNoEmbeddedWorkflow: "この画像にはComfyUIワークフローが埋め込まれていません。",
galleryBulkSelected: "件選択中",
galleryBulkDeselectAll: "選択解除",
galleryBulkSelectAll: "全選択",
galleryBulkAddToGroup: "グループに追加...",
galleryBulkAdd: "追加",
galleryBulkFavAll: "★ お気に入り追加(全件)",
galleryBulkUnfavAll: "☆ お気に入り解除(全件)",
galleryBulkMoveTo: "移動先...",
galleryBulkDelete: "削除",
tabAi: "AI TOOL",
tabTagger: "Tagger",
// -- Tagger Tab --
taggerSingleTab: "シングル",
taggerBatchTab: "バッチ",
taggerDbTab: "DB",
taggerFromGallery: "Galleryから",
taggerUpload: "アップロード",
taggerModel: "モデル",
taggerThreshold: "閾値",
taggerCharThreshold: "キャラ閾値",
taggerGenerateTags: "タグ生成",
taggerOllamaEnable: "Ollama VLM",
taggerOllamaUrl: "API URL",
taggerOllamaModel: "モデル",
taggerOllamaPrompt: "プロンプト",
taggerOllamaMaxTags: "最大タグ数",
taggerResult: "生成タグ",
taggerSendToGenUI: "GenUI:P",
taggerSendToPrompt: "プロンプトに送信",
taggerSaveToGallery: "Galleryに保存",
taggerWriteToFile: "ファイルに書込",
taggerBatchWriteTxt: ".txt出力",
taggerSaveToDB: "DBに保存",
taggerBatchFolder: "画像フォルダ",
taggerBatchOutput: "出力オプション",
taggerBatchStart: "バッチ開始",
taggerBatchStop: "停止",
taggerDbSearch: "検索",
taggerDbShowAll: "全表示",
taggerDbExport: "CSV出力",
taggerDbFile: "ファイル名",
taggerDbInterrogator: "WDタグ",
taggerDbVlm: "VLMタグ",
taggerDbDate: "日付",
taggerDbSave: "保存",
taggerDbDelete: "削除",
taggerDbSaved: "保存しました",
taggerDbDeleted: "削除しました",
taggerDbEmpty: "レコードなし",
taggerNoImage: "画像が読み込まれていません",
taggerNoModel: "-- モデルなし --",
taggerNoTags: "タグが生成されていません",
taggerDone: "完了",
taggerSentToGenUI: "生成UIのポジティブプロンプトに送信しました",
taggerNoGenUI: "生成UIにワークフローが読み込まれていません",
taggerSentToPrompt: "プロンプトタブに送信しました",
taggerSavedToGallery: "Galleryに保存しました",
taggerNoGalleryImage: "画像パスがありません",
taggerWrittenToFile: "ファイルに書き込みました",
taggerSavedToDB: "DBに保存しました",
taggerSelectGalleryImage: "Galleryタブで画像を選択してください",
// -- AI Tab --
aiSubTabTranslate: "翻訳",
@@ -1076,6 +1421,9 @@ const LANGUAGES = {
aiToastNoImage: "画像をドロップしてください",
aiToastVlmFailed: "VLM実行失敗: ",
aiModels: "モデル",
aiStatusChatting: "考え中...",
aiToastChatFailed: "チャット失敗: ",
aiToastWcNoName: "ワイルドカード名を入力してください",
// -- Help & Support --
tabHelp: "ヘルプ",
@@ -1089,10 +1437,10 @@ const LANGUAGES = {
helpWf3: "グループの作成・名前変更・削除、ワークフローの割り当て・解除",
helpWf4: "JSON/PNGファイルのインポート(ボタンまたはドラッグ&ドロップ)",
helpWf5: "サイドパネル:サムネイル、JSONビューア(フォーマットバッジ:UI/API/App形式)、クリップボードコピー、グループ管理",
helpWf6: "詳細モーダル:名前変更、お気に入り、サムネイル変更、バッジ付与、タグ、メモ、AI要約、ComfyUIで開く、生成UIに読み込み、デフォルト設定、削除",
helpWf6: "詳細モーダル:名前変更、お気に入り、サムネイル変更、バッジ付与、タグ、メモ、AI要約、キャンバスへ送る、生成UIに読み込み、デフォルト設定、削除",
helpWf7: "バッジ管理:バッジの追加・名前変更・削除、カスタム色設定(Modelsタブと共有)— ⚙ Badgeボタン",
helpGen1: "ComfyUIの接続・切断、接続状態の確認",
helpGen2: "Workflowタブからワークフローを読み込み(App形式 .app.json は非対応)",
helpGen2: "Workflowタブからワークフローを読み込み(App形式 .app.json は非対応)。Reset Workflowボタンは現在のワークフローファイルをディスクから再読込してエディタをリロード。Saveボタン(タブバー右端)はエディタでの編集を含む現在のワークフローを新しい.jsonファイルとしてWorkflowタブに保存(現在のワークフロー名を初期値としたファイル名ダイアログを表示)",
helpGen3: "5タブ構成 — Input(プロンプト+画像)、Model、Settings、Feeder、Batch — Input/Model/SettingsタブにはRaw JSON列を常時表示",
helpGen4: "Inputタブ:左列にPrompt(上段)+ Image ドラッグ&ドロップ(下段)",
helpGen5: "Modelタブ:Checkpoint/VAE/LoRA(Single/Stackタブ)/ControlNet/UNET/TextEncoderのセレクタ(フィルタ検索付き)",
@@ -1146,7 +1494,7 @@ const LANGUAGES = {
helpNodes5: "サイドパネル:詳細(クラス名、パッケージ、カテゴリ、説明、フラグ)、I/O仕様(入出力の型・デフォルト値)、グループ管理",
helpNodes6: "ノードセット:再利用可能なノードコレクションの作成(説明、タグ、ノード間リンク定義付き)",
helpModels1: "インストール済みモデルの閲覧:Checkpoint、LoRA、VAE、ControlNet、UNET、TextEncoder、Hypernetwork、Embeddingをサブタブで切り替え",
helpModels2: "サムネイル / テーブル表示モード切り替え(ページネーション付き)",
helpModels2: "サムネイル / テーブル表示モード切り替え(ページネーション付き)。テーブル表示ではファイル名・サブフォルダ・拡張子に加えCivitAI由来のType / Base Model列を表示。列ヘッダーをクリックでソート — 1回で昇順(▲)、2回で降順(▼)、3回でソート解除。E/D列は有効/無効状態でソート",
helpModels3: "検索、タグフィルタ、グループフィルタ、お気に入りフィルタ、ステータスフィルタ(すべて / 有効のみ / 無効のみ)",
helpModels4: "サイドパネル:基本情報(ファイルパス、タグ、メモ)、グループ管理、CivitAI連携",
helpModels5: "CivitAI連携:SHA256ハッシュでモデル情報取得、モデルタイプごとの一括取得;プレビュー画像がない場合は自動でダウンロード・保存",
@@ -1156,6 +1504,7 @@ const LANGUAGES = {
helpModels9: "ユーザー定義バッジ:自由ラベルのバッジをモデルに付与(Workflowタブと色パレットを共有)",
helpModels10: "モデルの有効/無効切り替え:拡張子リネーム(.disabledサフィックス)でComfyUIへの表示を制御。各カードの⏸ボタンで単体操作、グループパネルの「全て有効化 / 全て無効化」でグループ一括操作。変更はComfyUIリフレッシュ後に反映。",
helpModels11: "複数選択と一括操作:「選択」ボタンで選択モードに入り複数モデルにチェックを入れると、一括操作バーからグループへの追加/削除、またはファイルの完全削除(モデルファイル+プレビュー画像+.json/.infoなどのサイドカーファイル)が行えます。",
helpModels12: "モデルの移動・削除後はComfyUIが古いパスをキャッシュしているためモデル読み込みエラーが発生することがあります。ComfyUIメニューのHard Reset(Queue → Hard Reset)またはComfyUIを再起動してモデルキャッシュを更新してください。",
helpGalleryTitle: "Galleryタブ",
helpGallery1: "ComfyUIの出力フォルダ内画像を閲覧 — Settings > Gallery Output Folder でフォルダパスを設定可能",
helpGallery2: "3カラムレイアウト: フォルダツリー (左) | 画像グリッド (中央) | 詳細パネル (右)",
@@ -1164,10 +1513,26 @@ const LANGUAGES = {
helpGallery5: "フォルダツリー:クリックで画像を読み込み;▶で展開;「+ New」で選択フォルダ内にサブフォルダを作成;「Del」でそのフォルダとすべての内容を削除",
helpGallery6: "Ctrl+クリックで複数選択 — 一括操作:グループへ追加、一括お気に入り、一括お気に入り解除、移動(Move To...)、削除",
helpGallery7: "詳細パネル — Infoタブ:ファイル名、サイズ、日付、タグ(追加/削除)、メモ;「Move To...」で他フォルダへ移動;「Delete」で完全削除",
helpGallery8: "詳細パネル — Metadataタブ:PNGの埋め込みデータ(prompt / workflow キー)またはGenerateUIタブで保存したメタデータからワークフローJSONを表示;ワンクリックでクリップボードコピー",
helpGallery8: "詳細パネル — JSONタブ:PNGの埋め込みデータ(prompt / workflow キー)またはGenerateUIタブで保存したメタデータからワークフローJSONを表示;「Copy & Send Canvas」ボタンでクリップボードへのコピーとキャンバスへのタイトルドラッグ用保存を同時に行う",
helpGallery9: "詳細パネル — Groupsタブ:画像ごとのグループ作成、割り当て、解除、名前変更、削除",
helpGallery10: "ワークフロー自動保存:GenerateUIタブで生成した画像はワークフローが自動でギャラリーメタデータに保存され、Metadataタブで確認可能",
helpGallery10: "ワークフロー自動保存:GenerateUIタブで生成した画像はワークフローが自動でギャラリーメタデータに保存され、JSONタブで確認可能",
helpGallery11: "PNG (tEXt/iTXt)、JPEG、WebP、GIF対応;PNG形式はComfyUIの埋め込みJSON(prompt / workflow キー)を読み込んでワークフロー抽出が可能",
helpGallery12: "Metadataボタン(緑、詳細パネルのタブバー内):選択画像をMetadataタブで開いて埋め込みデータを詳細確認。画像サムネイルのAlt+クリックでも同じ操作が可能",
helpGallery13: "Load GenUIボタン(青、詳細パネルのタブバー内):選択画像に埋め込まれたComfyUIワークフローをGenerateUIタブへ直接読み込んで切り替え。ワークフローが埋め込まれていない場合や非対応形式の場合は警告トーストを表示",
helpGallery14: "Taggerボタン(紫、詳細パネルのアクション行):選択画像をTaggerタブのSingleモードで直接開き、即座にタグ付けを開始できる",
// -- Tagger Tab --
helpTaggerTitle: "Taggerタブ",
helpTagger1: "WD Tagger(ONNX)・SwinV2・DeepDanbooru(.h5)・Ollama VLMによる自動タグ付け — サブタブ: Single / Batch / DB",
helpTagger2: "モデル配置:ComfyUI/models/tagger/<モデル名>/ 以下に各モデルのフォルダを作成し、.onnx + selected_tags.csv(DeepDanbooruは .h5 + ラベルファイル)を格納",
helpTagger3: "Singleタブ:プレビューエリアへ画像をドラッグ&ドロップ、またはUploadボタンでファイルを選択;GalleryタブのTaggerボタンで選択画像を直接開くことも可能",
helpTagger4: "閾値スライダー:一般タグの信頼スコア下限(デフォルト0.35);キャラ閾値:character: プレフィックス付きタグ専用の閾値(デフォルト0.85)",
helpTagger5: "Ollama VLM:チェックボックスをオンにするとWD Taggerと並行してビジョンモデルを実行;API URLとモデルを設定(↻で一覧更新)、プロンプトを編集可能;両モデルの結果はマージされる",
helpTagger6: "生成タグの送信先:(1) GenUI:P — 生成UIタブのポジティブプロンプトに追記し、読み込み中のワークフローへ即時適用;(2) プロンプトに送信 — Promptタブの正プロンプトテキストエリアに追記;(3) Galleryに保存 — ギャラリーの画像メタデータに保存(Galleryから開いた画像のみ有効);(4) ファイルに書込 — JPEGはEXIF(ImageDescription)、PNGはtEXt(Tagsキー)に書き込み;(5) DBに保存 — 内蔵SQLiteデータベースに保存",
helpTagger7: "Batchタブ:処理対象フォルダパスを入力してWD Tagger・Ollamaの設定を行い、出力オプション(DBに保存〈デフォルトON〉・ファイルに書込〈EXIF/PNGメタデータ〉・.txt出力〈画像と同フォルダに <ファイル名>.txt を生成〉)を選択;バッチ開始で指定フォルダ内の全画像を処理;進行状況バーとログがリアルタイム更新;停止ボタンは現在の画像処理完了後にキャンセル",
helpTagger8: "DBタブ:タグ付けした画像の検索可能データベース;行をクリックすると編集パネルでWDタグ・VLMタグを編集可能;保存で更新、削除でレコード削除;CSV出力で全レコードをダウンロード",
helpTagger9: "依存パッケージのインストール:python_embeded\\python.exe -m pip install -r requirements.txt;GPU推論にはonnxruntimeの代わりにonnxruntime-gpuをインストール;TensorFlow(DeepDanbooru用)はサイズ大のためデフォルトではコメントアウト",
helpSidepanelTitle: "Workflow Studio Library(ComfyUIサイドパネル)",
helpSidepanel1: "ComfyUIツールバーのWorkflow Studio Libraryボタンから開く",
helpSidepanel2: "Workflowsタブ:All / ★ Favorites / Groupsサブタブ、Allビューでお気に入りに★表示",
@@ -1184,13 +1549,14 @@ const LANGUAGES = {
helpSidepanel13: "I タブ(Information):ComfyUI の PNG / WebP / JSON をドロップするとサイドパネル内でモデル・LoRA・プロンプトのメタデータを確認可能 — サブタブ: model / lora / Prompts;UnetLoaderGGUF・QuadrupleCLIPLoader・Lora Loader (LoraManager) ノードタイプに対応",
helpSidepanel14: "Information タブ — キャンバスへドラッグ:model サブタブのアイテムをドラッグすると対応ローダーノードを配置(Checkpoint → CheckpointLoaderSimple、VAE → VAELoader、Diffusion Model → UNETLoader、Text Encoder → CLIPLoader);ダブルクリックでもキャンバス中央に配置可能",
helpSidepanel15: "Information タブ — lora サブタブ:LoraLoader・LoraLoaderModelOnly・Lora Loader (LoraManager) ノード(APIフォーマット含む)から LoRA を検出;個別 LoRA をドラッグで LoraLoader を配置;「Multiple LORA」セクションで全 LoRA を Lora Loader (LoraManager) ノードに一括配置(LoRA構文自動入力);Prompts サブタブ:プロンプトをドラッグするとテキスト入力済みの CLIPTextEncode ノードを配置;クリックで全文表示・コピー可能",
helpSidepanel16: "A タブ(AI ツール):翻訳・VLM サブタブ;設定(バックエンド・URL・モデル)は SPA の AI タブと localStorage で共有される",
helpSidepanel16: "A タブ(AI ツール):翻訳・Chat・TOOLS・設定のサブタブ;Chat は LLM とのマルチターン会話;TOOLS は VLM 画像解析とワイルドカード生成に対応;設定は SPA の AI タブと localStorage で共有される",
helpSidepanel17: "タイトルドラッグ(Send to Canvas):WorkflowタブのSend to CanvasまたはGalleryタブのCopy & Send Canvasクリック後、タイトルが青くハイライトし緑の●が表示される — タイトルをキャンバスへドラッグするとワークフローが読み込まれ、タイトルは自動リセットされる",
helpAiTitle: "AI タブ(A)",
helpAi1: "翻訳サブタブ:Ollama または LM Studio を使って日本語・英語・中国語・カスタム言語(Free)間でテキストを翻訳",
helpAi2: "入力言語・出力言語セレクターと ⇄ 入替ボタン付き;テキスト内容も同時に入替;選択は自動保存",
helpAi3: "TOOLS ペイン:画像をドロップゾーンにドロップしてタスクを選択(画像の解説 / プロンプト作成 / タグ作成)し、実行ボタンでビジョンモデルに解析させる",
helpAi4: "VLM の結果は出力エリアに表示され、コピーボタンでクリップボードに取得可能",
helpAi5: "設定サブタブ:バックエンド(Ollama / LM Studio)・API URL・接続テスト・モデル選択・翻訳の Free 言語名を設定",
helpAi1: "4ペインレイアウト — Translation | Chat | TOOLS | Settings — 全ペインが常時表示される",
helpAi2: "翻訳ペイン:Ollama または LM Studio を使って日本語・英語・中国語・カスタム言語(Free)間でテキストを翻訳;⇄ ボタンで言語とテキストを同時入替;選択は自動保存",
helpAi3: "Chat ペイン:LLM とのマルチターン会話;Enter で送信、Shift+Enter で改行;Clear ボタンで会話履歴をリセット",
helpAi4: "TOOLS ペイン — VLM:画像(PNG/JPG/WebP)をドロップしてタスク(画像解説 / プロンプト作成 / タグ作成)を選んで Run;または「Create wildcards」を選んでカテゴリ名と件数を入力すると1行1エントリのワイルドカードを生成",
helpAi5: "設定ペイン:バックエンド(Ollama / LM Studio)・API URL・接続テスト・モデル選択・Free 言語名を設定",
helpAi6: "設定は localStorage に保存され、Library パネルの A タブと共有される",
helpShortcutsTitle: "キーボード操作",
helpShortcuts1: "Escape:モーダル・パネルを閉じる",
@@ -1203,6 +1569,8 @@ const LANGUAGES = {
helpTrouble3: "ワークフローが表示されない:更新ボタン押下、ComfyUIで読み込めるか確認、ブラウザ・ComfyUI再起動",
helpTrouble4: "画像生成が失敗する:指定モデルの存在確認、ComfyUI接続確認、再起動",
helpTrouble5: "LoRAスタック実行時に「No such file or directory」エラー:comfyui-lora-managerが該当LoRAを認識していない可能性があります(既知の問題)。別のLoRAを試すか、Lora Manager自体のUIで該当ファイルが表示されるか確認してください",
helpTrouble6: "モデルの移動・削除後にモデル読み込みエラーが発生する:ComfyUIがファイルパスをキャッシュしており、古い場所を参照することがあります。ComfyUIメニューのHard Reset(Queue → Hard Reset)またはComfyUIを再起動してキャッシュをクリアしてください。",
helpTrouble7: "Taggerタブにモデルが表示されない:ComfyUI/models/tagger/<モデル名>/ フォルダの存在と .onnx または .h5 ファイルの有無を確認;onnxruntimeが未インストールの場合は python_embeded\\python.exe -m pip install onnxruntime を実行",
helpSupportTitle: "サポート",
helpSupportDesc: "このプラグインが役に立ったら、開発を支援していただけると嬉しいです!",
helpGithubDesc: "バグ報告、機能リクエスト、コントリビュート",
@@ -1426,6 +1794,9 @@ const LANGUAGES = {
summaryPlaceholder: "摘要...",
openInComfyUI: "在ComfyUI中打开",
openedInComfyUI: "已在ComfyUI中打开",
sendToCanvas: "发送到画布",
copyAndSendCanvas: "复制并发送到画布",
workflowSentToCanvas: "工作流已就绪 — 将标题拖拽到画布",
comfyUILoadTimeout: "ComfyUI加载超时",
popupBlocked: "弹窗被阻止。请允许此站点的弹窗。",
setAsDefault: "设为默认",
@@ -1477,6 +1848,93 @@ const LANGUAGES = {
increment: "递增",
decrement: "递减",
// -- GenerateUI: workflow save --
saveWorkflowTitle: "保存工作流",
filenameLabel: "文件名",
pleaseEnterFilename: "请输入文件名",
saveFailed: (msg) => msg ? `保存失败: ${msg}` : "保存失败",
savedAs: (f) => `已保存: ${f}`,
overwriteConfirm: (f) => `「${f}」已存在。要覆盖吗?`,
uiFormatOverwriteWarn: "原文件为UI格式。保存将以API格式覆盖,节点布局等信息将丢失。要继续吗?",
rawJsonUnappliedInvalid: "Raw JSON有未应用的编辑,但不是有效的JSON。请先应用或修正后再保存。",
// -- Toast messages (shared) --
errorWithMsg: (msg) => `错误: ${msg}`,
errorsList: (msgs) => `错误: ${msgs}`,
copyFailed: "复制失败",
workflowCopied: "工作流已复制到剪贴板",
memoSaved: "备注已保存",
refreshed: "已刷新",
deleteFailed: (msg) => msg ? `删除失败: ${msg}` : "删除失败",
deletedName: (name) => `已删除: ${name}`,
renameFailed: "重命名失败",
renamedTo: (name) => `已重命名为「${name}」`,
importErrorMsg: (msg) => `导入错误: ${msg}`,
importedViaDrop: (n) => `已通过拖放导入${n}个文件`,
nameAlreadyExists: (name) => `「${name}」已存在`,
languageChanged: "语言已更改。正在重新加载...",
groupExists: "分组已存在",
groupNameExists: "同名分组已存在",
groupCreated: (name) => `已创建分组「${name}」`,
groupDeleted: (name) => `已删除分组「${name}」`,
addedToGroup: "已添加到分组",
addedToGroupName: (g) => `已添加到「${g}」`,
removedFromGroupName: (g) => `已从「${g}」中移除`,
alreadyInGroup: "已在此分组中",
selectGroupFirst: "请先选择分组",
selectPresetFirst: "请先选择预设",
feederNoNode: "未选择ImageFeeder节点",
appliedToWorkflow: "已应用到工作流",
notConnectedToComfyUI: "未连接到ComfyUI",
wsConnectionFailed: "WebSocket连接失败",
feederRunError: (msg) => `Feeder运行错误: ${msg}`,
feederStopped: "Feeder已停止",
feederComplete: (n) => `Feeder完成(已生成${n}张)`,
presetSavedName: (name) => `预设已保存: ${name}`,
presetLoaded: (name) => `预设已加载: ${name}`,
presetDeleted: (name) => `预设已删除: ${name}`,
selectParentFolderFirst: "请先选择父文件夹",
folderDeleted: "文件夹已删除",
folderCreated: (name) => `已创建文件夹「${name}」`,
noOtherFolders: "没有其他可用文件夹。请先创建子文件夹。",
deletedNImages: (n) => `已删除${n}张图像`,
movedNImages: (n) => `已移动${n}张图像`,
addedNImagesToGroup: (n, g) => `已将${n}张图像添加到「${g}」`,
favoritedNImages: (n) => `已收藏${n}张图像`,
unfavoritedNImages: (n) => `已取消收藏${n}张图像`,
unknownWorkflowFormat: "未知的工作流格式",
generationComplete: "生成完成",
generationError: (msg) => `生成错误: ${msg}`,
batchNoneSelected: (what) => `未选择${what}`,
batchItemFailed: (i, total, msg) => `[${i}/${total}] 失败: ${msg}`,
batchStopped: (completed, failed) => `批处理已停止 — 完成${completed}个,失败${failed}个`,
connectedToComfyUI: "已连接到ComfyUI",
failedToConnect: "连接失败",
modelListsRefreshed: "模型列表已刷新",
noFileWorkflowLoaded: "未加载基于文件的工作流",
resetFailed: (msg) => `重置失败: ${msg}`,
interrupted: "已中断",
invalidJsonMsg: (msg) => `无效的JSON: ${msg}`,
workflowLoadedName: (name) => `工作流已加载: ${name}`,
stackCleared: "堆栈已清空",
enterPositiveInt: "请输入正整数",
sentToPositive: "已发送到正向提示词",
sentToNegative: "已发送到负向提示词",
invalidPathFormat: "路径无效。请使用 folder/name 格式,各部分仅限字母、数字、-、_、.",
// -- Settings: text size & JSON colors --
textSizeLabel: "文字大小",
textSizeTextarea: "提示词 / 聊天输入框",
textSizeHint: "适用于:生成UI提示词、AI助手聊天、预设提示词、通配符编辑、Metadata提示词预览",
jsonColorsSection: "RAW JSON 文字颜色",
jsonColorBase: "普通文本",
jsonColorYellow: "名称 / 调度器",
jsonColorPink: "标题",
jsonColorGreen: "Width / Height",
jsonColorCyan: "提示词 / 文本",
jsonColorRed: "图像 / 文件",
jsonColorReset: "恢复默认",
// -- Prompt tab --
tabPrompt: "提示词",
you: "你",
@@ -1489,6 +1947,10 @@ const LANGUAGES = {
enterPresetName: "请输入预设名称",
noPromptToSave: "没有可保存的提示词",
presetSaved: "预设已保存",
copyPositivePrompt: "PP 复制",
copyNegativePrompt: "NP 复制",
copiedToClipboard: "已复制到剪贴板",
noTextToCopy: "没有可复制的文本",
attachImage: "附加图片",
clearChat: "清空聊天",
send: "发送",
@@ -1638,7 +2100,14 @@ const LANGUAGES = {
modelBulkDeleteConfirm: "永久删除 {count} 个模型文件及其预览图?此操作无法撤销。",
modelBulkDeleteDone: "个模型文件已删除",
modelBulkDeleteError: "部分模型删除失败",
modelBulkMoveRoot: "(根目录)",
modelBulkMoveBtn: "移动",
modelBulkMoveNewFolder: "新建文件夹名",
modelBulkMoveCreateMove: "创建并移动",
modelBulkMoveDone: "个模型已移动",
modelBulkMoveError: "部分模型移动失败",
modelBulkDeselectAll: "取消全选",
modelBulkSelectAll: "全选",
modelBulkFavAdd: "★ 收藏",
modelBulkFavRemove: "☆ 取消收藏",
modelBulkFavDone: "个模型已收藏",
@@ -1697,8 +2166,71 @@ const LANGUAGES = {
galleryOutputDir: "图库输出文件夹",
galleryOutputDirLabel: "输出文件夹路径",
galleryOutputDirHint: "设置图库标签页浏览的ComfyUI输出文件夹。留空则使用ComfyUI默认输出目录。",
gallerySelectImageFirst: "请先选择图像",
galleryNoEmbeddedWorkflow: "此图像中未嵌入ComfyUI工作流。",
galleryBulkSelected: "项已选择",
galleryBulkDeselectAll: "取消全选",
galleryBulkSelectAll: "全选",
galleryBulkAddToGroup: "添加到分组...",
galleryBulkAdd: "添加",
galleryBulkFavAll: "★ 全部收藏",
galleryBulkUnfavAll: "☆ 全部取消收藏",
galleryBulkMoveTo: "移动到...",
galleryBulkDelete: "删除",
tabAi: "AI TOOL",
tabTagger: "Tagger",
// -- Tagger Tab --
taggerSingleTab: "单张",
taggerBatchTab: "批量",
taggerDbTab: "DB",
taggerFromGallery: "从图库",
taggerUpload: "上传",
taggerModel: "模型",
taggerThreshold: "阈值",
taggerCharThreshold: "角色阈值",
taggerGenerateTags: "生成标签",
taggerOllamaEnable: "Ollama VLM",
taggerOllamaUrl: "API URL",
taggerOllamaModel: "模型",
taggerOllamaPrompt: "提示词",
taggerOllamaMaxTags: "最大标签数",
taggerResult: "生成标签",
taggerSendToGenUI: "GenUI:P",
taggerSendToPrompt: "发送到提示词",
taggerSaveToGallery: "保存到图库",
taggerWriteToFile: "写入文件",
taggerBatchWriteTxt: "输出.txt",
taggerSaveToDB: "保存到DB",
taggerBatchFolder: "图像文件夹",
taggerBatchOutput: "输出选项",
taggerBatchStart: "开始批处理",
taggerBatchStop: "停止",
taggerDbSearch: "搜索",
taggerDbShowAll: "显示全部",
taggerDbExport: "导出CSV",
taggerDbFile: "文件名",
taggerDbInterrogator: "WD标签",
taggerDbVlm: "VLM标签",
taggerDbDate: "日期",
taggerDbSave: "保存",
taggerDbDelete: "删除",
taggerDbSaved: "已保存",
taggerDbDeleted: "已删除",
taggerDbEmpty: "无记录",
taggerNoImage: "未加载图像",
taggerNoModel: "-- 无模型 --",
taggerNoTags: "未生成标签",
taggerDone: "完成",
taggerSentToGenUI: "已发送到生成UI正向提示词",
taggerNoGenUI: "生成UI未加载工作流",
taggerSentToPrompt: "已发送到提示词标签",
taggerSavedToGallery: "已保存到图库",
taggerNoGalleryImage: "无图像路径",
taggerWrittenToFile: "已写入文件",
taggerSavedToDB: "已保存到DB",
taggerSelectGalleryImage: "请在图库标签中选择图像",
// -- AI Tab --
aiSubTabTranslate: "翻译",
@@ -1743,6 +2275,9 @@ const LANGUAGES = {
aiToastNoImage: "请拖放图像",
aiToastVlmFailed: "VLM执行失败:",
aiModels: "个模型",
aiStatusChatting: "思考中...",
aiToastChatFailed: "聊天失败:",
aiToastWcNoName: "请输入通配符名称",
// -- Help & Support --
tabHelp: "帮助",
@@ -1756,10 +2291,10 @@ const LANGUAGES = {
helpWf3: "创建、重命名、删除分组,分配/移除工作流",
helpWf4: "通过按钮或拖放导入JSON/PNG文件",
helpWf5: "侧面板:缩略图、JSON查看器(格式徽章:UI/API/App)、剪贴板复制、分组管理",
helpWf6: "详情弹窗:重命名、收藏、缩略图更换、徽章分配、标签、备注、AI摘要、在ComfyUI中打开、加载到生成UI、设为默认、删除",
helpWf6: "详情弹窗:重命名、收藏、缩略图更换、徽章分配、标签、备注、AI摘要、发送到画布、加载到生成UI、设为默认、删除",
helpWf7: "徽章管理:添加、重命名、删除徽章并自定义颜色(与Models标签共享)— ⚙ Badge按钮",
helpGen1: "连接/断开ComfyUI,检查连接状态",
helpGen2: "从工作流标签页加载工作流(不支持App格式.app.json)",
helpGen2: "从工作流标签页加载工作流(不支持App格式.app.json)。Reset Workflow按钮从磁盘重新读取当前工作流文件并重新加载编辑器。Save按钮(标签栏右端)将当前工作流(包括在编辑器中所做的编辑)保存为新的.json文件到工作流标签页;会显示以当前工作流名称为默认值的文件名对话框",
helpGen3: "5标签布局 — Input(提示词+图像)、Model、Settings、Feeder、Batch — Input/Model/Settings各含实时预览和直接编辑的Raw JSON列",
helpGen4: "Input标签:左列为Prompt(上)+ Image拖放(下)",
helpGen5: "Model标签:Checkpoint/VAE/LoRA(Single/Stack标签)/ControlNet/UNET/TextEncoder选择器(含筛选)",
@@ -1813,7 +2348,7 @@ const LANGUAGES = {
helpNodes5: "侧面板:详情(类名、包、分类、描述、标志)、I/O规格(输入输出类型和默认值)、组管理",
helpNodes6: "节点集:创建可复用的节点集合(含描述、标签、节点间链接定义)",
helpModels1: "浏览已安装模型:Checkpoint、LoRA、VAE、ControlNet、UNET、TextEncoder、Hypernetwork、Embedding,通过子标签切换",
helpModels2: "缩略图和表格视图模式切换(带分页)",
helpModels2: "缩略图和表格视图模式切换(带分页)。表格视图除文件名、子文件夹和扩展名外,还显示来自CivitAI数据的Type / Base Model列。点击列标题可排序 — 第一次升序(▲),第二次降序(▼),第三次取消排序。E/D列按启用/禁用状态排序",
helpModels3: "搜索、标签筛选、分组筛选、收藏筛选、状态筛选(全部 / 仅启用 / 仅禁用)",
helpModels4: "侧面板:基本信息(文件路径、标签、备注)、分组管理、CivitAI集成",
helpModels5: "CivitAI集成:通过SHA256哈希获取模型信息,按模型类型批量获取;无预览图时自动下载并保存",
@@ -1823,6 +2358,7 @@ const LANGUAGES = {
helpModels9: "用户自定义徽章:为模型添加自由标签徽章(颜色调色板与Workflow标签共享)",
helpModels10: "模型启用/禁用:通过重命名文件扩展名(添加.disabled后缀)控制ComfyUI中的显示。点击每个卡片上的⏸按钮单独操作,或在分组面板中使用「全部启用/全部禁用」进行批量操作。更改在刷新ComfyUI后生效。",
helpModels11: "多选与批量操作:点击「选择」按钮进入选择模式,勾选多个模型后,可通过批量操作栏将其添加/移出分组,或永久删除文件(模型文件+预览图+.json/.info等附属文件)。",
helpModels12: "移动或删除模型后,ComfyUI可能因缓存旧路径而无法加载模型。请通过ComfyUI菜单执行Hard Reset(Queue → Hard Reset)或重启ComfyUI以刷新模型缓存。",
helpGalleryTitle: "图库标签页 (Gallery)",
helpGallery1: "浏览 ComfyUI 输出文件夹中的图像 — 可以在 设置 > 图库输出文件夹 中设置文件夹路径",
helpGallery2: "三列布局:文件夹树(左) | 图像网格(中) | 详情面板(右)",
@@ -1831,10 +2367,26 @@ const LANGUAGES = {
helpGallery5: "文件夹树:点击加载图像,▶展开;'+ New'在选定文件夹内创建子文件夹;'Del'删除该文件夹及其所有内容",
helpGallery6: "使用Ctrl+点击多选 — 批量操作:添加到分组、全部收藏、取消全部收藏、移动到...、删除",
helpGallery7: "详情面板 — 信息(Info)标签:文件名、大小、日期、标签(添加/移除)、备注;'移动到...'将图像移至另一文件夹;'删除'永久删除",
helpGallery8: "详情面板 — 元数据(Metadata)标签:显示来自PNG嵌入数据(prompt / workflow键)或Generate UI标签保存的工作流JSON;一键复制到剪贴板",
helpGallery8: "详情面板 — JSON标签:显示来自PNG嵌入数据(prompt / workflow键)或Generate UI标签保存的工作流JSON;「Copy & Send Canvas」按钮将工作流复制到剪贴板并存储以供标题拖拽到画布",
helpGallery9: "详情面板 — 分组(Groups)标签:对每个图像进行组的创建、分配、移除、重命名和删除",
helpGallery10: "工作流自动保存:在Generate UI标签生成的图像,其工作流会自动保存到图库元数据,并在Metadata标签中显示",
helpGallery10: "工作流自动保存:在Generate UI标签生成的图像,其工作流会自动保存到图库元数据,并在JSON标签中显示",
helpGallery11: "支持PNG(tEXt/iTXt)、JPEG、WebP、GIF;PNG格式读取ComfyUI嵌入的JSON(prompt / workflow键)提取工作流",
helpGallery12: "Metadata按钮(绿色,位于详情面板标签栏):在Metadata标签中打开所选图像以全面查看嵌入数据;Alt+点击任意图像缩略图效果相同",
helpGallery13: "Load GenUI按钮(蓝色,位于详情面板标签栏):将所选图像中嵌入的ComfyUI工作流直接加载到GenerateUI标签并切换过去;如果没有嵌入工作流或格式不受支持,则显示警告提示",
helpGallery14: "Tagger按钮(紫色,位于详情面板操作行):将所选图像直接在Tagger标签的Single模式中打开,即可立即进行标注",
// -- Tagger Tab --
helpTaggerTitle: "Tagger标签",
helpTagger1: "使用WD Tagger(ONNX)、SwinV2、DeepDanbooru(.h5)和Ollama VLM进行自动图像标注 — 子标签:Single / Batch / DB",
helpTagger2: "模型放置:在ComfyUI/models/tagger/<模型名>/ 下为每个模型创建单独子文件夹,必须包含 .onnx + selected_tags.csv(DeepDanbooru为 .h5 + 标签文件)",
helpTagger3: "Single标签:将图像拖放到预览区域,或点击Upload选择文件;图库详情面板的Tagger按钮可直接在此处打开所选图像",
helpTagger4: "阈值滑块:一般标签的最低置信度(默认0.35);角色阈值:character: 前缀标签的独立阈值(默认0.85)",
helpTagger5: "Ollama VLM:勾选复选框可与WD Tagger并行运行视觉模型;设置API URL、选择模型(点击↻刷新列表)并自定义提示词;两个模型的结果将合并",
helpTagger6: "生成标签的发送目标:(1) GenUI:P — 追加到生成UI标签的正向提示词并立即应用到已加载工作流;(2) 发送到提示词 — 追加到提示词标签的正向文本区;(3) 保存到图库 — 保存到图库图像元数据(仅限从图库打开的图像);(4) 写入文件 — JPEG写入EXIF(ImageDescription)、PNG写入tEXt(Tags键);(5) 保存到DB — 存入内置SQLite数据库",
helpTagger7: "Batch标签:输入目标文件夹路径并配置WD Tagger和Ollama设置,选择输出选项(保存DB〈默认开启〉、写入文件〈EXIF/PNG元数据〉、输出.txt〈在图像同目录生成 <文件名>.txt〉);开始批处理后将处理文件夹内所有图像;进度条和日志实时更新;停止按钮在当前图像处理完成后取消",
helpTagger8: "DB标签:所有已标注图像的可搜索数据库;点击行可在编辑面板中修改WD标签/VLM标签;保存更新记录,删除移除记录;导出CSV可下载所有记录",
helpTagger9: "安装依赖包:python_embeded\\python.exe -m pip install -r requirements.txt;GPU推理请安装onnxruntime-gpu替代onnxruntime;TensorFlow(用于DeepDanbooru)因体积较大默认已注释",
helpSidepanelTitle: "Workflow Studio Library(ComfyUI侧面板)",
helpSidepanel1: "从ComfyUI工具栏的Workflow Studio Library按钮打开",
helpSidepanel2: "Workflows标签:All / ★ Favorites / Groups子标签,All视图中收藏项显示★",
@@ -1851,13 +2403,14 @@ const LANGUAGES = {
helpSidepanel13: "I 标签(Information):拖放 ComfyUI PNG/WebP/JSON 即可在侧面板内查看模型、LoRA 和提示词元数据 — 子标签:model / lora / Prompts;支持 UnetLoaderGGUF、QuadrupleCLIPLoader 和 Lora Loader (LoraManager) 节点类型",
helpSidepanel14: "Information 标签 — 拖拽到画布:model 子标签拖拽可放置对应加载节点(Checkpoint → CheckpointLoaderSimple、VAE → VAELoader、Diffusion Model → UNETLoader、Text Encoder → CLIPLoader);双击也可放置到画布中央",
helpSidepanel15: "Information 标签 — lora 子标签:可检测 LoraLoader、LoraLoaderModelOnly 及 Lora Loader (LoraManager) 节点(含API格式)的 LoRA;拖拽单个 LoRA 放置 LoraLoader;「Multiple LORA」区域可将全部 LoRA 一次性放入 Lora Loader (LoraManager) 节点并自动填入LoRA语法;Prompts 子标签:拖拽提示词放置预填文本的 CLIPTextEncode 节点;点击可查看全文并复制",
helpSidepanel16: "A 标签(AI 工具):翻译子标签和 VLM 子标签;设置(后端、URL、模型)通过 localStorage 与 SPA 的 AI 标签共享",
helpSidepanel16: "A 标签(AI 工具):翻译、Chat、TOOLS 和设置子标签;Chat 支持与 LLM 的多轮对话;TOOLS 包含 VLM 图像分析和通配符生成;设置通过 localStorage 与 SPA 的 AI 标签共享",
helpSidepanel17: "标题拖拽(Send to Canvas):在Workflow标签点击'Send to Canvas'或在Gallery标签点击'Copy & Send Canvas'后,面板标题变蓝并显示绿色●——将标题拖拽到画布即可加载工作流;加载后标题自动重置",
helpAiTitle: "AI 标签页(A)",
helpAi1: "翻译子标签:使用 Ollama 或 LM Studio 在日语、英语、中文或自定义语言(Free)之间翻译文本",
helpAi2: "源语言和目标语言选择器,带 ⇄ 互换按钮;文本内容也同时互换;选择自动保存",
helpAi3: "TOOLS 面板:将图像拖放到投放区域,选择任务(图像描述 / 提示词生成 / 标签生成),点击执行按钮用视觉模型进行分析",
helpAi4: "VLM 结果显示在输出区域,可通过复制按钮复制到剪贴板",
helpAi5: "设置子标签:选择后端(Ollama / LM Studio)、设置 API URL、测试连接、选择模型、配置翻译的 Free 语言名称",
helpAi1: "4 面板布局 — Translation | Chat | TOOLS | Settings — 所有面板始终可见",
helpAi2: "翻译面板:使用 Ollama 或 LM Studio 在日语、英语、中文或自定义语言(Free)之间翻译;⇄ 按钮同时互换语言和文本内容;选择自动保存",
helpAi3: "Chat 面板:与 LLM 进行多轮对话;Enter 发送消息,Shift+Enter 换行;Clear 按钮重置对话历史",
helpAi4: "TOOLS 面板 — VLM:拖放图像(PNG/JPG/WebP)并选择任务(图像描述 / 提示词生成 / 标签生成),点击 Run;或选择「Create wildcards」,输入类别名称和数量生成纯文本通配符条目(每行一条)",
helpAi5: "设置面板:选择后端(Ollama / LM Studio)、设置 API URL、测试连接、选择模型、配置 Free 语言名称",
helpAi6: "设置保存至 localStorage,并与 Library 面板的 A 标签共享",
helpShortcutsTitle: "键盘操作",
helpShortcuts1: "Escape:关闭弹窗/面板",
@@ -1870,6 +2423,8 @@ const LANGUAGES = {
helpTrouble3: "工作流不显示:点击刷新按钮、确认能在ComfyUI中加载、尝试重启浏览器/ComfyUI",
helpTrouble4: "图片生成失败:确认指定模型存在、验证ComfyUI连接、尝试重启",
helpTrouble5: "LoRA Stack出现「No such file or directory」错误:该LoRA可能未被comfyui-lora-manager识别(已知问题)。请尝试其他LoRA,或检查该文件是否显示在Lora Manager自身的界面中",
helpTrouble6: "移动或删除模型后出现模型加载错误:ComfyUI会缓存文件路径,可能仍引用旧位置。请通过ComfyUI菜单执行Hard Reset(Queue → Hard Reset)或重启ComfyUI以清除缓存。",
helpTrouble7: "Tagger标签不显示模型:确认ComfyUI/models/tagger/<模型名>/文件夹存在且包含.onnx或.h5文件;如未安装onnxruntime,请运行:python_embeded\\python.exe -m pip install onnxruntime",
helpSupportTitle: "支持",
helpSupportDesc: "如果您觉得这个插件有用,请考虑支持它的开发!",
helpGithubDesc: "报告问题、请求功能和贡献代码",
@@ -2052,14 +2607,9 @@ let _summaryLang = "en";
* Initialize i18n from localStorage settings.
*/
export function initI18n() {
try {
const s = JSON.parse(localStorage.getItem("wfm_settings") || "{}");
_currentLang = s.uiLang || "en";
_summaryLang = s.summaryLang || "en";
} catch {
_currentLang = "en";
_summaryLang = "en";
}
const s = getSettings();
_currentLang = s.uiLang || "en";
_summaryLang = s.summaryLang || "en";
}
/**
+12 -1
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;
@@ -504,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");
@@ -550,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");
@@ -743,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"); });
+258 -52
View File
@@ -7,6 +7,7 @@ import { showToast, openModal, closeModal } from "./app.js";
import { t } from "./i18n.js";
import { comfyUI } from "./comfyui-client.js";
import { comfyEditor } from "./comfyui-editor.js";
import { escapeHtml, readJsonStorage } from "./util.js";
// ── Constants ─────────────────────────────────────────────
const RESERVED_GROUPS = ["Batch", "Stack"];
@@ -31,6 +32,7 @@ const state = {
allModelGroups: {}, // { type: { groupName: [models] } } — all types
civitaiCache: {},
disabledModels: {}, // { type: Set<modelName> }
subdirs: [],
selectMode: false,
selectedModels: new Set(),
searchText: "",
@@ -46,6 +48,8 @@ const state = {
selectedModel: null,
loaded: {},
currentPage: 0,
sortColumn: null, // "fav" | "filename" | "subdir" | "civtype" | "basemodel" | "ext" | "tags" | "memo" | "enabled"
sortDir: "asc", // "asc" | "desc"
};
@@ -187,9 +191,7 @@ function applyToGenUI(modelName, modelType) {
// User-defined badge colors (stored in metadata per model)
// Global badge palette: label → color, stored in localStorage
function getBadgePalette() {
try {
return JSON.parse(localStorage.getItem("wfm_models_badge_palette") || "{}");
} catch { return {}; }
return readJsonStorage("wfm_models_badge_palette");
}
function saveBadgePalette(palette) {
@@ -198,13 +200,6 @@ function saveBadgePalette(palette) {
// ── Helpers ───────────────────────────────────────────────
function escapeHtml(s) {
return String(s)
.replace(/&/g, "&amp;")
.replace(/</g, "&lt;")
.replace(/>/g, "&gt;")
.replace(/"/g, "&quot;");
}
function parseModelPath(fullName) {
const lastSlash = Math.max(fullName.lastIndexOf("/"), fullName.lastIndexOf("\\"));
@@ -319,6 +314,12 @@ function clearSelection() {
renderBulkActionBar();
}
function selectAll() {
filterModels().forEach(m => state.selectedModels.add(m));
renderModelGrid();
renderBulkActionBar();
}
function renderBulkActionBar() {
const bar = document.getElementById("wfm-models-bulk-bar");
if (!bar) return;
@@ -342,28 +343,48 @@ function renderBulkActionBar() {
bar.style.display = "flex";
bar.innerHTML = `
<span class="wfm-bulk-count">${count} ${t("modelSelected")}</span>
<button class="wfm-btn wfm-btn-sm" id="wfm-bulk-deselect-all-btn">${t("modelBulkDeselectAll")}</button>
<span class="wfm-bulk-sep">|</span>
<button class="wfm-btn wfm-btn-sm" id="wfm-bulk-fav-add-btn" title="${t("modelBulkFavAdd")}">${t("modelBulkFavAdd")}</button>
<button class="wfm-btn wfm-btn-sm" id="wfm-bulk-fav-remove-btn" title="${t("modelBulkFavRemove")}">${t("modelBulkFavRemove")}</button>
<span class="wfm-bulk-sep">|</span>
<select id="wfm-bulk-group-select" class="wfm-select" style="font-size:12px;">${groupOptions}</select>
<button class="wfm-btn wfm-btn-sm wfm-btn-primary" id="wfm-bulk-add-btn"${noGroups ? " disabled" : ""}>${t("modelBulkAddGroup")}</button>
<button class="wfm-btn wfm-btn-sm wfm-btn-danger" id="wfm-bulk-remove-btn"${noGroups ? " disabled" : ""}>${t("modelBulkRemoveGroup")}</button>
<span class="wfm-bulk-sep">|</span>
<input type="text" id="wfm-bulk-new-group-input" class="wfm-search-input" style="width:120px;font-size:12px;" placeholder="${t("modelsGroupName")}">
<button class="wfm-btn wfm-btn-sm" id="wfm-bulk-create-add-btn">${t("modelBulkCreateAdd")}</button>
<span class="wfm-bulk-sep">|</span>
<select id="wfm-bulk-badge-select" class="wfm-select" style="font-size:12px;">${badgeOptions}</select>
<button class="wfm-btn wfm-btn-sm wfm-btn-primary" id="wfm-bulk-badge-apply-btn"${noBadges ? " disabled" : ""}>${t("modelBulkBadgeApply")}</button>
<button class="wfm-btn wfm-btn-sm wfm-btn-danger" id="wfm-bulk-badge-remove-btn"${noBadges ? " disabled" : ""}>${t("modelBulkBadgeRemove")}</button>
<span class="wfm-bulk-sep">|</span>
<button class="wfm-btn wfm-btn-sm" id="wfm-bulk-clear-btn" title="Clear selection">&times;</button>
<button class="wfm-btn wfm-btn-sm wfm-btn-danger" id="wfm-bulk-delete-btn" style="margin-left:4px;">${t("modelBulkDelete")}</button>
<div class="wfm-bulk-header">
<span class="wfm-bulk-count">${count} ${t("modelSelected")}</span>
<button class="wfm-btn wfm-btn-sm" id="wfm-bulk-deselect-all-btn">${t("modelBulkDeselectAll")}</button>
<button class="wfm-btn wfm-btn-sm" id="wfm-bulk-select-all-btn">${t("modelBulkSelectAll")}</button>
<span class="wfm-bulk-sep"></span>
<button class="wfm-btn wfm-btn-sm" id="wfm-bulk-fav-add-btn">${t("modelBulkFavAdd")}</button>
<button class="wfm-btn wfm-btn-sm" id="wfm-bulk-fav-remove-btn">${t("modelBulkFavRemove")}</button>
</div>
<div class="wfm-bulk-rows">
<div class="wfm-bulk-row">
<span class="wfm-bulk-row-label">Group:</span>
<select id="wfm-bulk-group-select" class="wfm-select wfm-bulk-select">${groupOptions}</select>
<button class="wfm-btn wfm-btn-sm wfm-btn-primary" id="wfm-bulk-add-btn"${noGroups ? " disabled" : ""}>${t("modelBulkAddGroup")}</button>
<button class="wfm-btn wfm-btn-sm wfm-btn-danger" id="wfm-bulk-remove-btn"${noGroups ? " disabled" : ""}>${t("modelBulkRemoveGroup")}</button>
<span class="wfm-bulk-sep"></span>
<input type="text" id="wfm-bulk-new-group-input" class="wfm-search-input wfm-bulk-input" placeholder="${t("modelsGroupName")}">
<button class="wfm-btn wfm-btn-sm" id="wfm-bulk-create-add-btn">${t("modelBulkCreateAdd")}</button>
</div>
<div class="wfm-bulk-row">
<span class="wfm-bulk-row-label">Badge:</span>
<select id="wfm-bulk-badge-select" class="wfm-select wfm-bulk-select">${badgeOptions}</select>
<button class="wfm-btn wfm-btn-sm wfm-btn-primary" id="wfm-bulk-badge-apply-btn"${noBadges ? " disabled" : ""}>${t("modelBulkBadgeApply")}</button>
<button class="wfm-btn wfm-btn-sm wfm-btn-danger" id="wfm-bulk-badge-remove-btn"${noBadges ? " disabled" : ""}>${t("modelBulkBadgeRemove")}</button>
</div>
<div class="wfm-bulk-row">
<span class="wfm-bulk-row-label">File:</span>
<select id="wfm-bulk-move-select" class="wfm-select wfm-bulk-select">
<option value="">${t("modelBulkMoveRoot")}</option>
${state.subdirs.map((d) => `<option value="${escapeHtml(d)}">${escapeHtml(d)}</option>`).join("")}
</select>
<button class="wfm-btn wfm-btn-sm" id="wfm-bulk-move-btn">${t("modelBulkMoveBtn")}</button>
<span class="wfm-bulk-sep"></span>
<input type="text" id="wfm-bulk-new-dir-input" class="wfm-search-input wfm-bulk-input" placeholder="${t("modelBulkMoveNewFolder")}">
<button class="wfm-btn wfm-btn-sm" id="wfm-bulk-mkdir-move-btn">${t("modelBulkMoveCreateMove")}</button>
<span style="flex:1"></span>
<button class="wfm-btn wfm-btn-sm wfm-btn-danger" id="wfm-bulk-delete-btn">${t("modelBulkDelete")}</button>
</div>
</div>
`;
document.getElementById("wfm-bulk-deselect-all-btn")?.addEventListener("click", clearSelection);
document.getElementById("wfm-bulk-select-all-btn")?.addEventListener("click", selectAll);
document.getElementById("wfm-bulk-fav-add-btn")?.addEventListener("click", () => bulkSetFavorite(true));
document.getElementById("wfm-bulk-fav-remove-btn")?.addEventListener("click", () => bulkSetFavorite(false));
document.getElementById("wfm-bulk-add-btn")?.addEventListener("click", () => {
@@ -389,7 +410,16 @@ function renderBulkActionBar() {
const label = document.getElementById("wfm-bulk-badge-select")?.value;
if (label) bulkApplyBadge(label, false);
});
document.getElementById("wfm-bulk-clear-btn")?.addEventListener("click", clearSelection);
document.getElementById("wfm-bulk-move-btn")?.addEventListener("click", () => {
const dest = document.getElementById("wfm-bulk-move-select")?.value || "";
bulkMoveModels(dest);
});
document.getElementById("wfm-bulk-mkdir-move-btn")?.addEventListener("click", () => {
const input = document.getElementById("wfm-bulk-new-dir-input");
const name = input?.value.trim();
if (!name) return;
bulkMoveModels(name);
});
document.getElementById("wfm-bulk-delete-btn")?.addEventListener("click", bulkDeleteModels);
}
@@ -494,6 +524,58 @@ async function bulkDeleteModels() {
}
}
async function fetchSubdirs() {
try {
const res = await fetch(`/api/wfm/models/subdirs?type=${encodeURIComponent(state.activeModelType)}`);
state.subdirs = res.ok ? await res.json() : [];
} catch { state.subdirs = []; }
}
async function bulkMoveModels(destSubdir) {
const model_names = [...state.selectedModels];
if (model_names.length === 0) return;
try {
const res = await fetch("/api/wfm/models/move", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ model_type: state.activeModelType, model_names, dest: destSubdir }),
});
const data = await res.json();
const okCount = data.moved?.length || 0;
const errCount = data.errors?.length || 0;
if (okCount > 0) {
data.moved.forEach(({ from, to }) => {
const list = state.modelsByType[state.activeModelType];
const idx = list.indexOf(from);
if (idx !== -1) list[idx] = to;
if (state.modelMetadata[from]) {
state.modelMetadata[to] = state.modelMetadata[from];
delete state.modelMetadata[from];
}
const ds = state.disabledModels[state.activeModelType];
if (ds && ds.has(from)) { ds.delete(from); ds.add(to); }
state.selectedModels.delete(from);
});
if (state.selectedModel && data.moved.some((m) => m.from === state.selectedModel)) {
state.selectedModel = null;
const titleEl = document.getElementById("wfm-models-panel-title");
if (titleEl) titleEl.textContent = "";
}
showToast(`${okCount} ${t("modelBulkMoveDone")}`, "success");
await fetchSubdirs();
renderDirFilter();
renderModelGrid();
renderBulkActionBar();
}
if (errCount > 0) {
showToast(`${t("modelBulkMoveError")}: ${data.errors[0].error}`, "error");
}
} catch (err) {
showToast(`${t("modelBulkMoveError")}: ${err.message}`, "error");
}
}
// ── Enable / Disable helpers ──────────────────────────────
function isModelDisabled(modelName) {
@@ -588,7 +670,7 @@ async function saveModelMetadata(modelName, updates) {
}
return data;
} catch (err) {
showToast("Error saving metadata: " + err.message, "error");
showToast(t("saveFailed", err.message), "error");
return null;
}
}
@@ -657,7 +739,47 @@ function filterModels() {
});
}
return models;
return sortModels(models);
}
function sortKeyOf(modelName) {
const meta = state.modelMetadata[modelName] || {};
switch (state.sortColumn) {
case "fav":
return meta.favorite ? 1 : 0;
case "filename":
return parseModelPath(modelName).name.toLowerCase();
case "subdir":
return parseModelPath(modelName).dir.toLowerCase();
case "civtype": {
const civ = meta.sha256 && state.civitaiCache[meta.sha256];
return (civ?.type || "").toLowerCase();
}
case "basemodel": {
const civ = meta.sha256 && state.civitaiCache[meta.sha256];
return (civ?.baseModel || "").toLowerCase();
}
case "ext":
return getExtension(parseModelPath(modelName).name).toLowerCase();
case "tags":
return (meta.tags || []).join(", ").toLowerCase();
case "memo":
return (meta.memo || "").toLowerCase();
case "enabled":
return isModelDisabled(modelName) ? 1 : 0;
default:
return 0;
}
}
function sortModels(models) {
if (!state.sortColumn) return models;
// ソートキーを1モデル1回だけ計算(比較ごとのparseModelPath等の再計算を回避)
const dir = state.sortDir === "asc" ? 1 : -1;
return models
.map((m) => [sortKeyOf(m), m])
.sort((a, b) => (a[0] < b[0] ? -dir : a[0] > b[0] ? dir : 0))
.map((pair) => pair[1]);
}
function getAllTags() {
@@ -935,13 +1057,19 @@ function renderThumbView(grid, models) {
const placeholder = card.querySelector(".wfm-card-thumb-placeholder");
loadPreviewImage(img, placeholder, modelName);
card.querySelector(".wfm-batch-btn")?.addEventListener("click", (e) => {
card.querySelector(".wfm-batch-btn")?.addEventListener("click", async (e) => {
e.stopPropagation();
toggleBatch(modelName);
await toggleBatch(modelName);
if (state.showBatchOnly) {
renderModelGrid();
} else {
e.currentTarget.classList.toggle("active", isInBatch(modelName));
}
});
card.querySelector(".wfm-stack-btn")?.addEventListener("click", (e) => {
card.querySelector(".wfm-stack-btn")?.addEventListener("click", async (e) => {
e.stopPropagation();
toggleStack(modelName);
await toggleStack(modelName);
e.currentTarget.classList.toggle("active", isInStack(modelName));
});
card.querySelector(".wfm-fav-btn").addEventListener("click", (e) => {
e.stopPropagation();
@@ -972,6 +1100,14 @@ function renderThumbView(grid, models) {
// ── Table View ────────────────────────────────────────────
function thSortHtml(label, col, extraClass = "", extraStyle = "") {
const isActive = state.sortColumn === col;
const arrow = isActive ? (state.sortDir === "asc" ? " ▲" : " ▼") : "";
const activeStyle = isActive ? "color:var(--wfm-accent,#6366f1);" : "";
const cls = ["wfm-table-th-sortable", extraClass].filter(Boolean).join(" ");
return `<th class="${cls}" data-sort-col="${col}" style="${activeStyle}${extraStyle}">${label}${arrow}</th>`;
}
function renderTableView(grid, models) {
const showBatchBtn = ["checkpoint", "lora"].includes(state.activeModelType);
const showStackBtn = state.activeModelType === "lora";
@@ -980,6 +1116,10 @@ function renderTableView(grid, models) {
const meta = state.modelMetadata[modelName] || {};
const { dir, name } = parseModelPath(modelName);
const ext = getExtension(name);
const sha256 = meta.sha256;
const civitai = sha256 && state.civitaiCache[sha256];
const civitaiType = civitai ? (civitai.type || "") : "";
const civitaiBaseModel = civitai ? (civitai.baseModel || "") : "";
const disabled = isModelDisabled(modelName);
const isChecked = state.selectMode && state.selectedModels.has(modelName);
const favIcon = meta.favorite ? "&#9733;" : "&#9734;";
@@ -996,8 +1136,10 @@ function renderTableView(grid, models) {
${checkCell}
<td class="wfm-models-table-fav" title="Favorite">${favIcon}</td>
<td class="wfm-table-td-thumb"><img class="wfm-table-thumb" style="display:none" /></td>
<td title="${escapeHtml(modelName)}">${escapeHtml(name)}</td>
<td class="wfm-table-td-filename" title="${escapeHtml(modelName)}">${escapeHtml(name)}</td>
<td class="wfm-table-td-subdir">${escapeHtml(dir)}</td>
<td class="wfm-table-td-civtype" title="${escapeHtml(civitaiType)}">${escapeHtml(civitaiType)}</td>
<td class="wfm-table-td-basemodel" title="${escapeHtml(civitaiBaseModel)}">${escapeHtml(civitaiBaseModel)}</td>
<td class="wfm-table-td-ext">${escapeHtml(ext)}</td>
<td>${escapeHtml(tagsStr)}</td>
<td class="wfm-table-td-memo" title="${escapeHtml(memo)}">${escapeHtml(memo)}</td>
@@ -1011,14 +1153,16 @@ function renderTableView(grid, models) {
const checkTh = state.selectMode ? `<th style="width:24px;"></th>` : "";
grid.innerHTML = `<table class="wfm-models-table"><thead><tr>
${checkTh}
<th style="width:30px;">&#9733;</th>
${thSortHtml("&#9733;", "fav", "", "width:30px;text-align:center;")}
<th style="width:40px;"></th>
<th>${t("modelsFileName")}</th>
<th class="wfm-table-th-subdir">${t("modelsSubdir")}</th>
<th class="wfm-table-th-ext">${t("modelsExt")}</th>
<th>${t("modelsTags")}</th>
<th>${t("modelsMemo")}</th>
<th style="width:50px;"></th>
${thSortHtml(t("modelsFileName"), "filename", "wfm-table-th-filename")}
${thSortHtml(t("modelsSubdir"), "subdir", "wfm-table-th-subdir")}
${thSortHtml(t("civitaiType"), "civtype", "wfm-table-th-civtype")}
${thSortHtml(t("civitaiBaseModel"), "basemodel", "wfm-table-th-basemodel")}
${thSortHtml(t("modelsExt"), "ext", "wfm-table-th-ext")}
${thSortHtml(t("modelsTags"), "tags")}
${thSortHtml(t("modelsMemo"), "memo")}
${thSortHtml("E/D", "enabled", "", "width:50px;text-align:center;")}
${showBatchBtn ? `<th style="width:30px;">B</th>` : ""}
${showStackBtn ? `<th style="width:30px;">S</th>` : ""}
</tr></thead><tbody>${rows}</tbody></table>`;
@@ -1045,13 +1189,37 @@ function renderTableView(grid, models) {
e.stopPropagation();
toggleModelEnable(mn);
});
row.querySelector(".wfm-batch-btn")?.addEventListener("click", (e) => {
row.querySelector(".wfm-batch-btn")?.addEventListener("click", async (e) => {
e.stopPropagation();
toggleBatch(mn);
await toggleBatch(mn);
if (state.showBatchOnly) {
renderModelGrid();
} else {
e.currentTarget.classList.toggle("active", isInBatch(mn));
}
});
row.querySelector(".wfm-stack-btn")?.addEventListener("click", (e) => {
row.querySelector(".wfm-stack-btn")?.addEventListener("click", async (e) => {
e.stopPropagation();
toggleStack(mn);
await toggleStack(mn);
e.currentTarget.classList.toggle("active", isInStack(mn));
});
});
grid.querySelectorAll(".wfm-table-th-sortable").forEach((th) => {
th.addEventListener("click", () => {
const col = th.dataset.sortCol;
if (state.sortColumn === col) {
if (state.sortDir === "asc") {
state.sortDir = "desc";
} else {
state.sortColumn = null;
state.sortDir = "asc";
}
} else {
state.sortColumn = col;
state.sortDir = "asc";
}
renderModelGrid();
});
});
}
@@ -1073,7 +1241,6 @@ async function toggleBatch(modelName) {
state.modelGroups["Batch"] = batch;
state.allModelGroups[state.activeModelType] = state.modelGroups;
await saveModelGroups(state.modelGroups);
renderModelGrid();
}
async function clearBatchGroup() {
@@ -1103,7 +1270,6 @@ async function toggleStack(modelName) {
state.modelGroups["Stack"] = stack;
state.allModelGroups[state.activeModelType] = state.modelGroups;
await saveModelGroups(state.modelGroups);
renderModelGrid();
}
async function clearStackGroup() {
@@ -1111,7 +1277,7 @@ async function clearStackGroup() {
state.allModelGroups[state.activeModelType] = state.modelGroups;
await saveModelGroups(state.modelGroups);
renderModelGrid();
showToast("Stack cleared", "success");
showToast(t("stackCleared"), "success");
}
// ── Favorite toggle ───────────────────────────────────────
@@ -1182,6 +1348,7 @@ function openDetailModal(modelName) {
${GENUI_TYPE_MAP[state.activeModelType]
? `<button class="wfm-btn wfm-btn-sm" id="wfm-modal-genui-model" title="${t("modelsGenUITitle")}">${t("modelsGenUIBtn")}</button>`
: ""}
<button class="wfm-btn wfm-btn-sm wfm-btn-danger" id="wfm-modal-model-delete" style="margin-left:auto;">${t("modelsDelete")}</button>
</div>
</div>
</div>`;
@@ -1236,6 +1403,41 @@ function openDetailModal(modelName) {
applyToGenUI(modelName, state.activeModelType);
});
// Delete model button
document.getElementById("wfm-modal-model-delete")?.addEventListener("click", async () => {
const confirmMsg = t("modelBulkDeleteConfirm").replace("{count}", "1");
if (!confirm(confirmMsg)) return;
try {
const res = await fetch("/api/wfm/models/delete", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ model_type: state.activeModelType, model_names: [modelName] }),
});
const data = await res.json();
if (data.errors?.length > 0) {
showToast(`${t("modelBulkDeleteError")}: ${data.errors[0].error}`, "error");
return;
}
showToast(`${getStem(name)} ${t("modelBulkDeleteDone")}`, "success");
closeModal();
const list = state.modelsByType[state.activeModelType];
const idx = list.indexOf(modelName);
if (idx !== -1) list.splice(idx, 1);
delete state.modelMetadata[modelName];
const ds = state.disabledModels[state.activeModelType];
if (ds) ds.delete(modelName);
state.selectedModels.delete(modelName);
if (state.selectedModel === modelName) {
state.selectedModel = null;
const titleEl = document.getElementById("wfm-models-panel-title");
if (titleEl) titleEl.textContent = "";
}
renderModelGrid();
} catch (err) {
showToast(`${t("modelBulkDeleteError")}: ${err.message}`, "error");
}
});
// Change thumbnail
const changeBtn = document.getElementById("wfm-modal-change-thumb");
const thumbFile = document.getElementById("wfm-modal-thumb-file");
@@ -1833,11 +2035,13 @@ async function loadModelsForCurrentType() {
state.modelGroups["Stack"] = [];
await saveModelGroups(state.modelGroups);
}
if (!STACK_MODEL_TYPES.includes(type)) delete state.modelGroups["Stack"];
state.allModelGroups[type] = state.modelGroups;
renderTagFilter();
renderDirFilter();
renderGroupFilter();
renderModelGrid();
fetchSubdirs();
return;
}
@@ -1860,6 +2064,7 @@ async function loadModelsForCurrentType() {
groups["Stack"] = [];
await saveModelGroups(groups);
}
if (!STACK_MODEL_TYPES.includes(type)) delete groups["Stack"];
state.modelGroups = groups;
state.allModelGroups[type] = groups;
@@ -1874,10 +2079,11 @@ async function loadModelsForCurrentType() {
renderDirFilter();
renderGroupFilter();
renderModelGrid();
fetchSubdirs();
} catch (err) {
console.error("Failed to load models:", err);
if (placeholder) placeholder.textContent = t("modelsLoadError");
showToast("Error: " + err.message, "error");
showToast(t("errorWithMsg", err.message), "error");
}
}
+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");
});
}
+18 -19
View File
@@ -4,6 +4,7 @@
import { showToast } from "./app.js";
import { t } from "./i18n.js";
import { readJsonStorage } from "./util.js";
// ============================================
// State
@@ -115,9 +116,7 @@ async function loadAllPresets() {
promptPresets = await fetchPresets();
// Load groups from localStorage
try {
pmGroups = JSON.parse(localStorage.getItem(PM_GROUPS_KEY) || "{}");
} catch { pmGroups = {}; }
pmGroups = readJsonStorage(PM_GROUPS_KEY);
// Clean stale entries from groups (preserve reserved groups even if empty)
const validIds = new Set(promptPresets.map(p => p.id));
@@ -1050,43 +1049,43 @@ export function initPromptTab() {
if (!name || !name.trim()) return;
const key = name.trim();
if (pmGroups[key]) {
showToast("Group already exists", "error");
showToast(t("groupExists"), "error");
return;
}
pmGroups[key] = [];
saveGroups();
renderPresetManager();
showToast(`Group "${key}" created`, "success");
showToast(t("groupCreated", key), "success");
});
document.getElementById("wfm-preset-add-to-group-btn")?.addEventListener("click", () => {
const groupSelect = document.getElementById("wfm-preset-group-select");
const groupName = groupSelect?.value;
if (!groupName) {
showToast("Select a group first", "error");
showToast(t("selectGroupFirst"), "error");
return;
}
const id = presetSelect?.value;
if (!id) {
showToast("Select a preset first", "error");
showToast(t("selectPresetFirst"), "error");
return;
}
if (!pmGroups[groupName]) pmGroups[groupName] = [];
if (pmGroups[groupName].includes(id)) {
showToast("Already in this group", "info");
showToast(t("alreadyInGroup"), "info");
return;
}
pmGroups[groupName].push(id);
saveGroups();
renderPresetManager();
showToast("Added to group", "success");
showToast(t("addedToGroup"), "success");
});
document.getElementById("wfm-preset-del-group-btn")?.addEventListener("click", () => {
const groupSelect = document.getElementById("wfm-preset-group-select");
const groupName = groupSelect?.value;
if (!groupName) {
showToast("Select a group first", "error");
showToast(t("selectGroupFirst"), "error");
return;
}
if (PROMPT_RESERVED_GROUPS.includes(groupName)) {
@@ -1097,7 +1096,7 @@ export function initPromptTab() {
delete pmGroups[groupName];
saveGroups();
renderPresetManager();
showToast(`Group "${groupName}" deleted`, "success");
showToast(t("groupDeleted", groupName), "success");
});
// --- Preset Manager ---
@@ -1160,7 +1159,7 @@ export function initPromptTab() {
const n = prompt("Number of items to pick (n):", "2");
if (n === null) return;
const num = parseInt(n, 10);
if (isNaN(num) || num < 1) { showToast("Enter a positive integer", "error"); return; }
if (isNaN(num) || num < 1) { showToast(t("enterPositiveInt"), "error"); return; }
const template = "{" + num + "$$|}";
const start = ta.selectionStart;
wcInsertAtCursor(ta, template);
@@ -1198,7 +1197,7 @@ export function initPromptTab() {
if (!src || !dst) return;
dst.value = src.value;
dst.dispatchEvent(new Event("input", { bubbles: true }));
showToast("Sent to Positive Prompt", "success");
showToast(t("sentToPositive"), "success");
});
document.getElementById("wfm-wc-to-neg-btn")?.addEventListener("click", () => {
@@ -1207,7 +1206,7 @@ export function initPromptTab() {
if (!src || !dst) return;
dst.value = src.value;
dst.dispatchEvent(new Event("input", { bubbles: true }));
showToast("Sent to Negative Prompt", "success");
showToast(t("sentToNegative"), "success");
});
document.getElementById("wfm-wc-clear-btn")?.addEventListener("click", () => {
@@ -1235,22 +1234,22 @@ export function initPromptTab() {
const ext = extSelect?.value || "txt";
const content = contentTA?.value || "";
if (!rawName) { showToast("Enter a filename", "error"); return; }
if (!rawName) { showToast(t("pleaseEnterFilename"), "error"); return; }
// Validate each path component (allow letters, numbers, -, _, ., space)
const nameParts = rawName.split("/");
if (nameParts.some(p => !p || !/^[\w\-. ]+$/.test(p))) {
showToast("Invalid path. Use folder/name format, each part: letters, numbers, -, _, . only", "error");
showToast(t("invalidPathFormat"), "error");
return;
}
const name = rawName;
const filename = `${name}.${ext}`;
const saved = await wcSaveFile(filename, content);
if (saved) {
showToast(`Saved: ${filename}`, "success");
showToast(t("savedAs", filename), "success");
wcCloseEditor();
wcRefreshFiles();
} else {
showToast("Failed to save file", "error");
showToast(t("saveFailed"), "error");
}
});
@@ -1259,7 +1258,7 @@ export function initPromptTab() {
if (!wcEditingFilename) return;
if (!confirm(`Delete "${wcEditingFilename}"?`)) return;
await wcDeleteFile(wcEditingFilename);
showToast(`Deleted: ${wcEditingFilename}`, "success");
showToast(t("deletedName", wcEditingFilename), "success");
wcCloseEditor();
wcRefreshFiles();
});
+5 -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) {
@@ -960,7 +958,7 @@ export async function initSettingsTab() {
setLang(lang);
saveLocalSettings({ ...loadLocalSettings(), uiLang: lang });
// Re-render the entire page to apply new language
showToast("Language changed. Reloading...", "success");
showToast(t("languageChanged"), "success");
setTimeout(() => location.reload(), 500);
});
@@ -1176,7 +1174,7 @@ export async function initSettingsTab() {
// Clear default workflow
document.getElementById("wfm-settings-clear-wf")?.addEventListener("click", () => {
const s = JSON.parse(localStorage.getItem("wfm_settings") || "{}");
const s = getSettings();
delete s.defaultWorkflow;
delete s.defaultWorkflowData;
localStorage.setItem("wfm_settings", JSON.stringify(s));
+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");
}
+32 -30
View File
@@ -10,6 +10,7 @@ import { loadWorkflowIntoEditor } from "./generate-tab.js";
import { t, getSummaryPrompt } from "./i18n.js";
import { highlightJSON } from "./json-highlight.js";
import { openBadgeEditModal } from "./models-tab.js";
import { escapeHtml, getSettings, readJsonStorage } from "./util.js";
// ============================================
// Constants
@@ -33,26 +34,27 @@ const state = {
function getBadgePalette() {
try { return JSON.parse(localStorage.getItem("wfm_models_badge_palette") || "{}"); }
catch { return {}; }
return readJsonStorage("wfm_models_badge_palette");
}
function saveBadgePalette(palette) {
localStorage.setItem("wfm_models_badge_palette", JSON.stringify(palette));
}
function escapeHtml(s) {
return String(s)
.replace(/&/g, "&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.
@@ -94,7 +96,7 @@ const groups = {
load() {
try {
this._data = JSON.parse(localStorage.getItem("wfm_groups") || "{}");
this._data = readJsonStorage("wfm_groups");
} catch {
this._data = {};
}
@@ -501,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");
}
}
@@ -677,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");
});
});
@@ -687,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に追加)
@@ -696,14 +698,14 @@ function renderSideGroup(wf) {
const name = input?.value.trim();
if (!name) return;
if (!groups.createGroup(name)) {
showToast(`"${name}" already exists`, "warning");
showToast(t("nameAlreadyExists", name), "warning");
return;
}
groups.assign(filename, name);
input.value = "";
renderSideGroup(wf);
_refreshGroupFilter();
showToast(`Group "${name}" created`, "success");
showToast(t("groupCreated", name), "success");
});
// グループ名変更
@@ -717,13 +719,13 @@ function renderSideGroup(wf) {
const newName = prompt(`Rename group "${oldName}" to:`, oldName);
if (!newName || newName === oldName) return;
if (!groups.renameGroup(oldName, newName)) {
showToast("Rename failed", "error");
showToast(t("renameFailed"), "error");
return;
}
if (state.groupFilter === oldName) state.groupFilter = newName;
renderSideGroup(wf);
_refreshGroupFilter();
showToast(`Renamed to "${newName}"`, "success");
showToast(t("renamedTo", newName), "success");
});
// グループ削除
@@ -743,7 +745,7 @@ function renderSideGroup(wf) {
}
renderSideGroup(wf);
_refreshGroupFilter();
showToast(`Group "${name}" deleted`, "success");
showToast(t("groupDeleted", name), "success");
});
_refreshGroupFilter();
@@ -865,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">
@@ -903,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);
@@ -1015,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");
}
@@ -1036,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));
@@ -1186,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 = "";
});
@@ -1229,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");
}
});
}
@@ -1292,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");
}
@@ -1306,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)
+307 -25
View File
@@ -7,6 +7,7 @@
<link rel="icon" type="image/svg+xml" href="/wfm_static/favicon.svg">
<link rel="stylesheet" href="/wfm_static/css/main.css">
<link rel="stylesheet" href="/wfm_static/css/gallery-tab.css">
<link rel="stylesheet" href="/wfm_static/css/tagger-tab.css">
</head>
<body>
<!-- Header -->
@@ -22,6 +23,7 @@
<button class="wfm-tab" data-tab="prompt">Prompt</button>
<button class="wfm-tab" data-tab="metadata">Metadata</button>
<button class="wfm-tab" data-tab="gallery">Gallery</button>
<button class="wfm-tab" data-tab="tagger">Tagger</button>
<button class="wfm-tab" data-tab="settings">Settings</button>
<button class="wfm-tab" data-tab="help">Help</button>
<button class="wfm-tab" data-tab="ai">AI TOOL</button>
@@ -47,7 +49,7 @@
<option value="">All Groups</option>
</select>
<button id="wfm-list-load-btn" class="wfm-btn wfm-btn-sm wfm-btn-primary" disabled title="Select a card first">Load in GenerateUI</button>
<button id="wfm-list-open-comfyui-btn" class="wfm-btn wfm-btn-sm" disabled title="Select a card first">Open in ComfyUI</button>
<button id="wfm-list-open-comfyui-btn" class="wfm-btn wfm-btn-sm" disabled title="Select a card first">Send to Canvas</button>
<div class="wfm-view-btns">
<button class="wfm-view-btn active" data-view="thumb" title="Thumbnail">&#8862;</button>
<button class="wfm-view-btn" data-view="table" title="Table">&#8801;</button>
@@ -209,7 +211,7 @@
<button id="wfm-models-civitai-batch-btn" class="wfm-btn wfm-btn-sm" title="Fetch CivitAI info for all models">CivitAI</button>
<span id="wfm-models-civitai-progress" style="font-size:12px;color:var(--wfm-text-secondary);"></span>
<button id="wfm-models-badge-settings-btn" class="wfm-btn wfm-btn-sm" title="Badge settings">&#9881; Badge</button>
<button id="wfm-models-select-btn" class="wfm-btn wfm-btn-sm" title="Multi-select models">Select</button>
<button id="wfm-models-select-btn" class="wfm-btn wfm-btn-sm wfm-btn-success" title="Multi-select models">Select</button>
<button id="wfm-models-batch-clear-btn" class="wfm-btn wfm-btn-sm" title="Clear all batch entries">BC</button>
<button id="wfm-models-stack-clear-btn" class="wfm-btn wfm-btn-sm" title="Clear all stack entries (Lora)">SC</button>
</div>
@@ -271,6 +273,7 @@
<button class="wfm-gen-subtab-btn" data-subtab="settings">Settings</button>
<button class="wfm-gen-subtab-btn" data-subtab="feeder">Feeder</button>
<button class="wfm-gen-subtab-btn" data-subtab="batch">Batch</button>
<button id="wfm-gen-save-btn" class="wfm-btn wfm-btn-sm wfm-btn-primary" style="margin-left:auto;" title="Save current workflow to Workflow tab">Save</button>
</div>
<!-- Tab: Input — left sub-col: Prompt/Image (tabbed), right sub-col: Raw JSON -->
@@ -919,6 +922,7 @@
<button class="wfm-help-nav-item" data-help-page="models">Models Tab</button>
<button class="wfm-help-nav-item" data-help-page="sidepanel">Library (Side Panel)</button>
<button class="wfm-help-nav-item" data-help-page="aitool">AI TOOL Tab</button>
<button class="wfm-help-nav-item" data-help-page="tagger">Tagger Tab</button>
<button class="wfm-help-nav-item" data-help-page="shortcuts">Keyboard Shortcuts</button>
<button class="wfm-help-nav-item" data-help-page="trouble">Troubleshooting</button>
</div>
@@ -949,7 +953,7 @@
<li id="wfm-help-wf-3">Create, rename, delete groups and assign/remove workflows</li>
<li id="wfm-help-wf-4">Import JSON/PNG files via button or drag &amp; drop</li>
<li id="wfm-help-wf-5">Side panel: thumbnail, JSON viewer (format badge: UI/API/App), clipboard copy, group management</li>
<li id="wfm-help-wf-6">Detail modal: rename, favorite, thumbnail change, badge assignment, tags, memo, AI summary, open in ComfyUI, load in GenerateUI, set as default, delete</li>
<li id="wfm-help-wf-6">Detail modal: rename, favorite, thumbnail change, badge assignment, tags, memo, AI summary, send to canvas, load in GenerateUI, set as default, delete</li>
<li id="wfm-help-wf-7">Badge management: add, rename, delete badges with custom colors shared with the Models tab (⚙ Badge button)</li>
</ul>
</div>
@@ -960,7 +964,7 @@
<h3>GenerateUI Tab</h3>
<ul>
<li id="wfm-help-gen-1">Connect/disconnect ComfyUI and check connection status</li>
<li id="wfm-help-gen-2">Load workflows from Workflow tab (App format .app.json not supported); Reset Workflow button re-reads the current workflow file from disk and reloads the editor</li>
<li id="wfm-help-gen-2">Load workflows from Workflow tab (App format .app.json not supported); Reset Workflow button re-reads the current workflow file from disk and reloads the editor; <b>Save</b> button (right end of the tab bar) saves the current workflow — including any edits made in the editor — as a new .json file to the Workflow tab; a filename dialog appears with the current workflow name as the default</li>
<li id="wfm-help-gen-3">5-tab layout — Input (Prompt + Image), Model, Settings, Feeder, Batch — Input/Model/Settings each include a Raw JSON column for instant preview and direct editing</li>
<li id="wfm-help-gen-4">Input tab: inner tabs — Prompt (positive/negative textboxes with doubled height) and Image (drag-and-drop upload); switch between tabs with the tab bar at the top of the left column</li>
<li id="wfm-help-gen-5">Model tab: Checkpoint, VAE, LoRA, ControlNet, UNET, TextEncoder selectors with filter; LoRA Stack — Apply writes all active LoRAs to the target node and simultaneously inserts LoRA syntax and CivitAI trigger words into the Positive prompt; re-applying updates the prompt by removing inactive LoRAs and re-adding active ones</li>
@@ -1073,10 +1077,13 @@
<li id="wfm-help-gallery-5">Folder tree: click to load images, expand with ▶; "+ New" creates a subfolder inside the selected folder, "Del" deletes it with all contents</li>
<li id="wfm-help-gallery-6">Multi-select with Ctrl+click — bulk operations: Add to Group, Favorite All, Unfavorite All, Move To..., Delete</li>
<li id="wfm-help-gallery-7">Detail panel — Info tab: filename, size, date, tags (add/remove), memo; "Move To..." moves the image to another folder, "Delete" removes it permanently</li>
<li id="wfm-help-gallery-8">Detail panel — Metadata tab: displays workflow JSON from PNG embedded data (prompt / workflow keys) or from metadata saved by the Generate UI tab; one-click clipboard copy</li>
<li id="wfm-help-gallery-8">Detail panel — JSON tab: displays workflow JSON from PNG embedded data (prompt / workflow keys) or from metadata saved by the Generate UI tab; 'Copy &amp; Send Canvas' button copies to clipboard and stores the workflow for title-drag to canvas</li>
<li id="wfm-help-gallery-9">Detail panel — Groups tab: create, assign, remove, rename, and delete groups per image</li>
<li id="wfm-help-gallery-10">Workflow auto-save: images generated in the Generate UI tab automatically have their workflow saved to gallery metadata and shown in the Metadata tab</li>
<li id="wfm-help-gallery-10">Workflow auto-save: images generated in the Generate UI tab automatically have their workflow saved to gallery metadata and shown in the JSON tab</li>
<li id="wfm-help-gallery-11">Supports PNG (tEXt/iTXt), JPEG, WebP, GIF; workflow extraction reads ComfyUI prompt and workflow keys embedded in PNG metadata</li>
<li id="wfm-help-gallery-12"><b>Metadata</b> button (green, in the detail panel tab bar): opens the selected image in the Metadata tab for full embedded-data inspection; Alt+click on any image thumbnail has the same effect</li>
<li id="wfm-help-gallery-13"><b>Load GenUI</b> button (blue, in the detail panel tab bar): loads the embedded ComfyUI workflow from the selected image directly into the GenerateUI tab and switches to it; shows a warning toast if no workflow is embedded or the format is not supported</li>
<li id="wfm-help-gallery-14"><b>Tagger</b> button (purple, in the detail panel action row): opens the selected image directly in the Tagger tab's Single mode for instant tagging</li>
</ul>
</div>
</div>
@@ -1086,16 +1093,17 @@
<h3>Models Tab</h3>
<ul>
<li id="wfm-help-models-1">Browse installed models: Checkpoint, LoRA, VAE, ControlNet, UNET, TextEncoder, Hypernetwork, Embedding with sub-tab switching</li>
<li id="wfm-help-models-2">Thumbnail, Card, and Table view modes with pagination</li>
<li id="wfm-help-models-2">Thumbnail and Table view modes with pagination; Table view shows Type and Base Model columns sourced from CivitAI data alongside filename, subdirectory, and extension; <b>column headers are clickable to sort</b> — click once for ascending (▲), again for descending (▼), a third time to clear the sort; the <b>E/D</b> column sorts by enable/disable status</li>
<li id="wfm-help-models-3">Search, tag filter, group filter, favorites filter, and status filter (All / Enabled only / Disabled only)</li>
<li id="wfm-help-models-4">Side panel: opens to CivitAI tab by default when a model is selected; Info (file path, tags, memo), Groups management, CivitAI integration</li>
<li id="wfm-help-models-5">CivitAI integration: fetch model info by SHA256 hash, batch fetch per model type</li>
<li id="wfm-help-models-6">Detail modal: preview image, CivitAI info (base model, trained words, tags), thumbnail change — upload any image format to replace the preview; changes take effect immediately without restarting ComfyUI; broken/empty preview files are automatically skipped</li>
<li id="wfm-help-models-7">Group management: create, rename, delete groups and assign/remove models</li>
<li id="wfm-help-models-6">Detail modal: preview image, CivitAI info (base model, trained words, tags), thumbnail change — upload any image format to replace the preview; changes take effect immediately without restarting ComfyUI; broken/empty preview files are automatically skipped; Delete button permanently removes the model file and all associated sidecar files</li>
<li id="wfm-help-models-7">Group management: create, rename, delete groups and assign/remove models; Checkpoint and LoRA tabs support B (Batch) and S (Stack) quick-assign buttons per model in both card and table views</li>
<li id="wfm-help-models-8">GenUI Model button: apply the selected model to the corresponding node in GenerateUI's current workflow (Checkpoint / LoRA / VAE / ControlNet / UNET / TextEncoder)</li>
<li id="wfm-help-models-9">User-defined badges: assign free-label badges with custom colors shared with the Workflow tab</li>
<li id="wfm-help-models-10">Enable/Disable models: toggle visibility in ComfyUI by renaming file extension (.disabled suffix). Disable per model (⏸ button on each card) or per group (Enable All / Disable All in Group panel). Changes take effect after ComfyUI refresh.</li>
<li id="wfm-help-models-11">Multi-select &amp; bulk operations: click Select to enter selection mode, then check multiple models; the bulk action bar provides: Deselect All — clear all selections without exiting select mode; ★ Favorite / ☆ Unfavorite — toggle favorites for all selected models; Add to Group / Remove from Group — assign or remove from an existing group; Create &amp; Add — type a new group name and add all selected; +Badge / −Badge — apply or remove a badge from all selected; Delete Files — permanently remove model files, preview images, and sidecar files (.json/.info)</li>
<li id="wfm-help-models-11">Multi-select &amp; bulk operations: click Select (green) to enter selection mode, then check multiple models; the bulk action bar is organized into three rows — <b>Group row:</b> select an existing group and Add/Remove, or type a new name and Create &amp; Add; <b>Badge row:</b> select a badge and +Badge / −Badge to apply or remove; <b>File row:</b> select a destination subfolder (or type a new folder name) and Move to relocate model files with all sidecar files (.preview.png, .json, .civitai.info, etc.), Delete Files to permanently remove selected models; header row provides Deselect All and ★/☆ Favorite toggles</li>
<li id="wfm-help-models-12">After moving or deleting models, ComfyUI may fail to load them because it caches the old file paths. Perform a Hard Reset from the ComfyUI menu (Queue → Hard Reset) or restart ComfyUI to refresh the model cache.</li>
</ul>
</div>
</div>
@@ -1119,7 +1127,8 @@
<li id="wfm-help-sidepanel-13">I tab (Information): drop a ComfyUI PNG/WebP/JSON to inspect model, LoRA, and prompt metadata in the side panel — sub-tabs: model / lora / Prompts; supports UnetLoaderGGUF and QuadrupleCLIPLoader node types</li>
<li id="wfm-help-sidepanel-14">Information tab — drag items to canvas: model sub-tab places the loader node (Checkpoint → CheckpointLoaderSimple, VAE → VAELoader, Diffusion Model → UNETLoader, Text Encoder → CLIPLoader); double-click also places at canvas center</li>
<li id="wfm-help-sidepanel-15">Information tab — LoRA sub-tab: drag individual LoRA to place LoraLoader; "Multiple LORA" section at bottom places all LoRAs in a single Lora Loader (LoraManager) node; Prompts sub-tab: drag a prompt to place CLIPTextEncode node with text pre-filled; click prompt to view full text and copy</li>
<li id="wfm-help-sidepanel-16">AI TOOL tab: Translation and TOOLS (VLM) panes powered by Ollama or LM Studio; 3-pane layout (Translation | TOOLS | Settings) always visible; settings (backend, URL, model) are shared with the SPA AI TOOL tab via localStorage</li>
<li id="wfm-help-sidepanel-16">AI TOOL tab: Translation, Chat, TOOLS, and Settings sub-tabs powered by Ollama or LM Studio; Chat supports multi-turn conversations; TOOLS includes VLM image analysis and wildcard generation; settings shared with the SPA AI TOOL tab via localStorage</li>
<li id="wfm-help-sidepanel-17">Title drag (Send to Canvas): after clicking 'Send to Canvas' (Workflow tab) or 'Copy &amp; Send Canvas' (Gallery tab), the 'Workflow Studio Library' title turns blue with a green ● — drag it onto the canvas to load the workflow; title resets automatically after loading</li>
</ul>
</div>
</div>
@@ -1128,11 +1137,29 @@
<div class="wfm-help-card">
<h3 id="wfm-help-ai-title">AI TOOL Tab</h3>
<ul>
<li id="wfm-help-ai-1">3-pane layout — Translation (40%) | TOOLS (40%) | Settings (20%) — all panes are always visible simultaneously</li>
<li id="wfm-help-ai-2">Translation pane: translate text between Japanese, English, Chinese, or a custom Free language using Ollama or LM Studio; language selectors with ⇄ swap button; text content is also swapped on swap; selections are saved automatically</li>
<li id="wfm-help-ai-3">TOOLS pane (VLM): drop an image into the drop zone and select a task — Describe Image or Create Prompt — then click Run to analyze with a vision model; result displayed with Copy button</li>
<li id="wfm-help-ai-4">Settings pane: choose backend (Ollama / LM Studio), set the API URL, test connection, select model, and configure Free language names for translation</li>
<li id="wfm-help-ai-5">Settings are saved to localStorage and shared with the Library panel's AI TOOL tab</li>
<li id="wfm-help-ai-1">4-pane layout — Translation | Chat | TOOLS | Settings — all panes are always visible simultaneously</li>
<li id="wfm-help-ai-2">Translation pane: translate text between Japanese, English, Chinese, or a custom Free language using Ollama or LM Studio; ⇄ swap button swaps both language selectors and text content; selections are saved automatically</li>
<li id="wfm-help-ai-3">Chat pane: multi-turn conversation with the LLM; Enter to send a message, Shift+Enter for a newline; Clear button resets the conversation history</li>
<li id="wfm-help-ai-4">TOOLS pane — VLM: drop an image (PNG/JPG/WebP) and select a task (Describe Image, Create Prompt, Create Tags), then click Run to analyze with a vision model; result shown with Copy button</li>
<li id="wfm-help-ai-5">TOOLS pane — Wildcards: select "Create wildcards" from the dropdown, enter a category name and count, click Run to generate plain-text wildcard entries one per line</li>
<li id="wfm-help-ai-6">Settings pane: choose backend (Ollama / LM Studio), set API URL, test connection, select model, configure Free language names; settings are shared with the Library panel's A tab via localStorage</li>
</ul>
</div>
</div>
<div class="wfm-help-page" id="wfm-help-page-tagger">
<div class="wfm-help-card">
<h3 id="wfm-help-tagger-title">Tagger Tab</h3>
<ul>
<li id="wfm-help-tagger-1"></li>
<li id="wfm-help-tagger-2"></li>
<li id="wfm-help-tagger-3"></li>
<li id="wfm-help-tagger-4"></li>
<li id="wfm-help-tagger-5"></li>
<li id="wfm-help-tagger-6"></li>
<li id="wfm-help-tagger-7"></li>
<li id="wfm-help-tagger-8"></li>
<li id="wfm-help-tagger-9"></li>
</ul>
</div>
</div>
@@ -1158,6 +1185,8 @@
<li id="wfm-help-trouble-3">Workflows not showing: Click refresh button, check if loadable in ComfyUI, try restarting browser/ComfyUI</li>
<li id="wfm-help-trouble-4">Image generation fails: Check if specified models exist in ComfyUI, verify connection, try restarting</li>
<li id="wfm-help-trouble-5">LoRA Stack fails with "No such file or directory" error: The LoRA may not be recognized by comfyui-lora-manager (known issue). Try a different LoRA or check if the file appears in Lora Manager's own UI</li>
<li id="wfm-help-trouble-6">Model loading error after moving or deleting models: ComfyUI caches file paths and may still reference old locations. Perform a Hard Reset from the ComfyUI menu (Queue → Hard Reset) or restart ComfyUI to clear the cache.</li>
<li id="wfm-help-trouble-7"></li>
</ul>
</div>
</div>
@@ -1219,15 +1248,16 @@
<!-- 複数選択時の一括操作バー -->
<div id="wfm-gallery-bulk-bar" class="wfm-gallery-bulk-bar" style="display:none;">
<span id="wfm-gallery-bulk-count" class="wfm-gallery-bulk-count"></span>
<button id="wfm-gallery-bulk-deselect" class="wfm-btn wfm-btn-sm">Deselect All</button>
<button id="wfm-gallery-bulk-deselect" class="wfm-btn wfm-btn-sm"></button>
<button id="wfm-gallery-bulk-select-all" class="wfm-btn wfm-btn-sm"></button>
<select id="wfm-gallery-bulk-group-select" class="wfm-select" style="font-size:12px;padding:3px 6px;">
<option value="">Add to Group...</option>
<option value=""></option>
</select>
<button id="wfm-gallery-bulk-group-add" class="wfm-btn wfm-btn-sm wfm-btn-primary">Add</button>
<button id="wfm-gallery-bulk-fav" class="wfm-btn wfm-btn-sm">★ Favorite All</button>
<button id="wfm-gallery-bulk-unfav" class="wfm-btn wfm-btn-sm">☆ Unfavorite All</button>
<button id="wfm-gallery-bulk-move" class="wfm-btn wfm-btn-sm">Move To...</button>
<button id="wfm-gallery-bulk-delete" class="wfm-btn wfm-btn-sm wfm-btn-danger">Delete</button>
<button id="wfm-gallery-bulk-group-add" class="wfm-btn wfm-btn-sm wfm-btn-primary"></button>
<button id="wfm-gallery-bulk-fav" class="wfm-btn wfm-btn-sm"></button>
<button id="wfm-gallery-bulk-unfav" class="wfm-btn wfm-btn-sm"></button>
<button id="wfm-gallery-bulk-move" class="wfm-btn wfm-btn-sm"></button>
<button id="wfm-gallery-bulk-delete" class="wfm-btn wfm-btn-sm wfm-btn-danger"></button>
</div>
</div>
@@ -1266,9 +1296,14 @@
<!-- タブナビ -->
<div class="wfm-side-tab-nav">
<button class="wfm-gallery-detail-tab-btn active" data-detail-tab="info">Info</button>
<button class="wfm-gallery-detail-tab-btn" data-detail-tab="meta">Metadata</button>
<button class="wfm-gallery-detail-tab-btn" data-detail-tab="meta">JSON</button>
<button class="wfm-gallery-detail-tab-btn" data-detail-tab="group">Groups</button>
</div>
<div class="wfm-gallery-detail-action-row">
<button id="wfm-gallery-open-metadata-btn" class="wfm-gallery-action-btn wfm-gallery-action-btn-green" title="Open in Metadata tab (or Alt+click image)">Metadata</button>
<button id="wfm-gallery-load-genui-btn" class="wfm-gallery-action-btn wfm-gallery-action-btn-primary" title="Load workflow into GenerateUI">Load GenUI</button>
<button id="wfm-gallery-open-tagger-btn" class="wfm-gallery-action-btn wfm-gallery-action-btn-tagger" title="Open in Tagger"></button>
</div>
<!-- Info タブ -->
<div id="wfm-gallery-detail-info" class="wfm-gallery-detail-tab-content active">
<div class="wfm-gallery-info-section">
@@ -1304,7 +1339,7 @@
<div id="wfm-gallery-detail-meta" class="wfm-gallery-detail-tab-content wfm-gallery-meta-tab" style="display:none;">
<div class="wfm-gallery-meta-toolbar">
<span id="wfm-gallery-meta-status" class="wfm-gallery-meta-status"></span>
<button id="wfm-gallery-copy-workflow-btn" class="wfm-btn wfm-btn-sm wfm-btn-primary" disabled title="Copy embedded workflow JSON">Copy Workflow</button>
<button id="wfm-gallery-copy-workflow-btn" class="wfm-btn wfm-btn-sm wfm-btn-primary" disabled title="Copy to clipboard and send to canvas">Copy &amp; Send Canvas</button>
</div>
<pre id="wfm-gallery-workflow-json" class="wfm-gallery-workflow-json">No workflow found in this image.</pre>
</div>
@@ -1317,6 +1352,226 @@
</div>
</section>
<!-- Tagger Tab -->
<section id="wfm-tab-tagger" class="wfm-tab-content">
<div class="wfm-tagger-subtab-nav">
<button class="wfm-tagger-subtab-btn active" data-tagger-tab="single"></button>
<button class="wfm-tagger-subtab-btn" data-tagger-tab="batch"></button>
<button class="wfm-tagger-subtab-btn" data-tagger-tab="db"></button>
</div>
<!-- Single サブタブ -->
<div id="wfm-tagger-single" class="wfm-tagger-subtab">
<div class="wfm-tagger-single-layout">
<!-- 左: 画像 -->
<div class="wfm-tagger-image-pane">
<div class="wfm-tagger-image-sources">
<label class="wfm-btn wfm-btn-sm" style="cursor:pointer">
<span id="wfm-tagger-upload-label"></span>
<input type="file" id="wfm-tagger-upload" accept="image/*" style="display:none">
</label>
</div>
<div class="wfm-tagger-preview-wrap" id="wfm-tagger-drop-zone">
<img id="wfm-tagger-preview" style="display:none; max-width:100%; max-height:100%; object-fit:contain;">
<div id="wfm-tagger-preview-placeholder" class="wfm-placeholder"></div>
</div>
<div id="wfm-tagger-image-name" class="wfm-tagger-image-name"></div>
</div>
<!-- 右: 設定・結果 -->
<div class="wfm-tagger-controls-pane">
<!-- WD Tagger -->
<div class="wfm-tagger-section">
<div class="wfm-tagger-section-header">WD Tagger / DeepDanbooru</div>
<div class="wfm-form-row wfm-tagger-form-row">
<label class="wfm-tagger-label"></label>
<select id="wfm-tagger-model" class="wfm-select wfm-tagger-select"></select>
</div>
<div class="wfm-form-row wfm-tagger-form-row">
<label class="wfm-tagger-label" id="wfm-tagger-threshold-label"></label>
<input type="range" id="wfm-tagger-threshold" min="0" max="1" step="0.01" value="0.35" class="wfm-tagger-slider">
<span id="wfm-tagger-threshold-val" class="wfm-tagger-slider-val">0.35</span>
</div>
<div class="wfm-form-row wfm-tagger-form-row">
<label class="wfm-tagger-label" id="wfm-tagger-char-threshold-label"></label>
<input type="range" id="wfm-tagger-char-threshold" min="0" max="1" step="0.01" value="0.85" class="wfm-tagger-slider">
<span id="wfm-tagger-char-threshold-val" class="wfm-tagger-slider-val">0.85</span>
</div>
<button id="wfm-tagger-generate-btn" class="wfm-btn wfm-btn-primary" style="width:100%;margin-top:6px;"></button>
</div>
<!-- Ollama VLM -->
<div class="wfm-tagger-section">
<div class="wfm-tagger-section-header">
<label style="display:flex;align-items:center;gap:6px;cursor:pointer;font-weight:600;">
<input type="checkbox" id="wfm-tagger-ollama-enable">
<span id="wfm-tagger-ollama-header-label">Ollama VLM</span>
</label>
</div>
<div id="wfm-tagger-ollama-settings" style="display:none">
<div class="wfm-form-row wfm-tagger-form-row">
<label class="wfm-tagger-label" id="wfm-tagger-ollama-url-label"></label>
<input type="text" id="wfm-tagger-ollama-url" class="wfm-search-input" value="http://127.0.0.1:11434" style="flex:1;">
</div>
<div class="wfm-form-row wfm-tagger-form-row">
<label class="wfm-tagger-label" id="wfm-tagger-ollama-model-label"></label>
<select id="wfm-tagger-ollama-model" class="wfm-select wfm-tagger-select"></select>
<button id="wfm-tagger-ollama-refresh-btn" class="wfm-btn wfm-btn-sm" title="Refresh models">↻</button>
</div>
<div class="wfm-form-row wfm-tagger-form-row" style="align-items:flex-start">
<label class="wfm-tagger-label" id="wfm-tagger-ollama-prompt-label" style="padding-top:4px;"></label>
<textarea id="wfm-tagger-ollama-prompt" class="wfm-textarea" rows="3" style="flex:1;resize:vertical;">Output danbooru-style, comma-separated, English tags for this image. ONLY output the tags. Do not use double quotes or hyphens in the tags.</textarea>
</div>
<div class="wfm-form-row wfm-tagger-form-row">
<label class="wfm-tagger-label" id="wfm-tagger-ollama-max-label"></label>
<input type="number" id="wfm-tagger-ollama-max-tags" class="wfm-search-input" value="40" min="1" max="500" style="width:70px;">
</div>
</div>
</div>
<!-- 結果 -->
<div class="wfm-tagger-section">
<div class="wfm-tagger-section-header" id="wfm-tagger-result-header"></div>
<textarea id="wfm-tagger-result" class="wfm-textarea" rows="5" style="width:100%;resize:vertical;" placeholder="Tags will appear here..."></textarea>
<div class="wfm-tagger-result-actions">
<button id="wfm-tagger-send-genui-btn" class="wfm-btn wfm-btn-sm"></button>
<button id="wfm-tagger-send-prompt-btn" class="wfm-btn wfm-btn-sm"></button>
<button id="wfm-tagger-save-gallery-btn" class="wfm-btn wfm-btn-sm"></button>
<button id="wfm-tagger-write-file-btn" class="wfm-btn wfm-btn-sm"></button>
<button id="wfm-tagger-save-db-btn" class="wfm-btn wfm-btn-sm"></button>
</div>
</div>
</div>
</div>
</div>
<!-- Batch サブタブ -->
<div id="wfm-tagger-batch" class="wfm-tagger-subtab" style="display:none">
<div class="wfm-tagger-batch-layout">
<div class="wfm-tagger-section">
<div class="wfm-tagger-section-header" id="wfm-tagger-batch-folder-header"></div>
<div class="wfm-form-row wfm-tagger-form-row">
<input type="text" id="wfm-tagger-batch-folder" class="wfm-search-input" style="flex:1;" placeholder="C:\path\to\images">
</div>
</div>
<div class="wfm-tagger-batch-cols">
<!-- WD Tagger 設定 -->
<div class="wfm-tagger-section">
<div class="wfm-tagger-section-header">WD Tagger / DeepDanbooru</div>
<div class="wfm-form-row wfm-tagger-form-row">
<label class="wfm-tagger-label"></label>
<select id="wfm-tagger-batch-model" class="wfm-select wfm-tagger-select"></select>
</div>
<div class="wfm-form-row wfm-tagger-form-row">
<label class="wfm-tagger-label" id="wfm-tagger-batch-threshold-label"></label>
<input type="range" id="wfm-tagger-batch-threshold" min="0" max="1" step="0.01" value="0.35" class="wfm-tagger-slider">
<span id="wfm-tagger-batch-threshold-val" class="wfm-tagger-slider-val">0.35</span>
</div>
<div class="wfm-form-row wfm-tagger-form-row">
<label class="wfm-tagger-label" id="wfm-tagger-batch-char-threshold-label"></label>
<input type="range" id="wfm-tagger-batch-char-threshold" min="0" max="1" step="0.01" value="0.85" class="wfm-tagger-slider">
<span id="wfm-tagger-batch-char-threshold-val" class="wfm-tagger-slider-val">0.85</span>
</div>
</div>
<!-- Ollama 設定 -->
<div class="wfm-tagger-section">
<div class="wfm-tagger-section-header">
<label style="display:flex;align-items:center;gap:6px;cursor:pointer;font-weight:600;">
<input type="checkbox" id="wfm-tagger-batch-ollama-enable">
Ollama VLM
</label>
</div>
<div id="wfm-tagger-batch-ollama-settings">
<div class="wfm-form-row wfm-tagger-form-row">
<label class="wfm-tagger-label" id="wfm-tagger-batch-url-label"></label>
<input type="text" id="wfm-tagger-batch-ollama-url" class="wfm-search-input" value="http://127.0.0.1:11434" style="flex:1;">
</div>
<div class="wfm-form-row wfm-tagger-form-row">
<label class="wfm-tagger-label" id="wfm-tagger-batch-model-label"></label>
<select id="wfm-tagger-batch-ollama-model" class="wfm-select wfm-tagger-select"></select>
<button id="wfm-tagger-batch-ollama-refresh-btn" class="wfm-btn wfm-btn-sm">↻</button>
</div>
<div class="wfm-form-row wfm-tagger-form-row" style="align-items:flex-start">
<label class="wfm-tagger-label" id="wfm-tagger-batch-prompt-label" style="padding-top:4px;"></label>
<textarea id="wfm-tagger-batch-ollama-prompt" class="wfm-textarea" rows="3" style="flex:1;resize:vertical;">Output danbooru-style, comma-separated, English tags for this image. ONLY output the tags.</textarea>
</div>
</div>
</div>
</div>
<!-- 出力設定 -->
<div class="wfm-tagger-section">
<div class="wfm-tagger-section-header" id="wfm-tagger-batch-output-header"></div>
<div style="display:flex;gap:16px;">
<label style="display:flex;align-items:center;gap:6px;cursor:pointer;">
<input type="checkbox" id="wfm-tagger-batch-save-db" checked>
<span id="wfm-tagger-batch-save-db-label"></span>
</label>
<label style="display:flex;align-items:center;gap:6px;cursor:pointer;">
<input type="checkbox" id="wfm-tagger-batch-write-file">
<span id="wfm-tagger-batch-write-file-label"></span>
</label>
<label style="display:flex;align-items:center;gap:6px;cursor:pointer;">
<input type="checkbox" id="wfm-tagger-batch-write-txt">
<span id="wfm-tagger-batch-write-txt-label"></span>
</label>
</div>
</div>
<!-- ボタン + プログレス -->
<div style="display:flex;gap:8px;align-items:center;margin-bottom:8px;">
<button id="wfm-tagger-batch-start-btn" class="wfm-btn wfm-btn-primary"></button>
<button id="wfm-tagger-batch-stop-btn" class="wfm-btn wfm-btn-danger" disabled></button>
<span id="wfm-tagger-batch-progress-text" style="font-size:12px;color:var(--wfm-text-muted);"></span>
</div>
<div class="wfm-tagger-progress-bar-wrap">
<div id="wfm-tagger-batch-progress-bar" class="wfm-tagger-progress-bar" style="width:0%"></div>
</div>
<textarea id="wfm-tagger-batch-log" class="wfm-textarea" rows="10" readonly style="width:100%;margin-top:8px;font-family:monospace;font-size:11px;"></textarea>
</div>
</div>
<!-- DB サブタブ -->
<div id="wfm-tagger-db" class="wfm-tagger-subtab" style="display:none">
<div class="wfm-tagger-db-layout">
<div class="wfm-tagger-db-toolbar">
<input type="text" id="wfm-tagger-db-search-input" class="wfm-search-input" style="flex:1;" placeholder="Search tags or filename...">
<button id="wfm-tagger-db-search-btn" class="wfm-btn wfm-btn-sm wfm-btn-primary"></button>
<button id="wfm-tagger-db-show-all-btn" class="wfm-btn wfm-btn-sm"></button>
<button id="wfm-tagger-db-export-btn" class="wfm-btn wfm-btn-sm"></button>
</div>
<div id="wfm-tagger-db-table-wrap" class="wfm-tagger-db-table-wrap">
<table id="wfm-tagger-db-table" class="wfm-table wfm-tagger-db-table">
<thead>
<tr>
<th>ID</th>
<th id="wfm-tagger-db-th-file"></th>
<th id="wfm-tagger-db-th-interrogator"></th>
<th id="wfm-tagger-db-th-vlm"></th>
<th id="wfm-tagger-db-th-date"></th>
</tr>
</thead>
<tbody id="wfm-tagger-db-tbody"></tbody>
</table>
</div>
<!-- 編集パネル -->
<div id="wfm-tagger-db-edit-panel" class="wfm-tagger-db-edit-panel" style="display:none">
<div class="wfm-tagger-section-header" id="wfm-tagger-db-edit-header"></div>
<div class="wfm-form-row wfm-tagger-form-row">
<label class="wfm-tagger-label" id="wfm-tagger-db-edit-interr-label"></label>
<textarea id="wfm-tagger-db-edit-interrogator" class="wfm-textarea" rows="3" style="flex:1;resize:vertical;"></textarea>
</div>
<div class="wfm-form-row wfm-tagger-form-row">
<label class="wfm-tagger-label" id="wfm-tagger-db-edit-vlm-label"></label>
<textarea id="wfm-tagger-db-edit-vlm" class="wfm-textarea" rows="3" style="flex:1;resize:vertical;"></textarea>
</div>
<div style="display:flex;gap:8px;margin-top:6px;">
<button id="wfm-tagger-db-save-btn" class="wfm-btn wfm-btn-sm wfm-btn-primary"></button>
<button id="wfm-tagger-db-delete-btn" class="wfm-btn wfm-btn-sm wfm-btn-danger"></button>
</div>
</div>
</div>
</div>
</section>
<!-- AI Tab -->
<section id="wfm-tab-ai" class="wfm-tab-content">
<!-- Translation pane -->
@@ -1348,6 +1603,22 @@
</div>
</div>
<div class="wfm-ai-pane-divider"></div>
<!-- Chat pane -->
<div class="wfm-ai-pane wfm-ai-pane-chat">
<div class="wfm-ai-pane-header">Chat</div>
<div class="wfm-ai-chat-container">
<div class="wfm-ai-chat-messages" id="wfm-ai-chat-messages"></div>
<div class="wfm-ai-chat-input-area">
<textarea id="wfm-ai-chat-input" class="wfm-ai-chat-input" placeholder="Type a message... (Enter to send, Shift+Enter for newline)"></textarea>
<div class="wfm-ai-chat-actions">
<button id="wfm-ai-chat-send-btn" class="wfm-btn wfm-btn-primary">Send</button>
<button id="wfm-ai-chat-clear-btn" class="wfm-btn">Clear</button>
<span id="wfm-ai-chat-status" class="wfm-ai-trans-status"></span>
</div>
</div>
</div>
</div>
<div class="wfm-ai-pane-divider"></div>
<!-- TOOLS pane -->
<div class="wfm-ai-pane wfm-ai-pane-tools">
<div class="wfm-ai-pane-header">TOOLS</div>
@@ -1357,11 +1628,22 @@
<span id="wfm-ai-vlm-label" class="wfm-ai-vlm-label">Drop or click PNG / JPG / WebP</span>
<input type="file" id="wfm-ai-vlm-file" accept="image/png,image/jpeg,image/webp" style="display:none;">
</div>
<div class="wfm-ai-wc-inputs" id="wfm-ai-wc-inputs" style="display:none">
<div class="wfm-ai-wc-row">
<label class="wfm-ai-label">Name</label>
<input type="text" id="wfm-ai-wc-name" class="wfm-input" placeholder="e.g. sports, emotions, colors">
</div>
<div class="wfm-ai-wc-row">
<label class="wfm-ai-label">Count</label>
<input type="number" id="wfm-ai-wc-count" class="wfm-input wfm-ai-wc-count" value="20" min="1" max="200">
</div>
</div>
<div class="wfm-ai-vlm-task-row">
<select id="wfm-ai-vlm-task" class="wfm-select">
<option value="describe">Describe image</option>
<option value="prompt">Create prompt</option>
<option value="tags">Create tags</option>
<option value="wildcard">Create wildcards</option>
</select>
<button id="wfm-ai-vlm-run" class="wfm-btn wfm-btn-primary">Run</button>
</div>
+244 -5
View File
@@ -61,7 +61,7 @@ const state = {
infoSubTab: "info-model", // "info-model" | "info-lora" | "info-prompt"
infoMeta: null, // parsed metadata from dropped file
// AI tab
aiSubTab: "ai-translate", // "ai-translate" | "ai-vlm" | "ai-settings"
aiSubTab: "ai-translate", // "ai-translate" | "ai-chat" | "ai-vlm" | "ai-settings"
};
// ============================================
@@ -548,7 +548,8 @@ const installCanvasDropHandler = () => {
e.dataTransfer.types.includes("application/x-wfm-prompt") ||
e.dataTransfer.types.includes("application/x-wfm-model") ||
e.dataTransfer.types.includes("application/x-wfm-lora-multi") ||
e.dataTransfer.types.includes("application/x-wfm-clip-text")) {
e.dataTransfer.types.includes("application/x-wfm-clip-text") ||
e.dataTransfer.types.includes("application/x-wfm-pending")) {
e.preventDefault();
e.dataTransfer.dropEffect = "copy";
}
@@ -595,6 +596,29 @@ const installCanvasDropHandler = () => {
return;
}
// Handle pending workflow drop (from Gallery / Workflow tab "Send to Canvas")
const pendingRaw = e.dataTransfer.getData("application/x-wfm-pending");
if (pendingRaw) {
e.preventDefault();
try {
const wfData = JSON.parse(pendingRaw);
app.loadGraphData(wfData);
localStorage.removeItem("wfm_pending_workflow");
if (panelEl) {
const titleEl = panelEl.querySelector(".wfm-nlp-title");
if (titleEl) {
titleEl.draggable = false;
titleEl.classList.remove("wfm-nlp-title-pending");
titleEl.title = "Workflow Studio Library";
}
}
showToast("Workflow loaded on canvas", "success");
} catch (err) {
showToast("Failed to load workflow: " + err.message, "error");
}
return;
}
// Handle workflow drop
const wfRaw = e.dataTransfer.getData("application/x-wfm-workflow");
if (wfRaw) {
@@ -763,6 +787,28 @@ const createPanel = () => {
});
});
// Pending workflow drag-to-canvas
const titleEl = panel.querySelector(".wfm-nlp-title");
const updateTitlePendingState = () => {
const hasPending = !!localStorage.getItem("wfm_pending_workflow");
titleEl.draggable = hasPending;
titleEl.classList.toggle("wfm-nlp-title-pending", hasPending);
titleEl.title = hasPending
? "Drag to canvas to load workflow"
: "Workflow Studio Library";
};
updateTitlePendingState();
panel.addEventListener("mouseenter", updateTitlePendingState);
window.addEventListener("storage", (e) => {
if (e.key === "wfm_pending_workflow") updateTitlePendingState();
});
titleEl.addEventListener("dragstart", (e) => {
const pendingRaw = localStorage.getItem("wfm_pending_workflow");
if (!pendingRaw) { e.preventDefault(); return; }
e.dataTransfer.effectAllowed = "copy";
e.dataTransfer.setData("application/x-wfm-pending", pendingRaw);
});
// Close
panel.querySelector(".wfm-nlp-close").addEventListener("click", () => togglePanel());
@@ -833,6 +879,7 @@ const rebuildSubTabs = () => {
if (state.topTab === "ai") {
const row1Tabs = [
{ key: "ai-translate", label: "Translation" },
{ key: "ai-chat", label: "Chat" },
{ key: "ai-vlm", label: "TOOLS" },
{ key: "ai-settings", label: "Settings" },
];
@@ -2959,6 +3006,24 @@ async function aiCallVLM(url, backend, model, prompt, base64Image, mimeType) {
}
}
async function aiCallChat(url, backend, model, messages) {
if (backend === "ollama") {
const r = await fetch(`${url}/api/chat`, {
method: "POST", headers: { "Content-Type": "application/json" },
body: JSON.stringify({ model, messages, stream: false }),
});
if (!r.ok) throw new Error(`HTTP ${r.status}`);
return (await r.json()).message?.content || "";
} else {
const r = await fetch(`${url}/v1/chat/completions`, {
method: "POST", headers: { "Content-Type": "application/json" },
body: JSON.stringify({ model, messages, stream: false }),
});
if (!r.ok) throw new Error(`HTTP ${r.status}`);
return (await r.json()).choices?.[0]?.message?.content || "";
}
}
async function aiFetchModels(url, backend) {
if (backend === "ollama") {
const r = await fetch(`${url}/api/tags`);
@@ -3000,6 +3065,16 @@ const renderAiTab = (container) => {
</div>
<textarea id="wfm-nlp-ai-output" class="wfm-nlp-ai-textarea wfm-nlp-ai-output" placeholder="Translation result..." readonly></textarea>
</div>
<!-- Chat sub -->
<div id="wfm-nlp-ai-chat" class="wfm-nlp-ai-pane" style="display:none;">
<div class="wfm-nlp-ai-chat-msgs" id="wfm-nlp-ai-chat-msgs"></div>
<textarea id="wfm-nlp-ai-chat-input" class="wfm-nlp-ai-textarea wfm-nlp-ai-chat-input" placeholder="Type a message..."></textarea>
<div class="wfm-nlp-ai-actions">
<button id="wfm-nlp-ai-chat-send" class="wfm-nlp-ai-btn wfm-nlp-ai-btn-primary">Send</button>
<button id="wfm-nlp-ai-chat-clear" class="wfm-nlp-ai-btn">Clear</button>
<span id="wfm-nlp-ai-chat-status" class="wfm-nlp-ai-status"></span>
</div>
</div>
<!-- TOOLS sub -->
<div id="wfm-nlp-ai-vlm" class="wfm-nlp-ai-pane" style="display:none;">
<div class="wfm-nlp-ai-vlm-drop" id="wfm-nlp-ai-vlm-drop">
@@ -3007,11 +3082,22 @@ const renderAiTab = (container) => {
<span id="wfm-nlp-ai-vlm-label" class="wfm-nlp-ai-vlm-label">Drop PNG / JPG / WebP</span>
<input type="file" id="wfm-nlp-ai-vlm-file" accept="image/png,image/jpeg,image/webp" style="display:none;">
</div>
<div id="wfm-nlp-ai-wc-inputs" style="display:none;flex-direction:column;gap:5px;">
<div class="wfm-nlp-ai-row">
<span class="wfm-nlp-ai-lbl">Name</span>
<input type="text" id="wfm-nlp-ai-wc-name" class="wfm-nlp-ai-input" style="flex:1;" placeholder="e.g. sports">
</div>
<div class="wfm-nlp-ai-row">
<span class="wfm-nlp-ai-lbl">Count</span>
<input type="number" id="wfm-nlp-ai-wc-count" class="wfm-nlp-ai-input wfm-nlp-ai-wc-count" value="20" min="1" max="200">
</div>
</div>
<div class="wfm-nlp-ai-row">
<select id="wfm-nlp-ai-vlm-task" class="wfm-nlp-ai-sel" style="flex:1;">
<option value="describe">Describe image</option>
<option value="prompt">Create prompt</option>
<option value="tags">Create tags</option>
<option value="wildcard">Create wildcards</option>
</select>
<button id="wfm-nlp-ai-vlm-run" class="wfm-nlp-ai-btn wfm-nlp-ai-btn-primary">Run</button>
</div>
@@ -3069,7 +3155,7 @@ const renderAiTab = (container) => {
const renderAiSubContent = () => {
if (!panelEl) return;
const panes = { "ai-translate": "wfm-nlp-ai-translate", "ai-vlm": "wfm-nlp-ai-vlm", "ai-settings": "wfm-nlp-ai-settings" };
const panes = { "ai-translate": "wfm-nlp-ai-translate", "ai-chat": "wfm-nlp-ai-chat", "ai-vlm": "wfm-nlp-ai-vlm", "ai-settings": "wfm-nlp-ai-settings" };
for (const [key, id] of Object.entries(panes)) {
const el = panelEl.querySelector(`#${id}`);
if (el) el.style.display = state.aiSubTab === key ? "flex" : "none";
@@ -3224,6 +3310,67 @@ const setupAiHandlers = (container) => {
// Auto-load models if settings exist
if (cfg.backendUrl && cfg.backend) refreshModels().catch(() => {});
// ---- Chat handlers ----
let chatHistory = [];
const chatMsgsEl = container.querySelector("#wfm-nlp-ai-chat-msgs");
const chatInputEl = container.querySelector("#wfm-nlp-ai-chat-input");
const chatSendBtn = container.querySelector("#wfm-nlp-ai-chat-send");
const chatClearBtn= container.querySelector("#wfm-nlp-ai-chat-clear");
const chatStatusEl= container.querySelector("#wfm-nlp-ai-chat-status");
const appendChatBubble = (role, content) => {
const div = document.createElement("div");
div.className = `wfm-nlp-ai-chat-msg wfm-nlp-ai-chat-msg-${role}`;
div.textContent = content;
chatMsgsEl.appendChild(div);
chatMsgsEl.scrollTop = chatMsgsEl.scrollHeight;
};
const sendChatMessage = async () => {
const text = chatInputEl?.value?.trim();
if (!text) return;
const c = loadAiCfg();
const backend = c.backend || "ollama";
const url = c.backendUrl || (backend === "ollama" ? "http://localhost:11434" : "http://localhost:1234");
const model = c.model;
if (!isValidAiUrl(url)) { showToast("URLは http:// または https:// で始まる必要があります", "error"); return; }
if (!model) { showToast("Please select a model in Settings", "error"); return; }
chatInputEl.value = "";
chatHistory.push({ role: "user", content: text });
appendChatBubble("user", text);
chatSendBtn.disabled = true;
chatStatusEl.textContent = "Thinking...";
chatStatusEl.className = "wfm-nlp-ai-status wfm-nlp-ai-working";
try {
const reply = await aiCallChat(url, backend, model, chatHistory);
chatHistory.push({ role: "assistant", content: reply });
appendChatBubble("assistant", reply);
chatStatusEl.textContent = "";
chatStatusEl.className = "wfm-nlp-ai-status";
} catch (err) {
chatHistory.pop();
if (chatMsgsEl.lastChild) chatMsgsEl.removeChild(chatMsgsEl.lastChild);
chatInputEl.value = text;
chatStatusEl.textContent = `エラー: ${err.message}`;
chatStatusEl.className = "wfm-nlp-ai-status wfm-nlp-ai-err";
} finally {
chatSendBtn.disabled = false;
}
};
chatSendBtn?.addEventListener("click", sendChatMessage);
chatInputEl?.addEventListener("keydown", e => {
if (e.key === "Enter" && !e.shiftKey) { e.preventDefault(); sendChatMessage(); }
});
chatClearBtn?.addEventListener("click", () => {
chatHistory = [];
if (chatMsgsEl) chatMsgsEl.innerHTML = "";
if (chatStatusEl) { chatStatusEl.textContent = ""; chatStatusEl.className = "wfm-nlp-ai-status"; }
});
// ---- VLM handlers ----
let vlmImage = null; // { base64, mimeType }
@@ -3231,10 +3378,22 @@ const setupAiHandlers = (container) => {
const vlmPreview = container.querySelector("#wfm-nlp-ai-vlm-preview");
const vlmLabel = container.querySelector("#wfm-nlp-ai-vlm-label");
const vlmFile = container.querySelector("#wfm-nlp-ai-vlm-file");
const vlmTaskSel = container.querySelector("#wfm-nlp-ai-vlm-task");
const vlmRunBtn = container.querySelector("#wfm-nlp-ai-vlm-run");
const vlmStatus = container.querySelector("#wfm-nlp-ai-vlm-status");
const vlmResult = container.querySelector("#wfm-nlp-ai-vlm-result");
const vlmCopy = container.querySelector("#wfm-nlp-ai-vlm-copy");
const wcInputs = container.querySelector("#wfm-nlp-ai-wc-inputs");
const wcNameEl = container.querySelector("#wfm-nlp-ai-wc-name");
const wcCountEl = container.querySelector("#wfm-nlp-ai-wc-count");
const updateVlmTaskUI = () => {
const isWc = vlmTaskSel?.value === "wildcard";
if (vlmDrop) vlmDrop.style.display = isWc ? "none" : "";
if (wcInputs) wcInputs.style.display = isWc ? "flex" : "none";
};
vlmTaskSel?.addEventListener("change", updateVlmTaskUI);
updateVlmTaskUI();
const loadVlmImage = async (file) => {
if (!file || !file.type.startsWith("image/")) return;
@@ -3263,7 +3422,7 @@ const setupAiHandlers = (container) => {
};
vlmRunBtn?.addEventListener("click", async () => {
if (!vlmImage) { showToast("Please drop an image", "error"); return; }
const task = vlmTaskSel?.value || "describe";
const c = loadAiCfg();
const backend = c.backend || "ollama";
const url = c.backendUrl || (backend === "ollama" ? "http://localhost:11434" : "http://localhost:1234");
@@ -3271,7 +3430,37 @@ const setupAiHandlers = (container) => {
if (!isValidAiUrl(url)) { showToast("URLは http:// または https:// で始まる必要があります", "error"); return; }
if (!model) { showToast("Please select a model in Settings", "error"); return; }
const task = container.querySelector("#wfm-nlp-ai-vlm-task")?.value || "describe";
if (task === "wildcard") {
const name = wcNameEl?.value?.trim() || "";
const count = Math.max(1, parseInt(wcCountEl?.value) || 20);
if (!name) { showToast("Please enter a wildcard name", "error"); return; }
vlmRunBtn.disabled = true;
vlmStatus.textContent = "Running...";
vlmStatus.className = "wfm-nlp-ai-status wfm-nlp-ai-working";
vlmResult.value = "";
const prompt = `Generate ${count} wildcard entries for the category "${name}". Output only plain text in English, one entry per line, no numbers, no markdown, no asterisks, no bold, nothing else.`;
try {
const result = await aiCallLLM(url, backend, model, prompt);
vlmResult.value = result.trim()
.split("\n")
.map(l => l.replace(/\*\*/g, "").replace(/^\*\s*/, "").replace(/^\d+\.\s*/, "").trim())
.filter(l => l.length > 0)
.join("\n");
vlmStatus.textContent = "完了";
vlmStatus.className = "wfm-nlp-ai-status wfm-nlp-ai-ok";
} catch (err) {
vlmStatus.textContent = `エラー: ${err.message}`;
vlmStatus.className = "wfm-nlp-ai-status wfm-nlp-ai-err";
} finally {
vlmRunBtn.disabled = false;
}
return;
}
if (!vlmImage) { showToast("Please drop an image", "error"); return; }
vlmRunBtn.disabled = true;
vlmStatus.textContent = "Running...";
vlmStatus.className = "wfm-nlp-ai-status wfm-nlp-ai-working";
@@ -3427,6 +3616,16 @@ const injectStyles = () => {
font-size: 14px;
flex: 1;
}
.wfm-nlp-title-pending {
cursor: grab;
color: #66aaff;
}
.wfm-nlp-title-pending::after {
content: " ●";
font-size: 7px;
color: #4caf50;
vertical-align: super;
}
.wfm-nlp-close {
background: none;
border: none;
@@ -4128,6 +4327,46 @@ const injectStyles = () => {
color: var(--descrip-text, #999);
pointer-events: none;
}
/* Chat */
.wfm-nlp-ai-chat-msgs {
flex: 1;
overflow-y: auto;
display: flex;
flex-direction: column;
gap: 6px;
min-height: 0;
padding: 2px;
}
.wfm-nlp-ai-chat-msg {
max-width: 92%;
padding: 6px 8px;
border-radius: 6px;
font-size: 11px;
line-height: 1.5;
word-break: break-word;
white-space: pre-wrap;
}
.wfm-nlp-ai-chat-msg-user {
align-self: flex-end;
background: var(--p-button-background, #4a9eff);
color: #fff;
}
.wfm-nlp-ai-chat-msg-assistant {
align-self: flex-start;
background: var(--comfy-input-bg, #2a2a2a);
border: 1px solid var(--border-color, #4e4e4e);
color: var(--input-text, #ddd);
}
.wfm-nlp-ai-chat-input {
min-height: 50px;
max-height: 100px;
flex: none;
flex-shrink: 0;
}
/* Wildcard count */
.wfm-nlp-ai-wc-count {
width: 60px;
}
`;
document.head.appendChild(style);
};