mirror of
https://github.com/willmiao/ComfyUI-Lora-Manager.git
synced 2026-09-21 03:01:27 -03:00
Compare commits
52 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| ed7cf418b4 | |||
| 634ea7f299 | |||
| 6ba64ebb3c | |||
| 03569c62df | |||
| a61840b366 | |||
| 726fc178f1 | |||
| 8260bd022d | |||
| b309becdf9 | |||
| 1e375bb8d9 | |||
| 14da8a6f17 | |||
| da71985c3e | |||
| 7c4c8b8f30 | |||
| 77109b3cf8 | |||
| 00095a5398 | |||
| 6b41c3bbb4 | |||
| b37238d790 | |||
| bc33e32c6f | |||
| 49704d801c | |||
| 34ca14d7fc | |||
| f7b247f9e8 | |||
| 3005d2877e | |||
| ed2a17970f | |||
| 9584fa85c9 | |||
| 1fd7cc0123 | |||
| 39e7c1376c | |||
| 2a3c632dc5 | |||
| 8d46d26abe | |||
| d761ac77f7 | |||
| c8b9db5bf4 | |||
| bce7d1d30c | |||
| bccd494a56 | |||
| 3fd29f6943 | |||
| 838a374a56 | |||
| 6e31da7a70 | |||
| fc9088bfd6 | |||
| 675421ea84 | |||
| 2ff98ae089 | |||
| c972c755fc | |||
| ebe3df7d22 | |||
| be44a75b74 | |||
| fd1227d3b8 | |||
| 3a9e02137d | |||
| d8a2be8edc | |||
| 1c46b2e8c3 | |||
| 3c3ac49f2f | |||
| 1a1be95a64 | |||
| 7a36659a20 | |||
| cb18281b14 | |||
| 856c9a87ac | |||
| a7d65fe84a | |||
| 15bf079af2 | |||
| 65ba750634 |
@@ -72,6 +72,16 @@ python scripts/sync_translation_keys.py
|
||||
|
||||
Locale files are in `locales/` (en, zh-CN, zh-TW, ja, ko, fr, de, es, ru, he).
|
||||
|
||||
After adding keys to `en.json` and syncing, **stop**: the `[TODO: Translate]` placeholders in
|
||||
the other locales are the expected end state during feature development. Do NOT translate
|
||||
proactively — translate only when the feature owner explicitly asks (see
|
||||
`docs/i18n-translation-guidelines.md` §7).
|
||||
|
||||
**Before translating anything, read `docs/i18n-translation-guidelines.md`** — it defines the
|
||||
term conventions (e.g. "Recipe" stays untranslated in French, 配方 in Chinese; model-type and
|
||||
brand names are never translated), per-locale preferred renderings, placeholder rules, and
|
||||
the known confusion hot-spots.
|
||||
|
||||
## Code Style
|
||||
|
||||
### Python
|
||||
@@ -223,11 +233,4 @@ The system runs in two modes:
|
||||
resolved. `os.path.realpath` is only for scanner dedup and the symlink cache.
|
||||
Any path passed to `os.remove`/`os.rename`/`shutil.move` or validated by a
|
||||
containment check MUST use the business path (i.e. `os.path.abspath`, not
|
||||
`realpath`).
|
||||
|
||||
## Git / Commit Messages
|
||||
|
||||
- Follow the style of recent repository commits when writing commit messages
|
||||
- Prefer the repo's existing `feat(...)`, `fix(...)`, `chore:` style where applicable
|
||||
- If the user has provided a GitHub issue link or issue ID for the task, mention that issue in the commit message, for example `(#871)`
|
||||
- When unrelated local changes exist, stage and commit only the files relevant to the requested task
|
||||
`realpath`).
|
||||
-10
@@ -3,8 +3,6 @@ try: # pragma: no cover - import fallback for pytest collection
|
||||
from .py.nodes.lora_loader import LoraLoaderLM, LoraTextLoaderLM
|
||||
from .py.nodes.checkpoint_loader import CheckpointLoaderLM
|
||||
from .py.nodes.unet_loader import UNETLoaderLM
|
||||
from .py.nodes.random_checkpoint_loader import RandomCheckpointLoaderLM
|
||||
from .py.nodes.random_unet_loader import RandomUNETLoaderLM
|
||||
from .py.nodes.trigger_word_toggle import TriggerWordToggleLM
|
||||
from .py.nodes.prompt import PromptLM
|
||||
from .py.nodes.text import TextLM
|
||||
@@ -42,12 +40,6 @@ except (
|
||||
"py.nodes.checkpoint_loader"
|
||||
).CheckpointLoaderLM
|
||||
UNETLoaderLM = importlib.import_module("py.nodes.unet_loader").UNETLoaderLM
|
||||
RandomCheckpointLoaderLM = importlib.import_module(
|
||||
"py.nodes.random_checkpoint_loader"
|
||||
).RandomCheckpointLoaderLM
|
||||
RandomUNETLoaderLM = importlib.import_module(
|
||||
"py.nodes.random_unet_loader"
|
||||
).RandomUNETLoaderLM
|
||||
TriggerWordToggleLM = importlib.import_module(
|
||||
"py.nodes.trigger_word_toggle"
|
||||
).TriggerWordToggleLM
|
||||
@@ -87,8 +79,6 @@ NODE_CLASS_MAPPINGS = {
|
||||
LoraTextLoaderLM.NAME: LoraTextLoaderLM,
|
||||
CheckpointLoaderLM.NAME: CheckpointLoaderLM,
|
||||
UNETLoaderLM.NAME: UNETLoaderLM,
|
||||
RandomCheckpointLoaderLM.NAME: RandomCheckpointLoaderLM,
|
||||
RandomUNETLoaderLM.NAME: RandomUNETLoaderLM,
|
||||
TriggerWordToggleLM.NAME: TriggerWordToggleLM,
|
||||
LoraStackerLM.NAME: LoraStackerLM,
|
||||
LoraStackCombinerLM.NAME: LoraStackCombinerLM,
|
||||
|
||||
@@ -54,7 +54,7 @@ The dedicated services encapsulate long-running work so handlers stay thin.
|
||||
| Use case | Entry point | Dependencies | Guarantees |
|
||||
| --- | --- | --- | --- |
|
||||
| `RecipeAnalysisService` | `analyze_uploaded_image`, `analyze_remote_image`, `analyze_local_image`, `analyze_widget_metadata` | `ExifUtils`, `RecipeParserFactory`, downloader factory, optional metadata collector/processor | Normalises missing/invalid payloads into `RecipeValidationError`; generates consistent fingerprint data to keep duplicate detection stable; temporary files are cleaned up after every analysis path. |
|
||||
| `RecipePersistenceService` | `save_recipe`, `delete_recipe`, `update_recipe`, `reconnect_lora`, `bulk_delete`, `save_recipe_from_widget` | `ExifUtils`, recipe scanner, card preview sizing constants | Writes images/JSON metadata atomically; updates scanner caches and hash indices before returning; recalculates fingerprints whenever LoRA assignments change. |
|
||||
| `RecipePersistenceService` | `save_recipe`, `delete_recipe`, `update_recipe`, `reconnect_lora`, `get_reconnect_suggestions`, `bulk_delete`, `save_recipe_from_widget` | `ExifUtils`, recipe scanner, card preview sizing constants | Writes images/JSON metadata atomically; updates scanner caches and hash indices before returning; recalculates fingerprints whenever LoRA assignments change. |
|
||||
| `RecipeSharingService` | `share_recipe`, `prepare_download` | `tempfile`, recipe scanner | Copies originals to TTL-managed temp files; metadata lookups re-use the scanner; expired shares trigger cleanup and `RecipeNotFoundError`. |
|
||||
|
||||
## Maintaining critical invariants
|
||||
|
||||
@@ -0,0 +1,370 @@
|
||||
# i18n Translation Guidelines
|
||||
|
||||
This document is the canonical set of conventions for translating LoRA Manager UI strings.
|
||||
It applies to **human translators and AI agents** alike. Read it before editing anything in
|
||||
`locales/`.
|
||||
|
||||
Source of truth: `locales/en.json` (10 locales, 1810 leaf keys; all locales share the exact
|
||||
same key structure).
|
||||
|
||||
Locales: `en`, `zh-CN`, `zh-TW`, `ja`, `ko`, `fr`, `de`, `es`, `ru`, `he` (RTL).
|
||||
|
||||
> **Status (2026-08 sweep):** a full audit was executed and the terminology, placeholder,
|
||||
> stale-text, and untranslated-block fixes described in §2–§6 were applied across all locales
|
||||
> (commits `3c3ac49f` … `fd1227d3`). The tables below are now the **normative target state**,
|
||||
> not a to-do list — future edits should preserve these renderings and only add what is new.
|
||||
|
||||
---
|
||||
|
||||
## 1. Hard rules (do not violate)
|
||||
|
||||
### R1 — Key structure is sacred
|
||||
- Only `locales/en.json` may add/remove/rename keys. All other locales must keep the exact
|
||||
same nested key set. `tests/i18n/test_i18n.py` enforces this.
|
||||
- When a new UI string is added to `en.json`, run
|
||||
`python scripts/sync_translation_keys.py` (adds the missing keys to all locales with
|
||||
`[TODO: Translate]` placeholder copies) — **then stop**. Do NOT translate proactively:
|
||||
placeholders are the expected end state during feature development, and translations are
|
||||
filled in only when the feature owner explicitly asks (workflow details in §7).
|
||||
- Never reorder, re-indent, or reformat a locale file "for tidiness". The sync script
|
||||
preserves formatting; manual reformatting creates noisy diffs.
|
||||
|
||||
### R2 — Placeholders and HTML must be preserved verbatim
|
||||
- `{name}`-style placeholders must appear in the translation exactly as in `en.json`.
|
||||
Do not invent placeholders the source string does not have — the caller may not pass them
|
||||
(example bug: `zh-CN recipes.controls.import.downloadLocationPreview` added `{path}`; the
|
||||
template renders this key with no parameters, so the literal text `{path}` shows in the UI).
|
||||
- `{{...}}` in a locale value is an escaped literal brace — keep it identical.
|
||||
- Keep embedded HTML tags (e.g. `<strong>...</strong>`, `<code>...</code>`) intact.
|
||||
You may move the tag around the sentence if the target language needs different word order.
|
||||
|
||||
### R3 — Never translate or transliterate these
|
||||
- Model types: **LoRA, Checkpoint, Embedding, Diffusion Model**
|
||||
- Products/brands: **LoRA Manager, ComfyUI, CivitAI, CivArchive, HuggingFace, Ko-fi**
|
||||
- Ecosystem names: **LyCORIS, DoRA**, trigger-adjacent jargon **Prompt, Workflow**
|
||||
(these are used as-is in the target-language SD community; see §2 per-language policy)
|
||||
- Theme names: **Nord, Midnight, Monokai, Dracula, Solarized**
|
||||
|
||||
### R4 — The "Recipe" convention (the most important domain term)
|
||||
Product intent: a *Recipe* records a **LoRA combination + generation parameters**
|
||||
(prompt, seed, sampler, …) that reproduces an image style. The metaphor is a **cooking
|
||||
recipe** — "follow it and you get a similar dish". It is **not** a menu, not a dish list,
|
||||
not a prescription.
|
||||
|
||||
Decision per language — translate only into a word whose everyday primary meaning is a
|
||||
cooking recipe; where that word would mislead users, **keep the English "Recipe(s)"**:
|
||||
|
||||
| Locale | Use | Never use |
|
||||
|---|---|---|
|
||||
| fr | **Recipe / Recipes** (keep English) | recette(s) — cooking reading is secondary and it was explicitly judged misleading |
|
||||
| zh-CN / zh-TW | 配方 | 食谱 (reads as "food cookbook") |
|
||||
| ja | レシピ | — (leftover English "Recipe" in `initialization.recipes.title` / `toast.recipes.recipeSaved` → translate) |
|
||||
| ko | 레시피 | — |
|
||||
| de | Rezept / Rezepte | — (cooking meaning dominant; prescription reading acceptable) |
|
||||
| es | receta / recetas | — (cooking meaning dominant) |
|
||||
| ru | рецепт / рецепты | — (leftover English "Recipe" in `initialization.recipes.title` / `toast.recipes.recipeSaved` → translate) |
|
||||
| he | מתכון / מתכונים | — (cooking meaning dominant) |
|
||||
|
||||
Whatever the choice, **one concept = one noun within a locale**. Currently violated in:
|
||||
- `fr` — "Recipe" (~97 keys, incl. nav) mixed with "recette" (~58 keys)
|
||||
- `zh-CN` / `zh-TW` — 配方 (126/122 keys) mixed with 食谱 / 食譜 (14/17 keys, all in the
|
||||
*rematch* flow: `globalContextMenu.rematchRecipes.*`, `toast.recipes.rematch*`)
|
||||
- `de` — "Rezept" (136 keys) mixed with leftover English "Recipe" (5 keys)
|
||||
- `ja` / `ru` — leftover English "Recipe" in `initialization.recipes.title` ("Recipe Manager
|
||||
zu initialisieren" / «Инициализация Recipe Manager») and `toast.recipes.recipeSaved`
|
||||
|
||||
### R5 — One term, one rendering (within each locale)
|
||||
Same source word must not be translated several ways in one file. Known offender areas
|
||||
(see §5 for the full fix list): recipe, Checkpoint, Embedding, prompt, base model, preset,
|
||||
workflow, hash, metadata, tags, bulk. Every locale currently mixes variants of at least one
|
||||
of these — pick the preferred form in the §2 tables and normalize.
|
||||
|
||||
### R6 — Register consistency
|
||||
- `zh-CN` / `zh-TW`: pick 你 or 您 once. Do not mix (zh-CN has 44×你 + 5×您; zh-TW has
|
||||
27×您 + 18×你).
|
||||
- `de`: pick "du" or "Sie" once (currently 143×Sie + ~7×du).
|
||||
- `es`: pick "tú" or "usted" once.
|
||||
|
||||
### R7 — Punctuation per script
|
||||
- Full-width punctuation `:()` is correct **only in CJK locales** (zh-CN, zh-TW, ja, ko).
|
||||
- Latin/Cyrillic/Hebrew locales must use ASCII `: ()` — full-width colons leaked in there
|
||||
are machine-translation artifacts. Known: `fr toast.recipes.createError/createFailed`,
|
||||
`es toast.recipes.createError/createFailed` (e.g. "…de la receta:" should be "…de la receta:").
|
||||
- `fr` apostrophes must be U+2019 `'` / ASCII `'`, never a straight double quote:
|
||||
`fr header.filter.allowSellingGeneratedContentTooltip` currently reads
|
||||
`vendre d"images` → fix to `d'images`. Do not mix `'` and `'` in one file (fr has 299 vs 15).
|
||||
- Ellipsis: use ASCII `...` (project style). Don't introduce `…`.
|
||||
- Keep the sentence-ending period/omission consistent with the source string where the
|
||||
language allows it.
|
||||
- `he` is RTL: mix of Hebrew and Latin scripts is normal; keep Latin term ordering natural.
|
||||
|
||||
### R8 — No untranslated English leftovers
|
||||
Full sentences left byte-identical to `en.json` are bugs (brand names and URL placeholders
|
||||
are the exception). Every locale has them; see §6 for the per-locale checklist.
|
||||
`[TODO: Translate]` placeholders are the sanctioned intermediate state during feature
|
||||
development (see §7) — do not "fix" them unless the feature owner asked for translations.
|
||||
|
||||
### R9 — Mirror the source even when the source is wrong
|
||||
If `en.json` itself contains an inconsistency (e.g. the `Civitai` vs `CivitAI` casing split,
|
||||
or the `CivitArchive` typo in `modals.relinkCivitai.helpText.format4`), translate/transcribe
|
||||
it as-is in your locale and instead **fix the source** in `en.json` (then propagate by
|
||||
re-syncing and re-translating affected keys). Do not silently diverge in one locale only.
|
||||
|
||||
---
|
||||
|
||||
## 2. Per-language term maps
|
||||
|
||||
Preferred rendering per term. "Fix" means the locale currently contains the wrong variant
|
||||
and must be normalized. `en` = keep the English word as-is.
|
||||
|
||||
### fr
|
||||
|
||||
| Term | Use | Fix |
|
||||
|---|---|---|
|
||||
| recipe | Recipe(s) | Replace all "recette(s)" (58 keys, e.g. `recipes.actions.deleteRecipeWithShortcut`, `toast.recipes.rematchComplete`) with "Recipe(s)" |
|
||||
| Checkpoint | Checkpoint | `statistics.modelTypes.checkpoint` = "Point de contrôle" → "Checkpoint" |
|
||||
| trigger words | mot(s)-clé(s) | unify: `modals.model.triggerWords.editWord` uses "mot déclencheur" — pick one |
|
||||
| prompt / negative prompt | Prompt / prompt négatif | — |
|
||||
| base model | modèle(s) de base | — |
|
||||
| preset | préréglage | unify: `modals.model.usageTips.addPresetParameter` "prédéfini", `toast.presets.restored` "par défaut" |
|
||||
| hash | hash | `conflictConfirm.message` "hachage" → "hash" |
|
||||
| tags | tags | `settings.sections.priorityTags` "Étiquettes" → "Tags" |
|
||||
| metadata | métadonnées | `loras.controls.refresh.fullTooltip` keeps English "metadata" |
|
||||
| duplicates | doublon(s) | unify with "dupliqué(e)s" |
|
||||
| bulk | groupé(e) | unify with "par lot / mode lot" variants |
|
||||
|
||||
### de
|
||||
|
||||
| Term | Use | Fix |
|
||||
|---|---|---|
|
||||
| recipe | Rezept/Rezepte | 5 leftover English "Recipe" keys → Rezept (e.g. `globalContextMenu.repairRecipes.label`, `toast.recipes.recipeSaved`) |
|
||||
| base model | pick Basis-Modell or Basismodell | currently 27× hyphenated vs 15× closed |
|
||||
| metadata | Metadaten | 4 keys use "Modelldaten" (`onboarding.steps.fetch.title/content`) → Metadaten |
|
||||
| bulk | pick Massen- or Sammelmodus | `loras.controls.bulk.action` = "Massen" reads as "crowds" — use "Massenbearbeitung"/"Mehrfachauswahl" |
|
||||
| register | Sie (formal) | 7 keys use "du/dein" (`settings.backup.managementHelp`, `modals.checkUpdates.message/tip`, `doctor.footer`, …) |
|
||||
|
||||
### es
|
||||
|
||||
| Term | Use | Fix |
|
||||
|---|---|---|
|
||||
| recipe | receta(s) | — |
|
||||
| Checkpoint | Checkpoint | 5 statistics keys "Punto(s) de control" → "Checkpoints" (`statistics.metrics.checkpoints`, `statistics.insights.unusedCheckpoints.*`, `statistics.modelTypes.checkpoint`) |
|
||||
| trigger words | palabra(s) de activación | 2 keys already use it; ~15 keys "palabra(s) clave" (reads as search keyword) → unify |
|
||||
| base model | modelo base | — |
|
||||
| preset | preajuste | 3 keys keep English "preset", 1 "preestablecido" → preajuste |
|
||||
| workflow | pick flujo de trabajo or workflow | currently 21× "flujo de trabajo" vs 10× "workflow" |
|
||||
| bulk | masivo / por lotes | unify; "Batch Import" → traducción |
|
||||
| tags | etiquetas | — |
|
||||
|
||||
### ru
|
||||
|
||||
| Term | Use | Fix |
|
||||
|---|---|---|
|
||||
| recipe | рецепт(ы) | English leftovers: `initialization.recipes.title`, `recipes.batchImport.*`, `toast.recipes.recipeSaved` → translate |
|
||||
| Checkpoint | Checkpoint (recommended) | 3 variants today: "Checkpoint" (17 keys), «Чекпойнт», «Контрольная точка» (statistics, 6 keys) — statistics MUST drop «Контрольная точка» |
|
||||
| Embedding | Embedding | «Эмбеддинг» variant exists in `settings.priorityTags.modelTypes.embedding` — unify |
|
||||
| prompt | промпт | 8 keys use «запрос» (reads as "database/HTTP request") → «промпт» |
|
||||
| base model | базовая модель | — |
|
||||
| preset | пресет | `header.theme.presets` "Предустановки" → пресеты |
|
||||
| workflow | Workflow (recommended) | «рабочий процесс» used in 4 keys — unify |
|
||||
| hash | pick хеш or хэш | both spellings co-occur |
|
||||
| tag(s) | тег(и) | — |
|
||||
| typos | — | `settings.misc.loraSyntaxFormatHelp`: «безпотерьного» → «беспотерьного» |
|
||||
|
||||
### he
|
||||
|
||||
| Term | Use | Fix |
|
||||
|---|---|---|
|
||||
| recipe | מתכון / מתכונים | — |
|
||||
| Checkpoint | Checkpoint | 5 statistics keys «נקודת/נקודות ביקורת» (road/security checkpoint) → "Checkpoint(s)" (`statistics.metrics.checkpoints`, `statistics.modelTypes.checkpoint`, `statistics.insights.unusedCheckpoints.*`) |
|
||||
| Embedding | Embedding | `statistics` keys use הטמעות → Embedding |
|
||||
| prompt | pick הנחיה or פרומפט | 9 keys הנחיה vs 3 פרומפט — unify (recommend פרומפט, SD-community loanword) |
|
||||
| preset | קביעה מראש | `header.filter.presetOverwriteConfirm` uses פריסט → unify |
|
||||
| hash | pick one of האש / גיבוב / hash | 3 variants co-occur — unify (recommend hash or גיבוב) |
|
||||
| metadata | pick מטא-דאטה or מטא-נתונים | 38 vs 17 keys — unify |
|
||||
| model | מודל | 13 keys use דגם/דגמים — unify |
|
||||
| bulk | pick one of 5 variants | 5 different renderings ("כמות גדולה", "המוני", "קבוצתי", "אצווה", …) — unify; `loras.controls.bulk.action` "כמות גדולה" reads as "large quantity" |
|
||||
|
||||
### ja
|
||||
|
||||
| Term | Use | Fix |
|
||||
|---|---|---|
|
||||
| recipe | レシピ | `initialization.recipes.title` keeps English "Recipe Manager" — translate to レシピマネージャー |
|
||||
| Checkpoint | Checkpoint or チェックポイント (pick one) | 3 variants: Checkpoint (~14), checkpoint lowercase (4), チェックポイント (4, e.g. `settings.priorityTags.modelTypes.checkpoint`) |
|
||||
| Embedding | Embedding | 4 keys lowercase "embedding" mid-sentence |
|
||||
| bulk | 一括 | `modals.checkUpdates.tip` "バルクモード" → 一括モード |
|
||||
| recipe counter | 件 or 個 | `repairRecipes.success` uses 件, `.cancelled` uses 個 — unify |
|
||||
|
||||
### ko
|
||||
|
||||
| Term | Use | Fix |
|
||||
|---|---|---|
|
||||
| recipe | 레시피 | — |
|
||||
| Checkpoint | Checkpoint (recommended) | 4 keys transliterate 체크포인트 (`settings.priorityTags.modelTypes.checkpoint`, `toast.recipes.missingCheckpointPath/missingCheckpointInfo/downloadCheckpointFailed`) |
|
||||
| Embedding | Embedding | 3 keys 임베딩 (`settings.priorityTags.modelTypes.embedding`, `uiHelpers.nodeSelector.embedding`) |
|
||||
| base model | 베이스 모델 | 6 keys «기본 모델» read as "default model" → 베이스 모델 (`settings.downloadSkipBaseModels.*`, `toast.loras.downloadSkippedByBaseModel`) |
|
||||
| workflow | pick 워크플로 or 워크플로우 | 26 vs 6 keys — unify |
|
||||
| bulk | 일괄 | `modals.checkUpdates.tip` "벌크 모드" → 일괄 모드 |
|
||||
| tag logic | — | `header.filter.tagLogicAny` = "모든 태그 일치 (OR)" is **inverted** (should be "하나 이상의 태그 일치") and identical to `tagLogicAll` |
|
||||
| particle | — | `modelCard.sendToWorkflow.checkpointNotImplemented`: "Checkpoint을" → "Checkpoint를" |
|
||||
|
||||
### zh-CN / zh-TW
|
||||
|
||||
| Term | zh-CN | zh-TW |
|
||||
|---|---|---|
|
||||
| recipe | 配方 (fix 食谱 → 配方, 14 keys in rematch flow) | 配方 (fix 食譜 → 配方, 17 keys in rematch flow) |
|
||||
| Checkpoint | Checkpoint (fix 检查点 → Checkpoint, 5 keys: `toast.recipes.missingCheckpointPath/missingCheckpointInfo/downloadCheckpointFailed`, `modelCard.actions.checkpointNameCopied`, `modelCard.sendToWorkflow.checkpointNotImplemented`) | Checkpoint (fix 檢查點 → Checkpoint, 4 keys: `modelCard.actions.copyCheckpointName`, `toast.recipes.missing*`×2, `toast.recipes.downloadCheckpointFailed`) |
|
||||
| base model | 基础模型 (fix 基模型 → 基础模型, 3 keys in `modals.model.versions.filters.*`) | 基礎模型 ✓ consistent |
|
||||
| prompt | 提示词 ✓ | 提示詞 ✓ |
|
||||
| preset | 预设 ✓ | 預設 ✓ |
|
||||
| workflow | 工作流 ✓ | 工作流 ✓ |
|
||||
| trigger words | 触发词 ✓ | 觸發詞 ✓ |
|
||||
| hash | 哈希 (哈希值 variant OK) | 雜湊 ✓ |
|
||||
| register | 你 (fix 5×您 → 你) | 您 (fix 18×你 → 您) |
|
||||
|
||||
---
|
||||
|
||||
## 3. Cross-cutting confusion hot-spots (must-fix list)
|
||||
|
||||
All items below were **resolved** in the 2026-08 sweep — treat them as a regression
|
||||
watch-list: do not reintroduce these renderings.
|
||||
|
||||
1. **Checkpoint rendered as a literal security/road checkpoint** — fr, es, ru, he, zh-CN,
|
||||
zh-TW all had 4–6 keys in the `statistics.*` domain reading as "control point"; reverted
|
||||
to "Checkpoint".
|
||||
2. **"recipe" variants that break the one-noun rule** — fr "recette" → "Recipe", zh
|
||||
食谱/食譜 → 配方, de/ja/ru leftover English "Recipe" translated.
|
||||
3. **ko `header.filter.tagLogicAny`** — was inverted ("모든 태그 일치 (OR)") and identical
|
||||
to `tagLogicAll`; now "어느 하나의 태그와 일치 (OR)".
|
||||
4. **ja `modals.model.versions.actions.viewLocalTooltip`** — was the stale "近日対応予定"
|
||||
("coming soon"); all 9 locales now describe the actual action.
|
||||
5. **Stale help texts** — `settings.downloadSkipBaseModels.help`,
|
||||
`settings.aiProvider.apiBaseHelp`, `settings.hideEarlyAccessUpdates.help` retranslated
|
||||
in all locales to the current `en.json` wording.
|
||||
6. **en.json source bugs** (fixed in source, then mirrored):
|
||||
- "Civitai" → "CivitAI" brand casing (values only; key names `relinkCivitai` etc. keep
|
||||
their lowercase form and must not be renamed)
|
||||
- `modals.relinkCivitai.helpText.format4` "CivitArchive" typo → "CivArchive"
|
||||
- `zh-CN recipes.controls.import.downloadLocationPreview` invented `{path}` removed
|
||||
|
||||
---
|
||||
|
||||
## 4. Placeholder contract deviations (current)
|
||||
|
||||
`{...}` token sets must match `en.json` per key. All deviations found in the 2026-08 sweep
|
||||
were fixed, with one *intentional* exception:
|
||||
|
||||
**`toast.settings.mappingsUpdated`** — the caller passes a hardcoded English inflection
|
||||
(`plural: count !== 1 ? 's' : ''`). Languages that cannot build a plural by appending that
|
||||
`s` (zh-CN/zh-TW, ja, ko, de, ru, he) **drop `{plural}`** and render a count-friendly form
|
||||
(`({count})` or a measure word); fr and es keep it (`mappage{plural}`, `mapeo{plural}`).
|
||||
|
||||
```python
|
||||
# keep a copy of this rule next to the key if it ever moves:
|
||||
# fr/es: "... ({count} mappage{plural})"
|
||||
# de/ru/he: "... ({count})"
|
||||
# zh-CN: "({count} 条映射)" / zh-TW: "({count} 個對應)" / ja: "({count} マッピング)"
|
||||
```
|
||||
|
||||
Do NOT add `{...}` tokens the source lacks (the caller will not supply them, and the literal
|
||||
text renders in the UI), and do NOT rename source tokens (`{typePlural}` stays `{typePlural}`).
|
||||
|
||||
---
|
||||
|
||||
## 5. One term, one rendering — offender matrix
|
||||
|
||||
Cross-locale summary of §2 inconsistencies. "✓" = already consistent. All ✗ cells were
|
||||
resolved in the 2026-08 sweep; the row shows the single rendering now in force per locale.
|
||||
|
||||
| Term | fr | de | es | ru | he | ja | ko | zh-CN | zh-TW |
|
||||
|---|---|---|---|---|---|---|---|---|---|
|
||||
| recipe | Recipe | Rezept | receta | рецепт | מתכון | レシピ | 레시피 | 配方 | 配方 |
|
||||
| Checkpoint | Checkpoint | Checkpoint | Checkpoint | Checkpoint | Checkpoint | Checkpoint | Checkpoint | Checkpoint | Checkpoint |
|
||||
| Embedding | Embedding | Embedding | Embedding | Embedding | Embedding | Embedding | Embedding | Embedding | Embedding |
|
||||
| prompt | Prompt | Prompt | prompt | промпт | פרומפט | プロンプト | 프롬프트 | 提示词 | 提示詞 |
|
||||
| base model | modèle de base | Basismodell | modelo base | базовая модель | מודל בסיס | ベースモデル | 베이스 모델 | 基础模型 | 基礎模型 |
|
||||
| preset | préréglage | Voreinstellung | preajuste | пресет | קביעה מראש | プリセット | 프리셋 | 预设 | 預設 |
|
||||
| workflow | Workflow | Workflow | workflow | Workflow | workflow | ワークフロー | 워크플로 | 工作流 | 工作流 |
|
||||
| hash | hash | Hash | hash | хеш | hash | ハッシュ | 해시 | 哈希 | 雜湊 |
|
||||
| metadata | métadonnées | Metadaten | metadatos | метаданные | מטא-נתונים | メタデータ | 메타데이터 | 元数据 | 中繼資料 |
|
||||
| tags | Tags | Tags | etiquetas | теги | תגיות | タグ | 태그 | 标签 | 標籤 |
|
||||
| duplicates | en double | Duplikate | duplicados | дубликаты | כפילויות | 重複 | 중복 | 重复项 | 重複項 |
|
||||
| bulk | groupé | Massen- | por lotes | пакетный | בכמות גדולה | 一括 | 일괄 | 批量 | 批量 |
|
||||
|
||||
Watch: ja/ko keep the model-type names **Checkpoint/Embedding** and `Diffusion Model` in
|
||||
Latin (consistent with their model-type sections) — do not transliterate them as
|
||||
チェックポイント/체크포인트.
|
||||
|
||||
---
|
||||
|
||||
## 6. Untranslated English leftovers (status)
|
||||
|
||||
Values byte-identical to `en.json` that are actual UI sentences are bugs (brand names and
|
||||
URL placeholders are the exception). As of the 2026-08 sweep, **all previously untranslated
|
||||
blocks are translated** in every locale: `recipes.batchImport.*` + `toast.recipes.batchImport*`
|
||||
(fr/de/es/ru/he/ja/ko), `banners.communitySupport.*`, `modals.model.license.*`,
|
||||
`globalContextMenu.fetchMissingLicenses.*`, the `doctor.*` issue/action/label subset,
|
||||
`toast.settings.libraryLoadFailed` / `libraryActivateFailed`, `toast.api.moveFailed`,
|
||||
`settings.extraFolderPaths.restartRequired`, `toast.recipes.recipeSaved`,
|
||||
`sidebar.dragDrop.moveUnsupported`, `checkpoints.modelTypes.diffusion_model`
|
||||
(ja/ko keep the English loanword), `initialization.recipes.title`.
|
||||
|
||||
The only values that remain intentionally identical to `en.json` are non-translatable:
|
||||
URL/path placeholders (`https://…`, `C:/…`), numeric presets (`5 (1080p), 6 (2K), 8 (4K)`),
|
||||
example token lists (`character, concept, style(toon|toon_style)`), service/provider names
|
||||
(`CivitAI → CivArchive → Archive DB`), and the external playlist title
|
||||
(`help.updateVlogs.playlistTitle`, de: translated to "LoRA Manager-Update-Playlist").
|
||||
|
||||
Rule for `uiHelpers.workflow.noPromptTargets`: the second line (`Mark as → Send Prompt
|
||||
Target`) quotes literal ComfyUI context-menu items — keep those menu labels in English in
|
||||
every locale because that is what the user actually sees in ComfyUI.
|
||||
|
||||
License labels (`modals.model.license.*`): the restriction labels are now translated in all
|
||||
locales (the sibling `creditRequired` has always been translated).
|
||||
|
||||
---
|
||||
|
||||
## 7. Workflow for agents and translators
|
||||
|
||||
### Adding a new UI string
|
||||
1. Add the key to `locales/en.json` only.
|
||||
2. Run `python scripts/sync_translation_keys.py` — it inserts the key into the other 9
|
||||
locales (as a `[TODO: Translate]` placeholder) preserving formatting.
|
||||
3. **During feature development, stop here.** While the UI copy is still in flux, leave the
|
||||
`[TODO: Translate]` placeholders as-is — translating churning strings into 9 locales is
|
||||
wasted work. Placeholders are a normal intermediate state, not a bug.
|
||||
4. Once the wording is final and the feature owner explicitly asks for translations,
|
||||
translate **all** pending `[TODO: Translate]` keys in every locale (not just the latest
|
||||
feature's), applying §1–§3 (placeholders verbatim, Recipe rule, term maps, register).
|
||||
Find pending keys with: `grep -c "TODO: Translate" locales/*.json`
|
||||
5. If the new string contains new terminology, extend §2 tables.
|
||||
|
||||
### Fixing a translation bug
|
||||
1. Locate the key (dotted path) in the relevant locale file.
|
||||
2. Check the corresponding `en.json` value and the actual caller (grep `static/js` or
|
||||
`web/comfyui` for the key) to learn which placeholders are passed.
|
||||
3. Fix trivially; for normalization sweeps (e.g. "recette" → "Recipe"), do it file-wide for
|
||||
the offending keys only — do not touch unrelated lines.
|
||||
4. If the bug is in `en.json` itself (R9), fix the source first, then re-sync and update all
|
||||
locales.
|
||||
|
||||
### Verification
|
||||
```bash
|
||||
pytest tests/i18n/test_i18n.py # key parity + JSON validity + JS key references
|
||||
python scripts/sync_translation_keys.py --dry-run # shows which keys would change; add --verbose for per-key detail
|
||||
npm test # frontend tests incl. i18n helpers
|
||||
```
|
||||
|
||||
`pytest tests/i18n` only checks structure. Quality conventions in this document are not
|
||||
machine-enforced — a human/agent review pass is required.
|
||||
|
||||
### Anti-patterns checklist
|
||||
- [ ] Placeholders `{x}` / `{{x}}` differ from `en.json`
|
||||
- [ ] Same source term translated 2+ ways in the same file (see §5)
|
||||
- [ ] "Checkpoint" became a literal checkpoint; "recipe" became menu/prescription/food-cookbook
|
||||
- [ ] Brand names translated or transliterated (LoRA, CivitAI, ComfyUI, …)
|
||||
- [ ] Latin locale using full-width `:()`; fr using `"` as apostrophe
|
||||
- [ ] Mixed 你/您, du/Sie, tú/usted
|
||||
- [ ] Full English sentences left behind (see §6)
|
||||
- [ ] Register/typos/mojibake; source string is stale vs `en.json` (compare semantics, not
|
||||
just words)
|
||||
+389
-197
File diff suppressed because it is too large
Load Diff
+250
-58
@@ -50,6 +50,27 @@
|
||||
"mb": "MB",
|
||||
"gb": "GB",
|
||||
"tb": "TB"
|
||||
},
|
||||
"scanProgress": {
|
||||
"refreshing": "Refreshing {type}s...",
|
||||
"fullRebuilding": "Full rebuild {type}s...",
|
||||
"actionRefresh": "Refresh",
|
||||
"actionFullRebuild": "Full rebuild",
|
||||
"actionRefreshLower": "refresh",
|
||||
"actionRebuildLower": "rebuild",
|
||||
"stages": {
|
||||
"scan_folders": "Scanning folders...",
|
||||
"count_models": "Found {total} files",
|
||||
"process_models": "Processing models",
|
||||
"reconcile_scan": "Checking for changes...",
|
||||
"process_new": "Processing new models",
|
||||
"finalizing": "Finalizing..."
|
||||
},
|
||||
"eta": {
|
||||
"lessThanMinute": "Less than a minute remaining",
|
||||
"minutes": "~{minutes} min remaining",
|
||||
"hours": "~{hours} hr {minutes} min remaining"
|
||||
}
|
||||
}
|
||||
},
|
||||
"onboarding": {
|
||||
@@ -67,15 +88,15 @@
|
||||
"steps": {
|
||||
"fetch": {
|
||||
"title": "Fetch Models Metadata",
|
||||
"content": "Click the <strong>Fetch</strong> button to download model metadata and preview images from Civitai."
|
||||
"content": "Click the <strong>Fetch</strong> button to download model metadata and preview images from CivitAI."
|
||||
},
|
||||
"download": {
|
||||
"title": "Download New Models",
|
||||
"content": "Use the <strong>Download</strong> button to download models directly from Civitai URLs."
|
||||
"content": "Use the <strong>Download</strong> button to download models directly from CivitAI URLs."
|
||||
},
|
||||
"bulk": {
|
||||
"title": "Bulk Operations",
|
||||
"content": "Enter bulk mode by clicking this button or pressing <span class=\"onboarding-shortcut\">B</span>. Select multiple models and perform batch operations. Use <span class=\"onboarding-shortcut\">Ctrl+A</span> to select all visible models."
|
||||
"content": "Enter bulk mode by clicking this button or pressing <span class=\"onboarding-shortcut\">B</span> to select multiple models and perform batch operations.<br>• <span class=\"onboarding-shortcut\">Ctrl/Cmd+A</span> select all visible models, <span class=\"onboarding-shortcut\">Shift+Click</span> select a range.<br>• <span class=\"onboarding-shortcut\">Esc</span> or clicking an empty area exits bulk mode."
|
||||
},
|
||||
"searchOptions": {
|
||||
"title": "Search Options",
|
||||
@@ -95,7 +116,19 @@
|
||||
},
|
||||
"contextMenu": {
|
||||
"title": "Context Menu",
|
||||
"content": "<strong>Right-click</strong> any model card for a context menu with additional actions."
|
||||
"content": "<strong>Right-click</strong> any model card for a context menu with card actions like moving, deleting, or editing metadata."
|
||||
},
|
||||
"marqueeSelect": {
|
||||
"title": "Drag to Select",
|
||||
"content": "Hold the <strong>left mouse button</strong> on an empty area of the grid and drag to draw a marquee that selects multiple cards at once."
|
||||
},
|
||||
"dragToSidebar": {
|
||||
"title": "Organize by Dragging",
|
||||
"content": "Drag a model card onto a folder in the sidebar to move the file there. This also works with multiple selected cards in bulk mode."
|
||||
},
|
||||
"contextMenus": {
|
||||
"title": "More Context Menus",
|
||||
"content": "In bulk mode, <strong>right-click a selected card</strong> for bulk actions. <strong>Right-click an empty area</strong> of the page for global actions like update checks and managing excluded models."
|
||||
}
|
||||
}
|
||||
},
|
||||
@@ -103,8 +136,8 @@
|
||||
"actions": {
|
||||
"addToFavorites": "Add to favorites",
|
||||
"removeFromFavorites": "Remove from favorites",
|
||||
"viewOnCivitai": "View on Civitai",
|
||||
"notAvailableFromCivitai": "Not available from Civitai",
|
||||
"viewOnCivitai": "View on CivitAI",
|
||||
"notAvailableFromCivitai": "Not available from CivitAI",
|
||||
"viewOnHuggingFace": "View on Hugging Face",
|
||||
"sendToWorkflow": "Send to ComfyUI (Click: Append, Shift+Click: Replace)",
|
||||
"copyLoRASyntax": "Copy LoRA Syntax",
|
||||
@@ -137,7 +170,7 @@
|
||||
"exampleImages": {
|
||||
"checkError": "Error checking for example images",
|
||||
"missingHash": "Missing model hash information.",
|
||||
"noRemoteImagesAvailable": "No remote example images available for this model on Civitai"
|
||||
"noRemoteImagesAvailable": "No remote example images available for this model on CivitAI"
|
||||
},
|
||||
"badges": {
|
||||
"update": "Update",
|
||||
@@ -290,15 +323,15 @@
|
||||
}
|
||||
},
|
||||
"settings": {
|
||||
"civitaiApiKey": "Civitai API Key",
|
||||
"civitaiApiKeyPlaceholder": "Enter your Civitai API key",
|
||||
"civitaiApiKeyHelp": "Used for authentication when downloading models from Civitai",
|
||||
"civitaiApiKey": "CivitAI API Key",
|
||||
"civitaiApiKeyPlaceholder": "Enter your CivitAI API key",
|
||||
"civitaiApiKeyHelp": "Used for authentication when downloading models from CivitAI",
|
||||
"civitaiApiKeyConfigured": "Configured",
|
||||
"civitaiApiKeyNotConfigured": "Not configured",
|
||||
"civitaiApiKeySet": "Set up",
|
||||
"civitaiHost": {
|
||||
"label": "Civitai host",
|
||||
"help": "Choose which Civitai site opens when using View on Civitai links.",
|
||||
"label": "CivitAI host",
|
||||
"help": "Choose which CivitAI site opens when using View on CivitAI links.",
|
||||
"options": {
|
||||
"com": "civitai.com (SFW)",
|
||||
"red": "civitai.red (unrestricted)"
|
||||
@@ -319,8 +352,8 @@
|
||||
},
|
||||
"aria2HelpLink": "Learn how to set up the aria2 download backend",
|
||||
"civitaiHostBanner": {
|
||||
"title": "Civitai host preference available",
|
||||
"content": "Civitai now uses civitai.com for SFW content and civitai.red for unrestricted content. You can change which site opens by default in Settings.",
|
||||
"title": "CivitAI host preference available",
|
||||
"content": "CivitAI now uses civitai.com for SFW content and civitai.red for unrestricted content. You can change which site opens by default in Settings.",
|
||||
"openSettings": "Open Settings"
|
||||
},
|
||||
"openSettingsFileLocation": {
|
||||
@@ -450,7 +483,7 @@
|
||||
},
|
||||
"layoutSettings": {
|
||||
"groupByModel": "Group by Model",
|
||||
"groupByModelHelp": "When enabled, only the latest version of each Civitai model is shown as a single card. Older versions are hidden.",
|
||||
"groupByModelHelp": "When enabled, only the latest version of each CivitAI model is shown as a single card. Older versions are hidden.",
|
||||
"displayDensity": "Display Density",
|
||||
"displayDensityOptions": {
|
||||
"default": "Default",
|
||||
@@ -555,7 +588,7 @@
|
||||
},
|
||||
"downloadPathTemplates": {
|
||||
"title": "Download Path Templates",
|
||||
"help": "Configure folder structures for different model types when downloading from Civitai.",
|
||||
"help": "Configure folder structures for different model types when downloading from CivitAI.",
|
||||
"availablePlaceholders": "Available placeholders:",
|
||||
"templateOptions": {
|
||||
"flatStructure": "Flat Structure",
|
||||
@@ -592,7 +625,7 @@
|
||||
"exampleImages": {
|
||||
"downloadLocation": "Download Location",
|
||||
"downloadLocationPlaceholder": "Enter folder path for example images",
|
||||
"downloadLocationHelp": "Enter the folder path where example images from Civitai will be saved",
|
||||
"downloadLocationHelp": "Enter the folder path where example images from CivitAI will be saved",
|
||||
"autoDownload": "Auto Download Example Images",
|
||||
"autoDownloadHelp": "Automatically download example images for models that don't have them (requires download location to be set)",
|
||||
"openMode": "Open Example Images Action",
|
||||
@@ -647,7 +680,7 @@
|
||||
},
|
||||
"metadataArchive": {
|
||||
"enableArchiveDb": "Enable Metadata Archive Database",
|
||||
"enableArchiveDbHelp": "Use a local database to access metadata for models that have been deleted from Civitai.",
|
||||
"enableArchiveDbHelp": "Use a local database to access metadata for models that have been deleted from CivitAI.",
|
||||
"status": "Status",
|
||||
"statusAvailable": "Available",
|
||||
"statusUnavailable": "Not Available",
|
||||
@@ -750,7 +783,7 @@
|
||||
"fullTooltip": "Reload all model details from metadata files—use if the library looks out of date or after manual edits."
|
||||
},
|
||||
"fetch": {
|
||||
"title": "Fetch metadata from Civitai",
|
||||
"title": "Fetch metadata from CivitAI",
|
||||
"action": "Fetch"
|
||||
},
|
||||
"download": {
|
||||
@@ -825,10 +858,10 @@
|
||||
"enrichHfAgent": "Enrich HF Metadata (AI)"
|
||||
},
|
||||
"contextMenu": {
|
||||
"refreshMetadata": "Refresh Civitai Data",
|
||||
"refreshMetadata": "Refresh CivitAI Data",
|
||||
"checkUpdates": "Check Updates",
|
||||
"linkModel": "Link Model",
|
||||
"linkCivitai": "Link to Civitai",
|
||||
"linkCivitai": "Link to CivitAI",
|
||||
"linkHuggingFace": "Link to HuggingFace",
|
||||
"copySyntax": "Copy LoRA Syntax",
|
||||
"copyFilename": "Copy Model Filename",
|
||||
@@ -860,6 +893,7 @@
|
||||
"actions": {
|
||||
"sendCheckpoint": "Send to ComfyUI",
|
||||
"sendRecipe": "Send to ComfyUI",
|
||||
"copyRecipeSyntax": "Copy Recipe Syntax",
|
||||
"deleteRecipeWithShortcut": "Delete recipe (Del)"
|
||||
},
|
||||
"navigation": {
|
||||
@@ -867,12 +901,110 @@
|
||||
"previousWithShortcut": "Previous recipe (←)",
|
||||
"nextWithShortcut": "Next recipe (→)"
|
||||
},
|
||||
"modal": {
|
||||
"metadata": {
|
||||
"id": "ID"
|
||||
},
|
||||
"actions": {
|
||||
"openFileLocation": "Open File Location",
|
||||
"copyId": "Copy recipe ID"
|
||||
},
|
||||
"openFileLocation": {
|
||||
"success": "File location opened successfully",
|
||||
"failed": "Failed to open file location",
|
||||
"copied": "Path copied to clipboard: {{path}}",
|
||||
"clipboardFallback": "Path: {{path}}"
|
||||
}
|
||||
},
|
||||
"workflow": {
|
||||
"sendWorkflow": "Send Workflow to ComfyUI",
|
||||
"sent": "Workflow sent to ComfyUI",
|
||||
"sendFailed": "Failed to send workflow to ComfyUI",
|
||||
"noWorkflow": "No embedded workflow found in this recipe"
|
||||
},
|
||||
"status": {
|
||||
"ready": "Ready to use",
|
||||
"missingCount": "{count} missing",
|
||||
"deletedCount": "{count} deleted",
|
||||
"downloadMissing": "Download {count} missing LoRAs",
|
||||
"downloadMissingTooltip": "Click to download missing LoRAs"
|
||||
},
|
||||
"loraStatus": {
|
||||
"none": "No LoRAs in this recipe",
|
||||
"allAvailable": "All LoRAs available - Ready to use",
|
||||
"missing": "{missing} of {total} LoRAs missing",
|
||||
"missingAndUnavailable": "{missing} of {total} LoRAs missing, {unavailable} unavailable (deleted from source or unresolvable hash)",
|
||||
"partial": "{unavailable} of {total} LoRAs unavailable (deleted from source or unresolvable hash) - skipped when recipe is used",
|
||||
"noneUsable": "No usable LoRAs - {unavailable} of {total} deleted from source or unresolvable hash"
|
||||
},
|
||||
"resources": {
|
||||
"inLibrary": "In Library",
|
||||
"notInLibrary": "Not in Library",
|
||||
"deleted": "Deleted",
|
||||
"hashInvalid": "Unresolvable Hash",
|
||||
"inLibraryTooltip": "This model exists in your local library",
|
||||
"notInLibraryTooltip": "This model is not in your library",
|
||||
"deletedTooltip": "This LoRA was deleted from the source and is no longer available for download",
|
||||
"hashInvalidTooltip": "This LoRA hash cannot be resolved on CivitAI - the model may have been updated",
|
||||
"noLorasAssociated": "No LoRAs associated with this recipe",
|
||||
"noLorasWhyToggle": "Why no LoRAs?",
|
||||
"noLorasImportMethod": "Import method",
|
||||
"noLorasInferredNote": "Possible reason (inferred) — this recipe was imported before import diagnostics were recorded.",
|
||||
"noLorasChannels": {
|
||||
"batch_import_url": "Batch import (image URL)",
|
||||
"batch_import_local": "Batch import (local file)",
|
||||
"url": "Image URL import",
|
||||
"local": "Local file import",
|
||||
"upload": "Image upload",
|
||||
"widget": "Saved from workflow",
|
||||
"reimport_url": "Re-import (image URL)",
|
||||
"reimport_local": "Re-import (local file)"
|
||||
},
|
||||
"noLorasReasons": {
|
||||
"no_loras_used": "The generation metadata is complete and does not reference any LoRAs.",
|
||||
"api_meta_no_lora_resources": "The source API returned no LoRA resource data for this image. LoRAs shown on the CivitAI page may come from internal data that the public API does not expose.",
|
||||
"api_meta_missing": "The source API returned no generation metadata for this image.",
|
||||
"no_embedded_metadata": "The image has no embedded generation metadata, so LoRA information could not be recovered.",
|
||||
"workflow_metadata_limited": "The image's embedded metadata is a ComfyUI workflow; extracting LoRA information from workflows is limited.",
|
||||
"video_no_metadata": "Video files do not carry embedded generation metadata.",
|
||||
"metadata_unsupported": "The image contains metadata in a format that could not be parsed.",
|
||||
"unknown": "The reason could not be determined from the stored recipe data."
|
||||
},
|
||||
"noLorasDetails": {
|
||||
"apiMetaFields": "API metadata fields",
|
||||
"modelVersionIds": "Model version IDs reported",
|
||||
"embeddedMetadata": "Embedded metadata",
|
||||
"present": "found",
|
||||
"absent": "none"
|
||||
},
|
||||
"download": "Download",
|
||||
"downloadLoraTooltip": "Download this LoRA",
|
||||
"preparingDownload": "Preparing download...",
|
||||
"reconnect": "Reconnect",
|
||||
"reconnectTooltip": "Reconnect with a local LoRA",
|
||||
"reconnectInstructions": "Enter LoRA syntax or name to reconnect:",
|
||||
"reconnectExample": "Example: <lora:name:1> or just the name",
|
||||
"reconnectPlaceholder": "Enter LoRA name or syntax",
|
||||
"reconnectSuggestionsLoading": "Searching local library...",
|
||||
"reconnectSuggestionsEmpty": "No matching LoRAs in your local library",
|
||||
"reconnectMatchSameHash": "Same hash",
|
||||
"reconnectMatchSameVersion": "Same model version",
|
||||
"reconnectMatchSimilarFilename": "Similar filename",
|
||||
"reconnectMatchSimilarName": "Similar name",
|
||||
"undoReconnect": "Undo",
|
||||
"undoReconnectTooltip": "Restore the association this entry had before reconnecting",
|
||||
"undoReconnectTooltipNamed": "Restore to {name} (the association before reconnecting)",
|
||||
"viewOnCivitai": "View on CivitAI",
|
||||
"openLoraDetails": "View {name} in the LoRA library",
|
||||
"openCheckpointDetails": "View {name} in the model library",
|
||||
"checkpointDeletedTooltip": "This checkpoint was deleted from the source and can no longer be downloaded - reconnect it with a local model",
|
||||
"checkpointHashInvalidTooltip": "This checkpoint hash cannot be resolved on CivitAI - the model may have been updated",
|
||||
"reconnectCheckpoint": "Reconnect",
|
||||
"reconnectCheckpointTooltip": "Reconnect with a local checkpoint",
|
||||
"checkpointReconnectInstructions": "Enter checkpoint name to reconnect:",
|
||||
"checkpointReconnectPlaceholder": "Enter checkpoint name",
|
||||
"checkpointReconnectSuggestionsEmpty": "No matching checkpoints in your local library"
|
||||
},
|
||||
"controls": {
|
||||
"import": {
|
||||
"action": "Import",
|
||||
@@ -910,7 +1042,7 @@
|
||||
"downloadingLoras": "Downloading LoRAs...",
|
||||
"savingRecipe": "Saving recipe...",
|
||||
"startingDownload": "Starting download for LoRA {current}/{total}",
|
||||
"deletedFromCivitai": "Deleted from Civitai",
|
||||
"deletedFromCivitai": "Deleted from CivitAI",
|
||||
"inLibrary": "In Library",
|
||||
"notInLibrary": "Not in Library",
|
||||
"earlyAccessRequired": "This LoRA requires early access payment to download.",
|
||||
@@ -1238,7 +1370,7 @@
|
||||
"download": {
|
||||
"title": "Download Model from URL",
|
||||
"titleWithType": "Download {type} from URL",
|
||||
"civitaiUrl": "Civitai URL(s):",
|
||||
"civitaiUrl": "CivitAI URL(s):",
|
||||
"placeholder": "https://civitai.com/models/...",
|
||||
"urlHint": "Enter one CivitAI, CivArchive, or Hugging Face URL per line. Supports multiple URLs for batch download.",
|
||||
"selectHfFiles": "Select file(s) to download from this repository:",
|
||||
@@ -1273,7 +1405,7 @@
|
||||
"inLibrary": "In Library"
|
||||
},
|
||||
"errors": {
|
||||
"invalidUrl": "Invalid Civitai URL format",
|
||||
"invalidUrl": "Invalid CivitAI URL format",
|
||||
"noVersions": "No versions available for this model",
|
||||
"mixedSources": "Cannot mix CivitAI and Hugging Face URLs in the same batch.",
|
||||
"noModelFiles": "No model files found in this repository."
|
||||
@@ -1387,7 +1519,7 @@
|
||||
"title": "Local Example Images",
|
||||
"message": "No local example images found for this model. View options:",
|
||||
"downloadOption": {
|
||||
"title": "Download from Civitai",
|
||||
"title": "Download from CivitAI",
|
||||
"description": "Save remote examples locally for offline use and faster loading"
|
||||
},
|
||||
"importOption": {
|
||||
@@ -1414,7 +1546,7 @@
|
||||
"confirmAction": "Save & Link"
|
||||
},
|
||||
"relinkCivitai": {
|
||||
"title": "Re-link to Civitai",
|
||||
"title": "Re-link to CivitAI",
|
||||
"warning": "Warning:",
|
||||
"warningText": "This is a potentially destructive operation. Re-linking will:",
|
||||
"warningList": {
|
||||
@@ -1423,15 +1555,15 @@
|
||||
"unintendedConsequences": "May have other unintended consequences"
|
||||
},
|
||||
"proceedText": "Only proceed if you're sure this is what you want.",
|
||||
"urlLabel": "Civitai Model URL:",
|
||||
"urlLabel": "CivitAI Model URL:",
|
||||
"urlPlaceholder": "https://civitai.com/models/12345/model-name?modelVersionId=67890 or https://civitai.red/models/12345/model-name?modelVersionId=67890",
|
||||
"helpText": {
|
||||
"title": "Paste any Civitai or CivitArchive model URL. Supported formats:",
|
||||
"title": "Paste any CivitAI or CivitArchive model URL. Supported formats:",
|
||||
"format1": "https://civitai.com/models/12345",
|
||||
"format2": "https://civitai.com/models/12345?modelVersionId=67890",
|
||||
"format3": "https://civitai.com/models/12345/model-name?modelVersionId=67890",
|
||||
"note": "Note: If no modelVersionId is provided, the latest version will be used.",
|
||||
"format4": "https://civarchive.com/models/12345 (CivitArchive)"
|
||||
"format4": "https://civarchive.com/models/12345 (CivArchive)"
|
||||
},
|
||||
"confirmAction": "Confirm Re-link"
|
||||
},
|
||||
@@ -1441,8 +1573,8 @@
|
||||
"editFileName": "Edit file name",
|
||||
"editBaseModel": "Edit base model",
|
||||
"editVersionName": "Edit version name",
|
||||
"viewOnCivitai": "View on Civitai",
|
||||
"viewOnCivitaiText": "View on Civitai",
|
||||
"viewOnCivitai": "View on CivitAI",
|
||||
"viewOnCivitaiText": "View on CivitAI",
|
||||
"viewOnHuggingFace": "View on Hugging Face",
|
||||
"viewOnHuggingFaceText": "View on Hugging Face",
|
||||
"viewCreatorProfile": "View Creator Profile",
|
||||
@@ -1494,7 +1626,11 @@
|
||||
"clipSkip": "Clip Skip",
|
||||
"valuePlaceholder": "Value",
|
||||
"add": "Add",
|
||||
"invalidRange": "Invalid range format. Use x.x-y.y"
|
||||
"invalidRange": "Invalid range format. Use x.x-y.y",
|
||||
"invalidValue": "Please enter a valid number",
|
||||
"saveFailed": "Failed to save preset parameter",
|
||||
"added": "Preset parameter added",
|
||||
"updated": "Preset parameter updated"
|
||||
},
|
||||
"triggerWords": {
|
||||
"label": "Trigger Words",
|
||||
@@ -1505,7 +1641,7 @@
|
||||
"addPlaceholder": "Type to add or click suggestions below",
|
||||
"editWord": "Edit trigger word",
|
||||
"editPlaceholder": "Edit trigger word",
|
||||
"copyWord": "Copy trigger word",
|
||||
"copyOrEditWord": "Click to copy, double-click to edit",
|
||||
"deleteWord": "Delete trigger word",
|
||||
"suggestions": {
|
||||
"noSuggestions": "No suggestions available",
|
||||
@@ -1544,7 +1680,7 @@
|
||||
},
|
||||
"license": {
|
||||
"noImageSell": "No selling generated content",
|
||||
"noRentCivit": "No Civitai generation",
|
||||
"noRentCivit": "No CivitAI generation",
|
||||
"noRent": "No generation services",
|
||||
"noSell": "No selling models",
|
||||
"creditRequired": "Creator credit required",
|
||||
@@ -1565,8 +1701,8 @@
|
||||
"showCount": "Show examples ({count})",
|
||||
"hideExamples": "Hide examples",
|
||||
"addExamples": "Add examples",
|
||||
"previousExample": "Previous example",
|
||||
"nextExample": "Next example",
|
||||
"previousExample": "Previous example ([)",
|
||||
"nextExample": "Next example (])",
|
||||
"noExamples": "No example images available",
|
||||
"addMoreExamples": "Add more examples",
|
||||
"dragDrop": "Drag & drop images or videos here",
|
||||
@@ -1609,28 +1745,28 @@
|
||||
"newer": "Newer Version",
|
||||
"newerTooltip": "This version is newer than your latest local version",
|
||||
"earlyAccess": "Early Access",
|
||||
"earlyAccessTooltip": "This version currently requires Civitai early access",
|
||||
"earlyAccessTooltip": "This version currently requires CivitAI early access",
|
||||
"paid": "Paid",
|
||||
"paidTooltip": "This version requires payment to download",
|
||||
"ignored": "Ignored",
|
||||
"ignoredTooltip": "Update notifications are disabled for this version",
|
||||
"onSiteOnly": "On-Site Only",
|
||||
"onSiteOnlyTooltip": "This version is only available for on-site generation on Civitai"
|
||||
"onSiteOnlyTooltip": "This version is only available for on-site generation on CivitAI"
|
||||
},
|
||||
"actions": {
|
||||
"download": "Download",
|
||||
"downloadTooltip": "Download this version",
|
||||
"downloadChooseFilesTooltip": "Choose which files to download",
|
||||
"downloadEarlyAccessTooltip": "Download this early access version from Civitai",
|
||||
"downloadPaidTooltip": "Download this paid version from Civitai",
|
||||
"downloadNotAllowedTooltip": "This version is only available for on-site generation on Civitai",
|
||||
"downloadEarlyAccessTooltip": "Download this early access version from CivitAI",
|
||||
"downloadPaidTooltip": "Download this paid version from CivitAI",
|
||||
"downloadNotAllowedTooltip": "This version is only available for on-site generation on CivitAI",
|
||||
"delete": "Delete",
|
||||
"deleteTooltip": "Delete this local version",
|
||||
"ignore": "Ignore",
|
||||
"unignore": "Unignore",
|
||||
"ignoreTooltip": "Ignore update notifications for this version",
|
||||
"unignoreTooltip": "Resume update notifications for this version",
|
||||
"viewVersionOnCivitai": "View version on Civitai",
|
||||
"viewVersionOnCivitai": "View version on CivitAI",
|
||||
"earlyAccessTooltip": "Requires early access purchase",
|
||||
"resumeModelUpdates": "Resume updates for this model",
|
||||
"ignoreModelUpdates": "Ignore updates for this model",
|
||||
@@ -1651,7 +1787,7 @@
|
||||
},
|
||||
"empty": "No version history available for this model yet.",
|
||||
"error": "Failed to load versions.",
|
||||
"missingModelId": "This model is missing a Civitai model id.",
|
||||
"missingModelId": "This model is missing a CivitAI model id.",
|
||||
"hfGroupInfo": "This is a HuggingFace model group. Open the library to see all versions in the grid.",
|
||||
"confirm": {
|
||||
"delete": "Delete this version from your library?"
|
||||
@@ -1735,14 +1871,14 @@
|
||||
"tips": {
|
||||
"title": "Tips & Tricks",
|
||||
"civitai": {
|
||||
"title": "Civitai Integration",
|
||||
"description": "Connect your Civitai account: Visit Profile Avatar → Settings → API Keys → Add API Key, then paste it in Lora Manager settings.",
|
||||
"alt": "Civitai API Setup"
|
||||
"title": "CivitAI Integration",
|
||||
"description": "Connect your CivitAI account: Visit Profile Avatar → Settings → API Keys → Add API Key, then paste it in Lora Manager settings.",
|
||||
"alt": "CivitAI API Setup"
|
||||
},
|
||||
"download": {
|
||||
"title": "Easy Download",
|
||||
"description": "Use Civitai URLs to quickly download and install new models.",
|
||||
"alt": "Civitai Download"
|
||||
"description": "Use CivitAI URLs to quickly download and install new models.",
|
||||
"alt": "CivitAI Download"
|
||||
},
|
||||
"recipes": {
|
||||
"title": "Save Recipes",
|
||||
@@ -1830,10 +1966,52 @@
|
||||
"tabs": {
|
||||
"gettingStarted": "Getting Started",
|
||||
"updateVlogs": "Update Vlogs",
|
||||
"documentation": "Documentation"
|
||||
"documentation": "Documentation",
|
||||
"shortcuts": "Shortcuts"
|
||||
},
|
||||
"gettingStarted": {
|
||||
"title": "Getting Started with LoRA Manager"
|
||||
"title": "Getting Started with LoRA Manager",
|
||||
"replayTutorial": "Replay Tutorial"
|
||||
},
|
||||
"shortcuts": {
|
||||
"title": "Keyboard & Mouse Shortcuts",
|
||||
"groups": {
|
||||
"general": "General",
|
||||
"actions": "Actions",
|
||||
"selection": "Selection & Bulk Mode",
|
||||
"navigation": "Navigation",
|
||||
"modelModal": "Model / Recipe Modal",
|
||||
"mediaViewer": "Media Viewer / Showcase"
|
||||
},
|
||||
"keys": {
|
||||
"click": "Click",
|
||||
"drag": "Drag",
|
||||
"rightClick": "Right-click",
|
||||
"letter": "Letter",
|
||||
"swipe": "Swipe"
|
||||
},
|
||||
"entries": {
|
||||
"focusSearch": "Focus search",
|
||||
"closeModal": "Close modal / panel",
|
||||
"openShortcuts": "Open this shortcuts panel",
|
||||
"refresh": "Refresh model list",
|
||||
"fetchMetadata": "Fetch metadata from CivitAI (model pages only)",
|
||||
"downloadModel": "Download a model (model pages only)",
|
||||
"toggleBulkMode": "Toggle bulk mode",
|
||||
"selectAll": "Select all visible models",
|
||||
"rangeSelect": "Range select",
|
||||
"marqueeSelect": "Marquee-select cards (on empty grid area)",
|
||||
"exitBulkMode": "Exit bulk mode",
|
||||
"bulkActions": "On selected card: bulk actions menu",
|
||||
"globalActions": "On empty page area: global actions menu (update check, manage excluded models)",
|
||||
"scrollPages": "Scroll pages",
|
||||
"jumpAlphabet": "Jump alphabet bar",
|
||||
"prevNext": "Previous / next model",
|
||||
"deleteEntry": "Delete",
|
||||
"cycleMedia": "Cycle media ([ / ] in showcase gallery)",
|
||||
"swipeTouch": "Cycle media on touch devices",
|
||||
"closeViewer": "Close viewer"
|
||||
}
|
||||
},
|
||||
"updateVlogs": {
|
||||
"title": "Latest Updates",
|
||||
@@ -1850,7 +2028,8 @@
|
||||
"settings": "Settings & Configuration",
|
||||
"extensions": "Extensions",
|
||||
"newBadge": "NEW"
|
||||
}
|
||||
},
|
||||
"newContentBadge": "New"
|
||||
},
|
||||
"update": {
|
||||
"title": "Check for Updates",
|
||||
@@ -1926,7 +2105,7 @@
|
||||
"submitGithubIssue": "Submit GitHub Issue",
|
||||
"joinDiscord": "Join Discord",
|
||||
"youtubeChannel": "YouTube Channel",
|
||||
"civitaiProfile": "Civitai Profile",
|
||||
"civitaiProfile": "CivitAI Profile",
|
||||
"supportKofi": "Support on Ko-fi",
|
||||
"supportPatreon": "Support on Patreon"
|
||||
},
|
||||
@@ -2009,7 +2188,10 @@
|
||||
"preparingForDownloadFailed": "Error preparing LoRAs for download",
|
||||
"enterLoraName": "Please enter a LoRA name or syntax",
|
||||
"reconnectedSuccessfully": "LoRA reconnected successfully",
|
||||
"reconnectBaseModelMismatch": "Reconnected, but base models differ (recipe: {recipe}, LoRA: {lora}) — they are architecture-compatible",
|
||||
"reconnectFailed": "Error reconnecting LoRA: {message}",
|
||||
"loraRestored": "LoRA restored to its previous association",
|
||||
"loraRestoreFailed": "Error restoring LoRA: {message}",
|
||||
"noPromptToSend": "No prompt to send",
|
||||
"cannotSend": "Cannot send recipe: Missing recipe ID",
|
||||
"sendFailed": "Failed to send recipe to workflow",
|
||||
@@ -2017,6 +2199,16 @@
|
||||
"missingCheckpointPath": "Checkpoint path not available",
|
||||
"missingCheckpointInfo": "Missing checkpoint information",
|
||||
"downloadCheckpointFailed": "Failed to download checkpoint: {message}",
|
||||
"enterCheckpointName": "Please enter a checkpoint name",
|
||||
"checkpointReconnectedSuccessfully": "Checkpoint reconnected successfully",
|
||||
"reconnectCheckpointBaseModelMismatch": "Reconnected, but base models differ (recipe: {recipe}, checkpoint: {checkpoint}) — they are architecture-compatible",
|
||||
"checkpointReconnectFailed": "Error reconnecting checkpoint: {message}",
|
||||
"checkpointRestored": "Checkpoint restored to its previous association",
|
||||
"checkpointRestoreFailed": "Error restoring checkpoint: {message}",
|
||||
"checkpointDownloadUnavailable": "This checkpoint cannot be downloaded without CivitAI identifiers - try reconnecting it with a local checkpoint",
|
||||
"missingLoraDownloadInfo": "Missing download information for this LoRA",
|
||||
"hashNotFoundOnCivitai": "This LoRA hash cannot be resolved on CivitAI - the model may have been updated or the hash is invalid",
|
||||
"downloadLoraFailed": "Failed to download LoRA: {message}",
|
||||
"cannotDelete": "Cannot delete recipe: Missing recipe ID",
|
||||
"deleteConfirmationError": "Error showing delete confirmation",
|
||||
"deletedSuccessfully": "Recipe deleted successfully",
|
||||
@@ -2098,8 +2290,8 @@
|
||||
"bulkUpdatesChecking": "Checking selected {type}(s) for updates...",
|
||||
"bulkUpdatesSuccess": "Updates available for {count} selected {type}(s)",
|
||||
"bulkUpdatesNone": "No updates found for selected {type}(s)",
|
||||
"bulkUpdatesMissing": "Selected {type}(s) are not linked to Civitai updates",
|
||||
"bulkUpdatesPartialMissing": "Skipped {missing} selected {type}(s) without Civitai links",
|
||||
"bulkUpdatesMissing": "Selected {type}(s) are not linked to CivitAI updates",
|
||||
"bulkUpdatesPartialMissing": "Skipped {missing} selected {type}(s) without CivitAI links",
|
||||
"bulkUpdatesFailed": "Failed to check updates for selected {type}(s): {message}",
|
||||
"invalidCharactersRemoved": "Invalid characters removed from filename",
|
||||
"filenameCannotBeEmpty": "File name cannot be empty",
|
||||
@@ -2225,7 +2417,7 @@
|
||||
"contextMenu": {
|
||||
"contentRatingSet": "Content rating set to {level}",
|
||||
"contentRatingFailed": "Failed to set content rating: {message}",
|
||||
"relinkSuccess": "Model successfully re-linked to Civitai",
|
||||
"relinkSuccess": "Model successfully re-linked to CivitAI",
|
||||
"relinkFailed": "Error: {message}",
|
||||
"linkHfSuccess": "Model successfully linked to HuggingFace",
|
||||
"linkHfFailed": "Error: {message}",
|
||||
@@ -2319,7 +2511,7 @@
|
||||
},
|
||||
"issues": {
|
||||
"civitai_api_key": {
|
||||
"title": "Civitai API Key"
|
||||
"title": "CivitAI API Key"
|
||||
},
|
||||
"cache_health": {
|
||||
"title": "Model Cache Health"
|
||||
@@ -2373,9 +2565,9 @@
|
||||
},
|
||||
"communitySupport": {
|
||||
"title": "Keep LoRA Manager Thriving with Your Support ❤️",
|
||||
"content": "LoRA Manager is a passion project maintained full-time by a solo developer. Your support on Ko-fi helps cover development costs, keeps new updates coming, and unlocks a license key for the LM Civitai Extension as a thank-you gift. Every contribution truly makes a difference.",
|
||||
"content": "LoRA Manager is a passion project maintained full-time by a solo developer. Your support on Ko-fi helps cover development costs, keeps new updates coming, and unlocks a license key for the LM CivitAI Extension as a thank-you gift. Every contribution truly makes a difference.",
|
||||
"supportCta": "Support on Ko-fi",
|
||||
"learnMore": "LM Civitai Extension Tutorial"
|
||||
"learnMore": "LM CivitAI Extension Tutorial"
|
||||
},
|
||||
"cacheHealth": {
|
||||
"corrupted": {
|
||||
|
||||
+394
-202
File diff suppressed because it is too large
Load Diff
+423
-231
File diff suppressed because it is too large
Load Diff
+427
-235
File diff suppressed because it is too large
Load Diff
+353
-161
@@ -50,6 +50,27 @@
|
||||
"mb": "MB",
|
||||
"gb": "GB",
|
||||
"tb": "TB"
|
||||
},
|
||||
"scanProgress": {
|
||||
"refreshing": "{type}を更新中...",
|
||||
"fullRebuilding": "{type}を完全に再構築中...",
|
||||
"actionRefresh": "更新",
|
||||
"actionFullRebuild": "完全な再構築",
|
||||
"actionRefreshLower": "更新",
|
||||
"actionRebuildLower": "再構築",
|
||||
"stages": {
|
||||
"scan_folders": "フォルダをスキャン中...",
|
||||
"count_models": "{total} 件のファイルが見つかりました",
|
||||
"process_models": "モデルを処理中",
|
||||
"reconcile_scan": "変更を確認中...",
|
||||
"process_new": "新しいモデルを処理中",
|
||||
"finalizing": "最終処理中..."
|
||||
},
|
||||
"eta": {
|
||||
"lessThanMinute": "残り1分未満",
|
||||
"minutes": "残り約 {minutes} 分",
|
||||
"hours": "残り約 {hours} 時間 {minutes} 分"
|
||||
}
|
||||
}
|
||||
},
|
||||
"onboarding": {
|
||||
@@ -67,15 +88,15 @@
|
||||
"steps": {
|
||||
"fetch": {
|
||||
"title": "モデルメタデータの取得",
|
||||
"content": "<strong>取得</strong>ボタンをクリックして、Civitaiからモデルのメタデータとプレビュー画像をダウンロードします。"
|
||||
"content": "<strong>取得</strong>ボタンをクリックして、CivitAIからモデルのメタデータとプレビュー画像をダウンロードします。"
|
||||
},
|
||||
"download": {
|
||||
"title": "新しいモデルのダウンロード",
|
||||
"content": "<strong>ダウンロード</strong>ボタンを使って、CivitaiのURLから直接モデルをダウンロードできます。"
|
||||
"content": "<strong>ダウンロード</strong>ボタンを使って、CivitAIのURLから直接モデルをダウンロードできます。"
|
||||
},
|
||||
"bulk": {
|
||||
"title": "一括操作",
|
||||
"content": "このボタンをクリックするか、<span class=\"onboarding-shortcut\">B</span>キーを押して一括モードに入ります。複数のモデルを選択して一括操作が可能です。<span class=\"onboarding-shortcut\">Ctrl+A</span>で表示中のモデルをすべて選択できます。"
|
||||
"content": "このボタンをクリックするか、<span class=\"onboarding-shortcut\">B</span>キーを押して一括モードに入り、複数のモデルを選択して一括操作を実行できます。<br>• <span class=\"onboarding-shortcut\">Ctrl/Cmd+A</span>で表示中のモデルをすべて選択、<span class=\"onboarding-shortcut\">Shift+Click</span>で範囲選択。<br>• <span class=\"onboarding-shortcut\">Esc</span>キーまたは空白部分をクリックすると一括モードを終了します。"
|
||||
},
|
||||
"searchOptions": {
|
||||
"title": "検索オプション",
|
||||
@@ -95,7 +116,19 @@
|
||||
},
|
||||
"contextMenu": {
|
||||
"title": "コンテキストメニュー",
|
||||
"content": "<strong>モデルカードを右クリック</strong>すると追加の操作ができるコンテキストメニューが表示されます。"
|
||||
"content": "<strong>モデルカードを右クリック</strong>すると、移動、削除、メタデータの編集などのカード操作を含むコンテキストメニューが表示されます。"
|
||||
},
|
||||
"marqueeSelect": {
|
||||
"title": "ドラッグで選択",
|
||||
"content": "グリッドの空白部分で<strong>マウスの左ボタン</strong>を押したままドラッグすると、複数のカードを一度に選択する矩形(マーキー)を描画できます。"
|
||||
},
|
||||
"dragToSidebar": {
|
||||
"title": "ドラッグで整理",
|
||||
"content": "モデルカードをサイドバーのフォルダにドラッグすると、ファイルをそこに移動できます。一括モードで複数選択したカードでも同様に機能します。"
|
||||
},
|
||||
"contextMenus": {
|
||||
"title": "その他のコンテキストメニュー",
|
||||
"content": "一括モードでは、<strong>選択したカードを右クリック</strong>すると一括操作メニューが表示されます。<strong>ページの空白部分を右クリック</strong>すると、更新の確認や除外モデルの管理などのグローバル操作メニューが表示されます。"
|
||||
}
|
||||
}
|
||||
},
|
||||
@@ -103,17 +136,17 @@
|
||||
"actions": {
|
||||
"addToFavorites": "お気に入りに追加",
|
||||
"removeFromFavorites": "お気に入りから削除",
|
||||
"viewOnCivitai": "Civitaiで表示",
|
||||
"notAvailableFromCivitai": "Civitaiでは利用できません",
|
||||
"viewOnCivitai": "CivitAIで表示",
|
||||
"notAvailableFromCivitai": "CivitAIでは利用できません",
|
||||
"viewOnHuggingFace": "Hugging Face で見る",
|
||||
"sendToWorkflow": "ComfyUIに送信(クリック:追加、Shift+クリック:置換)",
|
||||
"copyLoRASyntax": "LoRA構文をコピー",
|
||||
"checkpointNameCopied": "checkpointの名前をコピーしました",
|
||||
"checkpointNameCopied": "Checkpointの名前をコピーしました",
|
||||
"toggleBlur": "ぼかしの切り替え",
|
||||
"show": "表示",
|
||||
"openExampleImages": "例画像フォルダを開く",
|
||||
"replacePreview": "プレビューを置換",
|
||||
"copyCheckpointName": "checkpoint名をコピー",
|
||||
"copyCheckpointName": "Checkpoint名をコピー",
|
||||
"copyEmbeddingName": "embedding名をコピー",
|
||||
"embeddingNameCopied": "Embedding構文をコピーしました",
|
||||
"sendCheckpointToWorkflow": "ComfyUIに送信",
|
||||
@@ -131,13 +164,13 @@
|
||||
"updateFailed": "お気に入り状態の更新に失敗しました"
|
||||
},
|
||||
"sendToWorkflow": {
|
||||
"checkpointNotImplemented": "checkpointをワークフローに送信 - 実装予定の機能",
|
||||
"checkpointNotImplemented": "Checkpointをワークフローに送信 - 実装予定の機能",
|
||||
"missingPath": "このカードのモデルパスを特定できません"
|
||||
},
|
||||
"exampleImages": {
|
||||
"checkError": "例画像の確認中にエラーが発生しました",
|
||||
"missingHash": "モデルハッシュ情報がありません。",
|
||||
"noRemoteImagesAvailable": "このモデルのCivitaiでのリモート例画像は利用できません"
|
||||
"noRemoteImagesAvailable": "このモデルのCivitAIでのリモート例画像は利用できません"
|
||||
},
|
||||
"badges": {
|
||||
"update": "アップデート",
|
||||
@@ -160,7 +193,7 @@
|
||||
},
|
||||
"checkModelUpdates": {
|
||||
"label": "アップデートを確認",
|
||||
"loading": "{type} のアップデートを確認中…",
|
||||
"loading": "{type} のアップデートを確認中...",
|
||||
"success": "{type} のアップデートが {count} 件見つかりました",
|
||||
"none": "すべての {type} は最新です",
|
||||
"error": "{type} のアップデート確認に失敗しました: {message}"
|
||||
@@ -173,17 +206,17 @@
|
||||
"error": "例画像フォルダのクリーンアップに失敗しました:{message}"
|
||||
},
|
||||
"fetchMissingLicenses": {
|
||||
"label": "Refresh license metadata",
|
||||
"loading": "Refreshing license metadata for {typePlural}...",
|
||||
"success": "Updated license metadata for {count} {typePlural}",
|
||||
"none": "All {typePlural} already have license metadata",
|
||||
"error": "Failed to refresh license metadata for {typePlural}: {message}"
|
||||
"label": "ライセンスメタデータを更新",
|
||||
"loading": "{typePlural}のライセンスメタデータを更新中...",
|
||||
"success": "{count} 件の{typePlural}のライセンスメタデータを更新しました",
|
||||
"none": "すべての{typePlural}には既にライセンスメタデータがあります",
|
||||
"error": "{typePlural}のライセンスメタデータを更新できませんでした: {message}"
|
||||
},
|
||||
"repairRecipes": {
|
||||
"label": "レシピデータの修復",
|
||||
"loading": "レシピデータを修復中...",
|
||||
"success": "{count} 件のレシピを正常に修復しました。",
|
||||
"cancelled": "修復がキャンセルされました。{count}個のレシピが修復されました。",
|
||||
"cancelled": "修復がキャンセルされました。{count}件のレシピが修復されました。",
|
||||
"error": "レシピの修復に失敗しました: {message}"
|
||||
},
|
||||
"rematchRecipes": {
|
||||
@@ -290,15 +323,15 @@
|
||||
}
|
||||
},
|
||||
"settings": {
|
||||
"civitaiApiKey": "Civitai APIキー",
|
||||
"civitaiApiKeyPlaceholder": "Civitai APIキーを入力してください",
|
||||
"civitaiApiKeyHelp": "Civitaiからモデルをダウンロードするときの認証に使用されます",
|
||||
"civitaiApiKey": "CivitAI APIキー",
|
||||
"civitaiApiKeyPlaceholder": "CivitAI APIキーを入力してください",
|
||||
"civitaiApiKeyHelp": "CivitAIからモデルをダウンロードするときの認証に使用されます",
|
||||
"civitaiApiKeyConfigured": "設定済み",
|
||||
"civitaiApiKeyNotConfigured": "未設定",
|
||||
"civitaiApiKeySet": "設定",
|
||||
"civitaiHost": {
|
||||
"label": "Civitai ホスト",
|
||||
"help": "「View on Civitai」リンクを使うときに開く Civitai サイトを選択します。",
|
||||
"label": "CivitAI ホスト",
|
||||
"help": "「View on CivitAI」リンクを使うときに開く CivitAI サイトを選択します。",
|
||||
"options": {
|
||||
"com": "civitai.com(SFW のみ)",
|
||||
"red": "civitai.red(制限なし)"
|
||||
@@ -319,8 +352,8 @@
|
||||
},
|
||||
"aria2HelpLink": "aria2 ダウンロードバックエンドの設定方法",
|
||||
"civitaiHostBanner": {
|
||||
"title": "Civitai ホスト設定を利用できます",
|
||||
"content": "Civitai は現在、SFW コンテンツには civitai.com、制限なしコンテンツには civitai.red を使用しています。設定で既定で開くサイトを変更できます。",
|
||||
"title": "CivitAI ホスト設定を利用できます",
|
||||
"content": "CivitAI は現在、SFW コンテンツには civitai.com、制限なしコンテンツには civitai.red を使用しています。設定で既定で開くサイトを変更できます。",
|
||||
"openSettings": "設定を開く"
|
||||
},
|
||||
"openSettingsFileLocation": {
|
||||
@@ -428,7 +461,7 @@
|
||||
},
|
||||
"downloadSkipBaseModels": {
|
||||
"label": "ベースモデルのダウンロードをスキップ",
|
||||
"help": "すべてのダウンロードフローに適用されます。ここでは対応しているベースモデルのみ選択できます。",
|
||||
"help": "有効にすると、選択したベースモデルを使用するバージョンはスキップされます。",
|
||||
"searchPlaceholder": "ベースモデルを絞り込む...",
|
||||
"empty": "現在の検索に一致するベースモデルはありません。",
|
||||
"summary": {
|
||||
@@ -450,7 +483,7 @@
|
||||
},
|
||||
"layoutSettings": {
|
||||
"groupByModel": "モデルでグループ化",
|
||||
"groupByModelHelp": "有効にすると、各Civitaiモデルの最新バージョンのみが1枚のカードとして表示され、古いバージョンは非表示になります。",
|
||||
"groupByModelHelp": "有効にすると、各CivitAIモデルの最新バージョンのみが1枚のカードとして表示され、古いバージョンは非表示になります。",
|
||||
"displayDensity": "表示密度",
|
||||
"displayDensityOptions": {
|
||||
"default": "デフォルト",
|
||||
@@ -503,7 +536,7 @@
|
||||
"defaultLoraRoot": "LoRAルート",
|
||||
"defaultLoraRootHelp": "ダウンロード、インポート、移動用のデフォルトLoRAルートディレクトリを設定",
|
||||
"defaultCheckpointRoot": "Checkpointルート",
|
||||
"defaultCheckpointRootHelp": "ダウンロード、インポート、移動用のデフォルトcheckpointルートディレクトリを設定",
|
||||
"defaultCheckpointRootHelp": "ダウンロード、インポート、移動用のデフォルトCheckpointルートディレクトリを設定",
|
||||
"defaultUnetRoot": "Diffusion Modelルート",
|
||||
"defaultUnetRootHelp": "ダウンロード、インポート、移動用のデフォルトDiffusion Model (UNET)ルートディレクトリを設定",
|
||||
"defaultEmbeddingRoot": "Embeddingルート",
|
||||
@@ -517,7 +550,7 @@
|
||||
"extraFolderPaths": {
|
||||
"title": "追加フォルダーパス",
|
||||
"description": "LoRA Manager専用の追加モデルルートパス。ComfyUIの標準フォルダー外の場所からモデルを読み込みます。ComfyUIの動作を低下させる可能性のある大規模ライブラリに最適です。",
|
||||
"restartRequired": "Requires restart to take effect",
|
||||
"restartRequired": "変更を有効にするには再起動が必要です",
|
||||
"modelTypes": {
|
||||
"lora": "LoRAパス",
|
||||
"checkpoint": "Checkpointパス",
|
||||
@@ -529,8 +562,8 @@
|
||||
"saveError": "追加フォルダーパスの更新に失敗しました: {message}",
|
||||
"validation": {
|
||||
"duplicatePath": "このパスはすでに設定されています",
|
||||
"checkpointUnetOverlap": "checkpoints と diffusion models に同じパスは使用できません:{paths}",
|
||||
"checkpointUnetOverlapInline": "このパスは別のモデルタイプですでに使用されています。checkpoints と diffusion models には別々のフォルダを使用してください。"
|
||||
"checkpointUnetOverlap": "Checkpoints と diffusion models に同じパスは使用できません:{paths}",
|
||||
"checkpointUnetOverlapInline": "このパスは別のモデルタイプですでに使用されています。Checkpoints と diffusion models には別々のフォルダを使用してください。"
|
||||
}
|
||||
},
|
||||
"priorityTags": {
|
||||
@@ -540,7 +573,7 @@
|
||||
"helpLinkLabel": "優先タグのヘルプを開く",
|
||||
"modelTypes": {
|
||||
"lora": "LoRA",
|
||||
"checkpoint": "チェックポイント",
|
||||
"checkpoint": "Checkpoint",
|
||||
"embedding": "埋め込み"
|
||||
},
|
||||
"saveSuccess": "優先タグを更新しました。",
|
||||
@@ -555,7 +588,7 @@
|
||||
},
|
||||
"downloadPathTemplates": {
|
||||
"title": "ダウンロードパステンプレート",
|
||||
"help": "Civitaiからダウンロードする際の異なるモデルタイプのフォルダ構造を設定します。",
|
||||
"help": "CivitAIからダウンロードする際の異なるモデルタイプのフォルダ構造を設定します。",
|
||||
"availablePlaceholders": "利用可能なプレースホルダー:",
|
||||
"templateOptions": {
|
||||
"flatStructure": "フラット構造",
|
||||
@@ -592,7 +625,7 @@
|
||||
"exampleImages": {
|
||||
"downloadLocation": "ダウンロード場所",
|
||||
"downloadLocationPlaceholder": "例画像のフォルダパスを入力",
|
||||
"downloadLocationHelp": "Civitaiからの例画像を保存するフォルダパスを入力してください",
|
||||
"downloadLocationHelp": "CivitAIからの例画像を保存するフォルダパスを入力してください",
|
||||
"autoDownload": "例画像の自動ダウンロード",
|
||||
"autoDownloadHelp": "例画像がないモデルの例画像を自動的にダウンロードします(ダウンロード場所の設定が必要)",
|
||||
"openMode": "サンプル画像を開く動作",
|
||||
@@ -625,7 +658,7 @@
|
||||
},
|
||||
"hideEarlyAccessUpdates": {
|
||||
"label": "早期アクセス更新を非表示",
|
||||
"help": "早期アクセスのみの更新"
|
||||
"help": "有効にすると、早期アクセス更新のみのモデルには「更新あり」バッジが表示されません。"
|
||||
},
|
||||
"hidePaidUpdates": {
|
||||
"label": "有料更新を非表示",
|
||||
@@ -647,7 +680,7 @@
|
||||
},
|
||||
"metadataArchive": {
|
||||
"enableArchiveDb": "メタデータアーカイブデータベースを有効化",
|
||||
"enableArchiveDbHelp": "Civitaiから削除されたモデルのメタデータにアクセスするためにローカルデータベースを使用します。",
|
||||
"enableArchiveDbHelp": "CivitAIから削除されたモデルのメタデータにアクセスするためにローカルデータベースを使用します。",
|
||||
"status": "ステータス",
|
||||
"statusAvailable": "利用可能",
|
||||
"statusUnavailable": "利用不可",
|
||||
@@ -708,7 +741,7 @@
|
||||
"custom": "カスタム(OpenAI 互換)"
|
||||
},
|
||||
"apiBase": "APIベースURL",
|
||||
"apiBaseHelp": "LLM APIのベースURL(例:https://api.openai.com/v1)。空の場合はプロバイダーのデフォルトが使用されます。",
|
||||
"apiBaseHelp": "LLM APIのベースURL。プリセットを選択するか、カスタムURLを入力してください。ドロップダウンには対応しているすべてのプロバイダーのプリセットが表示されます。",
|
||||
"apiBasePlaceholder": "https://api.openai.com/v1",
|
||||
"apiKey": "APIキー",
|
||||
"apiKeyHelp": "LLMプロバイダーのAPIキー。ローカルに保存され、選択したLLMプロバイダー以外のサーバーに送信されることはありません。",
|
||||
@@ -750,7 +783,7 @@
|
||||
"fullTooltip": "メタデータファイルから全モデル情報を再読み込みします。リストが古いと感じるときや手動編集後に使用してください。"
|
||||
},
|
||||
"fetch": {
|
||||
"title": "Civitaiからメタデータを取得",
|
||||
"title": "CivitAIからメタデータを取得",
|
||||
"action": "取得"
|
||||
},
|
||||
"download": {
|
||||
@@ -825,10 +858,10 @@
|
||||
"enrichHfAgent": "HF メタデータをAIで補完"
|
||||
},
|
||||
"contextMenu": {
|
||||
"refreshMetadata": "Civitaiデータを更新",
|
||||
"refreshMetadata": "CivitAIデータを更新",
|
||||
"checkUpdates": "更新確認",
|
||||
"linkModel": "モデルをリンク",
|
||||
"linkCivitai": "Civitai にリンク",
|
||||
"linkCivitai": "CivitAI にリンク",
|
||||
"linkHuggingFace": "HuggingFace にリンク",
|
||||
"copySyntax": "LoRA構文をコピー",
|
||||
"copyFilename": "モデルファイル名をコピー",
|
||||
@@ -860,6 +893,7 @@
|
||||
"actions": {
|
||||
"sendCheckpoint": "ComfyUIへ送信",
|
||||
"sendRecipe": "ComfyUIへ送信",
|
||||
"copyRecipeSyntax": "レシピ構文をコピー",
|
||||
"deleteRecipeWithShortcut": "レシピを削除(Del)"
|
||||
},
|
||||
"navigation": {
|
||||
@@ -867,12 +901,110 @@
|
||||
"previousWithShortcut": "前のレシピ(←)",
|
||||
"nextWithShortcut": "次のレシピ(→)"
|
||||
},
|
||||
"modal": {
|
||||
"metadata": {
|
||||
"id": "ID"
|
||||
},
|
||||
"actions": {
|
||||
"openFileLocation": "ファイルの場所を開く",
|
||||
"copyId": "レシピIDをコピー"
|
||||
},
|
||||
"openFileLocation": {
|
||||
"success": "ファイルの場所を正常に開きました",
|
||||
"failed": "ファイルの場所を開くのに失敗しました",
|
||||
"copied": "パスをクリップボードにコピーしました: {{path}}",
|
||||
"clipboardFallback": "パス: {{path}}"
|
||||
}
|
||||
},
|
||||
"workflow": {
|
||||
"sendWorkflow": "ワークフローをComfyUIへ送信",
|
||||
"sent": "ワークフローをComfyUIへ送信しました",
|
||||
"sendFailed": "ワークフローをComfyUIへ送信できませんでした",
|
||||
"noWorkflow": "このレシピに埋め込まれたワークフローが見つかりません"
|
||||
},
|
||||
"status": {
|
||||
"ready": "使用可能",
|
||||
"missingCount": "{count} 件不足",
|
||||
"deletedCount": "{count} 件削除済み",
|
||||
"downloadMissing": "不足している {count} 件のLoRAをダウンロード",
|
||||
"downloadMissingTooltip": "クリックして不足しているLoRAをダウンロード"
|
||||
},
|
||||
"loraStatus": {
|
||||
"none": "このレシピにはLoRAがありません",
|
||||
"allAvailable": "すべてのLoRAが利用可能 - 使用可能",
|
||||
"missing": "{total} 件中 {missing} 件のLoRAが不足",
|
||||
"missingAndUnavailable": "{total} 件中 {missing} 件のLoRAが不足、{unavailable} 件は利用不可(ソースから削除済みかハッシュを解決できません)",
|
||||
"partial": "{total} 件中 {unavailable} 件のLoRAが利用不可(ソースから削除済みかハッシュを解決できません)- レシピ使用時はスキップされます",
|
||||
"noneUsable": "使用可能なLoRAがありません - {total} 件中 {unavailable} 件がソースから削除済みかハッシュを解決できません"
|
||||
},
|
||||
"resources": {
|
||||
"inLibrary": "ライブラリ内",
|
||||
"notInLibrary": "ライブラリ外",
|
||||
"deleted": "削除済み",
|
||||
"hashInvalid": "解決不能なハッシュ",
|
||||
"inLibraryTooltip": "このモデルはローカルライブラリに存在します",
|
||||
"notInLibraryTooltip": "このモデルはライブラリにありません",
|
||||
"deletedTooltip": "この LoRA は配信元から削除されたため、ダウンロードできません",
|
||||
"hashInvalidTooltip": "このLoRAハッシュはCivitAIで解決できません - モデルが更新された可能性があります",
|
||||
"noLorasAssociated": "このレシピに関連付けられた LoRA はありません",
|
||||
"noLorasWhyToggle": "LoRA がない理由",
|
||||
"noLorasImportMethod": "インポート方法",
|
||||
"noLorasInferredNote": "考えられる理由(推定)— このレシピはインポート診断が記録される前にインポートされました。",
|
||||
"noLorasChannels": {
|
||||
"batch_import_url": "一括インポート(画像 URL)",
|
||||
"batch_import_local": "一括インポート(ローカルファイル)",
|
||||
"url": "画像 URL からのインポート",
|
||||
"local": "ローカルファイルのインポート",
|
||||
"upload": "画像のアップロード",
|
||||
"widget": "ワークフローから保存",
|
||||
"reimport_url": "再インポート(画像 URL)",
|
||||
"reimport_local": "再インポート(ローカルファイル)"
|
||||
},
|
||||
"noLorasReasons": {
|
||||
"no_loras_used": "生成メタデータは完全で、LoRA への参照は含まれていません。",
|
||||
"api_meta_no_lora_resources": "ソース API がこの画像の LoRA リソースデータを返しませんでした。CivitAI ページに表示される LoRA は、公開 API では公開されない内部データに由来する場合があります。",
|
||||
"api_meta_missing": "ソース API がこの画像の生成メタデータを返しませんでした。",
|
||||
"no_embedded_metadata": "画像に埋め込まれた生成メタデータがないため、LoRA 情報を復元できませんでした。",
|
||||
"workflow_metadata_limited": "画像に埋め込まれたメタデータは ComfyUI ワークフローです。ワークフローからの LoRA 情報の抽出には限界があります。",
|
||||
"video_no_metadata": "動画ファイルには埋め込み生成メタデータがありません。",
|
||||
"metadata_unsupported": "画像に解析できない形式のメタデータが含まれています。",
|
||||
"unknown": "保存されたレシピデータから理由を特定できませんでした。"
|
||||
},
|
||||
"noLorasDetails": {
|
||||
"apiMetaFields": "API メタデータフィールド",
|
||||
"modelVersionIds": "報告されたモデルバージョン ID 数",
|
||||
"embeddedMetadata": "埋め込みメタデータ",
|
||||
"present": "あり",
|
||||
"absent": "なし"
|
||||
},
|
||||
"download": "ダウンロード",
|
||||
"downloadLoraTooltip": "この LoRA をダウンロード",
|
||||
"preparingDownload": "ダウンロードを準備中...",
|
||||
"reconnect": "再接続",
|
||||
"reconnectTooltip": "ローカルの LoRA と再接続",
|
||||
"reconnectInstructions": "再接続する LoRA の構文または名前を入力してください:",
|
||||
"reconnectExample": "例:<lora:name:1> または名前のみ",
|
||||
"reconnectPlaceholder": "LoRA 名または構文を入力",
|
||||
"reconnectSuggestionsLoading": "ローカルライブラリを検索中...",
|
||||
"reconnectSuggestionsEmpty": "ローカルライブラリに一致するLoRAがありません",
|
||||
"reconnectMatchSameHash": "同じハッシュ",
|
||||
"reconnectMatchSameVersion": "同じモデルバージョン",
|
||||
"reconnectMatchSimilarFilename": "類似のファイル名",
|
||||
"reconnectMatchSimilarName": "類似の名前",
|
||||
"undoReconnect": "元に戻す",
|
||||
"undoReconnectTooltip": "このエントリーを再接続前の関連付けに戻します",
|
||||
"undoReconnectTooltipNamed": "{name} に戻す(再接続前の関連付け)",
|
||||
"viewOnCivitai": "CivitAI で表示",
|
||||
"openLoraDetails": "LoRA ライブラリで {name} を表示",
|
||||
"openCheckpointDetails": "モデルライブラリで {name} を表示",
|
||||
"checkpointDeletedTooltip": "この Checkpoint はソースから削除されたため、ダウンロードできません - ローカルモデルで再接続してください",
|
||||
"checkpointHashInvalidTooltip": "この Checkpoint のハッシュは CivitAI で解決できません - モデルが更新された可能性があります",
|
||||
"reconnectCheckpoint": "再接続",
|
||||
"reconnectCheckpointTooltip": "ローカルの Checkpoint と再接続",
|
||||
"checkpointReconnectInstructions": "再接続する Checkpoint の名前を入力してください:",
|
||||
"checkpointReconnectPlaceholder": "Checkpoint 名を入力",
|
||||
"checkpointReconnectSuggestionsEmpty": "ローカルライブラリに一致するCheckpointがありません"
|
||||
},
|
||||
"controls": {
|
||||
"import": {
|
||||
"action": "インポート",
|
||||
@@ -881,7 +1013,7 @@
|
||||
"dropZoneHint": "画像をここにドラッグ&ドロップ、クリップボードから貼り付け、またはクリックして参照",
|
||||
"orDivider": "または画像をドラッグ&ドロップ / 貼り付け",
|
||||
"imageUrlOrPath": "画像URLまたはファイルパス:",
|
||||
"urlPlaceholder": "https://civitai.com/images/... または C:/path/to/image.png",
|
||||
"urlPlaceholder": "https://civitai.com/images/... または https://civitai.red/images/... または C:/path/to/image.png",
|
||||
"fetchImage": "画像を取得",
|
||||
"recipeName": "レシピ名",
|
||||
"recipeNamePlaceholder": "レシピ名を入力",
|
||||
@@ -910,7 +1042,7 @@
|
||||
"downloadingLoras": "LoRAをダウンロード中...",
|
||||
"savingRecipe": "レシピを保存中...",
|
||||
"startingDownload": "LoRA {current}/{total} のダウンロードを開始",
|
||||
"deletedFromCivitai": "Civitaiから削除済み",
|
||||
"deletedFromCivitai": "CivitAIから削除済み",
|
||||
"inLibrary": "ライブラリ内",
|
||||
"notInLibrary": "ライブラリ外",
|
||||
"earlyAccessRequired": "このLoRAはダウンロードにアーリーアクセス料金が必要です。",
|
||||
@@ -1012,63 +1144,63 @@
|
||||
}
|
||||
},
|
||||
"batchImport": {
|
||||
"title": "Batch Import Recipes",
|
||||
"action": "Batch Import",
|
||||
"urlList": "URL List",
|
||||
"directory": "Directory",
|
||||
"urlDescription": "Enter image URLs or local file paths (one per line). Each will be imported as a recipe.",
|
||||
"directoryDescription": "Enter a directory path to import all images from that folder.",
|
||||
"urlsLabel": "Image URLs or Local Paths",
|
||||
"title": "レシピを一括インポート",
|
||||
"action": "一括インポート",
|
||||
"urlList": "URLリスト",
|
||||
"directory": "フォルダ",
|
||||
"urlDescription": "画像URLまたはローカルファイルパスを入力してください(1行に1つ)。それぞれがレシピとしてインポートされます。",
|
||||
"directoryDescription": "フォルダパスを入力すると、そのフォルダ内のすべての画像がインポートされます。",
|
||||
"urlsLabel": "画像URLまたはローカルパス",
|
||||
"urlsPlaceholder": "https://civitai.com/images/...\nhttps://civitai.com/images/...\nC:/path/to/image.png\n...",
|
||||
"urlsHint": "Enter one URL or path per line",
|
||||
"directoryPath": "Directory Path",
|
||||
"urlsHint": "1行に1つのURLまたはパスを入力",
|
||||
"directoryPath": "フォルダパス",
|
||||
"directoryPlaceholder": "/path/to/images/folder",
|
||||
"browse": "Browse",
|
||||
"recursive": "Include subdirectories",
|
||||
"tagsOptional": "Tags (optional, applied to all recipes)",
|
||||
"tagsPlaceholder": "Enter tags separated by commas",
|
||||
"tagsHint": "Tags will be added to all imported recipes",
|
||||
"skipNoMetadata": "Skip images without metadata",
|
||||
"skipNoMetadataHelp": "Images without LoRA metadata will be skipped automatically.",
|
||||
"start": "Start Import",
|
||||
"startImport": "Start Import",
|
||||
"importing": "Importing...",
|
||||
"rateLimitedSlowdown": "[TODO: Translate] Rate limited — slowing down...",
|
||||
"rateLimitedHint": "[TODO: Translate] Some items were skipped due to metadata provider rate limits. Re-run the import later to retry them.",
|
||||
"progress": "Progress",
|
||||
"total": "Total",
|
||||
"success": "Success",
|
||||
"failed": "Failed",
|
||||
"skipped": "Skipped",
|
||||
"current": "Current",
|
||||
"currentItem": "Current",
|
||||
"preparing": "Preparing...",
|
||||
"cancel": "Cancel",
|
||||
"cancelImport": "Cancel",
|
||||
"cancelled": "Import cancelled",
|
||||
"completed": "Import completed",
|
||||
"completedWithErrors": "Completed with errors",
|
||||
"completedSuccess": "Successfully imported {count} recipe(s)",
|
||||
"successCount": "Successful",
|
||||
"failedCount": "Failed",
|
||||
"skippedCount": "Skipped",
|
||||
"totalProcessed": "Total processed",
|
||||
"viewDetails": "View Details",
|
||||
"newImport": "New Import",
|
||||
"manualPathEntry": "Please enter the directory path manually. File browser is not available in this browser.",
|
||||
"batchImportDirectorySelected": "Directory selected: {path}",
|
||||
"batchImportManualEntryRequired": "File browser not available. Please enter the directory path manually.",
|
||||
"backToParent": "Back to parent directory",
|
||||
"folders": "Folders",
|
||||
"folderCount": "{count} folders",
|
||||
"imageFiles": "Image Files",
|
||||
"images": "images",
|
||||
"imageCount": "{count} images",
|
||||
"selectFolder": "Select This Folder",
|
||||
"browse": "参照",
|
||||
"recursive": "サブフォルダを含める",
|
||||
"tagsOptional": "タグ(任意、すべてのレシピに適用)",
|
||||
"tagsPlaceholder": "タグをカンマ区切りで入力",
|
||||
"tagsHint": "タグはインポートされたすべてのレシピに追加されます",
|
||||
"skipNoMetadata": "メタデータのない画像をスキップ",
|
||||
"skipNoMetadataHelp": "LoRAメタデータのない画像は自動的にスキップされます。",
|
||||
"start": "インポートを開始",
|
||||
"startImport": "インポートを開始",
|
||||
"importing": "インポート中...",
|
||||
"rateLimitedSlowdown": "レート制限中 — 速度を落としています...",
|
||||
"rateLimitedHint": "メタデータプロバイダーのレート制限により一部の項目がスキップされました。後でもう一度インポートを実行して再試行してください。",
|
||||
"progress": "進捗",
|
||||
"total": "合計",
|
||||
"success": "成功",
|
||||
"failed": "失敗",
|
||||
"skipped": "スキップ",
|
||||
"current": "現在",
|
||||
"currentItem": "現在",
|
||||
"preparing": "準備中...",
|
||||
"cancel": "キャンセル",
|
||||
"cancelImport": "キャンセル",
|
||||
"cancelled": "インポートがキャンセルされました",
|
||||
"completed": "インポートが完了しました",
|
||||
"completedWithErrors": "エラーありで完了",
|
||||
"completedSuccess": "{count} 件のレシピを正常にインポートしました",
|
||||
"successCount": "成功",
|
||||
"failedCount": "失敗",
|
||||
"skippedCount": "スキップ",
|
||||
"totalProcessed": "処理済みの合計",
|
||||
"viewDetails": "詳細を見る",
|
||||
"newImport": "新しいインポート",
|
||||
"manualPathEntry": "フォルダパスを手動で入力してください。このブラウザではファイルブラウザは利用できません。",
|
||||
"batchImportDirectorySelected": "選択されたフォルダ: {path}",
|
||||
"batchImportManualEntryRequired": "ファイルブラウザが利用できません。フォルダパスを手動で入力してください。",
|
||||
"backToParent": "親フォルダに戻る",
|
||||
"folders": "フォルダ",
|
||||
"folderCount": "{count} 個のフォルダ",
|
||||
"imageFiles": "画像ファイル",
|
||||
"images": "画像",
|
||||
"imageCount": "{count} 枚の画像",
|
||||
"selectFolder": "このフォルダを選択",
|
||||
"errors": {
|
||||
"enterUrls": "Please enter at least one URL or path",
|
||||
"enterDirectory": "Please enter a directory path",
|
||||
"startFailed": "Failed to start import: {message}"
|
||||
"enterUrls": "URLまたはパスを少なくとも1つ入力してください",
|
||||
"enterDirectory": "フォルダパスを入力してください",
|
||||
"startFailed": "インポートを開始できませんでした: {message}"
|
||||
}
|
||||
}
|
||||
},
|
||||
@@ -1238,7 +1370,7 @@
|
||||
"download": {
|
||||
"title": "URLからモデルをダウンロード",
|
||||
"titleWithType": "URLから{type}をダウンロード",
|
||||
"civitaiUrl": "Civitai URL:",
|
||||
"civitaiUrl": "CivitAI URL:",
|
||||
"placeholder": "https://civitai.com/models/...",
|
||||
"urlHint": "1行に1つのCivitAI、CivArchive、またはHugging Face URLを入力してください。複数のURLを一括ダウンロードできます。",
|
||||
"selectHfFiles": "このリポジトリからダウンロードするファイルを選択してください:",
|
||||
@@ -1273,7 +1405,7 @@
|
||||
"inLibrary": "ライブラリ内"
|
||||
},
|
||||
"errors": {
|
||||
"invalidUrl": "無効なCivitai URL形式",
|
||||
"invalidUrl": "無効なCivitAI URL形式",
|
||||
"noVersions": "このモデルの利用可能なバージョンがありません",
|
||||
"mixedSources": "同じバッチ内でCivitAIとHugging FaceのURLを混在させることはできません。",
|
||||
"noModelFiles": "このリポジトリにモデルファイルが見つかりませんでした。"
|
||||
@@ -1352,9 +1484,9 @@
|
||||
"action": "すべて削除"
|
||||
},
|
||||
"checkUpdates": {
|
||||
"title": "すべての{type}の更新を確認しますか?",
|
||||
"message": "ライブラリ内のすべての{type}で更新を確認します。コレクションが大きい場合は時間がかかることがあります。",
|
||||
"tip": "少しずつ確認したい場合はバルクモードに切り替え、必要なモデルを選んで「選択項目の更新を確認」を使ってください。",
|
||||
"title": "すべての{typePlural}の更新を確認しますか?",
|
||||
"message": "ライブラリ内のすべての{typePlural}で更新を確認します。コレクションが大きい場合は時間がかかることがあります。",
|
||||
"tip": "少しずつ確認したい場合は一括モードに切り替え、必要なモデルを選んで「選択項目の更新を確認」を使ってください。",
|
||||
"action": "すべて確認"
|
||||
},
|
||||
"bulkAddTags": {
|
||||
@@ -1387,7 +1519,7 @@
|
||||
"title": "ローカル例画像",
|
||||
"message": "このモデルのローカル例画像が見つかりませんでした。表示オプション:",
|
||||
"downloadOption": {
|
||||
"title": "Civitaiからダウンロード",
|
||||
"title": "CivitAIからダウンロード",
|
||||
"description": "リモート例画像をローカルに保存して、オフライン使用と高速読み込みを可能にします"
|
||||
},
|
||||
"importOption": {
|
||||
@@ -1414,7 +1546,7 @@
|
||||
"confirmAction": "保存&リンク"
|
||||
},
|
||||
"relinkCivitai": {
|
||||
"title": "Civitaiに再リンク",
|
||||
"title": "CivitAIに再リンク",
|
||||
"warning": "警告:",
|
||||
"warningText": "これは破壊的な操作になる可能性があります。再リンクは以下を行います:",
|
||||
"warningList": {
|
||||
@@ -1423,15 +1555,15 @@
|
||||
"unintendedConsequences": "その他の意図しない結果を引き起こす可能性"
|
||||
},
|
||||
"proceedText": "これが本当に必要な場合のみ続行してください。",
|
||||
"urlLabel": "CivitaiモデルURL:",
|
||||
"urlPlaceholder": "https://civitai.com/models/12345/model-name?modelVersionId=67890",
|
||||
"urlLabel": "CivitAIモデルURL:",
|
||||
"urlPlaceholder": "https://civitai.com/models/12345/model-name?modelVersionId=67890 または https://civitai.red/models/12345/model-name?modelVersionId=67890",
|
||||
"helpText": {
|
||||
"title": "CivitaiまたはCivitArchiveのモデルURLを貼り付けてください。対応形式:",
|
||||
"title": "CivitAIまたはCivitArchiveのモデルURLを貼り付けてください。対応形式:",
|
||||
"format1": "https://civitai.com/models/12345",
|
||||
"format2": "https://civitai.com/models/12345?modelVersionId=67890",
|
||||
"format3": "https://civitai.com/models/12345/model-name?modelVersionId=67890",
|
||||
"note": "注:modelVersionIdが提供されていない場合、最新バージョンが使用されます。",
|
||||
"format4": "https://civarchive.com/models/12345 (CivitArchive)"
|
||||
"format4": "https://civarchive.com/models/12345 (CivArchive)"
|
||||
},
|
||||
"confirmAction": "再リンクを確認"
|
||||
},
|
||||
@@ -1441,8 +1573,8 @@
|
||||
"editFileName": "ファイル名を編集",
|
||||
"editBaseModel": "ベースモデルを編集",
|
||||
"editVersionName": "バージョン名を編集",
|
||||
"viewOnCivitai": "Civitaiで表示",
|
||||
"viewOnCivitaiText": "Civitaiで表示",
|
||||
"viewOnCivitai": "CivitAIで表示",
|
||||
"viewOnCivitaiText": "CivitAIで表示",
|
||||
"viewOnHuggingFace": "Hugging Face で見る",
|
||||
"viewOnHuggingFaceText": "Hugging Face で見る",
|
||||
"viewCreatorProfile": "作成者プロフィールを表示",
|
||||
@@ -1474,7 +1606,7 @@
|
||||
"notesHint": "Enterで保存、Shift+Enterで改行",
|
||||
"addNotesPlaceholder": "メモをここに追加...",
|
||||
"aboutThisVersion": "このバージョンについて",
|
||||
"baseModelSearchPlaceholder": "ベースモデルを検索…",
|
||||
"baseModelSearchPlaceholder": "ベースモデルを検索...",
|
||||
"baseModelSuggested": "おすすめ",
|
||||
"baseModelNoMatch": "該当するベースモデルがありません"
|
||||
},
|
||||
@@ -1494,7 +1626,11 @@
|
||||
"clipSkip": "Clip Skip",
|
||||
"valuePlaceholder": "値",
|
||||
"add": "追加",
|
||||
"invalidRange": "無効な範囲形式です。x.x-y.y を使用してください"
|
||||
"invalidRange": "無効な範囲形式です。x.x-y.y を使用してください",
|
||||
"invalidValue": "有効な数値を入力してください",
|
||||
"saveFailed": "プリセットパラメータの保存に失敗しました",
|
||||
"added": "プリセットパラメータを追加しました",
|
||||
"updated": "プリセットパラメータを更新しました"
|
||||
},
|
||||
"triggerWords": {
|
||||
"label": "トリガーワード",
|
||||
@@ -1505,7 +1641,7 @@
|
||||
"addPlaceholder": "入力して追加するか、下の提案をクリック",
|
||||
"editWord": "トリガーワードを編集",
|
||||
"editPlaceholder": "トリガーワードを編集",
|
||||
"copyWord": "トリガーワードをコピー",
|
||||
"copyOrEditWord": "クリックでコピー、ダブルクリックで編集",
|
||||
"deleteWord": "トリガーワードを削除",
|
||||
"suggestions": {
|
||||
"noSuggestions": "提案はありません",
|
||||
@@ -1543,10 +1679,10 @@
|
||||
"noNext": "次のモデルがありません"
|
||||
},
|
||||
"license": {
|
||||
"noImageSell": "No selling generated content",
|
||||
"noRentCivit": "No Civitai generation",
|
||||
"noRent": "No generation services",
|
||||
"noSell": "No selling models",
|
||||
"noImageSell": "生成画像の販売禁止",
|
||||
"noRentCivit": "CivitAIでの生成不可",
|
||||
"noRent": "生成サービス不可",
|
||||
"noSell": "モデルの販売禁止",
|
||||
"creditRequired": "作成者のクレジットが必要",
|
||||
"noDerivatives": "共有マージ不可",
|
||||
"noReLicense": "同じ権限が必要",
|
||||
@@ -1565,8 +1701,8 @@
|
||||
"showCount": "例を表示({count})",
|
||||
"hideExamples": "例を非表示",
|
||||
"addExamples": "例を追加",
|
||||
"previousExample": "前の例",
|
||||
"nextExample": "次の例",
|
||||
"previousExample": "前の例([)",
|
||||
"nextExample": "次の例(])",
|
||||
"noExamples": "利用可能な例画像がありません",
|
||||
"addMoreExamples": "さらに例を追加",
|
||||
"dragDrop": "画像または動画をここにドラッグ&ドロップ",
|
||||
@@ -1609,33 +1745,33 @@
|
||||
"newer": "新しいバージョン",
|
||||
"newerTooltip": "このバージョンはローカルの最新バージョンより新しいです",
|
||||
"earlyAccess": "早期アクセス",
|
||||
"earlyAccessTooltip": "このバージョンは現在 Civitai の早期アクセスが必要です",
|
||||
"earlyAccessTooltip": "このバージョンは現在 CivitAI の早期アクセスが必要です",
|
||||
"paid": "有料",
|
||||
"paidTooltip": "このバージョンのダウンロードには支払いが必要です",
|
||||
"ignored": "無視中",
|
||||
"ignoredTooltip": "このバージョンの更新通知は無効です",
|
||||
"onSiteOnly": "サイト内のみ",
|
||||
"onSiteOnlyTooltip": "このバージョンはCivitaiサイト内でのみ利用可能で、ダウンロードはできません"
|
||||
"onSiteOnlyTooltip": "このバージョンはCivitAIサイト内でのみ利用可能で、ダウンロードはできません"
|
||||
},
|
||||
"actions": {
|
||||
"download": "ダウンロード",
|
||||
"downloadTooltip": "このバージョンをダウンロード",
|
||||
"downloadChooseFilesTooltip": "ダウンロードするファイルを選択",
|
||||
"downloadEarlyAccessTooltip": "Civitai からこの早期アクセス版をダウンロード",
|
||||
"downloadPaidTooltip": "Civitai からこの有料バージョンをダウンロード",
|
||||
"downloadNotAllowedTooltip": "このバージョンはCivitaiサイト内でのみ利用可能で、ダウンロードはできません",
|
||||
"downloadEarlyAccessTooltip": "CivitAI からこの早期アクセス版をダウンロード",
|
||||
"downloadPaidTooltip": "CivitAI からこの有料バージョンをダウンロード",
|
||||
"downloadNotAllowedTooltip": "このバージョンはCivitAIサイト内でのみ利用可能で、ダウンロードはできません",
|
||||
"delete": "削除",
|
||||
"deleteTooltip": "このローカルバージョンを削除",
|
||||
"ignore": "無視",
|
||||
"unignore": "無視を解除",
|
||||
"ignoreTooltip": "このバージョンの更新通知を無視",
|
||||
"unignoreTooltip": "このバージョンの更新通知を再開",
|
||||
"viewVersionOnCivitai": "Civitai でバージョンを表示",
|
||||
"viewVersionOnCivitai": "CivitAI でバージョンを表示",
|
||||
"earlyAccessTooltip": "早期アクセス購入が必要",
|
||||
"resumeModelUpdates": "このモデルの更新を再開",
|
||||
"ignoreModelUpdates": "このモデルの更新を無視",
|
||||
"viewLocalVersions": "ローカルの全バージョンを表示",
|
||||
"viewLocalTooltip": "近日対応予定"
|
||||
"viewLocalTooltip": "このモデルのすべてのローカルバージョンをメインページで表示"
|
||||
},
|
||||
"filters": {
|
||||
"label": "ベースフィルター",
|
||||
@@ -1651,7 +1787,7 @@
|
||||
},
|
||||
"empty": "このモデルにはまだバージョン履歴がありません。",
|
||||
"error": "バージョンの読み込みに失敗しました。",
|
||||
"missingModelId": "このモデルにはCivitaiのモデルIDがありません。",
|
||||
"missingModelId": "このモデルにはCivitAIのモデルIDがありません。",
|
||||
"hfGroupInfo": "これは HuggingFace モデルグループです。ライブラリを開いてグリッドですべてのバージョンを表示してください。",
|
||||
"confirm": {
|
||||
"delete": "このバージョンをライブラリから削除しますか?"
|
||||
@@ -1718,14 +1854,14 @@
|
||||
},
|
||||
"checkpoints": {
|
||||
"title": "Checkpoint Managerを初期化中",
|
||||
"message": "checkpointキャッシュをスキャンして構築中。数分かかる場合があります..."
|
||||
"message": "Checkpointキャッシュをスキャンして構築中。数分かかる場合があります..."
|
||||
},
|
||||
"embeddings": {
|
||||
"title": "Embedding Managerを初期化中",
|
||||
"message": "embeddingキャッシュをスキャンして構築中。数分かかる場合があります..."
|
||||
},
|
||||
"recipes": {
|
||||
"title": "Recipe Managerを初期化中",
|
||||
"title": "レシピマネージャーを初期化中",
|
||||
"message": "レシピを読み込んで処理中。数分かかる場合があります..."
|
||||
},
|
||||
"statistics": {
|
||||
@@ -1735,14 +1871,14 @@
|
||||
"tips": {
|
||||
"title": "ヒント&コツ",
|
||||
"civitai": {
|
||||
"title": "Civitai統合",
|
||||
"description": "Civitaiアカウントを接続:プロフィールアバター → 設定 → APIキー → APIキーを追加し、LoRA Manager設定に貼り付けてください。",
|
||||
"alt": "Civitai API設定"
|
||||
"title": "CivitAI統合",
|
||||
"description": "CivitAIアカウントを接続:プロフィールアバター → 設定 → APIキー → APIキーを追加し、LoRA Manager設定に貼り付けてください。",
|
||||
"alt": "CivitAI API設定"
|
||||
},
|
||||
"download": {
|
||||
"title": "簡単ダウンロード",
|
||||
"description": "Civitai URLを使用して新しいモデルを素早くダウンロードしてインストールできます。",
|
||||
"alt": "Civitaiダウンロード"
|
||||
"description": "CivitAI URLを使用して新しいモデルを素早くダウンロードしてインストールできます。",
|
||||
"alt": "CivitAIダウンロード"
|
||||
},
|
||||
"recipes": {
|
||||
"title": "レシピを保存",
|
||||
@@ -1830,10 +1966,52 @@
|
||||
"tabs": {
|
||||
"gettingStarted": "はじめに",
|
||||
"updateVlogs": "更新Vlog",
|
||||
"documentation": "ドキュメント"
|
||||
"documentation": "ドキュメント",
|
||||
"shortcuts": "ショートカット"
|
||||
},
|
||||
"gettingStarted": {
|
||||
"title": "LoRA Managerを始める"
|
||||
"title": "LoRA Managerを始める",
|
||||
"replayTutorial": "チュートリアルをもう一度再生"
|
||||
},
|
||||
"shortcuts": {
|
||||
"title": "キーボード & マウスのショートカット",
|
||||
"groups": {
|
||||
"general": "一般",
|
||||
"actions": "操作",
|
||||
"selection": "選択 & 一括モード",
|
||||
"navigation": "ナビゲーション",
|
||||
"modelModal": "モデル / レシピモーダル",
|
||||
"mediaViewer": "メディアビューア / ショーケース"
|
||||
},
|
||||
"keys": {
|
||||
"click": "クリック",
|
||||
"drag": "ドラッグ",
|
||||
"rightClick": "右クリック",
|
||||
"letter": "文字キー",
|
||||
"swipe": "スワイプ"
|
||||
},
|
||||
"entries": {
|
||||
"focusSearch": "検索にフォーカス",
|
||||
"closeModal": "モーダル / パネルを閉じる",
|
||||
"openShortcuts": "このショートカットパネルを開く",
|
||||
"refresh": "モデルリストを更新",
|
||||
"fetchMetadata": "CivitAIからメタデータを取得(モデルページのみ)",
|
||||
"downloadModel": "モデルをダウンロード(モデルページのみ)",
|
||||
"toggleBulkMode": "一括モードを切り替え",
|
||||
"selectAll": "表示中のモデルをすべて選択",
|
||||
"rangeSelect": "範囲選択",
|
||||
"marqueeSelect": "カードを矩形選択(グリッドの空白部分で)",
|
||||
"exitBulkMode": "一括モードを終了",
|
||||
"bulkActions": "選択したカード上:一括操作メニュー",
|
||||
"globalActions": "ページの空白部分:グローバル操作メニュー(更新の確認、除外モデルの管理)",
|
||||
"scrollPages": "ページをスクロール",
|
||||
"jumpAlphabet": "アルファベットバーへジャンプ",
|
||||
"prevNext": "前 / 次のモデル",
|
||||
"deleteEntry": "削除",
|
||||
"cycleMedia": "メディアを切り替え(ショーケースギャラリーでは [ / ])",
|
||||
"swipeTouch": "タッチデバイスでメディアを切り替え",
|
||||
"closeViewer": "ビューアを閉じる"
|
||||
}
|
||||
},
|
||||
"updateVlogs": {
|
||||
"title": "最新の更新",
|
||||
@@ -1850,7 +2028,8 @@
|
||||
"settings": "設定&構成",
|
||||
"extensions": "拡張機能",
|
||||
"newBadge": "新着"
|
||||
}
|
||||
},
|
||||
"newContentBadge": "新着"
|
||||
},
|
||||
"update": {
|
||||
"title": "更新確認",
|
||||
@@ -1926,7 +2105,7 @@
|
||||
"submitGithubIssue": "GitHub Issueを提出",
|
||||
"joinDiscord": "Discordに参加",
|
||||
"youtubeChannel": "YouTubeチャンネル",
|
||||
"civitaiProfile": "Civitaiプロフィール",
|
||||
"civitaiProfile": "CivitAIプロフィール",
|
||||
"supportKofi": "Ko-fiでサポート",
|
||||
"supportPatreon": "Patreonでサポート"
|
||||
},
|
||||
@@ -2009,14 +2188,27 @@
|
||||
"preparingForDownloadFailed": "ダウンロード用LoRAの準備中にエラーが発生しました",
|
||||
"enterLoraName": "LoRA名または構文を入力してください",
|
||||
"reconnectedSuccessfully": "LoRAが正常に再接続されました",
|
||||
"reconnectBaseModelMismatch": "再接続しましたが、ベースモデルが異なります(レシピ:{recipe}、LoRA:{lora})— アーキテクチャ互換です",
|
||||
"reconnectFailed": "LoRA再接続エラー:{message}",
|
||||
"loraRestored": "LoRAが以前の関連付けに復元されました",
|
||||
"loraRestoreFailed": "LoRA復元エラー:{message}",
|
||||
"noPromptToSend": "送信するプロンプトがありません",
|
||||
"cannotSend": "レシピを送信できません:レシピIDがありません",
|
||||
"sendFailed": "レシピのワークフローへの送信に失敗しました",
|
||||
"sendError": "レシピのワークフロー送信エラー",
|
||||
"missingCheckpointPath": "チェックポイントのパスがありません",
|
||||
"missingCheckpointInfo": "チェックポイント情報が不足しています",
|
||||
"downloadCheckpointFailed": "チェックポイントのダウンロードに失敗しました: {message}",
|
||||
"missingCheckpointPath": "Checkpointのパスがありません",
|
||||
"missingCheckpointInfo": "Checkpoint情報が不足しています",
|
||||
"downloadCheckpointFailed": "Checkpointのダウンロードに失敗しました: {message}",
|
||||
"enterCheckpointName": "Checkpoint 名を入力してください",
|
||||
"checkpointReconnectedSuccessfully": "Checkpointが正常に再接続されました",
|
||||
"reconnectCheckpointBaseModelMismatch": "再接続しましたが、ベースモデルが異なります(レシピ:{recipe}、Checkpoint:{checkpoint})— アーキテクチャ互換です",
|
||||
"checkpointReconnectFailed": "Checkpoint再接続エラー:{message}",
|
||||
"checkpointRestored": "Checkpoint が以前の関連付けに復元されました",
|
||||
"checkpointRestoreFailed": "Checkpoint復元エラー:{message}",
|
||||
"checkpointDownloadUnavailable": "CivitAI の識別子がないため、この Checkpoint をダウンロードできません - ローカルの Checkpoint と再接続してみてください",
|
||||
"missingLoraDownloadInfo": "この LoRA のダウンロード情報がありません",
|
||||
"hashNotFoundOnCivitai": "このLoRAハッシュはCivitAIで解決できません - モデルが更新されたか、ハッシュが無効な可能性があります",
|
||||
"downloadLoraFailed": "LoRA のダウンロードに失敗しました: {message}",
|
||||
"cannotDelete": "レシピを削除できません:レシピIDがありません",
|
||||
"deleteConfirmationError": "削除確認の表示中にエラーが発生しました",
|
||||
"deletedSuccessfully": "レシピが正常に削除されました",
|
||||
@@ -2031,18 +2223,18 @@
|
||||
"processingError": "処理エラー:{message}",
|
||||
"folderBrowserError": "フォルダブラウザの読み込みエラー:{message}",
|
||||
"recipeSaveFailed": "レシピの保存に失敗しました:{error}",
|
||||
"recipeSaved": "Recipe saved successfully",
|
||||
"recipeSaved": "レシピを保存しました",
|
||||
"importFailed": "インポートに失敗しました:{message}",
|
||||
"folderTreeFailed": "フォルダツリーの読み込みに失敗しました",
|
||||
"folderTreeError": "フォルダツリー読み込みエラー",
|
||||
"batchImportFailed": "Failed to start batch import: {message}",
|
||||
"batchImportCancelling": "Cancelling batch import...",
|
||||
"batchImportCancelFailed": "Failed to cancel batch import: {message}",
|
||||
"batchImportNoUrls": "Please enter at least one URL or file path",
|
||||
"batchImportNoDirectory": "Please enter a directory path",
|
||||
"batchImportRateLimited": "[TODO: Translate] Metadata provider rate limit reached — requests are being slowed and some items may be skipped. You can re-run the import later.",
|
||||
"batchImportBrowseFailed": "Failed to browse directory: {message}",
|
||||
"batchImportDirectorySelected": "Directory selected: {path}",
|
||||
"batchImportFailed": "一括インポートを開始できませんでした: {message}",
|
||||
"batchImportCancelling": "一括インポートをキャンセルしています...",
|
||||
"batchImportCancelFailed": "一括インポートをキャンセルできませんでした: {message}",
|
||||
"batchImportNoUrls": "URLまたはファイルパスを少なくとも1つ入力してください",
|
||||
"batchImportNoDirectory": "フォルダパスを入力してください",
|
||||
"batchImportRateLimited": "メタデータプロバイダーのレート制限に達しました — リクエストが遅延され、一部の項目がスキップされる場合があります。後でインポートを再実行できます。",
|
||||
"batchImportBrowseFailed": "フォルダを参照できませんでした: {message}",
|
||||
"batchImportDirectorySelected": "選択されたフォルダ: {path}",
|
||||
"noRecipesSelected": "レシピが選択されていません",
|
||||
"repairBulkComplete": "修復完了:{repaired} 件修復、{skipped} 件スキップ(合計 {total} 件)",
|
||||
"repairBulkSkipped": "選択した {total} 件のレシピは修復不要です",
|
||||
@@ -2098,8 +2290,8 @@
|
||||
"bulkUpdatesChecking": "選択された{type}の更新を確認しています...",
|
||||
"bulkUpdatesSuccess": "{count} 件の選択された{type}に利用可能な更新があります",
|
||||
"bulkUpdatesNone": "選択された{type}には更新が見つかりませんでした",
|
||||
"bulkUpdatesMissing": "選択された{type}はCivitaiの更新にリンクされていません",
|
||||
"bulkUpdatesPartialMissing": "Civitaiリンクがない{missing} 件の{type}をスキップしました",
|
||||
"bulkUpdatesMissing": "選択された{type}はCivitAIの更新にリンクされていません",
|
||||
"bulkUpdatesPartialMissing": "CivitAIリンクがない{missing} 件の{type}をスキップしました",
|
||||
"bulkUpdatesFailed": "選択された{type}の更新確認に失敗しました: {message}",
|
||||
"invalidCharactersRemoved": "ファイル名から無効な文字が削除されました",
|
||||
"filenameCannotBeEmpty": "ファイル名を空にすることはできません",
|
||||
@@ -2125,10 +2317,10 @@
|
||||
},
|
||||
"settings": {
|
||||
"loraRootsFailed": "LoRAルートの読み込みに失敗しました:{message}",
|
||||
"checkpointRootsFailed": "checkpointルートの読み込みに失敗しました:{message}",
|
||||
"checkpointRootsFailed": "Checkpointルートの読み込みに失敗しました:{message}",
|
||||
"unetRootsFailed": "Diffusion Modelルートの読み込みに失敗しました:{message}",
|
||||
"embeddingRootsFailed": "embeddingルートの読み込みに失敗しました:{message}",
|
||||
"mappingsUpdated": "ベースモデルパスマッピングが更新されました({count} マッピング{plural})",
|
||||
"mappingsUpdated": "ベースモデルパスマッピングが更新されました({count} マッピング)",
|
||||
"mappingsCleared": "ベースモデルパスマッピングがクリアされました",
|
||||
"mappingSaveFailed": "ベースモデルマッピングの保存に失敗しました:{message}",
|
||||
"downloadTemplatesUpdated": "ダウンロードパステンプレートが更新されました",
|
||||
@@ -2139,8 +2331,8 @@
|
||||
"compactModeToggled": "コンパクトモード {state}",
|
||||
"settingSaveFailed": "設定の保存に失敗しました:{message}",
|
||||
"displayDensitySet": "表示密度が {density} に設定されました",
|
||||
"libraryLoadFailed": "Failed to load libraries: {message}",
|
||||
"libraryActivateFailed": "Failed to activate library: {message}",
|
||||
"libraryLoadFailed": "ライブラリを読み込めませんでした: {message}",
|
||||
"libraryActivateFailed": "ライブラリをアクティブ化できませんでした: {message}",
|
||||
"languageChangeFailed": "言語の変更に失敗しました:{message}",
|
||||
"cacheCleared": "キャッシュファイルが正常にクリアされました。次回のアクションでキャッシュが再構築されます。",
|
||||
"cacheClearFailed": "キャッシュのクリアに失敗しました:{error}",
|
||||
@@ -2225,7 +2417,7 @@
|
||||
"contextMenu": {
|
||||
"contentRatingSet": "コンテンツレーティングが {level} に設定されました",
|
||||
"contentRatingFailed": "コンテンツレーティングの設定に失敗しました:{message}",
|
||||
"relinkSuccess": "モデルがCivitaiに正常に再リンクされました",
|
||||
"relinkSuccess": "モデルがCivitAIに正常に再リンクされました",
|
||||
"relinkFailed": "エラー:{message}",
|
||||
"linkHfSuccess": "モデルを HuggingFace にリンクしました",
|
||||
"linkHfFailed": "エラー:{message}",
|
||||
@@ -2289,7 +2481,7 @@
|
||||
"bulkMoveSuccess": "{successCount} {type}が正常に移動されました",
|
||||
"exampleImagesDownloadSuccess": "例画像が正常にダウンロードされました!",
|
||||
"exampleImagesDownloadFailed": "例画像のダウンロードに失敗しました:{message}",
|
||||
"moveFailed": "Failed to move item: {message}",
|
||||
"moveFailed": "アイテムを移動できませんでした: {message}",
|
||||
"copiedToClipboard": "クリップボードにコピーしました",
|
||||
"downloadStarted": "ダウンロードを開始しました"
|
||||
},
|
||||
@@ -2319,7 +2511,7 @@
|
||||
},
|
||||
"issues": {
|
||||
"civitai_api_key": {
|
||||
"title": "Civitai API キー"
|
||||
"title": "CivitAI API キー"
|
||||
},
|
||||
"cache_health": {
|
||||
"title": "モデルキャッシュの健全性"
|
||||
@@ -2372,10 +2564,10 @@
|
||||
"seconds": "秒"
|
||||
},
|
||||
"communitySupport": {
|
||||
"title": "Keep LoRA Manager Thriving with Your Support ❤️",
|
||||
"content": "LoRA Manager is a passion project maintained full-time by a solo developer. Your support on Ko-fi helps cover development costs, keeps new updates coming, and unlocks a license key for the LM Civitai Extension as a thank-you gift. Every contribution truly makes a difference.",
|
||||
"supportCta": "Support on Ko-fi",
|
||||
"learnMore": "LM Civitai Extension Tutorial"
|
||||
"title": "あなたのサポートで LoRA Manager は成長し続けます ❤️",
|
||||
"content": "LoRA Managerは一人の開発者がフルタイムで維持している情熱的なプロジェクトです。Ko-fiでのご支援は開発費用のカバーや新機能のリリースに役立ち、お礼としてLM CivitAI拡張機能のライセンスキーもご提供します。すべてのご寄付が大きな違いを生みます。",
|
||||
"supportCta": "Ko-fiでサポート",
|
||||
"learnMore": "LM CivitAI拡張機能チュートリアル"
|
||||
},
|
||||
"cacheHealth": {
|
||||
"corrupted": {
|
||||
|
||||
+357
-165
@@ -50,6 +50,27 @@
|
||||
"mb": "MB",
|
||||
"gb": "GB",
|
||||
"tb": "TB"
|
||||
},
|
||||
"scanProgress": {
|
||||
"refreshing": "{type} 새로고침 중...",
|
||||
"fullRebuilding": "{type} 전체 재구성 중...",
|
||||
"actionRefresh": "새로고침",
|
||||
"actionFullRebuild": "전체 재구성",
|
||||
"actionRefreshLower": "새로고침",
|
||||
"actionRebuildLower": "재구성",
|
||||
"stages": {
|
||||
"scan_folders": "폴더 스캔 중...",
|
||||
"count_models": "파일 {total}개 발견",
|
||||
"process_models": "모델 처리 중",
|
||||
"reconcile_scan": "변경 사항 확인 중...",
|
||||
"process_new": "새 모델 처리 중",
|
||||
"finalizing": "마무리 중..."
|
||||
},
|
||||
"eta": {
|
||||
"lessThanMinute": "남은 시간 1분 미만",
|
||||
"minutes": "약 {minutes}분 남음",
|
||||
"hours": "약 {hours}시간 {minutes}분 남음"
|
||||
}
|
||||
}
|
||||
},
|
||||
"onboarding": {
|
||||
@@ -67,15 +88,15 @@
|
||||
"steps": {
|
||||
"fetch": {
|
||||
"title": "모델 메타데이터 가져오기",
|
||||
"content": "<strong>가져오기</strong> 버튼을 클릭하여 Civitai에서 모델 메타데이터와 미리보기 이미지를 다운로드하세요."
|
||||
"content": "<strong>가져오기</strong> 버튼을 클릭하여 CivitAI에서 모델 메타데이터와 미리보기 이미지를 다운로드하세요."
|
||||
},
|
||||
"download": {
|
||||
"title": "새 모델 다운로드",
|
||||
"content": "<strong>다운로드</strong> 버튼을 사용하여 Civitai URL에서 모델을 직접 다운로드하세요."
|
||||
"content": "<strong>다운로드</strong> 버튼을 사용하여 CivitAI URL에서 모델을 직접 다운로드하세요."
|
||||
},
|
||||
"bulk": {
|
||||
"title": "일괄 작업",
|
||||
"content": "이 버튼을 클릭하거나 <span class=\"onboarding-shortcut\">B</span> 키를 눌러 일괄 모드로 진입하세요. 여러 모델을 선택하여 일괄 작업을 수행할 수 있습니다. <span class=\"onboarding-shortcut\">Ctrl+A</span>로 모든 표시된 모델을 선택하세요."
|
||||
"content": "이 버튼을 클릭하거나 <span class=\"onboarding-shortcut\">B</span> 키를 눌러 일괄 모드로 진입하여 여러 모델을 선택하고 일괄 작업을 수행하세요.<br>• <span class=\"onboarding-shortcut\">Ctrl/Cmd+A</span>로 모든 표시된 모델을 선택하고, <span class=\"onboarding-shortcut\">Shift+Click</span>으로 범위를 선택할 수 있습니다.<br>• <span class=\"onboarding-shortcut\">Esc</span> 키를 누르거나 빈 영역을 클릭하면 일괄 모드가 종료됩니다."
|
||||
},
|
||||
"searchOptions": {
|
||||
"title": "검색 옵션",
|
||||
@@ -95,7 +116,19 @@
|
||||
},
|
||||
"contextMenu": {
|
||||
"title": "컨텍스트 메뉴",
|
||||
"content": "<strong>오른쪽 클릭</strong>으로 모델 카드의 추가 작업 메뉴를 사용할 수 있습니다."
|
||||
"content": "모델 카드를 <strong>오른쪽 클릭</strong>하면 이동, 삭제, 메타데이터 편집 같은 카드 작업이 담긴 컨텍스트 메뉴를 사용할 수 있습니다."
|
||||
},
|
||||
"marqueeSelect": {
|
||||
"title": "드래그로 선택",
|
||||
"content": "그리드의 빈 영역에서 <strong>마우스 왼쪽 버튼</strong>을 누른 채 드래그하여 여러 카드를 한 번에 선택하는 선택 영역을 그리세요."
|
||||
},
|
||||
"dragToSidebar": {
|
||||
"title": "드래그로 정리",
|
||||
"content": "모델 카드를 사이드바의 폴더로 드래그하면 파일이 해당 폴더로 이동합니다. 일괄 모드에서 선택한 여러 카드에도 적용됩니다."
|
||||
},
|
||||
"contextMenus": {
|
||||
"title": "더 많은 컨텍스트 메뉴",
|
||||
"content": "일괄 모드에서는 <strong>선택한 카드를 오른쪽 클릭</strong>하여 일괄 작업을 사용할 수 있습니다. 페이지의 <strong>빈 영역을 오른쪽 클릭</strong>하면 업데이트 확인이나 제외된 모델 관리 같은 전역 작업을 사용할 수 있습니다."
|
||||
}
|
||||
}
|
||||
},
|
||||
@@ -103,8 +136,8 @@
|
||||
"actions": {
|
||||
"addToFavorites": "즐겨찾기에 추가",
|
||||
"removeFromFavorites": "즐겨찾기에서 제거",
|
||||
"viewOnCivitai": "Civitai에서 보기",
|
||||
"notAvailableFromCivitai": "Civitai에서 사용할 수 없음",
|
||||
"viewOnCivitai": "CivitAI에서 보기",
|
||||
"notAvailableFromCivitai": "CivitAI에서 사용할 수 없음",
|
||||
"viewOnHuggingFace": "Hugging Face에서 보기",
|
||||
"sendToWorkflow": "ComfyUI로 전송 (클릭: 추가, Shift+클릭: 교체)",
|
||||
"copyLoRASyntax": "LoRA 문법 복사",
|
||||
@@ -131,13 +164,13 @@
|
||||
"updateFailed": "즐겨찾기 상태 업데이트 실패"
|
||||
},
|
||||
"sendToWorkflow": {
|
||||
"checkpointNotImplemented": "Checkpoint을 워크플로로 전송 - 구현 예정 기능",
|
||||
"checkpointNotImplemented": "Checkpoint를 워크플로로 전송 - 구현 예정 기능",
|
||||
"missingPath": "이 카드의 모델 경로를 확인할 수 없습니다"
|
||||
},
|
||||
"exampleImages": {
|
||||
"checkError": "예시 이미지 확인 중 오류",
|
||||
"missingHash": "모델 해시 정보가 없습니다.",
|
||||
"noRemoteImagesAvailable": "Civitai에서 이 모델의 원격 예시 이미지를 사용할 수 없습니다"
|
||||
"noRemoteImagesAvailable": "CivitAI에서 이 모델의 원격 예시 이미지를 사용할 수 없습니다"
|
||||
},
|
||||
"badges": {
|
||||
"update": "업데이트",
|
||||
@@ -173,11 +206,11 @@
|
||||
"error": "예시 이미지 폴더 정리에 실패했습니다: {message}"
|
||||
},
|
||||
"fetchMissingLicenses": {
|
||||
"label": "Refresh license metadata",
|
||||
"loading": "Refreshing license metadata for {typePlural}...",
|
||||
"success": "Updated license metadata for {count} {typePlural}",
|
||||
"none": "All {typePlural} already have license metadata",
|
||||
"error": "Failed to refresh license metadata for {typePlural}: {message}"
|
||||
"label": "라이선스 메타데이터 새로고침",
|
||||
"loading": "{typePlural}의 라이선스 메타데이터를 새로고침하는 중...",
|
||||
"success": "{count}개의 {typePlural} 라이선스 메타데이터를 업데이트했습니다",
|
||||
"none": "모든 {typePlural}에 이미 라이선스 메타데이터가 있습니다",
|
||||
"error": "{typePlural}의 라이선스 메타데이터를 새로고침하지 못했습니다: {message}"
|
||||
},
|
||||
"repairRecipes": {
|
||||
"label": "레시피 데이터 복구",
|
||||
@@ -259,7 +292,7 @@
|
||||
"clearAll": "모든 필터 지우기",
|
||||
"any": "아무",
|
||||
"all": "모두",
|
||||
"tagLogicAny": "모든 태그 일치 (OR)",
|
||||
"tagLogicAny": "어느 하나의 태그와 일치 (OR)",
|
||||
"tagLogicAll": "모든 태그 일치 (AND)",
|
||||
"loraAvailability": "LoRA 가용성",
|
||||
"availabilityReady": "바로 사용 가능",
|
||||
@@ -290,15 +323,15 @@
|
||||
}
|
||||
},
|
||||
"settings": {
|
||||
"civitaiApiKey": "Civitai API 키",
|
||||
"civitaiApiKeyPlaceholder": "Civitai API 키를 입력하세요",
|
||||
"civitaiApiKeyHelp": "Civitai에서 모델을 다운로드할 때 인증에 사용됩니다",
|
||||
"civitaiApiKey": "CivitAI API 키",
|
||||
"civitaiApiKeyPlaceholder": "CivitAI API 키를 입력하세요",
|
||||
"civitaiApiKeyHelp": "CivitAI에서 모델을 다운로드할 때 인증에 사용됩니다",
|
||||
"civitaiApiKeyConfigured": "설정됨",
|
||||
"civitaiApiKeyNotConfigured": "설정되지 않음",
|
||||
"civitaiApiKeySet": "설정",
|
||||
"civitaiHost": {
|
||||
"label": "Civitai 호스트",
|
||||
"help": "\"View on Civitai\" 링크를 사용할 때 어떤 Civitai 사이트를 열지 선택합니다.",
|
||||
"label": "CivitAI 호스트",
|
||||
"help": "\"View on CivitAI\" 링크를 사용할 때 어떤 CivitAI 사이트를 열지 선택합니다.",
|
||||
"options": {
|
||||
"com": "civitai.com(SFW 전용)",
|
||||
"red": "civitai.red(무제한)"
|
||||
@@ -319,8 +352,8 @@
|
||||
},
|
||||
"aria2HelpLink": "aria2 다운로드 백엔드 설정 방법 알아보기",
|
||||
"civitaiHostBanner": {
|
||||
"title": "Civitai 호스트 기본 설정 사용 가능",
|
||||
"content": "이제 Civitai는 SFW 콘텐츠에 civitai.com을, 무제한 콘텐츠에 civitai.red를 사용합니다. 설정에서 기본으로 열 사이트를 변경할 수 있습니다.",
|
||||
"title": "CivitAI 호스트 기본 설정 사용 가능",
|
||||
"content": "이제 CivitAI는 SFW 콘텐츠에 civitai.com을, 무제한 콘텐츠에 civitai.red를 사용합니다. 설정에서 기본으로 열 사이트를 변경할 수 있습니다.",
|
||||
"openSettings": "설정 열기"
|
||||
},
|
||||
"openSettingsFileLocation": {
|
||||
@@ -427,10 +460,10 @@
|
||||
"noneAvailable": "아직 스냅샷이 없습니다"
|
||||
},
|
||||
"downloadSkipBaseModels": {
|
||||
"label": "기본 모델 다운로드 건너뛰기",
|
||||
"help": "모든 다운로드 흐름에 적용됩니다. 여기서는 지원되는 기본 모델만 선택할 수 있습니다.",
|
||||
"searchPlaceholder": "기본 모델 필터링...",
|
||||
"empty": "현재 검색과 일치하는 기본 모델이 없습니다.",
|
||||
"label": "베이스 모델 다운로드 건너뛰기",
|
||||
"help": "활성화하면 선택한 베이스 모델을 사용하는 버전은 건너뜁니다.",
|
||||
"searchPlaceholder": "베이스 모델 필터링...",
|
||||
"empty": "현재 검색과 일치하는 베이스 모델이 없습니다.",
|
||||
"summary": {
|
||||
"none": "선택 없음",
|
||||
"count": "{count}개 선택됨"
|
||||
@@ -441,7 +474,7 @@
|
||||
"clear": "지우기"
|
||||
},
|
||||
"validation": {
|
||||
"saveFailed": "제외된 기본 모델을 저장할 수 없습니다: {message}"
|
||||
"saveFailed": "제외된 베이스 모델을 저장할 수 없습니다: {message}"
|
||||
}
|
||||
},
|
||||
"skipPreviouslyDownloadedModelVersions": {
|
||||
@@ -450,7 +483,7 @@
|
||||
},
|
||||
"layoutSettings": {
|
||||
"groupByModel": "모델별 그룹화",
|
||||
"groupByModelHelp": "활성화하면 각 Civitai 모델의 최신 버전만 단일 카드로 표시되며, 이전 버전은 숨겨집니다.",
|
||||
"groupByModelHelp": "활성화하면 각 CivitAI 모델의 최신 버전만 단일 카드로 표시되며, 이전 버전은 숨겨집니다.",
|
||||
"displayDensity": "표시 밀도",
|
||||
"displayDensityOptions": {
|
||||
"default": "기본",
|
||||
@@ -517,7 +550,7 @@
|
||||
"extraFolderPaths": {
|
||||
"title": "추가 폴다 경로",
|
||||
"description": "LoRA Manager 전용 추가 모델 루트 경로입니다. ComfyUI의 표준 폴더 외부 위치에서 모델을 로드하여 대규모 라이브러리로 인한 성능 저하를 방지합니다.",
|
||||
"restartRequired": "Requires restart to take effect",
|
||||
"restartRequired": "변경 사항을 적용하려면 재시작이 필요합니다",
|
||||
"modelTypes": {
|
||||
"lora": "LoRA 경로",
|
||||
"checkpoint": "Checkpoint 경로",
|
||||
@@ -540,8 +573,8 @@
|
||||
"helpLinkLabel": "우선순위 태그 도움말 열기",
|
||||
"modelTypes": {
|
||||
"lora": "LoRA",
|
||||
"checkpoint": "체크포인트",
|
||||
"embedding": "임베딩"
|
||||
"checkpoint": "Checkpoint",
|
||||
"embedding": "Embedding"
|
||||
},
|
||||
"saveSuccess": "우선순위 태그가 업데이트되었습니다.",
|
||||
"saveError": "우선순위 태그를 업데이트하지 못했습니다.",
|
||||
@@ -555,7 +588,7 @@
|
||||
},
|
||||
"downloadPathTemplates": {
|
||||
"title": "다운로드 경로 템플릿",
|
||||
"help": "Civitai에서 다운로드할 때 다양한 모델 유형의 폴더 구조를 구성합니다.",
|
||||
"help": "CivitAI에서 다운로드할 때 다양한 모델 유형의 폴더 구조를 구성합니다.",
|
||||
"availablePlaceholders": "사용 가능한 플레이스홀더:",
|
||||
"templateOptions": {
|
||||
"flatStructure": "플랫 구조",
|
||||
@@ -592,7 +625,7 @@
|
||||
"exampleImages": {
|
||||
"downloadLocation": "다운로드 위치",
|
||||
"downloadLocationPlaceholder": "예시 이미지 폴더 경로를 입력하세요",
|
||||
"downloadLocationHelp": "Civitai의 예시 이미지가 저장될 폴더 경로를 입력하세요",
|
||||
"downloadLocationHelp": "CivitAI의 예시 이미지가 저장될 폴더 경로를 입력하세요",
|
||||
"autoDownload": "예시 이미지 자동 다운로드",
|
||||
"autoDownloadHelp": "예시 이미지가 없는 모델의 예시 이미지를 자동으로 다운로드합니다 (다운로드 위치 설정 필요)",
|
||||
"openMode": "예시 이미지 열기 동작",
|
||||
@@ -625,7 +658,7 @@
|
||||
},
|
||||
"hideEarlyAccessUpdates": {
|
||||
"label": "얼리 액세스 업데이트 숨기기",
|
||||
"help": "얼리 액세스 업데이트만"
|
||||
"help": "활성화하면 얼리 액세스 업데이트만 있는 모델에는 '업데이트 가능' 배지가 표시되지 않습니다."
|
||||
},
|
||||
"hidePaidUpdates": {
|
||||
"label": "유료 업데이트 숨기기",
|
||||
@@ -647,7 +680,7 @@
|
||||
},
|
||||
"metadataArchive": {
|
||||
"enableArchiveDb": "메타데이터 아카이브 데이터베이스 활성화",
|
||||
"enableArchiveDbHelp": "Civitai에서 삭제된 모델의 메타데이터에 접근하기 위해 로컬 데이터베이스를 사용합니다.",
|
||||
"enableArchiveDbHelp": "CivitAI에서 삭제된 모델의 메타데이터에 접근하기 위해 로컬 데이터베이스를 사용합니다.",
|
||||
"status": "상태",
|
||||
"statusAvailable": "사용 가능",
|
||||
"statusUnavailable": "사용 불가",
|
||||
@@ -708,7 +741,7 @@
|
||||
"custom": "사용자 정의 (OpenAI 호환)"
|
||||
},
|
||||
"apiBase": "API 기본 URL",
|
||||
"apiBaseHelp": "LLM API의 기본 URL입니다 (예: https://api.openai.com/v1). 비워두면 제공자 기본값이 사용됩니다.",
|
||||
"apiBaseHelp": "LLM API의 기본 URL입니다. 프리셋을 선택하거나 사용자 정의 URL을 입력하세요. 드롭다운에 지원되는 모든 제공자의 프리셋이 표시됩니다.",
|
||||
"apiBasePlaceholder": "https://api.openai.com/v1",
|
||||
"apiKey": "API 키",
|
||||
"apiKeyHelp": "LLM 제공자의 API 키입니다. 로컬에 저장되며 선택한 LLM 제공자 외의 서버로 전송되지 않습니다.",
|
||||
@@ -750,7 +783,7 @@
|
||||
"fullTooltip": "메타데이터 파일에서 모든 모델 정보를 다시 불러옵니다. 라이브러리가 오래되어 보이거나 수동 수정 후에 사용하세요."
|
||||
},
|
||||
"fetch": {
|
||||
"title": "Civitai에서 메타데이터 가져오기",
|
||||
"title": "CivitAI에서 메타데이터 가져오기",
|
||||
"action": "가져오기"
|
||||
},
|
||||
"download": {
|
||||
@@ -805,9 +838,9 @@
|
||||
"clear": "선택 지우기",
|
||||
"skipMetadataRefreshCount": "건너뛰기({count}개 모델)",
|
||||
"resumeMetadataRefreshCount": "재개({count}개 모델)",
|
||||
"sendToWorkflow": "워크플로우로 보내기",
|
||||
"sendToWorkflow": "워크플로로 보내기",
|
||||
"sections": {
|
||||
"workflow": "워크플로우",
|
||||
"workflow": "워크플로",
|
||||
"metadata": "메타데이터",
|
||||
"attributes": "속성",
|
||||
"organize": "정리",
|
||||
@@ -825,10 +858,10 @@
|
||||
"enrichHfAgent": "HF AI로 메타데이터 보강"
|
||||
},
|
||||
"contextMenu": {
|
||||
"refreshMetadata": "Civitai 데이터 새로고침",
|
||||
"refreshMetadata": "CivitAI 데이터 새로고침",
|
||||
"checkUpdates": "업데이트 확인",
|
||||
"linkModel": "모델 연결",
|
||||
"linkCivitai": "Civitai에 연결",
|
||||
"linkCivitai": "CivitAI에 연결",
|
||||
"linkHuggingFace": "HuggingFace에 연결",
|
||||
"copySyntax": "LoRA 문법 복사",
|
||||
"copyFilename": "모델 파일명 복사",
|
||||
@@ -860,6 +893,7 @@
|
||||
"actions": {
|
||||
"sendCheckpoint": "ComfyUI로 보내기",
|
||||
"sendRecipe": "ComfyUI로 보내기",
|
||||
"copyRecipeSyntax": "레시피 문법 복사",
|
||||
"deleteRecipeWithShortcut": "레시피 삭제(Del)"
|
||||
},
|
||||
"navigation": {
|
||||
@@ -867,12 +901,110 @@
|
||||
"previousWithShortcut": "이전 레시피(←)",
|
||||
"nextWithShortcut": "다음 레시피(→)"
|
||||
},
|
||||
"modal": {
|
||||
"metadata": {
|
||||
"id": "ID"
|
||||
},
|
||||
"actions": {
|
||||
"openFileLocation": "파일 위치 열기",
|
||||
"copyId": "레시피 ID 복사"
|
||||
},
|
||||
"openFileLocation": {
|
||||
"success": "파일 위치가 성공적으로 열렸습니다",
|
||||
"failed": "파일 위치 열기에 실패했습니다",
|
||||
"copied": "경로가 클립보드에 복사되었습니다: {{path}}",
|
||||
"clipboardFallback": "경로: {{path}}"
|
||||
}
|
||||
},
|
||||
"workflow": {
|
||||
"sendWorkflow": "워크플로를 ComfyUI로 보내기",
|
||||
"sent": "워크플로를 ComfyUI로 보냈습니다",
|
||||
"sendFailed": "워크플로를 ComfyUI로 보내지 못했습니다",
|
||||
"noWorkflow": "이 레시피에서 임베드된 워크플로를 찾을 수 없습니다"
|
||||
},
|
||||
"status": {
|
||||
"ready": "바로 사용 가능",
|
||||
"missingCount": "{count}개 누락",
|
||||
"deletedCount": "{count}개 삭제됨",
|
||||
"downloadMissing": "누락된 LoRA {count}개 다운로드",
|
||||
"downloadMissingTooltip": "클릭하여 누락된 LoRA 다운로드"
|
||||
},
|
||||
"loraStatus": {
|
||||
"none": "이 레시피에는 LoRA가 없습니다",
|
||||
"allAvailable": "모든 LoRA 사용 가능 - 바로 사용 가능",
|
||||
"missing": "총 {total}개 중 {missing}개 LoRA 누락",
|
||||
"missingAndUnavailable": "총 {total}개 중 {missing}개 LoRA 누락, {unavailable}개 사용 불가(소스에서 삭제되었거나 해시를 확인할 수 없음)",
|
||||
"partial": "총 {total}개 중 {unavailable}개 LoRA 사용 불가(소스에서 삭제되었거나 해시를 확인할 수 없음) - 레시피 사용 시 건너뜁니다",
|
||||
"noneUsable": "사용 가능한 LoRA가 없습니다 - 총 {total}개 중 {unavailable}개가 소스에서 삭제되었거나 해시를 확인할 수 없습니다"
|
||||
},
|
||||
"resources": {
|
||||
"inLibrary": "라이브러리에 있음",
|
||||
"notInLibrary": "라이브러리에 없음",
|
||||
"deleted": "삭제됨",
|
||||
"hashInvalid": "해석할 수 없는 해시",
|
||||
"inLibraryTooltip": "이 모델은 로컬 라이브러리에 있습니다",
|
||||
"notInLibraryTooltip": "이 모델은 라이브러리에 없습니다",
|
||||
"deletedTooltip": "이 LoRA는 소스에서 삭제되어 더 이상 다운로드할 수 없습니다",
|
||||
"hashInvalidTooltip": "이 LoRA 해시는 CivitAI에서 해석할 수 없습니다 - 모델이 업데이트되었을 수 있습니다",
|
||||
"noLorasAssociated": "이 레시피에 연결된 LoRA가 없습니다",
|
||||
"noLorasWhyToggle": "LoRA가 없는 이유",
|
||||
"noLorasImportMethod": "가져오기 방법",
|
||||
"noLorasInferredNote": "가능한 이유(추정) — 이 레시피는 가져오기 진단이 기록되기 전에 가져온 것입니다.",
|
||||
"noLorasChannels": {
|
||||
"batch_import_url": "일괄 가져오기(이미지 URL)",
|
||||
"batch_import_local": "일괄 가져오기(로컬 파일)",
|
||||
"url": "이미지 URL 가져오기",
|
||||
"local": "로컬 파일 가져오기",
|
||||
"upload": "이미지 업로드",
|
||||
"widget": "워크플로에서 저장",
|
||||
"reimport_url": "다시 가져오기(이미지 URL)",
|
||||
"reimport_local": "다시 가져오기(로컬 파일)"
|
||||
},
|
||||
"noLorasReasons": {
|
||||
"no_loras_used": "생성 메타데이터가 완전하며 LoRA를 참조하지 않습니다.",
|
||||
"api_meta_no_lora_resources": "소스 API가 이 이미지에 대한 LoRA 리소스 데이터를 반환하지 않았습니다. CivitAI 페이지에 표시되는 LoRA는 공개 API가 노출하지 않는 내부 데이터에서 비롯될 수 있습니다.",
|
||||
"api_meta_missing": "소스 API가 이 이미지에 대한 생성 메타데이터를 반환하지 않았습니다.",
|
||||
"no_embedded_metadata": "이미지에 내장된 생성 메타데이터가 없어 LoRA 정보를 복구할 수 없습니다.",
|
||||
"workflow_metadata_limited": "이미지에 내장된 메타데이터는 ComfyUI 워크플로입니다. 워크플로에서 LoRA 정보를 추출하는 것은 제한적입니다.",
|
||||
"video_no_metadata": "동영상 파일에는 내장 생성 메타데이터가 없습니다.",
|
||||
"metadata_unsupported": "이미지에 파싱할 수 없는 형식의 메타데이터가 포함되어 있습니다.",
|
||||
"unknown": "저장된 레시피 데이터에서 이유를 확인할 수 없습니다."
|
||||
},
|
||||
"noLorasDetails": {
|
||||
"apiMetaFields": "API 메타데이터 필드",
|
||||
"modelVersionIds": "보고된 모델 버전 ID 수",
|
||||
"embeddedMetadata": "내장 메타데이터",
|
||||
"present": "있음",
|
||||
"absent": "없음"
|
||||
},
|
||||
"download": "다운로드",
|
||||
"downloadLoraTooltip": "이 LoRA 다운로드",
|
||||
"preparingDownload": "다운로드 준비 중...",
|
||||
"reconnect": "다시 연결",
|
||||
"reconnectTooltip": "로컬 LoRA와 다시 연결",
|
||||
"reconnectInstructions": "다시 연결할 LoRA 구문 또는 이름을 입력하세요:",
|
||||
"reconnectExample": "예:<lora:name:1> 또는 이름만 입력",
|
||||
"reconnectPlaceholder": "LoRA 이름 또는 구문 입력",
|
||||
"reconnectSuggestionsLoading": "로컬 라이브러리 검색 중...",
|
||||
"reconnectSuggestionsEmpty": "로컬 라이브러리에 일치하는 LoRA가 없습니다",
|
||||
"reconnectMatchSameHash": "동일한 해시",
|
||||
"reconnectMatchSameVersion": "동일한 모델 버전",
|
||||
"reconnectMatchSimilarFilename": "유사한 파일 이름",
|
||||
"reconnectMatchSimilarName": "유사한 이름",
|
||||
"undoReconnect": "실행 취소",
|
||||
"undoReconnectTooltip": "이 항목을 다시 연결 전의 연결 상태로 복원",
|
||||
"undoReconnectTooltipNamed": "이전 연결 상태로 복원: {name}",
|
||||
"viewOnCivitai": "CivitAI에서 보기",
|
||||
"openLoraDetails": "LoRA 라이브러리에서 {name} 보기",
|
||||
"openCheckpointDetails": "모델 라이브러리에서 {name} 보기",
|
||||
"checkpointDeletedTooltip": "이 Checkpoint는 소스에서 삭제되어 더 이상 다운로드할 수 없습니다 - 로컬 모델로 다시 연결하세요",
|
||||
"checkpointHashInvalidTooltip": "이 Checkpoint의 해시를 CivitAI에서 확인할 수 없습니다 - 모델이 업데이트되었을 수 있습니다",
|
||||
"reconnectCheckpoint": "다시 연결",
|
||||
"reconnectCheckpointTooltip": "로컬 Checkpoint와 다시 연결",
|
||||
"checkpointReconnectInstructions": "다시 연결할 Checkpoint 이름을 입력하세요:",
|
||||
"checkpointReconnectPlaceholder": "Checkpoint 이름 입력",
|
||||
"checkpointReconnectSuggestionsEmpty": "로컬 라이브러리에 일치하는 Checkpoint가 없습니다"
|
||||
},
|
||||
"controls": {
|
||||
"import": {
|
||||
"action": "가져오기",
|
||||
@@ -881,7 +1013,7 @@
|
||||
"dropZoneHint": "이미지를 여기에 끌어다 놓거나, 클립보드에서 붙여넣거나, 클릭하여 찾아보세요",
|
||||
"orDivider": "또는 이미지를 끌어다 놓기 / 붙여넣기",
|
||||
"imageUrlOrPath": "이미지 URL 또는 파일 경로:",
|
||||
"urlPlaceholder": "https://civitai.com/images/... 또는 C:/path/to/image.png",
|
||||
"urlPlaceholder": "https://civitai.com/images/... 또는 https://civitai.red/images/... 또는 C:/path/to/image.png",
|
||||
"fetchImage": "이미지 가져오기",
|
||||
"recipeName": "레시피 이름",
|
||||
"recipeNamePlaceholder": "레시피 이름을 입력하세요",
|
||||
@@ -910,7 +1042,7 @@
|
||||
"downloadingLoras": "LoRA 다운로드 중...",
|
||||
"savingRecipe": "레시피 저장 중...",
|
||||
"startingDownload": "LoRA {current}/{total} 다운로드 시작",
|
||||
"deletedFromCivitai": "Civitai에서 삭제됨",
|
||||
"deletedFromCivitai": "CivitAI에서 삭제됨",
|
||||
"inLibrary": "라이브러리에 있음",
|
||||
"notInLibrary": "라이브러리에 없음",
|
||||
"earlyAccessRequired": "이 LoRA는 얼리 액세스 결제가 필요합니다.",
|
||||
@@ -1012,63 +1144,63 @@
|
||||
}
|
||||
},
|
||||
"batchImport": {
|
||||
"title": "Batch Import Recipes",
|
||||
"action": "Batch Import",
|
||||
"urlList": "URL List",
|
||||
"directory": "Directory",
|
||||
"urlDescription": "Enter image URLs or local file paths (one per line). Each will be imported as a recipe.",
|
||||
"directoryDescription": "Enter a directory path to import all images from that folder.",
|
||||
"urlsLabel": "Image URLs or Local Paths",
|
||||
"title": "레시피 일괄 가져오기",
|
||||
"action": "일괄 가져오기",
|
||||
"urlList": "URL 목록",
|
||||
"directory": "폴더",
|
||||
"urlDescription": "이미지 URL 또는 로컬 파일 경로를 입력하세요 (줄당 하나). 각 항목은 레시피로 가져옵니다.",
|
||||
"directoryDescription": "폴더 경로를 입력하면 해당 폴더의 모든 이미지를 가져옵니다.",
|
||||
"urlsLabel": "이미지 URL 또는 로컬 경로",
|
||||
"urlsPlaceholder": "https://civitai.com/images/...\nhttps://civitai.com/images/...\nC:/path/to/image.png\n...",
|
||||
"urlsHint": "Enter one URL or path per line",
|
||||
"directoryPath": "Directory Path",
|
||||
"urlsHint": "줄당 URL 또는 경로 하나를 입력하세요",
|
||||
"directoryPath": "폴더 경로",
|
||||
"directoryPlaceholder": "/path/to/images/folder",
|
||||
"browse": "Browse",
|
||||
"recursive": "Include subdirectories",
|
||||
"tagsOptional": "Tags (optional, applied to all recipes)",
|
||||
"tagsPlaceholder": "Enter tags separated by commas",
|
||||
"tagsHint": "Tags will be added to all imported recipes",
|
||||
"skipNoMetadata": "Skip images without metadata",
|
||||
"skipNoMetadataHelp": "Images without LoRA metadata will be skipped automatically.",
|
||||
"start": "Start Import",
|
||||
"startImport": "Start Import",
|
||||
"importing": "Importing...",
|
||||
"rateLimitedSlowdown": "[TODO: Translate] Rate limited — slowing down...",
|
||||
"rateLimitedHint": "[TODO: Translate] Some items were skipped due to metadata provider rate limits. Re-run the import later to retry them.",
|
||||
"progress": "Progress",
|
||||
"total": "Total",
|
||||
"success": "Success",
|
||||
"failed": "Failed",
|
||||
"skipped": "Skipped",
|
||||
"current": "Current",
|
||||
"currentItem": "Current",
|
||||
"preparing": "Preparing...",
|
||||
"cancel": "Cancel",
|
||||
"cancelImport": "Cancel",
|
||||
"cancelled": "Import cancelled",
|
||||
"completed": "Import completed",
|
||||
"completedWithErrors": "Completed with errors",
|
||||
"completedSuccess": "Successfully imported {count} recipe(s)",
|
||||
"successCount": "Successful",
|
||||
"failedCount": "Failed",
|
||||
"skippedCount": "Skipped",
|
||||
"totalProcessed": "Total processed",
|
||||
"viewDetails": "View Details",
|
||||
"newImport": "New Import",
|
||||
"manualPathEntry": "Please enter the directory path manually. File browser is not available in this browser.",
|
||||
"batchImportDirectorySelected": "Directory selected: {path}",
|
||||
"batchImportManualEntryRequired": "File browser not available. Please enter the directory path manually.",
|
||||
"backToParent": "Back to parent directory",
|
||||
"folders": "Folders",
|
||||
"folderCount": "{count} folders",
|
||||
"imageFiles": "Image Files",
|
||||
"images": "images",
|
||||
"imageCount": "{count} images",
|
||||
"selectFolder": "Select This Folder",
|
||||
"browse": "찾아보기",
|
||||
"recursive": "하위 폴더 포함",
|
||||
"tagsOptional": "태그 (선택 사항, 모든 레시피에 적용)",
|
||||
"tagsPlaceholder": "쉼표로 구분된 태그 입력",
|
||||
"tagsHint": "태그가 가져온 모든 레시피에 추가됩니다",
|
||||
"skipNoMetadata": "메타데이터 없는 이미지 건너뛰기",
|
||||
"skipNoMetadataHelp": "LoRA 메타데이터가 없는 이미지는 자동으로 건너뜁니다.",
|
||||
"start": "가져오기 시작",
|
||||
"startImport": "가져오기 시작",
|
||||
"importing": "가져오는 중...",
|
||||
"rateLimitedSlowdown": "속도 제한 — 느려지고 있습니다...",
|
||||
"rateLimitedHint": "메타데이터 제공자의 속도 제한으로 일부 항목이 건너뛰어졌습니다. 나중에 가져오기를 다시 실행하여 재시도하세요.",
|
||||
"progress": "진행률",
|
||||
"total": "전체",
|
||||
"success": "성공",
|
||||
"failed": "실패",
|
||||
"skipped": "건너뜀",
|
||||
"current": "현재",
|
||||
"currentItem": "현재",
|
||||
"preparing": "준비 중...",
|
||||
"cancel": "취소",
|
||||
"cancelImport": "취소",
|
||||
"cancelled": "가져오기가 취소되었습니다",
|
||||
"completed": "가져오기가 완료되었습니다",
|
||||
"completedWithErrors": "오류와 함께 완료됨",
|
||||
"completedSuccess": "{count}개의 레시피를 성공적으로 가져왔습니다",
|
||||
"successCount": "성공",
|
||||
"failedCount": "실패",
|
||||
"skippedCount": "건너뜀",
|
||||
"totalProcessed": "처리된 전체",
|
||||
"viewDetails": "세부 정보 보기",
|
||||
"newImport": "새 가져오기",
|
||||
"manualPathEntry": "폴더 경로를 직접 입력하세요. 이 브라우저에서는 파일 브라우저를 사용할 수 없습니다.",
|
||||
"batchImportDirectorySelected": "선택한 폴더: {path}",
|
||||
"batchImportManualEntryRequired": "파일 브라우저를 사용할 수 없습니다. 폴더 경로를 직접 입력하세요.",
|
||||
"backToParent": "상위 폴더로",
|
||||
"folders": "폴더",
|
||||
"folderCount": "폴더 {count}개",
|
||||
"imageFiles": "이미지 파일",
|
||||
"images": "이미지",
|
||||
"imageCount": "이미지 {count}개",
|
||||
"selectFolder": "이 폴더 선택",
|
||||
"errors": {
|
||||
"enterUrls": "Please enter at least one URL or path",
|
||||
"enterDirectory": "Please enter a directory path",
|
||||
"startFailed": "Failed to start import: {message}"
|
||||
"enterUrls": "URL 또는 경로를 하나 이상 입력하세요",
|
||||
"enterDirectory": "폴더 경로를 입력하세요",
|
||||
"startFailed": "가져오기를 시작하지 못했습니다: {message}"
|
||||
}
|
||||
}
|
||||
},
|
||||
@@ -1080,7 +1212,7 @@
|
||||
},
|
||||
"contextMenu": {
|
||||
"moveToOtherTypeFolder": "{otherType} 폴더로 이동",
|
||||
"sendToWorkflow": "워크플로우로 전송"
|
||||
"sendToWorkflow": "워크플로로 전송"
|
||||
}
|
||||
},
|
||||
"embeddings": {
|
||||
@@ -1238,7 +1370,7 @@
|
||||
"download": {
|
||||
"title": "URL에서 모델 다운로드",
|
||||
"titleWithType": "URL에서 {type} 다운로드",
|
||||
"civitaiUrl": "Civitai URL:",
|
||||
"civitaiUrl": "CivitAI URL:",
|
||||
"placeholder": "https://civitai.com/models/...",
|
||||
"urlHint": "한 줄에 하나의 CivitAI, CivArchive 또는 Hugging Face URL을 입력하세요. 여러 URL을 일괄 다운로드할 수 있습니다.",
|
||||
"selectHfFiles": "이 저장소에서 다운로드할 파일을 선택하세요:",
|
||||
@@ -1273,7 +1405,7 @@
|
||||
"inLibrary": "라이브러리에 있음"
|
||||
},
|
||||
"errors": {
|
||||
"invalidUrl": "잘못된 Civitai URL 형식",
|
||||
"invalidUrl": "잘못된 CivitAI URL 형식",
|
||||
"noVersions": "이 모델에 사용 가능한 버전이 없습니다",
|
||||
"mixedSources": "동일한 배치에서 CivitAI와 Hugging Face URL을 혼합할 수 없습니다.",
|
||||
"noModelFiles": "이 저장소에서 모델 파일을 찾을 수 없습니다."
|
||||
@@ -1352,9 +1484,9 @@
|
||||
"action": "모두 삭제"
|
||||
},
|
||||
"checkUpdates": {
|
||||
"title": "{type} 전체 업데이트를 확인할까요?",
|
||||
"message": "라이브러리에 있는 모든 {type}의 업데이트를 확인합니다. 컬렉션이 클수록 시간이 조금 더 걸릴 수 있습니다.",
|
||||
"tip": "나눠서 진행하고 싶다면 벌크 모드로 전환해 필요한 모델만 선택한 뒤 \"선택 항목 업데이트 확인\"을 사용하세요.",
|
||||
"title": "{typePlural} 전체 업데이트를 확인할까요?",
|
||||
"message": "라이브러리에 있는 모든 {typePlural}의 업데이트를 확인합니다. 컬렉션이 클수록 시간이 조금 더 걸릴 수 있습니다.",
|
||||
"tip": "나눠서 진행하고 싶다면 일괄 모드로 전환해 필요한 모델만 선택한 뒤 \"선택 항목 업데이트 확인\"을 사용하세요.",
|
||||
"action": "전체 확인"
|
||||
},
|
||||
"bulkAddTags": {
|
||||
@@ -1387,7 +1519,7 @@
|
||||
"title": "로컬 예시 이미지",
|
||||
"message": "이 모델의 로컬 예시 이미지를 찾을 수 없습니다. 보기 옵션:",
|
||||
"downloadOption": {
|
||||
"title": "Civitai에서 다운로드",
|
||||
"title": "CivitAI에서 다운로드",
|
||||
"description": "오프라인 사용 및 빠른 로딩을 위해 원격 예시를 로컬에 저장"
|
||||
},
|
||||
"importOption": {
|
||||
@@ -1414,7 +1546,7 @@
|
||||
"confirmAction": "저장 및 연결"
|
||||
},
|
||||
"relinkCivitai": {
|
||||
"title": "Civitai에 다시 연결",
|
||||
"title": "CivitAI에 다시 연결",
|
||||
"warning": "경고:",
|
||||
"warningText": "이것은 잠재적으로 파괴적인 작업입니다. 다시 연결하면:",
|
||||
"warningList": {
|
||||
@@ -1423,15 +1555,15 @@
|
||||
"unintendedConsequences": "기타 의도하지 않은 결과가 있을 수 있음"
|
||||
},
|
||||
"proceedText": "원하는 작업이 확실한 경우에만 진행하세요.",
|
||||
"urlLabel": "Civitai 모델 URL:",
|
||||
"urlPlaceholder": "https://civitai.com/models/12345/model-name?modelVersionId=67890",
|
||||
"urlLabel": "CivitAI 모델 URL:",
|
||||
"urlPlaceholder": "https://civitai.com/models/12345/model-name?modelVersionId=67890 또는 https://civitai.red/models/12345/model-name?modelVersionId=67890",
|
||||
"helpText": {
|
||||
"title": "Civitai 또는 CivitArchive 모델 URL을 붙여넣으세요. 지원되는 형식:",
|
||||
"title": "CivitAI 또는 CivitArchive 모델 URL을 붙여넣으세요. 지원되는 형식:",
|
||||
"format1": "https://civitai.com/models/12345",
|
||||
"format2": "https://civitai.com/models/12345?modelVersionId=67890",
|
||||
"format3": "https://civitai.com/models/12345/model-name?modelVersionId=67890",
|
||||
"note": "참고: modelVersionId가 제공되지 않으면 최신 버전이 사용됩니다.",
|
||||
"format4": "https://civarchive.com/models/12345 (CivitArchive)"
|
||||
"format4": "https://civarchive.com/models/12345 (CivArchive)"
|
||||
},
|
||||
"confirmAction": "다시 연결 확인"
|
||||
},
|
||||
@@ -1441,8 +1573,8 @@
|
||||
"editFileName": "파일명 편집",
|
||||
"editBaseModel": "베이스 모델 편집",
|
||||
"editVersionName": "버전명 편집",
|
||||
"viewOnCivitai": "Civitai에서 보기",
|
||||
"viewOnCivitaiText": "Civitai에서 보기",
|
||||
"viewOnCivitai": "CivitAI에서 보기",
|
||||
"viewOnCivitaiText": "CivitAI에서 보기",
|
||||
"viewOnHuggingFace": "Hugging Face에서 보기",
|
||||
"viewOnHuggingFaceText": "Hugging Face에서 보기",
|
||||
"viewCreatorProfile": "제작자 프로필 보기",
|
||||
@@ -1474,7 +1606,7 @@
|
||||
"notesHint": "Enter로 저장, Shift+Enter로 줄바꿈",
|
||||
"addNotesPlaceholder": "메모를 여기에 추가하세요...",
|
||||
"aboutThisVersion": "이 버전에 대해",
|
||||
"baseModelSearchPlaceholder": "베이스 모델 검색…",
|
||||
"baseModelSearchPlaceholder": "베이스 모델 검색...",
|
||||
"baseModelSuggested": "추천",
|
||||
"baseModelNoMatch": "일치하는 베이스 모델 없음"
|
||||
},
|
||||
@@ -1494,7 +1626,11 @@
|
||||
"clipSkip": "클립 스킵",
|
||||
"valuePlaceholder": "값",
|
||||
"add": "추가",
|
||||
"invalidRange": "잘못된 범위 형식입니다. x.x-y.y를 사용하세요"
|
||||
"invalidRange": "잘못된 범위 형식입니다. x.x-y.y를 사용하세요",
|
||||
"invalidValue": "유효한 숫자를 입력하세요",
|
||||
"saveFailed": "프리셋 매개변수 저장에 실패했습니다",
|
||||
"added": "프리셋 매개변수가 추가되었습니다",
|
||||
"updated": "프리셋 매개변수가 업데이트되었습니다"
|
||||
},
|
||||
"triggerWords": {
|
||||
"label": "트리거 단어",
|
||||
@@ -1505,7 +1641,7 @@
|
||||
"addPlaceholder": "입력하거나 아래 제안을 클릭하세요",
|
||||
"editWord": "트리거 단어 편집",
|
||||
"editPlaceholder": "트리거 단어 편집",
|
||||
"copyWord": "트리거 단어 복사",
|
||||
"copyOrEditWord": "클릭하여 복사, 더블 클릭하여 편집",
|
||||
"deleteWord": "트리거 단어 삭제",
|
||||
"suggestions": {
|
||||
"noSuggestions": "사용 가능한 제안이 없습니다",
|
||||
@@ -1543,10 +1679,10 @@
|
||||
"noNext": "다음 모델이 없습니다"
|
||||
},
|
||||
"license": {
|
||||
"noImageSell": "No selling generated content",
|
||||
"noRentCivit": "No Civitai generation",
|
||||
"noRent": "No generation services",
|
||||
"noSell": "No selling models",
|
||||
"noImageSell": "생성 콘텐츠 판매 금지",
|
||||
"noRentCivit": "CivitAI 생성 불가",
|
||||
"noRent": "생성 서비스 불가",
|
||||
"noSell": "모델 판매 금지",
|
||||
"creditRequired": "제작자 크레딧 필요",
|
||||
"noDerivatives": "공유 병합 불가",
|
||||
"noReLicense": "동일한 권한 필요",
|
||||
@@ -1565,8 +1701,8 @@
|
||||
"showCount": "예시 보기 ({count})",
|
||||
"hideExamples": "예시 숨기기",
|
||||
"addExamples": "예시 추가",
|
||||
"previousExample": "이전 예시",
|
||||
"nextExample": "다음 예시",
|
||||
"previousExample": "이전 예시([)",
|
||||
"nextExample": "다음 예시(])",
|
||||
"noExamples": "사용 가능한 예시 이미지가 없습니다",
|
||||
"addMoreExamples": "예시 더 추가",
|
||||
"dragDrop": "이미지 또는 비디오를 여기로 끌어다 놓으세요",
|
||||
@@ -1609,33 +1745,33 @@
|
||||
"newer": "최신 버전",
|
||||
"newerTooltip": "이 버전은 로컬의 최신 버전보다 더 새롭습니다",
|
||||
"earlyAccess": "얼리 액세스",
|
||||
"earlyAccessTooltip": "이 버전은 현재 Civitai 얼리 액세스가 필요합니다",
|
||||
"earlyAccessTooltip": "이 버전은 현재 CivitAI 얼리 액세스가 필요합니다",
|
||||
"paid": "유료",
|
||||
"paidTooltip": "이 버전은 다운로드하려면 결제가 필요합니다",
|
||||
"ignored": "무시됨",
|
||||
"ignoredTooltip": "이 버전은 업데이트 알림이 비활성화되어 있습니다",
|
||||
"onSiteOnly": "사이트 내 전용",
|
||||
"onSiteOnlyTooltip": "이 버전은 Civitai 사이트 내에서만 사용 가능하며 다운로드할 수 없습니다"
|
||||
"onSiteOnlyTooltip": "이 버전은 CivitAI 사이트 내에서만 사용 가능하며 다운로드할 수 없습니다"
|
||||
},
|
||||
"actions": {
|
||||
"download": "다운로드",
|
||||
"downloadTooltip": "이 버전 다운로드",
|
||||
"downloadChooseFilesTooltip": "다운로드할 파일 선택",
|
||||
"downloadEarlyAccessTooltip": "Civitai에서 이 얼리 액세스 버전 다운로드",
|
||||
"downloadPaidTooltip": "Civitai에서 이 유료 버전 다운로드",
|
||||
"downloadNotAllowedTooltip": "이 버전은 Civitai 사이트 내에서만 사용 가능하며 다운로드할 수 없습니다",
|
||||
"downloadEarlyAccessTooltip": "CivitAI에서 이 얼리 액세스 버전 다운로드",
|
||||
"downloadPaidTooltip": "CivitAI에서 이 유료 버전 다운로드",
|
||||
"downloadNotAllowedTooltip": "이 버전은 CivitAI 사이트 내에서만 사용 가능하며 다운로드할 수 없습니다",
|
||||
"delete": "삭제",
|
||||
"deleteTooltip": "이 로컬 버전 삭제",
|
||||
"ignore": "무시",
|
||||
"unignore": "무시 해제",
|
||||
"ignoreTooltip": "이 버전의 업데이트 알림 무시",
|
||||
"unignoreTooltip": "이 버전의 업데이트 알림 다시 받기",
|
||||
"viewVersionOnCivitai": "Civitai에서 버전 보기",
|
||||
"viewVersionOnCivitai": "CivitAI에서 버전 보기",
|
||||
"earlyAccessTooltip": "얼리 액세스 구매 필요",
|
||||
"resumeModelUpdates": "이 모델 업데이트 재개",
|
||||
"ignoreModelUpdates": "이 모델 업데이트 무시",
|
||||
"viewLocalVersions": "로컬 버전 모두 보기",
|
||||
"viewLocalTooltip": "곧 제공 예정"
|
||||
"viewLocalTooltip": "이 모델의 모든 로컬 버전을 메인 페이지에 표시"
|
||||
},
|
||||
"filters": {
|
||||
"label": "기본 필터",
|
||||
@@ -1651,7 +1787,7 @@
|
||||
},
|
||||
"empty": "이 모델에는 아직 버전 기록이 없습니다.",
|
||||
"error": "버전을 불러오지 못했습니다.",
|
||||
"missingModelId": "이 모델에는 Civitai 모델 ID가 없습니다.",
|
||||
"missingModelId": "이 모델에는 CivitAI 모델 ID가 없습니다.",
|
||||
"hfGroupInfo": "HuggingFace 모델 그룹입니다. 라이브러리를 열어 그리드에서 모든 버전을 확인하세요.",
|
||||
"confirm": {
|
||||
"delete": "이 버전을 라이브러리에서 삭제하시겠습니까?"
|
||||
@@ -1725,7 +1861,7 @@
|
||||
"message": "Embedding 캐시를 스캔하고 구축하고 있습니다. 몇 분이 걸릴 수 있습니다..."
|
||||
},
|
||||
"recipes": {
|
||||
"title": "Recipe Manager 초기화 중",
|
||||
"title": "레시피 매니저 초기화 중",
|
||||
"message": "레시피를 로딩하고 처리하고 있습니다. 몇 분이 걸릴 수 있습니다..."
|
||||
},
|
||||
"statistics": {
|
||||
@@ -1735,14 +1871,14 @@
|
||||
"tips": {
|
||||
"title": "팁 & 요령",
|
||||
"civitai": {
|
||||
"title": "Civitai 통합",
|
||||
"description": "Civitai 계정 연결: 프로필 아바타 → 설정 → API 키 → API 키 추가를 방문한 후 LoRA Manager 설정에 붙여넣으세요.",
|
||||
"alt": "Civitai API 설정"
|
||||
"title": "CivitAI 통합",
|
||||
"description": "CivitAI 계정 연결: 프로필 아바타 → 설정 → API 키 → API 키 추가를 방문한 후 LoRA Manager 설정에 붙여넣으세요.",
|
||||
"alt": "CivitAI API 설정"
|
||||
},
|
||||
"download": {
|
||||
"title": "간편 다운로드",
|
||||
"description": "Civitai URL을 사용하여 새로운 모델을 빠르게 다운로드하고 설치하세요.",
|
||||
"alt": "Civitai 다운로드"
|
||||
"description": "CivitAI URL을 사용하여 새로운 모델을 빠르게 다운로드하고 설치하세요.",
|
||||
"alt": "CivitAI 다운로드"
|
||||
},
|
||||
"recipes": {
|
||||
"title": "레시피 저장",
|
||||
@@ -1792,7 +1928,7 @@
|
||||
"recipeReplaced": "레시피가 워크플로에서 교체되었습니다",
|
||||
"recipeFailedToSend": "레시피를 워크플로로 전송하지 못했습니다",
|
||||
"noMatchingNodes": "현재 워크플로에서 호환되는 노드가 없습니다",
|
||||
"noPromptTargets": "워크플로우에 호환되는 프롬프트 타겟이 없습니다.\nComfyUI에서 노드를 우클릭 → Mark as → Send Prompt Target",
|
||||
"noPromptTargets": "워크플로에 호환되는 프롬프트 타겟이 없습니다.\nComfyUI에서 노드를 우클릭 → Mark as → Send Prompt Target",
|
||||
"noTargetNodeSelected": "대상 노드가 선택되지 않았습니다",
|
||||
"modelUpdated": "모델이 워크플로에서 업데이트되었습니다",
|
||||
"modelFailed": "모델 노드 업데이트 실패",
|
||||
@@ -1804,7 +1940,7 @@
|
||||
"nodeSelector": {
|
||||
"recipe": "레시피",
|
||||
"lora": "LoRA",
|
||||
"embedding": "임베딩",
|
||||
"embedding": "Embedding",
|
||||
"prompt": "프롬프트",
|
||||
"replace": "교체",
|
||||
"append": "추가",
|
||||
@@ -1830,10 +1966,52 @@
|
||||
"tabs": {
|
||||
"gettingStarted": "시작하기",
|
||||
"updateVlogs": "업데이트 영상",
|
||||
"documentation": "문서"
|
||||
"documentation": "문서",
|
||||
"shortcuts": "단축키"
|
||||
},
|
||||
"gettingStarted": {
|
||||
"title": "LoRA Manager 시작하기"
|
||||
"title": "LoRA Manager 시작하기",
|
||||
"replayTutorial": "튜토리얼 다시 보기"
|
||||
},
|
||||
"shortcuts": {
|
||||
"title": "키보드 & 마우스 단축키",
|
||||
"groups": {
|
||||
"general": "일반",
|
||||
"actions": "작업",
|
||||
"selection": "선택 & 일괄 모드",
|
||||
"navigation": "내비게이션",
|
||||
"modelModal": "모델 / 레시피 모달",
|
||||
"mediaViewer": "미디어 뷰어 / 쇼케이스"
|
||||
},
|
||||
"keys": {
|
||||
"click": "클릭",
|
||||
"drag": "드래그",
|
||||
"rightClick": "오른쪽 클릭",
|
||||
"letter": "문자 키",
|
||||
"swipe": "스와이프"
|
||||
},
|
||||
"entries": {
|
||||
"focusSearch": "검색창으로 포커스 이동",
|
||||
"closeModal": "모달 / 패널 닫기",
|
||||
"openShortcuts": "이 단축키 패널 열기",
|
||||
"refresh": "모델 목록 새로고침",
|
||||
"fetchMetadata": "CivitAI에서 메타데이터 가져오기 (모델 페이지만)",
|
||||
"downloadModel": "모델 다운로드 (모델 페이지만)",
|
||||
"toggleBulkMode": "일괄 모드 전환",
|
||||
"selectAll": "표시된 모든 모델 선택",
|
||||
"rangeSelect": "범위 선택",
|
||||
"marqueeSelect": "드래그로 카드 선택 (빈 그리드 영역에서)",
|
||||
"exitBulkMode": "일괄 모드 종료",
|
||||
"bulkActions": "선택한 카드에서: 일괄 작업 메뉴",
|
||||
"globalActions": "페이지 빈 영역에서: 전역 작업 메뉴 (업데이트 확인, 제외된 모델 관리)",
|
||||
"scrollPages": "페이지 스크롤",
|
||||
"jumpAlphabet": "알파벳 바로 이동",
|
||||
"prevNext": "이전 / 다음 모델",
|
||||
"deleteEntry": "삭제",
|
||||
"cycleMedia": "미디어 전환 (쇼케이스 갤러리에서 [ / ])",
|
||||
"swipeTouch": "터치 기기에서 미디어 전환",
|
||||
"closeViewer": "뷰어 닫기"
|
||||
}
|
||||
},
|
||||
"updateVlogs": {
|
||||
"title": "최신 업데이트",
|
||||
@@ -1850,7 +2028,8 @@
|
||||
"settings": "설정 & 구성",
|
||||
"extensions": "확장",
|
||||
"newBadge": "신규"
|
||||
}
|
||||
},
|
||||
"newContentBadge": "신규"
|
||||
},
|
||||
"update": {
|
||||
"title": "업데이트 확인",
|
||||
@@ -1926,7 +2105,7 @@
|
||||
"submitGithubIssue": "GitHub 이슈 제출",
|
||||
"joinDiscord": "Discord 참여",
|
||||
"youtubeChannel": "YouTube 채널",
|
||||
"civitaiProfile": "Civitai 프로필",
|
||||
"civitaiProfile": "CivitAI 프로필",
|
||||
"supportKofi": "Ko-fi에서 지원",
|
||||
"supportPatreon": "Patreon에서 지원"
|
||||
},
|
||||
@@ -1972,7 +2151,7 @@
|
||||
"pleaseSelectFile": "파일을 하나 이상 선택해주세요",
|
||||
"versionExists": "이 버전은 이미 라이브러리에 있습니다",
|
||||
"downloadCompleted": "다운로드가 성공적으로 완료되었습니다",
|
||||
"downloadSkippedByBaseModel": "기본 모델 {baseModel}이(가) 제외되어 다운로드를 건너뛰었습니다",
|
||||
"downloadSkippedByBaseModel": "베이스 모델 {baseModel}이(가) 제외되어 다운로드를 건너뛰었습니다",
|
||||
"autoOrganizeSuccess": "{count}개의 {type}에 대해 자동 정리가 성공적으로 완료되었습니다",
|
||||
"autoOrganizePartialSuccess": "자동 정리 완료: 전체 {total}개 중 {success}개 이동, {failures}개 실패",
|
||||
"autoOrganizeFailed": "자동 정리 실패: {error}",
|
||||
@@ -1996,7 +2175,7 @@
|
||||
"negativePromptUpdated": "네거티브 프롬프트가 성공적으로 업데이트되었습니다",
|
||||
"promptEditorHint": "Enter 키를 눌러 저장, Shift+Enter로 새 줄",
|
||||
"noRecipeId": "사용 가능한 레시피 ID가 없습니다",
|
||||
"sendToWorkflowFailed": "워크플로우에 레시피 보내기 실패: {message}",
|
||||
"sendToWorkflowFailed": "워크플로에 레시피 보내기 실패: {message}",
|
||||
"copyFailed": "레시피 문법 복사 오류: {message}",
|
||||
"createError": "레시피 생성 중 오류 발생:{message}",
|
||||
"createFailed": "레시피 생성 실패:{error}",
|
||||
@@ -2009,14 +2188,27 @@
|
||||
"preparingForDownloadFailed": "LoRA 다운로드 준비 오류",
|
||||
"enterLoraName": "LoRA 이름 또는 문법을 입력해주세요",
|
||||
"reconnectedSuccessfully": "LoRA가 성공적으로 다시 연결되었습니다",
|
||||
"reconnectBaseModelMismatch": "다시 연결했지만 베이스 모델이 다릅니다(레시피: {recipe}, LoRA: {lora}) — 아키텍처 호환입니다",
|
||||
"reconnectFailed": "LoRA 다시 연결 오류: {message}",
|
||||
"loraRestored": "LoRA가 이전 연결 상태로 복원되었습니다",
|
||||
"loraRestoreFailed": "LoRA 복원 오류: {message}",
|
||||
"noPromptToSend": "보낼 프롬프트가 없습니다",
|
||||
"cannotSend": "레시피를 전송할 수 없습니다: 레시피 ID 누락",
|
||||
"sendFailed": "레시피를 워크플로로 전송하는데 실패했습니다",
|
||||
"sendError": "레시피를 워크플로로 전송하는 중 오류",
|
||||
"missingCheckpointPath": "체크포인트 경로를 사용할 수 없습니다",
|
||||
"missingCheckpointInfo": "체크포인트 정보가 부족합니다",
|
||||
"downloadCheckpointFailed": "체크포인트 다운로드 실패: {message}",
|
||||
"missingCheckpointPath": "Checkpoint 경로를 사용할 수 없습니다",
|
||||
"missingCheckpointInfo": "Checkpoint 정보가 부족합니다",
|
||||
"downloadCheckpointFailed": "Checkpoint 다운로드 실패: {message}",
|
||||
"enterCheckpointName": "Checkpoint 이름을 입력하세요",
|
||||
"checkpointReconnectedSuccessfully": "Checkpoint가 성공적으로 다시 연결되었습니다",
|
||||
"reconnectCheckpointBaseModelMismatch": "다시 연결했지만 베이스 모델이 다릅니다(레시피: {recipe}, Checkpoint: {checkpoint}) — 아키텍처 호환입니다",
|
||||
"checkpointReconnectFailed": "Checkpoint 다시 연결 오류: {message}",
|
||||
"checkpointRestored": "Checkpoint가 이전 연결 상태로 복원되었습니다",
|
||||
"checkpointRestoreFailed": "Checkpoint 복원 오류: {message}",
|
||||
"checkpointDownloadUnavailable": "CivitAI 식별자가 없어 이 Checkpoint를 다운로드할 수 없습니다 - 로컬 Checkpoint로 다시 연결해 보세요",
|
||||
"missingLoraDownloadInfo": "이 LoRA의 다운로드 정보가 없습니다",
|
||||
"hashNotFoundOnCivitai": "이 LoRA 해시는 CivitAI에서 해석할 수 없습니다 - 모델이 업데이트되었거나 해시가 유효하지 않을 수 있습니다",
|
||||
"downloadLoraFailed": "LoRA 다운로드 실패: {message}",
|
||||
"cannotDelete": "레시피를 삭제할 수 없습니다: 레시피 ID 누락",
|
||||
"deleteConfirmationError": "삭제 확인 표시 오류",
|
||||
"deletedSuccessfully": "레시피가 성공적으로 삭제되었습니다",
|
||||
@@ -2031,18 +2223,18 @@
|
||||
"processingError": "처리 오류: {message}",
|
||||
"folderBrowserError": "폴더 브라우저 로딩 오류: {message}",
|
||||
"recipeSaveFailed": "레시피 저장 실패: {error}",
|
||||
"recipeSaved": "Recipe saved successfully",
|
||||
"recipeSaved": "레시피가 저장되었습니다",
|
||||
"importFailed": "가져오기 실패: {message}",
|
||||
"folderTreeFailed": "폴더 트리 로딩 실패",
|
||||
"folderTreeError": "폴더 트리 로딩 오류",
|
||||
"batchImportFailed": "Failed to start batch import: {message}",
|
||||
"batchImportCancelling": "Cancelling batch import...",
|
||||
"batchImportCancelFailed": "Failed to cancel batch import: {message}",
|
||||
"batchImportNoUrls": "Please enter at least one URL or file path",
|
||||
"batchImportNoDirectory": "Please enter a directory path",
|
||||
"batchImportRateLimited": "[TODO: Translate] Metadata provider rate limit reached — requests are being slowed and some items may be skipped. You can re-run the import later.",
|
||||
"batchImportBrowseFailed": "Failed to browse directory: {message}",
|
||||
"batchImportDirectorySelected": "Directory selected: {path}",
|
||||
"batchImportFailed": "일괄 가져오기를 시작하지 못했습니다: {message}",
|
||||
"batchImportCancelling": "일괄 가져오기를 취소하는 중...",
|
||||
"batchImportCancelFailed": "일괄 가져오기를 취소하지 못했습니다: {message}",
|
||||
"batchImportNoUrls": "URL 또는 파일 경로를 하나 이상 입력하세요",
|
||||
"batchImportNoDirectory": "폴더 경로를 입력하세요",
|
||||
"batchImportRateLimited": "메타데이터 제공자 속도 제한 도달 — 요청이 느려지고 일부 항목이 건너뛰어질 수 있습니다. 나중에 가져오기를 다시 실행할 수 있습니다.",
|
||||
"batchImportBrowseFailed": "폴더를 찾아보지 못했습니다: {message}",
|
||||
"batchImportDirectorySelected": "선택한 폴더: {path}",
|
||||
"noRecipesSelected": "선택한 레시피가 없습니다",
|
||||
"repairBulkComplete": "복구 완료: {repaired}개 복구, {skipped}개 건너뜀 (총 {total}개)",
|
||||
"repairBulkSkipped": "선택한 {total}개 레시피는 복구가 필요하지 않습니다",
|
||||
@@ -2098,8 +2290,8 @@
|
||||
"bulkUpdatesChecking": "선택한 {type}의 업데이트를 확인하는 중...",
|
||||
"bulkUpdatesSuccess": "선택한 {count}개의 {type}에 사용할 수 있는 업데이트가 있습니다",
|
||||
"bulkUpdatesNone": "선택한 {type}에 대한 업데이트가 없습니다",
|
||||
"bulkUpdatesMissing": "선택한 {type}이 Civitai 업데이트에 연결되어 있지 않습니다",
|
||||
"bulkUpdatesPartialMissing": "Civitai 링크가 없는 {missing}개의 {type}을 건너뛰었습니다",
|
||||
"bulkUpdatesMissing": "선택한 {type}이 CivitAI 업데이트에 연결되어 있지 않습니다",
|
||||
"bulkUpdatesPartialMissing": "CivitAI 링크가 없는 {missing}개의 {type}을 건너뛰었습니다",
|
||||
"bulkUpdatesFailed": "선택한 {type}의 업데이트 확인에 실패했습니다: {message}",
|
||||
"invalidCharactersRemoved": "파일명에서 잘못된 문자가 제거되었습니다",
|
||||
"filenameCannotBeEmpty": "파일 이름은 비어있을 수 없습니다",
|
||||
@@ -2139,8 +2331,8 @@
|
||||
"compactModeToggled": "컴팩트 모드 {state}",
|
||||
"settingSaveFailed": "설정 저장 실패: {message}",
|
||||
"displayDensitySet": "표시 밀도가 {density}로 설정되었습니다",
|
||||
"libraryLoadFailed": "Failed to load libraries: {message}",
|
||||
"libraryActivateFailed": "Failed to activate library: {message}",
|
||||
"libraryLoadFailed": "라이브러리를 불러오지 못했습니다: {message}",
|
||||
"libraryActivateFailed": "라이브러리를 활성화하지 못했습니다: {message}",
|
||||
"languageChangeFailed": "언어 변경 실패: {message}",
|
||||
"cacheCleared": "캐시 파일이 성공적으로 지워졌습니다. 다음 작업 시 캐시가 재구축됩니다.",
|
||||
"cacheClearFailed": "캐시 지우기 실패: {error}",
|
||||
@@ -2225,7 +2417,7 @@
|
||||
"contextMenu": {
|
||||
"contentRatingSet": "콘텐츠 등급이 {level}로 설정되었습니다",
|
||||
"contentRatingFailed": "콘텐츠 등급 설정 실패: {message}",
|
||||
"relinkSuccess": "모델이 Civitai에 성공적으로 다시 연결되었습니다",
|
||||
"relinkSuccess": "모델이 CivitAI에 성공적으로 다시 연결되었습니다",
|
||||
"relinkFailed": "오류: {message}",
|
||||
"linkHfSuccess": "모델이 HuggingFace에 연결되었습니다",
|
||||
"linkHfFailed": "오류: {message}",
|
||||
@@ -2289,7 +2481,7 @@
|
||||
"bulkMoveSuccess": "{successCount}개 {type}이(가) 성공적으로 이동되었습니다",
|
||||
"exampleImagesDownloadSuccess": "예시 이미지가 성공적으로 다운로드되었습니다!",
|
||||
"exampleImagesDownloadFailed": "예시 이미지 다운로드 실패: {message}",
|
||||
"moveFailed": "Failed to move item: {message}",
|
||||
"moveFailed": "항목을 이동하지 못했습니다: {message}",
|
||||
"copiedToClipboard": "클립보드에 복사됨",
|
||||
"downloadStarted": "다운로드 시작됨"
|
||||
},
|
||||
@@ -2319,7 +2511,7 @@
|
||||
},
|
||||
"issues": {
|
||||
"civitai_api_key": {
|
||||
"title": "Civitai API 키"
|
||||
"title": "CivitAI API 키"
|
||||
},
|
||||
"cache_health": {
|
||||
"title": "모델 캐시 상태"
|
||||
@@ -2357,7 +2549,7 @@
|
||||
"conflictConfirm": {
|
||||
"title": "파일명 충돌 해결",
|
||||
"message": "중복 파일명에 4자리 해시를 추가하여 이름을 변경합니다.",
|
||||
"note": "이 작업은 디스크에 있는 파일의 이름을 변경합니다. A1111 구문 형식을 사용하는 경우 기존 워크플로우의 모델 참조를 업데이트해야 할 수 있습니다.",
|
||||
"note": "이 작업은 디스크에 있는 파일의 이름을 변경합니다. A1111 구문 형식을 사용하는 경우 기존 워크플로의 모델 참조를 업데이트해야 할 수 있습니다.",
|
||||
"detail": "예시: <code>filename_v1.2</code> → <code>filename_v1.2-ab3c</code>",
|
||||
"impact": "<strong>{groups}</strong>개 중복 그룹에서 <strong>{count}</strong>개 파일 이름을 변경합니다",
|
||||
"confirm": "파일 이름 변경",
|
||||
@@ -2372,10 +2564,10 @@
|
||||
"seconds": "초"
|
||||
},
|
||||
"communitySupport": {
|
||||
"title": "Keep LoRA Manager Thriving with Your Support ❤️",
|
||||
"content": "LoRA Manager is a passion project maintained full-time by a solo developer. Your support on Ko-fi helps cover development costs, keeps new updates coming, and unlocks a license key for the LM Civitai Extension as a thank-you gift. Every contribution truly makes a difference.",
|
||||
"supportCta": "Support on Ko-fi",
|
||||
"learnMore": "LM Civitai Extension Tutorial"
|
||||
"title": "여러분의 지원으로 LoRA Manager가 계속 성장합니다 ❤️",
|
||||
"content": "LoRA Manager는 한 명의 개발자가 전담으로 유지하는 열정적인 프로젝트입니다. Ko-fi에서의 지원은 개발 비용을 충당하고 새로운 업데이트를 제공하는 데 도움이 되며, 감사의 의미로 LM CivitAI 확장 기능의 라이선스 키를 드립니다. 모든 기여가 실질적인 차이를 만듭니다.",
|
||||
"supportCta": "Ko-fi에서 지원하기",
|
||||
"learnMore": "LM CivitAI 확장 기능 튜토리얼"
|
||||
},
|
||||
"cacheHealth": {
|
||||
"corrupted": {
|
||||
|
||||
+374
-182
File diff suppressed because it is too large
Load Diff
+295
-103
@@ -50,6 +50,27 @@
|
||||
"mb": "MB",
|
||||
"gb": "GB",
|
||||
"tb": "TB"
|
||||
},
|
||||
"scanProgress": {
|
||||
"refreshing": "正在刷新 {type}...",
|
||||
"fullRebuilding": "正在完全重建 {type}...",
|
||||
"actionRefresh": "刷新",
|
||||
"actionFullRebuild": "完全重建",
|
||||
"actionRefreshLower": "刷新",
|
||||
"actionRebuildLower": "重建",
|
||||
"stages": {
|
||||
"scan_folders": "正在扫描文件夹...",
|
||||
"count_models": "找到 {total} 个文件",
|
||||
"process_models": "正在处理模型",
|
||||
"reconcile_scan": "正在检查变更...",
|
||||
"process_new": "正在处理新模型",
|
||||
"finalizing": "正在收尾..."
|
||||
},
|
||||
"eta": {
|
||||
"lessThanMinute": "剩余时间不到一分钟",
|
||||
"minutes": "剩余约 {minutes} 分钟",
|
||||
"hours": "剩余约 {hours} 小时 {minutes} 分钟"
|
||||
}
|
||||
}
|
||||
},
|
||||
"onboarding": {
|
||||
@@ -67,15 +88,15 @@
|
||||
"steps": {
|
||||
"fetch": {
|
||||
"title": "获取模型元数据",
|
||||
"content": "点击 <strong>获取</strong> 按钮,从 Civitai 下载模型元数据和预览图片。"
|
||||
"content": "点击 <strong>获取</strong> 按钮,从 CivitAI 下载模型元数据和预览图片。"
|
||||
},
|
||||
"download": {
|
||||
"title": "下载新模型",
|
||||
"content": "使用 <strong>下载</strong> 按钮,可直接通过 Civitai URL 下载模型。"
|
||||
"content": "使用 <strong>下载</strong> 按钮,可直接通过 CivitAI URL 下载模型。"
|
||||
},
|
||||
"bulk": {
|
||||
"title": "批量操作",
|
||||
"content": "点击此按钮或按 <span class=\"onboarding-shortcut\">B</span> 进入批量模式。可多选模型并进行批量操作。使用 <span class=\"onboarding-shortcut\">Ctrl+A</span> 全选所有可见模型。"
|
||||
"content": "点击此按钮或按 <span class=\"onboarding-shortcut\">B</span> 进入批量模式,可多选模型并执行批量操作。<br>• <span class=\"onboarding-shortcut\">Ctrl/Cmd+A</span> 全选所有可见模型,<span class=\"onboarding-shortcut\">Shift+Click</span> 选择一个范围。<br>• 按 <span class=\"onboarding-shortcut\">Esc</span> 或点击空白区域退出批量模式。"
|
||||
},
|
||||
"searchOptions": {
|
||||
"title": "搜索选项",
|
||||
@@ -95,7 +116,19 @@
|
||||
},
|
||||
"contextMenu": {
|
||||
"title": "右键菜单",
|
||||
"content": "<strong>右键点击</strong>任意模型卡片可打开更多操作菜单。"
|
||||
"content": "<strong>右键点击</strong>任意模型卡片,可打开包含移动、删除或编辑元数据等卡片操作的菜单。"
|
||||
},
|
||||
"marqueeSelect": {
|
||||
"title": "拖动框选",
|
||||
"content": "在网格的空白区域按住<strong>鼠标左键</strong>并拖动,绘制一个可同时选中多张卡片的框选区域。"
|
||||
},
|
||||
"dragToSidebar": {
|
||||
"title": "拖放整理",
|
||||
"content": "将模型卡片拖到侧边栏的文件夹上,即可把文件移动到该文件夹。批量模式下选中的多张卡片也可如此操作。"
|
||||
},
|
||||
"contextMenus": {
|
||||
"title": "更多右键菜单",
|
||||
"content": "在批量模式下,<strong>右键点击已选中的卡片</strong>可进行批量操作。<strong>右键点击页面空白区域</strong>可使用检查更新、管理已排除的模型等全局操作。"
|
||||
}
|
||||
}
|
||||
},
|
||||
@@ -103,12 +136,12 @@
|
||||
"actions": {
|
||||
"addToFavorites": "添加到收藏",
|
||||
"removeFromFavorites": "从收藏移除",
|
||||
"viewOnCivitai": "在 Civitai 查看",
|
||||
"notAvailableFromCivitai": "Civitai 上不可用",
|
||||
"viewOnCivitai": "在 CivitAI 查看",
|
||||
"notAvailableFromCivitai": "CivitAI 上不可用",
|
||||
"viewOnHuggingFace": "在 Hugging Face 查看",
|
||||
"sendToWorkflow": "发送到 ComfyUI(点击:追加,Shift+点击:替换)",
|
||||
"copyLoRASyntax": "复制 LoRA 语法",
|
||||
"checkpointNameCopied": "检查点名称已复制",
|
||||
"checkpointNameCopied": "Checkpoint 名称已复制",
|
||||
"toggleBlur": "切换模糊",
|
||||
"show": "显示",
|
||||
"openExampleImages": "打开示例图片文件夹",
|
||||
@@ -131,13 +164,13 @@
|
||||
"updateFailed": "收藏状态更新失败"
|
||||
},
|
||||
"sendToWorkflow": {
|
||||
"checkpointNotImplemented": "发送检查点到工作流 - 功能待实现",
|
||||
"checkpointNotImplemented": "发送Checkpoint到工作流 - 功能待实现",
|
||||
"missingPath": "无法确定此卡片的模型路径"
|
||||
},
|
||||
"exampleImages": {
|
||||
"checkError": "检查示例图片时出错",
|
||||
"missingHash": "缺少模型哈希信息。",
|
||||
"noRemoteImagesAvailable": "此模型在 Civitai 上没有远程示例图片"
|
||||
"noRemoteImagesAvailable": "此模型在 CivitAI 上没有远程示例图片"
|
||||
},
|
||||
"badges": {
|
||||
"update": "更新",
|
||||
@@ -187,14 +220,14 @@
|
||||
"error": "配方修复失败:{message}"
|
||||
},
|
||||
"rematchRecipes": {
|
||||
"label": "将食谱重新匹配到本地模型",
|
||||
"loading": "正在将食谱重新匹配到本地模型...",
|
||||
"success": "已匹配 {entries} 个条目,涉及 {recipes} 个食谱",
|
||||
"successErrors": "已匹配 {entries} 个条目,涉及 {recipes} 个食谱,{failures} 个失败",
|
||||
"allFailed": "{failures}/{total} 个食谱重新匹配失败",
|
||||
"noMatch": "在 {recipes} 个食谱中未找到 {entries} 个条目的本地匹配",
|
||||
"cancelled": "已取消重新匹配。{recipes} 个食谱已更新({entries} 个条目)。",
|
||||
"error": "食谱重新匹配失败:{message}"
|
||||
"label": "将配方重新匹配到本地模型",
|
||||
"loading": "正在将配方重新匹配到本地模型...",
|
||||
"success": "已匹配 {entries} 个条目,涉及 {recipes} 个配方",
|
||||
"successErrors": "已匹配 {entries} 个条目,涉及 {recipes} 个配方,{failures} 个失败",
|
||||
"allFailed": "{failures}/{total} 个配方重新匹配失败",
|
||||
"noMatch": "在 {recipes} 个配方中未找到 {entries} 个条目的本地匹配",
|
||||
"cancelled": "已取消重新匹配。{recipes} 个配方已更新({entries} 个条目)。",
|
||||
"error": "配方重新匹配失败:{message}"
|
||||
},
|
||||
"manageExcludedModels": {
|
||||
"label": "管理已排除的模型"
|
||||
@@ -290,15 +323,15 @@
|
||||
}
|
||||
},
|
||||
"settings": {
|
||||
"civitaiApiKey": "Civitai API 密钥",
|
||||
"civitaiApiKeyPlaceholder": "请输入你的 Civitai API 密钥",
|
||||
"civitaiApiKeyHelp": "用于从 Civitai 下载模型时的身份验证",
|
||||
"civitaiApiKey": "CivitAI API 密钥",
|
||||
"civitaiApiKeyPlaceholder": "请输入你的 CivitAI API 密钥",
|
||||
"civitaiApiKeyHelp": "用于从 CivitAI 下载模型时的身份验证",
|
||||
"civitaiApiKeyConfigured": "已配置",
|
||||
"civitaiApiKeyNotConfigured": "未配置",
|
||||
"civitaiApiKeySet": "设置",
|
||||
"civitaiHost": {
|
||||
"label": "Civitai 站点",
|
||||
"help": "选择使用“在 Civitai 中查看”时默认打开的 Civitai 站点。",
|
||||
"label": "CivitAI 站点",
|
||||
"help": "选择使用“在 CivitAI 中查看”时默认打开的 CivitAI 站点。",
|
||||
"options": {
|
||||
"com": "civitai.com(仅 SFW)",
|
||||
"red": "civitai.red(无限制)"
|
||||
@@ -319,8 +352,8 @@
|
||||
},
|
||||
"aria2HelpLink": "了解如何配置 aria2 下载后端",
|
||||
"civitaiHostBanner": {
|
||||
"title": "已提供 Civitai 站点偏好设置",
|
||||
"content": "Civitai 现在使用 civitai.com 提供 SFW 内容,使用 civitai.red 提供无限制内容。你可以在设置中更改默认打开的站点。",
|
||||
"title": "已提供 CivitAI 站点偏好设置",
|
||||
"content": "CivitAI 现在使用 civitai.com 提供 SFW 内容,使用 civitai.red 提供无限制内容。你可以在设置中更改默认打开的站点。",
|
||||
"openSettings": "打开设置"
|
||||
},
|
||||
"openSettingsFileLocation": {
|
||||
@@ -428,7 +461,7 @@
|
||||
},
|
||||
"downloadSkipBaseModels": {
|
||||
"label": "跳过这些基础模型的下载",
|
||||
"help": "适用于所有下载流程。这里只能选择受支持的基础模型。",
|
||||
"help": "启用后,使用所选基础模型的版本将被跳过。",
|
||||
"searchPlaceholder": "筛选基础模型...",
|
||||
"empty": "没有与当前搜索匹配的基础模型。",
|
||||
"summary": {
|
||||
@@ -450,7 +483,7 @@
|
||||
},
|
||||
"layoutSettings": {
|
||||
"groupByModel": "按模型分组",
|
||||
"groupByModelHelp": "开启后,每个 Civitai 模型仅显示最新版本的单张卡片,旧版本将被隐藏。",
|
||||
"groupByModelHelp": "开启后,每个 CivitAI 模型仅显示最新版本的单张卡片,旧版本将被隐藏。",
|
||||
"displayDensity": "显示密度",
|
||||
"displayDensityOptions": {
|
||||
"default": "默认",
|
||||
@@ -555,7 +588,7 @@
|
||||
},
|
||||
"downloadPathTemplates": {
|
||||
"title": "下载路径模板",
|
||||
"help": "配置从 Civitai 下载不同模型类型的文件夹结构。",
|
||||
"help": "配置从 CivitAI 下载不同模型类型的文件夹结构。",
|
||||
"availablePlaceholders": "可用占位符:",
|
||||
"templateOptions": {
|
||||
"flatStructure": "扁平结构",
|
||||
@@ -592,7 +625,7 @@
|
||||
"exampleImages": {
|
||||
"downloadLocation": "下载位置",
|
||||
"downloadLocationPlaceholder": "输入示例图片文件夹路径",
|
||||
"downloadLocationHelp": "输入保存从 Civitai 下载的示例图片的文件夹路径",
|
||||
"downloadLocationHelp": "输入保存从 CivitAI 下载的示例图片的文件夹路径",
|
||||
"autoDownload": "自动下载示例图片",
|
||||
"autoDownloadHelp": "自动为没有示例图片的模型下载示例图片(需设置下载位置)",
|
||||
"openMode": "打开示例图片操作",
|
||||
@@ -625,7 +658,7 @@
|
||||
},
|
||||
"hideEarlyAccessUpdates": {
|
||||
"label": "隐藏抢先体验更新",
|
||||
"help": "抢先体验更新"
|
||||
"help": "启用后,仅有抢先体验更新的模型将不显示“可更新”徽章。"
|
||||
},
|
||||
"hidePaidUpdates": {
|
||||
"label": "隐藏付费更新",
|
||||
@@ -647,7 +680,7 @@
|
||||
},
|
||||
"metadataArchive": {
|
||||
"enableArchiveDb": "启用元数据归档数据库",
|
||||
"enableArchiveDbHelp": "使用本地数据库访问已从 Civitai 删除的模型元数据。",
|
||||
"enableArchiveDbHelp": "使用本地数据库访问已从 CivitAI 删除的模型元数据。",
|
||||
"status": "状态",
|
||||
"statusAvailable": "可用",
|
||||
"statusUnavailable": "不可用",
|
||||
@@ -696,7 +729,7 @@
|
||||
"aiProvider": {
|
||||
"title": "AI 提供商",
|
||||
"provider": "提供商",
|
||||
"providerHelp": "选择您的 LLM 提供商。OpenAI 和 Ollama 使用预设的 API 端点。自定义允许您指定任何兼容 OpenAI 的端点。",
|
||||
"providerHelp": "选择你的 LLM 提供商。OpenAI 和 Ollama 使用预设的 API 端点。自定义允许你指定任何兼容 OpenAI 的端点。",
|
||||
"providerOptions": {
|
||||
"openai": "OpenAI",
|
||||
"ollama": "Ollama(本地)",
|
||||
@@ -711,7 +744,7 @@
|
||||
"apiBaseHelp": "LLM API 的基础地址。选择预设或输入自定义地址,下拉框显示所有支持的提供商预设。",
|
||||
"apiBasePlaceholder": "https://api.openai.com/v1",
|
||||
"apiKey": "API 密钥",
|
||||
"apiKeyHelp": "LLM 提供商的 API 密钥。本地存储,除您选择的 LLM 提供商外不会发送到任何服务器。",
|
||||
"apiKeyHelp": "LLM 提供商的 API 密钥。本地存储,除你选择的 LLM 提供商外不会发送到任何服务器。",
|
||||
"apiKeyPlaceholder": "sk-...",
|
||||
"apiKeyNotSet": "未设置",
|
||||
"apiKeyConfigured": "已配置",
|
||||
@@ -750,7 +783,7 @@
|
||||
"fullTooltip": "从元数据文件重新加载所有模型信息;用于列表过时或手动编辑后。"
|
||||
},
|
||||
"fetch": {
|
||||
"title": "从 Civitai 获取元数据",
|
||||
"title": "从 CivitAI 获取元数据",
|
||||
"action": "获取"
|
||||
},
|
||||
"download": {
|
||||
@@ -825,10 +858,10 @@
|
||||
"enrichHfAgent": "AI HF 元数据增强"
|
||||
},
|
||||
"contextMenu": {
|
||||
"refreshMetadata": "刷新 Civitai 数据",
|
||||
"refreshMetadata": "刷新 CivitAI 数据",
|
||||
"checkUpdates": "检查更新",
|
||||
"linkModel": "链接模型",
|
||||
"linkCivitai": "链接到 Civitai",
|
||||
"linkCivitai": "链接到 CivitAI",
|
||||
"linkHuggingFace": "链接到 HuggingFace",
|
||||
"copySyntax": "复制 LoRA 语法",
|
||||
"copyFilename": "复制模型文件名",
|
||||
@@ -860,6 +893,7 @@
|
||||
"actions": {
|
||||
"sendCheckpoint": "发送到 ComfyUI",
|
||||
"sendRecipe": "发送到 ComfyUI",
|
||||
"copyRecipeSyntax": "复制配方语法",
|
||||
"deleteRecipeWithShortcut": "删除配方(Del)"
|
||||
},
|
||||
"navigation": {
|
||||
@@ -867,12 +901,110 @@
|
||||
"previousWithShortcut": "上一个配方(←)",
|
||||
"nextWithShortcut": "下一个配方(→)"
|
||||
},
|
||||
"modal": {
|
||||
"metadata": {
|
||||
"id": "ID"
|
||||
},
|
||||
"actions": {
|
||||
"openFileLocation": "打开文件位置",
|
||||
"copyId": "复制配方 ID"
|
||||
},
|
||||
"openFileLocation": {
|
||||
"success": "文件位置已成功打开",
|
||||
"failed": "打开文件位置失败",
|
||||
"copied": "路径已复制到剪贴板:{{path}}",
|
||||
"clipboardFallback": "路径:{{path}}"
|
||||
}
|
||||
},
|
||||
"workflow": {
|
||||
"sendWorkflow": "发送工作流到 ComfyUI",
|
||||
"sent": "工作流已发送到 ComfyUI",
|
||||
"sendFailed": "发送工作流到 ComfyUI 失败",
|
||||
"noWorkflow": "此配方中未找到内嵌工作流"
|
||||
},
|
||||
"status": {
|
||||
"ready": "可直接使用",
|
||||
"missingCount": "缺失 {count} 个",
|
||||
"deletedCount": "已删除 {count} 个",
|
||||
"downloadMissing": "下载 {count} 个缺失的 LoRA",
|
||||
"downloadMissingTooltip": "点击下载缺失的 LoRA"
|
||||
},
|
||||
"loraStatus": {
|
||||
"none": "此配方不包含 LoRA",
|
||||
"allAvailable": "所有 LoRA 均已就绪 - 可直接使用",
|
||||
"missing": "{total} 个 LoRA 中缺失 {missing} 个",
|
||||
"missingAndUnavailable": "{total} 个 LoRA 中缺失 {missing} 个,{unavailable} 个不可用(已从源站删除或哈希无法解析)",
|
||||
"partial": "{total} 个 LoRA 中 {unavailable} 个不可用(已从源站删除或哈希无法解析)- 使用配方时将被跳过",
|
||||
"noneUsable": "没有可用的 LoRA - {total} 个中 {unavailable} 个已从源站删除或哈希无法解析"
|
||||
},
|
||||
"resources": {
|
||||
"inLibrary": "在库中",
|
||||
"notInLibrary": "不在库中",
|
||||
"deleted": "已删除",
|
||||
"hashInvalid": "无法解析的哈希",
|
||||
"inLibraryTooltip": "该模型已存在于本地库中",
|
||||
"notInLibraryTooltip": "该模型不在你的本地库中",
|
||||
"deletedTooltip": "该 LoRA 已从来源站删除,无法下载",
|
||||
"hashInvalidTooltip": "此 LoRA 哈希无法在 CivitAI 上解析——模型可能已更新",
|
||||
"noLorasAssociated": "此配方没有关联任何 LoRA",
|
||||
"noLorasWhyToggle": "为什么没有 LoRA?",
|
||||
"noLorasImportMethod": "导入方式",
|
||||
"noLorasInferredNote": "可能的原因(推断)——该配方是在记录导入诊断信息之前导入的。",
|
||||
"noLorasChannels": {
|
||||
"batch_import_url": "批量导入(图片 URL)",
|
||||
"batch_import_local": "批量导入(本地文件)",
|
||||
"url": "图片 URL 导入",
|
||||
"local": "本地文件导入",
|
||||
"upload": "图片上传",
|
||||
"widget": "从工作流保存",
|
||||
"reimport_url": "重新导入(图片 URL)",
|
||||
"reimport_local": "重新导入(本地文件)"
|
||||
},
|
||||
"noLorasReasons": {
|
||||
"no_loras_used": "生成元数据完整,且未引用任何 LoRA。",
|
||||
"api_meta_no_lora_resources": "来源 API 未返回此图片的 LoRA 资源数据。CivitAI 页面上显示的 LoRA 可能来自公开 API 未开放的内部数据。",
|
||||
"api_meta_missing": "来源 API 未返回此图片的生成元数据。",
|
||||
"no_embedded_metadata": "图片没有内嵌生成元数据,因此无法恢复 LoRA 信息。",
|
||||
"workflow_metadata_limited": "图片内嵌的元数据是 ComfyUI 工作流;从工作流中提取 LoRA 信息的能力有限。",
|
||||
"video_no_metadata": "视频文件不携带内嵌生成元数据。",
|
||||
"metadata_unsupported": "图片包含的元数据格式无法解析。",
|
||||
"unknown": "无法从存储的配方数据中确定原因。"
|
||||
},
|
||||
"noLorasDetails": {
|
||||
"apiMetaFields": "API 元数据字段",
|
||||
"modelVersionIds": "报告的模型版本 ID 数",
|
||||
"embeddedMetadata": "内嵌元数据",
|
||||
"present": "已找到",
|
||||
"absent": "无"
|
||||
},
|
||||
"download": "下载",
|
||||
"downloadLoraTooltip": "下载此 LoRA",
|
||||
"preparingDownload": "正在准备下载...",
|
||||
"reconnect": "重新关联",
|
||||
"reconnectTooltip": "与本地 LoRA 重新关联",
|
||||
"reconnectInstructions": "输入 LoRA 语法或名称以重新关联:",
|
||||
"reconnectExample": "示例:<lora:name:1> 或只填名称",
|
||||
"reconnectPlaceholder": "输入 LoRA 名称或语法",
|
||||
"reconnectSuggestionsLoading": "正在搜索本地库...",
|
||||
"reconnectSuggestionsEmpty": "本地库中没有匹配的 LoRA",
|
||||
"reconnectMatchSameHash": "相同哈希",
|
||||
"reconnectMatchSameVersion": "相同模型版本",
|
||||
"reconnectMatchSimilarFilename": "相似文件名",
|
||||
"reconnectMatchSimilarName": "相似名称",
|
||||
"undoReconnect": "撤销",
|
||||
"undoReconnectTooltip": "恢复此条目在重新关联前的关联",
|
||||
"undoReconnectTooltipNamed": "恢复为 {name}(重新关联前的关联)",
|
||||
"viewOnCivitai": "在 CivitAI 上查看",
|
||||
"openLoraDetails": "在 LoRA 库中查看 {name}",
|
||||
"openCheckpointDetails": "在模型库中查看 {name}",
|
||||
"checkpointDeletedTooltip": "此 Checkpoint 已从来源删除,无法再下载 - 请使用本地模型重新关联",
|
||||
"checkpointHashInvalidTooltip": "此 Checkpoint 的哈希无法在 CivitAI 上解析 - 模型可能已更新",
|
||||
"reconnectCheckpoint": "重新关联",
|
||||
"reconnectCheckpointTooltip": "与本地 Checkpoint 重新关联",
|
||||
"checkpointReconnectInstructions": "输入 Checkpoint 名称以重新关联:",
|
||||
"checkpointReconnectPlaceholder": "输入 Checkpoint 名称",
|
||||
"checkpointReconnectSuggestionsEmpty": "本地库中没有匹配的 Checkpoint"
|
||||
},
|
||||
"controls": {
|
||||
"import": {
|
||||
"action": "导入",
|
||||
@@ -890,7 +1022,7 @@
|
||||
"addTag": "添加",
|
||||
"noTagsAdded": "未添加标签",
|
||||
"lorasInRecipe": "此配方中的 LoRA",
|
||||
"downloadLocationPreview": "下载位置预览:{path}",
|
||||
"downloadLocationPreview": "下载位置预览:",
|
||||
"useDefaultPath": "使用默认路径",
|
||||
"useDefaultPathTooltip": "启用后,文件将自动使用配置的路径模板进行组织",
|
||||
"selectLoraRoot": "选择 LoRA 根目录",
|
||||
@@ -904,20 +1036,20 @@
|
||||
"importAndDownload": "导入并下载",
|
||||
"downloadMissingLoras": "下载缺失的 LoRA",
|
||||
"saveRecipe": "保存配方",
|
||||
"loraCountInfo": "({existing}/{total} in library)",
|
||||
"loraCountInfo": "(库中 {existing}/{total})",
|
||||
"processingInput": "处理输入...",
|
||||
"analyzingMetadata": "分析图像元数据...",
|
||||
"downloadingLoras": "下载 LoRA...",
|
||||
"savingRecipe": "保存配方...",
|
||||
"startingDownload": "开始下载 LoRA {current}/{total}",
|
||||
"deletedFromCivitai": "从 Civitai 中删除",
|
||||
"deletedFromCivitai": "从 CivitAI 中删除",
|
||||
"inLibrary": "在库中",
|
||||
"notInLibrary": "不在库中",
|
||||
"earlyAccessRequired": "此 LoRA 需要提前访问权限才能下载。",
|
||||
"earlyAccessEnds": "提前访问权限将于 {date} 结束。",
|
||||
"earlyAccess": "提前访问",
|
||||
"verifyEarlyAccess": "在下载之前,请验证您是否已购买提前访问权限。",
|
||||
"duplicateRecipesFound": "在您的库中找到 {count} 个相同的配方。",
|
||||
"verifyEarlyAccess": "在下载之前,请确认你已购买提前访问权限。",
|
||||
"duplicateRecipesFound": "在你的库中找到 {count} 个相同的配方。",
|
||||
"duplicateRecipesDescription": "这些配方包含相同的 LoRA,权重完全相同。",
|
||||
"showDuplicates": "显示重复项",
|
||||
"hideDuplicates": "隐藏重复项",
|
||||
@@ -1033,8 +1165,8 @@
|
||||
"start": "开始导入",
|
||||
"startImport": "开始导入",
|
||||
"importing": "正在导入配方...",
|
||||
"rateLimitedSlowdown": "[TODO: Translate] Rate limited — slowing down...",
|
||||
"rateLimitedHint": "[TODO: Translate] Some items were skipped due to metadata provider rate limits. Re-run the import later to retry them.",
|
||||
"rateLimitedSlowdown": "触发速率限制 — 正在减速...",
|
||||
"rateLimitedHint": "部分条目因元数据提供方的速率限制而被跳过。稍后重新运行导入即可重试这些条目。",
|
||||
"progress": "进度",
|
||||
"total": "总计",
|
||||
"success": "成功",
|
||||
@@ -1076,7 +1208,7 @@
|
||||
"title": "Checkpoint 模型",
|
||||
"modelTypes": {
|
||||
"checkpoint": "Checkpoint",
|
||||
"diffusion_model": "Diffusion Model"
|
||||
"diffusion_model": "扩散模型"
|
||||
},
|
||||
"contextMenu": {
|
||||
"moveToOtherTypeFolder": "移动到 {otherType} 文件夹",
|
||||
@@ -1100,7 +1232,7 @@
|
||||
"collapseAllDisabled": "列表视图下不可用",
|
||||
"dragDrop": {
|
||||
"unableToResolveRoot": "无法确定移动的目标路径。",
|
||||
"moveUnsupported": "Move is not supported for this item.",
|
||||
"moveUnsupported": "此条目不支持移动。",
|
||||
"createFolderHint": "释放以创建新文件夹",
|
||||
"newFolderName": "新文件夹名称",
|
||||
"folderNameHint": "按 Enter 确认,Escape 取消",
|
||||
@@ -1238,7 +1370,7 @@
|
||||
"download": {
|
||||
"title": "从 URL 下载模型",
|
||||
"titleWithType": "从 URL 下载 {type}",
|
||||
"civitaiUrl": "Civitai URL:",
|
||||
"civitaiUrl": "CivitAI URL:",
|
||||
"placeholder": "https://civitai.com/models/...",
|
||||
"urlHint": "每行输入一个 CivitAI、CivArchive 或 Hugging Face URL。支持批量下载多个 URL。",
|
||||
"selectHfFiles": "选择从此仓库下载的文件:",
|
||||
@@ -1273,7 +1405,7 @@
|
||||
"inLibrary": "已在库中"
|
||||
},
|
||||
"errors": {
|
||||
"invalidUrl": "无效的 Civitai URL 格式",
|
||||
"invalidUrl": "无效的 CivitAI URL 格式",
|
||||
"noVersions": "此模型没有可用版本",
|
||||
"mixedSources": "无法在同一批次中混合使用 CivitAI 和 Hugging Face URL。",
|
||||
"noModelFiles": "在此仓库中未找到模型文件。"
|
||||
@@ -1352,8 +1484,8 @@
|
||||
"action": "全部删除"
|
||||
},
|
||||
"checkUpdates": {
|
||||
"title": "检查所有 {type} 的更新?",
|
||||
"message": "这会为库中的每个 {type} 检查更新,大型集合可能需要一些时间。",
|
||||
"title": "检查所有 {typePlural} 的更新?",
|
||||
"message": "这会检查库中的每个 {typePlural} 的更新,大型集合可能需要一些时间。",
|
||||
"tip": "想分批进行?切换到批量模式,选中需要的模型,然后使用“检查所选更新”。",
|
||||
"action": "检查全部"
|
||||
},
|
||||
@@ -1387,7 +1519,7 @@
|
||||
"title": "本地示例图片",
|
||||
"message": "未找到此模型的本地示例图片。可选操作:",
|
||||
"downloadOption": {
|
||||
"title": "从 Civitai 下载",
|
||||
"title": "从 CivitAI 下载",
|
||||
"description": "将远程示例保存到本地,便于离线使用和更快加载"
|
||||
},
|
||||
"importOption": {
|
||||
@@ -1414,7 +1546,7 @@
|
||||
"confirmAction": "保存并链接"
|
||||
},
|
||||
"relinkCivitai": {
|
||||
"title": "重新关联到 Civitai",
|
||||
"title": "重新关联到 CivitAI",
|
||||
"warning": "警告:",
|
||||
"warningText": "这是一个有潜在风险的操作。重新关联将:",
|
||||
"warningList": {
|
||||
@@ -1423,15 +1555,15 @@
|
||||
"unintendedConsequences": "可能有其他不可预期的后果"
|
||||
},
|
||||
"proceedText": "仅在你确定需要此操作时继续。",
|
||||
"urlLabel": "Civitai 模型 URL:",
|
||||
"urlLabel": "CivitAI 模型 URL:",
|
||||
"urlPlaceholder": "https://civitai.com/models/12345/model-name?modelVersionId=67890 或 https://civitai.red/models/12345/model-name?modelVersionId=67890",
|
||||
"helpText": {
|
||||
"title": "粘贴任意 Civitai 或 CivitArchive 模型 URL。支持格式:",
|
||||
"title": "粘贴任意 CivitAI 或 CivitArchive 模型 URL。支持格式:",
|
||||
"format1": "https://civitai.com/models/12345",
|
||||
"format2": "https://civitai.com/models/12345?modelVersionId=67890",
|
||||
"format3": "https://civitai.com/models/12345/model-name?modelVersionId=67890",
|
||||
"note": "注意:如果未提供 modelVersionId,将使用最新版本。",
|
||||
"format4": "https://civarchive.com/models/12345 (CivitArchive)"
|
||||
"format4": "https://civarchive.com/models/12345 (CivArchive)"
|
||||
},
|
||||
"confirmAction": "确认重新关联"
|
||||
},
|
||||
@@ -1441,8 +1573,8 @@
|
||||
"editFileName": "编辑文件名",
|
||||
"editBaseModel": "编辑基础模型",
|
||||
"editVersionName": "编辑版本名称",
|
||||
"viewOnCivitai": "在 Civitai 查看",
|
||||
"viewOnCivitaiText": "在 Civitai 查看",
|
||||
"viewOnCivitai": "在 CivitAI 查看",
|
||||
"viewOnCivitaiText": "在 CivitAI 查看",
|
||||
"viewOnHuggingFace": "在 Hugging Face 查看",
|
||||
"viewOnHuggingFaceText": "在 Hugging Face 查看",
|
||||
"viewCreatorProfile": "查看创作者主页",
|
||||
@@ -1474,7 +1606,7 @@
|
||||
"notesHint": "回车保存,Shift+回车换行",
|
||||
"addNotesPlaceholder": "在此添加你的备注...",
|
||||
"aboutThisVersion": "关于此版本",
|
||||
"baseModelSearchPlaceholder": "搜索基础模型…",
|
||||
"baseModelSearchPlaceholder": "搜索基础模型...",
|
||||
"baseModelSuggested": "推荐",
|
||||
"baseModelNoMatch": "没有匹配的基础模型"
|
||||
},
|
||||
@@ -1494,7 +1626,11 @@
|
||||
"clipSkip": "Clip Skip",
|
||||
"valuePlaceholder": "数值",
|
||||
"add": "添加",
|
||||
"invalidRange": "无效的范围格式。请使用 x.x-y.y"
|
||||
"invalidRange": "无效的范围格式。请使用 x.x-y.y",
|
||||
"invalidValue": "请输入有效的数值",
|
||||
"saveFailed": "保存预设参数失败",
|
||||
"added": "已添加预设参数",
|
||||
"updated": "已更新预设参数"
|
||||
},
|
||||
"triggerWords": {
|
||||
"label": "触发词",
|
||||
@@ -1505,7 +1641,7 @@
|
||||
"addPlaceholder": "输入或点击下方建议添加",
|
||||
"editWord": "编辑触发词",
|
||||
"editPlaceholder": "编辑触发词",
|
||||
"copyWord": "复制触发词",
|
||||
"copyOrEditWord": "单击复制,双击编辑",
|
||||
"deleteWord": "删除触发词",
|
||||
"suggestions": {
|
||||
"noSuggestions": "暂无建议",
|
||||
@@ -1543,10 +1679,10 @@
|
||||
"noNext": "没有下一个模型"
|
||||
},
|
||||
"license": {
|
||||
"noImageSell": "No selling generated content",
|
||||
"noRentCivit": "No Civitai generation",
|
||||
"noRent": "No generation services",
|
||||
"noSell": "No selling models",
|
||||
"noImageSell": "禁止出售生成的图片",
|
||||
"noRentCivit": "禁止在 CivitAI 上生成",
|
||||
"noRent": "禁止生成服务",
|
||||
"noSell": "禁止出售模型",
|
||||
"creditRequired": "需要创作者署名",
|
||||
"noDerivatives": "禁止分享合并作品",
|
||||
"noReLicense": "需要相同权限",
|
||||
@@ -1565,8 +1701,8 @@
|
||||
"showCount": "显示示例({count})",
|
||||
"hideExamples": "隐藏示例",
|
||||
"addExamples": "添加示例",
|
||||
"previousExample": "上一个示例",
|
||||
"nextExample": "下一个示例",
|
||||
"previousExample": "上一个示例([)",
|
||||
"nextExample": "下一个示例(])",
|
||||
"noExamples": "暂无示例图片",
|
||||
"addMoreExamples": "添加更多示例",
|
||||
"dragDrop": "将图片或视频拖放到此处",
|
||||
@@ -1609,49 +1745,49 @@
|
||||
"newer": "较新的版本",
|
||||
"newerTooltip": "此版本比你本地的最新版本更新",
|
||||
"earlyAccess": "抢先体验",
|
||||
"earlyAccessTooltip": "此版本当前需要 Civitai 抢先体验权限",
|
||||
"earlyAccessTooltip": "此版本当前需要 CivitAI 抢先体验权限",
|
||||
"paid": "付费",
|
||||
"paidTooltip": "此版本需要付费后才能下载",
|
||||
"ignored": "已忽略",
|
||||
"ignoredTooltip": "此版本已关闭更新通知",
|
||||
"onSiteOnly": "仅站内生成",
|
||||
"onSiteOnlyTooltip": "此版本仅在 Civitai 站内可用,无法下载"
|
||||
"onSiteOnlyTooltip": "此版本仅在 CivitAI 站内可用,无法下载"
|
||||
},
|
||||
"actions": {
|
||||
"download": "下载",
|
||||
"downloadTooltip": "下载此版本",
|
||||
"downloadChooseFilesTooltip": "选择要下载的文件",
|
||||
"downloadEarlyAccessTooltip": "从 Civitai 下载此抢先体验版本",
|
||||
"downloadPaidTooltip": "从 Civitai 下载此付费版本",
|
||||
"downloadNotAllowedTooltip": "此版本仅在 Civitai 站内可用,无法下载",
|
||||
"downloadEarlyAccessTooltip": "从 CivitAI 下载此抢先体验版本",
|
||||
"downloadPaidTooltip": "从 CivitAI 下载此付费版本",
|
||||
"downloadNotAllowedTooltip": "此版本仅在 CivitAI 站内可用,无法下载",
|
||||
"delete": "删除",
|
||||
"deleteTooltip": "删除此本地版本",
|
||||
"ignore": "忽略",
|
||||
"unignore": "取消忽略",
|
||||
"ignoreTooltip": "忽略此版本的更新通知",
|
||||
"unignoreTooltip": "恢复此版本的更新通知",
|
||||
"viewVersionOnCivitai": "在 Civitai 上查看版本",
|
||||
"viewVersionOnCivitai": "在 CivitAI 上查看版本",
|
||||
"earlyAccessTooltip": "需要购买抢先体验",
|
||||
"resumeModelUpdates": "继续跟踪该模型的更新",
|
||||
"ignoreModelUpdates": "忽略该模型的更新",
|
||||
"viewLocalVersions": "查看所有本地版本",
|
||||
"viewLocalTooltip": "敬请期待"
|
||||
"viewLocalTooltip": "在主页面上显示该模型的所有本地版本"
|
||||
},
|
||||
"filters": {
|
||||
"label": "基础筛选",
|
||||
"state": {
|
||||
"showAll": "全部版本",
|
||||
"showSameBase": "相同基模型"
|
||||
"showSameBase": "相同基础模型"
|
||||
},
|
||||
"tooltip": {
|
||||
"showAllVersions": "切换为显示所有版本",
|
||||
"showSameBaseVersions": "仅显示与当前基模型匹配的版本"
|
||||
"showSameBaseVersions": "仅显示与当前基础模型匹配的版本"
|
||||
},
|
||||
"empty": "没有与当前基模型筛选匹配的版本。"
|
||||
"empty": "没有与当前基础模型筛选匹配的版本。"
|
||||
},
|
||||
"empty": "该模型还没有版本历史。",
|
||||
"error": "加载版本失败。",
|
||||
"missingModelId": "该模型缺少 Civitai 模型 ID。",
|
||||
"missingModelId": "该模型缺少 CivitAI 模型 ID。",
|
||||
"hfGroupInfo": "这是一个 HuggingFace 模型组。打开库页面即可在网格中查看所有版本。",
|
||||
"confirm": {
|
||||
"delete": "从库中删除此版本?"
|
||||
@@ -1735,14 +1871,14 @@
|
||||
"tips": {
|
||||
"title": "技巧与提示",
|
||||
"civitai": {
|
||||
"title": "Civitai 集成",
|
||||
"description": "连接你的 Civitai 账号:访问头像 → 设置 → API 密钥 → 添加密钥,然后粘贴到 LoRA 管理器设置中。",
|
||||
"alt": "Civitai API 设置"
|
||||
"title": "CivitAI 集成",
|
||||
"description": "连接你的 CivitAI 账号:访问头像 → 设置 → API 密钥 → 添加密钥,然后粘贴到 LoRA 管理器设置中。",
|
||||
"alt": "CivitAI API 设置"
|
||||
},
|
||||
"download": {
|
||||
"title": "便捷下载",
|
||||
"description": "使用 Civitai URL 快速下载和安装新模型。",
|
||||
"alt": "Civitai 下载"
|
||||
"description": "使用 CivitAI URL 快速下载和安装新模型。",
|
||||
"alt": "CivitAI 下载"
|
||||
},
|
||||
"recipes": {
|
||||
"title": "保存配方",
|
||||
@@ -1820,7 +1956,7 @@
|
||||
"copiedUri": "链接已复制到剪贴板:{{uri}}",
|
||||
"uriClipboardFallback": "链接:{{uri}}",
|
||||
"setupRequired": "示例图片存储",
|
||||
"setupDescription": "要添加自定义示例图片,您需要先设置下载位置。",
|
||||
"setupDescription": "要添加自定义示例图片,你需要先设置下载位置。",
|
||||
"setupUsage": "此路径用于存储下载的示例图片和自定义图片。",
|
||||
"openSettings": "打开设置"
|
||||
}
|
||||
@@ -1830,10 +1966,52 @@
|
||||
"tabs": {
|
||||
"gettingStarted": "新手入门",
|
||||
"updateVlogs": "更新日志",
|
||||
"documentation": "文档"
|
||||
"documentation": "文档",
|
||||
"shortcuts": "快捷键"
|
||||
},
|
||||
"gettingStarted": {
|
||||
"title": "LoRA 管理器新手入门"
|
||||
"title": "LoRA 管理器新手入门",
|
||||
"replayTutorial": "重播教程"
|
||||
},
|
||||
"shortcuts": {
|
||||
"title": "键盘与鼠标快捷键",
|
||||
"groups": {
|
||||
"general": "通用",
|
||||
"actions": "操作",
|
||||
"selection": "选择与批量模式",
|
||||
"navigation": "导航",
|
||||
"modelModal": "模型 / 配方弹窗",
|
||||
"mediaViewer": "媒体查看器 / 示例展示"
|
||||
},
|
||||
"keys": {
|
||||
"click": "单击",
|
||||
"drag": "拖动",
|
||||
"rightClick": "右键点击",
|
||||
"letter": "字母",
|
||||
"swipe": "滑动"
|
||||
},
|
||||
"entries": {
|
||||
"focusSearch": "聚焦搜索框",
|
||||
"closeModal": "关闭弹窗 / 面板",
|
||||
"openShortcuts": "打开本快捷键面板",
|
||||
"refresh": "刷新模型列表",
|
||||
"fetchMetadata": "从 CivitAI 获取元数据(仅模型页面)",
|
||||
"downloadModel": "下载模型(仅模型页面)",
|
||||
"toggleBulkMode": "切换批量模式",
|
||||
"selectAll": "全选所有可见模型",
|
||||
"rangeSelect": "范围选择",
|
||||
"marqueeSelect": "框选卡片(在网格空白区域)",
|
||||
"exitBulkMode": "退出批量模式",
|
||||
"bulkActions": "在已选中的卡片上:批量操作菜单",
|
||||
"globalActions": "在页面空白区域:全局操作菜单(检查更新、管理已排除的模型)",
|
||||
"scrollPages": "滚动页面",
|
||||
"jumpAlphabet": "字母索引栏跳转",
|
||||
"prevNext": "上一个 / 下一个模型",
|
||||
"deleteEntry": "删除",
|
||||
"cycleMedia": "切换媒体(在示例展示中按 [ / ])",
|
||||
"swipeTouch": "在触屏设备上切换媒体",
|
||||
"closeViewer": "关闭查看器"
|
||||
}
|
||||
},
|
||||
"updateVlogs": {
|
||||
"title": "最新更新",
|
||||
@@ -1850,7 +2028,8 @@
|
||||
"settings": "设置与配置",
|
||||
"extensions": "扩展",
|
||||
"newBadge": "新"
|
||||
}
|
||||
},
|
||||
"newContentBadge": "新"
|
||||
},
|
||||
"update": {
|
||||
"title": "检查更新",
|
||||
@@ -1926,7 +2105,7 @@
|
||||
"submitGithubIssue": "提交 GitHub 问题",
|
||||
"joinDiscord": "加入 Discord",
|
||||
"youtubeChannel": "YouTube 频道",
|
||||
"civitaiProfile": "Civitai 个人资料",
|
||||
"civitaiProfile": "CivitAI 个人资料",
|
||||
"supportKofi": "支持 Ko-fi",
|
||||
"supportPatreon": "支持 Patreon"
|
||||
},
|
||||
@@ -2009,14 +2188,27 @@
|
||||
"preparingForDownloadFailed": "准备下载 LoRA 时出错",
|
||||
"enterLoraName": "请输入 LoRA 名称或语法",
|
||||
"reconnectedSuccessfully": "LoRA 重新连接成功",
|
||||
"reconnectBaseModelMismatch": "已重新关联,但基础模型不同(配方:{recipe},LoRA:{lora})——两者架构兼容",
|
||||
"reconnectFailed": "LoRA 重新连接出错:{message}",
|
||||
"loraRestored": "LoRA 已恢复为重新关联前的关联",
|
||||
"loraRestoreFailed": "LoRA 恢复出错:{message}",
|
||||
"noPromptToSend": "没有可发送的提示词",
|
||||
"cannotSend": "无法发送配方:缺少配方 ID",
|
||||
"sendFailed": "发送配方到工作流失败",
|
||||
"sendError": "发送配方到工作流出错",
|
||||
"missingCheckpointPath": "缺少检查点路径",
|
||||
"missingCheckpointInfo": "缺少检查点信息",
|
||||
"downloadCheckpointFailed": "下载检查点失败:{message}",
|
||||
"missingCheckpointPath": "缺少Checkpoint路径",
|
||||
"missingCheckpointInfo": "缺少Checkpoint信息",
|
||||
"downloadCheckpointFailed": "下载Checkpoint失败:{message}",
|
||||
"enterCheckpointName": "请输入 Checkpoint 名称",
|
||||
"checkpointReconnectedSuccessfully": "Checkpoint 重新连接成功",
|
||||
"reconnectCheckpointBaseModelMismatch": "已重新关联,但基础模型不同(配方:{recipe},Checkpoint:{checkpoint})——两者架构兼容",
|
||||
"checkpointReconnectFailed": "Checkpoint 重新连接出错:{message}",
|
||||
"checkpointRestored": "Checkpoint 已恢复为重新关联前的关联",
|
||||
"checkpointRestoreFailed": "Checkpoint 恢复出错:{message}",
|
||||
"checkpointDownloadUnavailable": "缺少 CivitAI 标识,无法下载此 Checkpoint - 请尝试使用本地 Checkpoint 重新关联",
|
||||
"missingLoraDownloadInfo": "缺少此 LoRA 的下载信息",
|
||||
"hashNotFoundOnCivitai": "此 LoRA 哈希无法在 CivitAI 上解析——模型可能已更新或哈希无效",
|
||||
"downloadLoraFailed": "下载 LoRA 失败:{message}",
|
||||
"cannotDelete": "无法删除配方:缺少配方 ID",
|
||||
"deleteConfirmationError": "显示删除确认出错",
|
||||
"deletedSuccessfully": "配方删除成功",
|
||||
@@ -2040,19 +2232,19 @@
|
||||
"batchImportCancelFailed": "取消批量导入失败:{message}",
|
||||
"batchImportNoUrls": "请输入至少一个 URL 或文件路径",
|
||||
"batchImportNoDirectory": "请输入目录路径",
|
||||
"batchImportRateLimited": "[TODO: Translate] Metadata provider rate limit reached — requests are being slowed and some items may be skipped. You can re-run the import later.",
|
||||
"batchImportRateLimited": "已达到元数据提供方的速率限制 — 请求正在放缓,部分条目可能被跳过。你可以稍后重新运行导入。",
|
||||
"batchImportBrowseFailed": "浏览目录失败:{message}",
|
||||
"batchImportDirectorySelected": "已选择目录:{path}",
|
||||
"noRecipesSelected": "未选择任何配方",
|
||||
"repairBulkComplete": "修复完成:{repaired} 个已修复,{skipped} 个已跳过(共 {total} 个)",
|
||||
"repairBulkSkipped": "所选 {total} 个配方无需修复",
|
||||
"repairBulkFailed": "修复所选配方失败:{message}",
|
||||
"rematchComplete": "已匹配 {entries} 个条目,涉及 {recipes} 个食谱",
|
||||
"rematchCompleteErrors": "已匹配 {entries} 个条目,涉及 {recipes} 个食谱,{failures} 个失败",
|
||||
"rematchAllFailed": "{failures}/{total} 个所选食谱重新匹配失败",
|
||||
"rematchUnmatched": "在 {recipes} 个食谱中未找到 {entries} 个条目的本地匹配",
|
||||
"rematchSkipped": "{total} 个所选食谱均无需重新匹配",
|
||||
"rematchFailed": "重新匹配所选食谱失败:{message}",
|
||||
"rematchComplete": "已匹配 {entries} 个条目,涉及 {recipes} 个配方",
|
||||
"rematchCompleteErrors": "已匹配 {entries} 个条目,涉及 {recipes} 个配方,{failures} 个失败",
|
||||
"rematchAllFailed": "{failures}/{total} 个所选配方重新匹配失败",
|
||||
"rematchUnmatched": "在 {recipes} 个配方中未找到 {entries} 个条目的本地匹配",
|
||||
"rematchSkipped": "{total} 个所选配方均无需重新匹配",
|
||||
"rematchFailed": "重新匹配所选配方失败:{message}",
|
||||
"reimporting": "正在从源重新导入配方...",
|
||||
"reimportSuccess": "配方已从源重新导入成功",
|
||||
"reimportBulkComplete": "重新导入完成:{completed} 个已导入,{failed} 个失败(共 {total} 个)",
|
||||
@@ -2098,8 +2290,8 @@
|
||||
"bulkUpdatesChecking": "正在检查所选 {type} 的更新...",
|
||||
"bulkUpdatesSuccess": "{count} 个所选 {type} 有可用更新",
|
||||
"bulkUpdatesNone": "所选 {type} 未发现更新",
|
||||
"bulkUpdatesMissing": "所选 {type} 未关联 Civitai 更新",
|
||||
"bulkUpdatesPartialMissing": "已跳过 {missing} 个未关联 Civitai 的所选 {type}",
|
||||
"bulkUpdatesMissing": "所选 {type} 未关联 CivitAI 更新",
|
||||
"bulkUpdatesPartialMissing": "已跳过 {missing} 个未关联 CivitAI 的所选 {type}",
|
||||
"bulkUpdatesFailed": "检查所选 {type} 的更新失败:{message}",
|
||||
"invalidCharactersRemoved": "文件名中的无效字符已移除",
|
||||
"filenameCannotBeEmpty": "文件名不能为空",
|
||||
@@ -2128,7 +2320,7 @@
|
||||
"checkpointRootsFailed": "加载 Checkpoint 根目录失败:{message}",
|
||||
"unetRootsFailed": "加载 Diffusion Model 根目录失败:{message}",
|
||||
"embeddingRootsFailed": "加载 Embedding 根目录失败:{message}",
|
||||
"mappingsUpdated": "基础模型路径映射已更新({count} 条映射{plural})",
|
||||
"mappingsUpdated": "基础模型路径映射已更新({count} 条映射)",
|
||||
"mappingsCleared": "基础模型路径映射已清除",
|
||||
"mappingSaveFailed": "保存基础模型映射失败:{message}",
|
||||
"downloadTemplatesUpdated": "下载路径模板已更新",
|
||||
@@ -2139,8 +2331,8 @@
|
||||
"compactModeToggled": "紧凑模式 {state}",
|
||||
"settingSaveFailed": "保存设置失败:{message}",
|
||||
"displayDensitySet": "显示密度已设置为 {density}",
|
||||
"libraryLoadFailed": "Failed to load libraries: {message}",
|
||||
"libraryActivateFailed": "Failed to activate library: {message}",
|
||||
"libraryLoadFailed": "加载模型库失败:{message}",
|
||||
"libraryActivateFailed": "激活模型库失败:{message}",
|
||||
"languageChangeFailed": "切换语言失败:{message}",
|
||||
"cacheCleared": "缓存文件已成功清除。下次操作将重建缓存。",
|
||||
"cacheClearFailed": "清除缓存失败:{error}",
|
||||
@@ -2225,7 +2417,7 @@
|
||||
"contextMenu": {
|
||||
"contentRatingSet": "内容评级已设置为 {level}",
|
||||
"contentRatingFailed": "设置内容评级失败:{message}",
|
||||
"relinkSuccess": "模型已成功重新关联到 Civitai",
|
||||
"relinkSuccess": "模型已成功重新关联到 CivitAI",
|
||||
"relinkFailed": "错误:{message}",
|
||||
"linkHfSuccess": "模型已成功链接到 HuggingFace",
|
||||
"linkHfFailed": "错误:{message}",
|
||||
@@ -2289,7 +2481,7 @@
|
||||
"bulkMoveSuccess": "成功移动 {successCount} 个 {type}",
|
||||
"exampleImagesDownloadSuccess": "示例图片下载成功!",
|
||||
"exampleImagesDownloadFailed": "示例图片下载失败:{message}",
|
||||
"moveFailed": "Failed to move item: {message}",
|
||||
"moveFailed": "移动条目失败:{message}",
|
||||
"copiedToClipboard": "已复制到剪贴板",
|
||||
"downloadStarted": "下载已开始"
|
||||
},
|
||||
@@ -2319,7 +2511,7 @@
|
||||
},
|
||||
"issues": {
|
||||
"civitai_api_key": {
|
||||
"title": "Civitai API 密钥"
|
||||
"title": "CivitAI API 密钥"
|
||||
},
|
||||
"cache_health": {
|
||||
"title": "模型缓存健康状态"
|
||||
|
||||
+310
-118
@@ -50,6 +50,27 @@
|
||||
"mb": "MB",
|
||||
"gb": "GB",
|
||||
"tb": "TB"
|
||||
},
|
||||
"scanProgress": {
|
||||
"refreshing": "正在重新整理 {type}...",
|
||||
"fullRebuilding": "正在完整重建 {type}...",
|
||||
"actionRefresh": "重新整理",
|
||||
"actionFullRebuild": "完整重建",
|
||||
"actionRefreshLower": "重新整理",
|
||||
"actionRebuildLower": "重建",
|
||||
"stages": {
|
||||
"scan_folders": "正在掃描資料夾...",
|
||||
"count_models": "找到 {total} 個檔案",
|
||||
"process_models": "正在處理模型",
|
||||
"reconcile_scan": "正在檢查變更...",
|
||||
"process_new": "正在處理新模型",
|
||||
"finalizing": "正在收尾..."
|
||||
},
|
||||
"eta": {
|
||||
"lessThanMinute": "剩餘時間不到一分鐘",
|
||||
"minutes": "剩餘約 {minutes} 分鐘",
|
||||
"hours": "剩餘約 {hours} 小時 {minutes} 分鐘"
|
||||
}
|
||||
}
|
||||
},
|
||||
"onboarding": {
|
||||
@@ -67,15 +88,15 @@
|
||||
"steps": {
|
||||
"fetch": {
|
||||
"title": "取得模型 metadata",
|
||||
"content": "點擊 <strong>取得</strong> 按鈕,從 Civitai 下載模型 metadata 與預覽圖片。"
|
||||
"content": "點擊 <strong>取得</strong> 按鈕,從 CivitAI 下載模型 metadata 與預覽圖片。"
|
||||
},
|
||||
"download": {
|
||||
"title": "下載新模型",
|
||||
"content": "使用 <strong>下載</strong> 按鈕,直接從 Civitai 網址下載模型。"
|
||||
"content": "使用 <strong>下載</strong> 按鈕,直接從 CivitAI 網址下載模型。"
|
||||
},
|
||||
"bulk": {
|
||||
"title": "批次操作",
|
||||
"content": "點擊此按鈕或按下 <span class=\"onboarding-shortcut\">B</span> 進入批次模式。可選取多個模型並執行批量操作。使用 <span class=\"onboarding-shortcut\">Ctrl+A</span> 選取所有可見模型。"
|
||||
"content": "點擊此按鈕或按下 <span class=\"onboarding-shortcut\">B</span> 進入批量模式,選取多個模型並執行批量操作。<br>• <span class=\"onboarding-shortcut\">Ctrl/Cmd+A</span> 選取所有可見模型,<span class=\"onboarding-shortcut\">Shift+Click</span> 選取一段範圍。<br>• <span class=\"onboarding-shortcut\">Esc</span> 或點擊空白處離開批量模式。"
|
||||
},
|
||||
"searchOptions": {
|
||||
"title": "搜尋選項",
|
||||
@@ -95,7 +116,19 @@
|
||||
},
|
||||
"contextMenu": {
|
||||
"title": "右鍵選單",
|
||||
"content": "<strong>右鍵點擊</strong>任一模型卡片可開啟更多操作選單。"
|
||||
"content": "<strong>右鍵點擊</strong>任一模型卡片,可開啟包含移動、刪除或編輯中繼資料等卡片操作的右鍵選單。"
|
||||
},
|
||||
"marqueeSelect": {
|
||||
"title": "拖曳框選",
|
||||
"content": "在網格空白處按住<strong>滑鼠左鍵</strong>並拖曳,畫出框選範圍,一次選取多張卡片。"
|
||||
},
|
||||
"dragToSidebar": {
|
||||
"title": "拖曳整理",
|
||||
"content": "將模型卡片拖曳到側邊欄的資料夾上,即可將檔案移動到該處。在批量模式下選取多張卡片也可一起拖曳。"
|
||||
},
|
||||
"contextMenus": {
|
||||
"title": "更多右鍵選單",
|
||||
"content": "在批量模式下,<strong>右鍵點擊已選取的卡片</strong>可開啟批量操作選單。<strong>右鍵點擊頁面空白處</strong>可開啟全域操作選單,例如檢查更新與管理已排除的模型。"
|
||||
}
|
||||
}
|
||||
},
|
||||
@@ -103,8 +136,8 @@
|
||||
"actions": {
|
||||
"addToFavorites": "加入收藏",
|
||||
"removeFromFavorites": "移除收藏",
|
||||
"viewOnCivitai": "在 Civitai 查看",
|
||||
"notAvailableFromCivitai": "Civitai 不提供",
|
||||
"viewOnCivitai": "在 CivitAI 查看",
|
||||
"notAvailableFromCivitai": "CivitAI 不提供",
|
||||
"viewOnHuggingFace": "在 Hugging Face 查看",
|
||||
"sendToWorkflow": "傳送到 ComfyUI(點擊:附加,Shift+點擊:取代)",
|
||||
"copyLoRASyntax": "複製 LoRA 語法",
|
||||
@@ -113,7 +146,7 @@
|
||||
"show": "顯示",
|
||||
"openExampleImages": "開啟範例圖片資料夾",
|
||||
"replacePreview": "更換預覽圖",
|
||||
"copyCheckpointName": "複製檢查點名稱",
|
||||
"copyCheckpointName": "複製 Checkpoint 名稱",
|
||||
"copyEmbeddingName": "複製嵌入名稱",
|
||||
"embeddingNameCopied": "已複製 Embedding 語法",
|
||||
"sendCheckpointToWorkflow": "傳送到 ComfyUI",
|
||||
@@ -137,7 +170,7 @@
|
||||
"exampleImages": {
|
||||
"checkError": "檢查範例圖片時發生錯誤",
|
||||
"missingHash": "缺少模型雜湊資訊。",
|
||||
"noRemoteImagesAvailable": "此模型在 Civitai 上無遠端範例圖片"
|
||||
"noRemoteImagesAvailable": "此模型在 CivitAI 上無遠端範例圖片"
|
||||
},
|
||||
"badges": {
|
||||
"update": "更新",
|
||||
@@ -187,14 +220,14 @@
|
||||
"error": "配方修復失敗:{message}"
|
||||
},
|
||||
"rematchRecipes": {
|
||||
"label": "將食譜重新匹配到本地模型",
|
||||
"loading": "正在將食譜重新匹配到本地模型...",
|
||||
"success": "已匹配 {entries} 個條目,涉及 {recipes} 個食譜",
|
||||
"successErrors": "已匹配 {entries} 個條目,涉及 {recipes} 個食譜,{failures} 個失敗",
|
||||
"allFailed": "{failures}/{total} 個食譜重新匹配失敗",
|
||||
"noMatch": "在 {recipes} 個食譜中找不到 {entries} 個條目的本地匹配",
|
||||
"cancelled": "已取消重新匹配。{recipes} 個食譜已更新({entries} 個條目)。",
|
||||
"error": "食譜重新匹配失敗:{message}"
|
||||
"label": "將配方重新匹配到本地模型",
|
||||
"loading": "正在將配方重新匹配到本地模型...",
|
||||
"success": "已匹配 {entries} 個條目,涉及 {recipes} 個配方",
|
||||
"successErrors": "已匹配 {entries} 個條目,涉及 {recipes} 個配方,{failures} 個失敗",
|
||||
"allFailed": "{failures}/{total} 個配方重新匹配失敗",
|
||||
"noMatch": "在 {recipes} 個配方中找不到 {entries} 個條目的本地匹配",
|
||||
"cancelled": "已取消重新匹配。{recipes} 個配方已更新({entries} 個條目)。",
|
||||
"error": "配方重新匹配失敗:{message}"
|
||||
},
|
||||
"manageExcludedModels": {
|
||||
"label": "管理已排除的模型"
|
||||
@@ -259,7 +292,7 @@
|
||||
"clearAll": "清除所有篩選",
|
||||
"any": "任一",
|
||||
"all": "全部",
|
||||
"tagLogicAny": "符合任一票籤 (或)",
|
||||
"tagLogicAny": "符合任一標籤 (或)",
|
||||
"tagLogicAll": "符合所有標籤 (與)",
|
||||
"loraAvailability": "LoRA 可用性",
|
||||
"availabilityReady": "可直接使用",
|
||||
@@ -290,15 +323,15 @@
|
||||
}
|
||||
},
|
||||
"settings": {
|
||||
"civitaiApiKey": "Civitai API 金鑰",
|
||||
"civitaiApiKeyPlaceholder": "請輸入您的 Civitai API 金鑰",
|
||||
"civitaiApiKeyHelp": "用於從 Civitai 下載模型時的身份驗證",
|
||||
"civitaiApiKey": "CivitAI API 金鑰",
|
||||
"civitaiApiKeyPlaceholder": "請輸入您的 CivitAI API 金鑰",
|
||||
"civitaiApiKeyHelp": "用於從 CivitAI 下載模型時的身份驗證",
|
||||
"civitaiApiKeyConfigured": "已設定",
|
||||
"civitaiApiKeyNotConfigured": "未設定",
|
||||
"civitaiApiKeySet": "設定",
|
||||
"civitaiHost": {
|
||||
"label": "Civitai 站點",
|
||||
"help": "選擇使用「在 Civitai 中查看」時預設開啟的 Civitai 站點。",
|
||||
"label": "CivitAI 站點",
|
||||
"help": "選擇使用「在 CivitAI 中查看」時預設開啟的 CivitAI 站點。",
|
||||
"options": {
|
||||
"com": "civitai.com(僅 SFW)",
|
||||
"red": "civitai.red(無限制)"
|
||||
@@ -319,8 +352,8 @@
|
||||
},
|
||||
"aria2HelpLink": "了解如何設定 aria2 下載後端",
|
||||
"civitaiHostBanner": {
|
||||
"title": "已提供 Civitai 站點偏好設定",
|
||||
"content": "Civitai 現在使用 civitai.com 提供 SFW 內容,使用 civitai.red 提供無限制內容。你可以在設定中變更預設開啟的站點。",
|
||||
"title": "已提供 CivitAI 站點偏好設定",
|
||||
"content": "CivitAI 現在使用 civitai.com 提供 SFW 內容,使用 civitai.red 提供無限制內容。您可以在設定中變更預設開啟的站點。",
|
||||
"openSettings": "開啟設定"
|
||||
},
|
||||
"openSettingsFileLocation": {
|
||||
@@ -407,7 +440,7 @@
|
||||
"retentionHelp": "在刪除舊快照之前,要保留多少自動快照。",
|
||||
"management": "備份管理",
|
||||
"managementHelp": "匯出目前的使用者狀態,或從備份封存中還原。",
|
||||
"scopeHelp": "備份你的設定、下載歷史與模型更新狀態。不包含模型檔案或可重建的快取。",
|
||||
"scopeHelp": "備份您的設定、下載歷史與模型更新狀態。不包含模型檔案或可重建的快取。",
|
||||
"locationSummary": "目前備份位置",
|
||||
"openFolderButton": "開啟備份資料夾",
|
||||
"openFolderSuccess": "已開啟備份資料夾",
|
||||
@@ -428,7 +461,7 @@
|
||||
},
|
||||
"downloadSkipBaseModels": {
|
||||
"label": "跳過這些基礎模型的下載",
|
||||
"help": "適用於所有下載流程。這裡只能選擇受支援的基礎模型。",
|
||||
"help": "啟用後,使用所選基礎模型的版本將被略過。",
|
||||
"searchPlaceholder": "篩選基礎模型...",
|
||||
"empty": "沒有符合目前搜尋條件的基礎模型。",
|
||||
"summary": {
|
||||
@@ -450,7 +483,7 @@
|
||||
},
|
||||
"layoutSettings": {
|
||||
"groupByModel": "按模型分組",
|
||||
"groupByModelHelp": "啟用後,每個 Civitai 模型僅顯示最新版本的單張卡片,舊版本將被隱藏。",
|
||||
"groupByModelHelp": "啟用後,每個 CivitAI 模型僅顯示最新版本的單張卡片,舊版本將被隱藏。",
|
||||
"displayDensity": "顯示密度",
|
||||
"displayDensityOptions": {
|
||||
"default": "預設",
|
||||
@@ -517,7 +550,7 @@
|
||||
"extraFolderPaths": {
|
||||
"title": "額外資料夾路徑",
|
||||
"description": "LoRA Manager 專屬的額外模型根目錄。從 ComfyUI 標準資料夾之外的位置載入模型,特別適合管理大型模型庫,避免影響 ComfyUI 效能。",
|
||||
"restartRequired": "Requires restart to take effect",
|
||||
"restartRequired": "需要重新啟動才能生效",
|
||||
"modelTypes": {
|
||||
"lora": "LoRA 路徑",
|
||||
"checkpoint": "Checkpoint 路徑",
|
||||
@@ -555,7 +588,7 @@
|
||||
},
|
||||
"downloadPathTemplates": {
|
||||
"title": "下載路徑範本",
|
||||
"help": "設定從 Civitai 下載時不同模型類型的資料夾結構。",
|
||||
"help": "設定從 CivitAI 下載時不同模型類型的資料夾結構。",
|
||||
"availablePlaceholders": "可用佔位符:",
|
||||
"templateOptions": {
|
||||
"flatStructure": "扁平結構",
|
||||
@@ -592,7 +625,7 @@
|
||||
"exampleImages": {
|
||||
"downloadLocation": "下載位置",
|
||||
"downloadLocationPlaceholder": "輸入範例圖片的資料夾路徑",
|
||||
"downloadLocationHelp": "輸入從 Civitai 下載範例圖片要儲存的資料夾路徑",
|
||||
"downloadLocationHelp": "輸入從 CivitAI 下載範例圖片要儲存的資料夾路徑",
|
||||
"autoDownload": "自動下載範例圖片",
|
||||
"autoDownloadHelp": "自動為沒有範例圖片的模型下載範例圖片(需設定下載位置)",
|
||||
"openMode": "開啟範例圖片動作",
|
||||
@@ -625,7 +658,7 @@
|
||||
},
|
||||
"hideEarlyAccessUpdates": {
|
||||
"label": "隱藏搶先體驗更新",
|
||||
"help": "搶先體驗更新"
|
||||
"help": "啟用後,只有搶先體驗更新的模型將不顯示「可更新」徽章。"
|
||||
},
|
||||
"hidePaidUpdates": {
|
||||
"label": "隱藏付費更新",
|
||||
@@ -647,7 +680,7 @@
|
||||
},
|
||||
"metadataArchive": {
|
||||
"enableArchiveDb": "啟用中繼資料封存資料庫",
|
||||
"enableArchiveDbHelp": "使用本機資料庫以存取已從 Civitai 刪除模型的中繼資料。",
|
||||
"enableArchiveDbHelp": "使用本機資料庫以存取已從 CivitAI 刪除模型的中繼資料。",
|
||||
"status": "狀態",
|
||||
"statusAvailable": "可用",
|
||||
"statusUnavailable": "不可用",
|
||||
@@ -750,7 +783,7 @@
|
||||
"fullTooltip": "從中繼資料檔重新載入所有模型資訊;適用於清單過時或手動編輯後。"
|
||||
},
|
||||
"fetch": {
|
||||
"title": "從 Civitai 取得 metadata",
|
||||
"title": "從 CivitAI 取得 metadata",
|
||||
"action": "取得"
|
||||
},
|
||||
"download": {
|
||||
@@ -825,10 +858,10 @@
|
||||
"enrichHfAgent": "AI HF 中繼資料增強"
|
||||
},
|
||||
"contextMenu": {
|
||||
"refreshMetadata": "刷新 Civitai 資料",
|
||||
"refreshMetadata": "刷新 CivitAI 資料",
|
||||
"checkUpdates": "檢查更新",
|
||||
"linkModel": "連結模型",
|
||||
"linkCivitai": "連結到 Civitai",
|
||||
"linkCivitai": "連結到 CivitAI",
|
||||
"linkHuggingFace": "連結到 HuggingFace",
|
||||
"copySyntax": "複製 LoRA 語法",
|
||||
"copyFilename": "複製模型檔名",
|
||||
@@ -860,6 +893,7 @@
|
||||
"actions": {
|
||||
"sendCheckpoint": "傳送到 ComfyUI",
|
||||
"sendRecipe": "傳送到 ComfyUI",
|
||||
"copyRecipeSyntax": "複製配方語法",
|
||||
"deleteRecipeWithShortcut": "刪除配方(Del)"
|
||||
},
|
||||
"navigation": {
|
||||
@@ -867,12 +901,110 @@
|
||||
"previousWithShortcut": "上一個配方(←)",
|
||||
"nextWithShortcut": "下一個配方(→)"
|
||||
},
|
||||
"modal": {
|
||||
"metadata": {
|
||||
"id": "ID"
|
||||
},
|
||||
"actions": {
|
||||
"openFileLocation": "開啟檔案位置",
|
||||
"copyId": "複製配方 ID"
|
||||
},
|
||||
"openFileLocation": {
|
||||
"success": "檔案位置已成功開啟",
|
||||
"failed": "開啟檔案位置失敗",
|
||||
"copied": "路徑已複製到剪貼簿:{{path}}",
|
||||
"clipboardFallback": "路徑:{{path}}"
|
||||
}
|
||||
},
|
||||
"workflow": {
|
||||
"sendWorkflow": "傳送工作流到 ComfyUI",
|
||||
"sent": "工作流已傳送到 ComfyUI",
|
||||
"sendFailed": "傳送工作流到 ComfyUI 失敗",
|
||||
"noWorkflow": "此配方中未找到內嵌工作流"
|
||||
},
|
||||
"status": {
|
||||
"ready": "可直接使用",
|
||||
"missingCount": "缺少 {count} 個",
|
||||
"deletedCount": "已刪除 {count} 個",
|
||||
"downloadMissing": "下載 {count} 個缺少的 LoRA",
|
||||
"downloadMissingTooltip": "點擊下載缺少的 LoRA"
|
||||
},
|
||||
"loraStatus": {
|
||||
"none": "此配方不含 LoRA",
|
||||
"allAvailable": "所有 LoRA 皆已就緒 - 可直接使用",
|
||||
"missing": "{total} 個 LoRA 中缺少 {missing} 個",
|
||||
"missingAndUnavailable": "{total} 個 LoRA 中缺少 {missing} 個,{unavailable} 個不可用(已從來源刪除或雜湊無法解析)",
|
||||
"partial": "{total} 個 LoRA 中 {unavailable} 個不可用(已從來源刪除或雜湊無法解析)- 使用配方時將被略過",
|
||||
"noneUsable": "沒有可用的 LoRA - {total} 個中 {unavailable} 個已從來源刪除或雜湊無法解析"
|
||||
},
|
||||
"resources": {
|
||||
"inLibrary": "已在庫存",
|
||||
"notInLibrary": "不在庫存",
|
||||
"deleted": "已刪除",
|
||||
"hashInvalid": "無法解析的雜湊",
|
||||
"inLibraryTooltip": "此模型已存在於本地庫",
|
||||
"notInLibraryTooltip": "此模型不在您的本地庫中",
|
||||
"deletedTooltip": "此 LoRA 已從來源站刪除,無法下載",
|
||||
"hashInvalidTooltip": "此 LoRA 雜湊無法在 CivitAI 上解析——模型可能已更新",
|
||||
"noLorasAssociated": "此配方未關聯任何 LoRA",
|
||||
"noLorasWhyToggle": "為什麼沒有 LoRA?",
|
||||
"noLorasImportMethod": "匯入方式",
|
||||
"noLorasInferredNote": "可能的原因(推斷)——此配方是在記錄匯入診斷資訊之前匯入的。",
|
||||
"noLorasChannels": {
|
||||
"batch_import_url": "批量匯入(圖片 URL)",
|
||||
"batch_import_local": "批量匯入(本機檔案)",
|
||||
"url": "圖片 URL 匯入",
|
||||
"local": "本機檔案匯入",
|
||||
"upload": "圖片上傳",
|
||||
"widget": "從工作流儲存",
|
||||
"reimport_url": "重新匯入(圖片 URL)",
|
||||
"reimport_local": "重新匯入(本機檔案)"
|
||||
},
|
||||
"noLorasReasons": {
|
||||
"no_loras_used": "生成中繼資料完整,且未引用任何 LoRA。",
|
||||
"api_meta_no_lora_resources": "來源 API 未回傳此圖片的 LoRA 資源資料。CivitAI 頁面上顯示的 LoRA 可能來自公開 API 未開放的內部資料。",
|
||||
"api_meta_missing": "來源 API 未回傳此圖片的生成中繼資料。",
|
||||
"no_embedded_metadata": "圖片沒有內嵌生成中繼資料,因此無法復原 LoRA 資訊。",
|
||||
"workflow_metadata_limited": "圖片內嵌的中繼資料是 ComfyUI 工作流;從工作流中提取 LoRA 資訊的能力有限。",
|
||||
"video_no_metadata": "影片檔案不攜帶內嵌生成中繼資料。",
|
||||
"metadata_unsupported": "圖片包含的中繼資料格式無法解析。",
|
||||
"unknown": "無法從儲存的配方資料中確定原因。"
|
||||
},
|
||||
"noLorasDetails": {
|
||||
"apiMetaFields": "API 中繼資料欄位",
|
||||
"modelVersionIds": "回報的模型版本 ID 數",
|
||||
"embeddedMetadata": "內嵌中繼資料",
|
||||
"present": "已找到",
|
||||
"absent": "無"
|
||||
},
|
||||
"download": "下載",
|
||||
"downloadLoraTooltip": "下載此 LoRA",
|
||||
"preparingDownload": "正在準備下載...",
|
||||
"reconnect": "重新關聯",
|
||||
"reconnectTooltip": "與本地 LoRA 重新關聯",
|
||||
"reconnectInstructions": "輸入 LoRA 語法或名稱以重新關聯:",
|
||||
"reconnectExample": "範例:<lora:name:1> 或只填名稱",
|
||||
"reconnectPlaceholder": "輸入 LoRA 名稱或語法",
|
||||
"reconnectSuggestionsLoading": "正在搜尋本地庫...",
|
||||
"reconnectSuggestionsEmpty": "本地庫中沒有符合的 LoRA",
|
||||
"reconnectMatchSameHash": "相同雜湊",
|
||||
"reconnectMatchSameVersion": "相同模型版本",
|
||||
"reconnectMatchSimilarFilename": "相似檔案名稱",
|
||||
"reconnectMatchSimilarName": "相似名稱",
|
||||
"undoReconnect": "撤銷",
|
||||
"undoReconnectTooltip": "恢復此條目在重新關聯前的關聯",
|
||||
"undoReconnectTooltipNamed": "恢復為 {name}(重新關聯前的關聯)",
|
||||
"viewOnCivitai": "在 CivitAI 上檢視",
|
||||
"openLoraDetails": "在 LoRA 庫中檢視 {name}",
|
||||
"openCheckpointDetails": "在模型庫中檢視 {name}",
|
||||
"checkpointDeletedTooltip": "此 Checkpoint 已從來源刪除,無法再下載 - 請使用本地模型重新關聯",
|
||||
"checkpointHashInvalidTooltip": "此 Checkpoint 的雜湊無法在 CivitAI 上解析 - 模型可能已更新",
|
||||
"reconnectCheckpoint": "重新關聯",
|
||||
"reconnectCheckpointTooltip": "與本地 Checkpoint 重新關聯",
|
||||
"checkpointReconnectInstructions": "輸入 Checkpoint 名稱以重新關聯:",
|
||||
"checkpointReconnectPlaceholder": "輸入 Checkpoint 名稱",
|
||||
"checkpointReconnectSuggestionsEmpty": "本地庫中沒有符合的 Checkpoint"
|
||||
},
|
||||
"controls": {
|
||||
"import": {
|
||||
"action": "匯入",
|
||||
@@ -881,7 +1013,7 @@
|
||||
"dropZoneHint": "將圖片拖曳至此處、從剪貼簿貼上,或點擊瀏覽",
|
||||
"orDivider": "或拖曳 / 貼上圖片",
|
||||
"imageUrlOrPath": "圖片網址或檔案路徑:",
|
||||
"urlPlaceholder": "https://civitai.com/images/... 或 C:/path/to/image.png",
|
||||
"urlPlaceholder": "https://civitai.com/images/... 或 https://civitai.red/images/... 或 C:/path/to/image.png",
|
||||
"fetchImage": "取得圖片",
|
||||
"recipeName": "配方名稱",
|
||||
"recipeNamePlaceholder": "輸入配方名稱",
|
||||
@@ -910,7 +1042,7 @@
|
||||
"downloadingLoras": "下載 LoRA 中...",
|
||||
"savingRecipe": "儲存配方中...",
|
||||
"startingDownload": "開始下載 LoRA {current}/{total}",
|
||||
"deletedFromCivitai": "已從 Civitai 刪除",
|
||||
"deletedFromCivitai": "已從 CivitAI 刪除",
|
||||
"inLibrary": "已在庫存",
|
||||
"notInLibrary": "不在庫存",
|
||||
"earlyAccessRequired": "此 LoRA 需購買早期存取才能下載。",
|
||||
@@ -1033,8 +1165,8 @@
|
||||
"start": "開始匯入",
|
||||
"startImport": "開始匯入",
|
||||
"importing": "匯入中...",
|
||||
"rateLimitedSlowdown": "[TODO: Translate] Rate limited — slowing down...",
|
||||
"rateLimitedHint": "[TODO: Translate] Some items were skipped due to metadata provider rate limits. Re-run the import later to retry them.",
|
||||
"rateLimitedSlowdown": "觸發速率限制 — 正在減速...",
|
||||
"rateLimitedHint": "部分項目因元數據提供方的速率限制而被略過。稍後重新執行匯入即可重試這些項目。",
|
||||
"progress": "進度",
|
||||
"total": "總計",
|
||||
"success": "成功",
|
||||
@@ -1076,7 +1208,7 @@
|
||||
"title": "Checkpoint 模型",
|
||||
"modelTypes": {
|
||||
"checkpoint": "Checkpoint",
|
||||
"diffusion_model": "Diffusion Model"
|
||||
"diffusion_model": "擴散模型"
|
||||
},
|
||||
"contextMenu": {
|
||||
"moveToOtherTypeFolder": "移動到 {otherType} 資料夾",
|
||||
@@ -1100,7 +1232,7 @@
|
||||
"collapseAllDisabled": "列表檢視下不可用",
|
||||
"dragDrop": {
|
||||
"unableToResolveRoot": "無法確定移動的目標路徑。",
|
||||
"moveUnsupported": "Move is not supported for this item.",
|
||||
"moveUnsupported": "此項目不支援移動。",
|
||||
"createFolderHint": "放開以建立新資料夾",
|
||||
"newFolderName": "新資料夾名稱",
|
||||
"folderNameHint": "按 Enter 確認,Escape 取消",
|
||||
@@ -1163,36 +1295,36 @@
|
||||
"unusedLoras": {
|
||||
"high": {
|
||||
"title": "大量未使用的 LoRA",
|
||||
"description": "你的 LoRA 中有 {percent}%({count}/{total})從未被使用過。",
|
||||
"description": "您的 LoRA 中有 {percent}%({count}/{total})從未被使用過。",
|
||||
"suggestion": "考慮整理或封存未使用的模型以釋放儲存空間。"
|
||||
}
|
||||
},
|
||||
"unusedCheckpoints": {
|
||||
"detected": {
|
||||
"title": "檢測到未使用的 Checkpoint",
|
||||
"description": "你的 Checkpoint 中有 {percent}%({count}/{total})從未被使用過。",
|
||||
"description": "您的 Checkpoint 中有 {percent}%({count}/{total})從未被使用過。",
|
||||
"suggestion": "審查並考慮刪除不再需要的 Checkpoint。"
|
||||
}
|
||||
},
|
||||
"unusedEmbeddings": {
|
||||
"high": {
|
||||
"title": "大量未使用的 Embedding",
|
||||
"description": "你的 Embedding 中有 {percent}%({count}/{total})從未被使用過。",
|
||||
"suggestion": "考慮整理或封存未使用的 Embedding 以優化你的收藏。"
|
||||
"description": "您的 Embedding 中有 {percent}%({count}/{total})從未被使用過。",
|
||||
"suggestion": "考慮整理或封存未使用的 Embedding 以優化您的收藏。"
|
||||
}
|
||||
},
|
||||
"collection": {
|
||||
"large": {
|
||||
"title": "檢測到大型收藏",
|
||||
"description": "你的模型收藏正在使用 {size} 的儲存空間。",
|
||||
"description": "您的模型收藏正在使用 {size} 的儲存空間。",
|
||||
"suggestion": "考慮使用外部儲存或雲端解決方案以獲得更好的組織。"
|
||||
}
|
||||
},
|
||||
"activity": {
|
||||
"active": {
|
||||
"title": "活躍用戶",
|
||||
"description": "你已經完成了 {count} 次生成!",
|
||||
"suggestion": "繼續探索並用你的模型創作精彩內容。"
|
||||
"description": "您已經完成了 {count} 次生成!",
|
||||
"suggestion": "繼續探索並用您的模型創作精彩內容。"
|
||||
}
|
||||
}
|
||||
},
|
||||
@@ -1238,7 +1370,7 @@
|
||||
"download": {
|
||||
"title": "從網址下載模型",
|
||||
"titleWithType": "從網址下載 {type}",
|
||||
"civitaiUrl": "Civitai 網址:",
|
||||
"civitaiUrl": "CivitAI 網址:",
|
||||
"placeholder": "https://civitai.com/models/...",
|
||||
"urlHint": "每行輸入一個 CivitAI、CivArchive 或 Hugging Face URL。支援批量下載多個 URL。",
|
||||
"selectHfFiles": "選擇從此倉庫下載的檔案:",
|
||||
@@ -1262,7 +1394,7 @@
|
||||
"earlyAccessTooltip": "需要早期存取",
|
||||
"inLibrary": "已在庫存",
|
||||
"downloaded": "已下載",
|
||||
"downloadedTooltip": "先前已下載,但目前不在你的庫中。",
|
||||
"downloadedTooltip": "先前已下載,但目前不在您的庫中。",
|
||||
"alreadyInLibrary": "已在庫存",
|
||||
"partiallyDownloaded": "部分已下載",
|
||||
"autoOrganizedPath": "[依路徑範本自動整理]",
|
||||
@@ -1273,7 +1405,7 @@
|
||||
"inLibrary": "已在庫中"
|
||||
},
|
||||
"errors": {
|
||||
"invalidUrl": "Civitai 網址格式無效",
|
||||
"invalidUrl": "CivitAI 網址格式無效",
|
||||
"noVersions": "此模型無可用版本",
|
||||
"mixedSources": "無法在同一批次中混合使用 CivitAI 和 Hugging Face URL。",
|
||||
"noModelFiles": "在此倉庫中未找到模型檔案。"
|
||||
@@ -1352,8 +1484,8 @@
|
||||
"action": "全部刪除"
|
||||
},
|
||||
"checkUpdates": {
|
||||
"title": "要檢查所有 {type} 的更新嗎?",
|
||||
"message": "這會為資料庫中的每個 {type} 檢查更新,大型收藏可能會花上一些時間。",
|
||||
"title": "要檢查所有 {typePlural} 的更新嗎?",
|
||||
"message": "這會檢查資料庫中的每個 {typePlural} 的更新,大型收藏可能會花上一些時間。",
|
||||
"tip": "想分批處理?切換到批次模式,選擇需要的模型,然後使用「檢查所選更新」。",
|
||||
"action": "全部檢查"
|
||||
},
|
||||
@@ -1377,7 +1509,7 @@
|
||||
},
|
||||
"bulkDownloadMissingLoras": {
|
||||
"title": "下載缺失的 LoRAs",
|
||||
"message": "發現 {uniqueCount} 個獨特的缺失 LoRAs(從選取食譜中的 {totalCount} 個總數)。",
|
||||
"message": "發現 {uniqueCount} 個獨特的缺失 LoRAs(從選取配方中的 {totalCount} 個總數)。",
|
||||
"previewTitle": "要下載的 LoRAs:",
|
||||
"moreItems": "...還有 {count} 個",
|
||||
"note": "檔案將使用預設路徑模板下載。根據 LoRAs 的數量,這可能需要一些時間。",
|
||||
@@ -1387,7 +1519,7 @@
|
||||
"title": "本機範例圖片",
|
||||
"message": "此模型未找到本機範例圖片。可選擇:",
|
||||
"downloadOption": {
|
||||
"title": "從 Civitai 下載",
|
||||
"title": "從 CivitAI 下載",
|
||||
"description": "將遠端範例儲存到本機以便離線使用及加快載入"
|
||||
},
|
||||
"importOption": {
|
||||
@@ -1414,7 +1546,7 @@
|
||||
"confirmAction": "儲存並連結"
|
||||
},
|
||||
"relinkCivitai": {
|
||||
"title": "重新連結至 Civitai",
|
||||
"title": "重新連結至 CivitAI",
|
||||
"warning": "警告:",
|
||||
"warningText": "這是可能造成破壞性的操作。重新連結將會:",
|
||||
"warningList": {
|
||||
@@ -1423,15 +1555,15 @@
|
||||
"unintendedConsequences": "可能產生其他非預期後果"
|
||||
},
|
||||
"proceedText": "僅在確定需要執行時才繼續。",
|
||||
"urlLabel": "Civitai 模型網址:",
|
||||
"urlPlaceholder": "https://civitai.com/models/12345/model-name?modelVersionId=67890",
|
||||
"urlLabel": "CivitAI 模型網址:",
|
||||
"urlPlaceholder": "https://civitai.com/models/12345/model-name?modelVersionId=67890 或 https://civitai.red/models/12345/model-name?modelVersionId=67890",
|
||||
"helpText": {
|
||||
"title": "貼上任意 Civitai 或 CivitArchive 模型網址。支援格式:",
|
||||
"title": "貼上任意 CivitAI 或 CivitArchive 模型網址。支援格式:",
|
||||
"format1": "https://civitai.com/models/12345",
|
||||
"format2": "https://civitai.com/models/12345?modelVersionId=67890",
|
||||
"format3": "https://civitai.com/models/12345/model-name?modelVersionId=67890",
|
||||
"note": "注意:若未提供 modelVersionId,將使用最新版本。",
|
||||
"format4": "https://civarchive.com/models/12345 (CivitArchive)"
|
||||
"format4": "https://civarchive.com/models/12345 (CivArchive)"
|
||||
},
|
||||
"confirmAction": "確認重新連結"
|
||||
},
|
||||
@@ -1441,8 +1573,8 @@
|
||||
"editFileName": "編輯檔案名稱",
|
||||
"editBaseModel": "編輯基礎模型",
|
||||
"editVersionName": "編輯版本名稱",
|
||||
"viewOnCivitai": "在 Civitai 查看",
|
||||
"viewOnCivitaiText": "在 Civitai 查看",
|
||||
"viewOnCivitai": "在 CivitAI 查看",
|
||||
"viewOnCivitaiText": "在 CivitAI 查看",
|
||||
"viewOnHuggingFace": "在 Hugging Face 查看",
|
||||
"viewOnHuggingFaceText": "在 Hugging Face 查看",
|
||||
"viewCreatorProfile": "查看創作者個人檔案",
|
||||
@@ -1474,7 +1606,7 @@
|
||||
"notesHint": "按 Enter 儲存,Shift+Enter 換行",
|
||||
"addNotesPlaceholder": "在此新增備註...",
|
||||
"aboutThisVersion": "關於此版本",
|
||||
"baseModelSearchPlaceholder": "搜尋基礎模型…",
|
||||
"baseModelSearchPlaceholder": "搜尋基礎模型...",
|
||||
"baseModelSuggested": "推薦",
|
||||
"baseModelNoMatch": "沒有符合的基礎模型"
|
||||
},
|
||||
@@ -1494,7 +1626,11 @@
|
||||
"clipSkip": "Clip Skip",
|
||||
"valuePlaceholder": "數值",
|
||||
"add": "新增",
|
||||
"invalidRange": "無效的範圍格式。請使用 x.x-y.y"
|
||||
"invalidRange": "無效的範圍格式。請使用 x.x-y.y",
|
||||
"invalidValue": "請輸入有效的數值",
|
||||
"saveFailed": "儲存預設參數失敗",
|
||||
"added": "已新增預設參數",
|
||||
"updated": "已更新預設參數"
|
||||
},
|
||||
"triggerWords": {
|
||||
"label": "觸發詞",
|
||||
@@ -1505,7 +1641,7 @@
|
||||
"addPlaceholder": "輸入或點擊下方建議",
|
||||
"editWord": "編輯觸發詞",
|
||||
"editPlaceholder": "編輯觸發詞",
|
||||
"copyWord": "複製觸發詞",
|
||||
"copyOrEditWord": "點擊複製,雙擊編輯",
|
||||
"deleteWord": "刪除觸發詞",
|
||||
"suggestions": {
|
||||
"noSuggestions": "無可用建議",
|
||||
@@ -1543,10 +1679,10 @@
|
||||
"noNext": "沒有下一個模型"
|
||||
},
|
||||
"license": {
|
||||
"noImageSell": "No selling generated content",
|
||||
"noRentCivit": "No Civitai generation",
|
||||
"noRent": "No generation services",
|
||||
"noSell": "No selling models",
|
||||
"noImageSell": "禁止出售生成的圖片",
|
||||
"noRentCivit": "禁止在 CivitAI 上生成",
|
||||
"noRent": "禁止生成服務",
|
||||
"noSell": "禁止出售模型",
|
||||
"creditRequired": "需要創作者標示",
|
||||
"noDerivatives": "禁止分享合併作品",
|
||||
"noReLicense": "需要相同授權",
|
||||
@@ -1565,8 +1701,8 @@
|
||||
"showCount": "顯示範例({count})",
|
||||
"hideExamples": "隱藏範例",
|
||||
"addExamples": "新增範例",
|
||||
"previousExample": "上一個範例",
|
||||
"nextExample": "下一個範例",
|
||||
"previousExample": "上一個範例([)",
|
||||
"nextExample": "下一個範例(])",
|
||||
"noExamples": "沒有可用的範例圖片",
|
||||
"addMoreExamples": "新增更多範例",
|
||||
"dragDrop": "拖放圖片或影片到此處",
|
||||
@@ -1576,8 +1712,8 @@
|
||||
"importing": "正在匯入檔案...",
|
||||
"noSupportedFiles": "未選擇支援的檔案。請選擇圖片或影片檔案。",
|
||||
"allFiltered": "所有範例圖片都因 NSFW 內容設定而被過濾",
|
||||
"sfwOnlyEnabled": "你目前的設定為僅顯示安全(SFW)內容",
|
||||
"changeInSettings": "你可以在設定中變更此選項",
|
||||
"sfwOnlyEnabled": "您目前的設定為僅顯示安全(SFW)內容",
|
||||
"changeInSettings": "您可以在設定中變更此選項",
|
||||
"nsfwMature": "成熟內容",
|
||||
"nsfwR": "R 級內容",
|
||||
"nsfwX": "X 級內容",
|
||||
@@ -1601,41 +1737,41 @@
|
||||
},
|
||||
"badges": {
|
||||
"current": "已開啟版本",
|
||||
"currentTooltip": "這是你用來開啟此彈窗的版本",
|
||||
"currentTooltip": "這是您用來開啟此彈窗的版本",
|
||||
"inLibrary": "已在庫中",
|
||||
"inLibraryTooltip": "此版本已存在於你的本地庫中",
|
||||
"inLibraryTooltip": "此版本已存在於您的本地庫中",
|
||||
"downloaded": "已下載",
|
||||
"downloadedTooltip": "此版本之前下載過,但目前不在你的本地庫中",
|
||||
"downloadedTooltip": "此版本之前下載過,但目前不在您的本地庫中",
|
||||
"newer": "較新版本",
|
||||
"newerTooltip": "此版本比你本地的最新版本更新",
|
||||
"newerTooltip": "此版本比您本地的最新版本更新",
|
||||
"earlyAccess": "搶先體驗",
|
||||
"earlyAccessTooltip": "此版本目前需要 Civitai 搶先體驗權限",
|
||||
"earlyAccessTooltip": "此版本目前需要 CivitAI 搶先體驗權限",
|
||||
"paid": "付費",
|
||||
"paidTooltip": "此版本需要付費才能下載",
|
||||
"ignored": "已忽略",
|
||||
"ignoredTooltip": "此版本已關閉更新通知",
|
||||
"onSiteOnly": "僅站內生成",
|
||||
"onSiteOnlyTooltip": "此版本僅在 Civitai 站內可用,無法下載"
|
||||
"onSiteOnlyTooltip": "此版本僅在 CivitAI 站內可用,無法下載"
|
||||
},
|
||||
"actions": {
|
||||
"download": "下載",
|
||||
"downloadTooltip": "下載此版本",
|
||||
"downloadChooseFilesTooltip": "選擇要下載的檔案",
|
||||
"downloadEarlyAccessTooltip": "從 Civitai 下載此搶先體驗版本",
|
||||
"downloadPaidTooltip": "從 Civitai 下載此付費版本",
|
||||
"downloadNotAllowedTooltip": "此版本僅在 Civitai 站內可用,無法下載",
|
||||
"downloadEarlyAccessTooltip": "從 CivitAI 下載此搶先體驗版本",
|
||||
"downloadPaidTooltip": "從 CivitAI 下載此付費版本",
|
||||
"downloadNotAllowedTooltip": "此版本僅在 CivitAI 站內可用,無法下載",
|
||||
"delete": "刪除",
|
||||
"deleteTooltip": "刪除此本地版本",
|
||||
"ignore": "忽略",
|
||||
"unignore": "取消忽略",
|
||||
"ignoreTooltip": "忽略此版本的更新通知",
|
||||
"unignoreTooltip": "恢復此版本的更新通知",
|
||||
"viewVersionOnCivitai": "在 Civitai 上查看版本",
|
||||
"viewVersionOnCivitai": "在 CivitAI 上查看版本",
|
||||
"earlyAccessTooltip": "需要購買搶先體驗",
|
||||
"resumeModelUpdates": "恢復追蹤此模型的更新",
|
||||
"ignoreModelUpdates": "忽略此模型的更新",
|
||||
"viewLocalVersions": "檢視所有本地版本",
|
||||
"viewLocalTooltip": "敬請期待"
|
||||
"viewLocalTooltip": "在主頁面上顯示此模型的所有本機版本"
|
||||
},
|
||||
"filters": {
|
||||
"label": "基礎篩選",
|
||||
@@ -1651,7 +1787,7 @@
|
||||
},
|
||||
"empty": "此模型尚無版本歷史。",
|
||||
"error": "載入版本失敗。",
|
||||
"missingModelId": "此模型缺少 Civitai 模型 ID。",
|
||||
"missingModelId": "此模型缺少 CivitAI 模型 ID。",
|
||||
"hfGroupInfo": "這是一個 HuggingFace 模型組。打開庫頁面即可在網格中查看所有版本。",
|
||||
"confirm": {
|
||||
"delete": "要從庫中刪除此版本嗎?"
|
||||
@@ -1735,14 +1871,14 @@
|
||||
"tips": {
|
||||
"title": "小技巧",
|
||||
"civitai": {
|
||||
"title": "Civitai 整合",
|
||||
"description": "連結您的 Civitai 帳號:前往個人頭像 → 設定 → API 金鑰 → 新增 API 金鑰,然後貼到 LoRA 管理器設定中。",
|
||||
"alt": "Civitai API 設定"
|
||||
"title": "CivitAI 整合",
|
||||
"description": "連結您的 CivitAI 帳號:前往個人頭像 → 設定 → API 金鑰 → 新增 API 金鑰,然後貼到 LoRA 管理器設定中。",
|
||||
"alt": "CivitAI API 設定"
|
||||
},
|
||||
"download": {
|
||||
"title": "快速下載",
|
||||
"description": "使用 Civitai 網址即可快速下載並安裝新模型。",
|
||||
"alt": "Civitai 下載"
|
||||
"description": "使用 CivitAI 網址即可快速下載並安裝新模型。",
|
||||
"alt": "CivitAI 下載"
|
||||
},
|
||||
"recipes": {
|
||||
"title": "儲存配方",
|
||||
@@ -1830,10 +1966,52 @@
|
||||
"tabs": {
|
||||
"gettingStarted": "快速開始",
|
||||
"updateVlogs": "更新影片",
|
||||
"documentation": "文件"
|
||||
"documentation": "文件",
|
||||
"shortcuts": "快捷鍵"
|
||||
},
|
||||
"gettingStarted": {
|
||||
"title": "LoRA 管理器快速開始"
|
||||
"title": "LoRA 管理器快速開始",
|
||||
"replayTutorial": "重新播放教學"
|
||||
},
|
||||
"shortcuts": {
|
||||
"title": "鍵盤與滑鼠快捷鍵",
|
||||
"groups": {
|
||||
"general": "一般",
|
||||
"actions": "操作",
|
||||
"selection": "選取與批量模式",
|
||||
"navigation": "導覽",
|
||||
"modelModal": "模型 / 配方彈窗",
|
||||
"mediaViewer": "媒體檢視器 / 範例展示"
|
||||
},
|
||||
"keys": {
|
||||
"click": "點擊",
|
||||
"drag": "拖曳",
|
||||
"rightClick": "右鍵點擊",
|
||||
"letter": "字母鍵",
|
||||
"swipe": "滑動"
|
||||
},
|
||||
"entries": {
|
||||
"focusSearch": "聚焦搜尋欄",
|
||||
"closeModal": "關閉彈窗 / 面板",
|
||||
"openShortcuts": "開啟此快捷鍵面板",
|
||||
"refresh": "重新整理模型列表",
|
||||
"fetchMetadata": "從 CivitAI 擷取中繼資料(僅限模型頁面)",
|
||||
"downloadModel": "下載模型(僅限模型頁面)",
|
||||
"toggleBulkMode": "切換批量模式",
|
||||
"selectAll": "選取所有可見模型",
|
||||
"rangeSelect": "範圍選取",
|
||||
"marqueeSelect": "框選卡片(在網格空白處拖曳)",
|
||||
"exitBulkMode": "離開批量模式",
|
||||
"bulkActions": "在已選取的卡片上:批量操作選單",
|
||||
"globalActions": "在頁面空白處:全域操作選單(檢查更新、管理已排除的模型)",
|
||||
"scrollPages": "捲動頁面",
|
||||
"jumpAlphabet": "字母列跳轉",
|
||||
"prevNext": "上一個 / 下一個模型",
|
||||
"deleteEntry": "刪除",
|
||||
"cycleMedia": "切換媒體(範例展示中的 [ / ])",
|
||||
"swipeTouch": "在觸控裝置上滑動切換媒體",
|
||||
"closeViewer": "關閉檢視器"
|
||||
}
|
||||
},
|
||||
"updateVlogs": {
|
||||
"title": "最新更新",
|
||||
@@ -1850,7 +2028,8 @@
|
||||
"settings": "設定與配置",
|
||||
"extensions": "擴充功能",
|
||||
"newBadge": "新"
|
||||
}
|
||||
},
|
||||
"newContentBadge": "新"
|
||||
},
|
||||
"update": {
|
||||
"title": "檢查更新",
|
||||
@@ -1926,7 +2105,7 @@
|
||||
"submitGithubIssue": "提交 GitHub 問題",
|
||||
"joinDiscord": "加入 Discord",
|
||||
"youtubeChannel": "YouTube 頻道",
|
||||
"civitaiProfile": "Civitai 個人檔案",
|
||||
"civitaiProfile": "CivitAI 個人檔案",
|
||||
"supportKofi": "在 Ko-fi 支持",
|
||||
"supportPatreon": "在 Patreon 支持"
|
||||
},
|
||||
@@ -2009,14 +2188,27 @@
|
||||
"preparingForDownloadFailed": "準備下載 LoRA 時發生錯誤",
|
||||
"enterLoraName": "請輸入 LoRA 名稱或語法",
|
||||
"reconnectedSuccessfully": "LoRA 重新連結成功",
|
||||
"reconnectBaseModelMismatch": "已重新關聯,但基礎模型不同(配方:{recipe},LoRA:{lora})——兩者架構相容",
|
||||
"reconnectFailed": "LoRA 重新連結錯誤:{message}",
|
||||
"loraRestored": "LoRA 已恢復為重新關聯前的關聯",
|
||||
"loraRestoreFailed": "LoRA 恢復錯誤:{message}",
|
||||
"noPromptToSend": "沒有可發送的提示詞",
|
||||
"cannotSend": "無法傳送配方:缺少配方 ID",
|
||||
"sendFailed": "傳送配方到工作流失敗",
|
||||
"sendError": "傳送配方到工作流錯誤",
|
||||
"missingCheckpointPath": "缺少檢查點路徑",
|
||||
"missingCheckpointInfo": "缺少檢查點資訊",
|
||||
"downloadCheckpointFailed": "下載檢查點失敗:{message}",
|
||||
"missingCheckpointPath": "缺少Checkpoint路徑",
|
||||
"missingCheckpointInfo": "缺少Checkpoint資訊",
|
||||
"downloadCheckpointFailed": "下載Checkpoint失敗:{message}",
|
||||
"enterCheckpointName": "請輸入 Checkpoint 名稱",
|
||||
"checkpointReconnectedSuccessfully": "Checkpoint 重新連結成功",
|
||||
"reconnectCheckpointBaseModelMismatch": "已重新關聯,但基礎模型不同(配方:{recipe},Checkpoint:{checkpoint})——兩者架構相容",
|
||||
"checkpointReconnectFailed": "Checkpoint 重新連結錯誤:{message}",
|
||||
"checkpointRestored": "Checkpoint 已恢復為重新關聯前的關聯",
|
||||
"checkpointRestoreFailed": "Checkpoint 恢復錯誤:{message}",
|
||||
"checkpointDownloadUnavailable": "缺少 CivitAI 標識,無法下載此 Checkpoint - 請嘗試使用本地 Checkpoint 重新關聯",
|
||||
"missingLoraDownloadInfo": "缺少此 LoRA 的下載資訊",
|
||||
"hashNotFoundOnCivitai": "此 LoRA 雜湊無法在 CivitAI 上解析——模型可能已更新或雜湊無效",
|
||||
"downloadLoraFailed": "下載 LoRA 失敗:{message}",
|
||||
"cannotDelete": "無法刪除配方:缺少配方 ID",
|
||||
"deleteConfirmationError": "顯示刪除確認時發生錯誤",
|
||||
"deletedSuccessfully": "配方已成功刪除",
|
||||
@@ -2040,24 +2232,24 @@
|
||||
"batchImportCancelFailed": "取消批量匯入失敗:{message}",
|
||||
"batchImportNoUrls": "請輸入至少一個 URL 或檔案路徑",
|
||||
"batchImportNoDirectory": "請輸入目錄路徑",
|
||||
"batchImportRateLimited": "[TODO: Translate] Metadata provider rate limit reached — requests are being slowed and some items may be skipped. You can re-run the import later.",
|
||||
"batchImportRateLimited": "已達到元數據提供方的速率限制 — 請求正在放緩,部分項目可能被略過。您可以稍後重新執行匯入。",
|
||||
"batchImportBrowseFailed": "瀏覽目錄失敗:{message}",
|
||||
"batchImportDirectorySelected": "已選擇目錄:{path}",
|
||||
"noRecipesSelected": "未選取任何食譜",
|
||||
"noRecipesSelected": "未選取任何配方",
|
||||
"repairBulkComplete": "修復完成:{repaired} 個已修復,{skipped} 個已跳過(共 {total} 個)",
|
||||
"repairBulkSkipped": "所選 {total} 個配方無需修復",
|
||||
"repairBulkFailed": "修復所選配方失敗:{message}",
|
||||
"rematchComplete": "已匹配 {entries} 個條目,涉及 {recipes} 個食譜",
|
||||
"rematchCompleteErrors": "已匹配 {entries} 個條目,涉及 {recipes} 個食譜,{failures} 個失敗",
|
||||
"rematchAllFailed": "{failures}/{total} 個所選食譜重新匹配失敗",
|
||||
"rematchUnmatched": "在 {recipes} 個食譜中找不到 {entries} 個條目的本地匹配",
|
||||
"rematchSkipped": "{total} 個所選食譜均無需重新匹配",
|
||||
"rematchFailed": "重新匹配所選食譜失敗:{message}",
|
||||
"rematchComplete": "已匹配 {entries} 個條目,涉及 {recipes} 個配方",
|
||||
"rematchCompleteErrors": "已匹配 {entries} 個條目,涉及 {recipes} 個配方,{failures} 個失敗",
|
||||
"rematchAllFailed": "{failures}/{total} 個所選配方重新匹配失敗",
|
||||
"rematchUnmatched": "在 {recipes} 個配方中找不到 {entries} 個條目的本地匹配",
|
||||
"rematchSkipped": "{total} 個所選配方均無需重新匹配",
|
||||
"rematchFailed": "重新匹配所選配方失敗:{message}",
|
||||
"reimporting": "正在從來源重新匯入配方...",
|
||||
"reimportSuccess": "配方已從來源重新匯入成功",
|
||||
"reimportBulkComplete": "重新匯入完成:{completed} 個已匯入,{failed} 個失敗(共 {total} 個)",
|
||||
"reimportBulkFailed": "重新匯入某些配方失敗",
|
||||
"noMissingLorasInSelection": "在選取的食譜中未找到缺失的 LoRAs",
|
||||
"noMissingLorasInSelection": "在選取的配方中未找到缺失的 LoRAs",
|
||||
"noLoraRootConfigured": "未配置 LoRA 根目錄。請在設定中設定預設的 LoRA 根目錄。",
|
||||
"workflowSent": "工作流已傳送到 ComfyUI",
|
||||
"workflowSendFailed": "傳送工作流到 ComfyUI 失敗: {error}",
|
||||
@@ -2098,8 +2290,8 @@
|
||||
"bulkUpdatesChecking": "正在檢查所選 {type} 的更新...",
|
||||
"bulkUpdatesSuccess": "{count} 個所選 {type} 有可用更新",
|
||||
"bulkUpdatesNone": "所選 {type} 未找到更新",
|
||||
"bulkUpdatesMissing": "所選 {type} 未連結 Civitai 更新",
|
||||
"bulkUpdatesPartialMissing": "已略過 {missing} 個未連結 Civitai 的所選 {type}",
|
||||
"bulkUpdatesMissing": "所選 {type} 未連結 CivitAI 更新",
|
||||
"bulkUpdatesPartialMissing": "已略過 {missing} 個未連結 CivitAI 的所選 {type}",
|
||||
"bulkUpdatesFailed": "檢查所選 {type} 更新失敗:{message}",
|
||||
"invalidCharactersRemoved": "已移除檔名中的無效字元",
|
||||
"filenameCannotBeEmpty": "檔案名稱不可為空",
|
||||
@@ -2139,8 +2331,8 @@
|
||||
"compactModeToggled": "緊湊模式已{state}",
|
||||
"settingSaveFailed": "儲存設定失敗:{message}",
|
||||
"displayDensitySet": "顯示密度已設為 {density}",
|
||||
"libraryLoadFailed": "Failed to load libraries: {message}",
|
||||
"libraryActivateFailed": "Failed to activate library: {message}",
|
||||
"libraryLoadFailed": "載入模型庫失敗:{message}",
|
||||
"libraryActivateFailed": "啟動模型庫失敗:{message}",
|
||||
"languageChangeFailed": "切換語言失敗:{message}",
|
||||
"cacheCleared": "快取檔案已成功清除。快取將於下次操作時重建。",
|
||||
"cacheClearFailed": "清除快取失敗:{error}",
|
||||
@@ -2218,14 +2410,14 @@
|
||||
},
|
||||
"controls": {
|
||||
"reloadFailed": "重新載入 {pageType} 失敗:{message}",
|
||||
"refreshFailed": "刷新 {pageType} 失敗:{message}",
|
||||
"refreshFailed": "{action} {pageType} 失敗:{message}",
|
||||
"fetchMetadataFailed": "取得 metadata 失敗:{message}",
|
||||
"clearFilterFailed": "清除自訂篩選失敗:{message}"
|
||||
},
|
||||
"contextMenu": {
|
||||
"contentRatingSet": "內容分級已設為 {level}",
|
||||
"contentRatingFailed": "設定內容分級失敗:{message}",
|
||||
"relinkSuccess": "模型已成功重新連結至 Civitai",
|
||||
"relinkSuccess": "模型已成功重新連結至 CivitAI",
|
||||
"relinkFailed": "錯誤:{message}",
|
||||
"linkHfSuccess": "模型已成功連結到 HuggingFace",
|
||||
"linkHfFailed": "錯誤:{message}",
|
||||
@@ -2289,7 +2481,7 @@
|
||||
"bulkMoveSuccess": "已成功移動 {successCount} 個 {type}",
|
||||
"exampleImagesDownloadSuccess": "範例圖片下載成功!",
|
||||
"exampleImagesDownloadFailed": "下載範例圖片失敗:{message}",
|
||||
"moveFailed": "Failed to move item: {message}",
|
||||
"moveFailed": "移動項目失敗:{message}",
|
||||
"copiedToClipboard": "已複製到剪貼簿",
|
||||
"downloadStarted": "下載已開始"
|
||||
},
|
||||
@@ -2319,7 +2511,7 @@
|
||||
},
|
||||
"issues": {
|
||||
"civitai_api_key": {
|
||||
"title": "Civitai API 金鑰"
|
||||
"title": "CivitAI API 金鑰"
|
||||
},
|
||||
"cache_health": {
|
||||
"title": "模型快取健康狀態"
|
||||
@@ -2372,10 +2564,10 @@
|
||||
"seconds": "秒後重新整理"
|
||||
},
|
||||
"communitySupport": {
|
||||
"title": "Keep LoRA Manager Thriving with Your Support ❤️",
|
||||
"content": "LoRA Manager is a passion project maintained full-time by a solo developer. Your support on Ko-fi helps cover development costs, keeps new updates coming, and unlocks a license key for the LM Civitai Extension as a thank-you gift. Every contribution truly makes a difference.",
|
||||
"supportCta": "Support on Ko-fi",
|
||||
"learnMore": "LM Civitai Extension Tutorial"
|
||||
"title": "用您的支持讓 LoRA Manager 持續茁壯 ❤️",
|
||||
"content": "LoRA Manager 是由一位獨立開發者全職維護的熱情項目。您在 Ko-fi 上的支持有助於支付開發成本、持續推出新更新,並將贈送 LM CivitAI 擴充功能的授權金鑰作為感謝之禮。每一份貢獻都意義重大。",
|
||||
"supportCta": "在 Ko-fi 上支持",
|
||||
"learnMore": "LM CivitAI 擴充功能教學"
|
||||
},
|
||||
"cacheHealth": {
|
||||
"corrupted": {
|
||||
|
||||
@@ -1,214 +0,0 @@
|
||||
import logging
|
||||
import os
|
||||
import random
|
||||
from typing import Any, List, Optional, Tuple
|
||||
import comfy.sd # pyright: ignore[reportMissingImports]
|
||||
import folder_paths # pyright: ignore[reportMissingImports]
|
||||
from ..utils.utils import get_checkpoint_info_absolute, _format_model_name_for_comfyui
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
class RandomCheckpointLoaderLM:
|
||||
"""Checkpoint Loader that can randomly pick a checkpoint from the pool
|
||||
|
||||
Loads checkpoints from both standard ComfyUI folders and LoRA Manager's
|
||||
extra folder paths. When select_at_random is enabled, ignores ckpt_name
|
||||
and picks a random checkpoint (optionally filtered by base_model) on
|
||||
every run.
|
||||
"""
|
||||
|
||||
NAME = "Random Checkpoint Loader (LoraManager)"
|
||||
CATEGORY = "Lora Manager/loaders"
|
||||
|
||||
@classmethod
|
||||
def INPUT_TYPES(cls):
|
||||
# Get list of checkpoint names from scanner (includes extra folder paths)
|
||||
checkpoint_names = cls._get_checkpoint_names()
|
||||
base_models = cls._get_available_base_models()
|
||||
return {
|
||||
"required": {
|
||||
"ckpt_name": (
|
||||
checkpoint_names,
|
||||
{"tooltip": "The name of the checkpoint (model) to load."},
|
||||
),
|
||||
"select_at_random": (
|
||||
"BOOLEAN",
|
||||
{
|
||||
"default": False,
|
||||
"tooltip": (
|
||||
"Ignore ckpt_name and pick a random checkpoint from the "
|
||||
"pool (optionally filtered by base_model) on every run."
|
||||
),
|
||||
},
|
||||
),
|
||||
"base_model": (
|
||||
base_models,
|
||||
{
|
||||
"default": "Any",
|
||||
"tooltip": "Restrict random selection to this base model. 'Any' uses the full pool.",
|
||||
},
|
||||
),
|
||||
}
|
||||
}
|
||||
|
||||
RETURN_TYPES = ("MODEL", "CLIP", "VAE", "STRING")
|
||||
RETURN_NAMES = ("MODEL", "CLIP", "VAE", "model_name")
|
||||
OUTPUT_TOOLTIPS = (
|
||||
"The model used for denoising latents.",
|
||||
"The CLIP model used for encoding text prompts.",
|
||||
"The VAE model used for encoding and decoding images to and from latent space.",
|
||||
"The name of the checkpoint that was loaded (useful when select_at_random is enabled).",
|
||||
)
|
||||
FUNCTION = "load_checkpoint"
|
||||
|
||||
@classmethod
|
||||
def IS_CHANGED(cls, ckpt_name, select_at_random=False, base_model="Any"):
|
||||
# Force re-execution on every run while randomizing, since the widget
|
||||
# values themselves don't change between queue runs.
|
||||
if select_at_random:
|
||||
return float("nan")
|
||||
return ckpt_name
|
||||
|
||||
@staticmethod
|
||||
def _run_async(coro_fn):
|
||||
"""Run an async fetcher, handling the case where an event loop is already running."""
|
||||
import asyncio
|
||||
|
||||
try:
|
||||
asyncio.get_running_loop()
|
||||
import concurrent.futures
|
||||
|
||||
def run_in_thread():
|
||||
new_loop = asyncio.new_event_loop()
|
||||
asyncio.set_event_loop(new_loop)
|
||||
try:
|
||||
return new_loop.run_until_complete(coro_fn())
|
||||
finally:
|
||||
new_loop.close()
|
||||
|
||||
with concurrent.futures.ThreadPoolExecutor() as executor:
|
||||
future = executor.submit(run_in_thread)
|
||||
return future.result()
|
||||
except RuntimeError:
|
||||
return asyncio.run(coro_fn())
|
||||
|
||||
@classmethod
|
||||
def _get_checkpoint_names(cls, base_model: Optional[str] = None) -> List[str]:
|
||||
"""Get list of checkpoint names from scanner cache in ComfyUI format (relative path with extension)
|
||||
|
||||
Args:
|
||||
base_model: If given (and not "Any"), only include checkpoints matching this base model.
|
||||
"""
|
||||
try:
|
||||
from ..services.service_registry import ServiceRegistry
|
||||
|
||||
async def _get_names():
|
||||
scanner = await ServiceRegistry.get_checkpoint_scanner()
|
||||
cache = await scanner.get_cached_data()
|
||||
|
||||
# Get all model roots for calculating relative paths
|
||||
model_roots = scanner.get_model_roots()
|
||||
|
||||
# Filter only checkpoint type (not diffusion_model) and format names
|
||||
names = []
|
||||
for item in cache.raw_data:
|
||||
if item.get("sub_type") != "checkpoint":
|
||||
continue
|
||||
if (
|
||||
base_model
|
||||
and base_model != "Any"
|
||||
and item.get("base_model") != base_model
|
||||
):
|
||||
continue
|
||||
file_path = item.get("file_path", "")
|
||||
# Only offer models that still exist on disk so ComfyUI
|
||||
# flags missing checkpoints at queue time via
|
||||
# "value not in list" (the scanner cache can be stale).
|
||||
if file_path and os.path.exists(file_path):
|
||||
# Format using relative path with OS-native separator
|
||||
formatted_name = _format_model_name_for_comfyui(
|
||||
file_path, model_roots
|
||||
)
|
||||
if formatted_name:
|
||||
names.append(formatted_name)
|
||||
|
||||
return sorted(names)
|
||||
|
||||
return cls._run_async(_get_names)
|
||||
except Exception as e:
|
||||
logger.error(f"Error getting checkpoint names: {e}")
|
||||
return []
|
||||
|
||||
@classmethod
|
||||
def _get_available_base_models(cls) -> List[str]:
|
||||
"""Get distinct base_model values present among indexed checkpoints, for the random-selection filter."""
|
||||
try:
|
||||
from ..services.service_registry import ServiceRegistry
|
||||
|
||||
async def _get_base_models():
|
||||
scanner = await ServiceRegistry.get_checkpoint_scanner()
|
||||
cache = await scanner.get_cached_data()
|
||||
|
||||
base_models = set()
|
||||
for item in cache.raw_data:
|
||||
if item.get("sub_type") != "checkpoint":
|
||||
continue
|
||||
base_model = item.get("base_model")
|
||||
file_path = item.get("file_path", "")
|
||||
if base_model and file_path and os.path.exists(file_path):
|
||||
base_models.add(base_model)
|
||||
|
||||
return sorted(base_models)
|
||||
|
||||
return ["Any"] + cls._run_async(_get_base_models)
|
||||
except Exception as e:
|
||||
logger.error(f"Error getting available base models: {e}")
|
||||
return ["Any"]
|
||||
|
||||
def load_checkpoint(
|
||||
self,
|
||||
ckpt_name: str,
|
||||
select_at_random: bool = False,
|
||||
base_model: str = "Any",
|
||||
) -> Tuple[Any, Any, Any, str]:
|
||||
"""Load a checkpoint by name, supporting extra folder paths
|
||||
|
||||
Args:
|
||||
ckpt_name: The name of the checkpoint to load (relative path with extension)
|
||||
select_at_random: If True, ignore ckpt_name and pick randomly from the pool
|
||||
base_model: Restricts random selection to this base model ("Any" = no filter)
|
||||
|
||||
Returns:
|
||||
Tuple of (MODEL, CLIP, VAE, model_name)
|
||||
"""
|
||||
if select_at_random:
|
||||
pool = self._get_checkpoint_names(base_model)
|
||||
if not pool:
|
||||
raise FileNotFoundError(
|
||||
f"No checkpoints found for base model '{base_model}'. "
|
||||
"Pick a different base model or disable 'select_at_random'."
|
||||
)
|
||||
ckpt_name = random.choice(pool)
|
||||
logger.info(
|
||||
f"[RandomCheckpointLoaderLM] Randomly selected checkpoint: {ckpt_name}"
|
||||
)
|
||||
|
||||
# Get absolute path from cache using ComfyUI-style name
|
||||
ckpt_path, metadata = get_checkpoint_info_absolute(ckpt_name)
|
||||
|
||||
if metadata is None:
|
||||
raise FileNotFoundError(
|
||||
f"Checkpoint '{ckpt_name}' not found in LoRA Manager cache. "
|
||||
"Make sure the checkpoint is indexed and try again."
|
||||
)
|
||||
|
||||
# Load regular checkpoint using ComfyUI's API
|
||||
logger.info(f"Loading checkpoint from: {ckpt_path}")
|
||||
out = comfy.sd.load_checkpoint_guess_config(
|
||||
ckpt_path,
|
||||
output_vae=True,
|
||||
output_clip=True,
|
||||
embedding_directory=folder_paths.get_folder_paths("embeddings"),
|
||||
)
|
||||
return out[:3] + (ckpt_name,)
|
||||
@@ -1,326 +0,0 @@
|
||||
import logging
|
||||
import os
|
||||
import random
|
||||
from typing import Any, List, Optional, Tuple
|
||||
import comfy.sd # pyright: ignore[reportMissingImports]
|
||||
from ..utils.utils import get_checkpoint_info_absolute, _format_model_name_for_comfyui
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
def _reload_gguf_unet(
|
||||
unet_path: str, weight_dtype: str, disable_dynamic: bool = False
|
||||
) -> object:
|
||||
"""Reload a GGUF diffusion model from disk (cached_patcher_init factory).
|
||||
|
||||
Mirrors the GGUF branch of RandomUNETLoaderLM.load_unet so ModelPatcher
|
||||
deepclone/dynamic machinery can rebuild GGUF models with the correct
|
||||
GGMLOps. ``disable_dynamic`` is accepted for signature compatibility
|
||||
with core ComfyUI loaders.
|
||||
"""
|
||||
loader = RandomUNETLoaderLM()
|
||||
model, _unet_name = loader._load_gguf_unet(unet_path, unet_path, weight_dtype)
|
||||
return model
|
||||
|
||||
|
||||
class RandomUNETLoaderLM:
|
||||
"""UNET Loader that can randomly pick a diffusion model from the pool
|
||||
|
||||
Loads diffusion models/UNets from both standard ComfyUI folders and LoRA
|
||||
Manager's extra folder paths. Supports both regular diffusion models and
|
||||
GGUF format models. When select_at_random is enabled, ignores unet_name
|
||||
and picks a random diffusion model (optionally filtered by base_model)
|
||||
on every run.
|
||||
"""
|
||||
|
||||
NAME = "Random Unet Loader (LoraManager)"
|
||||
CATEGORY = "Lora Manager/loaders"
|
||||
|
||||
@classmethod
|
||||
def INPUT_TYPES(cls):
|
||||
# Get list of unet names from scanner (includes extra folder paths)
|
||||
unet_names = cls._get_unet_names()
|
||||
base_models = cls._get_available_base_models()
|
||||
return {
|
||||
"required": {
|
||||
"unet_name": (
|
||||
unet_names,
|
||||
{"tooltip": "The name of the diffusion model to load."},
|
||||
),
|
||||
"weight_dtype": (
|
||||
["default", "fp8_e4m3fn", "fp8_e4m3fn_fast", "fp8_e5m2"],
|
||||
{"tooltip": "The dtype to use for the model weights."},
|
||||
),
|
||||
"select_at_random": (
|
||||
"BOOLEAN",
|
||||
{
|
||||
"default": False,
|
||||
"tooltip": (
|
||||
"Ignore unet_name and pick a random diffusion model from "
|
||||
"the pool (optionally filtered by base_model) on every run."
|
||||
),
|
||||
},
|
||||
),
|
||||
"base_model": (
|
||||
base_models,
|
||||
{
|
||||
"default": "Any",
|
||||
"tooltip": "Restrict random selection to this base model. 'Any' uses the full pool.",
|
||||
},
|
||||
),
|
||||
}
|
||||
}
|
||||
|
||||
RETURN_TYPES = ("MODEL", "STRING")
|
||||
RETURN_NAMES = ("MODEL", "model_name")
|
||||
OUTPUT_TOOLTIPS = (
|
||||
"The model used for denoising latents.",
|
||||
"The name of the diffusion model that was loaded (useful when select_at_random is enabled).",
|
||||
)
|
||||
FUNCTION = "load_unet"
|
||||
|
||||
@classmethod
|
||||
def IS_CHANGED(
|
||||
cls, unet_name, weight_dtype, select_at_random=False, base_model="Any"
|
||||
):
|
||||
# Force re-execution on every run while randomizing, since the widget
|
||||
# values themselves don't change between queue runs.
|
||||
if select_at_random:
|
||||
return float("nan")
|
||||
return unet_name
|
||||
|
||||
@staticmethod
|
||||
def _run_async(coro_fn):
|
||||
"""Run an async fetcher, handling the case where an event loop is already running."""
|
||||
import asyncio
|
||||
|
||||
try:
|
||||
asyncio.get_running_loop()
|
||||
import concurrent.futures
|
||||
|
||||
def run_in_thread():
|
||||
new_loop = asyncio.new_event_loop()
|
||||
asyncio.set_event_loop(new_loop)
|
||||
try:
|
||||
return new_loop.run_until_complete(coro_fn())
|
||||
finally:
|
||||
new_loop.close()
|
||||
|
||||
with concurrent.futures.ThreadPoolExecutor() as executor:
|
||||
future = executor.submit(run_in_thread)
|
||||
return future.result()
|
||||
except RuntimeError:
|
||||
return asyncio.run(coro_fn())
|
||||
|
||||
@classmethod
|
||||
def _get_unet_names(cls, base_model: Optional[str] = None) -> List[str]:
|
||||
"""Get list of diffusion model names from scanner cache in ComfyUI format (relative path with extension)
|
||||
|
||||
Args:
|
||||
base_model: If given (and not "Any"), only include models matching this base model.
|
||||
"""
|
||||
try:
|
||||
from ..services.service_registry import ServiceRegistry
|
||||
|
||||
async def _get_names():
|
||||
scanner = await ServiceRegistry.get_checkpoint_scanner()
|
||||
cache = await scanner.get_cached_data()
|
||||
|
||||
# Get all model roots for calculating relative paths
|
||||
model_roots = scanner.get_model_roots()
|
||||
|
||||
# Filter only diffusion_model type and format names
|
||||
names = []
|
||||
for item in cache.raw_data:
|
||||
if item.get("sub_type") != "diffusion_model":
|
||||
continue
|
||||
if (
|
||||
base_model
|
||||
and base_model != "Any"
|
||||
and item.get("base_model") != base_model
|
||||
):
|
||||
continue
|
||||
file_path = item.get("file_path", "")
|
||||
# Only offer models that still exist on disk so ComfyUI
|
||||
# flags missing diffusion models at queue time via
|
||||
# "value not in list" (the scanner cache can be stale).
|
||||
if file_path and os.path.exists(file_path):
|
||||
# Format using relative path with OS-native separator
|
||||
formatted_name = _format_model_name_for_comfyui(
|
||||
file_path, model_roots
|
||||
)
|
||||
if formatted_name:
|
||||
names.append(formatted_name)
|
||||
|
||||
return sorted(names)
|
||||
|
||||
return cls._run_async(_get_names)
|
||||
except Exception as e:
|
||||
logger.error(f"Error getting unet names: {e}")
|
||||
return []
|
||||
|
||||
@classmethod
|
||||
def _get_available_base_models(cls) -> List[str]:
|
||||
"""Get distinct base_model values present among indexed diffusion models, for the random-selection filter."""
|
||||
try:
|
||||
from ..services.service_registry import ServiceRegistry
|
||||
|
||||
async def _get_base_models():
|
||||
scanner = await ServiceRegistry.get_checkpoint_scanner()
|
||||
cache = await scanner.get_cached_data()
|
||||
|
||||
base_models = set()
|
||||
for item in cache.raw_data:
|
||||
if item.get("sub_type") != "diffusion_model":
|
||||
continue
|
||||
base_model = item.get("base_model")
|
||||
file_path = item.get("file_path", "")
|
||||
if base_model and file_path and os.path.exists(file_path):
|
||||
base_models.add(base_model)
|
||||
|
||||
return sorted(base_models)
|
||||
|
||||
return ["Any"] + cls._run_async(_get_base_models)
|
||||
except Exception as e:
|
||||
logger.error(f"Error getting available base models: {e}")
|
||||
return ["Any"]
|
||||
|
||||
def load_unet(
|
||||
self,
|
||||
unet_name: str,
|
||||
weight_dtype: str,
|
||||
select_at_random: bool = False,
|
||||
base_model: str = "Any",
|
||||
) -> Tuple[Any, ...]:
|
||||
"""Load a diffusion model by name, supporting extra folder paths
|
||||
|
||||
Args:
|
||||
unet_name: The name of the diffusion model to load (relative path with extension)
|
||||
weight_dtype: The dtype to use for model weights
|
||||
select_at_random: If True, ignore unet_name and pick randomly from the pool
|
||||
base_model: Restricts random selection to this base model ("Any" = no filter)
|
||||
|
||||
Returns:
|
||||
Tuple of (MODEL, model_name)
|
||||
"""
|
||||
import torch
|
||||
|
||||
if select_at_random:
|
||||
pool = self._get_unet_names(base_model)
|
||||
if not pool:
|
||||
raise FileNotFoundError(
|
||||
f"No diffusion models found for base model '{base_model}'. "
|
||||
"Pick a different base model or disable 'select_at_random'."
|
||||
)
|
||||
unet_name = random.choice(pool)
|
||||
logger.info(
|
||||
f"[RandomUNETLoaderLM] Randomly selected diffusion model: {unet_name}"
|
||||
)
|
||||
|
||||
# Get absolute path from cache using ComfyUI-style name
|
||||
unet_path, metadata = get_checkpoint_info_absolute(unet_name)
|
||||
|
||||
if metadata is None:
|
||||
raise FileNotFoundError(
|
||||
f"Diffusion model '{unet_name}' not found in LoRA Manager cache. "
|
||||
"Make sure the model is indexed and try again."
|
||||
)
|
||||
|
||||
# Check if it's a GGUF model
|
||||
if unet_path.endswith(".gguf"):
|
||||
return self._load_gguf_unet(unet_path, unet_name, weight_dtype)
|
||||
|
||||
# Load regular diffusion model using ComfyUI's API
|
||||
logger.info(f"Loading diffusion model from: {unet_path}")
|
||||
|
||||
# Build model options based on weight_dtype
|
||||
model_options = {}
|
||||
if weight_dtype == "fp8_e4m3fn":
|
||||
model_options["dtype"] = torch.float8_e4m3fn
|
||||
elif weight_dtype == "fp8_e4m3fn_fast":
|
||||
model_options["dtype"] = torch.float8_e4m3fn
|
||||
model_options["fp8_optimizations"] = True
|
||||
elif weight_dtype == "fp8_e5m2":
|
||||
model_options["dtype"] = torch.float8_e5m2
|
||||
|
||||
model = comfy.sd.load_diffusion_model(unet_path, model_options=model_options)
|
||||
return (model, unet_name)
|
||||
|
||||
def _load_gguf_unet(
|
||||
self, unet_path: str, unet_name: str, weight_dtype: str
|
||||
) -> Tuple[Any, ...]:
|
||||
"""Load a GGUF format diffusion model
|
||||
|
||||
Args:
|
||||
unet_path: Absolute path to the GGUF file
|
||||
unet_name: Name of the model for error messages
|
||||
weight_dtype: The dtype to use for model weights
|
||||
|
||||
Returns:
|
||||
Tuple of (MODEL, model_name)
|
||||
"""
|
||||
import torch
|
||||
from .gguf_import_helper import get_gguf_modules
|
||||
|
||||
# Get ComfyUI-GGUF modules using helper (handles various import scenarios)
|
||||
try:
|
||||
loader_module, ops_module, nodes_module = get_gguf_modules()
|
||||
gguf_sd_loader = getattr(loader_module, "gguf_sd_loader")
|
||||
GGMLOps = getattr(ops_module, "GGMLOps")
|
||||
GGUFModelPatcher = getattr(nodes_module, "GGUFModelPatcher")
|
||||
except RuntimeError as e:
|
||||
raise RuntimeError(f"Cannot load GGUF model '{unet_name}'. {str(e)}")
|
||||
|
||||
logger.info(f"Loading GGUF diffusion model from: {unet_path}")
|
||||
|
||||
try:
|
||||
# Load GGUF state dict
|
||||
sd, extra = gguf_sd_loader(unet_path)
|
||||
|
||||
# Prepare kwargs for metadata if supported
|
||||
kwargs = {}
|
||||
import inspect
|
||||
|
||||
valid_params = inspect.signature(
|
||||
comfy.sd.load_diffusion_model_state_dict
|
||||
).parameters
|
||||
if "metadata" in valid_params:
|
||||
kwargs["metadata"] = extra.get("metadata", {})
|
||||
|
||||
# Setup custom operations with GGUF support
|
||||
ops = GGMLOps()
|
||||
|
||||
# Handle weight_dtype for GGUF models
|
||||
if weight_dtype in ("default", None):
|
||||
ops.Linear.dequant_dtype = None
|
||||
elif weight_dtype in ["target"]:
|
||||
ops.Linear.dequant_dtype = weight_dtype
|
||||
else:
|
||||
ops.Linear.dequant_dtype = getattr(torch, weight_dtype, None)
|
||||
|
||||
# Load the model
|
||||
model = comfy.sd.load_diffusion_model_state_dict(
|
||||
sd, model_options={"custom_operations": ops}, **kwargs
|
||||
)
|
||||
|
||||
if model is None:
|
||||
raise RuntimeError(
|
||||
f"Could not detect model type for GGUF diffusion model: {unet_path}"
|
||||
)
|
||||
|
||||
# Wrap with GGUFModelPatcher
|
||||
model = GGUFModelPatcher.clone(model)
|
||||
|
||||
# Register a reload factory so the MODEL carries its source path
|
||||
# (cached_patcher_init) like core ComfyUI loaders do — required
|
||||
# for model-name extraction downstream and for ModelPatcher
|
||||
# deepclone/dynamic machinery.
|
||||
model.cached_patcher_init = (_reload_gguf_unet, (unet_path, weight_dtype))
|
||||
|
||||
return (model, unet_name)
|
||||
|
||||
except Exception as e:
|
||||
logger.error(f"Error loading GGUF diffusion model '{unet_name}': {e}")
|
||||
raise RuntimeError(
|
||||
f"Failed to load GGUF diffusion model '{unet_name}': {str(e)}"
|
||||
)
|
||||
@@ -8,6 +8,7 @@ from typing import Dict, Any
|
||||
from ..base import RecipeMetadataParser
|
||||
from ..constants import GEN_PARAM_KEYS
|
||||
from ...services.metadata_service import get_default_metadata_provider
|
||||
from ...utils.constants import is_empty_placeholder_hash
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
@@ -146,15 +147,13 @@ class AutomaticMetadataParser(RecipeMetadataParser):
|
||||
# Initialize hashes dict if it doesn't exist
|
||||
if "hashes" not in metadata:
|
||||
metadata["hashes"] = {}
|
||||
# Add as lora type in the same format as
|
||||
# regular hashes. Only override an
|
||||
# existing entry if its value is empty
|
||||
# (Lora hashes is the more reliable
|
||||
# source when Hashes JSON has blanks).
|
||||
# Lora hashes carries the 12-char AutoV3
|
||||
# hash (resolvable on CivitAI and the local
|
||||
# autov3 index); the Hashes JSON value is
|
||||
# only the 10-char AutoV2 prefix, so on
|
||||
# conflict the Lora hashes value wins.
|
||||
key = f"lora:{lora_name}"
|
||||
existing = metadata["hashes"].get(key, "")
|
||||
if not existing:
|
||||
metadata["hashes"][key] = lora_hash
|
||||
metadata["hashes"][key] = lora_hash
|
||||
|
||||
# Remove lora hashes from params section
|
||||
params_section = params_section.replace(lora_hashes_match.group(0), '')
|
||||
@@ -526,6 +525,26 @@ class AutomaticMetadataParser(RecipeMetadataParser):
|
||||
weight = prompt_entries[0][1] if len(prompt_entries) == 1 else 1.0
|
||||
lora_entry = make_lora_entry(lora_type, lora_name, weight, lora_hash)
|
||||
|
||||
if is_empty_placeholder_hash(lora_hash):
|
||||
# The empty-hash placeholder (SHA256 of an empty byte
|
||||
# string) is not a real hash: never look it up in the
|
||||
# local hash index or on CivitAI. Match by filename;
|
||||
# otherwise keep the item as unresolved (no hash, flagged
|
||||
# hashInvalid so the UI shows the unresolvable-hash state
|
||||
# and offers reconnect instead of download) rather than
|
||||
# dropping it.
|
||||
if recipe_scanner and lora_type == 'lora' and basename_key not in queried_local_basenames:
|
||||
local_lora = await recipe_scanner.get_local_lora(lora_name, recipe_base_model)
|
||||
if local_lora:
|
||||
local_entry = self.populate_lora_from_local(lora_entry, local_lora)
|
||||
merge_or_append_local(local_entry)
|
||||
continue
|
||||
lora_entry['hash'] = ''
|
||||
lora_entry['hashInvalid'] = True
|
||||
if not resource_lora_count:
|
||||
loras.append(lora_entry)
|
||||
continue
|
||||
|
||||
if lora_hash and recipe_scanner and lora_type == 'lora':
|
||||
local_lora = await recipe_scanner.get_local_lora_by_hash(lora_hash)
|
||||
if local_lora:
|
||||
|
||||
@@ -115,6 +115,27 @@ class CivitaiApiMetadataParser(RecipeMetadataParser):
|
||||
):
|
||||
metadata = inner_meta
|
||||
|
||||
# Civitai's image API meta parser mangles the A1111 "Lora hashes"
|
||||
# text field into a quote-wrapped dict entry:
|
||||
# '"Daphne Blake Cosplay_v1": "e67ebd5e315f"'
|
||||
# The 12-char AutoV3 it carries is more reliable than the stale
|
||||
# 10-char AutoV2 value in the "hashes" dict, so recover it and
|
||||
# let it override the conflicting entry.
|
||||
if isinstance(metadata, dict):
|
||||
for key, hash_value in list(metadata.items()):
|
||||
if (
|
||||
isinstance(key, str)
|
||||
and key.startswith('"')
|
||||
and isinstance(hash_value, str)
|
||||
and hash_value.endswith('"')
|
||||
):
|
||||
clean_name = key.strip('"').strip()
|
||||
clean_hash = hash_value.strip('"').strip()
|
||||
if clean_name and clean_hash:
|
||||
hashes_dict = metadata.get("hashes")
|
||||
if isinstance(hashes_dict, dict):
|
||||
hashes_dict[f"lora:{clean_name}"] = clean_hash
|
||||
|
||||
# Initialize result structure
|
||||
result: Dict[str, Any] = {
|
||||
"base_model": None,
|
||||
|
||||
@@ -196,7 +196,7 @@ class RecipeFormatParser(RecipeMetadataParser):
|
||||
filtered_gen_params[key] = value
|
||||
|
||||
return {
|
||||
'base_model': checkpoint['baseModel'] if checkpoint and checkpoint.get('baseModel') else recipe_metadata.get('base_model', ''),
|
||||
'base_model': checkpoint['baseModel'] if checkpoint and checkpoint.get('baseModel') else (recipe_metadata.get('base_model') or None),
|
||||
'loras': loras,
|
||||
'gen_params': filtered_gen_params,
|
||||
'tags': recipe_metadata.get('tags', []),
|
||||
@@ -208,3 +208,24 @@ class RecipeFormatParser(RecipeMetadataParser):
|
||||
except Exception as e:
|
||||
logger.error(f"Error parsing recipe format metadata: {e}", exc_info=True)
|
||||
return {"error": str(e), "loras": []}
|
||||
|
||||
|
||||
def strip_recipe_metadata(metadata_text: str) -> str:
|
||||
"""Strip the ``Recipe metadata: {...}`` block appended by LoRA Manager.
|
||||
|
||||
The saved recipe image carries the original generation metadata followed
|
||||
by an appended recipe JSON block (see ``ExifUtils.append_recipe_metadata``).
|
||||
Re-import wants to re-parse the original embedded metadata, so this returns
|
||||
only the text before the appended marker. The input is returned unchanged
|
||||
when no marker is present.
|
||||
"""
|
||||
if not metadata_text:
|
||||
return metadata_text
|
||||
match = re.search(
|
||||
RecipeFormatParser.METADATA_MARKER,
|
||||
metadata_text,
|
||||
re.IGNORECASE | re.DOTALL,
|
||||
)
|
||||
if not match:
|
||||
return metadata_text
|
||||
return metadata_text[: match.start()].strip()
|
||||
|
||||
@@ -47,15 +47,16 @@ class CheckpointRoutes(BaseModelRoutes):
|
||||
registrar.add_prefixed_route('GET', '/api/lm/{prefix}/checkpoints_roots', prefix, self.get_checkpoints_roots)
|
||||
registrar.add_prefixed_route('GET', '/api/lm/{prefix}/unet_roots', prefix, self.get_unet_roots)
|
||||
|
||||
# Name/base_model pool for the Random Checkpoint/Unet Loader nodes
|
||||
# Name/base_model pool for the Checkpoint/Unet Loader nodes' base_model filtering
|
||||
registrar.add_prefixed_route('GET', '/api/lm/{prefix}/loader-pool', prefix, self.get_loader_pool)
|
||||
|
||||
async def get_loader_pool(self, request: web.Request) -> web.Response:
|
||||
"""Return ComfyUI-formatted model names with their base_model.
|
||||
|
||||
Backing data for the Random Checkpoint/Unet Loader nodes: the front-end
|
||||
filters the ckpt_name/unet_name combo options by base_model using this
|
||||
pool, so control_after_generate randomizes within the narrowed set.
|
||||
Backing data for the Checkpoint/Unet Loader nodes'
|
||||
control_after_generate feature: the front-end filters the
|
||||
ckpt_name/unet_name combo options by base_model using this pool, so
|
||||
randomize mode picks within the narrowed set.
|
||||
"""
|
||||
try:
|
||||
sub_type = request.query.get("sub_type", "checkpoint")
|
||||
|
||||
@@ -15,6 +15,10 @@ from aiohttp import web
|
||||
import jinja2
|
||||
|
||||
from ...config import config
|
||||
from ...services.active_filters_store import (
|
||||
ActiveFiltersStore,
|
||||
active_filters_to_query_kwargs,
|
||||
)
|
||||
from ...services.download_coordinator import DownloadCoordinator
|
||||
from ...services.connectivity_guard import (
|
||||
OFFLINE_FRIENDLY_MESSAGE,
|
||||
@@ -1595,12 +1599,50 @@ class ModelQueryHandler:
|
||||
allow_selling_generated_content.lower() not in ("false", "0", "")
|
||||
)
|
||||
|
||||
# When requested, merge the manager page's active filters stored
|
||||
# server-side. Explicit query parameters take precedence over the
|
||||
# stored values.
|
||||
use_active_filters = (
|
||||
request.query.get("use_active_filters", "").lower() in ("1", "true")
|
||||
)
|
||||
if use_active_filters:
|
||||
stored = ActiveFiltersStore.get_instance().get_filters(
|
||||
self._service.model_type
|
||||
)
|
||||
injected = active_filters_to_query_kwargs(stored)
|
||||
if folder is None and "folder" in injected:
|
||||
folder = injected["folder"]
|
||||
if "recursive" not in request.query and "recursive" in injected:
|
||||
recursive = injected["recursive"]
|
||||
if not base_models and injected.get("base_models"):
|
||||
base_models = injected["base_models"]
|
||||
if not model_types and injected.get("model_types"):
|
||||
model_types = injected["model_types"]
|
||||
if not tag_filters and injected.get("tags"):
|
||||
tag_filters = injected["tags"]
|
||||
if not auto_tag_filters and injected.get("auto_tags"):
|
||||
auto_tag_filters = injected["auto_tags"]
|
||||
if "tag_logic" not in request.query and injected.get("tag_logic"):
|
||||
injected_logic = str(injected["tag_logic"]).lower()
|
||||
if injected_logic in ("any", "all"):
|
||||
tag_logic = injected_logic
|
||||
if credit_required is None and "credit_required" in injected:
|
||||
credit_required = injected["credit_required"]
|
||||
if (
|
||||
allow_selling_generated_content is None
|
||||
and "allow_selling_generated_content" in injected
|
||||
):
|
||||
allow_selling_generated_content = injected[
|
||||
"allow_selling_generated_content"
|
||||
]
|
||||
|
||||
# The presence of the recursive param (always sent by the loras
|
||||
# widget when filter mode is on) signals that the filter pipeline
|
||||
# must run even when no concrete filter is set, so global settings
|
||||
# like show_only_sfw stay consistent with the list endpoint.
|
||||
apply_filters = (
|
||||
"recursive" in request.query
|
||||
use_active_filters
|
||||
or "recursive" in request.query
|
||||
or folder is not None
|
||||
or bool(base_models)
|
||||
or bool(model_types)
|
||||
@@ -1634,6 +1676,50 @@ class ModelQueryHandler:
|
||||
)
|
||||
return web.json_response({"success": False, "error": str(exc)}, status=500)
|
||||
|
||||
async def update_active_filters(self, request: web.Request) -> web.Response:
|
||||
"""Store the manager page's active filters for this model type."""
|
||||
try:
|
||||
payload = await request.json()
|
||||
except Exception:
|
||||
return web.json_response(
|
||||
{"success": False, "error": "Invalid JSON body"}, status=400
|
||||
)
|
||||
|
||||
if not isinstance(payload, dict):
|
||||
return web.json_response(
|
||||
{"success": False, "error": "Body must be a JSON object"}, status=400
|
||||
)
|
||||
|
||||
try:
|
||||
ActiveFiltersStore.get_instance().set_filters(
|
||||
self._service.model_type, payload
|
||||
)
|
||||
return web.json_response({"success": True})
|
||||
except Exception as exc:
|
||||
self._logger.error(
|
||||
"Error updating active filters for %s: %s",
|
||||
self._service.model_type,
|
||||
exc,
|
||||
exc_info=True,
|
||||
)
|
||||
return web.json_response({"success": False, "error": str(exc)}, status=500)
|
||||
|
||||
async def get_active_filters(self, request: web.Request) -> web.Response:
|
||||
"""Return the stored active filters for this model type."""
|
||||
try:
|
||||
filters = ActiveFiltersStore.get_instance().get_filters(
|
||||
self._service.model_type
|
||||
)
|
||||
return web.json_response({"success": True, "filters": filters})
|
||||
except Exception as exc:
|
||||
self._logger.error(
|
||||
"Error getting active filters for %s: %s",
|
||||
self._service.model_type,
|
||||
exc,
|
||||
exc_info=True,
|
||||
)
|
||||
return web.json_response({"success": False, "error": str(exc)}, status=500)
|
||||
|
||||
|
||||
class ModelDownloadHandler:
|
||||
"""Coordinate downloads and progress reporting."""
|
||||
@@ -3339,6 +3425,8 @@ class ModelHandlerSet:
|
||||
"get_model_metadata": self.query.get_model_metadata,
|
||||
"get_model_description": self.query.get_model_description,
|
||||
"get_relative_paths": self.query.get_relative_paths,
|
||||
"update_active_filters": self.query.update_active_filters,
|
||||
"get_active_filters": self.query.get_active_filters,
|
||||
"refresh_model_updates": self.updates.refresh_model_updates,
|
||||
"fetch_missing_civitai_license_data": self.updates.fetch_missing_civitai_license_data,
|
||||
"set_model_update_ignore": self.updates.set_model_update_ignore,
|
||||
|
||||
@@ -26,6 +26,7 @@ from ...services.recipes import (
|
||||
RecipeValidationError,
|
||||
)
|
||||
from ...services.metadata_service import get_default_metadata_provider
|
||||
from ...services.recipe_scanner import UNKNOWN_BASE_MODEL_FILTER
|
||||
from ...utils.civitai_utils import (
|
||||
build_civitai_image_page_url,
|
||||
extract_civitai_image_id,
|
||||
@@ -113,6 +114,13 @@ class RecipeHandlerSet:
|
||||
"update_recipe": self.management.update_recipe,
|
||||
"record_recipe_open": self.management.record_recipe_open,
|
||||
"reconnect_lora": self.management.reconnect_lora,
|
||||
"restore_lora": self.management.restore_lora,
|
||||
"get_reconnect_suggestions": self.management.get_reconnect_suggestions,
|
||||
"mark_lora_hash_invalid": self.management.mark_lora_hash_invalid,
|
||||
"reconnect_checkpoint": self.management.reconnect_checkpoint,
|
||||
"restore_checkpoint": self.management.restore_checkpoint,
|
||||
"get_checkpoint_reconnect_suggestions": self.management.get_checkpoint_reconnect_suggestions,
|
||||
"mark_checkpoint_hash_invalid": self.management.mark_checkpoint_hash_invalid,
|
||||
"find_duplicates": self.query.find_duplicates,
|
||||
"move_recipes_bulk": self.management.move_recipes_bulk,
|
||||
"bulk_delete": self.management.bulk_delete,
|
||||
@@ -345,6 +353,17 @@ class RecipeListingHandler:
|
||||
|
||||
if not recipe:
|
||||
return web.json_response({"error": "Recipe not found"}, status=404)
|
||||
|
||||
# Expose the on-disk recipe JSON path so the modal can offer
|
||||
# "open file location" without guessing the storage layout.
|
||||
recipe = dict(recipe)
|
||||
try:
|
||||
json_path = await recipe_scanner.get_recipe_json_path(recipe_id)
|
||||
except Exception: # pragma: no cover - details must still load
|
||||
json_path = None
|
||||
if json_path:
|
||||
recipe["recipe_json_path"] = json_path
|
||||
|
||||
return web.json_response(recipe)
|
||||
except Exception as exc:
|
||||
self._logger.error(
|
||||
@@ -466,17 +485,32 @@ class RecipeQueryHandler:
|
||||
cache = await recipe_scanner.get_cached_data()
|
||||
|
||||
base_model_counts: Dict[str, int] = {}
|
||||
unknown_count = 0
|
||||
for recipe in getattr(cache, "raw_data", []):
|
||||
base_model = recipe.get("base_model")
|
||||
if base_model:
|
||||
base_model_counts[base_model] = (
|
||||
base_model_counts.get(base_model, 0) + 1
|
||||
)
|
||||
else:
|
||||
unknown_count += 1
|
||||
|
||||
sorted_models = [
|
||||
{"name": model, "count": count}
|
||||
for model, count in base_model_counts.items()
|
||||
]
|
||||
if unknown_count:
|
||||
# Synthetic "Unknown" bucket for recipes whose base model could
|
||||
# not be determined. `value` carries the filter marker so the
|
||||
# UI can display "Unknown" without colliding with real base
|
||||
# model strings.
|
||||
sorted_models.append(
|
||||
{
|
||||
"name": "Unknown",
|
||||
"value": UNKNOWN_BASE_MODEL_FILTER,
|
||||
"count": unknown_count,
|
||||
}
|
||||
)
|
||||
sorted_models.sort(key=lambda entry: entry["count"], reverse=True)
|
||||
if limit > 0:
|
||||
sorted_models = sorted_models[:limit]
|
||||
@@ -1067,12 +1101,14 @@ class RecipeManagementHandler:
|
||||
return web.json_response({"success": False, "error": str(exc)}, status=500)
|
||||
|
||||
async def reimport_recipe(self, request: web.Request) -> web.Response:
|
||||
"""Delete a recipe and re-import it from its source URL.
|
||||
"""Delete a recipe and re-import it from its source.
|
||||
|
||||
This gives the recipe a fresh start — re-downloads the image from
|
||||
CivitAI, re-parses EXIF metadata with the current parser, and
|
||||
re-resolves LoRAs / checkpoint. User edits (title, tags, favorite)
|
||||
are carried over from the old recipe.
|
||||
Gives the recipe a fresh start: URL-sourced recipes re-download the
|
||||
image from CivitAI; local ones re-parse the saved recipe image. Both
|
||||
use the original embedded generation metadata (the appended recipe
|
||||
metadata block is ignored) with the current parser, and re-resolve
|
||||
LoRAs / checkpoint. User edits (title, tags, favorite) are carried
|
||||
over from the old recipe.
|
||||
"""
|
||||
try:
|
||||
await self._ensure_dependencies_ready()
|
||||
@@ -1085,13 +1121,40 @@ class RecipeManagementHandler:
|
||||
if not old_recipe:
|
||||
raise RecipeNotFoundError(f"Recipe {recipe_id} not found")
|
||||
|
||||
source_path = old_recipe.get("source_path")
|
||||
if not source_path:
|
||||
old_file_path = old_recipe.get("file_path", "")
|
||||
old_folder = os.path.dirname(old_file_path) if old_file_path else None
|
||||
|
||||
source_path = old_recipe.get("source_path") or ""
|
||||
image_id = extract_civitai_image_id(source_path) if source_path else None
|
||||
|
||||
# Local re-import sources: an explicit local source_path, or — when
|
||||
# no usable source_path was recorded (drag & drop / file-picker
|
||||
# imports, or a dangling path left by an earlier re-import) — the
|
||||
# recipe's own saved image, which still carries the original
|
||||
# embedded generation metadata next to the recipe metadata block.
|
||||
# In the fallback case nothing is persisted as source_path: the
|
||||
# recipe's own previous preview is not an external source, and it
|
||||
# is deleted together with the old recipe below.
|
||||
local_source = None
|
||||
persisted_source_path = ""
|
||||
if not image_id and source_path and os.path.isfile(source_path):
|
||||
local_source = source_path
|
||||
persisted_source_path = source_path
|
||||
elif (
|
||||
not image_id
|
||||
and not source_path.startswith(("http://", "https://"))
|
||||
and old_file_path
|
||||
and os.path.isfile(old_file_path)
|
||||
):
|
||||
local_source = old_file_path
|
||||
|
||||
if not image_id and not local_source:
|
||||
return web.json_response(
|
||||
{
|
||||
"success": False,
|
||||
"error": (
|
||||
"Recipe has no source URL — cannot re-import. "
|
||||
"Recipe has no re-importable source (no source URL "
|
||||
"and no accessible local image). "
|
||||
"Use repair or manual import instead."
|
||||
),
|
||||
},
|
||||
@@ -1105,33 +1168,15 @@ class RecipeManagementHandler:
|
||||
if "tags" in user_edits and not isinstance(user_edits["tags"], list):
|
||||
del user_edits["tags"]
|
||||
|
||||
old_file_path = old_recipe.get("file_path", "")
|
||||
old_folder = os.path.dirname(old_file_path) if old_file_path else None
|
||||
|
||||
image_id = extract_civitai_image_id(source_path)
|
||||
is_local_file = not image_id and os.path.isfile(source_path)
|
||||
|
||||
if not image_id and not is_local_file:
|
||||
return web.json_response(
|
||||
{
|
||||
"success": False,
|
||||
"error": (
|
||||
"Recipe source is neither a valid CivitAI image URL "
|
||||
"nor an accessible local file. "
|
||||
"Use repair or manual import instead."
|
||||
),
|
||||
},
|
||||
status=400,
|
||||
)
|
||||
|
||||
if is_local_file:
|
||||
if local_source:
|
||||
return await self._do_reimport_from_local(
|
||||
source_path,
|
||||
local_source,
|
||||
recipe_scanner,
|
||||
recipe_id=recipe_id,
|
||||
target_dir=old_folder,
|
||||
user_edits=user_edits,
|
||||
old_title=old_recipe.get("title", ""),
|
||||
persisted_source_path=persisted_source_path,
|
||||
)
|
||||
|
||||
async with self._import_semaphore:
|
||||
@@ -1592,6 +1637,204 @@ class RecipeManagementHandler:
|
||||
self._logger.error("Error reconnecting LoRA: %s", exc, exc_info=True)
|
||||
return web.json_response({"error": str(exc)}, status=500)
|
||||
|
||||
async def restore_lora(self, request: web.Request) -> web.Response:
|
||||
try:
|
||||
await self._ensure_dependencies_ready()
|
||||
recipe_scanner = self._recipe_scanner_getter()
|
||||
if recipe_scanner is None:
|
||||
raise RuntimeError("Recipe scanner unavailable")
|
||||
|
||||
data = await request.json()
|
||||
for field in ("recipe_id", "lora_index"):
|
||||
if field not in data:
|
||||
raise RecipeValidationError(f"Missing required field: {field}")
|
||||
|
||||
result = await self._persistence_service.restore_lora(
|
||||
recipe_scanner=recipe_scanner,
|
||||
recipe_id=data["recipe_id"],
|
||||
lora_index=int(data["lora_index"]),
|
||||
)
|
||||
return web.json_response(result.payload, status=result.status)
|
||||
except RecipeValidationError as exc:
|
||||
return web.json_response({"error": str(exc)}, status=400)
|
||||
except RecipeNotFoundError as exc:
|
||||
return web.json_response({"error": str(exc)}, status=404)
|
||||
except Exception as exc:
|
||||
self._logger.error("Error restoring LoRA: %s", exc, exc_info=True)
|
||||
return web.json_response({"error": str(exc)}, status=500)
|
||||
|
||||
async def get_reconnect_suggestions(self, request: web.Request) -> web.Response:
|
||||
try:
|
||||
await self._ensure_dependencies_ready()
|
||||
recipe_scanner = self._recipe_scanner_getter()
|
||||
if recipe_scanner is None:
|
||||
raise RuntimeError("Recipe scanner unavailable")
|
||||
|
||||
recipe_id = request.match_info.get("recipe_id")
|
||||
lora_index_raw = request.match_info.get("lora_index")
|
||||
if not recipe_id or lora_index_raw is None:
|
||||
raise RecipeValidationError("recipe_id and lora_index are required")
|
||||
try:
|
||||
lora_index = int(lora_index_raw)
|
||||
except (TypeError, ValueError):
|
||||
raise RecipeValidationError("lora_index must be an integer")
|
||||
|
||||
result = await self._persistence_service.get_reconnect_suggestions(
|
||||
recipe_scanner=recipe_scanner,
|
||||
recipe_id=recipe_id,
|
||||
lora_index=lora_index,
|
||||
query=request.query.get("query") or None,
|
||||
)
|
||||
return web.json_response(result.payload, status=result.status)
|
||||
except RecipeValidationError as exc:
|
||||
return web.json_response({"error": str(exc)}, status=400)
|
||||
except RecipeNotFoundError as exc:
|
||||
return web.json_response({"error": str(exc)}, status=404)
|
||||
except Exception as exc:
|
||||
self._logger.error(
|
||||
"Error suggesting reconnect candidates: %s", exc, exc_info=True
|
||||
)
|
||||
return web.json_response({"error": str(exc)}, status=500)
|
||||
|
||||
async def mark_lora_hash_invalid(self, request: web.Request) -> web.Response:
|
||||
try:
|
||||
await self._ensure_dependencies_ready()
|
||||
recipe_scanner = self._recipe_scanner_getter()
|
||||
if recipe_scanner is None:
|
||||
raise RuntimeError("Recipe scanner unavailable")
|
||||
|
||||
data = await request.json()
|
||||
for field in ("recipe_id", "lora_index"):
|
||||
if field not in data:
|
||||
raise RecipeValidationError(f"Missing required field: {field}")
|
||||
|
||||
result = await self._persistence_service.mark_lora_hash_invalid(
|
||||
recipe_scanner=recipe_scanner,
|
||||
recipe_id=data["recipe_id"],
|
||||
lora_index=int(data["lora_index"]),
|
||||
hash_invalid=bool(data.get("hash_invalid", True)),
|
||||
)
|
||||
return web.json_response(result.payload, status=result.status)
|
||||
except RecipeValidationError as exc:
|
||||
return web.json_response({"error": str(exc)}, status=400)
|
||||
except RecipeNotFoundError as exc:
|
||||
return web.json_response({"error": str(exc)}, status=404)
|
||||
except Exception as exc:
|
||||
self._logger.error(
|
||||
"Error marking LoRA hash invalid: %s", exc, exc_info=True
|
||||
)
|
||||
return web.json_response({"error": str(exc)}, status=500)
|
||||
|
||||
async def reconnect_checkpoint(self, request: web.Request) -> web.Response:
|
||||
try:
|
||||
await self._ensure_dependencies_ready()
|
||||
recipe_scanner = self._recipe_scanner_getter()
|
||||
if recipe_scanner is None:
|
||||
raise RuntimeError("Recipe scanner unavailable")
|
||||
|
||||
data = await request.json()
|
||||
for field in ("recipe_id", "target_name"):
|
||||
if field not in data:
|
||||
raise RecipeValidationError(f"Missing required field: {field}")
|
||||
|
||||
result = await self._persistence_service.reconnect_checkpoint(
|
||||
recipe_scanner=recipe_scanner,
|
||||
recipe_id=data["recipe_id"],
|
||||
target_name=data["target_name"],
|
||||
)
|
||||
return web.json_response(result.payload, status=result.status)
|
||||
except RecipeValidationError as exc:
|
||||
return web.json_response({"error": str(exc)}, status=400)
|
||||
except RecipeNotFoundError as exc:
|
||||
return web.json_response({"error": str(exc)}, status=404)
|
||||
except Exception as exc:
|
||||
self._logger.error(
|
||||
"Error reconnecting checkpoint: %s", exc, exc_info=True
|
||||
)
|
||||
return web.json_response({"error": str(exc)}, status=500)
|
||||
|
||||
async def restore_checkpoint(self, request: web.Request) -> web.Response:
|
||||
try:
|
||||
await self._ensure_dependencies_ready()
|
||||
recipe_scanner = self._recipe_scanner_getter()
|
||||
if recipe_scanner is None:
|
||||
raise RuntimeError("Recipe scanner unavailable")
|
||||
|
||||
data = await request.json()
|
||||
if "recipe_id" not in data:
|
||||
raise RecipeValidationError("Missing required field: recipe_id")
|
||||
|
||||
result = await self._persistence_service.restore_checkpoint(
|
||||
recipe_scanner=recipe_scanner,
|
||||
recipe_id=data["recipe_id"],
|
||||
)
|
||||
return web.json_response(result.payload, status=result.status)
|
||||
except RecipeValidationError as exc:
|
||||
return web.json_response({"error": str(exc)}, status=400)
|
||||
except RecipeNotFoundError as exc:
|
||||
return web.json_response({"error": str(exc)}, status=404)
|
||||
except Exception as exc:
|
||||
self._logger.error("Error restoring checkpoint: %s", exc, exc_info=True)
|
||||
return web.json_response({"error": str(exc)}, status=500)
|
||||
|
||||
async def get_checkpoint_reconnect_suggestions(
|
||||
self, request: web.Request
|
||||
) -> web.Response:
|
||||
try:
|
||||
await self._ensure_dependencies_ready()
|
||||
recipe_scanner = self._recipe_scanner_getter()
|
||||
if recipe_scanner is None:
|
||||
raise RuntimeError("Recipe scanner unavailable")
|
||||
|
||||
recipe_id = request.match_info.get("recipe_id")
|
||||
if not recipe_id:
|
||||
raise RecipeValidationError("recipe_id is required")
|
||||
|
||||
result = await self._persistence_service.get_checkpoint_reconnect_suggestions(
|
||||
recipe_scanner=recipe_scanner,
|
||||
recipe_id=recipe_id,
|
||||
query=request.query.get("query") or None,
|
||||
)
|
||||
return web.json_response(result.payload, status=result.status)
|
||||
except RecipeValidationError as exc:
|
||||
return web.json_response({"error": str(exc)}, status=400)
|
||||
except RecipeNotFoundError as exc:
|
||||
return web.json_response({"error": str(exc)}, status=404)
|
||||
except Exception as exc:
|
||||
self._logger.error(
|
||||
"Error suggesting checkpoint reconnect candidates: %s",
|
||||
exc,
|
||||
exc_info=True,
|
||||
)
|
||||
return web.json_response({"error": str(exc)}, status=500)
|
||||
|
||||
async def mark_checkpoint_hash_invalid(self, request: web.Request) -> web.Response:
|
||||
try:
|
||||
await self._ensure_dependencies_ready()
|
||||
recipe_scanner = self._recipe_scanner_getter()
|
||||
if recipe_scanner is None:
|
||||
raise RuntimeError("Recipe scanner unavailable")
|
||||
|
||||
data = await request.json()
|
||||
if "recipe_id" not in data:
|
||||
raise RecipeValidationError("Missing required field: recipe_id")
|
||||
|
||||
result = await self._persistence_service.mark_checkpoint_hash_invalid(
|
||||
recipe_scanner=recipe_scanner,
|
||||
recipe_id=data["recipe_id"],
|
||||
hash_invalid=bool(data.get("hash_invalid", True)),
|
||||
)
|
||||
return web.json_response(result.payload, status=result.status)
|
||||
except RecipeValidationError as exc:
|
||||
return web.json_response({"error": str(exc)}, status=400)
|
||||
except RecipeNotFoundError as exc:
|
||||
return web.json_response({"error": str(exc)}, status=404)
|
||||
except Exception as exc:
|
||||
self._logger.error(
|
||||
"Error marking checkpoint hash invalid: %s", exc, exc_info=True
|
||||
)
|
||||
return web.json_response({"error": str(exc)}, status=500)
|
||||
|
||||
async def bulk_delete(self, request: web.Request) -> web.Response:
|
||||
try:
|
||||
await self._ensure_dependencies_ready()
|
||||
@@ -2024,6 +2267,23 @@ class RecipeManagementHandler:
|
||||
await self._download_remote_media(image_url)
|
||||
)
|
||||
|
||||
# Diagnostics for the recipe modal's "Why no LoRAs?" panel. This path
|
||||
# always comes from a CivitAI image URL (import_from_url validates the
|
||||
# image id), so civitai_image is True.
|
||||
diagnostics: Dict[str, Any] = {
|
||||
"civitai_image": True,
|
||||
"is_video": extension in (".mp4", ".webm"),
|
||||
}
|
||||
if isinstance(civitai_meta_raw, dict):
|
||||
raw_mvids = civitai_meta_raw.get("modelVersionIds")
|
||||
diagnostics["api_model_version_ids"] = (
|
||||
len(raw_mvids) if isinstance(raw_mvids, list) else 0
|
||||
)
|
||||
inner_meta_for_diag = civitai_meta_raw.get("meta")
|
||||
if isinstance(inner_meta_for_diag, dict):
|
||||
diagnostics["api_meta_present"] = True
|
||||
diagnostics["api_meta_keys"] = sorted(inner_meta_for_diag.keys())
|
||||
|
||||
# Build a version-cached map of local model hashes to cache items so
|
||||
# CivitaiApiMetadataParser can skip CivitAI API calls for models that
|
||||
# exist on disk. Built once and shared by every parse pass below.
|
||||
@@ -2044,6 +2304,7 @@ class RecipeManagementHandler:
|
||||
raw_embedded = await asyncio.to_thread(
|
||||
ExifUtils.extract_image_metadata, temp_img_path
|
||||
)
|
||||
diagnostics["exif_present"] = bool(raw_embedded)
|
||||
if raw_embedded:
|
||||
parser = (
|
||||
self._analysis_service._recipe_parser_factory.create_parser(
|
||||
@@ -2051,6 +2312,7 @@ class RecipeManagementHandler:
|
||||
)
|
||||
)
|
||||
if parser:
|
||||
diagnostics["exif_parser"] = parser.__class__.__name__
|
||||
if isinstance(parser, CivitaiApiMetadataParser):
|
||||
parsed_embedded = await parser.parse_metadata(
|
||||
raw_embedded,
|
||||
@@ -2091,6 +2353,7 @@ class RecipeManagementHandler:
|
||||
raw_orig = await asyncio.to_thread(
|
||||
ExifUtils.extract_image_metadata, orig_tmp_path
|
||||
)
|
||||
diagnostics["exif_present"] = bool(raw_orig)
|
||||
if raw_orig:
|
||||
parser = (
|
||||
self._analysis_service._recipe_parser_factory.create_parser(
|
||||
@@ -2098,6 +2361,7 @@ class RecipeManagementHandler:
|
||||
)
|
||||
)
|
||||
if parser:
|
||||
diagnostics["exif_parser"] = parser.__class__.__name__
|
||||
if isinstance(parser, CivitaiApiMetadataParser):
|
||||
parsed_embedded = await parser.parse_metadata(
|
||||
raw_orig,
|
||||
@@ -2183,14 +2447,21 @@ class RecipeManagementHandler:
|
||||
civitai_base_model = civitai_parsed.get("base_model")
|
||||
if civitai_base_model and not metadata.get("base_model"):
|
||||
metadata["base_model"] = civitai_base_model
|
||||
elif parsed_embedded:
|
||||
parsed_loras = parsed_embedded.get("loras")
|
||||
if parsed_loras and not metadata.get("loras"):
|
||||
metadata["loras"] = parsed_loras
|
||||
parsed_model = parsed_embedded.get("model")
|
||||
if parsed_model and not metadata.get("checkpoint"):
|
||||
metadata["checkpoint"] = parsed_model
|
||||
if parsed_embedded.get("base_model") and not metadata.get("base_model"):
|
||||
|
||||
# EXIF fills whatever the API-only parse left open — when the image
|
||||
# API meta is null (only modelVersionIds present) the API parse
|
||||
# yields a checkpoint but no LoRAs, while the image EXIF carries the
|
||||
# full resource list.
|
||||
if parsed_embedded:
|
||||
if not metadata.get("loras"):
|
||||
parsed_loras = parsed_embedded.get("loras")
|
||||
if parsed_loras:
|
||||
metadata["loras"] = parsed_loras
|
||||
if not metadata.get("checkpoint"):
|
||||
parsed_model = parsed_embedded.get("model")
|
||||
if parsed_model:
|
||||
metadata["checkpoint"] = parsed_model
|
||||
if not metadata.get("base_model") and parsed_embedded.get("base_model"):
|
||||
metadata["base_model"] = parsed_embedded["base_model"]
|
||||
|
||||
civitai_client = self._civitai_client_getter()
|
||||
@@ -2212,6 +2483,20 @@ class RecipeManagementHandler:
|
||||
else:
|
||||
name = f"Civitai Image {image_id}"
|
||||
|
||||
# Record why this import ended up with no LoRAs so the recipe modal
|
||||
# can explain it (collapsed by default).
|
||||
from ...services.recipes.import_info import (
|
||||
CHANNEL_REIMPORT_URL,
|
||||
CHANNEL_URL,
|
||||
build_import_info,
|
||||
)
|
||||
|
||||
metadata["import_info"] = build_import_info(
|
||||
CHANNEL_REIMPORT_URL if recipe_id else CHANNEL_URL,
|
||||
diagnostics,
|
||||
metadata.get("loras"),
|
||||
)
|
||||
|
||||
result = await self._persistence_service.save_recipe(
|
||||
recipe_scanner=recipe_scanner,
|
||||
image_bytes=image_bytes,
|
||||
@@ -2234,11 +2519,20 @@ class RecipeManagementHandler:
|
||||
target_dir: str | None,
|
||||
user_edits: dict[str, Any],
|
||||
old_title: str,
|
||||
persisted_source_path: str,
|
||||
) -> web.Response:
|
||||
"""Re-import a recipe from a local image file.
|
||||
|
||||
Reads the original source file, re-parses its EXIF metadata, saves a
|
||||
fresh recipe, then deletes the old one.
|
||||
Reads the original source file, re-parses its original embedded
|
||||
generation metadata (the appended recipe metadata block is ignored so
|
||||
the current parser gets a fresh pass), saves a new recipe, then deletes
|
||||
the old one.
|
||||
|
||||
``persisted_source_path`` is the source_path recorded on the new
|
||||
recipe: the external source file when one exists, or empty when the
|
||||
re-import fell back to the recipe's own previous preview image (that
|
||||
file is deleted with the old recipe, so recording it would leave a
|
||||
dangling path that blocks future re-imports).
|
||||
"""
|
||||
normalized = os.path.normpath(file_path)
|
||||
if not os.path.isfile(normalized):
|
||||
@@ -2254,6 +2548,7 @@ class RecipeManagementHandler:
|
||||
analysis_result = await self._analysis_service.analyze_local_image(
|
||||
file_path=normalized,
|
||||
recipe_scanner=recipe_scanner,
|
||||
ignore_recipe_metadata=True,
|
||||
)
|
||||
analysis_payload: dict[str, Any] = analysis_result.payload
|
||||
|
||||
@@ -2266,11 +2561,22 @@ class RecipeManagementHandler:
|
||||
"base_model": base_model,
|
||||
"loras": loras,
|
||||
"gen_params": gen_params,
|
||||
"source_path": normalized,
|
||||
"source_path": persisted_source_path,
|
||||
}
|
||||
if checkpoint:
|
||||
metadata["checkpoint"] = checkpoint
|
||||
|
||||
from ...services.recipes.import_info import (
|
||||
CHANNEL_REIMPORT_LOCAL,
|
||||
build_import_info,
|
||||
)
|
||||
|
||||
metadata["import_info"] = build_import_info(
|
||||
CHANNEL_REIMPORT_LOCAL,
|
||||
analysis_payload.get("diagnostics"),
|
||||
loras,
|
||||
)
|
||||
|
||||
prompt = (
|
||||
gen_params.get("prompt")
|
||||
or gen_params.get("positivePrompt")
|
||||
@@ -2287,6 +2593,10 @@ class RecipeManagementHandler:
|
||||
metadata=metadata,
|
||||
extension=extension,
|
||||
target_dir=target_dir,
|
||||
# The source is the recipe's own already-optimized preview image;
|
||||
# store its bytes verbatim instead of re-compressing (which would
|
||||
# only degrade quality) and skip the metadata re-append.
|
||||
skip_optimize=True,
|
||||
)
|
||||
|
||||
await self._persistence_service.delete_recipe(
|
||||
@@ -2314,7 +2624,7 @@ class RecipeManagementHandler:
|
||||
"success": True,
|
||||
"old_recipe_id": recipe_id,
|
||||
"recipe_id": new_recipe_id,
|
||||
"source_path": normalized,
|
||||
"source_path": persisted_source_path,
|
||||
}
|
||||
)
|
||||
|
||||
|
||||
@@ -68,6 +68,8 @@ COMMON_ROUTE_DEFINITIONS: tuple[RouteDefinition, ...] = (
|
||||
"GET", "/api/lm/{prefix}/model-description", "get_model_description"
|
||||
),
|
||||
RouteDefinition("GET", "/api/lm/{prefix}/relative-paths", "get_relative_paths"),
|
||||
RouteDefinition("PUT", "/api/lm/{prefix}/active-filters", "update_active_filters"),
|
||||
RouteDefinition("GET", "/api/lm/{prefix}/active-filters", "get_active_filters"),
|
||||
RouteDefinition(
|
||||
"GET", "/api/lm/{prefix}/civitai/versions/{model_id}", "get_civitai_versions"
|
||||
),
|
||||
|
||||
@@ -49,6 +49,31 @@ ROUTE_DEFINITIONS: tuple[RouteDefinition, ...] = (
|
||||
RouteDefinition("POST", "/api/lm/recipe/move", "move_recipe"),
|
||||
RouteDefinition("POST", "/api/lm/recipes/move-bulk", "move_recipes_bulk"),
|
||||
RouteDefinition("POST", "/api/lm/recipe/lora/reconnect", "reconnect_lora"),
|
||||
RouteDefinition("POST", "/api/lm/recipe/lora/restore", "restore_lora"),
|
||||
RouteDefinition(
|
||||
"GET",
|
||||
"/api/lm/recipe/{recipe_id}/lora/{lora_index}/reconnect-suggestions",
|
||||
"get_reconnect_suggestions",
|
||||
),
|
||||
RouteDefinition(
|
||||
"POST", "/api/lm/recipe/lora/mark-hash-invalid", "mark_lora_hash_invalid"
|
||||
),
|
||||
RouteDefinition(
|
||||
"POST", "/api/lm/recipe/checkpoint/reconnect", "reconnect_checkpoint"
|
||||
),
|
||||
RouteDefinition(
|
||||
"POST", "/api/lm/recipe/checkpoint/restore", "restore_checkpoint"
|
||||
),
|
||||
RouteDefinition(
|
||||
"GET",
|
||||
"/api/lm/recipe/{recipe_id}/checkpoint/reconnect-suggestions",
|
||||
"get_checkpoint_reconnect_suggestions",
|
||||
),
|
||||
RouteDefinition(
|
||||
"POST",
|
||||
"/api/lm/recipe/checkpoint/mark-hash-invalid",
|
||||
"mark_checkpoint_hash_invalid",
|
||||
),
|
||||
RouteDefinition("GET", "/api/lm/recipes/find-duplicates", "find_duplicates"),
|
||||
RouteDefinition("POST", "/api/lm/recipes/bulk-delete", "bulk_delete"),
|
||||
RouteDefinition(
|
||||
|
||||
@@ -0,0 +1,135 @@
|
||||
"""In-memory store for the LoRA Manager page's active filters.
|
||||
|
||||
The manager page keeps its filter state in localStorage for its own
|
||||
restoration, but the ComfyUI node autocomplete runs in a potentially
|
||||
different browser/origin (or Electron shell) where that storage is not
|
||||
shared. This store mirrors the active filters server-side so the
|
||||
``/api/lm/{prefix}/relative-paths`` endpoint can inject them into
|
||||
autocomplete searches regardless of which client set them.
|
||||
|
||||
State is process-local and intentionally not persisted; the manager page
|
||||
re-pushes its restored state on load.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import logging
|
||||
from typing import Any, Dict, Optional
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
# Keys copied from the manager page's persisted filter snapshot.
|
||||
_FILTER_KEYS = (
|
||||
"baseModel",
|
||||
"tags",
|
||||
"autoTags",
|
||||
"modelTypes",
|
||||
"tagLogic",
|
||||
"license",
|
||||
)
|
||||
|
||||
|
||||
class ActiveFiltersStore:
|
||||
"""Process-local store of active filters, keyed by model type."""
|
||||
|
||||
_instance: Optional["ActiveFiltersStore"] = None
|
||||
|
||||
def __init__(self) -> None:
|
||||
self._filters: Dict[str, Dict[str, Any]] = {}
|
||||
|
||||
@classmethod
|
||||
def get_instance(cls) -> "ActiveFiltersStore":
|
||||
if cls._instance is None:
|
||||
cls._instance = cls()
|
||||
return cls._instance
|
||||
|
||||
@classmethod
|
||||
def reset_instance(cls) -> None:
|
||||
"""Drop the singleton (test isolation)."""
|
||||
cls._instance = None
|
||||
|
||||
def set_filters(self, model_type: str, payload: Dict[str, Any]) -> None:
|
||||
"""Replace the stored active filters for a model type.
|
||||
|
||||
Only recognized keys are kept; everything else is discarded.
|
||||
"""
|
||||
filters = payload.get("filters")
|
||||
sanitized: Dict[str, Any] = {
|
||||
"activeFolder": payload.get("activeFolder"),
|
||||
"recursiveSearch": bool(payload.get("recursiveSearch", True)),
|
||||
"filters": (
|
||||
{key: filters[key] for key in _FILTER_KEYS if key in filters}
|
||||
if isinstance(filters, dict)
|
||||
else None
|
||||
),
|
||||
}
|
||||
self._filters[model_type] = sanitized
|
||||
|
||||
def get_filters(self, model_type: str) -> Optional[Dict[str, Any]]:
|
||||
"""Return the stored payload for a model type, or None if unset."""
|
||||
return self._filters.get(model_type)
|
||||
|
||||
def clear(self, model_type: str) -> None:
|
||||
self._filters.pop(model_type, None)
|
||||
|
||||
|
||||
def active_filters_to_query_kwargs(payload: Optional[Dict[str, Any]]) -> Dict[str, Any]:
|
||||
"""Map a stored active-filters payload to ``search_relative_paths`` kwargs.
|
||||
|
||||
Mirrors the query-param mapping that the ComfyUI autocomplete used to
|
||||
build client-side from localStorage (web/comfyui/autocomplete.js).
|
||||
"""
|
||||
kwargs: Dict[str, Any] = {}
|
||||
if not payload:
|
||||
return kwargs
|
||||
|
||||
active_folder = payload.get("activeFolder")
|
||||
recursive = payload.get("recursiveSearch", True)
|
||||
|
||||
if active_folder and active_folder != "null":
|
||||
kwargs["folder"] = active_folder
|
||||
elif not recursive:
|
||||
# Root folder with recursion disabled mirrors the page list,
|
||||
# which matches only root-level files via folder=''.
|
||||
kwargs["folder"] = ""
|
||||
|
||||
filters = payload.get("filters")
|
||||
if isinstance(filters, dict):
|
||||
base_models = filters.get("baseModel")
|
||||
if isinstance(base_models, list):
|
||||
kwargs["base_models"] = [m for m in base_models if m]
|
||||
|
||||
for source_key, target_key in (("tags", "tags"), ("autoTags", "auto_tags")):
|
||||
states = filters.get(source_key)
|
||||
if isinstance(states, dict):
|
||||
mapped = {
|
||||
tag: state
|
||||
for tag, state in states.items()
|
||||
if state in ("include", "exclude")
|
||||
}
|
||||
if mapped:
|
||||
kwargs[target_key] = mapped
|
||||
|
||||
model_types = filters.get("modelTypes")
|
||||
if isinstance(model_types, list):
|
||||
kwargs["model_types"] = [t for t in model_types if t]
|
||||
|
||||
tag_logic = filters.get("tagLogic")
|
||||
if tag_logic:
|
||||
kwargs["tag_logic"] = tag_logic
|
||||
|
||||
license_filter = filters.get("license")
|
||||
if isinstance(license_filter, dict):
|
||||
no_credit = license_filter.get("noCredit")
|
||||
if no_credit == "include":
|
||||
kwargs["credit_required"] = False
|
||||
elif no_credit == "exclude":
|
||||
kwargs["credit_required"] = True
|
||||
allow_selling = license_filter.get("allowSelling")
|
||||
if allow_selling == "include":
|
||||
kwargs["allow_selling_generated_content"] = True
|
||||
elif allow_selling == "exclude":
|
||||
kwargs["allow_selling_generated_content"] = False
|
||||
|
||||
kwargs["recursive"] = recursive
|
||||
return kwargs
|
||||
@@ -82,6 +82,17 @@ CIVITAI_DOWNLOAD_URL_PREFIXES = (
|
||||
)
|
||||
|
||||
|
||||
def _is_no_uri_available_error(message: str) -> bool:
|
||||
"""Return True for aria2's "No URI available" transfer failure.
|
||||
|
||||
aria2 reports this when every URI for the transfer has become unusable.
|
||||
For CivitAI downloads this typically means the temporary signed URL
|
||||
expired mid-download; the transfer can be recovered by resolving a fresh
|
||||
signed URL and re-scheduling with ``continue=true``.
|
||||
"""
|
||||
return "no uri available" in message.lower()
|
||||
|
||||
|
||||
class Aria2Error(RuntimeError):
|
||||
"""Raised when aria2 integration fails."""
|
||||
|
||||
@@ -145,8 +156,11 @@ class Aria2Downloader:
|
||||
disappears (e.g. another download restarted the daemon and
|
||||
``close()`` cleared ``_transfers``) or the RPC becomes unreachable,
|
||||
the transfer is re-scheduled with ``continue=true`` so the download
|
||||
resumes from the on-disk ``.aria2`` control file. Recovery is bounded
|
||||
by ``MAX_TRANSFER_RECOVERY_ATTEMPTS``.
|
||||
resumes from the on-disk ``.aria2`` control file. The same
|
||||
re-scheduling happens when aria2 fails with "No URI available"
|
||||
(typically an expired CivitAI signed URL): a fresh URL is resolved
|
||||
and the partial download continues. Recovery is bounded by
|
||||
``MAX_TRANSFER_RECOVERY_ATTEMPTS``.
|
||||
"""
|
||||
|
||||
await self._ensure_process()
|
||||
@@ -201,7 +215,36 @@ class Aria2Downloader:
|
||||
completed_path = self._resolve_completed_path(status, save_path)
|
||||
return True, completed_path
|
||||
if state == "error":
|
||||
return False, status.get("errorMessage") or "aria2 download failed"
|
||||
error_message = status.get("errorMessage") or "aria2 download failed"
|
||||
if (
|
||||
_is_no_uri_available_error(error_message)
|
||||
and recovery_attempts < MAX_TRANSFER_RECOVERY_ATTEMPTS
|
||||
):
|
||||
# The signed URL (e.g. CivitAI's) expired before the
|
||||
# transfer finished. Re-registering resolves a fresh
|
||||
# URL and resumes from the on-disk partial payload and
|
||||
# .aria2 control file via ``continue=true``.
|
||||
recovery_attempts += 1
|
||||
logger.warning(
|
||||
"aria2 transfer %s failed with %r; refreshing the "
|
||||
"URL and resuming the partial download "
|
||||
"(attempt %d/%d)",
|
||||
download_id,
|
||||
error_message,
|
||||
recovery_attempts,
|
||||
MAX_TRANSFER_RECOVERY_ATTEMPTS,
|
||||
)
|
||||
await asyncio.sleep(1.0)
|
||||
await self._ensure_process()
|
||||
async with self._register_lock:
|
||||
transfer = await self._register_transfer(
|
||||
url,
|
||||
save_path,
|
||||
download_id=download_id,
|
||||
headers=headers,
|
||||
)
|
||||
continue
|
||||
return False, error_message
|
||||
if state == "removed":
|
||||
return False, "Download was cancelled"
|
||||
|
||||
|
||||
@@ -1295,6 +1295,27 @@ class BaseModelService(ABC):
|
||||
path_for_sorting,
|
||||
)
|
||||
|
||||
@staticmethod
|
||||
def _relative_path_folder_group_sort_key(
|
||||
relative_path: str, include_terms: List[str]
|
||||
) -> tuple:
|
||||
"""Group paths by folder, then sort by relevance within each group.
|
||||
|
||||
Folders are ordered alphabetically (case-insensitive) by their full
|
||||
folder path, with root-level files (empty folder) first. Within a
|
||||
folder, paths keep the relevance ordering of
|
||||
``_relative_path_sort_key``. This keeps same-folder entries together
|
||||
in the autocomplete dropdown instead of interleaving them by filename.
|
||||
"""
|
||||
path_for_sorting = BaseModelService._remove_model_extension(
|
||||
relative_path.lower()
|
||||
)
|
||||
folder = path_for_sorting.rpartition(os.sep)[0]
|
||||
|
||||
return (folder,) + BaseModelService._relative_path_sort_key(
|
||||
relative_path, include_terms
|
||||
)
|
||||
|
||||
async def search_relative_paths(
|
||||
self,
|
||||
search_term: str,
|
||||
@@ -1404,9 +1425,13 @@ class BaseModelService(ABC):
|
||||
):
|
||||
matching_paths.append(relative_path)
|
||||
|
||||
# Sort by relevance (prefix and earliest hits first, then by length and alphabetically)
|
||||
# Group by folder (root first, then alphabetically) and sort by
|
||||
# relevance (prefix and earliest hits, then length and alphabetically)
|
||||
# within each folder group.
|
||||
matching_paths.sort(
|
||||
key=lambda relative: self._relative_path_sort_key(relative, include_terms)
|
||||
key=lambda relative: self._relative_path_folder_group_sort_key(
|
||||
relative, include_terms
|
||||
)
|
||||
)
|
||||
|
||||
# Apply offset and limit
|
||||
|
||||
@@ -20,6 +20,11 @@ from .recipes import (
|
||||
RecipeDownloadError,
|
||||
RecipeNotFoundError,
|
||||
)
|
||||
from .recipes.import_info import (
|
||||
CHANNEL_BATCH_IMPORT_LOCAL,
|
||||
CHANNEL_BATCH_IMPORT_URL,
|
||||
build_import_info,
|
||||
)
|
||||
|
||||
|
||||
class ImportItemType(Enum):
|
||||
@@ -624,6 +629,17 @@ class BatchImportService:
|
||||
"loras": loras,
|
||||
"gen_params": payload.get("gen_params", {}),
|
||||
"source_path": item.source,
|
||||
# Record why this import ended up with no LoRAs so the
|
||||
# recipe modal can explain it (collapsed by default).
|
||||
"import_info": build_import_info(
|
||||
(
|
||||
CHANNEL_BATCH_IMPORT_URL
|
||||
if item.item_type == ImportItemType.URL
|
||||
else CHANNEL_BATCH_IMPORT_LOCAL
|
||||
),
|
||||
payload.get("diagnostics"),
|
||||
loras,
|
||||
),
|
||||
}
|
||||
|
||||
if payload.get("checkpoint"):
|
||||
|
||||
@@ -21,7 +21,7 @@ from .model_metadata_provider import (
|
||||
from .downloader import get_downloader
|
||||
from .errors import RateLimitError, ResourceNotFoundError
|
||||
from ..utils.civitai_utils import resolve_license_payload
|
||||
from ..utils.constants import MODEL_WEIGHT_FILE_TYPES
|
||||
from ..utils.constants import MODEL_WEIGHT_FILE_TYPES, is_empty_placeholder_hash
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
@@ -180,6 +180,11 @@ class CivitaiClient:
|
||||
async def get_model_by_hash(
|
||||
self, model_hash: str
|
||||
) -> Tuple[Optional[Dict[str, Any]], Optional[str]]:
|
||||
if is_empty_placeholder_hash(model_hash):
|
||||
# The empty-hash placeholder (SHA256 of an empty byte string)
|
||||
# matches no real file; CivitAI's by-hash index can contain
|
||||
# polluted entries for it, so never resolve it.
|
||||
return None, "Model not found"
|
||||
try:
|
||||
success, version = await self._make_request(
|
||||
"GET",
|
||||
@@ -503,6 +508,8 @@ class CivitaiClient:
|
||||
async def _fetch_version_by_hash(self, model_hash: Optional[str]) -> Optional[Dict[str, Any]]:
|
||||
if not model_hash:
|
||||
return None
|
||||
if is_empty_placeholder_hash(model_hash):
|
||||
return None
|
||||
|
||||
success, version = await self._make_request(
|
||||
"GET",
|
||||
|
||||
@@ -717,6 +717,47 @@ class DownloadManager:
|
||||
await asyncio.sleep(delay)
|
||||
return False
|
||||
|
||||
@staticmethod
|
||||
def _reconcile_failed_aria2_partial(save_path: str) -> None:
|
||||
"""Reconcile on-disk partial state after a failed aria2 transfer.
|
||||
|
||||
The payload and its ``.aria2`` control file form a resumable pair and
|
||||
are preserved together so a retry (with a refreshed URL when needed)
|
||||
can resume via aria2's ``continue=true``. A control file without its
|
||||
payload cannot resume anything, so the orphan is reported and removed.
|
||||
"""
|
||||
control_path = f"{save_path}.aria2"
|
||||
payload_exists = os.path.exists(save_path)
|
||||
control_exists = os.path.exists(control_path)
|
||||
|
||||
if payload_exists and not control_exists:
|
||||
# If the .aria2 control file is missing, aria2 considers the
|
||||
# download complete. A transient RPC failure may have made us
|
||||
# think the download failed even though the file is fully on disk.
|
||||
# Keep the file so a retry can find it already complete.
|
||||
logger.warning(
|
||||
"aria2 download reported failure but .aria2 file is absent "
|
||||
"for %s — the file is likely complete. Preserving it for retry.",
|
||||
save_path,
|
||||
)
|
||||
elif payload_exists and control_exists:
|
||||
logger.info(
|
||||
"Preserving aria2 partial download for resume: %s", save_path
|
||||
)
|
||||
elif control_exists:
|
||||
logger.warning(
|
||||
"Orphaned aria2 control file without payload: %s — removing it",
|
||||
control_path,
|
||||
)
|
||||
try:
|
||||
os.remove(control_path)
|
||||
except OSError as exc:
|
||||
logger.warning(
|
||||
"Failed to remove orphaned aria2 control file %s: %s",
|
||||
control_path,
|
||||
exc,
|
||||
)
|
||||
|
||||
async def _cleanup_cancelled_download_files(
|
||||
self,
|
||||
download_id: str,
|
||||
@@ -1226,6 +1267,24 @@ class DownloadManager:
|
||||
)
|
||||
continue
|
||||
|
||||
if not os.path.exists(save_path) and os.path.exists(control_path):
|
||||
# A control file without its payload cannot resume
|
||||
# anything; report it and clean up the orphan.
|
||||
logger.warning(
|
||||
"Orphaned aria2 control file without payload for %s: "
|
||||
"%s — removing it",
|
||||
download_id,
|
||||
control_path,
|
||||
)
|
||||
try:
|
||||
os.remove(control_path)
|
||||
except OSError as exc:
|
||||
logger.warning(
|
||||
"Failed to remove orphaned aria2 control file %s: %s",
|
||||
control_path,
|
||||
exc,
|
||||
)
|
||||
|
||||
await self._aria2_state_store.remove(download_id)
|
||||
|
||||
self._restored_persisted_downloads = True
|
||||
@@ -2423,20 +2482,8 @@ class DownloadManager:
|
||||
break
|
||||
|
||||
last_error = result
|
||||
# For aria2: if the .aria2 control file is missing, aria2 considers
|
||||
# the download complete. A transient RPC failure may have made us
|
||||
# think the download failed even though the file is fully on disk.
|
||||
# Keep the file so a retry can find it already complete.
|
||||
if (
|
||||
transfer_backend == "aria2"
|
||||
and os.path.exists(save_path)
|
||||
and not os.path.exists(f"{save_path}.aria2")
|
||||
):
|
||||
logger.warning(
|
||||
"aria2 download reported failure but .aria2 file is absent "
|
||||
"for %s — the file is likely complete. Preserving it for retry.",
|
||||
save_path,
|
||||
)
|
||||
if transfer_backend == "aria2":
|
||||
self._reconcile_failed_aria2_partial(save_path)
|
||||
elif os.path.exists(save_path):
|
||||
try:
|
||||
os.remove(save_path)
|
||||
|
||||
@@ -1,6 +1,8 @@
|
||||
from typing import Dict, Optional, Set, List
|
||||
import os
|
||||
|
||||
from ..utils.constants import is_empty_placeholder_hash
|
||||
|
||||
class ModelHashIndex:
|
||||
"""Index for looking up models by hash or filename"""
|
||||
|
||||
@@ -81,6 +83,8 @@ class ModelHashIndex:
|
||||
# mapping. First-time registrations stay O(1).
|
||||
if autov3:
|
||||
autov3 = autov3.lower()
|
||||
if is_empty_placeholder_hash(autov3):
|
||||
autov3 = None
|
||||
if is_re_registration and (existing_hash != sha256 or autov3):
|
||||
stale_autov3_keys = [
|
||||
key for key, mapped_path in self._autov3_to_path.items()
|
||||
@@ -93,7 +97,7 @@ class ModelHashIndex:
|
||||
|
||||
def add_autov3(self, autov3: str, file_path: str) -> None:
|
||||
"""Add or update an AutoV3-only index entry (used when only AutoV3 is known)"""
|
||||
if not autov3:
|
||||
if not autov3 or is_empty_placeholder_hash(autov3):
|
||||
return
|
||||
autov3 = autov3.lower()
|
||||
self._autov3_to_path[autov3] = file_path
|
||||
@@ -250,6 +254,8 @@ class ModelHashIndex:
|
||||
|
||||
def has_hash(self, hash_value: str) -> bool:
|
||||
"""Check if hash exists in index (SHA256, AutoV2, or AutoV3)"""
|
||||
if is_empty_placeholder_hash(hash_value):
|
||||
return False
|
||||
normalized = hash_value.lower()
|
||||
if normalized in self._hash_to_path:
|
||||
return True
|
||||
@@ -261,6 +267,8 @@ class ModelHashIndex:
|
||||
|
||||
def get_path(self, hash_value: str) -> Optional[str]:
|
||||
"""Get file path for a hash (SHA256, AutoV2, or AutoV3)"""
|
||||
if is_empty_placeholder_hash(hash_value):
|
||||
return None
|
||||
normalized = hash_value.lower()
|
||||
path = self._hash_to_path.get(normalized)
|
||||
if path is not None:
|
||||
|
||||
+137
-16
@@ -66,6 +66,14 @@ def _is_hidden_relative_path(rel_path: str) -> bool:
|
||||
# requests (modal open + autocomplete) do not re-walk the model roots.
|
||||
ALL_FOLDERS_CACHE_TTL_SECONDS = 5.0
|
||||
|
||||
# Maps a scanner model type to the manager page type used in progress
|
||||
# broadcasts (e.g. 'lora' -> 'loras').
|
||||
PAGE_TYPE_MAP = {
|
||||
'lora': 'loras',
|
||||
'checkpoint': 'checkpoints',
|
||||
'embedding': 'embeddings',
|
||||
}
|
||||
|
||||
|
||||
def _is_pending_delete_path(path: str) -> bool:
|
||||
"""Return True when any path component is the pending-delete staging dir."""
|
||||
@@ -149,6 +157,38 @@ class ModelScanner:
|
||||
# Register this service
|
||||
asyncio.create_task(self._register_service())
|
||||
|
||||
@property
|
||||
def page_type(self) -> str:
|
||||
"""Manager page type used in progress broadcasts (e.g. 'loras')."""
|
||||
return PAGE_TYPE_MAP.get(self.model_type, self.model_type)
|
||||
|
||||
async def _broadcast_scan_progress(
|
||||
self,
|
||||
status: str,
|
||||
stage: str,
|
||||
progress: int,
|
||||
full_rebuild: bool,
|
||||
**extra: Any,
|
||||
) -> None:
|
||||
"""Broadcast manual-refresh scan progress on the generic WS channel.
|
||||
|
||||
Best-effort only: broadcast failures must never affect the scan itself.
|
||||
"""
|
||||
payload: Dict[str, Any] = {
|
||||
'type': 'scan_progress',
|
||||
'status': status,
|
||||
'model_type': self.model_type,
|
||||
'pageType': self.page_type,
|
||||
'stage': stage,
|
||||
'full_rebuild': full_rebuild,
|
||||
'progress': progress,
|
||||
}
|
||||
payload.update(extra)
|
||||
try:
|
||||
await ws_manager.broadcast(payload)
|
||||
except Exception as exc: # pragma: no cover - defensive logging
|
||||
logger.error(f"Error broadcasting scan progress for {self.model_type}: {exc}")
|
||||
|
||||
@property
|
||||
def cache_version(self) -> int:
|
||||
"""Monotonic version counter for the in-memory cache.
|
||||
@@ -434,12 +474,7 @@ class ModelScanner:
|
||||
self._is_initializing = True
|
||||
|
||||
# Determine the page type based on model type
|
||||
page_type_map = {
|
||||
'lora': 'loras',
|
||||
'checkpoint': 'checkpoints',
|
||||
'embedding': 'embeddings'
|
||||
}
|
||||
page_type = page_type_map.get(self.model_type, self.model_type)
|
||||
page_type = self.page_type
|
||||
|
||||
# First, try to load from cache
|
||||
await ws_manager.broadcast_init_progress({
|
||||
@@ -804,7 +839,7 @@ class ModelScanner:
|
||||
last_progress_time = time.time()
|
||||
last_progress_percent = 0
|
||||
|
||||
async def progress_callback(processed_files: int, expected_total: int) -> None:
|
||||
async def progress_callback(processed_files: int, expected_total: int, current_name: str = '') -> None:
|
||||
nonlocal last_progress_time, last_progress_percent
|
||||
|
||||
if expected_total <= 0:
|
||||
@@ -871,32 +906,84 @@ class ModelScanner:
|
||||
async def _initialize_cache(self) -> None:
|
||||
"""Initialize or refresh the cache"""
|
||||
self._is_initializing = True # Set flag
|
||||
last_progress_percent = 0
|
||||
try:
|
||||
start_time = time.time()
|
||||
|
||||
|
||||
await self._broadcast_scan_progress('started', 'scan_folders', 0, True)
|
||||
|
||||
# Manually trigger a symlink rescan during a full rebuild.
|
||||
# This ensures that any new symlink mappings are correctly picked up.
|
||||
config.rebuild_symlink_cache()
|
||||
|
||||
# Determine the page type based on model type
|
||||
# Count files in a thread so the event loop stays responsive
|
||||
loop = asyncio.get_running_loop()
|
||||
total_files = await loop.run_in_executor(None, self._count_model_files)
|
||||
await self._broadcast_scan_progress(
|
||||
'processing', 'count_models', 1, True,
|
||||
processed=0, total=total_files,
|
||||
)
|
||||
|
||||
last_progress_time = time.time()
|
||||
|
||||
async def progress_callback(processed_files: int, expected_total: int, current_name: str = '') -> None:
|
||||
nonlocal last_progress_time, last_progress_percent
|
||||
|
||||
if expected_total <= 0:
|
||||
return
|
||||
|
||||
current_time = time.time()
|
||||
progress_percent = min(99, int(1 + (processed_files / expected_total) * 98))
|
||||
|
||||
if progress_percent <= last_progress_percent:
|
||||
return
|
||||
|
||||
if current_time - last_progress_time <= 0.5 and processed_files != expected_total:
|
||||
return
|
||||
|
||||
last_progress_percent = progress_percent
|
||||
last_progress_time = current_time
|
||||
|
||||
await self._broadcast_scan_progress(
|
||||
'processing', 'process_models', progress_percent, True,
|
||||
processed=processed_files, total=expected_total,
|
||||
current_name=current_name,
|
||||
)
|
||||
|
||||
# Scan for new data
|
||||
scan_result = await self._gather_model_data()
|
||||
scan_result = await self._gather_model_data(
|
||||
total_files=total_files,
|
||||
progress_callback=progress_callback,
|
||||
)
|
||||
if not self.is_cancelled():
|
||||
await self._broadcast_scan_progress('finalizing', 'finalizing', 99, True)
|
||||
await self._apply_scan_result(scan_result)
|
||||
await self._save_persistent_cache(scan_result)
|
||||
await self._sync_download_history(scan_result.raw_data, source='scan')
|
||||
await self._broadcast_scan_progress(
|
||||
'completed', 'finalizing', 100, True,
|
||||
elapsed_seconds=time.time() - start_time,
|
||||
)
|
||||
|
||||
logger.info(
|
||||
f"{self.model_type.capitalize()} Scanner: Cache initialization completed in {time.time() - start_time:.2f} seconds, "
|
||||
f"found {len(scan_result.raw_data)} models"
|
||||
)
|
||||
else:
|
||||
await self._broadcast_scan_progress(
|
||||
'cancelled', 'process_models', last_progress_percent, True,
|
||||
elapsed_seconds=time.time() - start_time,
|
||||
)
|
||||
logger.info(
|
||||
f"{self.model_type.capitalize()} Scanner: Cache initialization cancelled "
|
||||
f"after {time.time() - start_time:.2f} seconds"
|
||||
)
|
||||
except Exception as e:
|
||||
logger.error(f"{self.model_type.capitalize()} Scanner: Error initializing cache: {e}")
|
||||
await self._broadcast_scan_progress(
|
||||
'error', 'process_models', last_progress_percent, True,
|
||||
error=str(e),
|
||||
)
|
||||
# Ensure cache is at least an empty structure on error
|
||||
if self._cache is None:
|
||||
self._cache = ModelCache(
|
||||
@@ -914,6 +1001,8 @@ class ModelScanner:
|
||||
try:
|
||||
start_time = time.time()
|
||||
logger.info(f"{self.model_type.capitalize()} Scanner: Starting fast cache reconciliation...")
|
||||
|
||||
await self._broadcast_scan_progress('started', 'reconcile_scan', 0, False)
|
||||
|
||||
# Get current cached file paths
|
||||
cached_paths = {item['file_path'] for item in self._cache.raw_data}
|
||||
@@ -987,6 +1076,10 @@ class ModelScanner:
|
||||
await asyncio.sleep(0)
|
||||
if self.is_cancelled():
|
||||
logger.info(f"{self.model_type.capitalize()} Scanner: Reconcile scan cancelled")
|
||||
await self._broadcast_scan_progress(
|
||||
'cancelled', 'reconcile_scan', 0, False,
|
||||
elapsed_seconds=time.time() - start_time,
|
||||
)
|
||||
return
|
||||
|
||||
# Process new files in batches
|
||||
@@ -994,10 +1087,14 @@ class ModelScanner:
|
||||
if new_files:
|
||||
logger.info(f"{self.model_type.capitalize()} Scanner: Found {len(new_files)} new files to process")
|
||||
batch_size = 50
|
||||
for i in range(0, len(new_files), batch_size):
|
||||
total_new = len(new_files)
|
||||
processed_new = 0
|
||||
last_progress_time = time.time()
|
||||
for i in range(0, total_new, batch_size):
|
||||
batch = new_files[i:i+batch_size]
|
||||
for path in batch:
|
||||
logger.info(f"{self.model_type.capitalize()} Scanner: Processing {path}")
|
||||
processed_new += 1
|
||||
try:
|
||||
# Find the appropriate root path for this file
|
||||
root_path = None
|
||||
@@ -1053,9 +1150,24 @@ class ModelScanner:
|
||||
logger.error(f"Could not determine root path for {path}")
|
||||
except Exception as e:
|
||||
logger.error(f"Error adding {path} to cache: {e}")
|
||||
|
||||
|
||||
current_time = time.time()
|
||||
if current_time - last_progress_time > 0.5 or processed_new == total_new:
|
||||
last_progress_time = current_time
|
||||
await self._broadcast_scan_progress(
|
||||
'processing', 'process_new',
|
||||
min(99, int(1 + (processed_new / total_new) * 98)), False,
|
||||
processed=processed_new, total=total_new,
|
||||
current_name=os.path.basename(path),
|
||||
)
|
||||
|
||||
if self.is_cancelled():
|
||||
logger.info(f"{self.model_type.capitalize()} Scanner: Reconcile processing cancelled")
|
||||
await self._broadcast_scan_progress(
|
||||
'cancelled', 'process_new',
|
||||
min(99, int(1 + (processed_new / total_new) * 98)), False,
|
||||
elapsed_seconds=time.time() - start_time,
|
||||
)
|
||||
return
|
||||
|
||||
# Find missing files (in cache but not in filesystem)
|
||||
@@ -1121,8 +1233,17 @@ class ModelScanner:
|
||||
await self._persist_current_cache()
|
||||
|
||||
logger.info(f"{self.model_type.capitalize()} Scanner: Cache reconciliation completed in {time.time() - start_time:.2f} seconds. Added {total_added}, removed {total_removed} models.")
|
||||
await self._broadcast_scan_progress(
|
||||
'completed', 'process_new', 100, False,
|
||||
added=total_added, removed=total_removed,
|
||||
elapsed_seconds=time.time() - start_time,
|
||||
)
|
||||
except Exception as e:
|
||||
logger.error(f"{self.model_type.capitalize()} Scanner: Error reconciling cache: {e}", exc_info=True)
|
||||
await self._broadcast_scan_progress(
|
||||
'error', 'reconcile_scan', 0, False,
|
||||
error=str(e),
|
||||
)
|
||||
finally:
|
||||
self._is_initializing = False # Unset flag
|
||||
self.bump_cache_version()
|
||||
@@ -1498,7 +1619,7 @@ class ModelScanner:
|
||||
self,
|
||||
*,
|
||||
total_files: int = 0,
|
||||
progress_callback: Optional[Callable[[int, int], Awaitable[None]]] = None
|
||||
progress_callback: Optional[Callable[[int, int, str], Awaitable[None]]] = None
|
||||
) -> CacheBuildResult:
|
||||
"""Collect metadata for all model files."""
|
||||
|
||||
@@ -1510,11 +1631,11 @@ class ModelScanner:
|
||||
processed_real_files: Set[str] = set()
|
||||
visited_real_dirs: Set[str] = set()
|
||||
|
||||
async def handle_progress() -> None:
|
||||
async def handle_progress(current_name: str = '') -> None:
|
||||
if progress_callback is None:
|
||||
return
|
||||
try:
|
||||
await progress_callback(processed_files, total_files)
|
||||
await progress_callback(processed_files, total_files, current_name)
|
||||
except Exception as exc: # pragma: no cover - defensive logging
|
||||
logger.error(f"Error reporting progress for {self.model_type}: {exc}")
|
||||
|
||||
@@ -1580,7 +1701,7 @@ class ModelScanner:
|
||||
for tag in result.get('tags') or []:
|
||||
tags_count[tag] = tags_count.get(tag, 0) + 1
|
||||
|
||||
await handle_progress()
|
||||
await handle_progress(entry.name)
|
||||
await asyncio.sleep(0)
|
||||
if self.is_cancelled():
|
||||
return
|
||||
|
||||
@@ -59,6 +59,7 @@ class PersistentRecipeCache:
|
||||
"gen_params_json",
|
||||
"tags_json",
|
||||
"has_workflow",
|
||||
"import_info_json",
|
||||
)
|
||||
_instances: Dict[str, "PersistentRecipeCache"] = {}
|
||||
_instance_lock = threading.Lock()
|
||||
@@ -447,7 +448,8 @@ class PersistentRecipeCache:
|
||||
checkpoint_json TEXT,
|
||||
gen_params_json TEXT,
|
||||
tags_json TEXT,
|
||||
has_workflow INTEGER DEFAULT 0
|
||||
has_workflow INTEGER DEFAULT 0,
|
||||
import_info_json TEXT
|
||||
);
|
||||
|
||||
CREATE INDEX IF NOT EXISTS idx_recipes_json_path ON recipes(json_path);
|
||||
@@ -473,6 +475,13 @@ class PersistentRecipeCache:
|
||||
)
|
||||
except Exception:
|
||||
pass # column already exists
|
||||
# Migration: add import_info_json column to existing databases
|
||||
try:
|
||||
conn.execute(
|
||||
"ALTER TABLE recipes ADD COLUMN import_info_json TEXT"
|
||||
)
|
||||
except Exception:
|
||||
pass # column already exists
|
||||
conn.commit()
|
||||
self._schema_initialized = True
|
||||
except Exception as exc:
|
||||
@@ -504,6 +513,9 @@ class PersistentRecipeCache:
|
||||
tags = recipe.get("tags")
|
||||
tags_json = json.dumps(tags) if tags else None
|
||||
|
||||
import_info = recipe.get("import_info")
|
||||
import_info_json = json.dumps(import_info) if import_info else None
|
||||
|
||||
# Get file stats if json_path exists
|
||||
file_mtime = 0.0
|
||||
file_size = 0
|
||||
@@ -536,6 +548,7 @@ class PersistentRecipeCache:
|
||||
gen_params_json,
|
||||
tags_json,
|
||||
1 if recipe.get("has_workflow") else 0,
|
||||
import_info_json,
|
||||
)
|
||||
|
||||
def _row_to_recipe(self, row: sqlite3.Row) -> Dict[str, Any]:
|
||||
@@ -568,6 +581,13 @@ class PersistentRecipeCache:
|
||||
except json.JSONDecodeError:
|
||||
pass
|
||||
|
||||
import_info = None
|
||||
if row["import_info_json"]:
|
||||
try:
|
||||
import_info = json.loads(row["import_info_json"])
|
||||
except json.JSONDecodeError:
|
||||
pass
|
||||
|
||||
recipe = {
|
||||
"id": row["recipe_id"],
|
||||
"file_path": row["file_path"] or "",
|
||||
@@ -592,6 +612,9 @@ class PersistentRecipeCache:
|
||||
if checkpoint:
|
||||
recipe["checkpoint"] = checkpoint
|
||||
|
||||
if import_info:
|
||||
recipe["import_info"] = import_info
|
||||
|
||||
return recipe
|
||||
|
||||
|
||||
|
||||
+729
-13
@@ -5,6 +5,8 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
import copy
|
||||
import difflib
|
||||
import json
|
||||
import logging
|
||||
import os
|
||||
@@ -18,7 +20,11 @@ from ..utils.file_utils import calculate_autov3
|
||||
from ..utils.recipe_open_stats import RecipeOpenStats
|
||||
from .model_scanner import WEIGHT_FILE_EXTENSIONS
|
||||
from .recipe_cache import RecipeCache
|
||||
from .recipes.errors import RecipeNotFoundError, RecipePersistenceError
|
||||
from .recipes.errors import (
|
||||
RecipeNotFoundError,
|
||||
RecipePersistenceError,
|
||||
RecipeValidationError,
|
||||
)
|
||||
from .websocket_manager import ws_manager
|
||||
from natsort import natsorted
|
||||
import sys
|
||||
@@ -42,6 +48,12 @@ _CHECKPOINT_MODEL_TYPE_ALIASES = {"diffusionmodel": "diffusion_model"}
|
||||
# Valid LoRA availability statuses for the recipe listing filter.
|
||||
_VALID_LORA_AVAILABILITY_STATUSES = frozenset({"ready", "missing", "deleted"})
|
||||
|
||||
# Filter marker for recipes whose base model could not be determined
|
||||
# (base_model is None or empty). The UI displays "Unknown" for this bucket;
|
||||
# the marker keeps the semantics explicit and disjoint from any real base
|
||||
# model string.
|
||||
UNKNOWN_BASE_MODEL_FILTER = "__unknown__"
|
||||
|
||||
|
||||
class RecipeScanner:
|
||||
"""Service for scanning and managing recipe images"""
|
||||
@@ -240,12 +252,257 @@ class RecipeScanner:
|
||||
self._local_filename_cache_versions = versions
|
||||
return cache
|
||||
|
||||
@staticmethod
|
||||
def _strip_weight_extension(name: str) -> str:
|
||||
"""Strip a known weight-file extension, preserving the original case."""
|
||||
lower = name.lower()
|
||||
for ext in sorted(WEIGHT_FILE_EXTENSIONS, key=len, reverse=True):
|
||||
if lower.endswith(ext):
|
||||
return name[: -len(ext)]
|
||||
return name
|
||||
|
||||
async def suggest_reconnect_candidates(
|
||||
self,
|
||||
*,
|
||||
entry: dict[str, Any],
|
||||
recipe_base_model: Optional[str],
|
||||
query: Optional[str] = None,
|
||||
limit: int = 5,
|
||||
) -> list[dict[str, Any]]:
|
||||
"""Rank local LoRAs as reconnect candidates for a broken recipe entry.
|
||||
|
||||
Thin wrapper over ``_suggest_reconnect_candidates`` scoped to the
|
||||
LoRA library (see it for the ranking contract).
|
||||
"""
|
||||
return await self._suggest_reconnect_candidates(
|
||||
entry=entry,
|
||||
recipe_base_model=recipe_base_model,
|
||||
query=query,
|
||||
limit=limit,
|
||||
is_checkpoint=False,
|
||||
)
|
||||
|
||||
async def suggest_checkpoint_reconnect_candidates(
|
||||
self,
|
||||
*,
|
||||
entry: dict[str, Any],
|
||||
recipe_base_model: Optional[str],
|
||||
query: Optional[str] = None,
|
||||
limit: int = 5,
|
||||
) -> list[dict[str, Any]]:
|
||||
"""Rank local checkpoints as reconnect candidates for a broken entry.
|
||||
|
||||
Thin wrapper over ``_suggest_reconnect_candidates`` scoped to the
|
||||
checkpoint library (see it for the ranking contract).
|
||||
"""
|
||||
return await self._suggest_reconnect_candidates(
|
||||
entry=entry,
|
||||
recipe_base_model=recipe_base_model,
|
||||
query=query,
|
||||
limit=limit,
|
||||
is_checkpoint=True,
|
||||
)
|
||||
|
||||
async def _suggest_reconnect_candidates(
|
||||
self,
|
||||
*,
|
||||
entry: dict[str, Any],
|
||||
recipe_base_model: Optional[str],
|
||||
query: Optional[str] = None,
|
||||
limit: int = 5,
|
||||
is_checkpoint: bool,
|
||||
) -> list[dict[str, Any]]:
|
||||
"""Rank local models as reconnect candidates for a broken recipe entry.
|
||||
|
||||
Identity signals (same hash / same CivitAI model version) outrank
|
||||
similarity signals (filename / model name fuzzy match). A confident
|
||||
base-model mismatch (both sides known and different) is a hard
|
||||
rejection here. This is deliberately stricter than reconnect itself,
|
||||
which tolerates same-architecture-family labels (Pony ↔ Illustrious):
|
||||
suggestions trade recall for a noise-free list, and the input box
|
||||
remains available for deliberate cross-family picks. Unknown on
|
||||
either side stays eligible, matching ``find_matching_models``.
|
||||
When ``query`` is given
|
||||
(search-as-you-type), identity signals are skipped and both
|
||||
similarity signals score against the query, with a substring hit
|
||||
(query of 3+ chars) flooring that signal's ratio at 0.8.
|
||||
|
||||
The name-similarity threshold (0.65) is stricter than the filename
|
||||
one (0.55): long generic names share tokens like "style"/"pony" and
|
||||
score deceptively high (measured 0.638 for unrelated models), while
|
||||
filenames are the authoritative match key and get more slack.
|
||||
"""
|
||||
if limit <= 0 or not isinstance(entry, dict):
|
||||
return []
|
||||
|
||||
scanner = self._checkpoint_scanner if is_checkpoint else self._lora_scanner
|
||||
if scanner is None:
|
||||
return []
|
||||
|
||||
data = await scanner.get_cached_data()
|
||||
recipe_bm = (recipe_base_model or "").strip().casefold()
|
||||
|
||||
def _base_model_known_mismatch(item: dict[str, Any]) -> bool:
|
||||
"""Confident mismatch only — unknown on either side stays eligible."""
|
||||
if not recipe_bm or recipe_bm == "unknown":
|
||||
return False
|
||||
item_bm = (item.get("base_model") or "").strip().casefold()
|
||||
return bool(item_bm) and item_bm != "unknown" and item_bm != recipe_bm
|
||||
|
||||
def _base_model_adjustment(item: dict[str, Any]) -> float:
|
||||
# Mismatches are already filtered out; this only boosts known-equal.
|
||||
if not recipe_bm or recipe_bm == "unknown":
|
||||
return 0.0
|
||||
item_bm = (item.get("base_model") or "").strip().casefold()
|
||||
return 0.1 if item_bm == recipe_bm else 0.0
|
||||
|
||||
pool: list[dict[str, Any]] = []
|
||||
for item in getattr(data, "raw_data", None) or []:
|
||||
if not isinstance(item, dict):
|
||||
continue
|
||||
# Items without a sha256 (pending/failed downloads) leave the
|
||||
# entry without a usable hash — same rule as the filename cache.
|
||||
if not (item.get("sha256") or "").strip():
|
||||
continue
|
||||
if not self._is_type_compatible(item, is_checkpoint=is_checkpoint):
|
||||
continue
|
||||
if _base_model_known_mismatch(item):
|
||||
continue
|
||||
pool.append(item)
|
||||
if not pool:
|
||||
return []
|
||||
|
||||
# Basename collision counts decide whether target_name needs the
|
||||
# folder-relative path to resolve uniquely in find_matching_models.
|
||||
basename_counts: dict[str, int] = {}
|
||||
for item in pool:
|
||||
key = self._normalize_filename_key(item.get("file_name") or "")
|
||||
if key:
|
||||
basename_counts[key] = basename_counts.get(key, 0) + 1
|
||||
|
||||
best: dict[str, dict[str, Any]] = {}
|
||||
|
||||
def _consider(item: dict[str, Any], score: float, reason: str) -> None:
|
||||
key = item.get("file_path") or item.get("file_name") or ""
|
||||
if not key:
|
||||
return
|
||||
current = best.get(key)
|
||||
if current is None or score > current["score"]:
|
||||
best[key] = {"item": item, "score": score, "reason": reason}
|
||||
|
||||
query_text = (query or "").strip()
|
||||
|
||||
if not query_text:
|
||||
entry_hash = (entry.get("hash") or "").lower()
|
||||
if entry_hash:
|
||||
hash_cache = await self.build_local_hash_cache()
|
||||
hit = hash_cache.get(entry_hash)
|
||||
if (
|
||||
isinstance(hit, dict)
|
||||
and (hit.get("sha256") or "").strip()
|
||||
and self._is_type_compatible(hit, is_checkpoint=is_checkpoint)
|
||||
and not _base_model_known_mismatch(hit)
|
||||
):
|
||||
_consider(hit, 1.0 + _base_model_adjustment(hit), "same_hash")
|
||||
|
||||
version_id = entry.get("modelVersionId") or entry.get("id")
|
||||
if version_id is not None:
|
||||
if is_checkpoint:
|
||||
hit = self._get_checkpoint_from_version_index(str(version_id))
|
||||
else:
|
||||
hit = self._get_lora_from_version_index(str(version_id))
|
||||
if (
|
||||
isinstance(hit, dict)
|
||||
and (hit.get("sha256") or "").strip()
|
||||
and not _base_model_known_mismatch(hit)
|
||||
):
|
||||
_consider(hit, 0.95 + _base_model_adjustment(hit), "same_version")
|
||||
|
||||
filename_source = query_text or (entry.get("file_name") or "")
|
||||
# Parser-style checkpoint entries carry the model name under ``name``,
|
||||
# widget-style ones under ``modelName`` — try both for checkpoints.
|
||||
if is_checkpoint:
|
||||
name_source = query_text or (entry.get("name") or entry.get("modelName") or "")
|
||||
else:
|
||||
name_source = query_text or (entry.get("modelName") or "")
|
||||
norm_filename_source = self._normalize_filename_key(filename_source)
|
||||
name_source_cf = name_source.casefold()
|
||||
# Substring hits floor the similarity ratio, but only for meaningful
|
||||
# queries — a 1-2 character query is a substring of nearly every
|
||||
# filename and would flood the suggestions with noise.
|
||||
substring_floor = len(query_text) >= 3
|
||||
|
||||
for item in pool:
|
||||
adjustment = _base_model_adjustment(item)
|
||||
|
||||
item_filename = self._normalize_filename_key(item.get("file_name") or "")
|
||||
if norm_filename_source and item_filename:
|
||||
ratio = difflib.SequenceMatcher(
|
||||
None, norm_filename_source, item_filename
|
||||
).ratio()
|
||||
if substring_floor and norm_filename_source in item_filename:
|
||||
ratio = max(ratio, 0.8)
|
||||
if ratio >= 0.55:
|
||||
_consider(
|
||||
item, 0.5 + 0.4 * ratio + adjustment, "similar_filename"
|
||||
)
|
||||
|
||||
item_name = (item.get("model_name") or "").casefold()
|
||||
if name_source_cf and item_name:
|
||||
ratio = difflib.SequenceMatcher(
|
||||
None, name_source_cf, item_name
|
||||
).ratio()
|
||||
if substring_floor and name_source_cf in item_name:
|
||||
ratio = max(ratio, 0.8)
|
||||
if ratio >= 0.65:
|
||||
_consider(item, 0.4 + 0.35 * ratio + adjustment, "similar_name")
|
||||
|
||||
suggestions = []
|
||||
for record in best.values():
|
||||
item = record["item"]
|
||||
file_name = item.get("file_name") or ""
|
||||
stem = self._strip_weight_extension(file_name)
|
||||
folder = (item.get("folder") or "").replace("\\", "/").strip("/")
|
||||
norm_key = self._normalize_filename_key(file_name)
|
||||
if norm_key and basename_counts.get(norm_key, 0) > 1 and folder:
|
||||
target_name = f"{folder}/{stem}"
|
||||
else:
|
||||
target_name = stem
|
||||
suggestions.append(
|
||||
{
|
||||
"file_name": file_name,
|
||||
"file_path": item.get("file_path") or "",
|
||||
"model_name": item.get("model_name") or "",
|
||||
"base_model": item.get("base_model") or "",
|
||||
"preview_url": item.get("preview_url") or "",
|
||||
"hash": (item.get("sha256") or "").lower(),
|
||||
"score": round(record["score"], 3),
|
||||
"match_reason": record["reason"],
|
||||
"target_name": target_name,
|
||||
}
|
||||
)
|
||||
|
||||
suggestions.sort(key=lambda s: (-s["score"], s["file_name"].lower()))
|
||||
return suggestions[:limit]
|
||||
|
||||
def _is_rematch_candidate(self, entry: dict[str, Any]) -> bool:
|
||||
"""Return True when a recipe entry is eligible for local re-matching."""
|
||||
"""Return True when a recipe entry is eligible for local re-matching.
|
||||
|
||||
An entry counts as unresolved when its identity is known to be
|
||||
broken (``isDeleted`` or ``hashInvalid``) or when it is missing
|
||||
identity fields (``hash``/``file_name``). A healthy entry whose
|
||||
hash is simply not present in the local library is NOT a candidate:
|
||||
it may be a recipe imported without downloading the model yet, and
|
||||
its CivitAI-valid hash must never be overwritten by the imprecise
|
||||
filename fallback.
|
||||
"""
|
||||
if not isinstance(entry, dict):
|
||||
return False
|
||||
unresolved = (
|
||||
entry.get("isDeleted") or not entry.get("hash") or not entry.get("file_name")
|
||||
entry.get("isDeleted")
|
||||
or entry.get("hashInvalid")
|
||||
or not entry.get("hash")
|
||||
or not entry.get("file_name")
|
||||
)
|
||||
has_identifier = (
|
||||
entry.get("hash")
|
||||
@@ -1262,6 +1519,7 @@ class RecipeScanner:
|
||||
) -> None:
|
||||
"""Write back a matched local model to a lora recipe entry."""
|
||||
entry["isDeleted"] = False
|
||||
entry["hashInvalid"] = False
|
||||
|
||||
# Only truthy hashes are written — pending/failed items carry an empty
|
||||
# sha256 and an unconditional write would wipe a valid stored hash.
|
||||
@@ -1295,6 +1553,7 @@ class RecipeScanner:
|
||||
identifier key when neither identifier form exists).
|
||||
"""
|
||||
entry["isDeleted"] = False
|
||||
entry["hashInvalid"] = False
|
||||
|
||||
new_hash = (item.get("sha256") or "").lower()
|
||||
if new_hash:
|
||||
@@ -1494,7 +1753,36 @@ class RecipeScanner:
|
||||
# Mark initialization as complete regardless of outcome
|
||||
self._is_initializing = False
|
||||
|
||||
def _initialize_recipe_cache_sync(self):
|
||||
async def _broadcast_scan_progress(
|
||||
self,
|
||||
status: str,
|
||||
stage: str,
|
||||
progress: int,
|
||||
full_rebuild: bool,
|
||||
**extra: Any,
|
||||
) -> None:
|
||||
"""Broadcast manual-refresh scan progress on the generic WS channel.
|
||||
|
||||
Mirrors ``ModelScanner._broadcast_scan_progress`` so the recipes page
|
||||
can reuse the same frontend contract. Best-effort only: broadcast
|
||||
failures must never affect the scan itself.
|
||||
"""
|
||||
payload: Dict[str, Any] = {
|
||||
'type': 'scan_progress',
|
||||
'status': status,
|
||||
'model_type': 'recipe',
|
||||
'pageType': 'recipes',
|
||||
'stage': stage,
|
||||
'full_rebuild': full_rebuild,
|
||||
'progress': progress,
|
||||
}
|
||||
payload.update(extra)
|
||||
try:
|
||||
await ws_manager.broadcast(payload)
|
||||
except Exception as exc: # pragma: no cover - defensive logging
|
||||
logger.error(f"Error broadcasting scan progress for recipe: {exc}")
|
||||
|
||||
def _initialize_recipe_cache_sync(self, report_progress: bool = False):
|
||||
"""Synchronous version of recipe cache initialization for thread pool execution.
|
||||
|
||||
Uses persistent cache for fast startup when available:
|
||||
@@ -1502,8 +1790,14 @@ class RecipeScanner:
|
||||
2. Reconcile with filesystem (check mtime/size for changes)
|
||||
3. Fall back to full directory scan if cache miss or reconciliation fails
|
||||
4. Persist results for next startup
|
||||
|
||||
Args:
|
||||
report_progress: When True (manual force-refresh only), broadcast
|
||||
scan_progress messages during the full directory scan. Startup
|
||||
initialization leaves this False and behaves as before.
|
||||
"""
|
||||
loop = None
|
||||
scan_start_time: Optional[float] = None
|
||||
try:
|
||||
# Ensure cache exists to avoid None reference errors
|
||||
if self._cache is None:
|
||||
@@ -1585,7 +1879,17 @@ class RecipeScanner:
|
||||
|
||||
# Fall back to full directory scan
|
||||
logger.info("Recipe cache miss: performing full directory scan")
|
||||
recipes, json_paths = self._full_directory_scan_sync(recipes_dir)
|
||||
if report_progress:
|
||||
scan_start_time = time.time()
|
||||
# Broadcast from the worker thread via its own event loop,
|
||||
# mirroring ModelScanner._initialize_cache_sync.
|
||||
loop.run_until_complete(
|
||||
self._broadcast_scan_progress('started', 'scan_folders', 0, True)
|
||||
)
|
||||
recipes, json_paths = self._full_directory_scan_sync(
|
||||
recipes_dir,
|
||||
progress_loop=loop if report_progress else None,
|
||||
)
|
||||
self._json_path_map = json_paths
|
||||
|
||||
# Update cache with the collected data
|
||||
@@ -1599,12 +1903,30 @@ class RecipeScanner:
|
||||
recipes, json_paths, self._cache.image_id_map
|
||||
)
|
||||
|
||||
if report_progress:
|
||||
loop.run_until_complete(
|
||||
self._broadcast_scan_progress(
|
||||
'completed', 'finalizing', 100, True,
|
||||
elapsed_seconds=time.time() - (scan_start_time or time.time()),
|
||||
total=len(recipes),
|
||||
)
|
||||
)
|
||||
|
||||
return self._cache
|
||||
except Exception as e:
|
||||
logger.error(f"Error in thread-based recipe cache initialization: {e}")
|
||||
import traceback
|
||||
|
||||
traceback.print_exc(file=sys.stderr)
|
||||
if report_progress and loop is not None:
|
||||
try:
|
||||
loop.run_until_complete(
|
||||
self._broadcast_scan_progress(
|
||||
'error', 'process_models', 0, True, error=str(e)
|
||||
)
|
||||
)
|
||||
except Exception: # pragma: no cover - defensive logging
|
||||
logger.error("Error broadcasting recipe scan failure", exc_info=True)
|
||||
return self._cache if hasattr(self, "_cache") else None
|
||||
finally:
|
||||
# Clean up the event loop
|
||||
@@ -1758,12 +2080,16 @@ class RecipeScanner:
|
||||
return updated
|
||||
|
||||
def _full_directory_scan_sync(
|
||||
self, recipes_dir: str
|
||||
self,
|
||||
recipes_dir: str,
|
||||
progress_loop: Optional[asyncio.AbstractEventLoop] = None,
|
||||
) -> Tuple[List[Dict[str, Any]], Dict[str, str]]:
|
||||
"""Perform a full synchronous directory scan for recipes.
|
||||
|
||||
Args:
|
||||
recipes_dir: Path to the recipes directory.
|
||||
progress_loop: When set (manual force-refresh only), broadcast
|
||||
scan_progress messages through this thread-local event loop.
|
||||
|
||||
Returns:
|
||||
Tuple of (recipes list, json_paths dict).
|
||||
@@ -1778,6 +2104,17 @@ class RecipeScanner:
|
||||
if file.lower().endswith(".recipe.json"):
|
||||
recipe_files.append(os.path.join(root, file))
|
||||
|
||||
total_files = len(recipe_files)
|
||||
if progress_loop is not None:
|
||||
progress_loop.run_until_complete(
|
||||
self._broadcast_scan_progress(
|
||||
'processing', 'count_models', 1, True,
|
||||
processed=0, total=total_files,
|
||||
)
|
||||
)
|
||||
|
||||
last_progress_time = time.time()
|
||||
|
||||
# Process each recipe file
|
||||
for i, recipe_path in enumerate(recipe_files):
|
||||
recipe_data = self._load_recipe_file_sync(recipe_path)
|
||||
@@ -1785,6 +2122,23 @@ class RecipeScanner:
|
||||
recipe_id = str(recipe_data.get("id", ""))
|
||||
recipes.append(recipe_data)
|
||||
json_paths[recipe_id] = recipe_path
|
||||
if progress_loop is not None and total_files > 0:
|
||||
processed = i + 1
|
||||
current_time = time.time()
|
||||
# Throttle to one update per 0.5s; always send the final one.
|
||||
if (
|
||||
processed == total_files
|
||||
or current_time - last_progress_time > 0.5
|
||||
):
|
||||
last_progress_time = current_time
|
||||
progress_percent = min(99, int(1 + (processed / total_files) * 98))
|
||||
progress_loop.run_until_complete(
|
||||
self._broadcast_scan_progress(
|
||||
'processing', 'process_models', progress_percent, True,
|
||||
processed=processed, total=total_files,
|
||||
current_name=os.path.basename(recipe_path),
|
||||
)
|
||||
)
|
||||
# Periodically release GIL so the event loop thread can run
|
||||
if i % 100 == 0:
|
||||
time.sleep(0)
|
||||
@@ -2354,11 +2708,14 @@ class RecipeScanner:
|
||||
start_time = time.time()
|
||||
|
||||
# Run the heavy lifting in a thread pool – same path
|
||||
# used by initialize_in_background().
|
||||
# used by initialize_in_background(). Pass
|
||||
# report_progress=True so manual refreshes broadcast
|
||||
# scan_progress updates; startup init keeps it off.
|
||||
loop = asyncio.get_event_loop()
|
||||
cache = await loop.run_in_executor(
|
||||
None,
|
||||
self._initialize_recipe_cache_sync,
|
||||
True,
|
||||
)
|
||||
if cache is not None:
|
||||
self._cache = cache
|
||||
@@ -3089,6 +3446,19 @@ class RecipeScanner:
|
||||
|
||||
return await self._lora_scanner.find_models_by_name(name, base_model=base_model)
|
||||
|
||||
async def find_local_checkpoints_by_name(
|
||||
self, name: str, base_model: Optional[str] = None
|
||||
) -> List[Dict[str, Any]]:
|
||||
"""Return every local checkpoint matching ``name`` (used to explain lookup misses)."""
|
||||
|
||||
checkpoint_scanner = getattr(self, "_checkpoint_scanner", None)
|
||||
if not checkpoint_scanner or not name:
|
||||
return []
|
||||
|
||||
return await checkpoint_scanner.find_models_by_name(
|
||||
name, base_model=base_model
|
||||
)
|
||||
|
||||
async def get_local_lora_by_hash(self, hash_value: str) -> Optional[Dict[str, Any]]:
|
||||
"""Lookup a local LoRA through the scanner's hash index."""
|
||||
|
||||
@@ -3264,11 +3634,23 @@ class RecipeScanner:
|
||||
if filters:
|
||||
# Filter by base model
|
||||
if "base_model" in filters and filters["base_model"]:
|
||||
filtered_data = [
|
||||
item
|
||||
for item in filtered_data
|
||||
if item.get("base_model", "") in filters["base_model"]
|
||||
]
|
||||
base_model_filter = filters["base_model"]
|
||||
if UNKNOWN_BASE_MODEL_FILTER in base_model_filter:
|
||||
# The unknown bucket matches recipes whose base model
|
||||
# could not be determined (None/empty); real base
|
||||
# models in the list still match by exact name.
|
||||
filtered_data = [
|
||||
item
|
||||
for item in filtered_data
|
||||
if not item.get("base_model")
|
||||
or item.get("base_model") in base_model_filter
|
||||
]
|
||||
else:
|
||||
filtered_data = [
|
||||
item
|
||||
for item in filtered_data
|
||||
if item.get("base_model", "") in base_model_filter
|
||||
]
|
||||
|
||||
# Filter by favorite
|
||||
if "favorite" in filters and filters["favorite"]:
|
||||
@@ -3660,7 +4042,15 @@ class RecipeScanner:
|
||||
raise RecipeNotFoundError("LoRA index out of range in recipe")
|
||||
|
||||
lora_entry = loras[lora_index]
|
||||
# Snapshot the pre-update state so the association can be restored
|
||||
# later (undo reconnect). Never nest snapshots.
|
||||
snapshot = {
|
||||
key: copy.deepcopy(value)
|
||||
for key, value in lora_entry.items()
|
||||
if key != "reconnectSnapshot"
|
||||
}
|
||||
lora_entry["isDeleted"] = False
|
||||
lora_entry["hashInvalid"] = False
|
||||
lora_entry["exclude"] = False
|
||||
lora_entry["file_name"] = target_name
|
||||
|
||||
@@ -3677,6 +4067,8 @@ class RecipeScanner:
|
||||
lora_entry["modelVersionName"] = civitai_info.get("name", "")
|
||||
lora_entry["modelVersionId"] = civitai_info.get("id")
|
||||
|
||||
lora_entry["reconnectSnapshot"] = snapshot
|
||||
|
||||
from ..utils.utils import calculate_recipe_fingerprint
|
||||
|
||||
recipe_data["fingerprint"] = calculate_recipe_fingerprint(
|
||||
@@ -3712,6 +4104,327 @@ class RecipeScanner:
|
||||
updated_lora = self._enrich_lora_entry(updated_lora)
|
||||
return recipe_data, updated_lora
|
||||
|
||||
async def restore_lora_entry(
|
||||
self,
|
||||
recipe_id: str,
|
||||
lora_index: int,
|
||||
) -> Tuple[Dict[str, Any], Dict[str, Any]]:
|
||||
"""Restore a LoRA entry to its pre-reconnect snapshot.
|
||||
|
||||
Reverses :meth:`update_lora_entry`: the entry saved under
|
||||
``reconnectSnapshot`` becomes the entry again and the snapshot is
|
||||
dropped. Returns the updated recipe data and the restored LoRA
|
||||
metadata.
|
||||
"""
|
||||
|
||||
recipe_json_path = await self.get_recipe_json_path(recipe_id)
|
||||
if not recipe_json_path or not os.path.exists(recipe_json_path):
|
||||
raise RecipeNotFoundError("Recipe not found")
|
||||
|
||||
async with self._mutation_lock:
|
||||
with open(recipe_json_path, "r", encoding="utf-8") as file_obj:
|
||||
recipe_data = json.load(file_obj)
|
||||
|
||||
loras = recipe_data.get("loras", [])
|
||||
if lora_index < 0 or lora_index >= len(loras):
|
||||
raise RecipeNotFoundError("LoRA index out of range in recipe")
|
||||
|
||||
snapshot = loras[lora_index].get("reconnectSnapshot")
|
||||
if not isinstance(snapshot, dict):
|
||||
raise RecipeValidationError(
|
||||
"LoRA entry has no reconnect snapshot to restore"
|
||||
)
|
||||
|
||||
restored_entry = copy.deepcopy(snapshot)
|
||||
restored_entry.pop("reconnectSnapshot", None)
|
||||
loras[lora_index] = restored_entry
|
||||
|
||||
from ..utils.utils import calculate_recipe_fingerprint
|
||||
|
||||
recipe_data["fingerprint"] = calculate_recipe_fingerprint(
|
||||
recipe_data.get("loras", [])
|
||||
)
|
||||
recipe_data["modified"] = time.time()
|
||||
|
||||
with open(recipe_json_path, "w", encoding="utf-8") as file_obj:
|
||||
json.dump(recipe_data, file_obj, indent=4, ensure_ascii=False)
|
||||
|
||||
cache = await self.get_cached_data()
|
||||
replaced = await cache.replace_recipe(recipe_id, recipe_data, resort=False)
|
||||
if not replaced:
|
||||
await cache.add_recipe(recipe_data, resort=False)
|
||||
self._schedule_resort()
|
||||
|
||||
# Update FTS index
|
||||
self._update_fts_index_for_recipe(recipe_data, "update")
|
||||
|
||||
# Update persistent SQLite cache
|
||||
if self._persistent_cache:
|
||||
self._persistent_cache.update_recipe(recipe_data, recipe_json_path)
|
||||
self._json_path_map[recipe_id] = recipe_json_path
|
||||
|
||||
restored_lora = self._enrich_lora_entry(dict(restored_entry))
|
||||
return recipe_data, restored_lora
|
||||
|
||||
async def set_lora_entry_hash_invalid(
|
||||
self,
|
||||
recipe_id: str,
|
||||
lora_index: int,
|
||||
hash_invalid: bool,
|
||||
) -> Tuple[Dict[str, Any], Dict[str, Any]]:
|
||||
"""Set the ``hashInvalid`` flag on a specific LoRA entry.
|
||||
|
||||
``hashInvalid`` records that the entry's hash could not be resolved
|
||||
on CivitAI (e.g. a download attempt returned "Model not found").
|
||||
Marking it makes the entry an unresolved rematch candidate without
|
||||
touching its stored hash/file_name.
|
||||
|
||||
Returns:
|
||||
The updated recipe data and the refreshed LoRA metadata.
|
||||
"""
|
||||
recipe_json_path = await self.get_recipe_json_path(recipe_id)
|
||||
if not recipe_json_path or not os.path.exists(recipe_json_path):
|
||||
raise RecipeNotFoundError("Recipe not found")
|
||||
|
||||
async with self._mutation_lock:
|
||||
with open(recipe_json_path, "r", encoding="utf-8") as file_obj:
|
||||
recipe_data = json.load(file_obj)
|
||||
|
||||
loras = recipe_data.get("loras", [])
|
||||
if lora_index >= len(loras):
|
||||
raise RecipeNotFoundError("LoRA index out of range in recipe")
|
||||
|
||||
lora_entry = loras[lora_index]
|
||||
if not isinstance(lora_entry, dict):
|
||||
raise RecipeValidationError("LoRA entry is not a dict")
|
||||
|
||||
lora_entry["hashInvalid"] = bool(hash_invalid)
|
||||
recipe_data["modified"] = time.time()
|
||||
|
||||
with open(recipe_json_path, "w", encoding="utf-8") as file_obj:
|
||||
json.dump(recipe_data, file_obj, indent=4, ensure_ascii=False)
|
||||
|
||||
cache = await self.get_cached_data()
|
||||
replaced = await cache.replace_recipe(recipe_id, recipe_data, resort=False)
|
||||
if not replaced:
|
||||
await cache.add_recipe(recipe_data, resort=False)
|
||||
self._schedule_resort()
|
||||
|
||||
if self._persistent_cache:
|
||||
self._persistent_cache.update_recipe(recipe_data, recipe_json_path)
|
||||
self._json_path_map[recipe_id] = recipe_json_path
|
||||
|
||||
updated_lora = self._enrich_lora_entry(dict(lora_entry))
|
||||
return recipe_data, updated_lora
|
||||
|
||||
async def update_checkpoint_entry(
|
||||
self,
|
||||
recipe_id: str,
|
||||
*,
|
||||
target_name: str,
|
||||
target_checkpoint: Optional[Dict[str, Any]] = None,
|
||||
) -> Tuple[Dict[str, Any], Dict[str, Any]]:
|
||||
"""Update the checkpoint entry within a recipe (manual reconnect).
|
||||
|
||||
Mirrors :meth:`update_lora_entry`: the pre-update entry is snapshotted
|
||||
under ``reconnectSnapshot`` so the association can be restored later,
|
||||
then the matched local checkpoint is written back following the same
|
||||
pinned key set as ``_write_rematch_checkpoint_entry``. ``file_name``
|
||||
keeps the user-entered ``target_name`` (the same convention as the
|
||||
LoRA reconnect), while hash/name/version/baseModel/identifier are
|
||||
refreshed from the local item. The fingerprint is untouched — it is
|
||||
computed over LoRAs only.
|
||||
|
||||
Returns:
|
||||
The updated recipe data and the refreshed checkpoint metadata.
|
||||
"""
|
||||
if target_name is None:
|
||||
raise ValueError("target_name must be provided")
|
||||
|
||||
recipe_json_path = await self.get_recipe_json_path(recipe_id)
|
||||
if not recipe_json_path or not os.path.exists(recipe_json_path):
|
||||
raise RecipeNotFoundError("Recipe not found")
|
||||
|
||||
async with self._mutation_lock:
|
||||
with open(recipe_json_path, "r", encoding="utf-8") as file_obj:
|
||||
recipe_data = json.load(file_obj)
|
||||
|
||||
checkpoint = recipe_data.get("checkpoint")
|
||||
if not isinstance(checkpoint, dict):
|
||||
raise RecipeValidationError(
|
||||
"Recipe has no checkpoint entry to reconnect"
|
||||
)
|
||||
|
||||
# Snapshot the pre-update state so the association can be restored
|
||||
# later (undo reconnect). Never nest snapshots.
|
||||
snapshot = {
|
||||
key: copy.deepcopy(value)
|
||||
for key, value in checkpoint.items()
|
||||
if key != "reconnectSnapshot"
|
||||
}
|
||||
checkpoint["isDeleted"] = False
|
||||
checkpoint["hashInvalid"] = False
|
||||
checkpoint["file_name"] = target_name
|
||||
|
||||
if target_checkpoint is not None:
|
||||
sha_value = target_checkpoint.get("sha256") or target_checkpoint.get(
|
||||
"sha"
|
||||
)
|
||||
if sha_value:
|
||||
checkpoint["hash"] = sha_value.lower()
|
||||
|
||||
self._write_rematch_checkpoint_entry(checkpoint, target_checkpoint)
|
||||
|
||||
# The write-back only refreshes keys the entry already has;
|
||||
# a manual reconnect must also backfill the display keys so a
|
||||
# sparse parser-style entry renders properly after the swap.
|
||||
if not checkpoint.get("name") and target_checkpoint.get("model_name"):
|
||||
checkpoint["name"] = target_checkpoint["model_name"]
|
||||
civitai = target_checkpoint.get("civitai") or {}
|
||||
civ_name = civitai.get("name")
|
||||
if not checkpoint.get("version") and civ_name:
|
||||
checkpoint["version"] = civ_name
|
||||
if (
|
||||
not checkpoint.get("baseModel")
|
||||
and target_checkpoint.get("base_model")
|
||||
):
|
||||
checkpoint["baseModel"] = target_checkpoint["base_model"]
|
||||
|
||||
checkpoint["reconnectSnapshot"] = snapshot
|
||||
recipe_data["modified"] = time.time()
|
||||
|
||||
with open(recipe_json_path, "w", encoding="utf-8") as file_obj:
|
||||
json.dump(recipe_data, file_obj, indent=4, ensure_ascii=False)
|
||||
|
||||
cache = await self.get_cached_data()
|
||||
replaced = await cache.replace_recipe(recipe_id, recipe_data, resort=False)
|
||||
if not replaced:
|
||||
await cache.add_recipe(recipe_data, resort=False)
|
||||
self._schedule_resort()
|
||||
|
||||
# Update FTS index
|
||||
self._update_fts_index_for_recipe(recipe_data, "update")
|
||||
|
||||
# Update persistent SQLite cache
|
||||
if self._persistent_cache:
|
||||
self._persistent_cache.update_recipe(recipe_data, recipe_json_path)
|
||||
self._json_path_map[recipe_id] = recipe_json_path
|
||||
|
||||
updated_checkpoint = dict(checkpoint)
|
||||
if target_checkpoint is not None:
|
||||
preview_url = target_checkpoint.get("preview_url")
|
||||
if preview_url:
|
||||
updated_checkpoint["preview_url"] = config.get_preview_static_url(
|
||||
preview_url
|
||||
)
|
||||
if target_checkpoint.get("file_path"):
|
||||
updated_checkpoint["localPath"] = target_checkpoint["file_path"]
|
||||
|
||||
updated_checkpoint = self._enrich_checkpoint_entry(updated_checkpoint)
|
||||
return recipe_data, updated_checkpoint
|
||||
|
||||
async def restore_checkpoint_entry(
|
||||
self,
|
||||
recipe_id: str,
|
||||
) -> Tuple[Dict[str, Any], Dict[str, Any]]:
|
||||
"""Restore the checkpoint entry to its pre-reconnect snapshot.
|
||||
|
||||
Reverses :meth:`update_checkpoint_entry`: the entry saved under
|
||||
``reconnectSnapshot`` becomes the checkpoint again and the snapshot is
|
||||
dropped. Returns the updated recipe data and the restored checkpoint
|
||||
metadata.
|
||||
"""
|
||||
recipe_json_path = await self.get_recipe_json_path(recipe_id)
|
||||
if not recipe_json_path or not os.path.exists(recipe_json_path):
|
||||
raise RecipeNotFoundError("Recipe not found")
|
||||
|
||||
async with self._mutation_lock:
|
||||
with open(recipe_json_path, "r", encoding="utf-8") as file_obj:
|
||||
recipe_data = json.load(file_obj)
|
||||
|
||||
checkpoint = recipe_data.get("checkpoint")
|
||||
if not isinstance(checkpoint, dict):
|
||||
raise RecipeValidationError(
|
||||
"Recipe has no checkpoint entry to restore"
|
||||
)
|
||||
|
||||
snapshot = checkpoint.get("reconnectSnapshot")
|
||||
if not isinstance(snapshot, dict):
|
||||
raise RecipeValidationError(
|
||||
"Checkpoint entry has no reconnect snapshot to restore"
|
||||
)
|
||||
|
||||
restored_entry = copy.deepcopy(snapshot)
|
||||
restored_entry.pop("reconnectSnapshot", None)
|
||||
recipe_data["checkpoint"] = restored_entry
|
||||
recipe_data["modified"] = time.time()
|
||||
|
||||
with open(recipe_json_path, "w", encoding="utf-8") as file_obj:
|
||||
json.dump(recipe_data, file_obj, indent=4, ensure_ascii=False)
|
||||
|
||||
cache = await self.get_cached_data()
|
||||
replaced = await cache.replace_recipe(recipe_id, recipe_data, resort=False)
|
||||
if not replaced:
|
||||
await cache.add_recipe(recipe_data, resort=False)
|
||||
self._schedule_resort()
|
||||
|
||||
# Update FTS index
|
||||
self._update_fts_index_for_recipe(recipe_data, "update")
|
||||
|
||||
# Update persistent SQLite cache
|
||||
if self._persistent_cache:
|
||||
self._persistent_cache.update_recipe(recipe_data, recipe_json_path)
|
||||
self._json_path_map[recipe_id] = recipe_json_path
|
||||
|
||||
restored_checkpoint = self._enrich_checkpoint_entry(dict(restored_entry))
|
||||
return recipe_data, restored_checkpoint
|
||||
|
||||
async def set_checkpoint_entry_hash_invalid(
|
||||
self,
|
||||
recipe_id: str,
|
||||
hash_invalid: bool,
|
||||
) -> Tuple[Dict[str, Any], Dict[str, Any]]:
|
||||
"""Set the ``hashInvalid`` flag on the recipe's checkpoint entry.
|
||||
|
||||
``hashInvalid`` records that the entry's hash could not be resolved
|
||||
on CivitAI (e.g. a download attempt returned "Model not found").
|
||||
Marking it makes the entry an unresolved rematch candidate without
|
||||
touching its stored hash/file_name.
|
||||
|
||||
Returns:
|
||||
The updated recipe data and the refreshed checkpoint metadata.
|
||||
"""
|
||||
recipe_json_path = await self.get_recipe_json_path(recipe_id)
|
||||
if not recipe_json_path or not os.path.exists(recipe_json_path):
|
||||
raise RecipeNotFoundError("Recipe not found")
|
||||
|
||||
async with self._mutation_lock:
|
||||
with open(recipe_json_path, "r", encoding="utf-8") as file_obj:
|
||||
recipe_data = json.load(file_obj)
|
||||
|
||||
checkpoint = recipe_data.get("checkpoint")
|
||||
if not isinstance(checkpoint, dict):
|
||||
raise RecipeValidationError("Checkpoint entry is not a dict")
|
||||
|
||||
checkpoint["hashInvalid"] = bool(hash_invalid)
|
||||
recipe_data["modified"] = time.time()
|
||||
|
||||
with open(recipe_json_path, "w", encoding="utf-8") as file_obj:
|
||||
json.dump(recipe_data, file_obj, indent=4, ensure_ascii=False)
|
||||
|
||||
cache = await self.get_cached_data()
|
||||
replaced = await cache.replace_recipe(recipe_id, recipe_data, resort=False)
|
||||
if not replaced:
|
||||
await cache.add_recipe(recipe_data, resort=False)
|
||||
self._schedule_resort()
|
||||
|
||||
if self._persistent_cache:
|
||||
self._persistent_cache.update_recipe(recipe_data, recipe_json_path)
|
||||
self._json_path_map[recipe_id] = recipe_json_path
|
||||
|
||||
updated_checkpoint = self._enrich_checkpoint_entry(dict(checkpoint))
|
||||
return recipe_data, updated_checkpoint
|
||||
|
||||
async def get_recipes_for_lora(self, lora_hash: str) -> List[Dict[str, Any]]:
|
||||
"""Return recipes that reference a given LoRA hash."""
|
||||
|
||||
@@ -3820,7 +4533,10 @@ class RecipeScanner:
|
||||
break
|
||||
|
||||
if not file_name:
|
||||
if lora.get("isDeleted", False):
|
||||
# LoRAs deleted from the source or with an unresolvable hash
|
||||
# cannot be downloaded; skip them instead of emitting a token
|
||||
# pointing at a file that does not exist locally.
|
||||
if lora.get("isDeleted", False) or lora.get("hashInvalid", False):
|
||||
continue
|
||||
file_name = lora.get("file_name", "unknown-lora")
|
||||
folder = lora.get("folder", "")
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
"""Recipe service layer implementations."""
|
||||
|
||||
from .analysis_service import RecipeAnalysisService
|
||||
from .import_info import build_import_info, compute_no_loras_reason
|
||||
from .persistence_service import RecipePersistenceService
|
||||
from .sharing_service import RecipeSharingService
|
||||
from .errors import (
|
||||
@@ -15,6 +16,8 @@ __all__ = [
|
||||
"RecipeAnalysisService",
|
||||
"RecipePersistenceService",
|
||||
"RecipeSharingService",
|
||||
"build_import_info",
|
||||
"compute_no_loras_reason",
|
||||
"RecipeServiceError",
|
||||
"RecipeValidationError",
|
||||
"RecipeNotFoundError",
|
||||
|
||||
@@ -72,15 +72,28 @@ class RecipeAnalysisService:
|
||||
metadata = self._exif_utils.extract_image_metadata(temp_path)
|
||||
if not metadata:
|
||||
return AnalysisResult(
|
||||
{"error": "No metadata found in this image", "loras": []}
|
||||
{
|
||||
"error": "No metadata found in this image",
|
||||
"loras": [],
|
||||
"diagnostics": {
|
||||
"channel": "upload",
|
||||
"exif_present": False,
|
||||
},
|
||||
}
|
||||
)
|
||||
|
||||
return await self._parse_metadata(
|
||||
result = await self._parse_metadata(
|
||||
metadata,
|
||||
recipe_scanner=recipe_scanner,
|
||||
image_path=None,
|
||||
include_image_base64=False,
|
||||
)
|
||||
result.payload["diagnostics"] = {
|
||||
"channel": "upload",
|
||||
"exif_present": True,
|
||||
"exif_parser": result.payload.get("parser"),
|
||||
}
|
||||
return result
|
||||
finally:
|
||||
self._safe_cleanup(temp_path)
|
||||
|
||||
@@ -104,9 +117,13 @@ class RecipeAnalysisService:
|
||||
image_info: Optional[dict[str, Any]] = None
|
||||
is_video = False
|
||||
extension = ".jpg" # Default
|
||||
# Diagnostics collected during analysis; surfaced in the payload so
|
||||
# callers can persist an import_info block explaining empty LoRA lists.
|
||||
diagnostics: dict[str, Any] = {"channel": "url"}
|
||||
|
||||
try:
|
||||
civitai_image_id = extract_civitai_image_id(url)
|
||||
diagnostics["civitai_image"] = bool(civitai_image_id)
|
||||
if civitai_image_id:
|
||||
image_info = await civitai_client.get_image_info(
|
||||
civitai_image_id, source_url=url
|
||||
@@ -147,11 +164,23 @@ class RecipeAnalysisService:
|
||||
):
|
||||
metadata = metadata["meta"]
|
||||
|
||||
# Diagnostics: capture the API meta shape before injecting
|
||||
# modelVersionIds / browsingLevel so the recipe modal can
|
||||
# explain why an import ended up without LoRAs.
|
||||
diagnostics["api_meta_present"] = isinstance(metadata, dict)
|
||||
if isinstance(metadata, dict):
|
||||
diagnostics["api_meta_keys"] = sorted(metadata.keys())
|
||||
|
||||
# Include modelVersionIds from root level if available.
|
||||
# CivitAI API returns modelVersionIds at root level, not in meta.
|
||||
# When meta is null (None), create a minimal dict so downstream
|
||||
# parsers can still discover LoRAs and checkpoints.
|
||||
model_version_ids = image_info.get("modelVersionIds")
|
||||
diagnostics["api_model_version_ids"] = (
|
||||
len(model_version_ids)
|
||||
if isinstance(model_version_ids, list)
|
||||
else 0
|
||||
)
|
||||
if model_version_ids:
|
||||
if isinstance(metadata, dict):
|
||||
metadata["modelVersionIds"] = model_version_ids
|
||||
@@ -229,6 +258,8 @@ class RecipeAnalysisService:
|
||||
finally:
|
||||
self._safe_cleanup(orig_temp_path)
|
||||
|
||||
diagnostics["exif_present"] = bool(exif_metadata)
|
||||
|
||||
# Parse EXIF data (typically a string like parameters/prompt/workflow)
|
||||
# and API metadata (dict with modelVersionIds, browsingLevel) separately,
|
||||
# then merge: API loras/checkpoint override, EXIF gen_params fill in gaps.
|
||||
@@ -237,6 +268,7 @@ class RecipeAnalysisService:
|
||||
if isinstance(exif_metadata, str):
|
||||
exif_parser = self._recipe_parser_factory.create_parser(exif_metadata)
|
||||
if exif_parser:
|
||||
diagnostics["exif_parser"] = exif_parser.__class__.__name__
|
||||
exif_data = await exif_parser.parse_metadata(
|
||||
exif_metadata, recipe_scanner=recipe_scanner,
|
||||
)
|
||||
@@ -270,6 +302,22 @@ class RecipeAnalysisService:
|
||||
if merged_gp:
|
||||
result.payload["gen_params"] = merged_gp
|
||||
|
||||
# The API-only parse (meta=null with only modelVersionIds)
|
||||
# yields a checkpoint but no LoRAs; the image EXIF carries the
|
||||
# full resource list. Fill the gaps the API parse left open.
|
||||
if not result.payload.get("loras"):
|
||||
exif_loras = exif_parsed_result.get("loras") or []
|
||||
if exif_loras:
|
||||
result.payload["loras"] = exif_loras
|
||||
if not result.payload.get("checkpoint") and not result.payload.get("model"):
|
||||
exif_checkpoint = exif_parsed_result.get("model") or exif_parsed_result.get(
|
||||
"checkpoint"
|
||||
)
|
||||
if exif_checkpoint:
|
||||
result.payload["checkpoint"] = exif_checkpoint
|
||||
if not result.payload.get("base_model") and exif_parsed_result.get("base_model"):
|
||||
result.payload["base_model"] = exif_parsed_result["base_model"]
|
||||
|
||||
if civitai_image_id and image_info and not result.payload.get("error"):
|
||||
# Use the metadata dict we built (may contain modelVersionIds
|
||||
# and browsingLevel from the API root level). Do NOT pass
|
||||
@@ -308,6 +356,8 @@ class RecipeAnalysisService:
|
||||
if isinstance(bl, int) and bl > 0:
|
||||
result.payload["preview_nsfw_level"] = bl
|
||||
|
||||
diagnostics["is_video"] = is_video
|
||||
result.payload["diagnostics"] = diagnostics
|
||||
return result
|
||||
finally:
|
||||
if temp_path:
|
||||
@@ -318,6 +368,7 @@ class RecipeAnalysisService:
|
||||
*,
|
||||
file_path: str | None,
|
||||
recipe_scanner,
|
||||
ignore_recipe_metadata: bool = False,
|
||||
) -> AnalysisResult:
|
||||
"""Analyze a file already present on disk."""
|
||||
|
||||
@@ -332,14 +383,41 @@ class RecipeAnalysisService:
|
||||
self._exif_utils.extract_image_metadata, normalized_path
|
||||
)
|
||||
if not metadata:
|
||||
return self._metadata_not_found_response(normalized_path)
|
||||
result = self._metadata_not_found_response(normalized_path)
|
||||
result.payload["diagnostics"] = {
|
||||
"channel": "local",
|
||||
"exif_present": False,
|
||||
}
|
||||
return result
|
||||
|
||||
return await self._parse_metadata(
|
||||
if ignore_recipe_metadata:
|
||||
# Re-import: re-parse the original embedded generation metadata
|
||||
# instead of the recipe JSON block LoRA Manager appended on save.
|
||||
from ...recipes.parsers.recipe_format import strip_recipe_metadata
|
||||
|
||||
metadata = strip_recipe_metadata(metadata)
|
||||
if not metadata:
|
||||
result = self._metadata_not_found_response(normalized_path)
|
||||
result.payload["diagnostics"] = {
|
||||
"channel": "local",
|
||||
"exif_present": True,
|
||||
"ignore_recipe_metadata": True,
|
||||
"reason": "only_recipe_metadata",
|
||||
}
|
||||
return result
|
||||
|
||||
result = await self._parse_metadata(
|
||||
metadata,
|
||||
recipe_scanner=recipe_scanner,
|
||||
image_path=normalized_path,
|
||||
include_image_base64=True,
|
||||
)
|
||||
result.payload["diagnostics"] = {
|
||||
"channel": "local",
|
||||
"exif_present": True,
|
||||
"exif_parser": result.payload.get("parser"),
|
||||
}
|
||||
return result
|
||||
|
||||
async def analyze_widget_metadata(self, *, recipe_scanner) -> AnalysisResult:
|
||||
"""Analyse the most recent generation metadata for widget saves."""
|
||||
@@ -436,6 +514,10 @@ class RecipeAnalysisService:
|
||||
metadata, recipe_scanner=recipe_scanner
|
||||
)
|
||||
|
||||
# Record which parser handled the metadata so import diagnostics
|
||||
# can distinguish e.g. ComfyUI workflow sources.
|
||||
result["parser"] = parser.__class__.__name__
|
||||
|
||||
if include_image_base64 and image_path:
|
||||
result["image_base64"] = self._encode_file(image_path)
|
||||
|
||||
|
||||
@@ -0,0 +1,129 @@
|
||||
"""Import provenance helpers for recipes.
|
||||
|
||||
Builds the ``import_info`` block persisted on a recipe: the import channel
|
||||
(batch import / single URL / local file / upload / widget) and, when the
|
||||
recipe ended up with no LoRAs, a machine-readable reason plus the diagnostic
|
||||
details that led to it. The recipe modal renders this block in a collapsed
|
||||
"Why no LoRAs?" panel; legacy recipes without ``import_info`` fall back to a
|
||||
frontend heuristic.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import Any, Dict, List, Optional
|
||||
|
||||
# Import channels (how the recipe entered the library).
|
||||
CHANNEL_BATCH_IMPORT_URL = "batch_import_url"
|
||||
CHANNEL_BATCH_IMPORT_LOCAL = "batch_import_local"
|
||||
CHANNEL_URL = "url"
|
||||
CHANNEL_LOCAL = "local"
|
||||
CHANNEL_UPLOAD = "upload"
|
||||
CHANNEL_WIDGET = "widget"
|
||||
CHANNEL_REIMPORT_URL = "reimport_url"
|
||||
CHANNEL_REIMPORT_LOCAL = "reimport_local"
|
||||
|
||||
_URL_CHANNELS = frozenset(
|
||||
{CHANNEL_BATCH_IMPORT_URL, CHANNEL_URL, CHANNEL_REIMPORT_URL}
|
||||
)
|
||||
|
||||
# No-LoRA reason codes (persisted, consumed by the recipe modal).
|
||||
REASON_NO_LORAS_USED = "no_loras_used"
|
||||
REASON_API_NO_LORA_RESOURCES = "api_meta_no_lora_resources"
|
||||
REASON_API_META_MISSING = "api_meta_missing"
|
||||
REASON_NO_EMBEDDED_METADATA = "no_embedded_metadata"
|
||||
REASON_WORKFLOW_METADATA_LIMITED = "workflow_metadata_limited"
|
||||
REASON_VIDEO_NO_METADATA = "video_no_metadata"
|
||||
REASON_METADATA_UNSUPPORTED = "metadata_unsupported"
|
||||
REASON_UNKNOWN = "unknown"
|
||||
|
||||
_COMFY_PARSER_NAME = "ComfyMetadataParser"
|
||||
|
||||
# Cap for api_meta_keys kept in details — enough for the UI bullet without
|
||||
# bloating the recipe JSON.
|
||||
_MAX_DETAIL_KEYS = 12
|
||||
|
||||
|
||||
def compute_no_loras_reason(
|
||||
channel: str, diagnostics: Optional[Dict[str, Any]]
|
||||
) -> str:
|
||||
"""Classify why an import produced no LoRA entries.
|
||||
|
||||
Args:
|
||||
channel: One of the CHANNEL_* constants.
|
||||
diagnostics: Signals collected during analysis (see
|
||||
``RecipeAnalysisService``), or None for channels without analysis
|
||||
(e.g. widget saves).
|
||||
"""
|
||||
diag = diagnostics or {}
|
||||
|
||||
if diag.get("is_video"):
|
||||
return REASON_VIDEO_NO_METADATA
|
||||
|
||||
# Embedded metadata that is a ComfyUI workflow: LoRA extraction from
|
||||
# workflows is limited, so report that specifically.
|
||||
parser = diag.get("exif_parser") or diag.get("parser")
|
||||
if parser == _COMFY_PARSER_NAME:
|
||||
return REASON_WORKFLOW_METADATA_LIMITED
|
||||
|
||||
if channel in _URL_CHANNELS:
|
||||
if not diag.get("civitai_image"):
|
||||
# Generic (non-CivitAI) URL: only embedded metadata is available.
|
||||
if not diag.get("exif_present"):
|
||||
return REASON_NO_EMBEDDED_METADATA
|
||||
return (
|
||||
REASON_NO_LORAS_USED if parser else REASON_METADATA_UNSUPPORTED
|
||||
)
|
||||
# NOTE: no "parsed EXIF means no LoRAs were used" shortcut here.
|
||||
# CivitAI's onsite generator writes A1111-style EXIF (prompt, seed,
|
||||
# steps, ...) WITHOUT LoRA references — LoRA usage lives only in
|
||||
# CivitAI-internal data — so cleanly parsed EXIF cannot prove the
|
||||
# generation used no LoRAs. Report the API meta shape instead.
|
||||
api_keys = diag.get("api_meta_keys") or []
|
||||
api_mvids = diag.get("api_model_version_ids") or 0
|
||||
if api_keys or api_mvids:
|
||||
return REASON_API_NO_LORA_RESOURCES
|
||||
return REASON_API_META_MISSING
|
||||
|
||||
if channel == CHANNEL_WIDGET:
|
||||
return REASON_NO_LORAS_USED
|
||||
|
||||
# Local file / upload / local re-import: embedded metadata only.
|
||||
if not diag.get("exif_present"):
|
||||
return REASON_NO_EMBEDDED_METADATA
|
||||
return REASON_NO_LORAS_USED if parser else REASON_METADATA_UNSUPPORTED
|
||||
|
||||
|
||||
def build_import_info(
|
||||
channel: str,
|
||||
diagnostics: Optional[Dict[str, Any]],
|
||||
loras: Optional[List[Dict[str, Any]]],
|
||||
) -> Dict[str, Any]:
|
||||
"""Build the ``import_info`` block persisted on a recipe.
|
||||
|
||||
Always records the import channel; adds ``reason`` and ``details`` only
|
||||
when the recipe has no LoRAs.
|
||||
"""
|
||||
info: Dict[str, Any] = {"channel": channel}
|
||||
if loras:
|
||||
return info
|
||||
|
||||
info["reason"] = compute_no_loras_reason(channel, diagnostics)
|
||||
|
||||
diag = diagnostics or {}
|
||||
details: Dict[str, Any] = {}
|
||||
api_keys = diag.get("api_meta_keys")
|
||||
if api_keys:
|
||||
details["api_meta_keys"] = list(api_keys)[:_MAX_DETAIL_KEYS]
|
||||
api_mvids = diag.get("api_model_version_ids")
|
||||
if api_mvids is not None:
|
||||
details["api_model_version_ids"] = api_mvids
|
||||
if "exif_present" in diag:
|
||||
details["exif_present"] = bool(diag.get("exif_present"))
|
||||
if diag.get("exif_parser"):
|
||||
details["exif_parser"] = diag["exif_parser"]
|
||||
if diag.get("is_video"):
|
||||
details["is_video"] = True
|
||||
if details:
|
||||
info["details"] = details
|
||||
|
||||
return info
|
||||
@@ -13,9 +13,15 @@ from typing import Any, Awaitable, Dict, Iterable, Optional, cast
|
||||
|
||||
from ...config import config
|
||||
from ...recipes.constants import GEN_PARAM_KEYS
|
||||
from ...utils.base_model import (
|
||||
RELATION_COMPATIBLE,
|
||||
RELATION_INCOMPATIBLE,
|
||||
base_model_relation,
|
||||
)
|
||||
from ...utils.utils import calculate_recipe_fingerprint
|
||||
from ..pending_delete_service import get_pending_delete_service
|
||||
from .errors import RecipeNotFoundError, RecipeValidationError
|
||||
from .import_info import CHANNEL_UPLOAD, CHANNEL_WIDGET, build_import_info
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
@@ -52,6 +58,7 @@ class RecipePersistenceService:
|
||||
extension: str | None = None,
|
||||
recipe_id: str | None = None,
|
||||
target_dir: str | None = None,
|
||||
skip_optimize: bool = False,
|
||||
) -> PersistenceResult:
|
||||
"""Persist a user uploaded recipe.
|
||||
|
||||
@@ -61,6 +68,11 @@ class RecipePersistenceService:
|
||||
target_dir: If provided, save recipe files to this directory instead
|
||||
of the default recipes_dir. Used by re-import to preserve the
|
||||
original folder location.
|
||||
skip_optimize: If True, store the image bytes verbatim without
|
||||
resizing/re-encoding (recipe metadata is still embedded via a
|
||||
byte-level EXIF update that leaves the pixels untouched). Used
|
||||
by local re-import, where the source is the recipe's own
|
||||
already-optimized preview image.
|
||||
"""
|
||||
|
||||
missing_fields = []
|
||||
@@ -81,9 +93,12 @@ class RecipePersistenceService:
|
||||
|
||||
recipe_id = recipe_id or str(uuid.uuid4())
|
||||
|
||||
# Handle video formats by bypassing optimization and metadata embedding
|
||||
# Handle video formats by bypassing optimization and metadata embedding.
|
||||
# Local re-import also bypasses optimization: the source is the
|
||||
# recipe's own already-optimized preview image, so re-compressing it
|
||||
# would only degrade quality.
|
||||
is_video = extension in [".mp4", ".webm"]
|
||||
if is_video:
|
||||
if is_video or skip_optimize:
|
||||
optimized_image = resolved_image_bytes
|
||||
# extension is already set
|
||||
else:
|
||||
@@ -129,6 +144,22 @@ class RecipePersistenceService:
|
||||
if metadata.get("source_path"):
|
||||
recipe_data["source_path"] = metadata.get("source_path")
|
||||
|
||||
# Persist import provenance. Batch import / re-import paths pass a
|
||||
# prebuilt import_info; frontend-driven saves (upload, single URL,
|
||||
# local path) carry the analysis payload's diagnostics, from which
|
||||
# import_info is derived here.
|
||||
import_info = metadata.get("import_info")
|
||||
if not isinstance(import_info, dict):
|
||||
diagnostics = metadata.get("diagnostics")
|
||||
if isinstance(diagnostics, dict):
|
||||
import_info = build_import_info(
|
||||
diagnostics.get("channel") or CHANNEL_UPLOAD,
|
||||
diagnostics,
|
||||
loras_data,
|
||||
)
|
||||
if isinstance(import_info, dict) and import_info:
|
||||
recipe_data["import_info"] = import_info
|
||||
|
||||
nsfw_level = metadata.get("preview_nsfw_level")
|
||||
if nsfw_level is not None and isinstance(nsfw_level, int):
|
||||
recipe_data["preview_nsfw_level"] = nsfw_level
|
||||
@@ -153,7 +184,11 @@ class RecipePersistenceService:
|
||||
json.dump(recipe_data, file_obj, indent=4, ensure_ascii=False)
|
||||
|
||||
if not is_video:
|
||||
self._exif_utils.append_recipe_metadata(normalized_image_path, recipe_data)
|
||||
self._exif_utils.append_recipe_metadata(
|
||||
normalized_image_path,
|
||||
recipe_data,
|
||||
pixel_preserving=skip_optimize,
|
||||
)
|
||||
|
||||
matching_recipes = await self._find_matching_recipes(recipe_scanner, fingerprint, exclude_id=recipe_id)
|
||||
await recipe_scanner.add_recipe(recipe_data)
|
||||
@@ -430,20 +465,31 @@ class RecipePersistenceService:
|
||||
with open(recipe_path, "r", encoding="utf-8") as file_obj:
|
||||
recipe_base_model = json.load(file_obj).get("base_model", "")
|
||||
|
||||
target_lora = await recipe_scanner.get_local_lora(target_name, recipe_base_model)
|
||||
if not target_lora:
|
||||
matches = await recipe_scanner.find_local_loras_by_name(target_name)
|
||||
if len(matches) > 1:
|
||||
raise RecipeValidationError(
|
||||
f"Multiple local LoRAs match '{target_name}'; "
|
||||
"include the folder path to disambiguate"
|
||||
)
|
||||
if len(matches) == 1:
|
||||
raise RecipeValidationError(
|
||||
f"Local LoRA '{target_name}' has a different base model than the recipe"
|
||||
)
|
||||
matches = await recipe_scanner.find_local_loras_by_name(target_name)
|
||||
if not matches:
|
||||
raise RecipeNotFoundError(f"Local LoRA not found with name: {target_name}")
|
||||
|
||||
# Three-tier base-model guard: exact/unknown labels pass silently;
|
||||
# labels from the same architecture family (e.g. Pony ↔ Illustrious)
|
||||
# pass but are reported so the UI can warn; confident architecture
|
||||
# mismatches stay hard-rejected because they can never load.
|
||||
eligible: list[tuple[dict, str]] = []
|
||||
for match in matches:
|
||||
relation = base_model_relation(recipe_base_model, match.get("base_model"))
|
||||
if relation != RELATION_INCOMPATIBLE:
|
||||
eligible.append((match, relation))
|
||||
|
||||
if not eligible:
|
||||
raise RecipeValidationError(
|
||||
f"Local LoRA '{target_name}' has a different base model than the recipe"
|
||||
)
|
||||
if len(eligible) > 1:
|
||||
raise RecipeValidationError(
|
||||
f"Multiple local LoRAs match '{target_name}'; "
|
||||
"include the folder path to disambiguate"
|
||||
)
|
||||
target_lora, target_relation = eligible[0]
|
||||
|
||||
recipe_data, updated_lora = await recipe_scanner.update_lora_entry(
|
||||
recipe_id,
|
||||
lora_index,
|
||||
@@ -451,6 +497,43 @@ class RecipePersistenceService:
|
||||
target_lora=target_lora,
|
||||
)
|
||||
|
||||
image_path = recipe_data.get("file_path")
|
||||
if image_path and os.path.exists(image_path):
|
||||
self._exif_utils.append_recipe_metadata(image_path, recipe_data)
|
||||
|
||||
matching_recipes = []
|
||||
if "fingerprint" in recipe_data:
|
||||
matching_recipes = await recipe_scanner.find_recipes_by_fingerprint(recipe_data["fingerprint"])
|
||||
if recipe_id in matching_recipes:
|
||||
matching_recipes.remove(recipe_id)
|
||||
|
||||
payload: dict[str, Any] = {
|
||||
"success": True,
|
||||
"recipe_id": recipe_id,
|
||||
"updated_lora": updated_lora,
|
||||
"matching_recipes": matching_recipes,
|
||||
}
|
||||
if target_relation == RELATION_COMPATIBLE:
|
||||
# Structured data, not prose — the frontend localizes the warning.
|
||||
payload["base_model_mismatch"] = {
|
||||
"recipe_base_model": recipe_base_model,
|
||||
"lora_base_model": target_lora.get("base_model") or "",
|
||||
}
|
||||
return PersistenceResult(payload)
|
||||
|
||||
async def restore_lora(
|
||||
self,
|
||||
*,
|
||||
recipe_scanner,
|
||||
recipe_id: str,
|
||||
lora_index: int,
|
||||
) -> PersistenceResult:
|
||||
"""Restore a LoRA entry to the state captured before its reconnect."""
|
||||
|
||||
recipe_data, updated_lora = await recipe_scanner.restore_lora_entry(
|
||||
recipe_id, lora_index
|
||||
)
|
||||
|
||||
image_path = recipe_data.get("file_path")
|
||||
if image_path and os.path.exists(image_path):
|
||||
self._exif_utils.append_recipe_metadata(image_path, recipe_data)
|
||||
@@ -470,6 +553,231 @@ class RecipePersistenceService:
|
||||
}
|
||||
)
|
||||
|
||||
async def get_reconnect_suggestions(
|
||||
self,
|
||||
*,
|
||||
recipe_scanner,
|
||||
recipe_id: str,
|
||||
lora_index: int,
|
||||
query: str | None = None,
|
||||
) -> PersistenceResult:
|
||||
"""Return ranked local LoRA candidates for reconnecting a recipe entry."""
|
||||
|
||||
recipe_path = await recipe_scanner.get_recipe_json_path(recipe_id)
|
||||
if not recipe_path or not os.path.exists(recipe_path):
|
||||
raise RecipeNotFoundError("Recipe not found")
|
||||
|
||||
with open(recipe_path, "r", encoding="utf-8") as file_obj:
|
||||
recipe_data = json.load(file_obj)
|
||||
|
||||
loras = recipe_data.get("loras") or []
|
||||
if lora_index < 0 or lora_index >= len(loras):
|
||||
raise RecipeValidationError(f"Invalid lora_index: {lora_index}")
|
||||
|
||||
suggestions = await recipe_scanner.suggest_reconnect_candidates(
|
||||
entry=loras[lora_index],
|
||||
recipe_base_model=recipe_data.get("base_model"),
|
||||
query=query,
|
||||
)
|
||||
|
||||
return PersistenceResult({"success": True, "suggestions": suggestions})
|
||||
|
||||
async def mark_lora_hash_invalid(
|
||||
self,
|
||||
*,
|
||||
recipe_scanner,
|
||||
recipe_id: str,
|
||||
lora_index: int,
|
||||
hash_invalid: bool = True,
|
||||
) -> PersistenceResult:
|
||||
"""Mark a recipe LoRA entry's hash as unresolvable on CivitAI.
|
||||
|
||||
Called when a download attempt by hash returned "Model not found".
|
||||
The flag makes the entry an unresolved rematch candidate without
|
||||
altering its stored hash/file_name.
|
||||
"""
|
||||
|
||||
recipe_data, updated_lora = await recipe_scanner.set_lora_entry_hash_invalid(
|
||||
recipe_id,
|
||||
lora_index,
|
||||
hash_invalid=hash_invalid,
|
||||
)
|
||||
|
||||
return PersistenceResult(
|
||||
{
|
||||
"success": True,
|
||||
"recipe_id": recipe_id,
|
||||
"hash_invalid": bool(hash_invalid),
|
||||
"updated_lora": updated_lora,
|
||||
}
|
||||
)
|
||||
|
||||
async def reconnect_checkpoint(
|
||||
self,
|
||||
*,
|
||||
recipe_scanner,
|
||||
recipe_id: str,
|
||||
target_name: str,
|
||||
) -> PersistenceResult:
|
||||
"""Reconnect the checkpoint entry within an existing recipe."""
|
||||
|
||||
recipe_path = await recipe_scanner.get_recipe_json_path(recipe_id)
|
||||
if not recipe_path or not os.path.exists(recipe_path):
|
||||
raise RecipeNotFoundError("Recipe not found")
|
||||
|
||||
with open(recipe_path, "r", encoding="utf-8") as file_obj:
|
||||
recipe_base_model = json.load(file_obj).get("base_model", "")
|
||||
|
||||
matches = await recipe_scanner.find_local_checkpoints_by_name(target_name)
|
||||
if not matches:
|
||||
raise RecipeNotFoundError(
|
||||
f"Local checkpoint not found with name: {target_name}"
|
||||
)
|
||||
|
||||
# Same three-tier base-model guard as reconnect_lora: exact/unknown
|
||||
# labels pass silently; same-architecture-family labels pass but are
|
||||
# reported so the UI can warn; confident mismatches stay hard-rejected.
|
||||
eligible: list[tuple[dict, str]] = []
|
||||
for match in matches:
|
||||
relation = base_model_relation(recipe_base_model, match.get("base_model"))
|
||||
if relation != RELATION_INCOMPATIBLE:
|
||||
eligible.append((match, relation))
|
||||
|
||||
if not eligible:
|
||||
raise RecipeValidationError(
|
||||
f"Local checkpoint '{target_name}' has a different base model "
|
||||
"than the recipe"
|
||||
)
|
||||
if len(eligible) > 1:
|
||||
raise RecipeValidationError(
|
||||
f"Multiple local checkpoints match '{target_name}'; "
|
||||
"include the folder path to disambiguate"
|
||||
)
|
||||
target_checkpoint, target_relation = eligible[0]
|
||||
|
||||
recipe_data, updated_checkpoint = await recipe_scanner.update_checkpoint_entry(
|
||||
recipe_id,
|
||||
target_name=target_name,
|
||||
target_checkpoint=target_checkpoint,
|
||||
)
|
||||
|
||||
image_path = recipe_data.get("file_path")
|
||||
if image_path and os.path.exists(image_path):
|
||||
self._exif_utils.append_recipe_metadata(image_path, recipe_data)
|
||||
|
||||
matching_recipes = []
|
||||
if "fingerprint" in recipe_data:
|
||||
matching_recipes = await recipe_scanner.find_recipes_by_fingerprint(
|
||||
recipe_data["fingerprint"]
|
||||
)
|
||||
if recipe_id in matching_recipes:
|
||||
matching_recipes.remove(recipe_id)
|
||||
|
||||
payload: dict[str, Any] = {
|
||||
"success": True,
|
||||
"recipe_id": recipe_id,
|
||||
"updated_checkpoint": updated_checkpoint,
|
||||
"matching_recipes": matching_recipes,
|
||||
}
|
||||
if target_relation == RELATION_COMPATIBLE:
|
||||
# Structured data, not prose — the frontend localizes the warning.
|
||||
payload["base_model_mismatch"] = {
|
||||
"recipe_base_model": recipe_base_model,
|
||||
"checkpoint_base_model": target_checkpoint.get("base_model") or "",
|
||||
}
|
||||
return PersistenceResult(payload)
|
||||
|
||||
async def restore_checkpoint(
|
||||
self,
|
||||
*,
|
||||
recipe_scanner,
|
||||
recipe_id: str,
|
||||
) -> PersistenceResult:
|
||||
"""Restore the checkpoint entry to the state captured before its reconnect."""
|
||||
|
||||
recipe_data, updated_checkpoint = await recipe_scanner.restore_checkpoint_entry(
|
||||
recipe_id
|
||||
)
|
||||
|
||||
image_path = recipe_data.get("file_path")
|
||||
if image_path and os.path.exists(image_path):
|
||||
self._exif_utils.append_recipe_metadata(image_path, recipe_data)
|
||||
|
||||
matching_recipes = []
|
||||
if "fingerprint" in recipe_data:
|
||||
matching_recipes = await recipe_scanner.find_recipes_by_fingerprint(
|
||||
recipe_data["fingerprint"]
|
||||
)
|
||||
if recipe_id in matching_recipes:
|
||||
matching_recipes.remove(recipe_id)
|
||||
|
||||
return PersistenceResult(
|
||||
{
|
||||
"success": True,
|
||||
"recipe_id": recipe_id,
|
||||
"updated_checkpoint": updated_checkpoint,
|
||||
"matching_recipes": matching_recipes,
|
||||
}
|
||||
)
|
||||
|
||||
async def get_checkpoint_reconnect_suggestions(
|
||||
self,
|
||||
*,
|
||||
recipe_scanner,
|
||||
recipe_id: str,
|
||||
query: str | None = None,
|
||||
) -> PersistenceResult:
|
||||
"""Return ranked local checkpoint candidates for reconnecting a recipe entry."""
|
||||
|
||||
recipe_path = await recipe_scanner.get_recipe_json_path(recipe_id)
|
||||
if not recipe_path or not os.path.exists(recipe_path):
|
||||
raise RecipeNotFoundError("Recipe not found")
|
||||
|
||||
with open(recipe_path, "r", encoding="utf-8") as file_obj:
|
||||
recipe_data = json.load(file_obj)
|
||||
|
||||
checkpoint = recipe_data.get("checkpoint")
|
||||
if not isinstance(checkpoint, dict):
|
||||
raise RecipeValidationError("Recipe has no checkpoint entry")
|
||||
|
||||
suggestions = await recipe_scanner.suggest_checkpoint_reconnect_candidates(
|
||||
entry=checkpoint,
|
||||
recipe_base_model=recipe_data.get("base_model"),
|
||||
query=query,
|
||||
)
|
||||
|
||||
return PersistenceResult({"success": True, "suggestions": suggestions})
|
||||
|
||||
async def mark_checkpoint_hash_invalid(
|
||||
self,
|
||||
*,
|
||||
recipe_scanner,
|
||||
recipe_id: str,
|
||||
hash_invalid: bool = True,
|
||||
) -> PersistenceResult:
|
||||
"""Mark the recipe checkpoint entry's hash as unresolvable on CivitAI.
|
||||
|
||||
Called when a download attempt by hash returned "Model not found".
|
||||
The flag makes the entry an unresolved rematch candidate without
|
||||
altering its stored hash/file_name.
|
||||
"""
|
||||
|
||||
recipe_data, updated_checkpoint = (
|
||||
await recipe_scanner.set_checkpoint_entry_hash_invalid(
|
||||
recipe_id,
|
||||
hash_invalid=hash_invalid,
|
||||
)
|
||||
)
|
||||
|
||||
return PersistenceResult(
|
||||
{
|
||||
"success": True,
|
||||
"recipe_id": recipe_id,
|
||||
"hash_invalid": bool(hash_invalid),
|
||||
"updated_checkpoint": updated_checkpoint,
|
||||
}
|
||||
)
|
||||
|
||||
async def bulk_delete(
|
||||
self,
|
||||
*,
|
||||
@@ -619,6 +927,9 @@ class RecipePersistenceService:
|
||||
# Widget saves re-encode an in-memory tensor to PNG/WebP with no
|
||||
# embedded metadata chunks, so a workflow can never be present.
|
||||
"has_workflow": False,
|
||||
# Widget saves read LoRAs straight from the current workflow; an
|
||||
# empty list means the workflow used no LoRAs.
|
||||
"import_info": build_import_info(CHANNEL_WIDGET, None, loras_data),
|
||||
}
|
||||
if checkpoint_entry:
|
||||
recipe_data["checkpoint"] = checkpoint_entry
|
||||
@@ -793,6 +1104,7 @@ class RecipePersistenceService:
|
||||
"modelName": lora.get("name", ""),
|
||||
"modelVersionName": lora.get("version", ""),
|
||||
"isDeleted": lora.get("isDeleted", False),
|
||||
"hashInvalid": lora.get("hashInvalid", False),
|
||||
"exclude": lora.get("exclude", False),
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,79 @@
|
||||
"""Base-model architecture families and compatibility relations.
|
||||
|
||||
CivitAI base-model labels describe fine-tune lineages, not architectures.
|
||||
A LoRA physically loads on any checkpoint sharing its tensor architecture,
|
||||
so e.g. Pony / Illustrious / NoobAI / SDXL 1.0 LoRAs are interchangeable
|
||||
(quality varies, but nothing breaks). Different architectures (SD 1.5 vs
|
||||
SDXL vs Flux) are guaranteed failures and must stay hard-rejected.
|
||||
|
||||
Only families with high-confidence architecture equivalence are listed.
|
||||
Anything not in the table is treated as its own family, i.e. only an exact
|
||||
label match is accepted — unknown new labels never get wrongly waved through.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import Optional
|
||||
|
||||
# Normalized (casefolded, stripped) base-model label -> architecture family.
|
||||
_BASE_MODEL_FAMILIES = {
|
||||
# SD 1.x — all share the original 512px latent UNet.
|
||||
"sd 1.4": "sd1",
|
||||
"sd 1.5": "sd1",
|
||||
"sd 1.5 lcm": "sd1",
|
||||
"sd 1.5 hyper": "sd1",
|
||||
# SDXL lineage — Pony / Illustrious / NoobAI are SDXL fine-tunes.
|
||||
# Note: Pony V7 is AuraFlow-based, NOT SDXL, so it is deliberately absent.
|
||||
"sdxl 1.0": "sdxl",
|
||||
"sdxl lightning": "sdxl",
|
||||
"sdxl hyper": "sdxl",
|
||||
"pony": "sdxl",
|
||||
"pony diffusion": "sdxl",
|
||||
"pony diffusion v6 xl": "sdxl",
|
||||
"illustrious": "sdxl",
|
||||
"illustrious 0.1": "sdxl",
|
||||
"illustrious 1.0": "sdxl",
|
||||
"illustrious 1.1": "sdxl",
|
||||
"noobai": "sdxl",
|
||||
# Flux.1 — dev/schnell/Krea share the 12B rectified-flow transformer.
|
||||
"flux.1 d": "flux1",
|
||||
"flux.1 s": "flux1",
|
||||
"flux.1 krea": "flux1",
|
||||
# SD 3.5 Large and its Turbo distill share the 8B MMDiT. SD 3 (2B) and
|
||||
# SD 3.5 Medium (2.5B) have different shapes and stay unlisted.
|
||||
"sd 3.5 large": "sd35-large",
|
||||
"sd 3.5 large turbo": "sd35-large",
|
||||
}
|
||||
|
||||
_UNKNOWN_TOKENS = {"", "unknown", "other", "none", "null"}
|
||||
|
||||
# Relation constants returned by base_model_relation().
|
||||
RELATION_UNKNOWN = "unknown" # at least one side has no usable label
|
||||
RELATION_SAME = "same" # identical labels
|
||||
RELATION_COMPATIBLE = "compatible" # different labels, same architecture family
|
||||
RELATION_INCOMPATIBLE = "incompatible" # different labels, different/unknown family
|
||||
|
||||
|
||||
def _normalize(label: Optional[str]) -> str:
|
||||
return (label or "").strip().casefold()
|
||||
|
||||
|
||||
def base_model_relation(a: Optional[str], b: Optional[str]) -> str:
|
||||
"""Classify how two base-model labels relate for reconnect purposes.
|
||||
|
||||
``RELATION_UNKNOWN`` when either side has no usable label (callers treat
|
||||
it as lenient-allow), ``RELATION_SAME`` for identical labels,
|
||||
``RELATION_COMPATIBLE`` when both labels map to the same architecture
|
||||
family, and ``RELATION_INCOMPATIBLE`` otherwise — including when a label
|
||||
is missing from the family table (conservative fallback).
|
||||
"""
|
||||
na, nb = _normalize(a), _normalize(b)
|
||||
if na in _UNKNOWN_TOKENS or nb in _UNKNOWN_TOKENS:
|
||||
return RELATION_UNKNOWN
|
||||
if na == nb:
|
||||
return RELATION_SAME
|
||||
fa = _BASE_MODEL_FAMILIES.get(na)
|
||||
fb = _BASE_MODEL_FAMILIES.get(nb)
|
||||
if fa is not None and fa == fb:
|
||||
return RELATION_COMPATIBLE
|
||||
return RELATION_INCOMPATIBLE
|
||||
+26
-5
@@ -1,3 +1,5 @@
|
||||
from typing import Any
|
||||
|
||||
NSFW_LEVELS = {
|
||||
"PG": 1,
|
||||
"PG13": 2,
|
||||
@@ -99,11 +101,30 @@ DEFAULT_HASH_CHUNK_SIZE_MB = 4
|
||||
# absurd 64-bit header length from forcing a multi-GB allocation during scan.
|
||||
MAX_SAFETENSORS_HEADER_BYTES = 64 * 1024 * 1024
|
||||
|
||||
# First 12 chars of the SHA256 of an empty byte string. Some (re-packaging)
|
||||
# training tools write this placeholder into safetensors metadata instead of a
|
||||
# real hash; it must never be treated as a valid AutoV3 — several broken
|
||||
# models sharing it would collide in the hash index and falsely match recipes.
|
||||
INVALID_AUTOV3_EMPTY_HASH = "e3b0c44298fc"
|
||||
# SHA256 of an empty byte string. Some (re-packaging) training tools write a
|
||||
# truncated form of this placeholder into safetensors metadata (as
|
||||
# ``modelspec.hash_sha256`` / ``sshs_model_hash``), and hashing an empty or
|
||||
# unreadable file produces it directly. It must never be treated as a valid
|
||||
# hash: several broken models share it, CivitAI's by-hash index can contain
|
||||
# such polluted entries, and matching it falsely attributes recipes.
|
||||
EMPTY_HASH_SHA256 = "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855"
|
||||
INVALID_AUTOV3_EMPTY_HASH = EMPTY_HASH_SHA256[:12]
|
||||
INVALID_AUTOV2_EMPTY_HASH = EMPTY_HASH_SHA256[:10]
|
||||
|
||||
|
||||
def is_empty_placeholder_hash(value: Any) -> bool:
|
||||
"""True for a 10/12/64-hex-char spelling of the empty-hash placeholder.
|
||||
|
||||
These are the AutoV2, AutoV3 and full-SHA256 forms of the placeholder;
|
||||
such values identify no real model and must never be resolved against
|
||||
local files or CivitAI.
|
||||
"""
|
||||
if not isinstance(value, str):
|
||||
return False
|
||||
v = value.strip().lower()
|
||||
if len(v) not in (10, 12, 64):
|
||||
return False
|
||||
return v == EMPTY_HASH_SHA256[: len(v)]
|
||||
|
||||
# Auto-organize settings
|
||||
AUTO_ORGANIZE_BATCH_SIZE = (
|
||||
|
||||
+67
-3
@@ -348,8 +348,14 @@ class ExifUtils:
|
||||
return image_path
|
||||
|
||||
@staticmethod
|
||||
def append_recipe_metadata(image_path, recipe_data) -> str:
|
||||
"""Append recipe metadata to an image's EXIF data"""
|
||||
def append_recipe_metadata(image_path, recipe_data, pixel_preserving=False) -> str:
|
||||
"""Append recipe metadata to an image's EXIF data
|
||||
|
||||
When ``pixel_preserving`` is True (and the image is a WebP) only the
|
||||
EXIF container is rewritten at the byte level, so the preview pixels
|
||||
are never re-encoded. Local re-import uses this because its source is
|
||||
the recipe's own already-optimized preview image.
|
||||
"""
|
||||
try:
|
||||
if image_path:
|
||||
ext = os.path.splitext(image_path)[1].lower()
|
||||
@@ -417,13 +423,71 @@ class ExifUtils:
|
||||
|
||||
# Append to existing metadata or create new one
|
||||
new_metadata = f"{metadata} \n {recipe_metadata_marker}" if metadata else recipe_metadata_marker
|
||||
|
||||
|
||||
# Write back to the image. Re-import keeps the already-optimized
|
||||
# preview pixels untouched and updates only the WebP EXIF chunk
|
||||
# instead of re-encoding the whole image.
|
||||
if pixel_preserving and image_path.lower().endswith(".webp"):
|
||||
metadata_fields = ExifUtils._load_structured_metadata(image_path)
|
||||
metadata_fields["parameters"] = new_metadata
|
||||
exif_bytes = ExifUtils._build_exif_bytes(metadata_fields)
|
||||
with open(image_path, "rb") as file_obj:
|
||||
image_bytes = file_obj.read()
|
||||
try:
|
||||
updated = ExifUtils._replace_webp_exif(image_bytes, exif_bytes)
|
||||
except ValueError:
|
||||
# Container without an EXIF chunk; fall back to re-encoding.
|
||||
return ExifUtils.update_image_metadata(image_path, new_metadata)
|
||||
with open(image_path, "wb") as file_obj:
|
||||
file_obj.write(updated)
|
||||
return image_path
|
||||
|
||||
# Write back to the image
|
||||
return ExifUtils.update_image_metadata(image_path, new_metadata)
|
||||
except Exception as e:
|
||||
logger.error(f"Error appending recipe metadata: {e}", exc_info=True)
|
||||
return image_path
|
||||
|
||||
@staticmethod
|
||||
def _replace_webp_exif(image_bytes: bytes, exif_bytes: bytes) -> bytes:
|
||||
"""Replace the EXIF chunk of a WebP file without re-encoding pixels."""
|
||||
if image_bytes[:4] != b"RIFF" or image_bytes[8:12] != b"WEBP":
|
||||
raise ValueError("Not a WebP file")
|
||||
# The WebP EXIF chunk stores raw TIFF data; strip the JPEG-style
|
||||
# "Exif\\0\\0" prefix that piexif.dump may prepend.
|
||||
tiff = exif_bytes[6:] if exif_bytes[:6] == b"Exif\x00\x00" else exif_bytes
|
||||
|
||||
out = bytearray(image_bytes[:12])
|
||||
pos = 12
|
||||
exif_payload = None
|
||||
while pos + 8 <= len(image_bytes):
|
||||
fourcc = image_bytes[pos : pos + 4]
|
||||
size = struct.unpack("<I", image_bytes[pos + 4 : pos + 8])[0]
|
||||
chunk_data = image_bytes[pos + 8 : pos + 8 + size]
|
||||
pad = size % 2
|
||||
if fourcc == b"EXIF":
|
||||
exif_payload = tiff
|
||||
else:
|
||||
out += (
|
||||
fourcc
|
||||
+ struct.pack("<I", size)
|
||||
+ chunk_data
|
||||
+ (b"\x00" * pad)
|
||||
)
|
||||
pos += 8 + size + pad
|
||||
|
||||
if exif_payload is None:
|
||||
raise ValueError("WebP has no EXIF chunk")
|
||||
|
||||
out += (
|
||||
b"EXIF"
|
||||
+ struct.pack("<I", len(exif_payload))
|
||||
+ exif_payload
|
||||
+ (b"\x00" * (len(exif_payload) % 2))
|
||||
)
|
||||
out[4:8] = struct.pack("<I", len(out) - 8)
|
||||
return bytes(out)
|
||||
|
||||
@staticmethod
|
||||
def remove_recipe_metadata(user_comment):
|
||||
"""Remove recipe metadata from user comment"""
|
||||
|
||||
+8
-3
@@ -31,9 +31,14 @@ body {
|
||||
--header-height: 48px;
|
||||
--scrollbar-width: 8px;
|
||||
|
||||
--shortcut-bg: var(--color-accent-subtle);
|
||||
--shortcut-border: var(--color-accent-border);
|
||||
--shortcut-text: var(--text-primary);
|
||||
/* Neutral "keycap" style for keyboard shortcut hints (GitHub/Linear-like).
|
||||
Derived from --text-muted so it adapts to every theme/preset. */
|
||||
--shortcut-bg: color-mix(in oklch, var(--text-muted) 10%, transparent);
|
||||
--shortcut-bg-hover: color-mix(in oklch, var(--text-muted) 16%, transparent);
|
||||
--shortcut-border: color-mix(in oklch, var(--text-muted) 30%, transparent);
|
||||
--shortcut-border-hover: color-mix(in oklch, var(--text-muted) 45%, transparent);
|
||||
--shortcut-text: var(--text-muted);
|
||||
--shortcut-shadow: 0 1.5px 0 color-mix(in oklch, var(--text-muted) 30%, transparent);
|
||||
|
||||
--lora-accent-transparent: var(--color-accent-transparent);
|
||||
|
||||
|
||||
@@ -671,23 +671,46 @@ body.hide-card-version .hl-badge {
|
||||
user-select: none;
|
||||
}
|
||||
|
||||
/* Compact LoRA status pill: state icon + available/total fraction (e.g. "2/3").
|
||||
The icon switches by state (warning/check/layers) so status never relies on
|
||||
color alone; the tooltip spells out the full details. */
|
||||
.lora-count {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 4px;
|
||||
background: rgba(255, 255, 255, 0.2);
|
||||
padding: 2px 8px;
|
||||
border-radius: var(--border-radius-xs);
|
||||
flex-shrink: 0;
|
||||
/* Pin to the bottom-right corner of the footer, matching how model card
|
||||
footer .card-actions behave when the title wraps to multiple lines */
|
||||
align-self: flex-end;
|
||||
font-size: 0.85em;
|
||||
position: relative;
|
||||
padding: 2px 8px;
|
||||
background: rgba(255, 255, 255, 0.2);
|
||||
border: 1px solid rgba(255, 255, 255, 0.25);
|
||||
border-radius: var(--border-radius-xs);
|
||||
}
|
||||
|
||||
.lora-count.ready {
|
||||
background: rgba(46, 204, 113, 0.3);
|
||||
border-color: rgba(46, 204, 113, 0.6);
|
||||
}
|
||||
|
||||
.lora-count.missing {
|
||||
background: rgba(231, 76, 60, 0.3);
|
||||
background: rgba(231, 76, 60, 0.35);
|
||||
border-color: rgba(231, 76, 60, 0.65);
|
||||
}
|
||||
|
||||
/* Partial: usable but degraded — some LoRAs are unobtainable (deleted from
|
||||
the source or unresolvable hash) and are skipped when the recipe is used.
|
||||
Amber sits between ready green and missing red. */
|
||||
.lora-count.partial {
|
||||
background: rgba(243, 156, 18, 0.35);
|
||||
border-color: rgba(243, 156, 18, 0.65);
|
||||
}
|
||||
|
||||
/* Unavailable: no usable LoRA at all — gray marks the recipe as dead. */
|
||||
.lora-count.unavailable {
|
||||
background: rgba(149, 165, 166, 0.35);
|
||||
border-color: rgba(149, 165, 166, 0.65);
|
||||
}
|
||||
|
||||
.placeholder-message {
|
||||
|
||||
@@ -249,10 +249,10 @@
|
||||
font-family: inherit;
|
||||
font-size: 0.68rem;
|
||||
font-weight: 500;
|
||||
color: var(--text-muted);
|
||||
/* Subtle tint derived from text color so it adapts to both light & dark themes */
|
||||
background: color-mix(in oklch, var(--text-muted) 12%, transparent);
|
||||
border: 1px solid color-mix(in oklch, var(--text-muted) 25%, transparent);
|
||||
color: var(--shortcut-text);
|
||||
background: var(--shortcut-bg);
|
||||
border: 1px solid var(--shortcut-border);
|
||||
box-shadow: var(--shortcut-shadow);
|
||||
border-radius: var(--border-radius-xs, 3px);
|
||||
line-height: 1;
|
||||
}
|
||||
|
||||
@@ -669,25 +669,6 @@
|
||||
/* Hide the old style */
|
||||
}
|
||||
|
||||
/* Update deleted badge to be more prominent */
|
||||
.deleted-badge {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
background: var(--lora-warning);
|
||||
color: white;
|
||||
padding: 4px 8px;
|
||||
border-radius: var(--border-radius-xs);
|
||||
font-size: 0.8em;
|
||||
font-weight: 500;
|
||||
white-space: nowrap;
|
||||
flex-shrink: 0;
|
||||
}
|
||||
|
||||
.deleted-badge i {
|
||||
margin-right: 4px;
|
||||
font-size: 0.9em;
|
||||
}
|
||||
|
||||
/* Error message styling */
|
||||
.error-message {
|
||||
color: var(--lora-error);
|
||||
|
||||
@@ -1078,6 +1078,19 @@
|
||||
color: #facc15;
|
||||
}
|
||||
|
||||
/* Partial: usable but degraded — some LoRAs are unobtainable and skipped.
|
||||
Orange sits between ready green and missing amber. */
|
||||
.recipe-card__badge--partial {
|
||||
background: rgba(249, 115, 22, 0.2);
|
||||
color: #fb923c;
|
||||
}
|
||||
|
||||
/* Unavailable: no usable LoRA at all — red marks the recipe as dead. */
|
||||
.recipe-card__badge--unavailable {
|
||||
background: rgba(239, 68, 68, 0.2);
|
||||
color: #f87171;
|
||||
}
|
||||
|
||||
.recipe-card__badge--empty {
|
||||
background: rgba(148, 163, 184, 0.18);
|
||||
color: #e2e8f0;
|
||||
@@ -1093,6 +1106,16 @@
|
||||
background: rgba(245, 199, 43, 0.22);
|
||||
}
|
||||
|
||||
[data-theme="light"] .recipe-card__badge--partial {
|
||||
color: #c2410c;
|
||||
background: rgba(249, 115, 22, 0.18);
|
||||
}
|
||||
|
||||
[data-theme="light"] .recipe-card__badge--unavailable {
|
||||
color: #b91c1c;
|
||||
background: rgba(239, 68, 68, 0.16);
|
||||
}
|
||||
|
||||
[data-theme="light"] .recipe-card__badge--empty {
|
||||
color: rgba(71, 85, 105, 0.9);
|
||||
background: rgba(148, 163, 184, 0.2);
|
||||
|
||||
@@ -65,4 +65,13 @@
|
||||
|
||||
.add-preset-btn:hover {
|
||||
opacity: 0.9;
|
||||
}
|
||||
|
||||
.add-preset-btn:disabled {
|
||||
opacity: 0.5;
|
||||
cursor: not-allowed;
|
||||
}
|
||||
|
||||
.add-preset-btn:hover:disabled {
|
||||
opacity: 0.5;
|
||||
}
|
||||
@@ -115,6 +115,9 @@
|
||||
position: relative;
|
||||
overflow: hidden;
|
||||
border-radius: var(--border-radius-sm);
|
||||
/* Horizontal touch pans are claimed for swipe navigation (ShowcaseView);
|
||||
vertical pans still scroll the modal */
|
||||
touch-action: pan-y;
|
||||
}
|
||||
|
||||
.main-media-container {
|
||||
@@ -134,6 +137,32 @@
|
||||
margin-bottom: 0;
|
||||
}
|
||||
|
||||
/* Direction-aware slide on example switches (set by updateMainDisplay) */
|
||||
.main-media-container.slide-from-right .media-wrapper {
|
||||
animation: gallery-slide-from-right 0.25s ease;
|
||||
}
|
||||
|
||||
.main-media-container.slide-from-left .media-wrapper {
|
||||
animation: gallery-slide-from-left 0.25s ease;
|
||||
}
|
||||
|
||||
@keyframes gallery-slide-from-right {
|
||||
from { transform: translateX(32px); opacity: 0; }
|
||||
to { transform: translateX(0); opacity: 1; }
|
||||
}
|
||||
|
||||
@keyframes gallery-slide-from-left {
|
||||
from { transform: translateX(-32px); opacity: 0; }
|
||||
to { transform: translateX(0); opacity: 1; }
|
||||
}
|
||||
|
||||
@media (prefers-reduced-motion: reduce) {
|
||||
.main-media-container.slide-from-right .media-wrapper,
|
||||
.main-media-container.slide-from-left .media-wrapper {
|
||||
animation: none;
|
||||
}
|
||||
}
|
||||
|
||||
.main-media-container .media-wrapper img,
|
||||
.main-media-container .media-wrapper video {
|
||||
position: absolute;
|
||||
|
||||
@@ -13,6 +13,16 @@
|
||||
overflow: auto; /* Change from hidden to auto to allow scrolling */
|
||||
}
|
||||
|
||||
/* Software-rendering fallback (set by applyModalBackdropBlurPolicy): a
|
||||
full-viewport backdrop-filter forces per-frame CPU rasterization of
|
||||
everything behind the modal and freezes the browser (issue #1092) */
|
||||
html.no-modal-backdrop-blur .modal,
|
||||
html.no-modal-backdrop-blur .delete-modal,
|
||||
html.no-modal-backdrop-blur .batch-preview-select-all {
|
||||
backdrop-filter: none;
|
||||
-webkit-backdrop-filter: none;
|
||||
}
|
||||
|
||||
/* Prevent body scroll when modal is open */
|
||||
body.modal-open {
|
||||
position: fixed;
|
||||
|
||||
@@ -921,8 +921,8 @@
|
||||
position: sticky;
|
||||
top: 0;
|
||||
z-index: 1;
|
||||
backdrop-filter: blur(8px);
|
||||
-webkit-backdrop-filter: blur(8px);
|
||||
backdrop-filter: blur(var(--modal-backdrop-blur, 6px));
|
||||
-webkit-backdrop-filter: blur(var(--modal-backdrop-blur, 6px));
|
||||
}
|
||||
|
||||
.batch-preview-select-all input[type="checkbox"] {
|
||||
|
||||
@@ -167,6 +167,29 @@
|
||||
box-shadow: var(--shadow-lg);
|
||||
}
|
||||
|
||||
/* Replay Tutorial button: badge hidden until the button is flagged as new content */
|
||||
.replay-tutorial-btn .new-content-badge {
|
||||
display: none;
|
||||
background-color: rgba(255, 255, 255, 0.22);
|
||||
color: #fff;
|
||||
box-shadow: none;
|
||||
margin-left: 2px;
|
||||
}
|
||||
|
||||
.replay-tutorial-btn.has-new-content .new-content-badge {
|
||||
display: inline-flex;
|
||||
}
|
||||
|
||||
/* One-time attention pulse when the button is flagged as new content */
|
||||
@keyframes new-content-glow {
|
||||
0% { box-shadow: 0 0 0 0 oklch(from var(--lora-accent) l c h / 55%); }
|
||||
100% { box-shadow: 0 0 0 16px transparent; }
|
||||
}
|
||||
|
||||
.replay-tutorial-btn.has-new-content {
|
||||
animation: new-content-glow 1.2s ease-out 3;
|
||||
}
|
||||
|
||||
/* Update video list styles */
|
||||
.video-list {
|
||||
display: flex;
|
||||
@@ -304,4 +327,87 @@
|
||||
/* Dark theme adjustments */
|
||||
[data-theme="dark"] .video-container {
|
||||
background-color: var(--surface-hover);
|
||||
}
|
||||
}
|
||||
/* Replay tutorial button styles */
|
||||
.help-actions {
|
||||
margin-top: var(--space-3);
|
||||
}
|
||||
|
||||
.replay-tutorial-btn {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
gap: 8px;
|
||||
padding: 10px 20px;
|
||||
border-radius: var(--border-radius-sm);
|
||||
font-weight: 500;
|
||||
cursor: pointer;
|
||||
transition: var(--transition-base);
|
||||
background-color: var(--lora-accent);
|
||||
color: white;
|
||||
border: none;
|
||||
}
|
||||
|
||||
.replay-tutorial-btn:hover {
|
||||
background-color: oklch(from var(--lora-accent) l c h / 85%);
|
||||
}
|
||||
|
||||
/* Shortcuts tab styles */
|
||||
.shortcuts-section {
|
||||
margin-bottom: var(--space-3);
|
||||
}
|
||||
|
||||
.shortcuts-section h4 {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 8px;
|
||||
margin-bottom: var(--space-1);
|
||||
}
|
||||
|
||||
.shortcuts-list {
|
||||
list-style-type: none;
|
||||
padding-left: var(--space-3);
|
||||
}
|
||||
|
||||
.shortcuts-list li {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 12px;
|
||||
margin-bottom: var(--space-1);
|
||||
}
|
||||
|
||||
.shortcut-keys {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
gap: 2px;
|
||||
flex-shrink: 0;
|
||||
min-width: 150px;
|
||||
}
|
||||
|
||||
.shortcut-sep {
|
||||
color: var(--text-muted);
|
||||
font-size: 0.75rem;
|
||||
margin: 0 1px;
|
||||
}
|
||||
|
||||
.shortcuts-list kbd {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
min-width: 18px;
|
||||
height: 18px;
|
||||
padding: 0 4px;
|
||||
font-family: inherit;
|
||||
font-size: 0.68rem;
|
||||
font-weight: 500;
|
||||
color: var(--shortcut-text);
|
||||
background: var(--shortcut-bg);
|
||||
border: 1px solid var(--shortcut-border);
|
||||
box-shadow: var(--shortcut-shadow);
|
||||
border-radius: var(--border-radius-xs, 3px);
|
||||
line-height: 1;
|
||||
}
|
||||
|
||||
.shortcut-description {
|
||||
font-size: 0.9em;
|
||||
opacity: 0.85;
|
||||
}
|
||||
|
||||
@@ -190,6 +190,44 @@
|
||||
justify-content: center;
|
||||
}
|
||||
|
||||
/* Icon-only companion to the Send button: same pill style as its neighbors,
|
||||
just without the text label. */
|
||||
.modal-copy-btn {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
padding: 6px 10px;
|
||||
background: var(--surface-subtle);
|
||||
border: 1px solid rgba(0, 0, 0, 0.1);
|
||||
border-radius: var(--border-radius-sm);
|
||||
color: var(--text-color);
|
||||
cursor: pointer;
|
||||
font-size: 0.9em;
|
||||
transition: var(--transition-base);
|
||||
}
|
||||
|
||||
[data-theme="dark"] .modal-copy-btn {
|
||||
background: var(--surface-subtle);
|
||||
border: 1px solid var(--lora-border);
|
||||
}
|
||||
|
||||
.modal-copy-btn:hover {
|
||||
background: oklch(var(--lora-accent-l) var(--lora-accent-c) var(--lora-accent-h) / 0.1);
|
||||
border-color: var(--lora-accent);
|
||||
transform: translateY(-1px);
|
||||
}
|
||||
|
||||
.modal-copy-btn:active {
|
||||
transform: translateY(0);
|
||||
}
|
||||
|
||||
.modal-copy-btn i {
|
||||
font-size: 14px;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
}
|
||||
|
||||
@media (max-height: 860px) {
|
||||
.recipe-header-actions {
|
||||
padding-bottom: 4px;
|
||||
@@ -677,6 +715,72 @@
|
||||
min-height: 0;
|
||||
}
|
||||
|
||||
/* Empty LoRA list + collapsible "Why no LoRAs?" explanation */
|
||||
.no-loras {
|
||||
color: var(--text-muted);
|
||||
font-size: 0.9em;
|
||||
padding: var(--space-2) 0;
|
||||
}
|
||||
|
||||
.no-loras-reason {
|
||||
margin: var(--space-1) 0 var(--space-2);
|
||||
border: 1px solid var(--lora-border);
|
||||
border-radius: var(--border-radius-xs);
|
||||
background: var(--lora-surface);
|
||||
font-size: 0.85em;
|
||||
}
|
||||
|
||||
.no-loras-reason summary {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: var(--space-2);
|
||||
padding: var(--space-2) var(--space-3);
|
||||
cursor: pointer;
|
||||
color: var(--text-muted);
|
||||
user-select: none;
|
||||
list-style: none;
|
||||
}
|
||||
|
||||
/* Hide the native disclosure triangle; rotate the icon instead. */
|
||||
.no-loras-reason summary::-webkit-details-marker {
|
||||
display: none;
|
||||
}
|
||||
|
||||
.no-loras-reason summary i {
|
||||
transition: transform 0.15s ease;
|
||||
}
|
||||
|
||||
.no-loras-reason[open] summary i {
|
||||
transform: rotate(90deg);
|
||||
}
|
||||
|
||||
.no-loras-reason summary:hover {
|
||||
color: var(--text-color);
|
||||
}
|
||||
|
||||
.no-loras-reason-body {
|
||||
padding: 0 var(--space-3) var(--space-3);
|
||||
color: var(--text-muted);
|
||||
}
|
||||
|
||||
.no-loras-reason-body ul {
|
||||
margin: 0;
|
||||
padding-left: var(--space-5);
|
||||
}
|
||||
|
||||
.no-loras-reason-body li {
|
||||
margin: var(--space-1) 0;
|
||||
}
|
||||
|
||||
.no-loras-bullet-label {
|
||||
color: var(--text-color);
|
||||
font-weight: 600;
|
||||
}
|
||||
|
||||
.no-loras-inferred-note {
|
||||
font-style: italic;
|
||||
}
|
||||
|
||||
.recipe-checkpoint-container {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
@@ -691,6 +795,9 @@
|
||||
|
||||
.recipe-lora-item {
|
||||
display: flex;
|
||||
/* The reconnect panel is a full-width child that wraps below the
|
||||
thumbnail + content row. */
|
||||
flex-wrap: wrap;
|
||||
gap: var(--space-2);
|
||||
padding: 10px var(--space-2);
|
||||
border: 1px solid var(--border-color);
|
||||
@@ -700,26 +807,42 @@
|
||||
will-change: transform;
|
||||
/* Create a new containing block for absolutely positioned descendants */
|
||||
transform: translateZ(0);
|
||||
cursor: pointer; /* Make it clear the item is clickable */
|
||||
/* Rows are not clickable by default; only in-library rows navigate */
|
||||
cursor: default;
|
||||
transition: transform 0.2s ease, box-shadow 0.2s ease, border-color 0.2s ease;
|
||||
}
|
||||
|
||||
.recipe-lora-item:hover {
|
||||
/* Click affordance (pointer + hover lift) is reserved for rows that
|
||||
actually navigate: in-library items open the local detail view. */
|
||||
.recipe-lora-item.exists-locally {
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
.recipe-lora-item.exists-locally:hover {
|
||||
transform: translateY(-1px);
|
||||
box-shadow: var(--shadow-header);
|
||||
border-color: var(--lora-accent);
|
||||
}
|
||||
|
||||
.recipe-lora-item.exists-locally:focus-visible {
|
||||
outline: 2px solid var(--lora-accent);
|
||||
outline-offset: 2px;
|
||||
}
|
||||
|
||||
.recipe-lora-item.exists-locally {
|
||||
background: oklch(var(--lora-accent) / 0.05);
|
||||
border-left: 4px solid var(--lora-accent);
|
||||
}
|
||||
|
||||
.recipe-lora-item.checkpoint-item {
|
||||
cursor: pointer;
|
||||
cursor: default;
|
||||
padding-top: 8px;
|
||||
padding-bottom: 8px;
|
||||
align-items: center;
|
||||
align-items: flex-start;
|
||||
}
|
||||
|
||||
.recipe-lora-item.checkpoint-item.exists-locally {
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
.recipe-lora-item.missing-locally {
|
||||
@@ -776,12 +899,24 @@
|
||||
transform: translateZ(0);
|
||||
}
|
||||
|
||||
.recipe-lora-title {
|
||||
display: flex;
|
||||
/* Top-align so the inline Civitai link stays glued to the FIRST line
|
||||
even when a long model name wraps to two lines. */
|
||||
align-items: flex-start;
|
||||
gap: 6px;
|
||||
flex: 1;
|
||||
min-width: 0; /* Allow the clamped title to shrink next to the badge */
|
||||
}
|
||||
|
||||
.recipe-lora-content h4 {
|
||||
margin: 0;
|
||||
font-size: 1em;
|
||||
color: var(--text-color);
|
||||
flex: 1;
|
||||
max-width: calc(100% - 120px); /* Make room for the badge */
|
||||
/* Shrink (for the 2-line clamp) but don't grow: the inline Civitai link
|
||||
should sit right after the name, not pushed to the far edge. */
|
||||
flex: 0 1 auto;
|
||||
min-width: 0;
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
display: -webkit-box;
|
||||
@@ -821,8 +956,36 @@
|
||||
color: var(--lora-accent);
|
||||
}
|
||||
|
||||
/* Restore icon for manually reconnected entries: its presence on the info
|
||||
row doubles as the "was reconnected" marker. Shared by LoRA and
|
||||
checkpoint entries, which use the same info-row flex layout. */
|
||||
.lora-undo-reconnect,
|
||||
.checkpoint-undo-reconnect {
|
||||
margin-left: auto;
|
||||
background: none;
|
||||
border: none;
|
||||
color: var(--text-color);
|
||||
opacity: 0.55;
|
||||
cursor: pointer;
|
||||
padding: 2px 4px;
|
||||
border-radius: var(--border-radius-xs);
|
||||
font-size: 0.95em;
|
||||
line-height: 1;
|
||||
transition: var(--transition-base);
|
||||
}
|
||||
|
||||
.lora-undo-reconnect:hover,
|
||||
.lora-undo-reconnect:focus-visible,
|
||||
.checkpoint-undo-reconnect:hover,
|
||||
.checkpoint-undo-reconnect:focus-visible {
|
||||
opacity: 1;
|
||||
color: var(--lora-accent);
|
||||
background: var(--lora-surface);
|
||||
}
|
||||
|
||||
.local-badge,
|
||||
.missing-badge {
|
||||
.missing-badge,
|
||||
.invalid-hash-badge {
|
||||
position: absolute;
|
||||
right: 0;
|
||||
top: 0;
|
||||
@@ -833,21 +996,12 @@
|
||||
|
||||
/* Specific styles for recipe modal badges - update z-index */
|
||||
.recipe-lora-header .local-badge,
|
||||
.recipe-lora-header .missing-badge {
|
||||
.recipe-lora-header .missing-badge,
|
||||
.recipe-lora-header .invalid-hash-badge {
|
||||
z-index: 2; /* Ensure the badge is above other elements */
|
||||
backface-visibility: hidden;
|
||||
}
|
||||
|
||||
/* Ensure local-path tooltip is properly positioned and won't move during scroll */
|
||||
.recipe-lora-header .local-badge .local-path {
|
||||
z-index: 3;
|
||||
top: calc(100% + 4px); /* Position tooltip below the badge */
|
||||
right: -4px; /* Align with the badge */
|
||||
max-width: 250px;
|
||||
/* Force hardware acceleration for Chrome */
|
||||
transform: translateZ(0);
|
||||
}
|
||||
|
||||
.missing-badge {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
@@ -885,49 +1039,42 @@
|
||||
font-size: 0.9em;
|
||||
}
|
||||
|
||||
/* Add reconnect functionality styles */
|
||||
.deleted-badge.reconnectable {
|
||||
position: relative;
|
||||
cursor: pointer;
|
||||
transition: background-color 0.2s ease;
|
||||
}
|
||||
|
||||
.deleted-badge.reconnectable:hover {
|
||||
background-color: var(--lora-accent);
|
||||
}
|
||||
|
||||
.deleted-badge .reconnect-tooltip {
|
||||
position: absolute;
|
||||
display: none;
|
||||
background-color: var(--card-bg);
|
||||
color: var(--text-color);
|
||||
padding: 8px 12px;
|
||||
/* Unresolvable-hash badge: the entry has identity fields, but its hash is
|
||||
not registered on CivitAI (stale or invalid). */
|
||||
.invalid-hash-badge {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
background: var(--lora-warning);
|
||||
color: white;
|
||||
padding: 3px 6px;
|
||||
border-radius: var(--border-radius-xs);
|
||||
border: 1px solid var(--border-color);
|
||||
box-shadow: var(--shadow-header);
|
||||
z-index: var(--z-overlay);
|
||||
width: max-content;
|
||||
max-width: 200px;
|
||||
font-size: 0.85rem;
|
||||
font-weight: normal;
|
||||
top: calc(100% + 5px);
|
||||
left: 0;
|
||||
margin-left: -100px;
|
||||
font-size: 0.75em;
|
||||
font-weight: 500;
|
||||
white-space: nowrap;
|
||||
flex-shrink: 0;
|
||||
}
|
||||
|
||||
.deleted-badge.reconnectable:hover .reconnect-tooltip {
|
||||
display: block;
|
||||
.invalid-hash-badge i {
|
||||
margin-right: 4px;
|
||||
font-size: 0.9em;
|
||||
}
|
||||
|
||||
/* LoRA reconnect container */
|
||||
/* Deleted badge is a pure status indicator; the reconnect action lives on
|
||||
an explicit ghost button in the item's action row. */
|
||||
|
||||
/* LoRA reconnect container: an inline extension of the item, not a nested
|
||||
card — a dashed separator reads lighter than another bordered box inside
|
||||
an already bordered item. It is a direct child of .recipe-lora-item and
|
||||
spans the full row (thumbnail column included). */
|
||||
.lora-reconnect-container {
|
||||
display: none;
|
||||
flex-direction: column;
|
||||
background: var(--lora-surface);
|
||||
border: 1px solid var(--border-color);
|
||||
border-radius: var(--border-radius-xs);
|
||||
padding: 12px;
|
||||
margin-top: 10px;
|
||||
flex-basis: 100%;
|
||||
/* Flex items default to min-width:auto — never let content force the
|
||||
panel wider than the row. */
|
||||
min-width: 0;
|
||||
border-top: 1px dashed var(--border-color);
|
||||
padding-top: 10px;
|
||||
gap: 10px;
|
||||
}
|
||||
|
||||
@@ -954,18 +1101,6 @@
|
||||
font-size: 0.85em;
|
||||
}
|
||||
|
||||
.reconnect-instructions code {
|
||||
background: rgba(0, 0, 0, 0.1);
|
||||
padding: 2px 4px;
|
||||
border-radius: 3px;
|
||||
font-family: var(--font-mono);
|
||||
font-size: 0.9em;
|
||||
}
|
||||
|
||||
[data-theme="dark"] .reconnect-instructions code {
|
||||
background: rgba(255, 255, 255, 0.1);
|
||||
}
|
||||
|
||||
.reconnect-form {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
@@ -973,13 +1108,108 @@
|
||||
}
|
||||
|
||||
.reconnect-input {
|
||||
width: calc(100% - 20px);
|
||||
box-sizing: border-box;
|
||||
width: 100%;
|
||||
padding: 8px 10px;
|
||||
border: 1px solid var(--border-color);
|
||||
border-radius: var(--border-radius-xs);
|
||||
background: var(--bg-color);
|
||||
color: var(--text-color);
|
||||
font-size: 0.95em;
|
||||
}
|
||||
|
||||
.reconnect-error {
|
||||
display: none;
|
||||
margin: 0;
|
||||
color: var(--lora-error);
|
||||
font-size: 0.85em;
|
||||
}
|
||||
|
||||
.reconnect-error.active {
|
||||
display: block;
|
||||
}
|
||||
|
||||
.reconnect-suggestions {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 4px;
|
||||
}
|
||||
|
||||
.reconnect-suggestions:empty {
|
||||
display: none;
|
||||
}
|
||||
|
||||
.reconnect-suggestions-loading,
|
||||
.reconnect-suggestions-empty {
|
||||
font-size: 0.85em;
|
||||
color: var(--text-color);
|
||||
opacity: 0.7;
|
||||
padding: 4px 2px;
|
||||
}
|
||||
|
||||
.reconnect-suggestion {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 10px;
|
||||
width: 100%;
|
||||
/* Buttons default to content-box: without this, width:100% + padding +
|
||||
border overflows the panel by 18px and forces a horizontal scrollbar. */
|
||||
box-sizing: border-box;
|
||||
padding: 6px 8px;
|
||||
border: 1px solid var(--border-color);
|
||||
border-radius: var(--border-radius-xs);
|
||||
background: var(--lora-surface, var(--bg-color));
|
||||
color: var(--text-color);
|
||||
font-size: 0.95em;
|
||||
text-align: left;
|
||||
cursor: pointer;
|
||||
transition: var(--transition-base);
|
||||
}
|
||||
|
||||
.reconnect-suggestion:hover,
|
||||
.reconnect-suggestion:focus-visible {
|
||||
border-color: var(--lora-accent);
|
||||
}
|
||||
|
||||
.reconnect-suggestion-preview {
|
||||
width: 40px;
|
||||
height: 40px;
|
||||
border-radius: var(--border-radius-xs);
|
||||
object-fit: cover;
|
||||
flex-shrink: 0;
|
||||
background: var(--bg-color);
|
||||
}
|
||||
|
||||
.reconnect-suggestion-info {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 2px;
|
||||
min-width: 0;
|
||||
flex: 1;
|
||||
}
|
||||
|
||||
.reconnect-suggestion-name {
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
.reconnect-suggestion-secondary {
|
||||
font-size: 0.9em;
|
||||
opacity: 0.7;
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
.reconnect-suggestion-reason {
|
||||
flex-shrink: 0;
|
||||
padding: 2px 6px;
|
||||
border-radius: var(--border-radius-xs);
|
||||
border: 1px solid var(--border-color);
|
||||
color: var(--lora-accent);
|
||||
font-size: 0.85em;
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
.reconnect-actions {
|
||||
@@ -1131,69 +1361,78 @@
|
||||
align-items: center;
|
||||
justify-content: flex-end;
|
||||
flex-shrink: 0;
|
||||
min-width: 110px;
|
||||
z-index: 2;
|
||||
}
|
||||
|
||||
/* Update the local-badge and missing-badge to be positioned within the badge-container */
|
||||
/* Badges are pure status indicators; actions live in .recipe-lora-actions */
|
||||
.badge-container .local-badge,
|
||||
.badge-container .missing-badge,
|
||||
.badge-container .deleted-badge {
|
||||
.badge-container .deleted-badge,
|
||||
.badge-container .invalid-hash-badge {
|
||||
position: static; /* Override absolute positioning */
|
||||
transform: none; /* Remove the transform */
|
||||
}
|
||||
|
||||
/* Ensure the tooltip is still properly positioned */
|
||||
.badge-container .local-badge .local-path {
|
||||
position: fixed; /* Keep as fixed for Chrome */
|
||||
z-index: 100;
|
||||
/* Tonal (soft) status badges: a tinted fill + colored text reads calmer
|
||||
than solid blocks when several rows stack, and matches the tonal
|
||||
"N missing" summary pill above the list. */
|
||||
.badge-container .local-badge {
|
||||
background: oklch(var(--lora-accent) / 0.12);
|
||||
color: var(--lora-accent);
|
||||
border: 1px solid oklch(var(--lora-accent) / 0.35);
|
||||
}
|
||||
|
||||
.badge-container .resource-action {
|
||||
margin-left: auto;
|
||||
.badge-container .missing-badge {
|
||||
background: oklch(var(--lora-error) / 0.14);
|
||||
color: var(--lora-error);
|
||||
border: 1px solid oklch(var(--lora-error) / 0.35);
|
||||
}
|
||||
|
||||
/* Add styles for missing LoRAs download feature */
|
||||
.recipe-status.missing {
|
||||
.badge-container .deleted-badge {
|
||||
background: rgba(127, 127, 127, 0.15);
|
||||
color: var(--text-muted);
|
||||
border: 1px solid rgba(127, 127, 127, 0.35);
|
||||
}
|
||||
|
||||
.badge-container .invalid-hash-badge {
|
||||
background: oklch(var(--lora-warning) / 0.14);
|
||||
color: var(--lora-warning);
|
||||
border: 1px solid oklch(var(--lora-warning) / 0.35);
|
||||
}
|
||||
|
||||
/* Pin the recipe status-badge family (missing / deleted / invalid-hash) to its
|
||||
compact size. import-modal.css defines unscoped .missing-badge/.deleted-badge
|
||||
and is loaded AFTER this file, so without this higher-specificity rule its
|
||||
padding/font-size would clobber recipe modal's, leaving invalid-hash-badge
|
||||
(which has no import counterpart) at a different size. local-badge
|
||||
intentionally keeps the global shared.css size. */
|
||||
#recipeModal .badge-container .missing-badge,
|
||||
#recipeModal .badge-container .deleted-badge,
|
||||
#recipeModal .badge-container .invalid-hash-badge {
|
||||
padding: 3px 6px;
|
||||
font-size: 0.75em;
|
||||
}
|
||||
|
||||
/* Missing LoRAs status is a real button: the affordance must be visible at
|
||||
rest (persistent border), not only on hover. */
|
||||
.recipe-status.missing.clickable {
|
||||
position: relative;
|
||||
cursor: pointer;
|
||||
transition: background-color 0.2s ease;
|
||||
font: inherit;
|
||||
background: oklch(var(--lora-error) / 0.12);
|
||||
color: var(--lora-error);
|
||||
border: 1px solid oklch(var(--lora-error) / 0.45);
|
||||
transition: background-color 0.2s ease, box-shadow 0.2s ease;
|
||||
}
|
||||
|
||||
.recipe-status.missing:hover {
|
||||
background-color: rgba(var(--lora-warning-rgb, 255, 165, 0), 0.2);
|
||||
.recipe-status.missing.clickable:hover {
|
||||
background: oklch(var(--lora-error) / 0.22);
|
||||
box-shadow: 0 0 0 2px oklch(var(--lora-error) / 0.25);
|
||||
}
|
||||
|
||||
.recipe-status.missing .missing-tooltip {
|
||||
position: absolute;
|
||||
display: none;
|
||||
background-color: var(--card-bg);
|
||||
color: var(--text-color);
|
||||
padding: 8px 12px;
|
||||
border-radius: var(--border-radius-xs);
|
||||
border: 1px solid var(--border-color);
|
||||
box-shadow: var(--shadow-header);
|
||||
z-index: var(--z-overlay);
|
||||
width: max-content;
|
||||
max-width: 200px;
|
||||
font-size: 0.85rem;
|
||||
font-weight: normal;
|
||||
margin-left: -100px;
|
||||
margin-top: -65px;
|
||||
}
|
||||
|
||||
.recipe-status.missing:hover .missing-tooltip {
|
||||
display: block;
|
||||
}
|
||||
|
||||
.recipe-status.clickable {
|
||||
cursor: pointer;
|
||||
padding: 4px 8px;
|
||||
border-radius: var(--border-radius-xs);
|
||||
}
|
||||
|
||||
.recipe-status.clickable:hover {
|
||||
background-color: rgba(var(--lora-warning-rgb, 255, 165, 0), 0.2);
|
||||
.recipe-status.missing.clickable:focus-visible {
|
||||
outline: 2px solid var(--lora-error);
|
||||
outline-offset: 2px;
|
||||
}
|
||||
|
||||
.recipe-checkpoint-meta {
|
||||
@@ -1205,11 +1444,11 @@
|
||||
margin-bottom: 2px;
|
||||
}
|
||||
|
||||
.recipe-checkpoint-meta .checkpoint-type {
|
||||
background: var(--lora-surface);
|
||||
padding: 2px 8px;
|
||||
border-radius: var(--border-radius-xs);
|
||||
color: var(--text-color);
|
||||
/* Checkpoint type is low-information text (the entry's position above the
|
||||
divider already implies "checkpoint"), so it renders as plain muted text
|
||||
instead of a chip competing with the base-model chip. */
|
||||
.recipe-checkpoint-meta .checkpoint-type-text {
|
||||
color: var(--text-muted);
|
||||
}
|
||||
|
||||
.recipe-resource-actions {
|
||||
@@ -1253,3 +1492,148 @@
|
||||
.resource-action.primary:hover {
|
||||
background: color-mix(in oklch, var(--lora-accent), black 10%);
|
||||
}
|
||||
|
||||
/* Ghost variant: secondary remediation actions (e.g. Reconnect), matching
|
||||
the ghost action pattern used in the versions tab. */
|
||||
.resource-action.ghost {
|
||||
background: transparent;
|
||||
color: var(--lora-accent);
|
||||
border-color: oklch(var(--lora-accent) / 0.4);
|
||||
}
|
||||
|
||||
.resource-action.ghost:hover {
|
||||
background: oklch(var(--lora-accent) / 0.1);
|
||||
border-color: var(--lora-accent);
|
||||
}
|
||||
|
||||
/* Per-item action row: remediation lives next to the status badge that
|
||||
surfaced the problem (download / reconnect / external link). Right-aligned
|
||||
so the reading order stays: name → status → meta → actions. */
|
||||
.recipe-lora-actions {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: flex-end;
|
||||
flex-wrap: wrap;
|
||||
gap: 8px;
|
||||
margin-top: 6px;
|
||||
}
|
||||
|
||||
/* External-link affordance, mirroring .version-civitai-link in the
|
||||
versions tab: leaving the app is always an explicit, signposted action. */
|
||||
.recipe-civitai-link {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
width: 24px;
|
||||
height: 24px;
|
||||
border-radius: 999px;
|
||||
color: var(--text-muted);
|
||||
text-decoration: none;
|
||||
flex: 0 0 auto;
|
||||
transition: color 0.2s ease, background-color 0.2s ease, transform 0.2s ease;
|
||||
}
|
||||
|
||||
.recipe-civitai-link:hover,
|
||||
.recipe-civitai-link:focus-visible {
|
||||
color: var(--lora-accent);
|
||||
background: color-mix(in oklch, var(--lora-accent) 12%, transparent);
|
||||
transform: translateY(-1px);
|
||||
outline: none;
|
||||
}
|
||||
|
||||
/* In titles, size the icon box to the first line box (1em * 1.3 line-height)
|
||||
so it aligns with the first line of both short and wrapped names. */
|
||||
.recipe-lora-title .recipe-civitai-link {
|
||||
width: 20px;
|
||||
height: calc(1em * 1.3);
|
||||
}
|
||||
|
||||
/* Meta footer: de-emphasized location + recipe ID line below the modal body,
|
||||
mirroring the hash footnote in the shared model modal. Location sits left
|
||||
(tail of the path survives truncation), ID + copy button sit right. */
|
||||
.recipe-meta-footer {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
gap: 12px;
|
||||
padding-top: 6px;
|
||||
margin-top: 8px;
|
||||
border-top: 1px solid var(--border-color);
|
||||
font-size: 0.75em;
|
||||
color: var(--text-muted);
|
||||
}
|
||||
|
||||
.recipe-meta-footer[hidden] {
|
||||
display: none;
|
||||
}
|
||||
|
||||
.recipe-meta-location {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
gap: 6px;
|
||||
min-width: 0;
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
.recipe-meta-location i {
|
||||
flex-shrink: 0;
|
||||
opacity: 0.6;
|
||||
}
|
||||
|
||||
.recipe-meta-location-path {
|
||||
font-family: var(--font-mono, monospace);
|
||||
opacity: 0.7;
|
||||
white-space: nowrap;
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
}
|
||||
|
||||
.recipe-meta-location:hover .recipe-meta-location-path,
|
||||
.recipe-meta-location:focus-visible .recipe-meta-location-path {
|
||||
opacity: 1;
|
||||
text-decoration: underline;
|
||||
}
|
||||
|
||||
.recipe-meta-location:focus-visible {
|
||||
outline: 1px solid var(--lora-accent);
|
||||
outline-offset: 2px;
|
||||
border-radius: var(--border-radius-xs);
|
||||
}
|
||||
|
||||
.recipe-meta-id {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
gap: 6px;
|
||||
flex-shrink: 0;
|
||||
}
|
||||
|
||||
.recipe-meta-id-label {
|
||||
font-size: 0.9em;
|
||||
opacity: 0.5;
|
||||
text-transform: uppercase;
|
||||
letter-spacing: 0.03em;
|
||||
}
|
||||
|
||||
.recipe-meta-id-value {
|
||||
font-family: var(--font-mono, monospace);
|
||||
opacity: 0.7;
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
.recipe-meta-copy-btn {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
padding: 0 2px;
|
||||
border: none;
|
||||
background: none;
|
||||
color: var(--text-muted);
|
||||
opacity: 0.35;
|
||||
font-size: 0.95em;
|
||||
cursor: pointer;
|
||||
flex-shrink: 0;
|
||||
}
|
||||
|
||||
.recipe-meta-copy-btn:hover {
|
||||
opacity: 0.9;
|
||||
}
|
||||
|
||||
@@ -202,15 +202,17 @@
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
margin-left: 6px;
|
||||
min-width: 16px;
|
||||
height: 16px;
|
||||
padding: 0 3px;
|
||||
min-width: 18px;
|
||||
height: 18px;
|
||||
padding: 0 5px;
|
||||
font-size: 11px;
|
||||
font-weight: 600;
|
||||
line-height: 1;
|
||||
text-transform: uppercase;
|
||||
border-radius: var(--border-radius-xs);
|
||||
background-color: var(--shortcut-bg);
|
||||
border: 1px solid var(--shortcut-border);
|
||||
box-shadow: var(--shortcut-shadow);
|
||||
color: var(--shortcut-text);
|
||||
vertical-align: middle;
|
||||
opacity: 0.8;
|
||||
@@ -219,12 +221,8 @@
|
||||
|
||||
.control-group button:hover .shortcut-key {
|
||||
opacity: 1;
|
||||
background-color: oklch(var(--lora-accent-l) var(--lora-accent-c) var(--lora-accent-h) / 0.2);
|
||||
}
|
||||
|
||||
[data-theme="dark"] .shortcut-key {
|
||||
--shortcut-bg: oklch(var(--lora-accent-l) var(--lora-accent-c) var(--lora-accent-h) / 0.15);
|
||||
--shortcut-border: oklch(var(--lora-accent-l) var(--lora-accent-c) var(--lora-accent-h) / 0.3);
|
||||
background-color: var(--shortcut-bg-hover);
|
||||
border-color: var(--shortcut-border-hover);
|
||||
}
|
||||
|
||||
/* Ensure correct vertical alignment for text+shortcut */
|
||||
|
||||
@@ -205,6 +205,7 @@
|
||||
display: inline-block;
|
||||
background: var(--shortcut-bg);
|
||||
border: 1px solid var(--shortcut-border);
|
||||
box-shadow: var(--shortcut-shadow);
|
||||
border-radius: var(--border-radius-xs);
|
||||
padding: 2px 6px;
|
||||
font-size: 0.8em;
|
||||
|
||||
@@ -12,6 +12,11 @@ import {
|
||||
} from './apiConfig.js';
|
||||
import { resetAndReload } from './modelApiFactory.js';
|
||||
import { sidebarManager } from '../components/SidebarManager.js';
|
||||
// Shared scan ETA helpers live in a dependency-light module so pages that do
|
||||
// not use BaseModelApiClient (e.g. recipes) can reuse them without pulling
|
||||
// this module's import cycle (modelApiFactory -> loraApi -> baseModelApi).
|
||||
import { createScanEtaTracker, formatScanRemainingTime } from '../utils/scanEtaUtils.js';
|
||||
export { createScanEtaTracker, formatScanRemainingTime };
|
||||
|
||||
/**
|
||||
* Abstract base class for all model API clients
|
||||
@@ -507,23 +512,67 @@ export class BaseModelApiClient {
|
||||
|
||||
async refreshModels(fullRebuild = false) {
|
||||
const abortController = new AbortController();
|
||||
try {
|
||||
state.loadingManager.show(
|
||||
`${fullRebuild ? 'Full rebuild' : 'Refreshing'} ${this.apiConfig.config.displayName}s...`,
|
||||
0
|
||||
const displayName = this.apiConfig.config.displayName;
|
||||
const singularName = this.apiConfig.config.singularName;
|
||||
const actionText = translate(
|
||||
fullRebuild ? 'common.scanProgress.actionFullRebuild' : 'common.scanProgress.actionRefresh',
|
||||
{},
|
||||
fullRebuild ? 'Full rebuild' : 'Refresh'
|
||||
);
|
||||
const actionLowerText = translate(
|
||||
fullRebuild ? 'common.scanProgress.actionRebuildLower' : 'common.scanProgress.actionRefreshLower',
|
||||
{},
|
||||
fullRebuild ? 'rebuild' : 'refresh'
|
||||
);
|
||||
const initialMessage = translate(
|
||||
fullRebuild ? 'common.scanProgress.fullRebuilding' : 'common.scanProgress.refreshing',
|
||||
{ type: displayName },
|
||||
`${fullRebuild ? 'Full rebuild' : 'Refreshing'} ${displayName}s...`
|
||||
);
|
||||
const etaTracker = createScanEtaTracker();
|
||||
let ws = null;
|
||||
|
||||
const handleScanProgress = (data) => {
|
||||
if (typeof data.progress === 'number') {
|
||||
state.loadingManager.setProgress(data.progress);
|
||||
}
|
||||
let statusText = translate(
|
||||
`common.scanProgress.stages.${data.stage}`,
|
||||
{ total: data.total },
|
||||
data.stage || ''
|
||||
);
|
||||
if (data.status === 'processing' && data.total > 0) {
|
||||
statusText += ` (${data.processed}/${data.total})`;
|
||||
if (data.current_name) {
|
||||
statusText += ` ${data.current_name}`;
|
||||
}
|
||||
const etaText = etaTracker.update(data.processed, data.total);
|
||||
if (etaText) {
|
||||
statusText += ` | ${etaText}`;
|
||||
}
|
||||
}
|
||||
state.loadingManager.setStatus(statusText);
|
||||
};
|
||||
|
||||
try {
|
||||
state.loadingManager.show(initialMessage, 0);
|
||||
state.loadingManager.showCancelButton(() => {
|
||||
this.cancelTask();
|
||||
abortController.abort();
|
||||
});
|
||||
|
||||
// Connect to the shared progress channel for live scan updates.
|
||||
// Failure to connect must not block the refresh itself — fall back
|
||||
// to the plain loading indicator.
|
||||
ws = await this._connectScanProgressSocket(handleScanProgress, singularName);
|
||||
|
||||
const url = new URL(this.apiConfig.endpoints.scan, window.location.origin);
|
||||
url.searchParams.append('full_rebuild', fullRebuild);
|
||||
|
||||
const response = await fetch(url, { signal: abortController.signal });
|
||||
|
||||
if (!response.ok) {
|
||||
throw new Error(`Failed to refresh ${this.apiConfig.config.displayName}s: ${response.status} ${response.statusText}`);
|
||||
throw new Error(`Failed to refresh ${displayName}s: ${response.status} ${response.statusText}`);
|
||||
}
|
||||
|
||||
const data = await response.json();
|
||||
@@ -534,20 +583,69 @@ export class BaseModelApiClient {
|
||||
|
||||
resetAndReload(true);
|
||||
|
||||
showToast('toast.api.refreshComplete', { action: fullRebuild ? 'Full rebuild' : 'Refresh' }, 'success');
|
||||
showToast('toast.api.refreshComplete', { action: actionText }, 'success');
|
||||
} catch (error) {
|
||||
if (error.name === 'AbortError') {
|
||||
showToast('toast.api.operationCancelled', {}, 'info');
|
||||
return;
|
||||
}
|
||||
console.error('Refresh failed:', error);
|
||||
showToast('toast.api.refreshFailed', { action: fullRebuild ? 'rebuild' : 'refresh', type: this.apiConfig.config.displayName }, 'error');
|
||||
showToast('toast.api.refreshFailed', { action: actionLowerText, type: displayName }, 'error');
|
||||
} finally {
|
||||
if (ws) {
|
||||
ws.close();
|
||||
}
|
||||
state.loadingManager.hide();
|
||||
state.loadingManager.restoreProgressBar();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Connect to the shared fetch-progress WebSocket for scan progress updates.
|
||||
* Returns null when the connection cannot be established (silent fallback).
|
||||
* @param {Function} onScanProgress - Handler for scan_progress messages
|
||||
* @param {string} singularName - Model type filter (e.g. 'lora')
|
||||
* @returns {Promise<WebSocket|null>}
|
||||
*/
|
||||
async _connectScanProgressSocket(onScanProgress, singularName) {
|
||||
let socket = null;
|
||||
try {
|
||||
const wsProtocol = window.location.protocol === 'https:' ? 'wss://' : 'ws://';
|
||||
socket = new WebSocket(`${wsProtocol}${window.location.host}${WS_ENDPOINTS.fetchProgress}`);
|
||||
|
||||
await new Promise((resolve, reject) => {
|
||||
socket.onopen = resolve;
|
||||
socket.onerror = reject;
|
||||
});
|
||||
|
||||
socket.onmessage = (event) => {
|
||||
let data;
|
||||
try {
|
||||
data = JSON.parse(event.data);
|
||||
} catch (parseError) {
|
||||
return;
|
||||
}
|
||||
// Only handle scan progress for this client's model type;
|
||||
// other operations share this channel and must be ignored.
|
||||
if (data.type !== 'scan_progress' || data.model_type !== singularName) {
|
||||
return;
|
||||
}
|
||||
onScanProgress(data);
|
||||
};
|
||||
|
||||
return socket;
|
||||
} catch (error) {
|
||||
if (socket) {
|
||||
try {
|
||||
socket.close();
|
||||
} catch (closeError) {
|
||||
// Ignore close errors during fallback
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
async refreshSingleModelMetadata(filePath) {
|
||||
try {
|
||||
state.loadingManager.showSimpleLoading('Refreshing metadata...');
|
||||
@@ -605,6 +703,9 @@ export class BaseModelApiClient {
|
||||
ws.onmessage = (event) => {
|
||||
const data = JSON.parse(event.data);
|
||||
|
||||
// Scan progress shares this channel; it is handled by refreshModels
|
||||
if (data.type === 'scan_progress') return;
|
||||
|
||||
switch (data.status) {
|
||||
case 'started':
|
||||
loading.setStatus('Starting metadata fetch...');
|
||||
|
||||
+100
-5
@@ -1,7 +1,12 @@
|
||||
import { RecipeCard } from '../components/RecipeCard.js';
|
||||
import { state, getCurrentPageState } from '../state/index.js';
|
||||
import { showToast } from '../utils/uiHelpers.js';
|
||||
import { translate } from '../utils/i18nHelpers.js';
|
||||
import { captureScrollPosition, restoreScrollPosition } from '../utils/infiniteScroll.js';
|
||||
import { WS_ENDPOINTS } from './apiConfig.js';
|
||||
// Import from the dependency-light utils module, not baseModelApi.js, to
|
||||
// avoid the baseModelApi <-> modelApiFactory import cycle on this page.
|
||||
import { createScanEtaTracker } from '../utils/scanEtaUtils.js';
|
||||
|
||||
const RECIPE_ENDPOINTS = {
|
||||
list: '/api/lm/recipes',
|
||||
@@ -333,11 +338,53 @@ export async function syncChanges() {
|
||||
}
|
||||
|
||||
export async function refreshRecipes(fullRebuild = true) {
|
||||
const actionLabel = fullRebuild ? 'Rebuilding recipe cache' : 'Refreshing recipes';
|
||||
const actionToast = fullRebuild ? 'Full rebuild' : 'Refresh';
|
||||
const actionText = translate(
|
||||
fullRebuild ? 'common.scanProgress.actionFullRebuild' : 'common.scanProgress.actionRefresh',
|
||||
{},
|
||||
fullRebuild ? 'Full rebuild' : 'Refresh'
|
||||
);
|
||||
const actionLowerText = translate(
|
||||
fullRebuild ? 'common.scanProgress.actionRebuildLower' : 'common.scanProgress.actionRefreshLower',
|
||||
{},
|
||||
fullRebuild ? 'rebuild' : 'refresh'
|
||||
);
|
||||
const initialMessage = translate(
|
||||
fullRebuild ? 'common.scanProgress.fullRebuilding' : 'common.scanProgress.refreshing',
|
||||
{ type: RECIPE_SIDEBAR_CONFIG.config.displayName },
|
||||
`${fullRebuild ? 'Full rebuild' : 'Refreshing'} Recipes...`
|
||||
);
|
||||
const etaTracker = createScanEtaTracker();
|
||||
let ws = null;
|
||||
|
||||
const handleScanProgress = (data) => {
|
||||
if (typeof data.progress === 'number') {
|
||||
state.loadingManager.setProgress(data.progress);
|
||||
}
|
||||
let statusText = translate(
|
||||
`common.scanProgress.stages.${data.stage}`,
|
||||
{ total: data.total },
|
||||
data.stage || ''
|
||||
);
|
||||
if (data.status === 'processing' && data.total > 0) {
|
||||
statusText += ` (${data.processed}/${data.total})`;
|
||||
if (data.current_name) {
|
||||
statusText += ` ${data.current_name}`;
|
||||
}
|
||||
const etaText = etaTracker.update(data.processed, data.total);
|
||||
if (etaText) {
|
||||
statusText += ` | ${etaText}`;
|
||||
}
|
||||
}
|
||||
state.loadingManager.setStatus(statusText);
|
||||
};
|
||||
|
||||
try {
|
||||
state.loadingManager.show(`${actionLabel}...`, 0);
|
||||
state.loadingManager.show(initialMessage, 0);
|
||||
|
||||
// Connect to the shared progress channel for live scan updates.
|
||||
// Failure to connect must not block the refresh itself — fall back
|
||||
// to the plain loading indicator.
|
||||
ws = await connectScanProgressSocket(handleScanProgress);
|
||||
|
||||
const url = new URL(RECIPE_ENDPOINTS.scan, window.location.origin);
|
||||
url.searchParams.append('full_rebuild', fullRebuild);
|
||||
@@ -356,16 +403,64 @@ export async function refreshRecipes(fullRebuild = true) {
|
||||
|
||||
await resetAndReload(false);
|
||||
|
||||
showToast('toast.api.refreshComplete', { action: actionToast }, 'success');
|
||||
showToast('toast.api.refreshComplete', { action: actionText }, 'success');
|
||||
} catch (error) {
|
||||
console.error('Error refreshing recipes:', error);
|
||||
showToast('toast.api.refreshFailed', { action: fullRebuild ? 'rebuild' : 'refresh', type: 'recipe' }, 'error');
|
||||
showToast('toast.api.refreshFailed', { action: actionLowerText, type: 'recipe' }, 'error');
|
||||
} finally {
|
||||
if (ws) {
|
||||
ws.close();
|
||||
}
|
||||
state.loadingManager.hide();
|
||||
state.loadingManager.restoreProgressBar();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Connect to the shared fetch-progress WebSocket for recipe scan progress.
|
||||
* Returns null when the connection cannot be established (silent fallback).
|
||||
* @param {Function} onScanProgress - Handler for scan_progress messages
|
||||
* @returns {Promise<WebSocket|null>}
|
||||
*/
|
||||
async function connectScanProgressSocket(onScanProgress) {
|
||||
let socket = null;
|
||||
try {
|
||||
const wsProtocol = window.location.protocol === 'https:' ? 'wss://' : 'ws://';
|
||||
socket = new WebSocket(`${wsProtocol}${window.location.host}${WS_ENDPOINTS.fetchProgress}`);
|
||||
|
||||
await new Promise((resolve, reject) => {
|
||||
socket.onopen = resolve;
|
||||
socket.onerror = reject;
|
||||
});
|
||||
|
||||
socket.onmessage = (event) => {
|
||||
let data;
|
||||
try {
|
||||
data = JSON.parse(event.data);
|
||||
} catch (parseError) {
|
||||
return;
|
||||
}
|
||||
// Only handle recipe scan progress; other operations share this
|
||||
// channel and must be ignored.
|
||||
if (data.type !== 'scan_progress' || data.model_type !== 'recipe') {
|
||||
return;
|
||||
}
|
||||
onScanProgress(data);
|
||||
};
|
||||
|
||||
return socket;
|
||||
} catch (error) {
|
||||
if (socket) {
|
||||
try {
|
||||
socket.close();
|
||||
} catch (closeError) {
|
||||
// Ignore close errors during fallback
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Load more recipes with pagination - updated to work with VirtualScroller
|
||||
* @param {boolean} resetPage - Whether to reset to the first page
|
||||
|
||||
@@ -3,6 +3,7 @@ import { confirmDelete, closeDeleteModal, confirmExclude, closeExcludeModal } fr
|
||||
import { createPageControls } from './components/controls/index.js';
|
||||
import { ModelDuplicatesManager } from './components/ModelDuplicatesManager.js';
|
||||
import { MODEL_TYPES } from './api/apiConfig.js';
|
||||
import { initActiveFiltersSync } from './utils/activeFiltersSync.js';
|
||||
|
||||
// Initialize the Checkpoints page
|
||||
export class CheckpointsPageManager {
|
||||
@@ -32,6 +33,9 @@ export class CheckpointsPageManager {
|
||||
// Initialize common page features (including context menus)
|
||||
appCore.initializePageFeatures();
|
||||
|
||||
// Mirror active filters to the backend for the ComfyUI-side autocomplete
|
||||
initActiveFiltersSync(MODEL_TYPES.CHECKPOINT);
|
||||
|
||||
console.log('Checkpoints Manager initialized');
|
||||
}
|
||||
}
|
||||
|
||||
@@ -28,8 +28,14 @@ export class Combobox {
|
||||
* @param {string[]} [options.presets=[]] Static preset values shown in dropdown.
|
||||
* @param {(inputValue: string) => Promise<string[]>} [options.fetchOptions]
|
||||
* Async function returning dynamic suggestions for the current input.
|
||||
* @param {string} [options.placeholder] Placeholder text for the empty state.
|
||||
* @param {string} [options.placeholder] Placeholder text for the input and the
|
||||
* dropdown empty state (see emptyText to override the latter).
|
||||
* @param {string} [options.emptyText] Text for the dropdown empty state;
|
||||
* defaults to `placeholder`, then 'No options'. Unlike `placeholder`
|
||||
* it never touches the input element.
|
||||
* @param {(value: string) => void} [options.onSelect] Callback when an option is chosen.
|
||||
* @param {(value: string) => void} [options.onCommit] Callback when Enter is
|
||||
* pressed without a highlighted option (free-text commit).
|
||||
*/
|
||||
constructor(inputElement, options = {}) {
|
||||
if (!inputElement || inputElement.tagName !== 'INPUT') {
|
||||
@@ -41,7 +47,9 @@ export class Combobox {
|
||||
this.presets = Array.isArray(options.presets) ? [...options.presets] : [];
|
||||
this.fetchOptions = typeof options.fetchOptions === 'function' ? options.fetchOptions : null;
|
||||
this.placeholder = options.placeholder || '';
|
||||
this.emptyText = options.emptyText || '';
|
||||
this.onSelect = typeof options.onSelect === 'function' ? options.onSelect : null;
|
||||
this.onCommit = typeof options.onCommit === 'function' ? options.onCommit : null;
|
||||
|
||||
// Internal state
|
||||
this._isOpen = false;
|
||||
@@ -109,19 +117,24 @@ export class Combobox {
|
||||
// ---- event wiring ----
|
||||
|
||||
_bindEvents() {
|
||||
this.input.addEventListener('focus', () => {
|
||||
// Keep references so destroy() can detach input listeners — callers
|
||||
// may destroy a Combobox while its input stays in the DOM.
|
||||
this._focusHandler = () => {
|
||||
if (this._suppressInputOpen) return;
|
||||
this._open();
|
||||
});
|
||||
};
|
||||
this.input.addEventListener('focus', this._focusHandler);
|
||||
|
||||
this.input.addEventListener('input', () => {
|
||||
this._inputHandler = () => {
|
||||
if (this._suppressInputOpen) return;
|
||||
this._open(); // no-op if already open
|
||||
this._refresh(); // re-filter by current input value
|
||||
this._scheduleFetch();
|
||||
});
|
||||
};
|
||||
this.input.addEventListener('input', this._inputHandler);
|
||||
|
||||
this.input.addEventListener('keydown', (event) => this._onKeyDown(event));
|
||||
this._keyDownHandler = (event) => this._onKeyDown(event);
|
||||
this.input.addEventListener('keydown', this._keyDownHandler);
|
||||
|
||||
// Click an option (delegated)
|
||||
this.panel.addEventListener('click', (event) => {
|
||||
@@ -167,6 +180,9 @@ export class Combobox {
|
||||
event.preventDefault();
|
||||
this._open();
|
||||
this._setActiveIndex(0);
|
||||
} else if (event.key === 'Enter' && typeof this.onCommit === 'function') {
|
||||
event.preventDefault();
|
||||
this.onCommit(this.input.value);
|
||||
}
|
||||
return;
|
||||
}
|
||||
@@ -184,11 +200,17 @@ export class Combobox {
|
||||
|
||||
case 'Enter':
|
||||
// Only intercept Enter to pick an option when one is actively
|
||||
// highlighted; otherwise let the input's default behavior
|
||||
// (form submit / free-text commit) proceed.
|
||||
// highlighted; otherwise commit the free-text value (when an
|
||||
// onCommit handler is registered) and let the input's default
|
||||
// behavior proceed otherwise.
|
||||
if (this._activeIndex >= 0 && this._activeIndex < this._renderedOptions.length) {
|
||||
event.preventDefault();
|
||||
this._choose(this._renderedOptions[this._activeIndex]);
|
||||
} else if (typeof this.onCommit === 'function') {
|
||||
event.preventDefault();
|
||||
const value = this.input.value;
|
||||
this._close();
|
||||
this.onCommit(value);
|
||||
}
|
||||
break;
|
||||
|
||||
@@ -254,7 +276,7 @@ export class Combobox {
|
||||
if (items.length === 0) {
|
||||
const empty = document.createElement('div');
|
||||
empty.className = 'lm-combobox-empty';
|
||||
empty.textContent = this.placeholder ? this.placeholder : 'No options';
|
||||
empty.textContent = this.emptyText || this.placeholder || 'No options';
|
||||
this.panel.appendChild(empty);
|
||||
this._activeIndex = -1;
|
||||
return;
|
||||
@@ -333,11 +355,19 @@ export class Combobox {
|
||||
if (this.panel && this.panel.parentNode) {
|
||||
this.panel.parentNode.removeChild(this.panel);
|
||||
}
|
||||
this.input.removeEventListener('focus', this._focusHandler);
|
||||
this.input.removeEventListener('input', this._inputHandler);
|
||||
this.input.removeEventListener('keydown', this._keyDownHandler);
|
||||
document.removeEventListener('mousedown', this._outsideClickHandler);
|
||||
window.removeEventListener('resize', this._resizeHandler);
|
||||
window.removeEventListener('scroll', this._resizeHandler, true);
|
||||
}
|
||||
|
||||
/** Whether the dropdown panel is currently open. */
|
||||
isOpen() {
|
||||
return this._isOpen;
|
||||
}
|
||||
|
||||
_choose(value) {
|
||||
this.input.value = value;
|
||||
this._close();
|
||||
|
||||
@@ -37,8 +37,7 @@ export class RecipeContextMenu extends BaseContextMenu {
|
||||
|
||||
if (recipeId && missingLorasItem) {
|
||||
// Check if this card has missing LoRAs
|
||||
const loraCountElement = card.querySelector('.lora-count');
|
||||
const hasMissingLoras = loraCountElement && loraCountElement.classList.contains('missing');
|
||||
const hasMissingLoras = Boolean(card.querySelector('.lora-count.missing'));
|
||||
|
||||
// Show/hide the download missing LoRAs option based on missing status
|
||||
if (hasMissingLoras) {
|
||||
@@ -205,8 +204,9 @@ export class RecipeContextMenu extends BaseContextMenu {
|
||||
const response = await fetch(`/api/lm/recipe/${recipeId}`);
|
||||
const recipe = await response.json();
|
||||
|
||||
// Get missing LoRAs
|
||||
const missingLoras = recipe.loras.filter(lora => !lora.inLibrary && !lora.isDeleted);
|
||||
// Get missing LoRAs (still downloadable: not deleted from the
|
||||
// source and hash still resolvable)
|
||||
const missingLoras = recipe.loras.filter(lora => !lora.inLibrary && !lora.isDeleted && !lora.hashInvalid);
|
||||
|
||||
if (missingLoras.length === 0) {
|
||||
showToast('recipes.contextMenu.downloadMissing.noMissingLoras', {}, 'info');
|
||||
|
||||
@@ -41,9 +41,36 @@ class RecipeCard {
|
||||
const loras = this.recipe.loras || [];
|
||||
const lorasCount = loras.length;
|
||||
|
||||
// Check if all LoRAs are available in the library
|
||||
const missingLorasCount = loras.filter(lora => !lora.inLibrary && !lora.isDeleted).length;
|
||||
const allLorasAvailable = missingLorasCount === 0 && lorasCount > 0;
|
||||
// Count LoRAs by availability: in library, missing (still downloadable
|
||||
// from the source), or unobtainable (deleted from the source, or an
|
||||
// unresolvable hash) which is silently skipped when the recipe is used.
|
||||
const availableLorasCount = loras.filter(lora => lora.inLibrary).length;
|
||||
const missingLorasCount = loras.filter(lora => !lora.inLibrary && !lora.isDeleted && !lora.hashInvalid).length;
|
||||
const unavailableLorasCount = lorasCount - availableLorasCount - missingLorasCount;
|
||||
|
||||
// Compact status pill: state icon + available/total fraction.
|
||||
// Icon switches by state so status never relies on color alone.
|
||||
// - missing (red): something can still be downloaded, most actionable
|
||||
// - partial (amber): usable but degraded, unobtainable LoRAs are skipped
|
||||
// - unavailable (gray, ban): no usable LoRA at all
|
||||
let loraCountStateClass = '';
|
||||
let loraCountIcon = 'fa-layer-group';
|
||||
if (lorasCount > 0) {
|
||||
if (availableLorasCount === lorasCount) {
|
||||
loraCountStateClass = 'ready';
|
||||
loraCountIcon = 'fa-check';
|
||||
} else if (missingLorasCount > 0) {
|
||||
loraCountStateClass = 'missing';
|
||||
loraCountIcon = 'fa-exclamation-triangle';
|
||||
} else if (availableLorasCount > 0) {
|
||||
loraCountStateClass = 'partial';
|
||||
loraCountIcon = 'fa-circle-minus';
|
||||
} else {
|
||||
loraCountStateClass = 'unavailable';
|
||||
loraCountIcon = 'fa-ban';
|
||||
}
|
||||
}
|
||||
const loraCountLabel = lorasCount > 0 ? `${availableLorasCount}/${lorasCount}` : `${lorasCount}`;
|
||||
|
||||
// Ensure file_url exists, fallback to API URL if needed
|
||||
let previewUrl = this.recipe.file_url;
|
||||
@@ -128,9 +155,8 @@ class RecipeCard {
|
||||
<span class="model-name">${this.recipe.title}</span>
|
||||
</div>
|
||||
${!isDuplicatesMode ? `
|
||||
<div class="lora-count ${allLorasAvailable ? 'ready' : (lorasCount > 0 ? 'missing' : '')}"
|
||||
title="${this.getLoraStatusTitle(lorasCount, missingLorasCount)}">
|
||||
<i class="fas fa-layer-group"></i> ${lorasCount}
|
||||
<div class="lora-count ${loraCountStateClass}" title="${this.getLoraStatusTitle(lorasCount, availableLorasCount, missingLorasCount, unavailableLorasCount)}">
|
||||
<i class="fas ${loraCountIcon}" aria-hidden="true"></i> ${loraCountLabel}
|
||||
</div>
|
||||
` : ''}
|
||||
</div>
|
||||
@@ -148,10 +174,39 @@ class RecipeCard {
|
||||
return card;
|
||||
}
|
||||
|
||||
getLoraStatusTitle(totalCount, missingCount) {
|
||||
if (totalCount === 0) return "No LoRAs in this recipe";
|
||||
if (missingCount === 0) return "All LoRAs available - Ready to use";
|
||||
return `${missingCount} of ${totalCount} LoRAs missing`;
|
||||
getLoraStatusTitle(totalCount, availableCount, missingCount, unavailableCount) {
|
||||
if (totalCount === 0) {
|
||||
return translate('recipes.loraStatus.none', {}, 'No LoRAs in this recipe');
|
||||
}
|
||||
if (availableCount === totalCount) {
|
||||
return translate('recipes.loraStatus.allAvailable', {}, 'All LoRAs available - Ready to use');
|
||||
}
|
||||
if (missingCount > 0 && unavailableCount > 0) {
|
||||
return translate(
|
||||
'recipes.loraStatus.missingAndUnavailable',
|
||||
{ missing: missingCount, unavailable: unavailableCount, total: totalCount },
|
||||
`${missingCount} of ${totalCount} LoRAs missing, ${unavailableCount} unavailable (deleted from source or unresolvable hash)`
|
||||
);
|
||||
}
|
||||
if (missingCount > 0) {
|
||||
return translate(
|
||||
'recipes.loraStatus.missing',
|
||||
{ missing: missingCount, total: totalCount },
|
||||
`${missingCount} of ${totalCount} LoRAs missing`
|
||||
);
|
||||
}
|
||||
if (availableCount > 0) {
|
||||
return translate(
|
||||
'recipes.loraStatus.partial',
|
||||
{ unavailable: unavailableCount, total: totalCount },
|
||||
`${unavailableCount} of ${totalCount} LoRAs unavailable (deleted from source or unresolvable hash) - skipped when recipe is used`
|
||||
);
|
||||
}
|
||||
return translate(
|
||||
'recipes.loraStatus.noneUsable',
|
||||
{ unavailable: unavailableCount, total: totalCount },
|
||||
`No usable LoRAs - ${unavailableCount} of ${totalCount} deleted from source or unresolvable hash`
|
||||
);
|
||||
}
|
||||
|
||||
async toggleFavorite(card) {
|
||||
|
||||
+1406
-167
File diff suppressed because it is too large
Load Diff
@@ -1,7 +1,8 @@
|
||||
// PageControls.js - Manages controls for both LoRAs and Checkpoints pages
|
||||
import { state, getCurrentPageState, setCurrentPageType } from '../../state/index.js';
|
||||
import { getStorageItem, setStorageItem, removeStorageItem, getSessionItem, setSessionItem, removeSessionItem } from '../../utils/storageHelpers.js';
|
||||
import { showToast, openCivitaiByMetadata } from '../../utils/uiHelpers.js';
|
||||
import { showToast, openCivitaiByMetadata, isTypingContext } from '../../utils/uiHelpers.js';
|
||||
import { eventManager } from '../../utils/EventManager.js';
|
||||
import { performModelUpdateCheck } from '../../utils/updateCheckHelpers.js';
|
||||
import { sidebarManager } from '../SidebarManager.js';
|
||||
import { initSortDropdown, applySortToSelect, randomizeSortValue } from './SortDropdown.js';
|
||||
@@ -146,6 +147,62 @@ export class PageControls {
|
||||
|
||||
// Page-specific event listeners
|
||||
this.initPageSpecificListeners();
|
||||
|
||||
// Keyboard shortcuts for the actions toolbar (R / F / D)
|
||||
this.registerKeyboardShortcuts();
|
||||
}
|
||||
|
||||
/**
|
||||
* Register keyboard shortcuts for the actions toolbar buttons
|
||||
* (R = refresh, F = fetch metadata, D = download)
|
||||
*/
|
||||
registerKeyboardShortcuts() {
|
||||
eventManager.addHandler('keydown', 'pageControls-actions', (e) => {
|
||||
return this.handleActionShortcut(e);
|
||||
}, {
|
||||
priority: 90,
|
||||
skipWhenModalOpen: true
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Handle a keydown event for the actions toolbar shortcuts
|
||||
* @param {KeyboardEvent} e
|
||||
* @returns {boolean} True when the event was handled and propagation should stop
|
||||
*/
|
||||
handleActionShortcut(e) {
|
||||
// Plain letters only — leave modified combos (Ctrl/Cmd/Alt) alone
|
||||
if (e.ctrlKey || e.metaKey || e.altKey) {
|
||||
return false;
|
||||
}
|
||||
|
||||
// Don't hijack keys while typing in a text entry context
|
||||
if (isTypingContext(e.target)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
const actionByKey = {
|
||||
r: 'refresh',
|
||||
f: 'fetch',
|
||||
d: 'download'
|
||||
};
|
||||
const action = actionByKey[e.key.toLowerCase()];
|
||||
if (!action) {
|
||||
return false;
|
||||
}
|
||||
|
||||
// The button may not exist on this page (e.g. recipes has no
|
||||
// fetch/download) — let other handlers run in that case
|
||||
const button = document.querySelector(`[data-action="${action}"]`);
|
||||
if (!button) {
|
||||
return false;
|
||||
}
|
||||
|
||||
e.preventDefault();
|
||||
// Native disabled buttons ignore .click(), so an in-progress
|
||||
// refresh is safe
|
||||
button.click();
|
||||
return true;
|
||||
}
|
||||
|
||||
initExcludedViewControls() {
|
||||
|
||||
@@ -607,9 +607,11 @@ export function createModelCard(model, modelType) {
|
||||
sendTitle = translate('modelCard.actions.sendToWorkflow', {}, 'Send to ComfyUI (Click: Append, Shift+Click: Replace)');
|
||||
copyTitle = translate('modelCard.actions.copyLoRASyntax', {}, 'Copy LoRA Syntax');
|
||||
} else if (modelType === MODEL_TYPES.CHECKPOINT) {
|
||||
// Checkpoint send sets the widget value directly; no append/replace modes.
|
||||
sendTitle = translate('modelCard.actions.sendCheckpointToWorkflow', {}, 'Send to ComfyUI');
|
||||
copyTitle = translate('modelCard.actions.copyCheckpointName', {}, 'Copy checkpoint name');
|
||||
} else if (modelType === MODEL_TYPES.EMBEDDING) {
|
||||
// Embedding send always appends to the prompt; no replace mode.
|
||||
sendTitle = translate('modelCard.actions.sendEmbeddingToWorkflow', {}, 'Send to ComfyUI');
|
||||
copyTitle = translate('modelCard.actions.copyEmbeddingName', {}, 'Copy embedding name');
|
||||
} else {
|
||||
|
||||
@@ -877,8 +877,9 @@ function renderLoraSpecificContent(lora, escapedWords) {
|
||||
<option value="clip_strength">${translate('modals.model.usageTips.clipStrength', {}, 'Clip Strength')}</option>
|
||||
<option value="clip_skip">${translate('modals.model.usageTips.clipSkip', {}, 'Clip Skip')}</option>
|
||||
</select>
|
||||
<input type="number" id="preset-value" step="0.01" placeholder="${translate('modals.model.usageTips.valuePlaceholder', {}, 'Value')}" style="display:none;">
|
||||
<button class="add-preset-btn">${translate('modals.model.usageTips.add', {}, 'Add')}</button>
|
||||
<!-- autofill opt-out attrs prevent password managers / email-alias extensions from attaching popups -->
|
||||
<input type="number" id="preset-value" step="0.01" placeholder="${translate('modals.model.usageTips.valuePlaceholder', {}, 'Value')}" style="display:none;" autocomplete="off" data-1p-ignore data-lpignore="true" data-bwignore data-form-type="other">
|
||||
<button class="add-preset-btn" disabled>${translate('modals.model.usageTips.add', {}, 'Add')}</button>
|
||||
</div>
|
||||
<div class="preset-tags">
|
||||
${renderPresetTags(parsePresets(lora.usage_tips))}
|
||||
@@ -1086,6 +1087,11 @@ function setupLoraSpecificFields(filePath) {
|
||||
|
||||
if (!presetSelector || !presetValue || !addPresetBtn || !presetTags) return;
|
||||
|
||||
// Add button stays disabled until both a parameter and a value are provided
|
||||
const updateAddPresetButtonState = () => {
|
||||
addPresetBtn.disabled = !(presetSelector.value && presetValue.value.trim());
|
||||
};
|
||||
|
||||
presetSelector.addEventListener('change', function () {
|
||||
const selected = this.value;
|
||||
if (selected) {
|
||||
@@ -1111,12 +1117,16 @@ function setupLoraSpecificFields(filePath) {
|
||||
} else {
|
||||
presetValue.style.display = 'none';
|
||||
}
|
||||
updateAddPresetButtonState();
|
||||
});
|
||||
|
||||
presetValue.addEventListener('input', updateAddPresetButtonState);
|
||||
|
||||
addPresetBtn.addEventListener('click', async function () {
|
||||
const key = presetSelector.value;
|
||||
const value = presetValue.value;
|
||||
const value = presetValue.value.trim();
|
||||
|
||||
// Unreachable via UI while the button is disabled; kept as a safety net
|
||||
if (!key || !value) return;
|
||||
|
||||
const currentPath = resolveFilePath();
|
||||
@@ -1131,9 +1141,11 @@ function setupLoraSpecificFields(filePath) {
|
||||
document.querySelector(`.model-card[data-filepath="${escapedFilePath}"]`);
|
||||
const currentPresets = parsePresets(loraCard?.dataset.usage_tips);
|
||||
|
||||
let isUpdate;
|
||||
if (key === 'strength_range') {
|
||||
const rangeMatch = value.match(/^(-?\d*\.?\d+)\s*[-~]\s*(-?\d*\.?\d+)$/);
|
||||
if (rangeMatch) {
|
||||
isUpdate = 'strength_min' in currentPresets || 'strength_max' in currentPresets;
|
||||
currentPresets['strength_min'] = parseFloat(rangeMatch[1]);
|
||||
currentPresets['strength_max'] = parseFloat(rangeMatch[2]);
|
||||
} else {
|
||||
@@ -1141,17 +1153,36 @@ function setupLoraSpecificFields(filePath) {
|
||||
return;
|
||||
}
|
||||
} else {
|
||||
currentPresets[key] = parseFloat(value);
|
||||
const numericValue = parseFloat(value);
|
||||
if (!Number.isFinite(numericValue)) {
|
||||
showToast('modals.model.usageTips.invalidValue', {}, 'error', 'Please enter a valid number');
|
||||
return;
|
||||
}
|
||||
isUpdate = key in currentPresets;
|
||||
currentPresets[key] = numericValue;
|
||||
}
|
||||
const newPresetsJson = JSON.stringify(currentPresets);
|
||||
|
||||
await getModelApiClient().saveModelMetadata(currentPath, { usage_tips: newPresetsJson });
|
||||
try {
|
||||
await getModelApiClient().saveModelMetadata(currentPath, { usage_tips: newPresetsJson });
|
||||
} catch (error) {
|
||||
console.error('Failed to save preset parameter:', error);
|
||||
showToast('modals.model.usageTips.saveFailed', {}, 'error', 'Failed to save preset parameter');
|
||||
return;
|
||||
}
|
||||
|
||||
presetTags.innerHTML = renderPresetTags(currentPresets);
|
||||
showToast(
|
||||
isUpdate ? 'modals.model.usageTips.updated' : 'modals.model.usageTips.added',
|
||||
{},
|
||||
'success',
|
||||
isUpdate ? 'Preset parameter updated' : 'Preset parameter added'
|
||||
);
|
||||
|
||||
presetSelector.value = '';
|
||||
presetValue.value = '';
|
||||
presetValue.style.display = 'none';
|
||||
addPresetBtn.disabled = true;
|
||||
});
|
||||
|
||||
// Add keydown event for preset value
|
||||
|
||||
@@ -130,17 +130,29 @@ function renderRecipes(tabElement, recipes, options) {
|
||||
const baseModel = recipe.base_model || '';
|
||||
const loras = recipe.loras || [];
|
||||
const lorasCount = loras.length;
|
||||
const missingLorasCount = loras.filter(lora => !lora.inLibrary && !lora.isDeleted).length;
|
||||
const allLorasAvailable = missingLorasCount === 0 && lorasCount > 0;
|
||||
const statusClass = lorasCount === 0 ? 'empty' : (allLorasAvailable ? 'ready' : 'missing');
|
||||
// Missing = still downloadable; unavailable = deleted from the source
|
||||
// or unresolvable hash, silently skipped when the recipe is used.
|
||||
const availableLorasCount = loras.filter(lora => lora.inLibrary).length;
|
||||
const missingLorasCount = loras.filter(lora => !lora.inLibrary && !lora.isDeleted && !lora.hashInvalid).length;
|
||||
const unavailableLorasCount = lorasCount - availableLorasCount - missingLorasCount;
|
||||
const statusClass = lorasCount === 0 ? 'empty'
|
||||
: (availableLorasCount === lorasCount ? 'ready'
|
||||
: (missingLorasCount > 0 ? 'missing'
|
||||
: (availableLorasCount > 0 ? 'partial' : 'unavailable')));
|
||||
let statusLabel;
|
||||
|
||||
if (lorasCount === 0) {
|
||||
statusLabel = 'No linked LoRAs';
|
||||
} else if (allLorasAvailable) {
|
||||
} else if (statusClass === 'ready') {
|
||||
statusLabel = `${lorasCount} LoRA${lorasCount > 1 ? 's' : ''} ready`;
|
||||
} else if (statusClass === 'missing') {
|
||||
statusLabel = unavailableLorasCount > 0
|
||||
? `Missing ${missingLorasCount}, ${unavailableLorasCount} of ${lorasCount} unavailable`
|
||||
: `Missing ${missingLorasCount} of ${lorasCount}`;
|
||||
} else if (statusClass === 'partial') {
|
||||
statusLabel = `${unavailableLorasCount} of ${lorasCount} unavailable - skipped when used`;
|
||||
} else {
|
||||
statusLabel = `Missing ${missingLorasCount} of ${lorasCount}`;
|
||||
statusLabel = 'No usable LoRAs';
|
||||
}
|
||||
|
||||
const imageUrl = recipe.file_url ||
|
||||
@@ -207,8 +219,16 @@ function renderRecipes(tabElement, recipes, options) {
|
||||
const statusBadge = document.createElement('span');
|
||||
statusBadge.className = `recipe-card__badge recipe-card__badge--${statusClass}`;
|
||||
|
||||
// Icon switches by state so status never relies on color alone.
|
||||
const statusIcons = {
|
||||
ready: 'fa-check',
|
||||
missing: 'fa-exclamation-triangle',
|
||||
partial: 'fa-circle-minus',
|
||||
unavailable: 'fa-ban',
|
||||
empty: 'fa-layer-group',
|
||||
};
|
||||
const statusIcon = document.createElement('i');
|
||||
statusIcon.className = 'fas fa-layer-group';
|
||||
statusIcon.className = `fas ${statusIcons[statusClass] || 'fa-layer-group'}`;
|
||||
statusIcon.setAttribute('aria-hidden', 'true');
|
||||
statusBadge.appendChild(statusIcon);
|
||||
|
||||
@@ -216,7 +236,7 @@ function renderRecipes(tabElement, recipes, options) {
|
||||
statusText.textContent = statusLabel;
|
||||
statusBadge.appendChild(statusText);
|
||||
|
||||
statusBadge.title = getLoraStatusTitle(lorasCount, missingLorasCount);
|
||||
statusBadge.title = getLoraStatusTitle(lorasCount, availableLorasCount, missingLorasCount, unavailableLorasCount);
|
||||
meta.appendChild(statusBadge);
|
||||
|
||||
body.appendChild(meta);
|
||||
@@ -264,13 +284,23 @@ function renderRecipes(tabElement, recipes, options) {
|
||||
/**
|
||||
* Returns a descriptive title for the LoRA status indicator
|
||||
* @param {number} totalCount - Total number of LoRAs in recipe
|
||||
* @param {number} missingCount - Number of missing LoRAs
|
||||
* @param {number} availableCount - Number of LoRAs present in the library
|
||||
* @param {number} missingCount - Number of missing LoRAs (still downloadable)
|
||||
* @param {number} unavailableCount - Number of unobtainable LoRAs (deleted
|
||||
* from the source or unresolvable hash)
|
||||
* @returns {string} Status title text
|
||||
*/
|
||||
function getLoraStatusTitle(totalCount, missingCount) {
|
||||
function getLoraStatusTitle(totalCount, availableCount, missingCount, unavailableCount) {
|
||||
if (totalCount === 0) return "No LoRAs in this recipe";
|
||||
if (missingCount === 0) return "All LoRAs available - Ready to use";
|
||||
return `${missingCount} of ${totalCount} LoRAs missing`;
|
||||
if (availableCount === totalCount) return "All LoRAs available - Ready to use";
|
||||
if (missingCount > 0 && unavailableCount > 0) {
|
||||
return `${missingCount} of ${totalCount} LoRAs missing, ${unavailableCount} unavailable (deleted from source or unresolvable hash)`;
|
||||
}
|
||||
if (missingCount > 0) return `${missingCount} of ${totalCount} LoRAs missing`;
|
||||
if (availableCount > 0) {
|
||||
return `${unavailableCount} of ${totalCount} LoRAs unavailable (deleted from source or unresolvable hash) - skipped when recipe is used`;
|
||||
}
|
||||
return `No usable LoRAs - ${unavailableCount} of ${totalCount} deleted from source or unresolvable hash`;
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@@ -227,7 +227,7 @@ export function renderTriggerWords(words, filePath) {
|
||||
const escapedWord = escapeHtml(word);
|
||||
const escapedAttr = escapeAttribute(word);
|
||||
return `
|
||||
<div class="trigger-word-tag" data-word="${escapedAttr}" title="${translate('modals.model.triggerWords.copyWord')}">
|
||||
<div class="trigger-word-tag" data-word="${escapedAttr}" title="${translate('modals.model.triggerWords.copyOrEditWord')}">
|
||||
<span class="trigger-word-content">${escapedWord}</span>
|
||||
<span class="trigger-word-copy">
|
||||
<i class="fas fa-copy"></i>
|
||||
@@ -455,7 +455,7 @@ function resetTriggerWordsUIState(section) {
|
||||
// Restore click-to-copy functionality
|
||||
tag.removeEventListener('click', startEditTriggerWord);
|
||||
setupDisplayTriggerWordTag(tag);
|
||||
tag.title = translate('modals.model.triggerWords.copyWord');
|
||||
tag.title = translate('modals.model.triggerWords.copyOrEditWord');
|
||||
|
||||
// Show copy icon, hide delete button
|
||||
if (copyIcon) copyIcon.style.display = '';
|
||||
@@ -503,7 +503,7 @@ function createTriggerWordTag(word, isEditMode = false) {
|
||||
const tag = document.createElement('div');
|
||||
tag.className = 'trigger-word-tag';
|
||||
tag.dataset.word = word;
|
||||
tag.title = translate(isEditMode ? 'modals.model.triggerWords.editWord' : 'modals.model.triggerWords.copyWord');
|
||||
tag.title = translate(isEditMode ? 'modals.model.triggerWords.editWord' : 'modals.model.triggerWords.copyOrEditWord');
|
||||
|
||||
const escapedWord = escapeHtml(word);
|
||||
tag.innerHTML = `
|
||||
@@ -537,7 +537,7 @@ function setupDisplayTriggerWordTag(tag) {
|
||||
|
||||
tag.addEventListener('click', handleDisplayTriggerWordClick);
|
||||
tag.addEventListener('dblclick', handleDisplayTriggerWordDoubleClick);
|
||||
tag.title = translate('modals.model.triggerWords.copyWord');
|
||||
tag.title = translate('modals.model.triggerWords.copyOrEditWord');
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@@ -76,6 +76,7 @@ export function generateImageWrapper(media, shouldBlur, nsfwText, metadataPanel,
|
||||
alt="Preview"
|
||||
width="${media.width}"
|
||||
height="${media.height}"
|
||||
fetchpriority="high"
|
||||
class="lazy ${shouldBlur ? 'blurred' : ''}">
|
||||
${shouldBlur ? `
|
||||
<div class="nsfw-overlay">
|
||||
|
||||
@@ -22,8 +22,8 @@ import {
|
||||
} from './MediaUtils.js';
|
||||
import { generateMetadataPanel } from './MetadataPanel.js';
|
||||
import { generateImageWrapper, generateVideoWrapper } from './MediaRenderers.js';
|
||||
import { getShowcaseUrl, getThumbnailUrl } from '../../../utils/civitaiUtils.js';
|
||||
import { openMediaViewer } from '../MediaViewer.js';
|
||||
import { getShowcaseUrl, getDisplayUrl, getGalleryThumbnailUrl } from '../../../utils/civitaiUtils.js';
|
||||
import { openMediaViewer, isMediaViewerOpen } from '../MediaViewer.js';
|
||||
import { escapeAttribute } from '../utils.js';
|
||||
|
||||
/**
|
||||
@@ -54,6 +54,13 @@ export async function loadExampleImages(images, modelHash, previewUrl = '') {
|
||||
const showcaseTab = document.getElementById('showcase-tab');
|
||||
if (!showcaseTab) return;
|
||||
|
||||
// Fresh load of a model's examples: reset the gallery position so a
|
||||
// previously viewed model's active index / expansion state never leaks
|
||||
// into this one (the modal is a singleton, state is module-level)
|
||||
galleryState.activeIndex = 0;
|
||||
galleryState.expanded = false;
|
||||
lastNavDirection = 1;
|
||||
|
||||
// First fetch local example files
|
||||
let localFiles = [];
|
||||
|
||||
@@ -224,10 +231,10 @@ export function renderShowcaseContent(images, exampleFiles = [], previewUrl = ''
|
||||
${renderMediaItem(activeImg, galleryState.activeIndex, exampleFiles)}
|
||||
${renderPositionBadge(positionText)}
|
||||
</div>
|
||||
${showNav ? `<button class="gallery-nav prev" id="galleryPrevBtn" title="${translate('modals.model.showcase.previousExample', {}, 'Previous example')}">
|
||||
${showNav ? `<button class="gallery-nav prev" id="galleryPrevBtn" title="${translate('modals.model.showcase.previousExample', {}, 'Previous example ([)')}">
|
||||
<i class="fas fa-chevron-left"></i>
|
||||
</button>
|
||||
<button class="gallery-nav next" id="galleryNextBtn" title="${translate('modals.model.showcase.nextExample', {}, 'Next example')}">
|
||||
<button class="gallery-nav next" id="galleryNextBtn" title="${translate('modals.model.showcase.nextExample', {}, 'Next example (])')}">
|
||||
<i class="fas fa-chevron-right"></i>
|
||||
</button>` : ''}
|
||||
</div>
|
||||
@@ -275,7 +282,7 @@ function renderThumbnail(img, index, exampleFiles) {
|
||||
originalRemoteUrl.endsWith('.mp4') || originalRemoteUrl.endsWith('.webm');
|
||||
const mediaType = isVideo ? 'video' : 'image';
|
||||
|
||||
const thumbUrl = localFile ? localFile.path : getThumbnailUrl(originalRemoteUrl, mediaType);
|
||||
const thumbUrl = localFile ? localFile.path : getGalleryThumbnailUrl(originalRemoteUrl, mediaType);
|
||||
|
||||
const nsfwLevel = img.nsfwLevel !== undefined ? img.nsfwLevel : 0;
|
||||
const matureBlurThreshold = getMatureBlurThreshold(state.settings);
|
||||
@@ -284,9 +291,9 @@ function renderThumbnail(img, index, exampleFiles) {
|
||||
const activeClass = index === galleryState.activeIndex ? ' active' : '';
|
||||
const blurClass = shouldBlur ? ' blurred' : '';
|
||||
const mediaHtml = isVideo ?
|
||||
`<video class="thumb-media${blurClass}" src="${escapeAttribute(thumbUrl)}" muted playsinline preload="metadata"></video>
|
||||
`<video class="thumb-media${blurClass}" src="${escapeAttribute(thumbUrl)}" muted playsinline preload="none" data-lazy-video></video>
|
||||
<i class="fas fa-play thumb-video-badge"></i>` :
|
||||
`<img class="thumb-media${blurClass}" src="${escapeAttribute(thumbUrl)}" loading="lazy" alt="">`;
|
||||
`<img class="thumb-media${blurClass}" src="${escapeAttribute(thumbUrl)}" loading="lazy" fetchpriority="low" alt="">`;
|
||||
const nsfwBadge = shouldBlur ? '<i class="fas fa-eye-slash thumb-nsfw-badge"></i>' : '';
|
||||
|
||||
return `<button class="gallery-thumb${activeClass}" data-index="${index}">${mediaHtml}${nsfwBadge}</button>`;
|
||||
@@ -311,8 +318,9 @@ function renderMediaItem(img, index, exampleFiles) {
|
||||
originalRemoteUrl.endsWith('.mp4') || originalRemoteUrl.endsWith('.webm');
|
||||
const mediaType = isVideo ? 'video' : 'image';
|
||||
|
||||
// Optimize CivitAI URLs for showcase display (full quality)
|
||||
const remoteUrl = getShowcaseUrl(originalRemoteUrl, mediaType);
|
||||
// Optimize CivitAI URLs for in-modal display (images capped at width=2400;
|
||||
// the full-size media viewer uses getShowcaseUrl separately)
|
||||
const remoteUrl = getDisplayUrl(originalRemoteUrl, mediaType);
|
||||
|
||||
const localUrl = localFile ? localFile.path : '';
|
||||
|
||||
@@ -438,6 +446,48 @@ function findLocalFile(img, index, exampleFiles) {
|
||||
return localFile;
|
||||
}
|
||||
|
||||
// URLs already warmed in the HTTP cache, so repeat navigations and re-renders
|
||||
// never issue duplicate prefetch requests
|
||||
const prefetchedUrls = new Set();
|
||||
|
||||
// Direction of the last main-viewer navigation (+1 next / -1 prev); users
|
||||
// tend to keep clicking the same arrow, so prefetch reaches one further
|
||||
// ahead along it. Defaults to forward (Next is the most common navigation)
|
||||
let lastNavDirection = 1;
|
||||
|
||||
/**
|
||||
* Warm the HTTP cache for the examples most likely to be shown next: both
|
||||
* indices adjacent to the active one, plus one extra ahead along the last
|
||||
* navigation direction, so prev/next navigation feels instant. Images only:
|
||||
* video payloads are too heavy for speculative prefetch, and locally stored
|
||||
* examples need no network fetch at all.
|
||||
*/
|
||||
function prefetchAdjacentMedia() {
|
||||
const { images, exampleFiles, activeIndex, expanded } = galleryState;
|
||||
if (!expanded || images.length < 2) return;
|
||||
|
||||
[1, -1, lastNavDirection * 2].forEach(offset => {
|
||||
const index = ((activeIndex + offset) % images.length + images.length) % images.length;
|
||||
const img = images[index];
|
||||
if (!img?.url || findLocalFile(img, index, exampleFiles)) return;
|
||||
|
||||
const isVideo = img.url.endsWith('.mp4') || img.url.endsWith('.webm');
|
||||
if (isVideo) return;
|
||||
|
||||
// Must match the main viewer's URL (display mode) or the warmed
|
||||
// cache entry is never used
|
||||
const url = getDisplayUrl(img.url, 'image');
|
||||
if (prefetchedUrls.has(url)) return;
|
||||
prefetchedUrls.add(url);
|
||||
|
||||
// Off-DOM image: fills the HTTP/memory cache without affecting layout.
|
||||
// Low priority keeps it from competing with the active media's load.
|
||||
const preloader = new Image();
|
||||
preloader.fetchPriority = 'low';
|
||||
preloader.src = url;
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Switch the main viewer to another example (wraps around)
|
||||
* @param {number} index - Target index in galleryState.images
|
||||
@@ -446,6 +496,11 @@ export function updateMainDisplay(index) {
|
||||
const count = galleryState.images.length;
|
||||
if (!count || !galleryState.expanded) return;
|
||||
|
||||
// Remember the navigation direction for direction-aware prefetching
|
||||
// (a raw index of -1 / count means wrap-around prev / next)
|
||||
const delta = index - galleryState.activeIndex;
|
||||
if (delta !== 0) lastNavDirection = delta > 0 ? 1 : -1;
|
||||
|
||||
galleryState.activeIndex = ((index % count) + count) % count;
|
||||
|
||||
const container = document.getElementById('mainMediaContainer');
|
||||
@@ -453,6 +508,13 @@ export function updateMainDisplay(index) {
|
||||
|
||||
const activeImg = galleryState.images[galleryState.activeIndex];
|
||||
container.style.setProperty('--media-aspect', mediaAspectRatio(activeImg));
|
||||
// Direction-aware slide makes every switch (wheel, keys, buttons,
|
||||
// thumbnails) perceivable instead of an instant, unexplained swap
|
||||
container.classList.remove('slide-from-left', 'slide-from-right');
|
||||
if (delta !== 0) {
|
||||
void container.offsetWidth; // restart the animation on rapid switches
|
||||
container.classList.add(delta > 0 ? 'slide-from-right' : 'slide-from-left');
|
||||
}
|
||||
// The badge lives inside the container, so rebuild it together with the media
|
||||
container.innerHTML = renderMediaItem(
|
||||
activeImg,
|
||||
@@ -470,6 +532,7 @@ export function updateMainDisplay(index) {
|
||||
});
|
||||
|
||||
initMainMediaInteractions(container);
|
||||
prefetchAdjacentMedia();
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -624,6 +687,211 @@ function setupScrollToExpand(gallery) {
|
||||
}, { passive: true });
|
||||
}
|
||||
|
||||
// Wheel-navigation tuning: one gesture = one step. Trackpads emit a stream
|
||||
// of small deltas, so deltas accumulate until the threshold; the cooldown
|
||||
// keeps the tail of the same gesture from stepping again
|
||||
const WHEEL_STEP_THRESHOLD = 50;
|
||||
const WHEEL_COOLDOWN_MS = 250;
|
||||
const WHEEL_ACCUM_RESET_MS = 200;
|
||||
|
||||
/**
|
||||
* Wheel navigation on the main viewer area. Bound to .gallery-main (not the
|
||||
* media element) so it works wherever the cursor rests within the viewer —
|
||||
* including over the nav buttons and the dead zones beside the media, and
|
||||
* regardless of whether the hover-triggered metadata panel is showing.
|
||||
*
|
||||
* - Horizontal-dominant deltas (trackpad two-finger swipe) always navigate;
|
||||
* the modal never scrolls horizontally, so nothing is hijacked.
|
||||
* - Vertical deltas navigate only when the modal content cannot scroll
|
||||
* further in that direction (same boundary pass-through pattern as the
|
||||
* metadata panel's wheel handler), so wheel-scrolling the modal through
|
||||
* the gallery is never trapped mid-way.
|
||||
* - Once a boundary crossing triggers a vertical switch, a "wheel session"
|
||||
* starts: while the pointer stays over .gallery-main, vertical wheel in
|
||||
* BOTH directions switches examples (down = next, up = prev — the reverse
|
||||
* gesture must undo, not scroll the modal away). The session ends when the
|
||||
* pointer leaves the area, returning vertical scroll to the modal.
|
||||
* @param {HTMLElement} gallery - The .showcase-gallery element
|
||||
*/
|
||||
function initWheelNavigation(gallery) {
|
||||
const main = gallery.querySelector('.gallery-main');
|
||||
if (!main || galleryState.images.length < 2) return;
|
||||
|
||||
let accumulated = 0;
|
||||
let lastEventAt = 0;
|
||||
let lastStepAt = 0;
|
||||
let verticalSession = false;
|
||||
|
||||
// Leaving the viewer area releases the vertical wheel back to the modal
|
||||
main.addEventListener('pointerleave', () => {
|
||||
verticalSession = false;
|
||||
accumulated = 0;
|
||||
});
|
||||
|
||||
main.addEventListener('wheel', (event) => {
|
||||
// The metadata panel and media controls keep their own behavior;
|
||||
// the panel passes boundary scrolls through to the modal by itself
|
||||
if (event.target.closest('.image-metadata-panel, .media-controls')) return;
|
||||
|
||||
const horizontal = Math.abs(event.deltaX) > Math.abs(event.deltaY);
|
||||
const delta = horizontal ? event.deltaX : event.deltaY;
|
||||
if (delta === 0) return;
|
||||
|
||||
if (!horizontal && !verticalSession) {
|
||||
const scroller = main.closest('.modal-content');
|
||||
if (scroller) {
|
||||
const atTop = scroller.scrollTop <= 0;
|
||||
const atBottom = scroller.scrollHeight - scroller.scrollTop - scroller.clientHeight <= 1;
|
||||
if ((delta < 0 && !atTop) || (delta > 0 && !atBottom)) return;
|
||||
}
|
||||
}
|
||||
|
||||
event.preventDefault();
|
||||
|
||||
const now = performance.now();
|
||||
if (now - lastEventAt > WHEEL_ACCUM_RESET_MS) accumulated = 0;
|
||||
lastEventAt = now;
|
||||
if (now - lastStepAt < WHEEL_COOLDOWN_MS) return;
|
||||
|
||||
accumulated += delta;
|
||||
if (Math.abs(accumulated) < WHEEL_STEP_THRESHOLD) return;
|
||||
|
||||
const direction = accumulated > 0 ? 1 : -1;
|
||||
accumulated = 0;
|
||||
lastStepAt = now;
|
||||
if (!horizontal) verticalSession = true;
|
||||
updateMainDisplay(galleryState.activeIndex + direction);
|
||||
}, { passive: false });
|
||||
}
|
||||
|
||||
// Touch/pen swipe tuning. Mouse is excluded: it already has wheel, keys and
|
||||
// buttons, and mouse-drag would fight the media's click-to-view gesture
|
||||
const SWIPE_THRESHOLD_PX = 50;
|
||||
const SWIPE_CLICK_SUPPRESS_MS = 400;
|
||||
|
||||
/**
|
||||
* Horizontal swipe navigation on the main viewer area (touch/pen). Requires
|
||||
* `touch-action: pan-y` on .gallery-main so horizontal pans reach these
|
||||
* handlers while vertical pans still scroll the modal.
|
||||
* @param {HTMLElement} gallery - The .showcase-gallery element
|
||||
*/
|
||||
function initSwipeNavigation(gallery) {
|
||||
const main = gallery.querySelector('.gallery-main');
|
||||
if (!main || galleryState.images.length < 2) return;
|
||||
|
||||
let startX = 0;
|
||||
let startY = 0;
|
||||
let tracking = false;
|
||||
let lastSwipeAt = 0;
|
||||
|
||||
main.addEventListener('pointerdown', (event) => {
|
||||
if (event.pointerType === 'mouse') return;
|
||||
// Native video controls own their pointer gestures (scrubbing etc.)
|
||||
if (event.target.closest('video, .image-metadata-panel, .media-controls, .gallery-nav')) return;
|
||||
startX = event.clientX;
|
||||
startY = event.clientY;
|
||||
tracking = true;
|
||||
});
|
||||
|
||||
main.addEventListener('pointercancel', () => { tracking = false; });
|
||||
|
||||
main.addEventListener('pointerup', (event) => {
|
||||
if (!tracking) return;
|
||||
tracking = false;
|
||||
const dx = event.clientX - startX;
|
||||
const dy = event.clientY - startY;
|
||||
if (Math.abs(dx) < SWIPE_THRESHOLD_PX || Math.abs(dx) < Math.abs(dy) * 1.5) return;
|
||||
lastSwipeAt = performance.now();
|
||||
updateMainDisplay(galleryState.activeIndex + (dx < 0 ? 1 : -1));
|
||||
});
|
||||
|
||||
// A completed swipe still produces a click on the media — swallow it in
|
||||
// the capture phase (beats the media element's own handler) so the
|
||||
// full-size viewer does not open
|
||||
main.addEventListener('click', (event) => {
|
||||
if (performance.now() - lastSwipeAt < SWIPE_CLICK_SUPPRESS_MS) {
|
||||
event.stopPropagation();
|
||||
event.preventDefault();
|
||||
}
|
||||
}, true);
|
||||
}
|
||||
|
||||
/**
|
||||
* True when the showcase tab is the active pane of an open modal
|
||||
* @returns {boolean}
|
||||
*/
|
||||
function isShowcaseTabVisible() {
|
||||
const showcaseTab = document.getElementById('showcase-tab');
|
||||
if (!showcaseTab || !showcaseTab.classList.contains('active')) return false;
|
||||
const modalEl = showcaseTab.closest('.modal');
|
||||
// No .modal ancestor: standalone/test rendering, treat as visible
|
||||
if (!modalEl) return true;
|
||||
return modalEl.classList.contains('show') || modalEl.style.display === 'block';
|
||||
}
|
||||
|
||||
/**
|
||||
* Typing-target guard for the example shortcuts. Unlike the model-level
|
||||
* navigation guard, buttons are NOT excluded: clicking a thumbnail or nav
|
||||
* button leaves focus on it, which would make [ ] feel dead right after the
|
||||
* most common interaction — and buttons consume Space/Enter natively, never
|
||||
* bracket keys.
|
||||
* @param {EventTarget|null} target - keydown event target
|
||||
* @returns {boolean}
|
||||
*/
|
||||
function isTypingTarget(target) {
|
||||
if (!target) return false;
|
||||
const tagName = target.tagName ? target.tagName.toLowerCase() : '';
|
||||
return target.isContentEditable || ['input', 'textarea', 'select'].includes(tagName);
|
||||
}
|
||||
|
||||
// '[' / ']' switch examples while the gallery is expanded. ArrowLeft/Right
|
||||
// stay reserved for model-level navigation (ModelModal), and the full-size
|
||||
// media viewer owns its keys while open.
|
||||
document.addEventListener('keydown', (event) => {
|
||||
if (event.key !== '[' && event.key !== ']') return;
|
||||
if (!galleryState.expanded || galleryState.images.length < 2) return;
|
||||
if (isTypingTarget(event.target)) return;
|
||||
if (isMediaViewerOpen()) return;
|
||||
if (!isShowcaseTabVisible()) return;
|
||||
|
||||
event.preventDefault();
|
||||
updateMainDisplay(galleryState.activeIndex + (event.key === ']' ? 1 : -1));
|
||||
});
|
||||
|
||||
/**
|
||||
* Defer metadata fetches for video thumbnails until they scroll into view:
|
||||
* with preload="metadata" on every strip video, expanding the gallery would
|
||||
* otherwise hit the network for all of them at once
|
||||
* @param {HTMLElement} gallery - The .showcase-gallery element
|
||||
*/
|
||||
function initStripVideoLazyLoading(gallery) {
|
||||
const videos = gallery.querySelectorAll('.gallery-strip video[data-lazy-video]');
|
||||
if (!videos.length) return;
|
||||
|
||||
const enable = (video) => {
|
||||
video.preload = 'metadata';
|
||||
video.load();
|
||||
video.removeAttribute('data-lazy-video');
|
||||
};
|
||||
|
||||
if (typeof IntersectionObserver === 'undefined') {
|
||||
videos.forEach(enable);
|
||||
return;
|
||||
}
|
||||
|
||||
// No explicit root: intersection accounts for the strip's overflow
|
||||
// clipping, so off-screen thumbnails stay at preload="none"
|
||||
const observer = new IntersectionObserver((entries) => {
|
||||
entries.forEach(entry => {
|
||||
if (entry.isIntersecting) {
|
||||
enable(entry.target);
|
||||
observer.unobserve(entry.target);
|
||||
}
|
||||
});
|
||||
});
|
||||
videos.forEach(video => observer.observe(video));
|
||||
}
|
||||
|
||||
/**
|
||||
* Initialize all gallery interactions
|
||||
* @param {HTMLElement} gallery - The .showcase-gallery element
|
||||
@@ -683,6 +951,13 @@ export function initShowcaseContent(gallery) {
|
||||
const container = gallery.querySelector('.main-media-container');
|
||||
if (container && galleryState.expanded) {
|
||||
initMainMediaInteractions(container);
|
||||
initWheelNavigation(gallery);
|
||||
initSwipeNavigation(gallery);
|
||||
// Gallery just (re)rendered expanded: warm the cache for the
|
||||
// examples adjacent to the active one
|
||||
prefetchAdjacentMedia();
|
||||
// Video thumbnails start at preload="none"; enable them on visibility
|
||||
initStripVideoLazyLoading(gallery);
|
||||
}
|
||||
|
||||
// Reposition controls on window resize
|
||||
|
||||
+6
-1
@@ -12,6 +12,7 @@ import { helpManager } from './managers/HelpManager.js';
|
||||
import { doctorManager } from './managers/DoctorManager.js';
|
||||
import { bannerService } from './managers/BannerService.js';
|
||||
import { initTheme, initBackToTop } from './utils/uiHelpers.js';
|
||||
import { applyModalBackdropBlurPolicy } from './utils/renderingCapability.js';
|
||||
import { initializeInfiniteScroll } from './utils/infiniteScroll.js';
|
||||
import { i18n } from './i18n/index.js';
|
||||
import { onboardingManager } from './managers/OnboardingManager.js';
|
||||
@@ -33,7 +34,11 @@ export class AppCore {
|
||||
if (this.initialized) return;
|
||||
|
||||
console.log('AppCore: Initializing...');
|
||||
|
||||
|
||||
// Disable full-viewport backdrop blur under software rendering before
|
||||
// anything can open a modal (issue #1092)
|
||||
applyModalBackdropBlurPolicy();
|
||||
|
||||
// Initialize i18n first
|
||||
window.i18n = i18n;
|
||||
// Wait for i18n to be ready
|
||||
|
||||
@@ -3,6 +3,7 @@ import { confirmDelete, closeDeleteModal, confirmExclude, closeExcludeModal } fr
|
||||
import { createPageControls } from './components/controls/index.js';
|
||||
import { ModelDuplicatesManager } from './components/ModelDuplicatesManager.js';
|
||||
import { MODEL_TYPES } from './api/apiConfig.js';
|
||||
import { initActiveFiltersSync } from './utils/activeFiltersSync.js';
|
||||
|
||||
// Initialize the Embeddings page
|
||||
class EmbeddingsPageManager {
|
||||
@@ -32,6 +33,9 @@ class EmbeddingsPageManager {
|
||||
// Initialize common page features (including context menus)
|
||||
appCore.initializePageFeatures();
|
||||
|
||||
// Mirror active filters to the backend for the ComfyUI-side autocomplete
|
||||
initActiveFiltersSync(MODEL_TYPES.EMBEDDING);
|
||||
|
||||
console.log('Embeddings Manager initialized');
|
||||
}
|
||||
}
|
||||
|
||||
@@ -4,6 +4,7 @@ import { updateCardsForBulkMode } from './components/shared/ModelCard.js';
|
||||
import { createPageControls } from './components/controls/index.js';
|
||||
import { confirmDelete, closeDeleteModal, confirmExclude, closeExcludeModal } from './utils/modalUtils.js';
|
||||
import { ModelDuplicatesManager } from './components/ModelDuplicatesManager.js';
|
||||
import { initActiveFiltersSync } from './utils/activeFiltersSync.js';
|
||||
|
||||
// Initialize the LoRA page
|
||||
export class LoraPageManager {
|
||||
@@ -41,6 +42,9 @@ export class LoraPageManager {
|
||||
|
||||
// Initialize common page features (including context menus and virtual scroll)
|
||||
appCore.initializePageFeatures();
|
||||
|
||||
// Mirror active filters to the backend for the ComfyUI-side autocomplete
|
||||
initActiveFiltersSync('loras');
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -30,8 +30,9 @@ export class BulkMissingLoraDownloadManager {
|
||||
|
||||
if (recipe.loras && Array.isArray(recipe.loras)) {
|
||||
recipe.loras.forEach(lora => {
|
||||
// Only include LoRAs not in library and not deleted
|
||||
if (!lora.inLibrary && !lora.isDeleted) {
|
||||
// Only include LoRAs not in library and still downloadable
|
||||
// (not deleted from the source, hash still resolvable)
|
||||
if (!lora.inLibrary && !lora.isDeleted && !lora.hashInvalid) {
|
||||
const uniqueKey = lora.hash || lora.id || lora.modelVersionId;
|
||||
|
||||
if (uniqueKey && !uniqueLoras.has(uniqueKey)) {
|
||||
|
||||
@@ -1182,10 +1182,13 @@ export class DownloadManager {
|
||||
if (!response?.success) {
|
||||
this.loadingManager.setStatus(translate('modals.download.status.finalizing'));
|
||||
const errorMessage = response?.error || 'Unknown error';
|
||||
// Always record the latest failure so callers can distinguish
|
||||
// an unresolvable model (not found / deleted) from a transient
|
||||
// transport failure; the summary flow below may or may not run.
|
||||
this._lastDownloadError = errorMessage;
|
||||
// When the caller aggregates failures itself (multi-file
|
||||
// loop), just record the error and return (#1058).
|
||||
if (suppressFailureSummary) {
|
||||
this._lastDownloadError = errorMessage;
|
||||
return false;
|
||||
}
|
||||
// A file-level "already in library" rejection is an expected
|
||||
|
||||
@@ -511,18 +511,21 @@ export class FilterManager {
|
||||
filteredModels.forEach(model => {
|
||||
const tag = document.createElement('div');
|
||||
tag.className = 'filter-tag base-model-tag';
|
||||
tag.dataset.baseModel = model.name;
|
||||
// Display name may differ from the filter value (e.g. the "Unknown"
|
||||
// bucket shows "Unknown" but filters via a dedicated marker).
|
||||
const filterValue = model.value ?? model.name;
|
||||
tag.dataset.baseModel = filterValue;
|
||||
tag.innerHTML = `${model.name} <span class="tag-count">${model.count}</span>`;
|
||||
|
||||
tag.addEventListener('click', async () => {
|
||||
tag.classList.toggle('active');
|
||||
|
||||
if (tag.classList.contains('active')) {
|
||||
if (!this.filters.baseModel.includes(model.name)) {
|
||||
this.filters.baseModel.push(model.name);
|
||||
if (!this.filters.baseModel.includes(filterValue)) {
|
||||
this.filters.baseModel.push(filterValue);
|
||||
}
|
||||
} else {
|
||||
this.filters.baseModel = this.filters.baseModel.filter(m => m !== model.name);
|
||||
this.filters.baseModel = this.filters.baseModel.filter(m => m !== filterValue);
|
||||
}
|
||||
|
||||
this.updateActiveFiltersCount();
|
||||
|
||||
@@ -1,23 +1,16 @@
|
||||
import { getStorageItem, setStorageItem } from '../utils/storageHelpers.js';
|
||||
import { onboardingManager } from './OnboardingManager.js';
|
||||
|
||||
/**
|
||||
* Manages help modal functionality and tutorial update notifications
|
||||
*/
|
||||
export class HelpManager {
|
||||
constructor() {
|
||||
this.lastViewedTimestamp = getStorageItem('help_last_viewed', 0);
|
||||
this.latestContentTimestamp = new Date('2025-10-11').getTime(); // Will be updated from server or config
|
||||
// Version of the help content the user has seen. Compared against the
|
||||
// data-help-content-version marker rendered into the help modal markup,
|
||||
// so badge state is always derived from the content actually served.
|
||||
this.viewedContentVersion = getStorageItem('help_viewed_content_version', null);
|
||||
this.isInitialized = false;
|
||||
|
||||
// Default latest content data - could be fetched from server
|
||||
this.latestVideoData = {
|
||||
timestamp: new Date('2024-06-09').getTime(), // Default timestamp
|
||||
walkthrough: {
|
||||
id: 'hvKw31YpE-U',
|
||||
title: 'Getting Started with LoRA Manager'
|
||||
},
|
||||
playlistUpdated: true
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -34,9 +27,6 @@ export class HelpManager {
|
||||
// Check if we need to show the badge
|
||||
this.updateHelpBadge();
|
||||
|
||||
// Fetch latest video data (could be implemented to fetch from remote source)
|
||||
this.fetchLatestVideoData();
|
||||
|
||||
this.isInitialized = true;
|
||||
return this;
|
||||
}
|
||||
@@ -55,77 +45,147 @@ export class HelpManager {
|
||||
const tabButtons = document.querySelectorAll('.help-tabs .tab-btn');
|
||||
tabButtons.forEach(button => {
|
||||
button.addEventListener('click', (event) => {
|
||||
// Remove active class from all buttons and panes
|
||||
document.querySelectorAll('.help-tabs .tab-btn').forEach(btn => {
|
||||
btn.classList.remove('active');
|
||||
});
|
||||
document.querySelectorAll('.help-content .tab-pane').forEach(pane => {
|
||||
pane.classList.remove('active');
|
||||
});
|
||||
|
||||
// Add active class to clicked button
|
||||
event.currentTarget.classList.add('active');
|
||||
|
||||
// Show corresponding tab content
|
||||
const tabId = event.currentTarget.getAttribute('data-tab');
|
||||
document.getElementById(tabId).classList.add('active');
|
||||
this.activateHelpTab(event.currentTarget.getAttribute('data-tab'));
|
||||
});
|
||||
});
|
||||
|
||||
// Replay tutorial button in the Getting Started tab
|
||||
const replayTutorialBtn = document.getElementById('replayTutorialBtn');
|
||||
if (replayTutorialBtn) {
|
||||
replayTutorialBtn.addEventListener('click', () => {
|
||||
// Close the help modal, then restart the onboarding tutorial
|
||||
if (window.modalManager) {
|
||||
window.modalManager.closeModal('helpModal');
|
||||
}
|
||||
onboardingManager.reset();
|
||||
onboardingManager.startTutorial();
|
||||
});
|
||||
}
|
||||
|
||||
// Global "?" shortcut opens the help modal on the Shortcuts tab
|
||||
document.addEventListener('keydown', (event) => {
|
||||
if (event.key !== '?') return;
|
||||
if (this.isTypingContext(event.target)) return;
|
||||
if (window.modalManager?.isAnyModalOpen()) return;
|
||||
|
||||
event.preventDefault();
|
||||
this.openHelpModal('shortcuts');
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Check if the event target is a text entry context where "?" is literal input
|
||||
*/
|
||||
isTypingContext(target) {
|
||||
if (!(target instanceof Element)) return false;
|
||||
|
||||
const tagName = target.tagName?.toLowerCase();
|
||||
return target.isContentEditable || tagName === 'input' || tagName === 'textarea' || tagName === 'select';
|
||||
}
|
||||
|
||||
/**
|
||||
* Activate a specific help modal tab by its data-tab id
|
||||
* @param {string} tabId - The tab id (matches data-tab and pane element id)
|
||||
*/
|
||||
activateHelpTab(tabId) {
|
||||
const tabButton = document.querySelector(`.help-tabs .tab-btn[data-tab="${tabId}"]`);
|
||||
const tabPane = document.getElementById(tabId);
|
||||
if (!tabButton || !tabPane) return;
|
||||
|
||||
// Remove active class from all buttons and panes
|
||||
document.querySelectorAll('.help-tabs .tab-btn').forEach(btn => {
|
||||
btn.classList.remove('active');
|
||||
});
|
||||
document.querySelectorAll('.help-content .tab-pane').forEach(pane => {
|
||||
pane.classList.remove('active');
|
||||
});
|
||||
|
||||
// Activate the requested tab
|
||||
tabButton.classList.add('active');
|
||||
tabPane.classList.add('active');
|
||||
}
|
||||
|
||||
/**
|
||||
* Open the help modal
|
||||
* @param {string} [tabId] - Optional tab id to activate after opening
|
||||
*/
|
||||
openHelpModal() {
|
||||
openHelpModal(tabId) {
|
||||
// Use modalManager to open the help modal
|
||||
if (window.modalManager) {
|
||||
window.modalManager.toggleModal('helpModal');
|
||||
|
||||
// Add visual indicator to Documentation tab if there's new content
|
||||
this.updateDocumentationTabIndicator();
|
||||
|
||||
// Update the last viewed timestamp
|
||||
this.markContentAsViewed();
|
||||
|
||||
// Hide the badge
|
||||
this.hideHelpBadge();
|
||||
if (!window.modalManager) return;
|
||||
|
||||
const hadNewContent = this.hasNewContent();
|
||||
|
||||
window.modalManager.toggleModal('helpModal');
|
||||
|
||||
if (tabId) {
|
||||
this.activateHelpTab(tabId);
|
||||
}
|
||||
|
||||
// Only acknowledge the content as viewed when the user opened the
|
||||
// modal while it actually contained new content. Opening a stale
|
||||
// (pre-upgrade) page must not suppress the badge after a refresh.
|
||||
if (hadNewContent) {
|
||||
this.updateNewContentTabIndicators();
|
||||
this.markContentAsViewed();
|
||||
}
|
||||
|
||||
// Hide the badge
|
||||
this.hideHelpBadge();
|
||||
}
|
||||
|
||||
/**
|
||||
* Add visual indicator to Documentation tab for new content
|
||||
* Add visual indicator to tabs that received new content
|
||||
*/
|
||||
updateDocumentationTabIndicator() {
|
||||
const docTab = document.querySelector('.tab-btn[data-tab="documentation"]');
|
||||
if (docTab && this.hasNewContent()) {
|
||||
docTab.classList.add('has-new-content');
|
||||
updateNewContentTabIndicators() {
|
||||
if (!this.hasNewContent()) return;
|
||||
|
||||
// Tabs updated in the 2026-09-03 discoverability release:
|
||||
// getting-started (Replay Tutorial button) and shortcuts (new cheat-sheet tab)
|
||||
const NEW_CONTENT_TABS = ['getting-started', 'shortcuts'];
|
||||
NEW_CONTENT_TABS.forEach(tabId => {
|
||||
const tab = document.querySelector(`.help-tabs .tab-btn[data-tab="${tabId}"]`);
|
||||
if (tab) {
|
||||
tab.classList.add('has-new-content');
|
||||
}
|
||||
});
|
||||
|
||||
// Point the indicator at the specific new element inside the
|
||||
// Getting Started tab, and scroll it into view so it is not lost
|
||||
// below the fold of the modal body.
|
||||
const replayBtn = document.getElementById('replayTutorialBtn');
|
||||
if (replayBtn) {
|
||||
replayBtn.classList.add('has-new-content');
|
||||
const gettingStartedActive = document.querySelector('#getting-started.tab-pane.active');
|
||||
if (gettingStartedActive && typeof replayBtn.scrollIntoView === 'function') {
|
||||
replayBtn.scrollIntoView({ behavior: 'smooth', block: 'nearest' });
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Mark content as viewed by saving current timestamp
|
||||
* Mark content as viewed by persisting the version rendered in the DOM.
|
||||
* No-op when the served markup carries no version marker (stale assets),
|
||||
* so viewing old content never suppresses the badge for new content.
|
||||
*/
|
||||
markContentAsViewed() {
|
||||
this.lastViewedTimestamp = Date.now();
|
||||
setStorageItem('help_last_viewed', this.lastViewedTimestamp);
|
||||
const currentVersion = this.getCurrentContentVersion();
|
||||
if (!currentVersion) return;
|
||||
|
||||
this.viewedContentVersion = currentVersion;
|
||||
setStorageItem('help_viewed_content_version', this.viewedContentVersion);
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Fetch latest video data (could be implemented to actually fetch from a remote source)
|
||||
* Read the help content version from the rendered modal markup
|
||||
* @returns {string|null} Version marker, or null if the served markup has none
|
||||
*/
|
||||
fetchLatestVideoData() {
|
||||
// In a real implementation, you'd fetch this from your server
|
||||
// For now, we'll just use the hardcoded data from constructor
|
||||
|
||||
// Update the timestamp with the latest data
|
||||
this.latestContentTimestamp = Math.max(this.latestContentTimestamp, this.latestVideoData.timestamp);
|
||||
|
||||
// Check again if we need to show the badge with this new data
|
||||
this.updateHelpBadge();
|
||||
getCurrentContentVersion() {
|
||||
const marker = document.querySelector('[data-help-content-version]');
|
||||
return marker ? marker.getAttribute('data-help-content-version') : null;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Update help badge visibility based on timestamps
|
||||
* Update help badge visibility based on viewed vs. served content version
|
||||
*/
|
||||
updateHelpBadge() {
|
||||
if (this.hasNewContent()) {
|
||||
@@ -134,13 +194,13 @@ export class HelpManager {
|
||||
this.hideHelpBadge();
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Check if there's new content the user hasn't seen
|
||||
* Check if the served help content is newer than what the user has viewed
|
||||
*/
|
||||
hasNewContent() {
|
||||
// If user has never viewed the help, or the content is newer than last viewed
|
||||
return this.lastViewedTimestamp === 0 || this.latestContentTimestamp > this.lastViewedTimestamp;
|
||||
const currentVersion = this.getCurrentContentVersion();
|
||||
return Boolean(currentVersion) && currentVersion !== this.viewedContentVersion;
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@@ -43,7 +43,7 @@ export class OnboardingManager {
|
||||
{
|
||||
target: '.controls .action-buttons [data-action="bulk"]',
|
||||
title: () => translate('onboarding.steps.bulk.title', {}, 'Bulk Operations'),
|
||||
content: () => translate('onboarding.steps.bulk.content', {}, 'Enter bulk mode by clicking this button or pressing <span class="onboarding-shortcut">B</span>. Select multiple models and perform batch operations. Use <span class="onboarding-shortcut">Ctrl+A</span> to select all visible models.'),
|
||||
content: () => translate('onboarding.steps.bulk.content', {}, 'Enter bulk mode by clicking this button or pressing <span class="onboarding-shortcut">B</span> to select multiple models and perform batch operations.<br>• <span class="onboarding-shortcut">Ctrl/Cmd+A</span> select all visible models, <span class="onboarding-shortcut">Shift+Click</span> select a range.<br>• <span class="onboarding-shortcut">Esc</span> or clicking an empty area exits bulk mode.'),
|
||||
position: 'bottom'
|
||||
},
|
||||
{
|
||||
@@ -71,10 +71,30 @@ export class OnboardingManager {
|
||||
position: 'top',
|
||||
customPosition: { top: '20%', left: '50%' }
|
||||
},
|
||||
{
|
||||
target: '.card-grid',
|
||||
title: () => translate('onboarding.steps.marqueeSelect.title', {}, 'Drag to Select'),
|
||||
content: () => translate('onboarding.steps.marqueeSelect.content', {}, 'Hold the <strong>left mouse button</strong> on an empty area of the grid and drag to draw a marquee that selects multiple cards at once.'),
|
||||
position: 'top',
|
||||
customPosition: { top: '20%', left: '50%' }
|
||||
},
|
||||
{
|
||||
target: '#folderSidebar',
|
||||
title: () => translate('onboarding.steps.dragToSidebar.title', {}, 'Organize by Dragging'),
|
||||
content: () => translate('onboarding.steps.dragToSidebar.content', {}, 'Drag a model card onto a folder in the sidebar to move the file there. This also works with multiple selected cards in bulk mode.'),
|
||||
position: 'right'
|
||||
},
|
||||
{
|
||||
target: '.card-grid',
|
||||
title: () => translate('onboarding.steps.contextMenu.title', {}, 'Context Menu'),
|
||||
content: () => translate('onboarding.steps.contextMenu.content', {}, '<strong>Right-click</strong> any model card for a context menu with additional actions.'),
|
||||
content: () => translate('onboarding.steps.contextMenu.content', {}, '<strong>Right-click</strong> any model card for a context menu with card actions like moving, deleting, or editing metadata.'),
|
||||
position: 'top',
|
||||
customPosition: { top: '20%', left: '50%' }
|
||||
},
|
||||
{
|
||||
target: '.card-grid',
|
||||
title: () => translate('onboarding.steps.contextMenus.title', {}, 'More Context Menus'),
|
||||
content: () => translate('onboarding.steps.contextMenus.content', {}, 'In bulk mode, <strong>right-click a selected card</strong> for bulk actions. <strong>Right-click an empty area</strong> of the page for global actions like update checks and managing excluded models.'),
|
||||
position: 'top',
|
||||
customPosition: { top: '20%', left: '50%' }
|
||||
}
|
||||
|
||||
@@ -65,6 +65,13 @@ export class DownloadManager {
|
||||
raw_metadata: this.importManager.recipeData.raw_metadata || {},
|
||||
};
|
||||
|
||||
// Pass analysis diagnostics through so the backend can record
|
||||
// why the recipe ended up with no LoRAs (recipe modal panel).
|
||||
const diagnostics = this.importManager.recipeData.diagnostics;
|
||||
if (diagnostics && typeof diagnostics === 'object') {
|
||||
completeMetadata.diagnostics = diagnostics;
|
||||
}
|
||||
|
||||
// Preserve preview_nsfw_level from analysis so the saved
|
||||
// recipe applies the correct NSFW blur on the preview image.
|
||||
const nsfwLevel = this.importManager.recipeData.preview_nsfw_level;
|
||||
|
||||
@@ -0,0 +1,61 @@
|
||||
/**
|
||||
* Mirrors the manager page's active filter state to the backend's in-memory
|
||||
* store, so the ComfyUI-side autocomplete can apply it even when the manager
|
||||
* page and ComfyUI run in different browsers/origins (localStorage is not
|
||||
* shared there).
|
||||
*/
|
||||
|
||||
import { getStorageItem, setActiveFiltersListener } from './storageHelpers.js';
|
||||
import { debounce } from './debounce.js';
|
||||
|
||||
const SYNC_DEBOUNCE_MS = 300;
|
||||
|
||||
const debouncedPushByPage = {};
|
||||
|
||||
function buildActiveFiltersPayload(pageType) {
|
||||
const activeFolder = getStorageItem(`${pageType}_activeFolder`);
|
||||
const recursiveSearch = getStorageItem(`${pageType}_recursiveSearch`, true);
|
||||
const filters = getStorageItem(`${pageType}_filters`);
|
||||
|
||||
return {
|
||||
// null stays null; legacy "null" string is normalized to null
|
||||
activeFolder: activeFolder && activeFolder !== 'null' ? activeFolder : null,
|
||||
recursiveSearch: recursiveSearch !== false,
|
||||
filters: filters && typeof filters === 'object' ? filters : null,
|
||||
};
|
||||
}
|
||||
|
||||
export async function pushActiveFilters(pageType) {
|
||||
try {
|
||||
const response = await fetch(`/api/lm/${pageType}/active-filters`, {
|
||||
method: 'PUT',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify(buildActiveFiltersPayload(pageType)),
|
||||
});
|
||||
if (!response.ok) {
|
||||
console.warn(`[Lora Manager] Failed to sync active filters for ${pageType}: HTTP ${response.status}`);
|
||||
}
|
||||
} catch (error) {
|
||||
console.warn(`[Lora Manager] Failed to sync active filters for ${pageType}:`, error);
|
||||
}
|
||||
}
|
||||
|
||||
export function syncActiveFilters(pageType) {
|
||||
if (!debouncedPushByPage[pageType]) {
|
||||
debouncedPushByPage[pageType] = debounce(() => {
|
||||
pushActiveFilters(pageType);
|
||||
}, SYNC_DEBOUNCE_MS);
|
||||
}
|
||||
debouncedPushByPage[pageType]();
|
||||
}
|
||||
|
||||
/**
|
||||
* Register the storage listener and push the current (restored) state once.
|
||||
* The initial push covers server restarts, where the backend store is empty
|
||||
* until the manager page re-publishes its localStorage-restored filters.
|
||||
* @param {string} pageType - 'loras' | 'checkpoints' | 'embeddings'
|
||||
*/
|
||||
export function initActiveFiltersSync(pageType) {
|
||||
setActiveFiltersListener((changedPageType) => syncActiveFilters(changedPageType));
|
||||
pushActiveFilters(pageType);
|
||||
}
|
||||
@@ -9,8 +9,13 @@
|
||||
export const OptimizationMode = {
|
||||
/** Full quality for showcase/display - uses /optimized=true only */
|
||||
SHOWCASE: 'showcase',
|
||||
/** In-modal display - caps image width at 2400 (covers the ~1200 CSS px
|
||||
* main viewer at DPR 2); videos stay full quality */
|
||||
DISPLAY: 'display',
|
||||
/** Thumbnail size for cards - uses /width=450,optimized=true */
|
||||
THUMBNAIL: 'thumbnail',
|
||||
/** Small thumbnails for the showcase gallery strip (72px display) - uses /width=160,optimized=true */
|
||||
GALLERY_THUMBNAIL: 'gallery-thumbnail',
|
||||
};
|
||||
|
||||
export const DEFAULT_CIVITAI_PAGE_HOST = 'civitai.com';
|
||||
@@ -95,15 +100,21 @@ export function rewriteCivitaiUrl(sourceUrl, mediaType = null, mode = Optimizati
|
||||
}
|
||||
|
||||
// Determine replacement based on mode and media type
|
||||
const isVideo = Boolean(mediaType && mediaType.toLowerCase() === 'video');
|
||||
let replacement;
|
||||
if (mode === OptimizationMode.SHOWCASE) {
|
||||
// Full quality for showcase - no width restriction
|
||||
replacement = '/optimized=true';
|
||||
} else if (mode === OptimizationMode.DISPLAY) {
|
||||
// Display mode caps image width for in-modal viewing; videos stay
|
||||
// full quality (CDN transcoding costs more than it saves here)
|
||||
replacement = isVideo ? '/optimized=true' : '/width=2400,optimized=true';
|
||||
} else {
|
||||
// Thumbnail mode with width restriction
|
||||
replacement = '/width=450,optimized=true';
|
||||
if (mediaType && mediaType.toLowerCase() === 'video') {
|
||||
replacement = '/transcode=true,width=450,optimized=true';
|
||||
// Thumbnail modes with width restriction
|
||||
const width = mode === OptimizationMode.GALLERY_THUMBNAIL ? 160 : 450;
|
||||
replacement = `/width=${width},optimized=true`;
|
||||
if (isVideo) {
|
||||
replacement = `/transcode=true,width=${width},optimized=true`;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -150,6 +161,19 @@ export function getShowcaseUrl(url, type = 'image') {
|
||||
return getOptimizedUrl(url, type, OptimizationMode.SHOWCASE);
|
||||
}
|
||||
|
||||
/**
|
||||
* Get display-optimized URL for the in-modal main viewer (images capped at
|
||||
* width=2400; videos full quality). Use getShowcaseUrl for full-size viewing
|
||||
* (e.g. the media viewer overlay)
|
||||
*
|
||||
* @param {string} url - Original URL
|
||||
* @param {string} type - Media type ("image" or "video")
|
||||
* @returns {string} - Optimized URL for in-modal display
|
||||
*/
|
||||
export function getDisplayUrl(url, type = 'image') {
|
||||
return getOptimizedUrl(url, type, OptimizationMode.DISPLAY);
|
||||
}
|
||||
|
||||
/**
|
||||
* Get thumbnail-optimized URL (width=450)
|
||||
*
|
||||
@@ -161,6 +185,17 @@ export function getThumbnailUrl(url, type = 'image') {
|
||||
return getOptimizedUrl(url, type, OptimizationMode.THUMBNAIL);
|
||||
}
|
||||
|
||||
/**
|
||||
* Get gallery-strip-thumbnail-optimized URL (width=160, for the 72px strip)
|
||||
*
|
||||
* @param {string} url - Original URL
|
||||
* @param {string} type - Media type ("image" or "video")
|
||||
* @returns {string} - Optimized URL for gallery strip thumbnail display
|
||||
*/
|
||||
export function getGalleryThumbnailUrl(url, type = 'image') {
|
||||
return getOptimizedUrl(url, type, OptimizationMode.GALLERY_THUMBNAIL);
|
||||
}
|
||||
|
||||
/**
|
||||
* Check if a URL is from CivitAI
|
||||
*
|
||||
|
||||
@@ -0,0 +1,66 @@
|
||||
/**
|
||||
* Software-rendering detection for degrading expensive visual effects.
|
||||
*
|
||||
* With hardware acceleration disabled (or a GPU blocklisted), Chrome rasterizes
|
||||
* in software. A full-viewport `backdrop-filter: blur()` then forces a per-frame
|
||||
* CPU blur over everything painted behind the modal, freezing the entire
|
||||
* browser (issue #1092). When software rendering is detected we add the
|
||||
* `no-modal-backdrop-blur` class to <html>, and CSS drops the backdrop blur.
|
||||
*/
|
||||
|
||||
const SOFTWARE_RENDERER_PATTERN = /swiftshader|llvmpipe|softpipe|software|basic render/i;
|
||||
|
||||
/**
|
||||
* Check a WebGL renderer string against known software rasterizers.
|
||||
* @param {string} renderer - UNMASKED_RENDERER_WEBGL string
|
||||
* @returns {boolean}
|
||||
*/
|
||||
export function isSoftwareRendererString(renderer) {
|
||||
return SOFTWARE_RENDERER_PATTERN.test(renderer || '');
|
||||
}
|
||||
|
||||
/**
|
||||
* Read the unmasked WebGL renderer string, or null when unavailable/masked.
|
||||
* @returns {string|null}
|
||||
*/
|
||||
function getWebGLRendererString() {
|
||||
const canvas = document.createElement('canvas');
|
||||
const gl = canvas.getContext('webgl') || canvas.getContext('experimental-webgl');
|
||||
if (!gl) return null;
|
||||
|
||||
const debugInfo = gl.getExtension('WEBGL_debug_renderer_info');
|
||||
const renderer = debugInfo
|
||||
? String(gl.getParameter(debugInfo.UNMASKED_RENDERER_WEBGL) || '')
|
||||
: '';
|
||||
|
||||
const loseContext = gl.getExtension('WEBGL_lose_context');
|
||||
if (loseContext) loseContext.loseContext();
|
||||
|
||||
return renderer || null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Heuristic: is the browser rasterizing in software?
|
||||
* - No WebGL at all: no evidence of GPU acceleration, assume software.
|
||||
* - Masked renderer string or detection failure: cannot tell, keep effects on.
|
||||
* @returns {boolean}
|
||||
*/
|
||||
export function isSoftwareRendering() {
|
||||
try {
|
||||
const renderer = getWebGLRendererString();
|
||||
if (renderer === null) {
|
||||
return true;
|
||||
}
|
||||
return isSoftwareRendererString(renderer);
|
||||
} catch (error) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Toggle the blur-disabling class on <html>. Runs once at app startup.
|
||||
* @param {boolean} [isSoftware] - Override for tests; defaults to detection.
|
||||
*/
|
||||
export function applyModalBackdropBlurPolicy(isSoftware = isSoftwareRendering()) {
|
||||
document.documentElement.classList.toggle('no-modal-backdrop-blur', isSoftware);
|
||||
}
|
||||
@@ -0,0 +1,61 @@
|
||||
import { translate } from './i18nHelpers.js';
|
||||
|
||||
/**
|
||||
* Format a remaining-time estimate for scan progress display.
|
||||
* @param {number} remainingMs - Estimated remaining time in milliseconds
|
||||
* @returns {string} Localized ETA text
|
||||
*/
|
||||
export function formatScanRemainingTime(remainingMs) {
|
||||
if (remainingMs < 60000) {
|
||||
return translate('common.scanProgress.eta.lessThanMinute', {}, 'Less than a minute remaining');
|
||||
}
|
||||
if (remainingMs < 3600000) {
|
||||
const minutes = Math.round(remainingMs / 60000);
|
||||
return translate('common.scanProgress.eta.minutes', { minutes }, `~${minutes} min remaining`);
|
||||
}
|
||||
const hours = Math.floor(remainingMs / 3600000);
|
||||
const minutes = Math.round((remainingMs % 3600000) / 60000);
|
||||
return translate('common.scanProgress.eta.hours', { hours, minutes }, `~${hours} hr ${minutes} min remaining`);
|
||||
}
|
||||
|
||||
/**
|
||||
* Create an ETA tracker for scan progress. Uses an exponential moving
|
||||
* average (0.7/0.3) over the observed per-file processing time, mirroring
|
||||
* the estimator in components/initialization.js.
|
||||
* @returns {{ update: (processed: number, total: number) => (string|null) }}
|
||||
*/
|
||||
export function createScanEtaTracker() {
|
||||
let startTime = null;
|
||||
let lastProcessed = 0;
|
||||
let averageMsPerFile = null;
|
||||
|
||||
return {
|
||||
/**
|
||||
* Update with the latest counters.
|
||||
* @returns {string|null} Localized ETA text, or null when not applicable
|
||||
*/
|
||||
update(processed, total) {
|
||||
if (!total || total <= 0 || processed >= total) {
|
||||
return null;
|
||||
}
|
||||
const now = Date.now();
|
||||
if (startTime === null) {
|
||||
// First sample only anchors the timer; not enough data yet
|
||||
startTime = now;
|
||||
lastProcessed = processed;
|
||||
return translate('initialization.estimatingTime', {}, 'Estimating time...');
|
||||
}
|
||||
if (processed > lastProcessed) {
|
||||
const msPerFile = (now - startTime) / processed;
|
||||
averageMsPerFile = averageMsPerFile === null
|
||||
? msPerFile
|
||||
: averageMsPerFile * 0.7 + msPerFile * 0.3;
|
||||
lastProcessed = processed;
|
||||
}
|
||||
if (averageMsPerFile === null) {
|
||||
return translate('initialization.estimatingTime', {}, 'Estimating time...');
|
||||
}
|
||||
return formatScanRemainingTime((total - lastProcessed) * averageMsPerFile);
|
||||
}
|
||||
};
|
||||
}
|
||||
@@ -6,6 +6,31 @@
|
||||
// Namespace prefix for all localStorage keys
|
||||
const STORAGE_PREFIX = 'lora_manager_';
|
||||
|
||||
// Matches keys that carry the manager page's active filter state
|
||||
// (e.g. 'loras_activeFolder', 'checkpoints_filters').
|
||||
const ACTIVE_FILTER_KEY_PATTERN = /^(loras|checkpoints|embeddings)_(activeFolder|recursiveSearch|filters)$/;
|
||||
|
||||
let activeFiltersListener = null;
|
||||
|
||||
/**
|
||||
* Register a listener invoked with the page type whenever one of the
|
||||
* active-filter storage keys changes. Used to mirror filter state to the
|
||||
* backend so the ComfyUI-side autocomplete can pick it up across
|
||||
* browsers/origins where localStorage is not shared.
|
||||
* @param {function(string): void} listener
|
||||
*/
|
||||
export function setActiveFiltersListener(listener) {
|
||||
activeFiltersListener = listener;
|
||||
}
|
||||
|
||||
function notifyActiveFiltersChanged(key) {
|
||||
if (!activeFiltersListener) return;
|
||||
const match = ACTIVE_FILTER_KEY_PATTERN.exec(key);
|
||||
if (match) {
|
||||
activeFiltersListener(match[1]);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Get an item from localStorage with namespace support and fallback to legacy keys
|
||||
* @param {string} key - The key without prefix
|
||||
@@ -51,13 +76,15 @@ export function getStorageItem(key, defaultValue = null) {
|
||||
*/
|
||||
export function setStorageItem(key, value) {
|
||||
const prefixedKey = STORAGE_PREFIX + key;
|
||||
|
||||
|
||||
// Convert objects and arrays to JSON strings
|
||||
if (typeof value === 'object' && value !== null) {
|
||||
localStorage.setItem(prefixedKey, JSON.stringify(value));
|
||||
} else {
|
||||
localStorage.setItem(prefixedKey, value);
|
||||
}
|
||||
|
||||
notifyActiveFiltersChanged(key);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -67,6 +94,8 @@ export function setStorageItem(key, value) {
|
||||
export function removeStorageItem(key) {
|
||||
localStorage.removeItem(STORAGE_PREFIX + key);
|
||||
localStorage.removeItem(key); // Also remove legacy key
|
||||
|
||||
notifyActiveFiltersChanged(key);
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@@ -311,6 +311,20 @@ export function showActionToast(key, params = {}, type = 'info', options = {}) {
|
||||
toast.append(closeBtn);
|
||||
}
|
||||
|
||||
/**
|
||||
* Check whether the event target is a text-entry context (input, textarea,
|
||||
* select, or contenteditable) where single-letter shortcuts should be treated
|
||||
* as literal input.
|
||||
* @param {EventTarget|null} target - The DOM event target
|
||||
* @returns {boolean}
|
||||
*/
|
||||
export function isTypingContext(target) {
|
||||
if (!(target instanceof Element)) return false;
|
||||
|
||||
const tagName = target.tagName?.toLowerCase();
|
||||
return target.isContentEditable || tagName === 'input' || tagName === 'textarea' || tagName === 'select';
|
||||
}
|
||||
|
||||
export function restoreFolderFilter() {
|
||||
const activeFolder = getStorageItem('activeFolder');
|
||||
const folderTag = activeFolder && document.querySelector(`.tag[data-folder="${activeFolder}"]`);
|
||||
|
||||
@@ -65,7 +65,7 @@
|
||||
</select>
|
||||
</div>
|
||||
<div title="{% if page_id == 'recipes' %}{{ t('recipes.controls.refresh.title') }}{% else %}{{ t('loras.controls.refresh.title') }}{% endif %}" class="control-group dropdown-group">
|
||||
<button data-action="refresh" class="dropdown-main"><i class="fas fa-sync"></i> <span>{{ t('common.actions.refresh') }}</span></button>
|
||||
<button data-action="refresh" class="dropdown-main"><i class="fas fa-sync"></i> <span><span>{{ t('common.actions.refresh') }}</span> <kbd class="shortcut-key">R</kbd></span></button>
|
||||
<button class="dropdown-toggle" aria-label="Show refresh options">
|
||||
<i class="fas fa-caret-down"></i>
|
||||
</button>
|
||||
@@ -78,11 +78,11 @@
|
||||
|
||||
{% if page_id != 'recipes' %}
|
||||
<div class="control-group">
|
||||
<button data-action="fetch" title="{{ t('loras.controls.fetch.title') }}"><i class="fas fa-download"></i> <span>{{ t('loras.controls.fetch.action') }}</span></button>
|
||||
<button data-action="fetch" title="{{ t('loras.controls.fetch.title') }}"><i class="fas fa-download"></i> <span><span>{{ t('loras.controls.fetch.action') }}</span> <kbd class="shortcut-key">F</kbd></span></button>
|
||||
</div>
|
||||
<div class="control-group">
|
||||
<button data-action="download" title="{{ t('loras.controls.download.title') }}">
|
||||
<i class="fas fa-cloud-download-alt"></i> <span>{{ t('loras.controls.download.action') }}</span>
|
||||
<i class="fas fa-cloud-download-alt"></i> <span><span>{{ t('loras.controls.download.action') }}</span> <kbd class="shortcut-key">D</kbd></span>
|
||||
</button>
|
||||
</div>
|
||||
{% endif %}
|
||||
@@ -96,7 +96,7 @@
|
||||
{% endif %}
|
||||
<div class="control-group">
|
||||
<button id="bulkOperationsBtn" data-action="bulk" title="{{ t('loras.controls.bulk.title') }}">
|
||||
<i class="fas fa-th-large"></i> <span><span>{{ t('loras.controls.bulk.action') }}</span> <div class="shortcut-key">B</div></span>
|
||||
<i class="fas fa-th-large"></i> <span><span>{{ t('loras.controls.bulk.action') }}</span> <kbd class="shortcut-key">B</kbd></span>
|
||||
</button>
|
||||
</div>
|
||||
<div class="control-group">
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
<!-- Help Modal -->
|
||||
<div id="helpModal" class="modal">
|
||||
<div id="helpModal" class="modal" data-help-content-version="2026-09-03">
|
||||
<div class="modal-content help-modal">
|
||||
<button class="close" onclick="modalManager.closeModal('helpModal')">×</button>
|
||||
<div class="help-header">
|
||||
@@ -10,6 +10,7 @@
|
||||
<button class="tab-btn active" data-tab="getting-started">{{ t('help.tabs.gettingStarted') }}</button>
|
||||
<button class="tab-btn" data-tab="update-vlogs">{{ t('help.tabs.updateVlogs') }}</button>
|
||||
<button class="tab-btn" data-tab="documentation">{{ t('help.tabs.documentation') }}</button>
|
||||
<button class="tab-btn" data-tab="shortcuts">{{ t('help.tabs.shortcuts') }}</button>
|
||||
</div>
|
||||
|
||||
<div class="help-content">
|
||||
@@ -39,6 +40,13 @@
|
||||
<li><strong>Recipe System:</strong> Create, save and share your perfect combinations</li>
|
||||
</ul>
|
||||
</div>
|
||||
<div class="help-actions">
|
||||
<button id="replayTutorialBtn" class="replay-tutorial-btn">
|
||||
<i class="fas fa-graduation-cap"></i>
|
||||
<span>{{ t('help.gettingStarted.replayTutorial') }}</span>
|
||||
<span class="new-content-badge">{{ t('help.newContentBadge') }}</span>
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Update Vlogs Tab -->
|
||||
@@ -136,6 +144,126 @@
|
||||
</ul>
|
||||
</div>
|
||||
</div>
|
||||
<!-- Shortcuts Tab -->
|
||||
<div class="tab-pane" id="shortcuts">
|
||||
<h3>{{ t('help.shortcuts.title') }}</h3>
|
||||
|
||||
<div class="shortcuts-section">
|
||||
<h4><i class="fas fa-keyboard"></i> {{ t('help.shortcuts.groups.general') }}</h4>
|
||||
<ul class="shortcuts-list">
|
||||
<li>
|
||||
<span class="shortcut-keys"><kbd>Ctrl</kbd><span class="shortcut-sep">/</span><kbd>Cmd</kbd><span class="shortcut-sep">+</span><kbd>F</kbd></span>
|
||||
<span class="shortcut-description">{{ t('help.shortcuts.entries.focusSearch') }}</span>
|
||||
</li>
|
||||
<li>
|
||||
<span class="shortcut-keys"><kbd>Esc</kbd></span>
|
||||
<span class="shortcut-description">{{ t('help.shortcuts.entries.closeModal') }}</span>
|
||||
</li>
|
||||
<li>
|
||||
<span class="shortcut-keys"><kbd>?</kbd></span>
|
||||
<span class="shortcut-description">{{ t('help.shortcuts.entries.openShortcuts') }}</span>
|
||||
</li>
|
||||
</ul>
|
||||
</div>
|
||||
|
||||
<div class="shortcuts-section">
|
||||
<h4><i class="fas fa-bolt"></i> {{ t('help.shortcuts.groups.actions') }}</h4>
|
||||
<ul class="shortcuts-list">
|
||||
<li>
|
||||
<span class="shortcut-keys"><kbd>R</kbd></span>
|
||||
<span class="shortcut-description">{{ t('help.shortcuts.entries.refresh') }}</span>
|
||||
</li>
|
||||
<li>
|
||||
<span class="shortcut-keys"><kbd>F</kbd></span>
|
||||
<span class="shortcut-description">{{ t('help.shortcuts.entries.fetchMetadata') }}</span>
|
||||
</li>
|
||||
<li>
|
||||
<span class="shortcut-keys"><kbd>D</kbd></span>
|
||||
<span class="shortcut-description">{{ t('help.shortcuts.entries.downloadModel') }}</span>
|
||||
</li>
|
||||
</ul>
|
||||
</div>
|
||||
|
||||
<div class="shortcuts-section">
|
||||
<h4><i class="fas fa-object-group"></i> {{ t('help.shortcuts.groups.selection') }}</h4>
|
||||
<ul class="shortcuts-list">
|
||||
<li>
|
||||
<span class="shortcut-keys"><kbd>B</kbd></span>
|
||||
<span class="shortcut-description">{{ t('help.shortcuts.entries.toggleBulkMode') }}</span>
|
||||
</li>
|
||||
<li>
|
||||
<span class="shortcut-keys"><kbd>Ctrl</kbd><span class="shortcut-sep">/</span><kbd>Cmd</kbd><span class="shortcut-sep">+</span><kbd>A</kbd></span>
|
||||
<span class="shortcut-description">{{ t('help.shortcuts.entries.selectAll') }}</span>
|
||||
</li>
|
||||
<li>
|
||||
<span class="shortcut-keys"><kbd>Shift</kbd><span class="shortcut-sep">+</span><kbd>{{ t('help.shortcuts.keys.click') }}</kbd></span>
|
||||
<span class="shortcut-description">{{ t('help.shortcuts.entries.rangeSelect') }}</span>
|
||||
</li>
|
||||
<li>
|
||||
<span class="shortcut-keys"><kbd>{{ t('help.shortcuts.keys.drag') }}</kbd></span>
|
||||
<span class="shortcut-description">{{ t('help.shortcuts.entries.marqueeSelect') }}</span>
|
||||
</li>
|
||||
<li>
|
||||
<span class="shortcut-keys"><kbd>Esc</kbd></span>
|
||||
<span class="shortcut-description">{{ t('help.shortcuts.entries.exitBulkMode') }}</span>
|
||||
</li>
|
||||
<li>
|
||||
<span class="shortcut-keys"><kbd>{{ t('help.shortcuts.keys.rightClick') }}</kbd></span>
|
||||
<span class="shortcut-description">{{ t('help.shortcuts.entries.bulkActions') }}</span>
|
||||
</li>
|
||||
<li>
|
||||
<span class="shortcut-keys"><kbd>{{ t('help.shortcuts.keys.rightClick') }}</kbd></span>
|
||||
<span class="shortcut-description">{{ t('help.shortcuts.entries.globalActions') }}</span>
|
||||
</li>
|
||||
</ul>
|
||||
</div>
|
||||
|
||||
<div class="shortcuts-section">
|
||||
<h4><i class="fas fa-arrows-alt-v"></i> {{ t('help.shortcuts.groups.navigation') }}</h4>
|
||||
<ul class="shortcuts-list">
|
||||
<li>
|
||||
<span class="shortcut-keys"><kbd>PageUp</kbd><span class="shortcut-sep">/</span><kbd>PageDown</kbd><span class="shortcut-sep">/</span><kbd>Home</kbd><span class="shortcut-sep">/</span><kbd>End</kbd></span>
|
||||
<span class="shortcut-description">{{ t('help.shortcuts.entries.scrollPages') }}</span>
|
||||
</li>
|
||||
<li>
|
||||
<span class="shortcut-keys"><kbd>Alt</kbd><span class="shortcut-sep">+</span><kbd>{{ t('help.shortcuts.keys.letter') }}</kbd></span>
|
||||
<span class="shortcut-description">{{ t('help.shortcuts.entries.jumpAlphabet') }}</span>
|
||||
</li>
|
||||
</ul>
|
||||
</div>
|
||||
|
||||
<div class="shortcuts-section">
|
||||
<h4><i class="fas fa-window-restore"></i> {{ t('help.shortcuts.groups.modelModal') }}</h4>
|
||||
<ul class="shortcuts-list">
|
||||
<li>
|
||||
<span class="shortcut-keys"><kbd>←</kbd><span class="shortcut-sep">/</span><kbd>→</kbd></span>
|
||||
<span class="shortcut-description">{{ t('help.shortcuts.entries.prevNext') }}</span>
|
||||
</li>
|
||||
<li>
|
||||
<span class="shortcut-keys"><kbd>Delete</kbd></span>
|
||||
<span class="shortcut-description">{{ t('help.shortcuts.entries.deleteEntry') }}</span>
|
||||
</li>
|
||||
</ul>
|
||||
</div>
|
||||
|
||||
<div class="shortcuts-section">
|
||||
<h4><i class="fas fa-images"></i> {{ t('help.shortcuts.groups.mediaViewer') }}</h4>
|
||||
<ul class="shortcuts-list">
|
||||
<li>
|
||||
<span class="shortcut-keys"><kbd>←</kbd><span class="shortcut-sep">/</span><kbd>→</kbd><span class="shortcut-sep">/</span><kbd>[</kbd><span class="shortcut-sep">/</span><kbd>]</kbd></span>
|
||||
<span class="shortcut-description">{{ t('help.shortcuts.entries.cycleMedia') }}</span>
|
||||
</li>
|
||||
<li>
|
||||
<span class="shortcut-keys"><kbd>{{ t('help.shortcuts.keys.swipe') }}</kbd></span>
|
||||
<span class="shortcut-description">{{ t('help.shortcuts.entries.swipeTouch') }}</span>
|
||||
</li>
|
||||
<li>
|
||||
<span class="shortcut-keys"><kbd>Esc</kbd></span>
|
||||
<span class="shortcut-description">{{ t('help.shortcuts.entries.closeViewer') }}</span>
|
||||
</li>
|
||||
</ul>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@@ -14,11 +14,14 @@
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
<!-- Header Actions: Send button is static; source URL button is appended dynamically in RecipeModal.js -->
|
||||
<!-- Header Actions: Send and Copy buttons are static; source URL button is appended dynamically in RecipeModal.js -->
|
||||
<div class="recipe-header-actions" id="recipeHeaderActions">
|
||||
<button class="modal-send-btn" id="sendRecipeBtn" title="Send Recipe to ComfyUI">
|
||||
<i class="fas fa-paper-plane"></i> <span>{{ t('recipes.actions.sendRecipe') }}</span>
|
||||
</button>
|
||||
<button class="modal-copy-btn" id="copyRecipeSyntaxBtn" title="{{ t('recipes.actions.copyRecipeSyntax') }}" aria-label="{{ t('recipes.actions.copyRecipeSyntax') }}">
|
||||
<i class="fas fa-copy" aria-hidden="true"></i>
|
||||
</button>
|
||||
<button class="modal-delete-btn" id="deleteRecipeBtn" title="{{ t('recipes.actions.deleteRecipeWithShortcut') }}" aria-label="{{ t('recipes.actions.deleteRecipeWithShortcut') }}">
|
||||
<i class="fas fa-trash" aria-hidden="true"></i>
|
||||
</button>
|
||||
@@ -141,5 +144,8 @@
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Meta footer: file location + recipe ID, populated by RecipeModal.syncMetaFooter() -->
|
||||
<footer class="recipe-meta-footer" id="recipeMetaFooter" hidden></footer>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@@ -0,0 +1,348 @@
|
||||
import { describe, it, beforeEach, afterEach, expect, vi } from 'vitest';
|
||||
|
||||
const {
|
||||
BASE_MODEL_API_MODULE,
|
||||
STATE_MODULE,
|
||||
UI_HELPERS_MODULE,
|
||||
I18N_MODULE,
|
||||
STORAGE_MODULE,
|
||||
API_CONFIG_MODULE,
|
||||
API_FACTORY_MODULE,
|
||||
SIDEBAR_MANAGER_MODULE,
|
||||
} = vi.hoisted(() => ({
|
||||
BASE_MODEL_API_MODULE: new URL('../../../static/js/api/baseModelApi.js', import.meta.url).pathname,
|
||||
STATE_MODULE: new URL('../../../static/js/state/index.js', import.meta.url).pathname,
|
||||
UI_HELPERS_MODULE: new URL('../../../static/js/utils/uiHelpers.js', import.meta.url).pathname,
|
||||
I18N_MODULE: new URL('../../../static/js/utils/i18nHelpers.js', import.meta.url).pathname,
|
||||
STORAGE_MODULE: new URL('../../../static/js/utils/storageHelpers.js', import.meta.url).pathname,
|
||||
API_CONFIG_MODULE: new URL('../../../static/js/api/apiConfig.js', import.meta.url).pathname,
|
||||
API_FACTORY_MODULE: new URL('../../../static/js/api/modelApiFactory.js', import.meta.url).pathname,
|
||||
SIDEBAR_MANAGER_MODULE: new URL('../../../static/js/components/SidebarManager.js', import.meta.url).pathname,
|
||||
}));
|
||||
|
||||
const showToastMock = vi.fn();
|
||||
const showMock = vi.fn();
|
||||
const showCancelButtonMock = vi.fn();
|
||||
const hideMock = vi.fn();
|
||||
const restoreProgressBarMock = vi.fn();
|
||||
const setProgressMock = vi.fn();
|
||||
const setStatusMock = vi.fn();
|
||||
const resetAndReloadMock = vi.fn();
|
||||
|
||||
vi.mock(STATE_MODULE, () => ({
|
||||
state: {
|
||||
loadingManager: {
|
||||
show: showMock,
|
||||
showCancelButton: showCancelButtonMock,
|
||||
hide: hideMock,
|
||||
restoreProgressBar: restoreProgressBarMock,
|
||||
setProgress: setProgressMock,
|
||||
setStatus: setStatusMock,
|
||||
},
|
||||
},
|
||||
getCurrentPageState: vi.fn(() => ({})),
|
||||
}));
|
||||
|
||||
vi.mock(UI_HELPERS_MODULE, () => ({
|
||||
showToast: showToastMock,
|
||||
}));
|
||||
|
||||
vi.mock(I18N_MODULE, () => ({
|
||||
translate: vi.fn((key, params, fallback) => {
|
||||
if (fallback) {
|
||||
return Object.entries(params || {}).reduce(
|
||||
(text, [name, value]) => text.replaceAll(`{${name}}`, value),
|
||||
fallback
|
||||
);
|
||||
}
|
||||
return key;
|
||||
}),
|
||||
}));
|
||||
|
||||
vi.mock(STORAGE_MODULE, () => ({
|
||||
getStorageItem: vi.fn(),
|
||||
getSessionItem: vi.fn(),
|
||||
removeSessionItem: vi.fn(),
|
||||
saveMapToStorage: vi.fn(),
|
||||
}));
|
||||
|
||||
vi.mock(API_CONFIG_MODULE, () => ({
|
||||
getCompleteApiConfig: vi.fn(() => ({
|
||||
endpoints: { scan: '/api/lm/loras/scan' },
|
||||
config: { displayName: 'LoRA', singularName: 'lora' },
|
||||
})),
|
||||
getCurrentModelType: vi.fn(() => 'loras'),
|
||||
isValidModelType: vi.fn(() => true),
|
||||
DOWNLOAD_ENDPOINTS: {},
|
||||
HF_ENDPOINTS: {},
|
||||
WS_ENDPOINTS: { fetchProgress: '/ws/fetch-progress' },
|
||||
}));
|
||||
|
||||
vi.mock(API_FACTORY_MODULE, () => ({
|
||||
resetAndReload: resetAndReloadMock,
|
||||
}));
|
||||
|
||||
vi.mock(SIDEBAR_MANAGER_MODULE, () => ({
|
||||
sidebarManager: { refresh: vi.fn() },
|
||||
}));
|
||||
|
||||
class FakeWebSocket {
|
||||
static instances = [];
|
||||
static failNextConnection = false;
|
||||
|
||||
constructor(url) {
|
||||
this.url = url;
|
||||
this.onopen = null;
|
||||
this.onerror = null;
|
||||
this.onmessage = null;
|
||||
this.close = vi.fn();
|
||||
FakeWebSocket.instances.push(this);
|
||||
const shouldFail = FakeWebSocket.failNextConnection;
|
||||
FakeWebSocket.failNextConnection = false;
|
||||
queueMicrotask(() => {
|
||||
if (shouldFail) {
|
||||
this.onerror?.(new Error('connection refused'));
|
||||
} else {
|
||||
this.onopen?.();
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
emit(data) {
|
||||
this.onmessage?.({ data: JSON.stringify(data) });
|
||||
}
|
||||
}
|
||||
|
||||
async function createClient() {
|
||||
const { BaseModelApiClient } = await import(BASE_MODEL_API_MODULE);
|
||||
class TestClient extends BaseModelApiClient {}
|
||||
return new TestClient('loras');
|
||||
}
|
||||
|
||||
async function flushMicrotasks() {
|
||||
await new Promise((resolve) => setTimeout(resolve, 0));
|
||||
}
|
||||
|
||||
describe('BaseModelApiClient.refreshModels scan progress', () => {
|
||||
beforeEach(() => {
|
||||
showToastMock.mockReset();
|
||||
showMock.mockReset();
|
||||
showCancelButtonMock.mockReset();
|
||||
hideMock.mockReset();
|
||||
restoreProgressBarMock.mockReset();
|
||||
setProgressMock.mockReset();
|
||||
setStatusMock.mockReset();
|
||||
resetAndReloadMock.mockReset();
|
||||
FakeWebSocket.instances = [];
|
||||
FakeWebSocket.failNextConnection = false;
|
||||
vi.stubGlobal('WebSocket', FakeWebSocket);
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
delete global.fetch;
|
||||
vi.unstubAllGlobals();
|
||||
vi.restoreAllMocks();
|
||||
});
|
||||
|
||||
function mockFetchPending() {
|
||||
let resolveFetch;
|
||||
global.fetch = vi.fn(() => new Promise((resolve) => { resolveFetch = resolve; }));
|
||||
return {
|
||||
resolveOk: (payload = { status: 'success' }) =>
|
||||
resolveFetch({ ok: true, json: async () => payload }),
|
||||
};
|
||||
}
|
||||
|
||||
async function startRefresh(client, fullRebuild = false) {
|
||||
const promise = client.refreshModels(fullRebuild);
|
||||
await vi.waitFor(() => {
|
||||
expect(FakeWebSocket.instances.length).toBe(1);
|
||||
});
|
||||
await flushMicrotasks();
|
||||
const socket = FakeWebSocket.instances[0];
|
||||
await vi.waitFor(() => {
|
||||
expect(socket.onmessage).toBeTruthy();
|
||||
});
|
||||
return { promise, socket };
|
||||
}
|
||||
|
||||
it('shows scan progress updates from the WebSocket channel', async () => {
|
||||
const fetchControl = mockFetchPending();
|
||||
const client = await createClient();
|
||||
const { promise, socket } = await startRefresh(client);
|
||||
|
||||
expect(socket.url).toBe(`ws://${window.location.host}/ws/fetch-progress`);
|
||||
|
||||
socket.emit({
|
||||
type: 'scan_progress',
|
||||
status: 'started',
|
||||
stage: 'scan_folders',
|
||||
model_type: 'lora',
|
||||
pageType: 'loras',
|
||||
full_rebuild: false,
|
||||
progress: 0,
|
||||
});
|
||||
socket.emit({
|
||||
type: 'scan_progress',
|
||||
status: 'processing',
|
||||
stage: 'process_models',
|
||||
model_type: 'lora',
|
||||
pageType: 'loras',
|
||||
full_rebuild: false,
|
||||
progress: 50,
|
||||
processed: 5,
|
||||
total: 10,
|
||||
current_name: 'style.safetensors',
|
||||
});
|
||||
|
||||
expect(setProgressMock).toHaveBeenCalledWith(0);
|
||||
expect(setProgressMock).toHaveBeenCalledWith(50);
|
||||
const lastStatus = setStatusMock.mock.calls.at(-1)[0];
|
||||
expect(lastStatus).toContain('(5/10)');
|
||||
expect(lastStatus).toContain('style.safetensors');
|
||||
// First ETA sample only anchors the timer
|
||||
expect(lastStatus).toContain('Estimating time...');
|
||||
|
||||
fetchControl.resolveOk();
|
||||
await promise;
|
||||
|
||||
expect(resetAndReloadMock).toHaveBeenCalledWith(true);
|
||||
expect(showToastMock).toHaveBeenCalledWith(
|
||||
'toast.api.refreshComplete',
|
||||
{ action: 'Refresh' },
|
||||
'success'
|
||||
);
|
||||
expect(socket.close).toHaveBeenCalled();
|
||||
expect(hideMock).toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('ignores messages for other types or other model types', async () => {
|
||||
const fetchControl = mockFetchPending();
|
||||
const client = await createClient();
|
||||
const { promise, socket } = await startRefresh(client);
|
||||
|
||||
socket.emit({
|
||||
type: 'scan_progress',
|
||||
status: 'processing',
|
||||
stage: 'process_models',
|
||||
model_type: 'checkpoint',
|
||||
progress: 33,
|
||||
processed: 1,
|
||||
total: 3,
|
||||
});
|
||||
socket.emit({
|
||||
type: 'example_images_progress',
|
||||
status: 'running',
|
||||
model_type: 'lora',
|
||||
progress: 66,
|
||||
processed: 2,
|
||||
total: 3,
|
||||
});
|
||||
|
||||
expect(setProgressMock).not.toHaveBeenCalled();
|
||||
expect(setStatusMock).not.toHaveBeenCalled();
|
||||
|
||||
fetchControl.resolveOk();
|
||||
await promise;
|
||||
});
|
||||
|
||||
it('falls back to plain loading when the WebSocket connection fails', async () => {
|
||||
FakeWebSocket.failNextConnection = true;
|
||||
global.fetch = vi.fn().mockResolvedValue({
|
||||
ok: true,
|
||||
json: async () => ({ status: 'success' }),
|
||||
});
|
||||
|
||||
const client = await createClient();
|
||||
await client.refreshModels(true);
|
||||
|
||||
expect(global.fetch).toHaveBeenCalled();
|
||||
const [url] = global.fetch.mock.calls[0];
|
||||
expect(url.searchParams.get('full_rebuild')).toBe('true');
|
||||
expect(showMock).toHaveBeenCalledWith('Full rebuild LoRAs...', 0);
|
||||
expect(showToastMock).toHaveBeenCalledWith(
|
||||
'toast.api.refreshComplete',
|
||||
{ action: 'Full rebuild' },
|
||||
'success'
|
||||
);
|
||||
});
|
||||
|
||||
it('computes an ETA with EMA smoothing once enough samples arrive', async () => {
|
||||
const fetchControl = mockFetchPending();
|
||||
let now = 1000;
|
||||
vi.spyOn(Date, 'now').mockImplementation(() => now);
|
||||
|
||||
const client = await createClient();
|
||||
const { promise, socket } = await startRefresh(client);
|
||||
|
||||
const emitProcessing = (processed, total) => socket.emit({
|
||||
type: 'scan_progress',
|
||||
status: 'processing',
|
||||
stage: 'process_models',
|
||||
model_type: 'lora',
|
||||
progress: Math.floor((processed / total) * 100),
|
||||
processed,
|
||||
total,
|
||||
});
|
||||
|
||||
// First sample anchors the timer
|
||||
emitProcessing(1, 10);
|
||||
expect(setStatusMock.mock.calls.at(-1)[0]).toContain('Estimating time...');
|
||||
|
||||
// 100s elapsed for 2 files -> 50s per file -> 400s remaining -> ~7 min
|
||||
now = 101000;
|
||||
emitProcessing(2, 10);
|
||||
expect(setStatusMock.mock.calls.at(-1)[0]).toContain('~7 min remaining');
|
||||
|
||||
// 110s elapsed for 4 files -> EMA = 50000*0.7 + 27500*0.3 = 43250ms/file
|
||||
// remaining 6 files -> 259.5s -> ~4 min
|
||||
now = 111000;
|
||||
emitProcessing(4, 10);
|
||||
expect(setStatusMock.mock.calls.at(-1)[0]).toContain('~4 min remaining');
|
||||
|
||||
fetchControl.resolveOk();
|
||||
await promise;
|
||||
});
|
||||
|
||||
it('shows the cancelled toast when the server reports cancellation', async () => {
|
||||
const fetchControl = mockFetchPending();
|
||||
const client = await createClient();
|
||||
const { promise } = await startRefresh(client);
|
||||
|
||||
fetchControl.resolveOk({ status: 'cancelled' });
|
||||
await promise;
|
||||
|
||||
expect(showToastMock).toHaveBeenCalledWith('toast.api.operationCancelled', {}, 'info');
|
||||
expect(resetAndReloadMock).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
|
||||
describe('createScanEtaTracker / formatScanRemainingTime', () => {
|
||||
it('estimates remaining time from EMA of per-file cost', async () => {
|
||||
const { createScanEtaTracker } = await import(BASE_MODEL_API_MODULE);
|
||||
let now = 0;
|
||||
vi.spyOn(Date, 'now').mockImplementation(() => now);
|
||||
|
||||
const tracker = createScanEtaTracker();
|
||||
expect(tracker.update(1, 10)).toBe('Estimating time...');
|
||||
|
||||
now = 60000; // 60s for 3 files -> 20s/file -> 7 * 20s = 140s -> ~2 min
|
||||
expect(tracker.update(3, 10)).toBe('~2 min remaining');
|
||||
|
||||
now = 61000; // tiny delta keeps EMA near 20s/file
|
||||
expect(tracker.update(4, 10)).toBe('~2 min remaining');
|
||||
|
||||
// Done: no ETA
|
||||
expect(tracker.update(10, 10)).toBeNull();
|
||||
expect(tracker.update(0, 0)).toBeNull();
|
||||
|
||||
vi.restoreAllMocks();
|
||||
});
|
||||
|
||||
it('formats hours and sub-minute remainders', async () => {
|
||||
const { formatScanRemainingTime } = await import(BASE_MODEL_API_MODULE);
|
||||
expect(formatScanRemainingTime(30000)).toBe('Less than a minute remaining');
|
||||
expect(formatScanRemainingTime(5 * 60000)).toBe('~5 min remaining');
|
||||
expect(formatScanRemainingTime(3600000 + 30 * 60000)).toBe('~1 hr 30 min remaining');
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,285 @@
|
||||
import { describe, it, beforeEach, afterEach, expect, vi } from 'vitest';
|
||||
|
||||
const showToastMock = vi.hoisted(() => vi.fn());
|
||||
const loadingManagerMock = vi.hoisted(() => ({
|
||||
show: vi.fn(),
|
||||
hide: vi.fn(),
|
||||
restoreProgressBar: vi.fn(),
|
||||
setProgress: vi.fn(),
|
||||
setStatus: vi.fn(),
|
||||
}));
|
||||
const virtualScrollerMock = vi.hoisted(() => ({
|
||||
refreshWithData: vi.fn(),
|
||||
}));
|
||||
const getCurrentPageStateMock = vi.hoisted(() => vi.fn());
|
||||
const etaUpdateMock = vi.hoisted(() => vi.fn(() => 'ETA soon'));
|
||||
|
||||
vi.mock('../../../static/js/components/RecipeCard.js', () => ({
|
||||
RecipeCard: vi.fn(() => ({ element: document.createElement('div') })),
|
||||
}));
|
||||
|
||||
vi.mock('../../../static/js/state/index.js', () => ({
|
||||
state: {
|
||||
loadingManager: loadingManagerMock,
|
||||
virtualScroller: virtualScrollerMock,
|
||||
},
|
||||
getCurrentPageState: getCurrentPageStateMock,
|
||||
}));
|
||||
|
||||
vi.mock('../../../static/js/utils/uiHelpers.js', () => ({
|
||||
showToast: showToastMock,
|
||||
}));
|
||||
|
||||
vi.mock('../../../static/js/utils/i18nHelpers.js', () => ({
|
||||
translate: vi.fn((key, params, fallback) => {
|
||||
if (fallback) {
|
||||
return Object.entries(params || {}).reduce(
|
||||
(text, [name, value]) => text.replaceAll(`{${name}}`, value),
|
||||
fallback
|
||||
);
|
||||
}
|
||||
return key;
|
||||
}),
|
||||
}));
|
||||
|
||||
vi.mock('../../../static/js/utils/infiniteScroll.js', () => ({
|
||||
captureScrollPosition: vi.fn(),
|
||||
restoreScrollPosition: vi.fn(),
|
||||
}));
|
||||
|
||||
vi.mock('../../../static/js/api/apiConfig.js', () => ({
|
||||
WS_ENDPOINTS: { fetchProgress: '/ws/fetch-progress' },
|
||||
}));
|
||||
|
||||
vi.mock('../../../static/js/utils/scanEtaUtils.js', () => ({
|
||||
createScanEtaTracker: () => ({ update: etaUpdateMock }),
|
||||
}));
|
||||
|
||||
import { refreshRecipes } from '../../../static/js/api/recipeApi.js';
|
||||
|
||||
class FakeWebSocket {
|
||||
static instances = [];
|
||||
static failNextConnection = false;
|
||||
|
||||
constructor(url) {
|
||||
this.url = url;
|
||||
this.onopen = null;
|
||||
this.onerror = null;
|
||||
this.onmessage = null;
|
||||
this.close = vi.fn();
|
||||
FakeWebSocket.instances.push(this);
|
||||
const shouldFail = FakeWebSocket.failNextConnection;
|
||||
FakeWebSocket.failNextConnection = false;
|
||||
queueMicrotask(() => {
|
||||
if (shouldFail) {
|
||||
this.onerror?.(new Error('connection refused'));
|
||||
} else {
|
||||
this.onopen?.();
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
emit(data) {
|
||||
this.onmessage?.({ data: JSON.stringify(data) });
|
||||
}
|
||||
}
|
||||
|
||||
async function flushMicrotasks() {
|
||||
await new Promise((resolve) => setTimeout(resolve, 0));
|
||||
}
|
||||
|
||||
describe('refreshRecipes scan progress', () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
getCurrentPageStateMock.mockReturnValue({
|
||||
pageSize: 50,
|
||||
currentPage: 1,
|
||||
hasMore: true,
|
||||
isLoading: false,
|
||||
sortBy: 'date:desc',
|
||||
showFavoritesOnly: false,
|
||||
activeFolder: null,
|
||||
searchOptions: { recursive: true },
|
||||
customFilter: { active: false },
|
||||
filters: {},
|
||||
});
|
||||
FakeWebSocket.instances = [];
|
||||
FakeWebSocket.failNextConnection = false;
|
||||
vi.stubGlobal('WebSocket', FakeWebSocket);
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
delete global.fetch;
|
||||
vi.unstubAllGlobals();
|
||||
});
|
||||
|
||||
function mockFetchPendingScan() {
|
||||
let resolveScan;
|
||||
global.fetch = vi.fn((input) => {
|
||||
const url = String(input);
|
||||
if (url.includes('/scan')) {
|
||||
return new Promise((resolve) => { resolveScan = resolve; });
|
||||
}
|
||||
// Recipe list reload after the scan completes
|
||||
return Promise.resolve({
|
||||
ok: true,
|
||||
json: async () => ({ items: [], total: 0, total_pages: 0 }),
|
||||
});
|
||||
});
|
||||
return {
|
||||
resolveOk: (payload = { status: 'success' }) =>
|
||||
resolveScan({ ok: true, json: async () => payload }),
|
||||
resolveNotOk: () =>
|
||||
resolveScan({ ok: false, status: 500, statusText: 'Server Error' }),
|
||||
};
|
||||
}
|
||||
|
||||
async function startRefresh(fullRebuild = true) {
|
||||
const promise = refreshRecipes(fullRebuild);
|
||||
await vi.waitFor(() => {
|
||||
expect(FakeWebSocket.instances.length).toBe(1);
|
||||
});
|
||||
await flushMicrotasks();
|
||||
const socket = FakeWebSocket.instances[0];
|
||||
await vi.waitFor(() => {
|
||||
expect(socket.onmessage).toBeTruthy();
|
||||
});
|
||||
return { promise, socket };
|
||||
}
|
||||
|
||||
it('shows scan progress updates from the WebSocket channel', async () => {
|
||||
const fetchControl = mockFetchPendingScan();
|
||||
const { promise, socket } = await startRefresh();
|
||||
|
||||
expect(socket.url).toBe(`ws://${window.location.host}/ws/fetch-progress`);
|
||||
|
||||
socket.emit({
|
||||
type: 'scan_progress',
|
||||
status: 'started',
|
||||
stage: 'scan_folders',
|
||||
model_type: 'recipe',
|
||||
pageType: 'recipes',
|
||||
full_rebuild: true,
|
||||
progress: 0,
|
||||
});
|
||||
socket.emit({
|
||||
type: 'scan_progress',
|
||||
status: 'processing',
|
||||
stage: 'process_models',
|
||||
model_type: 'recipe',
|
||||
pageType: 'recipes',
|
||||
full_rebuild: true,
|
||||
progress: 50,
|
||||
processed: 5,
|
||||
total: 10,
|
||||
current_name: 'style.recipe.json',
|
||||
});
|
||||
|
||||
expect(loadingManagerMock.setProgress).toHaveBeenCalledWith(0);
|
||||
expect(loadingManagerMock.setProgress).toHaveBeenCalledWith(50);
|
||||
const lastStatus = loadingManagerMock.setStatus.mock.calls.at(-1)[0];
|
||||
expect(lastStatus).toContain('(5/10)');
|
||||
expect(lastStatus).toContain('style.recipe.json');
|
||||
expect(lastStatus).toContain('ETA soon');
|
||||
expect(etaUpdateMock).toHaveBeenCalledWith(5, 10);
|
||||
|
||||
fetchControl.resolveOk();
|
||||
await promise;
|
||||
|
||||
expect(showToastMock).toHaveBeenCalledWith(
|
||||
'toast.api.refreshComplete',
|
||||
{ action: 'Full rebuild' },
|
||||
'success'
|
||||
);
|
||||
expect(socket.close).toHaveBeenCalled();
|
||||
expect(loadingManagerMock.hide).toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('ignores messages for other types or other model types', async () => {
|
||||
const fetchControl = mockFetchPendingScan();
|
||||
const { promise, socket } = await startRefresh();
|
||||
|
||||
socket.emit({
|
||||
type: 'scan_progress',
|
||||
status: 'processing',
|
||||
stage: 'process_models',
|
||||
model_type: 'lora',
|
||||
progress: 33,
|
||||
processed: 1,
|
||||
total: 3,
|
||||
});
|
||||
socket.emit({
|
||||
type: 'example_images_progress',
|
||||
status: 'running',
|
||||
model_type: 'recipe',
|
||||
progress: 66,
|
||||
processed: 2,
|
||||
total: 3,
|
||||
});
|
||||
|
||||
expect(loadingManagerMock.setProgress).not.toHaveBeenCalled();
|
||||
expect(loadingManagerMock.setStatus).not.toHaveBeenCalled();
|
||||
|
||||
fetchControl.resolveOk();
|
||||
await promise;
|
||||
});
|
||||
|
||||
it('falls back to plain loading when the WebSocket connection fails', async () => {
|
||||
FakeWebSocket.failNextConnection = true;
|
||||
global.fetch = vi.fn((input) => {
|
||||
const url = String(input);
|
||||
if (url.includes('/scan')) {
|
||||
return Promise.resolve({
|
||||
ok: true,
|
||||
json: async () => ({ status: 'success' }),
|
||||
});
|
||||
}
|
||||
return Promise.resolve({
|
||||
ok: true,
|
||||
json: async () => ({ items: [], total: 0, total_pages: 0 }),
|
||||
});
|
||||
});
|
||||
|
||||
await refreshRecipes(false);
|
||||
|
||||
expect(global.fetch).toHaveBeenCalled();
|
||||
const [url] = global.fetch.mock.calls[0];
|
||||
expect(url.searchParams.get('full_rebuild')).toBe('false');
|
||||
expect(loadingManagerMock.show).toHaveBeenCalledWith('Refreshing Recipes...', 0);
|
||||
expect(showToastMock).toHaveBeenCalledWith(
|
||||
'toast.api.refreshComplete',
|
||||
{ action: 'Refresh' },
|
||||
'success'
|
||||
);
|
||||
});
|
||||
|
||||
it('shows the cancelled toast when the server reports cancellation', async () => {
|
||||
const fetchControl = mockFetchPendingScan();
|
||||
const { promise } = await startRefresh();
|
||||
|
||||
fetchControl.resolveOk({ status: 'cancelled' });
|
||||
await promise;
|
||||
|
||||
expect(showToastMock).toHaveBeenCalledWith('toast.api.operationCancelled', {}, 'info');
|
||||
expect(showToastMock).not.toHaveBeenCalledWith(
|
||||
'toast.api.refreshComplete',
|
||||
expect.anything(),
|
||||
expect.anything()
|
||||
);
|
||||
});
|
||||
|
||||
it('reports refresh failures through the error toast', async () => {
|
||||
const fetchControl = mockFetchPendingScan();
|
||||
const { promise } = await startRefresh();
|
||||
|
||||
fetchControl.resolveNotOk();
|
||||
await promise;
|
||||
|
||||
expect(showToastMock).toHaveBeenCalledWith(
|
||||
'toast.api.refreshFailed',
|
||||
{ action: 'rebuild', type: 'recipe' },
|
||||
'error'
|
||||
);
|
||||
expect(loadingManagerMock.hide).toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,378 @@
|
||||
import { describe, it, beforeEach, afterEach, expect, vi } from 'vitest';
|
||||
|
||||
const {
|
||||
API_MODULE,
|
||||
APP_MODULE,
|
||||
CARET_HELPER_MODULE,
|
||||
PREVIEW_COMPONENT_MODULE,
|
||||
AUTOCOMPLETE_MODULE,
|
||||
} = vi.hoisted(() => ({
|
||||
API_MODULE: new URL('../../../scripts/api.js', import.meta.url).pathname,
|
||||
APP_MODULE: new URL('../../../scripts/app.js', import.meta.url).pathname,
|
||||
CARET_HELPER_MODULE: new URL('../../../web/comfyui/textarea_caret_helper.js', import.meta.url).pathname,
|
||||
PREVIEW_COMPONENT_MODULE: new URL('../../../web/comfyui/preview_tooltip.js', import.meta.url).pathname,
|
||||
AUTOCOMPLETE_MODULE: new URL('../../../web/comfyui/autocomplete.js', import.meta.url).pathname,
|
||||
}));
|
||||
|
||||
const fetchApiMock = vi.fn();
|
||||
const settingGetMock = vi.fn();
|
||||
const caretHelperInstance = {
|
||||
getBeforeCursor: vi.fn(() => ''),
|
||||
getCursorOffset: vi.fn(() => ({ left: 0, top: 0 })),
|
||||
};
|
||||
|
||||
vi.mock(API_MODULE, () => ({
|
||||
api: {
|
||||
fetchApi: fetchApiMock,
|
||||
},
|
||||
}));
|
||||
|
||||
vi.mock(APP_MODULE, () => ({
|
||||
app: {
|
||||
canvas: {
|
||||
ds: { scale: 1 },
|
||||
},
|
||||
extensionManager: {
|
||||
setting: {
|
||||
get: settingGetMock,
|
||||
set: vi.fn(),
|
||||
},
|
||||
},
|
||||
registerExtension: vi.fn(),
|
||||
},
|
||||
}));
|
||||
|
||||
vi.mock(CARET_HELPER_MODULE, () => ({
|
||||
TextAreaCaretHelper: vi.fn(() => caretHelperInstance),
|
||||
}));
|
||||
|
||||
vi.mock(PREVIEW_COMPONENT_MODULE, () => ({
|
||||
PreviewTooltip: vi.fn(() => ({ show: vi.fn(), hide: vi.fn(), cleanup: vi.fn() })),
|
||||
}));
|
||||
|
||||
async function createAutoComplete(modelType, activeFiltersEnabled) {
|
||||
settingGetMock.mockImplementation((key) => {
|
||||
if (key === 'loramanager.lora_active_filters_autocomplete') {
|
||||
return activeFiltersEnabled;
|
||||
}
|
||||
if (key === 'loramanager.autocomplete_append_comma') return false;
|
||||
if (key === 'loramanager.autocomplete_auto_format') return false;
|
||||
if (key === 'loramanager.autocomplete_accept_key') return 'both';
|
||||
return undefined;
|
||||
});
|
||||
|
||||
fetchApiMock.mockResolvedValue({
|
||||
json: () => Promise.resolve({ success: true, relative_paths: [] }),
|
||||
});
|
||||
|
||||
const input = document.createElement('textarea');
|
||||
document.body.append(input);
|
||||
|
||||
const { AutoComplete } = await import(AUTOCOMPLETE_MODULE);
|
||||
const autoComplete = new AutoComplete(input, modelType, { debounceDelay: 0, showPreview: false });
|
||||
|
||||
input.value = 'example';
|
||||
input.dispatchEvent(new Event('input', { bubbles: true }));
|
||||
await vi.runAllTimersAsync();
|
||||
await Promise.resolve();
|
||||
|
||||
return autoComplete;
|
||||
}
|
||||
|
||||
describe('AutoComplete active-filters flag', () => {
|
||||
beforeEach(() => {
|
||||
vi.useFakeTimers();
|
||||
document.body.innerHTML = '';
|
||||
document.head.querySelectorAll('style').forEach((styleEl) => styleEl.remove());
|
||||
Element.prototype.scrollIntoView = vi.fn();
|
||||
fetchApiMock.mockReset();
|
||||
settingGetMock.mockReset();
|
||||
caretHelperInstance.getBeforeCursor.mockReset();
|
||||
caretHelperInstance.getCursorOffset.mockReset();
|
||||
caretHelperInstance.getBeforeCursor.mockReturnValue('example');
|
||||
caretHelperInstance.getCursorOffset.mockReturnValue({ left: 0, top: 0 });
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
vi.useRealTimers();
|
||||
});
|
||||
|
||||
it('sends use_active_filters for loras when the setting is enabled', async () => {
|
||||
await createAutoComplete('loras', true);
|
||||
|
||||
expect(fetchApiMock).toHaveBeenCalledWith(
|
||||
'/lm/loras/relative-paths?search=example&limit=100&use_active_filters=true'
|
||||
);
|
||||
});
|
||||
|
||||
it('omits the flag when the setting is disabled', async () => {
|
||||
await createAutoComplete('loras', false);
|
||||
|
||||
expect(fetchApiMock).toHaveBeenCalledWith('/lm/loras/relative-paths?search=example&limit=100');
|
||||
});
|
||||
|
||||
it('omits the flag for non-lora model types even when enabled', async () => {
|
||||
fetchApiMock.mockResolvedValue({
|
||||
json: () => Promise.resolve({ success: true, words: [] }),
|
||||
});
|
||||
await createAutoComplete('prompt', true);
|
||||
|
||||
for (const call of fetchApiMock.mock.calls) {
|
||||
expect(call[0]).not.toContain('use_active_filters');
|
||||
}
|
||||
});
|
||||
|
||||
it('does not read filter state from localStorage anymore', async () => {
|
||||
localStorage.setItem('lora_manager_loras_activeFolder', 'SD_XL');
|
||||
localStorage.setItem('lora_manager_loras_filters', JSON.stringify({ baseModel: ['SDXL 1.0'] }));
|
||||
|
||||
await createAutoComplete('loras', true);
|
||||
|
||||
for (const call of fetchApiMock.mock.calls) {
|
||||
expect(call[0]).not.toContain('folder=');
|
||||
expect(call[0]).not.toContain('base_model=');
|
||||
}
|
||||
});
|
||||
|
||||
const typeLorasSlashCommand = async () => {
|
||||
const input = document.createElement('textarea');
|
||||
input.value = '/';
|
||||
input.selectionStart = 1;
|
||||
document.body.append(input);
|
||||
|
||||
caretHelperInstance.getBeforeCursor.mockReturnValue('/');
|
||||
|
||||
const { AutoComplete } = await import(AUTOCOMPLETE_MODULE);
|
||||
const autoComplete = new AutoComplete(input, 'loras', { showPreview: false, minChars: 1 });
|
||||
|
||||
input.dispatchEvent(new Event('input', { bubbles: true }));
|
||||
return autoComplete;
|
||||
};
|
||||
|
||||
it('shows the active-filters state below the loras slash command list', async () => {
|
||||
await typeLorasSlashCommand();
|
||||
|
||||
const footer = document.querySelector('.lm-autocomplete-command-footer');
|
||||
expect(footer).not.toBeNull();
|
||||
expect(footer.textContent).toContain('Active Filters Search: OFF');
|
||||
expect(footer.textContent).toContain('/activefilters to enable');
|
||||
});
|
||||
|
||||
it('shows how to disable active-filters search in the footer when it is on', async () => {
|
||||
settingGetMock.mockImplementation((key) => {
|
||||
if (key === 'loramanager.lora_active_filters_autocomplete') {
|
||||
return true;
|
||||
}
|
||||
return undefined;
|
||||
});
|
||||
|
||||
await typeLorasSlashCommand();
|
||||
|
||||
const footer = document.querySelector('.lm-autocomplete-command-footer');
|
||||
expect(footer).not.toBeNull();
|
||||
expect(footer.textContent).toContain('Active Filters Search: ON');
|
||||
expect(footer.textContent).toContain('/noactivefilters to disable');
|
||||
});
|
||||
|
||||
it('shows a dismissible first-run hint on loras suggestions and remembers dismissal', async () => {
|
||||
fetchApiMock.mockResolvedValue({
|
||||
json: () => Promise.resolve({
|
||||
success: true,
|
||||
relative_paths: ['models/example.safetensors'],
|
||||
}),
|
||||
});
|
||||
|
||||
const triggerSearch = async () => {
|
||||
const input = document.createElement('textarea');
|
||||
input.value = 'example';
|
||||
input.selectionStart = 7;
|
||||
document.body.append(input);
|
||||
|
||||
caretHelperInstance.getBeforeCursor.mockReturnValue('example');
|
||||
|
||||
const { AutoComplete } = await import(AUTOCOMPLETE_MODULE);
|
||||
const autoComplete = new AutoComplete(input, 'loras', {
|
||||
debounceDelay: 0,
|
||||
showPreview: false,
|
||||
minChars: 1,
|
||||
});
|
||||
|
||||
input.dispatchEvent(new Event('input', { bubbles: true }));
|
||||
await vi.runOnlyPendingTimersAsync();
|
||||
await vi.runOnlyPendingTimersAsync();
|
||||
await Promise.resolve();
|
||||
return autoComplete;
|
||||
};
|
||||
|
||||
const autoComplete = await triggerSearch();
|
||||
const hint = autoComplete.dropdown.querySelector('.lm-autocomplete-first-run-hint');
|
||||
expect(hint).not.toBeNull();
|
||||
expect(hint.textContent).toContain('/activefilters');
|
||||
|
||||
hint.querySelector('button').click();
|
||||
expect(autoComplete.dropdown.querySelector('.lm-autocomplete-first-run-hint')).toBeNull();
|
||||
expect(localStorage.getItem('lm:activefilters-tip-dismissed')).toBe('1');
|
||||
// A fresh instance no longer shows the hint once dismissed
|
||||
const autoComplete2 = await triggerSearch();
|
||||
expect(autoComplete2.dropdown.querySelector('.lm-autocomplete-first-run-hint')).toBeNull();
|
||||
});
|
||||
|
||||
it('does not show the loras first-run hint when active-filters search is already on', async () => {
|
||||
settingGetMock.mockImplementation((key) => {
|
||||
if (key === 'loramanager.lora_active_filters_autocomplete') {
|
||||
return true;
|
||||
}
|
||||
return undefined;
|
||||
});
|
||||
|
||||
fetchApiMock.mockResolvedValue({
|
||||
json: () => Promise.resolve({
|
||||
success: true,
|
||||
relative_paths: ['models/example.safetensors'],
|
||||
}),
|
||||
});
|
||||
|
||||
const input = document.createElement('textarea');
|
||||
input.value = 'example';
|
||||
input.selectionStart = 7;
|
||||
document.body.append(input);
|
||||
|
||||
caretHelperInstance.getBeforeCursor.mockReturnValue('example');
|
||||
|
||||
const { AutoComplete } = await import(AUTOCOMPLETE_MODULE);
|
||||
const autoComplete = new AutoComplete(input, 'loras', {
|
||||
debounceDelay: 0,
|
||||
showPreview: false,
|
||||
minChars: 1,
|
||||
});
|
||||
|
||||
input.dispatchEvent(new Event('input', { bubbles: true }));
|
||||
await vi.runOnlyPendingTimersAsync();
|
||||
await vi.runOnlyPendingTimersAsync();
|
||||
await Promise.resolve();
|
||||
|
||||
expect(autoComplete.dropdown.querySelector('.lm-autocomplete-first-run-hint')).toBeNull();
|
||||
});
|
||||
|
||||
it('broadcasts a setting-toggled window event when /activefilters is accepted', async () => {
|
||||
const events = [];
|
||||
const listener = (event) => events.push(event.detail);
|
||||
window.addEventListener('lora-manager:setting-toggled', listener);
|
||||
try {
|
||||
const input = document.createElement('textarea');
|
||||
input.value = '/activefilters';
|
||||
input.selectionStart = input.value.length;
|
||||
input.focus = vi.fn();
|
||||
input.setSelectionRange = vi.fn();
|
||||
document.body.append(input);
|
||||
|
||||
caretHelperInstance.getBeforeCursor.mockReturnValue('/activefilters');
|
||||
|
||||
const { AutoComplete } = await import(AUTOCOMPLETE_MODULE);
|
||||
const autoComplete = new AutoComplete(input, 'loras', { showPreview: false, minChars: 1 });
|
||||
input.dispatchEvent(new Event('input', { bubbles: true }));
|
||||
|
||||
// The command token is cleared after acceptance; simulate the caret
|
||||
// helper seeing the cleared input so the synthetic input event does
|
||||
// not re-trigger command parsing (same pattern as behavior tests).
|
||||
caretHelperInstance.getBeforeCursor.mockReturnValue('');
|
||||
await Promise.resolve();
|
||||
await Promise.resolve();
|
||||
expect(events).toContainEqual({
|
||||
settingId: 'loramanager.lora_active_filters_autocomplete',
|
||||
value: true,
|
||||
});
|
||||
} finally {
|
||||
window.removeEventListener('lora-manager:setting-toggled', listener);
|
||||
}
|
||||
});
|
||||
|
||||
it('removes a stale first-run hint when the toggle is switched on while the dropdown stays open', async () => {
|
||||
localStorage.removeItem('lm:activefilters-tip-dismissed');
|
||||
let enabled = false;
|
||||
settingGetMock.mockImplementation((key) => {
|
||||
if (key === 'loramanager.lora_active_filters_autocomplete') return enabled;
|
||||
if (key === 'loramanager.autocomplete_append_comma') return false;
|
||||
if (key === 'loramanager.autocomplete_auto_format') return false;
|
||||
if (key === 'loramanager.autocomplete_accept_key') return 'both';
|
||||
return undefined;
|
||||
});
|
||||
|
||||
fetchApiMock.mockResolvedValue({
|
||||
json: () => Promise.resolve({ success: true, relative_paths: ['models/example.safetensors'] }),
|
||||
});
|
||||
|
||||
const input = document.createElement('textarea');
|
||||
input.value = 'example';
|
||||
input.selectionStart = 7;
|
||||
document.body.append(input);
|
||||
caretHelperInstance.getBeforeCursor.mockReturnValue('example');
|
||||
|
||||
const { AutoComplete } = await import(AUTOCOMPLETE_MODULE);
|
||||
const autoComplete = new AutoComplete(input, 'loras', {
|
||||
debounceDelay: 0,
|
||||
showPreview: false,
|
||||
minChars: 1,
|
||||
});
|
||||
|
||||
const triggerShow = async () => {
|
||||
input.dispatchEvent(new Event('input', { bubbles: true }));
|
||||
await vi.runOnlyPendingTimersAsync();
|
||||
await vi.runOnlyPendingTimersAsync();
|
||||
await Promise.resolve();
|
||||
return autoComplete.dropdown.querySelector('.lm-autocomplete-first-run-hint');
|
||||
};
|
||||
|
||||
// OFF → the enable hint is shown in the suggestions dropdown.
|
||||
expect(await triggerShow()).not.toBeNull();
|
||||
|
||||
// The node's filter chip toggles the setting ON while the dropdown is
|
||||
// still open (ComfyUI can keep focus in the textarea, so no blur/hide
|
||||
// fires). settings.js broadcasts the setting-toggled event.
|
||||
enabled = true;
|
||||
window.dispatchEvent(new CustomEvent('lora-manager:setting-toggled', {
|
||||
detail: { settingId: 'loramanager.lora_active_filters_autocomplete', value: true },
|
||||
}));
|
||||
|
||||
// The stale OFF hint must be gone even though the dropdown never closed.
|
||||
expect(autoComplete.dropdown.querySelector('.lm-autocomplete-first-run-hint')).toBeNull();
|
||||
|
||||
// Further typing while ON must not resurrect the enable hint.
|
||||
expect(await triggerShow()).toBeNull();
|
||||
});
|
||||
|
||||
it('updates the command-list footer when the toggle changes while the command list is open', async () => {
|
||||
let enabled = false;
|
||||
settingGetMock.mockImplementation((key) => {
|
||||
if (key === 'loramanager.lora_active_filters_autocomplete') return enabled;
|
||||
return undefined;
|
||||
});
|
||||
|
||||
const input = document.createElement('textarea');
|
||||
input.value = '/';
|
||||
input.selectionStart = 1;
|
||||
document.body.append(input);
|
||||
caretHelperInstance.getBeforeCursor.mockReturnValue('/');
|
||||
|
||||
const { AutoComplete } = await import(AUTOCOMPLETE_MODULE);
|
||||
const autoComplete = new AutoComplete(input, 'loras', { showPreview: false, minChars: 1 });
|
||||
input.dispatchEvent(new Event('input', { bubbles: true }));
|
||||
await vi.runOnlyPendingTimersAsync();
|
||||
await Promise.resolve();
|
||||
|
||||
const footer = () => autoComplete.dropdown.querySelector('.lm-autocomplete-command-footer');
|
||||
expect(footer()).not.toBeNull();
|
||||
expect(footer().textContent).toContain('Active Filters Search: OFF');
|
||||
expect(footer().textContent).toContain('/activefilters to enable');
|
||||
|
||||
enabled = true;
|
||||
window.dispatchEvent(new CustomEvent('lora-manager:setting-toggled', {
|
||||
detail: { settingId: 'loramanager.lora_active_filters_autocomplete', value: true },
|
||||
}));
|
||||
|
||||
expect(footer()).not.toBeNull();
|
||||
expect(footer().textContent).toContain('Active Filters Search: ON');
|
||||
expect(footer().textContent).toContain('/noactivefilters to disable');
|
||||
});
|
||||
|
||||
});
|
||||
@@ -1789,7 +1789,7 @@ describe('AutoComplete widget interactions', () => {
|
||||
expect(settingSetMock).toHaveBeenCalledWith('loramanager.lora_active_filters_autocomplete', true);
|
||||
});
|
||||
|
||||
it('appends active filter params to loras autocomplete requests when enabled', async () => {
|
||||
it('sends only the use_active_filters flag when enabled (filters resolved server-side)', async () => {
|
||||
vi.useFakeTimers();
|
||||
|
||||
settingGetMock.mockImplementation((key) => {
|
||||
@@ -1799,12 +1799,11 @@ describe('AutoComplete widget interactions', () => {
|
||||
return undefined;
|
||||
});
|
||||
|
||||
// Stored manager-page filters must NOT leak into the request URL; the
|
||||
// backend injects them from its server-side store.
|
||||
localStorage.setItem('lora_manager_loras_filters', JSON.stringify({
|
||||
baseModel: ['SD 1.5'],
|
||||
tags: { anime: 'include', nsfw: 'exclude', __no_tags__: 'exclude' },
|
||||
autoTags: { I2V: 'include' },
|
||||
modelTypes: ['standard'],
|
||||
tagLogic: 'all',
|
||||
tags: { anime: 'include', nsfw: 'exclude' },
|
||||
license: { noCredit: 'include', allowSelling: 'exclude' },
|
||||
}));
|
||||
localStorage.setItem('lora_manager_loras_activeFolder', 'MyLoras');
|
||||
@@ -1830,19 +1829,7 @@ describe('AutoComplete widget interactions', () => {
|
||||
await Promise.resolve();
|
||||
|
||||
const calledUrl = fetchApiMock.mock.calls[0][0];
|
||||
expect(calledUrl).toContain('/lm/loras/relative-paths?search=example&limit=100');
|
||||
expect(calledUrl).toContain('folder=MyLoras');
|
||||
expect(calledUrl).toContain('recursive=true');
|
||||
expect(calledUrl).toContain('tag_include=anime');
|
||||
expect(calledUrl).toContain('tag_exclude=nsfw');
|
||||
expect(calledUrl).toContain('tag_exclude=__no_tags__');
|
||||
expect(calledUrl).toContain('auto_tag_include=I2V');
|
||||
expect(calledUrl).toContain('tag_logic=all');
|
||||
expect(calledUrl).toContain('credit_required=false');
|
||||
expect(calledUrl).toContain('allow_selling_generated_content=false');
|
||||
const parsed = new URL(calledUrl, 'https://example.com');
|
||||
expect(parsed.searchParams.get('base_model')).toBe('SD 1.5');
|
||||
expect(parsed.searchParams.get('model_type')).toBe('standard');
|
||||
expect(calledUrl).toBe('/lm/loras/relative-paths?search=example&limit=100&use_active_filters=true');
|
||||
});
|
||||
|
||||
it('keeps the default loras autocomplete URL when active-filters mode is off', async () => {
|
||||
@@ -1870,10 +1857,12 @@ describe('AutoComplete widget interactions', () => {
|
||||
expect(fetchApiMock).toHaveBeenCalledWith('/lm/loras/relative-paths?search=example&limit=100');
|
||||
});
|
||||
|
||||
it('sends the filter-pipeline signal even when no filters are stored', async () => {
|
||||
it('sends the filter-pipeline flag even when no filters are stored', async () => {
|
||||
// Regression: with filter mode on but no folder/filters stored, the request
|
||||
// carried no params, so the backend skipped the filter pipeline and global
|
||||
// settings like show_only_sfw diverged from the list endpoint.
|
||||
// carried no signal, so the backend skipped the filter pipeline and global
|
||||
// settings like show_only_sfw diverged from the list endpoint. The flag
|
||||
// makes the backend run the pipeline (injecting nothing when its store
|
||||
// is empty).
|
||||
vi.useFakeTimers();
|
||||
|
||||
settingGetMock.mockImplementation((key) => {
|
||||
@@ -1907,10 +1896,13 @@ describe('AutoComplete widget interactions', () => {
|
||||
await Promise.resolve();
|
||||
|
||||
const calledUrl = fetchApiMock.mock.calls[0][0];
|
||||
expect(calledUrl).toContain('recursive=true');
|
||||
expect(calledUrl).toContain('use_active_filters=true');
|
||||
});
|
||||
|
||||
it('omits folder param when active folder is root and recursion is enabled', async () => {
|
||||
it('leaves folder params to the backend when active folder is root with recursion enabled', async () => {
|
||||
// The root-folder/recursion semantics now live server-side (see
|
||||
// active_filters_store.active_filters_to_query_kwargs); the client only
|
||||
// sends the flag.
|
||||
vi.useFakeTimers();
|
||||
|
||||
settingGetMock.mockImplementation((key) => {
|
||||
@@ -1948,10 +1940,12 @@ describe('AutoComplete widget interactions', () => {
|
||||
|
||||
const calledUrl = fetchApiMock.mock.calls[0][0];
|
||||
expect(calledUrl).not.toContain('folder=');
|
||||
expect(calledUrl).toContain('recursive=true');
|
||||
expect(calledUrl).toContain('use_active_filters=true');
|
||||
});
|
||||
|
||||
it('sends an empty folder param for root with recursion disabled, mirroring the page list', async () => {
|
||||
it('leaves the root+non-recursive folder mapping to the backend', async () => {
|
||||
// Root with recursion disabled maps to folder='' server-side (mirroring
|
||||
// the page list); the client no longer encodes this in the URL.
|
||||
vi.useFakeTimers();
|
||||
|
||||
settingGetMock.mockImplementation((key) => {
|
||||
@@ -1988,15 +1982,14 @@ describe('AutoComplete widget interactions', () => {
|
||||
await Promise.resolve();
|
||||
|
||||
const calledUrl = fetchApiMock.mock.calls[0][0];
|
||||
expect(calledUrl).toContain('folder=');
|
||||
expect(calledUrl).toContain('recursive=false');
|
||||
const parsed = new URL(calledUrl, 'https://example.com');
|
||||
expect(parsed.searchParams.get('folder')).toBe('');
|
||||
expect(calledUrl).not.toContain('folder=');
|
||||
expect(calledUrl).toContain('use_active_filters=true');
|
||||
});
|
||||
|
||||
it('applies the active folder even when no filter-panel filters are set', async () => {
|
||||
it('sends the flag even when only a folder is stored (no filter-panel filters)', async () => {
|
||||
// Regression: folder was skipped when lora_manager_loras_filters was
|
||||
// missing because the filters key gate returned early.
|
||||
// missing because the filters key gate returned early. The flag is now
|
||||
// unconditional, and the backend injects the folder from its store.
|
||||
vi.useFakeTimers();
|
||||
|
||||
settingGetMock.mockImplementation((key) => {
|
||||
@@ -2029,8 +2022,8 @@ describe('AutoComplete widget interactions', () => {
|
||||
await Promise.resolve();
|
||||
|
||||
const calledUrl = fetchApiMock.mock.calls[0][0];
|
||||
expect(calledUrl).toContain('folder=Flux.1+D%2Fstyle');
|
||||
expect(calledUrl).toContain('recursive=true');
|
||||
expect(calledUrl).toContain('use_active_filters=true');
|
||||
expect(calledUrl).not.toContain('folder=');
|
||||
});
|
||||
|
||||
describe('discoverability hints', () => {
|
||||
|
||||
@@ -0,0 +1,234 @@
|
||||
import { describe, it, expect, vi } from 'vitest';
|
||||
|
||||
const {
|
||||
API_MODULE,
|
||||
APP_MODULE,
|
||||
CARET_HELPER_MODULE,
|
||||
PREVIEW_COMPONENT_MODULE,
|
||||
AUTOCOMPLETE_MODULE,
|
||||
} = vi.hoisted(() => ({
|
||||
API_MODULE: new URL('../../../scripts/api.js', import.meta.url).pathname,
|
||||
APP_MODULE: new URL('../../../scripts/app.js', import.meta.url).pathname,
|
||||
CARET_HELPER_MODULE: new URL('../../../web/comfyui/textarea_caret_helper.js', import.meta.url).pathname,
|
||||
PREVIEW_COMPONENT_MODULE: new URL('../../../web/comfyui/preview_tooltip.js', import.meta.url).pathname,
|
||||
AUTOCOMPLETE_MODULE: new URL('../../../web/comfyui/autocomplete.js', import.meta.url).pathname,
|
||||
}));
|
||||
|
||||
vi.mock(API_MODULE, () => ({
|
||||
api: { fetchApi: vi.fn() },
|
||||
}));
|
||||
|
||||
vi.mock(APP_MODULE, () => ({
|
||||
app: {
|
||||
canvas: { ds: { scale: 1 } },
|
||||
extensionManager: {
|
||||
setting: { get: vi.fn(), set: vi.fn() },
|
||||
},
|
||||
registerExtension: vi.fn(),
|
||||
},
|
||||
}));
|
||||
|
||||
vi.mock(CARET_HELPER_MODULE, () => ({
|
||||
TextAreaCaretHelper: vi.fn(() => ({
|
||||
getBeforeCursor: vi.fn(() => ''),
|
||||
getCursorOffset: vi.fn(() => ({ left: 0, top: 0 })),
|
||||
})),
|
||||
}));
|
||||
|
||||
vi.mock(PREVIEW_COMPONENT_MODULE, () => ({
|
||||
PreviewTooltip: vi.fn(() => ({ show: vi.fn(), hide: vi.fn(), cleanup: vi.fn() })),
|
||||
}));
|
||||
|
||||
const METADATA_NAME = '__lm_autocomplete_meta_text';
|
||||
|
||||
function makeMetadataValue() {
|
||||
return {
|
||||
version: 1,
|
||||
textWidgetName: 'text',
|
||||
lastAccepted: {
|
||||
start: 0,
|
||||
end: 6,
|
||||
insertedText: '1girl ',
|
||||
textSnapshot: 'old prompt text, 1girl ',
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
describe('stripAutocompleteLastAccepted', () => {
|
||||
let stripAutocompleteLastAccepted;
|
||||
|
||||
beforeAll(async () => {
|
||||
const module = await import(AUTOCOMPLETE_MODULE);
|
||||
stripAutocompleteLastAccepted = module.stripAutocompleteLastAccepted;
|
||||
});
|
||||
|
||||
it('removes lastAccepted while keeping the metadata base fields', () => {
|
||||
const value = makeMetadataValue();
|
||||
const stripped = stripAutocompleteLastAccepted(value);
|
||||
|
||||
expect(stripped).toEqual({ version: 1, textWidgetName: 'text' });
|
||||
expect('lastAccepted' in stripped).toBe(false);
|
||||
// Original value must not be mutated
|
||||
expect(value.lastAccepted).toBeDefined();
|
||||
});
|
||||
|
||||
it('returns values without lastAccepted as-is (same reference)', () => {
|
||||
const value = { version: 1, textWidgetName: 'text' };
|
||||
expect(stripAutocompleteLastAccepted(value)).toBe(value);
|
||||
});
|
||||
|
||||
it('returns non-object values as-is', () => {
|
||||
expect(stripAutocompleteLastAccepted(null)).toBe(null);
|
||||
expect(stripAutocompleteLastAccepted(undefined)).toBe(undefined);
|
||||
expect(stripAutocompleteLastAccepted('text')).toBe('text');
|
||||
expect(stripAutocompleteLastAccepted([1, 2])).toEqual([1, 2]);
|
||||
});
|
||||
});
|
||||
|
||||
describe('stripAutocompleteMetadataFromPromptResult', () => {
|
||||
let stripResult;
|
||||
|
||||
beforeAll(async () => {
|
||||
const module = await import(AUTOCOMPLETE_MODULE);
|
||||
stripResult = module.stripAutocompleteMetadataFromPromptResult;
|
||||
});
|
||||
|
||||
function makeWorkflowNode() {
|
||||
const metadataValue = makeMetadataValue();
|
||||
return {
|
||||
properties: { __lm_widget_ids: ['text', METADATA_NAME] },
|
||||
widgets_values: ['current text', metadataValue],
|
||||
widgets_values_named: {
|
||||
text: 'current text',
|
||||
[METADATA_NAME]: metadataValue,
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
it('strips lastAccepted from workflow widgets_values using __lm_widget_ids alignment', () => {
|
||||
const result = {
|
||||
workflow: { nodes: [makeWorkflowNode()] },
|
||||
output: {},
|
||||
};
|
||||
|
||||
const returned = stripResult(result);
|
||||
|
||||
expect(returned).toBe(result);
|
||||
expect(result.workflow.nodes[0].widgets_values[1])
|
||||
.toEqual({ version: 1, textWidgetName: 'text' });
|
||||
});
|
||||
|
||||
it('strips lastAccepted from widgets_values_named and leaves other widgets untouched', () => {
|
||||
const result = {
|
||||
workflow: { nodes: [makeWorkflowNode()] },
|
||||
output: {},
|
||||
};
|
||||
|
||||
stripResult(result);
|
||||
|
||||
const node = result.workflow.nodes[0];
|
||||
expect(node.widgets_values_named[METADATA_NAME])
|
||||
.toEqual({ version: 1, textWidgetName: 'text' });
|
||||
expect(node.widgets_values_named.text).toBe('current text');
|
||||
expect(node.widgets_values[0]).toBe('current text');
|
||||
});
|
||||
|
||||
it('handles null entries in widgets_values (bypass compatibility padding)', () => {
|
||||
const node = makeWorkflowNode();
|
||||
node.properties.__lm_widget_ids = ['text', 'seed', METADATA_NAME];
|
||||
node.widgets_values = ['current text', null, makeMetadataValue()];
|
||||
const result = { workflow: { nodes: [node] }, output: {} };
|
||||
|
||||
stripResult(result);
|
||||
|
||||
expect(result.workflow.nodes[0].widgets_values[1]).toBe(null);
|
||||
expect(result.workflow.nodes[0].widgets_values[2])
|
||||
.toEqual({ version: 1, textWidgetName: 'text' });
|
||||
});
|
||||
|
||||
it('still strips widgets_values_named when __lm_widget_ids is missing (legacy files)', () => {
|
||||
const node = makeWorkflowNode();
|
||||
delete node.properties;
|
||||
const arrayValue = node.widgets_values[1];
|
||||
const result = { workflow: { nodes: [node] }, output: {} };
|
||||
|
||||
stripResult(result);
|
||||
|
||||
// Array entries cannot be located without widget ids — left untouched
|
||||
expect(result.workflow.nodes[0].widgets_values[1]).toBe(arrayValue);
|
||||
expect(result.workflow.nodes[0].widgets_values_named[METADATA_NAME])
|
||||
.toEqual({ version: 1, textWidgetName: 'text' });
|
||||
});
|
||||
|
||||
it('strips lastAccepted from output (API prompt) inputs', () => {
|
||||
const result = {
|
||||
workflow: { nodes: [] },
|
||||
output: {
|
||||
'7': {
|
||||
class_type: 'Prompt (LoraManager)',
|
||||
inputs: {
|
||||
text: 'current text',
|
||||
[METADATA_NAME]: makeMetadataValue(),
|
||||
},
|
||||
},
|
||||
},
|
||||
};
|
||||
|
||||
stripResult(result);
|
||||
|
||||
const inputs = result.output['7'].inputs;
|
||||
expect(inputs[METADATA_NAME]).toEqual({ version: 1, textWidgetName: 'text' });
|
||||
expect(inputs.text).toBe('current text');
|
||||
});
|
||||
|
||||
it('strips lastAccepted inside subgraph definitions', () => {
|
||||
const result = {
|
||||
workflow: {
|
||||
nodes: [],
|
||||
definitions: {
|
||||
subgraphs: [{ nodes: [makeWorkflowNode()] }],
|
||||
},
|
||||
},
|
||||
output: {},
|
||||
};
|
||||
|
||||
stripResult(result);
|
||||
|
||||
const subgraphNode = result.workflow.definitions.subgraphs[0].nodes[0];
|
||||
expect(subgraphNode.widgets_values_named[METADATA_NAME])
|
||||
.toEqual({ version: 1, textWidgetName: 'text' });
|
||||
});
|
||||
|
||||
it('leaves results without lastAccepted unchanged', () => {
|
||||
const metadataValue = { version: 1, textWidgetName: 'text' };
|
||||
const result = {
|
||||
workflow: {
|
||||
nodes: [{
|
||||
properties: { __lm_widget_ids: ['text', METADATA_NAME] },
|
||||
widgets_values: ['abc', metadataValue],
|
||||
widgets_values_named: { text: 'abc', [METADATA_NAME]: metadataValue },
|
||||
}],
|
||||
},
|
||||
output: {
|
||||
'1': { inputs: { text: 'abc', [METADATA_NAME]: metadataValue } },
|
||||
},
|
||||
};
|
||||
|
||||
stripResult(result);
|
||||
|
||||
expect(result.workflow.nodes[0].widgets_values[1]).toBe(metadataValue);
|
||||
expect(result.output['1'].inputs[METADATA_NAME]).toBe(metadataValue);
|
||||
});
|
||||
|
||||
it('tolerates malformed results', () => {
|
||||
expect(stripResult(null)).toBe(null);
|
||||
expect(stripResult(undefined)).toBe(undefined);
|
||||
expect(stripResult({})).toEqual({});
|
||||
|
||||
const result = {
|
||||
workflow: { nodes: [null, { widgets_values: null }] },
|
||||
output: { '1': { inputs: null }, '2': {} },
|
||||
};
|
||||
expect(() => stripResult(result)).not.toThrow();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,141 @@
|
||||
import { describe, it, expect, beforeEach, vi } from "vitest";
|
||||
|
||||
const {
|
||||
APP_MODULE,
|
||||
API_MODULE,
|
||||
UTILS_MODULE,
|
||||
SETTINGS_MODULE,
|
||||
LORA_LOADER_MODULE,
|
||||
} = vi.hoisted(() => ({
|
||||
APP_MODULE: new URL("../../../scripts/app.js", import.meta.url).pathname,
|
||||
API_MODULE: new URL("../../../scripts/api.js", import.meta.url).pathname,
|
||||
UTILS_MODULE: new URL("../../../web/comfyui/utils.js", import.meta.url).pathname,
|
||||
SETTINGS_MODULE: new URL("../../../web/comfyui/settings.js", import.meta.url).pathname,
|
||||
LORA_LOADER_MODULE: new URL("../../../web/comfyui/lora_loader.js", import.meta.url).pathname,
|
||||
}));
|
||||
|
||||
const extensionState = { current: null };
|
||||
const registerExtensionMock = vi.fn((extension) => {
|
||||
extensionState.current = extension;
|
||||
});
|
||||
|
||||
vi.mock(APP_MODULE, () => ({
|
||||
app: {
|
||||
registerExtension: registerExtensionMock,
|
||||
graph: {},
|
||||
},
|
||||
}));
|
||||
|
||||
vi.mock(API_MODULE, () => ({
|
||||
api: {
|
||||
addEventListener: vi.fn(),
|
||||
},
|
||||
}));
|
||||
|
||||
const showToastMock = vi.fn();
|
||||
|
||||
vi.mock(UTILS_MODULE, () => ({
|
||||
collectActiveLorasFromChain: vi.fn(),
|
||||
updateConnectedTriggerWords: vi.fn(),
|
||||
mergeLoras: vi.fn(),
|
||||
chainCallback: (proto, property, callback) => {
|
||||
proto[property] = callback;
|
||||
},
|
||||
getAllGraphNodes: vi.fn(),
|
||||
getNodeFromGraph: vi.fn(),
|
||||
getWidgetByName: vi.fn(),
|
||||
getWidgetSerializedValue: vi.fn(),
|
||||
showToast: showToastMock,
|
||||
}));
|
||||
|
||||
const getActiveFiltersPreferenceMock = vi.fn();
|
||||
const setSettingValueMock = vi.fn();
|
||||
|
||||
vi.mock(SETTINGS_MODULE, () => ({
|
||||
LORA_ACTIVE_FILTERS_AUTOCOMPLETE_SETTING_ID:
|
||||
"loramanager.lora_active_filters_autocomplete",
|
||||
SETTING_TOGGLED_EVENT_NAME: "lora-manager:setting-toggled",
|
||||
getLoraActiveFiltersAutocompletePreference: getActiveFiltersPreferenceMock,
|
||||
setLoraManagerSettingValue: setSettingValueMock,
|
||||
}));
|
||||
|
||||
async function registerNodeType(comfyClass) {
|
||||
await import(LORA_LOADER_MODULE);
|
||||
const extension = extensionState.current;
|
||||
expect(extension).toBeDefined();
|
||||
const nodeType = { comfyClass, prototype: {} };
|
||||
await extension.beforeRegisterNodeDef(nodeType, {}, {});
|
||||
return nodeType;
|
||||
}
|
||||
|
||||
function getMenuOption(nodeType, enabled) {
|
||||
getActiveFiltersPreferenceMock.mockReturnValue(enabled);
|
||||
const options = [];
|
||||
nodeType.prototype.getExtraMenuOptions(null, options);
|
||||
return options.find(
|
||||
(option) =>
|
||||
option &&
|
||||
typeof option.content === "string" &&
|
||||
option.content.startsWith("Active Filters Search:")
|
||||
);
|
||||
}
|
||||
|
||||
describe("Lora Loader active-filters context menu", () => {
|
||||
beforeEach(() => {
|
||||
vi.resetModules();
|
||||
extensionState.current = null;
|
||||
registerExtensionMock.mockClear();
|
||||
showToastMock.mockClear();
|
||||
getActiveFiltersPreferenceMock.mockReset();
|
||||
setSettingValueMock.mockReset();
|
||||
setSettingValueMock.mockResolvedValue(true);
|
||||
});
|
||||
|
||||
it.each([
|
||||
"Lora Loader (LoraManager)",
|
||||
"Lora Stacker (LoraManager)",
|
||||
"WanVideo Lora Select (LoraManager)",
|
||||
"Create Hook LoRA (LoraManager)",
|
||||
])("adds the toggle entry to the %s context menu", async (comfyClass) => {
|
||||
const nodeType = await registerNodeType(comfyClass);
|
||||
|
||||
const option = getMenuOption(nodeType, false);
|
||||
expect(option).toBeDefined();
|
||||
expect(option.content).toContain("Active Filters Search: OFF");
|
||||
expect(option.content).toContain("/activefilters to enable");
|
||||
});
|
||||
|
||||
it("shows the disable hint when active-filters search is on", async () => {
|
||||
const nodeType = await registerNodeType("Lora Loader (LoraManager)");
|
||||
|
||||
const option = getMenuOption(nodeType, true);
|
||||
expect(option.content).toContain("Active Filters Search: ON");
|
||||
expect(option.content).toContain("/noactivefilters to disable");
|
||||
});
|
||||
|
||||
it("toggles the setting and toasts feedback", async () => {
|
||||
const nodeType = await registerNodeType("Lora Loader (LoraManager)");
|
||||
|
||||
const enableOption = getMenuOption(nodeType, false);
|
||||
await enableOption.callback();
|
||||
|
||||
expect(setSettingValueMock).toHaveBeenCalledWith(
|
||||
"loramanager.lora_active_filters_autocomplete",
|
||||
true
|
||||
);
|
||||
expect(showToastMock).toHaveBeenCalledWith(
|
||||
expect.objectContaining({ summary: "Active Filters Search Enabled" })
|
||||
);
|
||||
|
||||
const disableOption = getMenuOption(nodeType, true);
|
||||
await disableOption.callback();
|
||||
|
||||
expect(setSettingValueMock).toHaveBeenCalledWith(
|
||||
"loramanager.lora_active_filters_autocomplete",
|
||||
false
|
||||
);
|
||||
expect(showToastMock).toHaveBeenCalledWith(
|
||||
expect.objectContaining({ summary: "Active Filters Search Disabled" })
|
||||
);
|
||||
});
|
||||
});
|
||||
@@ -43,6 +43,12 @@ vi.mock('../../../static/js/utils/uiHelpers.js', () => ({
|
||||
showToast: showToastMock,
|
||||
openCivitaiByMetadata: openCivitaiByMetadataMock,
|
||||
updatePanelPositions: updatePanelPositionsMock,
|
||||
// Faithful stand-in for the real helper in uiHelpers.js
|
||||
isTypingContext: (target) => {
|
||||
if (!(target instanceof Element)) return false;
|
||||
const tagName = target.tagName?.toLowerCase();
|
||||
return target.isContentEditable || tagName === 'input' || tagName === 'textarea' || tagName === 'select';
|
||||
},
|
||||
}));
|
||||
|
||||
vi.mock('../../../static/js/managers/DownloadManager.js', () => ({
|
||||
@@ -350,6 +356,49 @@ describe('FilterManager tag and base model filters', () => {
|
||||
expect(baseModelChip.classList.contains('active')).toBe(false);
|
||||
});
|
||||
|
||||
it('filters recipes by the unknown base model bucket via its marker value', async () => {
|
||||
global.fetch = vi.fn().mockResolvedValue({
|
||||
ok: true,
|
||||
json: async () => ({
|
||||
success: true,
|
||||
base_models: [
|
||||
{ name: 'Unknown', value: '__unknown__', count: 3 },
|
||||
{ name: 'SDXL', count: 2 },
|
||||
],
|
||||
}),
|
||||
});
|
||||
|
||||
renderControlsDom('recipes');
|
||||
const stateModule = await import('../../../static/js/state/index.js');
|
||||
stateModule.initPageState('recipes');
|
||||
const { getCurrentPageState } = stateModule;
|
||||
const { FilterManager } = await import('../../../static/js/managers/FilterManager.js');
|
||||
|
||||
const loadRecipesMock = vi.fn().mockResolvedValue(undefined);
|
||||
window.recipeManager = { loadRecipes: loadRecipesMock };
|
||||
|
||||
new FilterManager({ page: 'recipes' });
|
||||
|
||||
await vi.waitFor(() => {
|
||||
const chip = document.querySelector('[data-base-model="__unknown__"]');
|
||||
expect(chip).not.toBeNull();
|
||||
});
|
||||
|
||||
const unknownChip = document.querySelector('[data-base-model="__unknown__"]');
|
||||
// Display label is "Unknown" even though the filter value is the marker
|
||||
expect(unknownChip.textContent).toContain('Unknown');
|
||||
|
||||
unknownChip.dispatchEvent(new Event('click', { bubbles: true }));
|
||||
await vi.waitFor(() => expect(loadRecipesMock).toHaveBeenCalledTimes(1));
|
||||
|
||||
expect(getCurrentPageState().filters.baseModel).toEqual(['__unknown__']);
|
||||
expect(unknownChip.classList.contains('active')).toBe(true);
|
||||
|
||||
const storageKey = 'lora_manager_recipes_filters';
|
||||
const storedFilters = JSON.parse(localStorage.getItem(storageKey));
|
||||
expect(storedFilters.baseModel).toEqual(['__unknown__']);
|
||||
});
|
||||
|
||||
it('filters base model chips locally without changing selected state', async () => {
|
||||
global.fetch = vi.fn().mockResolvedValue({
|
||||
ok: true,
|
||||
@@ -1157,4 +1206,87 @@ describe('PageControls favorites, sorting, and duplicates scenarios', () => {
|
||||
vi.useRealTimers();
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe('PageControls action keyboard shortcuts', () => {
|
||||
async function setupLorasControls() {
|
||||
renderControlsDom('loras');
|
||||
const stateModule = await import('../../../static/js/state/index.js');
|
||||
stateModule.initPageState('loras');
|
||||
const { LorasControls } = await import('../../../static/js/components/controls/LorasControls.js');
|
||||
return new LorasControls();
|
||||
}
|
||||
|
||||
function keydownEvent(key, { target = document.body, ...init } = {}) {
|
||||
const event = new KeyboardEvent('keydown', { key, bubbles: true, cancelable: true, ...init });
|
||||
Object.defineProperty(event, 'target', { value: target });
|
||||
return event;
|
||||
}
|
||||
|
||||
it('registers a pageControls-actions keydown handler with the event manager', async () => {
|
||||
await setupLorasControls();
|
||||
|
||||
const { eventManager } = await import('../../../static/js/utils/EventManager.js');
|
||||
const keydownHandlers = eventManager.handlers.get('keydown') || [];
|
||||
expect(keydownHandlers.some((h) => h.source === 'pageControls-actions')).toBe(true);
|
||||
});
|
||||
|
||||
it('triggers refresh, fetch, and download via the R / F / D keys', async () => {
|
||||
const controls = await setupLorasControls();
|
||||
|
||||
expect(controls.handleActionShortcut(keydownEvent('r'))).toBe(true);
|
||||
expect(refreshModelsMock).toHaveBeenCalledWith(false);
|
||||
|
||||
expect(controls.handleActionShortcut(keydownEvent('f'))).toBe(true);
|
||||
expect(fetchCivitaiMetadataMock).toHaveBeenCalledTimes(1);
|
||||
|
||||
expect(controls.handleActionShortcut(keydownEvent('d'))).toBe(true);
|
||||
expect(downloadManagerMock.showDownloadModal).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it('handles a real keydown dispatched on the document', async () => {
|
||||
await setupLorasControls();
|
||||
|
||||
const event = new KeyboardEvent('keydown', { key: 'r', bubbles: true, cancelable: true });
|
||||
document.dispatchEvent(event);
|
||||
|
||||
expect(event.defaultPrevented).toBe(true);
|
||||
expect(refreshModelsMock).toHaveBeenCalledWith(false);
|
||||
});
|
||||
|
||||
it('ignores R / F / D while typing in an input', async () => {
|
||||
const controls = await setupLorasControls();
|
||||
|
||||
const input = document.getElementById('searchInput');
|
||||
for (const key of ['r', 'f', 'd']) {
|
||||
const event = keydownEvent(key, { target: input });
|
||||
expect(controls.handleActionShortcut(event)).toBe(false);
|
||||
expect(event.defaultPrevented).toBe(false);
|
||||
}
|
||||
|
||||
expect(refreshModelsMock).not.toHaveBeenCalled();
|
||||
expect(fetchCivitaiMetadataMock).not.toHaveBeenCalled();
|
||||
expect(downloadManagerMock.showDownloadModal).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('ignores R / F / D when combined with modifier keys', async () => {
|
||||
const controls = await setupLorasControls();
|
||||
|
||||
const event = keydownEvent('r', { ctrlKey: true });
|
||||
expect(controls.handleActionShortcut(event)).toBe(false);
|
||||
expect(event.defaultPrevented).toBe(false);
|
||||
expect(refreshModelsMock).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('passes the event through when the action button does not exist', async () => {
|
||||
const controls = await setupLorasControls();
|
||||
|
||||
// Recipes page has no fetch/download buttons
|
||||
document.querySelector('[data-action="fetch"]').closest('.control-group').remove();
|
||||
|
||||
const event = keydownEvent('f');
|
||||
expect(controls.handleActionShortcut(event)).toBe(false);
|
||||
expect(event.defaultPrevented).toBe(false);
|
||||
expect(fetchCivitaiMetadataMock).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
@@ -13,6 +13,12 @@ vi.mock('../../../static/js/utils/uiHelpers.js', () => ({
|
||||
showToast: vi.fn(),
|
||||
openCivitaiByMetadata: vi.fn(),
|
||||
updatePanelPositions: vi.fn(),
|
||||
// Faithful stand-in for the real helper in uiHelpers.js
|
||||
isTypingContext: (target) => {
|
||||
if (!(target instanceof Element)) return false;
|
||||
const tagName = target.tagName?.toLowerCase();
|
||||
return target.isContentEditable || tagName === 'input' || tagName === 'textarea' || tagName === 'select';
|
||||
},
|
||||
}));
|
||||
|
||||
vi.mock('../../../static/js/managers/DownloadManager.js', () => ({
|
||||
|
||||
@@ -0,0 +1,202 @@
|
||||
import { describe, it, beforeEach, afterEach, expect, vi } from 'vitest';
|
||||
|
||||
const {
|
||||
RECIPE_CARD_MODULE,
|
||||
UI_HELPERS_MODULE,
|
||||
RECIPE_API_MODULE,
|
||||
MODEL_CARD_MODULE,
|
||||
MODAL_MANAGER_MODULE,
|
||||
STATE_MODULE,
|
||||
BULK_MANAGER_MODULE,
|
||||
CONSTANTS_MODULE,
|
||||
I18N_MODULE,
|
||||
UNDO_HELPERS_MODULE,
|
||||
} = vi.hoisted(() => ({
|
||||
RECIPE_CARD_MODULE: new URL('../../../static/js/components/RecipeCard.js', import.meta.url).pathname,
|
||||
UI_HELPERS_MODULE: new URL('../../../static/js/utils/uiHelpers.js', import.meta.url).pathname,
|
||||
RECIPE_API_MODULE: new URL('../../../static/js/api/recipeApi.js', import.meta.url).pathname,
|
||||
MODEL_CARD_MODULE: new URL('../../../static/js/components/shared/ModelCard.js', import.meta.url).pathname,
|
||||
MODAL_MANAGER_MODULE: new URL('../../../static/js/managers/ModalManager.js', import.meta.url).pathname,
|
||||
STATE_MODULE: new URL('../../../static/js/state/index.js', import.meta.url).pathname,
|
||||
BULK_MANAGER_MODULE: new URL('../../../static/js/managers/BulkManager.js', import.meta.url).pathname,
|
||||
CONSTANTS_MODULE: new URL('../../../static/js/utils/constants.js', import.meta.url).pathname,
|
||||
I18N_MODULE: new URL('../../../static/js/utils/i18nHelpers.js', import.meta.url).pathname,
|
||||
UNDO_HELPERS_MODULE: new URL('../../../static/js/utils/undoHelpers.js', import.meta.url).pathname,
|
||||
}));
|
||||
|
||||
const translateMock = vi.fn((key, params, fallback) => (typeof fallback === 'string' ? fallback : key));
|
||||
|
||||
vi.mock(UI_HELPERS_MODULE, () => ({
|
||||
showToast: vi.fn(),
|
||||
showActionToast: vi.fn(),
|
||||
copyToClipboard: vi.fn(),
|
||||
sendLoraToWorkflow: vi.fn(),
|
||||
}));
|
||||
|
||||
vi.mock(RECIPE_API_MODULE, () => ({
|
||||
updateRecipeMetadata: vi.fn(),
|
||||
}));
|
||||
|
||||
vi.mock(MODEL_CARD_MODULE, () => ({
|
||||
configureModelCardVideo: vi.fn(),
|
||||
}));
|
||||
|
||||
vi.mock(MODAL_MANAGER_MODULE, () => ({
|
||||
modalManager: {
|
||||
showModal: vi.fn(),
|
||||
closeModal: vi.fn(),
|
||||
},
|
||||
}));
|
||||
|
||||
vi.mock(STATE_MODULE, () => ({
|
||||
state: {
|
||||
global: { settings: {} },
|
||||
settings: {},
|
||||
virtualScroller: { removeItemByFilePath: vi.fn() },
|
||||
},
|
||||
getCurrentPageState: vi.fn(() => ({})),
|
||||
}));
|
||||
|
||||
vi.mock(BULK_MANAGER_MODULE, () => ({
|
||||
bulkManager: {},
|
||||
}));
|
||||
|
||||
vi.mock(CONSTANTS_MODULE, () => ({
|
||||
NSFW_LEVELS: {},
|
||||
getBaseModelAbbreviation: vi.fn((label) => label),
|
||||
getMatureBlurThreshold: vi.fn(() => 10),
|
||||
}));
|
||||
|
||||
vi.mock(I18N_MODULE, () => ({
|
||||
translate: translateMock,
|
||||
}));
|
||||
|
||||
vi.mock(UNDO_HELPERS_MODULE, () => ({
|
||||
handleUndoDelete: vi.fn(),
|
||||
}));
|
||||
|
||||
function buildRecipe(loras) {
|
||||
return {
|
||||
id: 'recipe-1',
|
||||
file_path: '/recipes/r1.json',
|
||||
title: 'Badge Recipe',
|
||||
file_url: '/preview.png',
|
||||
preview_nsfw_level: 0,
|
||||
created_date: '2024-01-01',
|
||||
base_model: 'SDXL',
|
||||
loras,
|
||||
};
|
||||
}
|
||||
|
||||
async function createCard(loras) {
|
||||
const { RecipeCard } = await import(RECIPE_CARD_MODULE);
|
||||
return new RecipeCard(buildRecipe(loras), vi.fn());
|
||||
}
|
||||
|
||||
describe('RecipeCard LoRA status pill', () => {
|
||||
beforeEach(() => {
|
||||
translateMock.mockClear();
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
document.body.innerHTML = '';
|
||||
});
|
||||
|
||||
it('shows available/total with a warning icon when LoRAs are missing', async () => {
|
||||
const card = await createCard([
|
||||
{ name: 'a', inLibrary: true },
|
||||
{ name: 'b', inLibrary: false },
|
||||
{ name: 'c', inLibrary: true },
|
||||
]);
|
||||
|
||||
const pill = card.element.querySelector('.lora-count.missing');
|
||||
expect(pill).not.toBeNull();
|
||||
expect(pill.querySelector('.fa-exclamation-triangle')).not.toBeNull();
|
||||
expect(pill.textContent).toContain('2/3');
|
||||
expect(pill.title).toBe('1 of 3 LoRAs missing');
|
||||
});
|
||||
|
||||
it('shows a green check with n/n when every LoRA is available', async () => {
|
||||
const card = await createCard([
|
||||
{ name: 'a', inLibrary: true },
|
||||
{ name: 'b', inLibrary: true },
|
||||
]);
|
||||
|
||||
const pill = card.element.querySelector('.lora-count.ready');
|
||||
expect(pill).not.toBeNull();
|
||||
expect(pill.querySelector('.fa-check')).not.toBeNull();
|
||||
expect(pill.textContent).toContain('2/2');
|
||||
expect(pill.title).toBe('All LoRAs available - Ready to use');
|
||||
expect(card.element.querySelector('.lora-count.missing')).toBeNull();
|
||||
});
|
||||
|
||||
it('marks deleted-from-source LoRAs as partial instead of ready', async () => {
|
||||
const card = await createCard([
|
||||
{ name: 'a', inLibrary: true },
|
||||
{ name: 'b', inLibrary: false, isDeleted: true },
|
||||
]);
|
||||
|
||||
expect(card.element.querySelector('.lora-count.missing')).toBeNull();
|
||||
expect(card.element.querySelector('.lora-count.ready')).toBeNull();
|
||||
|
||||
const pill = card.element.querySelector('.lora-count.partial');
|
||||
expect(pill).not.toBeNull();
|
||||
expect(pill.querySelector('.fa-circle-minus')).not.toBeNull();
|
||||
expect(pill.textContent).toContain('1/2');
|
||||
expect(pill.title).toBe('1 of 2 LoRAs unavailable (deleted from source or unresolvable hash) - skipped when recipe is used');
|
||||
});
|
||||
|
||||
it('treats an unresolvable hash as unobtainable, not missing', async () => {
|
||||
const card = await createCard([
|
||||
{ name: 'a', inLibrary: true },
|
||||
{ name: 'b', inLibrary: false, hashInvalid: true },
|
||||
]);
|
||||
|
||||
expect(card.element.querySelector('.lora-count.missing')).toBeNull();
|
||||
|
||||
const pill = card.element.querySelector('.lora-count.partial');
|
||||
expect(pill).not.toBeNull();
|
||||
expect(pill.textContent).toContain('1/2');
|
||||
});
|
||||
|
||||
it('shows 0/n unavailable when every LoRA is deleted and none is in the library', async () => {
|
||||
const card = await createCard([
|
||||
{ name: 'a', inLibrary: false, isDeleted: true },
|
||||
{ name: 'b', inLibrary: false, isDeleted: true },
|
||||
]);
|
||||
|
||||
const pill = card.element.querySelector('.lora-count.unavailable');
|
||||
expect(pill).not.toBeNull();
|
||||
expect(pill.querySelector('.fa-ban')).not.toBeNull();
|
||||
expect(pill.textContent).toContain('0/2');
|
||||
expect(pill.title).toBe('No usable LoRAs - 2 of 2 deleted from source or unresolvable hash');
|
||||
expect(card.element.querySelector('.lora-count.ready')).toBeNull();
|
||||
});
|
||||
|
||||
it('keeps the actionable missing state when LoRAs are both missing and deleted', async () => {
|
||||
const card = await createCard([
|
||||
{ name: 'a', inLibrary: true },
|
||||
{ name: 'b', inLibrary: false },
|
||||
{ name: 'c', inLibrary: false, isDeleted: true },
|
||||
]);
|
||||
|
||||
const pill = card.element.querySelector('.lora-count.missing');
|
||||
expect(pill).not.toBeNull();
|
||||
expect(pill.textContent).toContain('1/3');
|
||||
expect(pill.title).toBe('1 of 3 LoRAs missing, 1 unavailable (deleted from source or unresolvable hash)');
|
||||
expect(card.element.querySelector('.lora-count.partial')).toBeNull();
|
||||
});
|
||||
|
||||
it('shows a neutral layers icon with a bare 0 when the recipe has no LoRAs', async () => {
|
||||
const card = await createCard([]);
|
||||
|
||||
const pill = card.element.querySelector('.lora-count');
|
||||
expect(pill).not.toBeNull();
|
||||
expect(pill.classList.contains('missing')).toBe(false);
|
||||
expect(pill.classList.contains('ready')).toBe(false);
|
||||
expect(pill.querySelector('.fa-layer-group')).not.toBeNull();
|
||||
expect(pill.textContent).toContain('0');
|
||||
expect(pill.textContent).not.toContain('/');
|
||||
expect(pill.title).toBe('No LoRAs in this recipe');
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,132 @@
|
||||
import { describe, it, beforeEach, afterEach, expect, vi } from 'vitest';
|
||||
|
||||
const showToastMock = vi.fn();
|
||||
const copyToClipboardMock = vi.fn();
|
||||
const translateMock = vi.fn((key, params, fallback) => (typeof fallback === 'string' ? fallback : key));
|
||||
|
||||
const loadingManagerStub = {
|
||||
showSimpleLoading: vi.fn(),
|
||||
hide: vi.fn(),
|
||||
show: vi.fn(),
|
||||
restoreProgressBar: vi.fn(),
|
||||
};
|
||||
|
||||
const stateStub = {
|
||||
global: { settings: {}, loadingManager: loadingManagerStub },
|
||||
loadingManager: loadingManagerStub,
|
||||
virtualScroller: { updateSingleItem: vi.fn() },
|
||||
};
|
||||
|
||||
vi.mock('../../../static/js/utils/uiHelpers.js', () => ({
|
||||
showToast: showToastMock,
|
||||
copyToClipboard: copyToClipboardMock,
|
||||
sendLoraToWorkflow: vi.fn(),
|
||||
sendModelPathToWorkflow: vi.fn(),
|
||||
openCivitaiByMetadata: vi.fn(),
|
||||
stripLoraTags: vi.fn((text) => text),
|
||||
sendPromptToWorkflow: vi.fn(),
|
||||
sendGenParamsToWorkflow: vi.fn(),
|
||||
}));
|
||||
|
||||
vi.mock('../../../static/js/utils/i18nHelpers.js', () => ({
|
||||
translate: translateMock,
|
||||
}));
|
||||
|
||||
vi.mock('../../../static/js/state/index.js', () => ({
|
||||
state: stateStub,
|
||||
}));
|
||||
|
||||
vi.mock('../../../static/js/utils/storageHelpers.js', () => ({
|
||||
setSessionItem: vi.fn(),
|
||||
removeSessionItem: vi.fn(),
|
||||
getStorageItem: vi.fn(() => null),
|
||||
setStorageItem: vi.fn(),
|
||||
}));
|
||||
|
||||
vi.mock('../../../static/js/api/recipeApi.js', () => ({
|
||||
fetchRecipeDetails: vi.fn(),
|
||||
updateRecipeMetadata: vi.fn(() => Promise.resolve({ success: true })),
|
||||
sendRecipeWorkflow: vi.fn(),
|
||||
}));
|
||||
|
||||
vi.mock('../../../static/js/api/apiConfig.js', () => ({
|
||||
MODEL_TYPES: {
|
||||
LORA: 'loras',
|
||||
CHECKPOINT: 'checkpoints',
|
||||
EMBEDDING: 'embeddings',
|
||||
},
|
||||
}));
|
||||
|
||||
async function flushAsyncTasks() {
|
||||
await Promise.resolve();
|
||||
await new Promise((resolve) => setTimeout(resolve, 0));
|
||||
}
|
||||
|
||||
async function createRecipeModal() {
|
||||
const { RecipeModal } = await import('../../../static/js/components/RecipeModal.js');
|
||||
return new RecipeModal();
|
||||
}
|
||||
|
||||
describe('RecipeModal copy recipe syntax', () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
document.body.innerHTML = `
|
||||
<div class="recipe-header-actions" id="recipeHeaderActions">
|
||||
<button class="modal-send-btn" id="sendRecipeBtn"><i class="fas fa-paper-plane"></i></button>
|
||||
<button class="modal-copy-btn" id="copyRecipeSyntaxBtn"><i class="fas fa-copy"></i></button>
|
||||
</div>
|
||||
`;
|
||||
global.fetch = vi.fn();
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
document.body.innerHTML = '';
|
||||
delete global.fetch;
|
||||
});
|
||||
|
||||
it('copies the recipe syntax when the header copy button is clicked', async () => {
|
||||
const recipeModal = await createRecipeModal();
|
||||
recipeModal.recipeId = 'recipe-1';
|
||||
global.fetch.mockResolvedValue({
|
||||
ok: true,
|
||||
json: () => Promise.resolve({ success: true, syntax: '<lora:foo:1>' }),
|
||||
});
|
||||
|
||||
recipeModal.setupCopyButtons();
|
||||
document.getElementById('copyRecipeSyntaxBtn').dispatchEvent(new Event('click', { bubbles: true }));
|
||||
await flushAsyncTasks();
|
||||
|
||||
expect(global.fetch).toHaveBeenCalledWith('/api/lm/recipe/recipe-1/syntax');
|
||||
expect(copyToClipboardMock).toHaveBeenCalledWith('<lora:foo:1>', 'Recipe syntax copied to clipboard');
|
||||
});
|
||||
|
||||
it('shows an error toast and skips the API call without a recipe ID', async () => {
|
||||
const recipeModal = await createRecipeModal();
|
||||
recipeModal.recipeId = null;
|
||||
|
||||
await recipeModal.fetchAndCopyRecipeSyntax();
|
||||
|
||||
expect(global.fetch).not.toHaveBeenCalled();
|
||||
expect(showToastMock).toHaveBeenCalledWith('toast.recipes.noRecipeId', {}, 'error');
|
||||
});
|
||||
|
||||
it('shows an error toast when the backend returns no syntax', async () => {
|
||||
const errorSpy = vi.spyOn(console, 'error').mockImplementation(() => {});
|
||||
const recipeModal = await createRecipeModal();
|
||||
recipeModal.recipeId = 'recipe-1';
|
||||
global.fetch.mockResolvedValue({
|
||||
ok: true,
|
||||
json: () => Promise.resolve({ success: false, error: 'no syntax' }),
|
||||
});
|
||||
|
||||
await recipeModal.fetchAndCopyRecipeSyntax();
|
||||
|
||||
expect(copyToClipboardMock).not.toHaveBeenCalled();
|
||||
expect(showToastMock).toHaveBeenCalledWith(
|
||||
'toast.recipes.copyFailed',
|
||||
{ message: 'no syntax' },
|
||||
'error'
|
||||
);
|
||||
errorSpy.mockRestore();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,270 @@
|
||||
import { describe, it, beforeEach, afterEach, expect, vi } from 'vitest';
|
||||
|
||||
const showToastMock = vi.fn();
|
||||
const copyToClipboardMock = vi.fn();
|
||||
const translateMock = vi.fn((key, params, fallback) => (typeof fallback === 'string' ? fallback : key));
|
||||
|
||||
const loadingManagerStub = {
|
||||
showSimpleLoading: vi.fn(),
|
||||
hide: vi.fn(),
|
||||
show: vi.fn(),
|
||||
restoreProgressBar: vi.fn(),
|
||||
};
|
||||
|
||||
const recipeItem = {
|
||||
id: 'a1b2c3d4-e5f6-7890-abcd-ef1234567890',
|
||||
file_path: '/recipes/a1b2c3d4-e5f6-7890-abcd-ef1234567890.png',
|
||||
title: 'Demo Recipe',
|
||||
tags: [],
|
||||
loras: [],
|
||||
};
|
||||
|
||||
const virtualScrollerStub = {
|
||||
updateSingleItem: vi.fn(),
|
||||
getNavigationState: vi.fn(() => ({
|
||||
index: 0,
|
||||
hasPrev: false,
|
||||
hasNext: false,
|
||||
loadedItems: 1,
|
||||
totalItems: 1,
|
||||
})),
|
||||
getAdjacentItemByFilePath: vi.fn(async () => null),
|
||||
};
|
||||
|
||||
const stateStub = {
|
||||
global: { settings: {}, loadingManager: loadingManagerStub },
|
||||
loadingManager: loadingManagerStub,
|
||||
virtualScroller: virtualScrollerStub,
|
||||
};
|
||||
|
||||
const modalManagerMock = {
|
||||
showModal: vi.fn(),
|
||||
closeModal: vi.fn(),
|
||||
};
|
||||
|
||||
const fetchRecipeDetailsMock = vi.fn(async () => ({}));
|
||||
const updateRecipeMetadataMock = vi.fn(() => Promise.resolve({ success: true }));
|
||||
|
||||
vi.mock('../../../static/js/utils/uiHelpers.js', () => ({
|
||||
showToast: showToastMock,
|
||||
copyToClipboard: copyToClipboardMock,
|
||||
sendLoraToWorkflow: vi.fn(),
|
||||
sendModelPathToWorkflow: vi.fn(),
|
||||
openCivitaiByMetadata: vi.fn(),
|
||||
stripLoraTags: vi.fn((text) => text),
|
||||
sendPromptToWorkflow: vi.fn(),
|
||||
sendGenParamsToWorkflow: vi.fn(),
|
||||
}));
|
||||
|
||||
vi.mock('../../../static/js/utils/i18nHelpers.js', () => ({
|
||||
translate: translateMock,
|
||||
}));
|
||||
|
||||
vi.mock('../../../static/js/state/index.js', () => ({
|
||||
state: stateStub,
|
||||
}));
|
||||
|
||||
vi.mock('../../../static/js/utils/storageHelpers.js', () => ({
|
||||
setSessionItem: vi.fn(),
|
||||
removeSessionItem: vi.fn(),
|
||||
getStorageItem: vi.fn(() => null),
|
||||
setStorageItem: vi.fn(),
|
||||
}));
|
||||
|
||||
vi.mock('../../../static/js/api/recipeApi.js', () => ({
|
||||
fetchRecipeDetails: fetchRecipeDetailsMock,
|
||||
updateRecipeMetadata: updateRecipeMetadataMock,
|
||||
sendRecipeWorkflow: vi.fn(),
|
||||
}));
|
||||
|
||||
vi.mock('../../../static/js/api/apiConfig.js', () => ({
|
||||
MODEL_TYPES: {
|
||||
LORA: 'loras',
|
||||
CHECKPOINT: 'checkpoints',
|
||||
EMBEDDING: 'embeddings',
|
||||
},
|
||||
}));
|
||||
|
||||
function recipeModalFixture() {
|
||||
return `
|
||||
<div id="recipeModal" class="modal">
|
||||
<div class="modal-content">
|
||||
<header class="recipe-modal-header">
|
||||
<div class="recipe-modal-header-row">
|
||||
<h2 id="recipeModalTitle">Recipe Details</h2>
|
||||
<div class="modal-nav-controls">
|
||||
<button class="modal-nav-btn" id="recipeNavPrevBtn" disabled></button>
|
||||
<button class="modal-nav-btn" id="recipeNavNextBtn" disabled></button>
|
||||
</div>
|
||||
</div>
|
||||
<div class="recipe-header-actions" id="recipeHeaderActions">
|
||||
<button class="modal-send-btn" id="sendRecipeBtn"><i class="fas fa-paper-plane"></i></button>
|
||||
<button class="modal-copy-btn" id="copyRecipeSyntaxBtn"><i class="fas fa-copy"></i></button>
|
||||
</div>
|
||||
<div id="recipeTagsContainer"></div>
|
||||
</header>
|
||||
<div class="modal-body">
|
||||
<div class="recipe-media-column">
|
||||
<div class="recipe-preview-container" id="recipePreviewContainer">
|
||||
<img id="recipeModalImage" src="" alt="Recipe Preview" class="recipe-preview-media">
|
||||
</div>
|
||||
</div>
|
||||
<div class="info-section recipe-gen-params">
|
||||
<div class="gen-params-container">
|
||||
<div class="param-group info-item">
|
||||
<div class="param-content" id="recipePrompt"></div>
|
||||
<div class="param-editor" id="recipePromptEditor">
|
||||
<textarea class="param-textarea" id="recipePromptInput"></textarea>
|
||||
</div>
|
||||
</div>
|
||||
<div class="param-group info-item">
|
||||
<div class="param-content" id="recipeNegativePrompt"></div>
|
||||
<div class="param-editor" id="recipeNegativePromptEditor">
|
||||
<textarea class="param-textarea" id="recipeNegativePromptInput"></textarea>
|
||||
</div>
|
||||
</div>
|
||||
<div class="other-params" id="recipeOtherParams"></div>
|
||||
</div>
|
||||
</div>
|
||||
<div class="info-section recipe-bottom-section">
|
||||
<div class="recipe-section-actions">
|
||||
<span id="recipeLorasCount"></span>
|
||||
<button class="action-btn view-loras-btn" id="viewRecipeLorasBtn"></button>
|
||||
</div>
|
||||
<div class="recipe-loras-list" id="recipeLorasList"></div>
|
||||
</div>
|
||||
</div>
|
||||
<footer class="recipe-meta-footer" id="recipeMetaFooter" hidden></footer>
|
||||
</div>
|
||||
</div>
|
||||
`;
|
||||
}
|
||||
|
||||
async function flushAsyncTasks() {
|
||||
await Promise.resolve();
|
||||
await new Promise((resolve) => setTimeout(resolve, 0));
|
||||
}
|
||||
|
||||
const createdModals = [];
|
||||
|
||||
async function createRecipeModal() {
|
||||
const { RecipeModal } = await import('../../../static/js/components/RecipeModal.js');
|
||||
const recipeModal = new RecipeModal();
|
||||
createdModals.push(recipeModal);
|
||||
return recipeModal;
|
||||
}
|
||||
|
||||
function openLocationFetchCalls() {
|
||||
return global.fetch.mock.calls.filter(([url]) => url === '/api/lm/open-file-location');
|
||||
}
|
||||
|
||||
describe('RecipeModal meta footer', () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
document.body.innerHTML = recipeModalFixture();
|
||||
global.modalManager = modalManagerMock;
|
||||
global.fetch = vi.fn(async () => ({
|
||||
ok: true,
|
||||
json: async () => ({}),
|
||||
}));
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
createdModals.forEach(recipeModal => recipeModal.cleanupNavigationShortcuts());
|
||||
createdModals.length = 0;
|
||||
document.body.innerHTML = '';
|
||||
delete global.modalManager;
|
||||
delete global.fetch;
|
||||
});
|
||||
|
||||
it('shows the folder path and a middle-truncated recipe ID', async () => {
|
||||
const recipeModal = await createRecipeModal();
|
||||
recipeModal.showRecipeDetails(recipeItem);
|
||||
|
||||
const footer = document.getElementById('recipeMetaFooter');
|
||||
expect(footer.hidden).toBe(false);
|
||||
|
||||
const location = footer.querySelector('.recipe-meta-location');
|
||||
expect(location.querySelector('.recipe-meta-location-path').textContent).toBe('/recipes/');
|
||||
expect(location.dataset.filepath).toBe(recipeItem.file_path);
|
||||
|
||||
const idValue = footer.querySelector('.recipe-meta-id-value');
|
||||
expect(idValue.textContent).toBe('a1b2c3d4…7890');
|
||||
expect(idValue.getAttribute('title')).toBe(recipeItem.id);
|
||||
});
|
||||
|
||||
it('copies the full recipe ID when the copy button is clicked', async () => {
|
||||
const recipeModal = await createRecipeModal();
|
||||
recipeModal.showRecipeDetails(recipeItem);
|
||||
|
||||
document.querySelector('.recipe-meta-copy-btn').click();
|
||||
|
||||
expect(copyToClipboardMock).toHaveBeenCalledWith(recipeItem.id);
|
||||
});
|
||||
|
||||
it('opens the recipe file location when the path is clicked', async () => {
|
||||
const recipeModal = await createRecipeModal();
|
||||
recipeModal.showRecipeDetails(recipeItem);
|
||||
|
||||
document.querySelector('.recipe-meta-location').click();
|
||||
await flushAsyncTasks();
|
||||
|
||||
const calls = openLocationFetchCalls();
|
||||
expect(calls).toHaveLength(1);
|
||||
expect(JSON.parse(calls[0][1].body)).toEqual({ file_path: recipeItem.file_path });
|
||||
expect(showToastMock).toHaveBeenCalledWith('recipes.modal.openFileLocation.success', {}, 'success');
|
||||
});
|
||||
|
||||
it('opens the recipe JSON path once hydration provides it', async () => {
|
||||
const jsonPath = '/recipes/a1b2c3d4-e5f6-7890-abcd-ef1234567890.recipe.json';
|
||||
fetchRecipeDetailsMock.mockResolvedValueOnce({
|
||||
id: recipeItem.id,
|
||||
file_path: recipeItem.file_path,
|
||||
recipe_json_path: jsonPath,
|
||||
});
|
||||
|
||||
const recipeModal = await createRecipeModal();
|
||||
recipeModal.showRecipeDetails(recipeItem);
|
||||
await flushAsyncTasks();
|
||||
|
||||
const location = document.querySelector('.recipe-meta-location');
|
||||
expect(location.dataset.filepath).toBe(jsonPath);
|
||||
});
|
||||
|
||||
it('copies the path to clipboard when the backend reports clipboard mode', async () => {
|
||||
const writeTextMock = vi.fn(async () => {});
|
||||
Object.defineProperty(window.navigator, 'clipboard', {
|
||||
value: { writeText: writeTextMock },
|
||||
configurable: true,
|
||||
});
|
||||
|
||||
global.fetch = vi.fn(async (url) => ({
|
||||
ok: true,
|
||||
json: async () => (url === '/api/lm/open-file-location'
|
||||
? { mode: 'clipboard', path: '/recipes' }
|
||||
: {}),
|
||||
}));
|
||||
|
||||
const recipeModal = await createRecipeModal();
|
||||
recipeModal.showRecipeDetails(recipeItem);
|
||||
|
||||
document.querySelector('.recipe-meta-location').click();
|
||||
await flushAsyncTasks();
|
||||
|
||||
expect(writeTextMock).toHaveBeenCalledWith('/recipes');
|
||||
expect(showToastMock).toHaveBeenCalledWith(
|
||||
'recipes.modal.openFileLocation.copied',
|
||||
{ path: '/recipes' },
|
||||
'success',
|
||||
);
|
||||
});
|
||||
|
||||
it('hides the footer when neither ID nor file path is available', async () => {
|
||||
const recipeModal = await createRecipeModal();
|
||||
recipeModal.showRecipeDetails({ title: 'Orphan', tags: [], loras: [] });
|
||||
|
||||
const footer = document.getElementById('recipeMetaFooter');
|
||||
expect(footer.hidden).toBe(true);
|
||||
expect(footer.innerHTML).toBe('');
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,197 @@
|
||||
import { describe, it, beforeEach, afterEach, expect, vi } from 'vitest';
|
||||
|
||||
const showToastMock = vi.fn();
|
||||
const translateMock = vi.fn((key, params, fallback) => (typeof fallback === 'string' ? fallback : key));
|
||||
|
||||
const loadingManagerStub = {
|
||||
showSimpleLoading: vi.fn(),
|
||||
hide: vi.fn(),
|
||||
show: vi.fn(),
|
||||
restoreProgressBar: vi.fn(),
|
||||
};
|
||||
|
||||
const virtualScrollerStub = {
|
||||
updateSingleItem: vi.fn(),
|
||||
getNavigationState: vi.fn(() => ({
|
||||
index: 0,
|
||||
hasPrev: false,
|
||||
hasNext: false,
|
||||
loadedItems: 1,
|
||||
totalItems: 1,
|
||||
})),
|
||||
getAdjacentItemByFilePath: vi.fn(async () => null),
|
||||
};
|
||||
|
||||
const stateStub = {
|
||||
global: { settings: {}, loadingManager: loadingManagerStub },
|
||||
loadingManager: loadingManagerStub,
|
||||
virtualScroller: virtualScrollerStub,
|
||||
};
|
||||
|
||||
const modalManagerMock = {
|
||||
showModal: vi.fn(),
|
||||
closeModal: vi.fn(),
|
||||
};
|
||||
|
||||
vi.mock('../../../static/js/utils/uiHelpers.js', () => ({
|
||||
showToast: showToastMock,
|
||||
copyToClipboard: vi.fn(),
|
||||
sendLoraToWorkflow: vi.fn(),
|
||||
sendModelPathToWorkflow: vi.fn(),
|
||||
openCivitaiByMetadata: vi.fn(),
|
||||
stripLoraTags: vi.fn((text) => text),
|
||||
sendPromptToWorkflow: vi.fn(),
|
||||
sendGenParamsToWorkflow: vi.fn(),
|
||||
}));
|
||||
|
||||
vi.mock('../../../static/js/utils/i18nHelpers.js', () => ({
|
||||
translate: translateMock,
|
||||
}));
|
||||
|
||||
vi.mock('../../../static/js/state/index.js', () => ({
|
||||
state: stateStub,
|
||||
}));
|
||||
|
||||
vi.mock('../../../static/js/utils/storageHelpers.js', () => ({
|
||||
setSessionItem: vi.fn(),
|
||||
removeSessionItem: vi.fn(),
|
||||
getStorageItem: vi.fn(() => null),
|
||||
setStorageItem: vi.fn(),
|
||||
}));
|
||||
|
||||
vi.mock('../../../static/js/api/recipeApi.js', () => ({
|
||||
fetchRecipeDetails: vi.fn(),
|
||||
updateRecipeMetadata: vi.fn(() => Promise.resolve({ success: true })),
|
||||
sendRecipeWorkflow: vi.fn(),
|
||||
}));
|
||||
|
||||
vi.mock('../../../static/js/api/apiConfig.js', () => ({
|
||||
MODEL_TYPES: {
|
||||
LORA: 'loras',
|
||||
CHECKPOINT: 'checkpoints',
|
||||
EMBEDDING: 'embeddings',
|
||||
},
|
||||
}));
|
||||
|
||||
function recipeModalFixture() {
|
||||
return `
|
||||
<div id="recipeModal" class="modal">
|
||||
<div class="modal-content">
|
||||
<header class="recipe-modal-header">
|
||||
<h2 id="recipeModalTitle">Recipe Details</h2>
|
||||
<div id="recipeTagsContainer"></div>
|
||||
</header>
|
||||
<div class="modal-body">
|
||||
<div class="recipe-media-column">
|
||||
<div class="recipe-preview-container" id="recipePreviewContainer">
|
||||
<img id="recipeModalImage" src="" alt="Recipe Preview" class="recipe-preview-media">
|
||||
</div>
|
||||
</div>
|
||||
<div class="info-section recipe-bottom-section">
|
||||
<div class="recipe-section-actions">
|
||||
<span id="recipeLorasCount"></span>
|
||||
<button class="action-btn view-loras-btn" id="viewRecipeLorasBtn"></button>
|
||||
</div>
|
||||
<div class="recipe-loras-list" id="recipeLorasList"></div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
`;
|
||||
}
|
||||
|
||||
const recipeWithMissing = {
|
||||
id: 'recipe-missing',
|
||||
file_path: '/recipes/missing.json',
|
||||
title: 'Missing Recipe',
|
||||
tags: [],
|
||||
loras: [
|
||||
{ name: 'present-lora', inLibrary: true },
|
||||
{ name: 'gone-lora', inLibrary: false },
|
||||
],
|
||||
};
|
||||
|
||||
const recipeReady = {
|
||||
id: 'recipe-ready',
|
||||
file_path: '/recipes/ready.json',
|
||||
title: 'Ready Recipe',
|
||||
tags: [],
|
||||
loras: [
|
||||
{ name: 'present-lora', inLibrary: true },
|
||||
],
|
||||
};
|
||||
|
||||
const createdModals = [];
|
||||
|
||||
async function createRecipeModal() {
|
||||
const { RecipeModal } = await import('../../../static/js/components/RecipeModal.js');
|
||||
const recipeModal = new RecipeModal();
|
||||
createdModals.push(recipeModal);
|
||||
return recipeModal;
|
||||
}
|
||||
|
||||
describe('RecipeModal missing LoRA status', () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
document.body.innerHTML = recipeModalFixture();
|
||||
global.modalManager = modalManagerMock;
|
||||
global.fetch = vi.fn(async () => ({
|
||||
ok: true,
|
||||
json: async () => ({}),
|
||||
}));
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
createdModals.forEach(recipeModal => recipeModal.cleanupNavigationShortcuts());
|
||||
createdModals.length = 0;
|
||||
document.body.innerHTML = '';
|
||||
delete global.modalManager;
|
||||
delete global.fetch;
|
||||
});
|
||||
|
||||
it('renders the missing status as a button with a persistent affordance', async () => {
|
||||
const recipeModal = await createRecipeModal();
|
||||
recipeModal.showRecipeDetails(recipeWithMissing);
|
||||
|
||||
const status = document.querySelector('#recipeLorasCount .recipe-status.missing');
|
||||
expect(status).not.toBeNull();
|
||||
expect(status.tagName).toBe('BUTTON');
|
||||
expect(status.type).toBe('button');
|
||||
expect(status.classList.contains('clickable')).toBe(true);
|
||||
expect(status.getAttribute('aria-label')).toBe('Download 1 missing LoRAs');
|
||||
expect(status.title).toBe('Click to download missing LoRAs');
|
||||
// Leading download icon hints the action; the warning glyph was removed
|
||||
// because the red tint + text already encode the state
|
||||
expect(status.querySelector('i').classList.contains('fa-download')).toBe(true);
|
||||
expect(status.querySelector('.fa-exclamation-triangle')).toBeNull();
|
||||
expect(status.textContent).toContain('1 missing');
|
||||
|
||||
// The hover-only tooltip was replaced by the always-visible button styling
|
||||
expect(status.querySelector('.missing-tooltip')).toBeNull();
|
||||
});
|
||||
|
||||
it('opens the download-missing flow when the status button is clicked', async () => {
|
||||
const recipeModal = await createRecipeModal();
|
||||
const downloadSpy = vi
|
||||
.spyOn(recipeModal, 'showDownloadMissingLorasModal')
|
||||
.mockImplementation(() => {});
|
||||
|
||||
recipeModal.showRecipeDetails(recipeWithMissing);
|
||||
|
||||
const status = document.querySelector('#recipeLorasCount .recipe-status.missing');
|
||||
status.click();
|
||||
|
||||
expect(downloadSpy).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it('renders a non-interactive ready badge when every LoRA is available', async () => {
|
||||
const recipeModal = await createRecipeModal();
|
||||
recipeModal.showRecipeDetails(recipeReady);
|
||||
|
||||
const ready = document.querySelector('#recipeLorasCount .recipe-status.ready');
|
||||
expect(ready).not.toBeNull();
|
||||
expect(ready.tagName).toBe('DIV');
|
||||
expect(ready.textContent).toContain('Ready to use');
|
||||
expect(document.querySelector('#recipeLorasCount .recipe-status.missing')).toBeNull();
|
||||
});
|
||||
});
|
||||
@@ -110,6 +110,7 @@ function recipeModalFixture() {
|
||||
</div>
|
||||
<div class="recipe-header-actions" id="recipeHeaderActions">
|
||||
<button class="modal-send-btn" id="sendRecipeBtn"><i class="fas fa-paper-plane"></i></button>
|
||||
<button class="modal-copy-btn" id="copyRecipeSyntaxBtn"><i class="fas fa-copy"></i></button>
|
||||
</div>
|
||||
<div id="recipeTagsContainer"></div>
|
||||
</header>
|
||||
|
||||
@@ -0,0 +1,228 @@
|
||||
import { describe, it, beforeEach, expect, vi } from 'vitest';
|
||||
|
||||
const translateMock = vi.fn((key, params, fallback) => (typeof fallback === 'string' ? fallback : key));
|
||||
|
||||
const loadingManagerStub = {
|
||||
showSimpleLoading: vi.fn(),
|
||||
hide: vi.fn(),
|
||||
show: vi.fn(),
|
||||
restoreProgressBar: vi.fn(),
|
||||
};
|
||||
|
||||
const virtualScrollerStub = {
|
||||
updateSingleItem: vi.fn(),
|
||||
getNavigationState: vi.fn(() => ({
|
||||
index: 0,
|
||||
hasPrev: false,
|
||||
hasNext: false,
|
||||
loadedItems: 1,
|
||||
totalItems: 1,
|
||||
})),
|
||||
getAdjacentItemByFilePath: vi.fn(async () => null),
|
||||
};
|
||||
|
||||
const stateStub = {
|
||||
global: { settings: {}, loadingManager: loadingManagerStub },
|
||||
loadingManager: loadingManagerStub,
|
||||
virtualScroller: virtualScrollerStub,
|
||||
};
|
||||
|
||||
vi.mock('../../../static/js/utils/uiHelpers.js', () => ({
|
||||
showToast: vi.fn(),
|
||||
copyToClipboard: vi.fn(),
|
||||
sendLoraToWorkflow: vi.fn(),
|
||||
sendModelPathToWorkflow: vi.fn(),
|
||||
openCivitaiByMetadata: vi.fn(),
|
||||
stripLoraTags: vi.fn((text) => text),
|
||||
sendPromptToWorkflow: vi.fn(),
|
||||
sendGenParamsToWorkflow: vi.fn(),
|
||||
}));
|
||||
|
||||
vi.mock('../../../static/js/utils/i18nHelpers.js', () => ({
|
||||
translate: translateMock,
|
||||
}));
|
||||
|
||||
vi.mock('../../../static/js/state/index.js', () => ({
|
||||
state: stateStub,
|
||||
}));
|
||||
|
||||
vi.mock('../../../static/js/utils/storageHelpers.js', () => ({
|
||||
setSessionItem: vi.fn(),
|
||||
removeSessionItem: vi.fn(),
|
||||
getStorageItem: vi.fn(() => null),
|
||||
setStorageItem: vi.fn(),
|
||||
}));
|
||||
|
||||
vi.mock('../../../static/js/api/recipeApi.js', () => ({
|
||||
fetchRecipeDetails: vi.fn(),
|
||||
updateRecipeMetadata: vi.fn(() => Promise.resolve({ success: true })),
|
||||
sendRecipeWorkflow: vi.fn(),
|
||||
}));
|
||||
|
||||
vi.mock('../../../static/js/api/apiConfig.js', () => ({
|
||||
MODEL_TYPES: {
|
||||
LORA: 'loras',
|
||||
CHECKPOINT: 'checkpoints',
|
||||
EMBEDDING: 'embeddings',
|
||||
},
|
||||
}));
|
||||
|
||||
function recipeModalFixture() {
|
||||
return `
|
||||
<div id="recipeModal" class="modal">
|
||||
<div class="modal-content">
|
||||
<header class="recipe-modal-header">
|
||||
<h2 id="recipeModalTitle">Recipe Details</h2>
|
||||
<div id="recipeTagsContainer"></div>
|
||||
</header>
|
||||
<div class="modal-body">
|
||||
<div class="recipe-media-column">
|
||||
<div class="recipe-preview-container" id="recipePreviewContainer">
|
||||
<img id="recipeModalImage" src="" alt="Recipe Preview" class="recipe-preview-media">
|
||||
</div>
|
||||
</div>
|
||||
<div class="info-section recipe-bottom-section">
|
||||
<div class="recipe-section-actions">
|
||||
<span id="recipeLorasCount"></span>
|
||||
<button class="action-btn view-loras-btn" id="viewRecipeLorasBtn"></button>
|
||||
</div>
|
||||
<div class="recipe-loras-list" id="recipeLorasList"></div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
`;
|
||||
}
|
||||
|
||||
describe('RecipeModal no-LoRA reason panel', () => {
|
||||
let recipeModal;
|
||||
|
||||
beforeEach(async () => {
|
||||
vi.clearAllMocks();
|
||||
document.body.innerHTML = recipeModalFixture();
|
||||
const { RecipeModal } = await import('../../../static/js/components/RecipeModal.js');
|
||||
recipeModal = new RecipeModal();
|
||||
});
|
||||
|
||||
function sync(recipe) {
|
||||
recipeModal.syncResourcesSection(recipe);
|
||||
return document.getElementById('recipeLorasList');
|
||||
}
|
||||
|
||||
it('shows the base message only when generation genuinely used no LoRAs', () => {
|
||||
const list = sync({
|
||||
id: 'r1',
|
||||
loras: [],
|
||||
import_info: { channel: 'url', reason: 'no_loras_used' },
|
||||
});
|
||||
|
||||
expect(list.querySelector('.no-loras')).not.toBeNull();
|
||||
expect(list.textContent).toContain('No LoRAs associated with this recipe');
|
||||
expect(list.querySelector('details.no-loras-reason')).toBeNull();
|
||||
});
|
||||
|
||||
it('renders a collapsed reason panel from recorded import_info', () => {
|
||||
const list = sync({
|
||||
id: 'r2',
|
||||
loras: [],
|
||||
import_info: {
|
||||
channel: 'batch_import_url',
|
||||
reason: 'api_meta_no_lora_resources',
|
||||
details: {
|
||||
api_meta_keys: ['prompt'],
|
||||
api_model_version_ids: 0,
|
||||
exif_present: false,
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
const details = list.querySelector('details.no-loras-reason');
|
||||
expect(details).not.toBeNull();
|
||||
// Collapsed by default (no `open` attribute).
|
||||
expect(details.hasAttribute('open')).toBe(false);
|
||||
expect(details.querySelector('summary').textContent).toContain('Why no LoRAs?');
|
||||
|
||||
const body = details.querySelector('.no-loras-reason-body');
|
||||
expect(body.textContent).toContain('Batch import (image URL)');
|
||||
expect(body.textContent).toContain('The source API returned no LoRA resource data');
|
||||
expect(body.textContent).toContain('API metadata fields');
|
||||
expect(body.textContent).toContain('prompt');
|
||||
expect(body.textContent).toContain('Model version IDs reported');
|
||||
expect(body.textContent).toContain('Embedded metadata');
|
||||
// Recorded diagnostics are not labeled as inferred.
|
||||
expect(body.querySelector('.no-loras-inferred-note')).toBeNull();
|
||||
});
|
||||
|
||||
it('infers a possible reason for legacy URL recipes without import_info', () => {
|
||||
const list = sync({
|
||||
id: 'r3',
|
||||
loras: [],
|
||||
source_path: 'https://civitai.red/images/139995974',
|
||||
gen_params: { prompt: 'a castle' },
|
||||
});
|
||||
|
||||
const details = list.querySelector('details.no-loras-reason');
|
||||
expect(details).not.toBeNull();
|
||||
const body = details.querySelector('.no-loras-reason-body');
|
||||
expect(body.textContent).toContain('The source API returned no LoRA resource data');
|
||||
// Heuristic results must be labeled as inferred.
|
||||
expect(body.querySelector('.no-loras-inferred-note')).not.toBeNull();
|
||||
});
|
||||
|
||||
it('reports missing embedded metadata for legacy local recipes with no params', () => {
|
||||
const list = sync({
|
||||
id: 'r4',
|
||||
loras: [],
|
||||
source_path: '/data/images/photo.png',
|
||||
gen_params: {},
|
||||
});
|
||||
|
||||
const details = list.querySelector('details.no-loras-reason');
|
||||
expect(details).not.toBeNull();
|
||||
expect(details.querySelector('.no-loras-reason-body').textContent).toContain(
|
||||
'The image has no embedded generation metadata'
|
||||
);
|
||||
});
|
||||
|
||||
it('does not show the panel for legacy local recipes with complete params', () => {
|
||||
const list = sync({
|
||||
id: 'r5',
|
||||
loras: [],
|
||||
source_path: '/data/images/photo.png',
|
||||
gen_params: { prompt: 'a castle', steps: 20, seed: 42 },
|
||||
});
|
||||
|
||||
expect(list.querySelector('details.no-loras-reason')).toBeNull();
|
||||
});
|
||||
|
||||
it('flags ComfyUI workflow sources via has_workflow', () => {
|
||||
const list = sync({
|
||||
id: 'r6',
|
||||
loras: [],
|
||||
has_workflow: true,
|
||||
});
|
||||
|
||||
const details = list.querySelector('details.no-loras-reason');
|
||||
expect(details).not.toBeNull();
|
||||
expect(details.querySelector('.no-loras-reason-body').textContent).toContain(
|
||||
'ComfyUI workflow'
|
||||
);
|
||||
});
|
||||
|
||||
it('escapes HTML in recorded diagnostic values', () => {
|
||||
const list = sync({
|
||||
id: 'r7',
|
||||
loras: [],
|
||||
import_info: {
|
||||
channel: 'url',
|
||||
reason: 'api_meta_no_lora_resources',
|
||||
details: { api_meta_keys: ['<img src=x onerror=alert(1)>'] },
|
||||
},
|
||||
});
|
||||
|
||||
const details = list.querySelector('details.no-loras-reason');
|
||||
expect(details).not.toBeNull();
|
||||
expect(details.innerHTML).not.toContain('<img src=x');
|
||||
expect(details.textContent).toContain('<img src=x onerror=alert(1)>');
|
||||
});
|
||||
});
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user