Compare commits

...
21 Commits
Author SHA1 Message Date
ketle-manandClaude Sonnet 5.5 b81aa84898 release: v0.7.12 - restrict client-supplied backend URLs (SSRF)
Ollama chat, Tagger VLM, Eagle and the Unsloth relay accepted the target URL
from the request. Add py/services/url_guard.py: loopback or operator-listed
WFS_ALLOWED_BACKEND_HOSTS only, http(s) only, no credentials, no redirects.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-04 06:49:16 +09:00
ketle-manandClaude Sonnet 5.5 4179511e1b fix(security): restrict preview downloads to CivitAI hosts, fix Host-header based origin
- download_image: https + CivitAI hosts only (also validates redirects, 50MB cap);
  sidecar-supplied image URLs could trigger SSRF / file:// reads
- Lora Manager bridge: connect to 127.0.0.1 with the real listening port instead
  of the request Host header
- safeHttpUrl for sample/fallback image URLs; DEVLOG

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-02 22:32:58 +09:00
ketle-manandClaude Sonnet 5.5 cb9f5eecc4 release: v0.7.11 - sanitize CivitAI description HTML (stored XSS), harden sidecar import
- util.js: allowlist sanitizeHtml() / safeHttpUrl() (absolute http(s) only);
  applied to the Models detail panel description, model URL and sample images
- cm-info/metadata sidecar import: numeric IDs only, type checks, 2MB size cap
- DEVLOG, README badge, version bump

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-02 22:26:31 +09:00
ketle-manandClaude Sonnet 5.5 3262e843cf release: v0.7.10 - Selector event loop switch, no-hash CivitAI batch, models folder, preview 404 fix
- Windows: optional Selector asyncio loop (settings toggle / WFS_SELECTOR_LOOP=1)
  to avoid ComfyUI freezing in closesocket on the Proactor loop
- Models: skip image requests for models without previews (preview-keys API),
  show previews of .disabled models, add extra Models folder setting
- CivitAI: batch fetch no longer hashes; reads .cm-info.json (Stability Matrix);
  unhashed models shown in red and hashed individually; drop file path display
- Help/i18n for the new settings; DEVLOG, README badge, version bump

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-02 21:26:31 +09:00
ketle-manandClaude Sonnet 5.5 68836b0166 feat: reuse Lora Manager sha256 to skip hashing in CivitAI batch fetch
Query /api/lm/{loras,checkpoints,embeddings}/list for already-computed
sha256 and use it (size-matched only) for models without a stored hash.
Falls back to the existing hashing path if Lora Manager is unavailable.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-02 12:58:38 +09:00
ketle-manandClaude Sonnet 5.5 7b3d1f0bc3 feat: add Models folder setting and cancel CivitAI batch on disconnect
- Settings: new "Models Folder" (models_dir) to add extra model roots such as
  Stability Matrix's Models; subfolders (StableDiffusion/Lora/VAE/...) are
  merged into the Models tab list and folder resolution
- CivitAI batch: stop hashing/fetching when the client disconnects, keeping
  already computed hashes
- Lower load: hash workers 3->2, read chunk 1MB->512KB, preview download
  workers 4->2

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-02 10:14:21 +09:00
ketle-manandClaude Sonnet 5.5 255fdd3c92 release: v0.7.9 - CivitAI auto badges, faster batch fetch, folder link support
- Models: auto-create badges from CivitAI base model (keep existing badges,
  optional color overwrite, optional skip for models that already have badges)
- CivitAI batch fetch: reuse saved hashes (size/mtime checked), import from
  .metadata.json sidecars, parallel hashing with incremental saves, parallel
  preview download off the event loop, "Skip not found" option
- Folder symlink/junction support: loop-safe scan, allow moving into linked folders
- Help (3 languages) and DEVLOG updated

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-02 00:25:35 +09:00
ketle-manandClaude Sonnet 5.5 787bf01381 release: v0.7.8 - Video Edit multi-track (overlay/text/audio), timeline text, sounds, backup fix
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-01 13:44:32 +09:00
ketle-manandClaude Sonnet 5.5 ca5649b926 docs: backup help/README mention sounds and overlay clips media
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-01 13:38:46 +09:00
ketle-manandClaude Sonnet 5.5 93d13e1fd0 fix: full backup now includes media used by Video Edit timeline sounds and overlay clips
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-01 13:38:24 +09:00
ketle-manandClaude Sonnet 5.5 94840dade5 docs: mention Asset 'Add as overlay' in Video help
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-01 13:31:54 +09:00
ketle-manandClaude Sonnet 5.5 9a98e3e50a feat: add 'Add as overlay (PinP)' button to the Video Asset detail panel
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-01 12:46:14 +09:00
ketle-manandClaude Sonnet 5.5 f20e13e093 fix: overlay/sound file pickers use a transparent native input over the button
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-01 12:39:49 +09:00
ketle-manandClaude Sonnet 5.5 98645407d9 feat: Video Edit tool menu follows the track view (video/text/overlay/audio), export stays fixed
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-01 12:30:01 +09:00
ketle-manandClaude Sonnet 5.5 e5e2daf523 feat: cascade default position of newly added overlay clips
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-01 12:15:31 +09:00
ketle-manandClaude Sonnet 5.5 2413dd2d77 feat: overlay (PinP) video/image track in Video Edit, composited on export
Overlay clips are placed/scaled/faded per clip, drawn over the main video in the
same PyAV pass that burns in text. Includes track view, panel, preview boxes,
undo/redo and project save/load.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-01 12:09:14 +09:00
ketle-manandClaude Sonnet 5.5 e197356c6b docs: update Video Edit help for track views, timeline texts and sounds
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-01 12:03:41 +09:00
ketle-manandClaude Sonnet 5.5 1d7f5721ad feat: timeline sounds on the Video Edit audio track (placeable, trimmable extra audio clips)
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-01 11:43:49 +09:00
ketle-manandClaude Sonnet 5.5 74d1a5579b refactor: store Video Edit text overlays on the timeline (absolute time) instead of per clip
Texts can now be dragged across clip boundaries; legacy projects with
clip-relative texts are migrated on load.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-01 11:40:33 +09:00
ketle-manandClaude Sonnet 5.5 60e94b0ab2 feat: drag/resize text bands on the Video Edit text track
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-01 11:34:49 +09:00
ketle-manandClaude Sonnet 5.5 81d7d65af6 feat: add Video/Text/Audio track view switch to Video Edit timeline
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-01 11:34:31 +09:00
33 changed files with 2695 additions and 341 deletions
+5
View File
@@ -2,6 +2,11 @@
Condensed version-by-version index of DEVLOG.md (each line: version + one-line summary of what changed and why). Full rationale, code details, and "How to apply" lessons live in the excluded DEVLOG.md itself; this index exists so graphify can extract a queryable semantic node per release without feeding the full log to the local Ollama model. Regenerate with `python tools/generate_doc_index.py devlog` whenever DEVLOG.md changes.
- **v0.7.12(2026-10-04)** — セキュリティ: バックエンド接続先をブラウザから任意指定できた問題(SSRF)を修正
- **v0.7.11(2026-10-02)** — セキュリティ: CivitAI情報の説明文のHTML無害化(保存型XSS対策)
- **v0.7.10(2026-10-02)** — Windows: ComfyUIが固まる問題の原因特定と対策(Selectorイベントループ)
- **v0.7.9(2026-10-02)** — Models: CivitAIベースモデルからの自動バッジ作成
- **v0.7.8(2026-10-01)** — Video Edit: マルチトラック化(ビデオ/オーバーレイ/テキスト/オーディオ)
- **v0.7.7(2026-09-30)** — 意思決定モデル: Ollama 0.35+ バックエンド追加
- **v0.7.6(2026-09-30)** — Settings: 意思決定モデル (Laya) の専用設定
- **v0.7.5(2026-09-30)** — Ming Image ワークフロー対応(GenerateUI / Gallery・Metadata / サイドパネルIタブ)
+129
View File
@@ -2,6 +2,135 @@
---
## v0.7.12(2026-10-04)
### セキュリティ: バックエンド接続先をブラウザから任意指定できた問題(SSRF)を修正
ComfyUI-Manager登録PR(LiveChatStream、Comfy-Org/ComfyUI-Manager#3340)のレビューで指摘された「リクエストから接続先URLを受け取り、サーバーが接続する」問題が、WFSにも同じ構造で存在していたため修正。
- 対象: `POST /api/wfm/ollama/chat`(bodyの `url`。従来は**検証なし**で、任意ホスト・クラウドメタデータ・`file://` に接続できた)、Tagger VLM(`/wfm/tagger/vlm/models`・`vlm/predict`・`batch/start` の `api_url`。Unslothのみ制限されていた)、Eagle(`/api/wfm/eagle/add`・`/test` の `eagleUrl`)、Unslothプロキシ(`baseUrl`)。
- 新規 `py/services/url_guard.py` に共通化。許可は **loopback(localhost / 127.0.0.1 / ::1、ポート自由)** と、運用者が環境変数 `WFS_ALLOWED_BACKEND_HOSTS`(`host` または `host:port` のカンマ区切り)で指定したホストのみ。`http(s)` 以外(`file://` 等)、URL内の認証情報、`localhost.evil.com` のような偽装ホストは拒否。**リダイレクトは追従しない**(302は接続せずエラー)。
- **挙動変更**: LAN上の別マシンのOllama/Eagle等を使っている場合は `WFS_ALLOWED_BACKEND_HOSTS` の設定が必要(拒否時のエラーメッセージに案内を表示)。
- 実機(ComfyUI_5、ポート8189)で、メタデータIP・`file://`・公開IPの拒否、loopbackのOllama chat/Tagger一覧/Eagle test/Unsloth Decision APIの正常動作を確認。
- 注意: ComfyUIを `--listen` で公開すると、到達できる相手は引き続きこれらのルートを使える(接続先を変えられないだけ)。信頼できるネットワークでのみ使うこと。
---
## v0.7.11(2026-10-02)
### セキュリティ: CivitAI情報の説明文のHTML無害化(保存型XSS対策)
- Models詳細パネルのCivitAIタブは、説明文(`description`)をエスケープせずHTMLとして挿入していた。CivitAI APIの応答は従来から同じ扱いだったが、v0.7.10で追加した `.cm-info.json`(Stability Matrix)取り込みにより、**ローカルのサイドカーファイルからも同じ経路で入る**ようになった。細工されたファイルがモデルと一緒に配布された場合、詳細パネルを開いただけでスクリプトが実行され得る(ComfyUIと同一オリジンのため、ComfyUIのAPIを操作できる)。
- `static/js/util.js` に許可リスト方式の `sanitizeHtml()` と `safeHttpUrl()` を追加し、説明文・モデルURL・サンプル画像URLに適用。`script/style/iframe/svg/form` 等の要素、`on*` 属性、`style` 属性、`javascript:`/`data:` URL、**相対URL**(ComfyUI自身のURLへリクエストを送らせる経路)を除去する。許可するのは段落・見出し・リスト・強調・表・`code`・`a`/`img`(絶対http(s) URLのみ)など。
- Playwright(実ブラウザ)で攻撃文字列16種を検証し、スクリプトが一度も実行されないことを確認。
### セキュリティ: サイドカー経由のSSRF/ローカルファイル読み取りと、Hostヘッダ依存の接続先
取り込み経路の再点検で見つかった2件を修正。
- **プレビュー画像のダウンロード(`download_image`)のURLが無検証だった**。URLは `.metadata.json`(Lora Manager形式のローカルサイドカー)の `civitai.images` から来るため、細工されたサイドカーがあると、サーバーが任意のURLへ接続する(SSRF)。`file://` を指定すればローカルファイルを読んでプレビュー画像として保存でき、プレビューAPI経由で取り出せた。**https かつ CivitAI系ホスト(`civitai.com`/`civitai.red`/`civitai.green` とそのサブドメイン)のみ許可**し、リダイレクト先も同じ条件で検証、サイズ上限50MBを設定。正規のCivitAI画像の取得は実環境で確認済み。
- **Lora Manager連携(`lora_manager_bridge`)の接続先を、リクエストのHostヘッダから組み立てていた**。Hostの偽装(DNSリバインディング等)で任意のホストへ接続させられるため、**ループバック(`127.0.0.1`)+実際に待ち受けているポート**に固定。
- サンプル画像・フォールバック画像のURLにも `safeHttpUrl()`(絶対http(s)のみ)を適用。
### `.cm-info.json` / `.metadata.json` 取り込みの堅牢化
- `ModelId`/`VersionId` は正の整数のみ受け付ける(URLに文字列を埋め込まない)。不正なら情報は採用せず、sha256のみ利用。
- タグ・トリガーワードは文字列/数値のみ・件数上限あり。JSONのトップレベルがオブジェクトでない場合は無視。
- サイドカーJSONのサイズ上限を2MBに設定(巨大ファイルでメモリを使い切らない)。
---
## v0.7.10(2026-10-02)
### Windows: ComfyUIが固まる問題の原因特定と対策(Selectorイベントループ)
v0.7.9で「原因未特定」としていたComfyUIの無応答は、ほぼ素の環境(ComfyUI 0.34 / Workflow Studio 0.7.2〜0.7.9、ComfyUI Desktop・Stability Matrix両方)でも再現し、`/system_stats` すら応答しなかった。py-spy(`dump --native`)でメインスレッド(イベントループ)が `asyncio proactor _call_connection_lost → socket.close → closesocket → NtClose` で停止していることを確認。ハッシュ計算・モデルファイル・CivitAI取得・Windows更新(26H2を戻しても再現)・ComfyUI/WSL/Windows Firewall Controlのいずれも原因ではなかった。
- きっかけは「プレビュー画像の多い一覧を開き、続けて他の一覧へ切り替える」操作。ブラウザが読み込み中の画像リクエストを一斉に中止し、短時間に多数の接続が開閉する。
- **対策**: `prestartup_script.py` でWindowsのasyncioループをProactorからSelectorへ切り替えるスイッチを追加(既定オフ)。設定画面の「Windowsの安定性(イベントループ)」のチェック、または環境変数 `WFS_SELECTOR_LOOP=1` で有効化(ComfyUI再起動後に反映)。有効化すると同じ操作で再現しなくなった。
- トレードオフ: asyncioのサブプロセス機能が使えない/同時接続数の上限が約512。ComfyUI-Managerの閲覧・CivitAI取得は問題なし。
- 固まったプロセスは `taskkill` しても終了せずポートを握り続けるため、再起動が必要になる。固まったときは `py-spy dump --native --pid <PID>` でメインスレッドの位置を確認する。
### Models: プレビュー画像の404削減
- プレビューが無いモデルにも画像リクエストを出しており、一覧の切り替えごとに大量の404と接続の開閉が発生していた。
- 新API `GET /api/wfm/models/preview-keys?type=` がフォルダを1回走査して「プレビューを持つモデル」の一覧を返し、画面側は無いモデルへ画像リクエストを出さない(取得失敗時は従来動作)。サムネ変更・CivitAI取得でのプレビュー保存・一括取得後は一覧を更新。
- **無効化(`.disabled`)されたモデルのプレビューが表示されなかった問題を修正**(`find_preview_image` が `<名前>.disabled` を見ていなかった)。
### Models: モデルフォルダ設定(Stability Matrix対応)
- 設定に「モデルフォルダ」を追加。追加のモデルルート(例: Stability Matrixの `Models`、`;` 区切りで複数可)直下の `StableDiffusion/Lora/VAE/ControlNet/TextEncoders/DiffusionModels/Embeddings/HyperNetworks`(またはComfyUI名 `checkpoints/loras` …)をModelsタブの一覧とフォルダ解決に追加する。
- Modelsタブの一覧はComfyUIの `/object_info` 由来で追加フォルダを含まないため、`/api/wfm/models/files?extra_only=1` の結果を合流させている。
### CivitAI取得: ハッシュ計算を行わない運用へ
- 一括取得は**ハッシュ計算をしない**。保存済みsha256、`.metadata.json`(Lora Manager)、`.cm-info.json`(Stability Matrix)、Lora Managerの `/api/lm/{loras,checkpoints,embeddings}/list` のsha256から解決できる分だけを取得し、未確定のモデルは「ハッシュ未計算」として件数を表示する(大きなモデルを多数ハッシュするとディスクが飽和するため)。
- **`.cm-info.json` 取り込み**: `Hashes.SHA256` とCivitAI情報を読む。ファイルサイズが無いため `ImportedAt` より後にモデルが更新されていたら不採用。画像一覧を持たないので `source: "cm-info"` を付け、個別の取得/更新でAPIの完全な情報に置き換える。
- 詳細パネルのCivitAIタブで、ハッシュ未計算のモデルは赤字「未計算」を表示。取得/更新ボタンでハッシュ計算して取得する(ファイルサイズ/更新日時も保存)。
- クライアント切断(再読み込み・タブ遷移)で一括取得を中断し、計算済みのハッシュだけ保存して終了。ハッシュ計算を3→2並列、読み込み1MB→512KB、プレビュー保存4→2並列に抑制。
- 詳細パネルの「ファイルパス」表示を削除。
### ヘルプ・i18n
- 設定のヘルプに「モデルフォルダ」「Windowsの安定性」を追加(英日中)。
---
## v0.7.9(2026-10-02)
### Models: CivitAIベースモデルからの自動バッジ作成
バッジ管理モーダルに「CivitAIから自動バッジ作成」を追加(`static/js/models/auto-badge.js`)。現在のタブのモデルのCivitAI `baseModel` からバッジを作る。意思決定モデルは使わず、ルール表で決定的に決める("SDXL 1.0"/"SDXL Turbo"等はSDXLにまとめ、Pony/Illustrious/NoobAI/Flux.1/Flux.2/Qwen/Wan/Z-Image/HiDream等は別バッジ。表に無い値は文字列そのまま、"Other"と空は対象外)。
- モデル側は既存バッジを残したまま追加(同名が既にあれば何もしない)。パレットは同名バッジの色を上書き可(チェックで切替)。「すでにバッジが付いているモデルはスキップ」オプションあり(スキップ分のバッジ名はパレットにも作らない)。
- プレビューで件数・新規/既存を確認してから適用。
### CivitAI一括取得の高速化と安定化
参考にしたcivitai-updater/tiny-model-managerはどちらも単発GETの逐次実行で、当プラグインの一括POST(100件/回)のほうが進んでいた。遅さの原因は取得ではなくハッシュ計算側だった。
- **保存済みsha256の再利用**: 一括取得が保存済みハッシュを無視して毎回全件再計算していた。`sha256Size`/`sha256Mtime`を記録してファイル差し替えを検知(記録の無い旧データは信頼)。
- **サイドカー取り込み**: `<名前>.metadata.json` のsha256とCivitAI情報を、サイズ一致かつ`files[].hashes.SHA256`一致の場合だけ採用(ハッシュ計算・通信不要)。実データでサイドカー87件中74件が利用可能、58件にCivitAI情報あり。
- **並列ハッシュ(3並列)+ 1MB読み**、確定ごとに5秒間隔でメタデータへ保存(途中で止めても計算済み分が残る。以前は最後にまとめて保存していた)。
- **プレビュー保存**を4並列・別スレッド化(以前はasyncハンドラ内で逐次ダウンロードしイベントループを塞いでいた)。進捗に「プレビュー保存中」を追加。
- **未登録スキップ**: CivitAIに存在しなかったモデルに `civitaiNotFound` を記録し、ツールバーの「未登録はスキップ」で一括取得の対象外にできる(既定オフ)。通信エラーで失敗した分は記録しない。見つかれば記録は自動解除。
### フォルダのシンボリックリンク/ジャンクション対応
- モデル走査を `rglob` から自前の `_iter_files` に変更。リンクは辿りつつ、祖先フォルダへ戻る循環だけを検出して入らない(警告ログ)。
- 一括移動の移動先チェックを `resolve()` 比較から論理パス比較に変更し、リンク先フォルダへの移動が「Destination is outside model root」で拒否される問題を修正(`..`・絶対パスでの脱出は従来通り拒否)。
- 注意: リンク配下のモデルを削除すると、リンク先の実ファイルが消える。
### 実機で分かったこと
- TextEncoderタブでの一括取得中にComfyUIが応答しなくなる事象があった。py-spyのダンプでは、イベントループがWindowsの`closesocket`内で停止しており(作業スレッドは全て待機中でプラグインのコードはスタックに無い)、本変更が直接原因とは断定できなかった。PC再起動と動作に影響しうる他のカスタムノードの削除後は正常動作を確認。
- この環境(管理者権限なし)ではシンボリックリンクを作れず、ジャンクションのみでテストした。
---
## v0.7.8(2026-10-01)
### Video Edit: マルチトラック化(ビデオ/オーバーレイ/テキスト/オーディオ)
タイムライン上部のボタンでトラック表示を切り替える(ビデオ=青 `#4a9eff`・オーバーレイ=青・テキスト=緑 `#3fb950`・オーディオ=赤 `#f85149`)。下のツールメニューも連動して切り替わる(ビデオ=トリム+クロップ、オーバーレイ=オーバーレイクリップ、テキスト=テキストオーバーレイ、オーディオ=オーディオ設定)。Save/Load/書き出しは右に固定。
- **テキストをタイムライン直付けに変更**: 時間をクリップ相対でなくタイムライン絶対秒で持つ(`_s.texts`)。テキスト帯のドラッグ移動(クリップをまたげる)と端ドラッグでのリサイズに対応。旧形式プロジェクト(クリップ内`texts`)は読込時に絶対秒へ自動変換する(変換処理は実機未検証)。クリップ複製ではテキストは複製されなくなった。
- **追加サウンド**: オーディオトラックに「+ サウンド...」で効果音・ナレーションを何個でも配置(開始/長さ/音量dB、帯のドラッグで移動・端ドラッグでトリム)。書き出しは`LoadAudio→TrimAudioDuration→AudioAdjustVolume→AudioConcat(無音パディング)→AudioMerge`でBGMの上にミックス。実際のComfyUIで実行成功を確認(音の位置自体は耳では未確認)。
- **オーバーレイ(PinP)**: 動画/画像をメイン動画の上に重ねる。時間・位置(9方向プリセット/X/Y)・サイズ・不透明度を個別指定。追加位置は4隅→中央の順にずらす。プレビューには点線枠+サムネイルを表示。Assetタブの詳細パネルに「オーバーレイに追加(PinP)」ボタンを追加。
- **合成方式**: ComfyUIグラフには手を入れず、既存のテキスト焼き込みと同じPyAV 1パス(`/api/wfm/video/edit/overlay-text`に`pips`を追加)で、オーバーレイ→テキストの順に描画。動画オーバーレイは終端フレームを保持。オーバーレイ自身の音声はミックスしない。実際の書き出し出力のフレームを目視確認。
- Undo/Redo・プロジェクト保存/読込・ヘルプ(3言語)に対応。
### フルバックアップ: 追加サウンド/オーバーレイの素材漏れを修正
「Video Editプロジェクトの素材を含める」が、クリップとBGMしか集めていなかったため、追加サウンドとオーバーレイクリップの素材がZIPに入らなかった(`_iter_video_edit_media_refs`が`clips`とBGMだけを走査)。`sounds`/`pips`も走査するよう修正。単体テストと実APIでの出力ZIPの中身確認済み(パストラバーサル・出力フォルダ参照・旧形式・壊れたJSONの扱いも確認)。復元側は無変更。
### 実機で分かったこと
- **ファイル選択ダイアログ**: Overlay追加ボタン(label+非表示input、BGMと同方式)が、ユーザーの通常ブラウザタブではダイアログを出さず、Shift+クリックの別ウィンドウでは出た。コードの欠陥ではなく通常タブ環境側の可能性が高い(未特定)。念のためOverlay/Soundボタンは透明な本物の`<input type=file>`をボタンに重ねる方式に変更。Playwrightはダイアログを横取りするため、この種の不具合は自動テストでは検出できない。
- 検証用ブラウザに待機中のファイル選択が溜まると、ページが古い状態のままになりうる(サーバーは`Cache-Control: no-store`)。
---
## v0.7.7(2026-09-30)
### 意思決定モデル: Ollama 0.35+ バックエンド追加
+6 -2
View File
@@ -26,7 +26,7 @@ A comprehensive workflow, asset management, and generation UI plugin for [ComfyU
- Built-in AI tools (translation and more)
![Workflow Studio](https://img.shields.io/badge/ComfyUI-Custom_Node-blue)
![Version](https://img.shields.io/badge/version-0.7.7-green)
![Version](https://img.shields.io/badge/version-0.7.12-green)
## Features (tab -> feature names)
@@ -76,7 +76,7 @@ Model Browser, Thumbnail / Table views, Table column sort, Search & Filter, User
Layer-based image editor, Loading images, Open PSD button, Close button, New button, Tools, Layer panel, Duplicate layer (⧉), Layer lock, Text quality, Export, Canvas navigation, Undo / Redo
### Video Tab (v0.5.0 – v0.7.4)
Dedicated video generation UI, independent of GenerateUI, Plan subtab, Base settings row, Edit subtab, Edit: Audio / BGM, Edit: Text overlays, Edit: Crop, Edit: Undo / Redo, Edit project persistence, Asset subtab, Project subtab, Two center previews, First Frame / Last Frame are both optional, Semantic node lookup, not hardcoded IDs, Field highlight color, Load in Video, Frame tab, GIF tab, Playback volume
Dedicated video generation UI, independent of GenerateUI, Plan subtab, Base settings row, Edit subtab, Edit: Multi-track, Edit: Audio / BGM, Edit: Text overlays, Edit: Crop, Edit: Undo / Redo, Edit project persistence, Asset subtab, Project subtab, Two center previews, First Frame / Last Frame are both optional, Semantic node lookup, not hardcoded IDs, Field highlight color, Load in Video, Frame tab, GIF tab, Playback volume
### AI TOOL Tab (v0.3.14)
4-pane layout, Translation pane, Chat pane, Chat pane — image generation via Tool Calling, Chat pane — generate_image extra parameters, TOOLS pane (VLM), TOOLS pane — shared Chat attachment, TOOLS pane (Wildcards), Chat pane — image-to-image (I2I), Chat pane — SVG generation, no ComfyUI workflow involved, Chat pane — Skills, Settings pane, Unsloth backend, Decision API client, Settings pane — Chat Image Generation, Settings pane — Chat I2I Generation, Settings pane — Generation, Model unload, Settings shared, Backend support, URL security, Lemonade's other endpoints (not integrated)
@@ -162,6 +162,10 @@ Click the **camera icon** (next to the W button) in ComfyUI's top bar to capture
- **[comfyui-mask-editor-one](https://github.com/ketle-man/comfyui-mask-editor-one) (v0.1.9+)** — enables BiRefNet background removal, SAM3 text-prompt segmentation, and ABR stamp-brush library in the Image Edit Mask tool; `birefnet.safetensors` must be placed in `ComfyUI/models/background_removal/` for BiRefNet
- **[psd-tools](https://pypi.org/project/psd-tools/)** (v0.6.0) — enables all PSD (Photoshop) features: Gallery bulk "Create PSD" export, Gallery browsing/thumbnails for `.psd` files, and Image Edit's Save PSD / Open PSD buttons; `pip install -r requirements.txt` (ships prebuilt wheels, no C compiler required); without it, PSD-related actions show an error toast with the install command instead of failing silently
#### Backend connection security (v0.7.12)
Server-side proxies for Ollama, LM Studio, Lemonade, Unsloth, the Tagger VLM and Eagle only connect to **localhost / 127.0.0.1 / ::1** (any port); `http(s)` only, no credentials in the URL, and redirects are never followed. To use a backend on another machine (e.g. an Ollama server on your LAN), list it in the `WFS_ALLOWED_BACKEND_HOSTS` environment variable (comma-separated `host` or `host:port`, e.g. `192.168.1.20:11434,gpu-box`) and restart ComfyUI. If you start ComfyUI with `--listen`, anyone who can reach it can use these routes, so only do that on a trusted network.
---
## Supported Languages
+7 -2
View File
@@ -22,7 +22,7 @@ A comprehensive workflow, asset management, and generation UI plugin for [ComfyU
- Built-in AI tools (translation and more)
![Workflow Studio](https://img.shields.io/badge/ComfyUI-Custom_Node-blue)
![Version](https://img.shields.io/badge/version-0.7.7-green)
![Version](https://img.shields.io/badge/version-0.7.12-green)
## Screenshots
@@ -238,7 +238,7 @@ An experimental batch generator: runs the workflow currently loaded in GenerateU
- ~~AI Assistant Settings~~ (removed in v0.5.4) — the central Ollama backend/URL/model panel that used to live here was replaced by a ⚙ Settings button + modal directly in the Prompt tab and the Tagger tab, each with its own independent configuration (backend, URL, model, Thinking mode, Max tokens, and a model Unload button) — see those tabs below; the AI TOOL tab's own Settings pane is unaffected
- **Video Playback Volume** (v0.5.4) — the video preview's volume is remembered here and shared across every video player in the plugin (Video tab, Gallery tab), instead of resetting to maximum whenever a different video is opened
- **Data Management** — export core settings/metadata/prompts/CivitAI cache to a single JSON file; import to restore data (useful when migrating or reinstalling); API keys are excluded from exports for security
- **Full Backup (ZIP)** (v0.5.2) — additionally covers what the JSON bundle can't represent: folder-based data (AI Skills, Lab Plans, Video Plans, Video Edit projects, Style presets) and the Tagger SQLite database; two opt-in checkboxes can also include ComfyUI's default workflows folder (`user/default/workflows`) and the Impact Pack's wildcard folder in the export — both of those are export-only and stored under an `_external/` prefix in the ZIP that Restore always skips, since auto-overwriting files a different plugin/ComfyUI core manages would be unsafe; copy them back by hand if needed. A third opt-in checkbox (v0.7.6) bundles the clips/BGM that saved Video Edit projects reference in ComfyUI's input folder (the project JSON only stores references) under `_video_edit_media/`; unlike `_external/`, these are restored into the input folder, never overwriting a file that already exists there. Restoring overwrites existing files; restart ComfyUI afterward for either restore path
- **Full Backup (ZIP)** (v0.5.2) — additionally covers what the JSON bundle can't represent: folder-based data (AI Skills, Lab Plans, Video Plans, Video Edit projects, Style presets) and the Tagger SQLite database; two opt-in checkboxes can also include ComfyUI's default workflows folder (`user/default/workflows`) and the Impact Pack's wildcard folder in the export — both of those are export-only and stored under an `_external/` prefix in the ZIP that Restore always skips, since auto-overwriting files a different plugin/ComfyUI core manages would be unsafe; copy them back by hand if needed. A third opt-in checkbox (v0.7.6) bundles the clips/BGM/sounds/overlay clips that saved Video Edit projects reference in ComfyUI's input folder (the project JSON only stores references) under `_video_edit_media/`; unlike `_external/`, these are restored into the input folder, never overwriting a file that already exists there. Restoring overwrites existing files; restart ComfyUI afterward for either restore path
- **Text Size** — one slider (10–28 px) adjusts font size for all prompt and chat textareas at once: Generate UI positive/negative prompts, AI Assistant chat input, Preset prompts, Wildcard prompt and file editor, and Metadata prompt full preview; takes effect immediately and saved with Save Settings
- **RAW JSON Colors** — customize the 6 syntax highlight colors for the Raw JSON editor in Generate UI: Default Text (base), Name/Scheduler (yellow), Title (pink), Width/Height (green), Prompt/Text (cyan), Image/File (red); changes apply immediately on color pick; Reset Defaults restores the original scheme; saved to `localStorage` under `wfm_settings.jsonColors` and applied on startup
- **GenerateUI Model Tab Highlight** (v0.3.98) — 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; saved to `localStorage` under `wfm_settings.modelTabActiveColor`; the same color and mechanism also drives the Video tab's field highlighting (v0.5.4, see above)
@@ -422,6 +422,7 @@ An experimental batch generator: runs the workflow currently loaded in GenerateU
- **Plan subtab** (center panel, batch redesign in v0.5.5) — a **plan** is a sequence of timeline blocks, each a fully self-contained generation job with its own Prompt, Duration, and First/Last Image; split the timeline with **+ Split** / **+ Block** / **Delete**, then **Run** to generate every block in order (Pause/Cancel work mid-run) — a plan with a single block behaves exactly like the old one-shot form. First Image can be None, an explicit image, or "use previous block's last frame" (chaining — an explicit Last Image on the previous block always wins over extracting one from its generated output). Save / Save As / Clear a plan (`ws_videoplan_*.json`, with a PNG contact-sheet thumbnail that embeds the full plan data so dropping the image back on works too)
- **Base settings row** (topbar, v0.5.7) — Aspect Ratio / Megapixels / Multiple / Duration (seconds) / Noise Seed on one row — Duration always reflects the currently selected block (each block keeps its own value), the rest are plan-wide — plus a second row of model-specific fields: Width / Height (become directly editable for workflows with no Resolution Selector node, e.g. Wan2.2 and LTX-2.5's First & Last Frame to Video), Turbo Mode / Strength / Steps (MiniMax H3's turbo LoRA — Turbo Mode doubles as Wan2.2's own turbo toggle, sharing one field), and Prompt Enhance (LTX-2.5 only). Every field in both rows is enabled only when the loaded workflow actually has it — see Field highlight color below (one exception: Wan2.2's Text-to-Video variant doesn't expose Noise Seed at all, so it alone leaves that field disabled)
- **Edit subtab** (v0.7.0) — a lightweight clip timeline for trimming and concatenating video/image clips outside of generation: add clips via the Video Source panel's **Add to Edit** button or the Asset subtab's **Send to Edit** button, drag blocks to reorder (or use the ◀/▶ toolbar buttons), Duplicate/Delete the selected clip, Clear to empty the timeline. The trim panel for a selected video clip shows a Clipchamp-style scrubber — a time ruler, a draggable playhead synced to the Source preview, and draggable in/out handles with time badges (image clips get a simple hold-duration field instead); the playhead's own time badge sits a row above the in/out handle badges (v0.7.2) so it stays legible even when the playhead lands right on a trim point, and the scrubber has extra headroom/height and spacing from the clip name above it (v0.7.2). **▶ Preview** plays every ready clip back-to-back (trimmed to its in/out points) in the result preview, and **Export** builds and runs the actual ComfyUI graph (trim → crop → concatenate if more than one clip → save), tagging the result into Video Temp automatically. Multi-clip exports keep each clip's own audio (v0.7.4 — previously they were always silent). **Clear** empties the clips and also resets the Audio section to its defaults (v0.7.4)
- **Edit: Multi-track** (v0.7.8) — the buttons above the timeline switch the track view: **Video** (blue), **Overlay** (blue), **Text** (green) and **Audio** (red), and the tool menu below follows it (Video: trim + crop / Overlay: overlay clips / Text: text overlays / Audio: audio settings); Save / Load / Export stay fixed on the right. **Text** now belongs to the timeline (absolute seconds, no longer to a clip): drag a band to move it — even across clips — or drag its edges to retime it; projects saved with clip-relative text are converted on load. **Audio** adds any number of **+ Sound...** clips (sound effects, voice) that you place by dragging their bands, trim by dragging an edge, with their own start / length / volume, on top of the full-length BGM. **Overlay** adds picture-in-picture clips (video or image) via **+ Overlay clip...** or the Asset subtab's **Add as overlay (PinP)** button, each with its own time, position (9 presets or X/Y), size and opacity, shown as dashed boxes in the previews and composited over the main video in the same pass that burns in text on Export (an overlay's own audio is not mixed). Undo/Redo and project Save/Load cover all of it, and Full Backup's "Include media used by Video Edit projects" now also bundles the sounds' and overlays' media.
- **Edit: Audio / BGM** (v0.7.4) — the export panel's **Audio** section sets the soundtrack: **Keep original audio** (with its own volume in dB) keeps every clip's audio aligned to its segment even across multiple clips (image clips contribute silence), and one **BGM** file is laid over the whole video with its own volume and start offset (a longer BGM is cut to the video length). Pick the BGM with **BGM...**, by dropping an audio/video file onto the Audio section, or with **Set as BGM** on a video in the Asset subtab (that video's audio track is used; videos without audio are rejected). Built entirely inside the export graph with ComfyUI core audio nodes (EmptyAudio / AudioMerge / AudioConcat / LoadAudio / TrimAudioDuration / AudioAdjustVolume) passed to ConcatenateVideo's `complete_audio` — no extra dependencies. ▶ Preview plays the BGM alongside the clips
- **Edit: Text overlays** (v0.7.4) — each clip can carry any number of text overlays (**+ Add text** under the trim panel): text, start/end seconds within the clip, size as % of frame height, color, 9-position anchor, outline, and an optional background box. They follow the clip when it's reordered, are previewed live over the Source/Result panes, and are burned in on Export as a final pass (PyAV decode → Pillow → H.264 encode, frame by frame so memory stays flat; the soundtrack is remuxed untouched). Japanese/CJK text renders with a system CJK font (Meiryo / Yu Gothic / Noto Sans JP on Windows)
- **Edit: Crop** (v0.7.4) — **Edit crop** puts a draggable/corner-resizable rectangle over the Source preview (optionally locked to 16:9 / 9:16 / 1:1 / 4:3 / 3:4); **Done** keeps it, **Cancel** restores the crop from before editing, and switching to another subtab/tab ends editing like Done. Export applies it with ComfyUI core `VideoCrop`; the output size is the first video clip's cropped size, and other clips of a different size are center-fit to it. Text overlay previews are drawn relative to the cropped frame
@@ -583,6 +584,10 @@ Click the **camera icon** (next to the W button) in ComfyUI's top bar to capture
- **[comfyui-mask-editor-one](https://github.com/ketle-man/comfyui-mask-editor-one) (v0.1.9+)** — enables BiRefNet background removal, SAM3 text-prompt segmentation, and ABR stamp-brush library in the Image Edit Mask tool; `birefnet.safetensors` must be placed in `ComfyUI/models/background_removal/` for BiRefNet
- **[psd-tools](https://pypi.org/project/psd-tools/)** (v0.6.0) — enables all PSD (Photoshop) features: Gallery bulk "Create PSD" export, Gallery browsing/thumbnails for `.psd` files, and Image Edit's Save PSD / Open PSD buttons; `pip install -r requirements.txt` (ships prebuilt wheels, no C compiler required); without it, PSD-related actions show an error toast with the install command instead of failing silently
#### Backend connection security (v0.7.12)
Server-side proxies for Ollama, LM Studio, Lemonade, Unsloth, the Tagger VLM and Eagle only connect to **localhost / 127.0.0.1 / ::1** (any port); `http(s)` only, no credentials in the URL, and redirects are never followed. To use a backend on another machine (e.g. an Ollama server on your LAN), list it in the `WFS_ALLOWED_BACKEND_HOSTS` environment variable (comma-separated `host` or `host:port`, e.g. `192.168.1.20:11434,gpu-box`) and restart ComfyUI. If you start ComfyUI with `--listen`, anyone who can reach it can use these routes, so only do that on a trusted network.
---
## Supported Languages
+45
View File
@@ -11,6 +11,51 @@ from pathlib import Path
PLUGIN_DIR = Path(__file__).resolve().parent
ENV_FILE = PLUGIN_DIR / ".env"
def _maybe_use_selector_event_loop():
"""Windows: ProactorEventLoop(IOCP) を SelectorEventLoop に切り替える(既定はオフ)。
環境によっては、ソケットclose(closesocket/NtClose)でイベントループがOSカーネル内で停止し、
ComfyUI全体が無応答になる(再起動するまでポートも解放されない)。Selector方式はIOCPを使わず、
この停止を避けられる可能性がある。副作用: asyncioのサブプロセス機能が使えない、
同時接続数の上限(約512)がある。
有効化: 環境変数 WFS_SELECTOR_LOOP=1、または
user/default/Workflow-Studio/settings.json に "windows_selector_event_loop": true
ComfyUIがイベントループを作成する前に呼ぶ必要があるため、ここ(prestartup)で設定する。
"""
import os
import sys
if sys.platform != "win32":
return
enabled = os.environ.get("WFS_SELECTOR_LOOP", "").strip().lower() in ("1", "true", "yes")
if not enabled:
try:
import json
candidates = [
PLUGIN_DIR.parent.parent / "user" / "default" / "Workflow-Studio" / "settings.json",
PLUGIN_DIR / "data" / "settings.json", # config.py fallback when user/default is absent
]
for settings in candidates:
if settings.is_file():
with open(settings, "r", encoding="utf-8") as f:
enabled = bool(json.load(f).get("windows_selector_event_loop", False))
break
except Exception:
enabled = False
if not enabled:
return
try:
import asyncio
asyncio.set_event_loop_policy(asyncio.WindowsSelectorEventLoopPolicy())
print("[Workflow Studio] Using WindowsSelectorEventLoopPolicy (windows_selector_event_loop enabled)")
except Exception as e:
print(f"[WARNING] Workflow Studio: failed to switch to selector event loop: {e}")
_maybe_use_selector_event_loop()
if ENV_FILE.exists():
try:
from dotenv import load_dotenv
+7 -5
View File
@@ -9,6 +9,8 @@ import urllib.error
from aiohttp import web
from ..services.url_guard import require_backend_url, urlopen as _guarded_urlopen
logger = logging.getLogger(__name__)
@@ -92,7 +94,7 @@ def _eagle_add_from_path(eagle_url, file_path, name, tags):
headers={"Content-Type": "application/json"},
method="POST",
)
with urllib.request.urlopen(req, timeout=10) as resp:
with _guarded_urlopen(req, timeout=10) as resp:
return json.loads(resp.read().decode("utf-8"))
@@ -127,7 +129,7 @@ def _eagle_add(eagle_url, image_url, name, tags):
headers={"Content-Type": "application/json"},
method="POST",
)
with urllib.request.urlopen(req, timeout=10) as resp:
with _guarded_urlopen(req, timeout=10) as resp:
return json.loads(resp.read().decode("utf-8"))
@@ -138,7 +140,7 @@ def _eagle_test(eagle_url):
f"{eagle_url}/api/application/info",
method="GET",
)
with urllib.request.urlopen(req, timeout=5) as resp:
with _guarded_urlopen(req, timeout=5) as resp:
return json.loads(resp.read().decode("utf-8"))
@@ -146,7 +148,7 @@ async def handle_add(request: web.Request) -> web.Response:
"""POST /api/wfm/eagle/add - Add image to Eagle."""
try:
body = await request.json()
eagle_url = body.get("eagleUrl", "http://localhost:41595")
eagle_url = require_backend_url(body.get("eagleUrl", "http://localhost:41595"))
image_url = body.get("url", "")
name = body.get("name", "image.png")
tags = body.get("tags", [])
@@ -193,7 +195,7 @@ async def handle_test(request: web.Request) -> web.Response:
"""POST /api/wfm/eagle/test - Test Eagle connection."""
try:
body = await request.json()
eagle_url = body.get("eagleUrl", "http://localhost:41595")
eagle_url = require_backend_url(body.get("eagleUrl", "http://localhost:41595"))
result = await asyncio.to_thread(_eagle_test, eagle_url)
return web.json_response({
"status": "success",
+157 -38
View File
@@ -20,6 +20,7 @@ def setup_routes(app: web.Application):
app.router.add_get("/api/wfm/models/metadata", handle_get_metadata)
app.router.add_post("/api/wfm/models/metadata", handle_save_metadata)
app.router.add_get("/api/wfm/models/preview", handle_get_preview)
app.router.add_get("/api/wfm/models/preview-keys", handle_get_preview_keys)
app.router.add_get("/api/wfm/models/groups", handle_get_groups)
app.router.add_post("/api/wfm/models/groups", handle_save_groups)
app.router.add_post("/api/wfm/models/civitai/fetch", handle_civitai_fetch)
@@ -139,14 +140,20 @@ async def handle_civitai_fetch(request: web.Request) -> web.Response:
)
if not sha256:
return web.json_response({"error": "Failed to calculate hash"}, status=500)
# Cache the hash in model metadata
await asyncio.to_thread(
_service.update_metadata, model_name, {"sha256": sha256}
)
# Cache the hash (+ size/mtime so a replaced file invalidates it) in model metadata
try:
st = file_path.stat()
hash_meta = {"sha256": sha256, "sha256Size": st.st_size, "sha256Mtime": st.st_mtime}
except OSError:
hash_meta = {"sha256": sha256}
await asyncio.to_thread(_service.update_metadata, model_name, hash_meta)
# Fetch from CivitAI
info = await asyncio.to_thread(_civitai.fetch_by_hash, sha256)
if not info:
await asyncio.to_thread(
_service.update_metadata, model_name, {"civitaiNotFound": True}
)
return web.json_response({
"status": "not_found",
"sha256": sha256,
@@ -166,6 +173,10 @@ async def handle_civitai_fetch(request: web.Request) -> web.Response:
if preview_saved:
logger.info("Auto-saved preview for %s from CivitAI", model_name)
if model_meta.get("civitaiNotFound"):
await asyncio.to_thread(
_service.update_metadata, model_name, {"civitaiNotFound": False}
)
return web.json_response({
"status": "ok",
"sha256": sha256,
@@ -244,69 +255,159 @@ async def handle_civitai_batch(request: web.Request) -> web.Response:
def on_progress(current, total, model_name, status):
progress_q.put({"current": current, "total": total, "model": model_name, "status": status})
# 保存済みsha256(size/mtime付き)を渡して再ハッシュを避ける
import time as _time
all_meta0 = _service.get_all_metadata()
known = {}
for n, _p in model_files:
m = all_meta0.get(n) or {}
if m.get("sha256"):
known[n] = {"sha256": m["sha256"], "size": m.get("sha256Size"), "mtime": m.get("sha256Mtime")}
# 未計算のものは Lora Manager が保持済みのsha256を借りる(サイズ一致時のみ。ハッシュ計算を省く)
if len(known) < len(model_files):
from ..services.lora_manager_bridge import fetch_lm_hashes, _norm
# Hostヘッダは信用せず、自分自身のループバック+実際のポートへ接続する(Host偽装/DNSリバインディング対策)
sockname = request.transport.get_extra_info("sockname") if request.transport else None
port = sockname[1] if sockname else (request.url.port or 8188)
origin = f"http://127.0.0.1:{port}"
lm = await asyncio.to_thread(fetch_lm_hashes, origin, model_type)
for n, p in model_files:
if n in known:
continue
e = lm.get(_norm(p))
try:
if e and e.get("size") is not None and int(e["size"]) == p.stat().st_size:
known[n] = {"sha256": e["sha256"], "size": int(e["size"]), "mtime": None}
except OSError:
pass
# ハッシュ確定ごとに溜め、5秒おきにメタデータへ書き出す(途中で止めても計算済み分が残る)
pending_hashes = {}
last_flush = [_time.monotonic()]
def flush_hashes():
if not pending_hashes:
return
try:
all_meta = _service.get_all_metadata()
for mname, (sha, size, mtime) in list(pending_hashes.items()):
entry = all_meta.setdefault(mname, {"tags": [], "favorite": False, "memo": ""})
entry["sha256"] = sha
entry["sha256Size"] = size
entry["sha256Mtime"] = mtime
_service._save_metadata(all_meta)
pending_hashes.clear()
except Exception as e:
logger.warning("Failed to flush hashes: %s", e)
last_flush[0] = _time.monotonic()
def on_hash(name, sha, size, mtime):
pending_hashes[name] = (sha, size, mtime)
if _time.monotonic() - last_flush[0] > 5:
flush_hashes()
# Start batch in background thread
import threading
cancel = threading.Event()
loop = asyncio.get_event_loop()
fetch_task = loop.run_in_executor(None, _civitai.batch_fetch, model_files, on_progress)
fetch_task = loop.run_in_executor(
None, lambda: _civitai.batch_fetch(model_files, on_progress, known, on_hash, cancel=cancel)
)
# Stream progress events
import time as _time
try:
while not fetch_task.done():
# Drain queue
while not progress_q.empty():
try:
p = progress_q.get_nowait()
await response.write(send_sse("progress", p))
except queue.Empty:
break
await asyncio.sleep(0.1)
while not fetch_task.done():
# Drain queue
# Drain remaining events
while not progress_q.empty():
try:
p = progress_q.get_nowait()
await response.write(send_sse("progress", p))
except queue.Empty:
break
await asyncio.sleep(0.1)
# Drain remaining events
while not progress_q.empty():
except (ConnectionResetError, asyncio.CancelledError) as e:
# クライアント切断(再読み込み・タブ遷移): 重いハッシュ計算を打ち切り、計算済み分だけ保存して終了
logger.info("civitai batch: client disconnected, cancelling (%s)", type(e).__name__)
cancel.set()
try:
p = progress_q.get_nowait()
await response.write(send_sse("progress", p))
except queue.Empty:
break
await asyncio.shield(fetch_task)
except Exception:
pass
await asyncio.to_thread(flush_hashes)
if isinstance(e, asyncio.CancelledError):
raise
return response
# Get results and update metadata
results = fetch_task.result()
try:
results = fetch_task.result()
finally:
await asyncio.to_thread(flush_hashes)
meta_updates = {}
for model_name, result in results.items():
sha256 = result.get("sha256")
if sha256:
meta_updates[model_name] = sha256
# Bulk update sha256 in metadata
# Bulk update sha256 (+ CivitAI not-found marker) in metadata
if meta_updates:
all_meta = _service.get_all_metadata()
for mname, sha in meta_updates.items():
if mname not in all_meta:
all_meta[mname] = {"tags": [], "favorite": False, "memo": ""}
all_meta[mname]["sha256"] = sha
r = results[mname]
if r.get("civitai"):
all_meta[mname].pop("civitaiNotFound", None)
elif not r.get("fetch_failed") and not r.get("error"):
all_meta[mname]["civitaiNotFound"] = _service._now_iso()
_service._save_metadata(all_meta)
# Auto-set previews for models without preview image
# (ネットワークI/Oなのでイベントループを塞がないようスレッドで並列実行)
await response.write(send_sse("progress", {
"current": len(model_files), "total": len(model_files), "model": "", "status": "previews",
}))
dirs = _get_model_dirs(model_type)
preview_saved_count = 0
for model_name, result in results.items():
civitai = result.get("civitai")
if not civitai or not civitai.get("images"):
continue
if _service.find_preview_image(model_type, model_name):
continue
model_file = None
for d in dirs:
p = d / model_name
if p.is_file():
model_file = p
break
if not model_file:
continue
preview_path = model_file.parent / (model_file.stem + ".preview.png")
if CivitaiService.download_image(civitai["images"][0], preview_path):
preview_saved_count += 1
logger.info("Auto-saved preview for %s from CivitAI", model_name)
def _save_previews():
jobs = []
for model_name, result in results.items():
civitai = result.get("civitai")
if not civitai or not civitai.get("images"):
continue
if _service.find_preview_image(model_type, model_name):
continue
model_file = None
for d in dirs:
p = d / model_name
if p.is_file():
model_file = p
break
if not model_file:
continue
jobs.append((model_name, civitai["images"][0],
model_file.parent / (model_file.stem + ".preview.png")))
if not jobs:
return 0
from concurrent.futures import ThreadPoolExecutor
with ThreadPoolExecutor(max_workers=2) as pool:
oks = list(pool.map(lambda j: CivitaiService.download_image(j[1], j[2]), jobs))
for (mname, _u, _p), ok in zip(jobs, oks):
if ok:
logger.info("Auto-saved preview for %s from CivitAI", mname)
return sum(1 for ok in oks if ok)
preview_saved_count = await asyncio.to_thread(_save_previews)
# Send final result
summary = {
@@ -314,6 +415,7 @@ async def handle_civitai_batch(request: web.Request) -> web.Response:
"found": sum(1 for r in results.values() if r.get("civitai")),
"not_found": sum(1 for r in results.values() if r.get("sha256") and not r.get("civitai")),
"errors": sum(1 for r in results.values() if r.get("error")),
"needs_hash": sum(1 for r in results.values() if r.get("needs_hash")),
"hashes": {name: r.get("sha256") for name, r in results.items() if r.get("sha256")},
"preview_saved": preview_saved_count,
}
@@ -325,6 +427,22 @@ async def handle_civitai_batch(request: web.Request) -> web.Response:
# ── Model Preview Image ───────────────────────────────────
async def handle_get_preview_keys(request: web.Request) -> web.Response:
"""GET /api/wfm/models/preview-keys?type=checkpoint
プレビュー画像を持つモデルのキー一覧を返す(無いモデルへの画像リクエスト=404を避けるため)。
"""
model_type = request.query.get("type", "")
if not model_type:
return web.json_response({"error": "type required"}, status=400)
try:
keys = await asyncio.to_thread(_service.list_preview_keys, model_type)
return web.json_response({"keys": keys})
except Exception as e:
logger.error("Error listing preview keys: %s", e)
return web.json_response({"error": str(e)}, status=500)
async def handle_get_preview(request: web.Request) -> web.Response:
"""GET /api/wfm/models/preview?type=checkpoint&name=model.safetensors"""
model_type = request.query.get("type", "")
@@ -632,7 +750,8 @@ async def handle_list_model_files(request: web.Request) -> web.Response:
if not model_type or model_type not in MODEL_TYPE_FOLDER_KEYS:
return web.json_response({"error": "invalid type"}, status=400)
try:
result = await asyncio.to_thread(_service.list_model_files, model_type)
extra_only = request.query.get("extra_only") == "1"
result = await asyncio.to_thread(_service.list_model_files, model_type, extra_only)
return web.json_response(result)
except Exception as e:
logger.error("Error listing model files for %s: %s", model_type, e)
+9 -6
View File
@@ -7,6 +7,7 @@ import urllib.request
from aiohttp import web
from ..services.settings_service import SettingsService
from ..services.url_guard import require_backend_url, urlopen
logger = logging.getLogger(__name__)
@@ -39,11 +40,12 @@ async def handle_models(request: web.Request) -> web.Response:
import asyncio
try:
cfg = _get_ollama_config()
base_url = require_backend_url(cfg["url"])
def _fetch():
url = f"{cfg['url']}/api/tags"
url = f"{base_url}/api/tags"
req = urllib.request.Request(url)
with urllib.request.urlopen(req, timeout=5) as resp:
with urlopen(req, timeout=5) as resp:
return json.loads(resp.read().decode("utf-8"))
data = await asyncio.to_thread(_fetch)
@@ -61,11 +63,12 @@ async def handle_test(request: web.Request) -> web.Response:
import asyncio
try:
cfg = _get_ollama_config()
base_url = require_backend_url(cfg["url"])
def _test():
url = f"{cfg['url']}/api/tags"
url = f"{base_url}/api/tags"
req = urllib.request.Request(url, method="GET")
with urllib.request.urlopen(req, timeout=5) as resp:
with urlopen(req, timeout=5) as resp:
return resp.status == 200
ok = await asyncio.to_thread(_test)
@@ -83,7 +86,7 @@ async def handle_chat(request: web.Request) -> web.Response:
body = await request.json()
cfg = _get_ollama_config()
model = body.get("model") or cfg["model"]
base_url = (body.get("url") or cfg["url"]).rstrip("/")
base_url = require_backend_url(body.get("url") or cfg["url"])
messages = body.get("messages", [])
def _chat():
@@ -100,7 +103,7 @@ async def handle_chat(request: web.Request) -> web.Response:
headers={"Content-Type": "application/json"},
method="POST",
)
with urllib.request.urlopen(req, timeout=120) as resp:
with urlopen(req, timeout=120) as resp:
return json.loads(resp.read().decode("utf-8"))
resp_data = await asyncio.to_thread(_chat)
+54 -4
View File
@@ -38,6 +38,8 @@ def setup_routes(app: web.Application):
app.router.add_post("/api/wfm/settings", handle_post)
app.router.add_get("/api/wfm/settings/workflows-dir", handle_get_workflows_dir)
app.router.add_post("/api/wfm/settings/workflows-dir", handle_set_workflows_dir)
app.router.add_get("/api/wfm/settings/models-dir", handle_get_models_dir)
app.router.add_post("/api/wfm/settings/models-dir", handle_set_models_dir)
app.router.add_get("/api/wfm/settings/output-dir", handle_get_output_dir)
app.router.add_post("/api/wfm/settings/output-dir", handle_set_output_dir)
app.router.add_get("/api/wfm/settings/export", handle_export)
@@ -122,6 +124,47 @@ async def handle_set_workflows_dir(request: web.Request) -> web.Response:
return web.json_response({"error": str(e)}, status=500)
async def handle_get_models_dir(request: web.Request) -> web.Response:
"""GET /api/wfm/settings/models-dir - 追加モデルフォルダ設定と現在有効な探索先を返す。"""
try:
from ..services.models_service import (
MODEL_TYPE_FOLDER_KEYS, _get_model_dirs, parse_extra_model_roots,
)
saved = (await asyncio.to_thread(_service.load)).get("models_dir", "")
effective = await asyncio.to_thread(
lambda: {t: [str(d) for d in _get_model_dirs(t)] for t in MODEL_TYPE_FOLDER_KEYS}
)
return web.json_response({
"saved": saved,
"roots": parse_extra_model_roots(saved),
"effective": effective,
})
except Exception as e:
logger.error("Error getting models dir: %s", e)
return web.json_response({"error": str(e)}, status=500)
async def handle_set_models_dir(request: web.Request) -> web.Response:
"""POST /api/wfm/settings/models-dir - 追加モデルフォルダを保存(`;`/改行区切りで複数可、空でリセット)。"""
try:
from ..services.models_service import parse_extra_model_roots
body = await request.json()
roots = parse_extra_model_roots(body.get("models_dir", ""))
missing = [r for r in roots if not Path(r).is_dir()]
if missing:
return web.json_response(
{"error": f"Folder not found: {', '.join(missing)}"}, status=400)
saved = ";".join(roots)
await asyncio.to_thread(_service.update, {"models_dir": saved})
from ..routes.models_routes import _service as models_service
models_service._scan_cache.clear()
return await handle_get_models_dir(request)
except Exception as e:
logger.error("Error setting models dir: %s", e)
return web.json_response({"error": str(e)}, status=500)
def _get_comfyui_output_dir() -> str:
"""ComfyUIのデフォルトoutputフォルダを取得する。"""
try:
@@ -307,8 +350,8 @@ def _add_external_dir_to_zip(zf: zipfile.ZipFile, src_dir: Path, zip_prefix: str
# Video Edit projects (video_edit_project/*.json, inside DATA_DIR so always backed up) only
# store *references* — serverRef {filename, subfolder, type:"input"} — to clips and the BGM
# uploaded into ComfyUI's input dir, not the media itself. Backing up just the JSON means a
# store *references* — serverRef {filename, subfolder, type:"input"} — to clips, the BGM,
# timeline sounds and overlay (PinP) clips uploaded into ComfyUI's input dir, not the media itself. Backing up just the JSON means a
# restored project on another machine (or after input/ is cleaned up) opens with its clips
# missing. Opt-in (include_video_media) because the media can be large; stored under its own
# prefix so _apply_full_backup_zip can route it back into the input dir, not DATA_DIR.
@@ -322,7 +365,8 @@ def _comfyui_input_dir() -> Path:
def _iter_video_edit_media_refs():
"""Yields (subfolder, filename) for every input-dir file referenced by a saved Video
Edit project (clips + BGM). Unreadable project files are skipped."""
Edit project (clips + BGM + timeline sounds + overlay clips). Unreadable project files
are skipped."""
if not VIDEO_EDIT_PROJECT_DIR.is_dir():
return
for path in sorted(VIDEO_EDIT_PROJECT_DIR.glob("*.json")):
@@ -331,7 +375,13 @@ def _iter_video_edit_media_refs():
data = json.load(f)
except Exception:
continue
refs = [c.get("serverRef") for c in data.get("clips") or [] if isinstance(c, dict)]
# "sounds" / "pips" are top-level lists of {name, serverRef, ...} (absent in older projects).
refs = [
c.get("serverRef")
for key in ("clips", "sounds", "pips")
for c in data.get(key) or []
if isinstance(c, dict)
]
bgm = (data.get("audio") or {}).get("bgm")
if isinstance(bgm, dict):
refs.append(bgm.get("serverRef"))
+8 -19
View File
@@ -19,19 +19,19 @@ import logging
import os
import urllib.request
from urllib.error import HTTPError, URLError
from urllib.parse import urlparse
from aiohttp import web
from ..services.url_guard import HINT as _URL_HINT, is_allowed_backend_url, urlopen as _guarded_urlopen
logger = logging.getLogger(__name__)
UNSLOTH_DEFAULT_URL = "http://localhost:8888"
_ALLOWED_PATHS = {"/v1/models", "/v1/chat/completions", "/v1/systemone"}
# 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"}
# Authorization header carries a real secret — restrict the host (loopback, or
# WFS_ALLOWED_BACKEND_HOSTS set by the operator) so this proxy can't be used to
# exfiltrate UNSLOTH_API_KEY to an arbitrary server (SSRF). Redirects are not followed.
def _get_api_key():
@@ -47,15 +47,6 @@ KEYLESS_REJECTED_MESSAGE = (
)
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)
@@ -78,10 +69,8 @@ async def handle_proxy(request: web.Request) -> web.Response:
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)
if not is_allowed_backend_url(base_url):
return web.json_response({"message": _URL_HINT}, status=400)
# No key → relay without Authorization (Unsloth's Keyless API access); if Unsloth
# still demands one, the 401 below explains both ways to fix it.
@@ -93,7 +82,7 @@ async def handle_proxy(request: web.Request) -> web.Response:
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:
with _guarded_urlopen(req, timeout=120) as resp:
return json.loads(resp.read().decode("utf-8"))
data = await asyncio.to_thread(_fetch)
+4 -3
View File
@@ -104,15 +104,16 @@ async def handle_overlay_text(request: web.Request) -> web.Response:
type_ = body.get("type", "output")
overlays = body.get("overlays") or []
delete_source = bool(body.get("delete_source"))
pips = body.get("pips") or []
if not filename:
return web.json_response({"error": "filename required"}, status=400)
if not isinstance(overlays, list):
return web.json_response({"error": "overlays must be a list"}, status=400)
if not isinstance(overlays, list) or not isinstance(pips, list):
return web.json_response({"error": "overlays and pips must be lists"}, status=400)
# Decode+re-encode of every frame — run off the event loop so other
# requests aren't stalled for the duration of the burn-in.
result = await asyncio.to_thread(
_service.overlay_text_on_video, filename, subfolder, type_, overlays, "video/wfm_edit", delete_source
_service.overlay_text_on_video, filename, subfolder, type_, overlays, "video/wfm_edit", delete_source, pips
)
return web.json_response({"status": "ok", **result})
except FileNotFoundError as e:
+320 -32
View File
@@ -56,6 +56,38 @@ _MAX_RETRIES = 3
_BATCH_CHUNK_SIZE = 100
# サイドカーJSON(.metadata.json / .cm-info.json)の最大サイズ。巨大ファイルでメモリを使い切らないための上限
_SIDECAR_MAX_BYTES = 2 * 1024 * 1024
def _as_int(v):
"""数値IDだけを受け付ける(文字列に細工されたIDをURL等に埋め込まないため)。不正ならNone。"""
try:
if isinstance(v, bool):
return None
n = int(v)
return n if n > 0 else None
except (TypeError, ValueError):
return None
# プレビュー画像のダウンロード許可ホスト(サイドカーJSON由来のURLでSSRF/ローカルファイル読み取りをさせない)
_IMAGE_HOST_SUFFIXES = (".civitai.com", ".civitai.red", ".civitai.green")
_IMAGE_HOST_EXACT = ("civitai.com", "civitai.red", "civitai.green")
_IMAGE_MAX_BYTES = 50 * 1024 * 1024
def _is_allowed_image_url(url):
"""https かつ CivitAI 系ホストのURLだけ許可する(file:// や内部アドレス、他ホストは拒否)。"""
try:
from urllib.parse import urlparse
u = urlparse(str(url).strip())
host = (u.hostname or "").lower()
return u.scheme == "https" and (host in _IMAGE_HOST_EXACT or host.endswith(_IMAGE_HOST_SUFFIXES))
except Exception:
return False
class CivitaiService:
"""Fetch and cache CivitAI model metadata."""
@@ -117,14 +149,16 @@ class CivitaiService:
# ── ハッシュ計算 ──────────────────────────────────────────
@staticmethod
def calculate_sha256(file_path, chunk_size=65536):
"""Calculate SHA256 hash of a file."""
def calculate_sha256(file_path, chunk_size=512 * 1024, cancel=None):
"""Calculate SHA256 hash of a file. cancel(threading.Event)がセットされたらNoneを返して中断。"""
h = hashlib.sha256()
path = Path(file_path)
if not path.is_file():
return None
with open(path, "rb") as f:
while True:
if cancel is not None and cancel.is_set():
return None
chunk = f.read(chunk_size)
if not chunk:
break
@@ -142,8 +176,11 @@ class CivitaiService:
"""
sha256_lower = sha256_hash.lower()
cache = self._load_cache()
if sha256_lower in cache:
return cache[sha256_lower]
cached = cache.get(sha256_lower)
# Stability Matrix(.cm-info.json)由来の簡易情報は画像一覧を持たないため、
# 明示的な取得/更新ではAPIから完全な情報で上書きする
if cached is not None and cached.get("source") != "cm-info":
return cached
url = f"{CIVITAI_API_BASE}/model-versions/by-hash/{sha256_hash.upper()}"
@@ -198,6 +235,7 @@ class CivitaiService:
url = f"{CIVITAI_API_BASE}/model-versions/by-hash"
results = {h.lower(): None for h in sha256_hashes}
cache = self._load_cache()
failed = set()
for chunk_start in range(0, len(sha256_hashes), _BATCH_CHUNK_SIZE):
chunk = sha256_hashes[chunk_start:chunk_start + _BATCH_CHUNK_SIZE]
@@ -239,6 +277,7 @@ class CivitaiService:
time.sleep(wait)
continue
logger.warning("CivitAI batch POST error: %s %s", e.code, e.reason)
failed.update(chunk_lower)
break
except (URLError, Exception) as e:
if attempt < _MAX_RETRIES - 1:
@@ -247,8 +286,11 @@ class CivitaiService:
time.sleep(wait)
continue
logger.warning("CivitAI batch POST failed: %s", e)
failed.update(chunk_lower)
break
# 通信失敗したチャンクは「CivitAIに存在しない」と区別するため記録する
self.last_failed_hashes = failed
self._save_cache()
return results
@@ -338,64 +380,295 @@ class CivitaiService:
# ── バッチフェッチ ────────────────────────────────────────
def batch_fetch(self, model_files, progress_callback=None):
@staticmethod
def _known_hash(known, st):
"""メタデータに保存済みのsha256が、現在のファイルに対して有効ならそれを返す。
size/mtime が記録されていれば一致を確認する(ファイル差し替え検知)。
記録の無い旧データは信頼する。
"""
sha = (known or {}).get("sha256")
if not sha:
return None
try:
ks, km = known.get("size"), known.get("mtime")
if ks is not None and int(ks) != st.st_size:
return None
if km is not None and abs(float(km) - st.st_mtime) > 2:
return None
except (TypeError, ValueError):
return None
return str(sha).lower()
def _read_sidecar(self, file_path, size):
"""サイドカーからsha256とCivitAI情報を読む(ハッシュ計算・通信不要)。
Lora Manager の `<stem>.metadata.json` → Stability Matrix の `<stem>.cm-info.json` の順に試す。
Returns: (sha256_lower or None, extracted_info or None)
"""
sha, info = self._read_lm_sidecar(file_path, size)
if sha:
return sha, info
return self._read_cm_info(file_path)
@staticmethod
def _parse_iso_ts(value):
"""ISO8601文字列→epoch秒。.NETの7桁小数秒にも対応。失敗時はNone。"""
try:
import re
from datetime import datetime
s = str(value).replace("Z", "+00:00")
s = re.sub(r"(\.\d{6})\d+", r"\1", s)
return datetime.fromisoformat(s).timestamp()
except Exception:
return None
def _read_cm_info(self, file_path):
"""Stability Matrix の `<stem>.cm-info.json` から sha256 とCivitAI簡易情報を読む。
ファイルサイズ情報が無いため、ImportedAt より後にモデルファイルが更新されていたら不採用。
画像一覧は持たないので info には "source": "cm-info" を付け、個別取得で完全情報に置き換えられる。
"""
sc = file_path.with_name(file_path.stem + ".cm-info.json")
try:
if sc.stat().st_size > _SIDECAR_MAX_BYTES: # 巨大ファイルによるメモリ消費を避ける
return None, None
with open(sc, "r", encoding="utf-8-sig") as f:
d = json.load(f)
if not isinstance(d, dict):
return None, None
sha = str((d.get("Hashes") or {}).get("SHA256", "")).lower()
if len(sha) != 64 or any(c not in "0123456789abcdef" for c in sha):
return None, None
imported = self._parse_iso_ts(d.get("ImportedAt"))
if imported is None or file_path.stat().st_mtime > imported + 2:
return None, None
except Exception:
return None, None
info = None
try:
if d.get("Source", 0) == 0 and _as_int(d.get("VersionId")): # 0 = Civitai
info = self._info_from_cm_info(d)
except Exception:
info = None
return sha, info
@staticmethod
def _info_from_cm_info(d):
"""cm-info.json を _extract_info と同じ形式のdictに変換する。"""
model_id, version_id = _as_int(d.get("ModelId")), _as_int(d.get("VersionId"))
stats = d.get("Stats") or {}
return {
"versionId": version_id,
"modelId": model_id,
"modelName": d.get("ModelName", ""),
"versionName": d.get("VersionName", ""),
"type": d.get("ModelType", ""),
"description": d.get("VersionDescription") or d.get("ModelDescription", ""),
"tags": [str(x) for x in (d.get("Tags") or []) if isinstance(x, (str, int, float))][:100],
"nsfw": bool(d.get("Nsfw", False)),
"nsfwLevel": 0,
"air": "",
"creator": d.get("AuthorUsername") or "",
"images": [],
"imageDetails": [],
"trainedWords": [str(x) for x in (d.get("TrainedWords") or []) if isinstance(x, (str, int, float))][:200],
"baseModel": d.get("BaseModel") or "",
"fileSize": 0,
"fileMeta": d.get("FileMetadata") or {},
"fileHashes": d.get("Hashes") or {},
"downloadUrl": "",
"modelUrl": (
f"https://civitai.com/models/{model_id}?modelVersionId={version_id}"
if model_id else f"https://civitai.com/model-versions/{version_id}"
),
"stats": {
"downloadCount": stats.get("downloadCount", 0),
"thumbsUpCount": stats.get("thumbsUpCount", 0),
"thumbsDownCount": stats.get("thumbsDownCount", 0),
},
"updatedAt": "",
"publishedAt": "",
"source": "cm-info",
}
def _read_lm_sidecar(self, file_path, size):
"""`<stem>.metadata.json` (Lora Manager) サイドカーからsha256とCivitAI情報を読む。
サイドカーのsizeがファイルサイズと一致する場合のみ採用する。
Returns: (sha256_lower or None, extracted_info or None)
"""
sc = file_path.with_name(file_path.stem + ".metadata.json")
try:
if sc.stat().st_size > _SIDECAR_MAX_BYTES:
return None, None
with open(sc, "r", encoding="utf-8") as f:
d = json.load(f)
if not isinstance(d, dict):
return None, None
sha = str(d.get("sha256", "")).lower()
if len(sha) != 64 or any(c not in "0123456789abcdef" for c in sha):
return None, None
if d.get("size") is None or int(float(d["size"])) != size:
return None, None
except Exception:
return None, None
info = None
civ = d.get("civitai")
if isinstance(civ, dict) and civ.get("id"):
# 別ファイルの情報を取り込まないよう、files[].hashes.SHA256 に一致するものだけ採用
matched = any(
str(f.get("hashes", {}).get("SHA256", "")).lower() == sha
for f in civ.get("files", []) if isinstance(f, dict)
)
if matched:
try:
info = self._extract_info(civ)
except Exception:
info = None
return sha, info
def batch_fetch(self, model_files, progress_callback=None, known=None, on_hash=None, workers=2, cancel=None, hash_missing=False):
"""Batch fetch CivitAI info for multiple model files.
Phase 1: SHA256 計算("hashing")
Phase 0: 保存済みsha256 / サイドカーから解決(ハッシュ計算・通信なし)
Phase 1: 残りのSHA256を並列計算("hashing")— hash_missing=True のときのみ。
既定では計算せず needs_hash を返す
Phase 2: POST で一括取得("fetching")— キャッシュ済みはスキップ
Args:
model_files: list of (model_name, file_path) tuples
progress_callback: fn(current, total, model_name, status) called per model
known: { model_name: {"sha256", "size", "mtime"} } メタデータ保存済みハッシュ
on_hash: fn(model_name, sha256, size, mtime) ハッシュが新たに確定するたびに呼ばれる
workers: ハッシュ計算の並列数
cancel: threading.Event。セットされると未処理分を打ち切って戻る(クライアント切断時)
Returns: dict of { model_name: { sha256, civitai_info_or_none } }
"""
results = {}
total = len(model_files)
cache = self._load_cache()
known = known or {}
finished = 0
cache_dirty = False
# Phase 1: ハッシュ計算
hashes_needed = [] # [(model_name, sha256_lower, original_index)]
hashes_needed = [] # [(model_name, sha256_lower)]
to_hash = [] # [(model_name, file_path, stat)]
for i, (model_name, file_path) in enumerate(model_files):
if progress_callback:
progress_callback(i, total, model_name, "hashing")
sha256 = self.calculate_sha256(file_path)
if not sha256:
results[model_name] = {"sha256": None, "civitai": None, "error": "hash_failed"}
def _resolved(name, sha, st, new_hash):
"""sha256確定後の共通処理。キャッシュにあれば完了、無ければ取得待ちへ。"""
nonlocal finished
results[name] = {"sha256": sha, "civitai": None}
if new_hash and on_hash:
on_hash(name, sha, st.st_size, st.st_mtime)
if sha in cache:
results[name]["civitai"] = cache[sha]
finished += 1
if progress_callback:
progress_callback(i + 1, total, model_name, "not_found")
progress_callback(finished, total, name, "cached")
else:
hashes_needed.append((name, sha))
# Phase 0: ハッシュ計算なしで解決できるものを先に処理
for model_name, file_path in model_files:
try:
st = Path(file_path).stat()
except OSError:
results[model_name] = {"sha256": None, "civitai": None, "error": "hash_failed"}
finished += 1
if progress_callback:
progress_callback(finished, total, model_name, "not_found")
continue
sha256_lower = sha256.lower()
results[model_name] = {"sha256": sha256_lower, "civitai": None}
sha = self._known_hash(known.get(model_name), st)
if sha:
_resolved(model_name, sha, st, new_hash=False)
continue
if sha256_lower in cache:
results[model_name]["civitai"] = cache[sha256_lower]
sha, info = self._read_sidecar(Path(file_path), st.st_size)
if sha:
if info and sha not in cache:
cache[sha] = info
cache_dirty = True
_resolved(model_name, sha, st, new_hash=True)
continue
to_hash.append((model_name, file_path, st))
if cache_dirty:
self._save_cache()
logger.info("CivitAI batch: total=%d resolved_without_hash=%d need_hash=%d hash_missing=%s",
total, len(results), len(to_hash), hash_missing)
# ハッシュ未確定のものは、hash_missing=False(既定)なら計算せず "needs_hash" として返す
# (個別取得でハッシュ計算する運用。全件ハッシュ計算は負荷が高いため行わない)
if to_hash and not hash_missing:
for model_name, _fp, _st in to_hash:
results[model_name] = {"sha256": None, "civitai": None, "needs_hash": True}
finished += 1
if progress_callback:
progress_callback(i + 1, total, model_name, "cached")
else:
hashes_needed.append((model_name, sha256_lower, i))
progress_callback(finished, total, model_name, "needs_hash")
to_hash = []
# Phase 1: 残りを並列でハッシュ計算(hashlibは大きなチャンクでGILを解放する)
if to_hash:
from concurrent.futures import ThreadPoolExecutor, as_completed
def _hash(item):
return self.calculate_sha256(item[1], cancel=cancel)
with ThreadPoolExecutor(max_workers=max(1, workers)) as pool:
futures = {pool.submit(_hash, item): item for item in to_hash}
for fut in as_completed(futures):
if cancel is not None and cancel.is_set():
for f in futures:
f.cancel()
break
model_name, _fp, st = futures[fut]
try:
sha = fut.result()
except Exception:
sha = None
if not sha:
results[model_name] = {"sha256": None, "civitai": None, "error": "hash_failed"}
finished += 1
if progress_callback:
progress_callback(finished, total, model_name, "not_found")
continue
if progress_callback:
progress_callback(finished, total, model_name, "hashing")
_resolved(model_name, sha.lower(), st, new_hash=True)
if cancel is not None and cancel.is_set():
return results
# Phase 2: POST で一括取得(未キャッシュ分)
if hashes_needed:
if progress_callback:
progress_callback(len(results), total, "", "fetching")
progress_callback(finished, total, "", "fetching")
# 同一ハッシュが複数モデルに対応する場合を考慮
sha256_to_entries: dict[str, list] = {}
for name, sha256_lower, idx in hashes_needed:
sha256_to_entries.setdefault(sha256_lower, []).append((name, idx))
sha256_to_names: dict[str, list] = {}
for name, sha256_lower in hashes_needed:
sha256_to_names.setdefault(sha256_lower, []).append(name)
batch_results = self._batch_fetch_post(list(sha256_to_entries.keys()))
logger.info("CivitAI batch: POST %d hashes", len(sha256_to_names))
batch_results = self._batch_fetch_post(list(sha256_to_names.keys()))
logger.info("CivitAI batch: POST done")
failed = getattr(self, "last_failed_hashes", set())
for sha256_lower, info in batch_results.items():
for name, idx in sha256_to_entries.get(sha256_lower, []):
for name in sha256_to_names.get(sha256_lower, []):
results[name]["civitai"] = info
if not info and sha256_lower in failed:
results[name]["fetch_failed"] = True
finished += 1
if progress_callback:
status = "found" if info else "not_found"
progress_callback(idx + 1, total, name, status)
progress_callback(finished, total, name, status)
if progress_callback:
progress_callback(total, total, "", "done")
@@ -407,10 +680,25 @@ class CivitaiService:
@staticmethod
def download_image(url, save_path, timeout=15):
"""Download an image from URL and save to save_path. Returns True on success."""
if not _is_allowed_image_url(url):
logger.warning("Refusing to download preview from non-CivitAI URL: %s", str(url)[:120])
return False
try:
from urllib.request import HTTPRedirectHandler, HTTPSHandler, build_opener
class _SafeRedirect(HTTPRedirectHandler):
def redirect_request(self, req, fp, code, msg, headers, newurl):
if not _is_allowed_image_url(newurl): # リダイレクト先も検証
raise ValueError("redirect to disallowed host")
return super().redirect_request(req, fp, code, msg, headers, newurl)
opener = build_opener(_SafeRedirect, HTTPSHandler(context=_get_ssl_context()))
req = Request(url, headers={"User-Agent": "ComfyUI-Workflow-Studio/1.0"})
with urlopen(req, timeout=timeout, context=_get_ssl_context()) as resp:
data = resp.read()
with opener.open(req, timeout=timeout) as resp:
data = resp.read(_IMAGE_MAX_BYTES + 1)
if len(data) > _IMAGE_MAX_BYTES:
logger.warning("Preview too large, skipped: %s", str(url)[:120])
return False
with open(save_path, "wb") as f:
f.write(data)
return True
+48
View File
@@ -0,0 +1,48 @@
"""ComfyUI-Lora-Manager 連携: LMが保持済みのsha256を再利用してハッシュ計算を省く。
LMの `/api/lm/{prefix}/list` は sha256 / file_path / file_size を返す(CivitAI詳細は薄いので
情報そのものは使わず、重いハッシュ計算の省略にのみ利用する)。LM未導入・失敗時は空を返す。
"""
import json
import logging
import os
from urllib.request import urlopen
logger = logging.getLogger(__name__)
# 当アプリのモデルタイプ → LMのルート接頭辞
_LM_PREFIX = {"checkpoint": "checkpoints", "lora": "loras", "embedding": "embeddings"}
_PAGE_SIZE = 100 # LM側の上限
_MAX_PAGES = 200
_TIMEOUT = 5
def _norm(path):
return os.path.normcase(os.path.abspath(path))
def fetch_lm_hashes(origin, model_type):
"""Returns { normalized_file_path: {"sha256", "size"} }。LMが使えなければ {}。"""
prefix = _LM_PREFIX.get(model_type)
if not prefix:
return {}
out = {}
try:
page = 1
while page <= _MAX_PAGES:
url = f"{origin}/api/lm/{prefix}/list?page={page}&page_size={_PAGE_SIZE}"
with urlopen(url, timeout=_TIMEOUT) as resp:
data = json.loads(resp.read().decode("utf-8"))
for it in data.get("items", []):
sha, fp = it.get("sha256"), it.get("file_path")
if sha and fp and len(str(sha)) == 64:
out[_norm(fp)] = {"sha256": str(sha).lower(), "size": it.get("file_size")}
if page >= int(data.get("total_pages", 1) or 1):
break
page += 1
except Exception as e:
logger.info("Lora Manager hashes unavailable (%s): %s", prefix, e)
return {}
return out
+149 -25
View File
@@ -2,6 +2,7 @@
import json
import logging
import os
import shutil
import time
from datetime import datetime, timezone
@@ -41,32 +42,126 @@ MODEL_TYPE_FOLDER_KEYS = {
}
def _iter_files(root):
"""root 配下の全ファイルを返す。フォルダのシンボリックリンク/ジャンクションも辿る。
リンクが祖先フォルダを指していて循環する場合のみ、その枝には入らない
(rglob だとパス長上限まで再帰し続ける恐れがある)。
"""
def walk(d, ancestors):
try:
entries = list(os.scandir(d))
except OSError:
return
for e in entries:
try:
if e.is_dir(): # リンクは辿る
real = os.path.realpath(e.path)
if real in ancestors:
logger.warning("Skipping looping folder link: %s -> %s", e.path, real)
continue
yield from walk(e.path, ancestors | {real})
elif e.is_file():
yield Path(e.path)
except OSError:
continue
root = Path(root)
yield from walk(root, frozenset([os.path.realpath(root)]))
def _is_within(path, root):
"""path が root 配下か。`..` は正規化するが、リンクは解決しない(リンク先フォルダへの移動を許可)。"""
try:
a, r = os.path.abspath(path), os.path.abspath(root)
return os.path.commonpath([os.path.normcase(a), os.path.normcase(r)]) == os.path.normcase(r)
except ValueError: # 別ドライブなど
return False
# 追加モデルルート配下で探すサブフォルダ名(大小無視)。ComfyUI標準名 + Stability Matrix名
_EXTRA_ROOT_SUBDIRS = {
"checkpoint": ["checkpoints", "StableDiffusion"],
"lora": ["loras", "Lora"],
"vae": ["vae", "VAE"],
"controlnet": ["controlnet", "ControlNet"],
"unet": ["diffusion_models", "DiffusionModels", "unet"],
"textencoder": ["text_encoders", "TextEncoders", "clip"],
"hypernetwork": ["hypernetworks", "HyperNetworks"],
"embedding": ["embeddings", "Embeddings"],
}
def parse_extra_model_roots(value):
"""設定値(`;` または改行区切りの文字列)を重複なしのパス文字列リストにする。"""
if isinstance(value, (list, tuple)):
value = ";".join(str(v) for v in value)
parts = str(value or "").replace("\n", ";").split(";")
seen, out = set(), []
for p in parts:
p = p.strip().strip('"')
if p and p not in seen:
seen.add(p)
out.append(p)
return out
def _get_extra_model_dirs(model_type):
"""設定 `models_dir` で追加指定されたルート配下の、該当タイプのフォルダを返す。"""
names = _EXTRA_ROOT_SUBDIRS.get(model_type)
if not names:
return []
try:
from .settings_service import SettingsService
roots = parse_extra_model_roots(SettingsService().load().get("models_dir", ""))
except Exception:
return []
wanted = {n.lower() for n in names}
found = []
for root in roots:
try:
for e in os.scandir(root):
if e.is_dir() and e.name.lower() in wanted:
found.append(Path(e.path))
except OSError:
logger.warning("Configured models_dir not accessible: %s", root)
return found
def _get_model_dirs(model_type):
"""Get all model directories for a type using ComfyUI's folder_paths.
Returns a list of Path objects for all configured model directories
(includes extra_model_paths.yaml settings).
(includes extra_model_paths.yaml settings and the `models_dir` setting).
Falls back to plugin-relative path if folder_paths is unavailable.
"""
folder_key = MODEL_TYPE_FOLDER_KEYS.get(model_type)
if not folder_key:
return []
result = []
try:
import folder_paths # type: ignore # ComfyUI module
paths = folder_paths.get_folder_paths(folder_key)
result = [Path(p) for p in paths if Path(p).is_dir()]
if result:
return result
except Exception as e:
logger.debug("folder_paths unavailable (%s), using fallback", e)
# Fallback: custom_nodes/../../models/{folder_key}
plugin_dir = Path(__file__).resolve().parent.parent.parent
models_dir = plugin_dir.parent.parent / "models" / folder_key
if models_dir.is_dir():
return [models_dir]
return []
if not result:
# Fallback: custom_nodes/../../models/{folder_key}
plugin_dir = Path(__file__).resolve().parent.parent.parent
models_dir = plugin_dir.parent.parent / "models" / folder_key
if models_dir.is_dir():
result = [models_dir]
# 設定で追加されたルート(既存と同一実体は除外)
known = {os.path.normcase(os.path.realpath(p)) for p in result}
for d in _get_extra_model_dirs(model_type):
key = os.path.normcase(os.path.realpath(d))
if key not in known:
known.add(key)
result.append(d)
return result
class ModelsService:
@@ -111,6 +206,12 @@ class ModelsService:
entry["sha256"] = updates["sha256"]
if "badges" in updates:
entry["badges"] = updates["badges"]
if "civitaiNotFound" in updates:
# CivitAIに存在しなかった記録(一括取得のスキップ用)。None/False で解除
if updates["civitaiNotFound"]:
entry["civitaiNotFound"] = self._now_iso()
else:
entry.pop("civitaiNotFound", None)
entry["updatedAt"] = self._now_iso()
data[model_name] = entry
self._save_metadata(data)
@@ -131,9 +232,7 @@ class ModelsService:
for d in dirs:
if not d.is_dir():
continue
for f in d.rglob("*"):
if not f.is_file():
continue
for f in _iter_files(d):
try:
rel = str(f.relative_to(d)).replace("\\", "/")
if rel.endswith(_DISABLED_SUFFIX):
@@ -145,17 +244,16 @@ class ModelsService:
self._scan_cache[model_type] = (now, names)
return names
def list_model_files(self, model_type: str) -> list:
def list_model_files(self, model_type: str, extra_only: bool = False) -> list:
"""モデルタイプのモデルファイル名をソートして返す(拡張子付き、/区切り)。
プレビュー画像やサイドカーファイルを除外し、モデル拡張子のみを返す。"""
dirs = _get_model_dirs(model_type)
プレビュー画像やサイドカーファイルを除外し、モデル拡張子のみを返す。
extra_only=True なら設定 models_dir で追加されたフォルダのみ対象。"""
dirs = _get_extra_model_dirs(model_type) if extra_only else _get_model_dirs(model_type)
seen = set()
for d in dirs:
if not d.is_dir():
continue
for f in d.rglob("*"):
if not f.is_file():
continue
for f in _iter_files(d):
name = f.name
if name.endswith(_DISABLED_SUFFIX):
name = name[: -len(_DISABLED_SUFFIX)]
@@ -280,8 +378,8 @@ class ModelsService:
for d in dirs:
if not d.is_dir():
continue
for f in d.rglob("*"):
if f.is_file() and f.name.endswith(_DISABLED_SUFFIX):
for f in _iter_files(d):
if f.name.endswith(_DISABLED_SUFFIX):
try:
rel = str(f.relative_to(d))
if rel.endswith(_DISABLED_SUFFIX):
@@ -291,6 +389,32 @@ class ModelsService:
pass
return disabled
def list_preview_keys(self, model_type):
"""プレビュー画像を持つモデルのキー(`サブフォルダ/ファイル名(拡張子なし)`、小文字・/区切り)を返す。
一覧表示で「プレビューが無いモデルには画像リクエストを出さない」ために、フォルダを1回走査して求める
(画像ごとの404リクエストと接続の開閉を避ける)。判定は find_preview_image と同じ拡張子・サイズ条件。
"""
keys = set()
for d in _get_model_dirs(model_type):
if not d.is_dir():
continue
for f in _iter_files(d):
lname = f.name.lower()
exts = [e for e in _PREVIEW_EXTENSIONS if lname.endswith(e)]
if not exts:
continue
try:
if f.stat().st_size < 100:
continue
parent = str(f.parent.relative_to(d)).replace("\\", "/")
except (OSError, ValueError):
continue
prefix = "" if parent == "." else parent.lower() + "/"
for e in exts:
keys.add(prefix + lname[: -len(e)])
return sorted(keys)
def find_preview_image(self, model_type, model_name):
"""Find preview image for a model file.
@@ -311,7 +435,8 @@ class ModelsService:
for type_dir in dirs:
# model_name can include subdirectory (e.g., "subdir/model.safetensors")
model_path = type_dir / model_name
if not model_path.is_file():
# 無効化されたモデル(<name>.disabled)でも、隣のプレビュー画像は探す
if not model_path.is_file() and not (type_dir / (model_name + _DISABLED_SUFFIX)).is_file():
continue
stem = model_path.stem
@@ -436,11 +561,10 @@ class ModelsService:
errors.append({"model": model_name, "error": "Cannot determine root directory"})
continue
# Destination directory — verify it stays within root_dir after resolution
# Destination directory — verify it stays within root_dir (`..`/絶対パスは拒否。
# フォルダのシンボリックリンク/ジャンクション配下への移動は許可する)
dest_dir = root_dir / dest_subdir if dest_subdir else root_dir
try:
dest_dir.resolve().relative_to(root_dir.resolve())
except ValueError:
if not _is_within(dest_dir, root_dir):
errors.append({"model": model_name, "error": "Destination is outside model root"})
continue
dest_dir.mkdir(parents=True, exist_ok=True)
+13 -23
View File
@@ -13,7 +13,7 @@ import urllib.error
import urllib.request
from pathlib import Path
from typing import Optional
from urllib.parse import urlparse
from .url_guard import HINT as _URL_HINT, is_allowed_backend_url, urlopen as _guarded_urlopen
import numpy as np
from PIL import Image, ImageOps, PngImagePlugin
@@ -22,19 +22,9 @@ logger = logging.getLogger(__name__)
_model_lock = threading.Lock()
# Unsloth requires an Authorization: Bearer <UNSLOTH_API_KEY> header even for
# local access. api_url is client-supplied per request, so without a host
# check a client could point it at an arbitrary server and exfiltrate the key
# (SSRF). Mirrors unsloth_routes.py's _is_allowed_base_url/_ALLOWED_HOSTS.
_UNSLOTH_ALLOWED_HOSTS = {"localhost", "127.0.0.1", "::1"}
def _is_allowed_unsloth_url(api_url: str) -> bool:
try:
parsed = urlparse(api_url)
return parsed.scheme in ("http", "https") and parsed.hostname in _UNSLOTH_ALLOWED_HOSTS
except Exception:
return False
# api_url is client-supplied per request, so every backend (Ollama / OpenAI-compatible / Unsloth)
# goes through url_guard: loopback or WFS_ALLOWED_BACKEND_HOSTS only, no redirects. This also
# stops the Unsloth API key (Authorization header) from being sent to an arbitrary server.
class TaggerService:
@@ -279,22 +269,22 @@ class TaggerService:
def vlm_models(self, backend: str, api_url: str) -> list:
backend = (backend or "ollama").lower()
try:
if not is_allowed_backend_url(api_url):
logger.error("vlm_models: %s", _URL_HINT)
return []
if backend == "ollama":
req = urllib.request.Request(api_url.rstrip("/") + "/api/tags")
with urllib.request.urlopen(req, timeout=5) as resp:
with _guarded_urlopen(req, timeout=5) as resp:
data = json.loads(resp.read().decode("utf-8"))
return sorted(m["name"] for m in data.get("models", []))
headers = {}
if backend == "unsloth":
if not _is_allowed_unsloth_url(api_url):
logger.error("vlm_models: Unsloth backend URL must point to localhost/127.0.0.1/::1")
return []
key = self._unsloth_api_key()
if key:
headers["Authorization"] = f"Bearer {key}"
req = urllib.request.Request(api_url.rstrip("/") + "/v1/models", headers=headers)
with urllib.request.urlopen(req, timeout=5) as resp:
with _guarded_urlopen(req, timeout=5) as resp:
data = json.loads(resp.read().decode("utf-8"))
return sorted(m["id"] for m in data.get("data", []))
except Exception as e:
@@ -309,6 +299,8 @@ class TaggerService:
thinking_mode: bool = False, max_tokens: int = 0) -> dict:
backend = (backend or "ollama").lower()
try:
if not is_allowed_backend_url(api_url):
return {"error": _URL_HINT}
if backend == "ollama":
body = {
"model": model,
@@ -326,14 +318,12 @@ class TaggerService:
headers={"Content-Type": "application/json"},
method="POST",
)
with urllib.request.urlopen(req, timeout=180) as resp:
with _guarded_urlopen(req, timeout=180) as resp:
data = json.loads(resp.read().decode("utf-8"))
content = data.get("message", {}).get("content", "")
else:
headers = {"Content-Type": "application/json"}
if backend == "unsloth":
if not _is_allowed_unsloth_url(api_url):
return {"error": "Unsloth backend URL must point to localhost/127.0.0.1/::1"}
key = self._unsloth_api_key()
if key:
headers["Authorization"] = f"Bearer {key}"
@@ -354,7 +344,7 @@ class TaggerService:
headers=headers,
method="POST",
)
with urllib.request.urlopen(req, timeout=180) as resp:
with _guarded_urlopen(req, timeout=180) as resp:
data = json.loads(resp.read().decode("utf-8"))
message = data.get("choices", [{}])[0].get("message", {})
content = message.get("content", "")
+68
View File
@@ -0,0 +1,68 @@
"""Outbound URL guard for backend proxies (SSRF mitigation).
Several routes (Ollama chat, Tagger VLM, Eagle, Unsloth relay) connect to a backend whose
address is supplied by the browser. Without a check, any caller that can reach ComfyUI could
make the server connect to an arbitrary host (cloud metadata, LAN services, file://).
Allowed targets:
- loopback hosts (localhost / 127.0.0.1 / ::1), any port
- hosts listed by the operator in the WFS_ALLOWED_BACKEND_HOSTS environment variable
(comma-separated "host" or "host:port"; e.g. "192.168.1.20:11434,gpu-box")
Only http(s) URLs without credentials are accepted, and redirects are never followed.
"""
import os
import urllib.request
from urllib.parse import urlparse
LOOPBACK_HOSTS = {"localhost", "127.0.0.1", "::1"}
ALLOWED_HOSTS_ENV = "WFS_ALLOWED_BACKEND_HOSTS"
HINT = (
"Backend URL must point to localhost/127.0.0.1/::1. To use another host, list it in the "
f"{ALLOWED_HOSTS_ENV} environment variable (e.g. 192.168.1.20:11434) and restart ComfyUI."
)
def _operator_allowlist():
raw = os.environ.get(ALLOWED_HOSTS_ENV, "")
return {item.strip().lower() for item in raw.split(",") if item.strip()}
def is_allowed_backend_url(url):
"""True if url is an http(s) URL without credentials whose host[:port] is permitted."""
try:
parsed = urlparse((url or "").strip())
if parsed.scheme not in ("http", "https") or not parsed.hostname:
return False
if parsed.username or parsed.password:
return False
host = parsed.hostname.lower()
if host in LOOPBACK_HOSTS:
return True
allow = _operator_allowlist()
return host in allow or (parsed.port is not None and f"{host}:{parsed.port}" in allow)
except Exception:
return False
def require_backend_url(url):
"""Return url stripped of trailing slashes, or raise ValueError(HINT)."""
url = (url or "").strip()
if not is_allowed_backend_url(url):
raise ValueError(HINT)
return url.rstrip("/")
class _NoRedirect(urllib.request.HTTPRedirectHandler):
def redirect_request(self, *args, **kwargs):
return None
_opener = urllib.request.build_opener(_NoRedirect)
def urlopen(req, timeout):
"""urllib urlopen that never follows redirects (a 3xx surfaces as HTTPError)."""
return _opener.open(req, timeout=timeout)
+130 -4
View File
@@ -101,6 +101,104 @@ def _render_text_layer(width: int, height: int, ov: dict):
return layer
def _fit_layer(img, base_w: int, base_h: int, pip: dict):
"""Scales a picture-in-picture frame to its target width (a fraction of the
base frame's width, aspect preserved), applies opacity, and returns
(layer, left, top) with the position of its top-left corner on the base
frame (pip["x"]/["y"] are the layer's centre as fractions of the frame)."""
layer = img.convert("RGBA")
pw = max(2, int(round(float(pip["scale"]) * base_w)))
ph = max(2, int(round(pw * layer.height / max(1, layer.width))))
layer = layer.resize((pw, ph), _RESAMPLE)
opacity = float(pip.get("opacity", 1.0))
if opacity < 0.999:
layer.putalpha(layer.getchannel("A").point(lambda a: int(a * opacity)))
left = int(round(float(pip["x"]) * base_w - pw / 2))
top = int(round(float(pip["y"]) * base_h - ph / 2))
return layer, left, top
class _PipSource:
"""One overlay clip's frame source. Images are decoded once; videos are
decoded sequentially (seek once to the in-file start, then only forward),
since the base video is also processed strictly in time order. After a
video's last frame it holds that frame until the overlay's end."""
def __init__(self, path: Path, pip: dict, base_w: int, base_h: int):
import av # type: ignore
self.pip = pip
self.base_w, self.base_h = base_w, base_h
self.start = float(pip["start"])
self.end = self.start + float(pip["length"])
self.src_start = max(0.0, float(pip.get("src_start") or 0.0))
self.container = None
self._cache_key = None
self._cache = None
if pip.get("kind") == "image":
with Image.open(path) as im:
im.load()
self.static = _fit_layer(im, base_w, base_h, pip)
else:
self.static = None
self.container = av.open(str(path))
self.stream = self.container.streams.video[0]
if self.src_start > 0.05:
self.container.seek(int(self.src_start * 1_000_000))
self.gen = self.container.decode(self.stream)
self.cur = None
self.nxt = None
self.done = False
def _time(self, frame) -> float:
return float(frame.pts * self.stream.time_base) if frame.pts is not None else 0.0
def layer_at(self, t: float):
"""(layer, left, top) for timeline time t, or None when inactive."""
if not (self.start <= t < self.end):
return None
if self.static is not None:
return self.static
target = self.src_start + (t - self.start)
while True:
if self.nxt is None and not self.done:
try:
self.nxt = next(self.gen)
except StopIteration:
self.done = True
if self.nxt is not None and self._time(self.nxt) <= target + 1e-3:
self.cur, self.nxt = self.nxt, None
continue
break
frame = self.cur or self.nxt
if frame is None:
return None
key = id(frame)
if key != self._cache_key:
self._cache = _fit_layer(frame.to_image(), self.base_w, self.base_h, self.pip)
self._cache_key = key
return self._cache
def close(self):
if self.container is not None:
self.container.close()
self.container = None
def _paste_layer(base, layer, left: int, top: int):
"""Alpha-composites `layer` onto the RGBA `base` at (left, top), clipping
whatever falls outside the frame (a plain alpha_composite() dest can't be
negative)."""
x0, y0 = max(0, left), max(0, top)
x1, y1 = min(base.width, left + layer.width), min(base.height, top + layer.height)
if x1 <= x0 or y1 <= y0:
return
piece = layer.crop((x0 - left, y0 - top, x1 - left, y1 - top))
region = base.crop((x0, y0, x1, y1))
region.alpha_composite(piece)
base.paste(region, (x0, y0))
class VideoService:
def _resolve_media_path(self, filename: str, subfolder: str, type_: str) -> Path:
"""Resolves a ComfyUI-style {filename, subfolder, type} reference to an
@@ -248,8 +346,11 @@ class VideoService:
overlays: list,
filename_prefix: str = "video/wfm_edit",
delete_source: bool = False,
pips: list = None,
) -> dict:
"""Burns timed text overlays into a video (Video Edit tab, Phase 3).
"""Burns timed text overlays - and picture-in-picture overlay clips
(video or image, placed/scaled/faded on the frame) - into a video
(Video Edit tab, Phase 3 + overlay track).
ComfyUI core has no time-ranged video text node (core TextOverlay draws
on every frame of an IMAGE batch, top/bottom only), and routing the
@@ -262,6 +363,12 @@ class VideoService:
overlays: [{text, start, end, font_size (% of frame height), color,
anchor ("<top|middle|bottom>-<left|center|right>"), outline, background}]
with start/end in seconds from the start of the video.
pips: [{filename, subfolder, type (input), kind ("video"|"image"),
src_start (in-file start, s), start (timeline s), length (s),
x, y (centre, fractions of the frame), scale (width as a fraction of
the frame width), opacity (0..1)}]. Overlay audio is not mixed.
Pips are drawn first (in list order), then text on top.
"""
import av # type: ignore
import folder_paths # type: ignore
@@ -276,8 +383,20 @@ class VideoService:
continue
if end > start and str(ov.get("text") or "").strip():
items.append((start, end, ov))
if not items:
raise ValueError("No valid text overlays")
valid_pips = []
for pip in pips or []:
try:
if float(pip["length"]) > 0 and float(pip["scale"]) > 0 and pip.get("filename"):
valid_pips.append(pip)
except (KeyError, TypeError, ValueError):
continue
if not items and not valid_pips:
raise ValueError("No valid text or overlay clips")
# Resolve overlay files up front so a missing one fails before any encoding.
pip_paths = [
self._resolve_media_path(p["filename"], p.get("subfolder", ""), p.get("type", "input"))
for p in valid_pips
]
output_dir = folder_paths.get_output_directory()
full_output_folder, out_filename, counter, out_subfolder, _ = folder_paths.get_save_image_path(filename_prefix, output_dir)
@@ -286,12 +405,14 @@ class VideoService:
in_c = av.open(str(src_path))
out_c = None
pip_sources = []
try:
in_v = in_c.streams.video[0]
in_a = in_c.streams.audio[0] if in_c.streams.audio else None
width, height = in_v.codec_context.width, in_v.codec_context.height
rate = in_v.average_rate or in_v.guessed_rate or 24
pip_sources = [_PipSource(path, pip, width, height) for path, pip in zip(pip_paths, valid_pips)]
layers = [(s, e, _render_text_layer(width, height, ov)) for s, e, ov in items]
out_c = av.open(str(save_path), mode="w")
@@ -317,8 +438,11 @@ class VideoService:
first_pts = frame.pts
t = float((frame.pts - first_pts) * in_v.time_base) if frame.pts is not None else index / float(rate)
active = [layer for s, e, layer in layers if s <= t < e]
if active:
pip_layers = [pl for pl in (src.layer_at(t) for src in pip_sources) if pl is not None]
if active or pip_layers:
img = frame.to_image().convert("RGBA")
for layer, left, top in pip_layers:
_paste_layer(img, layer, left, top)
for layer in active:
img.alpha_composite(layer)
out_frame = av.VideoFrame.from_image(img.convert("RGB"))
@@ -340,6 +464,8 @@ class VideoService:
finally:
if out_c is not None:
out_c.close()
for src in pip_sources:
src.close()
in_c.close()
# The export graph's intermediate file is only deleted when the caller
+1 -1
View File
@@ -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.7.7"
version = "0.7.12"
license = { file = "LICENSE" }
requires-python = ">= 3.10"
dependencies = ["jinja2"]
+128
View File
@@ -409,6 +409,78 @@
flex: none; /* stay a fixed-height full-width bar; never shrink/stretch with clip content */
}
/* ── Edit: トラック切替(ビデオ=青/テキスト=緑/オーディオ=赤)──
--wfm-track-color は表示中トラックの色。トラックバーの枠線・ブロックの帯色に使う。
ビデオ色はテーマ可変の--wfm-primaryではなく固定の青にして、他トラックと並べても色が変わらないようにする。 */
.wfm-video-edit-track-tabs {
display: flex;
gap: 4px;
margin-bottom: 4px;
}
.wfm-video-edit-track-tab {
--tab-color: var(--wfm-track-video);
border-bottom: 2px solid var(--tab-color);
}
.wfm-video-edit-track-tab[data-track="video"] { --tab-color: var(--wfm-track-video); }
.wfm-video-edit-track-tab[data-track="pip"] { --tab-color: var(--wfm-track-video); }
.wfm-video-edit-track-tab[data-track="text"] { --tab-color: var(--wfm-track-text); }
.wfm-video-edit-track-tab[data-track="audio"] { --tab-color: var(--wfm-track-audio); }
.wfm-video-edit-track-tab.active {
background: var(--tab-color);
border-color: var(--tab-color);
color: #fff;
}
.wfm-video-edit-timeline-track {
--wfm-track-video: #4a9eff;
--wfm-track-text: #3fb950;
--wfm-track-audio: #f85149;
--wfm-track-color: var(--wfm-track-video);
}
.wfm-video-edit-track-tabs { --wfm-track-video: #4a9eff; --wfm-track-text: #3fb950; --wfm-track-audio: #f85149; }
.wfm-video-edit-timeline-track[data-track="pip"] { --wfm-track-color: var(--wfm-track-video); }
.wfm-video-edit-timeline-track[data-track="text"] { --wfm-track-color: var(--wfm-track-text); }
.wfm-video-edit-timeline-track[data-track="audio"] { --wfm-track-color: var(--wfm-track-audio); }
.wfm-video-edit-timeline-track[data-track="pip"],
.wfm-video-edit-timeline-track[data-track="text"],
.wfm-video-edit-timeline-track[data-track="audio"] { border-color: var(--wfm-track-color); }
.wfm-video-edit-timeline-track[data-track="video"] .wfm-video-edit-timeline-block {
border-left: 3px solid var(--wfm-track-color);
}
/* テキスト/オーディオ表示: 絶対時間(秒×px/秒)で配置するレーン */
.wfm-video-edit-lane {
position: relative;
flex: none;
min-height: 100%;
}
.wfm-video-edit-lane-clipband {
position: absolute;
top: 0;
bottom: 0;
border-left: 1px dashed var(--wfm-border);
box-sizing: border-box;
cursor: pointer;
}
.wfm-video-edit-lane-clipband.selected { background: rgba(255, 255, 255, 0.06); }
.wfm-video-edit-lane-item {
position: absolute;
height: 20px;
box-sizing: border-box;
padding: 0 6px;
border-radius: 3px;
background: color-mix(in srgb, var(--wfm-track-color) 35%, transparent);
border: 1px solid var(--wfm-track-color);
font-size: 11px;
line-height: 18px;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
cursor: pointer;
}
.wfm-video-edit-lane-item.selected { background: var(--wfm-track-color); color: #fff; }
.wfm-video-edit-lane-item.dim { opacity: 0.55; }
.wfm-video-edit-timeline-placeholder {
display: flex;
align-items: center;
@@ -1041,3 +1113,59 @@
}
.wfm-video-project-item-delete:hover { color: var(--wfm-danger); }
/* ── Edit: 追加サウンド(オーディオトラックに配置する効果音など)のリスト ── */
.wfm-video-edit-sound-head { margin-top: 8px; }
.wfm-video-edit-sound-list { display: flex; flex-direction: column; gap: 6px; margin-top: 6px; }
.wfm-video-edit-sound-row {
padding: 4px 6px;
border: 1px solid var(--wfm-border);
border-left: 3px solid #f85149;
border-radius: 3px;
}
.wfm-video-edit-sound-row-head { display: flex; align-items: center; gap: 6px; }
.wfm-video-edit-sound-name { flex: 1; min-width: 0; font-size: 11px; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
.wfm-video-edit-sound-grid { display: grid; grid-template-columns: repeat(3, minmax(0, 1fr)); gap: 4px; margin-top: 4px; }
.wfm-video-edit-sound-grid label { display: flex; flex-direction: column; font-size: 10px; color: var(--wfm-text-secondary); }
.wfm-video-edit-sound-grid input { min-width: 0; }
/* ── Edit: オーバーレイクリップ(PinP)パネル・プレビュー枠 ── */
.wfm-video-edit-pip-panel { margin-bottom: 10px; }
.wfm-video-edit-pip-row { border-left-color: #4a9eff; }
.wfm-video-edit-pip-preset { width: auto; max-width: 96px; padding: 0 2px; font-size: 10px; }
.wfm-video-edit-pip-box {
position: absolute;
box-sizing: border-box;
border: 1px dashed #4a9eff;
background: rgba(74, 158, 255, 0.15);
overflow: hidden;
}
.wfm-video-edit-pip-box img { width: 100%; height: 100%; object-fit: fill; display: block; pointer-events: none; }
/* ── Edit: ツールメニューはトラック表示(data-view)に連動 ──
video=トリム+クロップ / text=テキストオーバーレイ / pip=オーバーレイクリップ / audio=オーディオ。
書き出し(右の固定パネル)は常に表示。 */
.wfm-video-edit-tools { flex: 1; min-width: 0; }
.wfm-video-edit-tools .wfm-video-edit-pip-panel,
.wfm-video-edit-tools .wfm-video-edit-audio-panel { display: none; max-width: 480px; margin-top: 0; padding-top: 0; border-top: none; }
.wfm-video-edit-tools[data-view="pip"] .wfm-video-edit-pip-panel,
.wfm-video-edit-tools[data-view="audio"] .wfm-video-edit-audio-panel { display: block; }
.wfm-video-edit-tools[data-view="pip"] .wfm-video-edit-trim-panel,
.wfm-video-edit-tools[data-view="audio"] .wfm-video-edit-trim-panel { display: none; }
.wfm-video-edit-tools[data-view="video"] .wfm-video-edit-tool-text,
.wfm-video-edit-tools[data-view="text"] .wfm-video-edit-tool-trim { display: none; }
.wfm-video-edit-tools[data-view="text"] .wfm-video-edit-text-section { margin-top: 0; }
/* 透明な本物の<input type=file>をボタンに重ねる方式(label+display:none経由に頼らない) */
.wfm-video-edit-file-overlay { position: relative; overflow: hidden; }
.wfm-video-edit-file-overlay > input[type="file"] {
position: absolute;
inset: 0;
width: 100%;
height: 100%;
margin: 0;
padding: 0;
opacity: 0;
cursor: pointer;
font-size: 0;
}
+1
View File
@@ -557,6 +557,7 @@ function applyI18nToHtml() {
"wfm-help-settings-18": "helpSettings18", "wfm-help-settings-19": "helpSettings19",
"wfm-help-settings-20": "helpSettings20", "wfm-help-settings-21": "helpSettings21",
"wfm-help-settings-22": "helpSettings22",
"wfm-help-settings-23": "helpSettings23", "wfm-help-settings-24": "helpSettings24",
"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",
+164 -26
View File
File diff suppressed because one or more lines are too long
+12 -1
View File
@@ -13,6 +13,7 @@ import { openBadgeEditModal, renderBadgeFilter, setGridChangeCallback } from "./
import { isModelDisabled, renderTagFilter, renderGroupFilter, renderDirFilter } from "./models/filters.js";
import { renderModelGrid, clearBatchGroup, clearStackGroup } from "./models/grid-view.js";
import { toggleSelectMode, renderBulkActionBar, fetchSubdirs } from "./models/selection-bulk.js";
import { fetchPreviewKeys } from "./models/helpers.js";
import { closeSidePanel, renderSideCivitai, renderSideInfo, batchFetchCivitai, fetchCivitaiCache } from "./models/detail-panel.js";
export { openBadgeEditModal };
@@ -302,7 +303,7 @@ async function loadModelsForCurrentType() {
if (!fetchFn) throw new Error("Unknown model type: " + type);
const [models, disabledList, groups] = await Promise.all([
fetchFn(), fetchDisabledModels(type), fetchModelGroups(),
fetchFn(), fetchDisabledModels(type), fetchModelGroups(), fetchPreviewKeys(type),
]);
const disabledSet = new Set(Array.isArray(disabledList) ? disabledList : []);
state.disabledModels[type] = disabledSet;
@@ -550,6 +551,16 @@ export function initModelsTab() {
document.getElementById("wfm-models-civitai-batch-btn")?.addEventListener("click", () => {
batchFetchCivitai();
});
// Skip models already known to be missing on CivitAI (persisted per browser)
const skipNfEl = document.getElementById("wfm-models-civitai-skip-nf");
const skipNfLabel = document.getElementById("wfm-models-civitai-skip-nf-label");
if (skipNfLabel) skipNfLabel.textContent = t("civitaiSkipNotFound");
if (skipNfEl) {
skipNfEl.checked = localStorage.getItem("wfm_models_civitai_skip_nf") === "1";
skipNfEl.addEventListener("change", () => {
localStorage.setItem("wfm_models_civitai_skip_nf", skipNfEl.checked ? "1" : "0");
});
}
// Side panel tab switching
document.querySelectorAll(".wfm-models-side-tab-btn").forEach((btn) => {
+136
View File
@@ -0,0 +1,136 @@
/**
* Models Tab - Auto badges from CivitAI base model info
*
* CivitAI's `baseModel` is already a categorical string, so labels are derived
* with a deterministic rule table (variants such as "SDXL 1.0" / "SDXL Turbo"
* collapse into one family badge). Unknown strings fall back to the raw value.
* Apply semantics: model badges are appended (existing badges are kept);
* a label already in the palette gets its color overwritten (optional).
*/
import { openModal, closeModal, showToast } from "../app.js";
import { t } from "../i18n.js";
import { escapeHtml } from "../util.js";
import { state } from "./state.js";
import { getCurrentModels } from "./filters.js";
import { getBadgePalette, saveBadgePalette, renderBadgeFilter } from "./badges.js";
import { renderModelGrid } from "./grid-view.js";
import { saveModelMetadata } from "../models-tab.js";
// [pattern, label, color] — first match wins, so specific families come first.
const FAMILY_RULES = [
[/^pony/i, "Pony", "#d946ef"],
[/^illustrious/i, "Illustrious", "#f59e0b"],
[/^noobai/i, "NoobAI", "#14b8a6"],
[/^sdxl|^sd ?xl/i, "SDXL", "#3b82f6"],
[/^sd ?1\.[45]/i, "SD1.5", "#22c55e"],
[/^sd ?2/i, "SD2", "#84cc16"],
[/^sd ?3/i, "SD3", "#06b6d4"],
[/^flux\.?1|^flux$/i, "Flux.1", "#ef4444"],
[/^flux\.?2/i, "Flux.2", "#dc2626"],
[/^qwen/i, "Qwen", "#8b5cf6"],
[/^wan/i, "Wan", "#0ea5e9"],
[/^z-?image/i, "Z-Image", "#ec4899"],
[/^hidream/i, "HiDream", "#f97316"],
[/^hunyuan/i, "Hunyuan", "#6366f1"],
[/^chroma/i, "Chroma", "#a855f7"],
[/^lumina/i, "Lumina", "#10b981"],
[/^auraflow/i, "AuraFlow", "#64748b"],
[/^kolors/i, "Kolors", "#e11d48"],
];
const SKIP_VALUES = new Set(["", "other", "unknown"]);
const FALLBACK_COLORS = ["#0891b2", "#7c3aed", "#be185d", "#b45309", "#4d7c0f", "#475569"];
export function baseModelToBadge(baseModel) {
const raw = (baseModel || "").trim();
if (SKIP_VALUES.has(raw.toLowerCase())) return null;
for (const [re, label, color] of FAMILY_RULES) {
if (re.test(raw)) return { label, color };
}
let h = 0;
for (const ch of raw) h = (h * 31 + ch.charCodeAt(0)) >>> 0;
return { label: raw, color: FALLBACK_COLORS[h % FALLBACK_COLORS.length] };
}
/** Scan current-type models → { assignments: [{model, label}], labels: Map(label → {color, count}) } */
function buildPlan() {
const assignments = [];
const labels = new Map();
let noInfo = 0;
for (const m of getCurrentModels()) {
const sha = state.modelMetadata[m]?.sha256;
const civ = sha && state.civitaiCache[sha];
const badge = civ ? baseModelToBadge(civ.baseModel) : null;
if (!badge) { noInfo++; continue; }
assignments.push({ model: m, label: badge.label });
const entry = labels.get(badge.label) || { color: badge.color, count: 0 };
entry.count++;
labels.set(badge.label, entry);
}
return { assignments, labels, noInfo };
}
export function openAutoBadgeModal(onDone = null) {
const { assignments, labels, noInfo } = buildPlan();
if (assignments.length === 0) {
showToast(t("autoBadgeNoData"), "warning");
return;
}
const palette = getBadgePalette();
const rows = [...labels.entries()].sort((a, b) => b[1].count - a[1].count).map(([label, info]) => {
const exists = label in palette;
return `<div class="wfm-badge-color-row">
<span class="wfm-badge wfm-badge-model" style="background:${info.color};color:#fff;">${escapeHtml(label)}</span>
<span style="font-size:12px;">${info.count}</span>
<span style="font-size:11px;color:var(--wfm-text-secondary);">${exists ? t("autoBadgeExisting") : t("autoBadgeNew")}</span>
</div>`;
}).join("");
openModal(t("autoBadgeTitle"), `
<div style="min-width:340px;">
<p style="font-size:12px;color:var(--wfm-text-secondary);margin:0 0 8px;">${t("autoBadgeDesc")}</p>
${rows}
<p style="font-size:11px;color:var(--wfm-text-secondary);">${t("autoBadgeNoInfo")}: ${noInfo}</p>
<label style="font-size:12px;display:block;margin:8px 0;">
<input type="checkbox" id="wfm-auto-badge-overwrite" checked> ${t("autoBadgeOverwrite")}
</label>
<label style="font-size:12px;display:block;margin:8px 0;">
<input type="checkbox" id="wfm-auto-badge-skip"> ${t("autoBadgeSkipExisting")}
</label>
<button class="wfm-btn wfm-btn-sm wfm-btn-primary" id="wfm-auto-badge-apply">${t("autoBadgeApply")} (${assignments.length})</button>
</div>`);
const hasBadges = (m) => (state.modelMetadata[m]?.badges || []).length > 0;
const targets = () => document.getElementById("wfm-auto-badge-skip")?.checked
? assignments.filter(({ model }) => !hasBadges(model)) : assignments;
document.getElementById("wfm-auto-badge-skip")?.addEventListener("change", () => {
const btn = document.getElementById("wfm-auto-badge-apply");
if (btn) btn.textContent = `${t("autoBadgeApply")} (${targets().length})`;
});
document.getElementById("wfm-auto-badge-apply")?.addEventListener("click", async (e) => {
e.target.disabled = true;
const overwrite = document.getElementById("wfm-auto-badge-overwrite")?.checked;
const target = targets();
const pal = getBadgePalette();
const usedLabels = new Set(target.map((a) => a.label));
for (const [label, info] of labels) {
if (!usedLabels.has(label)) continue;
if (!(label in pal) || overwrite) pal[label] = info.color;
}
saveBadgePalette(pal);
const todo = target.filter(({ model, label }) => !(state.modelMetadata[model]?.badges || []).includes(label));
for (let i = 0; i < todo.length; i += 8) {
await Promise.all(todo.slice(i, i + 8).map(({ model, label }) => {
const badges = [...(state.modelMetadata[model]?.badges || []), label];
return saveModelMetadata(model, { badges });
}));
}
renderBadgeFilter();
renderModelGrid();
showToast(`${todo.length} ${t("autoBadgeDone")}`, "success");
closeModal();
if (onDone) onDone();
});
}
+8
View File
@@ -6,6 +6,7 @@ import { openModal } from "../app.js";
import { t } from "../i18n.js";
import { escapeHtml, readJsonStorage } from "../util.js";
import { state } from "./state.js";
import { openAutoBadgeModal } from "./auto-badge.js";
// Grid re-render is owned by models-tab.js (grid rendering hasn't been split
// out yet); registered once from initModelsTab() to avoid a circular import.
@@ -61,6 +62,9 @@ export function openBadgeEditModal(onPaletteChange = null) {
<input type="color" id="wfm-badge-new-color" value="#6366f1" style="width:36px;height:28px;padding:1px;border-radius:4px;cursor:pointer;">
<button class="wfm-btn wfm-btn-sm wfm-btn-primary" id="wfm-badge-add-btn">${t("badgeAdd")}</button>
</div>
<div style="margin-top:8px;">
<button class="wfm-btn wfm-btn-sm" id="wfm-badge-auto-btn" title="${t("autoBadgeDesc")}">&#10024; ${t("autoBadgeTitle")}</button>
</div>
</div>`;
openModal(t("badgeManage"), html);
@@ -93,6 +97,10 @@ function bindBadgeModalEvents(onPaletteChange = null) {
bindBadgeRowEvents(refreshList, afterChange);
document.getElementById("wfm-badge-auto-btn")?.addEventListener("click", () => {
openAutoBadgeModal(onPaletteChange);
});
document.getElementById("wfm-badge-add-btn")?.addEventListener("click", () => {
const labelInput = document.getElementById("wfm-badge-new-label");
const colorInput = document.getElementById("wfm-badge-new-color");
+31 -43
View File
@@ -8,11 +8,11 @@
import { showToast, openModal, closeModal } from "../app.js";
import { t } from "../i18n.js";
import { escapeHtml } from "../util.js";
import { escapeHtml, sanitizeHtml, safeHttpUrl } from "../util.js";
import { state, RESERVED_GROUPS, GENUI_TYPE_MAP } from "./state.js";
import { getCurrentModels, renderTagFilter, renderDirFilter } from "./filters.js";
import { getBadgePalette, modelBadgesHtml, openBadgeEditModal } from "./badges.js";
import { parseModelPath, getExtension, getStem, loadPreviewImage, previewUrl } from "./helpers.js";
import { parseModelPath, getExtension, getStem, loadPreviewImage, previewUrl, markHasPreview, fetchPreviewKeys } from "./helpers.js";
import { renderModelGrid } from "./grid-view.js";
import {
applyToGenUI, applyEmbeddingToPrompt, saveModelMetadata, toggleGroupEnable,
@@ -200,6 +200,7 @@ export function openDetailModal(modelName) {
const res = await fetch("/api/wfm/models/change-preview", { method: "POST", body: fd });
const data = await res.json();
if (data.error) throw new Error(data.error);
markHasPreview(modelName);
// Reload preview in modal
const newUrl = previewUrl(modelName) + "&t=" + Date.now();
const mImg = document.querySelector(".wfm-modal-thumb-img");
@@ -308,12 +309,6 @@ export function renderSideInfo(modelName) {
</div>
</div>
</div>
<div class="wfm-node-detail-section">
<div class="wfm-node-detail-label">${t("modelsFilePath")}</div>
<div class="wfm-node-detail-value">
<span id="wfm-models-side-filepath" class="wfm-model-filepath" title="${t("modelsCopyPath")}" style="cursor:pointer;word-break:break-all;font-size:0.85em;color:#aaa;">${t("modelsLoading")}...</span>
</div>
</div>
<div class="wfm-node-detail-section">
<div class="wfm-node-detail-label">${t("modelsTags")}</div>
<div class="wfm-node-detail-value">
@@ -348,33 +343,6 @@ export function renderSideInfo(modelName) {
});
});
// Fetch and display file path
fetch(`/api/wfm/models/filepath?type=${encodeURIComponent(state.activeModelType)}&name=${encodeURIComponent(modelName)}`)
.then((r) => r.json())
.then((data) => {
const fpEl = document.getElementById("wfm-models-side-filepath");
if (fpEl && data.path) {
fpEl.textContent = data.path;
fpEl.title = t("modelsCopyPath");
} else if (fpEl) {
fpEl.textContent = modelName;
}
})
.catch(() => {
const fpEl = document.getElementById("wfm-models-side-filepath");
if (fpEl) fpEl.textContent = modelName;
});
// Copy file path on click
el.querySelector("#wfm-models-side-filepath")?.addEventListener("click", () => {
const fpEl = document.getElementById("wfm-models-side-filepath");
if (fpEl) {
navigator.clipboard.writeText(fpEl.textContent).then(() => {
showToast(t("modelsCopiedPath"), "success");
});
}
});
// Save button
el.querySelector("#wfm-models-side-save-btn")?.addEventListener("click", () => {
const tagsInput = document.getElementById("wfm-models-side-tags");
@@ -564,6 +532,15 @@ export function renderSideGroup(modelName) {
// ── Side Panel: CivitAI Tab ───────────────────────────────
// ハッシュ未計算を示す赤字の行(CivitAIタブ)。更新/取得ボタンでハッシュ計算して取得する
function hashMissingRowHtml() {
return `
<div style="display:flex;align-items:center;justify-content:center;font-size:12px;margin-bottom:10px;">
<span style="color:var(--wfm-text-secondary);margin-right:8px;">${t("civitaiHashLabel")}</span>
<span id="wfm-civitai-hash-missing" style="color:#e53935;font-weight:600;">${t("civitaiHashNotCalculated")}</span>
</div>`;
}
export function renderSideCivitai(modelName) {
const el = document.getElementById("wfm-models-side-civitai");
if (!el) return;
@@ -593,6 +570,7 @@ export function renderSideCivitai(modelName) {
} else {
el.innerHTML = `
<div style="padding:0 4px;text-align:center;">
${hashMissingRowHtml()}
<p style="color:var(--wfm-text-secondary);font-size:13px;margin-bottom:12px;">
${t("civitaiFetchDesc")}
</p>
@@ -629,6 +607,7 @@ export async function fetchCivitaiForModel(modelName, el) {
if (!state.modelMetadata[modelName]) state.modelMetadata[modelName] = {};
state.modelMetadata[modelName].sha256 = data.sha256;
}
if (data.preview_saved) markHasPreview(modelName);
renderCivitaiInfo(el, data.civitai, modelName);
showToast(t("civitaiFound"), "success");
// Always refresh preview: local file if saved, otherwise civitai image as fallback
@@ -640,7 +619,7 @@ export async function fetchCivitaiForModel(modelName, el) {
if (data.preview_saved) {
sideImg.src = previewUrl(modelName) + "&t=" + Date.now();
} else {
const civitaiImg = data.civitai.images && data.civitai.images[0];
const civitaiImg = safeHttpUrl(data.civitai.images && data.civitai.images[0]);
if (civitaiImg) sideImg.src = civitaiImg;
}
sideImg.style.display = "";
@@ -669,7 +648,7 @@ export function renderCivitaiInfo(el, info, modelName) {
? `https://${civitaiHost}/models/${info.modelId}?modelVersionId=${info.versionId}`
: info.versionId
? `https://${civitaiHost}/model-versions/${info.versionId}`
: (info.modelUrl || "#");
: safeHttpUrl(info.modelUrl, "#");
// Hash: BLAKE3 優先、なければ SHA256
const fileHashes = info.fileHashes || {};
@@ -700,7 +679,11 @@ export function renderCivitaiInfo(el, info, modelName) {
<code class="wfm-hash-value" data-hash="${escapeHtml(hashFull)}"
style="background:var(--wfm-bg-secondary);padding:2px 6px;border-radius:3px;cursor:pointer;font-size:11px;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;max-width:calc(100% - 84px);"
title="${t("civitaiCopyHash")}">${escapeHtml(hashType)}: ${escapeHtml(hashFull.substring(0, 16).toUpperCase())}…</code>
</div>` : "";
</div>` : `
<div style="${ROW}">
<span style="${LABEL}">${t("civitaiHashLabel")}</span>
<span style="color:#e53935;font-weight:600;">${t("civitaiHashNotCalculated")}</span>
</div>`;
const detailSection = (typeRow || baseModelRow || hashRow)
? `<div style="margin-bottom:10px;">${typeRow}${baseModelRow}${hashRow}</div>` : "";
@@ -714,7 +697,7 @@ export function renderCivitaiInfo(el, info, modelName) {
).join(" ");
// Sample images — all go to Sample pane
const images = info.images || [];
const images = (info.images || []).filter((u) => safeHttpUrl(u));
const sampleImagesHtml = images.map((url) =>
`<a href="${escapeHtml(url)}" target="_blank" rel="noopener" title="${t("civitaiOpenImage")}"><img src="${escapeHtml(url)}" style="width:100%;border-radius:4px;margin-bottom:6px;cursor:pointer;display:block;" loading="lazy" /></a>`
).join("");
@@ -744,7 +727,7 @@ export function renderCivitaiInfo(el, info, modelName) {
${detailSection}
${tagsHtml ? `<div style="margin-bottom:8px;">${tagsHtml}</div>` : ""}
${trainedWordsHtml ? `<div style="margin-bottom:10px;"><div style="font-weight:600;font-size:12px;margin-bottom:4px;">${t("civitaiTriggerWords")}</div>${trainedWordsHtml}</div>` : ""}
${info.description ? `<div style="font-size:12px;color:var(--wfm-text-secondary);line-height:1.5;max-height:120px;overflow-y:auto;">${info.description}</div>` : ""}
${info.description ? `<div style="font-size:12px;color:var(--wfm-text-secondary);line-height:1.5;max-height:120px;overflow-y:auto;">${sanitizeHtml(info.description)}</div>` : ""}
<div style="margin-top:10px;">
<button class="wfm-btn wfm-btn-sm" id="wfm-civitai-refresh-btn">${t("civitaiRefresh")}</button>
</div>
@@ -815,10 +798,13 @@ export async function batchFetchCivitai() {
}
// Filter out models that already have CivitAI data
// Optionally also skip models previously recorded as "not found on CivitAI"
const skipNotFound = document.getElementById("wfm-models-civitai-skip-nf")?.checked;
const meta = state.modelMetadata;
const uncached = models.filter((m) => {
const sha = meta[m]?.sha256;
return !sha || !state.civitaiCache[sha];
if (sha && state.civitaiCache[sha]) return false;
return !(skipNotFound && meta[m]?.civitaiNotFound);
});
if (uncached.length === 0) {
@@ -860,15 +846,16 @@ export async function batchFetchCivitai() {
const pct = data.total > 0 ? Math.round((data.current / data.total) * 100) : 0;
const statusText = data.status === "hashing" ? t("civitaiHashing2")
: data.status === "fetching" ? t("civitaiFetching")
: data.status === "previews" ? t("civitaiSavingPreviews")
: data.status === "cached" ? "✓"
: data.status === "found" ? "✓"
: data.status === "not_found" ? "—"
: data.status === "not_found" || data.status === "needs_hash" ? "—"
: "";
if (progressEl) progressEl.textContent = `${pct}% (${data.current}/${data.total}) ${statusText}`;
} else if (eventType === "done") {
if (progressEl) progressEl.textContent = "";
const previewNote = data.preview_saved > 0 ? ` (+${data.preview_saved} preview)` : "";
showToast(t("civitaiBatchDone", data.found, data.not_found) + previewNote, "success");
showToast(t("civitaiBatchDone", data.found, data.not_found, data.needs_hash || 0) + previewNote, "success");
// Reload caches
const [newMeta, newCache] = await Promise.all([fetchModelMetadata(), fetchCivitaiCache()]);
// Apply sha256 hashes from batch result directly in case fetchModelMetadata
@@ -879,6 +866,7 @@ export async function batchFetchCivitai() {
if (!newMeta[modelName].sha256) newMeta[modelName].sha256 = sha256;
}
}
if (data.preview_saved > 0) await fetchPreviewKeys(state.activeModelType);
state.modelMetadata = newMeta;
state.civitaiCache = newCache;
renderModelGrid();
+30 -1
View File
@@ -3,6 +3,7 @@
*/
import { state } from "./state.js";
import { safeHttpUrl } from "../util.js";
export function parseModelPath(fullName) {
const lastSlash = Math.max(fullName.lastIndexOf("/"), fullName.lastIndexOf("\\"));
@@ -30,8 +31,35 @@ export function previewUrl(modelName, modelType) {
* (aiohttp add_get does not auto-handle HEAD method).
* Falls back to CivitAI cached image if no local preview exists.
*/
/** モデル名 → previewKeys のキー(`サブフォルダ/拡張子なし名`、小文字・/区切り) */
export function previewKey(modelName) {
const n = modelName.replace(/\\/g, "/");
const dot = n.lastIndexOf(".");
const slash = n.lastIndexOf("/");
return (dot > slash ? n.substring(0, dot) : n).toLowerCase();
}
/** プレビュー画像を持つモデルのキー一覧をサーバから取得してstateに保存。失敗時は保存せず従来動作に戻る */
export async function fetchPreviewKeys(modelType) {
const type = modelType || state.activeModelType;
try {
const res = await fetch(`/api/wfm/models/preview-keys?type=${encodeURIComponent(type)}`);
if (!res.ok) return;
const data = await res.json();
if (Array.isArray(data.keys)) state.previewKeys[type] = new Set(data.keys);
} catch { /* 従来動作(都度リクエスト)にフォールバック */ }
}
/** 新しくプレビューが作られた/変更されたモデルを登録する */
export function markHasPreview(modelName, modelType) {
const set = state.previewKeys[modelType || state.activeModelType];
if (set) set.add(previewKey(modelName));
}
export function loadPreviewImage(imgEl, placeholderEl, modelName, modelType) {
const url = previewUrl(modelName, modelType);
const keys = state.previewKeys[modelType || state.activeModelType];
const noLocalPreview = !!keys && !keys.has(previewKey(modelName));
imgEl.onload = () => {
imgEl.style.display = "";
if (placeholderEl) placeholderEl.style.display = "none";
@@ -41,7 +69,7 @@ export function loadPreviewImage(imgEl, placeholderEl, modelName, modelType) {
const meta = state.modelMetadata[modelName] || {};
const sha256 = meta.sha256;
const civitai = sha256 && state.civitaiCache[sha256];
const civitaiImg = civitai && civitai.images && civitai.images[0];
const civitaiImg = safeHttpUrl(civitai && civitai.images && civitai.images[0]);
if (civitaiImg) {
imgEl.onerror = () => {
imgEl.style.display = "none";
@@ -55,5 +83,6 @@ export function loadPreviewImage(imgEl, placeholderEl, modelName, modelType) {
if (placeholderEl) placeholderEl.style.display = "";
}
};
if (noLocalPreview) { imgEl.onerror(); return; }
imgEl.src = url;
}
+25 -7
View File
@@ -27,6 +27,7 @@ export const state = {
allModelGroups: {}, // { type: { groupName: [models] } } — all types
civitaiCache: {},
disabledModels: {}, // { type: Set<modelName> }
previewKeys: {}, // { type: Set<"subdir/stem"(小文字)> } プレビュー画像を持つモデル。未取得の型は従来どおり都度リクエスト
subdirs: [],
selectMode: false,
selectedModels: new Set(),
@@ -48,14 +49,31 @@ export const state = {
};
// 設定「モデルフォルダ」で追加されたフォルダのモデル(ComfyUIのobject_infoには出ない)
async function fetchExtraModels(type) {
try {
const res = await fetch(`/api/wfm/models/files?type=${encodeURIComponent(type)}&extra_only=1`);
if (res.ok) {
const list = await res.json();
return Array.isArray(list) ? list : [];
}
} catch {}
return [];
}
const withExtra = (type, fn) => async () => {
const [base, extra] = await Promise.all([fn(), fetchExtraModels(type)]);
return extra.length ? [...new Set([...base, ...extra])] : base;
};
export const FETCH_MAP = {
checkpoint: () => comfyUI.fetchCheckpoints(),
lora: () => comfyUI.fetchLoras(),
vae: () => comfyUI.fetchVaes(),
controlnet: () => comfyUI.fetchControlNets(),
unet: () => comfyUI.fetchDiffusionModels(),
textencoder: () => comfyUI.fetchTextEncoders(),
hypernetwork: () => comfyUI.fetchHypernetworks(),
checkpoint: withExtra("checkpoint", () => comfyUI.fetchCheckpoints()),
lora: withExtra("lora", () => comfyUI.fetchLoras()),
vae: withExtra("vae", () => comfyUI.fetchVaes()),
controlnet: withExtra("controlnet", () => comfyUI.fetchControlNets()),
unet: withExtra("unet", () => comfyUI.fetchDiffusionModels()),
textencoder: withExtra("textencoder", () => comfyUI.fetchTextEncoders()),
hypernetwork: withExtra("hypernetwork", () => comfyUI.fetchHypernetworks()),
embedding: () => comfyUI.fetchEmbeddings(),
};
+74
View File
@@ -676,6 +676,38 @@ export async function initSettingsTab() {
</div>
</details>
<!-- Models Folder -->
<details class="wfm-settings-section">
<summary class="wfm-settings-summary">${t("modelsDir")}</summary>
<div class="wfm-form-group">
<label>${t("modelsDirLabel")}</label>
<div style="display:flex;gap:8px;">
<input type="text" class="wfm-input" id="wfm-settings-models-dir"
value="${serverSettings.models_dir || ""}"
placeholder="C:\\Users\\...\\StabilityMatrix\\Models">
<button class="wfm-btn wfm-btn-primary wfm-btn-sm" id="wfm-settings-models-dir-apply">${t("workflowsDirApply")}</button>
<button class="wfm-btn wfm-btn-sm" id="wfm-settings-models-dir-reset">${t("workflowsDirDefault")}</button>
</div>
<small style="color:var(--wfm-text-secondary);font-size:11px;display:block;margin-top:4px;">
${t("modelsDirHint")}
</small>
</div>
</details>
<!-- Windows Event Loop (stability) -->
<details class="wfm-settings-section">
<summary class="wfm-settings-summary">${t("selectorLoop")}</summary>
<div class="wfm-form-group">
<label style="display:flex;align-items:center;gap:6px;cursor:pointer;">
<input type="checkbox" id="wfm-settings-selector-loop" ${serverSettings.windows_selector_event_loop ? "checked" : ""}>
<span>${t("selectorLoopLabel")}</span>
</label>
<small style="color:var(--wfm-text-secondary);font-size:11px;display:block;margin-top:4px;">
${t("selectorLoopHint")}
</small>
</div>
</details>
<!-- Gallery Output Folder -->
<details class="wfm-settings-section">
<summary class="wfm-settings-summary">${t("galleryOutputDir")}</summary>
@@ -1171,6 +1203,48 @@ export async function initSettingsTab() {
}
});
// --- Windows selector event loop (needs ComfyUI restart) ---
document.getElementById("wfm-settings-selector-loop")?.addEventListener("change", async (e) => {
const enabled = !!e.target.checked;
try {
await saveServerSettings({ windows_selector_event_loop: enabled });
serverSettings.windows_selector_event_loop = enabled;
showToast(t("selectorLoopSaved"), "success");
} catch (err) {
e.target.checked = !enabled;
showToast(`${t("saveError")}: ${err.message}`, "error");
}
});
// --- Models dir handlers ---
const saveModelsDir = async (value) => {
try {
const res = await fetch("/api/wfm/settings/models-dir", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ models_dir: value }),
});
const data = await res.json();
if (data.error) {
showToast(`${t("workflowsDirError")}: ${data.error}`, "error");
return;
}
const input = document.getElementById("wfm-settings-models-dir");
if (input) input.value = data.saved || "";
showToast(t("modelsDirChanged"), "success");
window.dispatchEvent(new CustomEvent("wfm-models-dir-changed"));
} catch (err) {
showToast(`${t("workflowsDirError")}: ${err.message}`, "error");
}
};
document.getElementById("wfm-settings-models-dir-apply")?.addEventListener("click", () => {
saveModelsDir(document.getElementById("wfm-settings-models-dir").value.trim());
});
document.getElementById("wfm-settings-models-dir-reset")?.addEventListener("click", () => {
document.getElementById("wfm-settings-models-dir").value = "";
saveModelsDir("");
});
// --- Gallery output dir handlers ---
document.getElementById("wfm-settings-output-dir-apply")?.addEventListener("click", async () => {
const dirInput = document.getElementById("wfm-settings-output-dir");
+51
View File
@@ -82,6 +82,57 @@ export function escapeHtml(s) {
.replace(/'/g, "&#x27;");
}
// http(s) 以外(javascript: / data: など)を拒否して安全なURLだけ返す。不正なら fallback
export function safeHttpUrl(url, fallback = "") {
// 絶対URLのhttp(s)のみ許可(相対URLだとComfyUI自身のURLへリクエストを送らせられるため不可)
const s = String(url ?? "").trim();
if (!/^https?:\/\/[^\s]+$/i.test(s)) return fallback;
try {
new URL(s);
return s;
} catch {
return fallback;
}
}
// 外部由来のHTML(CivitAIの説明文など)を許可リスト方式で無害化して返す。
// スクリプト・イベント属性・style・javascript:/data: URL・iframe等は除去する。
const _SAN_DROP = new Set(["script", "style", "iframe", "frame", "frameset", "object", "embed", "applet",
"link", "meta", "base", "form", "input", "button", "textarea", "select", "svg", "math", "template",
"noscript", "audio", "video", "source", "track", "canvas", "title", "head"]);
const _SAN_KEEP = new Set(["p", "br", "hr", "strong", "b", "em", "i", "u", "s", "del", "ins", "mark", "small",
"sub", "sup", "ul", "ol", "li", "h1", "h2", "h3", "h4", "h5", "h6", "blockquote", "code", "pre", "kbd",
"span", "div", "a", "img", "table", "thead", "tbody", "tfoot", "tr", "th", "td", "details", "summary"]);
export function sanitizeHtml(html) {
if (html == null || html === "") return "";
const doc = new DOMParser().parseFromString(String(html), "text/html"); // 不活性ドキュメント(スクリプト非実行)
const walk = (node) => {
let out = "";
for (const child of node.childNodes) {
if (child.nodeType === 3) { // text
out += escapeHtml(child.nodeValue);
} else if (child.nodeType === 1) { // element
const tag = child.tagName.toLowerCase();
if (_SAN_DROP.has(tag)) continue;
if (!_SAN_KEEP.has(tag)) { out += walk(child); continue; } // 未知タグは中身だけ残す
if (tag === "br" || tag === "hr") { out += `<${tag}>`; continue; }
if (tag === "a") {
const href = safeHttpUrl(child.getAttribute("href") || "", "");
out += `<a${href ? ` href="${escapeHtml(href)}"` : ""} target="_blank" rel="noopener noreferrer">${walk(child)}</a>`;
} else if (tag === "img") {
const src = safeHttpUrl(child.getAttribute("src") || "", "");
if (src) out += `<img src="${escapeHtml(src)}" alt="${escapeHtml(child.getAttribute("alt") || "")}" loading="lazy" style="max-width:100%;">`;
} else {
out += `<${tag}>${walk(child)}</${tag}>`;
}
}
}
return out;
};
return walk(doc.body);
}
// localStorage からJSONを安全に読む(不正JSON・未設定時はfallback)
export function readJsonStorage(key, fallback = {}) {
try {
+20 -1
View File
@@ -12,7 +12,7 @@ import { VIDEO_GROUP, VTEMP_GROUP, ensureVideoGroup, isVideoFile } from "./galle
import { setSourcePreview } from "./video-preview.js";
import { showToast } from "./app.js";
import { t } from "./i18n.js";
import { addClipFromFile, setBgmFromFile } from "./video-edit-tab.js";
import { addClipFromFile, setBgmFromFile, addPipFromFile } from "./video-edit-tab.js";
import { setBlockImageFromFile } from "./video-plan-tab.js";
// Sentinel for the "All Video Assets" option — not a real backend group, since
@@ -242,6 +242,7 @@ function _renderDetail(img) {
<textarea id="wfm-video-asset-memo" class="wfm-textarea" rows="3"></textarea>
<button type="button" class="wfm-btn wfm-btn-sm" id="wfm-video-asset-memo-save" style="margin-top:6px;">Save Memo</button>
<button type="button" class="wfm-btn wfm-btn-sm" id="wfm-video-asset-send-to-edit" style="width:100%;margin-top:12px;">${t("videoEditSendToEdit")}</button>
<button type="button" class="wfm-btn wfm-btn-sm" id="wfm-video-asset-add-overlay" style="width:100%;margin-top:6px;">${t("videoAssetAddAsOverlay")}</button>
<button type="button" class="wfm-btn wfm-btn-sm" id="wfm-video-asset-set-bgm" style="width:100%;margin-top:6px;display:${isVideoFile(img) ? "block" : "none"};">${t("videoAssetSetAsBgm")}</button>
<div id="wfm-video-asset-set-plan-image-row" style="display:${isVideoFile(img) ? "none" : "flex"};gap:6px;margin-top:6px;">
<button type="button" class="wfm-btn wfm-btn-sm" id="wfm-video-asset-set-first" style="flex:1;">${t("videoAssetSetAsFirst")}</button>
@@ -288,6 +289,24 @@ function _renderDetail(img) {
}
});
// Overlay clip (picture-in-picture): works for both videos and images, and
// jumps to the Edit subtab's Overlay track so the new clip is visible.
panel.querySelector("#wfm-video-asset-add-overlay")?.addEventListener("click", async () => {
try {
const res = await fetch(`/wfm/gallery/image/serve?path=${encodeURIComponent(img.path)}`);
if (!res.ok) throw new Error(String(res.status));
const blob = await res.blob();
const file = new File([blob], img.filename, { type: blob.type || (isVideoFile(img) ? "video/mp4" : "image/png") });
if (await addPipFromFile(file, img.filename)) {
document.querySelector('.wfm-video-center-panel .wfm-video-subtab-btn[data-video-subtab="edit"]')?.click();
document.getElementById("wfm-video-edit-track-pip")?.click();
showToast(t("videoAssetAddAsOverlayDone", img.filename), "success");
}
} catch (err) {
showToast(t("errorWithMsg", err.message), "error");
}
});
// Gallery lists no audio files, so a video asset's own audio track is the
// Asset-side way to pick a BGM (LoadAudio decodes audio from video files).
panel.querySelector("#wfm-video-asset-set-bgm")?.addEventListener("click", async () => {
File diff suppressed because it is too large Load Diff
+7
View File
@@ -127,6 +127,12 @@ function _applyVideoI18n() {
if (el) el.title = t(key);
};
setText("wfm-video-edit-export-btn", "videoEditExportBtn");
setText("wfm-video-edit-track-video", "videoEditTrackVideo");
setText("wfm-video-edit-track-pip", "videoEditTrackPip");
setText("wfm-video-edit-pip-title", "videoEditPipTitle");
setText("wfm-video-edit-pip-btn", "videoEditPipAdd");
setText("wfm-video-edit-track-text", "videoEditTrackText");
setText("wfm-video-edit-track-audio", "videoEditTrackAudio");
setTitle("wfm-video-edit-move-left-btn", "videoEditMoveLeft");
setTitle("wfm-video-edit-move-right-btn", "videoEditMoveRight");
setText("wfm-video-edit-duplicate-btn", "videoEditDuplicate");
@@ -142,6 +148,7 @@ function _applyVideoI18n() {
setText("wfm-video-edit-bgm-vol-label", "videoEditBgmVolume");
setText("wfm-video-edit-bgm-offset-label", "videoEditBgmOffset");
setText("wfm-video-edit-bgm-hint", "videoEditBgmHint");
setText("wfm-video-edit-sound-btn", "videoEditSoundAdd");
setText("wfm-video-source-add-to-edit", "videoSourceAddToEdit");
setText("wfm-video-source-label", "videoSourceLabel");
setText("wfm-video-source-hint", "videoSourceHint");
+42 -15
View File
@@ -247,6 +247,9 @@
<span id="wfm-models-count" class="wfm-nodes-count"></span>
<button id="wfm-models-refresh-btn" class="wfm-btn wfm-btn-sm">Refresh</button>
<button id="wfm-models-civitai-batch-btn" class="wfm-btn wfm-btn-sm" title="Fetch CivitAI info for all models">CivitAI</button>
<label style="font-size:11px;color:var(--wfm-text-secondary);white-space:nowrap;cursor:pointer;">
<input type="checkbox" id="wfm-models-civitai-skip-nf"> <span id="wfm-models-civitai-skip-nf-label">Skip not found</span>
</label>
<span id="wfm-models-civitai-progress" style="font-size:12px;color:var(--wfm-text-secondary);"></span>
<button id="wfm-models-badge-settings-btn" class="wfm-btn wfm-btn-sm" title="Badge settings">&#9881; Badge</button>
<button id="wfm-models-select-btn" class="wfm-btn wfm-btn-sm wfm-btn-success" title="Multi-select models">Select</button>
@@ -1679,6 +1682,7 @@
<h3 id="wfm-help-settings-card-workflow-title">Workflow Defaults</h3>
<ul>
<li id="wfm-help-settings-3">Workflow data folder path</li>
<li id="wfm-help-settings-23">Models Folder: add extra model root folders (e.g. Stability Matrix's Models) — their subfolders (StableDiffusion / Lora / VAE / ControlNet / TextEncoders / DiffusionModels / Embeddings / HyperNetworks, or ComfyUI names like checkpoints / loras) are listed in the Models tab in addition to ComfyUI's own folders; separate several roots with ; — Apply saves, Default clears</li>
<li id="wfm-help-settings-19">Gallery Output Folder: the ComfyUI output folder the Gallery tab browses — leave blank to use ComfyUI's default output directory; Apply takes effect immediately, Default resets it, and the folder currently in use is shown below the field</li>
<li id="wfm-help-settings-6">Default workflow setting</li>
<li id="wfm-help-settings-20">Default Checkpoint: when "Force default checkpoint on workflow load" is on, every checkpoint loader node's model is replaced with the chosen checkpoint whenever a workflow is loaded into GenerateUI (a toast shows when it's applied) — avoids errors or garbled images caused by a model name saved in the workflow that you don't have; Refresh reloads the checkpoint list, Save stores the setting</li>
@@ -1699,9 +1703,10 @@
<ul>
<li id="wfm-help-settings-8">Data Management: export core settings, metadata, and prompts to a JSON file, or import to restore. After importing, restart ComfyUI.</li>
<li id="wfm-help-settings-15">Full Backup (ZIP): unlike the JSON export above, also includes folder-based data (AI Skills, Lab Plans, Video Plans, Video Edit projects, Style presets) and the Tagger database — everything the JSON export can't represent. Restoring overwrites existing files; restart ComfyUI afterward.</li>
<li id="wfm-help-settings-16">Two opt-in checkboxes above the Full Backup buttons additionally include ComfyUI's default workflows folder and the Impact Pack's wildcard folder in the export — both export-only, never restored automatically; copy the ZIP's _external/ folder back by hand if you want them. A third checkbox includes the clips and BGM referenced by saved Video Edit projects (projects only store references to files in ComfyUI's input folder) — unlike the other two, these are restored into the input folder, skipping any file that already exists there.</li>
<li id="wfm-help-settings-16">Two opt-in checkboxes above the Full Backup buttons additionally include ComfyUI's default workflows folder and the Impact Pack's wildcard folder in the export — both export-only, never restored automatically; copy the ZIP's _external/ folder back by hand if you want them. A third checkbox includes the clips, BGM, sounds and overlay clips referenced by saved Video Edit projects (projects only store references to files in ComfyUI's input folder) — unlike the other two, these are restored into the input folder, skipping any file that already exists there.</li>
<li id="wfm-help-settings-13">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</li>
<li id="wfm-help-settings-21">CivitAI API Key: optional key for authenticated CivitAI access from the Models tab (get it at civitai.com → Account Settings → API Keys); stored in settings.json but left out of the JSON export and Full Backup, and the CIVITAI_API_KEY environment variable takes priority when set</li>
<li id="wfm-help-settings-24">Windows Stability: "Use the Selector event loop on Windows" switches ComfyUI's asyncio loop from Proactor to Selector (applied at the next ComfyUI start). Turn it on if ComfyUI freezes entirely after switching Models lists that load many preview images; the trade-offs are no asyncio subprocess support and a connection limit of about 512. The same switch is available through the WFS_SELECTOR_LOOP=1 environment variable</li>
</ul>
</div>
</div>
@@ -1824,7 +1829,7 @@
<h3 id="wfm-help-models-card-civitai-title">Side Panel &amp; CivitAI</h3>
<ul>
<li id="wfm-help-models-4">Side panel: opens to CivitAI tab by default when a model is selected; Info (file path, tags, memo), Groups management, CivitAI integration</li>
<li id="wfm-help-models-5">CivitAI integration: fetch model info by SHA256 hash, batch fetch per model type</li>
<li id="wfm-help-models-5">CivitAI integration: fetch model info by SHA256 hash, batch fetch per model type; the batch fetch reuses saved hashes, imports from existing .metadata.json sidecars and hashes the rest in parallel; 'Skip not found' skips models known to be missing on CivitAI</li>
</ul>
</div>
<div class="wfm-help-card">
@@ -1838,7 +1843,7 @@
<h3 id="wfm-help-models-card-groups-title">Groups &amp; Badges</h3>
<ul>
<li id="wfm-help-models-7">Group management: create, rename, delete groups and assign/remove models; Checkpoint and LoRA tabs support B (Batch) and S (Stack) quick-assign buttons per model in both card and table views</li>
<li id="wfm-help-models-9">User-defined badges: assign free-label badges with custom colors shared with the Workflow tab</li>
<li id="wfm-help-models-9">User-defined badges: assign free-label badges with custom colors shared with the Workflow tab; 'Auto badges from CivitAI' in Manage Badges creates badges from CivitAI base models</li>
</ul>
</div>
<div class="wfm-help-card">
@@ -2941,7 +2946,13 @@
(個別行ボタンではなく「選択中クリップに対して働く」共通ボタン方式)。 -->
<div id="wfm-video-subtab-edit" class="wfm-video-subtab-panel wfm-video-edit-panel" data-video-subtab-panel="edit" style="display:none;">
<div class="wfm-video-timeline-wrap">
<div class="wfm-video-edit-timeline-track" id="wfm-video-edit-timeline-track"></div>
<div class="wfm-video-edit-track-tabs" id="wfm-video-edit-track-tabs">
<button type="button" class="wfm-btn wfm-btn-xs wfm-video-edit-track-tab active" data-track="video" id="wfm-video-edit-track-video">Video</button>
<button type="button" class="wfm-btn wfm-btn-xs wfm-video-edit-track-tab" data-track="pip" id="wfm-video-edit-track-pip">Overlay</button>
<button type="button" class="wfm-btn wfm-btn-xs wfm-video-edit-track-tab" data-track="text" id="wfm-video-edit-track-text">Text</button>
<button type="button" class="wfm-btn wfm-btn-xs wfm-video-edit-track-tab" data-track="audio" id="wfm-video-edit-track-audio">Audio</button>
</div>
<div class="wfm-video-edit-timeline-track" id="wfm-video-edit-timeline-track" data-track="video"></div>
<div class="wfm-video-timeline-toolbar">
<button type="button" id="wfm-video-edit-move-left-btn" class="wfm-btn wfm-btn-xs" title="Move left">◀</button>
<button type="button" id="wfm-video-edit-move-right-btn" class="wfm-btn wfm-btn-xs" title="Move right">▶</button>
@@ -2956,17 +2967,17 @@
</div>
<div class="wfm-video-edit-main-row">
<div class="wfm-video-edit-trim-panel" id="wfm-video-edit-trim-panel"></div>
<div class="wfm-video-edit-export-panel">
<div id="wfm-video-edit-project-name" class="wfm-i2i-status" style="min-height:14px;margin-bottom:4px;"></div>
<div style="display:flex;gap:6px;">
<button type="button" id="wfm-video-edit-save-btn" class="wfm-btn wfm-btn-sm" style="flex:1;">Save</button>
<button type="button" id="wfm-video-edit-saveas-btn" class="wfm-btn wfm-btn-sm" style="flex:1;">Save As</button>
<!-- File pickers are native <label>-wrapped inputs (same as the Video Source drop zone),
not a button calling input.click() from JS — that programmatic path can be refused
by the browser without any error (confirmed on a user's machine for the BGM picker). -->
<label id="wfm-video-edit-load-btn" class="wfm-btn wfm-btn-sm wfm-video-edit-file-btn" style="flex:1;" tabindex="0" role="button">Load<input type="file" id="wfm-video-edit-load-file-input" accept="application/json,.json" style="display:none;"></label>
<!-- Tool menu: its contents follow the timeline's track view (data-view, set by _setTrackView):
video = trim + crop, text = text overlays, pip = overlay clips, audio = audio. Export stays fixed on the right. -->
<div class="wfm-video-edit-tools" id="wfm-video-edit-tools" data-view="video">
<div class="wfm-video-edit-trim-panel" id="wfm-video-edit-trim-panel"></div>
<div class="wfm-video-edit-pip-panel">
<div class="wfm-video-edit-section-head"><span id="wfm-video-edit-pip-title">Overlay clips (PinP)</span></div>
<div class="wfm-video-edit-sound-head">
<!-- The real <input> sits transparently over the button (not display:none behind a <label>), so the click lands on the native file input itself. -->
<label class="wfm-btn wfm-btn-xs wfm-video-edit-file-btn wfm-video-edit-file-overlay" tabindex="0" role="button"><span id="wfm-video-edit-pip-btn">+ Overlay clip...</span><input type="file" id="wfm-video-edit-pip-input" multiple accept="video/*,image/*"></label>
</div>
<div class="wfm-video-edit-sound-list" id="wfm-video-edit-pip-list"></div>
</div>
<div class="wfm-video-edit-audio-panel">
<div class="wfm-video-edit-section-head"><span id="wfm-video-edit-audio-title">Audio</span></div>
@@ -2993,6 +3004,22 @@
<label for="wfm-video-edit-bgm-offset" id="wfm-video-edit-bgm-offset-label">BGM start (s)</label>
<input type="number" id="wfm-video-edit-bgm-offset" class="wfm-input" min="0" step="0.1" value="0">
</div>
<div class="wfm-video-edit-sound-head">
<label class="wfm-btn wfm-btn-xs wfm-video-edit-file-btn wfm-video-edit-file-overlay" tabindex="0" role="button"><span id="wfm-video-edit-sound-btn">+ Sound...</span><input type="file" id="wfm-video-edit-sound-input" multiple accept="audio/*,video/*"></label>
</div>
<div class="wfm-video-edit-sound-list" id="wfm-video-edit-sound-list"></div>
</div>
</div>
<div class="wfm-video-edit-export-panel">
<div id="wfm-video-edit-project-name" class="wfm-i2i-status" style="min-height:14px;margin-bottom:4px;"></div>
<div style="display:flex;gap:6px;">
<button type="button" id="wfm-video-edit-save-btn" class="wfm-btn wfm-btn-sm" style="flex:1;">Save</button>
<button type="button" id="wfm-video-edit-saveas-btn" class="wfm-btn wfm-btn-sm" style="flex:1;">Save As</button>
<!-- File pickers are native <label>-wrapped inputs (same as the Video Source drop zone),
not a button calling input.click() from JS — that programmatic path can be refused
by the browser without any error (confirmed on a user's machine for the BGM picker). -->
<label id="wfm-video-edit-load-btn" class="wfm-btn wfm-btn-sm wfm-video-edit-file-btn" style="flex:1;" tabindex="0" role="button">Load<input type="file" id="wfm-video-edit-load-file-input" accept="application/json,.json" style="display:none;"></label>
</div>
<button type="button" id="wfm-video-edit-export-btn" class="wfm-btn wfm-btn-primary" style="width:100%;margin-top:8px;">Export</button>
<div class="wfm-gen-progress-container" style="margin-top:8px;">