Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
9d952c4b6e | ||
|
|
8248ff8ac7 | ||
|
|
7548c49910 | ||
|
|
e9f2c6171a | ||
|
|
90a7d824fb | ||
|
|
05e061d656 | ||
|
|
5afdec395c | ||
|
|
3ab4f3e36b | ||
|
|
4a23564c66 | ||
|
|
d8ffcc182e | ||
|
|
3d5bc47e20 | ||
|
|
35899bf53e |
@@ -0,0 +1,11 @@
|
||||
# ComfyUI-Workflow-Studio - Unsloth backend (AI TOOL tab / sidebar A tab)
|
||||
#
|
||||
# Unsloth Desktop requires an API key even for local access
|
||||
# (Settings -> API in the Unsloth app, shown only once when issued).
|
||||
#
|
||||
# 1. Copy this file to ".env" (same directory as this example file)
|
||||
# 2. Paste your key after the "=" below (do NOT add a leading #, or the
|
||||
# line becomes a comment and the key will not be loaded)
|
||||
# 3. Restart ComfyUI
|
||||
|
||||
UNSLOTH_API_KEY=
|
||||
@@ -194,9 +194,8 @@ os.environ["HF_HOME"] = "D:\\hf_cache"
|
||||
|
||||
1. `pyproject.toml` の `version` を新バージョン番号に更新してステージングに含める
|
||||
2. `README.md` のバージョンバッジを更新(``)
|
||||
3. `README.md` の Changelog に新バージョンのエントリを追加
|
||||
4. `DEVLOG.md` の先頭に変更詳細エントリを追加
|
||||
5. 上記すべてを同一コミットにまとめてプッシュ
|
||||
6. `gh release create vX.Y.Z` でリリースを作成
|
||||
3. `DEVLOG.md` の先頭に変更詳細エントリを追加
|
||||
4. 上記すべてを同一コミットにまとめてプッシュ
|
||||
5. `gh release create vX.Y.Z` でリリースを作成(リリースノート本文に変更点を記載する — v0.3.90でREADME.mdのChangelogセクションは廃止したため、以後のバージョン履歴はGitHub Releaseのリリースノートのみで管理する)
|
||||
|
||||
`pyproject.toml` のバージョン変更が GitHub Actions のトリガー(`paths: pyproject.toml`)になっており、ComfyUI Registry への自動公開もここで行われる。バージョン更新を忘れると Registry に反映されない。
|
||||
|
||||
@@ -2,6 +2,281 @@
|
||||
|
||||
---
|
||||
|
||||
## v0.3.99
|
||||
|
||||
### 機能追加: AI TOOLタブ + サイドパネルAタブにUnslothバックエンド追加(APIキーは.env管理、SSRF脆弱性修正、reasoning_content対応)
|
||||
|
||||
ユーザーから「作業計画のUnslothをAI TOOLタブ、サイドパネルAタブに導入したい。APIキーは.envファイルで設定したい」との依頼を受けて着手。v0.3.98時点で「今回は見送り」として`project_next_tasks`メモリに保留していたUnslothバックエンド追加を実装した一連のセッション。
|
||||
|
||||
**1. Unslothバックエンド追加**: Ollama/LM Studio/Lemonadeに続く4つ目のバックエンドとしてUnsloth(OpenAI互換API、既定`http://localhost:8888`)を追加。既存3バックエンドと異なりローカルアクセスでも常にAPIキー認証が必須(`Authorization: Bearer sk-unsloth-...`)なため、フロントエンドから直接fetchする既存方式ではなく、新設したサーバー側プロキシ(`py/routes/unsloth_routes.py`, `POST /api/wfm/unsloth/proxy`)経由にした。CivitAI連携(`civitai_service.py`)のAPIキー管理パターン(環境変数優先)を踏襲しつつ、今回はユーザーの要望通りAPIキーを`.env`ファイル(`UNSLOTH_API_KEY`)で管理する方式にした。`python-dotenv`を新規依存として追加し、ノードインポート前に実行される唯一のタイミングである`prestartup_script.py`(新規作成)で`.env`を読み込み`os.environ`へ反映する。フロントエンドはSPA(`ai-tab.js`)・サイドパネル(`node_sets_menu.js`)の両方で`fetchModels`/`callLLM`/`callVLM`/`callChat`各関数に`backend === "unsloth"`分岐を追加(既存の重複実装パターンを踏襲)。
|
||||
|
||||
**2. セキュリティレビュー対応(SSRF修正)**: 実装直後の自動セキュリティレビューで、プロキシがクライアント指定の`baseUrl`をそのまま信頼しており、悪意のあるページが`baseUrl`に任意の外部URLを指定すれば`UNSLOTH_API_KEY`を外部へ流出させられる脆弱性(SSRF経由の資格情報窃取)が指摘された。`baseUrl`のホスト名を`localhost`/`127.0.0.1`/`::1`のみに限定するアローリスト検証を追加して修正(ポート番号は自由のままとし、Unslothのカスタムポート起動に対応)。
|
||||
|
||||
**3. `.env.example`のコメントアウトの罠**: 動作確認時、ユーザーが`.env.example`の`# UNSLOTH_API_KEY=sk-unsloth-...`という例示行をそのまま`.env`にコピーし、先頭の`#`を消し忘れてコメントアウトされたまま値を入力してしまい「UNSLOTH_API_KEY is not set」エラーが発生。テンプレート自体を「空の実行可能な行」(`UNSLOTH_API_KEY=`)+手順コメントの形に変更し、同じ罠が再発しないようにした。
|
||||
|
||||
**4. Unsloth Desktop側「モデル自動切り替え」設定の仕様判明**: 動作確認中、Unsloth側の「モデル自動切り替え (OpenAI API)」設定がOFFだと、Unsloth Studio UI上で事前にモデルを手動ロードしていない限りAPIリクエストがHTTP 404で失敗することが判明(公式ドキュメント調査で確認:未知のモデル名は安全に現在ロード中のモデルへフォールバックするが、通常は明示的にONにしてAPI経由のモデル切り替えを許可する必要がある仕様)。本プラグイン側の不具合ではなくUnsloth Desktop自体の仕様のため、ヘルプ(`ai-6`)とREADMEに「Unsloth Desktop側でこの設定をONにする必要がある」旨を追記した。
|
||||
|
||||
**5. `reasoning_content`未対応バグ修正**: 「モデル自動切り替え」をONにした後も、会話が数ターン進むとチャットの応答が空のバブルになる不具合が発生。Unsloth Studioのサーバーログ(`~/.unsloth/studio/logs/server/`)と、ブラウザ操作MCP(kapture)の`evaluate`経由でプロキシへ生のAPIリクエストを直接送って実レスポンスを検証した結果、Unslothのreasoningモデル(`gemma-4-12B-it-QAT-GGUF`)はOpenAI互換APIで思考過程を`message.content`ではなく別フィールド`message.reasoning_content`に返す仕様であることが判明した。Ollama/LM Studio/Lemonadeはインラインの`<think>...</think>`タグ方式のため既存のThinking mode処理で問題にならなかったが、Unslothは別フィールド方式のため、Max tokens不足(初期値512)で思考中にトークンを使い切ると(`finish_reason: "length"`)、`content`が常に空文字列のまま返り、チャットに中身のないバブルだけが残っていた。`reasoning_content`を`<think>...</think>`として`content`に合成してから既存のThinking mode ON/OFF処理(`stripThinkingTags`)に流すよう修正し、SPA・サイドパネル両方に適用。Max tokensが小さすぎると根本的に回答本文が生成されない制約自体は残るため、ヘルプに「Unslothのreasoningモデルを使う場合はMax tokensを2048以上に」という推奨値も追記した。
|
||||
|
||||
**ヘルプタブ更新**: `project_v0336_conventions`の慣習(index.html + i18n.js 3言語 + app.jsのhelpIdMap)に従い、AI TOOL TabヘルプのSettings pane説明(`ai-6`)にUnsloth関連3項目(APIキーの`.env`設定・モデル自動切り替え要件・`reasoning_content`/Max tokens注意)を追記。`sidepanel-16`・`ai-2`にもバックエンド一覧へUnslothを追加。README.mdのBackend support・Settings pane等の該当箇所も同様に更新。
|
||||
|
||||
**検証**: 全JS/PythonファイルをそれぞれNode.jsの構文チェック(`node --check`)・`ast.parse()`で確認。開発元gitリポジトリと実行時`custom_nodes`フォルダは別実体のため([[project_dev_deploy_sync]]参照)、変更の都度`diff`で意図した差分のみであることを確認してから両フォルダへ同期し、`cmp`でファイル同一性を検証。実行時フォルダの`__pycache__`もクリア。最終的にユーザー自身が実機(Unsloth Desktop + ComfyUI)で一通り動作確認済み。
|
||||
|
||||
**How to apply**:
|
||||
1. 外部APIキーが常に必須なバックエンドを追加する場合、既存バックエンドと同じ「フロントエンドから直接fetch」方式は使えない(APIキーがブラウザに露出する)。サーバー側プロキシ方式が必須になる。
|
||||
2. サーバー側プロキシでクライアント指定のURLをそのまま信頼してAuthorizationヘッダーを付与すると、SSRF経由の資格情報漏洩につながる。ホスト名のアローリスト検証は必須。
|
||||
3. `.env`テンプレートに「コメントアウトされた例」を書くと、ユーザーが`#`を消し忘れてハマる典型パターンになる。テンプレートは「空の実行可能な行」+説明コメントの形にする。
|
||||
4. サードパーティAPIサーバーの独自拡張(`reasoning_content`等)は、標準的なOpenAI Chat Completions仕様と食い違うことがある。空応答やトークン切れなど不可解な挙動が出たら、実際の生レスポンスをブラウザから直接fetchして中身を見るのが最も早い切り分け方法(kaptureの`evaluate`ツールでプロキシへ直接リクエストを送るのが有効だった)。
|
||||
|
||||
---
|
||||
|
||||
## v0.3.98
|
||||
|
||||
### 機能追加・バグ修正: AI TOOL翻訳の信頼性向上 + GenerateUI Modelタブ再構成(ハイライト色・折りたたみ・並び替え)+ Thinking mode/Max tokens設定
|
||||
|
||||
ユーザーから「AI TOOLタブの翻訳、英語から日本語がうまく動かない(英語のまま、完了で翻訳されない)」との報告を受けて着手。原因調査後、関連するGenerateUI Modelタブの表示改善、AI TOOLタブへのLLM生成パラメータ設定追加と、複数の要望を連続して実装した一連のセッション。
|
||||
|
||||
**1. AI TOOL翻訳の信頼性向上**: 調査の結果、翻訳処理がOllamaの`/api/generate`(system role無しの生プロンプト文字列)またはLM Studio/Lemonadeの`/v1/chat/completions`(user roleのみ、system message無し)でLLMへ丸投げしており、指示追従が弱い小型・非力なローカルモデルが「翻訳してください」という指示を無視して原文をそのまま返すことがあった。それでもHTTPレスポンス自体は正常なため、画面上は「完了」と表示されたまま実際には未翻訳、という状態が発生していた。既にChatペインで使われていた`callChat()`(system role対応のchat API)を翻訳にも流用し、system promptで「翻訳結果のみを出力し、説明・前置き・原文の繰り返しをしない」と明確に指示するよう変更。加えてモデルが前置き文("Here is the translation:"等)や引用符を付けて返す場合の後処理除去(`cleanTranslationOutput`)と、出力が原文とほぼ同一=未翻訳の疑いがある場合の警告トースト(`looksUntranslated`)を追加。SPA(`ai-tab.js`)とサイドパネルAタブ(`node_sets_menu.js`)は全く同じ不具合パターンの重複実装だったため、両方に同じ修正を適用(設定は同じ`localStorage`キー`wfm_ai_settings`を共有)。
|
||||
|
||||
**2. GenerateUI Modelタブ: ハイライト色機能**: ユーザーから「読み込んだワークフローに関係なく項目を並べているため該当する項目(Checkpointなど)の色を変更表示、デフォルトは明るい緑、設定タブに色変更設定を追加したい」との要望。既存の「RAW JSON Colors」機能(`<style>`タグ動的注入+`localStorage`保存+Resetボタン)と全く同じパターンを踏襲し、`applyModelTabActiveColor()`を新設。`renderModelTab()`で各セクション(Checkpoint/VAE/Diffusion Model/Text Encoder/ControlNet/Hypernetwork)のラベルとLoRA列見出しに、対応するノードが実際にワークフローへ含まれる場合のみ`wfm-model-label-active`クラスを付与。既存CSS`.wfm-form-group label { color: var(--wfm-text-secondary); }`の方が詳細度が高く単純なクラス指定では上書きされなかったため、注入CSS側のセレクタを`.wfm-form-group label.wfm-model-label-active`(および後続の折りたたみ対応でsummary要素向けセレクタも追加)として詳細度を確実に上回るよう実装。
|
||||
|
||||
**3. ControlNet/Hypernetwork折りたたみ化 + Text Encoder並び替え**: 「使用頻度が低い、意図的に利用するControlNet、Hypernetworkは折りたたみにし、最新モデルで主流のText EncoderをControlNetの上にしたい」とのフィードバックを受け、表示順をCheckpoint→VAE→Diffusion Model→**Text Encoder**→ControlNet→Hypernetworkに変更。ControlNet/Hypernetworkは`Image Editタブのプレースホルダ設定`(v0.3.97)で既に使われていた`<details>/<summary>` + `.wfm-settings-section`パターンをそのまま再利用し、デフォルト折りたたみ状態に。折りたたんだ状態でもハイライト色(#2の機能)は見出し文字に残るため、展開しなくても「このワークフローはControlNetを使っているか」が一目で分かる設計とした。続けて「LoRAもハイライト可能にしたい」との追加要望で、`templates/index.html`のLoRA列見出し`<span>`にid付与、`renderLoraPane()`でワークフローにLoRAノードが1件でもあればハイライトクラスをtoggleするよう対応。
|
||||
|
||||
**4. AI TOOLタブ: Thinking mode / Max tokens設定**: 「Thinking mode ON/OFF、Max tokens設定を追加したい」との要望を受け実装。Ollamaは`think`パラメータ(bool)と`options.num_predict`で標準対応しているが、LM Studio/Lemonade(OpenAI互換API)には標準的なthinking切替パラメータが存在しないため`max_tokens`のみ送信し、代わりにThinking mode OFF時は出力から`<think>...</think>`(`<thinking>...</thinking>`も)タグをクライアント側で正規表現除去する方式を採用。これはOllama自身がパラメータを無視した場合の保険としても機能し、バックエンドを問わず一貫した挙動になる。SPA(`callLLM`/`callChat`/`callVLM`)とサイドパネル(`aiCallLLM`/`aiCallChat`/`aiCallVLM`)の両方に`_applyGenOptions()`ヘルパーとタグ除去処理を追加し、Translation/Chat/TOOLS(VLM)/Wildcard生成の全呼び出し経路に反映。
|
||||
- **付随調査(見送り)**: 「Unsloth Desktopアプリのバックエンド追加は可能か」との質問を受け、公式ドキュメントを調査。OpenAI/Anthropic互換APIを同一ポート(既定`localhost:8888`)で提供する点は好条件だが、既存3バックエンドと異なり**ローカルアクセスであってもAPIキー認証が常に必須**(`Authorization: Bearer sk-unsloth-...`、無いと401)と判明。実装には新規UI(APIキー入力欄)が必要になるためユーザー判断で今回は見送り、将来の作業候補として`project_next_tasks`メモリに記録。
|
||||
|
||||
**ヘルプタブ更新**: `project_v0336_conventions`の慣習(index.html + i18n.js 3言語 + app.jsのhelpIdMapの3点セット)に従い、GenerateUI TabヘルプにModelタブの新しい表示順・折りたたみ挙動(`gen-5`更新)とハイライト色機能(新規`gen-28`)、AI TOOL TabヘルプにThinking mode/Max tokens(`ai-6`更新)、SettingsタブヘルプにModelタブハイライト色設定(新規`settings-14`)を追加。この作業中に、以前から`index.html`にだけ存在し`i18n.js`(英語含む全言語)に対応キーが用意されていなかったため実際には一度も表示されていなかった「LoRA Stack — Apply writes...」の説明文を発見・復旧(`app.js`の`el.textContent = t(key)`は未定義キーでもキー名をそのまま返してHTML側の内容を問答無用に上書きするため、i18n.js側の追加漏れは静かな表示欠落を引き起こす)。
|
||||
|
||||
**検証**: 全JSファイルについて`node --check`で構文確認。開発元git リポジトリと実行時`custom_nodes`フォルダは別実体のため([[project_dev_deploy_sync]]参照)、変更の都度`diff`で意図した差分のみであることを確認してから両フォルダへ同期、CRLF/LF不一致がないことも`file`コマンドで事前チェック。各機能追加後にユーザー自身が実機(ComfyUI再起動後)で動作確認し、フィードバックを都度反映する形で進行。
|
||||
|
||||
**How to apply**:
|
||||
1. SPA(`ai-tab.js`)とサイドパネル(`node_sets_menu.js`)のように、同じ機能が2箇所に重複実装されている場合(設定は共通の`localStorage`キーを共有していても、API呼び出しロジック自体は別ファイルにコピーされている)、片方だけ修正すると「サイドパネル版だけ直っていない」という見落としが起きる。ai-tab.js相当の修正が必要な要望が来たら、必ずnode_sets_menu.js側の対応箇所も同時に確認する。
|
||||
2. ローカルLLM APIへの指示は、user発話に埋め込んだ「〜だけ出力して」という指示より、system roleとして明示的に分離した方が小型モデルの指示追従率が上がる。それでも従わないモデルへの保険として、クライアント側での出力後処理(前置き除去、echo検知)を組み合わせるとより堅牢になる。
|
||||
3. 動的注入`<style>`タグでハイライト色のような「上書き用クラス」を追加する場合、既存CSSがelement+classなど複合セレクタで詳細度を持っていると単純なクラス指定では負ける。読み込み順に依存せず確実に上書きするには、注入側のセレクタも同等以上の詳細度(同じ複合セレクタ構造にクラスを足す)にする。
|
||||
4. 折りたたみ(`<details>`)と色ハイライトを組み合わせる設計は、「低頻度機能は隠したいが、関連情報があるかどうかは常に見えていてほしい」という要望に対する良い組み合わせになる——折りたたんだ見出し自体を色の表示場所として使う。
|
||||
5. i18n.jsの「3点セット」規約が守られていないと、HTML側にどれだけ内容を書いてもJS側の`t(key)`上書きで静かに消える。ヘルプ文言を追加・編集する際は、既存の該当キーが本当に全言語ブロックに存在するか(特に英語)を都度確認する。
|
||||
|
||||
---
|
||||
|
||||
## v0.3.97
|
||||
|
||||
### 機能追加・バグ修正: KREA-2ワークフロー対応 + Labタブ拡張(Clear/Get from Previous/Bypass/ライブ反映)+ Input Imageプレースホルダ機能
|
||||
|
||||
ユーザーから「KREA2モデルワークフローを生成UIタブ、メタデータ、Workflow Studio LibraryのIタブ他対応させたい」との依頼を受けて着手。実機検証を進める過程で複数の既存バグを発見・修正し、続けてLabタブとInputタブImageサブパネルへの機能追加も行った一連のセッション。
|
||||
|
||||
**1. KREA-2ワークフロー対応で発覚した2件の既存バグ修正**: KREA-2 Turbo(`krea2_turbo_int8_convrot.safetensors`、Qwen3VLベースのLLMプロンプト拡張+サブグラフ構成)の2種類のワークフロー(T2I版・スタイル参照版)を実機で読み込み検証したところ、GenerateUIタブでPositive Promptが誤って`SaveImage`ノードを指し、プロンプト欄が空になる不具合を発見。原因は、ノードタイプ単位の役割伝播ロジック(`comfyui-workflow.js`の`analyzeWorkflow()`)が`PreviewAny`(値タップ中継)と`StringConcatenate`(LoRAトリガーワード連結)という中継ノードタイプを一切考慮しておらず、KREA-2のプロンプト強化トグル配線(`PrimitiveStringMultiline`→`ComfySwitchNode`→`PreviewAny`→`StringConcatenate`→`ComfySwitchNode`→`CLIPTextEncode`)の途中で役割伝播が途切れていたため。同様の理由でスタイル参照版では`TextEncodeQwenImageEditPlus`のリンク値(配列)がテキストとしてそのまま誤表示されるバグも発覚。「KREA2専用」ではなく`PreviewAny`/`StringConcatenate`/リンク経由`TextEncodeQwenImageEditPlus`という汎用ノードタイプ単位の役割伝播ルールとして`comfyui-workflow.js`に追加し、Metadataタブ(`metadata-tab.js`の`resolveLinkedText`系2関数)とサイドパネルIタブの重複実装(`node_sets_menu.js`の`_resolveLinkedText`系2関数)にも同じ汎用キー拡張(`source`/`string_a`)を反映。
|
||||
- 修正後、実際に生成を実行したところ**別の既存バグ**で`Prompt outputs failed validation`エラーが発生。調査の結果、`TextGenerate`ノードの`sampling_mode`(`COMFY_DYNAMICCOMBO_V3`型ウィジェット)が選択中オプションのサブフィールド(`temperature`/`top_k`等の必須6個+`presence_penalty`のoptional1個、計7スロット消費)を持つのに対し、サブグラフの境界値注入ロジック(`_getDynamicComboSubNames`・`_simulateWidgetValues`)がDynamicComboの複数スロット消費を全く理解しておらず単純に1スロットとして扱っていたため、`sampling_mode`より後に宣言されている`thinking`(LLM思考モード、サブグラフ境界に接続)の注入処理が実際には`sampling_mode.temperature`のスロットを誤って上書きし、`temperature`に境界値の`false`(数値比較で0.0扱い)が入り`min: 0.01`バリデーションに抵触していた。`_getDynamicComboSubNames`をrequired/optional両方のサブフィールドを返すよう修正し、`_simulateWidgetValues`にDynamicCombo展開に対応する`comboExpander`引数を追加してスロット数を正しく消費するよう修正。LLMプロンプト拡張(DynamicComboを持つノード)をサブグラフ経由で使うワークフロー全般に影響する汎用バグだったため、KREA-2以外の同様構成のワークフローにも恩恵がある。
|
||||
|
||||
**2. Labタブ: プロンプトモーダルにClear/Get from Previousボタン追加**: ユーザー要望「プロンプトモーダルにプロンプトクリアボタンと前の設定からプロンプトを取得ボタンを追加したい(#3で実行、#2のプロンプトをポジティブ、ネガティブ両方コピー)」を実装。Clearは両フィールドを空にするのみ(ワークフローノードには触れない)。Get from Previousは同じカラムの直前のキーフレーム(`idx-1`)からPositive/Negative両方をコピー。キーフレーム#1には「前」が存在しないためボタン自体を非表示。
|
||||
|
||||
**3. Labタブ: Setting 1(キーフレーム#1)のライブ反映**: ユーザー要望「設定1のそれぞれのモーダルに生成UIタブの内容を初期自動反映したい(ワークフローの設定まま)表示は編集された場合に表示を変更したい」を実装。各カラム(Checkpoint/VAE/Prompt/KSampler)のキーフレーム#1が、まだ明示的に上書き保存されていない間は、GenerateUIタブで現在読み込まれているワークフローの実際の値(`comfyUI.currentAnalysis`から取得)をグリッドセル(破線ボーダー)と編集モーダル(フィールド事前入力+ヒント文言)の両方に表示する。何も変更せず保存しただけでも実際の上書き値として確定し、以後はライブ反映されなくなる(`_isEmptyValue(col, kf.value)`が false になるため)。GenerateUIタブの他サブタブからLabサブタブへ切り替えるたびに`refreshLabLiveDefaults()`で再描画し、常に最新のGenerateUI状態を反映する。「Get from Previous」ボタンも`_effectiveDisplayValue()`経由でこのライブ反映値を透過的に扱う。
|
||||
|
||||
**4. Labタブ: Bypassチェックボックス追加**: ユーザーから「バイパスボタンを追加したい」との要望を受け、追加箇所(Labタブの各列 vs Model タブ vs Raw JSONパネル)と動作仕様(ComfyUIノードを実際にBypassモードにするか、Labタブ内部だけでキーフレーム行を無効化するか)の2点をAskUserQuestionで確認。KSamplerは入出力が同じLATENT型のため実際のBypass(mode:4)が構造的に成立するが、Checkpoint/VAE/Promptの各ローダー/エンコーダーは入力を持たないため下流が未接続になり生成エラーを誘発するリスクがあるとユーザーに説明した上で、「そのキーフレーム行を無効化(Labタブ内のみ)」を選択いただいた。各キーフレームに`bypassed`フラグを追加し、`_resolveKeyframe()`でbypassedな行を「存在しないもの」として完全スキップ(直前に有効だった設定がそのまま使われる)。キーフレーム#1自体もBypass可能で、その場合はライブ反映表示より優先される。BypassチェックはRevertチェックと排他(両方同時には使えない)。
|
||||
|
||||
**5. GenerateUI Inputタブ Imageサブパネル: Clearボタン + プレースホルダ画像機能**: ユーザー要望「クリアボタンと上部にプレースホルダ画像機能を追加したい。プレースホルダ画像機能は色と画像が選べ...LoadImageのプレースホルダボタンを押下した際、画像を作成し既存の画像を差し替えます...デフォルト画像の設定は記憶されます」を実装(`comfyui-editor.js`の`renderImageTab`)。各LoadImageカードにClear(保留中の選択/プレビューをリセット、ノードには触れない)とPlaceholderの2ボタンを追加。パネル上部に共有のPlaceholder Image設定:Colorモード(幅・高さ・色を指定、押下時にキャンバスでその場生成しアップロード)とImageモード(デフォルト画像を1枚アップロードし記憶、押下時は再アップロードせずファイル名を再利用)。設定は`localStorage`(`wfm_i2i_placeholder`)に永続化。各カード自身のPlaceholderボタンで個別に差し替え可能。
|
||||
- **フォローアップ(低頻度機能のため折りたたみ化)**: ユーザーから「使用頻度は高くないため。折りたたみにしたい」とのフィードバックを受け、Settingsタブと同じ`<details>/<summary>`アコーディオンパターン(`.wfm-settings-section`/`.wfm-settings-summary`)に変更し、デフォルトで折りたたみ状態に。
|
||||
|
||||
**ヘルプタブ更新**: `project_v0336_conventions`の慣習(index.html + i18n.js 3言語 + app.jsのhelpIdMapの3点セット)に従い、GenerateUI Tabヘルプに Imageサブパネルのプレースホルダ機能を1項目追加(`gen-27`)、Lab subtabヘルプにClear/Get from Previous・ライブ反映・Bypassの3項目を追加(`lab-11`〜`lab-13`)。EN側は`app.js`の`helpIdMap`が`el.textContent = t(key)`でHTMLタグを問答無用に上書きするため、新規追加時はi18n.js側の全言語ブロック(EN含む)に対応キーを用意しないとリッチHTML(`<b>`/`<code>`タグ)がプレーンテキストで消えてしまう点に注意して実装。
|
||||
|
||||
**検証**: 各修正について、実際にComfyUI(127.0.0.1:8189)とWorkflow Studioの実行時ComfyUI_5インスタンスへPlaywrightで接続し、KREA-2両ワークフローの読み込み・GenerateUI/Metadata/IタブでのPositive Prompt検出・実際の生成実行(バリデーション通過・画像出力まで)・Labタブの新機能(Clear/Get from Previous/ライブ反映/Bypass)の各UI操作・Input ImageサブパネルのColor/Imageモード双方でのPlaceholder適用とリロード後の設定復元・ヘルプタブのEN/JA両言語表示、をすべて実機で確認。開発元リポジトリと実行時`custom_nodes`フォルダはハッシュ比較で同一性を検証。
|
||||
|
||||
**How to apply**:
|
||||
1. ノードタイプ単位の汎用ロジック(役割伝播、ウィジェット値のインデックス復元など)を持つコードベースでは、特定モデル対応の不具合であっても「そのモデル専用」の分岐を足すのではなく、原因となっているノードタイプ(今回は`PreviewAny`/`StringConcatenate`/`COMFY_DYNAMICCOMBO_V3`)を汎用ロジック側に正しく組み込む修正を優先する。結果として対象モデル以外の同構成ワークフローにも自動的に恩恵が及ぶ。
|
||||
2. ウィジェット値の「インデックスから名前への復元」ロジックが複数箇所(今回は`_flattenSubgraphs`内の境界値注入と、最終API変換ループ)に重複実装されている場合、片方だけがDynamicCombo等の可変長ウィジェットを正しく理解していても、もう片方が単純な1対1対応を仮定しているとデータ破損が起きる。両方の実装が同じスロット数計算ロジックを共有しているか必ず確認する。
|
||||
3. 「バイパス」のような一般的な語でも、対象ノードの入出力型構成によって実際に構造的なComfyUI Bypassが成立するかは列ごとに異なりうる(LATENT型のKSamplerは素通し可能、入力を持たないLoader/Encoderは不可)。曖昧な機能要望は、AskUserQuestionで実装方式の選択肢とその技術的トレードオフを具体的に提示してから着手する。
|
||||
4. 低頻度機能をUIに追加する際は、既存のアコーディオン/折りたたみパターン(今回は`<details>/<summary>`+ `.wfm-settings-section`)を新規CSSクラスを増やさず再利用できないか確認する。
|
||||
|
||||
---
|
||||
|
||||
## v0.3.96
|
||||
|
||||
### バグ修正: カタログ作成バッチが特定件数で無言停止する問題の修正 + Style Catalog/Promptタブ機能拡張
|
||||
|
||||
ユーザーから「カタログ作成機能ですべてのスタイル(277)を選択して実行した149でバッチ処理が止まってしまった」との報告を受けて調査・修正した一連のセッション。合わせてStyle Catalogタブとカタログ作成機能、Promptタブへのスタイル管理機能追加も行った。
|
||||
|
||||
**1. バッチ処理が無言で停止するバグの修正(`comfyui-client.js`)**: 調査の結果、`trackProgress()`(WebSocket経由で生成完了を待つPromise)にタイムアウトが一切なく、`execution_interrupted`イベントも未処理だったことが根本原因と判明。ComfyUI側からの完了通知が何らかの理由で届かなくなると(WebSocket瞬断・生成中断など)、Promiseが永久に解決されないままバッチループの`await`が固まり、エラーも出さずに停止する状態になっていた。`_pendingTrackers`(promptId→reject関数のMap)を追加し、(a) `trackProgress()`に10分のタイムアウトを追加、(b) `execution_interrupted`イベントのハンドリングを追加、(c) WebSocket切断(`onclose`)時に待機中の全Promiseを即座にrejectする仕組みを実装。既存の`_runBatchLoop`(`generate-tab.js`)は元々「エラー時は次のアイテムへ進む」try/catch構造を備えていたが、`trackProgress()`が例外を投げないまま無限に待ち続けていたためこのcatchに到達できていなかった。今回の修正で、意図されていた挙動(1件失敗しても次へ進む)が正しく機能するようになった。停止した149件目(`MK shepard-fairey-style`)自体はJSON構文・エンコーディングとも正常で、スタイルデータ側に問題は無いことも確認済み。
|
||||
|
||||
**2. カタログ作成/バッチのスタイル処理順序の調査(コード変更なし)**: ユーザーからの追加質問(Batchタブの表示順とカタログ作成の生成順が異なる、149件目が停止する原因はファイルにあるか)に対して調査のみ実施。バックエンド`_load_styles()`(`settings_routes.py`)は`style/*.json`をファイル名のアルファベット順に読み込み、各ファイル内はJSON配列の記載順を維持する仕様であることを特定。Style Catalogギャラリーの表示順は生成順とは独立に常に`sort=name_asc`(ファイル名のアルファベット順)である仕様も確認。いずれも設計通りの挙動でありバグではないと結論。
|
||||
|
||||
**3. Style Catalogタブ: ワークフロー再利用ボタンの追加**: 「スタイルとして選択」ボタンの下に「Load in GenerateUI」「Open in Metadata Tab」の2ボタンを追加。当初「Outputフォルダの該当画像へ遷移するボタン」を検討したが、カタログ画像はOutput画像のバイト列そのままのコピー(`extra_pnginfo`のワークフローも含め完全に同一のPNGメタデータを保持)であるため、Output側の対応ファイルを探しに行かずカタログ画像自身から直接ワークフローを読み込む方式の方が、実装がシンプルな上に**既存の全カタログ画像に対しても即座に使える**(Output→カタログの対応を新たに記録する仕組みが不要)という利点があり、ユーザー確認の上でこちらを採用した。
|
||||
|
||||
**4. Style Catalogタブ: ダブルクリックでの拡大表示**: `gallery-tab.js`既存の`openLightbox()`と同じCSSクラスをそのまま流用し、右ペインのプレビュー画像に加えて中央ペインのサムネイルカード自体にも`dblclick`を追加(Output Galleryと同一の操作感になるよう、ユーザーからの「操作が異なるため都度、間違える」というフィードバックを受けて追加)。ESCで閉じる処理はgallery-tab.js側の既存グローバルリスナーがクラス名ベースで拾うため追加実装不要だった。
|
||||
|
||||
**5. Promptタブ右ペインにStyle管理サブタブを新設**: 右ペイン(旧Wildcard専用)をタブ化し、Wildcard/Styleの2モードを切り替えられるようにした。Wildcardファイルマネージャー(一覧→エディタ→保存/削除/キャンセル)と同一のUXパターンで、登録済みStyle(`DATA_DIR/style/*.json`)の作成・編集・削除を実装。
|
||||
- バックエンドに`POST /api/wfm/styles`(新規作成)・`PUT /api/wfm/styles/{name}`(更新・リネーム)・`DELETE /api/wfm/styles/{name}`(削除)を新設。リネーム時は元々定義されていたファイル内でその場を書き換え(他ファイルへ移動しない)、名前は全スタイル横断で一意になるよう検証。新規作成は既定で`style/custom.json`へ追記し、同梱のスタイルパックファイル(`sdxl_styles_*.json`)は直接変更しない設計とした。
|
||||
- 保存・削除の都度、`generate-tab.js`に新規exportした`refreshStylesList()`を呼び出し、GenerateUIのStyleドロップダウン・Batchタブのチェックリストをリロード無しで再同期する。
|
||||
- 一時ディレクトリを使った単体テスト(`_find_style`のファイル横断検索、リネーム時の位置保持、重複名の拒否など)で動作確認。
|
||||
- **ファイル名バッジ + 既存ファイルへの追加**(フォローアップ、ユーザーからの追加要望): `_load_styles()`が各エントリに定義元ファイル名を`file`として付与するように変更し、一覧の各項目にファイル名を小バッジ表示。既存スタイル編集中は「+ Add to this file」ボタンが現れ、クリックするとフォームが空になり同じファイルへ追加される新規エントリとして保存できる(`POST /api/wfm/styles`の`file`パラメータで対象ファイルを指定、実在するファイルのみ許可しパストラバーサルを防止)。
|
||||
|
||||
**6. カタログ作成: Outputフォルダにコピーを残さないオプション**: カタログ作成は元々、ワークフローのSave Imageノードが生成の都度Outputフォルダへ通常通り書き出した上で、その画像をカタログフォルダへコピー保存する仕組みだった。大量スタイル(200件超)を一括作成するとOutputフォルダがほぼ重複ファイルで溢れる問題があり、モーダルに「Don't keep a copy in the Output folder」チェックボックスを追加。カタログへのコピー保存が**成功した後にのみ**、新設の`POST /wfm/gallery/output-image/delete`(filename/subfolder/typeからComfyUI Output配下の実ファイルを削除、`type="output"`以外は拒否)を呼び出してOutput側の元ファイルを削除する。コピー保存に失敗した場合は削除せず元画像を保持するため、データを失う経路が無い設計。既存の`GalleryService.delete_images()`(`_check_path_allowed`によるパス検証済み)をそのまま再利用しており、Outputフォルダ外のファイルを誤って削除する経路は存在しない。
|
||||
|
||||
**ヘルプタブ更新**: `project_v0336_conventions`の慣習(index.html + i18n.js 3言語 + app.jsのhelpIdMapの3点セット)に従い、GenerateUI/Prompt/Galleryタブヘルプに今回の追加項目をそれぞれ反映。
|
||||
|
||||
**検証**: 各段階でNode `--check`(JS構文)・`python -c ast.parse`(Python構文)・一時ディレクトリでのバックエンドロジック単体テスト(スタイルCRUD、ファイル横断検索、削除経路の安全性)・開発元と実行時`custom_nodes`フォルダの`diff`比較を実施。ComfyUI再起動を要する変更(バックエンドAPI追加)の都度ユーザーへ明示。
|
||||
|
||||
**How to apply**:
|
||||
1. WebSocketやポーリングで「完了通知を待つ」Promiseには、必ずタイムアウトを設定する。通知が絶対に届く保証はネットワークにもサーバー実装にも無く、タイムアウト無しのPromiseはバッチ処理のような長時間ループで「無言のまま停止する」最悪のバグを生む。周辺のtry/catchが正しく書かれていても、例外が投げられなければ意味が無い。
|
||||
2. 画像のバイト列そのものをコピー保存する機能(今回のStyle Catalog)では、コピー先の画像自体に元のメタデータ(埋め込みワークフロー等)がそのまま残っていることを活用すれば、コピー元との対応関係を別途記録・追跡する仕組みを作らずに済む場合がある。「元データへの参照を持つ」設計と「元データの複製として自己完結させる」設計のどちらが適切かは、コピー後に元データが削除・移動されうるかどうかで判断するとよい。
|
||||
3. 「Outputフォルダにファイルを残さない」系のオプションを実装する際、生成自体を変更する(ワークフローのSaveImageノードをPreviewImageに差し替える等)よりも、「一旦生成させてから、後続処理が成功したのを確認した上で元ファイルを削除する」方が実装が単純で、かつ後続処理が失敗した場合にデータを失わない安全な設計になる。
|
||||
|
||||
---
|
||||
|
||||
## v0.3.95
|
||||
|
||||
### 機能追加: Style/Prompt→ImagePrompt改名 + Style_Catalogギャラリー新設 + GenerateUI「カタログ作成」機能
|
||||
|
||||
ユーザーから「GenerateUIタブのスタイルを画像から決めるためのスタイルカタログ機能を追加したい」との要望を受けて実装。まず前提としてGalleryタブの既存Style/Promptサブタブを「ImagePrompt」に改名(Style_Catalogと名前が紛らわしくなるのを避けるため)、続けて新規Style_Catalogサブタブと、GenerateUI側のカタログ生成機能を追加した。ブランチ`feature/style-catalog-imageprompt`(前セッションで未コミットのまま残していた`fix/output-gallery-style-prompt-display`ブランチから分岐、そちらの修正も本エントリに含む)。
|
||||
|
||||
**1. Style/Prompt → ImagePrompt 全面リネーム**: ユーザーから「内部ID/関数名/ファイル名も含めて全面リネーム」の指示を受け、タブラベルだけでなく`STYLE_PROMPT_FOLDER_NAME`→`IMAGE_PROMPT_FOLDER_NAME`(値も`ws_style_prompt`→`ws_image_prompt`)、APIルート(`/wfm/gallery/style-prompt/root`→`/wfm/gallery/image-prompt/root`等)、ファイル名(`static/js/style-gallery-tab.js`→`image-prompt-tab.js`)、関数名(`initStyleGalleryTab`→`initImagePromptTab`等)、CSSクラス(`.wfm-style-*`→`.wfm-imageprompt-*`)、i18nキー(`styleGallery*`→`imagePrompt*`)まで一貫して変更。実データフォルダも`mv`でリネーム(既存データはそのまま保持)。GenerateUI Batchタブの「Style」バッチ機能(`_stylesData`/`_batchStyleSelected`等、`DATA_DIR/style/*.json`のFooocus形式スタイルプリセット)とは全く別の概念であるため、こちらは意図的にリネーム対象から除外した。
|
||||
|
||||
**2. 事前調査: 既存Style機能・バッチ生成ループの理解**: 実装前にExploreエージェントで調査し、以下を把握した。
|
||||
- GenerateUIの「Style」はプリセットJSON(`{name, prompt, negative_prompt}`)を`DATA_DIR/style/`から読み込み、`_applyNamedStyle(workflow, style)`(`generate-tab.js`)がワークフローの複製に対して適用する。Positiveは`{prompt}`プレースホルダ置換または末尾追記、Negativeは常に末尾追記。
|
||||
- Batchタブに既に「Style」バッチ種別(複数スタイル選択→順次生成)が存在し、`_runBatchLoop(items, applyFn, labelFn)`という汎用バッチループを使っていた。カタログ作成はこの既存インフラをそのまま流用できると判断(新規バッチシステムを作らない)。
|
||||
- Positive/Negativeプロンプトの構造化抽出ロジック(ComfySwitchNode・CLIPTextEncodeEditPlus等の特殊ノード対応込み)は`metadata-tab.js`の`extractAllMetadata(file)`が既にexport済みで、Gallery側からもそのまま呼び出し可能と判明(Python側に同等ロジックは存在しない)。
|
||||
|
||||
**3. 新規: Style_Catalogギャラリーサブタブ**: Galleryタブ3つ目のサブタブとして追加。バックエンドは`get_style_catalog_root()`(`get_image_prompt_root()`と同型)のみ新設し、フォルダツリー・画像一覧・作成の各APIは既存の汎用エンドポイント(`root`/`folder`パラメータ対応済み)をそのまま再利用。フロントエンドは新規`static/js/style-catalog-tab.js`で、`image-prompt-tab.js`と同じツリー/グリッド実装を土台にしつつ、右ペインはプロンプトビルダーではなく「選択画像をfetch→Blob→File化→`extractAllMetadata()`でPositive/Negativeを抽出→個別コピーボタン」という読み取り専用パネルにした。「Select as Style」ボタンは、画像ファイル名(拡張子除く)と同名の登録済みStyleを`generate-tab.js`に新規exportした`selectStyleByName(name)`で探し、GenerateUIのStyleドロップダウンを切り替える方式(埋め込みプロンプトを直接適用するのではなく、既存Styleシステムへの視覚的ショートカットとする — ユーザー確認済みの方針)。
|
||||
|
||||
**4. 新規: バックエンド `save_image_to_folder`**: 既存の`save_image_to_gallery`(画像保存ルート、常に固定のギャラリールート直下にのみ保存)を一般化し、任意フォルダ+任意ファイル名+上書き保存に対応する`GalleryService.save_image_to_folder(folder_path, filename, image_data)`を新設。data URLデコード・拡張子解決・ファイル名サニタイズのロジックは`_decode_image_data_url()`/`_sanitize_save_filename()`としてモジュール関数に切り出し、既存の`save_image_to_gallery`ハンドラもこちらを使うようリファクタ(重複コード解消、既存動作は不変)。新規ルート`POST /wfm/gallery/image/save-to-folder`。
|
||||
|
||||
**5. 新規: GenerateUI「カタログ作成」/「カタログ」ボタン**: Style選択欄の右隣に設置。
|
||||
- スタイル選択の対象は、当初「全スタイル/選択中の1件」のラジオ選択UIを新設する設計で計画していたが、ユーザーから「カタログ作成の選択をバッチタブのStyleタブで行えるようにしたい。これにより複数選択も可能にしたい」とのフィードバックを受け、**新規UIを作らずBatchタブStyleサブタブの既存チェックリスト(`_batchStyleSelected`)をそのまま使う**方式に変更(複数選択は元から対応済み)。カタログ作成モーダルは保存先フォルダの指定(新規作成/既存選択)のみを担当する、よりシンプルな設計になった。
|
||||
- `_runBatchLoop`に第4引数`onResultFn(item, result)`を追加(既存呼び出し元は省略時no-opのため無影響)。カタログ作成はこのコールバックで、生成結果を`comfyUI.getImageBlob()`→data URL化→`save_image_to_folder`へPOST(ファイル名=スタイル名、拡張子はバックエンド側でBlobの実MIMEタイプから解決)。
|
||||
- 「カタログ」ボタン(カタログ作成ボタンの右隣、ユーザーからの追加要望)は、Galleryタブ→Style_Catalogサブタブへワンクリックで遷移するショートカット。
|
||||
|
||||
**6. Output Galleryのプロンプト表示修正(前セッションからの持ち越し)**: v0.3.94リリース直後、ユーザーがKapture目視確認で「Output Galleryの詳細パネルにプロンプトが表示されていない」ことを発見(リリースノートには書いたが実装漏れだった)。`gallery-tab.js`の`loadImageDetail()`が`metaRes`(`image_prompt`フィールドを含む)を取得していながら使っていなかったバグで、`renderImagePromptSection()`を追加し表示欄(Info タブ、Tags欄の上)を新設して解消。ユーザーの指示で当時はコミット・リリースまでは行わず、今回のブランチに持ち越して一緒に含めた。
|
||||
|
||||
**ヘルプタブ更新**: `project_v0336_conventions`の慣習(index.html + i18n.js 3言語 + app.jsのhelpIdMapの3点セット)に従い、Galleryタブヘルプの「Style/Prompt Gallery」カードを「ImagePrompt Gallery」に改名・`ws_image_prompt`表記に修正、新規「Style_Catalog Gallery」カードを追加。GenerateUIタブヘルプにもCreate Catalog/Catalogボタンの説明を追加。
|
||||
|
||||
**検証**: 各段階でNode `--check`(JS構文)・`python -m py_compile`(Python構文)・開発元と実行時`custom_nodes`フォルダの`diff -rq`比較を実施。ユーザー自身が実機でGallery 3サブタブ化・ImagePromptの既存データ動作・カタログ作成→保存→Style_Catalogでの閲覧→Select as Style→カタログボタンでの遷移、を一通り確認済み。
|
||||
|
||||
**How to apply**:
|
||||
1. 新機能が既存のバッチ処理・生成ループと概念的に重なる場合、専用の新規実装を書く前に「既存のバッチループに小さなフック(コールバック引数など)を追加するだけで実現できないか」を検討する。今回`_runBatchLoop`への1引数追加で、進捗バー・Pause/Resume・エラーハンドリングを含む既存バッチUI全体をタダで手に入れられた。
|
||||
2. ユーザーから「選択はA画面で行い、B画面はC機能だけ担当させたい」といった役割分担の指摘を受けたら、独自の選択UIを増やさず既存の選択UI(この場合Batchタブのチェックリスト)を再利用できないか確認する — 実装量が減るだけでなく、ユーザーにとって覚える操作系統が1つで済む。
|
||||
3. 「ファイル名を画像から画面Aのデータに紐付ける」機能を作る際、画像に実際に埋め込まれた値をそのまま複製・適用するのか、それとも名前で元のマスターデータ(この場合Style JSON)を検索し直すのかは、ユーザーの意図次第で大きく設計が変わる(前者はスナップショット的、後者は常に最新のマスターデータを参照する)。曖昧なら実装前に確認する。
|
||||
|
||||
---
|
||||
|
||||
## v0.3.94
|
||||
|
||||
### 機能追加: Gallery タブのサブタブ化 + Style/Prompt ギャラリー新設(視覚的プロンプトビルダー)
|
||||
|
||||
ユーザーから「Galleryタブをサブタブ化してスタイル・プロンプト用ギャラリーを追加したい。サムネイルによるスタイル/プロンプトの閲覧・プロンプト作成を行いたい」との要望を受けて新規実装。既存のGalleryタブの挙動は「Output」サブタブとしてそのまま残し、隣に「Style/Prompt」サブタブを新設した。参考として`comfyui_prompt_gallery`(CivitAI配布PonyXL wildcardパックをサムネイル一覧化しクリックでプロンプト挿入するツール)と、ユーザーの別プロジェクト`prompt_builder_proto`(CLIP埋め込み検索まで持つ高機能プロトタイプ)の2つが示されたが、後者の3D空間表示・埋め込み検索等は対象外とし、ユーザー指定の「左フォルダツリー/中央サムネイル/右にプロンプト表示+作成欄/下部コピーボタン」という素の画面構成のみを踏襲した。ブランチ`feature/style-prompt-gallery`で作業。
|
||||
|
||||
**1. データ設計判断: プロンプトは`.txt`サイドカーで保存し、`gallery_metadata.json`には触れない**: 既存の`GalleryMetadataStore`(`gallery_metadata.json`)は起動時にメモリへロードし保存時にファイル全体を書き戻す実装のため、ComfyUI実行中に外部スクリプトで数百件を直接書き込むと、サーバー側の別の保存操作で上書き・消失するリスクがあった。加えて`cleanup_stale_images()`はフォルダパスの**前方一致**でメタデータを判定しており、非再帰スキャンで親フォルダをlist_imagesすると、実際はサブフォルダに存在する画像のメタデータを「無くなった」と誤判定して削除してしまう潜在バグが既存コードにあることも判明(Output側のフラットな日付フォルダ構成ではほぼ顕在化しないが、深い階層を持つStyle/Promptギャラリーでは実害が出うる)。これらを踏まえ、プロンプトデータは画像と同名の`.txt`サイドカーファイル(例: `mobile_trooper.png` + `mobile_trooper.txt`)として画像フォルダに直接置く方式にした。実行中のJSONストアを一切触らないため競合リスクがゼロになり、かつ「画像+txtを置くだけ」でユーザー自身が将来データを追加できる最も簡単なフォーマットになる、という一石二鳥の設計。
|
||||
|
||||
**2. バックエンド (`gallery_service.py` / `gallery_routes.py`)**: `_read_sidecar_prompt()`/`save_style_prompt()`で`.txt`サイドカーの読み書きを実装し、`get_image_metadata()`の戻り値に`style_prompt`フィールドを追加(Outputギャラリー側からws_style_promptフォルダを閲覧した際にも同じ仕組みでプロンプトが表示される)。`list_images()`の検索フィルタにもサイドカー内容を追加。新規ルート`GET /wfm/gallery/style-prompt/root`・`POST /wfm/gallery/image/style-prompt`を追加。Settingsでユーザーが Output ギャラリーのルートを実outputフォルダ以外に変更していてもStyle/Promptギャラリー(常に実output直下)へアクセスできるよう、`_comfy_output_root`という不変ルートを`_allowed_root`とは別に保持し、`_check_path_allowed()`をいずれか一方の配下なら許可するよう拡張した。
|
||||
|
||||
**3. フロントエンド**: `templates/index.html`のGalleryタブ先頭に`lab-tab.js`の`.wfm-lab-subtab-*`と同一パターンの`.wfm-gallery-subtab-nav`を追加し、既存の3カラムmarkupを`#wfm-gallery-panel-output`でラップ、新規`#wfm-gallery-panel-style`を追加。既存`gallery-tab.js`(1994行、favorite/tags/groups/bulk操作等が密結合したシングルトン実装)への機能追加によるregression リスクを避けるため、Style/Prompt専用の新規ファイル`static/js/style-gallery-tab.js`を作成し、既存RESTエンドポイントを再利用しつつレンダリングのみ独自実装した。`i18n.js`はen/ja/zh 3言語に新規キーを追加(既存の`galleryFolders`/`gallerySelectFolder`/`galleryNoImages`/`gallerySearchPlaceholder`等、定義済みだが未使用だったキーをここで初めて実際に使用した)。ヘルプタブは`project_v0336_conventions`メモの「index.html + i18n.js(3言語) + app.jsのhelpIdMapの3点セット」の慣習に従い新規カードを追加。
|
||||
|
||||
**4. シードデータ投入**: `tools/import_style_prompt_seed.py`を新規作成(PyYAML不要、`comfyui_prompt_gallery/web/prompt_gallery.js`の`parseYamlForImages`と同じインデントベースの簡易パーサをPythonに移植)。ユーザーの`wildcard_data`フォルダ(`pack: set: category: leaf: [tag_string]`形式のYAML + `thumbnails/`配下の対応画像)のうち、サムネイル画像を伴う6カテゴリ(artstyle/body/expression/job/pose/scene)から、画像とタグの対が実際に揃っている**460枚**のみを`output/ws_style_prompt`へコピー+`.txt`サイドカー生成した(残り487枚は元データ側にタグ定義が無く「テキストのみ」相当のため、ユーザー指示通りスキップ)。CivitAI配布パックの再配布ライセンス問題を避けるため、実データ画像はリポジトリにコミットせず、書き込み先はユーザー個人のローカルComfyUI outputフォルダのみとした。
|
||||
|
||||
**5. フォローアップ改善(実機フィードバックを受けて)**:
|
||||
- **再帰的な画像表示**: 親フォルダを選択してもサブフォルダの画像が0件表示になっていた(インポートしたデータが深い階層に配置されるため)。`list_images()`に`recursive`パラメータを追加し`_scan_folder_recursive()`(`os.walk`ベース)を新設、Style/Promptギャラリー側は常に`recursive=true`で呼び出すよう変更。フォルダツリーの`list_folder_tree()`も`image_count`(直下のみ、Output側で従来通り使用)とは別に`image_count_total`(サブフォルダ込みの合計、後方互換で追加)を返すようにし、ツリーの件数バッジもStyle/Prompt側では合計値を表示するよう修正。
|
||||
- **右ペイン2カラム化**: 選択画像プレビュー/プロンプト/選択済みチップ(左)と、最終プロンプト(右、縦いっぱいに伸びる)に分割。詳細パネル幅を320px→520pxに拡大。
|
||||
- **選択済みプロンプトのチップ表示から拡張子を除去**: `chip.filename`表示時に`.replace(/\.[^.]+$/, "")`。
|
||||
- **ponyxlWildcardsVault形式のライブ(未インポート)対応**: ユーザーが`wildcard_data`のカテゴリフォルダ(yaml + thumbnails/、`thumbnails_option2/`の別プレビュー画像`{leaf}.preview3.ext`含む)を生のまま`ws_style_prompt`配下に置いて確認したところ「対応させたい」との要望。`_read_sidecar_prompt()`を「1. `.txt`サイドカーを優先 → 2. 無ければponyxlWildcardsVault形式としてその場でYAML解決」の2段構えに変更。`_find_vault_category_root()`で画像の祖先フォルダを最大8階層遡り`thumbnails`/`thumbnails_option2`を直下に持つフォルダ(=カテゴリルート)を探し、そこに隣接する`*.yaml`を都度パース(YAML群のmtimeシグネチャでインスタンス内キャッシュ)。二重拡張子ファイル名(`alchemist.preview3.jpeg`)にも対応するため、リーフ名候補は`ファイル名.split(".")[0]`で取る。同じロジックを`tools/import_style_prompt_seed.py`側にも移植し、`thumbnails_option2`もスキャン対象に含めた。
|
||||
|
||||
**6. フォルダ名タイポ修正**: ユーザーが当初指定したフォルダ名`ws_style_plompt`が実はスペルミス(正しくは`ws_style_prompt`)と判明。実データフォルダを`mv`でリネームし(460枚+vaultフォルダのデータはそのまま保持)、コード内の全参照(`STYLE_PROMPT_FOLDER_NAME`定数、`index.html`、`i18n.js`3言語のヘルプ文、`style-gallery-tab.js`コメント、`import_style_prompt_seed.py`)を一括修正。
|
||||
|
||||
**トラブルシューティング: 「ComfyUI再起動したのに404」の切り分け**: バックエンドのルート追加後、ユーザーが「再起動した」と報告したにもかかわらず新規エンドポイントが404/405を返す事象が発生。`curl -i`でヘッダを確認したところ、GETの404レスポンスが`Content-Type: application/octet-stream`+`Transfer-Encoding: chunked`という、自前のJSON APIハンドラ(常に`web.json_response`でapplication/json)とは異質なシグネチャだったことと、POSTが404ではなく`405 Method Not Allowed`(`Allow: GET,HEAD`)を返したことから、リクエストが自作ルートに全く到達せずaiohttpの静的ファイル系フォールバックに吸収されている=新しいルート登録が実際には有効化されていないと判断。`netstat`でポートを握っているプロセスを特定し、`Get-Process`でその起動時刻を確認したところ、コード変更よりずっと前から起動し続けているプロセスであることが分かり、「再起動」が実際にはポートを握るプロセスに反映されていなかったことを特定できた。
|
||||
|
||||
**How to apply**:
|
||||
1. 複数プロセス/外部スクリプトから同時に書き込まれうるJSONストア(`GalleryMetadataStore`のような「起動時ロード→都度書き戻し」実装)に、バッチ処理や別プロセスからデータを注入したい場合は、そのストアを経由せず**ファイルシステム上の独立したファイル**(サイドカー等)に逃がすことを検討する。競合の心配なく安全に外部から書き込める。
|
||||
2. `cleanup_stale_images()`のようなフォルダ配下メタデータの「前方一致による孤立削除」処理は、**呼び出し元が実際にスキャンした範囲**(非再帰なら直下のみ)を正しく反映した`existing_paths`を渡さないと、スキャンしていない孫階層のメタデータを誤って削除しうる。再帰スキャンに切り替える際は、この既存ロジックとの整合性を必ず確認すること。
|
||||
3. バックエンドAPIの新規エンドポイントが「再起動したのに反映されない」ように見える場合は、`curl -i`でレスポンスヘッダ(Content-Type、Transfer-Encoding、405のAllow等)を確認すると、リクエストが自作ハンドラに届いているか・別のフォールバック機構に吸収されているかの切り分けに使える。合わせて`netstat`でポートを握っているPIDを特定し`Get-Process`/`Get-CimInstance Win32_Process`でそのプロセスの起動時刻を見れば、「再起動」がそのプロセスに実際に反映されているかを客観的に確認できる。
|
||||
4. CivitAI等サードパーティ配布のデータセットをローカルで加工・利用する場合、生成物(画像そのもの)はリポジトリにコミットせず、変換・投入スクリプトのみをコミットしてユーザー自身のローカル環境に対して実行する方式にすることで、再配布ライセンス問題を回避できる。
|
||||
|
||||
---
|
||||
|
||||
## v0.3.93
|
||||
|
||||
### バグ修正・機能改善: Labタブ VAEキーフレーム不発バグの修正+Style適用UI刷新+Plan JSONスクロール同期修正+キーフレーム個別削除+Batch数超過警告+ワイルドカード対応+Save index image デフォルトON
|
||||
|
||||
ユーザーからの実機フィードバックを受けて、Labタブに対して一連の修正・改善をまとめて実施した。
|
||||
|
||||
**1. VAEキーフレームが2回目・3回目以降に反映されないバグの修正**: ユーザーから「Labでチェックポイント焼き込みVAE構成のワークフローに対し、VAEキーフレームを2列目・3列目に追加して実行したが、生成画像のメタデータを確認するとVAEが変更されていなかった」との報告を受け調査。`_buildWorkflowForIteration()`(`lab-tab.js`)は`analysis.vae_nodes[0]`という「ワークフロー中の`VAELoader`ノードを機械的に拾っただけの最初の1件」に無条件で書き込む設計だったが、独立した`VAELoader`ノードを持たず、チェックポイントに焼き込まれたVAEをそのまま使う構成のワークフロー(実際にユーザーが使用した`simple_i2i_save.json`は`VAELoader`ノードが存在した通常構成だったため、このケース自体には該当しなかったが、独立VAELoaderが無いワークフロー全般に共通する潜在バグとして特定・修正)では`vae_nodes`が空になり、キーフレームで指定した値が警告なく黙って捨てられていた。`analysis.vae_nodes[0]`が存在しない場合、その回のワークフロー複製に`VAELoader`ノードを動的に追加し、`vae`入力を持つ全ノード(`VAEDecode`/`VAEEncode`等)の接続先をそのノードへ張り替えるフォールバック処理を追加した。`comfyUI.currentWorkflow`自体は変更せず、`_buildWorkflowForIteration()`が毎回作るクローンにのみ適用するため、他のGenerateUIサブタブには影響しない。
|
||||
|
||||
**2. Style適用UIの刷新**: これまでPromptキーフレームの「Style」欄は、上部GenerateUIツールバーの Style 有効化チェックボックスがONの場合のみ機能する「Apply」ボタン(クリックするたびに上部で選択中のスタイル名をボタンラベルに表示)という設計だった。ユーザー要望により、(a) 上部の Style 有効化チェックボックスの状態に関係なく動作するように変更、(b) モーダル内に専用のON/OFFチェックボックスを追加してキーフレームごとに適用状態を保持、(c) 適用したスタイル名はボタン上ではなく横の別要素に表示、(d) チェックボックスをOFFにした際はその名前表示のみクリアし、既にPositive/Negativeへ追記済みのテキストは自動削除しない(あくまでユーザーが手動管理)という仕様に変更した。実装の紆余曲折として、当初「チェックボックスをONにした瞬間に自動でスタイルを追記する」形で実装したが、ユーザーから「追加は(従来通り)Apply ボタンで行いたい」とフィードバックを受け、Apply ボタン押下時にのみ追記しチェックボックスを自動ON化する方式に修正した。適用状態(`styleApplied`/`styleName`)はキーフレームの`value`に永続化し、Plan保存/読込・モーダル再オープンでも復元される。
|
||||
|
||||
**3. Plan JSONタブのスクロール同期バグ修正**: Plan JSONタブのテキストエリアは、色付きシンタックスハイライト用の`<pre>`オーバーレイを背後に重ねる仕組みだが、他のRaw JSON表示(GenerateUIのRaw JSON等)と異なり`scroll`イベントリスナーの配線が漏れていたため、テキストエリアをスクロールしてもオーバーレイの表示位置が追従せず「スクロールしても表示が変わらない」ように見えるバグがあった。`json-highlight.js`の`syncScroll()`を`lab-tab.js`にimportし、`_initPlanJsonTab()`に`scroll`イベントリスナーを追加して解消した。
|
||||
|
||||
**4. キーフレームをモーダルから個別に削除可能に**: 各キーフレームの編集モーダルにある「削除」ボタンは、従来は列内の最後のキーフレームでのみ表示されていた。ユーザー要望により、1回目(baseline、常に固定)以外の全てのキーフレームで表示するよう変更(「−」ボタン自体は従来通り末尾のみ削除する仕様を維持)。途中のキーフレームを削除すると配列の`splice`により後続が自然に繰り上がる。
|
||||
|
||||
**5. Batch数超過時の警告トースト追加**: 「プランの適用回数よりBatch数が少なくなった場合はどうなるか」という質問を受けて挙動を調査したところ、Batch数を後から減らしてもキーフレームは削除・再採番されず、単に実行ループ(`for (let i = 1; i <= _lab.batchCount; i++)`)が届かなくなるだけで無警告だった(データは残るため、Batch数を再び増やせば復活する)。ユーザー要望を受け、`_maxKeyframeIteration()`で全列の最大`atIteration`を求め、現在のBatch数を超えていれば警告トーストを出す`_warnIfKeyframesExceedBatch()`を追加。Batch数入力欄の`change`イベントと、`_applyPlanData()`(Plan読込・Plan JSON Apply共通)の両方から呼び出す。
|
||||
|
||||
**6. Promptキーフレームでのワイルドカード対応**: 「プロンプトでワイルドカードを使いたい」との要望を受け、GenerateUIメインの生成フローが既に持っていたSPA側ワイルドカード展開処理(`generate-tab.js`の`_expandWildcardsInWorkflow()`、A1111形式`__name__`構文、`Workflow-Studio/wildcards/`配下の.txtから1行ランダム選択、ネストは最大5パス、`ImpactWildcardEncode`/`Processor`はサーバー側処理のため対象外)を`export`し、`lab-tab.js`の`_runLabBatch()`から各イテレーションのワークフロー構築直後・生成実行直前に呼び出すよう配線した。これによりPromptキーフレームのテキストに`__name__`を書いておけば、同じキーフレームを複数イテレーションで使い回していても毎回ランダムに再展開される。`generate-tab.js`は既に`lab-tab.js`から`initLabTab`をimportしており、今回の変更で双方向の循環importになるが、両関数とも関数宣言(hoisted)でトップレベル即時実行はしていないため問題なし(Node上での動的import検証でモジュールグラフの解決自体に問題がないことを確認済み)。
|
||||
|
||||
**7. 「Save index image to Output on Run」のデフォルトON化**: ユーザー要望により`_emptyLabState()`の初期値を`false`→`true`に変更。あわせて、修正過程で`_clearPlan()`が`saveIndexEl.checked`を無条件に`false`へ固定していた(内部状態とチェックボックス表示が食い違う潜在バグ)ことに気づき、`_lab.saveIndexOnRun`の実値を反映するよう修正した。既存の保存済みPlanファイルは`save_index_on_run`の値をそのまま保持するため影響を受けない。
|
||||
|
||||
**検証**: 各修正・機能追加ごとに`node --check`で構文検証、開発元リポジトリと実行時`custom_nodes`フォルダの`diff`比較で意図した差分のみであることを確認してから同期。VAE修正は`analyzeWorkflow()`の実データ(ユーザー提供の`simple_i2i_save.json`)に対するNode単体実行で`vae_nodes`検出ロジックを確認済み。循環import追加分はNode上で`import()`によるモジュール解決を検証済み(`window is not defined`はNode実行環境固有の話で、モジュールグラフ解決自体は正常に完了することを確認)。
|
||||
|
||||
**How to apply**: (1) `analysis.*_nodes[0]`のような「先頭要素決め打ち」パターンは、そのノード種別がワークフロー中に必ず1つ存在する保証がない限り、存在しないケースへのフォールバックを用意すること(VAELoaderのように「省略可能」なノードは特に注意)。(2) UIのON/OFFチェックボックスとその内部状態(`_lab.xxx`)を分離して持つ場合、リセット系の関数(`_clearPlan()`等)で値をハードコードせず、必ず内部状態から読み出すこと——デフォルト値を変更した際に無言でズレるバグの温床になる。(3) `generate-tab.js`と`lab-tab.js`は既に循環importの関係にあるため、新たに一方から他方の関数を使う場合はトップレベルで即時評価される値(`const`の即時代入等)を挟まないよう注意する(関数宣言はhoistされるため安全)。
|
||||
|
||||
---
|
||||
|
||||
## v0.3.92
|
||||
|
||||
### バグ修正: CLIPTextEncodeEditPlus使用ワークフローがGenerateUI経由だと直接実行と異なる画像になる問題(根本原因はconvertUiToApiのForceInput 未考慮バグ)+LoRA Stack機能の改善一式
|
||||
|
||||
ユーザーから「`CLIPTextEncodeEditPlus`(CLIP Text Encode edit+、`model-and-prompt-from-metadata`由来)と`Lora Loader (LoraManager)`を組み合わせたワークフローを、ComfyUIで直接実行した場合とWorkflow StudioのGenerateUI経由で実行した場合とで生成画像が異なる。シードも固定しているのに一致しない」という報告を受け、一連の調査・修正を行った。
|
||||
|
||||
**1. Metadata/Infoタブでのプロンプト抽出漏れ**: `CLIPTextEncodeEditPlus`はPositiveプロンプトの実体を`text1`(リンク入力、例えばLoraManagerの`trigger_words`出力)と`text_edit`ウィジェットを`mode`(RAW/EDIT/front/back)に応じて結合する専用ノードだが、`metadata-tab.js`(およびその移植版`node_sets_menu.js`のIタブ側)の`extractPromptsAPI`/`extractPromptsFromNodeSet`は`widgets_values[0]`(=`text_edit`のみ)を素朴に読むか、API形式では`inputs.text`/`text_g`/`prompt`キーしか見ておらずこのノード自体を全く認識できていなかった(結果、生成画像のPNG内蔵メタデータを見るとPositiveが空、Negativeしか表示されない)。ノード本体のPython実装(`metadata_checkpoint_node.py`の`CLIPTextEncodeEditPlus.encode()`)と完全に同じ結合ルールを`resolveEditPlusText(mode, textEdit, text1, text2)`として両ファイルに実装し、LiteGraph形式・API形式それぞれのtextMap構築ロジックに組み込んだ。なお`text1`がLoraManagerの`trigger_words`のように実行時に動的計算される値の場合、ワークフローJSON自体にはそのテキストが保存されていないため静的解析では復元できない(この制約はユーザーに明示済み)。
|
||||
|
||||
**2. 根本原因: `convertUiToApi`の`_getWidgetInputNames`/`_getWidgetInputTypes`が`forceInput: true`を考慮していなかった**: 上記の表示バグを追っている過程で、実際にComfyUIサーバー(`http://127.0.0.1:8189/object_info/CLIPTextEncodeEditPlus`)から取得したobject_infoと突き合わせたところ、真の実行結果不一致の原因を発見した。`text1`/`text2`はComfyUI側で`["STRING", {"forceInput": true}]`(リンク専用・ウィジェット化されない入力)として定義されているが、`comfyui-workflow.js`の`_getWidgetInputNames`/`_getWidgetInputTypes`はこの`forceInput`フラグを一切チェックしておらず、型がSTRING/INT/FLOAT/BOOLEAN等であれば`optional`入力も無条件にウィジェット名列へ含めていた。そのため`text2`(未接続)が誤って「ウィジェット」として扱われ、`widgets_values`の3番目に入っていた本来どのウィジェットにも対応しない余りの空文字列`""`が`text2`の値として吸い込まれ、送信されるAPIワークフローに`text2: ""`が**明示的に**含まれてしまっていた。Python側の`encode()`は`insert = text2 if text2 is not None else text_edit`という判定をしており、`text2=""`は`None`ではないため`insert = ""`が採用され、`mode: "back"`の場合`selected = text1 + ", " + ""`——**`text_edit`の内容が完全に欠落**していた。ComfyUI本体から直接実行した場合は未接続のforceInput入力が送信データに一切含まれず`text2=None`となるため、この欠落は発生しない。これが「同じワークフローなのに画像が異なる」「LoRA強度を変えても結果が変わらない(そもそも肝心のプロンプト本文が消えていたため無関係だった)」の直接の原因。`_getWidgetInputNames`/`_getWidgetInputTypes`双方の必須・オプション入力ループに`if (Array.isArray(spec) && spec[1]?.forceInput) continue;`を追加して除外するよう修正。この修正は`forceInput`付きオプション入力を持つ他のノード全般にも同様に効く汎用修正。
|
||||
|
||||
**3. GenerateUI Model タブ — LoRA Stack機能の改善**: 上記の検証と並行して、LoRA周りのUI/UXも3点改善した。
|
||||
- **Use Stack Groupチェックボックス**: `Lora Loader (LoraManager)`ノードが存在するワークフローを読み込んだ際、従来はStackタブが常にModelsタブの登録済み「Stack」グループを参照しており、ワークフロー自体が保持している実際のLoRA構成とは無関係だった。新設したチェックボックスで、OFF(ワークフロー読み込み時の既定)はLoraManagerノードに実際に設定されているLoRAをそのまま表示・編集し、ON はModelsタブの「Stack」グループを表示・編集するよう切替可能にした。切替時は必ず対象ノードのLoRA一覧をクリアしてから新しいソースを読み込み、OFFへ戻すとワークフロー読み込み時点のLoRA一覧(読み込み時にスナップショットとして保存)へ正確に復元される。
|
||||
- **LORA SYNTAX表示が1件しか出ない不具合の修正**: SingleタブのLORA SYNTAXはLoraManagerノードの`loras[0]`(1件目)のみを見る設計(Single=1件専用のため仕様通り)だが、Stackタブ側もModelsタブ登録グループしか見ておらず、結果的に「ワークフローに実際設定されている複数LoRA」を表示する手段がどこにもなかった。上記のチェックボックスと合わせて、新規読み込み時にLoRAが2件以上あれば自動でStackタブを初期表示するようにし、正しく全件表示されるようにした。
|
||||
- **タブ切替でStackのON/OFF状態が意図せず戻る不具合の修正**: 「ワークフロー状態」表示モードでは、Modelタブへ戻るたびの単純な再描画のたびに各LoRAの有効/無効状態(`_stackActive`)をワークフロー本来のデータで毎回強制上書きしていたため、ユーザーがStackパネルのトグルオールチェックボックスをOFFにしても次の再描画で無条件にONへ戻ってしまっていた。ワークフロー実データからの同期を「新規読み込み時」と「Use Stack GroupチェックボックスをOFFに戻した直後」の2タイミングのみに限定し、それ以外の再描画では既にメモリ上にある値を維持するよう修正。ついでに`stackModels.every()`が空配列に対し空虚な真を返すことで、LoRAが0件のときトグルオールチェックボックスが誤ってON表示になる副次的な表示バグも修正した。
|
||||
|
||||
**検証**: ユーザー自身が実機で確認。(1) `lora_manager_normal_clip.json`(ネイティブCLIPTextEncode使用)でComfyUI直接実行とGenerateUI実行の生成画像が同一であることを確認。(2) `lora_m_editplus_comfyUI.json`(CLIPTextEncodeEditPlus使用、mode: back)でも同様に画像が同一であることを確認。(3) 残る3モード(RAW / EDIT / front)についても結果が同一であることを確認済み。実サーバーの`/object_info`を取得しての突き合わせ、および修正前後のconvertUiToApiロジックの単体シミュレーションで根本原因を再現・修正確認済み。
|
||||
|
||||
**How to apply**: (1) ComfyUIのカスタムノードで`optional`の`forceInput: true`入力を追加する場合、Workflow Studio側のUI→API変換ロジックはこのフラグを尊重する前提で書くこと(`_getWidgetInputNames`/`_getWidgetInputTypes`が該当)——見落とすと、未接続時に本来送信されるべきでない値が紛れ込み、Pythonの`if x is not None`判定を静かに壊す。(2) ワークフローJSON上に存在しない・実行時にしか計算されない値(今回のLoraManagerの`trigger_words`のように)は、静的なメタデータ抽出では原理的に復元できないことをドキュメント・ユーザー説明の両方で明示すること。(3) 複数箇所に同種のロジックが移植されている場合(`metadata-tab.js`と`node_sets_menu.js`など)、片方だけ直して終わりにせず両方に同じ修正を適用し、`node --check`+差分比較で開発元/ランタイム両フォルダの同一性を確認してから同期する。
|
||||
|
||||
---
|
||||
|
||||
## v0.3.91
|
||||
|
||||
### 機能拡張: Labインデックス画像にPlanメタデータをPNG埋め込み+README構成整理(Changelogセクション廃止)
|
||||
|
||||
v0.3.90でLabタブに追加した「Run時インデックス画像Output保存」機能について、ユーザーから「インデックス画像にPlanのメタデータは埋め込まれていないのでは」と確認を受け調査したところ、実際に埋め込まれていないことが判明。`_buildIndexImageDataUrl()`は`canvas.toDataURL("image/png")`でピクセルデータのみのプレーンなPNGを生成しており、バックエンド側(`lab_plan_service.py`の`save_index_image()`/`save_index_image_to_output()`)も受け取ったbase64をそのままバイト列として書き込むだけだった。特にOutputフォルダ側のコピーは対になる`.json`が存在しないため、画像単体では「どのPlanで生成したか」を後から追跡する手段が一切なかった。「Planドロップエリアにドロップして読み込める形にしたい」という要望を受け対応。
|
||||
|
||||
**PNG埋め込みの実装**: `static/js/util.js`に`embedPngTextChunk(dataUrl, keyword, text)`を新規追加。PNGのIHDR直後に**iTXt**チャンクを挿入する(挿入位置・CRC計算ロジックは、ComfyUI本体が既に持つワークフロー埋め込み機能=`web/comfyui/top_menu_extension.js`の`embedWorkflowInPng`と同じ方式を踏襲)。**tEXtではなくiTXtを選んだ理由**: このコードベースの既存PNGチャンク読み取り(`metadata-tab.js`の`readAllPNGTextChunks`)は、tEXtのtextフィールドをLatin-1でデコードする実装になっている。一方書き込み側(`embedWorkflowInPng`含む)は`TextEncoder().encode()`でUTF-8エンコードしているため、非ASCII文字(日本語のNoteやプロンプトなど)を含むテキストをtEXt経由で埋め込むと、読み取り時にLatin-1誤変換で文字化けする。iTXtチャンクは仕様上UTF-8前提であり、`readAllPNGTextChunks`の`parseITXtChunk`は既に正しくUTF-8デコードを行っているため、新規キー`wfm_lab_plan`はiTXtで統一した(既存のtEXt/workflow埋め込みが同じ問題を抱えている可能性があるが、それは既存機能でありスコープ外として手を付けていない)。
|
||||
|
||||
**読み書きの配線**: `metadata-tab.js`の`readAllPNGTextChunks`を新たに`export`(元は非export、Lab側から再利用するため)。`lab-tab.js`に`LAB_PLAN_PNG_KEY = "wfm_lab_plan"`を追加し、`_buildIndexImageDataUrl(planData)`が省略可能引数`planData`を受け取ってJSON文字列化・埋め込むよう変更。呼び出し元の`_savePlan()`と`_maybeSaveIndexImageOnRun()`双方で、既に構築済みの`_buildPlanData()`の結果を渡すようにした——Plan Save側(lab_plan/内、対になる.jsonが既にある)にも同じ埋め込みを行い、画像単体を持ち出しても再現可能にする一貫性を優先。`_loadPlanFromIndexImage(file)`は、まず`readAllPNGTextChunks(file)`でチャンクを直接読み`wfm_lab_plan`があれば`JSON.parse`して`_applyPlanData()`へ渡す(サーバー通信不要)よう変更し、埋め込みが無い古いインデックス画像に対してのみ従来の「同名.jsonをサーバーから取得」にフォールバックする。
|
||||
|
||||
**検証**: (1) Node単体テストでembed→PNGバイト解析→JSON.parseの往復を検証(日本語+絵文字を含む文字列が完全一致することを確認)。(2) Kaptureで実際にComfyUIを操作し、T2Iモード+Save index on Run+日本語/絵文字入りNoteでRunを実行、実際に生成された`Lab_index_00003_.png`の実バイトを別のNodeスクリプトで直接読み取り、埋め込まれた`wfm_lab_plan`チャンクの内容が実際のPlan状態と完全一致することを確認。(3) ブラウザの`evaluate`経由で`fetch`+`File`+`DataTransfer`+合成`drop`イベントを構築し、サーバー側に対応する`.json`が一切存在しないこのOutputフォルダPNGを実際にPlanドロップゾーンへドロップ、T2Iモード・Save index on Runチェックボックス・Note(日本語+絵文字)・Batch数・ワークフロー記録(Open Workflowボタン)が全てサーバー通信なしで正しく復元されることをスクリーンショットで確認済み。
|
||||
|
||||
**README構成整理**: README.mdの`## Changelog`セクション(v0.1.1〜v0.3.90まで692行)を全削除。バージョンを重ねるごとに肥大化しており、GitHub Releaseのリリースノートと内容が重複していたため、ユーザーの意向で「今後はGitHub Releaseのリリースノートのみでバージョン履歴を管理する」方針に変更。あわせて`CLAUDE.md`のリリース手順から「READMEのChangelogにエントリを追加」の手順を削除し、代わりに`gh release create`のリリースノート本文に変更点を記載する旨を明記した。README.mdは692行分の削減(1248行→556行)。
|
||||
|
||||
**How to apply**: (1) 今後PNGに新しいカスタムメタデータを埋め込みたい場合は、必ずtEXtではなく**iTXt**を使うこと(このコードベースのtEXt読み取りはLatin-1decodeのため非ASCII文字が壊れる)。`util.js`の`embedPngTextChunk(dataUrl, keyword, text)`と`metadata-tab.js`の`readAllPNGTextChunks(file)`(export済み)がその書き込み/読み取りのペア。(2) リリース時のバージョン履歴はREADME.mdではなく`gh release create`のリリースノートに記載する(README.mdにChangelogセクションを復活させない)。
|
||||
|
||||
---
|
||||
|
||||
## v0.3.90
|
||||
|
||||
### 機能拡張: Labタブの進化(ワークフロー呼び出し・T2I対応・Run時インデックス画像Output保存+Eagle連携・プラン接頭辞)+Galleryタブのルート表示簡略化
|
||||
|
||||
v0.3.87〜v0.3.89で実装したLabタブ(GenerateUI)に対する、実際の運用を通じたユーザーからの一連の追加要望をまとめて対応。
|
||||
|
||||
**1. Plan JSONへのワークフロー記録+呼び出し(Open Workflowボタン)**: これまでLabのPlanには「どのワークフローに対して」実行したキーフレーム設定なのかが記録されておらず、後日Planを見返しても再現できない問題があった。`_buildPlanData()`(`lab-tab.js`)が`#wfm-gen-wf-name`の`dataset.filename`(GenerateUIに現在ロード中のワークフローファイル名)を読み取り`workflow_filename`としてPlan JSONに保存するようにし、Plan読込後にPLANボックス内へ表示される**Open Workflow**ボタンから、その記録されたワークフローファイルを`/api/wfm/workflows/raw`経由で取得し`loadWorkflowIntoEditor()`へ渡してGenerateUIへ読み込み直せるようにした。自動読込はせず、常に`window.confirm`で確認を挟む(現在編集中のワークフローを不意に上書きしない安全策、ユーザー指定)。`loadWorkflowIntoEditor`は`generate-tab.js`にあり、`generate-tab.js`は既に`lab-tab.js`から`initLabTab`をimportしているため、静的importすると循環import(`generate-tab.js`→`lab-tab.js`→`generate-tab.js`)になる。v0.3.87で`getEagleSettings`/`saveToEagle`を`util.js`へ移設して回避した前例があるが、`loadWorkflowIntoEditor`はgenerate-tab.js固有の依存が多く移設は非現実的なため、今回はボタンのクリックハンドラ内で`const { loadWorkflowIntoEditor } = await import("./generate-tab.js");`と**動的import**する方式を採用(`gallery-tab.js`が`tagger-tab.js`に対して既に使っている前例パターンを踏襲)。
|
||||
|
||||
**2. T2Iワークフロー対応**: LabはもともとI2Iバッチ生成専用で、ソース画像が無いと`_runLabBatch()`が`labNoSourceImage`エラーで実行をブロックしていた。Imageペイン最上部に**T2I workflow (no source image)**チェックボックスを追加し、ON時は(a) ソース画像必須チェックをスキップ、(b) `_buildWorkflowForIteration()`でLoadImageノードへの書き込みを完全にスキップ(`imageRef = null`)、(c) Imageドロップゾーンと「Use generated image for next」をグレーアウト(既存の画像は削除せず、I2Iに戻したときのため保持)。Resultsパネルのソース画像欄には代わりに「T2I workflow (no source image)」の注記を表示。設定は`t2i_mode`としてPlan JSONに保存。実機確認では、実際にT2Iワークフロー(`EmptyLatentImage`使用、LoadImageノード無し)で画像生成に成功し、Eagle自動保存も正常動作することを確認した(検証中、テスト対象ワークフローのCheckpointが存在しないモデル名だったことによる`/prompt` 400エラーに遭遇したが、これはT2I機能自体のバグではなくテスト環境のモデル設定の問題だった)。
|
||||
|
||||
**3. Run時にインデックス画像をOutputフォルダへ保存+Eagle連携**: 右ペインに**Save index image to Output on Run**チェックボックスを追加。ONの場合、Run完了ごとに`_buildIndexImageDataUrl()`で作った9枚コンタクトシートを新設バックエンドAPI `POST /api/wfm/lab/index-image/save-to-output`へ送信し、`py/services/lab_plan_service.py`の`save_index_image_to_output()`が`folder_paths.get_output_directory()` + `folder_paths.get_save_image_path("Lab_index", output_dir)`を使って、通常の生成画像と同じ自動採番規則で`Lab_index_00001_.png`のように保存する(上書きしない)。Plan Save側の動作(`lab_plan/`への保存)は完全に独立したまま変更していない。続けて「インデックス画像もEagleに保存したい」という追加要望を受け、Output保存が成功した後に既存のグローバル設定(Settingsタブの`eagleAutoSave`、生成画像のEagle保存と同じ仕組み)を流用して`saveToEagle()`を呼ぶだけの実装を追加——Lab専用の別トグルは増やさず、既存パターンにそのまま乗せた。設定は`save_index_on_run`としてPlan JSONに保存。バックエンドのルート登録はComfyUI起動時の1回のみのため、この機能だけはPythonファイル変更を伴い**ComfyUI再起動後に実機確認**(Outputフォルダへの`Lab_index_00001_.png`保存、コンソールの`[Eagle] Saved: Lab_index_00002_.png`ログの両方を確認)。StabilityMatrix環境では`custom_nodes/.../output`が実体`Images/Text2Img`へのsymlinkになっている点に留意(`folder_paths.get_output_directory()`はsymlink越しに正しく解決される)。
|
||||
|
||||
**4. プランファイル名への`ws_labplan_`接頭辞自動付与**: `_savePlan()`(Plan Save/Save As共通処理)で、プロンプトに入力された名前から`_stripLabPlanPrefix()`で既存の接頭辞を除去してから`ws_labplan_`を付け直す方式にし、二重接頭辞を防止(ユーザーが手動で接頭辞込みの名前を入力しても安全)。JSON内部の`"name"`フィールドは接頭辞なしのプレーンな名前のまま(表示用と実ファイル名を分離)。Plan JSONサブタブのプレビュー(`_syncLabJsonView`)も同じ接頭辞除去ロジックで統一。
|
||||
|
||||
**5. Galleryタブ — ルートフォルダ表示の簡略化**: フォルダツリーのルートエントリが実際のディレクトリ名(例: StabilityMatrix環境の`Text2Img` — outputフォルダが`Images/Text2Img`へのsymlinkになっているため)をそのまま付けて「[root] Text2Img」と表示していたが、ルートにはT2I以外の画像(Lab_indexなど各種生成物)も含まれるため実態と合わず紛らわしいという指摘を受け、`gallery-tab.js`の`renderTreeNode()`で単に「[root]」とだけ表示するよう変更(`label.textContent = isRoot ? "[root]" : node.name;`)。
|
||||
|
||||
**README構成の見直し**: Featuresセクションが17個の`### <タブ名>`セクションで非常に長くなっていたため、GitHub Flavored MarkdownのHTML `<details><summary>`要素で各タブセクションを折りたたみ可能にした(見出しレベルは`<summary><h3>...</h3></summary>`として維持)。Changelog等の他セクションは対象外(ユーザー指定は「タブの項目ごと」=Featuresセクションのみ)。
|
||||
|
||||
**検証**: 4機能とも実機(Kapture経由でComfyUIの`http://127.0.0.1:8189/wfm`を直接操作)で確認済み。ワークフロー呼び出しはPlan保存直後にファイル名とボタンが表示されること・クリックで確認ダイアログ→再読込を確認(当初Save経路でUI更新関数`_updatePlanWorkflowUI()`を呼び忘れる不具合があり、実機確認で発覚・修正)。T2Iモードは実際の画像生成成功、Output保存はComfyUI再起動後に`Lab_index_00001_.png`の生成、Eagle連携はコンソールログとファイル両方で確認、Galleryルート表示はスクリーンショットで確認。いずれもテスト用に生成したファイルは検証後に削除(Output画像の削除はユーザー側で実施)。
|
||||
|
||||
**How to apply**: (1) Lab関連でstateを更新する処理(Save/Load/Clear)を追加・変更する際は、対応するUI更新関数を**全ての状態変更経路**で呼び忘れていないか確認すること — 今回まさにSave経路で呼び忘れて実機確認で発覚した。(2) `lab-tab.js`から`generate-tab.js`の関数を使いたい場合、`util.js`への機能移設が大げさすぎるなら動的import(`await import("./generate-tab.js")`)を検討する。(3) 新しいLabのRun時副作用(Output保存等)を追加する際は、可能な限り既存のグローバル設定(Eagle自動保存など)に乗せ、機能ごとに新しいトグルを増やさないこと。(4) StabilityMatrix環境のようにComfyUIのoutputフォルダがsymlinkになっている場合でも`folder_paths.get_output_directory()`は正しく解決されるが、`ls -lt`等で直接調査する際はsymlinkの実体を辿る必要がある。
|
||||
|
||||
---
|
||||
|
||||
## v0.3.89
|
||||
|
||||
### バグ修正: v0.3.88で追加したLab機能への実動作確認フィードバック3件を反映
|
||||
|
||||
@@ -0,0 +1,24 @@
|
||||
"""Runs before ComfyUI imports any custom node — the only place early enough
|
||||
to populate os.environ for code that reads env vars at import/request time.
|
||||
|
||||
Loads a .env file (if present) from this plugin's root directory so the
|
||||
Unsloth backend's API key (UNSLOTH_API_KEY) can be set without editing
|
||||
settings.json or exposing it to the frontend.
|
||||
"""
|
||||
|
||||
from pathlib import Path
|
||||
|
||||
PLUGIN_DIR = Path(__file__).resolve().parent
|
||||
ENV_FILE = PLUGIN_DIR / ".env"
|
||||
|
||||
if ENV_FILE.exists():
|
||||
try:
|
||||
from dotenv import load_dotenv
|
||||
load_dotenv(ENV_FILE)
|
||||
except ImportError:
|
||||
print(
|
||||
"[WARNING] Workflow Studio: .env file found but python-dotenv is not installed "
|
||||
"(pip install -r requirements.txt). UNSLOTH_API_KEY will not be loaded from .env."
|
||||
)
|
||||
except Exception as e:
|
||||
print(f"[WARNING] Workflow Studio: failed to load .env file: {e}")
|
||||
+99
-32
@@ -2,11 +2,9 @@
|
||||
Gallery Routes - ギャラリータブ用APIエンドポイント
|
||||
"""
|
||||
import asyncio
|
||||
import base64
|
||||
import json
|
||||
import mimetypes
|
||||
import logging
|
||||
import re
|
||||
from pathlib import Path
|
||||
from aiohttp import web
|
||||
|
||||
@@ -43,6 +41,16 @@ def _init_allowed_root() -> None:
|
||||
except Exception as e:
|
||||
logger.warning("GalleryRoutes: failed to get ComfyUI output dir: %s", e)
|
||||
|
||||
# ImagePrompt/Style Catalogギャラリー用に実outputフォルダを常に別途保持する
|
||||
# (Settingsで_allowed_rootが別フォルダに変更されていても影響しないようにするため)
|
||||
try:
|
||||
import folder_paths # type: ignore
|
||||
output_dir = folder_paths.get_output_directory()
|
||||
if output_dir and Path(output_dir).is_dir():
|
||||
_service.set_comfy_output_root(output_dir)
|
||||
except Exception as e:
|
||||
logger.warning("GalleryRoutes: failed to get ComfyUI output dir for image-prompt root: %s", e)
|
||||
|
||||
|
||||
_init_allowed_root()
|
||||
|
||||
@@ -55,7 +63,12 @@ def setup_routes(app: web.Application):
|
||||
app.router.add_get("/wfm/gallery/image/serve", serve_image)
|
||||
app.router.add_get("/wfm/gallery/image/thumb", serve_thumb)
|
||||
app.router.add_post("/wfm/gallery/image/meta", save_image_meta)
|
||||
app.router.add_get("/wfm/gallery/image-prompt/root", get_image_prompt_root)
|
||||
app.router.add_post("/wfm/gallery/image/image-prompt", save_image_prompt)
|
||||
app.router.add_get("/wfm/gallery/style-catalog/root", get_style_catalog_root)
|
||||
app.router.add_post("/wfm/gallery/image/save", save_image_to_gallery)
|
||||
app.router.add_post("/wfm/gallery/image/save-to-folder", save_image_to_folder_route)
|
||||
app.router.add_post("/wfm/gallery/output-image/delete", delete_output_image)
|
||||
app.router.add_post("/wfm/gallery/image/favorite", toggle_favorite)
|
||||
app.router.add_get("/wfm/gallery/groups", list_groups)
|
||||
app.router.add_post("/wfm/gallery/groups", create_group)
|
||||
@@ -104,6 +117,7 @@ async def list_images(request: web.Request) -> web.Response:
|
||||
favorite_only = request.rel_url.query.get("favorite", "false") == "true"
|
||||
tag_filter = request.rel_url.query.get("tag", "")
|
||||
group_filter = request.rel_url.query.get("group", "")
|
||||
recursive = request.rel_url.query.get("recursive", "false") == "true"
|
||||
|
||||
if not folder:
|
||||
return web.json_response({"error": "folder parameter required"}, status=400)
|
||||
@@ -117,6 +131,7 @@ async def list_images(request: web.Request) -> web.Response:
|
||||
favorite_only=favorite_only,
|
||||
tag_filter=tag_filter,
|
||||
group_filter=group_filter,
|
||||
recursive=recursive,
|
||||
)
|
||||
# 検索なしのフォルダロード時にバックグラウンドインデックスを起動
|
||||
if not search:
|
||||
@@ -248,6 +263,36 @@ async def save_image_meta(request: web.Request) -> web.Response:
|
||||
return web.json_response({"error": str(e)}, status=500)
|
||||
|
||||
|
||||
async def get_image_prompt_root(request: web.Request) -> web.Response:
|
||||
"""GET /wfm/gallery/image-prompt/root — ImagePromptギャラリーのルートフォルダを返す"""
|
||||
root = _service.get_image_prompt_root()
|
||||
if root is None:
|
||||
return web.json_response({"error": "ComfyUI output directory not resolved"}, status=500)
|
||||
return web.json_response({"root": root})
|
||||
|
||||
|
||||
async def save_image_prompt(request: web.Request) -> web.Response:
|
||||
"""POST /wfm/gallery/image/image-prompt — 画像の.txtサイドカーにプロンプトを保存"""
|
||||
try:
|
||||
body = await request.json()
|
||||
img_path = body.get("path", "")
|
||||
prompt = body.get("prompt", "")
|
||||
if not img_path:
|
||||
return web.json_response({"error": "path required"}, status=400)
|
||||
ok = _service.save_image_prompt(img_path, prompt)
|
||||
return web.json_response({"ok": ok})
|
||||
except Exception as e:
|
||||
return web.json_response({"error": str(e)}, status=500)
|
||||
|
||||
|
||||
async def get_style_catalog_root(request: web.Request) -> web.Response:
|
||||
"""GET /wfm/gallery/style-catalog/root — Style Catalogギャラリーのルートフォルダを返す"""
|
||||
root = _service.get_style_catalog_root()
|
||||
if root is None:
|
||||
return web.json_response({"error": "ComfyUI output directory not resolved"}, status=500)
|
||||
return web.json_response({"root": root})
|
||||
|
||||
|
||||
async def toggle_favorite(request: web.Request) -> web.Response:
|
||||
try:
|
||||
body = await request.json()
|
||||
@@ -260,15 +305,6 @@ async def toggle_favorite(request: web.Request) -> web.Response:
|
||||
return web.json_response({"error": str(e)}, status=500)
|
||||
|
||||
|
||||
_SAVE_EXT_BY_MIME = {
|
||||
"image/png": ".png",
|
||||
"image/jpeg": ".jpg",
|
||||
"image/webp": ".webp",
|
||||
"image/gif": ".gif",
|
||||
"image/svg+xml": ".svg",
|
||||
}
|
||||
|
||||
|
||||
async def save_image_to_gallery(request: web.Request) -> web.Response:
|
||||
"""Image Edit Tab / AI Chat からの画像(PNG等)やSVGをギャラリーのルートフォルダに保存する。
|
||||
imageData は data URL (data:<mime>;base64,<data>) を想定。ヘッダがなければPNG扱い(旧互換)。"""
|
||||
@@ -283,33 +319,64 @@ async def save_image_to_gallery(request: web.Request) -> web.Response:
|
||||
if _service._allowed_root is None:
|
||||
return web.json_response({"error": "Gallery root not configured. Open Gallery tab and set output folder first."}, status=500)
|
||||
|
||||
# data URL から MIME タイプを判定し、拡張子を決定する
|
||||
raw = image_data
|
||||
mime = "image/png"
|
||||
if raw.startswith("data:"):
|
||||
header, _, raw = raw.partition(",")
|
||||
m = re.match(r"data:([^;]+)", header)
|
||||
if m:
|
||||
mime = m.group(1)
|
||||
ext = _SAVE_EXT_BY_MIME.get(mime, ".png")
|
||||
result = _service.save_image_to_folder(str(_service._allowed_root), filename, image_data)
|
||||
if not result["ok"]:
|
||||
return web.json_response({"error": result["error"]}, status=400)
|
||||
|
||||
# ファイル名サニタイズ(OSで使えない文字を除去)
|
||||
safe = re.sub(r'[<>:"/\\|?*\x00-\x1f]', "_", filename)
|
||||
if not safe.lower().endswith(ext):
|
||||
safe += ext
|
||||
|
||||
image_bytes = base64.b64decode(raw)
|
||||
|
||||
save_path = _service._allowed_root / safe
|
||||
save_path.write_bytes(image_bytes)
|
||||
|
||||
logger.info("save_image_to_gallery: saved %s (%d bytes)", save_path, len(image_bytes))
|
||||
return web.json_response({"ok": True, "path": str(save_path)})
|
||||
logger.info("save_image_to_gallery: saved %s", result["path"])
|
||||
return web.json_response({"ok": True, "path": result["path"]})
|
||||
except Exception as e:
|
||||
logger.error("save_image_to_gallery error: %s", e)
|
||||
return web.json_response({"error": str(e)}, status=500)
|
||||
|
||||
|
||||
async def save_image_to_folder_route(request: web.Request) -> web.Response:
|
||||
"""POST /wfm/gallery/image/save-to-folder — 任意フォルダへ画像を保存(同名なら上書き)。
|
||||
Style Catalogのカタログ作成で、スタイル名をファイル名として使う際に利用する。"""
|
||||
try:
|
||||
body = await request.json()
|
||||
folder = body.get("folder", "").strip()
|
||||
filename = body.get("filename", "").strip()
|
||||
image_data = body.get("imageData", "")
|
||||
|
||||
if not folder or not filename or not image_data:
|
||||
return web.json_response({"error": "folder, filename and imageData required"}, status=400)
|
||||
|
||||
result = _service.save_image_to_folder(folder, filename, image_data)
|
||||
if not result["ok"]:
|
||||
return web.json_response({"error": result["error"]}, status=400)
|
||||
return web.json_response({"ok": True, "path": result["path"]})
|
||||
except Exception as e:
|
||||
logger.error("save_image_to_folder_route error: %s", e)
|
||||
return web.json_response({"error": str(e)}, status=500)
|
||||
|
||||
|
||||
async def delete_output_image(request: web.Request) -> web.Response:
|
||||
"""POST /wfm/gallery/output-image/delete — ComfyUI標準の画像参照(filename/subfolder/type)から
|
||||
実ファイルを削除する。Style Catalogのカタログ作成で「Outputフォルダに画像を残さない」
|
||||
オプションが有効な時、カタログへコピー保存した直後の元画像を消すために使う。
|
||||
type="output" 以外は拒否する(temp/inputの誤削除を防止)。"""
|
||||
try:
|
||||
body = await request.json()
|
||||
filename = (body.get("filename") or "").strip()
|
||||
subfolder = body.get("subfolder") or ""
|
||||
img_type = body.get("type") or ""
|
||||
if not filename or img_type != "output":
|
||||
return web.json_response({"error": "filename required and type must be 'output'"}, status=400)
|
||||
|
||||
import folder_paths # type: ignore
|
||||
output_dir = Path(folder_paths.get_output_directory())
|
||||
target = output_dir / subfolder / filename
|
||||
|
||||
result = await asyncio.to_thread(_service.delete_images, [str(target)])
|
||||
if result["deleted"]:
|
||||
return web.json_response({"ok": True})
|
||||
return web.json_response({"error": "; ".join(result["errors"]) or "File not found"}, status=404)
|
||||
except Exception as e:
|
||||
logger.error("delete_output_image error: %s", e)
|
||||
return web.json_response({"error": str(e)}, status=500)
|
||||
|
||||
|
||||
# ──────────────────────────────────────────────────────────────
|
||||
# グループ管理
|
||||
# ──────────────────────────────────────────────────────────────
|
||||
|
||||
@@ -18,6 +18,7 @@ def setup_routes(app: web.Application):
|
||||
app.router.add_get("/api/wfm/lab/plans/content", handle_get_content)
|
||||
app.router.add_post("/api/wfm/lab/plans/save", handle_save)
|
||||
app.router.add_post("/api/wfm/lab/plans/delete", handle_delete)
|
||||
app.router.add_post("/api/wfm/lab/index-image/save-to-output", handle_save_index_to_output)
|
||||
|
||||
|
||||
async def handle_list(request: web.Request) -> web.Response:
|
||||
@@ -69,3 +70,16 @@ async def handle_delete(request: web.Request) -> web.Response:
|
||||
except Exception as e:
|
||||
logger.error("Error deleting lab plan: %s", e)
|
||||
return web.json_response({"error": str(e)}, status=500)
|
||||
|
||||
|
||||
async def handle_save_index_to_output(request: web.Request) -> web.Response:
|
||||
try:
|
||||
body = await request.json()
|
||||
image_base64 = body.get("image_base64", "")
|
||||
if not image_base64:
|
||||
return web.json_response({"error": "image_base64 required"}, status=400)
|
||||
result = await asyncio.to_thread(_service.save_index_image_to_output, image_base64)
|
||||
return web.json_response({"status": "ok", **result})
|
||||
except Exception as e:
|
||||
logger.error("Error saving lab index image to output: %s", e)
|
||||
return web.json_response({"error": str(e)}, status=500)
|
||||
|
||||
@@ -38,6 +38,9 @@ def setup_routes(app: web.Application):
|
||||
app.router.add_get("/api/wfm/settings/export", handle_export)
|
||||
app.router.add_post("/api/wfm/settings/import", handle_import)
|
||||
app.router.add_get("/api/wfm/styles", handle_get_styles)
|
||||
app.router.add_post("/api/wfm/styles", handle_create_style)
|
||||
app.router.add_put("/api/wfm/styles/{name}", handle_update_style)
|
||||
app.router.add_delete("/api/wfm/styles/{name}", handle_delete_style)
|
||||
|
||||
|
||||
async def handle_get(request: web.Request) -> web.Response:
|
||||
@@ -245,18 +248,28 @@ async def handle_import(request: web.Request) -> web.Response:
|
||||
return web.json_response({"error": str(e)}, status=500)
|
||||
|
||||
|
||||
def _load_styles() -> list:
|
||||
"""Load all style JSON files from DATA_DIR/style/ directory."""
|
||||
def _style_files() -> list:
|
||||
style_dir = DATA_DIR / "style"
|
||||
styles = []
|
||||
if not style_dir.is_dir():
|
||||
return styles
|
||||
for json_file in sorted(style_dir.glob("*.json")):
|
||||
return []
|
||||
return sorted(style_dir.glob("*.json"))
|
||||
|
||||
|
||||
def _load_styles() -> list:
|
||||
"""Load all style JSON files from DATA_DIR/style/ directory.
|
||||
各エントリに定義元ファイル名を "file" として付与する(Promptタブの一覧表示・
|
||||
「このファイルへ追加」機能で使用)。"""
|
||||
styles = []
|
||||
for json_file in _style_files():
|
||||
try:
|
||||
with open(json_file, "r", encoding="utf-8") as f:
|
||||
data = json.load(f)
|
||||
if isinstance(data, list):
|
||||
styles.extend(data)
|
||||
for entry in data:
|
||||
if isinstance(entry, dict):
|
||||
entry = dict(entry)
|
||||
entry["file"] = json_file.name
|
||||
styles.append(entry)
|
||||
except Exception as e:
|
||||
logger.warning("Failed to load style file %s: %s", json_file.name, e)
|
||||
return styles
|
||||
@@ -270,3 +283,139 @@ async def handle_get_styles(request: web.Request) -> web.Response:
|
||||
except Exception as e:
|
||||
logger.error("Error loading styles: %s", e)
|
||||
return web.json_response({"error": str(e)}, status=500)
|
||||
|
||||
|
||||
# Promptタブ「Style」サブタブでの新規作成分の保存先。既存スタイルの編集は
|
||||
# 元々そのスタイルが記載されているファイルをそのまま書き換える(他ファイルへは移動しない)。
|
||||
_CUSTOM_STYLE_FILENAME = "custom.json"
|
||||
|
||||
|
||||
def _find_style(name: str):
|
||||
"""名前が一致する最初のスタイルを探し、(ファイルパス, そのファイルの全データ, インデックス) を返す。
|
||||
見つからなければ None。"""
|
||||
for json_file in _style_files():
|
||||
try:
|
||||
with open(json_file, "r", encoding="utf-8") as f:
|
||||
data = json.load(f)
|
||||
except Exception as e:
|
||||
logger.warning("Failed to load style file %s: %s", json_file.name, e)
|
||||
continue
|
||||
if not isinstance(data, list):
|
||||
continue
|
||||
for i, entry in enumerate(data):
|
||||
if isinstance(entry, dict) and entry.get("name") == name:
|
||||
return json_file, data, i
|
||||
return None
|
||||
|
||||
|
||||
def _write_style_file(path: Path, data: list) -> None:
|
||||
with open(path, "w", encoding="utf-8") as f:
|
||||
json.dump(data, f, ensure_ascii=False, indent=2)
|
||||
f.write("\n")
|
||||
|
||||
|
||||
async def handle_create_style(request: web.Request) -> web.Response:
|
||||
"""POST /api/wfm/styles - 新規スタイルを作成する。
|
||||
body.file を指定すると既存のそのファイルへ追記する(Promptタブの「このファイルへ追加」用、
|
||||
ファイル名はstyleディレクトリに実在するもののみ許可しパストラバーサルを防ぐ)。
|
||||
未指定ならデフォルトのcustom.jsonへ追記する。"""
|
||||
try:
|
||||
body = await request.json()
|
||||
name = (body.get("name") or "").strip()
|
||||
prompt = body.get("prompt", "") or ""
|
||||
negative_prompt = body.get("negative_prompt", "") or ""
|
||||
target_file = (body.get("file") or "").strip()
|
||||
if not name:
|
||||
return web.json_response({"error": "name is required"}, status=400)
|
||||
|
||||
def _create():
|
||||
if _find_style(name) is not None:
|
||||
return "duplicate"
|
||||
style_dir = DATA_DIR / "style"
|
||||
style_dir.mkdir(parents=True, exist_ok=True)
|
||||
|
||||
if target_file:
|
||||
path = next((f for f in _style_files() if f.name == target_file), None)
|
||||
if path is None:
|
||||
return "file_not_found"
|
||||
else:
|
||||
path = style_dir / _CUSTOM_STYLE_FILENAME
|
||||
|
||||
data = []
|
||||
if path.is_file():
|
||||
try:
|
||||
with open(path, "r", encoding="utf-8") as f:
|
||||
loaded = json.load(f)
|
||||
if isinstance(loaded, list):
|
||||
data = loaded
|
||||
except Exception as e:
|
||||
logger.warning("Failed to load %s, recreating: %s", path.name, e)
|
||||
data.append({"name": name, "prompt": prompt, "negative_prompt": negative_prompt})
|
||||
_write_style_file(path, data)
|
||||
return "ok"
|
||||
|
||||
result = await asyncio.to_thread(_create)
|
||||
if result == "duplicate":
|
||||
return web.json_response({"error": f'Style "{name}" already exists'}, status=400)
|
||||
if result == "file_not_found":
|
||||
return web.json_response({"error": f'File "{target_file}" not found'}, status=400)
|
||||
return web.json_response({"ok": True})
|
||||
except Exception as e:
|
||||
logger.error("Error creating style: %s", e)
|
||||
return web.json_response({"error": str(e)}, status=500)
|
||||
|
||||
|
||||
async def handle_update_style(request: web.Request) -> web.Response:
|
||||
"""PUT /api/wfm/styles/{name} - 既存スタイルを更新する(記載元のファイルをそのまま書き換え、リネームも可)。"""
|
||||
try:
|
||||
original_name = request.match_info.get("name", "")
|
||||
body = await request.json()
|
||||
new_name = (body.get("name") or "").strip()
|
||||
prompt = body.get("prompt", "") or ""
|
||||
negative_prompt = body.get("negative_prompt", "") or ""
|
||||
if not new_name:
|
||||
return web.json_response({"error": "name is required"}, status=400)
|
||||
|
||||
def _update():
|
||||
found = _find_style(original_name)
|
||||
if found is None:
|
||||
return "not_found"
|
||||
path, data, idx = found
|
||||
if new_name != original_name and _find_style(new_name) is not None:
|
||||
return "duplicate"
|
||||
data[idx] = {"name": new_name, "prompt": prompt, "negative_prompt": negative_prompt}
|
||||
_write_style_file(path, data)
|
||||
return "ok"
|
||||
|
||||
result = await asyncio.to_thread(_update)
|
||||
if result == "not_found":
|
||||
return web.json_response({"error": "Style not found"}, status=404)
|
||||
if result == "duplicate":
|
||||
return web.json_response({"error": f'Style "{new_name}" already exists'}, status=400)
|
||||
return web.json_response({"ok": True})
|
||||
except Exception as e:
|
||||
logger.error("Error updating style: %s", e)
|
||||
return web.json_response({"error": str(e)}, status=500)
|
||||
|
||||
|
||||
async def handle_delete_style(request: web.Request) -> web.Response:
|
||||
"""DELETE /api/wfm/styles/{name} - スタイルを削除する(記載元のファイルから該当エントリのみ除去)。"""
|
||||
try:
|
||||
name = request.match_info.get("name", "")
|
||||
|
||||
def _delete():
|
||||
found = _find_style(name)
|
||||
if found is None:
|
||||
return False
|
||||
path, data, idx = found
|
||||
del data[idx]
|
||||
_write_style_file(path, data)
|
||||
return True
|
||||
|
||||
ok = await asyncio.to_thread(_delete)
|
||||
if not ok:
|
||||
return web.json_response({"error": "Style not found"}, status=404)
|
||||
return web.json_response({"ok": True})
|
||||
except Exception as e:
|
||||
logger.error("Error deleting style: %s", e)
|
||||
return web.json_response({"error": str(e)}, status=500)
|
||||
|
||||
@@ -0,0 +1,99 @@
|
||||
"""Unsloth API proxy routes.
|
||||
|
||||
Unlike Ollama/LM Studio/Lemonade, Unsloth Desktop requires an API key even
|
||||
for local access (Authorization: Bearer sk-unsloth-...). The key lives in
|
||||
UNSLOTH_API_KEY (loaded from a .env file by prestartup_script.py) and is
|
||||
never sent to the frontend — the frontend calls this proxy with the target
|
||||
path/method/payload, and the server attaches the Authorization header before
|
||||
relaying to Unsloth's OpenAI-compatible API.
|
||||
"""
|
||||
|
||||
import json
|
||||
import logging
|
||||
import os
|
||||
import urllib.request
|
||||
from urllib.error import HTTPError, URLError
|
||||
from urllib.parse import urlparse
|
||||
|
||||
from aiohttp import web
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
UNSLOTH_DEFAULT_URL = "http://localhost:8888"
|
||||
_ALLOWED_PATHS = {"/v1/models", "/v1/chat/completions"}
|
||||
# baseUrl is client-supplied (so a custom Unsloth port works), but the
|
||||
# Authorization header carries a real secret — restrict the host to loopback
|
||||
# so this proxy can't be used to exfiltrate UNSLOTH_API_KEY to an arbitrary
|
||||
# server (SSRF). Port is unrestricted.
|
||||
_ALLOWED_HOSTS = {"localhost", "127.0.0.1", "::1"}
|
||||
|
||||
|
||||
def _get_api_key():
|
||||
"""Return the Unsloth API key from the environment (.env), or None."""
|
||||
return os.environ.get("UNSLOTH_API_KEY", "").strip() or None
|
||||
|
||||
|
||||
def _is_allowed_base_url(base_url):
|
||||
"""Only relay (and attach the API key) to a loopback host."""
|
||||
try:
|
||||
parsed = urlparse(base_url)
|
||||
return parsed.scheme in ("http", "https") and parsed.hostname in _ALLOWED_HOSTS
|
||||
except Exception:
|
||||
return False
|
||||
|
||||
|
||||
def setup_routes(app: web.Application):
|
||||
"""Register Unsloth API routes."""
|
||||
app.router.add_post("/api/wfm/unsloth/proxy", handle_proxy)
|
||||
|
||||
|
||||
async def handle_proxy(request: web.Request) -> web.Response:
|
||||
"""POST /api/wfm/unsloth/proxy - Relay a request to Unsloth's OpenAI-compatible API.
|
||||
|
||||
Body: { baseUrl, path: "/v1/models" | "/v1/chat/completions", method: "GET" | "POST", payload }
|
||||
"""
|
||||
import asyncio
|
||||
try:
|
||||
body = await request.json()
|
||||
base_url = (body.get("baseUrl") or UNSLOTH_DEFAULT_URL).rstrip("/")
|
||||
path = body.get("path") or "/v1/models"
|
||||
method = (body.get("method") or "GET").upper()
|
||||
payload = body.get("payload")
|
||||
|
||||
if path not in _ALLOWED_PATHS or method not in ("GET", "POST"):
|
||||
return web.json_response({"message": "Unsupported proxy target"}, status=400)
|
||||
|
||||
if not _is_allowed_base_url(base_url):
|
||||
return web.json_response({
|
||||
"message": "Unsloth backend URL must point to localhost/127.0.0.1/::1",
|
||||
}, status=400)
|
||||
|
||||
api_key = _get_api_key()
|
||||
if not api_key:
|
||||
return web.json_response({
|
||||
"message": "UNSLOTH_API_KEY is not set. Copy .env.example to .env in the "
|
||||
"plugin folder, fill in the key, and restart ComfyUI.",
|
||||
}, status=401)
|
||||
|
||||
def _fetch():
|
||||
data = json.dumps(payload).encode("utf-8") if payload is not None else None
|
||||
headers = {"Authorization": f"Bearer {api_key}"}
|
||||
if data is not None:
|
||||
headers["Content-Type"] = "application/json"
|
||||
req = urllib.request.Request(f"{base_url}{path}", data=data, headers=headers, method=method)
|
||||
with urllib.request.urlopen(req, timeout=120) as resp:
|
||||
return json.loads(resp.read().decode("utf-8"))
|
||||
|
||||
data = await asyncio.to_thread(_fetch)
|
||||
return web.json_response(data)
|
||||
|
||||
except HTTPError as e:
|
||||
detail = e.read().decode("utf-8", errors="replace") if e.fp else str(e)
|
||||
logger.warning("Unsloth proxy HTTP error: %s %s", e.code, detail)
|
||||
return web.json_response({"message": f"Unsloth API error: HTTP {e.code}"}, status=e.code)
|
||||
except URLError as e:
|
||||
logger.warning("Unsloth proxy connection error: %s", e)
|
||||
return web.json_response({"message": f"Could not reach Unsloth: {e.reason}"}, status=502)
|
||||
except Exception as e:
|
||||
logger.error("Unsloth proxy error: %s", e)
|
||||
return web.json_response({"message": str(e)}, status=500)
|
||||
+264
-11
@@ -1,6 +1,7 @@
|
||||
"""
|
||||
Gallery Service - outputフォルダの画像管理、メタデータ閲覧
|
||||
"""
|
||||
import base64
|
||||
import hashlib
|
||||
import json
|
||||
import logging
|
||||
@@ -18,6 +19,37 @@ logger = logging.getLogger(__name__)
|
||||
# サポートする画像拡張子
|
||||
IMAGE_EXTENSIONS = {".png", ".jpg", ".jpeg", ".webp", ".gif", ".svg"}
|
||||
|
||||
# data URL の MIME タイプ -> 拡張子(save_image_to_gallery / save_image_to_folder共用)
|
||||
_SAVE_EXT_BY_MIME = {
|
||||
"image/png": ".png",
|
||||
"image/jpeg": ".jpg",
|
||||
"image/webp": ".webp",
|
||||
"image/gif": ".gif",
|
||||
"image/svg+xml": ".svg",
|
||||
}
|
||||
|
||||
|
||||
def _decode_image_data_url(image_data: str) -> tuple[bytes, str]:
|
||||
"""data URL (data:<mime>;base64,<data>) をデコードし (バイト列, 拡張子) を返す。
|
||||
ヘッダが無ければPNG扱い(旧互換)。"""
|
||||
raw = image_data
|
||||
mime = "image/png"
|
||||
if raw.startswith("data:"):
|
||||
header, _, raw = raw.partition(",")
|
||||
m = re.match(r"data:([^;]+)", header)
|
||||
if m:
|
||||
mime = m.group(1)
|
||||
ext = _SAVE_EXT_BY_MIME.get(mime, ".png")
|
||||
return base64.b64decode(raw), ext
|
||||
|
||||
|
||||
def _sanitize_save_filename(filename: str, ext: str) -> str:
|
||||
"""OSで使えない文字を除去し、拡張子が無ければ付与する"""
|
||||
safe = re.sub(r'[<>:"/\\|?*\x00-\x1f]', "_", filename)
|
||||
if not safe.lower().endswith(ext):
|
||||
safe += ext
|
||||
return safe
|
||||
|
||||
# メタデータ保存ファイル (gallery専用)
|
||||
from .gallery_metadata import GalleryMetadataStore
|
||||
|
||||
@@ -30,6 +62,54 @@ _JPEG_READ_MAX = 64 * 1024 * 1024
|
||||
# フォルダキャッシュのTTL秒(フォルダmtimeが同じでも念のため)
|
||||
_CACHE_TTL = 60.0
|
||||
|
||||
# ImagePromptギャラリー: 画像と同名の.txtサイドカーに保存されたプロンプトテキストの最大読み込みサイズ
|
||||
_SIDECAR_PROMPT_MAX = 20_000
|
||||
|
||||
# ImagePromptギャラリーの管理フォルダ名(ComfyUI実outputフォルダ直下)
|
||||
IMAGE_PROMPT_FOLDER_NAME = "ws_image_prompt"
|
||||
|
||||
# Style Catalogギャラリーの管理フォルダ名(ComfyUI実outputフォルダ直下)
|
||||
STYLE_CATALOG_FOLDER_NAME = "ws_style_catalog"
|
||||
|
||||
# ponyxlWildcardsVault形式(.yaml + thumbnails/)を検出するための、画像の祖先フォルダ探索上限
|
||||
_VAULT_ROOT_SEARCH_DEPTH = 8
|
||||
_VAULT_THUMB_DIR_NAMES = ("thumbnails", "thumbnails_option2")
|
||||
|
||||
|
||||
def _clean_vault_tags(text: str) -> str:
|
||||
"""タグ文字列の前後の空白・カンマを整理する(tools/import_style_prompt_seed.py と同じ処理)"""
|
||||
text = text.strip()
|
||||
text = re.sub(r"^[,\s]+|[,\s]+$", "", text)
|
||||
text = re.sub(r"\s*,\s*", ", ", text)
|
||||
return text
|
||||
|
||||
|
||||
def _parse_vault_yaml_leaves(yaml_path: Path) -> dict[str, str]:
|
||||
"""comfyui_prompt_gallery の parseYamlForImages と同じ簡易パーサ(PyYAML不要)。
|
||||
「key:」行の直後が「- タグ文字列」で始まる行なら key をリーフとみなす。
|
||||
戻り値: {leaf_name(小文字): タグ文字列}
|
||||
"""
|
||||
leaves: dict[str, str] = {}
|
||||
try:
|
||||
lines = yaml_path.read_text(encoding="utf-8", errors="replace").split("\n")
|
||||
except OSError:
|
||||
return leaves
|
||||
for i, line in enumerate(lines):
|
||||
trimmed = line.strip()
|
||||
if not trimmed or trimmed.startswith("#") or not trimmed.endswith(":"):
|
||||
continue
|
||||
if i + 1 >= len(lines):
|
||||
continue
|
||||
next_trimmed = lines[i + 1].strip()
|
||||
if not next_trimmed.startswith("-"):
|
||||
continue
|
||||
key = trimmed[:-1].strip()
|
||||
tags = next_trimmed[1:].strip()
|
||||
if not tags or key.lower() == "skip":
|
||||
continue
|
||||
leaves[key.lower()] = _clean_vault_tags(tags)
|
||||
return leaves
|
||||
|
||||
|
||||
class _FolderCache:
|
||||
"""フォルダ単位の画像スキャン結果キャッシュ。
|
||||
@@ -73,15 +153,26 @@ class GalleryService:
|
||||
self.data_dir = data_dir
|
||||
self.metadata_store = GalleryMetadataStore(data_dir / "gallery_metadata.json")
|
||||
self._allowed_root: Path | None = None
|
||||
# ComfyUI実outputフォルダの不変ルート。Settingsでユーザーが_allowed_rootを
|
||||
# 別フォルダに変更しても、ImagePrompt/Style Catalogギャラリー(常に実output配下)への
|
||||
# アクセスが塞がれないようにするため_allowed_rootとは別管理にする
|
||||
self._comfy_output_root: Path | None = None
|
||||
self._folder_cache = _FolderCache()
|
||||
self._bg_cancel = threading.Event()
|
||||
self._bg_cancel.set() # 初期状態: キャンセル済み
|
||||
# ponyxlWildcardsVault形式フォールバック用キャッシュ: category_root文字列 -> (yamlシグネチャ, {leaf: tags})
|
||||
self._vault_leaf_cache: dict[str, tuple[tuple, dict]] = {}
|
||||
|
||||
def update_output_root(self, root_path: str) -> None:
|
||||
"""許可するルートパスを更新する(Settings変更時に呼ぶ)"""
|
||||
p = Path(root_path).resolve() if root_path else None
|
||||
self._allowed_root = p
|
||||
|
||||
def set_comfy_output_root(self, root_path: str) -> None:
|
||||
"""ComfyUI実outputフォルダの不変ルートを設定する(起動時に一度だけ呼ぶ)"""
|
||||
p = Path(root_path).resolve() if root_path else None
|
||||
self._comfy_output_root = p
|
||||
|
||||
# ──────────────────────────────────────────────────────────────
|
||||
# バックグラウンドインデックス
|
||||
# ──────────────────────────────────────────────────────────────
|
||||
@@ -147,14 +238,23 @@ class GalleryService:
|
||||
logger.debug("BG index error: %s", e)
|
||||
|
||||
def _check_path_allowed(self, path: Path) -> bool:
|
||||
"""パスが許可ルート配下かチェック(パストラバーサル防止)"""
|
||||
if self._allowed_root is None:
|
||||
return False
|
||||
try:
|
||||
path.resolve().relative_to(self._allowed_root)
|
||||
return True
|
||||
except ValueError:
|
||||
return False
|
||||
"""パスが許可ルート配下かチェック(パストラバーサル防止)。
|
||||
Output ギャラリーの _allowed_root、またはComfyUI実outputフォルダの
|
||||
_comfy_output_root のいずれか配下であれば許可する。"""
|
||||
resolved = path.resolve()
|
||||
if self._allowed_root is not None:
|
||||
try:
|
||||
resolved.relative_to(self._allowed_root)
|
||||
return True
|
||||
except ValueError:
|
||||
pass
|
||||
if self._comfy_output_root is not None:
|
||||
try:
|
||||
resolved.relative_to(self._comfy_output_root)
|
||||
return True
|
||||
except ValueError:
|
||||
pass
|
||||
return False
|
||||
|
||||
# ──────────────────────────────────────────────────────────────
|
||||
# フォルダツリー
|
||||
@@ -183,11 +283,13 @@ class GalleryService:
|
||||
except PermissionError:
|
||||
pass
|
||||
children_nodes = [build_tree(path / name, rel_base) for name in sorted(children)]
|
||||
total_count = image_count + sum(c["image_count_total"] for c in children_nodes)
|
||||
return {
|
||||
"name": path.name,
|
||||
"path": rel if rel != "." else "",
|
||||
"abs_path": str(path).replace("\\", "/"),
|
||||
"image_count": image_count,
|
||||
"image_count_total": total_count,
|
||||
"children": children_nodes,
|
||||
}
|
||||
|
||||
@@ -230,6 +332,33 @@ class GalleryService:
|
||||
self._folder_cache.set(folder, entries)
|
||||
return entries
|
||||
|
||||
def _scan_folder_recursive(self, folder: Path) -> list[tuple[str, str, int, float]]:
|
||||
"""os.walk() でフォルダ配下を再帰的に列挙する(サブフォルダの画像も含む)。
|
||||
ImagePrompt/Style Catalogギャラリーのように深い階層に画像が置かれるケース用。
|
||||
キャッシュはしない(フォルダ数が少なく、都度スキャンしても軽い想定)。
|
||||
"""
|
||||
entries = []
|
||||
try:
|
||||
for root, dirs, files in os.walk(folder):
|
||||
dirs[:] = [d for d in dirs if not d.startswith(".")]
|
||||
for name in files:
|
||||
if Path(name).suffix.lower() not in IMAGE_EXTENSIONS:
|
||||
continue
|
||||
full = Path(root) / name
|
||||
try:
|
||||
st = full.stat()
|
||||
entries.append((
|
||||
name,
|
||||
str(full.resolve()).replace("\\", "/"),
|
||||
st.st_size,
|
||||
st.st_mtime,
|
||||
))
|
||||
except OSError:
|
||||
continue
|
||||
except PermissionError:
|
||||
pass
|
||||
return entries
|
||||
|
||||
def list_images(
|
||||
self,
|
||||
folder_path: str,
|
||||
@@ -238,8 +367,9 @@ class GalleryService:
|
||||
favorite_only: bool = False,
|
||||
tag_filter: str = "",
|
||||
group_filter: str = "",
|
||||
recursive: bool = False,
|
||||
) -> list[dict]:
|
||||
"""指定フォルダ内の画像一覧を返す(サブフォルダなし)"""
|
||||
"""指定フォルダ内の画像一覧を返す(recursive=Trueならサブフォルダも含める)"""
|
||||
folder = Path(folder_path).resolve()
|
||||
if not folder.is_dir():
|
||||
return []
|
||||
@@ -253,7 +383,7 @@ class GalleryService:
|
||||
group_member_set = self.metadata_store.get_group_member_set(group_filter)
|
||||
|
||||
# os.scandir() でファイル情報を一括取得(stat()の個別呼び出しを排除)
|
||||
raw_entries = self._scan_folder(folder)
|
||||
raw_entries = self._scan_folder_recursive(folder) if recursive else self._scan_folder(folder)
|
||||
|
||||
# 孤立メタデータを自動クリーンアップ(移動・削除されたファイルの残骸を除去)
|
||||
existing_paths = {abs_path for _, abs_path, _, _ in raw_entries}
|
||||
@@ -289,14 +419,16 @@ class GalleryService:
|
||||
"groups": meta.get("groups", []),
|
||||
}
|
||||
|
||||
# 検索フィルタ(ファイル名・メモ・タグ・キャッシュ済みプロンプト)
|
||||
# 検索フィルタ(ファイル名・メモ・タグ・キャッシュ済みプロンプト・.txtサイドカー)
|
||||
if search:
|
||||
s = search.lower()
|
||||
sidecar_prompt = self._read_sidecar_prompt(Path(abs_path)) or ""
|
||||
if not (
|
||||
s in name.lower()
|
||||
or s in item["memo"].lower()
|
||||
or any(s in t.lower() for t in tags)
|
||||
or s in meta.get("prompt_cache", "").lower()
|
||||
or s in sidecar_prompt.lower()
|
||||
):
|
||||
continue
|
||||
|
||||
@@ -314,6 +446,126 @@ class GalleryService:
|
||||
|
||||
return results
|
||||
|
||||
# ──────────────────────────────────────────────────────────────
|
||||
# ImagePromptギャラリー: .txtサイドカーによるプロンプト保存
|
||||
# ──────────────────────────────────────────────────────────────
|
||||
|
||||
def get_image_prompt_root(self) -> str | None:
|
||||
"""ImagePromptギャラリーのルートフォルダ(ComfyUI実output/ws_image_prompt)を
|
||||
返す。無ければ作成する。"""
|
||||
if self._comfy_output_root is None:
|
||||
return None
|
||||
root = self._comfy_output_root / IMAGE_PROMPT_FOLDER_NAME
|
||||
root.mkdir(parents=True, exist_ok=True)
|
||||
return str(root).replace("\\", "/")
|
||||
|
||||
def get_style_catalog_root(self) -> str | None:
|
||||
"""Style Catalogギャラリーのルートフォルダ(ComfyUI実output/ws_style_catalog)を
|
||||
返す。無ければ作成する。"""
|
||||
if self._comfy_output_root is None:
|
||||
return None
|
||||
root = self._comfy_output_root / STYLE_CATALOG_FOLDER_NAME
|
||||
root.mkdir(parents=True, exist_ok=True)
|
||||
return str(root).replace("\\", "/")
|
||||
|
||||
def save_image_to_folder(self, folder_path: str, filename: str, image_data: str) -> dict:
|
||||
"""任意フォルダへ画像を保存する(data URL想定、同名なら上書き)。
|
||||
Style Catalogのカタログ作成(スタイル名でのファイル保存)で使用。"""
|
||||
folder = Path(folder_path).resolve()
|
||||
if not folder.is_dir():
|
||||
return {"ok": False, "error": "Destination folder not found"}
|
||||
if not self._check_path_allowed(folder):
|
||||
return {"ok": False, "error": "Access denied"}
|
||||
try:
|
||||
image_bytes, ext = _decode_image_data_url(image_data)
|
||||
except Exception as e:
|
||||
return {"ok": False, "error": f"Invalid imageData: {e}"}
|
||||
safe = _sanitize_save_filename(filename, ext)
|
||||
if not safe:
|
||||
return {"ok": False, "error": "Invalid filename"}
|
||||
save_path = folder / safe
|
||||
try:
|
||||
save_path.write_bytes(image_bytes)
|
||||
except OSError as e:
|
||||
return {"ok": False, "error": str(e)}
|
||||
return {"ok": True, "path": str(save_path).replace("\\", "/")}
|
||||
|
||||
def _sidecar_path(self, image_path: Path) -> Path:
|
||||
return image_path.with_suffix(".txt")
|
||||
|
||||
def _read_sidecar_prompt(self, image_path: Path) -> str | None:
|
||||
"""画像のプロンプトテキストを返す。
|
||||
1. 画像と同名の .txt サイドカーがあればそれを使う
|
||||
2. 無ければ ponyxlWildcardsVault 形式 (*.yaml + thumbnails/) をフォールバックとして
|
||||
その場で解決する(インポート未実施のフォルダをそのまま置いた場合に対応するため)
|
||||
"""
|
||||
sidecar = self._sidecar_path(image_path)
|
||||
try:
|
||||
if sidecar.is_file() and sidecar.stat().st_size <= _SIDECAR_PROMPT_MAX:
|
||||
text = sidecar.read_text(encoding="utf-8", errors="replace").strip()
|
||||
if text:
|
||||
return text
|
||||
except OSError:
|
||||
pass
|
||||
return self._read_vault_prompt(image_path)
|
||||
|
||||
def _find_vault_category_root(self, image_path: Path) -> Path | None:
|
||||
"""image_path の祖先を辿り、直下に thumbnails(_option2) を持つフォルダ
|
||||
(=ponyxlWildcardsVaultのカテゴリルート) を探す"""
|
||||
cur = image_path.parent
|
||||
for _ in range(_VAULT_ROOT_SEARCH_DEPTH):
|
||||
if any((cur / name).is_dir() for name in _VAULT_THUMB_DIR_NAMES):
|
||||
return cur
|
||||
if cur.parent == cur:
|
||||
break
|
||||
cur = cur.parent
|
||||
return None
|
||||
|
||||
def _load_vault_leaves(self, category_root: Path) -> dict[str, str]:
|
||||
yaml_files = sorted(category_root.glob("*.yaml")) + sorted(category_root.glob("*.yml"))
|
||||
if not yaml_files:
|
||||
return {}
|
||||
try:
|
||||
signature = tuple(sorted((str(f), f.stat().st_mtime) for f in yaml_files))
|
||||
except OSError:
|
||||
signature = ()
|
||||
cache_key = str(category_root)
|
||||
cached = self._vault_leaf_cache.get(cache_key)
|
||||
if cached is not None and cached[0] == signature:
|
||||
return cached[1]
|
||||
leaves: dict[str, str] = {}
|
||||
for yf in yaml_files:
|
||||
leaves.update(_parse_vault_yaml_leaves(yf))
|
||||
self._vault_leaf_cache[cache_key] = (signature, leaves)
|
||||
return leaves
|
||||
|
||||
def _read_vault_prompt(self, image_path: Path) -> str | None:
|
||||
"""ponyxlWildcardsVault形式のフォールバック解決。
|
||||
thumbnails_option2 の "{leaf}.preview3.ext" のような二重拡張子にも対応するため、
|
||||
ファイル名の最初の "." より前をリーフ名候補として使う。"""
|
||||
category_root = self._find_vault_category_root(image_path)
|
||||
if category_root is None:
|
||||
return None
|
||||
leaves = self._load_vault_leaves(category_root)
|
||||
if not leaves:
|
||||
return None
|
||||
leaf_candidate = image_path.name.split(".")[0].lower()
|
||||
return leaves.get(leaf_candidate)
|
||||
|
||||
def save_image_prompt(self, image_path: str, text: str) -> bool:
|
||||
"""画像と同名の.txtサイドカーにプロンプトテキストを保存する"""
|
||||
p = Path(image_path).resolve()
|
||||
if not p.is_file():
|
||||
return False
|
||||
if not self._check_path_allowed(p):
|
||||
return False
|
||||
try:
|
||||
self._sidecar_path(p).write_text((text or "").strip(), encoding="utf-8")
|
||||
return True
|
||||
except OSError as e:
|
||||
logger.warning("save_image_prompt: failed for %s: %s", p, e)
|
||||
return False
|
||||
|
||||
# ──────────────────────────────────────────────────────────────
|
||||
# 画像メタデータ
|
||||
# ──────────────────────────────────────────────────────────────
|
||||
@@ -355,6 +607,7 @@ class GalleryService:
|
||||
"tags": saved.get("tags", []),
|
||||
"memo": saved.get("memo", ""),
|
||||
"groups": saved.get("groups", []),
|
||||
"image_prompt": self._read_sidecar_prompt(path),
|
||||
}
|
||||
|
||||
def _read_png_metadata(self, path: Path) -> dict:
|
||||
|
||||
@@ -110,6 +110,23 @@ class LabPlanService:
|
||||
with open(thumb_path, "wb") as f:
|
||||
f.write(image_bytes)
|
||||
|
||||
def save_index_image_to_output(self, image_base64: str, filename_prefix: str = "Lab_index") -> dict:
|
||||
"""Saves the contact-sheet index image into ComfyUI's own output folder,
|
||||
alongside the images generated during the run (unlike save_index_image,
|
||||
which saves it next to the plan file in plan_dir)."""
|
||||
b64 = image_base64
|
||||
if "," in b64 and b64.strip().lower().startswith("data:"):
|
||||
b64 = b64.split(",", 1)[1]
|
||||
image_bytes = base64.b64decode(b64)
|
||||
|
||||
import folder_paths # type: ignore
|
||||
output_dir = folder_paths.get_output_directory()
|
||||
full_output_folder, filename, counter, subfolder, _ = folder_paths.get_save_image_path(filename_prefix, output_dir)
|
||||
save_name = f"{filename}_{counter:05}_.png"
|
||||
save_path = Path(full_output_folder) / save_name
|
||||
save_path.write_bytes(image_bytes)
|
||||
return {"filename": save_name, "subfolder": subfolder}
|
||||
|
||||
def delete_plan(self, filename: str) -> None:
|
||||
path = self._safe_path(filename)
|
||||
if path is None:
|
||||
|
||||
@@ -80,11 +80,12 @@ 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, tagger_routes, gmic_routes, skill_routes, lab_routes
|
||||
from .routes import workflow_routes, settings_routes, ollama_routes, unsloth_routes, eagle_routes, nodes_routes, prompts_routes, models_routes, gallery_routes, wildcard_routes, tagger_routes, gmic_routes, skill_routes, lab_routes
|
||||
|
||||
workflow_routes.setup_routes(app)
|
||||
settings_routes.setup_routes(app)
|
||||
ollama_routes.setup_routes(app)
|
||||
unsloth_routes.setup_routes(app)
|
||||
eagle_routes.setup_routes(app)
|
||||
nodes_routes.setup_routes(app)
|
||||
prompts_routes.setup_routes(app)
|
||||
|
||||
+1
-1
@@ -1,7 +1,7 @@
|
||||
[project]
|
||||
name = "comfyui-workflow-studio"
|
||||
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.89"
|
||||
version = "0.3.99"
|
||||
license = "MIT"
|
||||
requires-python = ">= 3.10"
|
||||
dependencies = ["jinja2"]
|
||||
|
||||
@@ -19,3 +19,6 @@ piexif>=1.1.3
|
||||
# Omit if you do not use DeepDanbooru models.
|
||||
# TensorFlow is large (~600MB) and conflicts with some CUDA setups.
|
||||
# tensorflow>=2.10
|
||||
|
||||
# -- Required to load UNSLOTH_API_KEY from a local .env file (Unsloth backend, AI TOOL tab) --
|
||||
python-dotenv>=1.0,<2.0
|
||||
|
||||
+160
-1
@@ -2,11 +2,45 @@
|
||||
Gallery Tab Styles
|
||||
============================================================ */
|
||||
|
||||
/* ── サブタブ (Output / Style-Prompt) ──────────────────────── */
|
||||
|
||||
.wfm-gallery-subtab-nav {
|
||||
display: flex;
|
||||
border-bottom: 1px solid var(--wfm-border);
|
||||
flex-shrink: 0;
|
||||
}
|
||||
|
||||
.wfm-gallery-subtab-btn {
|
||||
padding: 6px 16px;
|
||||
font-size: 12px;
|
||||
background: transparent;
|
||||
border: none;
|
||||
color: var(--wfm-text-secondary);
|
||||
cursor: pointer;
|
||||
border-bottom: 2px solid transparent;
|
||||
margin-bottom: -1px;
|
||||
transition: color 0.15s;
|
||||
}
|
||||
|
||||
.wfm-gallery-subtab-btn:hover { color: var(--wfm-text-primary); }
|
||||
.wfm-gallery-subtab-btn.active { color: var(--wfm-primary); border-bottom-color: var(--wfm-primary); }
|
||||
|
||||
.wfm-gallery-panel {
|
||||
display: none;
|
||||
flex-direction: column;
|
||||
flex: 1;
|
||||
min-height: 0;
|
||||
overflow: hidden;
|
||||
}
|
||||
|
||||
.wfm-gallery-panel.active { display: flex; }
|
||||
|
||||
/* ── 3カラムレイアウト ──────────────────────────────────────── */
|
||||
|
||||
.wfm-gallery-layout {
|
||||
display: flex;
|
||||
height: calc(100vh - var(--wfm-header-height, 96px));
|
||||
flex: 1;
|
||||
min-height: 0;
|
||||
overflow: hidden;
|
||||
gap: 0;
|
||||
}
|
||||
@@ -499,6 +533,20 @@
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
.wfm-gallery-image-prompt-text {
|
||||
font-size: 12px;
|
||||
color: var(--wfm-text-primary);
|
||||
line-height: 1.5;
|
||||
white-space: pre-wrap;
|
||||
word-break: break-word;
|
||||
background: var(--wfm-bg-primary, #16213e);
|
||||
border: 1px solid var(--wfm-border);
|
||||
border-radius: 4px;
|
||||
padding: 6px 8px;
|
||||
max-height: 160px;
|
||||
overflow-y: auto;
|
||||
}
|
||||
|
||||
.wfm-gallery-tags-display {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
@@ -833,3 +881,114 @@
|
||||
gap: 8px;
|
||||
justify-content: flex-end;
|
||||
}
|
||||
|
||||
/* ============================================================
|
||||
ImagePrompt / Style_Catalog ギャラリー (右ペイン)
|
||||
============================================================ */
|
||||
|
||||
.wfm-imageprompt-detail-panel {
|
||||
width: 520px;
|
||||
min-width: 520px;
|
||||
max-width: 520px;
|
||||
flex-direction: row;
|
||||
overflow: hidden;
|
||||
}
|
||||
|
||||
.wfm-imageprompt-detail-col {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
min-width: 0;
|
||||
}
|
||||
|
||||
.wfm-imageprompt-detail-col-left {
|
||||
width: 280px;
|
||||
min-width: 280px;
|
||||
max-width: 280px;
|
||||
overflow-y: auto;
|
||||
border-right: 1px solid var(--wfm-border);
|
||||
padding-bottom: 8px;
|
||||
}
|
||||
|
||||
.wfm-imageprompt-detail-col-right {
|
||||
flex: 1;
|
||||
min-width: 0;
|
||||
padding: 8px 10px;
|
||||
}
|
||||
|
||||
.wfm-imageprompt-section {
|
||||
padding: 8px 10px;
|
||||
}
|
||||
|
||||
.wfm-imageprompt-prompt-box {
|
||||
width: 100%;
|
||||
resize: vertical;
|
||||
font-size: 12px;
|
||||
padding: 6px 8px;
|
||||
background: var(--wfm-bg-primary, #16213e);
|
||||
border: 1px solid var(--wfm-border);
|
||||
border-radius: 4px;
|
||||
color: var(--wfm-text-primary);
|
||||
box-sizing: border-box;
|
||||
}
|
||||
|
||||
.wfm-imageprompt-btn-row {
|
||||
display: flex;
|
||||
gap: 6px;
|
||||
margin-top: 6px;
|
||||
}
|
||||
|
||||
.wfm-imageprompt-btn-row .wfm-btn {
|
||||
flex: 1;
|
||||
}
|
||||
|
||||
.wfm-imageprompt-chips {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
gap: 4px;
|
||||
margin-top: 6px;
|
||||
min-height: 24px;
|
||||
}
|
||||
|
||||
.wfm-imageprompt-chip {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
gap: 4px;
|
||||
max-width: 100%;
|
||||
background: rgba(79,142,247,0.15);
|
||||
color: var(--wfm-accent, #4f8ef7);
|
||||
border: 1px solid rgba(79,142,247,0.3);
|
||||
border-radius: 10px;
|
||||
padding: 2px 4px 2px 8px;
|
||||
font-size: 11px;
|
||||
}
|
||||
|
||||
.wfm-imageprompt-chip-text {
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
white-space: nowrap;
|
||||
max-width: 220px;
|
||||
}
|
||||
|
||||
.wfm-imageprompt-chip-remove {
|
||||
background: none;
|
||||
border: none;
|
||||
color: inherit;
|
||||
cursor: pointer;
|
||||
padding: 0 2px;
|
||||
font-size: 13px;
|
||||
line-height: 1;
|
||||
opacity: 0.7;
|
||||
}
|
||||
|
||||
.wfm-imageprompt-chip-remove:hover { opacity: 1; }
|
||||
|
||||
.wfm-imageprompt-final-section {
|
||||
height: 100%;
|
||||
}
|
||||
|
||||
.wfm-imageprompt-final-textarea {
|
||||
margin-top: 4px;
|
||||
flex: 1;
|
||||
min-height: 0;
|
||||
resize: none;
|
||||
}
|
||||
|
||||
@@ -86,6 +86,27 @@
|
||||
margin-top: 12px;
|
||||
}
|
||||
|
||||
.wfm-lab-plan-workflow-row {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 6px;
|
||||
margin-top: 8px;
|
||||
padding: 6px 8px;
|
||||
background: var(--wfm-bg-secondary);
|
||||
border: 1px solid var(--wfm-border);
|
||||
border-radius: 4px;
|
||||
}
|
||||
|
||||
.wfm-lab-plan-workflow-name {
|
||||
flex: 1;
|
||||
min-width: 0;
|
||||
font-size: 11px;
|
||||
color: var(--wfm-text-secondary);
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
.wfm-lab-field-row {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
@@ -191,6 +212,29 @@
|
||||
font-style: italic;
|
||||
}
|
||||
|
||||
/* Setting 1, not yet explicitly overridden: showing the live GenerateUI value instead of
|
||||
its own stored one (see _isLiveDisplay in lab-tab.js). Dashed border distinguishes it
|
||||
from a saved override (solid border) at a glance. */
|
||||
.wfm-lab-cell.wfm-lab-cell-live {
|
||||
border-style: dashed;
|
||||
}
|
||||
|
||||
.wfm-lab-cell.wfm-lab-cell-live .wfm-lab-cell-value {
|
||||
color: var(--wfm-text-secondary);
|
||||
}
|
||||
|
||||
/* This keyframe row is skipped entirely (see _resolveKeyframe's bypassed handling) —
|
||||
amber to read as "temporarily disabled", distinct from the neutral gray used for
|
||||
revert/live. Takes priority over both of those in _cellHtml. */
|
||||
.wfm-lab-cell.wfm-lab-cell-bypassed {
|
||||
border-color: var(--wfm-warning);
|
||||
opacity: 0.6;
|
||||
}
|
||||
|
||||
.wfm-lab-cell.wfm-lab-cell-bypassed .wfm-lab-cell-value {
|
||||
color: var(--wfm-warning);
|
||||
}
|
||||
|
||||
.wfm-lab-cell-applied {
|
||||
margin-top: 3px;
|
||||
padding-top: 3px;
|
||||
@@ -233,6 +277,13 @@
|
||||
margin-bottom: 10px;
|
||||
}
|
||||
|
||||
.wfm-lab-modal-hint {
|
||||
font-size: 11px;
|
||||
color: var(--wfm-text-secondary);
|
||||
font-style: italic;
|
||||
margin: 0 0 10px;
|
||||
}
|
||||
|
||||
.wfm-lab-modal-inline > div {
|
||||
flex: 1;
|
||||
min-width: 0;
|
||||
|
||||
@@ -2342,6 +2342,38 @@ body {
|
||||
flex-shrink: 0;
|
||||
}
|
||||
|
||||
/* Col3 (Wildcard/Style) タブ切り替え */
|
||||
.wfm-prompt-col3-tabs {
|
||||
display: flex;
|
||||
background: var(--wfm-surface);
|
||||
border-bottom: 1px solid var(--wfm-border);
|
||||
flex-shrink: 0;
|
||||
}
|
||||
.wfm-prompt-col3-tab {
|
||||
flex: 1;
|
||||
padding: 8px 4px;
|
||||
background: none;
|
||||
border: none;
|
||||
border-bottom: 2px solid transparent;
|
||||
color: var(--wfm-text-secondary);
|
||||
font-size: 13px;
|
||||
font-weight: bold;
|
||||
cursor: pointer;
|
||||
transition: all 0.15s;
|
||||
}
|
||||
.wfm-prompt-col3-tab:hover { color: var(--wfm-text); }
|
||||
.wfm-prompt-col3-tab.active {
|
||||
color: var(--wfm-text);
|
||||
border-bottom-color: var(--wfm-primary);
|
||||
}
|
||||
.wfm-prompt-col3-tab-content {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
flex: 1;
|
||||
min-height: 0;
|
||||
overflow: hidden;
|
||||
}
|
||||
|
||||
/* Ollama Assistant */
|
||||
.wfm-ollama-assistant {
|
||||
display: flex;
|
||||
@@ -2885,6 +2917,29 @@ body {
|
||||
Image Input (I2I) Slots
|
||||
============================================ */
|
||||
|
||||
/* Container/header styling comes from .wfm-settings-section / .wfm-settings-summary
|
||||
(shared details/summary accordion used by the Settings tab) — collapsed by default
|
||||
since this is a low-frequency feature. */
|
||||
|
||||
.wfm-i2i-placeholder-mode {
|
||||
display: flex;
|
||||
gap: 16px;
|
||||
font-size: 12px;
|
||||
margin-bottom: 8px;
|
||||
}
|
||||
|
||||
.wfm-i2i-placeholder-mode label {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 4px;
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
.wfm-i2i-placeholder-fields input[type="color"] {
|
||||
padding: 2px;
|
||||
height: 30px;
|
||||
}
|
||||
|
||||
.wfm-i2i-grid {
|
||||
display: grid;
|
||||
grid-template-columns: 1fr 1fr;
|
||||
@@ -2948,6 +3003,12 @@ body {
|
||||
background: rgba(74, 158, 255, 0.08);
|
||||
}
|
||||
|
||||
.wfm-i2i-drop-zone.wfm-disabled {
|
||||
opacity: 0.4;
|
||||
pointer-events: none;
|
||||
cursor: default;
|
||||
}
|
||||
|
||||
.wfm-i2i-drop-label {
|
||||
font-size: 12px;
|
||||
color: var(--wfm-text-secondary);
|
||||
|
||||
+164
-30
@@ -50,33 +50,102 @@ function fileToBase64(file) {
|
||||
});
|
||||
}
|
||||
|
||||
async function callVLM(url, backend, model, prompt, base64Image, mimeType) {
|
||||
// ============================================
|
||||
// Thinking mode / Max tokens (shared by callLLM / callChat / callVLM)
|
||||
// ============================================
|
||||
|
||||
// Ollamaは `think` (bool) と `options.num_predict` で制御できるが、
|
||||
// LM Studio/LemonadeはOpenAI互換APIのため max_tokens のみ標準対応。
|
||||
// thinking mode切替は非対応バックエンド/モデル向けに、出力からの
|
||||
// <think>タグ除去でも担保する(stripThinkingTagsを参照)。
|
||||
function _applyGenOptions(body, backend, settings) {
|
||||
const maxTokens = parseInt(settings?.maxTokens, 10);
|
||||
if (backend === "ollama") {
|
||||
body.think = !!settings?.thinkingMode;
|
||||
if (maxTokens > 0) body.options = { ...(body.options || {}), num_predict: maxTokens };
|
||||
} else if (maxTokens > 0) {
|
||||
body.max_tokens = maxTokens;
|
||||
}
|
||||
return body;
|
||||
}
|
||||
|
||||
function stripThinkingTags(text) {
|
||||
return (text || "")
|
||||
.replace(/<think>[\s\S]*?<\/think>/gi, "")
|
||||
.replace(/<thinking>[\s\S]*?<\/thinking>/gi, "")
|
||||
.trim();
|
||||
}
|
||||
|
||||
async function callVLM(url, backend, model, prompt, base64Image, mimeType, settings = {}) {
|
||||
if (backend === "ollama") {
|
||||
const res = await fetch(`${url}/api/generate`, {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify({ model, prompt, images: [base64Image], stream: false }),
|
||||
body: JSON.stringify(_applyGenOptions({ model, prompt, images: [base64Image], stream: false }, backend, settings)),
|
||||
});
|
||||
if (!res.ok) throw new Error(`HTTP ${res.status}`);
|
||||
return (await res.json()).response || "";
|
||||
const text = (await res.json()).response || "";
|
||||
return settings.thinkingMode ? text : stripThinkingTags(text);
|
||||
} else if (backend === "unsloth") {
|
||||
const body = _applyGenOptions({
|
||||
model,
|
||||
messages: [{ role: "user", content: [
|
||||
{ type: "text", text: prompt },
|
||||
{ type: "image_url", image_url: { url: `data:${mimeType};base64,${base64Image}` } },
|
||||
]}],
|
||||
stream: false,
|
||||
}, backend, settings);
|
||||
const data = await unslothProxy(url, "/v1/chat/completions", "POST", body);
|
||||
const text = _unslothContent(data.choices?.[0]?.message);
|
||||
return settings.thinkingMode ? text : stripThinkingTags(text);
|
||||
} else {
|
||||
const res = await fetch(`${url}/v1/chat/completions`, {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify({
|
||||
body: JSON.stringify(_applyGenOptions({
|
||||
model,
|
||||
messages: [{ role: "user", content: [
|
||||
{ type: "text", text: prompt },
|
||||
{ type: "image_url", image_url: { url: `data:${mimeType};base64,${base64Image}` } },
|
||||
]}],
|
||||
stream: false,
|
||||
}),
|
||||
}, backend, settings)),
|
||||
});
|
||||
if (!res.ok) throw new Error(`HTTP ${res.status}`);
|
||||
return (await res.json()).choices?.[0]?.message?.content || "";
|
||||
const text = (await res.json()).choices?.[0]?.message?.content || "";
|
||||
return settings.thinkingMode ? text : stripThinkingTags(text);
|
||||
}
|
||||
}
|
||||
|
||||
// ============================================
|
||||
// Unsloth proxy (server relays the request, attaching the API key from .env
|
||||
// so it never reaches the frontend — see py/routes/unsloth_routes.py)
|
||||
// ============================================
|
||||
|
||||
async function unslothProxy(baseUrl, path, method, payload) {
|
||||
const res = await fetch("/api/wfm/unsloth/proxy", {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify({ baseUrl, path, method, payload }),
|
||||
});
|
||||
const data = await res.json().catch(() => ({}));
|
||||
if (!res.ok) throw new Error(data.message || `HTTP ${res.status}`);
|
||||
return data;
|
||||
}
|
||||
|
||||
// Unlike Ollama/LM Studio/Lemonade (which inline reasoning as <think> tags
|
||||
// inside content), Unsloth's OpenAI-compatible API returns it in a separate
|
||||
// `reasoning_content` field. Fold it back into a <think> block so the
|
||||
// existing Thinking-mode show/strip logic (_applyGenOptions/stripThinkingTags)
|
||||
// still applies uniformly. Without this, a low max_tokens can make the model
|
||||
// spend its whole budget reasoning and return an empty `content` with no
|
||||
// visible explanation.
|
||||
function _unslothContent(message) {
|
||||
const reasoning = message?.reasoning_content;
|
||||
const content = message?.content || "";
|
||||
return reasoning ? `<think>${reasoning}</think>${content}` : content;
|
||||
}
|
||||
|
||||
// ============================================
|
||||
// URL validation
|
||||
// ============================================
|
||||
@@ -100,6 +169,9 @@ async function fetchModels(url, backend) {
|
||||
if (!res.ok) throw new Error(`HTTP ${res.status}`);
|
||||
const data = await res.json();
|
||||
return (data.models || []).map((m) => m.name);
|
||||
} else if (backend === "unsloth") {
|
||||
const data = await unslothProxy(url, "/v1/models", "GET");
|
||||
return (data.data || []).map((m) => m.id);
|
||||
} else {
|
||||
// LM Studio (OpenAI-compatible)
|
||||
const res = await fetch(`${url}/v1/models`);
|
||||
@@ -114,30 +186,37 @@ async function testConnection(url, backend) {
|
||||
return models.length;
|
||||
}
|
||||
|
||||
async function callLLM(url, backend, model, prompt) {
|
||||
async function callLLM(url, backend, model, prompt, settings = {}) {
|
||||
if (backend === "ollama") {
|
||||
const res = await fetch(`${url}/api/generate`, {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify({ model, prompt, stream: false }),
|
||||
body: JSON.stringify(_applyGenOptions({ model, prompt, stream: false }, backend, settings)),
|
||||
});
|
||||
if (!res.ok) throw new Error(`HTTP ${res.status}`);
|
||||
const data = await res.json();
|
||||
return data.response || "";
|
||||
const text = data.response || "";
|
||||
return settings.thinkingMode ? text : stripThinkingTags(text);
|
||||
} else if (backend === "unsloth") {
|
||||
const body = _applyGenOptions({ model, messages: [{ role: "user", content: prompt }], stream: false }, backend, settings);
|
||||
const data = await unslothProxy(url, "/v1/chat/completions", "POST", body);
|
||||
const text = _unslothContent(data.choices?.[0]?.message);
|
||||
return settings.thinkingMode ? text : stripThinkingTags(text);
|
||||
} else {
|
||||
// LM Studio (OpenAI-compatible)
|
||||
const res = await fetch(`${url}/v1/chat/completions`, {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify({
|
||||
body: JSON.stringify(_applyGenOptions({
|
||||
model,
|
||||
messages: [{ role: "user", content: prompt }],
|
||||
stream: false,
|
||||
}),
|
||||
}, backend, settings)),
|
||||
});
|
||||
if (!res.ok) throw new Error(`HTTP ${res.status}`);
|
||||
const data = await res.json();
|
||||
return data.choices?.[0]?.message?.content || "";
|
||||
const text = data.choices?.[0]?.message?.content || "";
|
||||
return settings.thinkingMode ? text : stripThinkingTags(text);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -145,11 +224,41 @@ async function callLLM(url, backend, model, prompt) {
|
||||
// Translation prompt builder
|
||||
// ============================================
|
||||
|
||||
function buildTranslationPrompt(text, srcLang, dstLang, settings) {
|
||||
const srcName = srcLang === "free" ? (settings.freeSrcLang || "Auto") : LANG_NAMES[srcLang];
|
||||
const dstName = dstLang === "free" ? (settings.freeDstLang || "English") : LANG_NAMES[dstLang];
|
||||
const fromPart = srcLang === "free" ? "" : `from ${srcName} `;
|
||||
return `Translate the following text ${fromPart}to ${dstName}. Output only the translated text, nothing else.\n\n${text}`;
|
||||
// Uses a system role (via callChat) rather than a single raw prompt string —
|
||||
// local models follow "translate only, no commentary" far more reliably
|
||||
// when it's a system instruction instead of buried inside the user text.
|
||||
function buildTranslationMessages(text, srcLang, dstLang, settings) {
|
||||
const srcName = srcLang === "free" ? (settings.freeSrcLang || "").trim() : LANG_NAMES[srcLang];
|
||||
const dstName = dstLang === "free" ? (settings.freeDstLang || "English").trim() || "English" : LANG_NAMES[dstLang];
|
||||
const fromPart = srcName ? ` from ${srcName}` : "";
|
||||
const system = `You are a professional translator. Translate the text the user sends${fromPart} into ${dstName}. `
|
||||
+ `Reply with ONLY the translated text and nothing else: no explanations, no notes, no preamble like "Here is the translation:", `
|
||||
+ `no surrounding quotes, and do not repeat or echo the original text.`;
|
||||
return [
|
||||
{ role: "system", content: system },
|
||||
{ role: "user", content: text },
|
||||
];
|
||||
}
|
||||
|
||||
// Strips common LLM wrapping/preamble artifacts that survive despite the system prompt.
|
||||
function cleanTranslationOutput(raw) {
|
||||
let s = (raw || "").trim();
|
||||
s = s.replace(/^(sure[,.]?\s*)?(here('|)s|here is)?\s*(the\s+)?translation\s*:?\s*/i, "");
|
||||
s = s.replace(/^(翻訳|译文|翻译)\s*[::]\s*/, "");
|
||||
if (s.length >= 2) {
|
||||
const first = s[0], last = s[s.length - 1];
|
||||
const pairs = { '"': '"', "'": "'", "“": "”", "「": "」" };
|
||||
if (pairs[first] === last) s = s.slice(1, -1).trim();
|
||||
}
|
||||
return s;
|
||||
}
|
||||
|
||||
// Heuristic: if the cleaned output is (near-)identical to the input, the
|
||||
// model most likely echoed the source instead of translating it.
|
||||
function looksUntranslated(input, output) {
|
||||
const normalize = (s) => s.trim().toLowerCase().replace(/[\s.,!?"'。、!?「」]/g, "");
|
||||
const a = normalize(input), b = normalize(output);
|
||||
return a.length > 0 && a === b;
|
||||
}
|
||||
|
||||
// ============================================
|
||||
@@ -217,11 +326,19 @@ function initTranslateTab() {
|
||||
outputEl.value = "";
|
||||
|
||||
try {
|
||||
const prompt = buildTranslationPrompt(text, srcLangSel.value, dstLangSel.value, settings);
|
||||
const result = await callLLM(url, backend, model, prompt);
|
||||
outputEl.value = result.trim();
|
||||
statusEl.textContent = t("aiStatusDone");
|
||||
statusEl.className = "wfm-ai-trans-status wfm-ai-status-ok";
|
||||
const messages = buildTranslationMessages(text, srcLangSel.value, dstLangSel.value, settings);
|
||||
const { content } = await callChat(url, backend, model, messages, undefined, settings);
|
||||
const cleaned = cleanTranslationOutput(content);
|
||||
outputEl.value = cleaned;
|
||||
|
||||
if (srcLangSel.value !== dstLangSel.value && looksUntranslated(text, cleaned)) {
|
||||
statusEl.textContent = t("aiStatusDone");
|
||||
statusEl.className = "wfm-ai-trans-status wfm-ai-status-error";
|
||||
showToast(t("aiToastMaybeNotTranslated"), "error");
|
||||
} else {
|
||||
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";
|
||||
@@ -288,6 +405,11 @@ function initSettingsTab() {
|
||||
const urlInput = document.getElementById("wfm-ai-backend-url");
|
||||
if (urlInput && saved.backendUrl) urlInput.value = saved.backendUrl;
|
||||
|
||||
const thinkingModeCheckbox = document.getElementById("wfm-ai-thinking-mode-checkbox");
|
||||
if (thinkingModeCheckbox) thinkingModeCheckbox.checked = !!saved.thinkingMode;
|
||||
const maxTokensInput = document.getElementById("wfm-ai-max-tokens");
|
||||
if (maxTokensInput && saved.maxTokens) maxTokensInput.value = saved.maxTokens;
|
||||
|
||||
// Switch URL to the new backend's default when the user changes backend
|
||||
backendRadios.forEach((r) => {
|
||||
r.addEventListener("change", () => {
|
||||
@@ -395,6 +517,8 @@ function initSettingsTab() {
|
||||
const chatGenDedicatedFilename = chatGenSelect?.value || "";
|
||||
const chatGenI2IDedicatedEnabled = !!chatGenI2ICheckbox?.checked;
|
||||
const chatGenI2IDedicatedFilename = chatGenI2ISelect?.value || "";
|
||||
const thinkingMode = !!thinkingModeCheckbox?.checked;
|
||||
const maxTokens = Math.max(0, parseInt(maxTokensInput?.value, 10) || 0);
|
||||
|
||||
if (url && !isValidBackendUrl(url)) {
|
||||
showToast(t("aiToastInvalidUrl"), "error");
|
||||
@@ -403,6 +527,7 @@ function initSettingsTab() {
|
||||
|
||||
saveAiSettings({
|
||||
backend, backendUrl: url, model, freeSrcLang, freeDstLang,
|
||||
thinkingMode, maxTokens,
|
||||
chatGenDedicatedEnabled, chatGenDedicatedFilename,
|
||||
chatGenI2IDedicatedEnabled, chatGenI2IDedicatedFilename,
|
||||
});
|
||||
@@ -453,10 +578,10 @@ function _formatMessagesForBackend(messages, backend) {
|
||||
});
|
||||
}
|
||||
|
||||
async function callChat(url, backend, model, messages, tools) {
|
||||
async function callChat(url, backend, model, messages, tools, settings = {}) {
|
||||
const formattedMessages = _formatMessagesForBackend(messages, backend);
|
||||
if (backend === "ollama") {
|
||||
const body = { model, messages: formattedMessages, stream: false };
|
||||
const body = _applyGenOptions({ model, messages: formattedMessages, stream: false }, backend, settings);
|
||||
if (tools) body.tools = tools;
|
||||
const res = await fetch(`${url}/api/chat`, {
|
||||
method: "POST",
|
||||
@@ -465,9 +590,17 @@ async function callChat(url, backend, model, messages, tools) {
|
||||
});
|
||||
if (!res.ok) throw new Error(`HTTP ${res.status}`);
|
||||
const message = (await res.json()).message || {};
|
||||
return { content: message.content || "", toolCalls: message.tool_calls || null };
|
||||
const content = message.content || "";
|
||||
return { content: settings.thinkingMode ? content : stripThinkingTags(content), toolCalls: message.tool_calls || null };
|
||||
} else if (backend === "unsloth") {
|
||||
const body = _applyGenOptions({ model, messages: formattedMessages, stream: false }, backend, settings);
|
||||
if (tools) { body.tools = tools; body.tool_choice = "auto"; }
|
||||
const data = await unslothProxy(url, "/v1/chat/completions", "POST", body);
|
||||
const message = data.choices?.[0]?.message || {};
|
||||
const content = _unslothContent(message);
|
||||
return { content: settings.thinkingMode ? content : stripThinkingTags(content), toolCalls: message.tool_calls || null };
|
||||
} else {
|
||||
const body = { model, messages: formattedMessages, stream: false };
|
||||
const body = _applyGenOptions({ model, messages: formattedMessages, stream: false }, backend, settings);
|
||||
if (tools) { body.tools = tools; body.tool_choice = "auto"; }
|
||||
const res = await fetch(`${url}/v1/chat/completions`, {
|
||||
method: "POST",
|
||||
@@ -476,7 +609,8 @@ async function callChat(url, backend, model, messages, tools) {
|
||||
});
|
||||
if (!res.ok) throw new Error(`HTTP ${res.status}`);
|
||||
const message = (await res.json()).choices?.[0]?.message || {};
|
||||
return { content: message.content || "", toolCalls: message.tool_calls || null };
|
||||
const content = message.content || "";
|
||||
return { content: settings.thinkingMode ? content : stripThinkingTags(content), toolCalls: message.tool_calls || null };
|
||||
}
|
||||
}
|
||||
|
||||
@@ -909,7 +1043,7 @@ function initChatTab() {
|
||||
const messagesToSend = skillPrompt
|
||||
? [{ role: "system", content: skillPrompt }, ...chatHistory]
|
||||
: chatHistory;
|
||||
const reply = await callChat(url, backend, model, messagesToSend, tools);
|
||||
const reply = await callChat(url, backend, model, messagesToSend, tools, settings);
|
||||
const toolCall = reply.toolCalls?.find(
|
||||
(tc) => (tc.function?.name || tc.name) === "generate_image"
|
||||
);
|
||||
@@ -1069,7 +1203,7 @@ function initVlmTab() {
|
||||
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);
|
||||
const result = await callLLM(url, backend, model, prompt, settings);
|
||||
resultEl.value = result.trim()
|
||||
.split("\n")
|
||||
.map(l => l.replace(/\*\*/g, "").replace(/^\*\s*/, "").replace(/^\d+\.\s*/, "").trim())
|
||||
@@ -1095,7 +1229,7 @@ function initVlmTab() {
|
||||
resultEl.value = "";
|
||||
|
||||
try {
|
||||
const result = await callVLM(url, backend, model, VLM_PROMPTS[task], _toolsImage.base64, _toolsImage.mimeType);
|
||||
const result = await callVLM(url, backend, model, VLM_PROMPTS[task], _toolsImage.base64, _toolsImage.mimeType, settings);
|
||||
resultEl.value = result.trim();
|
||||
statusEl.textContent = t("aiStatusDone");
|
||||
statusEl.className = "wfm-ai-trans-status wfm-ai-status-ok";
|
||||
|
||||
+94
-2
@@ -222,6 +222,68 @@ function applyI18nToHtml() {
|
||||
const galleryOpenTaggerBtn = document.getElementById("wfm-gallery-open-tagger-btn");
|
||||
if (galleryOpenTaggerBtn) galleryOpenTaggerBtn.textContent = t("tabTagger");
|
||||
|
||||
// Gallery サブタブ (Output / ImagePrompt / Style_Catalog)
|
||||
const galleryOutputSubtab = document.getElementById("wfm-gallery-subtab-output");
|
||||
if (galleryOutputSubtab) galleryOutputSubtab.textContent = t("galleryTabOutput");
|
||||
const galleryImagePromptSubtab = document.getElementById("wfm-gallery-subtab-imageprompt");
|
||||
if (galleryImagePromptSubtab) galleryImagePromptSubtab.textContent = t("galleryTabImagePrompt");
|
||||
const galleryStyleCatalogSubtab = document.getElementById("wfm-gallery-subtab-styleCatalog");
|
||||
if (galleryStyleCatalogSubtab) galleryStyleCatalogSubtab.textContent = t("galleryTabStyleCatalog");
|
||||
|
||||
// ImagePrompt ギャラリーパネル
|
||||
const imagePromptSearch = document.getElementById("wfm-imageprompt-search");
|
||||
if (imagePromptSearch) imagePromptSearch.placeholder = t("gallerySearchPlaceholder");
|
||||
const imagePromptRefreshBtn = document.getElementById("wfm-imageprompt-refresh-btn");
|
||||
if (imagePromptRefreshBtn) imagePromptRefreshBtn.textContent = t("refresh");
|
||||
const imagePromptTreeTitle = document.getElementById("wfm-imageprompt-tree-title");
|
||||
if (imagePromptTreeTitle) imagePromptTreeTitle.textContent = t("galleryFolders");
|
||||
const imagePromptListPlaceholder = document.getElementById("wfm-imageprompt-list-placeholder");
|
||||
if (imagePromptListPlaceholder) imagePromptListPlaceholder.textContent = t("gallerySelectFolder");
|
||||
const imagePromptNoSelection = document.getElementById("wfm-imageprompt-no-selection");
|
||||
if (imagePromptNoSelection) imagePromptNoSelection.textContent = t("galleryNoSelection");
|
||||
const imagePromptSelectedPromptTitle = document.getElementById("wfm-imageprompt-selected-prompt-title");
|
||||
if (imagePromptSelectedPromptTitle) imagePromptSelectedPromptTitle.textContent = t("imagePromptSelectedPrompt");
|
||||
const imagePromptSelectedPrompt = document.getElementById("wfm-imageprompt-selected-prompt");
|
||||
if (imagePromptSelectedPrompt) imagePromptSelectedPrompt.placeholder = t("imagePromptNoPrompt");
|
||||
const imagePromptSavePromptBtn = document.getElementById("wfm-imageprompt-save-prompt-btn");
|
||||
if (imagePromptSavePromptBtn) imagePromptSavePromptBtn.textContent = t("save");
|
||||
const imagePromptAddBtn = document.getElementById("wfm-imageprompt-add-btn");
|
||||
if (imagePromptAddBtn) imagePromptAddBtn.textContent = t("imagePromptAddBtn");
|
||||
const imagePromptChipsTitle = document.getElementById("wfm-imageprompt-chips-title");
|
||||
if (imagePromptChipsTitle) imagePromptChipsTitle.textContent = t("imagePromptChipsTitle");
|
||||
const imagePromptClearBtn = document.getElementById("wfm-imageprompt-clear-btn");
|
||||
if (imagePromptClearBtn) imagePromptClearBtn.textContent = t("imagePromptClearBtn");
|
||||
const imagePromptFinalPromptTitle = document.getElementById("wfm-imageprompt-final-prompt-title");
|
||||
if (imagePromptFinalPromptTitle) imagePromptFinalPromptTitle.textContent = t("imagePromptFinalPromptTitle");
|
||||
const imagePromptCopyBtn = document.getElementById("wfm-imageprompt-copy-btn");
|
||||
if (imagePromptCopyBtn) imagePromptCopyBtn.textContent = t("copy");
|
||||
|
||||
// Style_Catalog ギャラリーパネル
|
||||
const scSearch = document.getElementById("wfm-stylecatalog-search");
|
||||
if (scSearch) scSearch.placeholder = t("stylecatalogSearchPlaceholder");
|
||||
const scRefreshBtn = document.getElementById("wfm-stylecatalog-refresh-btn");
|
||||
if (scRefreshBtn) scRefreshBtn.textContent = t("refresh");
|
||||
const scTreeTitle = document.getElementById("wfm-stylecatalog-tree-title");
|
||||
if (scTreeTitle) scTreeTitle.textContent = t("galleryFolders");
|
||||
const scListPlaceholder = document.getElementById("wfm-stylecatalog-list-placeholder");
|
||||
if (scListPlaceholder) scListPlaceholder.textContent = t("gallerySelectFolder");
|
||||
const scNoSelection = document.getElementById("wfm-stylecatalog-no-selection");
|
||||
if (scNoSelection) scNoSelection.textContent = t("galleryNoSelection");
|
||||
const scPositiveTitle = document.getElementById("wfm-stylecatalog-positive-title");
|
||||
if (scPositiveTitle) scPositiveTitle.textContent = t("stylecatalogPositive");
|
||||
const scCopyPositiveBtn = document.getElementById("wfm-stylecatalog-copy-positive-btn");
|
||||
if (scCopyPositiveBtn) scCopyPositiveBtn.textContent = t("copy");
|
||||
const scNegativeTitle = document.getElementById("wfm-stylecatalog-negative-title");
|
||||
if (scNegativeTitle) scNegativeTitle.textContent = t("stylecatalogNegative");
|
||||
const scCopyNegativeBtn = document.getElementById("wfm-stylecatalog-copy-negative-btn");
|
||||
if (scCopyNegativeBtn) scCopyNegativeBtn.textContent = t("copy");
|
||||
const scSelectStyleBtn = document.getElementById("wfm-stylecatalog-select-style-btn");
|
||||
if (scSelectStyleBtn) scSelectStyleBtn.textContent = t("stylecatalogSelectStyleBtn");
|
||||
const scLoadGenuiBtn = document.getElementById("wfm-stylecatalog-load-genui-btn");
|
||||
if (scLoadGenuiBtn) scLoadGenuiBtn.textContent = t("stylecatalogLoadGenuiBtn");
|
||||
const scOpenMetadataBtn = document.getElementById("wfm-stylecatalog-open-metadata-btn");
|
||||
if (scOpenMetadataBtn) scOpenMetadataBtn.textContent = t("stylecatalogOpenMetadataBtn");
|
||||
|
||||
// Prompt tab
|
||||
const assistantHeader = document.querySelector(".wfm-prompt-split-left .wfm-prompt-split-header");
|
||||
if (assistantHeader) assistantHeader.textContent = t("assistantSubtab");
|
||||
@@ -302,6 +364,14 @@ function applyI18nToHtml() {
|
||||
}
|
||||
const aiModelRefreshBtn = document.getElementById("wfm-ai-model-refresh-btn");
|
||||
if (aiModelRefreshBtn) aiModelRefreshBtn.textContent = t("aiSettingsRefreshBtn");
|
||||
const aiGenerationTitle = document.getElementById("wfm-ai-settings-generation-title");
|
||||
if (aiGenerationTitle) aiGenerationTitle.textContent = t("aiSettingsGenerationTitle");
|
||||
const aiThinkingModeLabel = document.getElementById("wfm-ai-thinking-mode-label");
|
||||
if (aiThinkingModeLabel) aiThinkingModeLabel.textContent = t("aiSettingsThinkingMode");
|
||||
const aiMaxTokensLabel = document.getElementById("wfm-ai-max-tokens-label");
|
||||
if (aiMaxTokensLabel) aiMaxTokensLabel.textContent = t("aiSettingsMaxTokens");
|
||||
const aiMaxTokensInput = document.getElementById("wfm-ai-max-tokens");
|
||||
if (aiMaxTokensInput) aiMaxTokensInput.placeholder = t("aiSettingsMaxTokensPlaceholder");
|
||||
const aiFreeLangTitle = document.getElementById("wfm-ai-settings-freelang-title");
|
||||
if (aiFreeLangTitle) aiFreeLangTitle.textContent = t("aiSettingsFreeLang");
|
||||
const aiFreeSrcLabel = document.getElementById("wfm-ai-free-src-label");
|
||||
@@ -380,6 +450,11 @@ function applyI18nToHtml() {
|
||||
"wfm-help-gen-15": "helpGen15", "wfm-help-gen-16": "helpGen16",
|
||||
"wfm-help-gen-17": "helpGen17", "wfm-help-gen-18": "helpGen18",
|
||||
"wfm-help-gen-19": "helpGen19",
|
||||
"wfm-help-gen-20": "helpGen20", "wfm-help-gen-21": "helpGen21",
|
||||
"wfm-help-gen-22": "helpGen22", "wfm-help-gen-23": "helpGen23",
|
||||
"wfm-help-gen-24": "helpGen24", "wfm-help-gen-25": "helpGen25",
|
||||
"wfm-help-gen-26": "helpGen26", "wfm-help-gen-27": "helpGen27",
|
||||
"wfm-help-gen-28": "helpGen28",
|
||||
"wfm-help-feeder-title": "helpFeederTitle",
|
||||
"wfm-help-feeder-desc": "helpFeederDesc",
|
||||
"wfm-help-feeder-imgloop-title": "helpFeederImgloopTitle",
|
||||
@@ -401,11 +476,16 @@ function applyI18nToHtml() {
|
||||
"wfm-help-lab-3": "helpLab3", "wfm-help-lab-4": "helpLab4",
|
||||
"wfm-help-lab-5": "helpLab5", "wfm-help-lab-6": "helpLab6",
|
||||
"wfm-help-lab-7": "helpLab7", "wfm-help-lab-8": "helpLab8",
|
||||
"wfm-help-lab-9": "helpLab9", "wfm-help-lab-10": "helpLab10",
|
||||
"wfm-help-lab-11": "helpLab11", "wfm-help-lab-12": "helpLab12",
|
||||
"wfm-help-lab-13": "helpLab13",
|
||||
"wfm-help-lab-card-plan-title": "helpLabCardPlanTitle",
|
||||
"wfm-help-lab-plan-1": "helpLabPlan1", "wfm-help-lab-plan-2": "helpLabPlan2",
|
||||
"wfm-help-lab-plan-3": "helpLabPlan3", "wfm-help-lab-plan-4": "helpLabPlan4",
|
||||
"wfm-help-lab-plan-5": "helpLabPlan5", "wfm-help-lab-plan-6": "helpLabPlan6",
|
||||
"wfm-help-lab-plan-7": "helpLabPlan7", "wfm-help-lab-plan-8": "helpLabPlan8",
|
||||
"wfm-help-lab-plan-9": "helpLabPlan9", "wfm-help-lab-plan-10": "helpLabPlan10",
|
||||
"wfm-help-lab-plan-11": "helpLabPlan11",
|
||||
"wfm-help-lab-card-results-title": "helpLabCardResultsTitle",
|
||||
"wfm-help-lab-results-1": "helpLabResults1", "wfm-help-lab-results-2": "helpLabResults2",
|
||||
"wfm-help-lab-results-3": "helpLabResults3",
|
||||
@@ -414,13 +494,17 @@ function applyI18nToHtml() {
|
||||
"wfm-help-prompt-5": "helpPrompt5", "wfm-help-prompt-6": "helpPrompt6",
|
||||
"wfm-help-prompt-7": "helpPrompt7", "wfm-help-prompt-8": "helpPrompt8",
|
||||
"wfm-help-prompt-9": "helpPrompt9",
|
||||
"wfm-help-prompt-card-style-title": "helpPromptCardStyleTitle",
|
||||
"wfm-help-prompt-10": "helpPrompt10", "wfm-help-prompt-11": "helpPrompt11",
|
||||
"wfm-help-prompt-12": "helpPrompt12", "wfm-help-prompt-13": "helpPrompt13",
|
||||
"wfm-help-prompt-14": "helpPrompt14",
|
||||
"wfm-help-settings-1": "helpSettings1", "wfm-help-settings-2": "helpSettings2",
|
||||
"wfm-help-settings-3": "helpSettings3", "wfm-help-settings-4": "helpSettings4",
|
||||
"wfm-help-settings-5": "helpSettings5", "wfm-help-settings-6": "helpSettings6",
|
||||
"wfm-help-settings-7": "helpSettings7", "wfm-help-settings-8": "helpSettings8",
|
||||
"wfm-help-settings-9": "helpSettings9", "wfm-help-settings-10": "helpSettings10",
|
||||
"wfm-help-settings-11": "helpSettings11", "wfm-help-settings-12": "helpSettings12",
|
||||
"wfm-help-settings-13": "helpSettings13",
|
||||
"wfm-help-settings-13": "helpSettings13", "wfm-help-settings-14": "helpSettings14",
|
||||
"wfm-help-nodes-1": "helpNodes1", "wfm-help-nodes-2": "helpNodes2",
|
||||
"wfm-help-nodes-3": "helpNodes3", "wfm-help-nodes-4": "helpNodes4",
|
||||
"wfm-help-nodes-5": "helpNodes5", "wfm-help-nodes-6": "helpNodes6",
|
||||
@@ -441,6 +525,12 @@ function applyI18nToHtml() {
|
||||
"wfm-help-gallery-13": "helpGallery13", "wfm-help-gallery-14": "helpGallery14",
|
||||
"wfm-help-gallery-15": "helpGallery15", "wfm-help-gallery-16": "helpGallery16",
|
||||
"wfm-help-gallery-17": "helpGallery17",
|
||||
"wfm-help-gallery-18": "helpGallery18", "wfm-help-gallery-19": "helpGallery19",
|
||||
"wfm-help-gallery-20": "helpGallery20", "wfm-help-gallery-21": "helpGallery21",
|
||||
"wfm-help-gallery-22": "helpGallery22", "wfm-help-gallery-23": "helpGallery23",
|
||||
"wfm-help-gallery-24": "helpGallery24", "wfm-help-gallery-25": "helpGallery25",
|
||||
"wfm-help-gallery-card-styleprompt-title": "helpGalleryCardStyleprompt",
|
||||
"wfm-help-gallery-card-stylecatalog-title": "helpGalleryCardStylecatalog",
|
||||
"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",
|
||||
@@ -550,6 +640,7 @@ function applyI18nToHtml() {
|
||||
"wfm-help-gen-card-seed-title": "helpGenCardSeed",
|
||||
"wfm-help-gen-card-batchsetup-title": "helpGenCardBatchSetup",
|
||||
"wfm-help-gen-card-batchtypes-title": "helpGenCardBatchTypes",
|
||||
"wfm-help-gen-card-lora-title": "helpGenCardLora",
|
||||
"wfm-help-prompt-title": "helpPromptTitle",
|
||||
"wfm-help-prompt-card-ai-title": "helpPromptCardAi",
|
||||
"wfm-help-prompt-card-presets-title": "helpPromptCardPresets",
|
||||
@@ -674,7 +765,7 @@ import { initWorkflowTab } from "./workflow-tab.js";
|
||||
import { initNodesTab } from "./nodes-tab.js";
|
||||
import { initGenerateTab } from "./generate-tab.js";
|
||||
import { initPromptTab } from "./prompt-tab.js";
|
||||
import { initSettingsTab, applyTheme, getSavedTheme, applyTextareaFontSize, applyJsonColors } from "./settings-tab.js";
|
||||
import { initSettingsTab, applyTheme, getSavedTheme, applyTextareaFontSize, applyJsonColors, applyModelTabActiveColor } from "./settings-tab.js";
|
||||
import { initModelsTab } from "./models-tab.js";
|
||||
import { initGalleryTab } from "./gallery-tab.js";
|
||||
import { initMetadataTab } from "./metadata-tab.js";
|
||||
@@ -690,6 +781,7 @@ try {
|
||||
const _s = getSettings();
|
||||
if (_s.textareaFontSize) applyTextareaFontSize(_s.textareaFontSize);
|
||||
applyJsonColors(_s.jsonColors);
|
||||
applyModelTabActiveColor(_s.modelTabActiveColor);
|
||||
} catch {}
|
||||
|
||||
function initHelpTab() {
|
||||
|
||||
@@ -18,8 +18,15 @@ export const comfyUI = {
|
||||
connected: false,
|
||||
generating: false,
|
||||
currentPromptId: null,
|
||||
// trackProgress() 実行中の Promise を promptId -> reject関数 で保持。
|
||||
// WebSocket切断時に、待機中のPromiseを解決させずに放置してバッチループが
|
||||
// 無言のまま停止する(例: カタログ作成バッチが特定件数で止まる)のを防ぐ。
|
||||
_pendingTrackers: new Map(),
|
||||
currentWorkflow: null,
|
||||
currentAnalysis: null,
|
||||
// ワークフロー読み込み時点のLora Loader (LoraManager)ノードの loras/text 状態。
|
||||
// Stackグループチェックボックスのトグル時に、OFF側の「読み込み時の状態へ戻す」用に使う。
|
||||
loraManagerSnapshots: {},
|
||||
|
||||
updateUrl(url) {
|
||||
if (!url) {
|
||||
@@ -66,10 +73,18 @@ export const comfyUI = {
|
||||
this.socket = new WebSocket(url);
|
||||
this.socket.onopen = () => resolve(true);
|
||||
this.socket.onerror = () => resolve(false);
|
||||
this.socket.onclose = () => { this.socket = null; };
|
||||
this.socket.onclose = () => {
|
||||
this.socket = null;
|
||||
this._rejectPendingTrackers(new Error("WebSocket disconnected"));
|
||||
};
|
||||
});
|
||||
},
|
||||
|
||||
_rejectPendingTrackers(err) {
|
||||
for (const rejectFn of this._pendingTrackers.values()) rejectFn(err);
|
||||
this._pendingTrackers.clear();
|
||||
},
|
||||
|
||||
// Node info fetching
|
||||
async fetchObjectInfo(nodeClass) {
|
||||
const res = await fetch(`${this.baseUrl}/object_info/${nodeClass}`);
|
||||
@@ -196,12 +211,29 @@ export const comfyUI = {
|
||||
return await res.json();
|
||||
},
|
||||
|
||||
trackProgress(promptId, progressCallback) {
|
||||
// timeoutMs: この時間内に完了/エラー/中断通知が来なければ強制的にreject。
|
||||
// WebSocketの取りこぼしやexecution_interrupted未処理でPromiseが永久に
|
||||
// ぶら下がり続け、バッチループが無言で停止するのを防ぐための安全弁。
|
||||
trackProgress(promptId, progressCallback, timeoutMs = 10 * 60 * 1000) {
|
||||
return new Promise((resolve, reject) => {
|
||||
if (!this.socket || this.socket.readyState !== WebSocket.OPEN) {
|
||||
reject(new Error("WebSocket not connected"));
|
||||
return;
|
||||
}
|
||||
let settled = false;
|
||||
const finish = (isResolve, value) => {
|
||||
if (settled) return;
|
||||
settled = true;
|
||||
this.socket?.removeEventListener("message", handler);
|
||||
clearTimeout(timer);
|
||||
this._pendingTrackers.delete(promptId);
|
||||
if (isResolve) resolve(value); else reject(value);
|
||||
};
|
||||
|
||||
const timer = setTimeout(() => {
|
||||
finish(false, new Error(`Generation timed out after ${Math.round(timeoutMs / 1000)}s (prompt_id=${promptId})`));
|
||||
}, timeoutMs);
|
||||
|
||||
const handler = (event) => {
|
||||
try {
|
||||
const msg = JSON.parse(event.data);
|
||||
@@ -211,17 +243,19 @@ export const comfyUI = {
|
||||
}
|
||||
if (msg.type === "executing" && msg.data?.prompt_id === promptId) {
|
||||
if (msg.data.node === null) {
|
||||
this.socket.removeEventListener("message", handler);
|
||||
resolve();
|
||||
finish(true);
|
||||
}
|
||||
}
|
||||
if (msg.type === "execution_error" && msg.data?.prompt_id === promptId) {
|
||||
this.socket.removeEventListener("message", handler);
|
||||
reject(new Error(msg.data.exception_message || "Execution error"));
|
||||
finish(false, new Error(msg.data.exception_message || "Execution error"));
|
||||
}
|
||||
if (msg.type === "execution_interrupted" && msg.data?.prompt_id === promptId) {
|
||||
finish(false, new Error("Execution interrupted"));
|
||||
}
|
||||
} catch {}
|
||||
};
|
||||
this.socket.addEventListener("message", handler);
|
||||
this._pendingTrackers.set(promptId, (err) => finish(false, err));
|
||||
});
|
||||
},
|
||||
|
||||
@@ -276,7 +310,7 @@ export const comfyUI = {
|
||||
|
||||
// High-level generate
|
||||
async generate(workflow, options = {}) {
|
||||
const { seedMode = "random", seedValue = -1, onProgress, onComplete, onError } = options;
|
||||
const { seedMode = "random", seedValue = -1, onProgress, onComplete, onError, timeoutMs } = options;
|
||||
|
||||
this.generating = true;
|
||||
try {
|
||||
@@ -298,7 +332,7 @@ export const comfyUI = {
|
||||
this.currentPromptId = result.prompt_id;
|
||||
|
||||
// Track progress
|
||||
await this.trackProgress(result.prompt_id, onProgress);
|
||||
await this.trackProgress(result.prompt_id, onProgress, timeoutMs);
|
||||
|
||||
// Get history/results
|
||||
const history = await this.getHistory(result.prompt_id);
|
||||
|
||||
+382
-55
@@ -27,6 +27,114 @@ function _saveLatentPresets(list) {
|
||||
localStorage.setItem(_LATENT_PRESET_KEY, JSON.stringify(list));
|
||||
}
|
||||
|
||||
// ── I2I placeholder image (Input tab / Image sub-panel) ──────────────────
|
||||
// One shared default (color-generated or a fixed uploaded image), remembered across
|
||||
// sessions. Each LoadImage slot's own "Placeholder" button applies this same default
|
||||
// to just that slot — see renderImageTab.
|
||||
const _I2I_PLACEHOLDER_KEY = "wfm_i2i_placeholder";
|
||||
const _I2I_PLACEHOLDER_DEFAULT = { mode: "color", color: "#808080", width: 512, height: 512, imageFilename: "" };
|
||||
|
||||
function _loadI2IPlaceholderConfig() {
|
||||
try {
|
||||
const raw = localStorage.getItem(_I2I_PLACEHOLDER_KEY);
|
||||
return raw ? { ..._I2I_PLACEHOLDER_DEFAULT, ...JSON.parse(raw) } : { ..._I2I_PLACEHOLDER_DEFAULT };
|
||||
} catch { return { ..._I2I_PLACEHOLDER_DEFAULT }; }
|
||||
}
|
||||
|
||||
function _saveI2IPlaceholderConfig(cfg) {
|
||||
localStorage.setItem(_I2I_PLACEHOLDER_KEY, JSON.stringify(cfg));
|
||||
}
|
||||
|
||||
// Renders a solid-color PNG on an offscreen canvas and returns it as a File, ready to
|
||||
// upload through comfyUI.uploadImage() the same way a picked/dropped file would be.
|
||||
function _generateColorImageFile(width, height, color) {
|
||||
return new Promise((resolve, reject) => {
|
||||
const canvas = document.createElement("canvas");
|
||||
canvas.width = Math.max(1, width || 512);
|
||||
canvas.height = Math.max(1, height || 512);
|
||||
const ctx = canvas.getContext("2d");
|
||||
ctx.fillStyle = color || "#808080";
|
||||
ctx.fillRect(0, 0, canvas.width, canvas.height);
|
||||
canvas.toBlob((blob) => {
|
||||
if (!blob) { reject(new Error("Failed to render placeholder image")); return; }
|
||||
resolve(new File([blob], `placeholder_${canvas.width}x${canvas.height}.png`, { type: "image/png" }));
|
||||
}, "image/png");
|
||||
});
|
||||
}
|
||||
|
||||
// Wires the placeholder config panel at the top of the Image sub-panel (mode switch,
|
||||
// color/size fields, default-image drop zone). Every change is persisted immediately via
|
||||
// _saveI2IPlaceholderConfig so it's remembered next time the panel is rendered — this
|
||||
// panel is display-only config, it doesn't touch any workflow node itself; only each
|
||||
// slot's own Placeholder button (see renderImageTab) does that.
|
||||
function _wireI2IPlaceholderConfig(scopeEl) {
|
||||
const colorModeRadio = scopeEl.querySelector("#wfm-i2i-ph-mode-color");
|
||||
const imageModeRadio = scopeEl.querySelector("#wfm-i2i-ph-mode-image");
|
||||
const colorFields = scopeEl.querySelector("#wfm-i2i-ph-color-fields");
|
||||
const imageFields = scopeEl.querySelector("#wfm-i2i-ph-image-fields");
|
||||
const widthInput = scopeEl.querySelector("#wfm-i2i-ph-width");
|
||||
const heightInput = scopeEl.querySelector("#wfm-i2i-ph-height");
|
||||
const colorInput = scopeEl.querySelector("#wfm-i2i-ph-color");
|
||||
const dropZone = scopeEl.querySelector("#wfm-i2i-ph-drop");
|
||||
const fileInput = scopeEl.querySelector("#wfm-i2i-ph-file");
|
||||
const previewWrap = scopeEl.querySelector("#wfm-i2i-ph-preview-wrap");
|
||||
const previewImg = scopeEl.querySelector("#wfm-i2i-ph-preview-img");
|
||||
const statusEl = scopeEl.querySelector("#wfm-i2i-ph-status");
|
||||
if (!colorModeRadio) return; // no LoadImage slots rendered — panel doesn't exist
|
||||
|
||||
const setMode = (mode) => {
|
||||
if (colorFields) colorFields.style.display = mode === "color" ? "" : "none";
|
||||
if (imageFields) imageFields.style.display = mode === "image" ? "" : "none";
|
||||
_saveI2IPlaceholderConfig({ ..._loadI2IPlaceholderConfig(), mode });
|
||||
};
|
||||
colorModeRadio.addEventListener("change", () => { if (colorModeRadio.checked) setMode("color"); });
|
||||
imageModeRadio?.addEventListener("change", () => { if (imageModeRadio.checked) setMode("image"); });
|
||||
|
||||
widthInput?.addEventListener("change", () => {
|
||||
const width = Math.max(1, parseInt(widthInput.value, 10) || 512);
|
||||
widthInput.value = width;
|
||||
_saveI2IPlaceholderConfig({ ..._loadI2IPlaceholderConfig(), width });
|
||||
});
|
||||
heightInput?.addEventListener("change", () => {
|
||||
const height = Math.max(1, parseInt(heightInput.value, 10) || 512);
|
||||
heightInput.value = height;
|
||||
_saveI2IPlaceholderConfig({ ..._loadI2IPlaceholderConfig(), height });
|
||||
});
|
||||
colorInput?.addEventListener("change", () => {
|
||||
_saveI2IPlaceholderConfig({ ..._loadI2IPlaceholderConfig(), color: colorInput.value });
|
||||
});
|
||||
|
||||
// Default image: uploaded to ComfyUI immediately (its filename is what actually gets
|
||||
// reused later, not the raw file) so every slot's Placeholder button can apply it
|
||||
// without re-uploading.
|
||||
const applyDefaultImageFile = async (file) => {
|
||||
if (!file || !file.type.startsWith("image/")) return;
|
||||
if (statusEl) statusEl.textContent = t("i2iPlaceholderUploading");
|
||||
try {
|
||||
const result = await comfyUI.uploadImage(file, file.name);
|
||||
if (!result.name) throw new Error("Upload returned no filename");
|
||||
_saveI2IPlaceholderConfig({ ..._loadI2IPlaceholderConfig(), imageFilename: result.name });
|
||||
if (previewImg) previewImg.src = `/view?filename=${encodeURIComponent(result.name)}&type=input`;
|
||||
if (previewWrap) previewWrap.style.display = "";
|
||||
if (statusEl) { statusEl.textContent = `✓ ${result.name}`; statusEl.style.color = "var(--wfm-success)"; }
|
||||
} catch (err) {
|
||||
if (statusEl) { statusEl.textContent = `✗ ${err.message}`; statusEl.style.color = "var(--wfm-danger)"; }
|
||||
}
|
||||
};
|
||||
fileInput?.addEventListener("change", () => {
|
||||
if (fileInput.files.length > 0) applyDefaultImageFile(fileInput.files[0]);
|
||||
});
|
||||
if (dropZone) {
|
||||
dropZone.addEventListener("dragover", (e) => { e.preventDefault(); dropZone.classList.add("drag-over"); });
|
||||
dropZone.addEventListener("dragleave", () => dropZone.classList.remove("drag-over"));
|
||||
dropZone.addEventListener("drop", (e) => {
|
||||
e.preventDefault();
|
||||
dropZone.classList.remove("drag-over");
|
||||
if (e.dataTransfer.files.length > 0) applyDefaultImageFile(e.dataTransfer.files[0]);
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
function _buildPresetOptions(customPresets) {
|
||||
const customs = customPresets.map((p) =>
|
||||
`<option value="${p.w}x${p.h}">${p.w}x${p.h}</option>`
|
||||
@@ -344,11 +452,11 @@ export const comfyEditor = {
|
||||
return found || name;
|
||||
},
|
||||
|
||||
renderAll(analysis, workflow) {
|
||||
renderAll(analysis, workflow, opts = {}) {
|
||||
this.renderPromptTab(analysis, "wfm-gen-prompt-fields");
|
||||
this.renderImageTab(analysis, "wfm-gen-image-fields");
|
||||
this.renderModelTab(analysis, "wfm-gen-model-fields");
|
||||
this.renderLoraPane(analysis, "wfm-gen-lora-fields"); // async, fires independently
|
||||
this.renderLoraPane(analysis, "wfm-gen-lora-fields", opts); // async, fires independently
|
||||
this.renderSettingsTab(analysis, "wfm-gen-settings-fields");
|
||||
_syncRawJson();
|
||||
},
|
||||
@@ -508,10 +616,14 @@ export const comfyEditor = {
|
||||
const el = document.getElementById(containerId);
|
||||
if (!el) return;
|
||||
|
||||
const sections = [
|
||||
// 使用頻度の高い順: Checkpoint/VAE/Diffusion Model/Text Encoder は常時表示。
|
||||
// ControlNet/Hypernetwork は意図的に使う場面が限られるため折りたたみにする。
|
||||
const mainSections = [
|
||||
{ label: "Checkpoint", key: "checkpoints", nodes: analysis.checkpoint_nodes, inputKey: "ckpt_name" },
|
||||
{ label: "VAE", key: "vaes", nodes: analysis.vae_nodes, inputKey: "vae_name" },
|
||||
{ label: "Diffusion Model", key: "diffusionModels", nodes: analysis.diffusion_model_nodes, inputKey: "unet_name" },
|
||||
];
|
||||
const collapsibleSections = [
|
||||
{ label: "ControlNet", key: "controlNets", nodes: analysis.controlnet_nodes, inputKey: "control_net_name" },
|
||||
{
|
||||
label: "Hypernetwork", key: "hypernetworks", nodes: analysis.hypernetwork_nodes, inputKey: "hypernetwork_name",
|
||||
@@ -519,46 +631,65 @@ export const comfyEditor = {
|
||||
},
|
||||
];
|
||||
|
||||
el.innerHTML = sections
|
||||
.map((s) => {
|
||||
const models = this.models[s.key] || [];
|
||||
const currentVal = s.nodes?.[0]?.[s.inputKey] || "";
|
||||
const isMissing = !!currentVal && !models.includes(currentVal);
|
||||
const targetOpts = s.nodes
|
||||
.map((n) => `<option value="${n.id}">ID:${n.id} (${n.title})</option>`)
|
||||
.join("");
|
||||
const extrasHtml = (s.extras || []).map((ex) => {
|
||||
const curVal = s.nodes?.[0]?.[ex.inputKey] ?? ex.defaultVal;
|
||||
return `<div style="display:flex;gap:6px;align-items:center;margin-top:4px;">
|
||||
<label style="font-size:12px;white-space:nowrap;color:var(--wfm-text-secondary);">${ex.label}</label>
|
||||
<input type="${ex.type}" class="wfm-input wfm-model-extra" id="wfm-model-${s.key}-${ex.inputKey}"
|
||||
data-key="${s.key}" data-input-key="${ex.inputKey}"
|
||||
value="${curVal}" step="${ex.step}" min="${ex.min}" max="${ex.max}"
|
||||
style="width:80px;">
|
||||
</div>`;
|
||||
}).join("");
|
||||
const renderSectionBody = (s) => {
|
||||
const models = this.models[s.key] || [];
|
||||
const currentVal = s.nodes?.[0]?.[s.inputKey] || "";
|
||||
const isMissing = !!currentVal && !models.includes(currentVal);
|
||||
const targetOpts = s.nodes
|
||||
.map((n) => `<option value="${n.id}">ID:${n.id} (${n.title})</option>`)
|
||||
.join("");
|
||||
const extrasHtml = (s.extras || []).map((ex) => {
|
||||
const curVal = s.nodes?.[0]?.[ex.inputKey] ?? ex.defaultVal;
|
||||
return `<div style="display:flex;gap:6px;align-items:center;margin-top:4px;">
|
||||
<label style="font-size:12px;white-space:nowrap;color:var(--wfm-text-secondary);">${ex.label}</label>
|
||||
<input type="${ex.type}" class="wfm-input wfm-model-extra" id="wfm-model-${s.key}-${ex.inputKey}"
|
||||
data-key="${s.key}" data-input-key="${ex.inputKey}"
|
||||
value="${curVal}" step="${ex.step}" min="${ex.min}" max="${ex.max}"
|
||||
style="width:80px;">
|
||||
</div>`;
|
||||
}).join("");
|
||||
|
||||
return `
|
||||
<div class="wfm-form-group" style="border-bottom:1px solid var(--wfm-border);padding-bottom:12px;">
|
||||
<label>${s.label}</label>
|
||||
<div class="wfm-search-wrap" style="margin-bottom:4px;width:100%;">
|
||||
<input type="text" class="wfm-input wfm-search-input wfm-model-filter" id="wfm-model-${s.key}-filter" placeholder="Filter..." data-target="wfm-model-${s.key}">
|
||||
<button type="button" class="wfm-search-clear-btn" id="wfm-model-${s.key}-filter-clear" title="Clear search">✕</button>
|
||||
</div>
|
||||
<select class="wfm-select ${isMissing ? "wfm-select-missing" : ""}" id="wfm-model-${s.key}" style="margin-bottom:4px;">
|
||||
${isMissing ? `<option value="${escapeHtml(currentVal)}" selected>⚠ ${escapeHtml(currentVal)} (${t("modelNotFound")})</option>` : ""}
|
||||
${models.map((m) => `<option value="${m}" ${m === currentVal ? "selected" : ""}>${m}</option>`).join("")}
|
||||
</select>
|
||||
${isMissing ? `<div class="wfm-model-missing-hint">${t("modelNotFoundHint")}</div>` : ""}
|
||||
${extrasHtml}
|
||||
<div style="display:flex;gap:8px;align-items:center;margin-top:4px;">
|
||||
<select class="wfm-select" id="wfm-model-${s.key}-target" style="flex:1;">${targetOpts}</select>
|
||||
<button class="wfm-btn wfm-btn-sm wfm-model-apply" data-key="${s.key}" data-input="${s.inputKey}" title="Apply (Alt+Click: Apply & Generate)">Apply</button>
|
||||
</div>
|
||||
return `
|
||||
<div class="wfm-search-wrap" style="margin-bottom:4px;width:100%;">
|
||||
<input type="text" class="wfm-input wfm-search-input wfm-model-filter" id="wfm-model-${s.key}-filter" placeholder="Filter..." data-target="wfm-model-${s.key}">
|
||||
<button type="button" class="wfm-search-clear-btn" id="wfm-model-${s.key}-filter-clear" title="Clear search">✕</button>
|
||||
</div>
|
||||
<select class="wfm-select ${isMissing ? "wfm-select-missing" : ""}" id="wfm-model-${s.key}" style="margin-bottom:4px;">
|
||||
${isMissing ? `<option value="${escapeHtml(currentVal)}" selected>⚠ ${escapeHtml(currentVal)} (${t("modelNotFound")})</option>` : ""}
|
||||
${models.map((m) => `<option value="${m}" ${m === currentVal ? "selected" : ""}>${m}</option>`).join("")}
|
||||
</select>
|
||||
${isMissing ? `<div class="wfm-model-missing-hint">${t("modelNotFoundHint")}</div>` : ""}
|
||||
${extrasHtml}
|
||||
<div style="display:flex;gap:8px;align-items:center;margin-top:4px;">
|
||||
<select class="wfm-select" id="wfm-model-${s.key}-target" style="flex:1;">${targetOpts}</select>
|
||||
<button class="wfm-btn wfm-btn-sm wfm-model-apply" data-key="${s.key}" data-input="${s.inputKey}" title="Apply (Alt+Click: Apply & Generate)">Apply</button>
|
||||
</div>
|
||||
`;
|
||||
})
|
||||
.join("") + '<div class="wfm-form-group" id="wfm-te-section" style="border-bottom:1px solid var(--wfm-border);padding-bottom:12px;"><label>Text Encoder</label></div>';
|
||||
};
|
||||
|
||||
const mainHtml = mainSections.map((s) => {
|
||||
const hasNodes = (s.nodes?.length || 0) > 0;
|
||||
return `
|
||||
<div class="wfm-form-group" style="border-bottom:1px solid var(--wfm-border);padding-bottom:12px;">
|
||||
<label class="${hasNodes ? "wfm-model-label-active" : ""}">${s.label}</label>
|
||||
${renderSectionBody(s)}
|
||||
</div>`;
|
||||
}).join("");
|
||||
|
||||
const teHtml = '<div class="wfm-form-group" id="wfm-te-section" style="border-bottom:1px solid var(--wfm-border);padding-bottom:12px;"><label>Text Encoder</label></div>';
|
||||
|
||||
const collapsibleHtml = collapsibleSections.map((s) => {
|
||||
const hasNodes = (s.nodes?.length || 0) > 0;
|
||||
return `
|
||||
<details class="wfm-settings-section">
|
||||
<summary class="wfm-settings-summary ${hasNodes ? "wfm-model-label-active" : ""}">${s.label}</summary>
|
||||
<div class="wfm-form-group" style="margin-bottom:0;">
|
||||
${renderSectionBody(s)}
|
||||
</div>
|
||||
</details>`;
|
||||
}).join("");
|
||||
|
||||
el.innerHTML = mainHtml + teHtml + collapsibleHtml;
|
||||
|
||||
// Filter inputs
|
||||
el.querySelectorAll(".wfm-model-filter").forEach((input) => {
|
||||
@@ -611,13 +742,34 @@ export const comfyEditor = {
|
||||
_initTextEncoderSection(analysis, this.models.textEncoders || [], el).catch(() => {});
|
||||
},
|
||||
|
||||
async renderLoraPane(analysis, containerId) {
|
||||
async renderLoraPane(analysis, containerId, opts = {}) {
|
||||
const el = document.getElementById(containerId);
|
||||
if (!el) return;
|
||||
|
||||
const loraNodes = analysis.lora_nodes || [];
|
||||
document.getElementById("wfm-gen-lora-col-title")?.classList.toggle("wfm-model-label-active", loraNodes.length > 0);
|
||||
const loras = this.models.loras || [];
|
||||
const defaultStackTarget = (loraNodes.find((n) => n.is_lora_manager) || loraNodes[0])?.id;
|
||||
const hasLoraManager = loraNodes.some((n) => n.is_lora_manager);
|
||||
// Use Stack Group チェックボックスの現在状態を先読み(Stack表示の取得元判定に使う)。
|
||||
// resetStackMode(新規読み込み)時は常にOFF扱い。
|
||||
const stackModeChecked = hasLoraManager && !opts.resetStackMode && (el.querySelector("#wfm-lora-stack-mode-toggle")?.checked ?? false);
|
||||
|
||||
// ワークフロー新規読み込み時のみ: LoraManagerノードのloras/text状態をスナップショットし、
|
||||
// Stackグループ使用チェックボックスをOFFへリセットする(既存のGenUI状態への影響を避けるため
|
||||
// タブ切替やStack再読込などの単なる再描画では行わない)。
|
||||
if (opts.resetStackMode) {
|
||||
comfyUI.loraManagerSnapshots = {};
|
||||
for (const n of loraNodes) {
|
||||
if (!n.is_lora_manager) continue;
|
||||
const wfNode = comfyUI.currentWorkflow?.[n.id];
|
||||
if (!wfNode?.inputs) continue;
|
||||
comfyUI.loraManagerSnapshots[n.id] = {
|
||||
loras: Array.isArray(wfNode.inputs.loras?.__value__) ? JSON.parse(JSON.stringify(wfNode.inputs.loras.__value__)) : [],
|
||||
text: wfNode.inputs.text ?? "",
|
||||
};
|
||||
}
|
||||
}
|
||||
const nodeOpts = loraNodes
|
||||
.map((n) => `<option value="${n.id}">ID:${n.id} (${n.title})</option>`)
|
||||
.join("");
|
||||
@@ -642,26 +794,53 @@ export const comfyEditor = {
|
||||
}
|
||||
}
|
||||
|
||||
// Fetch Stack group, metadata, CivitAI cache in parallel
|
||||
// Stack表示の取得元: ON(Use Stack Group)ならModelsタブの登録済みStackグループ、
|
||||
// OFF(既定)ならLoraManagerノードに実際に設定されているLoRAをそのまま表示する。
|
||||
let stackModels = [];
|
||||
let metadata = {};
|
||||
let civitaiCache = {};
|
||||
const useWorkflowLoraState = hasLoraManager && !stackModeChecked;
|
||||
try {
|
||||
const [grpRes, metaRes, civRes] = await Promise.all([
|
||||
fetch("/api/wfm/models/groups?type=lora"),
|
||||
const [metaRes, civRes] = await Promise.all([
|
||||
fetch("/api/wfm/models/metadata"),
|
||||
fetch("/api/wfm/models/civitai/cache"),
|
||||
]);
|
||||
const groups = grpRes.ok ? await grpRes.json() : {};
|
||||
stackModels = groups["Stack"] || [];
|
||||
metadata = metaRes.ok ? await metaRes.json() : {};
|
||||
civitaiCache = civRes.ok ? await civRes.json() : {};
|
||||
} catch { /* ignore */ }
|
||||
|
||||
stackModels.forEach((m) => {
|
||||
if (!_stackStrengths[m]) _stackStrengths[m] = { m: 1.0, c: 1.0 };
|
||||
if (_stackActive[m] === undefined) _stackActive[m] = true;
|
||||
});
|
||||
if (stackModeChecked) {
|
||||
try {
|
||||
const grpRes = await fetch("/api/wfm/models/groups?type=lora");
|
||||
const groups = grpRes.ok ? await grpRes.json() : {};
|
||||
stackModels = groups["Stack"] || [];
|
||||
} catch { /* ignore */ }
|
||||
stackModels.forEach((m) => {
|
||||
if (!_stackStrengths[m]) _stackStrengths[m] = { m: 1.0, c: 1.0 };
|
||||
if (_stackActive[m] === undefined) _stackActive[m] = true;
|
||||
});
|
||||
} else if (useWorkflowLoraState) {
|
||||
const wfNode = comfyUI.currentWorkflow?.[defaultStackTarget];
|
||||
const wfLoras = wfNode?.inputs?.loras?.__value__;
|
||||
// resetStackMode(新規読み込み)/syncFromWorkflow(チェックボックスOFF切替直後)の時だけ
|
||||
// ワークフローの実データで強制上書きする。タブ切替等の単なる再描画では、
|
||||
// 既にメモリ上に値があればそれを維持し、Stackパネルでの一時的なON/OFF・強度編集を
|
||||
// 再描画のたびに消してしまわないようにする。
|
||||
const shouldSync = opts.resetStackMode || opts.syncFromWorkflow;
|
||||
if (Array.isArray(wfLoras)) {
|
||||
stackModels = wfLoras.map((l) => {
|
||||
const found = (this.models.loras || []).find((m) => _loraBasename(m) === l.name);
|
||||
const full = found || l.name;
|
||||
if (shouldSync || _stackStrengths[full] === undefined) {
|
||||
_stackStrengths[full] = { m: parseFloat(l.strength) || 1.0, c: parseFloat(l.clipStrength ?? l.strength) || 1.0 };
|
||||
}
|
||||
if (shouldSync || _stackActive[full] === undefined) {
|
||||
_stackActive[full] = l.active !== false;
|
||||
}
|
||||
return full;
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
// Build Stack trigger words
|
||||
const activeTriggerWords = [];
|
||||
@@ -678,7 +857,9 @@ export const comfyEditor = {
|
||||
? activeTriggerWords.map((w) => `<span class="wfm-lora-trigger-word">${w}</span>`).join(" ")
|
||||
: `<span style="color:var(--wfm-text-secondary);font-size:12px;">—</span>`;
|
||||
const stackLoraSyntax = _buildLoraSyntax(stackModels);
|
||||
const allActive = stackModels.every((m) => _stackActive[m] !== false);
|
||||
// stackModelsが空だと every() が空配列に対し true を返す(空虚な真)ため、
|
||||
// 何も無いのに「トグルオール」チェックボックスがON表示になるのを防ぐ
|
||||
const allActive = stackModels.length > 0 && stackModels.every((m) => _stackActive[m] !== false);
|
||||
const anyActive = stackModels.some((m) => _stackActive[m] !== false);
|
||||
|
||||
const stackModelRows = stackModels.map((m) => {
|
||||
@@ -696,7 +877,10 @@ export const comfyEditor = {
|
||||
</div>`;
|
||||
}).join("");
|
||||
|
||||
const _prevActiveTab = el.querySelector(".wfm-lora-tab-btn.active")?.dataset?.tab || "single";
|
||||
let _prevActiveTab = el.querySelector(".wfm-lora-tab-btn.active")?.dataset?.tab || "single";
|
||||
// 新規読み込み時、LoraManagerノードに実際に複数LoRAが設定されている場合は
|
||||
// Single(1件しか表示できない)ではなくStackタブを初期表示にする
|
||||
if (opts.resetStackMode && useWorkflowLoraState && stackModels.length > 1) _prevActiveTab = "stack";
|
||||
// applyToGenUIで設定したSingle表示の状態を保存(再描画後に復元)
|
||||
const _prevSingleSyntax = document.getElementById("wfm-lora-single-syntax")?.textContent || "";
|
||||
const _prevSingleTriggers = document.getElementById("wfm-lora-single-triggers")?.innerHTML || "";
|
||||
@@ -705,6 +889,11 @@ export const comfyEditor = {
|
||||
<div class="wfm-lora-tab-header">
|
||||
<button class="wfm-lora-tab-btn active" data-tab="single">Single</button>
|
||||
<button class="wfm-lora-tab-btn" data-tab="stack">Stack</button>
|
||||
${hasLoraManager ? `
|
||||
<label class="wfm-lora-stack-mode-label" style="margin-left:auto;display:flex;align-items:center;gap:4px;font-size:12px;white-space:nowrap;" title="ON: 登録済みStackグループを読み込む / OFF: ワークフローに実際に設定されているLoRAを表示・編集する">
|
||||
<input type="checkbox" id="wfm-lora-stack-mode-toggle" ${stackModeChecked ? "checked" : ""}>
|
||||
Use Stack Group
|
||||
</label>` : ""}
|
||||
</div>
|
||||
|
||||
<!-- Single tab -->
|
||||
@@ -739,6 +928,7 @@ export const comfyEditor = {
|
||||
|
||||
<!-- Stack tab -->
|
||||
<div class="wfm-lora-tab-content" id="wfm-lora-panel-stack" style="display:none;">
|
||||
${hasLoraManager ? `<div style="font-size:11px;color:var(--wfm-text-secondary);margin-bottom:6px;">${useWorkflowLoraState ? "Showing: LoRAs currently in workflow" : "Showing: registered Stack group"}</div>` : ""}
|
||||
<div class="wfm-lora-stack-header">
|
||||
<select class="wfm-select" id="wfm-lora-stack-target" style="flex:1;min-width:0;">${stackTargetOpts}</select>
|
||||
<button class="wfm-btn wfm-btn-sm" id="wfm-lora-stack-apply" title="Apply Stack to node and sync to Positive prompt">Apply</button>
|
||||
@@ -773,7 +963,7 @@ export const comfyEditor = {
|
||||
<div id="wfm-lora-stack-triggers" class="wfm-lora-stack-triggers">${stackTriggerHtml}</div>
|
||||
</div>
|
||||
<div class="wfm-lora-stack-models">
|
||||
${stackModelRows || `<p class="wfm-placeholder">No models in Stack group</p>`}
|
||||
${stackModelRows || `<p class="wfm-placeholder">${useWorkflowLoraState ? "No LoRAs set on this node" : "No models in Stack group"}</p>`}
|
||||
</div>
|
||||
</div>
|
||||
`;
|
||||
@@ -811,6 +1001,59 @@ export const comfyEditor = {
|
||||
document.getElementById("wfm-lora-panel-stack").style.display = "";
|
||||
}
|
||||
|
||||
// ── Stackグループ使用チェックボックス ─────────────────
|
||||
// ON: LoraManagerノードへStackグループを(クリアしてから)読み込む(既存のStack Applyを流用)
|
||||
// OFF: ワークフロー読み込み時点のloras/text状態へ(クリアしてから)戻す
|
||||
document.getElementById("wfm-lora-stack-mode-toggle")?.addEventListener("change", async (e) => {
|
||||
const nodeId = document.getElementById("wfm-lora-stack-target")?.value || defaultStackTarget;
|
||||
if (!nodeId || !comfyUI.currentWorkflow?.[nodeId]) return;
|
||||
|
||||
if (e.target.checked) {
|
||||
// stackModelsはこの時点では「ワークフロー state」を指したままのため、
|
||||
// 先に再描画してStackグループを取得させてからApplyする
|
||||
await this.renderLoraPane(analysis, containerId);
|
||||
document.getElementById("wfm-lora-stack-apply")?.click();
|
||||
return;
|
||||
}
|
||||
|
||||
const snap = comfyUI.loraManagerSnapshots?.[nodeId] || { loras: [], text: "" };
|
||||
comfyUI.currentWorkflow[nodeId].inputs.loras = { __value__: JSON.parse(JSON.stringify(snap.loras)) };
|
||||
comfyUI.currentWorkflow[nodeId].inputs.text = snap.text;
|
||||
_syncRawJson();
|
||||
|
||||
// ON時にPositiveプロンプトへ挿入されたStack由来の<lora:...>構文とトリガーワードを除去する
|
||||
// (新規に追加はしない。ワークフロー本来のプロンプトへ戻すだけ)
|
||||
const posTextarea = document.getElementById("wfm-prompt-pos-text");
|
||||
if (posTextarea && stackModels.length > 0) {
|
||||
let cleaned = posTextarea.value;
|
||||
for (const m of stackModels) {
|
||||
const stem = _loraBasename(m).replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
|
||||
cleaned = cleaned.replace(new RegExp(`,?\\s*<lora:${stem}:[^>]*>`, "gi"), "");
|
||||
}
|
||||
const stackWords = new Set();
|
||||
stackModels.forEach((m) => {
|
||||
const sha = (metadata[m] || {}).sha256;
|
||||
const civInfo = sha && civitaiCache[sha];
|
||||
civInfo?.trainedWords?.forEach((w) => stackWords.add(w.trim().toLowerCase()));
|
||||
});
|
||||
if (stackWords.size > 0) {
|
||||
cleaned = cleaned.split(",").map((p) => p.trim()).filter((p) => p && !stackWords.has(p.toLowerCase())).join(", ");
|
||||
}
|
||||
posTextarea.value = cleaned.replace(/,\s*$/, "").trim();
|
||||
|
||||
const posNodeId = document.getElementById("wfm-prompt-pos-target")?.value;
|
||||
if (posNodeId && comfyUI.currentWorkflow?.[posNodeId]) {
|
||||
const promptNode = comfyUI.currentAnalysis?.prompt_nodes?.find((n) => String(n.id) === String(posNodeId));
|
||||
comfyUI.currentWorkflow[posNodeId].inputs[promptNode?.textKey || "text"] = posTextarea.value;
|
||||
_syncRawJson();
|
||||
}
|
||||
}
|
||||
|
||||
// syncFromWorkflow: OFFへ戻した直後は、たった今書き戻したloras/text状態と
|
||||
// Stackパネルの強度/有効状態表示を一致させるため強制同期する
|
||||
this.renderLoraPane(analysis, containerId, { syncFromWorkflow: true });
|
||||
});
|
||||
|
||||
// ── Single: filter ───────────────────────────────────
|
||||
const loraFilterInput = document.getElementById("wfm-lora-filter");
|
||||
const rebuildLoraSingleList = () => {
|
||||
@@ -1249,8 +1492,34 @@ export const comfyEditor = {
|
||||
const slots = loadNodes.slice(0, 4);
|
||||
// Mask Editor One ノード(画像+マスクを内包、常に両方必須)— 別枠で最大2件表示
|
||||
const meoSlots = meoNodes.slice(0, 2);
|
||||
const phCfg = _loadI2IPlaceholderConfig();
|
||||
const isColorMode = phCfg.mode !== "image";
|
||||
el.innerHTML = `
|
||||
${slots.length === 0 ? "" : `
|
||||
<details class="wfm-settings-section wfm-i2i-placeholder-config">
|
||||
<summary class="wfm-settings-summary">${t("i2iPlaceholderTitle")}</summary>
|
||||
<div class="wfm-i2i-placeholder-mode">
|
||||
<label><input type="radio" name="wfm-i2i-ph-mode" id="wfm-i2i-ph-mode-color" value="color" ${isColorMode ? "checked" : ""}> ${t("i2iPlaceholderColor")}</label>
|
||||
<label><input type="radio" name="wfm-i2i-ph-mode" id="wfm-i2i-ph-mode-image" value="image" ${isColorMode ? "" : "checked"}> ${t("i2iPlaceholderImage")}</label>
|
||||
</div>
|
||||
<div id="wfm-i2i-ph-color-fields" class="wfm-i2i-placeholder-fields wfm-lab-modal-inline" style="${isColorMode ? "" : "display:none;"}">
|
||||
<div><label>${t("i2iPlaceholderWidth")}</label><input type="number" min="1" id="wfm-i2i-ph-width" class="wfm-input" value="${Number(phCfg.width) || 512}"></div>
|
||||
<div><label>${t("i2iPlaceholderHeight")}</label><input type="number" min="1" id="wfm-i2i-ph-height" class="wfm-input" value="${Number(phCfg.height) || 512}"></div>
|
||||
<div><label>${t("i2iPlaceholderColorLabel")}</label><input type="color" id="wfm-i2i-ph-color" class="wfm-input" value="${escapeHtml(/^#[0-9a-fA-F]{6}$/.test(phCfg.color) ? phCfg.color : "#808080")}"></div>
|
||||
</div>
|
||||
<div id="wfm-i2i-ph-image-fields" class="wfm-i2i-placeholder-fields" style="${isColorMode ? "display:none;" : ""}">
|
||||
<div class="wfm-i2i-preview-wrap" id="wfm-i2i-ph-preview-wrap" style="${phCfg.imageFilename ? "" : "display:none;"}">
|
||||
<img class="wfm-i2i-preview-img" id="wfm-i2i-ph-preview-img" src="${phCfg.imageFilename ? `/view?filename=${encodeURIComponent(phCfg.imageFilename)}&type=input` : ""}">
|
||||
</div>
|
||||
<div class="wfm-i2i-drop-zone" id="wfm-i2i-ph-drop">
|
||||
<label class="wfm-i2i-drop-label">
|
||||
${t("i2iPlaceholderDropImage")}
|
||||
<input type="file" accept="image/*" id="wfm-i2i-ph-file" style="display:none;">
|
||||
</label>
|
||||
</div>
|
||||
<span class="wfm-i2i-status" id="wfm-i2i-ph-status"></span>
|
||||
</div>
|
||||
</details>
|
||||
<div class="wfm-i2i-grid">
|
||||
${slots.map((node, i) => `
|
||||
<div class="wfm-i2i-slot" data-slot="${i}" data-node-id="${node.id}">
|
||||
@@ -1284,8 +1553,10 @@ export const comfyEditor = {
|
||||
</div>
|
||||
</div>
|
||||
` : ""}
|
||||
<div style="display:flex;gap:6px;margin-top:6px;">
|
||||
<div style="display:flex;gap:6px;margin-top:6px;flex-wrap:wrap;">
|
||||
<button class="wfm-btn wfm-btn-sm wfm-btn-primary wfm-i2i-apply" data-slot="${i}" disabled>Apply</button>
|
||||
<button type="button" class="wfm-btn wfm-btn-sm wfm-i2i-placeholder-btn" data-slot="${i}">${t("i2iPlaceholderApply")}</button>
|
||||
<button type="button" class="wfm-btn wfm-btn-sm wfm-i2i-clear" data-slot="${i}">${t("clear")}</button>
|
||||
<span class="wfm-i2i-status" id="wfm-i2i-status-${i}"></span>
|
||||
</div>
|
||||
</div>
|
||||
@@ -1446,8 +1717,64 @@ export const comfyEditor = {
|
||||
applyBtn.disabled = false;
|
||||
}
|
||||
});
|
||||
|
||||
// Clear: reset this slot's staged/preview state back to empty. Doesn't touch
|
||||
// the workflow node itself — LoadImage always needs *some* valid filename, so
|
||||
// there's nothing meaningful to "unset" there; this just lets the user cancel
|
||||
// a pending pick and start over.
|
||||
const clearBtn = el.querySelector(`.wfm-i2i-clear[data-slot="${i}"]`);
|
||||
clearBtn?.addEventListener("click", () => {
|
||||
pendingFile = null;
|
||||
previewImg.src = "";
|
||||
previewWrap.style.display = "none";
|
||||
filenameEl.textContent = "";
|
||||
if (fileInput) fileInput.value = "";
|
||||
applyBtn.disabled = !pendingMaskFile;
|
||||
statusEl.textContent = "";
|
||||
});
|
||||
|
||||
// Placeholder: generate (color mode) or reuse (image mode) the shared default
|
||||
// configured at the top of the panel, and replace this slot's image
|
||||
// immediately — no separate Apply click needed, matching the "one button,
|
||||
// one slot" behavior described for this feature.
|
||||
const placeholderBtn = el.querySelector(`.wfm-i2i-placeholder-btn[data-slot="${i}"]`);
|
||||
placeholderBtn?.addEventListener("click", async () => {
|
||||
const cfg = _loadI2IPlaceholderConfig();
|
||||
placeholderBtn.disabled = true;
|
||||
statusEl.textContent = t("i2iPlaceholderGenerating");
|
||||
try {
|
||||
let filename;
|
||||
if (cfg.mode === "image") {
|
||||
if (!cfg.imageFilename) throw new Error(t("i2iPlaceholderNoDefaultImage"));
|
||||
filename = cfg.imageFilename;
|
||||
} else {
|
||||
const file = await _generateColorImageFile(cfg.width, cfg.height, cfg.color);
|
||||
const result = await comfyUI.uploadImage(file, file.name);
|
||||
if (!result.name) throw new Error("Upload returned no filename");
|
||||
filename = result.name;
|
||||
}
|
||||
if (comfyUI.currentWorkflow?.[node.id]) {
|
||||
comfyUI.currentWorkflow[node.id].inputs.image = filename;
|
||||
}
|
||||
pendingFile = null;
|
||||
previewImg.src = `/view?filename=${encodeURIComponent(filename)}&type=input`;
|
||||
previewWrap.style.display = "";
|
||||
filenameEl.textContent = filename;
|
||||
applyBtn.disabled = !pendingMaskFile;
|
||||
statusEl.textContent = `✓ ${filename}`;
|
||||
statusEl.style.color = "var(--wfm-success)";
|
||||
_syncRawJson();
|
||||
} catch (err) {
|
||||
statusEl.textContent = `✗ ${err.message}`;
|
||||
statusEl.style.color = "var(--wfm-danger)";
|
||||
} finally {
|
||||
placeholderBtn.disabled = false;
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
_wireI2IPlaceholderConfig(el);
|
||||
|
||||
// Initialize each Mask Editor One slot(画像+マスク両方が揃って初めてApply可能)
|
||||
meoSlots.forEach((node, i) => {
|
||||
const fileInput = document.getElementById(`wfm-meo-file-${i}`);
|
||||
@@ -1789,7 +2116,7 @@ async function _initTextEncoderSection(analysis, textEncoders, containerEl) {
|
||||
const deviceOpts = ["default", "cpu"].map(d => `<option value="${d}" ${d === currentDevice ? "selected" : ""}>${d}</option>`).join("");
|
||||
|
||||
section.innerHTML = `
|
||||
<label>Text Encoder</label>
|
||||
<label class="wfm-model-label-active">Text Encoder</label>
|
||||
<input type="text" class="wfm-input" id="wfm-te-filter" placeholder="Filter..." style="margin-bottom:4px;">
|
||||
<select class="wfm-select" id="wfm-te-clip1" style="margin-bottom:4px;">${clip1Opts}</select>
|
||||
${isDual ? `<select class="wfm-select" id="wfm-te-clip2" style="margin-bottom:4px;">${clip2Opts}</select>` : ""}
|
||||
|
||||
@@ -85,6 +85,9 @@ function _getWidgetInputNames(objectInfo, classType) {
|
||||
// Required inputs: skip types that are linked (have uppercase first letter = node output types)
|
||||
for (const [name, spec] of Object.entries(required)) {
|
||||
const type = Array.isArray(spec) ? spec[0] : spec;
|
||||
// forceInput: true — link-only socket even though its type is a widget type
|
||||
// (e.g. CLIPTextEncodeEditPlus's text1/text2). Never has a widgets_values entry.
|
||||
if (Array.isArray(spec) && spec[1]?.forceInput) continue;
|
||||
// Link types are strings like "MODEL", "CLIP", "CONDITIONING", "LATENT", "IMAGE", etc.
|
||||
// Widget types are: "INT", "FLOAT", "STRING", "BOOLEAN", or an array of choices
|
||||
if (Array.isArray(type)) {
|
||||
@@ -102,6 +105,7 @@ function _getWidgetInputNames(objectInfo, classType) {
|
||||
// Optional inputs that are widgets
|
||||
for (const [name, spec] of Object.entries(optional)) {
|
||||
const type = Array.isArray(spec) ? spec[0] : spec;
|
||||
if (Array.isArray(spec) && spec[1]?.forceInput) continue;
|
||||
if (Array.isArray(type)) {
|
||||
names.push(name);
|
||||
} else if (typeof type === "string") {
|
||||
@@ -128,6 +132,7 @@ function _getWidgetInputTypes(objectInfo, classType) {
|
||||
|
||||
for (const [name, spec] of Object.entries(required)) {
|
||||
const type = Array.isArray(spec) ? spec[0] : spec;
|
||||
if (Array.isArray(spec) && spec[1]?.forceInput) continue;
|
||||
if (Array.isArray(type)) {
|
||||
types.push("COMBO");
|
||||
} else if (typeof type === "string") {
|
||||
@@ -139,6 +144,7 @@ function _getWidgetInputTypes(objectInfo, classType) {
|
||||
}
|
||||
for (const [name, spec] of Object.entries(optional)) {
|
||||
const type = Array.isArray(spec) ? spec[0] : spec;
|
||||
if (Array.isArray(spec) && spec[1]?.forceInput) continue;
|
||||
if (Array.isArray(type)) {
|
||||
types.push("COMBO");
|
||||
} else if (typeof type === "string") {
|
||||
@@ -154,6 +160,13 @@ function _getWidgetInputTypes(objectInfo, classType) {
|
||||
/**
|
||||
* Resolve the sub-input names for a DynamicCombo's currently-selected option.
|
||||
* objectInfo spec shape: ["COMFY_DYNAMICCOMBO_V3", { options: [{ key, inputs: { required: {...} } }, ...] }]
|
||||
*
|
||||
* Includes both required AND optional sub-fields: ComfyUI serializes every sub-field of the
|
||||
* selected option into widgets_values regardless of which bucket it's declared in (e.g.
|
||||
* TextGenerate's "on" option puts temperature/top_k/.../seed under required but
|
||||
* presence_penalty under optional — all 7 still occupy a widgets_values slot). Dropping the
|
||||
* optional ones here under-counts how many slots the combo actually consumed, misaligning
|
||||
* every widget declared after it in the node's schema.
|
||||
*/
|
||||
function _getDynamicComboSubNames(objectInfo, classType, widgetName, selectedKey) {
|
||||
const info = objectInfo[classType];
|
||||
@@ -161,7 +174,10 @@ function _getDynamicComboSubNames(objectInfo, classType, widgetName, selectedKey
|
||||
const options = spec?.[1]?.options;
|
||||
if (!Array.isArray(options)) return [];
|
||||
const opt = options.find((o) => o.key === selectedKey) || options[0];
|
||||
return Object.keys(opt?.inputs?.required || {});
|
||||
return [
|
||||
...Object.keys(opt?.inputs?.required || {}),
|
||||
...Object.keys(opt?.inputs?.optional || {}),
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -215,8 +231,15 @@ function _isLinkedWidgetName(remappedNode, sgDef, origInternalId, redirectedTarg
|
||||
* `continue`s before ever looking at the extra, leaving it unconsumed and silently misread as the
|
||||
* value of whatever non-linked widget comes after. Stripping a linked widget's position alone
|
||||
* (without its swallowed extra) reproduces exactly that bug one level up, in the injection step.
|
||||
*
|
||||
* comboExpander(name, selectedKey) — when a widget's type is COMFY_DYNAMICCOMBO_V3, its own turn
|
||||
* only consumes the *selector* slot (the chosen option's key); the selected option's sub-fields
|
||||
* (e.g. TextGenerate's sampling_mode → temperature/top_k/.../seed/presence_penalty) each occupy
|
||||
* one more widgets_values slot right after it. Without expanding those here too, every widget
|
||||
* declared later in the node's schema (e.g. TextGenerate's "thinking") gets matched against a
|
||||
* slot that's actually still inside the combo's sub-field span, corrupting both values.
|
||||
*/
|
||||
function _simulateWidgetValues(widgetNames, widgetTypes, widgetsValues, isLinkedName, skipLinked) {
|
||||
function _simulateWidgetValues(widgetNames, widgetTypes, widgetsValues, isLinkedName, skipLinked, comboExpander) {
|
||||
let idx = 0;
|
||||
const positions = {};
|
||||
const consumedIndices = {};
|
||||
@@ -240,6 +263,13 @@ function _simulateWidgetValues(widgetNames, widgetTypes, widgetsValues, isLinked
|
||||
p = idx;
|
||||
idx++;
|
||||
}
|
||||
if (widgetTypes[nIdx] === "COMFY_DYNAMICCOMBO_V3" && comboExpander) {
|
||||
const subNames = comboExpander(name, widgetsValues[p]);
|
||||
for (let s = 0; s < subNames.length && idx < widgetsValues.length; s++) {
|
||||
consumed.push(idx);
|
||||
idx++;
|
||||
}
|
||||
}
|
||||
positions[name] = p;
|
||||
consumedIndices[name] = consumed;
|
||||
}
|
||||
@@ -262,16 +292,17 @@ function _stripLegacyLinkedWidgetValues(objectInfo, remappedNode, sgDef, origInt
|
||||
const widgetNames = _getWidgetInputNames(objectInfo, remappedNode.type);
|
||||
const widgetTypes = _getWidgetInputTypes(objectInfo, remappedNode.type);
|
||||
const isLinkedName = (name) => _isLinkedWidgetName(remappedNode, sgDef, origInternalId, redirectedTargets, name);
|
||||
const comboExpander = (name, selectedKey) => _getDynamicComboSubNames(objectInfo, remappedNode.type, name, selectedKey);
|
||||
|
||||
// If skipping linked widgets already accounts for every entry, widgets_values is already in
|
||||
// the modern (no dangling linked entries) format — nothing to strip.
|
||||
const skipSim = _simulateWidgetValues(widgetNames, widgetTypes, widgetsValues, isLinkedName, true);
|
||||
const skipSim = _simulateWidgetValues(widgetNames, widgetTypes, widgetsValues, isLinkedName, true, comboExpander);
|
||||
if (skipSim.consumed === widgetsValues.length) return;
|
||||
|
||||
// Otherwise it's "legacy full": recompute with every widget present to find exactly which
|
||||
// indices the linked ones occupy — including any control_after_generate extra a linked
|
||||
// widget's own turn would have consumed, which must be dropped too (see _simulateWidgetValues).
|
||||
const fullSim = _simulateWidgetValues(widgetNames, widgetTypes, widgetsValues, isLinkedName, false);
|
||||
const fullSim = _simulateWidgetValues(widgetNames, widgetTypes, widgetsValues, isLinkedName, false, comboExpander);
|
||||
const linkedIdx = new Set();
|
||||
for (const name of widgetNames) {
|
||||
if (isLinkedName(name)) {
|
||||
@@ -295,7 +326,8 @@ function _findInjectedWidgetIndex(objectInfo, remappedNode, sgDef, origInternalI
|
||||
const widgetTypes = _getWidgetInputTypes(objectInfo, remappedNode.type);
|
||||
const widgetsValues = remappedNode.widgets_values || [];
|
||||
const isLinkedName = (name) => _isLinkedWidgetName(remappedNode, sgDef, origInternalId, redirectedTargets, name);
|
||||
const sim = _simulateWidgetValues(widgetNames, widgetTypes, widgetsValues, isLinkedName, true);
|
||||
const comboExpander = (name, selectedKey) => _getDynamicComboSubNames(objectInfo, remappedNode.type, name, selectedKey);
|
||||
const sim = _simulateWidgetValues(widgetNames, widgetTypes, widgetsValues, isLinkedName, true, comboExpander);
|
||||
return sim.positions[targetName] ?? -1;
|
||||
}
|
||||
|
||||
@@ -1020,6 +1052,37 @@ export const comfyWorkflow = {
|
||||
}
|
||||
}
|
||||
}
|
||||
// TextEncodeQwenImageEditPlus/TextEncodeQwenImageEdit — propagate role through its
|
||||
// linked "prompt" input when prompt-enhancement wiring feeds it via a switch chain
|
||||
// instead of a literal string (e.g. Krea-2's image-reference workflow).
|
||||
if (ct === "TextEncodeQwenImageEditPlus" || ct === "TextEncodeQwenImageEdit") {
|
||||
const tv = inputs.prompt;
|
||||
if (Array.isArray(tv)) {
|
||||
if (isPos) samplerPositiveRef[tv[0]] = true;
|
||||
if (isNeg) samplerNegativeRef[tv[0]] = true;
|
||||
}
|
||||
}
|
||||
// PreviewAny — generic value tap/relay used mid-chain in prompt-enhancement wiring
|
||||
// (e.g. Krea-2's "Refine Prompt?" switch output tap); pass role through its
|
||||
// "source" input unchanged.
|
||||
if (ct === "PreviewAny") {
|
||||
const sv = inputs.source;
|
||||
if (Array.isArray(sv)) {
|
||||
if (isPos) samplerPositiveRef[sv[0]] = true;
|
||||
if (isNeg) samplerNegativeRef[sv[0]] = true;
|
||||
}
|
||||
}
|
||||
// StringConcatenate — appends e.g. a LoRA trigger word onto the prompt text
|
||||
// (Krea-2); propagate role through both operands so the upstream literal is found.
|
||||
if (ct === "StringConcatenate") {
|
||||
for (const key of ["string_a", "string_b"]) {
|
||||
const tv = inputs[key];
|
||||
if (Array.isArray(tv)) {
|
||||
if (isPos) samplerPositiveRef[tv[0]] = true;
|
||||
if (isNeg) samplerNegativeRef[tv[0]] = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1174,13 +1237,17 @@ export const comfyWorkflow = {
|
||||
}
|
||||
|
||||
// Qwen-based image+text encoder (Plus variant takes up to 3 reference images;
|
||||
// the base variant takes one — both share the same "prompt" widget)
|
||||
// the base variant takes one — both share the same "prompt" widget). Only add when
|
||||
// "prompt" is a direct string; if linked (e.g. Krea-2's prompt-enhancement wiring),
|
||||
// the upstream literal node is resolved instead via the role propagation above.
|
||||
if (ct === "TextEncodeQwenImageEditPlus" || ct === "TextEncodeQwenImageEdit") {
|
||||
result.prompt_nodes.push({
|
||||
id, type: ct, title, role: getRole(),
|
||||
text: inputs.prompt || "",
|
||||
textKey: "prompt",
|
||||
});
|
||||
const textVal = inputs.prompt;
|
||||
if (typeof textVal === "string") {
|
||||
result.prompt_nodes.push({
|
||||
id, type: ct, title, role: getRole(),
|
||||
text: textVal, textKey: "prompt",
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
// TextEncodeBooguEdit (Boogu image-edit model) — prompt + negative_prompt in one node
|
||||
|
||||
@@ -12,6 +12,8 @@ import { comfyWorkflow } from "./comfyui-workflow.js";
|
||||
import { comfyUI } from "./comfyui-client.js";
|
||||
import { comfyEditor } from "./comfyui-editor.js";
|
||||
import { callLLM, loadAiSettings, isValidBackendUrl } from "./ai-tab.js";
|
||||
import { initImagePromptTab, activateImagePromptTab } from "./image-prompt-tab.js";
|
||||
import { initStyleCatalogTab, activateStyleCatalogTab } from "./style-catalog-tab.js";
|
||||
|
||||
// ── 定数 ─────────────────────────────────────────────────────
|
||||
|
||||
@@ -401,7 +403,7 @@ function renderTreeNode(node, container, depth, isRoot) {
|
||||
// フォルダ名
|
||||
const label = document.createElement("span");
|
||||
label.className = "wfm-gallery-tree-label";
|
||||
label.textContent = isRoot ? `[root] ${node.name}` : node.name;
|
||||
label.textContent = isRoot ? "[root]" : node.name;
|
||||
if (node.image_count > 0) {
|
||||
const badge = document.createElement("span");
|
||||
badge.className = "wfm-gallery-tree-count";
|
||||
@@ -911,15 +913,29 @@ async function loadImageDetail(img) {
|
||||
state.embeddedWorkflow = wfRes.has_workflow ? wfRes.workflow : null;
|
||||
renderWorkflowJson(state.embeddedWorkflow);
|
||||
_updateCopyCanvasBtn();
|
||||
renderImagePromptSection(metaRes.image_prompt);
|
||||
} catch (e) {
|
||||
renderWorkflowJson(null);
|
||||
_updateCopyCanvasBtn();
|
||||
renderImagePromptSection(null);
|
||||
}
|
||||
|
||||
// グループタブ更新
|
||||
renderDetailGroup(img);
|
||||
}
|
||||
|
||||
function renderImagePromptSection(imagePrompt) {
|
||||
const section = document.getElementById("wfm-gallery-image-prompt-section");
|
||||
const text = document.getElementById("wfm-gallery-image-prompt-text");
|
||||
if (!section || !text) return;
|
||||
if (imagePrompt) {
|
||||
text.textContent = imagePrompt;
|
||||
section.style.display = "";
|
||||
} else {
|
||||
section.style.display = "none";
|
||||
}
|
||||
}
|
||||
|
||||
function renderTagsDisplay(tags) {
|
||||
const container = document.getElementById("wfm-gallery-tags-display");
|
||||
container.innerHTML = "";
|
||||
@@ -1606,6 +1622,9 @@ export function initGalleryTab() {
|
||||
}
|
||||
|
||||
bindEvents();
|
||||
_initGallerySubtabToggle();
|
||||
initImagePromptTab();
|
||||
initStyleCatalogTab();
|
||||
}
|
||||
|
||||
let _initialized = false;
|
||||
@@ -1617,6 +1636,23 @@ function onGalleryTabActivated() {
|
||||
loadGroups();
|
||||
}
|
||||
|
||||
// ── サブタブ切替 (Output / ImagePrompt / Style_Catalog) ────────────────────────
|
||||
|
||||
function _initGallerySubtabToggle() {
|
||||
document.querySelectorAll(".wfm-gallery-subtab-btn").forEach((btn) => {
|
||||
btn.addEventListener("click", () => {
|
||||
const target = btn.dataset.gallerySubtab;
|
||||
document.querySelectorAll(".wfm-gallery-subtab-btn").forEach((b) => b.classList.remove("active"));
|
||||
btn.classList.add("active");
|
||||
document.getElementById("wfm-gallery-panel-output")?.classList.toggle("active", target === "output");
|
||||
document.getElementById("wfm-gallery-panel-imageprompt")?.classList.toggle("active", target === "imageprompt");
|
||||
document.getElementById("wfm-gallery-panel-styleCatalog")?.classList.toggle("active", target === "styleCatalog");
|
||||
if (target === "imageprompt") activateImagePromptTab();
|
||||
if (target === "styleCatalog") activateStyleCatalogTab();
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
function bindEvents() {
|
||||
// リフレッシュ
|
||||
document.getElementById("wfm-gallery-refresh-btn")?.addEventListener("click", () => {
|
||||
|
||||
+205
-5
@@ -9,7 +9,7 @@ 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 { initLabTab } from "./lab-tab.js";
|
||||
import { initLabTab, refreshLabLiveDefaults } from "./lab-tab.js";
|
||||
import { getSettings, readJsonStorage, escapeHtml, getEagleSettings, saveToEagle } from "./util.js";
|
||||
|
||||
// ============================================
|
||||
@@ -231,7 +231,9 @@ export async function loadWorkflowIntoEditor(workflow, filename) {
|
||||
comfyUI.currentAnalysis = comfyWorkflow.analyzeWorkflow(apiWorkflow);
|
||||
|
||||
// Render editor tabs
|
||||
comfyEditor.renderAll(comfyUI.currentAnalysis, apiWorkflow);
|
||||
// resetStackMode: 新規ワークフロー読み込み時のみ、LoraManagerノードのloras/text状態を
|
||||
// スナップショットし、Stackグループ使用チェックボックスをOFFへリセットする
|
||||
comfyEditor.renderAll(comfyUI.currentAnalysis, apiWorkflow, { resetStackMode: true });
|
||||
|
||||
// Update raw JSON with highlight
|
||||
const rawTextarea = document.getElementById("wfm-gen-raw-json");
|
||||
@@ -1263,6 +1265,12 @@ async function _loadStyles() {
|
||||
_rebuildStyleList();
|
||||
}
|
||||
|
||||
// Promptタブ「Style」サブタブでスタイルを作成・編集・削除した後に呼ばれる。
|
||||
// GenerateUIのStyleドロップダウン・Batchタブのチェックリストを最新の状態へ再同期する。
|
||||
export async function refreshStylesList() {
|
||||
await _loadStyles();
|
||||
}
|
||||
|
||||
function _renderStyleDropdown() {
|
||||
const sel = document.getElementById("wfm-style-select");
|
||||
if (!sel) return;
|
||||
@@ -1291,6 +1299,21 @@ function _rebuildStyleList() {
|
||||
);
|
||||
}
|
||||
|
||||
// Style Catalogギャラリーの「Select as Style」から呼ばれる。名前が一致する登録済み
|
||||
// Styleを探し、GenerateUIのStyleドロップダウンをそれに切り替えてタブへ移動する。
|
||||
// 画像に埋め込まれたプロンプトを直接適用するのではなく、既存Styleシステムへの
|
||||
// 視覚的なショートカットとして機能する(元のStyle JSONが変更・削除されても影響を受けない)。
|
||||
export function selectStyleByName(name) {
|
||||
const style = _stylesData.find((s) => s.name === name);
|
||||
if (!style) return false;
|
||||
const sel = document.getElementById("wfm-style-select");
|
||||
if (sel) sel.value = name;
|
||||
const enabled = document.getElementById("wfm-style-enabled");
|
||||
if (enabled) enabled.checked = true;
|
||||
document.querySelector('.wfm-tab[data-tab="generate"]')?.click();
|
||||
return true;
|
||||
}
|
||||
|
||||
function _applyNamedStyle(workflow, style) {
|
||||
if (!style) return workflow;
|
||||
const analysis = comfyUI.currentAnalysis;
|
||||
@@ -1391,7 +1414,7 @@ async function _expandWildcardText(text) {
|
||||
|
||||
const _IMPACT_WC_TYPES = new Set(["ImpactWildcardEncode", "ImpactWildcardProcessor"]);
|
||||
|
||||
async function _expandWildcardsInWorkflow(workflow) {
|
||||
export async function _expandWildcardsInWorkflow(workflow) {
|
||||
let hasWildcard = false;
|
||||
outer: for (const node of Object.values(workflow)) {
|
||||
if (_IMPACT_WC_TYPES.has(node.class_type)) continue;
|
||||
@@ -1539,7 +1562,9 @@ async function _coreGenerate(silent = false, workflowOverride = null) {
|
||||
// ============================================
|
||||
|
||||
// 汎用バッチループ: items を順に applyFn(item) → _coreGenerate() で処理する
|
||||
async function _runBatchLoop(items, applyFn, labelFn = (x) => String(x)) {
|
||||
// onResultFn(item, {images, seed}) が渡された場合、各アイテムの生成結果ごとに呼び出す
|
||||
// (Style Catalogのカタログ作成が、生成画像をスタイル名で保存するために使用)
|
||||
async function _runBatchLoop(items, applyFn, labelFn = (x) => String(x), onResultFn = null) {
|
||||
const batchProgress = document.getElementById("wfm-ckpt-batch-progress");
|
||||
const batchCurrentName = document.getElementById("wfm-ckpt-batch-current-name");
|
||||
const batchCount = document.getElementById("wfm-ckpt-batch-count");
|
||||
@@ -1574,7 +1599,8 @@ async function _runBatchLoop(items, applyFn, labelFn = (x) => String(x)) {
|
||||
|
||||
try {
|
||||
await applyFn(item);
|
||||
await _coreGenerate(true);
|
||||
const result = await _coreGenerate(true);
|
||||
if (onResultFn) await onResultFn(item, result);
|
||||
completed++;
|
||||
} catch (err) {
|
||||
if (_ckptBatch.aborted) break;
|
||||
@@ -1603,6 +1629,157 @@ async function _runBatchLoop(items, applyFn, labelFn = (x) => String(x)) {
|
||||
}
|
||||
}
|
||||
|
||||
// ============================================
|
||||
// Style Catalog 作成
|
||||
// ============================================
|
||||
// Batchタブ「Style」サブタブで選択済みのスタイル(_batchStyleSelected)を対象に、
|
||||
// 現在ロード中のワークフローでそれぞれ生成し、結果をスタイル名でws_style_catalog
|
||||
// 配下の指定フォルダへ保存する(Style Catalogギャラリーからの視覚的スタイル選択に使う)。
|
||||
|
||||
function _blobToDataUrl(blob) {
|
||||
return new Promise((resolve, reject) => {
|
||||
const reader = new FileReader();
|
||||
reader.onload = () => resolve(reader.result);
|
||||
reader.onerror = reject;
|
||||
reader.readAsDataURL(blob);
|
||||
});
|
||||
}
|
||||
|
||||
function _flattenFolderTree(node, acc = [], isRoot = true) {
|
||||
acc.push({ path: isRoot ? "[root]" : node.path, abs_path: node.abs_path });
|
||||
(node.children || []).forEach((c) => _flattenFolderTree(c, acc, false));
|
||||
return acc;
|
||||
}
|
||||
|
||||
async function openCatalogCreateModal() {
|
||||
const list = _stylesData.filter((s) => _batchStyleSelected.has(s.name));
|
||||
if (list.length === 0) {
|
||||
showToast(t("catalogCreateNoStyles"), "error");
|
||||
return;
|
||||
}
|
||||
|
||||
let catalogRoot = null;
|
||||
let folderTree = null;
|
||||
try {
|
||||
const rootRes = await fetch("/wfm/gallery/style-catalog/root");
|
||||
const rootData = await rootRes.json();
|
||||
catalogRoot = rootData.root;
|
||||
if (!catalogRoot) throw new Error(rootData.error || "Style Catalog root not resolved");
|
||||
const treeRes = await fetch(`/wfm/gallery/folders?root=${encodeURIComponent(catalogRoot)}`);
|
||||
folderTree = await treeRes.json();
|
||||
} catch (e) {
|
||||
showToast(t("errorWithMsg", e.message), "error");
|
||||
return;
|
||||
}
|
||||
|
||||
const folderOptions = folderTree && !folderTree.error ? _flattenFolderTree(folderTree) : [];
|
||||
|
||||
const html = `
|
||||
<p style="margin:0 0 10px;font-size:13px;color:var(--wfm-text-secondary);">${t("catalogCreateSelectedCount", list.length)}</p>
|
||||
<div style="display:flex;flex-direction:column;gap:8px;">
|
||||
<label style="display:flex;align-items:center;gap:6px;">
|
||||
<input type="radio" name="wfm-catalog-dest" value="new" checked>
|
||||
${t("catalogCreateNewFolder")}
|
||||
</label>
|
||||
<input type="text" id="wfm-catalog-new-folder-name" class="wfm-input" placeholder="folder name" style="margin-left:22px;">
|
||||
<label style="display:flex;align-items:center;gap:6px;">
|
||||
<input type="radio" name="wfm-catalog-dest" value="existing" ${folderOptions.length === 0 ? "disabled" : ""}>
|
||||
${t("catalogCreateExistingFolder")}
|
||||
</label>
|
||||
<select id="wfm-catalog-existing-folder" class="wfm-input" style="margin-left:22px;" ${folderOptions.length === 0 ? "disabled" : ""}>
|
||||
${folderOptions.map((f) => `<option value="${escapeHtml(f.abs_path)}">${escapeHtml(f.path)}</option>`).join("")}
|
||||
</select>
|
||||
<hr class="wfm-group-divider" style="margin:4px 0;">
|
||||
<label style="display:flex;align-items:center;gap:6px;">
|
||||
<input type="checkbox" id="wfm-catalog-skip-output">
|
||||
${t("catalogCreateSkipOutput")}
|
||||
</label>
|
||||
</div>
|
||||
<button id="wfm-catalog-run-btn" class="wfm-btn wfm-btn-primary" style="width:100%;margin-top:14px;">${t("catalogCreateRun")}</button>
|
||||
`;
|
||||
openModal(t("catalogCreateTitle"), html);
|
||||
|
||||
document.getElementById("wfm-catalog-run-btn")?.addEventListener("click", async () => {
|
||||
const destType = document.querySelector('input[name="wfm-catalog-dest"]:checked')?.value;
|
||||
let destFolder = null;
|
||||
|
||||
if (destType === "new") {
|
||||
const name = document.getElementById("wfm-catalog-new-folder-name")?.value.trim();
|
||||
if (!name) {
|
||||
showToast(t("catalogCreateFolderNameRequired"), "error");
|
||||
return;
|
||||
}
|
||||
try {
|
||||
const res = await fetch("/wfm/gallery/folder", {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify({ parent: catalogRoot, name }),
|
||||
});
|
||||
const data = await res.json();
|
||||
if (!data.ok) throw new Error(data.error || "Failed to create folder");
|
||||
destFolder = data.path;
|
||||
} catch (e) {
|
||||
showToast(t("errorWithMsg", e.message), "error");
|
||||
return;
|
||||
}
|
||||
} else {
|
||||
destFolder = document.getElementById("wfm-catalog-existing-folder")?.value || null;
|
||||
if (!destFolder) {
|
||||
showToast(t("catalogCreateFolderRequired"), "error");
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
const skipOutput = document.getElementById("wfm-catalog-skip-output")?.checked || false;
|
||||
|
||||
closeModal();
|
||||
await _runCatalogCreate(list, destFolder, skipOutput);
|
||||
});
|
||||
}
|
||||
|
||||
async function _runCatalogCreate(list, destFolder, skipOutput) {
|
||||
try {
|
||||
await _runBatchLoop(
|
||||
list,
|
||||
(style) => { _batchStyleOverride = style; },
|
||||
(s) => s.name,
|
||||
async (style, result) => {
|
||||
const outputImages = (result?.images || []).filter((img) => img.type !== "temp");
|
||||
if (outputImages.length === 0) return;
|
||||
const srcImage = outputImages[0];
|
||||
const blob = await comfyUI.getImageBlob(srcImage);
|
||||
const dataUrl = await _blobToDataUrl(blob);
|
||||
const res = await fetch("/wfm/gallery/image/save-to-folder", {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify({ folder: destFolder, filename: style.name, imageData: dataUrl }),
|
||||
});
|
||||
const data = await res.json();
|
||||
if (!data.ok) throw new Error(data.error || "Failed to save catalog image");
|
||||
|
||||
// Outputフォルダに元画像を残さないオプション: カタログへのコピー保存が
|
||||
// 成功した後にのみ、ComfyUIのOutputフォルダ側の元ファイルを削除する
|
||||
// (コピー失敗時は削除せず、元画像を保持したままにする)
|
||||
if (skipOutput) {
|
||||
try {
|
||||
await fetch("/wfm/gallery/output-image/delete", {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify({
|
||||
filename: srcImage.filename,
|
||||
subfolder: srcImage.subfolder || "",
|
||||
type: srcImage.type || "output",
|
||||
}),
|
||||
});
|
||||
} catch { /* 削除失敗はカタログ作成自体を止めない */ }
|
||||
}
|
||||
}
|
||||
);
|
||||
} finally {
|
||||
_batchStyleOverride = null;
|
||||
}
|
||||
}
|
||||
|
||||
// アクティブなバッチタイプに応じてバッチを実行するディスパッチャ
|
||||
async function _runBatchGenerate() {
|
||||
switch (_activeBatchType) {
|
||||
@@ -1891,6 +2068,25 @@ export async function initGenerateTab() {
|
||||
}
|
||||
});
|
||||
|
||||
// Style Catalog 作成ボタン
|
||||
const catalogCreateBtn = document.getElementById("wfm-gen-catalog-create-btn");
|
||||
if (catalogCreateBtn) {
|
||||
catalogCreateBtn.textContent = t("catalogCreateBtn");
|
||||
catalogCreateBtn.addEventListener("click", () => {
|
||||
openCatalogCreateModal().catch((e) => showToast(t("errorWithMsg", e.message), "error"));
|
||||
});
|
||||
}
|
||||
|
||||
// Style Catalog を開くボタン(Gallery タブ → Style_Catalog サブタブへ遷移)
|
||||
const catalogOpenBtn = document.getElementById("wfm-gen-catalog-open-btn");
|
||||
if (catalogOpenBtn) {
|
||||
catalogOpenBtn.textContent = t("catalogOpenBtn");
|
||||
catalogOpenBtn.addEventListener("click", () => {
|
||||
document.querySelector('.wfm-tab[data-tab="gallery"]')?.click();
|
||||
document.querySelector('.wfm-gallery-subtab-btn[data-gallery-subtab="styleCatalog"]')?.click();
|
||||
});
|
||||
}
|
||||
|
||||
// Generate button
|
||||
document.getElementById("wfm-gen-generate-btn")?.addEventListener("click", () => {
|
||||
handleGenerate().catch(() => {});
|
||||
@@ -1943,6 +2139,10 @@ export async function initGenerateTab() {
|
||||
if (target === "model" && comfyUI.currentAnalysis) {
|
||||
comfyEditor.renderLoraPane(comfyUI.currentAnalysis, "wfm-gen-lora-fields");
|
||||
}
|
||||
// Re-render Lab's column grid so Setting 1's live-reflected cells (checkpoint/
|
||||
// VAE/prompt/KSampler) pick up whatever is currently loaded in GenerateUI, not
|
||||
// whatever was loaded the last time Lab was rendered.
|
||||
if (target === "lab") refreshLabLiveDefaults();
|
||||
// Lab has its own Run/Results panel — hide the shared Generate/Seed/Batch column
|
||||
const rightCol = document.querySelector(".wfm-gen-right");
|
||||
if (rightCol) rightCol.style.display = (target === "lab") ? "none" : "";
|
||||
|
||||
+347
-30
@@ -149,6 +149,7 @@ const LANGUAGES = {
|
||||
saveWorkflowTitle: "Save Workflow",
|
||||
filenameLabel: "Filename",
|
||||
pleaseEnterFilename: "Please enter a filename",
|
||||
pleaseEnterStyleName: "Please enter a style name",
|
||||
saveFailed: (msg) => msg ? `Save failed: ${msg}` : "Save failed",
|
||||
savedAs: (f) => `Saved: ${f}`,
|
||||
overwriteConfirm: (f) => `"${f}" already exists. Overwrite?`,
|
||||
@@ -217,16 +218,30 @@ const LANGUAGES = {
|
||||
batchStopped: (completed, failed) => `Batch stopped — ${completed} completed, ${failed} failed`,
|
||||
batchComplete: (completed, total, failed) => failed > 0 ? `Batch complete: ${completed}/${total} (${failed} failed)` : `Batch complete: ${completed}/${total}`,
|
||||
batchLoraMissing: (count, total, sample) => `${count}/${total} selected LoRAs are not recognized by ComfyUI yet (e.g. ${sample}). Click Refresh in ComfyUI or restart the server, then try again.`,
|
||||
catalogCreateBtn: "Create Catalog",
|
||||
catalogOpenBtn: "Catalog",
|
||||
catalogCreateTitle: "Create Style Catalog",
|
||||
catalogCreateNoStyles: "No styles selected — select styles in the Batch tab's Style sub-tab first",
|
||||
catalogCreateSelectedCount: (n) => `${n} style${n === 1 ? "" : "s"} selected`,
|
||||
catalogCreateNewFolder: "Create new folder",
|
||||
catalogCreateExistingFolder: "Use existing folder",
|
||||
catalogCreateRun: "Run",
|
||||
catalogCreateFolderNameRequired: "Enter a folder name",
|
||||
catalogCreateFolderRequired: "Select a destination folder",
|
||||
catalogCreateSkipOutput: "Don't keep a copy in the Output folder",
|
||||
|
||||
// -- Lab tab --
|
||||
labImageUploaded: (name) => `Image uploaded: ${name}`,
|
||||
labUploadFailed: "Upload failed",
|
||||
labBatchCountTooSmall: "Increase the Batch count first to add a keyframe beyond it",
|
||||
labKeyframesExceedBatch: (maxIter, batchCount) => `Some keyframes are set up to iteration #${maxIter}, beyond the current Batch count (${batchCount}) — they won't be applied until Batch count is raised again`,
|
||||
labUseWorkflowDefault: "(workflow default)",
|
||||
labAppliedAt: (n) => `Applied: ${n}`,
|
||||
labRevertToBase: "↩ back to #1",
|
||||
labApplyFromIteration: "Applies from iteration #",
|
||||
labRevertCheckboxLabel: "Revert to iteration #1's setting",
|
||||
labBypassed: "⏭ Bypassed",
|
||||
labBypassCheckboxLabel: "Bypass this setting (keep whatever was active before it)",
|
||||
labSeedEmptyRandom: "Seed (empty = random)",
|
||||
labPause: "Pause",
|
||||
labResume: "Resume",
|
||||
@@ -243,10 +258,15 @@ const LANGUAGES = {
|
||||
labConfirmClear: "Clear all Lab settings (image, columns, note, results)?",
|
||||
labGetFromGenUI: "Get from GenerateUI",
|
||||
labGetFromImage: "Get from Image",
|
||||
labGetFromPrevious: "Get from Previous",
|
||||
labClearPrompt: "Clear",
|
||||
labPromptCleared: "Prompt cleared",
|
||||
labPromptCopiedFromPrevious: "Copied from the previous setting",
|
||||
labLiveHint: "Showing the current GenerateUI settings. Edit and save to override.",
|
||||
labStyle: "Style",
|
||||
labApply: "Apply",
|
||||
labNoStyles: "No styles",
|
||||
labEnableStyleFirst: "Enable the Style checkbox and pick a style at the top of the GenerateUI tab first",
|
||||
labEnableStyleFirst: "Pick a style in the Style dropdown at the top of the GenerateUI tab first",
|
||||
labPlanJsonRefreshed: "Refreshed from the current Setting tab",
|
||||
labPlanJsonApplied: "Plan JSON applied to Setting",
|
||||
labPlanJsonInvalid: "Invalid JSON",
|
||||
@@ -254,6 +274,24 @@ const LANGUAGES = {
|
||||
labPromptFetched: "Prompt loaded",
|
||||
labNoPromptInImage: "No prompt found in that file",
|
||||
labMetadataExtractFailed: "Failed to read metadata",
|
||||
labConfirmLoadWorkflow: (filename) => `Load "${filename}" into GenerateUI? This replaces the currently loaded workflow.`,
|
||||
labWorkflowLoadFailed: "Failed to load the workflow",
|
||||
labT2IImageIgnored: "T2I mode is on — image upload is not needed and was skipped",
|
||||
labIndexImageSaved: (filename) => `Index image saved to Output: ${filename}`,
|
||||
labIndexImageSaveFailed: "Failed to save the index image to Output",
|
||||
|
||||
// -- GenerateUI Input tab: Image sub-panel placeholder --
|
||||
i2iPlaceholderTitle: "Placeholder Image",
|
||||
i2iPlaceholderColor: "Color",
|
||||
i2iPlaceholderImage: "Image",
|
||||
i2iPlaceholderWidth: "Width",
|
||||
i2iPlaceholderHeight: "Height",
|
||||
i2iPlaceholderColorLabel: "Color",
|
||||
i2iPlaceholderDropImage: "Drop default image or click to select",
|
||||
i2iPlaceholderApply: "Placeholder",
|
||||
i2iPlaceholderGenerating: "Generating...",
|
||||
i2iPlaceholderNoDefaultImage: "No default image set — drop one above first",
|
||||
i2iPlaceholderUploading: "Uploading...",
|
||||
|
||||
connectedToComfyUI: "Connected to ComfyUI",
|
||||
failedToConnect: "Failed to connect",
|
||||
@@ -281,6 +319,9 @@ const LANGUAGES = {
|
||||
jsonColorCyan: "Prompts / Text",
|
||||
jsonColorRed: "Images / Files",
|
||||
jsonColorReset: "Reset to defaults",
|
||||
modelTabColorSection: "GenerateUI Model Tab Highlight",
|
||||
modelTabColorLabel: "Color for items present in the workflow",
|
||||
modelTabColorHint: "In the GenerateUI Model tab, labels for items actually present in the loaded workflow (Checkpoint, VAE, etc.) are shown in this color.",
|
||||
|
||||
// -- Prompt tab --
|
||||
tabPrompt: "Prompt",
|
||||
@@ -520,6 +561,31 @@ const LANGUAGES = {
|
||||
galleryCCNotAvailable: "Open this Gallery from ComfyUI Comic Creator to use Send CC",
|
||||
gallerySentCC: "Sent to ComfyUI Comic Creator",
|
||||
galleryNoEmbeddedWorkflow: "No ComfyUI workflow embedded in this image.",
|
||||
galleryTabOutput: "Output",
|
||||
galleryTabImagePrompt: "ImagePrompt",
|
||||
galleryTabStyleCatalog: "Style_Catalog",
|
||||
galleryNoSelection: "No selection",
|
||||
imagePromptSelectedPrompt: "Prompt",
|
||||
imagePromptNoPrompt: "No prompt data for this image.",
|
||||
imagePromptAddBtn: "+ Add",
|
||||
imagePromptChipsTitle: "Selected Prompts",
|
||||
imagePromptClearBtn: "Clear All",
|
||||
imagePromptFinalPromptTitle: "Final Prompt",
|
||||
imagePromptSaved: "Prompt saved",
|
||||
imagePromptAlreadyAdded: "Already added",
|
||||
imagePromptNothingToCopy: "Nothing to copy yet",
|
||||
imagePromptCopiedToast: "Copied to clipboard",
|
||||
stylecatalogSearchPlaceholder: "Search...",
|
||||
stylecatalogPositive: "Positive",
|
||||
stylecatalogNegative: "Negative",
|
||||
stylecatalogSelectStyleBtn: "Select as Style",
|
||||
stylecatalogLoadGenuiBtn: "Load in GenerateUI",
|
||||
stylecatalogOpenMetadataBtn: "Open in Metadata Tab",
|
||||
stylecatalogNoPromptFound: "No prompt found in this image.",
|
||||
stylecatalogNoMatch: "No matching style found",
|
||||
stylecatalogStyleSelected: (name) => `Style set to "${name}"`,
|
||||
stylecatalogNewFolderCreated: "Folder created",
|
||||
stylecatalogSaved: (name) => `Saved: ${name}`,
|
||||
galleryBulkSelected: "selected",
|
||||
galleryBulkDeselectAll: "Deselect All",
|
||||
galleryBulkSelectAll: "Select All",
|
||||
@@ -619,6 +685,10 @@ const LANGUAGES = {
|
||||
aiSettingsModelSection: "Model",
|
||||
aiSettingsRefreshBtn: "Refresh",
|
||||
aiSettingsModelPlaceholder: "-- Select Model --",
|
||||
aiSettingsGenerationTitle: "Generation",
|
||||
aiSettingsThinkingMode: "Thinking mode",
|
||||
aiSettingsMaxTokens: "Max tokens",
|
||||
aiSettingsMaxTokensPlaceholder: "0 = unlimited",
|
||||
aiSettingsFreeLang: "Free Language",
|
||||
aiSettingsInputLang: "Input",
|
||||
aiSettingsOutputLang: "Output",
|
||||
@@ -634,6 +704,7 @@ const LANGUAGES = {
|
||||
aiStatusConnectOk: "Connected",
|
||||
aiStatusConnectFail: "Connection failed: ",
|
||||
aiToastTransFailed: "Translation failed: ",
|
||||
aiToastMaybeNotTranslated: "The model returned the text unchanged — it may not have translated it. Try a different model.",
|
||||
aiToastNoCopyText: "No text to copy",
|
||||
aiToastCopied: "Copied",
|
||||
aiToastNoModels: "No models found",
|
||||
@@ -684,9 +755,13 @@ const LANGUAGES = {
|
||||
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 (subgraph-containing workflows are supported, e.g. Flux.2 / Qwen-Image / Z-Image / Mage-Flow / LongCat / Boogu / HiDream E1 / FireRed / Ernie Image templates; only ComfyUI's simplified App format [.app.json / Linear Mode] is not); 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",
|
||||
helpGen25: "Create Catalog button (next to the Style dropdown): generates one preview image per Style selected in the Batch tab's Style sub-tab (using the currently loaded workflow, typically T2I), then saves each result into a chosen ws_style_catalog subfolder with the Style's own name as the filename (existing files with the same name are overwritten); a modal lets you create a new destination folder or pick an existing one — separate folders are useful for grouping catalogs by checkpoint or by purpose; requires at least one Style checked in Batch tab → Style sub-tab first. Catalog button (right next to it): jumps straight to the Gallery tab's Style_Catalog sub-tab to browse the results",
|
||||
helpGen26: "Create Catalog modal — \"Don't keep a copy in the Output folder\" checkbox: each generation still writes a normal file to ComfyUI's Output folder first (that's simply how the workflow's own Save Image node works), but once its copy has been saved into the catalog folder, checking this deletes that Output-folder original right away — useful for large catalog runs (e.g. all 200+ styles) so the Output folder isn't flooded with near-duplicate files; if a particular style's catalog copy fails to save, its Output file is left alone rather than being deleted",
|
||||
helpGen27: "Input tab → Image sub-panel — each LoadImage card now has three buttons: Apply (unchanged), Clear (resets that card's pending selection/preview back to empty; doesn't touch the workflow node itself, since LoadImage always needs some valid filename), and Placeholder. A Placeholder Image section — collapsed by default since it's a low-frequency feature, click to expand — sits at the top of the panel with a shared default: Color mode (set Width/Height/Color; generates a solid-color PNG on the fly) or Image mode (drop one default image, reused as-is). Clicking a card's own Placeholder button immediately replaces just that card's image with the configured default — no separate Apply click needed, and with several LoadImage cards each can be replaced individually. The Placeholder config (mode, size, color, default image) is remembered across sessions",
|
||||
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: inner tabs — Prompt and Image (drag-and-drop upload); Prompt tab has Positive Prompt, Negative Prompt, and an Embeddings selector at the bottom — select a model, set Weight (default 1.0), then click Paste to insert (embedding:Name:weight) at the cursor position of the last focused textarea (defaults to Positive if neither is focused); a ↺ button next to each Apply button reverts the textarea to the node's currently applied value; select text (or just place the cursor on a word/parenthesis block) and press Ctrl+↑/↓ to adjust its emphasis weight in (text:weight) syntax by ±0.05 — the parentheses are removed automatically when the weight returns to 1.0",
|
||||
helpGen5: "Model tab: Checkpoint, VAE, LoRA (Single/Stack tabs), ControlNet, Diffusion Model (UNETLoader / UnetLoaderGGUF / LoaderGGUF), Text Encoder (CLIPLoader / DualCLIPLoader / ClipLoaderGGUF / DualClipLoaderGGUF — type and device selectors; DualCLIP shows two clip selectors), Hypernetwork (with Strength field) selectors with filter",
|
||||
helpGen5: "Model tab: Checkpoint, VAE, Diffusion Model (UNETLoader / UnetLoaderGGUF / LoaderGGUF), Text Encoder (CLIPLoader / DualCLIPLoader / ClipLoaderGGUF / DualClipLoaderGGUF — type and device selectors; DualCLIP shows two clip selectors) are always shown; ControlNet and Hypernetwork (with Strength field) are collapsed by default since they're used less often — click their header to expand; LoRA (Single/Stack tabs) has its own column to the right; all selectors have a 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",
|
||||
helpGen28: "Model tab — Highlight color: the label of each model type (Checkpoint, VAE, Diffusion Model, Text Encoder, ControlNet, Hypernetwork) and the LoRA column header turn a distinct color (default bright green) when the loaded workflow actually contains that type of node; this stays visible even while ControlNet/Hypernetwork are collapsed, so you can tell at a glance whether they're in use without expanding them; the color is customizable in the Settings tab",
|
||||
helpGen6: "Settings tab: KSampler and Latent Image side by side, each at 50% width",
|
||||
helpGen7: "Raw JSON always visible in the right column of each tab — edit directly and Apply to reload the workflow; if the loaded workflow has Bypass or Mute nodes, a note listing them appears above the search bar (Bypass nodes are excluded with their wires reconnected around them; Mute nodes are excluded with no reconnection, matching ComfyUI itself)",
|
||||
helpGen8: "Seed control: random, fixed, increment, decrement",
|
||||
@@ -701,6 +776,11 @@ const LANGUAGES = {
|
||||
helpGen17: "Style batch: select styles from the Style tab in the left pane, enable the Style column in Batch Queue, then Generate — each selected style is applied in sequence to the positive and negative prompts; applied to workflow copies so the loaded workflow is not modified; style files are re-read on each page load from user/default/Workflow-Studio/style/*.json",
|
||||
helpGen18: "Alt+Click any Apply button (Positive Prompt / Checkpoint / KSampler) to Apply & Generate in one step — applies the parameter to the workflow then immediately queues a generation; only fires when the target node exists in the loaded workflow",
|
||||
helpGen19: "Lora batch: for each LoRA, its syntax (<lora:name:strength_model:strength_clip>) and CivitAI trained words are automatically appended to the Positive prompt — rebuilt from the original prompt each time, not accumulated; the prompt is automatically restored to its pre-batch state when the batch completes or is stopped; if a selected LoRA is not yet recognized by ComfyUI's model list, a warning toast is shown (Refresh or restart ComfyUI)",
|
||||
helpGen20: "Two ways LoRAs are attached: a chain of standard LoraLoader nodes (one LoRA per node — add more by chaining additional nodes) or a single Lora Loader (LoraManager) node (from the ComfyUI-Lora-Manager custom node pack) that holds a list of LoRAs internally, each with its own active/model-strength/clip-strength; the Single/Stack tabs below adapt automatically depending on which type the target node is",
|
||||
helpGen21: "Single tab: pick one LoRA + Str M/Str C, then Apply — for a Lora Manager node this replaces its entire internal LoRA list with just this one entry, discarding any others it had",
|
||||
helpGen22: "Stack tab — Use Stack Group checkbox (shown only when a Lora Manager node exists in the workflow): OFF (the default whenever a workflow is loaded) shows and edits the LoRAs actually configured in the workflow's Lora Manager node itself; ON shows and edits the \"Stack\" group registered in the Models tab instead; switching either direction clears the node's LoRA list first, then loads it from the newly selected source; switching back to OFF restores exactly the LoRA list that was present when the workflow was loaded (captured as a snapshot at load time)",
|
||||
helpGen23: "Stack tab controls: each row has an active checkbox and Str M / Str C fields; the header \"Stack\" checkbox toggles all rows at once; the +/- step buttons adjust the strength of all currently active rows together; a \"Showing: LoRAs currently in workflow\" / \"Showing: registered Stack group\" label indicates which source is currently displayed; Apply writes the full list back to the target node and also appends LoRA syntax + CivitAI trigger words to the Positive prompt",
|
||||
helpGen24: "Caution for CLIP Text Encode edit+ (CLIPTextEncodeEditPlus) nodes: when a Lora Manager node's trigger_words output feeds this node's text1 input (RAW/EDIT/front/back modes combine text1 with the editable text_edit field), trigger words are already included automatically at generation time; clicking a LoRA Apply button or turning on Use Stack Group additionally writes LoRA syntax/trigger words into text_edit, duplicating them — leave Use Stack Group off and avoid the LoRA Apply buttons if you want the workflow's original prompt and LoRA composition to stay unmodified",
|
||||
helpFeederTitle: "GenerateUI Tab — Feeder subtab",
|
||||
helpFeederDesc: "Two modes switchable via the [Image Loop] / [Gallery] toggle at the top of the left pane.",
|
||||
helpFeederImgloopTitle: "Image Loop mode",
|
||||
@@ -729,20 +809,28 @@ const LANGUAGES = {
|
||||
helpLab1: "Left pane — Image: drop or click to select an I2I source image; it is uploaded to ComfyUI's input folder and used for every iteration unless \"Use generated image for next\" is checked",
|
||||
helpLab2: "Left pane — Use generated image for next: from iteration 2 onward, feeds the previous iteration's first output image back in as the I2I source instead of the original dropped image (iteration 1 always uses the original)",
|
||||
helpLab3: "Center pane — 4 independent columns: Checkpoint, VAE, Prompt, KSampler; each column keeps its own list of keyframes rather than sharing a row grid",
|
||||
helpLab4: "+ / − per column: + appends a new keyframe at the next free iteration number (up to the Batch count) and opens its edit modal immediately; − removes the last keyframe (iteration #1 can never be removed)",
|
||||
helpLab4: "+ / − per column: + appends a new keyframe at the next free iteration number (up to the Batch count) and opens its edit modal immediately; − removes the last keyframe (iteration #1 can never be removed); any keyframe other than #1 can also be deleted individually from inside its own edit modal via its Delete button, not just the last one",
|
||||
helpLab5: "Click a cell to edit it: iteration #1 sets the baseline value (leave it blank to keep the loaded workflow's own setting); iteration #2+ also lets you choose which iteration it starts applying from, plus a \"revert to #1's setting\" checkbox",
|
||||
helpLab6: "Effective value at iteration N: the latest keyframe with iteration ≤ N is used and carries forward until the next keyframe changes it; \"revert to #1\" reuses iteration #1's value (or the workflow default if #1 is blank) instead of specifying a new one",
|
||||
helpLab6: "Effective value at iteration N: the latest keyframe with iteration ≤ N is used and carries forward until the next keyframe changes it; \"revert to #1\" reuses iteration #1's value (or the workflow default if #1 is blank) instead of specifying a new one; lowering the Batch count (by hand, or by loading/applying a plan) below an existing keyframe's iteration number doesn't delete or renumber that keyframe — a warning toast appears, and the keyframe simply stays dormant (never reached by the run loop) until Batch count is raised again",
|
||||
helpLab7: "Lab never edits the workflow shown in Input/Model/Settings — every iteration runs on a fresh clone of the loaded workflow, so keyframes here never affect the other subtabs",
|
||||
helpLab8: "Prompt cell editor extras: Get from GenerateUI fills Positive/Negative from the workflow currently loaded in GenerateUI; Get from Image extracts a prompt from the image currently loaded in Lab's own Image drop zone (same detection as the Metadata tab; no separate file picker); Style appends whichever style is currently selected in the Style checkbox/dropdown at the top of the GenerateUI toolbar to the Positive/Negative text below, comma-separated after any existing text (never clears it) — enable that checkbox and pick a style first, Lab doesn't have its own separate style picker",
|
||||
helpLab8: "Prompt cell editor extras: Get from GenerateUI fills Positive/Negative from the workflow currently loaded in GenerateUI; Get from Image extracts a prompt from the image currently loaded in Lab's own Image drop zone (same detection as the Metadata tab; no separate file picker); Style row — the Apply button appends whichever style is currently selected in the Style dropdown at the top of the GenerateUI toolbar to the Positive/Negative text below, comma-separated after any existing text (never clears it), then checks the Style checkbox and shows the applied style's name next to it (not on the button) — the style NAME always comes from that top dropdown (Lab has no picker of its own), and clicking Apply works regardless of the top toolbar's own Style enable checkbox; unchecking the Style checkbox only clears that name label — it does not remove the already-appended text from Positive/Negative, which stays there for you to edit or delete by hand",
|
||||
helpLab9: "Left pane — T2I workflow (no source image): check this when the loaded workflow is text-to-image (no LoadImage node). It skips the \"drop a source image first\" requirement, ignores any dropped image, and the Checkpoint/VAE/Prompt/KSampler keyframes still apply normally; the Image drop zone and \"Use generated image for next\" are greyed out while it's on (any previously dropped image is kept, not deleted, in case you switch back to I2I); the setting is saved with the plan as t2i_mode",
|
||||
helpLab10: "Wildcards: Positive/Negative prompt text in Prompt column keyframes supports the same A1111-style __name__ syntax as the main GenerateUI — each keyframe's text is expanded fresh right before that iteration runs, so every iteration can draw a different random line even when reusing the same keyframe",
|
||||
helpLab11: "Prompt cell editor also has Clear (empties both Positive and Negative) and Get from Previous (copies both Positive and Negative from the keyframe immediately before this one in the same column — e.g. editing #3 copies #2's prompt wholesale; not shown on keyframe #1, which has no earlier row to copy from)",
|
||||
helpLab12: "Keyframe #1 in every column shows the currently loaded workflow's own live setting — Checkpoint, VAE, Prompt, and KSampler — instead of a blank placeholder, both in its grid cell (dashed border) and pre-filled into its edit modal, for as long as it hasn't been explicitly saved with an override; saving it (even without changing anything) locks that value in as a real override and the dashed/live styling goes away; switching to the Lab subtab always refreshes this against whatever is currently loaded in GenerateUI",
|
||||
helpLab13: "Bypass checkbox (every keyframe, including #1): skips that row entirely when picking which setting applies at a given iteration — as if the row didn't exist — so whatever was active before it (an earlier keyframe, or ultimately nothing) just keeps running; Lab-internal only, it never touches the actual ComfyUI node's mode; disables that row's value fields and its Revert checkbox while checked (the two are mutually exclusive); the cell shows an amber \"⏭ Bypassed\" label, which takes priority over both the Revert and live-value display",
|
||||
helpLabCardPlanTitle: "Setting subtab — Run & Plan files",
|
||||
helpLabPlan1: "Right pane — Batch: number of iterations to run; Note: free-text memo saved together with the plan",
|
||||
helpLabPlan2: "Run / Pause / Cancel: Run starts the batch loop; Pause/Resume freezes it between iterations; Cancel interrupts the current generation and stops the loop",
|
||||
helpLabPlan3: "Plan Save vs Save As: Plan Save silently overwrites the currently loaded plan (or asks for a name the first time); Save As always asks for a new name, even while a plan is already loaded",
|
||||
helpLabPlan4: "Plan Load: drop a plan's .json file, or its .png index-image thumbnail, onto the PLAN box (or click it to browse) — a dropped .json is read directly; a dropped .png fetches the matching .json (same filename) from the server",
|
||||
helpLabPlan4: "Plan Load: drop a plan's .json file, or any of its index-image PNGs, onto the PLAN box (or click it to browse) — a dropped .json is read directly; a dropped .png is read directly too if it carries embedded plan data (every index image since v0.3.90 does, in a wfm_lab_plan chunk), falling back to fetching a same-named .json from the server for older index images that predate this",
|
||||
helpLabPlan5: "Plan Clear resets the Setting tab to an empty plan (asks for confirmation first)",
|
||||
helpLabPlan6: "Plan files are stored in user/default/Workflow-Studio/lab_plan/ as <name>.json plus a <name>.png index image — a contact sheet of up to 9 result thumbnails (3 per row) generated automatically whenever a plan with results is saved",
|
||||
helpLabPlan6: "Plan files are stored in user/default/Workflow-Studio/lab_plan/ as ws_labplan_<name>.json plus a ws_labplan_<name>.png index image — a contact sheet of up to 9 result thumbnails (3 per row) generated automatically whenever a plan with results is saved. The ws_labplan_ prefix is added automatically by Plan Save/Save As (type just the plain name when prompted) so plan files are easy to pick out among other files in that folder",
|
||||
helpLabPlan7: "Eagle auto-save (configured in the Settings tab) applies to every image Lab generates, the same as GenerateUI's own Generate button",
|
||||
helpLabPlan8: "Plan JSON subtab: shows the current Setting tab's plan as raw JSON; Refresh re-reads it from the Setting tab (discarding any unapplied text edits), Apply to Setting parses your edits and writes them back into the Setting tab (columns, note, batch count, chain-image, source image, results) — the same effect as loading that JSON as a plan file, without needing to save it first",
|
||||
helpLabPlan9: "Each saved plan records the filename of the workflow that was loaded in GenerateUI at save time (workflow_filename in the Plan JSON). After loading a plan, an Open Workflow button appears in the PLAN box — click it to load that exact workflow file back into GenerateUI (asks for confirmation, since it replaces whatever is currently loaded)",
|
||||
helpLabPlan10: "Right pane — Save index image to Output on Run: when checked, every time Run finishes it builds the same contact-sheet index image used for Plan files and saves it directly into ComfyUI's own Output folder as Lab_index_<counter>_.png (auto-numbered like a normal generated image, never overwriting a previous run's). Once saved, it also goes through Eagle auto-save (if enabled in the Settings tab) just like every other Lab-generated image — no separate checkbox for that, it follows the same global toggle. This is independent of Plan Save, which still always writes its own index image next to the plan file in lab_plan/ regardless of this checkbox; this setting is saved with the plan as save_index_on_run",
|
||||
helpLabPlan11: "Every index image PNG — whether from Plan Save/Save As or from Save index image to Output on Run — carries the entire plan (columns, note, batch count, chain-image/T2I settings, workflow filename, results) embedded in it directly as a PNG wfm_lab_plan chunk, so the Output-folder copy is self-contained and works as a Plan Load source too even though it has no matching .json next to it anywhere",
|
||||
helpLabCardResultsTitle: "Results subtab",
|
||||
helpLabResults1: "Left pane shows the source image used for the run",
|
||||
helpLabResults2: "Center pane shows up to 9 generated images in generation order; click a thumbnail to view it enlarged",
|
||||
@@ -758,6 +846,11 @@ const LANGUAGES = {
|
||||
helpPrompt7: "GenUI Set: apply preset prompts directly to GenerateUI",
|
||||
helpPrompt8: "Wildcard toolbar: one-click buttons to insert wildcard syntax ({|}, {n$|}, __|__, <lora:>, etc.); wraps selected text",
|
||||
helpPrompt9: "Wildcard file manager: create/edit/delete .txt/.yaml wildcard files; click filename to insert __filename__ at cursor",
|
||||
helpPrompt10: "Right pane's Wildcard/Style tab bar switches the whole panel between the wildcard tools above and this Style manager — same right pane, two modes",
|
||||
helpPrompt11: "Create/edit/delete registered Styles (the same ones used by GenerateUI's Style dropdown, Batch tab, and the Style Catalog): click a name in the list to edit it, or \"+ New\" for a blank entry; Name, Positive prompt (supports the {prompt} placeholder — replaced with the user's own prompt, or appended after it if omitted) and Negative prompt (optional)",
|
||||
helpPrompt12: "Renaming a style keeps its position in whichever file it was originally defined in; new styles are saved into a dedicated custom.json inside the style folder so the bundled style packs are never modified directly; a name must be unique across all styles",
|
||||
helpPrompt13: "Saving, renaming, or deleting a style immediately refreshes GenerateUI's Style dropdown, the Batch tab's style checklist, and the Style Catalog's name list — no reload needed",
|
||||
helpPrompt14: "Each entry in the list shows its source file as a small badge next to the name (e.g. sdxl_styles_diva.json); while editing an existing style, that filename also appears above the Positive prompt field, and a \"+ Add to this file\" button appears next to Save — click it to clear the form for a brand-new style that gets appended to that same file instead of the default custom.json",
|
||||
helpSettings1: "UI language and summary language",
|
||||
helpSettings2: "Theme selection (13 presets) with customization: color overrides, background patterns (stripes, polka dot, checkerboard, SVG tiling), and font selection (16 Google Fonts including Japanese display fonts)",
|
||||
helpSettings3: "Workflow data folder path",
|
||||
@@ -771,6 +864,7 @@ const LANGUAGES = {
|
||||
helpSettings11: "Text Size: one slider (10–28 px) adjusts font size for all prompt and chat textareas at once — Generate UI positive/negative prompts, AI Assistant chat input, Preset positive/negative, Wildcard prompt and file editor, and Metadata prompt full preview; takes effect immediately and saved with Save Settings",
|
||||
helpSettings12: "RAW JSON Colors: customize the 6 syntax highlight colors for the Raw JSON editor in Generate UI — Default Text, Name/Scheduler, Title, Width/Height, Prompt/Text, Image/File; changes apply immediately on color pick; Reset Defaults restores the original color scheme",
|
||||
helpSettings13: "CivitAI Host: choose between civitai.com (SFW only) and civitai.red (unrestricted) — determines which site opens when clicking a model link in the Models tab CivitAI panel",
|
||||
helpSettings14: "GenerateUI Model Tab Highlight: pick the color used to mark Checkpoint/VAE/Diffusion Model/Text Encoder/ControlNet/Hypernetwork labels and the LoRA column header in GenerateUI's Model tab when the loaded workflow actually contains that type of node; default bright green; changes apply immediately, Reset Defaults restores it",
|
||||
helpNodes1: "Node Browser: search by name/description/alias/tag, filter by category, package, tag, group, favorites",
|
||||
helpNodes2: "Card and Table view modes with pagination",
|
||||
helpNodes3: "Favorite nodes and add custom tags for organization",
|
||||
@@ -808,6 +902,14 @@ const LANGUAGES = {
|
||||
helpGallery15: "F button (cyan overlay, top-left of each thumbnail): toggle the image in/out of the __Feeder__ group with a single click; cyan and always visible when in group, visible on hover only when not; quickly queue images for the Feeder tab Gallery mode",
|
||||
helpGallery16: "Image Edit button (toolbar, next to Refresh): sends the currently selected image to the Image Edit tab; if layers already exist the image is added as a new layer scaled to fit the canvas, otherwise it becomes Layer 1",
|
||||
helpGallery17: "Send GenUI Image button (toolbar, next to Image Edit): uploads the selected image to ComfyUI and sets it as the input for the first LoadImage node in the GenerateUI tab; automatically switches to GenerateUI → Input → Image; requires a workflow with at least one LoadImage node to be loaded first",
|
||||
helpGallery18: "Second sub-tab next to Output (top of the Gallery tab) for browsing a visual prompt library — manages the ws_image_prompt folder inside the ComfyUI output directory (created automatically)",
|
||||
helpGallery19: "Same 3-column layout: folder tree (left) | thumbnails (center) | prompt builder (right). Click a thumbnail to preview it and its prompt text — this does not add it to the prompt yet",
|
||||
helpGallery20: "\"+ Add\" appends the previewed image's prompt as a chip under \"Selected Prompts\"; chips can be removed individually (×) or all at once (\"Clear All\"); \"Save\" edits and persists the prompt text for that image",
|
||||
helpGallery21: "\"Final Prompt\" combines all chips into one comma-separated text (also freely editable); \"Copy\" copies it to the clipboard. Prompt text is stored as a plain .txt file next to each image, so anyone can add their own entries by dropping an image + matching .txt file into a subfolder",
|
||||
helpGallery22: "Third sub-tab (top of the Gallery tab) for visually picking a registered Style by its preview image — manages the ws_style_catalog folder inside the ComfyUI output directory (created automatically); populated by the GenerateUI tab's Create Catalog button (see GenerateUI Tab help)",
|
||||
helpGallery23: "Same 3-column layout: folder tree (left) | thumbnails (center) | Positive/Negative prompt panel (right). Click a thumbnail to read the Positive/Negative prompt actually embedded in that generated image, each with its own Copy button",
|
||||
helpGallery24: "Select as Style button: matches the selected image's filename (without extension) against a registered Style name and switches the GenerateUI tab's Style dropdown to it — a visual shortcut into the existing named-Style system, not a one-off apply of the embedded prompt (if the Style was renamed or deleted since the catalog image was created, a \"no matching style\" toast is shown instead)",
|
||||
helpGallery25: "Load in GenerateUI / Open in Metadata Tab buttons: read the workflow embedded in the catalog image itself (the catalog copy carries the same PNG metadata as the original output image) and either load it straight into the GenerateUI editor or open the image in the Metadata tab for inspection — no need to hunt down the original file in the Output folder",
|
||||
|
||||
// -- Tagger Tab --
|
||||
helpTaggerTitle: "Tagger Tab",
|
||||
@@ -837,14 +939,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, Chat, TOOLS, and Settings sub-tabs powered by Ollama, LM Studio, or Lemonade; Chat supports multi-turn conversations; TOOLS includes VLM image analysis and wildcard generation; settings shared with the SPA AI TOOL tab via localStorage",
|
||||
helpSidepanel16: "A tab (AI Tools): Translation, Chat, TOOLS, and Settings sub-tabs powered by Ollama, LM Studio, Lemonade, or Unsloth; Chat supports multi-turn conversations; TOOLS includes VLM image analysis and wildcard generation; settings shared with the SPA AI TOOL tab via localStorage",
|
||||
helpSidepanel17: "Send to Canvas: clicking 'Send to Canvas' (Workflow tab) or 'Copy & Send Canvas' (Gallery tab) sends the workflow directly to the ComfyUI canvas — both UI and API formats are supported; if Workflow Studio was not opened from the ComfyUI toolbar (window.opener unavailable), UI-format workflows fall back to title drag (title turns blue with a green ●)",
|
||||
helpAiTitle: "AI Tab (A)",
|
||||
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",
|
||||
helpAi2: "Translation pane: translate between Japanese, English, Chinese, or Free language using Ollama, LM Studio, Lemonade, or Unsloth; ⇄ 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; if the model supports tool calling and asks for an image (\"generate a cat picture\", etc.) it will run generation on the workflow currently loaded in GenerateUI and show the result inline; the \"Allow image generation\" checkbox in the pane header toggles this on/off; if an image is attached (dropped in the TOOLS pane) it is sent to the LLM as vision input and, when generate_image is called, used as the base for image-to-image generation instead of text-to-image; models verified to work well for tool calling and vision: Gemma 4:e4b, Qwen 3.5:9b, Ministral 3:3b (Ollama)",
|
||||
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; the dropped image is also shared with the Chat pane as its attachment (shown there and used for image-to-image generation) until cleared with the ✕ button",
|
||||
helpAi6: "Settings pane: choose backend (Ollama / LM Studio / Lemonade), set API URL, test connection, select model, configure Free language names; Chat Image Generation section lets you enable a dedicated workflow for Chat-triggered text-to-image generation instead of the one currently loaded in GenerateUI; Chat I2I Generation section is the same but for image-to-image generation when an image is attached; settings are shared with the Library panel's A tab via localStorage",
|
||||
helpAi6: "Settings pane: choose backend (Ollama / LM Studio / Lemonade / Unsloth), set API URL, test connection, select model; Unsloth always requires an API key even for local access — set UNSLOTH_API_KEY in a .env file in the plugin folder (copy .env.example) and restart ComfyUI, the key is read server-side and never sent to the browser; Unsloth also requires \"Auto model switching (OpenAI API)\" to be turned ON in the Unsloth Desktop app itself (its own Settings screen) — without it, requests fail with HTTP 404 unless a model was already manually loaded in the Unsloth Studio UI; Unsloth reasoning models return their thinking in a separate reasoning_content field rather than inline <think> tags, so a low Max tokens can make the model spend its whole budget reasoning and return an empty reply — increase Max tokens (2048+) if replies come back blank; Generation section — Thinking mode toggle (off by default; Ollama receives a think flag, and regardless of backend any <think>...</think> block is stripped from the output when off, so reasoning models don't clutter Translation/Chat/TOOLS results) and Max tokens (Ollama: num_predict, LM Studio/Lemonade/Unsloth: max_tokens; 0 = unlimited); configure Free language names; Chat Image Generation section lets you enable a dedicated workflow for Chat-triggered text-to-image generation instead of the one currently loaded in GenerateUI; Chat I2I Generation section is the same but for image-to-image generation when an image is attached; settings are shared with the Library panel's A tab via localStorage",
|
||||
helpAi7: "Chat pane — SVG: the LLM can also produce SVG graphics directly as text, with no ComfyUI workflow involved; ask it to draw something in SVG and, if the reply contains SVG code, it is rendered inline as a preview with a \"Save to Gallery\" button that writes it as a .svg file to the Gallery tab's output folder; this does not use tool calling, so it works with any model regardless of tool-calling support",
|
||||
helpAi8: "Chat pane — Skills: pick a skill from the dropdown above the message list to prepend its instructions to the conversation as a system prompt (not shown in the visible chat log); use the pencil button to open the skill manager and create, edit, or delete .md skill files, stored in user/default/Workflow-Studio/ai_skills/; a file's first line block between --- markers can define name/description shown in the dropdown; two starter skills are included by default: \"SVG Icon Generator\" (decomposes the subject into parts before drawing, for more recognizable SVG output) and \"Skill Creator\" (interviews you conversationally and drafts a new skill file, ready to save); when a reply contains a ```skill code block, a \"Save as new skill\" button appears below it that opens the manager with the draft pre-filled",
|
||||
helpAi9: "Tips for writing your own skills: give a clear frontmatter name/description so it reads well in the dropdown and tooltip; state the exact output format you want and, if there is a deliverable to extract later (like SVG or another skill file), wrap it in a distinctive fenced code block; write concrete, imperative instructions rather than vague ones - smaller local models follow explicit rules and a short worked example far better than general guidance; state hard constraints (forbidden content, security, length limits) explicitly rather than assuming they are implied; when in doubt, select the \"Skill Creator\" skill in the dropdown and describe what you want - it will interview you and draft the file for you",
|
||||
@@ -868,10 +970,12 @@ const LANGUAGES = {
|
||||
helpGenCardSeed: "Seed & Generation",
|
||||
helpGenCardBatchSetup: "Batch Tab — Setup",
|
||||
helpGenCardBatchTypes: "Batch Tab — Batch Types",
|
||||
helpGenCardLora: "Model Tab — LoRA Details",
|
||||
helpPromptTitle: "Prompt Tab",
|
||||
helpPromptCardAi: "AI Assistant & Translation",
|
||||
helpPromptCardPresets: "Presets",
|
||||
helpPromptCardWildcards: "Wildcards",
|
||||
helpPromptCardStyleTitle: "Style",
|
||||
helpMetadataCardOverview: "Overview",
|
||||
helpMetadataCardExtracted: "Extracted Information",
|
||||
helpMetadataCardFormats: "Supported Formats",
|
||||
@@ -886,6 +990,8 @@ const LANGUAGES = {
|
||||
helpNodesCardGroups: "Groups & Sets",
|
||||
helpNodesCardPanel: "Side Panel & Multi-select",
|
||||
helpGalleryCardBrowse: "Browsing",
|
||||
helpGalleryCardStyleprompt: "ImagePrompt Gallery",
|
||||
helpGalleryCardStylecatalog: "Style_Catalog Gallery",
|
||||
helpGalleryCardFolder: "Folder & Selection",
|
||||
helpGalleryCardDetail: "Detail Panel",
|
||||
helpGalleryCardActions: "Actions Toolbar",
|
||||
@@ -1296,6 +1402,7 @@ const LANGUAGES = {
|
||||
saveWorkflowTitle: "ワークフローを保存",
|
||||
filenameLabel: "ファイル名",
|
||||
pleaseEnterFilename: "ファイル名を入力してください",
|
||||
pleaseEnterStyleName: "スタイル名を入力してください",
|
||||
saveFailed: (msg) => msg ? `保存に失敗しました: ${msg}` : "保存に失敗しました",
|
||||
savedAs: (f) => `保存しました: ${f}`,
|
||||
overwriteConfirm: (f) => `「${f}」は既に存在します。上書きしますか?`,
|
||||
@@ -1364,16 +1471,30 @@ const LANGUAGES = {
|
||||
batchStopped: (completed, failed) => `バッチ停止 — 完了${completed}件、失敗${failed}件`,
|
||||
batchComplete: (completed, total, failed) => failed > 0 ? `バッチ完了: ${completed}/${total}件 (${failed}件失敗)` : `バッチ完了: ${completed}/${total}件`,
|
||||
batchLoraMissing: (count, total, sample) => `選択したLoRAのうち${count}/${total}件がComfyUIに認識されていません(例: ${sample})。ComfyUIでRefreshするかサーバーを再起動してから再実行してください。`,
|
||||
catalogCreateBtn: "カタログ作成",
|
||||
catalogOpenBtn: "カタログ",
|
||||
catalogCreateTitle: "スタイルカタログ作成",
|
||||
catalogCreateNoStyles: "スタイルが選択されていません。先にBatchタブのStyleサブタブでスタイルを選択してください",
|
||||
catalogCreateSelectedCount: (n) => `${n}件のスタイルが選択されています`,
|
||||
catalogCreateNewFolder: "新規フォルダを作成",
|
||||
catalogCreateExistingFolder: "既存フォルダを使用",
|
||||
catalogCreateRun: "実行",
|
||||
catalogCreateFolderNameRequired: "フォルダ名を入力してください",
|
||||
catalogCreateFolderRequired: "保存先フォルダを選択してください",
|
||||
catalogCreateSkipOutput: "Outputフォルダにコピーを残さない",
|
||||
|
||||
// -- Lab タブ --
|
||||
labImageUploaded: (name) => `画像をアップロードしました: ${name}`,
|
||||
labUploadFailed: "アップロードに失敗しました",
|
||||
labBatchCountTooSmall: "先にBatch数を増やしてからキーフレームを追加してください",
|
||||
labKeyframesExceedBatch: (maxIter, batchCount) => `${maxIter}回目まで設定されたキーフレームがありますが、現在のBatch数(${batchCount})を超えているため、Batch数を増やすまで適用されません`,
|
||||
labUseWorkflowDefault: "(ワークフローの設定のまま)",
|
||||
labAppliedAt: (n) => `適用:${n}`,
|
||||
labRevertToBase: "↩ 1回目に戻す",
|
||||
labApplyFromIteration: "何回目から適用するか",
|
||||
labRevertCheckboxLabel: "1回目の設定に戻す",
|
||||
labBypassed: "⏭ バイパス中",
|
||||
labBypassCheckboxLabel: "この設定をバイパス(直前まで有効だった設定を維持)",
|
||||
labSeedEmptyRandom: "Seed(空欄でランダム)",
|
||||
labPause: "一時停止",
|
||||
labResume: "再開",
|
||||
@@ -1390,10 +1511,15 @@ const LANGUAGES = {
|
||||
labConfirmClear: "Labの設定(画像・列・メモ・結果)をすべてクリアしますか?",
|
||||
labGetFromGenUI: "GenerateUIから取得",
|
||||
labGetFromImage: "画像から取得",
|
||||
labGetFromPrevious: "前の設定から取得",
|
||||
labClearPrompt: "クリア",
|
||||
labPromptCleared: "プロンプトをクリアしました",
|
||||
labPromptCopiedFromPrevious: "前の設定からコピーしました",
|
||||
labLiveHint: "現在のGenerateUIの設定を表示しています。編集して保存すると上書きされます。",
|
||||
labStyle: "スタイル",
|
||||
labApply: "適用",
|
||||
labNoStyles: "スタイルがありません",
|
||||
labEnableStyleFirst: "先にGenerateUIタブ上部のStyleチェックボックスをオンにし、スタイルを選択してください",
|
||||
labEnableStyleFirst: "先にGenerateUIタブ上部のStyleドロップダウンでスタイルを選択してください",
|
||||
labPlanJsonRefreshed: "現在のSettingタブの内容で更新しました",
|
||||
labPlanJsonApplied: "Plan JSONをSettingに適用しました",
|
||||
labPlanJsonInvalid: "JSONが不正です",
|
||||
@@ -1401,6 +1527,24 @@ const LANGUAGES = {
|
||||
labPromptFetched: "プロンプトを取得しました",
|
||||
labNoPromptInImage: "このファイルにはプロンプトが見つかりませんでした",
|
||||
labMetadataExtractFailed: "メタデータの読み取りに失敗しました",
|
||||
labConfirmLoadWorkflow: (filename) => `「${filename}」をGenerateUIに読み込みますか?現在読み込まれているワークフローは置き換えられます。`,
|
||||
labWorkflowLoadFailed: "ワークフローの読み込みに失敗しました",
|
||||
labT2IImageIgnored: "T2Iモードが有効なため、画像のアップロードは不要としてスキップしました",
|
||||
labIndexImageSaved: (filename) => `インデックス画像をOutputへ保存しました: ${filename}`,
|
||||
labIndexImageSaveFailed: "インデックス画像のOutputへの保存に失敗しました",
|
||||
|
||||
// -- GenerateUIタブ Inputサブタブ: Image内プレースホルダ --
|
||||
i2iPlaceholderTitle: "プレースホルダ画像",
|
||||
i2iPlaceholderColor: "色",
|
||||
i2iPlaceholderImage: "画像",
|
||||
i2iPlaceholderWidth: "幅",
|
||||
i2iPlaceholderHeight: "高さ",
|
||||
i2iPlaceholderColorLabel: "色",
|
||||
i2iPlaceholderDropImage: "デフォルト画像をドロップまたはクリックして選択",
|
||||
i2iPlaceholderApply: "プレースホルダ",
|
||||
i2iPlaceholderGenerating: "生成中...",
|
||||
i2iPlaceholderNoDefaultImage: "デフォルト画像が未設定です — 先に上部でドロップしてください",
|
||||
i2iPlaceholderUploading: "アップロード中...",
|
||||
|
||||
connectedToComfyUI: "ComfyUIに接続しました",
|
||||
failedToConnect: "接続に失敗しました",
|
||||
@@ -1428,6 +1572,9 @@ const LANGUAGES = {
|
||||
jsonColorCyan: "プロンプト / テキスト",
|
||||
jsonColorRed: "画像 / ファイル",
|
||||
jsonColorReset: "デフォルトに戻す",
|
||||
modelTabColorSection: "GenerateUI Modelタブ ハイライト色",
|
||||
modelTabColorLabel: "ワークフローに含まれる項目の色",
|
||||
modelTabColorHint: "GenerateUIのModelタブで、読み込んだワークフローに実際に含まれる項目(Checkpoint / VAE など)のラベルをこの色で表示します。",
|
||||
|
||||
// -- Prompt tab --
|
||||
tabPrompt: "プロンプト",
|
||||
@@ -1667,6 +1814,31 @@ const LANGUAGES = {
|
||||
galleryCCNotAvailable: "Send CCはComfyUI Comic Creator内のギャラリーから開いた場合のみ使用できます",
|
||||
gallerySentCC: "ComfyUI Comic Creatorへ送信しました",
|
||||
galleryNoEmbeddedWorkflow: "この画像にはComfyUIワークフローが埋め込まれていません。",
|
||||
galleryTabOutput: "Output",
|
||||
galleryTabImagePrompt: "ImagePrompt",
|
||||
galleryTabStyleCatalog: "Style_Catalog",
|
||||
galleryNoSelection: "選択なし",
|
||||
imagePromptSelectedPrompt: "プロンプト",
|
||||
imagePromptNoPrompt: "この画像にはプロンプトデータがありません。",
|
||||
imagePromptAddBtn: "+ 追加",
|
||||
imagePromptChipsTitle: "選択済みプロンプト",
|
||||
imagePromptClearBtn: "全クリア",
|
||||
imagePromptFinalPromptTitle: "最終プロンプト",
|
||||
imagePromptSaved: "プロンプトを保存しました",
|
||||
imagePromptAlreadyAdded: "すでに追加済みです",
|
||||
imagePromptNothingToCopy: "コピーする内容がありません",
|
||||
imagePromptCopiedToast: "クリップボードにコピーしました",
|
||||
stylecatalogSearchPlaceholder: "検索...",
|
||||
stylecatalogPositive: "Positive",
|
||||
stylecatalogNegative: "Negative",
|
||||
stylecatalogSelectStyleBtn: "スタイルとして選択",
|
||||
stylecatalogLoadGenuiBtn: "GenerateUIへ読み込む",
|
||||
stylecatalogOpenMetadataBtn: "Metadataタブで開く",
|
||||
stylecatalogNoPromptFound: "この画像にはプロンプトが見つかりません。",
|
||||
stylecatalogNoMatch: "一致するスタイルが見つかりません",
|
||||
stylecatalogStyleSelected: (name) => `スタイルを「${name}」に設定しました`,
|
||||
stylecatalogNewFolderCreated: "フォルダを作成しました",
|
||||
stylecatalogSaved: (name) => `保存しました: ${name}`,
|
||||
galleryBulkSelected: "件選択中",
|
||||
galleryBulkDeselectAll: "選択解除",
|
||||
galleryBulkSelectAll: "全選択",
|
||||
@@ -1766,6 +1938,10 @@ const LANGUAGES = {
|
||||
aiSettingsModelSection: "モデル選択",
|
||||
aiSettingsRefreshBtn: "更新",
|
||||
aiSettingsModelPlaceholder: "-- モデルを選択 --",
|
||||
aiSettingsGenerationTitle: "生成設定",
|
||||
aiSettingsThinkingMode: "Thinking mode(思考モード)",
|
||||
aiSettingsMaxTokens: "Max tokens(最大トークン数)",
|
||||
aiSettingsMaxTokensPlaceholder: "0 = 無制限",
|
||||
aiSettingsFreeLang: "Free 言語設定",
|
||||
aiSettingsInputLang: "入力言語",
|
||||
aiSettingsOutputLang: "翻訳言語",
|
||||
@@ -1781,6 +1957,7 @@ const LANGUAGES = {
|
||||
aiStatusConnectOk: "接続成功",
|
||||
aiStatusConnectFail: "接続失敗: ",
|
||||
aiToastTransFailed: "翻訳に失敗しました: ",
|
||||
aiToastMaybeNotTranslated: "モデルが原文をそのまま返しました。翻訳されていない可能性があります。別のモデルをお試しください。",
|
||||
aiToastNoCopyText: "コピーするテキストがありません",
|
||||
aiToastCopied: "コピーしました",
|
||||
aiToastNoModels: "モデルが見つかりません",
|
||||
@@ -1831,9 +2008,13 @@ const LANGUAGES = {
|
||||
helpWf7: "バッジ管理:バッジの追加・名前変更・削除、カスタム色設定(Modelsタブと共有)— ⚙ Badgeボタン",
|
||||
helpGen1: "ComfyUIの接続・切断、接続状態の確認",
|
||||
helpGen2: "Workflowタブからワークフローを読み込み(サブグラフを含むワークフローにも対応 — Flux.2 / Qwen-Image / Z-Image / Mage-Flow / LongCat / Boogu / HiDream E1 / FireRed / Ernie Image 等のテンプレート含む;ComfyUIの簡略化App形式 [.app.json / Linear Mode] のみ非対応)。Reset Workflowボタンは現在のワークフローファイルをディスクから再読込してエディタをリロード。Saveボタン(タブバー右端)はエディタでの編集を含む現在のワークフローを新しい.jsonファイルとしてWorkflowタブに保存(現在のワークフロー名を初期値としたファイル名ダイアログを表示)",
|
||||
helpGen25: "カタログ作成ボタン(Styleドロップダウンの隣):Batchタブ→Styleサブタブで選択中の各スタイルについて、現在読み込み中のワークフロー(通常はT2I)でプレビュー画像を1枚ずつ生成し、指定したws_style_catalogサブフォルダへスタイル名をファイル名として保存(同名ファイルは上書き)。実行時、新規フォルダ作成または既存フォルダ選択のモーダルが表示される — フォルダを分けることでチェックポイント別・用途別にカタログを整理できる。実行にはBatchタブ→Styleサブタブで最低1つスタイルを選択しておく必要がある。カタログボタン(その隣):Galleryタブ Style_Catalogサブタブへ直接移動して結果を確認できる",
|
||||
helpGen26: "カタログ作成モーダルの「Outputフォルダにコピーを残さない」チェックボックス:各生成は最初は必ずComfyUIのOutputフォルダへ通常通りファイルを書き出す(ワークフロー自体のSave Imageノードの仕様のため)。このチェックを入れておくと、カタログフォルダへのコピー保存が成功した直後に、そのOutput側の元ファイルを即座に削除する — 200件超の全スタイルなど大規模なカタログ作成でOutputフォルダがほぼ重複したファイルで溢れるのを防げる。特定のスタイルでカタログへのコピー保存自体に失敗した場合、そのOutputファイルは削除されずそのまま残る",
|
||||
helpGen27: "Inputタブ → Imageサブパネル — 各LoadImageカードにApply(変更なし)・Clear・Placeholderの3ボタンを追加。Clearはそのカードの保留中の選択・プレビューを空に戻す(LoadImageは常に有効なファイル名が必須なため、ワークフローノード自体には触れない)。パネル上部の「Placeholder Image」セクション(使用頻度が低い機能のためデフォルトで折りたたみ、クリックで展開)で共通のデフォルトを設定できる:Colorモード(幅・高さ・色を指定し、その場で単色PNGを生成)またはImageモード(デフォルト画像を1枚ドロップし、そのまま再利用)。各カード自身のPlaceholderボタンを押すと、そのカードの画像だけを設定済みデフォルトへ即座に差し替える(別途Applyクリック不要)— LoadImageが複数ある場合も個別に差し替え可能。Placeholder設定(モード・サイズ・色・デフォルト画像)はセッションをまたいで記憶される",
|
||||
helpGen3: "5タブ構成 — Input(プロンプト+画像)、Model、Settings、Feeder、Batch — Input/Model/SettingsタブにはRaw JSON列を常時表示",
|
||||
helpGen4: "Inputタブ:Prompt・Imageの内部タブ切り替え;PromptタブにはPositive Prompt・Negative Promptに加え最下部にEmbeddingsセレクタを表示(Filter+セレクト+Weight入力+Pasteボタン)— Pasteは最後にフォーカスしたテキストエリアのカーソル位置に(embedding:Name:weight)を挿入(未フォーカス時はPositiveに追加);各Applyボタンの左隣の↺ボタンはテキストエリアをノードの現在の適用値に戻す;テキストを選択(または単語・括弧内にカーソルを置くだけでも可)してCtrl+↑/↓を押すと(text:weight)形式で強調weightを±0.05単位で調整(weightが1.0に戻ると括弧を自動解除)",
|
||||
helpGen5: "Modelタブ:Checkpoint/VAE/LoRA(Single/Stackタブ)/ControlNet/Diffusion Model(UNETLoader / UnetLoaderGGUF / LoaderGGUF対応)/Text Encoder(CLIPLoader / DualCLIPLoader / ClipLoaderGGUF / DualClipLoaderGGUF対応 — typeおよびdevice選択付き、DualCLIPは2段モデル選択)/Hypernetwork(Strength入力付き)のセレクタ(フィルタ検索付き)",
|
||||
helpGen5: "Modelタブ:Checkpoint/VAE/Diffusion Model(UNETLoader / UnetLoaderGGUF / LoaderGGUF対応)/Text Encoder(CLIPLoader / DualCLIPLoader / ClipLoaderGGUF / DualClipLoaderGGUF対応 — typeおよびdevice選択付き、DualCLIPは2段モデル選択)は常時表示;ControlNetとHypernetwork(Strength入力付き)は使用頻度が低いためデフォルトで折りたたみ — 見出しをクリックで展開;LoRA(Single/Stackタブ)は右側に独立した列を表示;すべてのセレクタにフィルタ検索付き;LoRA Stack — Applyで有効な全LoRAを対象ノードに書き込み、同時にLoRA構文とCivitAIトリガーワードをPositiveプロンプトへ挿入;再Applyでは非アクティブなLoRAを削除し、アクティブなLoRAを再追加してプロンプトを更新",
|
||||
helpGen28: "Modelタブ — ハイライト色:読み込んだワークフローに実際に該当ノードが含まれる場合、各モデル種別(Checkpoint/VAE/Diffusion Model/Text Encoder/ControlNet/Hypernetwork)のラベルとLoRA列見出しが指定色(デフォルトは明るい緑)で表示される;ControlNet/Hypernetworkが折りたたまれた状態でも色は見えるため、展開しなくても使用有無が一目で分かる;色はSettingsタブでカスタマイズ可能",
|
||||
helpGen6: "Settingsタブ:KSamplerとLatent Imageを横並び(各50%幅)",
|
||||
helpGen7: "Raw JSONを各タブの右列に常時表示 — 直接編集してApplyでワークフロー即時反映;読み込んだワークフローにBypass/Muteノードがある場合、検索バー上部に一覧が表示される(Bypassは除外され配線が再接続される、Muteは除外されるが再接続はされない点はComfyUI本体と同じ)",
|
||||
helpGen8: "シード管理:ランダム / 固定 / 増加 / 減少",
|
||||
@@ -1848,6 +2029,11 @@ const LANGUAGES = {
|
||||
helpGen17: "スタイルバッチ:左ペインのStyleタブでスタイルを選択し、バッチキューのStyle列を有効化してGenerateを実行 — 選択した各スタイルをPositiveおよびNegativeプロンプトに順番に適用;ワークフローコピーに適用されるため読み込み済みワークフローは変更されない;スタイルファイルはページロードのたびに user/default/Workflow-Studio/style/*.json から再読み込み",
|
||||
helpGen18: "Applyボタンを Alt+Click すると Apply & Generate を1操作で実行 — 対象:Positive Prompt・Checkpoint・KSamplerの各Applyボタン;ワークフローに値を書き込んだ後、即座に生成をキューに追加;対象ノードが存在しない場合は何もしない",
|
||||
helpGen19: "Loraバッチ:各LoRA適用時にLora構文(<lora:名前:strength_model:strength_clip>)とCivitAIトリガーワードをPositiveプロンプトへ自動追加 — 毎回元のプロンプトを起点に再構築するため蓄積しない;バッチ完了・停止後はプロンプトを開始前の状態へ自動復元;選択したLoRAがComfyUIのモデル一覧にまだ認識されていない場合は警告トーストを表示(ComfyUIのRefreshまたは再起動が必要)",
|
||||
helpGen20: "LoRAの接続方式は2通り:標準の LoraLoader ノードをチェーン接続する方式(1ノードにつき1LoRA — 増やすにはノードを追加接続)と、単一の Lora Loader (LoraManager) ノード(ComfyUI-Lora-Manager由来のカスタムノード)にLoRA一覧を内部保持する方式(各LoRAごとに有効/モデル強度/CLIP強度を個別管理);下のSingle/Stackタブは対象ノードがどちらのタイプかによって自動的に挙動が変わる",
|
||||
helpGen21: "Singleタブ:LoRAを1つ選びStr M/Str Cを設定してApply — Lora Managerノードが対象の場合、内部のLoRA一覧を丸ごとこの1件だけに置き換え、既存の他のLoRAは失われる",
|
||||
helpGen22: "Stackタブ — Use Stack Groupチェックボックス(ワークフロー内にLora Managerノードがある場合のみ表示):OFF(ワークフロー読み込み時の既定)はLora Managerノードに実際に設定されているLoRAをそのまま表示・編集;ONにするとModelsタブに登録済みの「Stack」グループを表示・編集;どちらへの切替もまずノードのLoRA一覧をクリアしてから切替先のソースを読み込む;OFFへ戻すとワークフロー読み込み時点のLoRA一覧(読み込み時にスナップショットとして保存済み)へ正確に復元される",
|
||||
helpGen23: "Stackタブの操作:各行に有効チェックボックスとStr M / Str Cフィールド;ヘッダーの「Stack」チェックボックスで全行を一括切替;上部の+/-ステップボタンで現在有効な全行の強度をまとめて増減;「Showing: LoRAs currently in workflow」/「Showing: registered Stack group」のラベルで現在どちらのソースを表示中か分かる;Applyで対象ノードへ一覧全体を書き込み、同時にLoRA構文とCivitAIトリガーワードをPositiveプロンプトへ追加",
|
||||
helpGen24: "CLIP Text Encode edit+(CLIPTextEncodeEditPlus)ノードを使う場合の注意:Lora Managerノードのtrigger_words出力がこのノードのtext1入力に接続されている構成(RAW/EDIT/front/backモードでtext1と編集可能なtext_editを結合)では、生成時にトリガーワードは既に自動的に反映済み;LoRAのApplyボタンをクリックしたりUse Stack GroupをONにしたりすると、LoRA構文・トリガーワードがtext_editへも追加で書き込まれ二重になる — ワークフロー本来のプロンプト・LoRA構成を変更せず維持したい場合は、Use Stack GroupをOFFのままにしLoRAのApply系ボタンには触れないこと",
|
||||
helpFeederTitle: "GenerateUI Tab — Feeder サブタブ",
|
||||
helpFeederDesc: "左ペイン上部の [Image Loop] / [Gallery] トグルで2つのモードを切り替えられます。",
|
||||
helpFeederImgloopTitle: "Image Loop モード",
|
||||
@@ -1876,20 +2062,28 @@ const LANGUAGES = {
|
||||
helpLab1: "左ペイン — Image:I2Iの元になる画像をドロップまたはクリックして選択します。ComfyUIのinputフォルダにアップロードされ、「Use generated image for next」がオフの間は毎回この画像が使われます",
|
||||
helpLab2: "左ペイン — Use generated image for next:オンにすると2回目以降、直前の回で生成された1枚目の画像を次のI2I入力として使用します(1回目は常に元画像を使用)",
|
||||
helpLab3: "中央ペイン — Checkpoint・VAE・Prompt・KSamplerの4列は独立しています。共通の行グリッドではなく、列ごとに個別のキーフレーム(設定変更点)のリストを持ちます",
|
||||
helpLab4: "各列の+/-:+は次に空いている回数目(Batch数まで)にキーフレームを追加し、すぐに編集モーダルを開きます。-は末尾のキーフレームを削除します(1回目は削除できません)",
|
||||
helpLab4: "各列の+/-:+は次に空いている回数目(Batch数まで)にキーフレームを追加し、すぐに編集モーダルを開きます。-は末尾のキーフレームを削除します(1回目は削除できません)。1回目以外のキーフレームは、末尾でなくてもそれぞれの編集モーダル内の「削除」ボタンから個別に削除できます",
|
||||
helpLab5: "セルをクリックすると編集できます。1回目は基準となる設定値です(空欄のままにするとワークフロー本来の設定を使用)。2回目以降はさらに「何回目から適用するか」の指定と「1回目の設定に戻す」チェックボックスがあります",
|
||||
helpLab6: "N回目時点での実効値は、N以下で最も大きい回数目のキーフレームが次のキーフレームまで引き継がれます。「1回目に戻す」を使うと、新しい値を指定する代わりに1回目の値(空欄ならワークフロー本来の設定)がそのまま使われます",
|
||||
helpLab6: "N回目時点での実効値は、N以下で最も大きい回数目のキーフレームが次のキーフレームまで引き継がれます。「1回目に戻す」を使うと、新しい値を指定する代わりに1回目の値(空欄ならワークフロー本来の設定)がそのまま使われます。既存キーフレームの回数目より小さくBatch数を減らしても(手入力・プラン読込/適用いずれの場合も)、そのキーフレームは削除・繰り上げされず警告トーストが表示されるだけで、Batch数を再び増やすまで実行ループに到達しない「休眠」状態になります",
|
||||
helpLab7: "LabはInput/Model/Settingsに表示されているワークフローを直接編集しません。各回の実行はワークフローの複製に対して行われるため、Labでのキーフレーム設定が他のサブタブに影響することはありません",
|
||||
helpLab8: "Promptセル編集モーダルの追加機能:「Get from GenerateUI」で現在GenerateUIに読み込まれているワークフローからPositive/Negativeを取得、「Get from Image」でLab左ペインのIMAGEに現在読み込まれている画像からプロンプトを抽出(Metadataタブと同じ検出ロジック。別途ファイル選択は不要)、「Style」でGenerateUIツールバー上部のStyleチェックボックス/ドロップダウンで現在選択されているスタイルを、既存のPositive/Negativeテキストを消さずにカンマ区切りで追記(先に上部でチェックボックスをオンにしスタイルを選択しておく必要あり。Lab独自のスタイル選択はありません)",
|
||||
helpLab8: "Promptセル編集モーダルの追加機能:「Get from GenerateUI」で現在GenerateUIに読み込まれているワークフローからPositive/Negativeを取得、「Get from Image」でLab左ペインのIMAGEに現在読み込まれている画像からプロンプトを抽出(Metadataタブと同じ検出ロジック。別途ファイル選択は不要)、「Style」行の「適用」ボタンをクリックするとGenerateUIツールバー上部のStyleドロップダウンで現在選択されているスタイル名を、既存のPositive/Negativeテキストを消さずにカンマ区切りで追記し、Styleチェックボックスを自動でONにして適用したスタイル名をボタンではなく横に別表示します(スタイル名の選択は上部ドロップダウンのみを使用し、Lab独自のスタイル選択はありません。適用ボタンは上部のStyle有効化チェックボックスの状態に関係なく動作します)。Styleチェックボックスを手動でOFFにすると名前表示のみクリアされます(追記済みのPositive/Negativeテキストは自動削除されないため、不要な場合は手動で編集・削除してください)",
|
||||
helpLab9: "左ペイン — 「T2I workflow (no source image)」:読み込んでいるワークフローがT2I(LoadImageノードなし)の場合にオンにします。「先に元になる画像をドロップしてください」という要求をスキップし、ドロップ済みの画像があっても無視します。Checkpoint/VAE/Prompt/KSamplerのキーフレームは通常どおり適用されます。オンの間はImageドロップ領域と「Use generated image for next」がグレーアウトします(既にドロップ済みの画像は削除されず、I2Iに戻したときのために保持されます)。この設定はプランに t2i_mode として保存されます",
|
||||
helpLab10: "ワイルドカード:Promptカラムのキーフレームに入力するPositive/Negativeテキストは、通常のGenerateUIと同じA1111形式の __name__ 記法に対応しています。各キーフレームのテキストは、そのイテレーションが実行される直前に毎回展開されるため、同じキーフレームを使い回していてもイテレーションごとに異なるランダム行が選ばれます",
|
||||
helpLab11: "プロンプトセルの編集モーダルにはClear(Positive/Negative両方を空にする)とGet from Previous(同じカラムの直前のキーフレームからPositive/Negative両方をコピー — 例:#3を編集中に押すと#2のプロンプトをそのままコピー)も用意されています。1回目(#1)には直前の行が無いため表示されません",
|
||||
helpLab12: "各カラムの1回目(キーフレーム#1)は、明示的に上書き保存されていない間、現在GenerateUIで読み込まれているワークフロー本来の設定(Checkpoint・VAE・Prompt・KSampler)を、空欄プレースホルダの代わりにグリッドセル(破線枠)と編集モーダルの両方に表示します。何も変更せずに保存しただけでも実際の上書き値として確定し、破線・ライブ表示は解除されます。Labサブタブに切り替えるたびに、その時点でGenerateUIに読み込まれている内容へ再同期されます",
|
||||
helpLab13: "Bypassチェックボックス(1回目を含む全キーフレームに搭載):そのキーフレームの回数目判定において、行自体が存在しないかのように完全にスキップします — その結果、直前まで有効だった設定(それ以前のキーフレーム、なければ何も適用されない状態)がそのまま使われ続けます。Labタブ内だけの概念で、実際のComfyUIノードのmodeには一切触れません。チェック中はその行の値フィールドと「1回目に戻す」チェックボックスが無効化されます(両者は同時に使えない排他的な関係)。セルには琥珀色の「⏭ Bypassed」ラベルが表示され、Revert表示・ライブ表示のどちらよりも優先されます",
|
||||
helpLabCardPlanTitle: "Settingサブタブ — 実行とプランファイル",
|
||||
helpLabPlan1: "右ペイン — Batch:実行する回数。Note:プランと一緒に保存される自由記述のメモ",
|
||||
helpLabPlan2: "Run/Pause/Cancel:Runでバッチループを開始、Pause/Resumeで回と回の間を一時停止・再開、Cancelで現在の生成を中断してループを止めます",
|
||||
helpLabPlan3: "Plan SaveとSave Asの違い:Plan Saveは読込済みのプランがあればダイアログなしで上書き保存します(未読込の場合のみ名前を確認)。Save Asはプラン読込中でも常に新しい名前を確認します",
|
||||
helpLabPlan4: "Plan Load:プランの.jsonファイル、またはそのインデックス画像(.png)をPLAN欄にドロップします(クリックでファイル選択も可)。.jsonをドロップした場合はそのまま読み込み、.pngをドロップした場合は同名の.jsonをサーバーから取得します",
|
||||
helpLabPlan4: "Plan Load:プランの.jsonファイル、またはそのインデックス画像(.png)をPLAN欄にドロップします(クリックでファイル選択も可)。.jsonをドロップした場合はそのまま読み込みます。.pngをドロップした場合も、v0.3.90以降のインデックス画像であればwfm_lab_planチャンクに埋め込まれたプランデータを直接読み込みます。それより古いインデックス画像の場合のみ、同名の.jsonをサーバーから取得するフォールバック動作になります",
|
||||
helpLabPlan5: "Plan ClearはSettingタブの内容を空のプランにリセットします(確認あり)",
|
||||
helpLabPlan6: "プランファイルは user/default/Workflow-Studio/lab_plan/ に <名前>.json として保存され、結果がある場合は最大9枚(1行3枚)のサムネイルを並べたインデックス画像 <名前>.png も自動生成されます",
|
||||
helpLabPlan6: "プランファイルは user/default/Workflow-Studio/lab_plan/ に ws_labplan_<名前>.json として保存され、結果がある場合は最大9枚(1行3枚)のサムネイルを並べたインデックス画像 ws_labplan_<名前>.png も自動生成されます。ws_labplan_ の接頭辞はPlan Save/Save Asが自動的に付与するため、プロンプトには接頭辞なしの名前だけを入力すればよく、フォルダ内でプランファイルを見分けやすくなります",
|
||||
helpLabPlan7: "設定タブで構成したEagle自動保存は、GenerateUI本来のGenerateボタンと同様にLabで生成したすべての画像に適用されます",
|
||||
helpLabPlan8: "Plan JSONサブタブ:現在のSettingタブのプラン内容をそのままJSONで表示します。「Refresh」でSettingタブの現在の内容から再読込(未適用の編集は破棄)、「Apply to Setting」で編集内容を解析しSettingタブへ書き戻します(列・メモ・Batch数・画像連鎖・元画像・結果)。保存せずにそのままプランファイルとして読み込んだのと同じ効果があります",
|
||||
helpLabPlan9: "保存されたプランには、保存時にGenerateUIで読み込まれていたワークフローのファイル名が記録されます(Plan JSON内のworkflow_filename)。プランを読み込むとPLANボックスに「Open Workflow」ボタンが表示され、クリックするとその記録された正確なワークフローファイルをGenerateUIへ読み込み直せます(現在読み込まれているワークフローを置き換えるため、確認が入ります)",
|
||||
helpLabPlan10: "右ペイン — 「Save index image to Output on Run」:チェックすると、Run実行が終わるたびにPlanファイル用と同じコンタクトシート形式のインデックス画像を作成し、ComfyUI本来のOutputフォルダへ Lab_index_<counter>_.png として直接保存します(通常の生成画像と同様に自動採番され、前回の実行結果を上書きしません)。保存後は他のLab生成画像と同様にEagle自動保存(設定タブで有効な場合)にも渡されます——これ専用のチェックボックスはなく、同じ設定タブのグローバルなトグルに従います。Plan Saveの動作とは独立しており、Plan Saveは常にこのチェックボックスに関係なく lab_plan/ 内のプランファイルの隣に自分専用のインデックス画像を書き込みます。この設定はプランに save_index_on_run として保存されます",
|
||||
helpLabPlan11: "全てのインデックス画像PNG(Plan Save/Save Asで作成されたものも、Save index image to Output on Runで作成されたものも)には、プラン全体(列・メモ・Batch数・画像連鎖/T2I設定・ワークフローファイル名・結果一覧)がPNGのwfm_lab_planチャンクとして直接埋め込まれています。そのためOutputフォルダ側のコピーは単体で完結しており、隣に対応する.jsonが一切存在しなくてもPlan Loadの読込元として使えます",
|
||||
helpLabCardResultsTitle: "Resultsサブタブ",
|
||||
helpLabResults1: "左ペインには実行に使用した元画像が表示されます",
|
||||
helpLabResults2: "中央ペインには生成順に最大9枚の画像が表示されます。サムネイルをクリックすると拡大表示されます",
|
||||
@@ -1905,6 +2099,11 @@ const LANGUAGES = {
|
||||
helpPrompt7: "GenUI Set:プリセットのプロンプトをGenerateUIに直接適用",
|
||||
helpPrompt8: "ワイルドカードツールバー:{|}・{n$|}・__|__・<lora:>などの構文をワンクリック挿入。選択テキストのラップも対応",
|
||||
helpPrompt9: "ワイルドカードファイルマネージャー:.txt/.yamlファイルの作成・編集・削除。ファイル名をクリックすると__ファイル名__をカーソル位置に挿入",
|
||||
helpPrompt10: "右ペインのWildcard/Styleタブバーで、パネル全体をワイルドカードツールとこのStyle管理の2モード間で切り替える(同じ右ペインを共用)",
|
||||
helpPrompt11: "登録済みStyle(GenerateUIのStyleドロップダウン・Batchタブ・Style Catalogで使われるものと同一)の作成・編集・削除。リストの名前をクリックすると編集、「+ New」で空の新規エントリを作成。項目はName・Positive prompt({prompt}プレースホルダー対応 — ユーザー自身のプロンプトに置き換わる、省略時はその後ろに追加される)・Negative prompt(省略可)",
|
||||
helpPrompt12: "リネームしても、元々定義されていたファイル内での位置は保たれる。新規作成したStyleはstyleフォルダ内の専用custom.jsonへ保存されるため、同梱のスタイルパックファイルは直接変更されない。名前は全スタイル中で一意である必要がある",
|
||||
helpPrompt13: "Styleの保存・リネーム・削除は、GenerateUIのStyleドロップダウン、Batchタブのスタイルチェックリスト、Style Catalogの名前一覧に即座に反映される(再読み込み不要)",
|
||||
helpPrompt14: "一覧の各項目には、名前の横に定義元ファイル名が小さなバッジで表示される(例: sdxl_styles_diva.json)。既存スタイルを編集中は、そのファイル名がPositive promptフィールドの上にも表示され、Saveの隣に「+ Add to this file」ボタンが現れる。クリックするとフォームが空になり、デフォルトのcustom.jsonではなく同じファイルへ追加される新規スタイルを作成できる",
|
||||
helpSettings1: "UI言語と要約言語の設定",
|
||||
helpSettings2: "テーマ選択(13種プリセット)+カスタマイズ:カラー調整、背景パターン(ストライプ、ポルカドット、チェック、SVGタイリング)、フォント選択(日本語デザインフォント含む16種のGoogle Fonts)",
|
||||
helpSettings3: "ワークフローデータフォルダのパス変更・リセット",
|
||||
@@ -1918,6 +2117,7 @@ const LANGUAGES = {
|
||||
helpSettings11: "テキストサイズ:スライダー1本(10〜28px)でプロンプト・チャット全テキストエリアのフォントサイズを一括調整 — GenerateUI ポジティブ/ネガティブプロンプト、AIアシスタントチャット入力、プリセット ポジティブ/ネガティブ、ワイルドカードプロンプト・ファイルエディタ、メタデータプロンプト全文プレビュー;即時反映・保存で確定",
|
||||
helpSettings12: "RAW JSON カラー:GenerateUI の Raw JSON エディタの構文ハイライト色(6色)をカスタマイズ — デフォルトテキスト・名前/スケジューラー・タイトル・幅/高さ・プロンプト/テキスト・画像/ファイル;カラーピッカーで即時反映;「デフォルトにリセット」で元の配色に戻す",
|
||||
helpSettings13: "CivitAI ホスト:civitai.com(SFWのみ)と civitai.red(制限なし)を切り替え — ModelsタブのCivitAIパネルでモデルリンクをクリックしたときに開くサイトを指定",
|
||||
helpSettings14: "GenerateUI Modelタブ ハイライト色:GenerateUIのModelタブで、読み込んだワークフローに実際に該当ノードが含まれる場合にCheckpoint/VAE/Diffusion Model/Text Encoder/ControlNet/Hypernetworkのラベルおよび LoRA 列見出しを彩色する色を指定;デフォルトは明るい緑;変更は即時反映、「デフォルトにリセット」で元に戻す",
|
||||
helpNodes1: "ノードブラウザ:名前/説明/エイリアス/タグで検索、カテゴリ・パッケージ・タグ・グループ・お気に入りフィルタ",
|
||||
helpNodes2: "カード / テーブル表示モード切り替え(ページネーション付き)",
|
||||
helpNodes3: "ノードのお気に入り登録、カスタムタグの追加で整理",
|
||||
@@ -1955,6 +2155,13 @@ const LANGUAGES = {
|
||||
helpGallery15: "Fボタン(シアン色オーバーレイ、各サムネイル左上):クリック一つで画像を __Feeder__ グループに追加/削除;グループ内の場合は常にシアン色で表示、非グループ時はホバー時のみ表示;FeederタブのGalleryモードへ素早く画像を追加できる",
|
||||
helpGallery16: "Image Editボタン(ツールバー、Refreshボタン横):選択中の画像をImage Editタブに送信;既にレイヤーが存在する場合はキャンバスに合わせてスケールして新規レイヤーとして追加、存在しない場合はLayer 1になる",
|
||||
helpGallery17: "Send GenUI Imageボタン(ツールバー、Image Editボタン横):選択画像をComfyUIにアップロードし、GenerateUIタブの最初のLoadImageノードへ入力として設定;GenerateUI → Input → Imageへ自動切り替え;事前にLoadImageノードを含むワークフローの読み込みが必要",
|
||||
helpGallery18: "GalleryタブのOutputと並ぶ2つ目のサブタブ。視覚的なプロンプトライブラリを閲覧できる — ComfyUI outputフォルダ内のws_image_promptフォルダを管理(未作成時は自動生成)",
|
||||
helpGallery19: "同じ3カラムレイアウト:フォルダツリー(左)|サムネイル一覧(中央)|プロンプトビルダー(右)。サムネイルクリックでプレビューとプロンプトテキストを表示 — この時点ではまだプロンプトに追加されない",
|
||||
helpGallery20: "「+ 追加」で、プレビュー中の画像のプロンプトを「選択済みプロンプト」にチップとして追加;チップは個別(×)または一括(「全クリア」)で削除可能;「Save」でその画像のプロンプトテキストを編集・保存",
|
||||
helpGallery21: "「最終プロンプト」は全チップをカンマ区切りで結合したテキスト(自由に編集も可能);「Copy」でクリップボードへコピー。プロンプトは各画像と同名の.txtファイルとして保存されるため、サブフォルダに画像+対応する.txtファイルを置くだけで誰でも自作データを追加できる",
|
||||
helpGallery22: "Galleryタブ先頭にある3つ目のサブタブ。登録済みStyleをプレビュー画像から視覚的に選べる — ComfyUI outputフォルダ内のws_style_catalogフォルダを管理(未作成時は自動生成)。GenerateUIタブの「カタログ作成」ボタンで生成される(GenerateUIタブのヘルプ参照)",
|
||||
helpGallery23: "同じ3カラムレイアウト:フォルダツリー(左)|サムネイル一覧(中央)|Positive/Negativeプロンプトパネル(右)。サムネイルクリックで、その生成画像に実際に埋め込まれているPositive/Negativeプロンプトを表示、それぞれ個別のCopyボタン付き",
|
||||
helpGallery24: "Select as Styleボタン:選択中の画像のファイル名(拡張子除く)と同名の登録済みStyleを探し、GenerateUIタブのStyleドロップダウンをそれに切り替える — 既存Styleシステムへの視覚的なショートカットであり、埋め込みプロンプトをその場限りで適用するものではない(カタログ画像作成後にStyleがリネーム・削除されていた場合は「一致するスタイルが見つかりません」トーストを表示)",
|
||||
|
||||
// -- Tagger Tab --
|
||||
helpTaggerTitle: "Taggerタブ",
|
||||
@@ -1984,14 +2191,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 ツール):翻訳・Chat・TOOLS・設定のサブタブ;Chat は LLM とのマルチターン会話;TOOLS は VLM 画像解析とワイルドカード生成に対応;設定は SPA の AI タブと localStorage で共有される",
|
||||
helpSidepanel16: "A タブ(AI ツール):翻訳・Chat・TOOLS・設定のサブタブ。Ollama、LM Studio、Lemonade、Unsloth に対応;Chat は LLM とのマルチターン会話;TOOLS は VLM 画像解析とワイルドカード生成に対応;設定は SPA の AI タブと localStorage で共有される",
|
||||
helpSidepanel17: "Send to Canvas:WorkflowタブのSend to CanvasまたはGalleryタブのCopy & Send Canvasをクリックするとワークフローをキャンバスへ直接送信(UI形式・API形式どちらも対応);ComfyUIのツールバーから開いていない場合はUI形式のみタイトルドラッグのフォールバック(タイトルが青くなり緑の●が表示される — ドラッグで読み込み)",
|
||||
helpAiTitle: "AI タブ(A)",
|
||||
helpAi1: "4ペインレイアウト — Translation | Chat | TOOLS | Settings — 全ペインが常時表示される",
|
||||
helpAi2: "翻訳ペイン:Ollama、LM Studio、または Lemonade を使って日本語・英語・中国語・カスタム言語(Free)間でテキストを翻訳;⇄ ボタンで言語とテキストを同時入替;選択は自動保存",
|
||||
helpAi2: "翻訳ペイン:Ollama、LM Studio、Lemonade、または Unsloth を使って日本語・英語・中国語・カスタム言語(Free)間でテキストを翻訳;⇄ ボタンで言語とテキストを同時入替;選択は自動保存",
|
||||
helpAi3: "Chat ペイン:LLM とのマルチターン会話;Enter で送信、Shift+Enter で改行;Clear ボタンで会話履歴をリセット;モデルがtool callingに対応している場合、「猫の画像を作って」のように頼むとGenerateUIに読み込み中のワークフローで生成を実行し、結果をチャット内に表示する;ペインヘッダーの「画像生成を許可する」チェックボックスでこの機能のON/OFFを切り替えられる;画像が添付されている場合(TOOLSペインにドロップした画像)はLLMにもビジョン入力として送信され、generate_image呼び出し時はT2Iの代わりにI2I(image-to-image)の元画像として使われる;tool callingとビジョンの動作を確認済みのモデル: Gemma 4:e4b、Qwen 3.5:9b、Ministral 3:3b(Ollama)",
|
||||
helpAi4: "TOOLS ペイン — VLM:画像(PNG/JPG/WebP)をドロップしてタスク(画像解説 / プロンプト作成 / タグ作成)を選んで Run;または「Create wildcards」を選んでカテゴリ名と件数を入力すると1行1エントリのワイルドカードを生成;ドロップした画像はChatペインの添付としても共有され(Chat側にも表示、I2I生成に使用)、✕ボタンでクリアするまで保持される",
|
||||
helpAi6: "Settings ペイン:バックエンド(Ollama / LM Studio / Lemonade)の選択、APIのURL設定、接続テスト、モデル選択、Free言語名の設定;Chat Image Generationセクションでは、ChatからのT2I画像生成にGenerateUIの現在の読み込みワークフローの代わりに専用ワークフローを使うよう設定できる;Chat I2I Generationセクションは同様の設定を画像添付時のI2I生成向けに提供する;設定は localStorage に保存され、Library パネルの A タブと共有される",
|
||||
helpAi6: "Settings ペイン:バックエンド(Ollama / LM Studio / Lemonade / Unsloth)の選択、APIのURL設定、接続テスト、モデル選択;Unslothはローカルアクセスでも常にAPIキー認証が必須——プラグインフォルダの .env.example を .env にコピーして UNSLOTH_API_KEY を設定し ComfyUI を再起動する(キーはサーバー側でのみ読み込まれ、ブラウザには一切送信されない);Unsloth Desktopアプリ側の設定画面で「モデル自動切り替え (OpenAI API)」もONにする必要がある——OFFのままだと、Unsloth Studio上で事前にモデルを手動ロードしていない限り HTTP 404 で接続に失敗する;Unslothのreasoningモデルは思考内容をインラインの<think>タグではなく別のreasoning_contentフィールドで返すため、Max tokensが少ないとモデルが思考だけでトークンを使い切り、空の返信になることがある——返信が空になる場合はMax tokensを増やす(2048以上を推奨);Generationセクション — Thinking modeトグル(デフォルトOFF;OllamaにはthinkフラグとしてOFF/ONを送信、バックエンドを問わずOFF時は出力中の<think>...</think>ブロックをクライアント側で除去するため、推論モデルの思考過程がTranslation/Chat/TOOLSの結果に混入しない)とMax tokens(Ollama: num_predict、LM Studio/Lemonade/Unsloth: max_tokens;0で無制限);Free言語名の設定;Chat Image Generationセクションでは、ChatからのT2I画像生成にGenerateUIの現在の読み込みワークフローの代わりに専用ワークフローを使うよう設定できる;Chat I2I Generationセクションは同様の設定を画像添付時のI2I生成向けに提供する;設定は localStorage に保存され、Library パネルの A タブと共有される",
|
||||
helpAi7: "Chat ペイン — SVG:LLMはComfyUIワークフローを一切使わず、SVGグラフィックをテキストとして直接生成することもできる;「SVGで〜を描いて」のように頼み、応答にSVGコードが含まれていれば自動でインラインプレビュー表示され、「Galleryに保存」ボタンでGalleryタブの出力フォルダに.svgファイルとして保存できる;tool calling(function calling)を使用しないため、tool calling非対応のモデルでも動作する",
|
||||
helpAi8: "Chat ペイン — スキル:メッセージ一覧上部のドロップダウンでスキルを選ぶと、その指示内容が system prompt として会話の先頭に付加される(表示上のチャット履歴には含まれない);鉛筆ボタンでスキル管理パネルを開き、.mdスキルファイルを作成・編集・削除できる(保存先: user/default/Workflow-Studio/ai_skills/);ファイル先頭の---で囲まれた部分にname/descriptionを書くとドロップダウンの表示に反映される;初期状態で2つのスキルを同梱: 「SVG Icon Generator」(描く前に対象を部位分解することで認識しやすいSVGを生成)と「Skill Creator」(対話形式で質問しながら新しいスキルファイルを下書きする);応答に```skillコードブロックが含まれる場合、メッセージ下部に「スキルとして保存」ボタンが表示され、内容が入った状態で管理パネルが開く",
|
||||
helpAi9: "スキル作成のヒント:ドロップダウンやツールチップで分かりやすいよう、frontmatterのname/descriptionは明確に書く;期待する出力形式を具体的に指示し、SVGや別のスキルファイルのように後で抽出したい成果物がある場合は専用のコードフェンスで囲むよう指示する;曖昧な指示より具体的で命令形の指示の方がローカルの小型モデルには効きやすく、短い実例を1つ添えるとさらに効果的;禁止事項(不適切な内容、セキュリティ、文字数制限など)は暗黙に期待せず明示的に書く;迷ったらドロップダウンで「Skill Creator」スキルを選び、作りたいスキルの概要を伝えれば対話形式で下書きしてくれる",
|
||||
@@ -2015,10 +2222,12 @@ const LANGUAGES = {
|
||||
helpGenCardSeed: "シード・生成",
|
||||
helpGenCardBatchSetup: "Batchタブ — セットアップ",
|
||||
helpGenCardBatchTypes: "Batchタブ — バッチ種別",
|
||||
helpGenCardLora: "Modelタブ — LoRA詳細",
|
||||
helpPromptTitle: "プロンプトタブ",
|
||||
helpPromptCardAi: "AIアシスタント・翻訳",
|
||||
helpPromptCardPresets: "プリセット",
|
||||
helpPromptCardWildcards: "ワイルドカード",
|
||||
helpPromptCardStyleTitle: "Style",
|
||||
helpMetadataCardOverview: "概要",
|
||||
helpMetadataCardExtracted: "抽出情報",
|
||||
helpMetadataCardFormats: "対応フォーマット",
|
||||
@@ -2033,6 +2242,8 @@ const LANGUAGES = {
|
||||
helpNodesCardGroups: "グループ・セット",
|
||||
helpNodesCardPanel: "サイドパネル・複数選択",
|
||||
helpGalleryCardBrowse: "閲覧",
|
||||
helpGalleryCardStyleprompt: "ImagePrompt ギャラリー",
|
||||
helpGalleryCardStylecatalog: "Style_Catalog ギャラリー",
|
||||
helpGalleryCardFolder: "フォルダ・選択",
|
||||
helpGalleryCardDetail: "詳細パネル",
|
||||
helpGalleryCardActions: "アクションツールバー",
|
||||
@@ -2442,6 +2653,7 @@ const LANGUAGES = {
|
||||
saveWorkflowTitle: "保存工作流",
|
||||
filenameLabel: "文件名",
|
||||
pleaseEnterFilename: "请输入文件名",
|
||||
pleaseEnterStyleName: "请输入风格名称",
|
||||
saveFailed: (msg) => msg ? `保存失败: ${msg}` : "保存失败",
|
||||
savedAs: (f) => `已保存: ${f}`,
|
||||
overwriteConfirm: (f) => `「${f}」已存在。要覆盖吗?`,
|
||||
@@ -2510,16 +2722,30 @@ const LANGUAGES = {
|
||||
batchStopped: (completed, failed) => `批处理已停止 — 完成${completed}个,失败${failed}个`,
|
||||
batchComplete: (completed, total, failed) => failed > 0 ? `批处理完成: ${completed}/${total}个 (${failed}个失败)` : `批处理完成: ${completed}/${total}个`,
|
||||
batchLoraMissing: (count, total, sample) => `所选LoRA中有${count}/${total}个尚未被ComfyUI识别(例如:${sample})。请在ComfyUI中点击Refresh或重启服务器后再试。`,
|
||||
catalogCreateBtn: "创建目录",
|
||||
catalogOpenBtn: "目录",
|
||||
catalogCreateTitle: "创建风格目录",
|
||||
catalogCreateNoStyles: "未选择风格 — 请先在Batch标签的Style子标签中选择风格",
|
||||
catalogCreateSelectedCount: (n) => `已选择${n}个风格`,
|
||||
catalogCreateNewFolder: "创建新文件夹",
|
||||
catalogCreateExistingFolder: "使用现有文件夹",
|
||||
catalogCreateRun: "运行",
|
||||
catalogCreateFolderNameRequired: "请输入文件夹名称",
|
||||
catalogCreateFolderRequired: "请选择目标文件夹",
|
||||
catalogCreateSkipOutput: "不在Output文件夹中保留副本",
|
||||
|
||||
// -- Lab 标签页 --
|
||||
labImageUploaded: (name) => `图片已上传: ${name}`,
|
||||
labUploadFailed: "上传失败",
|
||||
labBatchCountTooSmall: "请先增加Batch数量再添加关键帧",
|
||||
labKeyframesExceedBatch: (maxIter, batchCount) => `存在设置到第${maxIter}次的关键帧,超过了当前Batch数量(${batchCount}),在增加Batch数量之前不会被应用`,
|
||||
labUseWorkflowDefault: "(保持工作流原设置)",
|
||||
labAppliedAt: (n) => `应用:${n}`,
|
||||
labRevertToBase: "↩ 恢复第1次的设置",
|
||||
labApplyFromIteration: "从第几次开始应用",
|
||||
labRevertCheckboxLabel: "恢复第1次的设置",
|
||||
labBypassed: "⏭ 已跳过",
|
||||
labBypassCheckboxLabel: "跳过此设置(保持它之前生效的设置)",
|
||||
labSeedEmptyRandom: "Seed(留空为随机)",
|
||||
labPause: "暂停",
|
||||
labResume: "继续",
|
||||
@@ -2536,10 +2762,15 @@ const LANGUAGES = {
|
||||
labConfirmClear: "确定要清除所有Lab设置(图片、列、备注、结果)吗?",
|
||||
labGetFromGenUI: "从GenerateUI获取",
|
||||
labGetFromImage: "从图片获取",
|
||||
labGetFromPrevious: "从上一设置获取",
|
||||
labClearPrompt: "清除",
|
||||
labPromptCleared: "提示词已清除",
|
||||
labPromptCopiedFromPrevious: "已从上一设置复制",
|
||||
labLiveHint: "正在显示当前GenerateUI的设置。编辑并保存即可覆盖。",
|
||||
labStyle: "风格",
|
||||
labApply: "应用",
|
||||
labNoStyles: "暂无风格",
|
||||
labEnableStyleFirst: "请先在GenerateUI标签页顶部勾选Style复选框并选择一个风格",
|
||||
labEnableStyleFirst: "请先在GenerateUI标签页顶部的Style下拉菜单中选择一个风格",
|
||||
labPlanJsonRefreshed: "已根据当前Setting标签页内容刷新",
|
||||
labPlanJsonApplied: "已将Plan JSON应用到Setting",
|
||||
labPlanJsonInvalid: "JSON格式无效",
|
||||
@@ -2547,6 +2778,24 @@ const LANGUAGES = {
|
||||
labPromptFetched: "已获取提示词",
|
||||
labNoPromptInImage: "该文件中未找到提示词",
|
||||
labMetadataExtractFailed: "读取元数据失败",
|
||||
labConfirmLoadWorkflow: (filename) => `将"${filename}"加载到GenerateUI?这将替换当前已加载的工作流。`,
|
||||
labWorkflowLoadFailed: "工作流加载失败",
|
||||
labT2IImageIgnored: "T2I模式已开启,无需上传图片,已跳过",
|
||||
labIndexImageSaved: (filename) => `索引图片已保存到Output:${filename}`,
|
||||
labIndexImageSaveFailed: "索引图片保存到Output失败",
|
||||
|
||||
// -- GenerateUI标签页 Input子标签: Image内占位图 --
|
||||
i2iPlaceholderTitle: "占位图片",
|
||||
i2iPlaceholderColor: "颜色",
|
||||
i2iPlaceholderImage: "图片",
|
||||
i2iPlaceholderWidth: "宽度",
|
||||
i2iPlaceholderHeight: "高度",
|
||||
i2iPlaceholderColorLabel: "颜色",
|
||||
i2iPlaceholderDropImage: "拖放默认图片或点击选择",
|
||||
i2iPlaceholderApply: "占位图",
|
||||
i2iPlaceholderGenerating: "生成中...",
|
||||
i2iPlaceholderNoDefaultImage: "尚未设置默认图片 — 请先在上方拖入一张",
|
||||
i2iPlaceholderUploading: "上传中...",
|
||||
|
||||
connectedToComfyUI: "已连接到ComfyUI",
|
||||
failedToConnect: "连接失败",
|
||||
@@ -2574,6 +2823,9 @@ const LANGUAGES = {
|
||||
jsonColorCyan: "提示词 / 文本",
|
||||
jsonColorRed: "图像 / 文件",
|
||||
jsonColorReset: "恢复默认",
|
||||
modelTabColorSection: "GenerateUI Model 标签高亮颜色",
|
||||
modelTabColorLabel: "工作流中包含的项目颜色",
|
||||
modelTabColorHint: "在 GenerateUI 的 Model 标签中,当前工作流实际包含的项目(Checkpoint / VAE 等)的标签将以此颜色显示。",
|
||||
|
||||
// -- Prompt tab --
|
||||
tabPrompt: "提示词",
|
||||
@@ -2813,6 +3065,31 @@ const LANGUAGES = {
|
||||
galleryCCNotAvailable: "仅当从ComfyUI Comic Creator内的图库打开时才能使用Send CC",
|
||||
gallerySentCC: "已发送至ComfyUI Comic Creator",
|
||||
galleryNoEmbeddedWorkflow: "此图像中未嵌入ComfyUI工作流。",
|
||||
galleryTabOutput: "Output",
|
||||
galleryTabImagePrompt: "ImagePrompt",
|
||||
galleryTabStyleCatalog: "Style_Catalog",
|
||||
galleryNoSelection: "未选择",
|
||||
imagePromptSelectedPrompt: "提示词",
|
||||
imagePromptNoPrompt: "此图像没有提示词数据。",
|
||||
imagePromptAddBtn: "+ 添加",
|
||||
imagePromptChipsTitle: "已选提示词",
|
||||
imagePromptClearBtn: "全部清除",
|
||||
imagePromptFinalPromptTitle: "最终提示词",
|
||||
imagePromptSaved: "提示词已保存",
|
||||
imagePromptAlreadyAdded: "已添加",
|
||||
imagePromptNothingToCopy: "暂无内容可复制",
|
||||
imagePromptCopiedToast: "已复制到剪贴板",
|
||||
stylecatalogSearchPlaceholder: "搜索...",
|
||||
stylecatalogPositive: "Positive",
|
||||
stylecatalogNegative: "Negative",
|
||||
stylecatalogSelectStyleBtn: "选为风格",
|
||||
stylecatalogLoadGenuiBtn: "载入GenerateUI",
|
||||
stylecatalogOpenMetadataBtn: "在Metadata标签中打开",
|
||||
stylecatalogNoPromptFound: "此图像中未找到提示词。",
|
||||
stylecatalogNoMatch: "未找到匹配的风格",
|
||||
stylecatalogStyleSelected: (name) => `风格已设为「${name}」`,
|
||||
stylecatalogNewFolderCreated: "文件夹已创建",
|
||||
stylecatalogSaved: (name) => `已保存: ${name}`,
|
||||
galleryBulkSelected: "项已选择",
|
||||
galleryBulkDeselectAll: "取消全选",
|
||||
galleryBulkSelectAll: "全选",
|
||||
@@ -2912,6 +3189,10 @@ const LANGUAGES = {
|
||||
aiSettingsModelSection: "选择模型",
|
||||
aiSettingsRefreshBtn: "刷新",
|
||||
aiSettingsModelPlaceholder: "-- 请选择模型 --",
|
||||
aiSettingsGenerationTitle: "生成设置",
|
||||
aiSettingsThinkingMode: "Thinking mode(思考模式)",
|
||||
aiSettingsMaxTokens: "Max tokens(最大令牌数)",
|
||||
aiSettingsMaxTokensPlaceholder: "0 = 无限制",
|
||||
aiSettingsFreeLang: "Free 语言设置",
|
||||
aiSettingsInputLang: "输入语言",
|
||||
aiSettingsOutputLang: "翻译语言",
|
||||
@@ -2927,6 +3208,7 @@ const LANGUAGES = {
|
||||
aiStatusConnectOk: "连接成功",
|
||||
aiStatusConnectFail: "连接失败:",
|
||||
aiToastTransFailed: "翻译失败:",
|
||||
aiToastMaybeNotTranslated: "模型原样返回了原文,可能未进行翻译。请尝试更换模型。",
|
||||
aiToastNoCopyText: "没有可复制的文字",
|
||||
aiToastCopied: "已复制",
|
||||
aiToastNoModels: "未找到模型",
|
||||
@@ -2977,9 +3259,13 @@ const LANGUAGES = {
|
||||
helpWf7: "徽章管理:添加、重命名、删除徽章并自定义颜色(与Models标签共享)— ⚙ Badge按钮",
|
||||
helpGen1: "连接/断开ComfyUI,检查连接状态",
|
||||
helpGen2: "从工作流标签页加载工作流(支持含子图的工作流,例如 Flux.2 / Qwen-Image / Z-Image / Mage-Flow / LongCat / Boogu / HiDream E1 / FireRed / Ernie Image 等模板;仅不支持ComfyUI的简化App格式 [.app.json / Linear Mode])。Reset Workflow按钮从磁盘重新读取当前工作流文件并重新加载编辑器。Save按钮(标签栏右端)将当前工作流(包括在编辑器中所做的编辑)保存为新的.json文件到工作流标签页;会显示以当前工作流名称为默认值的文件名对话框",
|
||||
helpGen25: "创建目录按钮(Style下拉框旁):为Batch标签→Style子标签中选中的每个风格,使用当前加载的工作流(通常为T2I)各生成一张预览图,并以风格名称为文件名保存到指定的ws_style_catalog子文件夹(同名文件将被覆盖);会弹出对话框让你新建目标文件夹或选择已有文件夹 — 使用多个文件夹便于按checkpoint或用途分类整理目录;执行前需先在Batch标签→Style子标签中至少勾选一个风格。目录按钮(紧邻其右):直接跳转到Gallery标签的Style_Catalog子标签查看结果",
|
||||
helpGen26: "创建目录对话框的「不在Output文件夹中保留副本」复选框:每次生成仍会先按工作流自身Save Image节点的机制,正常写入一份文件到ComfyUI的Output文件夹;勾选此项后,一旦该图像的副本已成功保存到目录文件夹,就会立即删除Output文件夹中的原始文件 — 适合大批量创建目录(例如全部200多个风格)时,避免Output文件夹被大量近似重复的文件淹没;若某个风格的目录副本保存失败,其Output文件不会被删除,会保留原样",
|
||||
helpGen27: "Input标签页 → Image子面板 — 每张LoadImage卡片现在有三个按钮:Apply(不变)、Clear(将该卡片待处理的选择/预览重置为空;不会改动工作流节点本身,因为LoadImage始终需要一个有效的文件名)和Placeholder。面板顶部的「Placeholder Image」区域(属于低频功能,默认折叠,点击可展开)用于配置共享的默认值:Color模式(设置宽度/高度/颜色,即时生成纯色PNG)或Image模式(拖入一张默认图片,之后原样复用)。点击某张卡片自己的Placeholder按钮,会立即只替换该卡片的图片为已配置的默认值——无需再点Apply;当有多张LoadImage卡片时,每张都可以单独替换。Placeholder配置(模式、尺寸、颜色、默认图片)会跨会话记住",
|
||||
helpGen3: "5标签布局 — Input(提示词+图像)、Model、Settings、Feeder、Batch — Input/Model/Settings各含实时预览和直接编辑的Raw JSON列",
|
||||
helpGen4: "Input标签:含Prompt和Image子标签(拖放上传);Prompt标签显示Positive Prompt、Negative Prompt,以及底部的Embeddings选择器(过滤+下拉+权重+Paste按钮)— Paste将(embedding:Name:weight)插入最后聚焦文本框的光标位置(未聚焦时默认追加到Positive);每个Apply按钮左侧的↺按钮可将文本框恢复为节点当前已应用的值;选中文字(或将光标置于单词/括号内也可)后按Ctrl+↑/↓,即可以(text:weight)语法以±0.05为单位调整强调权重(权重恢复为1.0时自动去除括号)",
|
||||
helpGen5: "Model标签:Checkpoint/VAE/LoRA(Single/Stack标签)/ControlNet/Diffusion Model(支持UNETLoader / UnetLoaderGGUF / LoaderGGUF)/Text Encoder(支持CLIPLoader / DualCLIPLoader / ClipLoaderGGUF / DualClipLoaderGGUF — 含type和device选择器,DualCLIP显示两段模型选择)/Hypernetwork(带Strength输入)选择器(含筛选)",
|
||||
helpGen5: "Model标签:Checkpoint/VAE/Diffusion Model(支持UNETLoader / UnetLoaderGGUF / LoaderGGUF)/Text Encoder(支持CLIPLoader / DualCLIPLoader / ClipLoaderGGUF / DualClipLoaderGGUF — 含type和device选择器,DualCLIP显示两段模型选择)始终显示;ControlNet和Hypernetwork(带Strength输入)因使用频率较低默认折叠 — 点击标题展开;LoRA(Single/Stack标签)拥有独立的列;所有选择器均含筛选;LoRA Stack — 点击Apply会将所有启用的LoRA写入目标节点,并同时将LoRA语法和CivitAI触发词插入Positive提示词;再次Apply会移除未启用的LoRA并重新添加启用的LoRA以更新提示词",
|
||||
helpGen28: "Model标签 — 高亮颜色:当前工作流实际包含某类型节点时(Checkpoint/VAE/Diffusion Model/Text Encoder/ControlNet/Hypernetwork),对应标签及LoRA列标题会以指定颜色(默认亮绿色)显示;即使ControlNet/Hypernetwork处于折叠状态该颜色依然可见,无需展开即可判断是否在使用;颜色可在Settings标签中自定义",
|
||||
helpGen6: "Settings标签:KSampler与Latent Image并排显示(各占50%宽度)",
|
||||
helpGen7: "Raw JSON在每个标签右列常驻显示 — 直接编辑并Apply即时重载工作流;如果加载的工作流包含Bypass或Mute节点,搜索栏上方会显示列表(Bypass节点会被排除但其连线会重新连接;Mute节点会被排除且不重新连接,与ComfyUI本体行为一致)",
|
||||
helpGen8: "种子管理:随机/固定/递增/递减",
|
||||
@@ -2994,6 +3280,11 @@ const LANGUAGES = {
|
||||
helpGen17: "样式批处理:在左窗格Style标签中选择样式,启用批次队列Style列后点击Generate — 每个选中样式依次应用到正向和负向提示词;样式应用于工作流副本,不会修改已加载的工作流;每次页面加载时从 user/default/Workflow-Studio/style/*.json 重新读取样式文件",
|
||||
helpGen18: "Alt+单击Apply按钮(Positive Prompt / Checkpoint / KSampler)可一步完成Apply & Generate — 将参数写入工作流后立即排队生成;仅当工作流中存在目标节点时才触发生成",
|
||||
helpGen19: "Lora批处理:应用每个LoRA时,会自动将其语法(<lora:名称:strength_model:strength_clip>)和CivitAI触发词追加到Positive提示词 — 每次都基于原始提示词重新构建,不会累积;批处理完成或停止后提示词会自动恢复到批处理前的状态;若所选LoRA尚未被ComfyUI模型列表识别,会显示警告提示(需在ComfyUI中Refresh或重启)",
|
||||
helpGen20: "LoRA有两种连接方式:链式连接标准 LoraLoader 节点(每个节点1个LoRA — 需要更多则继续串联节点),或使用单个 Lora Loader (LoraManager) 节点(来自ComfyUI-Lora-Manager自定义节点包,内部保存一个LoRA列表,每个LoRA各自管理启用/模型强度/CLIP强度);下方的Single/Stack标签会根据目标节点类型自动调整行为",
|
||||
helpGen21: "Single标签:选择一个LoRA并设置Str M/Str C后点击Apply — 若目标是Lora Manager节点,则会将其内部LoRA列表整体替换为仅这一项,其余原有LoRA将丢失",
|
||||
helpGen22: "Stack标签 — Use Stack Group复选框(仅当工作流中存在Lora Manager节点时显示):OFF(加载工作流时的默认状态)显示并编辑Lora Manager节点中实际配置的LoRA;ON则改为显示并编辑Models标签中已注册的\"Stack\"分组;切换任一方向都会先清空节点的LoRA列表,再从新选择的来源加载;切回OFF会精确恢复为加载工作流那一刻的LoRA列表(加载时已保存快照)",
|
||||
helpGen23: "Stack标签的操作:每行都有启用复选框及Str M / Str C字段;表头的\"Stack\"复选框可一次性切换所有行;顶部的+/-步进按钮可同时调整所有当前启用行的强度;\"Showing: LoRAs currently in workflow\" / \"Showing: registered Stack group\"标签指示当前显示的是哪个来源;点击Apply会将完整列表写回目标节点,并同时将LoRA语法和CivitAI触发词追加到Positive提示词",
|
||||
helpGen24: "使用 CLIP Text Encode edit+(CLIPTextEncodeEditPlus)节点时的注意事项:当Lora Manager节点的trigger_words输出连接到该节点的text1输入时(RAW/EDIT/front/back模式会将text1与可编辑的text_edit字段组合),触发词在生成时已自动包含;此时点击LoRA的Apply按钮或开启Use Stack Group会额外把LoRA语法/触发词写入text_edit,造成重复 — 如果想保持工作流原始的提示词和LoRA配置不被修改,请保持Use Stack Group为OFF,并避免点击LoRA的Apply类按钮",
|
||||
helpFeederTitle: "GenerateUI Tab — Feeder 子标签",
|
||||
helpFeederDesc: "通过左侧面板顶部的 [图片循环] / [图库] 切换按钮可在两种模式间切换。",
|
||||
helpFeederImgloopTitle: "图片循环模式",
|
||||
@@ -3022,20 +3313,28 @@ const LANGUAGES = {
|
||||
helpLab1: "左侧面板 — Image:拖入或点击选择作为I2I源图片;会上传到ComfyUI的input文件夹,只要未勾选\"Use generated image for next\",每次迭代都会使用该图片",
|
||||
helpLab2: "左侧面板 — Use generated image for next:勾选后,从第2次开始使用上一次迭代生成的第1张图片作为I2I输入,而不是原始拖入的图片(第1次始终使用原始图片)",
|
||||
helpLab3: "中间面板 — Checkpoint、VAE、Prompt、KSampler这4列相互独立;每列各自维护自己的关键帧列表,而不是共享同一个行网格",
|
||||
helpLab4: "每列的+/-:+会在下一个空闲的迭代序号(不超过Batch数)添加关键帧并立即打开编辑弹窗;-会删除最后一个关键帧(第1个关键帧无法删除)",
|
||||
helpLab4: "每列的+/-:+会在下一个空闲的迭代序号(不超过Batch数)添加关键帧并立即打开编辑弹窗;-会删除最后一个关键帧(第1个关键帧无法删除);除第1个之外的任何关键帧,也可以在其自己的编辑弹窗中通过「删除」按钮单独删除,不再限于最后一个",
|
||||
helpLab5: "点击单元格即可编辑:第1个关键帧设置基准值(留空则保持工作流本身的设置);第2个及以后的关键帧还可以选择从第几次开始应用,以及是否勾选\"恢复第1次的设置\"",
|
||||
helpLab6: "第N次迭代的实际生效值:使用迭代序号≤N中序号最大的关键帧,并一直延续到下一个关键帧改变它为止;勾选\"恢复第1次的设置\"时会直接复用第1次的值(若第1次为空则使用工作流默认值),而不是指定新值",
|
||||
helpLab6: "第N次迭代的实际生效值:使用迭代序号≤N中序号最大的关键帧,并一直延续到下一个关键帧改变它为止;勾选\"恢复第1次的设置\"时会直接复用第1次的值(若第1次为空则使用工作流默认值),而不是指定新值;将Batch数量减少到低于现有关键帧的迭代序号时(无论是手动修改,还是加载/应用方案),该关键帧不会被删除或重新编号,只会弹出警告提示,并在Batch数量再次提高之前一直处于运行循环无法到达的\"休眠\"状态",
|
||||
helpLab7: "Lab不会修改Input/Model/Settings中显示的工作流——每次迭代都在加载工作流的一个副本上运行,因此这里的关键帧设置不会影响其他子标签",
|
||||
helpLab8: "Prompt单元格编辑弹窗的附加功能:「Get from GenerateUI」从GenerateUI当前加载的工作流中获取Positive/Negative;「Get from Image」从Lab左侧IMAGE区域当前加载的图片中提取提示词(与Metadata标签相同的检测逻辑,无需另外选择文件);「Style」会将GenerateUI工具栏顶部Style复选框/下拉菜单中当前选中的风格,以逗号分隔追加到下方的Positive/Negative文本之后(不会清空已有内容)——需先在顶部勾选复选框并选择风格,Lab没有自己独立的风格选择器",
|
||||
helpLab8: "Prompt单元格编辑弹窗的附加功能:「Get from GenerateUI」从GenerateUI当前加载的工作流中获取Positive/Negative;「Get from Image」从Lab左侧IMAGE区域当前加载的图片中提取提示词(与Metadata标签相同的检测逻辑,无需另外选择文件);「Style」行点击「应用」按钮后,会将GenerateUI工具栏顶部Style下拉菜单中当前选中的风格名称,以逗号分隔追加到下方的Positive/Negative文本之后(不会清空已有内容),并自动勾选Style复选框、在按钮旁边(而非按钮上)显示已应用的风格名称——风格名称只能通过顶部下拉菜单选择,Lab没有自己独立的风格选择器;点击应用按钮与顶部工具栏自己的Style启用复选框无关;手动取消勾选Style复选框只会清除该名称显示(不会自动删除已追加到Positive/Negative中的文本,如不需要请手动编辑删除)",
|
||||
helpLab9: "左侧面板 — 「T2I workflow (no source image)」:当加载的工作流是文生图(T2I,没有LoadImage节点)时勾选此项。它会跳过\"请先拖入源图片\"的要求,忽略任何已拖入的图片,Checkpoint/VAE/Prompt/KSampler的关键帧仍会正常应用;开启期间Image拖放区域和「Use generated image for next」会变灰(之前拖入的图片不会被删除,以便切回I2I时使用);该设置会作为 t2i_mode 保存在方案中",
|
||||
helpLab10: "通配符:Prompt列关键帧中输入的Positive/Negative文本,支持与主GenerateUI相同的A1111风格 __name__ 语法——每个关键帧的文本会在该次迭代运行前才展开,因此即使复用同一个关键帧,每次迭代也可能抽到不同的随机行",
|
||||
helpLab11: "Prompt单元格编辑弹窗中还提供Clear(将Positive和Negative都清空)和Get from Previous(从同一列紧邻的上一个关键帧复制Positive和Negative——例如编辑#3时会整段复制#2的提示词);关键帧#1没有更早的行可复制,因此不显示该按钮",
|
||||
helpLab12: "每一列的关键帧#1,只要还没有被显式保存覆盖,就会用当前GenerateUI中已加载工作流的实际设置——Checkpoint、VAE、Prompt、KSampler——代替空白占位显示,同时体现在其网格单元格(虚线边框)和编辑弹窗的预填内容中;哪怕不做任何修改直接保存,也会将该值锁定为真正的覆盖值,虚线/实时显示随之消失;每次切换到Lab子标签页,都会重新根据当前GenerateUI中加载的内容刷新",
|
||||
helpLab13: "Bypass复选框(包括#1在内的每个关键帧都有):在判定某次迭代应使用哪一行设置时,会把该行完全跳过,如同它不存在——于是它之前生效的设置(更早的关键帧,或最终什么都不应用)会继续保持;这只是Lab内部的概念,绝不会改动实际ComfyUI节点的mode;勾选后会禁用该行的取值字段以及其Revert复选框(二者互斥,不能同时生效);单元格会显示琥珀色的「⏭ Bypassed」标签,其优先级高于Revert显示和实时显示",
|
||||
helpLabCardPlanTitle: "Setting子标签 — 运行与方案文件",
|
||||
helpLabPlan1: "右侧面板 — Batch:要运行的迭代次数;Note:与方案一起保存的自由备注",
|
||||
helpLabPlan2: "Run/Pause/Cancel:Run开始批量循环;Pause/Resume在各次迭代之间暂停/继续;Cancel会中断当前生成并停止循环",
|
||||
helpLabPlan3: "Plan Save与Save As的区别:Plan Save会在已加载方案时静默覆盖保存(未加载时才会询问名称);Save As无论是否已加载方案都会始终询问新名称",
|
||||
helpLabPlan4: "Plan Load:将方案的.json文件或其索引图片(.png)拖入PLAN区域(也可点击浏览选择)——拖入.json会直接读取;拖入.png会从服务器获取同名的.json",
|
||||
helpLabPlan4: "Plan Load:将方案的.json文件或其任意索引图片(.png)拖入PLAN区域(也可点击浏览选择)——拖入.json会直接读取;拖入.png时,如果是v0.3.90之后生成的索引图片(都会内嵌wfm_lab_plan数据块),也会直接读取其中的方案数据;仅对更早期、不含此数据的索引图片才会回退为从服务器获取同名的.json",
|
||||
helpLabPlan5: "Plan Clear会将Setting标签重置为空方案(会先确认)",
|
||||
helpLabPlan6: "方案文件保存在 user/default/Workflow-Studio/lab_plan/ 下,命名为<名称>.json,若方案含有结果,还会自动生成<名称>.png索引图片——最多9张结果缩略图组成的联系表(每行3张)",
|
||||
helpLabPlan6: "方案文件保存在 user/default/Workflow-Studio/lab_plan/ 下,命名为ws_labplan_<名称>.json,若方案含有结果,还会自动生成ws_labplan_<名称>.png索引图片——最多9张结果缩略图组成的联系表(每行3张)。ws_labplan_前缀由Plan Save/Save As自动添加,输入时只需填写不带前缀的名称,方便在该文件夹中辨认方案文件",
|
||||
helpLabPlan7: "设置标签页中配置的Eagle自动保存,会像GenerateUI自身的Generate按钮一样应用于Lab生成的每一张图片",
|
||||
helpLabPlan8: "Plan JSON子标签:以原始JSON形式显示当前Setting标签页的方案内容。「Refresh」会从Setting标签页重新读取(放弃尚未应用的编辑);「Apply to Setting」会解析你的编辑并写回Setting标签页(列、备注、Batch数量、图片链式生成、源图片、结果)——效果与直接将该JSON作为方案文件加载相同,无需先保存",
|
||||
helpLabPlan9: "每个已保存的方案都会记录保存时GenerateUI中加载的工作流文件名(Plan JSON中的workflow_filename)。加载方案后,PLAN框中会出现「Open Workflow」按钮——点击即可将该确切的工作流文件重新加载到GenerateUI中(会先弹出确认,因为这会替换当前已加载的工作流)",
|
||||
helpLabPlan10: "右侧面板 — 「Save index image to Output on Run」:勾选后,每次Run结束都会生成与方案文件相同的联系表索引图片,并直接保存到ComfyUI自身的Output文件夹,命名为 Lab_index_<counter>_.png(像普通生成图片一样自动编号,不会覆盖上一次运行的结果)。保存后还会像其他Lab生成的图片一样经过Eagle自动保存(若在设置标签页中启用)——没有单独的复选框,遵循同一个全局开关。这与Plan Save的行为相互独立——无论是否勾选此项,Plan Save都会照常在 lab_plan/ 中的方案文件旁写入自己的索引图片;该设置会作为 save_index_on_run 保存在方案中",
|
||||
helpLabPlan11: "每一张索引图片PNG——无论是来自Plan Save/Save As,还是来自Save index image to Output on Run——都会将完整的方案数据(列、备注、Batch数量、图片链式生成/T2I设置、工作流文件名、结果列表)直接嵌入为PNG的wfm_lab_plan数据块。因此Output文件夹中的那份副本是完全自包含的,即使旁边没有任何对应的.json文件,也可以作为Plan Load的加载来源",
|
||||
helpLabCardResultsTitle: "Results子标签",
|
||||
helpLabResults1: "左侧面板显示本次运行使用的源图片",
|
||||
helpLabResults2: "中间面板按生成顺序显示最多9张生成图片;点击缩略图可放大查看",
|
||||
@@ -3051,6 +3350,11 @@ const LANGUAGES = {
|
||||
helpPrompt7: "GenUI Set:将预设提示词直接应用到生成UI",
|
||||
helpPrompt8: "通配符工具栏:一键插入通配符语法({|}、{n$|}、__|__、<lora:>等);支持包裹选中文本",
|
||||
helpPrompt9: "通配符文件管理:创建/编辑/删除.txt/.yaml通配符文件;点击文件名在光标处插入__文件名__",
|
||||
helpPrompt10: "右侧面板的Wildcard/Style标签栏可在上方的通配符工具与此Style管理器之间切换整个面板(共用同一个右侧面板)",
|
||||
helpPrompt11: "创建/编辑/删除已注册的Style(与GenerateUI的Style下拉菜单、Batch标签、Style Catalog使用的是同一批数据):点击列表中的名称进行编辑,或点击「+ New」创建空白条目;字段包括Name、Positive prompt(支持{prompt}占位符 — 会被替换为用户自己的提示词,若省略则附加在其后)和Negative prompt(可选)",
|
||||
helpPrompt12: "重命名后仍保留其在原定义文件中的位置;新建的Style会保存到style文件夹内专用的custom.json中,因此内置的风格包文件不会被直接修改;名称在所有Style中必须唯一",
|
||||
helpPrompt13: "保存、重命名或删除Style会立即刷新GenerateUI的Style下拉菜单、Batch标签的风格勾选列表以及Style Catalog的名称列表 — 无需重新加载",
|
||||
helpPrompt14: "列表中每个条目的名称旁都会以小徽章显示其来源文件(例如sdxl_styles_diva.json);编辑现有Style时,该文件名也会显示在Positive prompt字段上方,并且Save按钮旁会出现「+ Add to this file」按钮 — 点击后表单会清空,可创建一个新Style并追加到同一文件,而不是默认的custom.json",
|
||||
helpSettings1: "UI语言和摘要语言设置",
|
||||
helpSettings2: "主题选择(13种预设)+ 自定义:颜色调整、背景图案(条纹、波点、棋盘格、SVG平铺)、字体选择(含日文显示字体在内的16种Google Fonts)",
|
||||
helpSettings3: "工作流数据文件夹路径更改/重置",
|
||||
@@ -3064,6 +3368,7 @@ const LANGUAGES = {
|
||||
helpSettings11: "文字大小:单个滑块(10–28 px)可一次性调整所有提示词和聊天文本框的字体大小 — GenerateUI正/负向提示词、AI助手聊天输入、预设正/负向提示、通配符提示和文件编辑器、元数据提示词全文预览;即时生效并通过「保存设置」保存",
|
||||
helpSettings12: "RAW JSON 配色:自定义GenerateUI中Raw JSON编辑器的6种语法高亮颜色 — 默认文本、名称/调度器、标题、宽度/高度、提示词/文本、图像/文件;颜色选择即时生效;「重置默认」恢复原始配色",
|
||||
helpSettings13: "CivitAI 站点:在 civitai.com(仅SFW)和 civitai.red(无限制)之间切换 — 决定在Models标签CivitAI面板中点击模型链接时打开的站点",
|
||||
helpSettings14: "GenerateUI Model标签高亮颜色:设置当前工作流实际包含对应类型节点时,GenerateUI Model标签中Checkpoint/VAE/Diffusion Model/Text Encoder/ControlNet/Hypernetwork标签及LoRA列标题的显示颜色;默认为亮绿色;更改即时生效,「重置默认」可恢复",
|
||||
helpNodes1: "节点浏览器:按名称/描述/别名/标签搜索,按分类、包、标签、组、收藏筛选",
|
||||
helpNodes2: "卡片和表格视图模式切换(带分页)",
|
||||
helpNodes3: "收藏节点,添加自定义标签进行整理",
|
||||
@@ -3101,6 +3406,14 @@ const LANGUAGES = {
|
||||
helpGallery15: "F按钮(青色悬浮按钮,每个缩略图左上角):单击即可将图像添加到/从__Feeder__组中移除;图像在组中时始终显示青色,不在组中时仅悬停时可见;可快速为Feeder标签Gallery模式添加队列图像",
|
||||
helpGallery16: "Image Edit按钮(工具栏,Refresh按钮旁):将当前选中的图像发送到Image Edit标签;如果已有图层则按比例缩放添加为新图层,否则将成为Layer 1",
|
||||
helpGallery17: "Send GenUI Image按钮(工具栏,Image Edit按钮旁):将选中图像上传至ComfyUI并设置为GenerateUI标签中第一个LoadImage节点的输入;自动切换至GenerateUI → Input → Image;需要预先加载包含至少一个LoadImage节点的工作流",
|
||||
helpGallery18: "Gallery标签页中与Output并列的第二个子标签,用于浏览可视化提示词库 — 管理ComfyUI output文件夹内的ws_image_prompt文件夹(未创建时自动生成)",
|
||||
helpGallery19: "相同的三栏布局:文件夹树(左)|缩略图(中)|提示词构建器(右)。点击缩略图可预览图像及其提示词文本 — 此时尚未添加到提示词中",
|
||||
helpGallery20: "「+ 添加」将预览中图像的提示词作为标签添加到「已选提示词」;标签可单独删除(×)或一次性清除(「全部清除」);「Save」用于编辑并保存该图像的提示词文本",
|
||||
helpGallery21: "「最终提示词」将所有标签以逗号连接为一段文本(也可自由编辑);「Copy」将其复制到剪贴板。提示词以纯文本.txt文件形式保存在对应图像旁,因此任何人只需在子文件夹中放入图像+对应的.txt文件即可添加自己的数据",
|
||||
helpGallery22: "Gallery标签页顶部的第三个子标签,可通过预览图直观地选择已注册的Style — 管理ComfyUI output文件夹内的ws_style_catalog文件夹(未创建时自动生成)。由GenerateUI标签的「创建目录」按钮生成(参见GenerateUI标签帮助)",
|
||||
helpGallery23: "相同的三栏布局:文件夹树(左)|缩略图(中)|Positive/Negative提示词面板(右)。点击缩略图可查看该生成图像中实际嵌入的Positive/Negative提示词,各自带有独立的Copy按钮",
|
||||
helpGallery24: "Select as Style按钮:以选中图像的文件名(不含扩展名)匹配已注册的Style名称,并将GenerateUI标签的Style下拉框切换为该风格 — 这是通往现有命名Style系统的可视化快捷方式,而非一次性应用嵌入的提示词(如果目录图像生成后该Style已被重命名或删除,则会显示「未找到匹配的风格」提示)",
|
||||
helpGallery25: "载入GenerateUI / 在Metadata标签中打开按钮:读取目录图像本身内嵌的工作流(目录副本携带与原始输出图像相同的PNG元数据),可直接载入GenerateUI编辑器,或在Metadata标签中打开该图像以供查看 — 无需在Output文件夹中寻找原始文件",
|
||||
|
||||
// -- Tagger Tab --
|
||||
helpTaggerTitle: "Tagger标签",
|
||||
@@ -3130,14 +3443,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 工具):翻译、Chat、TOOLS 和设置子标签;Chat 支持与 LLM 的多轮对话;TOOLS 包含 VLM 图像分析和通配符生成;设置通过 localStorage 与 SPA 的 AI 标签共享",
|
||||
helpSidepanel16: "A 标签(AI 工具):翻译、Chat、TOOLS 和设置子标签,支持 Ollama、LM Studio、Lemonade 或 Unsloth;Chat 支持与 LLM 的多轮对话;TOOLS 包含 VLM 图像分析和通配符生成;设置通过 localStorage 与 SPA 的 AI 标签共享",
|
||||
helpSidepanel17: "Send to Canvas:在Workflow标签点击'Send to Canvas'或Gallery标签点击'Copy & Send Canvas',工作流直接发送到ComfyUI画布(支持UI和API所有格式);若Workflow Studio不是从ComfyUI工具栏打开,UI格式工作流将回退到标题拖拽(标题变蓝并显示绿色●——拖拽到画布加载)",
|
||||
helpAiTitle: "AI 标签页(A)",
|
||||
helpAi1: "4 面板布局 — Translation | Chat | TOOLS | Settings — 所有面板始终可见",
|
||||
helpAi2: "翻译面板:使用 Ollama、LM Studio 或 Lemonade 在日语、英语、中文或自定义语言(Free)之间翻译;⇄ 按钮同时互换语言和文本内容;选择自动保存",
|
||||
helpAi2: "翻译面板:使用 Ollama、LM Studio、Lemonade 或 Unsloth 在日语、英语、中文或自定义语言(Free)之间翻译;⇄ 按钮同时互换语言和文本内容;选择自动保存",
|
||||
helpAi3: "Chat 面板:与 LLM 进行多轮对话;Enter 发送消息,Shift+Enter 换行;Clear 按钮重置对话历史;如果模型支持 tool calling,当你要求生成图像(例如\"生成一张猫的图片\")时,会使用 GenerateUI 中当前加载的工作流执行生成,并在对话中显示结果;面板标题栏的\"允许生成图像\"复选框可开关此功能;如果附加了图像(在 TOOLS 面板中拖放的图像),该图像会作为视觉输入发送给 LLM,调用 generate_image 时会以该图像为基础执行图生图(I2I),而不是文生图;已验证可正常支持 tool calling 与视觉功能的模型:Gemma 4:e4b、Qwen 3.5:9b、Ministral 3:3b(Ollama)",
|
||||
helpAi4: "TOOLS 面板 — VLM:拖放图像(PNG/JPG/WebP)并选择任务(图像描述 / 提示词生成 / 标签生成),点击 Run;或选择「Create wildcards」,输入类别名称和数量生成纯文本通配符条目(每行一条);拖放的图像也会作为 Chat 面板的附件共享(在该处显示并用于图生图生成),直到点击 ✕ 按钮清除",
|
||||
helpAi6: "Settings 面板:选择后端(Ollama / LM Studio / Lemonade)、设置 API URL、测试连接、选择模型、配置 Free 语言名称;Chat 图像生成部分可让 Chat 触发的文生图使用专用工作流,而不是 GenerateUI 中当前加载的工作流;Chat I2I 生成部分提供相同设置,用于附加图像时的图生图生成;设置保存至 localStorage,并与 Library 面板的 A 标签共享",
|
||||
helpAi6: "Settings 面板:选择后端(Ollama / LM Studio / Lemonade / Unsloth)、设置 API URL、测试连接、选择模型;Unsloth 即使在本地访问时也始终需要 API 密钥认证——将插件文件夹中的 .env.example 复制为 .env 并设置 UNSLOTH_API_KEY,然后重启 ComfyUI(密钥仅在服务器端读取,绝不会发送到浏览器);还需要在 Unsloth Desktop 应用自身的设置界面中开启「Auto model switching (OpenAI API)」——若保持关闭,除非已在 Unsloth Studio 中手动加载过模型,否则请求会以 HTTP 404 失败;Unsloth 的推理模型会将思考内容放在单独的 reasoning_content 字段中,而不是内联的 <think> 标签里,因此 Max tokens 太小会导致模型把全部配额都用在思考上,返回空白回复——如果回复为空,请调高 Max tokens(建议 2048 以上);Generation 部分 — Thinking mode 开关(默认关闭;Ollama会收到think标志,无论使用哪个后端,关闭时都会从输出中去除<think>...</think>思考块,避免推理模型的思考过程混入Translation/Chat/TOOLS的结果)以及 Max tokens(Ollama: num_predict,LM Studio/Lemonade/Unsloth: max_tokens;0为不限);配置 Free 语言名称;Chat 图像生成部分可让 Chat 触发的文生图使用专用工作流,而不是 GenerateUI 中当前加载的工作流;Chat I2I 生成部分提供相同设置,用于附加图像时的图生图生成;设置保存至 localStorage,并与 Library 面板的 A 标签共享",
|
||||
helpAi7: "Chat 面板 — SVG:LLM 还可以直接以文本形式生成 SVG 图形,完全不涉及 ComfyUI 工作流;只需要求它用 SVG 绘制内容,如果回复中包含 SVG 代码,会自动渲染为内嵌预览,并提供\"保存到图库\"按钮,将其保存为 .svg 文件到 Gallery 标签页的输出文件夹;该功能不使用 tool calling(函数调用),因此不支持 tool calling 的模型也可以使用",
|
||||
helpAi8: "Chat 面板 — 技能:在消息列表上方的下拉菜单中选择一个技能,其内容会作为 system prompt 添加到对话开头(不会显示在可见的聊天记录中);点击铅笔按钮打开技能管理面板,可创建、编辑、删除 .md 技能文件(保存路径:user/default/Workflow-Studio/ai_skills/);文件开头 --- 之间的 name/description 字段会显示在下拉菜单中;默认内置两个技能:「SVG Icon Generator」(在绘制前先将对象拆解为多个部件,以生成更易识别的 SVG)和「Skill Creator」(通过对话向你提问并起草新的技能文件);当回复中包含```skill代码块时,消息下方会出现「保存为技能」按钮,点击后会打开管理面板并预填内容",
|
||||
helpAi9: "编写技能的小贴士:为 frontmatter 的 name/description 写清楚的内容,便于在下拉菜单和提示中阅读;明确说明期望的输出格式,如果有需要后续提取的成果物(如 SVG 或另一个技能文件),指示它用专门的代码围栏包裹;具体、祈使句式的指令比笼统的说明对本地小模型更有效,附上一个简短示例效果更佳;明确写出硬性约束(禁止内容、安全性、长度限制等),不要指望模型会自行推断;如果不确定怎么写,可以在下拉菜单中选择「Skill Creator」技能并描述你想要的技能,它会通过提问帮你起草",
|
||||
@@ -3161,10 +3474,12 @@ const LANGUAGES = {
|
||||
helpGenCardSeed: "种子与生成",
|
||||
helpGenCardBatchSetup: "Batch 标签 — 设置",
|
||||
helpGenCardBatchTypes: "Batch 标签 — 批量类型",
|
||||
helpGenCardLora: "Model 标签 — LoRA 详情",
|
||||
helpPromptTitle: "提示词标签页",
|
||||
helpPromptCardAi: "AI 助手与翻译",
|
||||
helpPromptCardPresets: "预设",
|
||||
helpPromptCardWildcards: "通配符",
|
||||
helpPromptCardStyleTitle: "Style",
|
||||
helpMetadataCardOverview: "概述",
|
||||
helpMetadataCardExtracted: "提取的信息",
|
||||
helpMetadataCardFormats: "支持的格式",
|
||||
@@ -3179,6 +3494,8 @@ const LANGUAGES = {
|
||||
helpNodesCardGroups: "分组与节点集",
|
||||
helpNodesCardPanel: "侧边面板与多选",
|
||||
helpGalleryCardBrowse: "浏览",
|
||||
helpGalleryCardStyleprompt: "ImagePrompt 图库",
|
||||
helpGalleryCardStylecatalog: "Style_Catalog 图库",
|
||||
helpGalleryCardFolder: "文件夹与选择",
|
||||
helpGalleryCardDetail: "详情面板",
|
||||
helpGalleryCardActions: "操作工具栏",
|
||||
|
||||
@@ -0,0 +1,363 @@
|
||||
/**
|
||||
* ImagePrompt Gallery — Gallery タブのサブタブ。
|
||||
* ws_image_prompt フォルダ配下の画像+.txtサイドカーを閲覧し、
|
||||
* クリックで選択→「追加」でプロンプトを組み立てて最終的にコピーする。
|
||||
*/
|
||||
|
||||
import { showToast } from "./app.js";
|
||||
import { t } from "./i18n.js";
|
||||
import { escapeHtml, setupSearchClearBtn } from "./util.js";
|
||||
|
||||
const API = {
|
||||
root: () => `/wfm/gallery/image-prompt/root`,
|
||||
folders: (root) => `/wfm/gallery/folders?root=${encodeURIComponent(root)}`,
|
||||
images: (params) => `/wfm/gallery/images?${new URLSearchParams(params)}`,
|
||||
imageMeta: (path) => `/wfm/gallery/image/meta?path=${encodeURIComponent(path)}`,
|
||||
thumb: (path, w = 200) => `/wfm/gallery/image/thumb?path=${encodeURIComponent(path)}&w=${w}`,
|
||||
serveImage: (path) => `/wfm/gallery/image/serve?path=${encodeURIComponent(path)}`,
|
||||
savePrompt: `/wfm/gallery/image/image-prompt`,
|
||||
};
|
||||
|
||||
const state = {
|
||||
root: null,
|
||||
currentFolder: null,
|
||||
search: "",
|
||||
images: [],
|
||||
selectedImage: null,
|
||||
chips: [], // [{ path, filename, prompt }]
|
||||
};
|
||||
|
||||
let _initialized = false;
|
||||
|
||||
async function apiFetch(url, opts = {}) {
|
||||
const res = await fetch(url, opts);
|
||||
if (!res.ok) throw new Error(`HTTP ${res.status}`);
|
||||
return res.json();
|
||||
}
|
||||
|
||||
function debounce(fn, wait) {
|
||||
let timer;
|
||||
return (...args) => {
|
||||
clearTimeout(timer);
|
||||
timer = setTimeout(() => fn(...args), wait);
|
||||
};
|
||||
}
|
||||
|
||||
// ── 初期化 ────────────────────────────────────────────────────
|
||||
|
||||
export function initImagePromptTab() {
|
||||
document.getElementById("wfm-imageprompt-refresh-btn")?.addEventListener("click", () => {
|
||||
loadFolderTree();
|
||||
loadImages();
|
||||
});
|
||||
|
||||
setupSearchClearBtn("wfm-imageprompt-search", "wfm-imageprompt-search-clear-btn", () => {
|
||||
state.search = "";
|
||||
loadImages();
|
||||
});
|
||||
|
||||
const searchInput = document.getElementById("wfm-imageprompt-search");
|
||||
searchInput?.addEventListener("input", debounce(() => {
|
||||
state.search = searchInput.value.trim();
|
||||
loadImages();
|
||||
}, 300));
|
||||
|
||||
document.getElementById("wfm-imageprompt-add-btn")?.addEventListener("click", addSelectedToChips);
|
||||
document.getElementById("wfm-imageprompt-save-prompt-btn")?.addEventListener("click", saveSelectedPrompt);
|
||||
document.getElementById("wfm-imageprompt-clear-btn")?.addEventListener("click", clearAllChips);
|
||||
document.getElementById("wfm-imageprompt-copy-btn")?.addEventListener("click", copyFinalPrompt);
|
||||
}
|
||||
|
||||
export async function activateImagePromptTab() {
|
||||
if (_initialized) return;
|
||||
_initialized = true;
|
||||
try {
|
||||
const data = await apiFetch(API.root());
|
||||
state.root = data.root;
|
||||
await loadFolderTree();
|
||||
} catch (e) {
|
||||
const tree = document.getElementById("wfm-imageprompt-tree");
|
||||
if (tree) tree.innerHTML = `<p class="wfm-placeholder">Error: ${escapeHtml(e.message)}</p>`;
|
||||
}
|
||||
}
|
||||
|
||||
// ── フォルダツリー ────────────────────────────────────────────
|
||||
|
||||
async function loadFolderTree() {
|
||||
if (!state.root) return;
|
||||
const tree = document.getElementById("wfm-imageprompt-tree");
|
||||
tree.innerHTML = `<p class="wfm-placeholder">${t("loading")}</p>`;
|
||||
try {
|
||||
const data = await apiFetch(API.folders(state.root));
|
||||
if (data.error) {
|
||||
tree.innerHTML = `<p class="wfm-placeholder">${escapeHtml(data.error)}</p>`;
|
||||
return;
|
||||
}
|
||||
tree.innerHTML = "";
|
||||
renderTreeNode(data, tree, 0, true);
|
||||
const firstLabel = tree.querySelector(".wfm-gallery-tree-label");
|
||||
if (firstLabel) firstLabel.click();
|
||||
} catch (e) {
|
||||
tree.innerHTML = `<p class="wfm-placeholder">Error: ${escapeHtml(e.message)}</p>`;
|
||||
}
|
||||
}
|
||||
|
||||
function renderTreeNode(node, container, depth, isRoot) {
|
||||
const item = document.createElement("div");
|
||||
item.className = "wfm-gallery-tree-item";
|
||||
item.style.paddingLeft = `${depth * 12}px`;
|
||||
item.dataset.path = node.abs_path;
|
||||
|
||||
const hasChildren = node.children && node.children.length > 0;
|
||||
const absPath = node.abs_path;
|
||||
|
||||
const arrow = document.createElement("span");
|
||||
arrow.className = "wfm-gallery-tree-arrow";
|
||||
if (hasChildren) {
|
||||
arrow.textContent = "▶";
|
||||
arrow.dataset.expanded = "false";
|
||||
} else {
|
||||
arrow.textContent = " ";
|
||||
arrow.style.visibility = "hidden";
|
||||
}
|
||||
item.appendChild(arrow);
|
||||
|
||||
const label = document.createElement("span");
|
||||
label.className = "wfm-gallery-tree-label";
|
||||
label.textContent = isRoot ? "[root]" : node.name;
|
||||
// サブフォルダ内も含めた合計件数(クリックで再帰的に全画像を表示するため)
|
||||
const totalCount = node.image_count_total ?? node.image_count;
|
||||
if (totalCount > 0) {
|
||||
const badge = document.createElement("span");
|
||||
badge.className = "wfm-gallery-tree-count";
|
||||
badge.textContent = totalCount;
|
||||
label.appendChild(badge);
|
||||
}
|
||||
item.appendChild(label);
|
||||
|
||||
label.addEventListener("click", () => {
|
||||
document.querySelectorAll("#wfm-imageprompt-tree .wfm-gallery-tree-item.selected").forEach(el => el.classList.remove("selected"));
|
||||
item.classList.add("selected");
|
||||
state.currentFolder = absPath;
|
||||
loadImages();
|
||||
});
|
||||
|
||||
if (hasChildren) {
|
||||
const childContainer = document.createElement("div");
|
||||
childContainer.className = "wfm-gallery-tree-children";
|
||||
childContainer.style.display = "none";
|
||||
|
||||
arrow.addEventListener("click", (e) => {
|
||||
e.stopPropagation();
|
||||
const expanded = arrow.dataset.expanded === "true";
|
||||
if (!expanded) {
|
||||
arrow.dataset.expanded = "true";
|
||||
arrow.textContent = "▼";
|
||||
childContainer.style.display = "";
|
||||
if (childContainer.children.length === 0) {
|
||||
node.children.forEach(child => renderTreeNode(child, childContainer, depth + 1, false));
|
||||
}
|
||||
} else {
|
||||
arrow.dataset.expanded = "false";
|
||||
arrow.textContent = "▶";
|
||||
childContainer.style.display = "none";
|
||||
}
|
||||
});
|
||||
|
||||
container.appendChild(item);
|
||||
container.appendChild(childContainer);
|
||||
} else {
|
||||
container.appendChild(item);
|
||||
}
|
||||
}
|
||||
|
||||
// ── 画像一覧 ─────────────────────────────────────────────────
|
||||
|
||||
async function loadImages() {
|
||||
if (!state.currentFolder) return;
|
||||
const grid = document.getElementById("wfm-imageprompt-grid");
|
||||
grid.innerHTML = `<p class="wfm-placeholder">${t("loading")}</p>`;
|
||||
|
||||
// 上位フォルダを選択した場合もサブフォルダの画像をまとめて表示する
|
||||
const params = { folder: state.currentFolder, sort: "name_asc", recursive: "true" };
|
||||
if (state.search) params.search = state.search;
|
||||
|
||||
try {
|
||||
const data = await apiFetch(API.images(params));
|
||||
state.images = data.images || [];
|
||||
document.getElementById("wfm-imageprompt-count").textContent = `${state.images.length} images`;
|
||||
renderImages();
|
||||
} catch (e) {
|
||||
grid.innerHTML = `<p class="wfm-placeholder">Error: ${escapeHtml(e.message)}</p>`;
|
||||
}
|
||||
}
|
||||
|
||||
function renderImages() {
|
||||
const grid = document.getElementById("wfm-imageprompt-grid");
|
||||
if (state.images.length === 0) {
|
||||
grid.innerHTML = `<p class="wfm-placeholder">${t("galleryNoImages")}</p>`;
|
||||
return;
|
||||
}
|
||||
grid.innerHTML = "";
|
||||
const fragment = document.createDocumentFragment();
|
||||
state.images.forEach(img => fragment.appendChild(createThumbCard(img)));
|
||||
grid.appendChild(fragment);
|
||||
}
|
||||
|
||||
function createThumbCard(img) {
|
||||
const card = document.createElement("div");
|
||||
card.className = "wfm-gallery-thumb-card";
|
||||
card.title = img.filename;
|
||||
card.dataset.path = img.path;
|
||||
if (state.selectedImage && state.selectedImage.path === img.path) {
|
||||
card.classList.add("selected");
|
||||
}
|
||||
|
||||
const imgEl = document.createElement("img");
|
||||
imgEl.className = "wfm-gallery-thumb-img";
|
||||
imgEl.loading = "lazy";
|
||||
imgEl.src = API.thumb(img.path);
|
||||
imgEl.alt = img.filename;
|
||||
imgEl.onerror = () => {
|
||||
imgEl.style.display = "none";
|
||||
const placeholder = document.createElement("div");
|
||||
placeholder.className = "wfm-gallery-thumb-placeholder";
|
||||
placeholder.textContent = "?";
|
||||
card.insertBefore(placeholder, imgEl.nextSibling);
|
||||
};
|
||||
card.appendChild(imgEl);
|
||||
|
||||
card.addEventListener("click", () => selectImage(img));
|
||||
|
||||
return card;
|
||||
}
|
||||
|
||||
// ── 選択画像 / プロンプト表示 ─────────────────────────────────
|
||||
|
||||
async function selectImage(img) {
|
||||
state.selectedImage = img;
|
||||
document.querySelectorAll("#wfm-imageprompt-grid .wfm-gallery-thumb-card").forEach(el => {
|
||||
el.classList.toggle("selected", el.dataset.path === img.path);
|
||||
});
|
||||
|
||||
document.getElementById("wfm-imageprompt-selected-name").textContent = img.filename;
|
||||
const preview = document.getElementById("wfm-imageprompt-selected-preview");
|
||||
preview.innerHTML = "";
|
||||
const previewImg = document.createElement("img");
|
||||
previewImg.src = API.serveImage(img.path);
|
||||
previewImg.alt = img.filename;
|
||||
previewImg.style.cssText = "max-width:100%;max-height:100%;object-fit:contain;";
|
||||
preview.appendChild(previewImg);
|
||||
|
||||
const promptBox = document.getElementById("wfm-imageprompt-selected-prompt");
|
||||
promptBox.value = "";
|
||||
document.getElementById("wfm-imageprompt-save-prompt-btn").disabled = true;
|
||||
document.getElementById("wfm-imageprompt-add-btn").disabled = true;
|
||||
|
||||
try {
|
||||
const meta = await apiFetch(API.imageMeta(img.path));
|
||||
promptBox.value = meta.image_prompt || "";
|
||||
document.getElementById("wfm-imageprompt-save-prompt-btn").disabled = false;
|
||||
document.getElementById("wfm-imageprompt-add-btn").disabled = !meta.image_prompt;
|
||||
} catch (e) {
|
||||
showToast(t("errorWithMsg", e.message), "error");
|
||||
}
|
||||
}
|
||||
|
||||
async function saveSelectedPrompt() {
|
||||
if (!state.selectedImage) return;
|
||||
const promptBox = document.getElementById("wfm-imageprompt-selected-prompt");
|
||||
try {
|
||||
const res = await apiFetch(API.savePrompt, {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify({ path: state.selectedImage.path, prompt: promptBox.value }),
|
||||
});
|
||||
if (res.ok) {
|
||||
showToast(t("imagePromptSaved"), "success");
|
||||
document.getElementById("wfm-imageprompt-add-btn").disabled = !promptBox.value.trim();
|
||||
} else {
|
||||
showToast(t("saveFailed"), "error");
|
||||
}
|
||||
} catch (e) {
|
||||
showToast(t("errorWithMsg", e.message), "error");
|
||||
}
|
||||
}
|
||||
|
||||
// ── プロンプトビルダー (チップ / 最終プロンプト) ─────────────────
|
||||
|
||||
function cleanPromptText(text) {
|
||||
return String(text || "")
|
||||
.replace(/^[,\s]+|[,\s]+$/g, "")
|
||||
.replace(/\s*,\s*/g, ", ")
|
||||
.trim();
|
||||
}
|
||||
|
||||
function addSelectedToChips() {
|
||||
const img = state.selectedImage;
|
||||
if (!img) return;
|
||||
const promptBox = document.getElementById("wfm-imageprompt-selected-prompt");
|
||||
const prompt = cleanPromptText(promptBox.value);
|
||||
if (!prompt) return;
|
||||
if (state.chips.some(c => c.path === img.path)) {
|
||||
showToast(t("imagePromptAlreadyAdded"), "info");
|
||||
return;
|
||||
}
|
||||
state.chips.push({ path: img.path, filename: img.filename, prompt });
|
||||
renderChips();
|
||||
rebuildFinalPrompt();
|
||||
}
|
||||
|
||||
function removeChip(path) {
|
||||
state.chips = state.chips.filter(c => c.path !== path);
|
||||
renderChips();
|
||||
rebuildFinalPrompt();
|
||||
}
|
||||
|
||||
function clearAllChips() {
|
||||
state.chips = [];
|
||||
renderChips();
|
||||
document.getElementById("wfm-imageprompt-final-prompt").value = "";
|
||||
}
|
||||
|
||||
function renderChips() {
|
||||
const container = document.getElementById("wfm-imageprompt-chips");
|
||||
container.innerHTML = "";
|
||||
state.chips.forEach(chip => {
|
||||
const el = document.createElement("span");
|
||||
el.className = "wfm-imageprompt-chip";
|
||||
el.title = chip.prompt;
|
||||
|
||||
const text = document.createElement("span");
|
||||
text.className = "wfm-imageprompt-chip-text";
|
||||
text.textContent = chip.filename.replace(/\.[^.]+$/, "");
|
||||
el.appendChild(text);
|
||||
|
||||
const removeBtn = document.createElement("button");
|
||||
removeBtn.className = "wfm-imageprompt-chip-remove";
|
||||
removeBtn.textContent = "×";
|
||||
removeBtn.addEventListener("click", () => removeChip(chip.path));
|
||||
el.appendChild(removeBtn);
|
||||
|
||||
container.appendChild(el);
|
||||
});
|
||||
}
|
||||
|
||||
function rebuildFinalPrompt() {
|
||||
const combined = state.chips.map(c => c.prompt).join(", ");
|
||||
document.getElementById("wfm-imageprompt-final-prompt").value = cleanPromptText(combined);
|
||||
}
|
||||
|
||||
async function copyFinalPrompt() {
|
||||
const text = document.getElementById("wfm-imageprompt-final-prompt").value;
|
||||
if (!text.trim()) {
|
||||
showToast(t("imagePromptNothingToCopy"), "info");
|
||||
return;
|
||||
}
|
||||
try {
|
||||
await navigator.clipboard.writeText(text);
|
||||
showToast(t("imagePromptCopiedToast"), "success");
|
||||
} catch (e) {
|
||||
showToast(t("errorWithMsg", e.message), "error");
|
||||
}
|
||||
}
|
||||
+398
-62
@@ -12,26 +12,29 @@ import { comfyUI } from "./comfyui-client.js";
|
||||
import { comfyEditor } from "./comfyui-editor.js";
|
||||
import { showToast, openModal, closeModal } from "./app.js";
|
||||
import { t } from "./i18n.js";
|
||||
import { escapeHtml, getEagleSettings, saveToEagle, setupSearchClearBtn } from "./util.js";
|
||||
import { extractAllMetadata } from "./metadata-tab.js";
|
||||
import { syncJsonHighlight } from "./json-highlight.js";
|
||||
import { escapeHtml, embedPngTextChunk, getEagleSettings, saveToEagle, setupSearchClearBtn } from "./util.js";
|
||||
import { extractAllMetadata, readAllPNGTextChunks } from "./metadata-tab.js";
|
||||
import { syncJsonHighlight, syncScroll } from "./json-highlight.js";
|
||||
import { _expandWildcardsInWorkflow } from "./generate-tab.js";
|
||||
|
||||
const COLUMN_KEYS = ["checkpoint", "vae", "prompt", "ksampler"];
|
||||
const MAX_RESULTS = 9;
|
||||
const RESULTS_GRID_COLS = 3;
|
||||
const LAB_PLAN_PREFIX = "ws_labplan_";
|
||||
const LAB_PLAN_PNG_KEY = "wfm_lab_plan";
|
||||
|
||||
function _defaultValueFor(col) {
|
||||
if (col === "prompt") return { positive: "", negative: "" };
|
||||
if (col === "prompt") return { positive: "", negative: "", styleApplied: false, styleName: "" };
|
||||
if (col === "ksampler") return { steps: null, cfg: null, sampler_name: "", scheduler: "", denoise: null, seed: null };
|
||||
return "";
|
||||
}
|
||||
|
||||
function _emptyColumns() {
|
||||
return {
|
||||
checkpoint: [{ atIteration: 1, value: "", revertToBase: false }],
|
||||
vae: [{ atIteration: 1, value: "", revertToBase: false }],
|
||||
prompt: [{ atIteration: 1, value: _defaultValueFor("prompt"), revertToBase: false }],
|
||||
ksampler: [{ atIteration: 1, value: _defaultValueFor("ksampler"), revertToBase: false }],
|
||||
checkpoint: [{ atIteration: 1, value: "", revertToBase: false, bypassed: false }],
|
||||
vae: [{ atIteration: 1, value: "", revertToBase: false, bypassed: false }],
|
||||
prompt: [{ atIteration: 1, value: _defaultValueFor("prompt"), revertToBase: false, bypassed: false }],
|
||||
ksampler: [{ atIteration: 1, value: _defaultValueFor("ksampler"), revertToBase: false, bypassed: false }],
|
||||
};
|
||||
}
|
||||
|
||||
@@ -41,7 +44,10 @@ function _emptyLabState() {
|
||||
note: "",
|
||||
batchCount: 4,
|
||||
chainImage: false,
|
||||
t2iMode: false,
|
||||
saveIndexOnRun: true,
|
||||
sourceImageFilename: null,
|
||||
workflowFilename: null,
|
||||
columns: _emptyColumns(),
|
||||
results: { images: [] },
|
||||
};
|
||||
@@ -67,6 +73,16 @@ export function initLabTab() {
|
||||
_initPlanJsonTab();
|
||||
_renderAllColumns();
|
||||
_renderResultsGrid();
|
||||
_updateT2IModeUI();
|
||||
}
|
||||
|
||||
// Re-renders the column grid so Setting 1's live-reflected cells (see _isLiveDisplay)
|
||||
// pick up whatever is currently loaded in GenerateUI. Called by generate-tab.js each
|
||||
// time its own Lab subtab is switched to — cells are static HTML rendered once, so
|
||||
// without this they'd stay frozen at whatever GenerateUI showed the last time Lab was
|
||||
// rendered, not "initially" reflecting the workflow as the user opens Lab now.
|
||||
export function refreshLabLiveDefaults() {
|
||||
_renderAllColumns();
|
||||
}
|
||||
|
||||
function _initDropZone() {
|
||||
@@ -75,7 +91,16 @@ function _initDropZone() {
|
||||
const previewWrap = document.getElementById("wfm-lab-preview-wrap");
|
||||
const previewImg = document.getElementById("wfm-lab-preview-img");
|
||||
|
||||
document.getElementById("wfm-lab-t2i-mode")?.addEventListener("change", (e) => {
|
||||
_lab.t2iMode = e.target.checked;
|
||||
_updateT2IModeUI();
|
||||
});
|
||||
|
||||
const applyFile = async (file) => {
|
||||
if (_lab.t2iMode) {
|
||||
showToast(t("labT2IImageIgnored"), "info");
|
||||
return;
|
||||
}
|
||||
if (!file || !file.type.startsWith("image/")) return;
|
||||
const url = URL.createObjectURL(file);
|
||||
if (previewImg) previewImg.src = url;
|
||||
@@ -173,17 +198,28 @@ function _initPlanJsonTab() {
|
||||
_syncLabJsonView();
|
||||
showToast(t("labPlanJsonApplied"), "success");
|
||||
});
|
||||
|
||||
const editor = document.getElementById("wfm-lab-planjson-editor");
|
||||
const highlight = document.getElementById("wfm-lab-planjson-highlight");
|
||||
editor?.addEventListener("scroll", () => syncScroll(editor, highlight));
|
||||
}
|
||||
|
||||
// Serializes the live Setting-tab state into the same shape saved to disk by
|
||||
// _savePlan(), for display/editing in the Plan JSON panel.
|
||||
function _buildPlanData(name) {
|
||||
// The workflow currently loaded in GenerateUI is what this plan actually ran
|
||||
// against — read it live so Save/Save As always records the up-to-date file.
|
||||
const wfNameEl = document.getElementById("wfm-gen-wf-name");
|
||||
const workflowFilename = wfNameEl?.dataset.filename || _lab.workflowFilename || "";
|
||||
return {
|
||||
name,
|
||||
note: _lab.note,
|
||||
batch_count: _lab.batchCount,
|
||||
chain_image: _lab.chainImage,
|
||||
t2i_mode: _lab.t2iMode,
|
||||
save_index_on_run: _lab.saveIndexOnRun,
|
||||
source_image: _lab.sourceImageFilename,
|
||||
workflow_filename: workflowFilename,
|
||||
columns: _lab.columns,
|
||||
results: { images: _lab.results.images },
|
||||
};
|
||||
@@ -193,20 +229,42 @@ function _syncLabJsonView() {
|
||||
const editor = document.getElementById("wfm-lab-planjson-editor");
|
||||
const highlight = document.getElementById("wfm-lab-planjson-highlight");
|
||||
if (!editor) return;
|
||||
const name = _lab.planFilename ? _lab.planFilename.replace(/\.json$/i, "") : "";
|
||||
const name = _lab.planFilename ? _stripLabPlanPrefix(_lab.planFilename.replace(/\.json$/i, "")) : "";
|
||||
const json = JSON.stringify(_buildPlanData(name), null, 2);
|
||||
editor.value = json;
|
||||
syncJsonHighlight(highlight, json);
|
||||
}
|
||||
|
||||
// Highest atIteration among all columns' keyframes — used to detect keyframes that
|
||||
// fall outside the current Batch count (they aren't deleted, just never reached by
|
||||
// the run loop, so it's easy to lower Batch count without noticing they went dormant).
|
||||
function _maxKeyframeIteration() {
|
||||
let max = 1;
|
||||
for (const col of COLUMN_KEYS) {
|
||||
for (const kf of _lab.columns[col] || []) {
|
||||
if (kf.atIteration > max) max = kf.atIteration;
|
||||
}
|
||||
}
|
||||
return max;
|
||||
}
|
||||
|
||||
function _warnIfKeyframesExceedBatch() {
|
||||
const maxIter = _maxKeyframeIteration();
|
||||
if (maxIter > _lab.batchCount) {
|
||||
showToast(t("labKeyframesExceedBatch", maxIter, _lab.batchCount), "error");
|
||||
}
|
||||
}
|
||||
|
||||
function _initRunControls() {
|
||||
document.getElementById("wfm-lab-batch-count")?.addEventListener("change", (e) => {
|
||||
const v = parseInt(e.target.value, 10);
|
||||
_lab.batchCount = (isNaN(v) || v < 1) ? 1 : v;
|
||||
e.target.value = _lab.batchCount;
|
||||
_warnIfKeyframesExceedBatch();
|
||||
});
|
||||
document.getElementById("wfm-lab-note")?.addEventListener("input", (e) => { _lab.note = e.target.value; });
|
||||
document.getElementById("wfm-lab-chain-image")?.addEventListener("change", (e) => { _lab.chainImage = e.target.checked; });
|
||||
document.getElementById("wfm-lab-save-index-on-run")?.addEventListener("change", (e) => { _lab.saveIndexOnRun = e.target.checked; });
|
||||
|
||||
document.getElementById("wfm-lab-run-btn")?.addEventListener("click", () => _runLabBatch());
|
||||
document.getElementById("wfm-lab-cancel-btn")?.addEventListener("click", async () => {
|
||||
@@ -227,6 +285,7 @@ function _initPlanButtons() {
|
||||
document.getElementById("wfm-lab-plan-save-btn")?.addEventListener("click", () => _savePlan());
|
||||
document.getElementById("wfm-lab-plan-saveas-btn")?.addEventListener("click", () => _savePlan(null, true));
|
||||
document.getElementById("wfm-lab-plan-clear-btn")?.addEventListener("click", () => _clearPlan());
|
||||
document.getElementById("wfm-lab-plan-workflow-load-btn")?.addEventListener("click", () => _loadPlanWorkflow());
|
||||
}
|
||||
|
||||
// ============================================
|
||||
@@ -243,7 +302,7 @@ function _initColumnButtons() {
|
||||
showToast(t("labBatchCountTooSmall"), "error");
|
||||
return;
|
||||
}
|
||||
kfs.push({ atIteration: lastIter + 1, value: _defaultValueFor(col), revertToBase: false });
|
||||
kfs.push({ atIteration: lastIter + 1, value: _defaultValueFor(col), revertToBase: false, bypassed: false });
|
||||
_renderColumn(col);
|
||||
_openCellModal(col, kfs.length - 1);
|
||||
});
|
||||
@@ -275,20 +334,28 @@ function _renderColumn(col) {
|
||||
|
||||
function _cellHtml(col, kf, idx) {
|
||||
const revertClass = kf.revertToBase ? " wfm-lab-cell-revert" : "";
|
||||
const bypassClass = kf.bypassed ? " wfm-lab-cell-bypassed" : "";
|
||||
if (idx === 0) {
|
||||
return `<div class="wfm-lab-cell${revertClass}" data-idx="${idx}">
|
||||
// Bypassed takes priority over the live-reflect display — an explicit "skip this
|
||||
// row" toggle shouldn't be masked by Setting 1's usual "show the workflow's
|
||||
// current value" behavior (see _isLiveDisplay).
|
||||
const live = !kf.bypassed && _isLiveDisplay(col, idx);
|
||||
const liveClass = live ? " wfm-lab-cell-live" : "";
|
||||
const label = live ? _cellLabel(col, { value: _liveValueFor(col), revertToBase: false, bypassed: false }) : _cellLabel(col, kf);
|
||||
return `<div class="wfm-lab-cell${revertClass}${bypassClass}${liveClass}" data-idx="${idx}">
|
||||
<span class="wfm-lab-cell-index">${kf.atIteration}:</span>
|
||||
<span class="wfm-lab-cell-value">${_cellLabel(col, kf)}</span>
|
||||
<span class="wfm-lab-cell-value">${label}</span>
|
||||
</div>`;
|
||||
}
|
||||
// Iteration #2 and beyond: value on its own line, applied-at iteration below it
|
||||
return `<div class="wfm-lab-cell${revertClass}" data-idx="${idx}">
|
||||
return `<div class="wfm-lab-cell${revertClass}${bypassClass}" data-idx="${idx}">
|
||||
<div class="wfm-lab-cell-value">${_cellLabel(col, kf)}</div>
|
||||
<div class="wfm-lab-cell-applied">${t("labAppliedAt", kf.atIteration)}</div>
|
||||
</div>`;
|
||||
}
|
||||
|
||||
function _cellLabel(col, kf) {
|
||||
if (kf.bypassed) return t("labBypassed");
|
||||
if (kf.revertToBase) return t("labRevertToBase");
|
||||
if (col === "checkpoint" || col === "vae") {
|
||||
return kf.value ? escapeHtml(kf.value) : t("labUseWorkflowDefault");
|
||||
@@ -321,10 +388,64 @@ function _isEmptyValue(col, value) {
|
||||
return true;
|
||||
}
|
||||
|
||||
// Reads the currently loaded GenerateUI workflow's live setting for a column. Used so
|
||||
// Setting 1 (the baseline keyframe, idx 0) visibly "keeps the workflow's setting" —
|
||||
// both in its grid cell and pre-filled into its modal — for as long as the user hasn't
|
||||
// explicitly saved an override on it. Returns null when nothing is loaded or the
|
||||
// workflow has no matching node, in which case callers fall back to the plain
|
||||
// "(workflow default)" placeholder as before.
|
||||
function _liveValueFor(col) {
|
||||
const analysis = comfyUI.currentAnalysis;
|
||||
if (!analysis) return null;
|
||||
if (col === "checkpoint") {
|
||||
return analysis.checkpoint_nodes?.[0]?.ckpt_name || null;
|
||||
}
|
||||
if (col === "vae") {
|
||||
return analysis.vae_nodes?.[0]?.vae_name || null;
|
||||
}
|
||||
if (col === "prompt") {
|
||||
const posNode = analysis.prompt_nodes?.find((n) => n.role === "positive");
|
||||
const negNode = analysis.prompt_nodes?.find((n) => n.role === "negative");
|
||||
if (!posNode && !negNode) return null;
|
||||
return { positive: posNode?.text || "", negative: negNode?.text || "", styleApplied: false, styleName: "" };
|
||||
}
|
||||
if (col === "ksampler") {
|
||||
const s = analysis.sampler_nodes?.[0];
|
||||
if (!s) return null;
|
||||
return {
|
||||
steps: s.steps ?? null, cfg: s.cfg ?? null,
|
||||
sampler_name: s.sampler_name || "", scheduler: s.scheduler || "",
|
||||
denoise: s.denoise ?? null, seed: s.seed ?? null,
|
||||
};
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
// True when a column/keyframe is currently showing the live GenerateUI value instead of
|
||||
// its own stored value — i.e. Setting 1, never explicitly overridden, with a workflow
|
||||
// actually loaded. Once the user saves an edit on it (even re-saving the same live
|
||||
// values), _isEmptyValue(col, kf.value) becomes false and this permanently stops
|
||||
// applying — the cell/modal switch to showing that saved override instead.
|
||||
function _isLiveDisplay(col, idx) {
|
||||
if (idx !== 0) return false;
|
||||
const kf = _lab.columns[col][0];
|
||||
if (kf.bypassed || !_isEmptyValue(col, kf.value)) return false;
|
||||
return _liveValueFor(col) != null;
|
||||
}
|
||||
|
||||
// Resolves what a keyframe should actually display/prefill with: its own stored value,
|
||||
// or — for a live-displaying Setting 1 — the current GenerateUI value in its place.
|
||||
function _effectiveDisplayValue(col, idx) {
|
||||
if (_isLiveDisplay(col, idx)) return _liveValueFor(col);
|
||||
return _lab.columns[col][idx]?.value;
|
||||
}
|
||||
|
||||
function _openCellModal(col, idx) {
|
||||
const kf = _lab.columns[col][idx];
|
||||
const isFirst = idx === 0;
|
||||
const isLast = idx === _lab.columns[col].length - 1;
|
||||
const live = _isLiveDisplay(col, idx);
|
||||
const effectiveValue = live ? _liveValueFor(col) : kf.value;
|
||||
const hasPrevious = col === "prompt" && idx > 0;
|
||||
|
||||
let valueFieldsHtml = "";
|
||||
if (col === "checkpoint" || col === "vae") {
|
||||
@@ -338,15 +459,17 @@ function _openCellModal(col, idx) {
|
||||
</div>
|
||||
<select id="wfm-lab-modal-value" class="wfm-select">
|
||||
<option value="">${t("labUseWorkflowDefault")}</option>
|
||||
${options.map((m) => `<option value="${escapeHtml(m)}" ${m === kf.value ? "selected" : ""}>${escapeHtml(m)}</option>`).join("")}
|
||||
${options.map((m) => `<option value="${escapeHtml(m)}" ${m === effectiveValue ? "selected" : ""}>${escapeHtml(m)}</option>`).join("")}
|
||||
</select>
|
||||
</div>`;
|
||||
} else if (col === "prompt") {
|
||||
const v = kf.value || {};
|
||||
const v = effectiveValue || {};
|
||||
valueFieldsHtml = `
|
||||
<div class="wfm-lab-modal-btnrow">
|
||||
<button type="button" id="wfm-lab-modal-get-genui" class="wfm-btn wfm-btn-sm">${t("labGetFromGenUI")}</button>
|
||||
<button type="button" id="wfm-lab-modal-get-image" class="wfm-btn wfm-btn-sm">${t("labGetFromImage")}</button>
|
||||
${hasPrevious ? `<button type="button" id="wfm-lab-modal-get-previous" class="wfm-btn wfm-btn-sm">${t("labGetFromPrevious")}</button>` : ""}
|
||||
<button type="button" id="wfm-lab-modal-clear" class="wfm-btn wfm-btn-sm">${t("labClearPrompt")}</button>
|
||||
</div>
|
||||
<div class="wfm-lab-modal-row">
|
||||
<label>Positive</label>
|
||||
@@ -356,12 +479,14 @@ function _openCellModal(col, idx) {
|
||||
<label>Negative</label>
|
||||
<textarea id="wfm-lab-modal-negative" class="wfm-input" rows="3">${escapeHtml(v.negative || "")}</textarea>
|
||||
</div>
|
||||
<div class="wfm-lab-modal-row">
|
||||
<label>${t("labStyle")}</label>
|
||||
<div class="wfm-lab-modal-checkbox">
|
||||
<input type="checkbox" id="wfm-lab-modal-style-toggle" ${v.styleApplied ? "checked" : ""}>
|
||||
<label for="wfm-lab-modal-style-toggle">${t("labStyle")}</label>
|
||||
<button type="button" id="wfm-lab-modal-style-apply" class="wfm-btn wfm-btn-sm">${t("labApply")}</button>
|
||||
<span id="wfm-lab-modal-style-name" style="color:var(--wfm-text-secondary);">${v.styleApplied && v.styleName ? escapeHtml(v.styleName) : ""}</span>
|
||||
</div>`;
|
||||
} else if (col === "ksampler") {
|
||||
const v = kf.value || {};
|
||||
const v = effectiveValue || {};
|
||||
const samplers = comfyEditor.models.samplers || [];
|
||||
const schedulers = comfyEditor.models.schedulers || [];
|
||||
valueFieldsHtml = `
|
||||
@@ -402,29 +527,52 @@ function _openCellModal(col, idx) {
|
||||
<label for="wfm-lab-modal-revert">${t("labRevertCheckboxLabel")}</label>
|
||||
</div>`;
|
||||
|
||||
const deleteBtn = (!isFirst && isLast)
|
||||
// Bypass is available on every row, including Setting 1: skip this keyframe's
|
||||
// override entirely (as if the row didn't exist) so whatever was active before it
|
||||
// keeps running — see _resolveKeyframe. Lab-internal only; never touches the actual
|
||||
// ComfyUI node's mode.
|
||||
const bypassRow = `
|
||||
<div class="wfm-lab-modal-checkbox">
|
||||
<input type="checkbox" id="wfm-lab-modal-bypass" ${kf.bypassed ? "checked" : ""}>
|
||||
<label for="wfm-lab-modal-bypass">${t("labBypassCheckboxLabel")}</label>
|
||||
</div>`;
|
||||
|
||||
const deleteBtn = !isFirst
|
||||
? `<button id="wfm-lab-modal-delete" class="wfm-btn wfm-btn-danger">${t("delete")}</button>` : "";
|
||||
|
||||
const liveHint = live ? `<p class="wfm-lab-modal-hint">${t("labLiveHint")}</p>` : "";
|
||||
|
||||
const html = `
|
||||
${liveHint}
|
||||
<div id="wfm-lab-modal-fields">${valueFieldsHtml}</div>
|
||||
${atIterRow}
|
||||
${bypassRow}
|
||||
${revertRow}
|
||||
<div style="display:flex;gap:8px;margin-top:12px;justify-content:flex-end;">
|
||||
${deleteBtn}
|
||||
<button id="wfm-lab-modal-save" class="wfm-btn wfm-btn-primary">${t("save")}</button>
|
||||
</div>`;
|
||||
openModal(`${col} #${idx + 1}`, html);
|
||||
if (col === "prompt") _wireLabPromptModalExtras();
|
||||
if (col === "prompt") _wireLabPromptModalExtras(idx);
|
||||
if (col === "checkpoint" || col === "vae") _wireLabValueFilter(col);
|
||||
|
||||
// Bypass disables everything else on the modal (value fields AND the Revert
|
||||
// checkbox) — the two are mutually exclusive since bypass already means "ignore
|
||||
// this row", making a simultaneous revertToBase moot.
|
||||
const revertCb = document.getElementById("wfm-lab-modal-revert");
|
||||
const bypassCb = document.getElementById("wfm-lab-modal-bypass");
|
||||
const fieldsWrap = document.getElementById("wfm-lab-modal-fields");
|
||||
const revertRowEl = revertCb?.closest(".wfm-lab-modal-checkbox");
|
||||
const syncDisabled = () => {
|
||||
const disabled = !!revertCb?.checked;
|
||||
if (fieldsWrap) fieldsWrap.style.opacity = disabled ? "0.4" : "1";
|
||||
fieldsWrap?.querySelectorAll("input,select,textarea").forEach((el) => { el.disabled = disabled; });
|
||||
const bypassed = !!bypassCb?.checked;
|
||||
const fieldsDisabled = bypassed || !!revertCb?.checked;
|
||||
if (fieldsWrap) fieldsWrap.style.opacity = fieldsDisabled ? "0.4" : "1";
|
||||
fieldsWrap?.querySelectorAll("input,select,textarea").forEach((el) => { el.disabled = fieldsDisabled; });
|
||||
if (revertCb) revertCb.disabled = bypassed;
|
||||
if (revertRowEl) revertRowEl.style.opacity = bypassed ? "0.4" : "1";
|
||||
};
|
||||
revertCb?.addEventListener("change", syncDisabled);
|
||||
bypassCb?.addEventListener("change", syncDisabled);
|
||||
syncDisabled();
|
||||
|
||||
document.getElementById("wfm-lab-modal-delete")?.addEventListener("click", () => {
|
||||
@@ -435,6 +583,7 @@ function _openCellModal(col, idx) {
|
||||
|
||||
document.getElementById("wfm-lab-modal-save")?.addEventListener("click", () => {
|
||||
const revert = !!document.getElementById("wfm-lab-modal-revert")?.checked;
|
||||
const bypassed = !!document.getElementById("wfm-lab-modal-bypass")?.checked;
|
||||
let atIteration = kf.atIteration;
|
||||
if (!isFirst) {
|
||||
const parsed = parseInt(document.getElementById("wfm-lab-modal-iter")?.value, 10);
|
||||
@@ -442,13 +591,15 @@ function _openCellModal(col, idx) {
|
||||
}
|
||||
|
||||
let value = kf.value;
|
||||
if (!revert) {
|
||||
if (!revert && !bypassed) {
|
||||
if (col === "checkpoint" || col === "vae") {
|
||||
value = document.getElementById("wfm-lab-modal-value")?.value || "";
|
||||
} else if (col === "prompt") {
|
||||
value = {
|
||||
positive: document.getElementById("wfm-lab-modal-positive")?.value || "",
|
||||
negative: document.getElementById("wfm-lab-modal-negative")?.value || "",
|
||||
styleApplied: !!document.getElementById("wfm-lab-modal-style-toggle")?.checked,
|
||||
styleName: document.getElementById("wfm-lab-modal-style-name")?.textContent || "",
|
||||
};
|
||||
} else if (col === "ksampler") {
|
||||
const numOrNull = (id) => {
|
||||
@@ -466,7 +617,7 @@ function _openCellModal(col, idx) {
|
||||
}
|
||||
}
|
||||
|
||||
_lab.columns[col][idx] = { atIteration, value, revertToBase: revert };
|
||||
_lab.columns[col][idx] = { atIteration, value, revertToBase: revert, bypassed };
|
||||
_lab.columns[col].sort((a, b) => a.atIteration - b.atIteration);
|
||||
_renderColumn(col);
|
||||
closeModal();
|
||||
@@ -512,22 +663,48 @@ function _wireLabValueFilter(col) {
|
||||
}
|
||||
|
||||
// Wires the Prompt-column modal's extra actions: fetch the live GenerateUI prompt,
|
||||
// extract a prompt from a dropped image/workflow file, and apply a saved Style.
|
||||
function _wireLabPromptModalExtras() {
|
||||
// Reuses the Style checkbox/dropdown already at the top of the GenerateUI toolbar
|
||||
// (populated by generate-tab.js's _loadStyles()) instead of duplicating a second
|
||||
// style picker inside this modal.
|
||||
// extract a prompt from a dropped image/workflow file, copy the previous keyframe's
|
||||
// prompt, clear the fields, and apply/toggle a saved Style. idx is this keyframe's own
|
||||
// position in _lab.columns.prompt (needed for the "Get from Previous" lookup).
|
||||
function _wireLabPromptModalExtras(idx) {
|
||||
document.getElementById("wfm-lab-modal-clear")?.addEventListener("click", () => {
|
||||
const posEl = document.getElementById("wfm-lab-modal-positive");
|
||||
const negEl = document.getElementById("wfm-lab-modal-negative");
|
||||
if (posEl) posEl.value = "";
|
||||
if (negEl) negEl.value = "";
|
||||
showToast(t("labPromptCleared"), "success");
|
||||
});
|
||||
|
||||
// Copies BOTH positive and negative from the keyframe immediately before this one
|
||||
// (idx - 1) in the same column — e.g. editing #3 copies #2's prompt wholesale. If #2
|
||||
// is itself the unedited Setting 1, this naturally picks up its live GenerateUI value
|
||||
// via _effectiveDisplayValue() rather than an empty string.
|
||||
document.getElementById("wfm-lab-modal-get-previous")?.addEventListener("click", () => {
|
||||
if (idx <= 0) return;
|
||||
const prev = _effectiveDisplayValue("prompt", idx - 1) || {};
|
||||
const posEl = document.getElementById("wfm-lab-modal-positive");
|
||||
const negEl = document.getElementById("wfm-lab-modal-negative");
|
||||
if (posEl) posEl.value = prev.positive || "";
|
||||
if (negEl) negEl.value = prev.negative || "";
|
||||
showToast(t("labPromptCopiedFromPrevious"), "success");
|
||||
});
|
||||
|
||||
// Style NAME always comes from the dropdown already at the top of the GenerateUI
|
||||
// toolbar (populated by generate-tab.js's _loadStyles()) — Lab has no picker of its
|
||||
// own. The Apply button merges it into the text below (independent of the top
|
||||
// toolbar's own enable checkbox); the checkbox only tracks on/off state and shows/
|
||||
// clears the applied name — it never merges text by itself.
|
||||
const styleToggle = document.getElementById("wfm-lab-modal-style-toggle");
|
||||
const styleApplyBtn = document.getElementById("wfm-lab-modal-style-apply");
|
||||
const topStyleName = document.getElementById("wfm-style-select")?.value;
|
||||
const topStyleEnabled = !!document.getElementById("wfm-style-enabled")?.checked;
|
||||
if (styleApplyBtn) {
|
||||
styleApplyBtn.textContent = (topStyleEnabled && topStyleName) ? `${t("labApply")}: ${topStyleName}` : t("labApply");
|
||||
}
|
||||
const styleNameEl = document.getElementById("wfm-lab-modal-style-name");
|
||||
|
||||
styleToggle?.addEventListener("change", () => {
|
||||
if (!styleToggle.checked && styleNameEl) styleNameEl.textContent = "";
|
||||
});
|
||||
|
||||
styleApplyBtn?.addEventListener("click", async () => {
|
||||
const enabled = !!document.getElementById("wfm-style-enabled")?.checked;
|
||||
const styleName = document.getElementById("wfm-style-select")?.value;
|
||||
if (!enabled || !styleName) {
|
||||
if (!styleName) {
|
||||
showToast(t("labEnableStyleFirst"), "error");
|
||||
return;
|
||||
}
|
||||
@@ -537,13 +714,18 @@ function _wireLabPromptModalExtras() {
|
||||
styles = res.ok ? await res.json() : [];
|
||||
} catch { styles = []; }
|
||||
const style = styles.find((s) => s.name === styleName);
|
||||
if (!style) { showToast(t("labNoStyles"), "error"); return; }
|
||||
if (!style) {
|
||||
showToast(t("labNoStyles"), "error");
|
||||
return;
|
||||
}
|
||||
|
||||
const posEl = document.getElementById("wfm-lab-modal-positive");
|
||||
const negEl = document.getElementById("wfm-lab-modal-negative");
|
||||
const merged = _applyStyleToText(posEl?.value || "", negEl?.value || "", style);
|
||||
if (posEl) posEl.value = merged.positive;
|
||||
if (negEl) negEl.value = merged.negative;
|
||||
if (styleToggle) styleToggle.checked = true;
|
||||
if (styleNameEl) styleNameEl.textContent = styleName;
|
||||
showToast(t("labStyleApplied"), "success");
|
||||
});
|
||||
|
||||
@@ -593,17 +775,22 @@ function _wireLabPromptModalExtras() {
|
||||
// Effective-value resolution & workflow build
|
||||
// ============================================
|
||||
|
||||
// A bypassed keyframe is skipped entirely when picking which row is "in effect" for a
|
||||
// given iteration — as if it weren't there — so whatever was active before it (an
|
||||
// earlier keyframe, or ultimately nothing) just keeps running. This only affects
|
||||
// which row *applies*; the bypassed row's own value/atIteration stay untouched so
|
||||
// un-bypassing it later restores it exactly as configured.
|
||||
function _resolveKeyframe(col, iteration) {
|
||||
const kfs = _lab.columns[col];
|
||||
let applicable = null;
|
||||
for (const kf of kfs) {
|
||||
if (kf.atIteration <= iteration) applicable = kf;
|
||||
else break;
|
||||
if (kf.atIteration > iteration) break;
|
||||
if (!kf.bypassed) applicable = kf;
|
||||
}
|
||||
if (!applicable) return null;
|
||||
if (applicable.revertToBase) {
|
||||
const row1 = kfs.find((k) => k.atIteration === 1);
|
||||
return (row1 && !_isEmptyValue(col, row1.value)) ? row1.value : null;
|
||||
return (row1 && !row1.bypassed && !_isEmptyValue(col, row1.value)) ? row1.value : null;
|
||||
}
|
||||
return _isEmptyValue(col, applicable.value) ? null : applicable.value;
|
||||
}
|
||||
@@ -623,8 +810,19 @@ function _buildWorkflowForIteration(iteration, chainImageRef) {
|
||||
}
|
||||
|
||||
const vae = _resolveKeyframe("vae", iteration);
|
||||
if (vae && analysis.vae_nodes?.[0]) {
|
||||
write(analysis.vae_nodes[0].id, "vae_name", vae);
|
||||
if (vae) {
|
||||
const vaeNode = analysis.vae_nodes?.[0];
|
||||
if (vaeNode && wf[vaeNode.id]) {
|
||||
write(vaeNode.id, "vae_name", vae);
|
||||
} else {
|
||||
// Workflow has no standalone VAELoader node (VAE baked into the checkpoint) —
|
||||
// inject one and repoint every "vae" input link at it so the override actually applies.
|
||||
const newId = String(Math.max(0, ...Object.keys(wf).map(Number)) + 1);
|
||||
wf[newId] = { class_type: "VAELoader", inputs: { vae_name: vae }, _meta: { title: "VAE Loader" } };
|
||||
for (const node of Object.values(wf)) {
|
||||
if (Array.isArray(node?.inputs?.vae)) node.inputs.vae = [newId, 0];
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const prompt = _resolveKeyframe("prompt", iteration);
|
||||
@@ -647,7 +845,7 @@ function _buildWorkflowForIteration(iteration, chainImageRef) {
|
||||
if (ks.seed != null) seed = ks.seed;
|
||||
}
|
||||
|
||||
const imageRef = chainImageRef || _lab.sourceImageFilename;
|
||||
const imageRef = _lab.t2iMode ? null : (chainImageRef || _lab.sourceImageFilename);
|
||||
if (imageRef && analysis.load_image_nodes?.[0]) {
|
||||
write(analysis.load_image_nodes[0].id, "image", imageRef);
|
||||
}
|
||||
@@ -688,7 +886,7 @@ async function _runLabBatch() {
|
||||
showToast(t("labNoWorkflowLoaded"), "error");
|
||||
return;
|
||||
}
|
||||
if (!_lab.sourceImageFilename) {
|
||||
if (!_lab.t2iMode && !_lab.sourceImageFilename) {
|
||||
showToast(t("labNoSourceImage"), "error");
|
||||
return;
|
||||
}
|
||||
@@ -712,11 +910,12 @@ async function _runLabBatch() {
|
||||
if (_aborted) break;
|
||||
|
||||
if (progressText) progressText.textContent = `[${i}/${_lab.batchCount}] ...`;
|
||||
const chainRef = (_lab.chainImage && i > 1) ? _lastGeneratedImageRef : null;
|
||||
const chainRef = (!_lab.t2iMode && _lab.chainImage && i > 1) ? _lastGeneratedImageRef : null;
|
||||
const { workflow, seed } = _buildWorkflowForIteration(i, chainRef);
|
||||
const workflowExpanded = await _expandWildcardsInWorkflow(workflow);
|
||||
|
||||
try {
|
||||
const { images } = await comfyUI.generate(workflow, {
|
||||
const { images } = await comfyUI.generate(workflowExpanded, {
|
||||
seedMode: seed != null ? "fixed" : "random",
|
||||
seedValue: seed ?? -1,
|
||||
onProgress: (pct) => {
|
||||
@@ -751,6 +950,8 @@ async function _runLabBatch() {
|
||||
_setRunUiState(false);
|
||||
}
|
||||
|
||||
await _maybeSaveIndexImageOnRun();
|
||||
|
||||
if (progressBar) progressBar.style.width = "100%";
|
||||
if (_aborted) {
|
||||
showToast(t("batchStopped", completed, failed), "info");
|
||||
@@ -788,13 +989,31 @@ function _renderResultsGrid() {
|
||||
|
||||
function _updateResultsSourceImage() {
|
||||
const img = document.getElementById("wfm-lab-results-source-img");
|
||||
const t2iNote = document.getElementById("wfm-lab-results-t2i-note");
|
||||
if (!img) return;
|
||||
if (_lab.sourceImageFilename) {
|
||||
if (!_lab.t2iMode && _lab.sourceImageFilename) {
|
||||
img.src = `/view?filename=${encodeURIComponent(_lab.sourceImageFilename)}&type=input`;
|
||||
img.style.display = "";
|
||||
} else {
|
||||
img.style.display = "none";
|
||||
}
|
||||
if (t2iNote) t2iNote.style.display = _lab.t2iMode ? "" : "none";
|
||||
}
|
||||
|
||||
// Greys out image-related controls that don't apply to a T2I workflow (no
|
||||
// LoadImage node to feed): the drop zone and the "use generated image for
|
||||
// next" chain checkbox. Doesn't clear any already-uploaded source image, so
|
||||
// toggling back to I2I restores prior state.
|
||||
function _updateT2IModeUI() {
|
||||
const t2iEl = document.getElementById("wfm-lab-t2i-mode");
|
||||
const dropZone = document.getElementById("wfm-lab-drop-zone");
|
||||
const previewWrap = document.getElementById("wfm-lab-preview-wrap");
|
||||
const chainEl = document.getElementById("wfm-lab-chain-image");
|
||||
if (t2iEl) t2iEl.checked = _lab.t2iMode;
|
||||
if (dropZone) dropZone.classList.toggle("wfm-disabled", _lab.t2iMode);
|
||||
if (previewWrap && _lab.t2iMode) previewWrap.style.display = "none";
|
||||
if (chainEl) chainEl.disabled = _lab.t2iMode;
|
||||
_updateResultsSourceImage();
|
||||
}
|
||||
|
||||
// ============================================
|
||||
@@ -810,7 +1029,11 @@ function _loadImageEl(src) {
|
||||
});
|
||||
}
|
||||
|
||||
async function _buildIndexImageDataUrl() {
|
||||
// planData, when given, is embedded into the resulting PNG as an iTXt chunk
|
||||
// (LAB_PLAN_PNG_KEY) so the image alone — dropped onto the Plan drop zone, from
|
||||
// anywhere, not just lab_plan/ — can be loaded back without needing a same-named
|
||||
// .json alongside it on the server.
|
||||
async function _buildIndexImageDataUrl(planData) {
|
||||
const imgs = _lab.results.images.slice(0, MAX_RESULTS);
|
||||
if (imgs.length === 0) return null;
|
||||
|
||||
@@ -832,29 +1055,76 @@ async function _buildIndexImageDataUrl() {
|
||||
const w = im.width * scale, h = im.height * scale;
|
||||
ctx.drawImage(im, col * cellSize - (w - cellSize) / 2, row * cellSize - (h - cellSize) / 2, w, h);
|
||||
}
|
||||
return canvas.toDataURL("image/png");
|
||||
const dataUrl = canvas.toDataURL("image/png");
|
||||
if (!planData) return dataUrl;
|
||||
try {
|
||||
return embedPngTextChunk(dataUrl, LAB_PLAN_PNG_KEY, JSON.stringify(planData));
|
||||
} catch (err) {
|
||||
console.warn("Failed to embed Lab plan metadata into index image:", err);
|
||||
return dataUrl;
|
||||
}
|
||||
}
|
||||
|
||||
// When "Save index image to Output on Run" is checked, builds the same
|
||||
// contact-sheet used for Plan files and writes it into ComfyUI's own Output
|
||||
// folder (auto-numbered, like a normal generated image) — independent of
|
||||
// Plan Save, which always writes its own copy next to the plan file. Once it
|
||||
// has a real file in Output, it also feeds it through the same Eagle
|
||||
// auto-save path as every other Lab-generated image (single global toggle
|
||||
// in Settings, no separate checkbox here).
|
||||
async function _maybeSaveIndexImageOnRun() {
|
||||
if (!_lab.saveIndexOnRun) return;
|
||||
try {
|
||||
const name = _lab.planFilename ? _stripLabPlanPrefix(_lab.planFilename.replace(/\.json$/i, "")) : "";
|
||||
const dataUrl = await _buildIndexImageDataUrl(_buildPlanData(name));
|
||||
if (!dataUrl) return;
|
||||
const res = await fetch("/api/wfm/lab/index-image/save-to-output", {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify({ image_base64: dataUrl }),
|
||||
});
|
||||
const json = await res.json();
|
||||
if (!res.ok) throw new Error(json.error || `HTTP ${res.status}`);
|
||||
showToast(t("labIndexImageSaved", json.filename), "success");
|
||||
|
||||
if (getEagleSettings().autoSave) {
|
||||
const viewUrl = `/view?filename=${encodeURIComponent(json.filename)}&subfolder=${encodeURIComponent(json.subfolder || "")}&type=output`;
|
||||
saveToEagle(viewUrl, json.filename, [], { filename: json.filename, subfolder: json.subfolder || "", type: "output" });
|
||||
}
|
||||
} catch (err) {
|
||||
showToast(`${t("labIndexImageSaveFailed")}: ${err.message}`, "error");
|
||||
}
|
||||
}
|
||||
|
||||
// ============================================
|
||||
// Plan save / load / clear
|
||||
// ============================================
|
||||
|
||||
// Plan files are always saved with the ws_labplan_ prefix so they're easy to
|
||||
// spot (and script against) among other files in lab_plan/. Existing plans
|
||||
// that already carry it are re-saved as-is rather than double-prefixed.
|
||||
function _stripLabPlanPrefix(base) {
|
||||
return base.toLowerCase().startsWith(LAB_PLAN_PREFIX) ? base.slice(LAB_PLAN_PREFIX.length) : base;
|
||||
}
|
||||
|
||||
async function _savePlan(filenameOverride, forceNewName = false) {
|
||||
let filename = filenameOverride;
|
||||
if (!filename) {
|
||||
let inputName = filenameOverride;
|
||||
if (!inputName) {
|
||||
if (forceNewName || !_lab.planFilename) {
|
||||
filename = window.prompt(t("labEnterPlanName"), forceNewName ? "" : (_lab.planFilename || ""));
|
||||
if (!filename) return;
|
||||
inputName = window.prompt(t("labEnterPlanName"), "");
|
||||
if (!inputName) return;
|
||||
} else {
|
||||
filename = _lab.planFilename;
|
||||
inputName = _lab.planFilename;
|
||||
}
|
||||
}
|
||||
|
||||
const data = _buildPlanData(filename.replace(/\.json$/i, ""));
|
||||
const baseName = _stripLabPlanPrefix(inputName.replace(/\.json$/i, ""));
|
||||
const filename = `${LAB_PLAN_PREFIX}${baseName}.json`;
|
||||
const data = _buildPlanData(baseName);
|
||||
|
||||
let indexImageBase64 = null;
|
||||
try {
|
||||
indexImageBase64 = await _buildIndexImageDataUrl();
|
||||
indexImageBase64 = await _buildIndexImageDataUrl(data);
|
||||
} catch { /* thumbnail generation is best-effort */ }
|
||||
|
||||
try {
|
||||
@@ -866,6 +1136,8 @@ async function _savePlan(filenameOverride, forceNewName = false) {
|
||||
const json = await res.json();
|
||||
if (!res.ok) throw new Error(json.error || `HTTP ${res.status}`);
|
||||
_lab.planFilename = json.filename;
|
||||
_lab.workflowFilename = data.workflow_filename || null;
|
||||
_updatePlanWorkflowUI();
|
||||
showToast(t("labPlanSaved"), "success");
|
||||
} catch (err) {
|
||||
showToast(`${t("labPlanSaveFailed")}: ${err.message}`, "error");
|
||||
@@ -877,16 +1149,23 @@ function _applyPlanData(filename, data) {
|
||||
_lab.note = data.note || "";
|
||||
_lab.batchCount = data.batch_count || 1;
|
||||
_lab.chainImage = !!data.chain_image;
|
||||
_lab.t2iMode = !!data.t2i_mode;
|
||||
_lab.saveIndexOnRun = !!data.save_index_on_run;
|
||||
_lab.sourceImageFilename = data.source_image || null;
|
||||
_lab.workflowFilename = data.workflow_filename || null;
|
||||
_lab.columns = data.columns || _emptyColumns();
|
||||
_lab.results = { images: (data.results?.images || []).slice(0, MAX_RESULTS) };
|
||||
_updatePlanWorkflowUI();
|
||||
_updateT2IModeUI();
|
||||
|
||||
const noteEl = document.getElementById("wfm-lab-note");
|
||||
const batchEl = document.getElementById("wfm-lab-batch-count");
|
||||
const chainEl = document.getElementById("wfm-lab-chain-image");
|
||||
const saveIndexEl = document.getElementById("wfm-lab-save-index-on-run");
|
||||
if (noteEl) noteEl.value = _lab.note;
|
||||
if (batchEl) batchEl.value = _lab.batchCount;
|
||||
if (chainEl) chainEl.checked = _lab.chainImage;
|
||||
if (saveIndexEl) saveIndexEl.checked = _lab.saveIndexOnRun;
|
||||
|
||||
const previewWrap = document.getElementById("wfm-lab-preview-wrap");
|
||||
const previewImg = document.getElementById("wfm-lab-preview-img");
|
||||
@@ -900,6 +1179,7 @@ function _applyPlanData(filename, data) {
|
||||
_renderAllColumns();
|
||||
_renderResultsGrid();
|
||||
_updateResultsSourceImage();
|
||||
_warnIfKeyframesExceedBatch();
|
||||
}
|
||||
|
||||
// Plan Load reads a dropped/picked .json plan file directly in the browser (no
|
||||
@@ -918,11 +1198,25 @@ async function _loadPlanFromFile(file) {
|
||||
}
|
||||
}
|
||||
|
||||
// Dropping the index-image thumbnail (same basename as its .json, saved
|
||||
// alongside it on the server) fetches the actual plan JSON by that filename.
|
||||
// Dropping the index-image thumbnail. Since v0.3.90 every index image (both the
|
||||
// lab_plan/ companion PNG from Plan Save, and the Output-folder copy from "Save
|
||||
// index image to Output on Run") carries the full plan data embedded as a
|
||||
// LAB_PLAN_PNG_KEY iTXt chunk, so it can be read directly from the dropped file
|
||||
// with no server round-trip — this is the only way to load a plan back from an
|
||||
// Output-folder PNG, which has no same-named .json anywhere. Falls back to the
|
||||
// old same-basename server lookup for older index images saved before this.
|
||||
async function _loadPlanFromIndexImage(file) {
|
||||
const stem = file.name.replace(/\.[^.]+$/, "");
|
||||
await _loadPlanFromServer(`${stem}.json`);
|
||||
const filename = `${stem}.json`;
|
||||
try {
|
||||
const chunks = await readAllPNGTextChunks(file);
|
||||
if (chunks?.[LAB_PLAN_PNG_KEY]) {
|
||||
_applyPlanData(filename, JSON.parse(chunks[LAB_PLAN_PNG_KEY]));
|
||||
showToast(t("labPlanLoaded"), "success");
|
||||
return;
|
||||
}
|
||||
} catch { /* fall through to the server lookup below */ }
|
||||
await _loadPlanFromServer(filename);
|
||||
}
|
||||
|
||||
async function _loadPlanFromServer(filename) {
|
||||
@@ -944,9 +1238,11 @@ function _clearPlan() {
|
||||
const noteEl = document.getElementById("wfm-lab-note");
|
||||
const batchEl = document.getElementById("wfm-lab-batch-count");
|
||||
const chainEl = document.getElementById("wfm-lab-chain-image");
|
||||
const saveIndexEl = document.getElementById("wfm-lab-save-index-on-run");
|
||||
if (noteEl) noteEl.value = "";
|
||||
if (batchEl) batchEl.value = _lab.batchCount;
|
||||
if (chainEl) chainEl.checked = false;
|
||||
if (chainEl) chainEl.checked = _lab.chainImage;
|
||||
if (saveIndexEl) saveIndexEl.checked = _lab.saveIndexOnRun;
|
||||
|
||||
const previewWrap = document.getElementById("wfm-lab-preview-wrap");
|
||||
if (previewWrap) previewWrap.style.display = "none";
|
||||
@@ -954,4 +1250,44 @@ function _clearPlan() {
|
||||
_renderAllColumns();
|
||||
_renderResultsGrid();
|
||||
_updateResultsSourceImage();
|
||||
_updatePlanWorkflowUI();
|
||||
_updateT2IModeUI();
|
||||
}
|
||||
|
||||
// ============================================
|
||||
// Plan → workflow recall
|
||||
// ============================================
|
||||
|
||||
// Shows/hides the recorded-workflow row in the Plan pane based on _lab.workflowFilename.
|
||||
function _updatePlanWorkflowUI() {
|
||||
const row = document.getElementById("wfm-lab-plan-workflow-row");
|
||||
const nameEl = document.getElementById("wfm-lab-plan-workflow-name");
|
||||
if (!row || !nameEl) return;
|
||||
if (_lab.workflowFilename) {
|
||||
nameEl.textContent = _lab.workflowFilename;
|
||||
nameEl.title = _lab.workflowFilename;
|
||||
row.style.display = "";
|
||||
} else {
|
||||
row.style.display = "none";
|
||||
}
|
||||
}
|
||||
|
||||
// Loads the plan's recorded workflow file into GenerateUI, replacing whatever is
|
||||
// currently loaded there. Requires explicit confirmation — Lab never swaps the
|
||||
// active workflow on its own (e.g. when a plan is loaded via drag & drop).
|
||||
// Uses a dynamic import to avoid a static circular import with generate-tab.js,
|
||||
// which already imports initLabTab from this file.
|
||||
async function _loadPlanWorkflow() {
|
||||
const filename = _lab.workflowFilename;
|
||||
if (!filename) return;
|
||||
if (!window.confirm(t("labConfirmLoadWorkflow", filename))) return;
|
||||
try {
|
||||
const resp = await fetch(`/api/wfm/workflows/raw?filename=${encodeURIComponent(filename)}`);
|
||||
if (!resp.ok) throw new Error(`HTTP ${resp.status}`);
|
||||
const data = await resp.json();
|
||||
const { loadWorkflowIntoEditor } = await import("./generate-tab.js");
|
||||
await loadWorkflowIntoEditor(data, filename);
|
||||
} catch (err) {
|
||||
showToast(`${t("labWorkflowLoadFailed")}: ${err.message}`, "error");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -75,7 +75,7 @@ function parseITXtChunk(data, latin1, utf8) {
|
||||
pos = findNull(data, pos); if (pos === -1) return null; pos++;
|
||||
return { keyword, text: utf8.decode(data.slice(pos)) };
|
||||
}
|
||||
async function readAllPNGTextChunks(file) {
|
||||
export async function readAllPNGTextChunks(file) {
|
||||
const buffer = await file.arrayBuffer();
|
||||
const bytes = new Uint8Array(buffer);
|
||||
const PNG_SIG = [0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a];
|
||||
@@ -188,6 +188,21 @@ function isTextEncoderNode(ct) { return ct === "CLIPTextEncode" || ct.includes("
|
||||
function isSamplerNode(ct) { return ct === "KSampler" || ct === "KSamplerAdvanced" || ct.includes("KSampler") || ct.includes("Sampler"); }
|
||||
function isPromptStylerNode(ct) { return ct.includes("PromptStyler"); }
|
||||
|
||||
// CLIPTextEncodeEditPlus (model-and-prompt-from-metadata) の encode() と同じ結合ルール。
|
||||
// RAW: text1のみ。EDIT: text_editのみ。front/back: text2(未接続ならtext_edit)をtext1の前/後に結合。
|
||||
function resolveEditPlusText(mode, textEdit, text1, text2) {
|
||||
const t1 = typeof text1 === "string" ? text1 : "";
|
||||
const edit = typeof textEdit === "string" ? textEdit : "";
|
||||
const insert = typeof text2 === "string" && text2 !== "" ? text2 : edit;
|
||||
switch (mode) {
|
||||
case "RAW": return t1;
|
||||
case "EDIT": return edit;
|
||||
case "front": return t1 ? `${insert}, ${t1}` : insert;
|
||||
case "back": return t1 ? `${t1}, ${insert}` : insert;
|
||||
default: return t1 || edit;
|
||||
}
|
||||
}
|
||||
|
||||
function extractPrompts(wf) {
|
||||
if (!wf || typeof wf !== "object") return { positives: [], negatives: [] };
|
||||
return Array.isArray(wf.nodes) ? extractPromptsLiteGraph(wf) : extractPromptsAPI(wf);
|
||||
@@ -221,8 +236,10 @@ function resolveLinkedTextInNodeSet(nodeMap, linkOrigin, linkSlot, srcId, slot,
|
||||
const v = srcNode.widgets_values?.[slot] ?? srcNode.widgets_values?.[0];
|
||||
if (v && typeof v === "string") return v;
|
||||
// さらにリンクされている場合(StringReplace等の中継ノード)は追跡する
|
||||
// "source" = PreviewAny(値タップ中継), "string_a" = StringConcatenate(LoRAトリガーワード
|
||||
// 連結等)— Krea-2のプロンプト強化配線で使われる中継ノード
|
||||
if (Array.isArray(srcNode.inputs)) {
|
||||
const nextInput = srcNode.inputs.find(i => ["text", "value", "prompt", "string"].includes(i.name));
|
||||
const nextInput = srcNode.inputs.find(i => ["text", "value", "prompt", "string", "source", "string_a"].includes(i.name));
|
||||
if (nextInput?.link != null) {
|
||||
const originId = linkOrigin.get(nextInput.link);
|
||||
const originSlot = linkSlot.get(nextInput.link) ?? 0;
|
||||
@@ -251,7 +268,22 @@ function extractPromptsFromNodeSet(nodes, links) {
|
||||
}
|
||||
const textMap = new Map();
|
||||
for (const n of nodes) {
|
||||
if (!isTextEncoderNode(n.type ?? "")) continue;
|
||||
const type = n.type ?? "";
|
||||
if (type === "CLIPTextEncodeEditPlus") {
|
||||
const resolveNamedInput = (name) => {
|
||||
if (!Array.isArray(n.inputs)) return null;
|
||||
const inp = n.inputs.find(i => i.name === name);
|
||||
if (inp?.link == null) return null;
|
||||
const originId = linkOrigin.get(inp.link);
|
||||
const originSlot = linkSlot.get(inp.link) ?? 0;
|
||||
if (originId == null) return null;
|
||||
return resolveLinkedTextInNodeSet(nodeMap, linkOrigin, linkSlot, originId, originSlot);
|
||||
};
|
||||
const combined = resolveEditPlusText(n.widgets_values?.[1], n.widgets_values?.[0], resolveNamedInput("text1"), resolveNamedInput("text2"));
|
||||
if (combined) textMap.set(n.id, combined);
|
||||
continue;
|
||||
}
|
||||
if (!isTextEncoderNode(type)) continue;
|
||||
const text = n.widgets_values?.[0];
|
||||
if (text && typeof text === "string") {
|
||||
textMap.set(n.id, text);
|
||||
@@ -388,10 +420,12 @@ function resolveLinkedText(wf, srcId, slot, depth = 0) {
|
||||
}
|
||||
return null;
|
||||
}
|
||||
// 汎用テキストキー("value" は PrimitiveString/PrimitiveStringMultiline)
|
||||
// 汎用テキストキー("value" は PrimitiveString/PrimitiveStringMultiline、"source" は
|
||||
// PreviewAny の値タップ中継、"string_a" は StringConcatenate の主オペランド — いずれも
|
||||
// Krea-2のプロンプト強化配線で使われる中継ノード)
|
||||
const keys = slot === 0
|
||||
? ["text_positive", "text", "text_g", "prompt", "value"]
|
||||
: ["text_negative", "text_l"];
|
||||
? ["text_positive", "text", "text_g", "prompt", "value", "source", "string_a"]
|
||||
: ["text_negative", "text_l", "source", "string_a"];
|
||||
for (const k of keys) {
|
||||
const v = src.inputs?.[k];
|
||||
if (typeof v === "string" && v) return v;
|
||||
@@ -412,7 +446,20 @@ function extractPromptsAPI(wf) {
|
||||
}
|
||||
const textMap = new Map();
|
||||
for (const [id, n] of Object.entries(wf)) {
|
||||
if (!n || !isTextEncoderNode(n.class_type ?? "")) continue;
|
||||
if (!n) continue;
|
||||
const ct = n.class_type ?? "";
|
||||
if (ct === "CLIPTextEncodeEditPlus") {
|
||||
const resolveField = (key) => {
|
||||
const v = n.inputs?.[key];
|
||||
if (typeof v === "string") return v;
|
||||
if (Array.isArray(v)) return resolveLinkedText(wf, v[0], v[1] ?? 0);
|
||||
return null;
|
||||
};
|
||||
const combined = resolveEditPlusText(n.inputs?.mode, n.inputs?.text_edit, resolveField("text1"), resolveField("text2"));
|
||||
if (combined) textMap.set(id, combined);
|
||||
continue;
|
||||
}
|
||||
if (!isTextEncoderNode(ct)) continue;
|
||||
// "prompt" — TextEncodeQwenImageEdit(Plus)/TextEncodeBooguEdit and similar Image Edit
|
||||
// model text encoders use this key instead of "text"/"text_g".
|
||||
const raw = n.inputs?.text ?? n.inputs?.text_g ?? n.inputs?.prompt ?? null;
|
||||
|
||||
+224
-1
@@ -4,7 +4,8 @@
|
||||
|
||||
import { showToast } from "./app.js";
|
||||
import { t } from "./i18n.js";
|
||||
import { readJsonStorage, getAiBackendDefaultUrl } from "./util.js";
|
||||
import { readJsonStorage, getAiBackendDefaultUrl, setupSearchClearBtn } from "./util.js";
|
||||
import { refreshStylesList } from "./generate-tab.js";
|
||||
|
||||
// ============================================
|
||||
// State
|
||||
@@ -903,6 +904,144 @@ function wcUpdateFilePicker() {
|
||||
}
|
||||
}
|
||||
|
||||
// ============================================
|
||||
// Style manager (Col3 "Style" タブ)
|
||||
// ============================================
|
||||
// Wildcardファイルマネージャーと同じCRUDパターン(一覧→エディタ→保存/削除/キャンセル)。
|
||||
// 保存・削除後は generate-tab.js の refreshStylesList() を呼び、GenerateUIのStyleドロップダウンや
|
||||
// Batchタブのチェックリストを再読み込み無しで最新状態へ同期する。
|
||||
|
||||
let styleListData = [];
|
||||
let styleSearchText = "";
|
||||
let styleEditingOriginalName = null; // null = 新規作成
|
||||
let styleEditingFile = null; // 編集中/追加先スタイルの定義元ファイル名(style/配下、null = デフォルトのcustom.json)
|
||||
|
||||
async function styleFetchList() {
|
||||
try {
|
||||
const res = await fetch("/api/wfm/styles");
|
||||
return res.ok ? await res.json() : [];
|
||||
} catch { return []; }
|
||||
}
|
||||
|
||||
async function styleApiCreate(name, prompt, negativePrompt, targetFile) {
|
||||
try {
|
||||
const body = { name, prompt, negative_prompt: negativePrompt };
|
||||
if (targetFile) body.file = targetFile;
|
||||
const res = await fetch("/api/wfm/styles", {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify(body),
|
||||
});
|
||||
const data = await res.json().catch(() => ({}));
|
||||
return res.ok ? { ok: true } : { ok: false, error: data.error || `HTTP ${res.status}` };
|
||||
} catch (e) {
|
||||
return { ok: false, error: e.message };
|
||||
}
|
||||
}
|
||||
|
||||
async function styleApiUpdate(originalName, name, prompt, negativePrompt) {
|
||||
try {
|
||||
const res = await fetch(`/api/wfm/styles/${encodeURIComponent(originalName)}`, {
|
||||
method: "PUT",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify({ name, prompt, negative_prompt: negativePrompt }),
|
||||
});
|
||||
const data = await res.json().catch(() => ({}));
|
||||
return res.ok ? { ok: true } : { ok: false, error: data.error || `HTTP ${res.status}` };
|
||||
} catch (e) {
|
||||
return { ok: false, error: e.message };
|
||||
}
|
||||
}
|
||||
|
||||
async function styleApiDelete(name) {
|
||||
try {
|
||||
const res = await fetch(`/api/wfm/styles/${encodeURIComponent(name)}`, { method: "DELETE" });
|
||||
const data = await res.json().catch(() => ({}));
|
||||
return res.ok ? { ok: true } : { ok: false, error: data.error || `HTTP ${res.status}` };
|
||||
} catch (e) {
|
||||
return { ok: false, error: e.message };
|
||||
}
|
||||
}
|
||||
|
||||
function styleRenderList() {
|
||||
const list = document.getElementById("wfm-style-list");
|
||||
if (!list) return;
|
||||
list.innerHTML = "";
|
||||
|
||||
const q = styleSearchText.trim().toLowerCase();
|
||||
const filtered = q ? styleListData.filter(s => s.name.toLowerCase().includes(q)) : styleListData;
|
||||
|
||||
if (filtered.length === 0) {
|
||||
list.innerHTML = styleListData.length === 0
|
||||
? `<div class="wfm-pm-empty" style="font-size:12px;">No styles yet.<br><small>Click "+ New" to create one.</small></div>`
|
||||
: `<div class="wfm-pm-empty" style="font-size:12px;">No matching styles.</div>`;
|
||||
return;
|
||||
}
|
||||
|
||||
for (const s of filtered) {
|
||||
const item = document.createElement("div");
|
||||
item.className = "wfm-wc-file-item";
|
||||
item.innerHTML = `
|
||||
<div class="wfm-wc-file-item-info">
|
||||
<span style="flex:1;min-width:0;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;">${esc(s.name)}</span>
|
||||
${s.file ? `<span class="wfm-wc-file-ext" title="${esc(s.file)}">${esc(s.file)}</span>` : ""}
|
||||
</div>
|
||||
<div class="wfm-wc-file-item-actions">
|
||||
<button class="wfm-pm-action-btn wfm-style-edit-btn" title="Edit style">✎</button>
|
||||
</div>
|
||||
`;
|
||||
item.querySelector(".wfm-style-edit-btn").addEventListener("click", (e) => {
|
||||
e.stopPropagation();
|
||||
styleOpenEditor(s);
|
||||
});
|
||||
item.addEventListener("click", () => styleOpenEditor(s));
|
||||
list.appendChild(item);
|
||||
}
|
||||
}
|
||||
|
||||
// forcedFile: 「+ Add to this file」から呼ばれた場合に、既存スタイルではなく
|
||||
// 特定ファイルを追加先として指定するために使う(styleは渡さずnullにする)
|
||||
function styleOpenEditor(style, forcedFile) {
|
||||
styleEditingOriginalName = style ? style.name : null;
|
||||
styleEditingFile = style ? (style.file || null) : (forcedFile || null);
|
||||
|
||||
const editor = document.getElementById("wfm-style-editor");
|
||||
const nameInput = document.getElementById("wfm-style-editor-name");
|
||||
const promptTA = document.getElementById("wfm-style-editor-prompt");
|
||||
const negativeTA = document.getElementById("wfm-style-editor-negative");
|
||||
const deleteBtn = document.getElementById("wfm-style-editor-delete-btn");
|
||||
const addFileBtn = document.getElementById("wfm-style-editor-addfile-btn");
|
||||
const fileLabel = document.getElementById("wfm-style-editor-file-label");
|
||||
|
||||
if (!editor) return;
|
||||
nameInput.value = style?.name || "";
|
||||
promptTA.value = style?.prompt || "";
|
||||
negativeTA.value = style?.negative_prompt || "";
|
||||
deleteBtn.style.display = style ? "" : "none";
|
||||
// 「このファイルへ追加」は既存スタイルを編集中(=対象ファイルが分かっている)時だけ表示
|
||||
addFileBtn.style.display = style ? "" : "none";
|
||||
if (styleEditingFile) {
|
||||
fileLabel.textContent = `File: ${styleEditingFile}`;
|
||||
fileLabel.style.display = "";
|
||||
} else {
|
||||
fileLabel.style.display = "none";
|
||||
}
|
||||
editor.style.display = "";
|
||||
nameInput.focus();
|
||||
}
|
||||
|
||||
function styleCloseEditor() {
|
||||
styleEditingOriginalName = null;
|
||||
styleEditingFile = null;
|
||||
const editor = document.getElementById("wfm-style-editor");
|
||||
if (editor) editor.style.display = "none";
|
||||
}
|
||||
|
||||
async function styleRefreshList() {
|
||||
styleListData = await styleFetchList();
|
||||
styleRenderList();
|
||||
}
|
||||
|
||||
// ============================================
|
||||
// Initialize
|
||||
// ============================================
|
||||
@@ -1319,4 +1458,88 @@ export function initPromptTab() {
|
||||
|
||||
// Initial wildcard file load
|
||||
wcRefreshFiles();
|
||||
|
||||
// ── Col3タブ切り替え (Wildcard / Style) ────────────────────
|
||||
document.querySelectorAll(".wfm-prompt-col3-tab[data-col3tab]").forEach(btn => {
|
||||
btn.addEventListener("click", () => {
|
||||
document.querySelectorAll(".wfm-prompt-col3-tab[data-col3tab]").forEach(b => b.classList.remove("active"));
|
||||
btn.classList.add("active");
|
||||
const tabId = btn.dataset.col3tab;
|
||||
document.querySelectorAll(".wfm-prompt-col3-tab-content").forEach(c => { c.style.display = "none"; });
|
||||
const content = document.getElementById(`wfm-col3-tab-${tabId}`);
|
||||
if (content) content.style.display = "";
|
||||
});
|
||||
});
|
||||
|
||||
// ── Style manager ────────────────────────────────
|
||||
document.getElementById("wfm-style-new-btn")?.addEventListener("click", () => {
|
||||
styleOpenEditor(null);
|
||||
});
|
||||
|
||||
document.getElementById("wfm-style-refresh-btn")?.addEventListener("click", () => {
|
||||
styleRefreshList();
|
||||
});
|
||||
|
||||
// 編集中の既存スタイルと同じファイルへ、新しい空のスタイルを追加する
|
||||
document.getElementById("wfm-style-editor-addfile-btn")?.addEventListener("click", () => {
|
||||
if (!styleEditingFile) return;
|
||||
styleOpenEditor(null, styleEditingFile);
|
||||
});
|
||||
|
||||
setupSearchClearBtn("wfm-style-search", "wfm-style-search-clear-btn", () => {
|
||||
styleSearchText = "";
|
||||
styleRenderList();
|
||||
});
|
||||
document.getElementById("wfm-style-search")?.addEventListener("input", (e) => {
|
||||
styleSearchText = e.target.value;
|
||||
styleRenderList();
|
||||
});
|
||||
|
||||
document.getElementById("wfm-style-editor-save-btn")?.addEventListener("click", async () => {
|
||||
const nameInput = document.getElementById("wfm-style-editor-name");
|
||||
const promptTA = document.getElementById("wfm-style-editor-prompt");
|
||||
const negativeTA = document.getElementById("wfm-style-editor-negative");
|
||||
|
||||
const name = (nameInput?.value || "").trim();
|
||||
const prompt = promptTA?.value || "";
|
||||
const negativePrompt = negativeTA?.value || "";
|
||||
|
||||
if (!name) { showToast(t("pleaseEnterStyleName"), "error"); return; }
|
||||
|
||||
const result = styleEditingOriginalName
|
||||
? await styleApiUpdate(styleEditingOriginalName, name, prompt, negativePrompt)
|
||||
: await styleApiCreate(name, prompt, negativePrompt, styleEditingFile);
|
||||
|
||||
if (result.ok) {
|
||||
showToast(t("savedAs", name), "success");
|
||||
styleCloseEditor();
|
||||
await styleRefreshList();
|
||||
await refreshStylesList();
|
||||
} else {
|
||||
showToast(t("errorWithMsg", result.error), "error");
|
||||
}
|
||||
});
|
||||
|
||||
// Editor: delete
|
||||
document.getElementById("wfm-style-editor-delete-btn")?.addEventListener("click", async () => {
|
||||
if (!styleEditingOriginalName) return;
|
||||
if (!confirm(`Delete "${styleEditingOriginalName}"?`)) return;
|
||||
const result = await styleApiDelete(styleEditingOriginalName);
|
||||
if (result.ok) {
|
||||
showToast(t("deletedName", styleEditingOriginalName), "success");
|
||||
styleCloseEditor();
|
||||
await styleRefreshList();
|
||||
await refreshStylesList();
|
||||
} else {
|
||||
showToast(t("errorWithMsg", result.error), "error");
|
||||
}
|
||||
});
|
||||
|
||||
// Editor: cancel
|
||||
document.getElementById("wfm-style-editor-cancel-btn")?.addEventListener("click", () => {
|
||||
styleCloseEditor();
|
||||
});
|
||||
|
||||
// Initial style list load
|
||||
styleRefreshList();
|
||||
}
|
||||
|
||||
@@ -366,6 +366,21 @@ export function applyJsonColors(colors) {
|
||||
].join("\n");
|
||||
}
|
||||
|
||||
// GenerateUI Model tab: highlight color for section labels that match the loaded workflow
|
||||
const MODEL_ACTIVE_COLOR_STYLE_ID = "wfm-model-active-color-style";
|
||||
const MODEL_ACTIVE_COLOR_DEFAULT = "#4ade80";
|
||||
|
||||
export function applyModelTabActiveColor(color) {
|
||||
const val = color || MODEL_ACTIVE_COLOR_DEFAULT;
|
||||
let el = document.getElementById(MODEL_ACTIVE_COLOR_STYLE_ID);
|
||||
if (!el) {
|
||||
el = document.createElement("style");
|
||||
el.id = MODEL_ACTIVE_COLOR_STYLE_ID;
|
||||
document.head.appendChild(el);
|
||||
}
|
||||
el.textContent = `.wfm-form-group label.wfm-model-label-active,\n.wfm-settings-summary.wfm-model-label-active,\n#wfm-gen-lora-col-title.wfm-model-label-active { color: ${val}; }`;
|
||||
}
|
||||
|
||||
export function applyTheme(themeId) {
|
||||
if (themeId) {
|
||||
document.documentElement.setAttribute("data-theme", themeId);
|
||||
@@ -577,6 +592,21 @@ export async function initSettingsTab() {
|
||||
</div>
|
||||
</details>
|
||||
|
||||
<!-- GenerateUI Model Tab Highlight Color -->
|
||||
<details class="wfm-settings-section" open>
|
||||
<summary class="wfm-settings-summary">${t("modelTabColorSection") || "GenerateUI Modelタブ ハイライト色"}</summary>
|
||||
<div class="wfm-form-group">
|
||||
<label>${t("modelTabColorLabel") || "ワークフローに含まれる項目の色"}</label>
|
||||
<div style="display:flex;align-items:center;gap:8px;">
|
||||
<input type="color" id="wfm-model-active-color" value="${settings.modelTabActiveColor || MODEL_ACTIVE_COLOR_DEFAULT}">
|
||||
<button class="wfm-btn wfm-btn-sm" id="wfm-model-active-color-reset">${t("jsonColorReset") || "デフォルトに戻す"}</button>
|
||||
</div>
|
||||
<small style="color:var(--wfm-text-secondary);font-size:11px;display:block;margin-top:4px;">
|
||||
${t("modelTabColorHint") || "GenerateUIのModelタブで、読み込んだワークフローに実際に含まれる項目(Checkpoint / VAE など)のラベルをこの色で表示します"}
|
||||
</small>
|
||||
</div>
|
||||
</details>
|
||||
|
||||
<!-- Workflow Data Folder -->
|
||||
<details class="wfm-settings-section">
|
||||
<summary class="wfm-settings-summary">${t("workflowsDir")}</summary>
|
||||
@@ -1333,6 +1363,22 @@ export async function initSettingsTab() {
|
||||
showToast(t("settingsSaved"), "success");
|
||||
});
|
||||
|
||||
// --- GenerateUI Model tab highlight color ---
|
||||
document.getElementById("wfm-model-active-color")?.addEventListener("input", (e) => {
|
||||
saveLocalSettings({ modelTabActiveColor: e.target.value });
|
||||
applyModelTabActiveColor(e.target.value);
|
||||
});
|
||||
|
||||
document.getElementById("wfm-model-active-color-reset")?.addEventListener("click", () => {
|
||||
const cur = loadLocalSettings();
|
||||
delete cur.modelTabActiveColor;
|
||||
localStorage.setItem(SETTINGS_KEY, JSON.stringify(cur));
|
||||
applyModelTabActiveColor(undefined);
|
||||
const inp = document.getElementById("wfm-model-active-color");
|
||||
if (inp) inp.value = MODEL_ACTIVE_COLOR_DEFAULT;
|
||||
showToast(t("settingsSaved"), "success");
|
||||
});
|
||||
|
||||
// Save (local settings)
|
||||
document.getElementById("wfm-settings-save")?.addEventListener("click", () => {
|
||||
const taFontSize = parseInt(document.getElementById("wfm-ta-font-size")?.value) || TEXTAREA_FONT_SIZE_DEFAULT;
|
||||
|
||||
@@ -0,0 +1,373 @@
|
||||
/**
|
||||
* Style Catalog Gallery — Gallery タブのサブタブ。
|
||||
* ws_style_catalog フォルダ配下の画像(GenerateUIの「カタログ作成」で生成した、
|
||||
* ファイル名=スタイル名のプレビュー画像)を閲覧し、埋め込みPositive/Negative
|
||||
* プロンプトを表示・コピーする。「Select as Style」でGenerateUIの登録済み
|
||||
* Styleドロップダウンをファイル名と同名のStyleに切り替える。
|
||||
*/
|
||||
|
||||
import { showToast } from "./app.js";
|
||||
import { t } from "./i18n.js";
|
||||
import { escapeHtml, setupSearchClearBtn } from "./util.js";
|
||||
import { extractAllMetadata, loadFileIntoMetadataTab } from "./metadata-tab.js";
|
||||
import { selectStyleByName, loadWorkflowIntoEditor } from "./generate-tab.js";
|
||||
|
||||
const API = {
|
||||
root: () => `/wfm/gallery/style-catalog/root`,
|
||||
folders: (root) => `/wfm/gallery/folders?root=${encodeURIComponent(root)}`,
|
||||
images: (params) => `/wfm/gallery/images?${new URLSearchParams(params)}`,
|
||||
thumb: (path, w = 200) => `/wfm/gallery/image/thumb?path=${encodeURIComponent(path)}&w=${w}`,
|
||||
serveImage: (path) => `/wfm/gallery/image/serve?path=${encodeURIComponent(path)}`,
|
||||
workflow: (path) => `/wfm/gallery/image/workflow?path=${encodeURIComponent(path)}`,
|
||||
};
|
||||
|
||||
const state = {
|
||||
root: null,
|
||||
currentFolder: null,
|
||||
search: "",
|
||||
images: [],
|
||||
selectedImage: null,
|
||||
};
|
||||
|
||||
let _initialized = false;
|
||||
|
||||
async function apiFetch(url, opts = {}) {
|
||||
const res = await fetch(url, opts);
|
||||
if (!res.ok) throw new Error(`HTTP ${res.status}`);
|
||||
return res.json();
|
||||
}
|
||||
|
||||
function debounce(fn, wait) {
|
||||
let timer;
|
||||
return (...args) => {
|
||||
clearTimeout(timer);
|
||||
timer = setTimeout(() => fn(...args), wait);
|
||||
};
|
||||
}
|
||||
|
||||
// ── 初期化 ────────────────────────────────────────────────────
|
||||
|
||||
export function initStyleCatalogTab() {
|
||||
document.getElementById("wfm-stylecatalog-refresh-btn")?.addEventListener("click", () => {
|
||||
loadFolderTree();
|
||||
loadImages();
|
||||
});
|
||||
|
||||
setupSearchClearBtn("wfm-stylecatalog-search", "wfm-stylecatalog-search-clear-btn", () => {
|
||||
state.search = "";
|
||||
loadImages();
|
||||
});
|
||||
|
||||
const searchInput = document.getElementById("wfm-stylecatalog-search");
|
||||
searchInput?.addEventListener("input", debounce(() => {
|
||||
state.search = searchInput.value.trim();
|
||||
loadImages();
|
||||
}, 300));
|
||||
|
||||
document.getElementById("wfm-stylecatalog-copy-positive-btn")?.addEventListener("click", () => copyText("wfm-stylecatalog-positive-text"));
|
||||
document.getElementById("wfm-stylecatalog-copy-negative-btn")?.addEventListener("click", () => copyText("wfm-stylecatalog-negative-text"));
|
||||
document.getElementById("wfm-stylecatalog-select-style-btn")?.addEventListener("click", onSelectStyleClick);
|
||||
document.getElementById("wfm-stylecatalog-load-genui-btn")?.addEventListener("click", onLoadGenUIClick);
|
||||
document.getElementById("wfm-stylecatalog-open-metadata-btn")?.addEventListener("click", onOpenMetadataClick);
|
||||
}
|
||||
|
||||
export async function activateStyleCatalogTab() {
|
||||
if (_initialized) return;
|
||||
_initialized = true;
|
||||
try {
|
||||
const data = await apiFetch(API.root());
|
||||
state.root = data.root;
|
||||
await loadFolderTree();
|
||||
} catch (e) {
|
||||
const tree = document.getElementById("wfm-stylecatalog-tree");
|
||||
if (tree) tree.innerHTML = `<p class="wfm-placeholder">Error: ${escapeHtml(e.message)}</p>`;
|
||||
}
|
||||
}
|
||||
|
||||
// ── フォルダツリー ────────────────────────────────────────────
|
||||
|
||||
async function loadFolderTree() {
|
||||
if (!state.root) return;
|
||||
const tree = document.getElementById("wfm-stylecatalog-tree");
|
||||
tree.innerHTML = `<p class="wfm-placeholder">${t("loading")}</p>`;
|
||||
try {
|
||||
const data = await apiFetch(API.folders(state.root));
|
||||
if (data.error) {
|
||||
tree.innerHTML = `<p class="wfm-placeholder">${escapeHtml(data.error)}</p>`;
|
||||
return;
|
||||
}
|
||||
tree.innerHTML = "";
|
||||
renderTreeNode(data, tree, 0, true);
|
||||
const firstLabel = tree.querySelector(".wfm-gallery-tree-label");
|
||||
if (firstLabel) firstLabel.click();
|
||||
} catch (e) {
|
||||
tree.innerHTML = `<p class="wfm-placeholder">Error: ${escapeHtml(e.message)}</p>`;
|
||||
}
|
||||
}
|
||||
|
||||
function renderTreeNode(node, container, depth, isRoot) {
|
||||
const item = document.createElement("div");
|
||||
item.className = "wfm-gallery-tree-item";
|
||||
item.style.paddingLeft = `${depth * 12}px`;
|
||||
item.dataset.path = node.abs_path;
|
||||
|
||||
const hasChildren = node.children && node.children.length > 0;
|
||||
const absPath = node.abs_path;
|
||||
|
||||
const arrow = document.createElement("span");
|
||||
arrow.className = "wfm-gallery-tree-arrow";
|
||||
if (hasChildren) {
|
||||
arrow.textContent = "▶";
|
||||
arrow.dataset.expanded = "false";
|
||||
} else {
|
||||
arrow.textContent = " ";
|
||||
arrow.style.visibility = "hidden";
|
||||
}
|
||||
item.appendChild(arrow);
|
||||
|
||||
const label = document.createElement("span");
|
||||
label.className = "wfm-gallery-tree-label";
|
||||
label.textContent = isRoot ? "[root]" : node.name;
|
||||
const totalCount = node.image_count_total ?? node.image_count;
|
||||
if (totalCount > 0) {
|
||||
const badge = document.createElement("span");
|
||||
badge.className = "wfm-gallery-tree-count";
|
||||
badge.textContent = totalCount;
|
||||
label.appendChild(badge);
|
||||
}
|
||||
item.appendChild(label);
|
||||
|
||||
label.addEventListener("click", () => {
|
||||
document.querySelectorAll("#wfm-stylecatalog-tree .wfm-gallery-tree-item.selected").forEach(el => el.classList.remove("selected"));
|
||||
item.classList.add("selected");
|
||||
state.currentFolder = absPath;
|
||||
loadImages();
|
||||
});
|
||||
|
||||
if (hasChildren) {
|
||||
const childContainer = document.createElement("div");
|
||||
childContainer.className = "wfm-gallery-tree-children";
|
||||
childContainer.style.display = "none";
|
||||
|
||||
arrow.addEventListener("click", (e) => {
|
||||
e.stopPropagation();
|
||||
const expanded = arrow.dataset.expanded === "true";
|
||||
if (!expanded) {
|
||||
arrow.dataset.expanded = "true";
|
||||
arrow.textContent = "▼";
|
||||
childContainer.style.display = "";
|
||||
if (childContainer.children.length === 0) {
|
||||
node.children.forEach(child => renderTreeNode(child, childContainer, depth + 1, false));
|
||||
}
|
||||
} else {
|
||||
arrow.dataset.expanded = "false";
|
||||
arrow.textContent = "▶";
|
||||
childContainer.style.display = "none";
|
||||
}
|
||||
});
|
||||
|
||||
container.appendChild(item);
|
||||
container.appendChild(childContainer);
|
||||
} else {
|
||||
container.appendChild(item);
|
||||
}
|
||||
}
|
||||
|
||||
// ── 画像一覧 ─────────────────────────────────────────────────
|
||||
|
||||
async function loadImages() {
|
||||
if (!state.currentFolder) return;
|
||||
const grid = document.getElementById("wfm-stylecatalog-grid");
|
||||
grid.innerHTML = `<p class="wfm-placeholder">${t("loading")}</p>`;
|
||||
|
||||
// 上位フォルダを選択した場合もサブフォルダの画像をまとめて表示する
|
||||
const params = { folder: state.currentFolder, sort: "name_asc", recursive: "true" };
|
||||
if (state.search) params.search = state.search;
|
||||
|
||||
try {
|
||||
const data = await apiFetch(API.images(params));
|
||||
state.images = data.images || [];
|
||||
document.getElementById("wfm-stylecatalog-count").textContent = `${state.images.length} images`;
|
||||
renderImages();
|
||||
} catch (e) {
|
||||
grid.innerHTML = `<p class="wfm-placeholder">Error: ${escapeHtml(e.message)}</p>`;
|
||||
}
|
||||
}
|
||||
|
||||
function renderImages() {
|
||||
const grid = document.getElementById("wfm-stylecatalog-grid");
|
||||
if (state.images.length === 0) {
|
||||
grid.innerHTML = `<p class="wfm-placeholder">${t("galleryNoImages")}</p>`;
|
||||
return;
|
||||
}
|
||||
grid.innerHTML = "";
|
||||
const fragment = document.createDocumentFragment();
|
||||
state.images.forEach(img => fragment.appendChild(createThumbCard(img)));
|
||||
grid.appendChild(fragment);
|
||||
}
|
||||
|
||||
function createThumbCard(img) {
|
||||
const card = document.createElement("div");
|
||||
card.className = "wfm-gallery-thumb-card";
|
||||
card.title = img.filename;
|
||||
card.dataset.path = img.path;
|
||||
if (state.selectedImage && state.selectedImage.path === img.path) {
|
||||
card.classList.add("selected");
|
||||
}
|
||||
|
||||
const imgEl = document.createElement("img");
|
||||
imgEl.className = "wfm-gallery-thumb-img";
|
||||
imgEl.loading = "lazy";
|
||||
imgEl.src = API.thumb(img.path);
|
||||
imgEl.alt = img.filename;
|
||||
imgEl.onerror = () => {
|
||||
imgEl.style.display = "none";
|
||||
const placeholder = document.createElement("div");
|
||||
placeholder.className = "wfm-gallery-thumb-placeholder";
|
||||
placeholder.textContent = "?";
|
||||
card.insertBefore(placeholder, imgEl.nextSibling);
|
||||
};
|
||||
card.appendChild(imgEl);
|
||||
|
||||
card.addEventListener("click", () => selectImage(img));
|
||||
card.addEventListener("dblclick", () => openLightbox(img));
|
||||
|
||||
return card;
|
||||
}
|
||||
|
||||
// ── 選択画像 / Positive・Negative表示 ─────────────────────────
|
||||
|
||||
function styleNameFromFilename(filename) {
|
||||
return filename.replace(/\.[^.]+$/, "");
|
||||
}
|
||||
|
||||
async function selectImage(img) {
|
||||
state.selectedImage = img;
|
||||
document.querySelectorAll("#wfm-stylecatalog-grid .wfm-gallery-thumb-card").forEach(el => {
|
||||
el.classList.toggle("selected", el.dataset.path === img.path);
|
||||
});
|
||||
|
||||
document.getElementById("wfm-stylecatalog-selected-name").textContent = img.filename;
|
||||
const preview = document.getElementById("wfm-stylecatalog-selected-preview");
|
||||
preview.innerHTML = "";
|
||||
const previewImg = document.createElement("img");
|
||||
previewImg.src = API.serveImage(img.path);
|
||||
previewImg.alt = img.filename;
|
||||
previewImg.title = "Double-click to enlarge";
|
||||
previewImg.style.cssText = "max-width:100%;max-height:100%;object-fit:contain;cursor:zoom-in;";
|
||||
previewImg.addEventListener("dblclick", () => openLightbox(img));
|
||||
preview.appendChild(previewImg);
|
||||
|
||||
const positiveText = document.getElementById("wfm-stylecatalog-positive-text");
|
||||
const negativeText = document.getElementById("wfm-stylecatalog-negative-text");
|
||||
const copyPositiveBtn = document.getElementById("wfm-stylecatalog-copy-positive-btn");
|
||||
const copyNegativeBtn = document.getElementById("wfm-stylecatalog-copy-negative-btn");
|
||||
const selectStyleBtn = document.getElementById("wfm-stylecatalog-select-style-btn");
|
||||
const loadGenuiBtn = document.getElementById("wfm-stylecatalog-load-genui-btn");
|
||||
const openMetadataBtn = document.getElementById("wfm-stylecatalog-open-metadata-btn");
|
||||
|
||||
positiveText.textContent = "";
|
||||
negativeText.textContent = "";
|
||||
copyPositiveBtn.disabled = true;
|
||||
copyNegativeBtn.disabled = true;
|
||||
selectStyleBtn.disabled = false; // ファイル名からのStyle選択はメタデータ抽出に依存しない
|
||||
loadGenuiBtn.disabled = false;
|
||||
openMetadataBtn.disabled = false;
|
||||
|
||||
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" });
|
||||
const meta = await extractAllMetadata(file);
|
||||
|
||||
const positive = meta?.positives?.[0] || "";
|
||||
const negative = meta?.negatives?.[0] || "";
|
||||
|
||||
if (!positive && !negative) {
|
||||
positiveText.textContent = t("stylecatalogNoPromptFound");
|
||||
} else {
|
||||
positiveText.textContent = positive;
|
||||
negativeText.textContent = negative;
|
||||
copyPositiveBtn.disabled = !positive;
|
||||
copyNegativeBtn.disabled = !negative;
|
||||
}
|
||||
} catch (e) {
|
||||
positiveText.textContent = t("stylecatalogNoPromptFound");
|
||||
}
|
||||
}
|
||||
|
||||
// gallery-tab.jsのライトボックスと同じCSSクラスを使う(ESCで閉じる処理もgallery-tab.js側の
|
||||
// グローバルkeydownリスナーが共通で担う)。
|
||||
function openLightbox(img) {
|
||||
const overlay = document.createElement("div");
|
||||
overlay.className = "wfm-gallery-lightbox";
|
||||
overlay.innerHTML = `
|
||||
<div class="wfm-gallery-lightbox-inner">
|
||||
<img src="${API.serveImage(img.path)}" class="wfm-gallery-lightbox-img" alt="${escapeHtml(img.filename)}">
|
||||
<div class="wfm-gallery-lightbox-footer">${escapeHtml(img.filename)}</div>
|
||||
<button class="wfm-gallery-lightbox-close">×</button>
|
||||
</div>
|
||||
`;
|
||||
overlay.addEventListener("click", (e) => {
|
||||
if (e.target === overlay || e.target.classList.contains("wfm-gallery-lightbox-close")) {
|
||||
overlay.remove();
|
||||
}
|
||||
});
|
||||
document.body.appendChild(overlay);
|
||||
}
|
||||
|
||||
function copyText(elementId) {
|
||||
const el = document.getElementById(elementId);
|
||||
const text = el?.textContent || "";
|
||||
if (!text.trim()) return;
|
||||
navigator.clipboard.writeText(text)
|
||||
.then(() => showToast(t("imagePromptCopiedToast"), "success"))
|
||||
.catch((e) => showToast(t("errorWithMsg", e.message), "error"));
|
||||
}
|
||||
|
||||
function onSelectStyleClick() {
|
||||
const img = state.selectedImage;
|
||||
if (!img) return;
|
||||
const name = styleNameFromFilename(img.filename);
|
||||
const ok = selectStyleByName(name);
|
||||
if (ok) {
|
||||
showToast(t("stylecatalogStyleSelected", name), "success");
|
||||
} else {
|
||||
showToast(t("stylecatalogNoMatch"), "error");
|
||||
}
|
||||
}
|
||||
|
||||
// カタログ画像は生成元の出力画像と同一バイト列で保存されているため、埋め込みワークフローも
|
||||
// そのまま残っている。Outputフォルダ内の元画像を探す必要なく、この画像から直接読み込める。
|
||||
async function onLoadGenUIClick() {
|
||||
const img = state.selectedImage;
|
||||
if (!img) return;
|
||||
try {
|
||||
const data = await apiFetch(API.workflow(img.path));
|
||||
if (!data.has_workflow) {
|
||||
showToast(t("galleryNoEmbeddedWorkflow"), "warning");
|
||||
return;
|
||||
}
|
||||
const loaded = await loadWorkflowIntoEditor(data.workflow, img.filename);
|
||||
if (loaded !== false) {
|
||||
document.querySelector('.wfm-tab[data-tab="generate"]')?.click();
|
||||
}
|
||||
} catch (e) {
|
||||
showToast(t("errorWithMsg", e.message), "error");
|
||||
}
|
||||
}
|
||||
|
||||
async function onOpenMetadataClick() {
|
||||
const img = state.selectedImage;
|
||||
if (!img) return;
|
||||
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");
|
||||
}
|
||||
}
|
||||
@@ -2,6 +2,76 @@
|
||||
* Shared utilities
|
||||
*/
|
||||
|
||||
// ============================================
|
||||
// PNG metadata embedding (iTXt chunk)
|
||||
// ============================================
|
||||
// Embeds an arbitrary key/UTF-8-text pair into a canvas-generated PNG data URL as
|
||||
// an iTXt chunk, inserted right after IHDR — same insertion point/CRC approach as
|
||||
// ComfyUI's own workflow-embedding (web/comfyui/top_menu_extension.js's
|
||||
// embedWorkflowInPng), but iTXt instead of tEXt so non-ASCII text (Japanese notes,
|
||||
// prompts, etc.) round-trips correctly through this codebase's PNG chunk reader
|
||||
// (metadata-tab.js's readAllPNGTextChunks already decodes iTXt text as UTF-8;
|
||||
// tEXt text there is decoded as Latin-1, which would mangle non-ASCII payloads).
|
||||
|
||||
function _n2b(n) {
|
||||
return new Uint8Array([(n >> 24) & 0xff, (n >> 16) & 0xff, (n >> 8) & 0xff, n & 0xff]);
|
||||
}
|
||||
|
||||
function _joinBytes(...arrs) {
|
||||
const result = new Uint8Array(arrs.reduce((total, a) => total + a.byteLength, 0));
|
||||
arrs.reduce((offset, a) => { result.set(a, offset); return offset + a.byteLength; }, 0);
|
||||
return result;
|
||||
}
|
||||
|
||||
let _pngCrcTable = null;
|
||||
function _pngCrc32(data) {
|
||||
if (!_pngCrcTable) {
|
||||
_pngCrcTable = [];
|
||||
for (let n = 0; n < 256; n++) {
|
||||
let c = n;
|
||||
for (let k = 0; k < 8; k++) c = c & 1 ? 0xedb88320 ^ (c >>> 1) : c >>> 1;
|
||||
_pngCrcTable[n] = c;
|
||||
}
|
||||
}
|
||||
let crc = 0 ^ -1;
|
||||
for (let i = 0; i < data.byteLength; i++) crc = (crc >>> 8) ^ _pngCrcTable[(crc ^ data[i]) & 0xff];
|
||||
return (crc ^ -1) >>> 0;
|
||||
}
|
||||
|
||||
function _dataUrlToBytes(dataUrl) {
|
||||
const binary = atob(dataUrl.slice(dataUrl.indexOf(",") + 1));
|
||||
const bytes = new Uint8Array(binary.length);
|
||||
for (let i = 0; i < binary.length; i++) bytes[i] = binary.charCodeAt(i);
|
||||
return bytes;
|
||||
}
|
||||
|
||||
function _bytesToDataUrl(bytes, mime) {
|
||||
let binary = "";
|
||||
const chunkSize = 0x8000;
|
||||
for (let i = 0; i < bytes.length; i += chunkSize) {
|
||||
binary += String.fromCharCode.apply(null, bytes.subarray(i, i + chunkSize));
|
||||
}
|
||||
return `data:${mime};base64,${btoa(binary)}`;
|
||||
}
|
||||
|
||||
export function embedPngTextChunk(dataUrl, keyword, text) {
|
||||
const bytes = _dataUrlToBytes(dataUrl);
|
||||
const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);
|
||||
|
||||
const data = _joinBytes(
|
||||
new TextEncoder().encode(`iTXt${keyword}`),
|
||||
new Uint8Array([0, 0, 0, 0, 0]), // keyword-NUL, compression flag(0), compression method(0), empty lang tag+NUL, empty translated keyword+NUL
|
||||
new TextEncoder().encode(text),
|
||||
);
|
||||
const chunk = _joinBytes(_n2b(data.byteLength - 4), data, _n2b(_pngCrc32(data)));
|
||||
|
||||
// Insert after IHDR (8-byte signature + 4-byte length + 4-byte type + IHDR data + 4-byte CRC)
|
||||
const ihdrDataLen = view.getUint32(8);
|
||||
const insertAt = ihdrDataLen + 20;
|
||||
const result = _joinBytes(bytes.subarray(0, insertAt), chunk, bytes.subarray(insertAt));
|
||||
return _bytesToDataUrl(result, "image/png");
|
||||
}
|
||||
|
||||
// HTMLエスケープ(属性値・テキストコンテンツ両方で安全に使える)
|
||||
export function escapeHtml(s) {
|
||||
return String(s)
|
||||
@@ -32,6 +102,7 @@ export const AI_BACKEND_DEFAULT_URLS = {
|
||||
ollama: "http://localhost:11434",
|
||||
lmstudio: "http://localhost:1234",
|
||||
lemonade: "http://localhost:13305",
|
||||
unsloth: "http://localhost:8888",
|
||||
};
|
||||
|
||||
export function getAiBackendDefaultUrl(backend) {
|
||||
|
||||
+300
-12
@@ -294,6 +294,8 @@
|
||||
Style
|
||||
</label>
|
||||
<select id="wfm-style-select" class="wfm-input" style="font-size:12px;padding:2px 6px;height:26px;min-width:120px;max-width:220px;"></select>
|
||||
<button id="wfm-gen-catalog-create-btn" class="wfm-btn wfm-btn-sm">Create Catalog</button>
|
||||
<button id="wfm-gen-catalog-open-btn" class="wfm-btn wfm-btn-sm">Catalog</button>
|
||||
</div>
|
||||
<div class="wfm-toolbar-right" style="display:flex;align-items:center;gap:8px;">
|
||||
<span id="wfm-gen-wf-name" style="color:var(--wfm-text-secondary);font-size:13px;">No workflow loaded</span>
|
||||
@@ -348,7 +350,7 @@
|
||||
</div>
|
||||
<div class="wfm-gen-lora-col">
|
||||
<div class="wfm-gen-lora-col-header">
|
||||
<span>LoRA</span>
|
||||
<span id="wfm-gen-lora-col-title">LoRA</span>
|
||||
<button class="wfm-btn wfm-btn-xs wfm-lora-refresh-btn" id="wfm-lora-stack-refresh" title="Refresh Stack group">🔄</button>
|
||||
</div>
|
||||
<div id="wfm-gen-lora-fields" class="wfm-gen-lora-col-body">
|
||||
@@ -517,6 +519,10 @@
|
||||
<!-- Left: source image + plan load/clear -->
|
||||
<div class="wfm-lab-pane wfm-lab-left">
|
||||
<div class="wfm-lab-pane-header">Image</div>
|
||||
<label class="wfm-lab-checkbox-label">
|
||||
<input type="checkbox" id="wfm-lab-t2i-mode">
|
||||
T2I workflow (no source image)
|
||||
</label>
|
||||
<div class="wfm-i2i-preview-wrap" id="wfm-lab-preview-wrap" style="display:none;">
|
||||
<img class="wfm-i2i-preview-img" id="wfm-lab-preview-img" alt="">
|
||||
</div>
|
||||
@@ -538,6 +544,10 @@
|
||||
Drop plan (.json/.png) here or click to select
|
||||
</label>
|
||||
</div>
|
||||
<div class="wfm-lab-plan-workflow-row" id="wfm-lab-plan-workflow-row" style="display:none;">
|
||||
<span id="wfm-lab-plan-workflow-name" class="wfm-lab-plan-workflow-name"></span>
|
||||
<button type="button" id="wfm-lab-plan-workflow-load-btn" class="wfm-btn wfm-btn-xs" title="Load this plan's recorded workflow into GenerateUI">Open Workflow</button>
|
||||
</div>
|
||||
<div class="wfm-lab-side-btns">
|
||||
<button id="wfm-lab-plan-clear-btn" class="wfm-btn">Plan Clear</button>
|
||||
</div>
|
||||
@@ -608,6 +618,10 @@
|
||||
<label>Batch:</label>
|
||||
<input type="number" id="wfm-lab-batch-count" class="wfm-input" value="4" min="1" max="50">
|
||||
</div>
|
||||
<label class="wfm-lab-checkbox-label" style="margin-top:6px;">
|
||||
<input type="checkbox" id="wfm-lab-save-index-on-run" checked>
|
||||
Save index image to Output on Run
|
||||
</label>
|
||||
|
||||
<div class="wfm-lab-pane-header" style="margin-top:12px;">Note</div>
|
||||
<textarea id="wfm-lab-note" class="wfm-input wfm-lab-note" rows="6"></textarea>
|
||||
@@ -624,6 +638,7 @@
|
||||
<div class="wfm-lab-pane wfm-lab-results-left">
|
||||
<div class="wfm-lab-pane-header">Image</div>
|
||||
<img id="wfm-lab-results-source-img" class="wfm-i2i-preview-img" style="display:none;" alt="">
|
||||
<p id="wfm-lab-results-t2i-note" class="wfm-placeholder" style="display:none;">T2I workflow (no source image)</p>
|
||||
</div>
|
||||
<div class="wfm-lab-pane wfm-lab-results-center">
|
||||
<div class="wfm-lab-pane-header">Results</div>
|
||||
@@ -1020,9 +1035,15 @@
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Col 3: Wildcard support -->
|
||||
<!-- Col 3: Wildcard / Style support -->
|
||||
<div class="wfm-prompt-split-col">
|
||||
<div class="wfm-prompt-split-header">Wildcard</div>
|
||||
<div class="wfm-prompt-col3-tabs">
|
||||
<button class="wfm-prompt-col3-tab active" id="wfm-col3-tab-wildcard-btn" data-col3tab="wildcard">Wildcard</button>
|
||||
<button class="wfm-prompt-col3-tab" id="wfm-col3-tab-style-btn" data-col3tab="style">Style</button>
|
||||
</div>
|
||||
|
||||
<!-- Wildcard タブ -->
|
||||
<div id="wfm-col3-tab-wildcard" class="wfm-prompt-col3-tab-content">
|
||||
<div class="wfm-wc-panel">
|
||||
|
||||
<!-- Input assistance section -->
|
||||
@@ -1089,6 +1110,49 @@
|
||||
</div>
|
||||
|
||||
</div>
|
||||
</div>
|
||||
<!-- /Wildcard タブ -->
|
||||
|
||||
<!-- Style タブ -->
|
||||
<div id="wfm-col3-tab-style" class="wfm-prompt-col3-tab-content" style="display:none;">
|
||||
<div class="wfm-wc-panel">
|
||||
<div class="wfm-wc-files-section" style="margin-top:0;border-top:none;padding-top:0;">
|
||||
<div class="wfm-wc-files-header">
|
||||
<span class="wfm-wc-files-title">Styles</span>
|
||||
<div style="display:flex;gap:4px;">
|
||||
<button id="wfm-style-new-btn" class="wfm-btn wfm-btn-sm wfm-btn-primary">+ New</button>
|
||||
<button id="wfm-style-refresh-btn" class="wfm-btn wfm-btn-sm" title="Reload style list">↻</button>
|
||||
</div>
|
||||
</div>
|
||||
<div class="wfm-search-wrap" style="margin:8px 0;">
|
||||
<input type="text" id="wfm-style-search" class="wfm-search-input" placeholder="Search styles...">
|
||||
<button class="wfm-search-clear-btn" id="wfm-style-search-clear-btn" title="Clear search">✕</button>
|
||||
</div>
|
||||
<!-- Style list -->
|
||||
<div id="wfm-style-list" class="wfm-wc-file-list">
|
||||
<p class="wfm-placeholder" style="padding:12px;font-size:12px;">Loading...</p>
|
||||
</div>
|
||||
<!-- Editor (shown when a style is selected or New is clicked) -->
|
||||
<div id="wfm-style-editor" class="wfm-wc-editor" style="display:none;">
|
||||
<div class="wfm-wc-editor-header">
|
||||
<input type="text" id="wfm-style-editor-name" class="wfm-input" placeholder="Style name" style="flex:1;min-width:0;">
|
||||
</div>
|
||||
<div class="wfm-wc-editor-hint" id="wfm-style-editor-file-label" style="display:none;"></div>
|
||||
<div class="wfm-wc-editor-hint" id="wfm-style-editor-prompt-label">Positive prompt (use {prompt} as a placeholder for the user's own prompt)</div>
|
||||
<textarea id="wfm-style-editor-prompt" class="wfm-textarea wfm-wc-editor-ta" rows="5" placeholder="e.g. cinematic still, {prompt}, dramatic lighting"></textarea>
|
||||
<div class="wfm-wc-editor-hint" id="wfm-style-editor-negative-label">Negative prompt (optional)</div>
|
||||
<textarea id="wfm-style-editor-negative" class="wfm-textarea wfm-wc-editor-ta" rows="3" placeholder="e.g. blurry, low quality"></textarea>
|
||||
<div class="wfm-wc-editor-actions">
|
||||
<button id="wfm-style-editor-save-btn" class="wfm-btn wfm-btn-sm wfm-btn-primary">Save</button>
|
||||
<button id="wfm-style-editor-addfile-btn" class="wfm-btn wfm-btn-sm" style="display:none;" title="Add a new style to this same file">+ Add to this file</button>
|
||||
<button id="wfm-style-editor-delete-btn" class="wfm-btn wfm-btn-sm wfm-btn-danger" style="display:none;">Delete</button>
|
||||
<button id="wfm-style-editor-cancel-btn" class="wfm-btn wfm-btn-sm" style="margin-left:auto;">Cancel</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<!-- /Style タブ -->
|
||||
</div>
|
||||
</div>
|
||||
</section>
|
||||
@@ -1256,6 +1320,9 @@
|
||||
<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 (subgraph-containing workflows are supported, e.g. Flux.2 / Qwen-Image / Z-Image / Mage-Flow templates; only ComfyUI's simplified App format [.app.json / Linear Mode] is not); 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; <b>Style</b> checkbox and dropdown (next to Reset Workflow): enable to apply a Fooocus-style JSON style to the positive and negative prompts at generation time — style files are loaded from <code>user/default/Workflow-Studio/style/*.json</code>; the style's <code>{prompt}</code> placeholder is replaced with the original prompt, or the style text is appended if no placeholder exists</li>
|
||||
<li id="wfm-help-gen-25"><b>Create Catalog</b> button (next to the Style dropdown): generates one preview image per Style selected in the Batch tab's Style sub-tab (using the currently loaded workflow, typically T2I), then saves each result into a chosen <b>ws_style_catalog</b> subfolder with the Style's own name as the filename (existing files with the same name are overwritten); a modal lets you create a new destination folder or pick an existing one — separate folders are useful for grouping catalogs by checkpoint or by purpose; requires at least one Style checked in Batch tab → Style sub-tab first. <b>Catalog</b> button (right next to it): jumps straight to the Gallery tab's Style_Catalog sub-tab to browse the results</li>
|
||||
<li id="wfm-help-gen-26">Create Catalog modal — <b>"Don't keep a copy in the Output folder"</b> checkbox: each generation still writes a normal file to ComfyUI's Output folder first (that's simply how the workflow's own Save Image node works), but once its copy has been saved into the catalog folder, checking this deletes that Output-folder original right away — useful for large catalog runs (e.g. all 200+ styles) so the Output folder isn't flooded with near-duplicate files; if a particular style's catalog copy fails to save, its Output file is left alone rather than being deleted</li>
|
||||
<li id="wfm-help-gen-27">Input tab → Image sub-panel — each LoadImage card now has three buttons: <b>Apply</b> (unchanged), <b>Clear</b> (resets that card's pending selection/preview back to empty; doesn't touch the workflow node itself, since LoadImage always needs some valid filename), and <b>Placeholder</b>. A <b>Placeholder Image</b> section — collapsed by default since it's a low-frequency feature, click to expand — sits at the top of the panel with a shared default: <b>Color</b> mode (set Width/Height/Color; generates a solid-color PNG on the fly) or <b>Image</b> mode (drop one default image, reused as-is). Clicking a card's own <b>Placeholder</b> button immediately replaces just that card's image with the configured default — no separate Apply click needed, and with several LoadImage cards each can be replaced individually. The Placeholder config (mode, size, color, default image) is remembered across sessions</li>
|
||||
</ul>
|
||||
</div>
|
||||
<div class="wfm-help-card">
|
||||
@@ -1263,7 +1330,8 @@
|
||||
<ul>
|
||||
<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 — <b>Prompt</b> and <b>Image</b> (drag-and-drop upload); Prompt tab has Positive Prompt, Negative Prompt, and an <b>Embeddings</b> selector at the bottom — select a model, set Weight (default 1.0), then click <b>Paste</b> to insert <code>(embedding:Name:weight)</code> at the cursor position of the last focused textarea (defaults to Positive if neither is focused); a <b>↺</b> button next to each Apply button reverts the textarea to the node's currently applied value; select text (or just place the cursor on a word/parenthesis block) and press <b>Ctrl+↑/↓</b> to adjust its emphasis weight in <code>(text:weight)</code> syntax by ±0.05 — the parentheses are removed automatically when the weight returns to 1.0</li>
|
||||
<li id="wfm-help-gen-5">Model tab: Checkpoint, VAE, LoRA (Single/Stack tabs), ControlNet, Diffusion Model (UNETLoader / UnetLoaderGGUF / LoaderGGUF), Text Encoder (CLIPLoader / DualCLIPLoader / ClipLoaderGGUF / DualClipLoaderGGUF — type and device selectors; DualCLIP shows two clip selectors), Hypernetwork (with Strength field) 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>
|
||||
<li id="wfm-help-gen-5">Model tab: Checkpoint, VAE, Diffusion Model (UNETLoader / UnetLoaderGGUF / LoaderGGUF), Text Encoder (CLIPLoader / DualCLIPLoader / ClipLoaderGGUF / DualClipLoaderGGUF — type and device selectors; DualCLIP shows two clip selectors) are always shown; ControlNet and Hypernetwork (with Strength field) are collapsed by default since they're used less often — click their header to expand; LoRA (Single/Stack tabs) has its own column to the right; all selectors have a 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>
|
||||
<li id="wfm-help-gen-28">Model tab — Highlight color: the label of each model type (Checkpoint, VAE, Diffusion Model, Text Encoder, ControlNet, Hypernetwork) and the LoRA column header turn a distinct color (default bright green) when the loaded workflow actually contains that type of node; this stays visible even while ControlNet/Hypernetwork are collapsed, so you can tell at a glance whether they're in use without expanding them; the color is customizable in the Settings tab</li>
|
||||
<li id="wfm-help-gen-6">Settings tab: KSampler and Latent Image side by side, each at 50% width</li>
|
||||
<li id="wfm-help-gen-7">Raw JSON always visible in the right column of each tab — edit directly and Apply to reload the workflow; if the loaded workflow has Bypass or Mute nodes, a note listing them appears above the search bar (Bypass nodes are excluded with their wires reconnected around them; Mute nodes are excluded with no reconnection, matching ComfyUI itself)</li>
|
||||
</ul>
|
||||
@@ -1295,6 +1363,16 @@
|
||||
<li id="wfm-help-gen-16">SPA-side wildcard expansion (A1111-style): when prompt text in non-ImpactWildcard nodes (e.g. CLIPTextEncode) contains __name__ syntax, the SPA expands it at generation time by randomly picking a line from the matching file in the WFS wildcard folder; nested wildcards are re-expanded up to 5 passes; unresolved wildcards are passed through unchanged; ImpactWildcardEncode/Processor nodes are skipped (handled server-side by Impact Pack); works in both single and batch generation</li>
|
||||
</ul>
|
||||
</div>
|
||||
<div class="wfm-help-card">
|
||||
<h3 id="wfm-help-gen-card-lora-title">Model Tab — LoRA Details</h3>
|
||||
<ul>
|
||||
<li id="wfm-help-gen-20">Two ways LoRAs are attached: a chain of standard <b>LoraLoader</b> nodes (one LoRA per node — add more by chaining additional nodes) or a single <b>Lora Loader (LoraManager)</b> node (from the ComfyUI-Lora-Manager custom node pack) that holds a list of LoRAs internally, each with its own active/model-strength/clip-strength; the Single/Stack tabs below adapt automatically depending on which type the target node is</li>
|
||||
<li id="wfm-help-gen-21">Single tab: pick one LoRA + Str M/Str C, then Apply — for a Lora Manager node this <b>replaces its entire internal LoRA list with just this one entry</b>, discarding any others it had</li>
|
||||
<li id="wfm-help-gen-22">Stack tab — Use Stack Group checkbox (shown only when a Lora Manager node exists in the workflow): <b>OFF</b> (the default whenever a workflow is loaded) shows and edits the LoRAs actually configured in the workflow's Lora Manager node itself; <b>ON</b> shows and edits the "Stack" group registered in the Models tab instead; switching either direction clears the node's LoRA list first, then loads it from the newly selected source; switching back to OFF restores exactly the LoRA list that was present when the workflow was loaded (captured as a snapshot at load time)</li>
|
||||
<li id="wfm-help-gen-23">Stack tab controls: each row has an active checkbox and Str M / Str C fields; the header "Stack" checkbox toggles all rows at once; the +/- step buttons adjust the strength of all currently active rows together; a "Showing: LoRAs currently in workflow" / "Showing: registered Stack group" label indicates which source is currently displayed; Apply writes the full list back to the target node and also appends LoRA syntax + CivitAI trigger words to the Positive prompt</li>
|
||||
<li id="wfm-help-gen-24">Caution for <b>CLIP Text Encode edit+</b> (CLIPTextEncodeEditPlus) nodes: when a Lora Manager node's trigger_words output feeds this node's text1 input (RAW/EDIT/front/back modes combine text1 with the editable text_edit field), trigger words are already included automatically at generation time; clicking a LoRA Apply button or turning on Use Stack Group additionally writes LoRA syntax/trigger words into text_edit, duplicating them — leave Use Stack Group off and avoid the LoRA Apply buttons if you want the workflow's original prompt and LoRA composition to stay unmodified</li>
|
||||
</ul>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="wfm-help-page" id="wfm-help-page-feeder">
|
||||
@@ -1347,11 +1425,16 @@
|
||||
<li id="wfm-help-lab-1">Left pane — Image: drop or click to select an I2I source image; it is uploaded to ComfyUI's input folder and used for every iteration unless "Use generated image for next" is checked</li>
|
||||
<li id="wfm-help-lab-2">Left pane — Use generated image for next: from iteration 2 onward, feeds the previous iteration's first output image back in as the I2I source instead of the original dropped image (iteration 1 always uses the original)</li>
|
||||
<li id="wfm-help-lab-3">Center pane — 4 independent columns: Checkpoint, VAE, Prompt, KSampler; each column keeps its own list of keyframes rather than sharing a row grid</li>
|
||||
<li id="wfm-help-lab-4">+ / − per column: + appends a new keyframe at the next free iteration number (up to the Batch count) and opens its edit modal immediately; − removes the last keyframe (iteration #1 can never be removed)</li>
|
||||
<li id="wfm-help-lab-4">+ / − per column: + appends a new keyframe at the next free iteration number (up to the Batch count) and opens its edit modal immediately; − removes the last keyframe (iteration #1 can never be removed); any keyframe other than #1 can also be deleted individually from inside its own edit modal via its <b>Delete</b> button, not just the last one</li>
|
||||
<li id="wfm-help-lab-5">Click a cell to edit it: iteration #1 sets the baseline value (leave it blank to keep the loaded workflow's own setting); iteration #2+ also lets you choose which iteration it starts applying from, plus a "revert to #1's setting" checkbox</li>
|
||||
<li id="wfm-help-lab-6">Effective value at iteration N: the latest keyframe with iteration ≤ N is used and carries forward until the next keyframe changes it; "revert to #1" reuses iteration #1's value (or the workflow default if #1 is blank) instead of specifying a new one</li>
|
||||
<li id="wfm-help-lab-6">Effective value at iteration N: the latest keyframe with iteration ≤ N is used and carries forward until the next keyframe changes it; "revert to #1" reuses iteration #1's value (or the workflow default if #1 is blank) instead of specifying a new one; lowering the Batch count (by hand, or by loading/applying a plan) below an existing keyframe's iteration number doesn't delete or renumber that keyframe — a warning toast appears, and the keyframe simply stays dormant (never reached by the run loop) until Batch count is raised again</li>
|
||||
<li id="wfm-help-lab-7">Lab never edits the workflow shown in Input/Model/Settings — every iteration runs on a fresh clone of the loaded workflow, so keyframes here never affect the other subtabs</li>
|
||||
<li id="wfm-help-lab-8">Prompt cell editor extras: <b>Get from GenerateUI</b> fills Positive/Negative from the workflow currently loaded in GenerateUI; <b>Get from Image</b> extracts a prompt from the image currently loaded in Lab's own Image drop zone (same detection as the Metadata tab; no separate file picker); <b>Style</b> appends whichever style is currently selected in the Style checkbox/dropdown at the top of the GenerateUI toolbar to the Positive/Negative text below, comma-separated after any existing text (never clears it) — enable that checkbox and pick a style first, Lab doesn't have its own separate style picker</li>
|
||||
<li id="wfm-help-lab-8">Prompt cell editor extras: <b>Get from GenerateUI</b> fills Positive/Negative from the workflow currently loaded in GenerateUI; <b>Get from Image</b> extracts a prompt from the image currently loaded in Lab's own Image drop zone (same detection as the Metadata tab; no separate file picker); <b>Style</b> row — the <b>Apply</b> button appends whichever style is currently selected in the Style dropdown at the top of the GenerateUI toolbar to the Positive/Negative text below, comma-separated after any existing text (never clears it), then checks the Style checkbox and shows the applied style's name next to it (not on the button) — the style NAME always comes from that top dropdown (Lab has no picker of its own), and clicking Apply works regardless of the top toolbar's own Style enable checkbox; unchecking the Style checkbox only clears that name label — it does not remove the already-appended text from Positive/Negative, which stays there for you to edit or delete by hand</li>
|
||||
<li id="wfm-help-lab-9">Left pane — <b>T2I workflow (no source image)</b>: check this when the loaded workflow is text-to-image (no LoadImage node). It skips the "drop a source image first" requirement, ignores any dropped image and the Checkpoint/VAE/Prompt/KSampler keyframes still apply normally; the Image drop zone and "Use generated image for next" are greyed out while it's on (any previously dropped image is kept, not deleted, in case you switch back to I2I); the setting is saved with the plan as <code>t2i_mode</code></li>
|
||||
<li id="wfm-help-lab-10">Wildcards: Positive/Negative prompt text in Prompt column keyframes supports the same A1111-style <code>__name__</code> syntax as the main GenerateUI (see Prompt tab's Wildcards help above) — each keyframe's text is expanded fresh right before that iteration runs, so every iteration can draw a different random line even when reusing the same keyframe</li>
|
||||
<li id="wfm-help-lab-11">Prompt cell editor also has <b>Clear</b> (empties both Positive and Negative) and <b>Get from Previous</b> (copies both Positive and Negative from the keyframe immediately before this one in the same column — e.g. editing #3 copies #2's prompt wholesale; not shown on keyframe #1, which has no earlier row to copy from)</li>
|
||||
<li id="wfm-help-lab-12">Keyframe #1 in every column shows the currently loaded workflow's own live setting — Checkpoint, VAE, Prompt, and KSampler — instead of a blank placeholder, both in its grid cell (dashed border) and pre-filled into its edit modal, for as long as it hasn't been explicitly saved with an override; saving it (even without changing anything) locks that value in as a real override and the dashed/live styling goes away; switching to the Lab subtab always refreshes this against whatever is currently loaded in GenerateUI</li>
|
||||
<li id="wfm-help-lab-13"><b>Bypass</b> checkbox (every keyframe, including #1): skips that row entirely when picking which setting applies at a given iteration — as if the row didn't exist — so whatever was active before it (an earlier keyframe, or ultimately nothing) just keeps running; Lab-internal only, it never touches the actual ComfyUI node's mode; disables that row's value fields and its Revert checkbox while checked (the two are mutually exclusive); the cell shows an amber "⏭ Bypassed" label, which takes priority over both the Revert and live-value display</li>
|
||||
</ul>
|
||||
</div>
|
||||
|
||||
@@ -1361,11 +1444,14 @@
|
||||
<li id="wfm-help-lab-plan-1">Right pane — Batch: number of iterations to run; Note: free-text memo saved together with the plan</li>
|
||||
<li id="wfm-help-lab-plan-2">Run / Pause / Cancel: Run starts the batch loop; Pause/Resume freezes it between iterations; Cancel interrupts the current generation and stops the loop</li>
|
||||
<li id="wfm-help-lab-plan-3">Plan Save vs Save As: Plan Save silently overwrites the currently loaded plan (or asks for a name the first time); Save As always asks for a new name, even while a plan is already loaded</li>
|
||||
<li id="wfm-help-lab-plan-4">Plan Load: drop a plan's .json file, or its .png index-image thumbnail, onto the PLAN box (or click it to browse) — a dropped .json is read directly; a dropped .png fetches the matching .json (same filename) from the server</li>
|
||||
<li id="wfm-help-lab-plan-4">Plan Load: drop a plan's .json file, or any of its index-image PNGs, onto the PLAN box (or click it to browse) — a dropped .json is read directly; a dropped .png is read directly too if it carries embedded plan data (every index image since v0.3.90 does, in a <code>wfm_lab_plan</code> chunk — see below), falling back to fetching a same-named .json from the server for older index images that predate this</li>
|
||||
<li id="wfm-help-lab-plan-5">Plan Clear resets the Setting tab to an empty plan (asks for confirmation first)</li>
|
||||
<li id="wfm-help-lab-plan-6">Plan files are stored in <code>user/default/Workflow-Studio/lab_plan/</code> as <code><name>.json</code> plus a <code><name>.png</code> index image — a contact sheet of up to 9 result thumbnails (3 per row) generated automatically whenever a plan with results is saved</li>
|
||||
<li id="wfm-help-lab-plan-6">Plan files are stored in <code>user/default/Workflow-Studio/lab_plan/</code> as <code>ws_labplan_<name>.json</code> plus a <code>ws_labplan_<name>.png</code> index image — a contact sheet of up to 9 result thumbnails (3 per row) generated automatically whenever a plan with results is saved. The <code>ws_labplan_</code> prefix is added automatically by Plan Save/Save As (type just the plain name when prompted) so plan files are easy to pick out among other files in that folder</li>
|
||||
<li id="wfm-help-lab-plan-7">Eagle auto-save (configured in the Settings tab) applies to every image Lab generates, the same as GenerateUI's own Generate button</li>
|
||||
<li id="wfm-help-lab-plan-8">Plan JSON subtab: shows the current Setting tab's plan as raw JSON; <b>Refresh</b> re-reads it from the Setting tab (discarding any unapplied text edits), <b>Apply to Setting</b> parses your edits and writes them back into the Setting tab (columns, note, batch count, chain-image, source image, results) — the same effect as loading that JSON as a plan file, without needing to save it first</li>
|
||||
<li id="wfm-help-lab-plan-9">Each saved plan records the filename of the workflow that was loaded in GenerateUI at save time (<code>workflow_filename</code> in the Plan JSON). After loading a plan, an <b>Open Workflow</b> button appears in the PLAN box — click it to load that exact workflow file back into GenerateUI (asks for confirmation, since it replaces whatever is currently loaded)</li>
|
||||
<li id="wfm-help-lab-plan-10">Right pane — <b>Save index image to Output on Run</b>: when checked, every time Run finishes it builds the same contact-sheet index image used for Plan files and saves it directly into ComfyUI's own Output folder as <code>Lab_index_<counter>_.png</code> (auto-numbered like a normal generated image, never overwriting a previous run's). Once saved, it also goes through Eagle auto-save (if enabled in the Settings tab) just like every other Lab-generated image — no separate checkbox for that, it follows the same global toggle. This is independent of Plan Save, which still always writes its own index image next to the plan file in <code>lab_plan/</code> regardless of this checkbox; this setting is saved with the plan as <code>save_index_on_run</code></li>
|
||||
<li id="wfm-help-lab-plan-11">Every index image PNG — whether from Plan Save/Save As or from <b>Save index image to Output on Run</b> — carries the entire plan (columns, note, batch count, chain-image/T2I settings, workflow filename, results) embedded in it directly as a PNG <code>wfm_lab_plan</code> chunk, so the Output-folder copy is self-contained and works as a Plan Load source too even though it has no matching .json next to it anywhere</li>
|
||||
</ul>
|
||||
</div>
|
||||
|
||||
@@ -1408,6 +1494,16 @@
|
||||
<li id="wfm-help-prompt-9">Wildcard file manager: create/edit/delete .txt/.yaml wildcard files; click filename to insert __filename__ at cursor</li>
|
||||
</ul>
|
||||
</div>
|
||||
<div class="wfm-help-card">
|
||||
<h3 id="wfm-help-prompt-card-style-title">Style</h3>
|
||||
<ul>
|
||||
<li id="wfm-help-prompt-10">Right pane's Wildcard/Style tab bar switches the whole panel between the wildcard tools above and this Style manager — same right pane, two modes</li>
|
||||
<li id="wfm-help-prompt-11">Create/edit/delete registered Styles (the same ones used by GenerateUI's Style dropdown, Batch tab, and the Style Catalog): click a name in the list to edit it, or <b>+ New</b> for a blank entry; <b>Name</b>, <b>Positive prompt</b> (supports the <code>{prompt}</code> placeholder — replaced with the user's own prompt, or appended after it if omitted) and <b>Negative prompt</b> (optional)</li>
|
||||
<li id="wfm-help-prompt-12">Renaming a style keeps its position in whichever file it was originally defined in; new styles are saved into a dedicated <code>custom.json</code> inside the style folder so the bundled style packs are never modified directly; a name must be unique across all styles</li>
|
||||
<li id="wfm-help-prompt-13">Saving, renaming, or deleting a style immediately refreshes GenerateUI's Style dropdown, the Batch tab's style checklist, and the Style Catalog's name list — no reload needed</li>
|
||||
<li id="wfm-help-prompt-14">Each entry in the list shows its source file as a small badge next to the name (e.g. <code>sdxl_styles_diva.json</code>); while editing an existing style, that filename also appears above the Positive prompt field, and a <b>+ Add to this file</b> button appears next to Save — click it to clear the form for a brand-new style that gets appended to that same file instead of the default <code>custom.json</code></li>
|
||||
</ul>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="wfm-help-page" id="wfm-help-page-metadata">
|
||||
@@ -1472,6 +1568,7 @@
|
||||
<ul>
|
||||
<li id="wfm-help-settings-11">Text Size: one slider (10–28 px) adjusts font size for all prompt and chat textareas at once — Generate UI positive/negative prompts, AI Assistant chat input, Preset positive/negative, Wildcard prompt and file editor, and Metadata prompt full preview; takes effect immediately and saved with Save Settings</li>
|
||||
<li id="wfm-help-settings-12">RAW JSON Colors: customize the 6 syntax highlight colors for the Raw JSON editor in Generate UI — Default Text, Name/Scheduler, Title, Width/Height, Prompt/Text, Image/File; changes apply immediately on color pick; Reset Defaults restores the original color scheme</li>
|
||||
<li id="wfm-help-settings-14">GenerateUI Model Tab Highlight: pick the color used to mark Checkpoint/VAE/Diffusion Model/Text Encoder/ControlNet/Hypernetwork labels and the LoRA column header in GenerateUI's Model tab when the loaded workflow actually contains that type of node; default bright green; changes apply immediately, Reset Defaults restores it</li>
|
||||
</ul>
|
||||
</div>
|
||||
<div class="wfm-help-card">
|
||||
@@ -1526,6 +1623,24 @@
|
||||
<li id="wfm-help-gallery-4">Toolbar filters: favorites (★), text search (filename / tag / prompt), tag filter, group filter, sort by date/name</li>
|
||||
</ul>
|
||||
</div>
|
||||
<div class="wfm-help-card">
|
||||
<h3 id="wfm-help-gallery-card-styleprompt-title">ImagePrompt Gallery</h3>
|
||||
<ul>
|
||||
<li id="wfm-help-gallery-18">Second sub-tab next to Output (top of the Gallery tab) for browsing a visual prompt library — manages the <b>ws_image_prompt</b> folder inside the ComfyUI output directory (created automatically)</li>
|
||||
<li id="wfm-help-gallery-19">Same 3-column layout: folder tree (left) | thumbnails (center) | prompt builder (right). Click a thumbnail to preview it and its prompt text — this does not add it to the prompt yet</li>
|
||||
<li id="wfm-help-gallery-20">"+ Add" appends the previewed image's prompt as a chip under "Selected Prompts"; chips can be removed individually (×) or all at once ("Clear All"); "Save" edits and persists the prompt text for that image</li>
|
||||
<li id="wfm-help-gallery-21">"Final Prompt" combines all chips into one comma-separated text (also freely editable); "Copy" copies it to the clipboard. Prompt text is stored as a plain <b>.txt</b> file next to each image, so anyone can add their own entries by dropping an image + matching .txt file into a subfolder</li>
|
||||
</ul>
|
||||
</div>
|
||||
<div class="wfm-help-card">
|
||||
<h3 id="wfm-help-gallery-card-stylecatalog-title">Style_Catalog Gallery</h3>
|
||||
<ul>
|
||||
<li id="wfm-help-gallery-22">Third sub-tab (top of the Gallery tab) for visually picking a registered Style by its preview image — manages the <b>ws_style_catalog</b> folder inside the ComfyUI output directory (created automatically); populated by the GenerateUI tab's <b>Create Catalog</b> button (see GenerateUI Tab help)</li>
|
||||
<li id="wfm-help-gallery-23">Same 3-column layout: folder tree (left) | thumbnails (center) | Positive/Negative prompt panel (right). Click a thumbnail to read the Positive/Negative prompt actually embedded in that generated image, each with its own <b>Copy</b> button</li>
|
||||
<li id="wfm-help-gallery-24"><b>Select as Style</b> button: matches the selected image's filename (without extension) against a registered Style name and switches the GenerateUI tab's Style dropdown to it — a visual shortcut into the existing named-Style system, not a one-off apply of the embedded prompt (if the Style was renamed or deleted since the catalog image was created, a "no matching style" toast is shown instead)</li>
|
||||
<li id="wfm-help-gallery-25"><b>Load in GenerateUI</b> / <b>Open in Metadata Tab</b> buttons: read the workflow embedded in the catalog image itself (the catalog copy carries the same PNG metadata as the original output image) and either load it straight into the GenerateUI editor or open the image in the Metadata tab for inspection — no need to hunt down the original file in the Output folder</li>
|
||||
</ul>
|
||||
</div>
|
||||
<div class="wfm-help-card">
|
||||
<h3 id="wfm-help-gallery-card-folder-title">Folder & Selection</h3>
|
||||
<ul>
|
||||
@@ -1641,7 +1756,7 @@
|
||||
<div class="wfm-help-card">
|
||||
<h3 id="wfm-help-sidepanel-card-ai-title">AI TOOL tab</h3>
|
||||
<ul>
|
||||
<li id="wfm-help-sidepanel-16">AI TOOL tab: Translation, Chat, TOOLS, and Settings sub-tabs powered by Ollama, LM Studio, or Lemonade; 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-16">AI TOOL tab: Translation, Chat, TOOLS, and Settings sub-tabs powered by Ollama, LM Studio, Lemonade, or Unsloth; Chat supports multi-turn conversations; TOOLS includes VLM image analysis and wildcard generation; settings shared with the SPA AI TOOL tab via localStorage</li>
|
||||
</ul>
|
||||
</div>
|
||||
<div class="wfm-help-card">
|
||||
@@ -1664,7 +1779,7 @@
|
||||
</div>
|
||||
<div class="wfm-help-card">
|
||||
<h3 id="wfm-help-ai-card-translate-title">Translation pane</h3>
|
||||
<p id="wfm-help-ai-2">Translation pane: translate text between Japanese, English, Chinese, or a custom Free language using Ollama, LM Studio, or Lemonade; ⇄ swap button swaps both language selectors and text content; selections are saved automatically</p>
|
||||
<p id="wfm-help-ai-2">Translation pane: translate text between Japanese, English, Chinese, or a custom Free language using Ollama, LM Studio, Lemonade, or Unsloth; ⇄ swap button swaps both language selectors and text content; selections are saved automatically</p>
|
||||
</div>
|
||||
<div class="wfm-help-card">
|
||||
<h3 id="wfm-help-ai-card-chat-title">Chat pane</h3>
|
||||
@@ -1688,7 +1803,7 @@
|
||||
</div>
|
||||
<div class="wfm-help-card">
|
||||
<h3 id="wfm-help-ai-card-settings-title">Settings pane</h3>
|
||||
<p id="wfm-help-ai-6">Settings pane: choose backend (Ollama / LM Studio / Lemonade), set API URL, test connection, select model, configure Free language names; Chat Image Generation section lets you enable a dedicated workflow for Chat-triggered text-to-image generation instead of the one currently loaded in GenerateUI; Chat I2I Generation section is the same but for image-to-image generation when an image is attached; settings are shared with the Library panel's A tab via localStorage</p>
|
||||
<p id="wfm-help-ai-6">Settings pane: choose backend (Ollama / LM Studio / Lemonade / Unsloth), set API URL, test connection, select model; Unsloth always requires an API key even for local access — set UNSLOTH_API_KEY in a .env file in the plugin folder (copy .env.example) and restart ComfyUI, the key is read server-side and never sent to the browser; Unsloth also requires "Auto model switching (OpenAI API)" to be turned ON in the Unsloth Desktop app itself (its own Settings screen) — without it, requests fail with HTTP 404 unless a model was already manually loaded in the Unsloth Studio UI; Unsloth reasoning models return their thinking in a separate reasoning_content field rather than inline <think> tags, so a low Max tokens can make the model spend its whole budget reasoning and return an empty reply — increase Max tokens (2048+) if replies come back blank; Generation section — Thinking mode toggle (off by default; Ollama receives a `think` flag, and regardless of backend any <think>...</think> block is stripped from the output when off, so reasoning models don't clutter Translation/Chat/TOOLS results) and Max tokens (Ollama: num_predict, LM Studio/Lemonade/Unsloth: max_tokens; 0 = unlimited); configure Free language names; Chat Image Generation section lets you enable a dedicated workflow for Chat-triggered text-to-image generation instead of the one currently loaded in GenerateUI; Chat I2I Generation section is the same but for image-to-image generation when an image is attached; settings are shared with the Library panel's A tab via localStorage</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@@ -1958,6 +2073,14 @@
|
||||
|
||||
<!-- Gallery Tab -->
|
||||
<section id="wfm-tab-gallery" class="wfm-tab-content">
|
||||
<div class="wfm-gallery-subtab-nav">
|
||||
<button id="wfm-gallery-subtab-output" class="wfm-gallery-subtab-btn active" data-gallery-subtab="output">Output</button>
|
||||
<button id="wfm-gallery-subtab-imageprompt" class="wfm-gallery-subtab-btn" data-gallery-subtab="imageprompt">ImagePrompt</button>
|
||||
<button id="wfm-gallery-subtab-styleCatalog" class="wfm-gallery-subtab-btn" data-gallery-subtab="styleCatalog">Style_Catalog</button>
|
||||
</div>
|
||||
|
||||
<!-- Output ギャラリーパネル -->
|
||||
<div id="wfm-gallery-panel-output" class="wfm-gallery-panel active">
|
||||
<!-- Toolbar -->
|
||||
<div class="wfm-toolbar">
|
||||
<div class="wfm-toolbar-row" style="gap:6px;flex-wrap:wrap;align-items:center;">
|
||||
@@ -2059,6 +2182,12 @@
|
||||
<div class="wfm-gallery-info-row" id="wfm-gallery-info-size"></div>
|
||||
<div class="wfm-gallery-info-row" id="wfm-gallery-info-date"></div>
|
||||
</div>
|
||||
<!-- ImagePromptサイドカー ( .txt / ponyxlWildcardsVault 由来のプロンプトがある画像のみ表示) -->
|
||||
<div class="wfm-gallery-info-section" id="wfm-gallery-image-prompt-section" style="display:none;">
|
||||
<hr class="wfm-group-divider">
|
||||
<div class="wfm-gallery-section-title">Prompt</div>
|
||||
<div id="wfm-gallery-image-prompt-text" class="wfm-gallery-image-prompt-text"></div>
|
||||
</div>
|
||||
<hr class="wfm-group-divider">
|
||||
<!-- タグ -->
|
||||
<div class="wfm-gallery-info-section">
|
||||
@@ -2098,6 +2227,149 @@
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<!-- /Output ギャラリーパネル -->
|
||||
|
||||
<!-- ImagePrompt ギャラリーパネル -->
|
||||
<div id="wfm-gallery-panel-imageprompt" class="wfm-gallery-panel">
|
||||
<div class="wfm-toolbar">
|
||||
<div class="wfm-toolbar-row" style="gap:6px;flex-wrap:wrap;align-items:center;">
|
||||
<div class="wfm-search-wrap">
|
||||
<input type="text" id="wfm-imageprompt-search" class="wfm-search-input" placeholder="Search prompts...">
|
||||
<button class="wfm-search-clear-btn" id="wfm-imageprompt-search-clear-btn" title="Clear search">✕</button>
|
||||
</div>
|
||||
<span id="wfm-imageprompt-count" class="wfm-nodes-count"></span>
|
||||
<button id="wfm-imageprompt-refresh-btn" class="wfm-btn wfm-btn-sm">Refresh</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="wfm-gallery-layout">
|
||||
<!-- 左: フォルダツリー (ws_image_prompt ルート) -->
|
||||
<div id="wfm-imageprompt-tree-panel" class="wfm-gallery-tree-panel">
|
||||
<div class="wfm-gallery-tree-header">
|
||||
<span id="wfm-imageprompt-tree-title" class="wfm-gallery-tree-title">Folders</span>
|
||||
</div>
|
||||
<div id="wfm-imageprompt-tree" class="wfm-gallery-tree">
|
||||
<p class="wfm-placeholder" id="wfm-imageprompt-tree-placeholder">Loading...</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- 中: サムネイル一覧 -->
|
||||
<div id="wfm-imageprompt-list-panel" class="wfm-gallery-list-panel">
|
||||
<div id="wfm-imageprompt-grid" class="wfm-gallery-grid wfm-gallery-view-thumb">
|
||||
<p class="wfm-placeholder" id="wfm-imageprompt-list-placeholder">Select a folder to browse images.</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- 右: プロンプトビルダーパネル (2カラム: 選択/チップ | 最終プロンプト) -->
|
||||
<div id="wfm-imageprompt-detail-panel" class="wfm-gallery-detail-panel wfm-imageprompt-detail-panel">
|
||||
<div class="wfm-imageprompt-detail-col wfm-imageprompt-detail-col-left">
|
||||
<div class="wfm-gallery-detail-header">
|
||||
<span id="wfm-imageprompt-selected-name" class="wfm-gallery-detail-filename"></span>
|
||||
</div>
|
||||
<div id="wfm-imageprompt-selected-preview" class="wfm-gallery-detail-preview wfm-gallery-preview-container">
|
||||
<span id="wfm-imageprompt-no-selection" class="wfm-placeholder">No selection</span>
|
||||
</div>
|
||||
|
||||
<div class="wfm-imageprompt-section">
|
||||
<div id="wfm-imageprompt-selected-prompt-title" class="wfm-gallery-section-title">Prompt</div>
|
||||
<textarea id="wfm-imageprompt-selected-prompt" class="wfm-imageprompt-prompt-box" rows="4" placeholder="No prompt data for this image."></textarea>
|
||||
<div class="wfm-imageprompt-btn-row">
|
||||
<button id="wfm-imageprompt-save-prompt-btn" class="wfm-btn wfm-btn-sm" disabled>Save</button>
|
||||
<button id="wfm-imageprompt-add-btn" class="wfm-btn wfm-btn-sm wfm-btn-primary" disabled>+ Add</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<hr class="wfm-group-divider">
|
||||
|
||||
<div class="wfm-imageprompt-section">
|
||||
<div class="wfm-gallery-detail-header" style="padding:0;background:none;border:none;display:flex;justify-content:space-between;align-items:center;">
|
||||
<span id="wfm-imageprompt-chips-title" class="wfm-gallery-section-title">Selected Prompts</span>
|
||||
<button id="wfm-imageprompt-clear-btn" class="wfm-btn wfm-btn-sm">Clear All</button>
|
||||
</div>
|
||||
<div id="wfm-imageprompt-chips" class="wfm-imageprompt-chips"></div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="wfm-imageprompt-detail-col wfm-imageprompt-detail-col-right wfm-imageprompt-final-section">
|
||||
<div id="wfm-imageprompt-final-prompt-title" class="wfm-gallery-section-title">Final Prompt</div>
|
||||
<textarea id="wfm-imageprompt-final-prompt" class="wfm-imageprompt-prompt-box wfm-imageprompt-final-textarea"></textarea>
|
||||
<button id="wfm-imageprompt-copy-btn" class="wfm-btn wfm-btn-primary" style="width:100%;margin-top:6px;">Copy</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<!-- /ImagePrompt ギャラリーパネル -->
|
||||
|
||||
<!-- Style_Catalog ギャラリーパネル -->
|
||||
<div id="wfm-gallery-panel-styleCatalog" class="wfm-gallery-panel">
|
||||
<div class="wfm-toolbar">
|
||||
<div class="wfm-toolbar-row" style="gap:6px;flex-wrap:wrap;align-items:center;">
|
||||
<div class="wfm-search-wrap">
|
||||
<input type="text" id="wfm-stylecatalog-search" class="wfm-search-input" placeholder="Search...">
|
||||
<button class="wfm-search-clear-btn" id="wfm-stylecatalog-search-clear-btn" title="Clear search">✕</button>
|
||||
</div>
|
||||
<span id="wfm-stylecatalog-count" class="wfm-nodes-count"></span>
|
||||
<button id="wfm-stylecatalog-refresh-btn" class="wfm-btn wfm-btn-sm">Refresh</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="wfm-gallery-layout">
|
||||
<!-- 左: フォルダツリー (ws_style_catalog ルート) -->
|
||||
<div id="wfm-stylecatalog-tree-panel" class="wfm-gallery-tree-panel">
|
||||
<div class="wfm-gallery-tree-header">
|
||||
<span id="wfm-stylecatalog-tree-title" class="wfm-gallery-tree-title">Folders</span>
|
||||
</div>
|
||||
<div id="wfm-stylecatalog-tree" class="wfm-gallery-tree">
|
||||
<p class="wfm-placeholder" id="wfm-stylecatalog-tree-placeholder">Loading...</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- 中: サムネイル一覧 -->
|
||||
<div id="wfm-stylecatalog-list-panel" class="wfm-gallery-list-panel">
|
||||
<div id="wfm-stylecatalog-grid" class="wfm-gallery-grid wfm-gallery-view-thumb">
|
||||
<p class="wfm-placeholder" id="wfm-stylecatalog-list-placeholder">Select a folder to browse images.</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- 右: Positive/Negativeプロンプト表示パネル -->
|
||||
<div id="wfm-stylecatalog-detail-panel" class="wfm-gallery-detail-panel">
|
||||
<div class="wfm-gallery-detail-header">
|
||||
<span id="wfm-stylecatalog-selected-name" class="wfm-gallery-detail-filename"></span>
|
||||
</div>
|
||||
<div id="wfm-stylecatalog-selected-preview" class="wfm-gallery-detail-preview wfm-gallery-preview-container">
|
||||
<span id="wfm-stylecatalog-no-selection" class="wfm-placeholder">No selection</span>
|
||||
</div>
|
||||
|
||||
<div class="wfm-imageprompt-section">
|
||||
<div class="wfm-gallery-detail-header" style="padding:0;background:none;border:none;display:flex;justify-content:space-between;align-items:center;">
|
||||
<span id="wfm-stylecatalog-positive-title" class="wfm-gallery-section-title">Positive</span>
|
||||
<button id="wfm-stylecatalog-copy-positive-btn" class="wfm-btn wfm-btn-sm" disabled>Copy</button>
|
||||
</div>
|
||||
<div id="wfm-stylecatalog-positive-text" class="wfm-gallery-image-prompt-text"></div>
|
||||
</div>
|
||||
|
||||
<hr class="wfm-group-divider">
|
||||
|
||||
<div class="wfm-imageprompt-section">
|
||||
<div class="wfm-gallery-detail-header" style="padding:0;background:none;border:none;display:flex;justify-content:space-between;align-items:center;">
|
||||
<span id="wfm-stylecatalog-negative-title" class="wfm-gallery-section-title">Negative</span>
|
||||
<button id="wfm-stylecatalog-copy-negative-btn" class="wfm-btn wfm-btn-sm" disabled>Copy</button>
|
||||
</div>
|
||||
<div id="wfm-stylecatalog-negative-text" class="wfm-gallery-image-prompt-text"></div>
|
||||
</div>
|
||||
|
||||
<hr class="wfm-group-divider">
|
||||
|
||||
<div class="wfm-imageprompt-section">
|
||||
<button id="wfm-stylecatalog-select-style-btn" class="wfm-btn wfm-btn-primary" style="width:100%;" disabled>Select as Style</button>
|
||||
<button id="wfm-stylecatalog-load-genui-btn" class="wfm-btn" style="width:100%;margin-top:6px;" disabled>Load in GenerateUI</button>
|
||||
<button id="wfm-stylecatalog-open-metadata-btn" class="wfm-btn" style="width:100%;margin-top:6px;" disabled>Open in Metadata Tab</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<!-- /Style_Catalog ギャラリーパネル -->
|
||||
</section>
|
||||
|
||||
<!-- Image Edit Tab -->
|
||||
@@ -2539,6 +2811,9 @@
|
||||
<label class="wfm-ai-radio-label">
|
||||
<input type="radio" name="wfm-ai-backend" value="lemonade"> Lemonade
|
||||
</label>
|
||||
<label class="wfm-ai-radio-label">
|
||||
<input type="radio" name="wfm-ai-backend" value="unsloth"> Unsloth
|
||||
</label>
|
||||
</div>
|
||||
</div>
|
||||
<div class="wfm-ai-settings-section">
|
||||
@@ -2561,6 +2836,19 @@
|
||||
<button id="wfm-ai-model-refresh-btn" class="wfm-btn">Refresh</button>
|
||||
</div>
|
||||
</div>
|
||||
<div class="wfm-ai-settings-section">
|
||||
<div class="wfm-ai-settings-title" id="wfm-ai-settings-generation-title">Generation</div>
|
||||
<div class="wfm-ai-settings-row">
|
||||
<label class="wfm-ai-label" style="display:flex;align-items:center;gap:6px;cursor:pointer;">
|
||||
<input type="checkbox" id="wfm-ai-thinking-mode-checkbox">
|
||||
<span id="wfm-ai-thinking-mode-label">Thinking mode</span>
|
||||
</label>
|
||||
</div>
|
||||
<div class="wfm-ai-settings-row">
|
||||
<label class="wfm-ai-label" id="wfm-ai-max-tokens-label">Max tokens</label>
|
||||
<input type="number" id="wfm-ai-max-tokens" class="wfm-input" min="0" step="1" placeholder="0 = unlimited">
|
||||
</div>
|
||||
</div>
|
||||
<div class="wfm-ai-settings-section">
|
||||
<div class="wfm-ai-settings-title" id="wfm-ai-settings-freelang-title">Free language</div>
|
||||
<div class="wfm-ai-settings-row">
|
||||
|
||||
@@ -0,0 +1,128 @@
|
||||
"""
|
||||
Style/Prompt ギャラリー用シードデータ投入スクリプト。
|
||||
|
||||
comfyui_prompt_gallery / prompt_builder_proto 形式の wildcard データ
|
||||
(pack: set: category: leaf: [tag_string] という4階層YAML + thumbnails/ 配下の対応画像)
|
||||
から、画像とタグ文字列の組が揃っているエントリだけを ws_style_prompt 用フォルダへコピーする。
|
||||
|
||||
- テキストのみのワイルドカード(画像が無いもの)は対象外
|
||||
- サムネイル画像はあってもYAML側にタグが無いもの(プレースホルダー画像等)も対象外
|
||||
- コピー先には画像と同名の .txt サイドカー(タグ文字列そのまま)を書き込む
|
||||
|
||||
Usage:
|
||||
python tools/import_style_prompt_seed.py --source <wildcard_dataディレクトリ> --dest <ws_style_promptディレクトリ>
|
||||
"""
|
||||
import argparse
|
||||
import re
|
||||
import shutil
|
||||
from pathlib import Path
|
||||
|
||||
IMAGE_EXTS = {".png", ".jpg", ".jpeg", ".webp"}
|
||||
|
||||
|
||||
def clean_tags(text: str) -> str:
|
||||
text = text.strip()
|
||||
text = re.sub(r"^[,\s]+|[,\s]+$", "", text)
|
||||
text = re.sub(r"\s*,\s*", ", ", text)
|
||||
return text
|
||||
|
||||
|
||||
def parse_yaml_leaves(yaml_path: Path) -> dict[str, str]:
|
||||
"""comfyui_prompt_gallery の parseYamlForImages と同じ簡易パーサ(PyYAML不要)。
|
||||
「key:」行の直後が「- タグ文字列」で始まる行なら key をリーフとみなす。
|
||||
戻り値: {leaf_name(小文字): タグ文字列}
|
||||
"""
|
||||
leaves: dict[str, str] = {}
|
||||
lines = yaml_path.read_text(encoding="utf-8", errors="replace").split("\n")
|
||||
for i, line in enumerate(lines):
|
||||
trimmed = line.strip()
|
||||
if not trimmed or trimmed.startswith("#"):
|
||||
continue
|
||||
if not trimmed.endswith(":"):
|
||||
continue
|
||||
if i + 1 >= len(lines):
|
||||
continue
|
||||
next_trimmed = lines[i + 1].strip()
|
||||
if not next_trimmed.startswith("-"):
|
||||
continue
|
||||
key = trimmed[:-1].strip()
|
||||
tags = next_trimmed[1:].strip()
|
||||
if not tags or key.lower() == "skip":
|
||||
continue
|
||||
leaves[key.lower()] = clean_tags(tags)
|
||||
return leaves
|
||||
|
||||
|
||||
def import_category(cat_dir: Path, dest_root: Path) -> tuple[int, int, int]:
|
||||
"""1カテゴリ分を投入する。戻り値: (copied, images_without_prompt, leaves_total)"""
|
||||
category = cat_dir.name
|
||||
yaml_files = sorted(cat_dir.glob("*.yaml")) + sorted(cat_dir.glob("*.yml"))
|
||||
|
||||
leaves: dict[str, str] = {}
|
||||
for yf in yaml_files:
|
||||
leaves.update(parse_yaml_leaves(yf))
|
||||
|
||||
copied = 0
|
||||
images_without_prompt = 0
|
||||
|
||||
# "thumbnails" と、preview違いの "thumbnails_option2"(例: alchemist.preview3.jpeg)の両方を対象にする
|
||||
for thumb_dir_name in ("thumbnails", "thumbnails_option2"):
|
||||
thumbnails_dir = cat_dir / thumb_dir_name
|
||||
if not thumbnails_dir.is_dir():
|
||||
continue
|
||||
for img_path in sorted(thumbnails_dir.rglob("*")):
|
||||
if not img_path.is_file() or img_path.suffix.lower() not in IMAGE_EXTS:
|
||||
continue
|
||||
# "alchemist.preview3.jpeg" のような二重拡張子にも対応するため、最初の "." より前をリーフ名候補にする
|
||||
leaf_candidate = img_path.name.split(".")[0].lower()
|
||||
tags = leaves.get(leaf_candidate)
|
||||
if tags is None:
|
||||
images_without_prompt += 1
|
||||
continue
|
||||
|
||||
rel_parts = img_path.relative_to(thumbnails_dir).parts
|
||||
# 先頭1階層(パック名。例: "ponyxl")は全カテゴリ共通で冗長なため省く
|
||||
dest_rel = Path(*rel_parts[1:]) if len(rel_parts) > 1 else Path(rel_parts[0])
|
||||
dest_path = dest_root / category / dest_rel
|
||||
dest_path.parent.mkdir(parents=True, exist_ok=True)
|
||||
|
||||
shutil.copy2(img_path, dest_path)
|
||||
dest_path.with_suffix(".txt").write_text(tags, encoding="utf-8")
|
||||
copied += 1
|
||||
|
||||
return copied, images_without_prompt, len(leaves)
|
||||
|
||||
|
||||
def main() -> None:
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument("--source", required=True, help="wildcard_data ディレクトリ")
|
||||
parser.add_argument("--dest", required=True, help="投入先 ws_style_prompt ディレクトリ")
|
||||
args = parser.parse_args()
|
||||
|
||||
source = Path(args.source)
|
||||
dest = Path(args.dest)
|
||||
if not source.is_dir():
|
||||
raise SystemExit(f"source not found: {source}")
|
||||
dest.mkdir(parents=True, exist_ok=True)
|
||||
|
||||
categories = [
|
||||
d for d in sorted(source.iterdir())
|
||||
if d.is_dir() and (d / "thumbnails").is_dir()
|
||||
]
|
||||
if not categories:
|
||||
raise SystemExit(f"No category with a thumbnails/ subfolder found under {source}")
|
||||
|
||||
total_copied = 0
|
||||
total_skipped = 0
|
||||
for cat_dir in categories:
|
||||
copied, skipped, leaf_total = import_category(cat_dir, dest)
|
||||
print(f"[{cat_dir.name}] copied={copied} images_without_prompt={skipped} yaml_leaves={leaf_total}")
|
||||
total_copied += copied
|
||||
total_skipped += skipped
|
||||
|
||||
print(f"\nDone. {len(categories)} categories, {total_copied} images copied, {total_skipped} skipped (no matching prompt).")
|
||||
print(f"Destination: {dest}")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
+204
-30
@@ -2939,6 +2939,21 @@ function _isTextEncoderNode(ct) { return ct === "CLIPTextEncode" || ct.includes(
|
||||
function _isSamplerNode(ct) { return ct === "KSampler" || ct === "KSamplerAdvanced" || ct.includes("KSampler") || ct.includes("Sampler"); }
|
||||
function _isPromptStylerNode(ct) { return ct.includes("PromptStyler"); }
|
||||
|
||||
// CLIPTextEncodeEditPlus (model-and-prompt-from-metadata) の encode() と同じ結合ルール。
|
||||
// RAW: text1のみ。EDIT: text_editのみ。front/back: text2(未接続ならtext_edit)をtext1の前/後に結合。
|
||||
function _resolveEditPlusText(mode, textEdit, text1, text2) {
|
||||
const t1 = typeof text1 === "string" ? text1 : "";
|
||||
const edit = typeof textEdit === "string" ? textEdit : "";
|
||||
const insert = typeof text2 === "string" && text2 !== "" ? text2 : edit;
|
||||
switch (mode) {
|
||||
case "RAW": return t1;
|
||||
case "EDIT": return edit;
|
||||
case "front": return t1 ? `${insert}, ${t1}` : insert;
|
||||
case "back": return t1 ? `${t1}, ${insert}` : insert;
|
||||
default: return t1 || edit;
|
||||
}
|
||||
}
|
||||
|
||||
// LiteGraph形式: リンクを辿ってテキストを解決(ComfySwitchNode等の中継ノードにも対応)
|
||||
function _resolveLinkedTextInNodeSet(nodeMap, linkOrigin, linkSlot, srcId, slot, depth = 0) {
|
||||
if (depth > 6) return null;
|
||||
@@ -2963,8 +2978,10 @@ function _resolveLinkedTextInNodeSet(nodeMap, linkOrigin, linkSlot, srcId, slot,
|
||||
}
|
||||
const v = srcNode.widgets_values?.[slot] ?? srcNode.widgets_values?.[0];
|
||||
if (v && typeof v === "string") return v;
|
||||
// "source" = PreviewAny(値タップ中継), "string_a" = StringConcatenate(LoRAトリガーワード
|
||||
// 連結等)— Krea-2のプロンプト強化配線で使われる中継ノード
|
||||
if (Array.isArray(srcNode.inputs)) {
|
||||
const nextInput = srcNode.inputs.find(i => ["text", "value", "prompt", "string"].includes(i.name));
|
||||
const nextInput = srcNode.inputs.find(i => ["text", "value", "prompt", "string", "source", "string_a"].includes(i.name));
|
||||
if (nextInput?.link != null) {
|
||||
const originId = linkOrigin.get(nextInput.link);
|
||||
const originSlot = linkSlot.get(nextInput.link) ?? 0;
|
||||
@@ -2986,7 +3003,22 @@ function _extractPromptsFromNodeSet(nodes, links) {
|
||||
}
|
||||
const textMap = new Map();
|
||||
for (const n of nodes) {
|
||||
if (!_isTextEncoderNode(n.type ?? "")) continue;
|
||||
const type = n.type ?? "";
|
||||
if (type === "CLIPTextEncodeEditPlus") {
|
||||
const resolveNamedInput = (name) => {
|
||||
if (!Array.isArray(n.inputs)) return null;
|
||||
const inp = n.inputs.find(i => i.name === name);
|
||||
if (inp?.link == null) return null;
|
||||
const originId = linkOrigin.get(inp.link);
|
||||
const originSlot = linkSlot.get(inp.link) ?? 0;
|
||||
if (originId == null) return null;
|
||||
return _resolveLinkedTextInNodeSet(nodeMap, linkOrigin, linkSlot, originId, originSlot);
|
||||
};
|
||||
const combined = _resolveEditPlusText(n.widgets_values?.[1], n.widgets_values?.[0], resolveNamedInput("text1"), resolveNamedInput("text2"));
|
||||
if (combined) textMap.set(n.id, combined);
|
||||
continue;
|
||||
}
|
||||
if (!_isTextEncoderNode(type)) continue;
|
||||
const text = n.widgets_values?.[0];
|
||||
if (text && typeof text === "string") { textMap.set(n.id, text); }
|
||||
else if (Array.isArray(n.inputs)) {
|
||||
@@ -3107,7 +3139,8 @@ function _resolveLinkedText(wf, srcId, slot, depth = 0) {
|
||||
}
|
||||
return null;
|
||||
}
|
||||
const keys = slot === 0 ? ["text_positive", "text", "text_g", "prompt", "value"] : ["text_negative", "text_l"];
|
||||
// "source" = PreviewAny の値タップ中継、"string_a" = StringConcatenate の主オペランド
|
||||
const keys = slot === 0 ? ["text_positive", "text", "text_g", "prompt", "value", "source", "string_a"] : ["text_negative", "text_l", "source", "string_a"];
|
||||
for (const k of keys) {
|
||||
const v = src.inputs?.[k];
|
||||
if (typeof v === "string" && v) return v;
|
||||
@@ -3125,7 +3158,20 @@ function _extractPromptsAPI(wf) {
|
||||
}
|
||||
const textMap = new Map();
|
||||
for (const [id, n] of Object.entries(wf)) {
|
||||
if (!n || !_isTextEncoderNode(n.class_type ?? "")) continue;
|
||||
if (!n) continue;
|
||||
const ct = n.class_type ?? "";
|
||||
if (ct === "CLIPTextEncodeEditPlus") {
|
||||
const resolveField = (key) => {
|
||||
const v = n.inputs?.[key];
|
||||
if (typeof v === "string") return v;
|
||||
if (Array.isArray(v)) return _resolveLinkedText(wf, v[0], v[1] ?? 0);
|
||||
return null;
|
||||
};
|
||||
const combined = _resolveEditPlusText(n.inputs?.mode, n.inputs?.text_edit, resolveField("text1"), resolveField("text2"));
|
||||
if (combined) textMap.set(id, combined);
|
||||
continue;
|
||||
}
|
||||
if (!_isTextEncoderNode(ct)) continue;
|
||||
// "prompt" — TextEncodeQwenImageEdit(Plus)/TextEncodeBooguEdit and similar Image Edit
|
||||
// model text encoders use this key instead of "text"/"text_g".
|
||||
const raw = n.inputs?.text ?? n.inputs?.text_g ?? n.inputs?.prompt ?? null;
|
||||
@@ -3576,11 +3622,38 @@ const AI_BACKEND_DEFAULT_URLS = {
|
||||
ollama: "http://localhost:11434",
|
||||
lmstudio: "http://localhost:1234",
|
||||
lemonade: "http://localhost:13305",
|
||||
unsloth: "http://localhost:8888",
|
||||
};
|
||||
function getAiBackendDefaultUrl(backend) {
|
||||
return AI_BACKEND_DEFAULT_URLS[backend] || AI_BACKEND_DEFAULT_URLS.ollama;
|
||||
}
|
||||
|
||||
// Server relays the request, attaching the Unsloth API key from .env so it
|
||||
// never reaches the frontend — see py/routes/unsloth_routes.py.
|
||||
async function aiUnslothProxy(baseUrl, path, method, payload) {
|
||||
const r = await fetch("/api/wfm/unsloth/proxy", {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify({ baseUrl, path, method, payload }),
|
||||
});
|
||||
const data = await r.json().catch(() => ({}));
|
||||
if (!r.ok) throw new Error(data.message || `HTTP ${r.status}`);
|
||||
return data;
|
||||
}
|
||||
|
||||
// Unlike Ollama/LM Studio/Lemonade (which inline reasoning as <think> tags
|
||||
// inside content), Unsloth's OpenAI-compatible API returns it in a separate
|
||||
// `reasoning_content` field. Fold it back into a <think> block so the
|
||||
// existing Thinking-mode show/strip logic (_aiApplyGenOptions/aiStripThinkingTags)
|
||||
// still applies uniformly. Without this, a low max_tokens can make the model
|
||||
// spend its whole budget reasoning and return an empty `content` with no
|
||||
// visible explanation.
|
||||
function _aiUnslothContent(message) {
|
||||
const reasoning = message?.reasoning_content;
|
||||
const content = message?.content || "";
|
||||
return reasoning ? `<think>${reasoning}</think>${content}` : content;
|
||||
}
|
||||
|
||||
function isValidAiUrl(url) {
|
||||
try {
|
||||
const u = new URL(url);
|
||||
@@ -3599,22 +3672,51 @@ function saveAiCfg(patch) {
|
||||
return d;
|
||||
}
|
||||
|
||||
async function aiCallLLM(url, backend, model, prompt) {
|
||||
// Ollamaは `think` (bool) と `options.num_predict` で制御できるが、
|
||||
// LM Studio/LemonadeはOpenAI互換APIのため max_tokens のみ標準対応。
|
||||
// thinking mode切替は非対応バックエンド/モデル向けに、出力からの
|
||||
// <think>タグ除去でも担保する(aiStripThinkingTagsを参照)。
|
||||
function _aiApplyGenOptions(body, backend, settings) {
|
||||
const maxTokens = parseInt(settings?.maxTokens, 10);
|
||||
if (backend === "ollama") {
|
||||
body.think = !!settings?.thinkingMode;
|
||||
if (maxTokens > 0) body.options = { ...(body.options || {}), num_predict: maxTokens };
|
||||
} else if (maxTokens > 0) {
|
||||
body.max_tokens = maxTokens;
|
||||
}
|
||||
return body;
|
||||
}
|
||||
|
||||
function aiStripThinkingTags(text) {
|
||||
return (text || "")
|
||||
.replace(/<think>[\s\S]*?<\/think>/gi, "")
|
||||
.replace(/<thinking>[\s\S]*?<\/thinking>/gi, "")
|
||||
.trim();
|
||||
}
|
||||
|
||||
async function aiCallLLM(url, backend, model, prompt, settings = {}) {
|
||||
if (backend === "ollama") {
|
||||
const r = await fetch(`${url}/api/generate`, {
|
||||
method: "POST", headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify({ model, prompt, stream: false }),
|
||||
body: JSON.stringify(_aiApplyGenOptions({ model, prompt, stream: false }, backend, settings)),
|
||||
});
|
||||
if (!r.ok) throw new Error(`HTTP ${r.status}`);
|
||||
return (await r.json()).response || "";
|
||||
const text = (await r.json()).response || "";
|
||||
return settings.thinkingMode ? text : aiStripThinkingTags(text);
|
||||
} else if (backend === "unsloth") {
|
||||
const body = _aiApplyGenOptions({ model, messages: [{ role: "user", content: prompt }], stream: false }, backend, settings);
|
||||
const d = await aiUnslothProxy(url, "/v1/chat/completions", "POST", body);
|
||||
const text = _aiUnslothContent(d.choices?.[0]?.message);
|
||||
return settings.thinkingMode ? text : aiStripThinkingTags(text);
|
||||
} else {
|
||||
const r = await fetch(`${url}/v1/chat/completions`, {
|
||||
method: "POST", headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify({ model, messages: [{ role: "user", content: prompt }], stream: false }),
|
||||
body: JSON.stringify(_aiApplyGenOptions({ model, messages: [{ role: "user", content: prompt }], stream: false }, backend, settings)),
|
||||
});
|
||||
if (!r.ok) throw new Error(`HTTP ${r.status}`);
|
||||
const d = await r.json();
|
||||
return d.choices?.[0]?.message?.content || "";
|
||||
const text = d.choices?.[0]?.message?.content || "";
|
||||
return settings.thinkingMode ? text : aiStripThinkingTags(text);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -3630,54 +3732,99 @@ function aiFileToBase64(file) {
|
||||
});
|
||||
}
|
||||
|
||||
async function aiCallVLM(url, backend, model, prompt, base64Image, mimeType) {
|
||||
async function aiCallVLM(url, backend, model, prompt, base64Image, mimeType, settings = {}) {
|
||||
if (backend === "ollama") {
|
||||
const r = await fetch(`${url}/api/generate`, {
|
||||
method: "POST", headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify({ model, prompt, images: [base64Image], stream: false }),
|
||||
body: JSON.stringify(_aiApplyGenOptions({ model, prompt, images: [base64Image], stream: false }, backend, settings)),
|
||||
});
|
||||
if (!r.ok) throw new Error(`HTTP ${r.status}`);
|
||||
return (await r.json()).response || "";
|
||||
const text = (await r.json()).response || "";
|
||||
return settings.thinkingMode ? text : aiStripThinkingTags(text);
|
||||
} else if (backend === "unsloth") {
|
||||
const body = _aiApplyGenOptions({
|
||||
model,
|
||||
messages: [{ role: "user", content: [
|
||||
{ type: "text", text: prompt },
|
||||
{ type: "image_url", image_url: { url: `data:${mimeType};base64,${base64Image}` } },
|
||||
]}],
|
||||
stream: false,
|
||||
}, backend, settings);
|
||||
const d = await aiUnslothProxy(url, "/v1/chat/completions", "POST", body);
|
||||
const text = _aiUnslothContent(d.choices?.[0]?.message);
|
||||
return settings.thinkingMode ? text : aiStripThinkingTags(text);
|
||||
} else {
|
||||
const r = await fetch(`${url}/v1/chat/completions`, {
|
||||
method: "POST", headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify({
|
||||
body: JSON.stringify(_aiApplyGenOptions({
|
||||
model,
|
||||
messages: [{ role: "user", content: [
|
||||
{ type: "text", text: prompt },
|
||||
{ type: "image_url", image_url: { url: `data:${mimeType};base64,${base64Image}` } },
|
||||
]}],
|
||||
stream: false,
|
||||
}),
|
||||
}, backend, settings)),
|
||||
});
|
||||
if (!r.ok) throw new Error(`HTTP ${r.status}`);
|
||||
return (await r.json()).choices?.[0]?.message?.content || "";
|
||||
const text = (await r.json()).choices?.[0]?.message?.content || "";
|
||||
return settings.thinkingMode ? text : aiStripThinkingTags(text);
|
||||
}
|
||||
}
|
||||
|
||||
async function aiCallChat(url, backend, model, messages) {
|
||||
async function aiCallChat(url, backend, model, messages, settings = {}) {
|
||||
if (backend === "ollama") {
|
||||
const r = await fetch(`${url}/api/chat`, {
|
||||
method: "POST", headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify({ model, messages, stream: false }),
|
||||
body: JSON.stringify(_aiApplyGenOptions({ model, messages, stream: false }, backend, settings)),
|
||||
});
|
||||
if (!r.ok) throw new Error(`HTTP ${r.status}`);
|
||||
return (await r.json()).message?.content || "";
|
||||
const text = (await r.json()).message?.content || "";
|
||||
return settings.thinkingMode ? text : aiStripThinkingTags(text);
|
||||
} else if (backend === "unsloth") {
|
||||
const body = _aiApplyGenOptions({ model, messages, stream: false }, backend, settings);
|
||||
const d = await aiUnslothProxy(url, "/v1/chat/completions", "POST", body);
|
||||
const text = _aiUnslothContent(d.choices?.[0]?.message);
|
||||
return settings.thinkingMode ? text : aiStripThinkingTags(text);
|
||||
} else {
|
||||
const r = await fetch(`${url}/v1/chat/completions`, {
|
||||
method: "POST", headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify({ model, messages, stream: false }),
|
||||
body: JSON.stringify(_aiApplyGenOptions({ model, messages, stream: false }, backend, settings)),
|
||||
});
|
||||
if (!r.ok) throw new Error(`HTTP ${r.status}`);
|
||||
return (await r.json()).choices?.[0]?.message?.content || "";
|
||||
const text = (await r.json()).choices?.[0]?.message?.content || "";
|
||||
return settings.thinkingMode ? text : aiStripThinkingTags(text);
|
||||
}
|
||||
}
|
||||
|
||||
// Strips common LLM wrapping/preamble artifacts that survive despite the system prompt.
|
||||
function cleanAiTranslationOutput(raw) {
|
||||
let s = (raw || "").trim();
|
||||
s = s.replace(/^(sure[,.]?\s*)?(here('|)s|here is)?\s*(the\s+)?translation\s*:?\s*/i, "");
|
||||
s = s.replace(/^(翻訳|译文|翻译)\s*[::]\s*/, "");
|
||||
if (s.length >= 2) {
|
||||
const first = s[0], last = s[s.length - 1];
|
||||
const pairs = { '"': '"', "'": "'", "“": "”", "「": "」" };
|
||||
if (pairs[first] === last) s = s.slice(1, -1).trim();
|
||||
}
|
||||
return s;
|
||||
}
|
||||
|
||||
// Heuristic: if the cleaned output is (near-)identical to the input, the
|
||||
// model most likely echoed the source instead of translating it.
|
||||
function aiLooksUntranslated(input, output) {
|
||||
const normalize = (s) => s.trim().toLowerCase().replace(/[\s.,!?"'。、!?「」]/g, "");
|
||||
const a = normalize(input), b = normalize(output);
|
||||
return a.length > 0 && a === b;
|
||||
}
|
||||
|
||||
async function aiFetchModels(url, backend) {
|
||||
if (backend === "ollama") {
|
||||
const r = await fetch(`${url}/api/tags`);
|
||||
if (!r.ok) throw new Error(`HTTP ${r.status}`);
|
||||
return ((await r.json()).models || []).map(m => m.name);
|
||||
} else if (backend === "unsloth") {
|
||||
const d = await aiUnslothProxy(url, "/v1/models", "GET");
|
||||
return (d.data || []).map(m => m.id);
|
||||
} else {
|
||||
const r = await fetch(`${url}/v1/models`);
|
||||
if (!r.ok) throw new Error(`HTTP ${r.status}`);
|
||||
@@ -3829,6 +3976,7 @@ const renderAiTab = (container) => {
|
||||
<label class="wfm-nlp-ai-radio"><input type="radio" name="wfm-nlp-ai-backend" value="ollama"> Ollama</label>
|
||||
<label class="wfm-nlp-ai-radio"><input type="radio" name="wfm-nlp-ai-backend" value="lmstudio"> LM Studio</label>
|
||||
<label class="wfm-nlp-ai-radio"><input type="radio" name="wfm-nlp-ai-backend" value="lemonade"> Lemonade</label>
|
||||
<label class="wfm-nlp-ai-radio"><input type="radio" name="wfm-nlp-ai-backend" value="unsloth"> Unsloth</label>
|
||||
</div>
|
||||
</div>
|
||||
<div class="wfm-nlp-ai-sec">
|
||||
@@ -3848,6 +3996,18 @@ const renderAiTab = (container) => {
|
||||
<button id="wfm-nlp-ai-model-refresh" class="wfm-nlp-ai-btn">↻</button>
|
||||
</div>
|
||||
</div>
|
||||
<div class="wfm-nlp-ai-sec">
|
||||
<div class="wfm-nlp-ai-sec-title">Generation</div>
|
||||
<div class="wfm-nlp-ai-row">
|
||||
<label class="wfm-nlp-ai-lbl" style="display:flex;align-items:center;gap:6px;cursor:pointer;">
|
||||
<input type="checkbox" id="wfm-nlp-ai-thinking-mode"> Thinking mode
|
||||
</label>
|
||||
</div>
|
||||
<div class="wfm-nlp-ai-row">
|
||||
<span class="wfm-nlp-ai-lbl">Max tokens</span>
|
||||
<input type="number" id="wfm-nlp-ai-max-tokens" class="wfm-nlp-ai-input" min="0" step="1" placeholder="0 = unlimited" style="flex:1;">
|
||||
</div>
|
||||
</div>
|
||||
<div class="wfm-nlp-ai-sec">
|
||||
<div class="wfm-nlp-ai-sec-title">Free language</div>
|
||||
<div class="wfm-nlp-ai-row">
|
||||
@@ -3901,6 +4061,11 @@ const setupAiHandlers = (container) => {
|
||||
if (freeSrcInput && cfg.freeSrcLang) freeSrcInput.value = cfg.freeSrcLang;
|
||||
if (freeDstInput && cfg.freeDstLang) freeDstInput.value = cfg.freeDstLang;
|
||||
|
||||
const thinkingModeInput = container.querySelector("#wfm-nlp-ai-thinking-mode");
|
||||
if (thinkingModeInput) thinkingModeInput.checked = !!cfg.thinkingMode;
|
||||
const maxTokensInput = container.querySelector("#wfm-nlp-ai-max-tokens");
|
||||
if (maxTokensInput && cfg.maxTokens) maxTokensInput.value = cfg.maxTokens;
|
||||
|
||||
const srcSel = container.querySelector("#wfm-nlp-ai-src");
|
||||
const dstSel = container.querySelector("#wfm-nlp-ai-dst");
|
||||
if (srcSel && cfg.srcLang) srcSel.value = cfg.srcLang;
|
||||
@@ -3932,10 +4097,13 @@ const setupAiHandlers = (container) => {
|
||||
|
||||
const srcLang = srcSel?.value || "ja";
|
||||
const dstLang = dstSel?.value || "en";
|
||||
const srcName = srcLang === "free" ? (c.freeSrcLang || "Auto") : AI_LANG_NAMES[srcLang];
|
||||
const dstName = dstLang === "free" ? (c.freeDstLang || "English") : AI_LANG_NAMES[dstLang];
|
||||
const fromPart = srcLang === "free" ? "" : `from ${srcName} `;
|
||||
const prompt = `Translate the following text ${fromPart}to ${dstName}. Output only the translated text, nothing else.\n\n${text}`;
|
||||
const srcName = srcLang === "free" ? (c.freeSrcLang || "").trim() : AI_LANG_NAMES[srcLang];
|
||||
const dstName = dstLang === "free" ? (c.freeDstLang || "English").trim() || "English" : AI_LANG_NAMES[dstLang];
|
||||
const fromPart = srcName ? ` from ${srcName}` : "";
|
||||
const systemPrompt = `You are a professional translator. Translate the text the user sends${fromPart} into ${dstName}. `
|
||||
+ `Reply with ONLY the translated text and nothing else: no explanations, no notes, no preamble like "Here is the translation:", `
|
||||
+ `no surrounding quotes, and do not repeat or echo the original text.`;
|
||||
const messages = [{ role: "system", content: systemPrompt }, { role: "user", content: text }];
|
||||
|
||||
const transBtn = container.querySelector("#wfm-nlp-ai-trans-btn");
|
||||
const statusEl = container.querySelector("#wfm-nlp-ai-status");
|
||||
@@ -3946,10 +4114,14 @@ const setupAiHandlers = (container) => {
|
||||
outputEl.value = "";
|
||||
|
||||
try {
|
||||
const result = await aiCallLLM(url, backend, model, prompt);
|
||||
outputEl.value = result.trim();
|
||||
const result = await aiCallChat(url, backend, model, messages, c);
|
||||
const cleaned = cleanAiTranslationOutput(result);
|
||||
outputEl.value = cleaned;
|
||||
statusEl.textContent = "完了";
|
||||
statusEl.className = "wfm-nlp-ai-status wfm-nlp-ai-ok";
|
||||
if (srcLang !== dstLang && aiLooksUntranslated(text, cleaned)) {
|
||||
showToast("モデルが原文をそのまま返しました。翻訳されていない可能性があります。別のモデルをお試しください。", "error");
|
||||
}
|
||||
} catch (err) {
|
||||
statusEl.textContent = `エラー: ${err.message}`;
|
||||
statusEl.className = "wfm-nlp-ai-status wfm-nlp-ai-err";
|
||||
@@ -4023,11 +4195,13 @@ const setupAiHandlers = (container) => {
|
||||
const model = container.querySelector("#wfm-nlp-ai-model")?.value || "";
|
||||
const freeSrcLang = container.querySelector("#wfm-nlp-ai-free-src")?.value?.trim() || "";
|
||||
const freeDstLang = container.querySelector("#wfm-nlp-ai-free-dst")?.value?.trim() || "";
|
||||
const thinkingMode = !!container.querySelector("#wfm-nlp-ai-thinking-mode")?.checked;
|
||||
const maxTokens = Math.max(0, parseInt(container.querySelector("#wfm-nlp-ai-max-tokens")?.value, 10) || 0);
|
||||
if (url && !isValidAiUrl(url)) {
|
||||
showToast("URLは http:// または https:// で始まる必要があります", "error");
|
||||
return;
|
||||
}
|
||||
saveAiCfg({ backend, backendUrl: url, model, freeSrcLang, freeDstLang });
|
||||
saveAiCfg({ backend, backendUrl: url, model, freeSrcLang, freeDstLang, thinkingMode, maxTokens });
|
||||
showToast("Settings saved", "success");
|
||||
});
|
||||
|
||||
@@ -4073,7 +4247,7 @@ const setupAiHandlers = (container) => {
|
||||
const messagesToSend = skillPrompt
|
||||
? [{ role: "system", content: skillPrompt }, ...chatHistory]
|
||||
: chatHistory;
|
||||
const reply = await aiCallChat(url, backend, model, messagesToSend);
|
||||
const reply = await aiCallChat(url, backend, model, messagesToSend, c);
|
||||
chatHistory.push({ role: "assistant", content: reply });
|
||||
appendChatBubble("assistant", reply);
|
||||
chatStatusEl.textContent = "";
|
||||
@@ -4305,7 +4479,7 @@ const setupAiHandlers = (container) => {
|
||||
|
||||
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);
|
||||
const result = await aiCallLLM(url, backend, model, prompt, c);
|
||||
vlmResult.value = result.trim()
|
||||
.split("\n")
|
||||
.map(l => l.replace(/\*\*/g, "").replace(/^\*\s*/, "").replace(/^\d+\.\s*/, "").trim())
|
||||
@@ -4330,7 +4504,7 @@ const setupAiHandlers = (container) => {
|
||||
vlmResult.value = "";
|
||||
|
||||
try {
|
||||
const result = await aiCallVLM(url, backend, model, VLM_PROMPTS[task], vlmImage.base64, vlmImage.mimeType);
|
||||
const result = await aiCallVLM(url, backend, model, VLM_PROMPTS[task], vlmImage.base64, vlmImage.mimeType, c);
|
||||
vlmResult.value = result.trim();
|
||||
vlmStatus.textContent = "完了";
|
||||
vlmStatus.className = "wfm-nlp-ai-status wfm-nlp-ai-ok";
|
||||
|
||||
Reference in New Issue
Block a user