Make videos on the computer you already own. FreeVideo runs MiniMax H3 in as little as 8 GB of VRAM and 16 GB of RAM, and adapts its acceleration path to your hardware.
Replace person: download its model on demand
Bowen Xuec7cc569ac8a2
diff --git a/__init__.py b/__init__.pyindex d97252d..69298ca 100644--- a/__init__.py+++ b/__init__.py@@ -49,6 +49,8 @@ async def comfy_entrypoint():subtitle_file_routes()from .freevideo_engine.comfy_share import register as share_routesshare_routes()+ from .freevideo_engine.swap_lora import register as swap_lora_routes+ swap_lora_routes()from .freevideo_engine.comfy_metadata import register as workflow_backfillworkflow_backfill()try:diff --git a/freevideo_engine/swap_lora.json b/freevideo_engine/swap_lora.jsonnew file mode 100644index 0000000..e8a9ca7--- /dev/null+++ b/freevideo_engine/swap_lora.json@@ -0,0 +1,21 @@+{+ "format": 1,+ "repo": "Alissonerdx/Minimax-H3-ComfyUI",+ "revision": "fd3dde7b3ec1ae4e09fafc46f000bedcc2db219b",+ "license": "BFS Character Swap Community License 1.1",+ "name": "alissonerdx-v1.1.safetensors",+ "files": [+ {+ "file": "LICENSE_CHARACTER_SWAP.md",+ "target": "LICENSE_CHARACTER_SWAP.md",+ "bytes": 3132,+ "sha256": "d6c36de728b812f9a751b2fdd441951e31fc8ca1e96b17fbef098a5c41c735f4"+ },+ {+ "file": "loras/minimax_h3_character_swap_v1.1_ref2va_fro.safetensors",+ "target": "alissonerdx-v1.1.safetensors",+ "bytes": 80673112,+ "sha256": "ab21167bed71db99ac09527ad1f26f5f3517687ebf2e1f1bd5e91cc0bdf9b9c3"+ }+ ]+}diff --git a/freevideo_engine/swap_lora.py b/freevideo_engine/swap_lora.pynew file mode 100644index 0000000..748bfb3--- /dev/null+++ b/freevideo_engine/swap_lora.py@@ -0,0 +1,220 @@+"""On-demand download of the Replace person LoRA into the LoRA folder.++Nothing here ships in the installer. The catalog (`swap_lora.json`) pins the+Hugging Face revision, and every file's size and sha256; its licence asks that+the licence text travel with the weights, so the licence file is fetched first+and the weights land beside it under the name Replace person looks for.++The transfer is the image pack's: the same measured source order, the user's+download source and proxy settings (Hugging Face or its mirror; a ModelScope+choice falls back to them), resumable partials and sha256 checks. A copy of the+LoRA that is already registered, at any depth of the LoRA folders, is used as it+is and never downloaded again.+"""+import json+from pathlib import Path, PurePosixPath+import threading+import time++from . import disk_space++RESERVE = 256 * 2**20+++class PackError(Exception):+ def __init__(self, reason):+ super().__init__(reason)+ self.reason = reason+++def catalog():+ return json.loads(Path(__file__).with_name('swap_lora.json').read_text(encoding='utf-8'))+++def present(names, spec=None):+ """Whether a registered LoRA name is the Replace person LoRA (by its file name, in any subfolder)."""+ wanted = (spec or catalog())['name'].lower()+ return any(isinstance(n, str) and PurePosixPath(n.replace('\\', '/')).name.lower() == wanted for n in names or ())+++def remote(spec, row):+ """One catalog file on the pinned Hugging Face revision, from the official host or its mirror."""+ from .network import source_url+ path = '/%s/resolve/%s/%s' % (spec['repo'], spec['revision'], row['file'])+ return dict(repo=spec['repo'], revision=spec['revision'], file=row['file'], family='image',+ sha256=row['sha256'], bytes=row['bytes'],+ sources=[dict(id=name, url=source_url('models', name) + path) for name in ('official', 'hf-mirror')])+++def _intact(path, row, check):+ from .depth_reference import digest+ try:+ return path.is_file() and path.stat().st_size == row['bytes'] and digest(path, check) == row['sha256']+ except OSError:+ return False+++def _partial(path):+ return path.with_name(path.name + '.partial')+++def install(folder, names=(), progress=None, check=None, *, engine_root=None, spec=None):+ """Fetch the licence and the LoRA into folder; skip when the LoRA is already registered or on disk."""+ from . import network+ from .image_gen.image_pack import PackError as TransferError, _download_plan, _transfer+ from .failure_details import image_pack_error_code+ from .locking import runtime_lock+ from .paths import data_root+ spec = spec or catalog()+ progress = progress or (lambda value: None)+ check = check or (lambda: None)+ folder = Path(folder)+ weights = folder / spec['files'][-1]['target']+ if present(names, spec) or weights.exists():+ return 'present'+ try:+ lock_root = Path(engine_root) if engine_root is not None else data_root()+ with runtime_lock(lock_root / 'swap-lora-download.lock', inherit=False):+ folder.mkdir(parents=True, exist_ok=True)+ todo = []+ for row in spec['files']:+ check()+ path = folder / row['target']+ if row is spec['files'][-1] and path.exists():+ return 'present'+ if _intact(path, row, check):+ continue+ if path.exists() or path.is_symlink():+ # Not the pinned file: kept under another name, never overwritten.+ network.retain_partial(path, 'rejected')+ todo.append(row)+ total = sum(row['bytes'] for row in todo)+ retained = sum(min(_partial(folder / r['target']).stat().st_size, r['bytes'])+ for r in todo if _partial(folder / r['target']).is_file())+ needed = total - retained + RESERVE+ if total and disk_space.free_bytes(folder) < needed:+ raise PackError('disk_space')+ plan = _download_plan(engine_root)+ plan.update(quiet=True, resource_check=check)+ done = 0+ progress(dict(done=0, total=total))+ for row in todo:+ check()++ def moved(current, size, speed, **kwargs):+ progress(dict(done=done + current, total=total))+ check()+ _transfer(plan, remote(spec, row), folder / row['target'], moved, check)+ # The record of which source the partial came from is only for resuming it.+ _partial(folder / row['target']).with_name(row['target'] + '.partial.source.json').unlink(missing_ok=True)+ done += row['bytes']+ progress(dict(done=done, total=total))+ return 'installed'+ except (PackError, InterruptedError):+ raise+ except TransferError as error:+ raise PackError(error.reason) from error+ except BlockingIOError as error:+ raise PackError('busy') from error+ except Exception as error:+ raise PackError(image_pack_error_code(error)) from error+++def lora_folder():+ import folder_paths+ return Path(folder_paths.get_folder_paths('loras')[0])+++def lora_names():+ import folder_paths+ return folder_paths.get_filename_list('loras')+++class Installer:+ """One background download at a time; the Studio polls `state()`."""++ def __init__(self, folder=None, names=None, engine_root=None):+ self.folder, self.names, self.engine_root = folder or lora_folder, names or lora_names, engine_root+ self.lock = threading.Lock()+ self.stop = threading.Event()+ self.thread = None+ self.value = dict(state='idle', done=0, total=0, reason=None)++ def state(self):+ with self.lock:+ return dict(self.value)++ def _set(self, **kwargs):+ with self.lock:+ self.value.update(kwargs)++ def status(self):+ spec = catalog()+ try:+ found = present(self.names(), spec)+ except Exception:+ found = False+ return dict(name=spec['name'], bytes=sum(r['bytes'] for r in spec['files']), present=found, install=self.state())++ def start(self):+ with self.lock:+ if self.thread is not None and self.thread.is_alive():+ return dict(self.value)+ self.stop = threading.Event()+ self.value = dict(state='running', done=0, total=0, reason=None, started=time.time())+ self.thread = threading.Thread(target=self._run, args=(self.stop,), name='freevideo-swap-lora', daemon=True)+ self.thread.start()+ return dict(self.value)++ def cancel(self):+ self.stop.set()+ return self.state()++ def _run(self, stop):+ def check():+ if stop.is_set():+ raise InterruptedError('cancelled')++ def progress(value):+ self._set(done=value.get('done', 0), total=value.get('total', 0))+ try:+ install(self.folder(), self.names(), progress, check, engine_root=self.engine_root)+ self._set(state='done', reason=None)+ except InterruptedError:+ self._set(state='cancelled', reason=None)+ except PackError as error:+ self._set(state='failed', reason=error.reason)+ except Exception:+ self._set(state='failed', reason='failed')+++def register():+ """GET /freevideo/swap-lora: whether the LoRA is in place and the download state; POST {action: install|cancel}."""+ import asyncio+ from aiohttp import web+ from server import PromptServer+ server = PromptServer.instance+ if server is None or getattr(server, '_freevideo_swap_lora', None) is not None:+ return+ installer = server._freevideo_swap_lora = Installer()++ def reply(value, status=200):+ return web.json_response(value, status=status, headers={'Cache-Control': 'no-store'})++ @server.routes.get('/freevideo/swap-lora')+ async def swap_lora_status(request):+ return reply(await asyncio.to_thread(installer.status))++ @server.routes.post('/freevideo/swap-lora')+ async def swap_lora_install(request):+ try:+ body = await request.json()+ if not isinstance(body, dict) or set(body) != {'action'} or body['action'] not in ('install', 'cancel'):+ raise ValueError('Invalid request')+ except (ValueError, TypeError):+ return reply({'reason': 'failed'}, 400)+ if body['action'] == 'cancel':+ installer.cancel()+ elif not (await asyncio.to_thread(installer.status))['present']:+ installer.start()+ return reply(await asyncio.to_thread(installer.status))diff --git a/pyproject.toml b/pyproject.tomlindex e9fb437..448e585 100644--- a/pyproject.toml+++ b/pyproject.toml@@ -36,4 +36,4 @@ include = ["freevideo_engine*"][tool.setuptools.package-data]"freevideo_engine.prompt_vlm" = ["model.json"]"freevideo_engine.image_gen" = ["image_models.json", "licenses/NOTICE.txt"]-freevideo_engine = ["stage_estimate_params.json", "build-version.txt", "build-identity.json", "release_notes.json", "dependencies.json", "model_files.json", "model_shares.json", "prepared_models.json", "macos_reference_catalog.json", "superseded_tables.json", "bootstrap_versions.json", "curl_windows.json", "git_linux.json", "git_macos.json", "gcc_linux.json", "uv_downloads.json", "torch_downloads.json", "test_prompts.json", "windows_bootstrap.ps1", "assets/*.png", "assets/*.ico", "launcher/*.qml", "launcher/licenses/*.txt", "licenses/*.txt", "licenses/runtime/*.txt", "subtitle_pack.json", "frame_preview_weights.json", "agent/skill/freevideo/*.txt", "agent/skill/freevideo/references/*.txt", "depth_reference_model.json"]+freevideo_engine = ["stage_estimate_params.json", "build-version.txt", "build-identity.json", "release_notes.json", "dependencies.json", "model_files.json", "model_shares.json", "prepared_models.json", "macos_reference_catalog.json", "superseded_tables.json", "bootstrap_versions.json", "curl_windows.json", "git_linux.json", "git_macos.json", "gcc_linux.json", "uv_downloads.json", "torch_downloads.json", "test_prompts.json", "windows_bootstrap.ps1", "assets/*.png", "assets/*.ico", "launcher/*.qml", "launcher/licenses/*.txt", "licenses/*.txt", "licenses/runtime/*.txt", "subtitle_pack.json", "frame_preview_weights.json", "agent/skill/freevideo/*.txt", "agent/skill/freevideo/references/*.txt", "depth_reference_model.json", "swap_lora.json"]diff --git a/web/replace_person.js b/web/replace_person.jsindex a627b77..4f47469 100644--- a/web/replace_person.js+++ b/web/replace_person.js@@ -36,8 +36,9 @@ function videoSeconds(file) {});}-// mount: the Media section body. onChange runs after any change to the state.-export function createReplacePerson({t, api, media, mount, view, onChange = () => {}}) {+// mount: the Media section body. onChange runs after any change to the state; extra (optional) sits under the note,+// shown only while the option is on.+export function createReplacePerson({t, api, media, mount, view, onChange = () => {}, extra = null}) {const stored = () => media.properties?.[KEY];const state = () => { media.properties ??= {}; return media.properties[KEY] ??= {on: false, source: null, person: null, keepSound: false}; };const save = info => { media.graph?.change?.(); onChange(info); paint(); };@@ -69,7 +70,7 @@ export function createReplacePerson({t, api, media, mount, view, onChange = () =soundInput.onchange = () => { state().keepSound = soundInput.checked; save(); };source.box.classList.add('fv-swap-source'); person.box.classList.add('fv-swap-person');slots.append(source.box, person.box, sound);- mount.prepend(toggle.row, slots, note);+ mount.prepend(...[toggle.row, slots, note, extra].filter(Boolean));let busy = false;async function choose(kind, file) {if (busy || media.isUploading) return;diff --git a/web/studio.css b/web/studio.cssindex a29409c..9935c12 100644--- a/web/studio.css+++ b/web/studio.css@@ -265,4 +265,14 @@.fv-studio .fv-swap-sound{display:flex;align-items:center;gap:8px;grid-column:1/-1;white-space:nowrap;font-size:var(--fv-small,13px)}.fv-studio .fv-swap-sound:has(input:disabled){opacity:.4}.fv-studio .fv-swap-note{margin-top:8px}+.fv-studio .fv-swap-download{margin-top:8px;font-size:var(--fv-micro);color:var(--fv-muted)}+.fv-studio .fv-swap-download[hidden],.fv-studio :not(.fv-swap-on)>.fv-swap-download,.fv-studio .fv-swap-download [hidden]{display:none}+.fv-studio .fv-swap-download[data-state=failed],.fv-studio .fv-swap-download[data-state=cancelled]{color:var(--fv-danger)}+.fv-studio .fv-swap-download-line{display:flex;align-items:center;gap:10px;min-height:22px}+.fv-studio .fv-swap-download-text{flex:1;min-width:0;overflow-wrap:anywhere}+.fv-studio .fv-swap-retry{flex:none;min-height:0;padding:3px 12px;font-size:var(--fv-micro)}+.fv-studio .fv-swap-meter{position:relative;height:3px;margin-top:6px;border-radius:2px;background:var(--fv-border);overflow:hidden}+.fv-studio .fv-swap-meter>i{position:absolute;inset:0 auto 0 0;width:0;border-radius:inherit;background:var(--fv-accent,#6db8fa);transition:width .4s ease-out}+.fv-studio .fv-swap-meter[data-indeterminate=true]>i{width:32%;animation:fv-swap-sweep 1.4s ease-in-out infinite}+@keyframes fv-swap-sweep{from{transform:translateX(-100%)}to{transform:translateX(320%)}}@media (max-width:480px){.fv-studio .fv-swap-slots{grid-template-columns:1fr}.fv-studio .fv-swap-source{order:1}.fv-studio .fv-swap-sound{order:2}.fv-studio .fv-swap-person{order:3}}diff --git a/web/studio.js b/web/studio.jsindex 52984d6..1ff0478 100644--- a/web/studio.js+++ b/web/studio.js@@ -46,7 +46,8 @@ import { registerTourWorkspace, triggerFeatureTour, offerVersionTour } from './fimport { createStudioLength, savedSeconds } from './studio_length.js?v=20261011-length';import { firstFrameRow } from './first_frame_row.js';import { createReplacePerson, swapMissingText } from './replace_person.js';-import { swapState, swapMissing, effectiveRows, prepareSwapLora, releaseSwapLora, SWAP_LORA } from './replace_state.js';+import { swapState, swapMissing, effectiveRows, prepareSwapLora, releaseSwapLora } from './replace_state.js';+import { swapLoraDownload } from './swap_lora.js';import { createStudioChain, chainPosition, chainParts, chainSplit, composePartText, readChainResult, sumPartEstimates, singleRunSnapshot } from './studio_chain.js?v=20261019-words';import { activeOriginal, checkOriginal, lockMark, blockOriginal, originalBlocked, usesOriginal, referenceRow } from './audio_original.js';import { waitingText } from './chain_support.js';@@ -986,13 +987,16 @@ export function openStudio(node, {extendFrom = null} = {}) {const loraNode = connectedLora?.properties?.[CREATED_BY_PANEL] ? pendingLoras(node, connectedLora) : connectedLora || pendingLoras(node);// Replace person: its LoRA row is found among the registered names (it may sit in a subfolder), a row the user had// switched off is switched on for the run, and everything done is undone when the option goes off.- // Returns '' when all is well, else the line to show; runs one at a time.+ // Not installed: it is downloaded (progress in the panel), then added. Returns '' when all is well, else the line+ // to show; runs one at a time.let swapLoraBusy = Promise.resolve('');- const swapLoraText = reason => reason === 'missing'- ? t(`"Replace person" needs the ${SWAP_LORA} LoRA in the models/loras folder.`, `“替换人物”需要把 ${SWAP_LORA} 放进 models/loras 文件夹。`)- : reason === 'ambiguous' ? t(`More than one ${SWAP_LORA} was found in models/loras. Add the one to use under "LoRA".`, `models/loras 中有多个 ${SWAP_LORA},请在“LoRA”一栏添加要使用的那个。`)+ const swapLoraText = reason => reason === 'ambiguous'+ ? t('More than one Replace person model was found. Add the one to use under "LoRA".', '找到多个替换人物模型,请在“LoRA”一栏添加要使用的那个。'): t('Could not read the LoRA list. Try again.', '无法读取 LoRA 列表,请重试。');- async function applySwapLora() {+ let swapPanel = null;+ const swapDownload = swapLoraDownload({t, api, onReady: () => ensureSwapLora().then(problem => swapPanel?.notify(problem))});+ cleanup.push(() => swapDownload.dispose());+ async function applySwapLora(retry = false) {const state = mediaNode?.properties?.freevideo_replace_person;if (!state || !loraNode || !widget(loraNode, 'adapters')) return '';const current = value(loraNode, 'adapters') || '[]';@@ -1008,22 +1012,22 @@ export function openStudio(node, {extendFrom = null} = {}) {if (!state.on) return '';const now = value(loraNode, 'adapters') || '[]';const result = prepareSwapLora(now, names, record);+ if (!result.ok && result.reason === 'missing') return (await swapDownload.need(retry)) || swapLoraText('unreadable');if (!result.ok) return swapLoraText(result.reason);state.lora = result.record;if (result.adapters !== now) { set(loraNode, 'adapters', result.adapters); window.dispatchEvent(new CustomEvent('freevideo-loras', {detail: loraNode.id})); }return '';}- const ensureSwapLora = () => (swapLoraBusy = swapLoraBusy.then(applySwapLora, applySwapLora));- let swapPanel = null;+ const ensureSwapLora = (retry = false) => (swapLoraBusy = swapLoraBusy.then(() => applySwapLora(retry), () => applySwapLora(retry)));function swapChanged(info) {mediaHint.textContent = swapState(mediaNode) ? t('Source video, person image', '源视频、人物图') : t('Reference images, first and last frames', '参考图、首帧、尾帧');// Switching the option only changes which media the prompt reads: its pictures are re-bound, never renumbered.syncReferencePrompt(node, t, info?.toggled === true); paintMediaHint();- ensureSwapLora().then(problem => { if (problem) swapPanel?.notify(problem); });+ ensureSwapLora(info?.toggled === true).then(problem => { if (problem && !swapDownload.shown) swapPanel?.notify(problem); });window.dispatchEvent(new CustomEvent('freevideo-media', {detail: mediaNode.id}));}if (mediaNode?.freevideoCreateMediaEditor) {- const swap = swapPanel = createReplacePerson({t, api, media: mediaNode, mount: mediaMount, view, onChange: swapChanged});+ const swap = swapPanel = createReplacePerson({t, api, media: mediaNode, mount: mediaMount, view, onChange: swapChanged, extra: swapDownload.element});cleanup.push(() => swap.dispose());if (swapState(mediaNode)) { mediaHint.textContent = t('Source video, person image', '源视频、人物图'); mediaDetails.open = true; }}@@ -1912,7 +1916,7 @@ export function openStudio(node, {extendFrom = null} = {}) {const sourceState = source ? await extendSourceState(api, source) : 'ok';if (sourceState !== 'ok') throw new Error(extendSourceProblem(t, sourceState));if (source && lengthPlan?.count > 1) lengthOptions.after = {work: source.video};- const swapProblem = await ensureSwapLora();+ const swapProblem = await ensureSwapLora(true);if (swapProblem) { status.dataset.error = 'true'; status.textContent = swapProblem; return; }// Only serialization briefly locks the editor. Network submission// and all GPU execution leave the next draft fully editable.diff --git a/web/swap_lora.js b/web/swap_lora.jsnew file mode 100644index 0000000..932e740--- /dev/null+++ b/web/swap_lora.js@@ -0,0 +1,84 @@+// Replace person's model, downloaded on demand into the LoRA folder (GET/POST /freevideo/swap-lora).+// The download starts on its own once the option is on and the model is not found (about 80 MB, part of the+// option, like the upscaler that a two-pass run fetches); progress, failure and retry show in the panel.+const el = (tag, cls, text) => { const e = document.createElement(tag); if (cls) e.className = cls; if (text != null) e.textContent = text; return e; };+const mb = bytes => `${Math.max(0, Math.round((bytes || 0) / 1e6))} MB`;+const POLL_MS = 500, DONE_MS = 4000;++export function swapLoraFailureText(reason, t) {+ const text = {+ offline: ['The network is unavailable, so the Replace person model could not be downloaded.', '网络不通,无法下载替换人物模型。'],+ source_failed: ["The Replace person model download didn't finish. Check the network and try again.", '替换人物模型没有下载完成,请检查网络后重试。'],+ integrity_failed: ['The downloaded Replace person model did not pass verification. Try again.', '下载的替换人物模型未通过校验,请重试。'],+ write_failed: ['The Replace person model could not be saved to disk.', '替换人物模型无法保存到磁盘。'],+ disk_space: ['Not enough disk space to download the Replace person model.', '磁盘空间不足,无法下载替换人物模型。'],+ busy: ['The Replace person model is being downloaded elsewhere. Try again shortly.', '替换人物模型正在别处下载,请稍后重试。'],+ }[reason] || ["The Replace person model download didn't finish. Try again.", '替换人物模型没有下载完成,请重试。'];+ return t(...text);+}++// onReady runs once a download has finished, so the caller can add the model to the run.+export function swapLoraDownload({t, api, onReady = () => {}}) {+ const box = el('div', 'fv-swap-download'); box.hidden = true; box.setAttribute('role', 'status');+ const line = el('div', 'fv-swap-download-line'), text = el('span', 'fv-swap-download-text');+ const retry = el('button', 'fv-swap-retry', t('Retry', '重试')); retry.type = 'button'; retry.hidden = true;+ const meter = el('div', 'fv-swap-meter'), fill = el('i'); meter.append(fill);+ line.append(text, retry); box.append(line, meter);+ let install = {state: 'idle'}, timer = 0, doneTimer = 0, disposed = false;+ const running = () => install.state === 'running';+ function paint() {+ const failed = install.state === 'failed' || install.state === 'cancelled', done = install.state === 'done';+ box.hidden = !(running() || failed || (done && doneTimer));+ box.dataset.state = install.state;+ retry.hidden = !failed; meter.hidden = !running();+ const total = install.total || 0;+ meter.dataset.indeterminate = String(!total);+ fill.style.width = total ? `${Math.min(100, 100 * (install.done || 0) / total).toFixed(1)}%` : '';+ text.textContent = running()+ ? (total ? t(`Downloading the Replace person model · ${mb(install.done)} / ${mb(total)}`, `正在下载替换人物模型 · ${mb(install.done)} / ${mb(total)}`)+ : t('Downloading the Replace person model…', '正在下载替换人物模型…'))+ : failed ? swapLoraFailureText(install.reason, t)+ : t('The Replace person model is ready.', '替换人物模型已就绪。');+ }+ function take(value) {+ const before = install.state;+ install = value?.install || {state: 'idle'};+ if (value?.present && !running() && install.state !== 'done') install = {state: 'idle'};+ if (install.state === 'done' && before === 'running') {+ clearTimeout(doneTimer); doneTimer = setTimeout(() => { doneTimer = 0; paint(); }, DONE_MS);+ paint(); onReady();+ } else paint();+ clearTimeout(timer);+ if (running() && !disposed) timer = setTimeout(poll, POLL_MS);+ }+ async function call(options) {+ const response = await api.fetchApi('/freevideo/swap-lora', {cache: 'no-store', ...options});+ if (!response.ok) throw new Error(response.statusText);+ return response.json();+ }+ async function poll() {+ if (disposed) return;+ try { take(await call()); }+ catch { if (!disposed) timer = setTimeout(poll, POLL_MS * 4); }+ }+ async function start() {+ install = {state: 'running', done: 0, total: 0}; paint();+ try { take(await call({method: 'POST', headers: {'Content-Type': 'application/json'}, body: JSON.stringify({action: 'install'})})); }+ catch { install = {state: 'failed', reason: 'failed'}; paint(); }+ }+ retry.onclick = () => start();+ return {+ element: box,+ // The model is not among the LoRAs: start the download unless it runs, or ended in a failure the panel shows+ // (retry: start again, for a Generate click or the option switched on). Returns the line a Generate click shows.+ async need(retry = false) {+ const failed = install.state === 'failed' || install.state === 'cancelled';+ if (!running() && (retry || !failed)) await start();+ return running() ? t('The Replace person model is still downloading. Generate when it finishes.', '替换人物模型正在下载,下载完成后才能生成。')+ : install.state === 'failed' || install.state === 'cancelled' ? swapLoraFailureText(install.reason, t) : '';+ },+ // True while the panel shows the download or its failure, so no second line repeats it.+ get shown() { return !box.hidden && install.state !== 'done'; },+ dispose() { disposed = true; clearTimeout(timer); clearTimeout(doneTimer); },+ };+}