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.

Prompt model check: no new download when only file times changed

Bowen Xue497aa7cb7477
diff --git a/freevideo_engine/agent/routes.py b/freevideo_engine/agent/routes.py
index 4def1fb..74f7eb7 100644
--- a/freevideo_engine/agent/routes.py
+++ b/freevideo_engine/agent/routes.py
@@ -197,7 +197,7 @@ def capabilities(port, jobs):
service = getattr(port.server, '_freevideo_prompt_vlm', None)
if service is not None:
try:
- vlm = {k: v for k, v in service.info().items() if k in ('ready', 'model', 'license', 'bytes', 'busy')}
+ vlm = {k: v for k, v in service.info(wait=False).items() if k in ('ready', 'model', 'license', 'bytes', 'busy')}
except (OSError, ValueError):
vlm = dict(ready=False)
running, pending = port.snapshot()
diff --git a/freevideo_engine/launcher/Main.qml b/freevideo_engine/launcher/Main.qml
index dee2e39..e8578e2 100644
--- a/freevideo_engine/launcher/Main.qml
+++ b/freevideo_engine/launcher/Main.qml
@@ -82,6 +82,7 @@ ApplicationWindow {
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.checking) return t("Checking the prompt model…", "正在检查提示词模型…")
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(", ", ","))
@@ -670,7 +671,7 @@ ApplicationWindow {
}
RowLayout {
objectName: "promptModelRow"
- visible: !!s.prompt_model && !s.prompt_model.ready
+ visible: !!s.prompt_model && !s.prompt_model.ready && !s.prompt_model.checking
Layout.fillWidth: true; spacing: 14
FCheck {
objectName: "promptModelSwitch"; Layout.fillWidth: true
@@ -962,7 +963,7 @@ ApplicationWindow {
}
FCard {
objectName: "promptModelCard"
- visible: !!s.prompt_model && !s.prompt_model.ready && (s.prompt_model.suggest || s.prompt_model.busy
+ visible: !!s.prompt_model && !s.prompt_model.ready && (s.prompt_model.suggest || s.prompt_model.busy || s.prompt_model.checking
|| ["failed", "cancelled"].indexOf(s.prompt_model.install.state) >= 0)
Layout.fillWidth: true; padding: 16; spacing: 10
FText {
@@ -974,8 +975,8 @@ ApplicationWindow {
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
+ visible: !s.prompt_model.checking; Layout.fillWidth: true; spacing: 8
+ FButton { objectName: "promptModelDownload"; visible: !s.prompt_model.busy && !s.prompt_model.checking
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() }
diff --git a/freevideo_engine/launcher_session.py b/freevideo_engine/launcher_session.py
index 3856bf5..15f2427 100644
--- a/freevideo_engine/launcher_session.py
+++ b/freevideo_engine/launcher_session.py
@@ -815,6 +815,9 @@ class Session:
engine = self._image_location()[1]
if self.prompt_installer and self.prompt_installer.busy:
return
+ from .prompt_vlm import assets
+ if assets.checking(engine):
+ 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()
@@ -826,6 +829,7 @@ class Session:
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)
+ checking = bool(engine) and not ready and assets.checking(engine)
installer = self.prompt_installer
active = installer.state() if installer and engine and installer.root == engine else {}
busy = bool(active and installer.busy)
@@ -841,9 +845,9 @@ class Session:
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,
+ return dict(ready=ready, checking=checking, 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']
+ suggest=bool(engine) and not ready and not checking 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):
diff --git a/freevideo_engine/prompt_vlm/assets.py b/freevideo_engine/prompt_vlm/assets.py
index 408906d..a2f3177 100644
--- a/freevideo_engine/prompt_vlm/assets.py
+++ b/freevideo_engine/prompt_vlm/assets.py
@@ -2,6 +2,7 @@
import json
from pathlib import Path
import shutil
+import threading
from .. import disk_space
FAMILY = 'image-models'
@@ -17,15 +18,107 @@ def directory(root):
def ready(root):
+ """Cheap, safe on the launcher's UI thread: version, sizes and modified times only.
+
+ Files whose modified time moved are checked by content once, in the
+ background; this returns False until that check has accepted them."""
+ return _state(root, wait=False)
+
+
+def settle(root):
+ """Same answer, but a moved modified time is checked by content in the
+ calling thread. For request handlers, never for a UI thread or under a lock."""
+ return ready(root) or _state(root, wait=True)
+
+
+_RECHECK = threading.Lock()
+_BOOKKEEPING = threading.Lock()
+_OUTCOME = {}
+_RUNNING = set()
+
+
+def _state(root, wait):
+ spec, folder = catalog(), directory(root)
+ try:
+ receipt = json.loads((folder / 'verified.json').read_text(encoding='utf-8'))
+ if receipt.get('revision') != spec['revision']:
+ return False
+ stats = {row['file']: (folder / row['file']).stat() for row in spec['files']}
+ if any(stats[row['file']].st_size != row['bytes'] for row in spec['files']):
+ return False
+ moved = [row for row in spec['files']
+ if receipt['files'].get(row['file']) != stats[row['file']].st_mtime_ns]
+ if not moved:
+ return True
+ key = (str(folder), spec['revision'],
+ tuple((row['file'], stats[row['file']].st_size, stats[row['file']].st_mtime_ns) for row in moved))
+ known = _OUTCOME.get(key)
+ if known is not None:
+ return known
+ if wait:
+ return _recheck(folder, spec, moved, key)
+ with _BOOKKEEPING:
+ if key in _RUNNING:
+ return False
+ _RUNNING.add(key)
+ threading.Thread(target=_recheck, args=(folder, spec, moved, key), daemon=True,
+ name='prompt-model-recheck').start()
+ return False
+ except (OSError, ValueError, KeyError, TypeError):
+ return False
+
+
+def checking(root):
+ """True while the files' content is being checked after a modified time moved.
+
+ A cheap look at the same file identity ready() uses, for a page that must not
+ call the model missing, or offer its download, in the meantime."""
spec, folder = catalog(), directory(root)
try:
receipt = json.loads((folder / 'verified.json').read_text(encoding='utf-8'))
- return receipt.get('revision') == spec['revision'] and all(
- (folder / row['file']).stat().st_size == row['bytes'] and
- receipt['files'].get(row['file']) == (folder / row['file']).stat().st_mtime_ns
- for row in spec['files'])
+ if receipt.get('revision') != spec['revision']:
+ return False
+ stats = {row['file']: (folder / row['file']).stat() for row in spec['files']}
+ if any(stats[row['file']].st_size != row['bytes'] for row in spec['files']):
+ return False
+ key = (str(folder), spec['revision'], tuple(
+ (row['file'], stats[row['file']].st_size, stats[row['file']].st_mtime_ns)
+ for row in spec['files'] if receipt['files'].get(row['file']) != stats[row['file']].st_mtime_ns))
except (OSError, ValueError, KeyError, TypeError):
return False
+ with _BOOKKEEPING:
+ return key in _RUNNING and key not in _OUTCOME
+
+
+def _recheck(folder, spec, moved, key):
+ """Accept files whose modified time changed (copied folder, unpacked archive,
+ antivirus) when their content still matches the catalog, then refresh the
+ receipt. The outcome is remembered per file identity, so one set of files is
+ hashed once whatever the answer."""
+ from .. import provision
+ from ..monitoring import save
+ ledger_path = folder / 'download-verified.json'
+ try:
+ with _RECHECK:
+ if key in _OUTCOME:
+ return _OUTCOME[key]
+ try:
+ ledger = json.loads(ledger_path.read_text(encoding='utf-8'))
+ except (OSError, ValueError):
+ ledger = {}
+ ok = all(provision.verified(folder / row['file'], row, ledger) for row in moved)
+ if ok:
+ save(ledger_path, ledger)
+ save(folder / 'verified.json', dict(revision=spec['revision'], files={
+ row['file']: (folder / row['file']).stat().st_mtime_ns for row in spec['files']}))
+ _OUTCOME[key] = ok
+ return ok
+ except Exception:
+ _OUTCOME[key] = False
+ return False
+ finally:
+ with _BOOKKEEPING:
+ _RUNNING.discard(key)
def remote(spec, row):
diff --git a/freevideo_engine/prompt_vlm/service.py b/freevideo_engine/prompt_vlm/service.py
index d82ff36..e512ec4 100644
--- a/freevideo_engine/prompt_vlm/service.py
+++ b/freevideo_engine/prompt_vlm/service.py
@@ -217,10 +217,11 @@ class Service:
pass_fds=() if descriptor is None else (descriptor,),
supervise=True, start_new_session=True)
- def info(self):
+ def info(self, wait=True):
+ """wait=False answers from the cheap check, for callers on an event loop or UI thread."""
root, machine = self.installation()
spec = assets.catalog()
- return dict(ready=assets.ready(root), model=spec['repo'], license=spec['license'],
+ return dict(ready=assets.settle(root) if wait else assets.ready(root), model=spec['repo'], license=spec['license'],
bytes=sum(row['bytes'] for row in spec['files']), busy=self.busy(),
ram_bytes=self.ram_bytes(machine))
@@ -271,15 +272,15 @@ class Service:
if value.get('accept_download') is not True:
raise ValueError('consent_required')
elif action == 'ask':
- if not assets.ready(root):
+ if not assets.settle(root):
raise ValueError('model_missing')
value = self.ask_images(rules.ask_request(value))
elif action == 'split':
- if not assets.ready(root):
+ if not assets.settle(root):
raise ValueError('model_missing')
value = rules.split_request(value)
else:
- if not assets.ready(root):
+ if not assets.settle(root):
raise ValueError('model_missing')
value = rules.request(value)
from ..comfy_assets import resolve_assets
@@ -627,6 +628,7 @@ def stop_prestart_for_generation(server):
def register():
+ import asyncio
from aiohttp import web
from server import PromptServer
import folder_paths
@@ -641,7 +643,7 @@ def register():
@server.routes.get('/freevideo/prompt-vlm')
async def info(request):
try:
- return web.json_response(dict(service.info(), token=token))
+ return web.json_response(dict(await asyncio.to_thread(service.info), token=token))
except (OSError, ValueError):
return web.json_response(dict(error='setup_required'), status=400)
@@ -670,6 +672,10 @@ def register():
running, pending = server.prompt_queue.get_current_queue()
if running or pending:
raise ValueError('busy')
+ if name in ('ask', 'split', 'rewrite'):
+ # A moved modified time is checked by content here, off the event loop;
+ # start() then finds the remembered answer.
+ await asyncio.to_thread(assets.settle, service.installation()[0])
result = service.start(name, value)
return web.json_response(result)
except (ValueError, OSError) as error:
diff --git a/freevideo_engine/request_assets.py b/freevideo_engine/request_assets.py
index 82e8ddb..85136b1 100644
--- a/freevideo_engine/request_assets.py
+++ b/freevideo_engine/request_assets.py
@@ -59,7 +59,7 @@ def _upscaler(root, sampled):
def _prompt_vlm(root):
from .prompt_vlm import assets
- if assets.ready(root):
+ if assets.settle(root):
return []
spec = assets.catalog()
return [dict(id='prompt-vlm', kind='prompt-vlm', files=len(spec['files']),