Skip to content

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.

Download guidance: say what a download is and how long it takes before it starts

Bowen Xuefc5707fadb0c
diff --git a/freevideo_engine/download_settings.py b/freevideo_engine/download_settings.py
index 2340294..a06fb78 100644
--- a/freevideo_engine/download_settings.py
+++ b/freevideo_engine/download_settings.py
@@ -39,6 +39,42 @@ def read(path):
return value
+SPEED_FILE = 'download-speed.json'
+SPEED_MIN_BYTES = 32 * 2**20
+
+
+def record_speed(root, size, seconds):
+ """Remember how fast the last large download ran, to say how long the next one takes."""
+ if not (size >= SPEED_MIN_BYTES and seconds >= 1.5):
+ return
+ path = Path(root) / SPEED_FILE
+ rate = size / seconds
+ try:
+ old = observed_speed(root)
+ save(path, dict(bytes_per_second=rate if old is None else (old + rate) / 2, updated_at=time.time()))
+ except OSError:
+ pass # A missing estimate only hides the time, never stops a download.
+
+
+def observed_speed(root):
+ """Bytes per second of recent real downloads, else the best connected source of the last speed test."""
+ try:
+ rate = json.loads(io_path(Path(root) / SPEED_FILE).read_text(encoding='utf-8')).get('bytes_per_second')
+ if isinstance(rate, (int, float)) and math.isfinite(rate) and rate > 0:
+ return float(rate)
+ except (OSError, ValueError, AttributeError):
+ pass
+ try:
+ rows = [r for family in read(Path(root) / 'download-settings.json').get('probe', {}).get('sources', {}).values()
+ for r in family if r.get('ok') and r.get('speed_measured') is not False]
+ rates = [r['bytes_per_second'] for r in rows
+ if isinstance(r.get('bytes_per_second'), (int, float)) and math.isfinite(r['bytes_per_second'])
+ and r['bytes_per_second'] > 0]
+ return float(max(rates)) if rates else None
+ except (OSError, ValueError, AttributeError, TypeError):
+ return None
+
+
def preference(root, source=None, *, proxy_mode=None):
if source is not None and source not in CHOICES:
raise ValueError('Choose Auto, Hugging Face, HF Mirror or ModelScope')
diff --git a/freevideo_engine/image_gen/service.py b/freevideo_engine/image_gen/service.py
index c3ac98c..a2d33bb 100644
--- a/freevideo_engine/image_gen/service.py
+++ b/freevideo_engine/image_gen/service.py
@@ -14,6 +14,7 @@ import time
import uuid
from . import image_pack
+from ..download_settings import observed_speed
from .failure import Context, ERRORS, FailureError, MESSAGE_ZH, NO_REPORT, STAGES, classify_exception
BODY_LIMIT = 64 * 1024
@@ -113,6 +114,7 @@ class Service:
self.queue_thread = None
self.queue_wake = threading.Event()
self.finished = OrderedDict()
+ self.pack_installer = None
atexit.register(self.close)
@staticmethod
@@ -131,7 +133,37 @@ class Service:
checking=not ready and image_pack.checking(machine['model_root']),
downloading=not ready and image_pack.downloading(machine['model_root'], engine_root),
bytes=sum(row['bytes'] for row in spec['groups']['image']), busy=self.busy(),
- max_images=MAX_IMAGES)
+ max_images=MAX_IMAGES, install=self.pack_state(ready),
+ bytes_per_second=None if ready else observed_speed(engine_root))
+
+ def pack_state(self, ready):
+ """Progress of the download this page started, in both languages for a failure."""
+ installer = self.pack_installer
+ if ready or installer is None:
+ return None
+ from ..failure_details import image_pack_failure
+ value = installer.state()
+ row = dict(state=value['state'], done=value.get('done', 0), total=value.get('total', 0),
+ bytes_per_second=round(value.get('bytes_per_second', 0)))
+ if value['state'] == 'failed':
+ row.update(reason=value.get('reason'), message_en=image_pack_failure(value.get('reason'))['detail'],
+ message_zh=image_pack_failure(value.get('reason'), zh=True)['detail'])
+ return row
+
+ def pack_action(self, action):
+ """Start or pause the image model download from the page; it yields to a running video."""
+ engine_root, machine = self.installation()
+ root = machine['model_root']
+ with self.mutex:
+ installer = self.pack_installer
+ if action == 'cancel':
+ if installer is not None:
+ installer.cancel()
+ elif not image_pack.ready(root) and not image_pack.downloading(root, engine_root):
+ if installer is None or installer.root != root or installer.engine_root != engine_root:
+ installer = self.pack_installer = image_pack.Installer(root, engine_root=engine_root, busy=self.video_busy)
+ installer.start('install', background=True)
+ return self.info()
def request(self, value):
if not isinstance(value, dict):
@@ -859,6 +891,8 @@ def register():
result = service.status(value.get('job'))
elif name == 'cancel':
result = service.cancel(value.get('job'))
+ elif name in ('pack-install', 'pack-cancel'):
+ result = service.pack_action(name.split('-')[1])
else:
result = service.start(name, value)
return web.json_response(result)
diff --git a/freevideo_engine/launcher/Main.qml b/freevideo_engine/launcher/Main.qml
index 622cfec..dee2e39 100644
--- a/freevideo_engine/launcher/Main.qml
+++ b/freevideo_engine/launcher/Main.qml
@@ -66,6 +66,27 @@ ApplicationWindow {
function sourceName(value) { return ({"auto": t("Automatic", "自动选择"), "official": "Hugging Face", "hf-mirror": t("HF Mirror", "HF 镜像"), "modelscope": t("ModelScope", "魔搭")})[value] || value }
function number(n) { return typeof n === "number" && isFinite(n) }
function fraction(row) { return row && number(row.total) && row.total > 0 && number(row.done) && row.done <= row.total ? row.done / row.total : -1 }
+ function gb(n) { return n >= 1e9 ? (n / 1e9).toFixed(1) + "\u00a0GB" : Math.max(1, Math.round(n / 1e6)) + "\u00a0MB" }
+ // "6.0 GB · about 12 min"; the time only when a real download speed has been measured.
+ function sizeAndTime(n, rate) {
+ var size = gb(n), speed = rate > 0 ? rate : s.bytes_per_second
+ if (!(speed > 0) || !(n > 0)) return size
+ var seconds = n / speed, minutes = Math.ceil(seconds / 60)
+ return size + " · " + (seconds >= 60 ? t("about " + minutes + " min", "约 " + minutes + " 分钟") : t("under 1 min", "不到 1 分钟"))
+ }
+ // The home-page line for the prompt model: the suggestion, then progress, a pause or the reason it stopped.
+ function promptModelLine() {
+ var m = s.prompt_model, total = gb(m.total_bytes), done = gb(m.downloaded_bytes)
+ if (m.busy) {
+ var rate = m.install.bytes_per_second, left = m.total_bytes - m.install.done
+ var more = rate > 0 || s.bytes_per_second > 0 ? sizeAndTime(left, rate).split(" · ")[1] : ""
+ return t("Downloading the prompt model · ", "正在下载提示词模型 · ") + gb(m.install.done) + " / " + total + (more ? " · " + more : "")
+ }
+ if (m.failure) return m.failure
+ if (m.install.state === "cancelled") return t("Prompt model download paused · ", "提示词模型下载已暂停 · ") + done + " / " + total
+ return t("You can also download the prompt model (", "可以再下载提示词模型(") + sizeAndTime(m.total_bytes).replace(" · ", t(", ", ","))
+ + t(") to refine prompts before generating.", "),生成前会自动完善提示词。")
+ }
function bytes(n) {
// macOS counts in decimal units like Finder: 1.26 TB, 64.4 GB.
if (s.decimal_sizes) {
@@ -634,20 +655,37 @@ ApplicationWindow {
FText { visible: !!s.offline.detail; text: s.offline.detail + (number(s.offline.total) ? " · " + bytes(s.offline.done) + " / " + bytes(s.offline.total) : ""); color: theme.muted; font.pixelSize: theme.micro; Layout.fillWidth: true }
}
FCard {
- visible: !manualEnvironment && !offlineSelected; Layout.fillWidth: true; padding: 16
- FSwitch {
- objectName: "samplingCaches"; Layout.fillWidth: true
- text: t("Prepare all quality levels", "提前下载全部质量档位")
- detail: t("Optional sampling caches · ", "可选采样缓存 · ") + bytes(s.sampling_cache_bytes)
- checked: !!s.form.sampling_caches; enabled: !s.busy
- onToggled: backend.edit("sampling_caches", checked)
+ objectName: "aheadCard"
+ visible: !manualEnvironment && !offlineSelected; Layout.fillWidth: true; padding: 16; spacing: 12
+ FText { text: t("Download ahead", "提前下载"); font.weight: Font.DemiBold; Layout.fillWidth: true }
+ RowLayout {
+ Layout.fillWidth: true; spacing: 14
+ FCheck {
+ objectName: "samplingCaches"; Layout.fillWidth: true
+ text: t("Sampling data for all quality levels", "全部质量档位的采样数据")
+ checked: !!s.form.sampling_caches; enabled: !s.busy
+ onToggled: backend.edit("sampling_caches", checked)
+ }
+ FText { objectName: "samplingCachesSize"; color: theme.muted; text: win.sizeAndTime(s.sampling_cache_bytes) }
+ }
+ RowLayout {
+ objectName: "promptModelRow"
+ visible: !!s.prompt_model && !s.prompt_model.ready
+ Layout.fillWidth: true; spacing: 14
+ FCheck {
+ objectName: "promptModelSwitch"; Layout.fillWidth: true
+ text: t("Prompt model", "提示词模型")
+ checked: !!s.form.prompt_model && s.prompt_model.enough_disk; enabled: !s.busy && s.prompt_model.enough_disk
+ onToggled: backend.edit("prompt_model", checked)
+ }
+ FText {
+ objectName: "promptModelSize"; color: theme.muted
+ text: s.prompt_model.enough_disk ? win.sizeAndTime(s.prompt_model.total_bytes) : win.gb(s.prompt_model.total_bytes) + " · " + t("Not enough disk space", "磁盘空间不足")
+ }
}
- }
- FCard {
- objectName: "imageModelCard"
- visible: Qt.platform.os !== "osx" && !!s.image_pack && s.image_pack.total_bytes > 0 && s.image_pack.state !== "ready"
- Layout.fillWidth: true; padding: 16
RowLayout {
+ objectName: "imageModelCard"
+ visible: Qt.platform.os !== "osx" && !!s.image_pack && s.image_pack.total_bytes > 0 && s.image_pack.state !== "ready"
Layout.fillWidth: true; spacing: 14
FCheck {
objectName: "imageModelSwitch"; Layout.fillWidth: true
@@ -657,7 +695,7 @@ ApplicationWindow {
}
FText {
objectName: "imageModelSize"; color: theme.muted
- text: s.image_pack.enough_disk ? bytes(s.image_pack.total_bytes).replace(" ", "\u00a0") : t("Not enough disk space", "磁盘空间不足")
+ text: s.image_pack.enough_disk ? win.sizeAndTime(s.image_pack.total_bytes) : win.gb(s.image_pack.total_bytes) + " · " + t("Not enough disk space", "磁盘空间不足")
}
}
}
@@ -922,6 +960,27 @@ ApplicationWindow {
fraction: s.image_pack.install.total > 0 ? s.image_pack.install.done / s.image_pack.install.total : -1
}
}
+ FCard {
+ objectName: "promptModelCard"
+ visible: !!s.prompt_model && !s.prompt_model.ready && (s.prompt_model.suggest || s.prompt_model.busy
+ || ["failed", "cancelled"].indexOf(s.prompt_model.install.state) >= 0)
+ Layout.fillWidth: true; padding: 16; spacing: 10
+ FText {
+ objectName: "promptModelText"; Layout.fillWidth: true; wrapMode: Text.WordWrap
+ text: win.promptModelLine()
+ }
+ FMeter {
+ objectName: "promptModelProgress"; visible: s.prompt_model.busy; Layout.fillWidth: true; active: visible
+ fraction: s.prompt_model.install.total > 0 ? s.prompt_model.install.done / s.prompt_model.install.total : -1
+ }
+ Flow {
+ Layout.fillWidth: true; spacing: 8
+ FButton { objectName: "promptModelDownload"; visible: !s.prompt_model.busy
+ text: s.prompt_model.suggest ? t("Download", "下载") : t("Resume", "继续"); enabled: !s.busy; onClicked: backend.promptModelAction("install") }
+ FButton { objectName: "promptModelPause"; visible: s.prompt_model.busy; text: t("Pause", "暂停"); onClicked: backend.promptModelAction("cancel") }
+ FButton { objectName: "promptModelDismiss"; visible: s.prompt_model.suggest; text: t("Don't ask again", "不再提示"); flat: true; onClicked: backend.dismissPromptHint() }
+ }
+ }
}
Item { height: 18 }
diff --git a/freevideo_engine/launcher_session.py b/freevideo_engine/launcher_session.py
index 1536217..378778c 100644
--- a/freevideo_engine/launcher_session.py
+++ b/freevideo_engine/launcher_session.py
@@ -80,7 +80,7 @@ class Session:
action_notice = ''
pending_update = None
pending_check = None
- upgrade = image_installer = None
+ upgrade = image_installer = prompt_installer = None
model_switch = None
language = 'en'
@@ -103,7 +103,7 @@ class Session:
url='http://127.0.0.1:8188', models='', model_dirs=[], model_method='auto', environment_method='auto',
separate=False, repair=False, new_comfy=True, offline_runtime='', offline_models=[],
imported_archives=[], kept_archives=[], sampling_caches=not saved.get('installation'),
- image_model=False)
+ image_model=False, prompt_model=False, prompt_hint_dismissed=False)
self.form['lan_access'] = False
self.form.update({k: v for k, v in saved.items() if k in self.form})
if 'environment_method' not in saved and self.form['offline_runtime']:
@@ -134,7 +134,7 @@ class Session:
self.tail = Tail()
self.log_source = None
self.model_groups = []
- self.image_installer = None
+ self.image_installer = self.prompt_installer = None
self.download_export = self.download_error = self.download_error_key = ''
self._download_view = None
self.browser_attempted = False
@@ -203,7 +203,7 @@ class Session:
return bool(self.controller.busy or self.importer.busy or self.cleaner.busy
or self.archives_busy or self.closing or self.upgrade and self.upgrade.active
or self.model_switch or self.engine_updating
- or self.image_installer and self.image_installer.busy)
+ or self.background_download_busy())
def can_manage(self):
return not (self.task_busy() or self.update_intent)
@@ -263,7 +263,7 @@ class Session:
if self.controller.busy or self.importer.busy or self.cleaner.busy or self.archives_busy:
self.explain_busy()
return
- if key in ('separate', 'repair', 'new_comfy', 'sampling_caches', 'lan_access', 'image_model'):
+ if key in ('separate', 'repair', 'new_comfy', 'sampling_caches', 'lan_access', 'image_model', 'prompt_model', 'prompt_hint_dismissed'):
value = bool(value)
if key == 'url':
value = local_url(str(value))
@@ -480,7 +480,7 @@ class Session:
return
if self.cleaner.busy or self.archives_busy:
return
- if self.image_installer and self.image_installer.busy and (
+ if self.background_download_busy() and (
name == 'setup' or name == 'update-engine'
or name == 'retry' and self.retry_kind() != 'launch'
or name == 'primary' and self.page != 'launcher'):
@@ -625,7 +625,7 @@ class Session:
return (bool(self.selected) and getattr(self.controller, 'fixed_environment', False) is not True
and not (self.controller.busy or self.importer.busy or self.cleaner.busy or self.archives_busy or self.closing
or self.engine_updating or self.upgrade.active or self.model_switch
- or self.image_installer and self.image_installer.busy))
+ or self.background_download_busy()))
def repair_unavailable(self):
"""Why Repair is missing: it appears once a task ends, never in an offline
@@ -781,6 +781,14 @@ class Session:
def start_image_model_after_install(self):
"""The installer's "also install the image model": once ComfyUI opens, the download runs in the background."""
+ if self.form['prompt_model'] and self.installation_engine() and self.controller.state.get('status') == 'open' \
+ and not self.controller.busy and not (self.prompt_installer and self.prompt_installer.busy):
+ from .prompt_vlm import assets
+ if not assets.ready(self._image_location()[1]):
+ self.prompt_model_action('install')
+ if self.prompt_installer and self.prompt_installer.busy or assets.ready(self._image_location()[1]):
+ self.form['prompt_model'] = False
+ self.persist()
if (not self.form['image_model'] or sys.platform == 'darwin' or not self.installation_engine()
or self.controller.state.get('status') != 'open' or self.controller.busy):
return
@@ -791,6 +799,57 @@ class Session:
self.form['image_model'] = False
self.persist()
+ def background_download_busy(self):
+ return bool(self.image_installer and self.image_installer.busy or self.prompt_installer and self.prompt_installer.busy)
+
+ def prompt_model_action(self, action):
+ from .prompt_vlm import installer as prompt_installer
+ if action == 'cancel':
+ if self.prompt_installer:
+ self.prompt_installer.cancel()
+ return
+ if (self.controller.busy or self.importer.busy or self.cleaner.busy or self.archives_busy
+ or self.closing or self.engine_updating or self.update_intent or self.upgrade.active or self.model_switch
+ or self.updater and self.updater.busy or not self.installation_engine()):
+ return
+ engine = self._image_location()[1]
+ if self.prompt_installer and self.prompt_installer.busy:
+ return
+ if not (self.prompt_installer and self.prompt_installer.root == engine):
+ self.prompt_installer = prompt_installer.Installer(engine, busy=self.generating)
+ self.prompt_installer.start()
+
+ def prompt_model_view(self):
+ """The prompt model as a row of the download card and as the suggestion on the home page."""
+ from .prompt_vlm import assets
+ spec = assets.catalog()
+ total = sum(row['bytes'] for row in spec['files'])
+ engine = self._image_location()[1] if self.installation_engine() else None
+ ready = bool(engine) and assets.ready(engine)
+ installer = self.prompt_installer
+ active = installer.state() if installer and engine and installer.root == engine else {}
+ busy = bool(active and installer.busy)
+ try:
+ folder = Path(self.form['destination'] if self.form['new_comfy'] else self.form['comfy'])
+ if engine:
+ folder = engine
+ enough = disk_space.free_bytes(folder.expanduser()) >= total + 2 * 2**30
+ except Exception: # A page reading the disk must never fail to draw.
+ enough = True
+ failure = ''
+ if active.get('state') == 'failed':
+ failure = {'disk_space': self.t('Not enough disk space.', '磁盘空间不足。'),
+ 'busy': self.t('Another download of this model is running.', '这个模型正在被另一处下载。')}.get(
+ active.get('reason'), self.t('The download stopped. Resume to continue.', '下载中断了,点继续可接着下载。'))
+ return dict(ready=ready, total_bytes=total, enough_disk=enough, busy=busy, install=active, failure=failure,
+ downloaded_bytes=active.get('done', 0), title=self.t(*NAMES['text']),
+ suggest=bool(engine) and not ready and not busy and enough and not self.form['prompt_hint_dismissed']
+ and active.get('state') not in ('failed', 'cancelled'))
+
+ def dismiss_prompt_hint(self):
+ self.form['prompt_hint_dismissed'] = True
+ self.persist()
+
def upgrade_model(self):
"""The user's one consent: download int8 beside the current model, switch, then release the old one.
@@ -1142,12 +1201,15 @@ class Session:
return
if self._open_release_page():
return
- if (self.image_installer and self.image_installer.busy and not self.controller.busy
+ if (self.background_download_busy() and not self.controller.busy
and not self.importer.busy and not self.cleaner.busy and not self.archives_busy
and not self.closing and not self.upgrade.active and not self.model_switch):
# An explicit update goes first. The image model download is the long, quiet kind and
# keeps what it has; it carries on from there when the user continues it.
- self.image_installer.cancel()
+ if self.image_installer:
+ self.image_installer.cancel()
+ if self.prompt_installer:
+ self.prompt_installer.cancel()
if self.task_busy() or self.updater and self.updater.busy:
self.pending_update = (token, source)
self.action_notice = 'update_queued'
@@ -1495,6 +1557,10 @@ class Session:
self.image_installer.cancel()
if self.image_installer.thread:
self.image_installer.thread.join(5)
+ if self.prompt_installer:
+ self.prompt_installer.cancel()
+ if self.prompt_installer.thread:
+ self.prompt_installer.thread.join(5)
self.controller.close()
from .launcher_bridge import remove
remove(self.bridge)
@@ -2045,6 +2111,12 @@ class Session:
rate='%.1f MiB/s' % (item['bytes_per_second']/2**20) if item.get('bytes_per_second') else ''))
image_pack = self.image_pack_view()
image_pack['enough_disk'] = self.image_disk_fits(image_pack['total_bytes'])
+ prompt_model = self.prompt_model_view()
+ try:
+ from .download_settings import observed_speed
+ speed = observed_speed(self.engine_root()) or 0
+ except Exception:
+ speed = 0
if image_pack['visible'] and 'image' not in by_id:
models.append(dict(id='image', title=image_pack['title'], state=image_pack['state'],
detail=image_pack['detail'], done=image_pack['downloaded_bytes'],
@@ -2156,6 +2228,7 @@ class Session:
if inspection_read_error:
download_state.update(error=self.t(*DOWNLOAD_COPY['error_read']), needs_check=True)
return plain_data(dict(download_list=download_state, sampling_cache_bytes=total_bytes(), version=__version__, image_pack=image_pack,
+ prompt_model=prompt_model, bytes_per_second=speed,
disk=disk, decimal_sizes=sys.platform == 'darwin', zh=self.language.startswith('zh'), form=dict(self.form),
page=self.page, status=row.get('status', 'idle'), busy=busy, working=working,
action_notice=self.t(*ACTION_COPY[self.action_notice]) if self.action_notice else '',
diff --git a/freevideo_engine/launcher_settings.py b/freevideo_engine/launcher_settings.py
index 4b80a48..12314a7 100644
--- a/freevideo_engine/launcher_settings.py
+++ b/freevideo_engine/launcher_settings.py
@@ -38,7 +38,7 @@ def sanitize(value):
extra = value.get('extra_model_dirs', []) if isinstance(value, dict) else []
value = plain_data(value) if isinstance(value, dict) else {}
result = {k: value[k] for k in TEXT if isinstance(value.get(k), str)}
- for key in ('separate', 'new_comfy', 'sampling_caches', 'lan_access', 'image_model'):
+ for key in ('separate', 'new_comfy', 'sampling_caches', 'lan_access', 'image_model', 'prompt_model', 'prompt_hint_dismissed'):
if type(value.get(key)) is bool:
result[key] = value[key]
if value.get('model_method') in ('auto', 'manual', 'reuse'):
diff --git a/freevideo_engine/modern_launcher.py b/freevideo_engine/modern_launcher.py
index 67fc54c..e3890af 100644
--- a/freevideo_engine/modern_launcher.py
+++ b/freevideo_engine/modern_launcher.py
@@ -165,6 +165,14 @@ def create_ui(session, *, show=True):
def imagePackAction(self, action):
self.invoke(session.image_pack_action, action)
+ @Slot(str)
+ def promptModelAction(self, action):
+ self.invoke(session.prompt_model_action, action)
+
+ @Slot()
+ def dismissPromptHint(self):
+ self.invoke(session.dismiss_prompt_hint)
+
@Slot()
def cancelModelUpgrade(self):
self.invoke(session.cancel_model_upgrade)
diff --git a/freevideo_engine/network.py b/freevideo_engine/network.py
index e69863a..d6e81fc 100644
--- a/freevideo_engine/network.py
+++ b/freevideo_engine/network.py
@@ -1018,6 +1018,10 @@ def download(candidates, path, expected, progress=None, *, network=None, env=Non
if matches(partial, name):
from .file_ops import publish
publish(partial, path)
+ if network.get('download_settings_path'):
+ from .download_settings import record_speed
+ record_speed(Path(network['download_settings_path']).parent,
+ max(0, current_size - offset), time.monotonic() - started)
source_health(network, category, name, True)
route_health(network, category, name, route)
event(network, category=category, source=name, route=route, file=path.name, action='verified', method='curl', bytes=path.stat().st_size)
diff --git a/freevideo_engine/prompt_vlm/installer.py b/freevideo_engine/prompt_vlm/installer.py
new file mode 100644
index 0000000..f9fd87b
--- /dev/null
+++ b/freevideo_engine/prompt_vlm/installer.py
@@ -0,0 +1,81 @@
+"""The launcher's own download of the prompt model: one background thread, pausable, resumable."""
+from collections import deque
+from pathlib import Path
+import threading
+import time
+
+from ..locking import runtime_lock
+from . import assets
+
+SPEED_WINDOW_SECONDS = 20
+
+
+class Installer:
+ """state: idle, running, cancelled, failed (reason), done; done/total in bytes."""
+
+ def __init__(self, root, *, busy=None):
+ self.root = Path(root)
+ self.generation_busy = busy
+ self.lock = threading.Lock()
+ self.stop = threading.Event()
+ self.thread = None
+ self.samples = deque()
+ self.value = dict(state='idle', done=0, total=0, reason=None)
+
+ @property
+ def busy(self):
+ return self.thread is not None and self.thread.is_alive()
+
+ def state(self):
+ with self.lock:
+ value = dict(self.value)
+ now = time.monotonic()
+ while len(self.samples) > 1 and self.samples[1][0] <= now - SPEED_WINDOW_SECONDS:
+ self.samples.popleft()
+ rate = 0
+ if value['state'] == 'running' and self.samples:
+ start, amount = self.samples[0]
+ if now > start:
+ rate = max(0, value['done'] - amount) / (now - start)
+ value['bytes_per_second'] = round(rate)
+ return value
+
+ def start(self):
+ with self.lock:
+ if self.busy:
+ return
+ self.stop = threading.Event()
+ self.samples.clear()
+ self.value = dict(state='running', done=0, total=0, reason=None)
+ self.thread = threading.Thread(target=self._run, args=(self.stop,), daemon=True)
+ self.thread.start()
+
+ def cancel(self):
+ self.stop.set()
+
+ def _progress(self, row):
+ with self.lock:
+ if row.get('phase') == 'download':
+ self.value.update(done=row['done'], total=row['total'])
+ self.samples.append((time.monotonic(), row['done']))
+
+ def _run(self, stop):
+ def check():
+ if stop.is_set():
+ raise InterruptedError('cancelled')
+ try:
+ # The engine's own install and this one never write the same partial files.
+ with runtime_lock(self.root / 'prompt-vlm-install.lock', inherit=False):
+ assets.install(self.root, self._progress, check)
+ with self.lock:
+ self.value.update(state='done', reason=None)
+ except InterruptedError:
+ with self.lock:
+ self.value.update(state='cancelled', reason=None)
+ except BlockingIOError:
+ with self.lock:
+ self.value.update(state='failed', reason='busy')
+ except Exception as error:
+ known = {'disk_space', 'ram_space'}
+ with self.lock:
+ self.value.update(state='failed', reason=str(error) if str(error) in known else 'download_failed')
diff --git a/freevideo_engine/prompt_vlm/service.py b/freevideo_engine/prompt_vlm/service.py
index cad2b22..d82ff36 100644
--- a/freevideo_engine/prompt_vlm/service.py
+++ b/freevideo_engine/prompt_vlm/service.py
@@ -384,7 +384,9 @@ class Service:
with runtime_lock(Path(root) / 'engine.lock', inherit=False) as descriptor:
self.check()
if action == 'install':
- assets.install(root, self.progress, self.check)
+ # The launcher's background download writes the same partial files under this lock.
+ with runtime_lock(Path(root) / 'prompt-vlm-install.lock', inherit=False):
+ assets.install(root, self.progress, self.check)
self.check()
self.progress(dict(phase='complete'))
else:
diff --git a/freevideo_engine/request_assets.py b/freevideo_engine/request_assets.py
index 6c9893a..624695b 100644
--- a/freevideo_engine/request_assets.py
+++ b/freevideo_engine/request_assets.py
@@ -87,4 +87,6 @@ def inspect(root, machine, request, *, lora_names=None):
if absent:
items.append(dict(id='lora', kind='lora', files=len(absent), bytes=0, source='',
action='manual', names=absent[:8]))
- return dict(items=items, bytes=sum(item['bytes'] for item in items), ready=not items)
+ from .download_settings import observed_speed
+ return dict(items=items, bytes=sum(item['bytes'] for item in items), ready=not items,
+ bytes_per_second=observed_speed(root))
diff --git a/web/autopilot.js b/web/autopilot.js
index d64dff0..4994d7a 100644
--- a/web/autopilot.js
+++ b/web/autopilot.js
@@ -2,6 +2,7 @@
import { api } from '../../scripts/api.js';
import { agentConnectCard, connectionLabel } from './agent_connect.js';
import { about, agentChat, jobName } from './autopilot_chat.js';
+import { createRequestAssets } from './request_assets.js';
import { openEditorView } from './editor_loader.js';
import { closeDialog } from './motion.js';
import { productVersion } from './updates.js';
@@ -46,7 +47,15 @@ export function openAutopilotView(node, {studio = null} = {}) {
const card = agentConnectCard(t, api, () => inSight() && !card.element.hidden);
// Leaving for another view waits until this page has closed, so the view underneath is never covered twice.
const closed = () => dialog.open ? new Promise(done => { dialog.addEventListener('close', done, {once: true}); closeDialog(dialog); }) : null;
- const chat = agentChat(t, api, {shown: inSight, productVersion,
+ // The next video at the studio's current settings; the agent may choose others, so this is only what is missing now.
+ const assets = createRequestAssets({t, api, request: () => {
+ const value = Object.fromEntries((node.widgets || []).filter(widget => widget.name).map(widget => [widget.name, widget.value]));
+ if (!(value.width > 0 && value.height > 0 && value.seconds > 0)) return null;
+ return new URLSearchParams({width: value.width, height: value.height, seconds: value.seconds, task: 't2va',
+ base_steps: value.base_steps ?? 8, refine_steps: value.refine_steps ?? 3, two_pass: value.two_pass === false ? '0' : '1',
+ enhance: node.properties?.freevideo_prompt_versions?.enabled ? '1' : '0'});
+ }});
+ const chat = agentChat(t, api, {shown: inSight, productVersion, hint: assets,
// Creations continues the work on the editor timeline; this page gives way first.
open: async job => (await import('./library.js')).openLibrary(t, {selectedWork: job.work, back: t('Back to chat', '返回对话'),
extend: async (record, options) => { await closed(); return openExtendEditor(record, node, {studio, ...options}); }}),
@@ -90,11 +99,11 @@ export function openAutopilotView(node, {studio = null} = {}) {
dialog.append(header, body);
dialog.addEventListener('cancel', event => { event.preventDefault(); closeDialog(dialog); });
dialog.onclose = () => {
- card.stop(); chat.stop(); dialog.remove();
+ card.stop(); chat.stop(); assets.dispose(); dialog.remove();
if (current === dialog) current = null;
next();
};
- current = dialog; document.body.append(dialog); dialog.showModal(); viewChanged('autopilot', node); show();
+ current = dialog; document.body.append(dialog); dialog.showModal(); viewChanged('autopilot', node); show(); assets.refresh(true);
navigation.querySelector('[data-view=autopilot]').focus();
return dialog;
}
diff --git a/web/autopilot_chat.css b/web/autopilot_chat.css
index dbdb1cf..e7d99bd 100644
--- a/web/autopilot_chat.css
+++ b/web/autopilot_chat.css
@@ -144,3 +144,5 @@
.fv-chat-me>.fv-chat-actions{margin-top:6px;flex-wrap:wrap;justify-content:flex-end}
.fv-chat-me .fv-chat-error{flex:1;min-width:0}
.fv-chat-keep{white-space:nowrap}
+.fv-chat-main > .fv-request-assets{font-size:12px;line-height:1.5;margin:0 0 6px;padding:0 4px}
+.fv-chat-main > .fv-request-assets[hidden]{display:none}
diff --git a/web/autopilot_chat.js b/web/autopilot_chat.js
index 5bbe650..96f5191 100644
--- a/web/autopilot_chat.js
+++ b/web/autopilot_chat.js
@@ -7,6 +7,7 @@ import { estimatedFraction, remainingAbove, remainingShown, createDiagnosticRepo
import {createErrorReport} from './error_panel.js';
import {canDeleteConversation, conversationMenu, emptyConversations, hasConversations, mergeConversations, removeConversation, runningElsewhere, selectConversation} from './autopilot_conversations.js';
import {renderImageFailure} from './image_generation.js';
+import {about} from './request_assets.js';
const css = document.createElement('link'); css.rel = 'stylesheet'; css.href = new URL('./autopilot_chat.css', import.meta.url).href; document.head.append(css);
@@ -41,7 +42,7 @@ function failureReason(value, t) {
return t(error?.message || 'Did not finish', reason || GENERIC_FAILURE_ZH);
}
-export const about = (seconds, t) => seconds >= 60 ? t(`About ${Math.ceil(seconds / 60)} min`, `约 ${Math.ceil(seconds / 60)} 分钟`) : t('Under 1 min', '不到 1 分钟');
+export {about};
export function clock(seconds) { const s = Math.max(0, Math.round(seconds)); return `${Math.floor(s / 60)}:${String(s % 60).padStart(2, '0')}`; }
export const jobName = (job, t) => job.label || (job.kind === 'image' ? t('Picture', '图片') : t('Video', '视频'));
export const jobFraction = job => Math.max(0, Math.min(1, Number(job.progress?.fraction) || 0));
@@ -232,7 +233,7 @@ function imageViewer(t, src, name, opener, failed) {
// open(job) shows a finished video in Creations, edit(job) takes it to the editing view. shown() says whether the
// user can see the conversation; the page calls sync() whenever that may have changed. changed(view) follows every
// answer: {known, agent, current, active, any}.
-export function agentChat(t, api, {open, edit, shown = () => true, changed = () => {}, interval = 1500, productVersion = () => null} = {}) {
+export function agentChat(t, api, {open, edit, shown = () => true, changed = () => {}, interval = 1500, productVersion = () => null, hint = null} = {}) {
const element = el('section', 'fv-chat'), main = el('div', 'fv-chat-main'), scroller = el('div', 'fv-chat-scroll'), log = el('ol', 'fv-chat-log');
log.setAttribute('role', 'log'); log.setAttribute('aria-label', t('Conversation', '对话'));
const down = press('fv-chat-down', null, () => { scroller.scrollTo({top: scroller.scrollHeight, behavior: 'smooth'}); });
@@ -242,6 +243,8 @@ export function agentChat(t, api, {open, edit, shown = () => true, changed = ()
sendButton.type = 'submit'; sendButton.setAttribute('aria-label', t('Send', '发送')); sendButton.append(glyph('M12 19V5M5 12l7-7 7 7'));
form.append(input, sendButton); scroller.append(log); main.append(scroller, down, form); element.append(main);
const notice = el('p', 'fv-chat-notice'); notice.hidden = true; notice.setAttribute('role', 'status'); main.insertBefore(notice, form);
+ // What the next video would download first, the studio's line, above the box the request is typed in.
+ if (hint) main.insertBefore(hint.element, form);
// A quoted button name stays on one line, so “新对话” never wraps in the middle.
function quoted(node, text) {
const parts = String(text).split(/(“[^”]{1,12}”|"[^"]{1,24}")/);
diff --git a/web/editor.css b/web/editor.css
index 9b17abd..7d2cfb2 100644
--- a/web/editor.css
+++ b/web/editor.css
@@ -75,6 +75,8 @@
.fv-ed-genbar[data-mode=running]>button:not(.fv-ed-generate){order:2}
.fv-ed-gen-note{font-size:13px;color:var(--fv-ink);flex:0 1 auto;min-width:0;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}
.fv-ed-gen-note[hidden]{display:none}
+.fv-ed-genbar .fv-request-assets{order:-2;flex:1 1 100%;min-width:0;font-size:12px;line-height:1.5}
+.fv-ed-genbar .fv-request-assets[hidden]{display:none}
.fv-editor:has(.fv-ed-gen-failure:not([hidden])){--fv-ed-generation-row:max-content}
.fv-ed-genbar:has(.fv-ed-gen-failure:not([hidden])){flex-wrap:wrap;padding-top:10px;padding-bottom:10px}
.fv-editor .fv-ed-gen-failure{display:block;flex:1 0 100%;min-width:0}
diff --git a/web/editor.js b/web/editor.js
index dafaabe..8329b0a 100644
--- a/web/editor.js
+++ b/web/editor.js
@@ -804,6 +804,12 @@ export function openEditor({api, app, from = null, panel = {}, components: given
references: panel.references ? {source: panel.references, notify, size: () => capability.generationSize || generationSize(state.record),
visible: () => store.generationAvailable && actions.supportedSelection() ? partStart() : null} : null,
setFirstFrame: value => { state.apply(t('First-frame reference', '首帧参考'), record => model.setFlag(record, 'first_frame_reference', value)); },
+ // The sampling data and models the next generated part would still download first.
+ assets: {api, query: () => {
+ const size = capability.generationSize || generationSize(state.record), set = state.record.settings || {};
+ return new URLSearchParams({width: size.width, height: size.height, seconds: 5, task: 't2va', enhance: '0',
+ base_steps: set.base_steps ?? 8, refine_steps: set.refine_steps ?? 3, two_pass: set.two_pass === false ? '0' : '1'});
+ }},
previewRange: selection => genbar?.preview(selection),
async estimate(selection) {
const range = selectionRange(selection); if (!range) return null;
diff --git a/web/editor_genbar.js b/web/editor_genbar.js
index a953c54..3802c84 100644
--- a/web/editor_genbar.js
+++ b/web/editor_genbar.js
@@ -2,6 +2,7 @@
import {createFirstFrameSwitch} from './editor_first_frame.js';
import {createEditorReferences} from './editor_references.js';
import {createExpandButton} from './editor_expand.js';
+import {createRequestAssets} from './request_assets.js';
const el = (tag, cls, text) => { const e = document.createElement(tag); if (cls) e.className = cls; if (text != null) e.textContent = text; return e; };
export const timeEstimate = (seconds, t) => seconds == null ? '' : seconds < 60
? t(`about ${Math.max(1, Math.ceil(seconds))} s`, `约 ${Math.max(1, Math.ceil(seconds))} 秒`)
@@ -47,6 +48,9 @@ export function createEditorGenbar(host, {state, t, actions, text = ''}) {
input.dataset.fvGuide = 'editor-describe'; generate.dataset.fvGuide = 'editor-generate';
for (const button of [generate, cancel, resume]) button.type = 'button';
host.append(hint, note, description, generate, cancel, resume);
+ // What this part will download first, above the bar like the studio's line above Generate.
+ const assets = actions.assets ? createRequestAssets({t, api: actions.assets.api, request: () => actions.assets.query()}) : null;
+ if (assets) host.prepend(assets.element);
const firstFrame = createFirstFrameSwitch(host, {state, t, actions});
description.after(firstFrame.element);
const failure = el('div', 'fv-ed-gen-failure fv-result-links'), failureBar = el('div', 'fv-ed-failure-actions fv-actions');
@@ -149,6 +153,7 @@ export function createEditorGenbar(host, {state, t, actions, text = ''}) {
resizeDescription();
input.dispatchEvent(new Event('change'));
generate.title = '';
+ if (assets) { if (selected && !busy) assets.refresh(); else assets.element.hidden = true; }
if (selected && !busy) {
const key = JSON.stringify(selection);
if (estimateCache?.key === key) generate.textContent += estimateCache.label;
@@ -219,7 +224,7 @@ export function createEditorGenbar(host, {state, t, actions, text = ''}) {
});
render();
return {element: host, say, downloadFailure, getText() { expand.commit(); return input.value; }, update(value) { status = value; render(); }, preview(selection) { previewSelection = selection; render(); }, setText(value) { input.value = value || ''; state.setRangeText(input.value); render(); },
- dispose() { disposed = true; ++serial; clearTimeout(noteTimer); unsubscribe(); resize?.disconnect(); expand.dispose(); references?.dispose(); }};
+ dispose() { disposed = true; ++serial; clearTimeout(noteTimer); unsubscribe(); resize?.disconnect(); expand.dispose(); references?.dispose(); assets?.dispose(); }};
}
// A missing optional module leaves the editor's existing progress in place.
diff --git a/web/image_editor.css b/web/image_editor.css
index 6de00b2..40d9d1a 100644
--- a/web/image_editor.css
+++ b/web/image_editor.css
@@ -270,6 +270,7 @@ button.fv-ie-size:hover{background:var(--fv-hover);color:var(--fv-ink)}
.fv-ie-generation[data-running=true]>.fv-ie-button{grid-column:3}
.fv-ie-generation[data-running=true]>.fv-ie-gen-note{grid-column:2;grid-row:2}
.fv-ie-generation[data-message=true]>.fv-ie-gen-note{max-width:none}
+ .fv-ie-generation[data-pack=true]>.fv-ie-gen-note{text-align:right}
.fv-ie-options.fv-ie-generation[data-empty=true]{grid-template-columns:minmax(0,1fr) auto}
.fv-ie-generation[data-empty=true]>.fv-ie-seg{grid-column:1;grid-row:1}
.fv-ie-generation[data-empty=true]>#fv-ie-gen-ratio{grid-column:2;grid-row:1}
diff --git a/web/image_generation.js b/web/image_generation.js
index aaafd25..96bb73a 100644
--- a/web/image_generation.js
+++ b/web/image_generation.js
@@ -3,6 +3,7 @@
import * as commands from './image_commands.js';
import {orientMatrix, rasterKinds, scaleSelection} from './image_editor_engine.js';
import {saveReport, reportIssue, showReportTip} from './report_issue.js';
+import {about} from './request_assets.js';
export const IMAGE_GEN_PROTOCOL = Object.freeze({
root: '/freevideo/image-gen', header: 'X-FreeVideo-Image', upload: '/upload/image',
@@ -14,6 +15,7 @@ export const IMAGE_GEN_PROTOCOL = Object.freeze({
});
export const IMAGE_GEN_POLL_MS = 500;
export const IMAGE_GEN_INFO_POLL_MS = 10000;
+export const IMAGE_PACK_POLL_MS = 2000;
export const BLANK_CANVAS_RATIOS = Object.freeze(['16:9', '9:16', '1:1', '4:3', '3:4']);
export function imageGenerationSupported(platform = globalThis.navigator?.userAgentData?.platform || globalThis.navigator?.platform || '') {
return !/Mac|iPhone|iPad/i.test(platform);
@@ -82,6 +84,9 @@ export function createImageGenClient(fetchImpl = globalThis.fetch.bind(globalThi
...(phase === 'cancelled' ? {error: 'cancelled'} : {})};
},
cancel: job => post('cancel', {[p.job]: job}),
+ // The image models are fetched by this page's own engine; the reply is the new info.
+ async packInstall() { const value = await post('pack-install', {}); return {...value, installed: value.installed ?? value[p.installed] ?? false}; },
+ async packCancel() { const value = await post('pack-cancel', {}); return {...value, installed: value.installed ?? value[p.installed] ?? false}; },
// The prompts and sizes of a new character's five pictures (the Agent's cards use the same ones).
castViews: async description => (await post('cast-views', {description})).views,
async upload(file) {
@@ -106,6 +111,28 @@ export function imagePackMessage(info, t) {
.replace(/ (?=[KMGT]i?B$)/, '\u00a0');
return t(`Download "${name}" in the launcher first, ${size}.`, `先在启动器里下载“${name}”,${size}。`);
}
+// What the page offers while the image models are missing: one button, one muted line, and the bar once loading.
+export function packView(info, t) {
+ const install = info?.install || {}, own = install.state === 'running' || install.state === 'paused_for_generation';
+ // Another process (the launcher) is fetching or re-checking them: nothing to press here.
+ if (!own && (info?.[IMAGE_GEN_PROTOCOL.downloading] || info?.[IMAGE_GEN_PROTOCOL.checking])) return null;
+ const total = install.total || info?.[IMAGE_GEN_PROTOCOL.bytes] || 0;
+ const gb = bytes => (bytes / 1e9).toFixed(1);
+ const size = total > 0 ? gb(total) + '\u00a0GB' : '17.3\u00a0GB';
+ const rate = install.bytes_per_second || info?.bytes_per_second || 0;
+ const left = Math.max(0, total - (install.done || 0));
+ const time = rate > 0 && left > 0 ? ' · ' + about(left / rate, t).replace(/^About/, 'about').replaceAll(' ', '\u00a0') : '';
+ if (own) {
+ const waiting = install.state === 'paused_for_generation';
+ return {loading: true, button: t('Pause', '暂停'), fraction: total > 0 ? Math.min(1, (install.done || 0) / total) : 0,
+ note: waiting ? t('Paused while a video generates', '视频生成中,已暂停')
+ : t(`Downloading · ${gb(install.done || 0)}\u00a0GB / ${size}${time}`, `正在下载 · ${gb(install.done || 0)}\u00a0GB / ${size}${time}`)};
+ }
+ const resume = install.state === 'failed' || install.state === 'cancelled' || install.done > 0;
+ const reason = install.state === 'failed' ? t(install.message_en, install.message_zh) : '';
+ return {loading: false, fraction: null, reason: !!reason, button: resume ? t('Resume download', '继续下载') : t('Download image generation models', '下载图像生成模型'),
+ note: reason || (resume ? t(`${gb(install.done || 0)}\u00a0GB / ${size}${time}`, `${gb(install.done || 0)}\u00a0GB / ${size}${time}`) : size + time)};
+}
export function imageGenError(code, info, t) {
const reasons = {
no_memory: ['Not enough GPU memory, even at the smallest size. Close other apps using the GPU, then try again.',
@@ -319,10 +346,11 @@ export function createImageGenSession({client, prepare, apply, onChange = () =>
function scheduleInfo() {
unschedule(infoTimer); infoTimer = null;
if (disposed || state.info?.installed) return;
+ const loading = ['running', 'paused_for_generation'].includes(state.info?.install?.state);
infoTimer = schedule(() => {
infoTimer = null;
if (visible()) void check(); else scheduleInfo();
- }, IMAGE_GEN_INFO_POLL_MS);
+ }, loading ? IMAGE_PACK_POLL_MS : IMAGE_GEN_INFO_POLL_MS);
}
async function check() {
if (checking || disposed) return checking;
@@ -401,7 +429,13 @@ export function createImageGenSession({client, prepare, apply, onChange = () =>
emit({running: false, job: null, stage: '', fraction: 0, error: '', report_id: null, waiting: '', fitted: null});
return job ? cancelJob(job) : Promise.resolve();
}
- return {check, start, resume, cancel, clearError: () => emit({error: '', report_id: null}), state: () => state,
+ // Start or pause the download of the image models; the reply is the new state, then polling follows it.
+ async function pack(action) {
+ try { const info = await (action === 'cancel' ? client.packCancel() : client.packInstall()); if (!disposed) emit({info, error: '', report_id: null}); }
+ catch (error) { if (!disposed) emit(failed(error)); }
+ finally { if (!disposed) scheduleInfo(); }
+ }
+ return {check, start, resume, cancel, pack, clearError: () => emit({error: '', report_id: null}), state: () => state,
dispose() { disposed = true; unschedule(infoTimer); infoTimer = null; return cancel(); }};
}
@@ -555,11 +589,12 @@ export function createImageGeneration({client, renderer, t, getDoc, getSelection
renderReferences(refs, disabled);
input.placeholder = mode === 'edit' ? t('What to change', '要改什么') : t('Describe the picture', '描述画面');
input.setAttribute('aria-label', input.placeholder);
- action.textContent = state.running ? t('Stop', '停止') : t('Generate', '生成');
+ const pack = missing ? packView(state.info, t) : null;
+ action.textContent = pack ? pack.button : state.running ? t('Stop', '停止') : t('Generate', '生成');
action.classList.toggle('fv-ie-primary', !state.running);
- action.setAttribute('aria-disabled', String(!state.running && (disabled || !prompt.trim())));
- action.title = !state.running && !prompt.trim() ? t('Write a prompt first', '请先写提示词') : '';
- action.hidden = !!missing;
+ action.setAttribute('aria-disabled', String(!pack && !state.running && (disabled || !prompt.trim())));
+ action.title = !pack && !state.running && !prompt.trim() ? t('Enter a prompt first', '请先填写提示词') : '';
+ action.hidden = !!missing && !pack;
const percent = Math.floor(state.fraction * 100) + '%';
if (state.error && !promptRequired) {
const failureKey = `${state.error}:${state.report_id || ''}:${state.stage || ''}`;
@@ -569,8 +604,9 @@ export function createImageGeneration({client, renderer, t, getDoc, getSelection
}
} else {
mounted.failureKey = null;
- note.textContent = missing ? imagePackUnavailableMessage(state.info, t)
- : promptRequired ? t('Write a prompt first.', '请先写提示词。')
+ note.textContent = pack ? pack.note
+ : missing ? imagePackUnavailableMessage(state.info, t)
+ : promptRequired ? t('Enter a prompt first.', '请先填写提示词。')
: state.running && state.waiting ? t(...(QUEUE_LABELS[state.waiting] || QUEUE_LABELS.image))
: state.running && state.fitted ? t(`Not enough GPU memory. Retrying at ${state.fitted.width}\u00a0×\u00a0${state.fitted.height}`,
`显存不足,改用 ${state.fitted.width}\u00a0×\u00a0${state.fitted.height} 重试`) + ' · ' + percent
@@ -581,8 +617,11 @@ export function createImageGeneration({client, renderer, t, getDoc, getSelection
bar.dataset.running = String(state.running);
bar.dataset.message = String(!!missing || promptRequired || !!state.error || !!note.textContent);
bar.dataset.failed = String(!!state.error && !promptRequired);
- meter.hidden = !state.running || !!state.waiting; meter.setAttribute('aria-valuenow', String(Math.floor(state.fraction * 100)));
- fill.style.width = state.fraction * 100 + '%';
+ bar.dataset.pack = String(!!pack && !pack.reason && !state.error);
+ const shown = pack ? pack.fraction : state.fraction;
+ meter.hidden = pack ? pack.fraction == null : !state.running || !!state.waiting;
+ meter.setAttribute('aria-valuenow', String(Math.floor(shown * 100)));
+ fill.style.width = shown * 100 + '%';
}
function mount(bar) {
bar.classList.add('fv-ie-generation');
@@ -608,7 +647,9 @@ export function createImageGeneration({client, renderer, t, getDoc, getSelection
box.append(input); field.append(refs, box);
const note = el('div', '', 'fv-ie-opt-note fv-ie-gen-note'); note.setAttribute('role', 'status');
const action = button(t('Generate', '生成'), null, () => {
- if (session.state().running) void session.cancel(); else void start();
+ const now = session.state(), pack = !now.running && now.info && !now.info.installed ? packView(now.info, t) : null;
+ if (pack) void session.pack(pack.loading ? 'cancel' : 'install');
+ else if (now.running) void session.cancel(); else void start();
}, 'fv-ie-button fv-ie-primary');
const meter = el('div', null, 'fv-ie-gen-meter'), fill = el('i'); meter.append(fill);
meter.setAttribute('role', 'progressbar'); meter.setAttribute('aria-label', t('Generate with AI', 'AI 生成'));
diff --git a/web/request_assets.js b/web/request_assets.js
index 17689f5..31eec2c 100644
--- a/web/request_assets.js
+++ b/web/request_assets.js
@@ -1,4 +1,11 @@
// One muted line above Generate: what this request will download first.
+export const about = (seconds, t) => seconds >= 60 ? t(`About ${Math.ceil(seconds / 60)} min`, `约 ${Math.ceil(seconds / 60)} 分钟`) : t('Under 1 min', '不到 1 分钟');
+// ", about 5 min" after a size, only when a real download speed is known.
+export function timeAfter(bytes, rate, t) {
+ if (!(bytes > 0) || !(rate > 0)) return '';
+ const text = about(bytes / rate, t).replaceAll(' ', '\u00a0'); // "about 2 min" never breaks across lines
+ return t(', ' + text.charAt(0).toLowerCase() + text.slice(1), ',' + text);
+}
// LoRA file names this request would load, through the whole `previous` chain.
export function enabledLoras(start, {upstream, widget, value}) {
const names = [];
@@ -33,8 +40,8 @@ export function createRequestAssets({t, api, request, onError = () => {}}) {
element.hidden = true;
element.setAttribute('aria-live', 'polite');
let timer = 0, controller = null, key = '', disposed = false;
- const size = bytes => bytes >= 2 ** 30 ? (bytes / 2 ** 30).toFixed(1) + ' GB' : Math.max(1, Math.round(bytes / 2 ** 20)) + ' MB';
- function lines(items) {
+ const size = bytes => bytes >= 1e9 ? (bytes / 1e9).toFixed(1) + ' GB' : Math.max(1, Math.round(bytes / 1e6)) + ' MB';
+ function lines(items, rate) {
const rows = [];
// One line names what Generate will fetch first: the two-pass model, then the sampling data.
const names = {upscaler: t('two-pass model', '二次采样模型'), sampling: t('sampling data', '采样数据')};
@@ -46,10 +53,12 @@ export function createRequestAssets({t, api, request, onError = () => {}}) {
}
const parts = [['upscaler', names.upscaler], ['sampling', names.sampling], ['other', t('other model files', '其他模型文件')]]
.filter(([kind]) => bytes[kind]).map(([kind, name]) => `${name} ${size(bytes[kind])}`);
- if (parts.length) rows.push(t(`Downloads before generating: ${parts.join(', ')}`, `生成前会先下载:${parts.join('、')}`));
+ const wait = timeAfter(Object.values(bytes).reduce((sum, n) => sum + n, 0), rate, t);
+ if (parts.length) rows.push(t(`Downloads before generating: ${parts.join(', ')}${wait}`, `生成前会先下载:${parts.join('、')}${wait}`));
for (const item of items) {
if (item.kind === 'prompt-vlm') {
- rows.push(t(`First prompt rewrite downloads ${size(item.bytes)}`, `首次改写提示词会先下载 ${size(item.bytes)}`));
+ const wait = timeAfter(item.bytes, rate, t);
+ rows.push(t(`First prompt rewrite downloads ${size(item.bytes)}${wait}`, `首次改写提示词会先下载 ${size(item.bytes)}${wait}`));
} else if (item.kind === 'lora') {
const names = (item.names || []).map(short);
rows.push(t(`LoRA not found: ${names.join(', ')}`, `找不到 LoRA:${names.join('、')}`));
@@ -57,8 +66,8 @@ export function createRequestAssets({t, api, request, onError = () => {}}) {
}
return rows;
}
- function show(items) {
- const rows = lines(items);
+ function show(items, rate = 0) {
+ const rows = lines(items, rate);
element.replaceChildren(...rows.map(text => Object.assign(document.createElement('div'), {textContent: text})));
element.hidden = rows.length === 0;
}
@@ -76,7 +85,7 @@ export function createRequestAssets({t, api, request, onError = () => {}}) {
if (!reply.ok) return;
const result = await reply.json();
if (disposed || current.signal.aborted || key !== next) return;
- show(Array.isArray(result.items) ? result.items : []);
+ show(Array.isArray(result.items) ? result.items : [], Number(result.bytes_per_second) || 0);
} catch (error) { if (error?.name !== 'AbortError') onError(error); } // Advisory; never blocks Generate.
}, 300);
}