From ec9f37f7427801ea99b02d010c75a6f972b07058 Mon Sep 17 00:00:00 2001 From: Bowen Xue Date: Thu, 19 Nov 2026 07:50:40 +0000 Subject: [PATCH 01/21] Release 0.6.4: update notes - Image worker: a full warm-up builds the model's own runner from the same table the picture uses - Update notice test follows the page's new user_message import - Image generation script test: the store failure case uses a real failure, since a busy engine now queues instead of failing - Assistant confirmation settings test: its stand-in page elements have a class list, and it checks that a failed save is marked as a warning and the next save that works clears the mark --- constraints/engine.txt | 2 +- web/editor_text.js | 3 ++- 2 files changed, 3 insertions(+), 2 deletions(-) diff --git a/constraints/engine.txt b/constraints/engine.txt index 7f56b90b..27cc7419 100644 --- a/constraints/engine.txt +++ b/constraints/engine.txt @@ -3,7 +3,7 @@ accelerate==1.14.0 annotated-doc==0.0.5 antlr4-python3-runtime==4.9.3 anyio==4.15.1 -apache-tvm-ffi==0.1.14rc3 +apache-tvm-ffi==0.1.14.post1 av==18.1.0 certifi==2026.7.22 cffi==2.1.1 diff --git a/web/editor_text.js b/web/editor_text.js index 711e1f3b..e5ae7337 100644 --- a/web/editor_text.js +++ b/web/editor_text.js @@ -87,7 +87,8 @@ export function createEditorText({element,state,t,actions,adjust,player,toolbar, speechEnd();if(!cues.length){actions.notify?.(speechSilent());return false;} finishInline();commitDraft(); // Lines already on the subtitle track are replaced in one step; the notice undoes it in one press (E15). - const had=state.record.tracks.some(track=>track.kind==='subtitle'&&track.clips.length); + // Only lines with words count: an empty one just added by "Add subtitle" is not subtitles the person had. + const had=state.record.tracks.some(track=>track.kind==='subtitle'&&track.clips.some(c=>String(c.text||'').trim())); if(!apply(t('Auto subtitles','自动字幕'),r=>addSubtitles(r,cues,{replace:true})))actions.notify?.(speechFailed(),SPEECH_ISSUE); else if(had){const step=state.step;actions.notify?.(t('The subtitles heard replaced the ones there.','识别出的字幕已替换原有字幕。'),null,null,{label:t('Undo','撤销'),use:t('Bring back the subtitles you had','恢复原来的字幕'),run:()=>{if(state.step===step)actions.undo?.();}});} else{const missing=projectMissing(state.record);if(missing.length)actions.notify?.(missingHint([...new Set(missing.flatMap(r=>r.chars))],t));} From b22e96a536b4c376b81a4220e65d55ad00fa3888 Mon Sep 17 00:00:00 2001 From: Bowen Xue Date: Thu, 19 Nov 2026 07:39:33 +0000 Subject: [PATCH 02/21] Image models kept on another drive through a link (a symbolic link or a Windows junction) are... Image models kept on another drive through a link (a symbolic link or a Windows junction) are used instead of refused, and a link problem in one image model no longer fails the whole image page The image model folder, its subfolders and the model files may be links that lead to something that exists. Files FreeVideo writes itself (download partials, receipts, the lock, logs, the notice) are never links and stay inside the folder, and a link or the file it leads to is never removed or overwritten. A link that leads nowhere, a model file that is a link to a damaged or different file, and a record file that is a link each say why and what to do next; the image page marks only that model as failed instead of answering with an empty error. --- freevideo_engine/failure_details.py | 7 +- freevideo_engine/image_gen/image_pack.py | 87 ++++++++++++++++++------ freevideo_engine/image_gen/service.py | 73 ++++++++++++++------ 3 files changed, 122 insertions(+), 45 deletions(-) diff --git a/freevideo_engine/failure_details.py b/freevideo_engine/failure_details.py index 23ba6590..74e6eb76 100644 --- a/freevideo_engine/failure_details.py +++ b/freevideo_engine/failure_details.py @@ -35,7 +35,12 @@ 'busy_video': ('A video is using the graphics card; try again when it finishes.', '视频正在使用显卡,完成后再试。'), 'needs_repair': ('The image model files are incomplete or damaged; repair them in the launcher.', '图像模型文件不完整或已损坏,请在启动器里修复。'), 'changed': ('The image model files changed during the check; they were kept, so check again.', '图像模型文件在检查期间发生变化,已保留,请重新检查。'), - 'unsafe_path': ('The image model folder contains a link that cannot be safely changed.', '图像模型目录含有无法安全修改的链接。'), + 'unsafe_path': ("One of FreeVideo's own record files in the image model folder (image_gen) is a link or leads outside that folder, so it was not written; delete that link and try again.", + '图像模型目录(image_gen)里 FreeVideo 自己的记录文件是链接或指向目录之外,所以没有写入;请删掉这个链接后重试。'), + 'broken_link': ('A link in the image model folder leads to a place that does not exist, for example a drive that is not connected; connect that drive or folder, or delete the link and download the model again.', + '图像模型目录里有链接指向不存在的位置(例如没接上的硬盘);请接上它指向的盘或文件夹,或删掉这个链接后重新下载模型。'), + 'link_mismatch': ('A model file in the image model folder is a link to a file that is damaged or a different version; delete the link so FreeVideo can download the file again, or point the link to the right file.', + '图像模型目录里有模型文件是链接,它指向的文件已损坏或版本不对;请删掉这个链接让 FreeVideo 重新下载,或把链接改指向正确的文件。'), 'failed': ('The image model operation stopped because of an unexpected error. Export the report, then use "Report a problem" and attach it.', '图像模型操作因意外错误停止。请先导出报告,再点击“提交问题”并附上报告。'), } diff --git a/freevideo_engine/image_gen/image_pack.py b/freevideo_engine/image_gen/image_pack.py index 9dd05baa..ce2fc392 100644 --- a/freevideo_engine/image_gen/image_pack.py +++ b/freevideo_engine/image_gen/image_pack.py @@ -205,16 +205,49 @@ def base(root=None): return Path(root).expanduser().absolute() / 'image_gen' -def _path(folder, name): - """Refuse links at the pack root or below it, including partials/receipts.""" +def _linked(path): + """A symbolic link, or a Windows directory junction (which is_symlink() does not count).""" + if path.is_symlink(): + return True + junction = getattr(path, 'is_junction', None) + return bool(junction and junction()) + + +def _follow(path): + """A link people use to keep the models on another drive must lead somewhere that exists.""" + try: + path.resolve(strict=True) + except (OSError, RuntimeError) as error: + logging.warning('[FreeVideo] An image model link leads nowhere: %s', redacted_launcher_error(str(path))) + raise PackError('broken_link', link=str(path)) from error + + +def _path(folder, name, *, kind='record'): + """Where `name` lives in the pack. People keep models on another drive with a link, so the pack folder, its + subfolders and the weights ('weight') may be links that lead to something that exists. A file FreeVideo writes + itself is never a link: a partial or source record ('beside') sits in its weight's folder wherever that is, and + any other record (receipts, ownership, the lock, logs, the notice) stays inside the pack folder itself. + Names never leave the pack: _relative refuses absolute paths and '..'.""" relative = _relative(name) path = folder - if path.is_symlink(): - raise PackError('unsafe_path') - for part in relative.parts: + if _linked(path): + _follow(path) + for index, part in enumerate(relative.parts): path /= part - if path.is_symlink(): - raise PackError('unsafe_path') + if not _linked(path): + continue + if index == len(relative.parts) - 1 and kind != 'weight': + logging.warning('[FreeVideo] An image model record file is a link: %s', redacted_launcher_error(str(path))) + raise PackError('unsafe_path', link=str(path)) + _follow(path) + if kind == 'record' and len(relative.parts) > 1: + try: + inside = path.parent.resolve().is_relative_to(folder.resolve()) + except (OSError, RuntimeError): + inside = False + if not inside: + logging.warning('[FreeVideo] An image model record folder leads outside the pack: %s', redacted_launcher_error(str(path))) + raise PackError('unsafe_path', link=str(path.parent)) return path @@ -237,14 +270,14 @@ def shared_root(root=None): def target(row, root=None): if row.get('shared'): return shared_root(root) / _relative(row['file']) - return _path(base(root), row['file']) + return _path(base(root), row['file'], kind='weight') def _side(folder, row, root, suffix): """A partial or source record sits next to its file, also for a file outside the pack folder.""" if row.get('shared'): return Path(str(target(row, root)) + suffix) - return _path(folder, row['file'] + suffix) + return _path(folder, row['file'] + suffix, kind='beside') def _read(folder, name): @@ -768,6 +801,9 @@ def install(root=None, progress=None, check=None, *, engine_root=None, repair=Fa check() path = target(row, root) if path.exists(): + if not row.get('shared') and _linked(path): + # The user's link leads to a different file: neither the link nor that file is ours to replace. + raise PackError('link_mismatch', link=str(path)) if not repair or row.get('shared'): raise PackError('needs_repair') approved = model_repair.replacement(path, row, model_repair.read(folder), set()) @@ -790,7 +826,7 @@ def moved(current, size, speed, **kwargs): finally: # Completed files and cancellable prefixes have separate identities. for artifact in (partial, affinity): - if not row.get('shared') and may_own[artifact] and _path(folder, artifact.relative_to(folder).as_posix()).is_file(): + if not row.get('shared') and may_own[artifact] and _path(folder, artifact.relative_to(folder).as_posix(), kind='beside').is_file(): _own(folder, owned, artifact) ledger[str(path)] = provision.file_identity(path, row) save(_path(folder, LEDGER), ledger) @@ -812,24 +848,29 @@ def repair(root=None, progress=None, check=None, *, engine_root=None, group='ima return install(root, progress, check, engine_root=engine_root, repair=True, group=group) +def _kinds(group): + """The files of a group FreeVideo may remove, by kind for _path: each weight and what resumes its download.""" + kinds = {} + for row in rows(group=group): + if not row.get('shared'): + kinds.update({row['file']: 'weight', row['file'] + '.partial': 'beside', row['file'] + '.partial.source.json': 'beside'}) + return kinds + + def removal_plan(root=None, *, group='image'): folder = base(root) owned = _read(folder, OWNERSHIP) notice = NOTICES[_notice_key(group)][0] - allowed = {notice} - for row in rows(group=group): - if not row.get('shared'): - allowed.update((row['file'], row['file'] + '.partial', row['file'] + '.partial.source.json')) - for name in allowed: - if name == notice: - continue - _path(folder, name) + kinds = _kinds(group) + allowed = {notice, *kinds} + for name in kinds: + _path(folder, name, kind=kinds[name]) files, skipped = [], [] for name, stamp in owned.items(): if name not in allowed or not isinstance(stamp, dict): continue try: - path = _path(folder, name) + path = _path(folder, name, kind=kinds.get(name, 'record')) except PackError: if name != notice: raise @@ -837,7 +878,8 @@ def removal_plan(root=None, *, group='image'): continue if not path.exists(): continue - if _owned_intact(path, stamp): + # A weight the user replaced with a link is theirs now: neither the link nor what it leads to is removed. + if not _linked(path) and _owned_intact(path, stamp): files.append(dict(file=name, identity=stamp, bytes=path.stat().st_size)) else: skipped.append(name) @@ -852,11 +894,12 @@ def remove(root=None, check=None, *, engine_root=None, group='image'): plan = removal_plan(root, group=group) owned, ledger = _read(folder, OWNERSHIP), _read(folder, LEDGER) released, removed = 0, [] + kinds = _kinds(group) for entry in plan['files']: check() - path = _path(folder, entry['file']) + path = _path(folder, entry['file'], kind=kinds.get(entry['file'], 'record')) stamp = entry['identity'] - if not _owned_intact(path, stamp): + if _linked(path) or not _owned_intact(path, stamp): plan['skipped'].append(entry['file']) continue path.unlink() diff --git a/freevideo_engine/image_gen/service.py b/freevideo_engine/image_gen/service.py index 5129c77f..533ea78a 100644 --- a/freevideo_engine/image_gen/service.py +++ b/freevideo_engine/image_gen/service.py @@ -268,18 +268,32 @@ def _video_busy(): def busy(self): return self._busy or self.segmenting + @staticmethod + def pack_checked(call, *args, **kwargs): + """(value, problem): a model folder that cannot be read safely (a link leading nowhere) marks that model as + failed with the reason and the next step, instead of failing the whole page.""" + try: + return call(*args, **kwargs), None + except image_pack.PackError as error: + from ..failure_details import image_pack_error_code, image_pack_failure + code = image_pack_error_code(error) + return None, dict(state='failed', done=0, total=0, bytes_per_second=0, reason=code, + message_en=image_pack_failure(code)['detail'], message_zh=image_pack_failure(code, zh=True)['detail']) + def info(self): engine_root, machine = self.installation() spec = image_pack.catalog() - ready = image_pack.ready(machine['model_root']) - downloading = not ready and image_pack.downloading(machine['model_root'], engine_root) - return dict(ready=ready, model=spec['repo'], models=self.model_rows(machine, ready, downloading), - checking=not ready and image_pack.checking(machine['model_root']), + root = machine['model_root'] + ready, problem = self.pack_checked(image_pack.ready, root) + ready = bool(ready) + downloading = not ready and not problem and bool(self.pack_checked(image_pack.downloading, root, engine_root)[0]) + return dict(ready=ready, model=spec['repo'], models=self.model_rows(machine, ready, downloading, problem), + checking=not ready and image_pack.checking(root), downloading=downloading, bytes=sum(row['bytes'] for row in spec['groups']['image']), busy=self.busy(), - max_images=MAX_IMAGES, sizes=self.size_tiers(machine), install=self.pack_state(ready), + max_images=MAX_IMAGES, sizes=self.size_tiers(machine), install=self.pack_state(ready, problem), face_box=True, - segment=dict(ready=image_pack.ready(machine['model_root'], group='segment'), + segment=dict(ready=bool(self.pack_checked(image_pack.ready, root, group='segment')[0]), max_points=16, device='cpu', install=self.segment_installer.state() if self.segment_installer else None), disk_free_bytes=self.disk_free(machine['model_root']), @@ -287,17 +301,20 @@ def info(self): purposes=list(PURPOSES), **({'unified_memory': True} if machine.get('device_backend') == 'mps' else {})) - def model_rows(self, machine, qwen_ready, qwen_downloading): + def model_rows(self, machine, qwen_ready, qwen_downloading, qwen_problem=None): """Both picture models for the page: installed, or being fetched with the bytes still to download.""" root = machine['model_root'] mac = sys.platform == 'darwin' - h3_ready = not mac and image_pack.ready(root, group=H3_GROUP) - h3_status = {} if h3_ready or mac else image_pack.status(root, group=H3_GROUP) + h3_ready, h3_problem = False, None + if not mac: + h3_ready, h3_problem = self.pack_checked(image_pack.ready, root, group=H3_GROUP) + h3_ready = bool(h3_ready) + h3_status = {} if h3_ready or mac or h3_problem else image_pack.status(root, group=H3_GROUP) installer = self.h3_installer h3_state = None if h3_ready or installer is None else installer.state() h3_active = h3_state is not None and h3_state['state'] in ('running', 'paused_for_generation') - qwen_state = None if qwen_ready else self.pack_state(False) - qwen_status = {} if qwen_ready else image_pack.status(root) + qwen_state = None if qwen_ready else self.pack_state(False, qwen_problem) + qwen_status = {} if qwen_ready or qwen_problem else image_pack.status(root) with self.mutex: waiting = list(self.pack_queue) active = self._active_pack() @@ -311,7 +328,7 @@ def model_rows(self, machine, qwen_ready, qwen_downloading): checking=bool(h3_status.get('checking')), shared_bytes=sum(r['bytes'] for r in h3_rows if r.get('shared')), blocked_by=active if active == image_model.QWEN and not h3_ready else None, - install=None if mac else queued if image_model.H3 in waiting else self.pack_row(self.h3_installer, h3_ready))] + install=None if mac else queued if image_model.H3 in waiting else self.pack_row(self.h3_installer, h3_ready, h3_problem))] if mac: rows[0]['unavailable_reason'] = 'platform' rows.append(dict(id=image_model.QWEN, label='Qwen-Image 2.1', available=True, ready=qwen_ready, max_images=MAX_IMAGES, @@ -322,8 +339,9 @@ def model_rows(self, machine, qwen_ready, qwen_downloading): shared_bytes=0, blocked_by=active if active == image_model.H3 and not qwen_ready else None, install=queued if image_model.QWEN in waiting else qwen_state)) - moss_ready = image_pack.ready(root, group=MOSS_GROUP) - moss_status = {} if moss_ready else image_pack.status(root, group=MOSS_GROUP) + moss_ready, moss_problem = self.pack_checked(image_pack.ready, root, group=MOSS_GROUP) + moss_ready = bool(moss_ready) + moss_status = {} if moss_ready or moss_problem else image_pack.status(root, group=MOSS_GROUP) moss_state = None if moss_ready or self.moss_installer is None else self.moss_installer.state() moss_active = moss_state is not None and moss_state['state'] in ('running', 'paused_for_generation') moss_rows = image_pack.rows(group=MOSS_GROUP) @@ -334,7 +352,7 @@ def model_rows(self, machine, qwen_ready, qwen_downloading): bytes_needed=moss_status.get('remaining_bytes', 0), shared_bytes=0, blocked_by=active if active not in (None, image_model.MOSS) and not moss_ready else None, install=None if moss_ready else queued if image_model.MOSS in waiting - else self.pack_row(self.moss_installer, moss_ready))) + else self.pack_row(self.moss_installer, moss_ready, moss_problem))) if mac: rows[-1]['unavailable_reason'] = 'platform' return rows @@ -393,15 +411,18 @@ def read(): total = None return ['standard', 'high'] if total and total >= HIGH_SIZE_MIN_TOTAL else ['standard'] - def pack_state(self, ready): + def pack_state(self, ready, problem=None): """Progress of the Qwen-Image download this page started, in both languages for a failure.""" - return self.pack_row(self.pack_installer, ready) + return self.pack_row(self.pack_installer, ready, problem) @staticmethod - def pack_row(installer, ready): - """Progress of one picture-model download; a failure carries both languages and the report id.""" - if ready or installer is None: + def pack_row(installer, ready, problem=None): + """Progress of one picture-model download; a failure carries both languages and the report id. A model + folder that cannot be read safely shows as that failure unless a download of it is under way.""" + if ready: return None + if installer is None or problem and installer.state()['state'] not in ('running', 'paused_for_generation', 'failed'): + return problem 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), @@ -425,8 +446,9 @@ def _pack_installer(self, model, root, engine_root): return installer def _pack_ready(self, model, root): + """Not ready when its folder cannot be read safely either: the download then stops with the reason.""" group = self.model_group(model) - return image_pack.ready(root, group=group) if group else image_pack.ready(root) + return bool(self.pack_checked(image_pack.ready, root, **({'group': group} if group else {}))[0]) @staticmethod def model_group(model): @@ -480,7 +502,8 @@ def pack_action(self, action, *, group='image', model=None): if action == 'cancel': if installer is not None: installer.cancel() - elif not image_pack.ready(root, group=group) and not image_pack.downloading(root, engine_root): + elif (not self.pack_checked(image_pack.ready, root, group=group)[0] + and not self.pack_checked(image_pack.downloading, root, engine_root)[0]): if installer is None or installer.root != root or installer.engine_root != engine_root: installer = image_pack.Installer(root, engine_root=engine_root, busy=self.video_busy, group=group) self.segment_installer = installer @@ -2662,6 +2685,12 @@ async def info(request): return web.json_response(dict(service.info(), token=token)) except (OSError, ValueError): return web.json_response(dict(error='setup_required'), status=400) + except image_pack.PackError as error: + # Never an empty 500: the reason and the next step, in both languages. + from ..failure_details import image_pack_error_code, image_pack_failure + code = image_pack_error_code(error) + return web.json_response(dict(error=code, message_en=image_pack_failure(code)['detail'], + message_zh=image_pack_failure(code, zh=True)['detail']), status=409) @server.routes.get('/freevideo/image-gen/report/{report_id}') async def report(request): From 987d089e5c04de6edc179c1cb7526be2c2cdc3eb Mon Sep 17 00:00:00 2001 From: Bowen Xue Date: Thu, 19 Nov 2026 08:48:16 +0000 Subject: [PATCH 03/21] Show the known fix first when reporting a failure that has one --- web/error_panel.js | 29 +++++++++++++++++++++-------- web/report_issue.js | 36 +++++++++++++++++++++++++++++++----- web/result_actions.css | 1 + 3 files changed, 53 insertions(+), 13 deletions(-) diff --git a/web/error_panel.js b/web/error_panel.js index a4f4e0b4..c2fd7ccc 100644 --- a/web/error_panel.js +++ b/web/error_panel.js @@ -5,7 +5,7 @@ import {detectBrowserExtension, browserExtensionAdvice, extensionSteps, isNetwor import {SAMPLING_EFFORTS, STEP_CACHES, UPSCALE_FACTORS, tableLevel} from './sampling_effort.js'; import {failureIssue, failureStage} from './failure_issue.js'; import {knownEngineExit} from './engine_exit.js'; -import {focusReportTip, reportIssue, showReportTip} from './report_issue.js'; +import {focusReportTip, hideReportTip, reportIssue, showReportTip} from './report_issue.js'; import { skin } from './glass/library.js'; const reports = new WeakSet(); const captured = new WeakMap(); @@ -711,7 +711,7 @@ export function createErrorPanel(t, route = null) { const privacyInside = document.createElement('p'); privacyInside.className = 'fv-failure-privacy'; privacyInside.hidden = true; privacyInside.textContent = t('Paths and typed text are removed.', '已去掉路径和输入的文字。'); const downloadStatus = document.createElement('p'); downloadStatus.setAttribute('role', 'status'); - let currentReport = null, githubLora = false; + let currentReport = null, githubLora = false, knownAdvice = '', adviceShown = false; const disclosure = document.createElement('details'), summary = document.createElement('summary'); disclosure.className = 'fv-failure-fold'; const chevron = document.createElement('span'); chevron.className = 'fv-failure-chevron'; chevron.setAttribute('aria-hidden', 'true'); @@ -738,20 +738,31 @@ export function createErrorPanel(t, route = null) { // page at once (a page opened after waiting can be blocked as a pop-up). let issueModules = null; const loadIssueModules = () => import('./feedback.js').then(feedback => import('./updates.js').then(updates => { issueModules = {feedback, updates}; })).catch(() => {}); + const openFeedback = async () => { + if (!issueModules) await loadIssueModules(); + if (!issueModules) return; + const draft = failureIssue(currentReport, element.freevideoKind, {lora: githubLora, t, engineExit: knownEngineExit()}); + const url = issueModules.feedback.feedbackIssueURL(draft.text, issueModules.updates.productVersion(), draft.summary, draft.title); + globalThis.open?.(url, '_blank', 'noopener'); + }; github.onclick = async () => { if (!currentReport) return; + // A known error that has its own advice shows it first, once per card; the way on stays one press away. + const lead = knownAdvice && !adviceShown ? knownAdvice : ''; + if (lead) adviceShown = true; + if (lead && !(route?.has() && diagnosticReports.has(currentReport) && !githubLora)) { + if (!issueModules) await loadIssueModules(); + showReportTip(head, github, t, {mode: 'advice', lead, proceed: openFeedback}); + return; + } // A generation with a diagnostic report goes the report route: save it, then the tip opens the form. if (route?.has() && diagnosticReports.has(currentReport) && !githubLora) { if (focusReportTip(head)) return; try { await route.download(); } catch { return; } - showReportTip(head, github, t, {mode: 'downloaded', submit: () => reportIssue(route.fetch, route.version(), {save: false})}); + showReportTip(head, github, t, {mode: 'downloaded', lead, submit: () => reportIssue(route.fetch, route.version(), {save: false})}); return; } - if (!issueModules) await loadIssueModules(); - if (!issueModules) return; - const draft = failureIssue(currentReport, element.freevideoKind, {lora: githubLora, t, engineExit: knownEngineExit()}); - const url = issueModules.feedback.feedbackIssueURL(draft.text, issueModules.updates.productVersion(), draft.summary, draft.title); - globalThis.open?.(url, '_blank', 'noopener'); + await openFeedback(); }; download.onclick = () => { if (!currentReport) return; @@ -791,6 +802,8 @@ export function createErrorPanel(t, route = null) { title.textContent = advice.title; explanation.textContent = advice.summary; explanation.hidden = !advice.summary; action.textContent = advice.action; element.querySelector('.fv-extension-steps')?.remove(); if (advice.kind === 'browser-extension') action.after(extensionSteps(advice)); + knownAdvice = advice.plain && PLAIN_ERRORS.some(error => error.key === advice.kind) ? advice.summary : ''; adviceShown = false; + hideReportTip(head); element.freevideoKind = advice.kind; reload.hidden = advice.kind !== 'browser-extension'; if (advice.kind === 'fa4-update') { const command = 'freevideo setup --fa4-guard'; diff --git a/web/report_issue.js b/web/report_issue.js index 06aefbc1..d813b6cb 100644 --- a/web/report_issue.js +++ b/web/report_issue.js @@ -166,7 +166,7 @@ export function hideReportTip(bar) { bar?.parentElement?.querySelector(':scope > .fv-report-tip:not(.fv-report-tip-leaving)')?.remove(); } -export function showReportTip(bar, anchor, t, {mode = 'invite', submit, onHide = null, animate = true} = {}) { +export function showReportTip(bar, anchor, t, {mode = 'invite', submit, onHide = null, animate = true, lead: leadText = '', proceed = null} = {}) { skin(); bar.parentElement.querySelector(':scope > .fv-report-tip:not(.fv-report-tip-leaving)')?.remove(); // Under a result in a view, the invitation is no card at all: its one sentence lives in the Report button's hover @@ -199,7 +199,7 @@ export function showReportTip(bar, anchor, t, {mode = 'invite', submit, onHide = if ((run.match(/[\u4e00-\u9fff]/g) || []).length <= 12) { parts.push(run); continue; } let first = true; for (const {segment} of new Intl.Segmenter('zh', {granularity: 'word'}).segment(run)) { - if (!first && /^[\u4e00-\u9fff]/.test(segment)) parts.push(document.createElement('wbr')); + if (!first && /^[\u4e00-\u9fff]/.test(segment) && !/[“「(《‘『【(]$/.test(String(parts.at(-1)))) parts.push(document.createElement('wbr')); parts.push(segment); first = false; } } @@ -224,7 +224,8 @@ export function showReportTip(bar, anchor, t, {mode = 'invite', submit, onHide = tip.animate([{maxHeight: `${tip.offsetHeight}px`, paddingTop: '6px', opacity: 1}, {maxHeight: '0px', paddingTop: '0px', opacity: 0}], {duration: 240, easing: 'cubic-bezier(.4,0,.2,1)', fill: 'forwards'}).finished.then(() => tip.remove(), () => tip.remove()); }; - const dismiss = () => { closeForGood(); hide(); }; + // The advice card is no invitation: closing it leaves the later invitations alone. + const dismiss = () => { if (mode !== 'advice') closeForGood(); hide(); }; // Leaving by hand returns focus to the Report button, as Esc does. const leave = () => { dismiss(); anchor.focus(); }; close.onclick = leave; @@ -249,14 +250,39 @@ export function showReportTip(bar, anchor, t, {mode = 'invite', submit, onHide = close.remove(); done.focus({preventScroll: true}); } - mark.append(glyph('report')); + if (mode !== 'advice') mark.append(glyph('report')); + if (mode === 'advice') { + // A known error with its own advice: the advice first, then the way on to the feedback page. + tip.classList.add('fv-report-tip-advice'); + lead.replaceChildren(...words(leadText)); + const next = el('button', 'fv-action fv-action-primary'); next.type = 'button'; + next.append(el('span', null, t('Continue to feedback', '继续反馈')), glyph('external')); + next.onclick = () => { hide(); proceed?.(); }; + row.append(next); + text.append(lead); + card.append(text, row, close); + tip.append(card); + tip.addEventListener('keydown', event => { + if (event.key !== 'Escape') return; + event.preventDefault(); event.stopPropagation(); leave(); + }); + bar.after(tip); + const place = anchor.getBoundingClientRect(), shape = card.getBoundingClientRect(); + tip.style.setProperty('--fv-tip-notch', `${Math.max(18, Math.min(shape.width - 18, place.left + place.width / 2 - shape.left))}px`); + if (animate && !reducedMotion() && typeof tip.animate === 'function') { + tip.animate([{maxHeight: '0px', paddingTop: '0px', opacity: 0}, {maxHeight: `${tip.offsetHeight}px`, paddingTop: '6px', opacity: 1}], + {duration: 340, easing: 'cubic-bezier(.22,1,.36,1)'}); + } + next.focus({preventScroll: true}); + return tip; + } if (mode === 'downloaded') { tip.classList.add('fv-report-tip-downloaded'); title.textContent = t('Diagnostic report downloaded', '诊断报告已下载'); } else { title.textContent = t('Share a diagnostic report?', '欢迎提交诊断报告'); } - lead.replaceChildren(...words(t("We'll optimize specifically for your setup, and it helps other users too.", + lead.replaceChildren(...words(leadText || t("We'll optimize specifically for your setup, and it helps other users too.", '我们会针对您的硬件配置进行专门优化,也能帮助其他用户。'))); note.append(glyph('lock', 'fv-report-tip-lock'), t('Hardware, settings and timings only. No prompts, images or videos.', '仅包含硬件信息、生成参数和耗时,不含提示词、参考图或视频。')); diff --git a/web/result_actions.css b/web/result_actions.css index 4c557d7b..08551e25 100644 --- a/web/result_actions.css +++ b/web/result_actions.css @@ -61,6 +61,7 @@ .fv-actions .fv-action-report.fv-report-attention::after{content:'';position:absolute;top:-3px;right:-3px;width:9px;height:9px;border-radius:var(--fv-r-pill);background:var(--fv-accent,#6db8fa);box-shadow:0 0 0 2px var(--fv-bg,#111720)} /* A narrow card keeps the text on full-width lines and moves the button below it. */ @container (max-width:640px){:is(.fv-result-links,.fv-failure,.fv-preview-column)>.fv-report-tip .fv-report-tip-card{flex-wrap:wrap;align-items:flex-start;padding-right:40px}:is(.fv-result-links,.fv-failure,.fv-preview-column)>.fv-report-tip .fv-report-tip-text{flex:1 1 calc(100% - 50px)}:is(.fv-result-links,.fv-failure,.fv-preview-column)>.fv-report-tip .fv-report-tip-actions{margin-left:50px}:is(.fv-result-links,.fv-failure,.fv-preview-column)>.fv-report-tip .fv-report-tip-close{position:absolute;top:8px;right:8px}} +@container (max-width:640px){:is(.fv-result-links,.fv-failure,.fv-preview-column)>.fv-report-tip.fv-report-tip-advice .fv-report-tip-text{flex-basis:100%}:is(.fv-result-links,.fv-failure,.fv-preview-column)>.fv-report-tip.fv-report-tip-advice .fv-report-tip-actions{margin-left:0}} @media(prefers-reduced-motion:reduce){:is(.fv-result-links,.fv-failure,.fv-preview-column)>.fv-report-tip .fv-report-tip-mark{transition:none}} @keyframes fv-menu-enter{from{opacity:0;transform:translateY(4px)}to{opacity:1;transform:none}} @media(prefers-reduced-motion:reduce){.fv-actions *{transition:none!important;animation:none!important}} From 69acb6cb9f2a7bc4d792cbe05213e0cb6d16729f Mon Sep 17 00:00:00 2001 From: Bowen Xue Date: Thu, 19 Nov 2026 08:49:43 +0000 Subject: [PATCH 04/21] H3 Image: the picture worker runs on CUDA's native allocator where ComfyUI had chosen the... H3 Image: the picture worker runs on CUDA's native allocator where ComfyUI had chosen the asynchronous one --- freevideo_engine/image_gen/service.py | 20 +++++++++++++++++++- 1 file changed, 19 insertions(+), 1 deletion(-) diff --git a/freevideo_engine/image_gen/service.py b/freevideo_engine/image_gen/service.py index 533ea78a..87563a2b 100644 --- a/freevideo_engine/image_gen/service.py +++ b/freevideo_engine/image_gen/service.py @@ -94,6 +94,24 @@ 'invalid_media', 'invalid_points', 'too_many_images')) | LORA_ERRORS +def native_allocator(env): + """``env`` with CUDA's native caching allocator where ComfyUI had chosen the asynchronous one. + + ComfyUI turns ``backend:cudaMallocAsync`` on in its own process and every child inherits it. The video worker + names its allocator itself; the picture worker did not, so its card memory was counted by an allocator the + placement plan was never measured with.""" + selected = env.get('PYTORCH_ALLOC_CONF', env.get('PYTORCH_CUDA_ALLOC_CONF')) + if not selected or 'cudaMallocAsync' not in selected: + return env + options = ['backend:native' if option.strip() == 'backend:cudaMallocAsync' else option + for option in selected.split(',')] + if 'backend:native' not in options: + options.insert(0, 'backend:native') + value = ','.join(option for option in options if 'cudaMallocAsync' not in option) + env.update(PYTORCH_ALLOC_CONF=value, PYTORCH_CUDA_ALLOC_CONF=value) + return env + + def comfy_server(): """ComfyUI's server in this process, or None (tests, the engine's own command line).""" try: @@ -2024,7 +2042,7 @@ def environment(self, root): for name in ('FREEVIDEO_RUNTIME_LOCK_FD', processes.HANDLE_ENV, resident_process.ENV, 'FREEVIDEO_PROMPT_PRESTART_WORKER'): env.pop(name, None) - return env + return native_allocator(env) def takes_video_room(self, machine, model): """Whether loading ``model`` now would give back what the kept video worker holds, as a picture session does From e9479872c35ef10dba82f0778bb5d6bb02a24dfc Mon Sep 17 00:00:00 2001 From: Bowen Xue Date: Thu, 19 Nov 2026 06:23:41 +0000 Subject: [PATCH 05/21] Export at 48 or 60 fps: the frames in between are made on the graphics card, cuts and still... Export at 48 or 60 fps: the frames in between are made on the graphics card, cuts and still frames are left as they are, and the sound is copied unchanged The two failure messages say what to do, in the wording agreed for the export dialog (English and Chinese). --- THIRD_PARTY_NOTICES.md | 1 + freevideo_engine/agent/routes.py | 9 +- freevideo_engine/component_licenses.py | 10 + freevideo_engine/editor_export.py | 65 +++- freevideo_engine/editor_export_options.py | 23 +- freevideo_engine/frame_interp.py | 366 ++++++++++++++++++ .../licenses/Practical-RIFE-MIT.txt | 21 + freevideo_engine/rife/__init__.py | 108 ++++++ freevideo_engine/rife_interp_model.json | 12 + pyproject.toml | 2 +- web/editor.js | 8 +- web/editor_export_dialog.js | 18 +- web/editor_voice_store.js | 3 +- 13 files changed, 627 insertions(+), 19 deletions(-) create mode 100644 freevideo_engine/frame_interp.py create mode 100644 freevideo_engine/licenses/Practical-RIFE-MIT.txt create mode 100644 freevideo_engine/rife/__init__.py create mode 100644 freevideo_engine/rife_interp_model.json diff --git a/THIRD_PARTY_NOTICES.md b/THIRD_PARTY_NOTICES.md index 01052663..aa009dd4 100644 --- a/THIRD_PARTY_NOTICES.md +++ b/THIRD_PARTY_NOTICES.md @@ -7,6 +7,7 @@ FreeVideo code uses [Apache-2.0](LICENSE). Its dependencies and models retain th | [Three.js](https://threejs.org/) r160 and its TransformControls (examples/jsm; import path and handle colours changed), © 2010–2023 three.js authors (bundled whitebox renderer and mannequin) | [MIT](web/vendor/three/LICENSE) | | [Depth Anything V2 Small](https://github.com/DepthAnything/Depth-Anything-V2/tree/a561b849ebae10a6f5ef49e26c83cbbcd36c71bf), © 2024 Depth Anything authors; DINOv2 © Meta Platforms, Inc. and affiliates. Small-only DPT/DINOv2 inference and preprocessing are adapted and bundled; Small weights are an optional download pinned at `03876f8651c73a60fe4c2c48294e09fcb6838fcf`. | [Apache-2.0 (code and Small weights)](freevideo_engine/licenses/Depth-Anything-V2-Apache-2.0.txt) | | [Real-ESRGAN](https://github.com/xinntao/Real-ESRGAN/tree/685d429c81888252bdb10f56c7754baededc3823) realesr-general-x4v3, © 2021 Xintao Wang. The SRVGGNetCompact inference network is adapted and bundled for upscaling finished videos to 4K; the weights are an optional download (4,885,111 bytes, SHA-256 `8dc7edb9ac80ccdc30c3a5dca6616509367f05fbc184ad95b731f05bece96292`, the v0.2.5.0 release file). | [BSD-3-Clause (code and weights)](freevideo_engine/licenses/Real-ESRGAN-BSD-3-Clause.txt) | +| [RIFE (Practical-RIFE) 4.25](https://github.com/hzwer/Practical-RIFE/tree/bbfd2ea90910789a860ea3e2b32a240cd577b75e), © 2021 hzwer. The IFNet inference network is adapted and bundled for 48/60 fps export; the 4.25 weights are an optional download pinned at Comfy-Org/Frame-Interpolation `aa7009be4d1471ea0bac91d6fe4d7e4b637cbbfc`. | [MIT (code and weights)](freevideo_engine/licenses/Practical-RIFE-MIT.txt) | | Qt, PySide6 and Shiboken6 | LGPL-3.0; [component notices](freevideo_engine/launcher/licenses/NOTICE.txt) | | PyInstaller bootloader | GPL-2.0 with the bootloader exception | | CPython / psutil | PSF / BSD-3-Clause | diff --git a/freevideo_engine/agent/routes.py b/freevideo_engine/agent/routes.py index 48e00898..9f2f7bdc 100644 --- a/freevideo_engine/agent/routes.py +++ b/freevideo_engine/agent/routes.py @@ -204,7 +204,7 @@ def voice_ready(port): return voice_state(port)[0] -def features(continuation, vlm, stems=False, voice=True, voice_install=False): +def features(continuation, vlm, stems=False, voice=True, voice_install=False, fps=False): """What an agent can use here (ready says whether the engine can run now). A missing name is not offered.""" from .editor_runtime import available rules = available() @@ -219,7 +219,9 @@ def features(continuation, vlm, stems=False, voice=True, voice_install=False): 'finish_sound')}, 'projects.stems': bool(rules and stems), 'projects.voice': bool(rules and stems and voice), # The machine could change a voice but the dubbing model is not there yet: the page offers its download. - 'projects.voice.install': bool(rules and stems and voice_install and not voice)} + 'projects.voice.install': bool(rules and stems and voice_install and not voice), + # 48/60 fps export makes the frames in between on the graphics card (far too slow without one). + 'projects.export.fps': bool(rules and fps)} def whitebox_support(jobs): @@ -258,7 +260,8 @@ def capabilities(port, jobs): return dict( api_version=API_VERSION, freevideo_version=release or __version__, build=__version__, ready=ready, problem=problem, continuation=continuation, - features=features(continuation, vlm, stems=stems_supported(machine), voice=voice[0], voice_install=voice[1]), + features=features(continuation, vlm, stems=stems_supported(machine), voice=voice[0], voice_install=voice[1], + fps=bool(machine) and machine.get('device_backend', 'cuda') == 'cuda'), whitebox=whitebox_support(jobs), device=dict(backend=machine.get('device_backend', 'cuda') if machine else None, vram_limit_gib=machine.get('vram_gib'), ram_limit_gib=machine.get('ram_gib')), diff --git a/freevideo_engine/component_licenses.py b/freevideo_engine/component_licenses.py index 56246938..e022b431 100644 --- a/freevideo_engine/component_licenses.py +++ b/freevideo_engine/component_licenses.py @@ -43,6 +43,9 @@ def row(key, name, licence, link, text=None, terms=None): UPSCALE = row('frame-upscale', ('Real-ESRGAN realesr-general-x4v3 code and weights', 'Real-ESRGAN realesr-general-x4v3 代码和权重'), ('BSD 3-Clause License', 'BSD 三条款许可证'), 'https://github.com/xinntao/Real-ESRGAN/blob/685d429c81888252bdb10f56c7754baededc3823/LICENSE') +RIFE = row('frame-interpolation', ('RIFE frame interpolation code and weights', 'RIFE 补帧代码和权重'), + ('MIT License', 'MIT 许可证'), + 'https://github.com/hzwer/Practical-RIFE/blob/bbfd2ea90910789a860ea3e2b32a240cd577b75e/LICENSE') def depth_license(): @@ -51,6 +54,10 @@ def depth_license(): def upscale_license(): return local(UPSCALE, HERE / 'licenses/Real-ESRGAN-BSD-3-Clause.txt') + + +def rife_license(): + return local(RIFE, HERE / 'licenses/Practical-RIFE-MIT.txt') # Libraries a runtime may carry, found by file name: versioned Windows names and Linux # lib*.so.* alike. A CUDA build of Torch counts for CUDA, so a runtime whose CUDA files # are named otherwise still lists it. @@ -135,6 +142,9 @@ def bundle(root, value): if any(entry['path'].replace('\\', '/').endswith('freevideo_engine/frame_upscale.py') or entry['path'].endswith('realesr-general-x4v3.pth') for entry in value['files']): rows.append(upscale_license()) + if any('freevideo_engine/rife/' in entry['path'].replace('\\', '/') + or entry['path'].endswith('rife_v4.25.safetensors') for entry in value['files']): + rows.append(rife_license()) return rows diff --git a/freevideo_engine/editor_export.py b/freevideo_engine/editor_export.py index 4a45561f..e0c2f5f5 100644 --- a/freevideo_engine/editor_export.py +++ b/freevideo_engine/editor_export.py @@ -5,6 +5,7 @@ """ import asyncio import copy +import dataclasses import errno import importlib import json @@ -46,7 +47,8 @@ class ExportError(Exception): """A public reason code; never retain a decoder's path-bearing message.""" def __init__(self, reason='failed'): - self.reason = reason if reason in ('source_missing', 'unreadable', 'disk_full', 'not_writable', 'failed') else 'failed' + self.reason = reason if reason in ('source_missing', 'unreadable', 'disk_full', 'not_writable', 'failed', + 'interp_download', 'interp_memory') else 'failed' super().__init__(self.reason) @@ -646,6 +648,18 @@ def render(project: dict, resolve, target: Path, *, progress=None, cancelled=Non Raises ExportError(reason) or ExportCancelled and removes owned partials. Existing destinations are refused and never removed. """ + try: + width, height, total, tracks = _layout(project) + settings = editor_export_options.effective(options, width, height, total) + except Exception: + settings = None # _render_once reports it the usual way + if settings is not None and settings.only == 'video' and settings.fps != FPS: + return _render_faster(project, resolve, target, settings, tracks.get('v1', []), + progress=progress, cancelled=cancelled) + return _render_seams(project, resolve, target, progress=progress, cancelled=cancelled, options=options) + + +def _render_seams(project, resolve, target, *, progress, cancelled, options): try: return _render_once(project, resolve, target, progress=progress, cancelled=cancelled, options=options, repair_seams=True) @@ -657,6 +671,55 @@ def render(project: dict, resolve, target: Path, *, progress=None, cancelled=Non options=options, repair_seams=False) +# Share of the progress bar for the 24 fps picture; interpolation and its encode take the rest (measured at 1080p). +_FIRST_PASS_SHARE = .4 + + +def _render_faster(project, resolve, target, settings, clips, *, progress, cancelled): + """48/60 fps: the usual 24 fps render to a near-lossless file next to the target, then frame interpolation.""" + from . import frame_interp + target = Path(target) + if target.exists() or target.is_symlink(): + raise ExportError() + target.parent.mkdir(parents=True, exist_ok=True) + base = target.with_name('.editor-export-24-' + uuid.uuid4().hex + '.mp4') + faster = _checked_target(target.with_name('.editor-export-' + uuid.uuid4().hex + '.mp4')) + first = (lambda fraction: progress(min(fraction, .99) * _FIRST_PASS_SHARE)) if progress else None + published = False + try: + _render_seams(project, resolve, base, progress=first, cancelled=cancelled, + options=dataclasses.replace(settings, fps=FPS, intermediate=True)) + _check(cancelled) + + def moved(value): + if progress and value.get('stage') == frame_interp.STAGE and value.get('total'): + progress(_FIRST_PASS_SHARE + (1 - _FIRST_PASS_SHARE) * .99 * value['done'] / value['total']) + try: + frame_interp.convert(base, faster, fps=settings.fps, video_options=settings.video_options, + cuts=frame_interp.cuts_of(clips, settings.start, settings.frames), + progress=moved, cancelled=cancelled) + except frame_interp.InterpolationError as error: + raise ExportError(error.code) from error + _check(cancelled) + _checked_target(faster) + with faster.open('r+b') as stream: + os.fsync(stream.fileno()) + _check(cancelled) + _checked_target(target) + faster.replace(target) + published = True + if progress: + progress(1.) + return target + except BaseException: + if published: + target.unlink(missing_ok=True) + raise + finally: + base.unlink(missing_ok=True) + faster.unlink(missing_ok=True) + + def _render_once(project, resolve, target, *, progress, cancelled, options, repair_seams): import av import numpy as np diff --git a/freevideo_engine/editor_export_options.py b/freevideo_engine/editor_export_options.py index 89df3bf1..c895e371 100644 --- a/freevideo_engine/editor_export_options.py +++ b/freevideo_engine/editor_export_options.py @@ -14,6 +14,9 @@ class ExportOptions: quality: str = 'high' sound_format: str = 'm4a' subtitles: str = 'burn' + # Above 24 the picture is first rendered at 24 fps (intermediate) and then interpolated. + fps: int = 24 + intermediate: bool = False @property def filename(self): @@ -30,6 +33,9 @@ def container_options(self): @property def video_options(self): + if self.intermediate: + # Near-lossless and quick: only the interpolation step reads it, then it is removed. + return {'crf': '10', 'preset': 'veryfast'} return {'crf': str({'high': 23, 'standard': 25, 'small': 30}[self.quality]), 'preset': 'medium'} @property @@ -41,12 +47,16 @@ def status(self): only=self.only, quality=self.quality if self.only == 'video' else None, range=dict(start=self.start, frames=self.frames), sound_format=self.sound_format if self.only == 'sound' else None, - **({'subtitles': 'none'} if self.only == 'video' and self.subtitles == 'none' else {})) + **({'subtitles': 'none'} if self.only == 'video' and self.subtitles == 'none' else {}), + **({'fps': self.fps} if self.only == 'video' and self.fps != 24 else {})) + + +FRAME_RATES = (24, 48, 60) def validate(options, width, height, frames): """Validate wire values once; the queue passes the immutable result to render.""" - if not isinstance(options, dict) or set(options) - {'short', 'quality', 'range', 'only', 'sound_format', 'subtitles'}: + if not isinstance(options, dict) or set(options) - {'short', 'quality', 'range', 'only', 'sound_format', 'subtitles', 'fps'}: raise ValueError('Invalid export options') if 'short' in options and (type(options['short']) is not int or not 144 <= options['short'] <= 4320 or options['short'] % 2): @@ -63,6 +73,8 @@ def validate(options, width, height, frames): or span['start'] < 0 or span['frames'] < 1 or span['start'] + span['frames'] > frames): raise ValueError('Invalid export range') start, count = span['start'], span['frames'] + if 'fps' in options and (type(options['fps']) is not int or options['fps'] not in FRAME_RATES): + raise ValueError('Invalid export fps') if options.get('only') == 'sound': return ExportOptions(0, 0, start, count, only='sound', sound_format=options.get('sound_format', 'm4a')) output_width, output_height = width, height @@ -74,7 +86,7 @@ def validate(options, width, height, frames): if max(output_width, output_height) > 8192: raise ValueError('Export picture is too large') return ExportOptions(output_width, output_height, start, count, quality=options.get('quality', 'high'), - subtitles=options.get('subtitles', 'burn')) + subtitles=options.get('subtitles', 'burn'), fps=options.get('fps', 24)) def effective(options, width, height, frames): @@ -105,12 +117,15 @@ def sound_samples(mixed, options): def report_values(report, options): geometry = report['geometry'] - if (options.only == 'video' and options.quality == 'high' and options.start == 0 + if (options.only == 'video' and options.quality == 'high' and options.start == 0 and options.fps == 24 and (options.width, options.height, options.frames) == (geometry['width'], geometry['height'], geometry['frames'])): return # Preserve the original default completion marker as well as media. report['geometry'].update(width=options.width, height=options.height, frames=options.frames, seconds=options.frames / 24) + if options.only == 'video' and options.fps != 24: + # The picture has fps times as many frames per second; the length stays the same. + report['geometry'].update(fps=options.fps, frames=-(-options.frames * options.fps // 24)) if options.only == 'sound': report.pop('video', None) report['audio'] = dict(format=options.sound_format) diff --git a/freevideo_engine/frame_interp.py b/freevideo_engine/frame_interp.py new file mode 100644 index 00000000..01e33516 --- /dev/null +++ b/freevideo_engine/frame_interp.py @@ -0,0 +1,366 @@ +"""Export at 48 or 60 fps: frames between the 24 fps frames are made by RIFE 4.25, in a disposable worker. + +The editor renders its 24 fps picture first (near-lossless); this worker reads it, writes the faster picture at the +user's quality and copies the sound unchanged. Nothing is made across a cut: there the nearer frame is repeated, and two +equal frames (a still) are copied without the model. Torch lives only in the worker. +""" +from contextlib import contextmanager +from fractions import Fraction +import hashlib +import json +import math +import os +from pathlib import Path +import subprocess +import tempfile +import time + +from . import processes +from .paths import data_root + +STAGE = 'frame_interp' +SOURCE_FPS = 24 +# Optical flow at half scale above 1080p: as sharp in the measured clips, and less memory. +FULL_SCALE_LONG_SIDE = 1920 + + +class InterpolationError(RuntimeError): + """code: 'interp_download' (the model could not be fetched) or 'interp_memory' (not enough video memory).""" + def __init__(self, code, message=''): + super().__init__(message or code) + self.code = code + + +def catalog(): + return json.loads(Path(__file__).with_name('rife_interp_model.json').read_text(encoding='utf-8')) + + +def output_frames(frames, fps): + return -(-frames * fps // SOURCE_FPS) + + +def plan(frames, fps, cuts=()): + """For every output frame: (left, right, t). right is None where the left frame is copied as it is. + + Output frame j shows time j / fps, that is source position p = j * 24 / fps; t is its fraction. + cuts holds the source frame numbers that start a new shot: no frame is made between cut - 1 and cut. + """ + cuts = set(cuts) + rows = [] + for j in range(output_frames(frames, fps)): + position = Fraction(j * SOURCE_FPS, fps) + left, t = math.floor(position), position - math.floor(position) + right = left + 1 + if t == 0 or right >= frames: + rows.append((min(left, frames - 1), None, 0.)) + elif right in cuts: + rows.append((left, None, 0.) if t < Fraction(1, 2) else (right, None, 0.)) + else: + rows.append((left, right, float(t))) + return rows + + +def cuts_of(clips, start, frames): + """Source frames (relative to the exported range) where the v1 picture changes to another clip or to black.""" + edges = set() + for clip in clips: + for edge in (clip['start'], clip['start'] + clip['frames']): + if start < edge < start + frames: + edges.add(edge - start) + return sorted(edges) + + +def _digest(path, check=lambda: None): + value = hashlib.sha256() + with Path(path).open('rb') as stream: + while block := stream.read(1024 * 1024): + check() + value.update(block) + return value.hexdigest() + + +@contextmanager +def _lock(path, check): + from .locking import runtime_lock + while True: + check() + try: + lease = runtime_lock(path) + lease.__enter__() + break + except BlockingIOError: + time.sleep(.1) + try: + yield + finally: + lease.__exit__(None, None, None) + + +def weights_folder(root): + return Path(root) / 'models' / 'rife' + + +def ensure_weights(root, emit, check): + """The same optional-model catalog, pins, resume and mainland fallback as the depth reference model.""" + from . import network + from .adaln_assets import _download_plan + from .prompt_vlm.assets import remote + spec = catalog() + row = spec['files'][0] + folder = weights_folder(root) + folder.mkdir(parents=True, exist_ok=True) + path = folder / Path(row['file']).name + with _lock(folder / 'download.lock', check): + if path.is_file() and path.stat().st_size == row['bytes'] and _digest(path, check) == row['sha256']: + return path + if path.exists(): + network.retain_partial(path, 'rejected') + plan_ = _download_plan(Path(root)) + sources = plan_['sources'] = dict(plan_.get('sources', {})) + if not sources.get('image-models'): + sources['image-models'] = [dict(item) for item in sources.get('models', []) + if item['id'] in ('official', 'hf-mirror')] + sources['image-models'].append({'id': 'modelscope'}) + plan_.update(quiet=True, resource_check=check) + + def moved(current, total, speed, **_): + emit(stage='frame_interp_download', done=current, total=row['bytes'], unit='bytes', bytes_per_second=speed) + check() + try: + network.download(network.model_urls(plan_, remote(spec, row)), path, row['sha256'], moved, + network=plan_, size=row['bytes'], category='image-models', keep_partial=True, + stall_seconds=30, slow_seconds=15, low_speed_limit=64 * 1024) + except Exception as error: + from .sampling_assets import _cancel_or_disk + if _cancel_or_disk(error): + raise + check() + raise InterpolationError('interp_download', 'Frame interpolation weights are unavailable. Retry with a ' + 'connection, or put rife_v4.25.safetensors (22,674,688 bytes, SHA-256 ' + + row['sha256'] + ') in ' + str(folder)) from error + if path.stat().st_size != row['bytes'] or _digest(path, check) != row['sha256']: + raise InterpolationError('interp_download', 'Frame interpolation weight size/SHA-256 verification failed') + return path + + +def write(source, target, *, fps, video_options, cuts, between, emit, check): + """Read the 24 fps source, write `fps` frames per second to target, copy its sound packets unchanged. + + between(a, b, t) returns the RGB frame at fraction t from a to b (uint8 arrays). Memory: two source frames. + """ + import av + import numpy as np + with av.open(str(source)) as reader, av.open(str(source)) as sound_reader: + stream = reader.streams.video[0] + frames = stream.frames or None + if not frames: + with av.open(str(source)) as counter: + frames = sum(1 for _ in counter.decode(video=0)) + rows = plan(frames, fps, cuts) + sound = sound_reader.streams.audio[0] if sound_reader.streams.audio else None + with av.open(str(target), 'w', format='mp4', + options={'movflags': 'use_metadata_tags+faststart', 'movie_timescale': '48000'}) as output: + video = output.add_stream('libx264', rate=fps) + video.width, video.height, video.pix_fmt = stream.codec_context.width, stream.codec_context.height, 'yuv420p' + video.options = dict(video_options) + video.codec_context.thread_count = 4 + audio = output.add_stream_from_template(sound) if sound is not None else None + packets = sound_reader.demux(sound) if sound is not None else iter(()) + pending = None + + def sound_until(seconds): + # Interleave sound with the picture so a player never has to read far ahead. + nonlocal pending + while True: + if pending is None: + pending = next(packets, None) + if pending is None: + return + if pending.dts is None: + pending = None + continue + if seconds is not None and float(pending.dts * pending.time_base) > seconds: + return + pending.stream = audio + output.mux(pending) + pending = None + + decoded = reader.decode(stream) + window = {} + next_number = 0 + + def frame(number): + nonlocal next_number + while number not in window: + value = next(decoded, None) + if value is None: + # A short stream: hold its last frame. + window[number] = window[max(window)] + break + window[next_number] = value.to_ndarray(format='rgb24') + next_number += 1 + for old in [key for key in window if key < number - 1]: + del window[old] + return window[number] + + for j, (left, right, t) in enumerate(rows): + check() + a = frame(left) + if right is None: + pixels = a + else: + b = frame(right) + pixels = a if np.array_equal(a, b) else between(a, b, t) + picture = av.VideoFrame.from_ndarray(np.ascontiguousarray(pixels), format='rgb24') + picture.pts, picture.time_base = j, Fraction(1, fps) + sound_until(j / fps) + for packet in video.encode(picture): + output.mux(packet) + emit(done=j + 1, total=len(rows)) + for packet in video.encode(None): + check() + output.mux(packet) + sound_until(None) + return len(rows) + + +def model_between(weights, device): + """RIFE in this process: returns between(a, b, t) and drops to half-scale flow once if memory runs out.""" + import numpy as np + import torch + from safetensors.torch import load_file + from .rife import IFNet, interpolate + net = IFNet() + net.load_state_dict(load_file(str(weights)), strict=True) + net = net.eval().to(device) + state = dict(scale=None) + + def tensor(image): + return torch.from_numpy(image).to(device).permute(2, 0, 1)[None].float().div_(255.) + + def between(a, b, t): + if state['scale'] is None: + state['scale'] = 1.0 if max(a.shape[:2]) <= FULL_SCALE_LONG_SIDE else .5 + while True: + try: + with torch.inference_mode(): + out = interpolate(net, tensor(a), tensor(b), t, state['scale']) + return (out[0].permute(1, 2, 0).mul_(255.).add_(.5).clamp_(0, 255).to(torch.uint8).cpu().numpy()) + except torch.cuda.OutOfMemoryError: + torch.cuda.empty_cache() + if state['scale'] <= .5: + raise InterpolationError('interp_memory', 'Not enough video memory for frame interpolation') from None + state['scale'] = .5 + return between + + +def main(): + import argparse + from .monitoring import save + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument('--request', required=True, type=Path) + args = parser.parse_args() + request = json.loads(args.request.read_text(encoding='utf-8')) + work = Path(request['work']) + + def check(): + if (work / 'cancelled').exists(): + raise InterruptedError('Frame interpolation cancelled') + state = dict(stage=STAGE, done=0, total=None, unit='frames') + + def emit(**values): + state.update(values) + save(work / 'progress.json', state) + try: + with processes.worker_signals(): + weights = ensure_weights(request['root'], emit, check) + emit(stage=STAGE, done=0, total=None, unit='frames') + between = model_between(weights, request.get('device', 'cuda')) + write(request['source'], request['target'], fps=request['fps'], video_options=request['video_options'], + cuts=request['cuts'], between=between, emit=emit, check=check) + except Exception as error: + save(work / 'error.json', dict(error=type(error).__name__ + ': ' + str(error), + code=getattr(error, 'code', None))) + return 1 + return 0 + + +def release_gpu(required=3 * 2 ** 30): + """Inside ComfyUI, let go of only as much video memory as the worker needs; other models stay loaded.""" + try: + import comfy.model_management as memory + except ImportError: + return + try: + device = memory.get_torch_device() + memory.free_memory(required, device) + memory.soft_empty_cache() + except Exception: + pass + + +def convert(source, target, *, fps, video_options, cuts, root=None, python=None, environ=None, + progress=None, cancelled=None, release=release_gpu): + """Run the worker; target exists only after it exits cleanly. progress gets done/total output frames.""" + root = Path(root or data_root()).resolve() + target = Path(target) + + def check(): + if cancelled and cancelled(): + from .editor_export import ExportCancelled + raise ExportCancelled() + check() + if release: + release() + with tempfile.TemporaryDirectory(prefix='.interp-', dir=target.parent) as directory: + work = Path(directory) + request = dict(source=str(Path(source).resolve()), target=str(target.resolve()), fps=int(fps), + video_options=dict(video_options), cuts=[int(c) for c in cuts], root=str(root), + device='cuda', work=str(work)) + (work / 'request.json').write_text(json.dumps(request), encoding='utf-8') + command = processes.module_command('freevideo_engine.frame_interp', '--request', work / 'request.json') + if python is not None: + command[0] = str(python) + with (work / 'worker.log').open('wb') as log: + child = processes.popen(command, env=environ, stdin=subprocess.DEVNULL, stdout=log, stderr=subprocess.STDOUT, + start_new_session=True, supervise=True, pass_fds=processes.descriptors()) + last = None + + def poll(): + nonlocal last + check() + try: + value = json.loads((work / 'progress.json').read_text(encoding='utf-8')) + except (OSError, ValueError): + return + if progress and value != last: + progress(value) + last = value + try: + while child.poll() is None: + poll() + try: + child.wait(timeout=.1) + except subprocess.TimeoutExpired: + pass + poll() + if child.returncode: + try: + error = json.loads((work / 'error.json').read_text(encoding='utf-8')) + except (OSError, ValueError): + error = {} + if error.get('code') in ('interp_download', 'interp_memory'): + raise InterpolationError(error['code'], error.get('error', '')) + raise RuntimeError(error.get('error') or 'Frame interpolation worker exited with code %s' + % child.returncode) + check() + return target + except BaseException: + (work / 'cancelled').touch() + processes.stop(child) + Path(target).unlink(missing_ok=True) + raise + + +if __name__ == '__main__': + raise SystemExit(main()) diff --git a/freevideo_engine/licenses/Practical-RIFE-MIT.txt b/freevideo_engine/licenses/Practical-RIFE-MIT.txt new file mode 100644 index 00000000..d6c5c55f --- /dev/null +++ b/freevideo_engine/licenses/Practical-RIFE-MIT.txt @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2021 hzwer + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/freevideo_engine/rife/__init__.py b/freevideo_engine/rife/__init__.py new file mode 100644 index 00000000..a05758ad --- /dev/null +++ b/freevideo_engine/rife/__init__.py @@ -0,0 +1,108 @@ +# RIFE (Practical-RIFE 4.25 IFNet_HDv3), Copyright (c) 2021 hzwer. +# Adapted from https://github.com/hzwer/Practical-RIFE/tree/bbfd2ea90910789a860ea3e2b32a240cd577b75e for inference. +# SPDX-License-Identifier: MIT; see freevideo_engine/licenses/Practical-RIFE-MIT.txt. +# Changes: inference only (no teacher, timestep network or ensemble), the five blocks in one list so the +# published safetensors keys (blocks.N.*) load directly, and padding/scale handling in interpolate(). +import math + +import torch +import torch.nn as nn +import torch.nn.functional as F + +_grids = {} + + +def warp(tensor, flow): + key = (str(flow.device), flow.dtype, flow.shape) + if key not in _grids: + n, _, h, w = flow.shape + hor = torch.linspace(-1.0, 1.0, w, device=flow.device, dtype=flow.dtype).view(1, 1, 1, w).expand(n, -1, h, -1) + ver = torch.linspace(-1.0, 1.0, h, device=flow.device, dtype=flow.dtype).view(1, 1, h, 1).expand(n, -1, -1, w) + _grids[key] = torch.cat([hor, ver], 1) + flow = torch.cat([flow[:, 0:1] / ((tensor.shape[3] - 1.0) / 2.0), flow[:, 1:2] / ((tensor.shape[2] - 1.0) / 2.0)], 1) + grid = (_grids[key] + flow).permute(0, 2, 3, 1) + return F.grid_sample(tensor, grid, mode='bilinear', padding_mode='border', align_corners=True) + + +def conv(in_planes, out_planes, kernel_size=3, stride=1, padding=1, dilation=1): + return nn.Sequential(nn.Conv2d(in_planes, out_planes, kernel_size=kernel_size, stride=stride, + padding=padding, dilation=dilation, bias=True), nn.LeakyReLU(0.2, True)) + + +class Head(nn.Module): + def __init__(self): + super().__init__() + self.cnn0 = nn.Conv2d(3, 16, 3, 2, 1) + self.cnn1 = nn.Conv2d(16, 16, 3, 1, 1) + self.cnn2 = nn.Conv2d(16, 16, 3, 1, 1) + self.cnn3 = nn.ConvTranspose2d(16, 4, 4, 2, 1) + self.relu = nn.LeakyReLU(0.2, True) + + def forward(self, x): + x = self.relu(self.cnn0(x)) + x = self.relu(self.cnn1(x)) + x = self.relu(self.cnn2(x)) + return self.cnn3(x) + + +class ResConv(nn.Module): + def __init__(self, c, dilation=1): + super().__init__() + self.conv = nn.Conv2d(c, c, 3, 1, dilation, dilation=dilation, groups=1) + self.beta = nn.Parameter(torch.ones((1, c, 1, 1)), requires_grad=True) + self.relu = nn.LeakyReLU(0.2, True) + + def forward(self, x): + return self.relu(self.conv(x) * self.beta + x) + + +class IFBlock(nn.Module): + def __init__(self, in_planes, c=64): + super().__init__() + self.conv0 = nn.Sequential(conv(in_planes, c // 2, 3, 2, 1), conv(c // 2, c, 3, 2, 1)) + self.convblock = nn.Sequential(*(ResConv(c) for _ in range(8))) + self.lastconv = nn.Sequential(nn.ConvTranspose2d(c, 4 * 13, 4, 2, 1), nn.PixelShuffle(2)) + + def forward(self, x, flow=None, scale=1): + x = F.interpolate(x, scale_factor=1. / scale, mode='bilinear', align_corners=False) + if flow is not None: + flow = F.interpolate(flow, scale_factor=1. / scale, mode='bilinear', align_corners=False) * 1. / scale + x = torch.cat((x, flow), 1) + feat = self.convblock(self.conv0(x)) + tmp = F.interpolate(self.lastconv(feat), scale_factor=scale, mode='bilinear', align_corners=False) + return tmp[:, :4] * scale, tmp[:, 4:5], tmp[:, 5:] + + +class IFNet(nn.Module): + def __init__(self): + super().__init__() + self.blocks = nn.ModuleList([IFBlock(7 + 8, c=192), IFBlock(8 + 4 + 8 + 8, c=128), IFBlock(8 + 4 + 8 + 8, c=96), + IFBlock(8 + 4 + 8 + 8, c=64), IFBlock(8 + 4 + 8 + 8, c=32)]) + self.encode = Head() + + def forward(self, img0, img1, timestep, scale_list): + timestep = (img0[:, :1].clone() * 0 + 1) * timestep + f0, f1 = self.encode(img0[:, :3]), self.encode(img1[:, :3]) + warped_img0, warped_img1 = img0, img1 + flow = mask = feat = None + for i, block in enumerate(self.blocks): + if flow is None: + flow, mask, feat = block(torch.cat((img0[:, :3], img1[:, :3], f0, f1, timestep), 1), None, scale=scale_list[i]) + else: + wf0, wf1 = warp(f0, flow[:, :2]), warp(f1, flow[:, 2:4]) + fd, mask, feat = block(torch.cat((warped_img0[:, :3], warped_img1[:, :3], wf0, wf1, timestep, mask, feat), 1), + flow, scale=scale_list[i]) + flow = flow + fd + warped_img0, warped_img1 = warp(img0, flow[:, :2]), warp(img1, flow[:, 2:4]) + mask = torch.sigmoid(mask) + return warped_img0 * mask + warped_img1 * (1 - mask) + + +def interpolate(net, a, b, t, scale=1.0): + """a, b: (1, 3, H, W) in 0..1. Pads to the network's multiple, as the reference inference does.""" + _, _, h, w = a.shape + step = max(128, int(128 / scale)) + pad = (0, math.ceil(w / step) * step - w, 0, math.ceil(h / step) * step - h) + a, b = F.pad(a, pad), F.pad(b, pad) + merged = net(a, b, t, [16 / scale, 8 / scale, 4 / scale, 2 / scale, 1 / scale]) + return merged[:, :, :h, :w].clamp(0, 1) diff --git a/freevideo_engine/rife_interp_model.json b/freevideo_engine/rife_interp_model.json new file mode 100644 index 00000000..965541eb --- /dev/null +++ b/freevideo_engine/rife_interp_model.json @@ -0,0 +1,12 @@ +{ + "repo": "Comfy-Org/Frame-Interpolation", + "revision": "aa7009be4d1471ea0bac91d6fe4d7e4b637cbbfc", + "source_commit": "bbfd2ea90910789a860ea3e2b32a240cd577b75e", + "license": "MIT", + "modelscope": {"repo": "Comfy-Org/rife", "revision": "master"}, + "files": [{ + "file": "frame_interpolation/rife_v4.25.safetensors", + "bytes": 22674688, + "sha256": "1505884b9bdae956795430d2a70f7e2317b2abd8f130f8cfdb35a5759f909481" + }] +} diff --git a/pyproject.toml b/pyproject.toml index 7db0915b..428ef840 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -37,4 +37,4 @@ include = ["freevideo_engine*"] "freevideo_engine.prompt_vlm" = ["model.json"] "freevideo_engine.dubbing" = ["cosyvoice3_pack.json"] "freevideo_engine.image_gen" = ["image_models.json", "face_box_weights.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", "frame_preview_decoder.safetensors", "agent/skill/freevideo/*.txt", "agent/skill/freevideo/references/*.txt", "depth_reference_model.json", "frame_upscale_model.json", "swap_lora.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", "frame_preview_decoder.safetensors", "agent/skill/freevideo/*.txt", "agent/skill/freevideo/references/*.txt", "depth_reference_model.json", "frame_upscale_model.json", "rife_interp_model.json", "swap_lora.json"] diff --git a/web/editor.js b/web/editor.js index 985d7000..4cfd0263 100644 --- a/web/editor.js +++ b/web/editor.js @@ -290,7 +290,7 @@ export function openEditor({api, app, from = null, panel = {}, components: given try { if (explainExport()) return; if (exportStatus?.state === 'done' && exportMatches()) { await actions.export(); return; } - const options = await openExportDialog({parent: element, state, sources: store.sources, t, onError: error}); + const options = await openExportDialog({parent: element, state, sources: store.sources, t, onError: error, fps: exportFps}); if (options && !disposed) await actions.export(options); } catch (value) { error(value, 'export'); } }, 'fv-primary fv-ed-export-main'); @@ -712,7 +712,7 @@ export function openEditor({api, app, from = null, panel = {}, components: given // Music on the second sound track goes through the same bar; the bar shows a chosen piece's own job. const music = createEditorMusic({state, store, t, completeSources, onStatus: () => genbar?.update(barValue)}); // Dubbing lines of a stretch of speech. - let voiceReady = false, voiceInstallable = false; + let voiceReady = false, voiceInstallable = false, exportFps = false; const generatedSource = value => { const match = /^generated:(.+)$/.exec(String(value || '')); return match ? {kind: 'generated', id: match[1]} : null; }; // Playing one line: the playhead goes to its start and the picture plays up to its end, then stops. let lineStop = null; @@ -1744,6 +1744,8 @@ export function openEditor({api, app, from = null, panel = {}, components: given if (['source_missing', 'missing_glyphs', 'MissingGlyphs'].includes(value.reason || value.code)) error(value, null, undefined, 'export'); else notify(value.reason === 'not_writable' ? t('Export failed: the output folder cannot be written to. Check that the folder can be written to, then retry.', '导出时出错:输出目录不可写。请检查这个文件夹的写入权限后重试。') : value.reason === 'disk_full' ? t('Export failed: the disk is full. Free some space, then export again.', '导出时出错:磁盘空间不够,空出空间后再导出。') + : value.reason === 'interp_download' ? t('Export failed: the model needed for 48/60 fps could not be downloaded. Check the connection and export again, or set the frame rate to 24.', '导出时出错:48/60 帧率需要的模型没能下载。请检查网络后重新导出,或把帧率改为 24。') + : value.reason === 'interp_memory' ? t('Export failed: the graphics card did not have enough free memory for 48/60 fps. Export again after the current generation finishes, or set the frame rate to 24.', '导出时出错:显卡空闲显存不足,无法导出 48/60 帧率。请等当前生成结束后重新导出,或把帧率改为 24。') : value.reason === 'unreadable' ? t('Export failed: a source file cannot be read. Import it again from the library.', '导出时出错:有素材读不出来,请在素材库重新导入。') : t('Export failed. Try again.', '导出时出错,请再试一次。'), EXPORT_ISSUE, failureKind('export', value)); } @@ -1758,7 +1760,7 @@ export function openEditor({api, app, from = null, panel = {}, components: given const found = await voiceFeatures(api); // An unanswered question changes nothing: the lines stay as they were, and a failed recognition says so. if (found.unknown) return voiceReady; - voiceReady = found.ready; voiceInstallable = found.install; + voiceReady = found.ready; voiceInstallable = found.install; exportFps = found.exportFps; if (!disposed) { voice.refresh(); narration.refresh(); if (found.install) voiceInstall.init(); genbar?.update(barValue); } return found.ready; } diff --git a/web/editor_export_dialog.js b/web/editor_export_dialog.js index 6d00e8b1..fc77f922 100644 --- a/web/editor_export_dialog.js +++ b/web/editor_export_dialog.js @@ -5,7 +5,8 @@ import {selectedRange} from './editor_transport_model.js'; import {isolateDialogKeys, listenDialogKey, routeDialogKey} from './dialog_keys.js'; export const EXPORT_SETTINGS_KEY = 'freevideo.editor.export-settings'; -const defaults = {short: null, quality: 'high', range: 'whole', only: null, sound_format: 'm4a'}; +const defaults = {short: null, quality: 'high', range: 'whole', only: null, sound_format: 'm4a', fps: 24}; +export const FRAME_RATES = [24, 48, 60]; const active = new WeakSet(); const style = document.createElement('link'); style.rel = 'stylesheet'; style.href = new URL('editor_export_dialog.css', import.meta.url).href; @@ -38,9 +39,9 @@ export function exportRange(record, selection) { return Number.isSafeInteger(start) && Number.isSafeInteger(end) && end > start ? {start, frames: end - start} : null; } -// Kept from the last export: size, range and sound format. Sound-only and a lower quality are not: the dialog opens on the +// Kept from the last export: size, frame rate, range and sound format. Sound-only and a lower quality are not: the dialog opens on the // full picture at high quality, so Enter never quietly exports a file without the picture or with less of it. -function settings(record, selection, value, {remembered = false} = {}) { +function settings(record, selection, value, {remembered = false, fps = true} = {}) { value = value && typeof value === 'object' ? value : {}; return { short: exportSizes(record).some(size => size.short === value.short) ? value.short : defaults.short, @@ -48,6 +49,8 @@ function settings(record, selection, value, {remembered = false} = {}) { range: value.range === 'selected' && exportRange(record, selection) ? 'selected' : 'whole', only: !remembered && value.only === 'sound' ? 'sound' : null, sound_format: value.sound_format === 'wav' ? 'wav' : 'm4a', + // 48/60 only where this machine can make the frames in between. + fps: fps && FRAME_RATES.includes(value.fps) ? value.fps : defaults.fps, }; } @@ -57,6 +60,7 @@ export function exportOptions(record, selection, value) { else { if (clean.quality !== 'high') options.quality = clean.quality; if (clean.short != null) options.short = clean.short; + if (clean.fps !== defaults.fps) options.fps = clean.fps; } if (clean.range === 'selected') options.range = exportRange(record, selection); return options; @@ -79,7 +83,7 @@ function croppedParts(record, sources, range) { && differentPictureShape(clipPictureSize(clip, sources), record)); } -export async function openExportDialog({parent, state, sources, t = en => en, onError = () => {}}) { +export async function openExportDialog({parent, state, sources, t = en => en, onError = () => {}, fps = false}) { // Only the first trigger owns confirmation, even while the stylesheet loads. if (active.has(parent)) return null; let resolve; @@ -89,7 +93,7 @@ export async function openExportDialog({parent, state, sources, t = en => en, on if (!parent.isConnected || !parent.open) { active.delete(parent); resolve(null); return result; } let saved; try { saved = JSON.parse(localStorage.getItem(EXPORT_SETTINGS_KEY)); } catch { /* Private browsing or old data. */ } - const value = settings(state.record, state.selection, saved, {remembered: true}), returnFocus = document.activeElement; + const value = settings(state.record, state.selection, saved, {remembered: true, fps}), returnFocus = document.activeElement; const dialog = el('dialog', 'fv-ed-export-dialog'); dialog.dataset.fvOwnTab = ''; // Tab cycles its buttons below; a11y.js stands aside dialog.setAttribute('aria-label', t('Export', '导出')); @@ -115,6 +119,8 @@ export async function openExportDialog({parent, state, sources, t = en => en, on group('short', t('Frame size', '画面大小'), exportSizes(state.record).map(size => [size.short, size.short == null ? t('Same as the edit', '与剪辑相同') : `${size.width} × ${size.height}`])); group('quality', t('Quality', '画质'), [['high', t('High', '高')], ['standard', t('Standard', '标准')], ['small', t('Small file', '省空间')]]); + // Without a graphics card the group is left out, not shown greyed. + if (fps) group('fps', t('Frame rate', '帧率'), FRAME_RATES.map(rate => [rate, String(rate)])); group('range', t('Range', '范围'), [['whole', t('Whole edit', '整条')], ['selected', t('Selected range', '选中的范围')]]); const contentRow = group('only', t('Content', '内容'), [[null, t('Video and audio', '画面和声音')], ['sound', t('Audio only', '只声音')]]); const formatRow = group('sound_format', t('Audio only', '只声音'), [['m4a', 'M4A'], ['wav', 'WAV']], contentRow); @@ -147,7 +153,7 @@ export async function openExportDialog({parent, state, sources, t = en => en, on const sound = value.only === 'sound'; for (const {name, controls, choices} of groups) [...controls.children].forEach((node, i) => { node.setAttribute('aria-pressed', String(value[name] === choices[i][0])); - node.disabled = sound && ['short', 'quality'].includes(name) + node.disabled = sound && ['short', 'quality', 'fps'].includes(name) || name === 'range' && choices[i][0] === 'selected' && !exportRange(state.record, state.selection) || name === 'only' && choices[i][0] === 'sound' && !audible; }); diff --git a/web/editor_voice_store.js b/web/editor_voice_store.js index e33cb4d1..5e5d5c69 100644 --- a/web/editor_voice_store.js +++ b/web/editor_voice_store.js @@ -16,7 +16,8 @@ export async function voiceFeatures(api) { const response = await agentGet(api, ROOT); if (!response.ok) return {ready: false, install: false, unknown: true}; const features = (await response.json())?.features; - return {ready: !!features?.['projects.voice'], install: !!features?.['projects.voice.install']}; + // The same answer says whether export can make 48/60 fps (it needs the graphics card). + return {ready: !!features?.['projects.voice'], install: !!features?.['projects.voice.install'], exportFps: !!features?.['projects.export.fps']}; } catch { return {ready: false, install: false, unknown: true}; } } From 126b9595252d72e0c5d8824d30f62c19921dfecf Mon Sep 17 00:00:00 2001 From: Bowen Xue Date: Thu, 19 Nov 2026 06:24:57 +0000 Subject: [PATCH 06/21] Export at 48/60 fps: a full disk is reported as a full disk, and plainly too little space is... Export at 48/60 fps: a full disk is reported as a full disk, and plainly too little space is said before the graphics card starts --- freevideo_engine/editor_export.py | 16 ++++++++++++++++ freevideo_engine/frame_interp.py | 20 +++++++++++++++++--- 2 files changed, 33 insertions(+), 3 deletions(-) diff --git a/freevideo_engine/editor_export.py b/freevideo_engine/editor_export.py index e0c2f5f5..c016c760 100644 --- a/freevideo_engine/editor_export.py +++ b/freevideo_engine/editor_export.py @@ -690,6 +690,8 @@ def _render_faster(project, resolve, target, settings, clips, *, progress, cance _render_seams(project, resolve, base, progress=first, cancelled=cancelled, options=dataclasses.replace(settings, fps=FPS, intermediate=True)) _check(cancelled) + if _clearly_too_full(base, settings): + raise ExportError('disk_full') def moved(value): if progress and value.get('stage') == frame_interp.STAGE and value.get('total'): @@ -720,6 +722,20 @@ def moved(value): faster.unlink(missing_ok=True) +def _clearly_too_full(base, settings): + """Whether the disk plainly cannot take the faster file, said before the graphics card spends minutes on it. + + The final file is estimated from the near-lossless 24 fps one: more frames, and about half the size for every 6 steps + of quality given up. Only half of that is asked for, so a close call is left to the write itself.""" + from .disk_space import free_bytes + try: + size, free = base.stat().st_size, free_bytes(base.parent) + except (OSError, ValueError): + return False + crf = int(settings.video_options['crf']) + return free < size * settings.fps / FPS * 2 ** ((10 - crf) / 6) / 2 + + def _render_once(project, resolve, target, *, progress, cancelled, options, repair_seams): import av import numpy as np diff --git a/freevideo_engine/frame_interp.py b/freevideo_engine/frame_interp.py index 01e33516..0d2744b0 100644 --- a/freevideo_engine/frame_interp.py +++ b/freevideo_engine/frame_interp.py @@ -279,8 +279,12 @@ def emit(**values): write(request['source'], request['target'], fps=request['fps'], video_options=request['video_options'], cuts=request['cuts'], between=between, emit=emit, check=check) except Exception as error: - save(work / 'error.json', dict(error=type(error).__name__ + ': ' + str(error), - code=getattr(error, 'code', None))) + from .disk_space import ran_out + try: + save(work / 'error.json', dict(error=type(error).__name__ + ': ' + str(error), + code='disk_full' if ran_out(error) else getattr(error, 'code', None))) + except OSError: + pass # A full disk may not take this either; the parent then looks at the free space itself. return 1 return 0 @@ -299,6 +303,14 @@ def release_gpu(required=3 * 2 ** 30): pass +def _nearly_full(folder, margin=16 * 2 ** 20): + from .disk_space import free_bytes + try: + return free_bytes(folder) < margin + except (OSError, ValueError): + return False + + def convert(source, target, *, fps, video_options, cuts, root=None, python=None, environ=None, progress=None, cancelled=None, release=release_gpu): """Run the worker; target exists only after it exits cleanly. progress gets done/total output frames.""" @@ -349,7 +361,9 @@ def poll(): error = json.loads((work / 'error.json').read_text(encoding='utf-8')) except (OSError, ValueError): error = {} - if error.get('code') in ('interp_download', 'interp_memory'): + if not error and _nearly_full(target.parent): + error = dict(code='disk_full') + if error.get('code') in ('interp_download', 'interp_memory', 'disk_full'): raise InterpolationError(error['code'], error.get('error', '')) raise RuntimeError(error.get('error') or 'Frame interpolation worker exited with code %s' % child.returncode) From a49453b9710db0e369978fa02ca359a3abc450b5 Mon Sep 17 00:00:00 2001 From: Bowen Xue Date: Thu, 19 Nov 2026 05:49:13 +0000 Subject: [PATCH 07/21] Image and video failures name their reason and next step: engine stop, model download... Image and video failures name their reason and next step: engine stop, model download, history-closed videos, editor parts The image view's download failure keeps its reason, and a full disk during the download is named in download words; the panel sentence joins with the language's own punctuation. A video closed from its history keeps the exception it raised, so the failure card names the reason instead of the generic sentence. Editor parts that fail say what to do and offer a report. --- web/editor.js | 7 +++++-- web/image_generation.js | 2 ++ web/image_view.js | 11 ++++++++++- web/task_float.js | 10 +++++++++- web/task_store.js | 5 ++++- 5 files changed, 30 insertions(+), 5 deletions(-) diff --git a/web/editor.js b/web/editor.js index 4cfd0263..120fcc00 100644 --- a/web/editor.js +++ b/web/editor.js @@ -122,8 +122,11 @@ export function editorErrorText(value, t = en => en) { if (['timeout', 'timed_out', 'generation_timeout'].includes(code) || /timed?\s*out|timeout|超时/i.test(raw)) return t(`${stage} timed out. Try again.`, `${stage}时等待超时,请再试一次。`); const received = raw || (/^[a-z_]+$/.test(code) ? '' : code); - return received ? t(`${generating} failed: ${received}`, `${generating}时出错:${received}`) - : t(`${generating} failed. Try again.`, `${generating}时出错,请再试一次。`); + if (received) return t(`${generating} failed: ${received}`, `${generating}时出错:${received}`); + // No readable text: say what the code names, and where the details are. + const named = /^[a-z_]+$/.test(code) ? code : ''; + return t(`${generating} failed. Try again; if it keeps failing, download the report and report the problem.${named ? ` Error code: ${named}` : ''}`, + `${generating}时出错。请重试;仍然失败请下载报告并提交问题。${named ? `错误代码:${named}` : ''}`); } function exportErrorText(value, t) { if (isNetworkTypeError(value)) return connectionLostText(t); diff --git a/web/image_generation.js b/web/image_generation.js index 76c4cd71..184c0833 100644 --- a/web/image_generation.js +++ b/web/image_generation.js @@ -239,6 +239,8 @@ export function imageGenError(code, info, t) { reload: ['Image generation was interrupted. Try again.', '图片生成中途被打断,请重试。'], engine_error: ['The image engine returned an unreadable answer. Try again; if it keeps failing, report the problem.', '图像引擎返回了无法读取的结果。请重试;仍然失败请提交问题。'], connection_lost: ['Lost the connection to FreeVideo. Try again once it is back.', '与 FreeVideo 的连接已断开,恢复后请重试。'], + engine_closed: ['FreeVideo stopped answering while this picture was being made. Start FreeVideo again, then generate again.', '生成过程中 FreeVideo 停止了响应。重新启动 FreeVideo 后再生成一次。'], + engine_restarted: ['FreeVideo restarted while this picture was being made, so it did not finish. Generate it again.', 'FreeVideo 在生成过程中重新启动,这张图没有完成。请再生成一次。'], generation_failed: ['Image generation ran into an error. Try again.', '图像生成出错了,请再试一次。'], small_memory: ['This Mac has less than 16 GB of memory and cannot generate pictures.', '这台 Mac 的内存不足 16 GB,无法生成图片。'], diff --git a/web/image_view.js b/web/image_view.js index 92416ddd..d7e119ef 100644 --- a/web/image_view.js +++ b/web/image_view.js @@ -1294,7 +1294,16 @@ export function openImageView(node, {studio = null, client: given = null, poll = // Installing from the page: the engine fetches the model; the page watches until it is ready, then generates if asked to. async function install() { const mine = model.id; - try { info = await client.packInstall(mine); } catch (error) { say(imageGenError(error.code, info, t)); return; } + try { info = await client.packInstall(mine); } catch (error) { + // A failed download says so in its own words; the generation sentences do not describe it. + say(error?.code === 'connection_lost' + ? t('The download did not start: FreeVideo could not be reached. Start FreeVideo again, then try again.', '下载没有开始:连不上 FreeVideo。请重新启动 FreeVideo 后再试。') + : error?.code === 'disk_full' + ? t('The download did not start: the disk is full. Free some space, then download again.', '下载没有开始:磁盘空间不够。空出空间后再下载。') + : ['no_memory', 'pack_missing', 'model_unreadable'].includes(error?.code) + ? t('The download did not start: ', '下载没有开始:') + imageGenError(error.code, info, t) + : t('The download did not start. Try again; if it keeps failing, report the problem.', '下载没有开始。请重试;仍然失败请提交问题。')); return; + } render(); while (alive && modelState(info, mine).state === 'downloading') { await new Promise(r => setTimeout(r, 1500)); try { info = await client.info(); } catch { /* asked again */ } render(); diff --git a/web/task_float.js b/web/task_float.js index 791f9739..58f62e7d 100644 --- a/web/task_float.js +++ b/web/task_float.js @@ -6,6 +6,7 @@ import { isNetworkTypeError, connectionLostText } from './browser_extension.js'; import { api } from '../../scripts/api.js'; import { app } from '../../scripts/app.js'; import { jobs, imageSource, progressSource, chainSource, queueSource, journalSource, ACTIVE, FINAL } from './task_store.js'; +import { errorText, failureAdvice } from './error_panel.js'; import { createImageGenClient, imageGenError, imageReportBar } from './image_generation.js'; import { saveGeneratedImage } from './image_library.js'; @@ -184,7 +185,14 @@ function reasonLong(row) { if (code === 'engine_closed') return t('FreeVideo stopped answering while this was being made. Start FreeVideo again, then generate again.', '生成过程中 FreeVideo 停止了响应。重新启动 FreeVideo 后再生成一次。'); if (code === 'engine_restarted' || row.status === 'interrupted') return t('FreeVideo restarted while this was being made, so it did not finish. Finished parts are in your works.', 'FreeVideo 在生成过程中重新启动,这次没有完成。已经完成的部分在作品里。'); if (row.kind === 'image') return imageGenError(code, row.failure, t) || t('The picture did not finish.', '这张图没有完成。'); - return row.failure?.message || t('The video did not finish.', '这段视频没有完成。'); + if (row.failure?.message) return row.failure.message; + // A run closed from the history has no message, only the exception it raised. + const advice = row.failure?.detail ? failureAdvice(errorText(row.failure.detail), t) : null; + const said = advice && advice.kind !== 'unknown' + ? [advice.summary || advice.title, advice.action].filter(Boolean).map(x => x.replace(/[.。]$/, '')).join(t('. ', '。')) + t('.', '。') : ''; + if (said) return said; + return t('FreeVideo did not report a reason for this video. Try again, and report the problem if it keeps failing.', + 'FreeVideo 没有给出这段视频失败的原因。请重试,仍然失败请提交问题。'); } function line2(row) { if (row.status === 'running') return etaText(row.eta_seconds) || elapsedText(row); diff --git a/web/task_store.js b/web/task_store.js index e6a73792..e26c7dd3 100644 --- a/web/task_store.js +++ b/web/task_store.js @@ -365,7 +365,10 @@ export function queueSource(store, {fetchJson, clientId = () => null, interval = } const messages = entry?.status?.messages || []; const stopped = !entry || row.status === 'cancelling' || messages.some(message => message?.[0] === 'execution_interrupted'); - store.upsert(stopped ? {id, status: 'cancelled'} : {id, status: 'failed', failure: {code: 'generation_failed', message: ''}}); + // The history keeps the exception the progress stream would have carried; the failure card reads its reason from it. + const raised = messages.find(message => message?.[0] === 'execution_error')?.[1]; + const detail = raised && typeof raised === 'object' ? {exception_type: raised.exception_type, exception_message: raised.exception_message, node_type: raised.node_type} : null; + store.upsert(stopped ? {id, status: 'cancelled'} : {id, status: 'failed', failure: {code: 'generation_failed', message: '', ...(detail ? {detail} : {})}}); } async function read() { const queue = await fetchJson('/queue'); From 90b3331a1bb64437dce827ba4796dfc1c9f422f1 Mon Sep 17 00:00:00 2001 From: Bowen Xue Date: Thu, 19 Nov 2026 05:55:30 +0000 Subject: [PATCH 08/21] Editor, image view, task float and notifications: a failure states the cause and the next step... Editor, image view, task float and notifications: a failure states the cause and the next step, offers a report, and never shows a raw failure code --- web/agent_activity.js | 2 +- web/autopilot_chat.js | 6 +++--- web/cast_photo.js | 12 ++++++------ web/editor.js | 2 +- web/editor_genbar.js | 2 +- web/editor_music.js | 2 +- web/editor_narration.js | 4 ++-- web/editor_stems.js | 2 +- web/editor_text.js | 6 +++--- web/editor_tracks.js | 4 ++-- web/editor_voice_install.js | 2 +- web/freevideo.js | 4 ++-- web/image_view.js | 18 +++++++++--------- web/image_view_models.js | 2 +- web/notifications.js | 9 ++++++++- web/settings_room.js | 2 +- web/task_float.js | 6 ++++-- 17 files changed, 47 insertions(+), 38 deletions(-) diff --git a/web/agent_activity.js b/web/agent_activity.js index be611c3b..61fb84f4 100644 --- a/web/agent_activity.js +++ b/web/agent_activity.js @@ -144,7 +144,7 @@ function row(job, t, api, refresh, open, cancellationErrors) { try { const response = await retryAgentPost(api, '/freevideo/agent/activity/cancel', {id: job.id}); if (!response?.ok) { - const message = t('Could not stop. Click again.', '没能停止,请再点一次。'); + const message = t('Could not stop. Click again; if it keeps failing, report the problem.', '没能停止。请再点一次;仍然失败时,请提交问题。'); details.textContent = message; cancellationErrors.set(job.id, message); issue.hidden = false; diff --git a/web/autopilot_chat.js b/web/autopilot_chat.js index e5bd1473..007b0f00 100644 --- a/web/autopilot_chat.js +++ b/web/autopilot_chat.js @@ -333,7 +333,7 @@ export function agentChat(t, api, {open, edit, shown = () => true, changed = () input.focus(); let done = false; try { done = (await dataLayer.abandon(session)).ok; } catch {} - if (!done && state.session === session) { state = {...state, abandoned: false}; render(); say(t('Could not stop. Click again.', '没能停止,请再点一次。')); } + if (!done && state.session === session) { state = {...state, abandoned: false}; render(); say(t('Could not stop. Click again; if it keeps failing, report the problem.', '没能停止。请再点一次;仍然失败时,请提交问题。')); } } let whiteboxPreview = false; try { whiteboxPreview = localStorage.getItem(WHITEBOX_PREVIEW.storageKey) === 'true'; } catch {} @@ -1108,7 +1108,7 @@ export function agentChat(t, api, {open, edit, shown = () => true, changed = () ids.forEach(id => stopping.add(id)); render(); report(); const results = await Promise.all(ids.map(id => dataLayer.cancel(id))); results.forEach((response, index) => { if (!response?.ok) stopping.delete(ids[index]); }); - if (results.some(response => !response?.ok)) say(t('Could not stop. Click again.', '没能停止,请再点一次。'), true); + if (results.some(response => !response?.ok)) say(t('Could not stop. Click again; if it keeps failing, report the problem.', '没能停止。请再点一次;仍然失败时,请提交问题。'), true); else say(''); if (!stopped) { render(); report(); void poll(); } } @@ -1704,7 +1704,7 @@ export function agentChat(t, api, {open, edit, shown = () => true, changed = () // Another sentence came first: the page reads it, and this one stays in the box. if (error?.code === 'invalid_request') return t('A newer message was sent first. This one was not sent.', '已有更新的消息,此⁠条⁠未⁠发⁠送⁠。'); if (WAIT_FOR_AGENT.includes(error?.code) || error?.code === 'session_full') return t('Not sent: ', '没发出去:') + failureReason({error}, t); - return t('Could not stop. Click again.', '未能停止,请再点一次。'); + return t('Could not stop. Click again; if it keeps failing, report the problem.', '未能停止。请再点一次;仍然失败时,请提交问题。'); } function render(follow = false) { diff --git a/web/cast_photo.js b/web/cast_photo.js index 0f91bd82..5655e59e 100644 --- a/web/cast_photo.js +++ b/web/cast_photo.js @@ -115,12 +115,12 @@ export function mountCastPhoto({container, api, text, viewURL, onState = () => { record = {file, url: URL.createObjectURL(file)}; paint(); onChange(); }; async function edit() { - let outcome; + let outcome, loadFailed = false; try { - const {openImageEditor} = await import('./image_editor.js'); + const {openImageEditor} = await import('./image_editor.js').catch(error => { loadFailed = true; throw error; }); outcome = await openImageEditor({source: record.original?.url || record.url, name: record.file.name || 'picture.png', edit: record.edit || null, role: 'reference', t: tr, resolve: url => url, upload: async blob => client.upload(blob), imageGenClient: client}); - } catch { attention = tr('This picture cannot be edited right now.', '这张图暂时无法编辑。'); render(); return; } + } catch { attention = loadFailed ? tr('The image editor did not load. Reload the page and try again.', '图片编辑器没有加载出来。请刷新页面后再试。') : tr('This picture could not be read. Choose another picture.', '这张图无法读取。请重新选择一张。'); render(); return; } if (!outcome || !record || disposed) return; if (outcome.restore) { back(); return; } if (!outcome.blob) return; @@ -272,12 +272,12 @@ export function mountCastPhoto({container, api, text, viewURL, onState = () => { // A view opens in the image editor; the edited picture takes its place on the card (marked, and Restore puts the // made one back). An edited face or front is what the others are redrawn from. async function editView(view) { - let outcome; + let outcome, loadFailed = false; try { - const {openImageEditor} = await import('./image_editor.js'); + const {openImageEditor} = await import('./image_editor.js').catch(error => { loadFailed = true; throw error; }); outcome = await openImageEditor({source: sourceOf(view), name: `${view}.png`, edit: edits[view]?.edit || null, role: 'reference', t: tr, resolve: url => url, upload: async blob => client.upload(blob), imageGenClient: client}); - } catch { attention = tr('This picture cannot be edited right now.', '这张图暂时无法编辑。'); render(); return; } + } catch { attention = loadFailed ? tr('The image editor did not load. Reload the page and try again.', '图片编辑器没有加载出来。请刷新页面后再试。') : tr('This picture could not be read. Choose another picture.', '这张图无法读取。请重新选择一张。'); render(); return; } if (!outcome || disposed) return; if (outcome.restore) { dropEdit(view); if (leads(view)) faceChanged = true; render(); return; } if (!outcome.blob) return; diff --git a/web/editor.js b/web/editor.js index 120fcc00..daa0d58a 100644 --- a/web/editor.js +++ b/web/editor.js @@ -490,7 +490,7 @@ export function openEditor({api, app, from = null, panel = {}, components: given if (said) out(said); return {ok: false, reason: code}; } - const text = step === 'generate' ? editorErrorText(value, t) : step === 'export' ? exportErrorText(value, t) : t('Could not complete. Try again.', '没有完成,请重试'); + const text = step === 'generate' ? editorErrorText(value, t) : step === 'export' ? exportErrorText(value, t) : isNetworkTypeError(value) ? connectionLostText(t) : t('This step did not finish. Try again; if it keeps failing, report the problem.', '这一步没有完成。请重试;仍然失败时,请提交问题。'); out(text, step === 'export' ? EXPORT_ISSUE : EDITOR_ISSUE, failureKind(site, value)); return {ok: false, reason: code, say: text}; } const store = createEditorStore(api, {t, notify, standIn: given?.generationStandIn, onGenerationChecking: () => { if (!disposed) settleService(); }, onGenerationReady: ready => { diff --git a/web/editor_genbar.js b/web/editor_genbar.js index 9897a1d7..f9c4c77c 100644 --- a/web/editor_genbar.js +++ b/web/editor_genbar.js @@ -574,7 +574,7 @@ export function createEditorGenbar(host, {state, t, actions, text = ''}) { // A specific reason is said once; the planning limits are already shown above. catch (error) { const result = actions.error(error, 'generate'); reason = result?.say || ''; if (result?.say && !['chain_too_long', 'chain_part_too_short', 'chain_short_parts', 'chain_source_full', 'timed_text', 'middle_frames'].includes(result.reason)) say(result.say, false, ['Editor generation', '剪辑器生成']); - else if (!result && !note.textContent) { reason = t('Could not start. Try again.', '没能开始,请重试。'); say(reason, false, ['Editor generation', '剪辑器生成']); } } + else if (!result && !note.textContent) { reason = t('Generation could not start. Try again; if it keeps failing, report the problem.', '生成没能开始。请重试;仍然失败时,请提交问题。'); say(reason, false, ['Editor generation', '剪辑器生成']); } } finally { pressing.delete(key); render(); } return reason; }; diff --git a/web/editor_music.js b/web/editor_music.js index de408a57..417d6de2 100644 --- a/web/editor_music.js +++ b/web/editor_music.js @@ -42,7 +42,7 @@ export function musicFailureText(reason, t) { out_of_memory: t('Not enough memory to generate the music. Close other programs that use the graphics card, then generate again.', '生成配乐时内存不足,请关闭其他占用显卡的程序后重新生成。'), unsupported: t('Music cannot be generated on this computer yet.', '这台电脑暂不能生成配乐。'), missing: t('Generation stopped. Generate again.', '生成已中断,请重新生成。'), - }[reason] || t('The music could not be generated. Generate again.', '无法生成配乐,请重新生成。'); + }[reason] || t('The music could not be generated. Generate again; if it keeps failing, report the problem.', '无法生成配乐。请重新生成;仍然失败时,请提交问题。'); } export function createEditorMusic({state, store, t, completeSources = async () => {}, onStatus = () => {}, clock = Date.now, random = Math.random}) { diff --git a/web/editor_narration.js b/web/editor_narration.js index ffa64929..3a34d0ec 100644 --- a/web/editor_narration.js +++ b/web/editor_narration.js @@ -35,7 +35,7 @@ export function narrationFailureText(reason, t) { no_speech_model: t('The speech model could not be used, so the voice could not be generated.', '语音识别模型无法使用,未能生成配音。'), voice_model_missing: t('The dubbing model is not fully installed. Generate again to download it.', '配音模型没有装全,重新生成会再下载。'), missing: t('Generation stopped. Generate again.', '生成已中断,请重新生成。'), - }[reason] || t('The voice could not be generated. Generate again.', '无法生成配音,请重新生成。'); + }[reason] || t('The voice could not be generated. Generate again; if it keeps failing, report the problem.', '无法生成配音。请重新生成;仍然失败时,请提交问题。'); } // How much longer than the stretch a line came out, as the bar says it: one decimal, a no-break space before the unit. const longer = (seconds, t) => { const value = (Math.round(seconds * 10) / 10).toFixed(1); return t(`${value}${NBSP}s`, `${value}${NBSP}秒`); }; @@ -253,7 +253,7 @@ export function createEditorNarration({state, store, t, sources = () => new Map( }, failure(selection = state.selection) { const found = target(selection); - return found?.clip?.pending === 'failed' ? {id: found.clip.id, text: narrationFailureText(found.clip.reason, t), report: false} : null; + return found?.clip?.pending === 'failed' ? {id: found.clip.id, text: narrationFailureText(found.clip.reason, t), report: narrationFailureText(found.clip.reason, t) === narrationFailureText('', t)} : null; }, // Seconds the line will take: this machine's pace from its last line; unknown before the first. estimate(selection = state.selection) { diff --git a/web/editor_stems.js b/web/editor_stems.js index abef58fa..f306950b 100644 --- a/web/editor_stems.js +++ b/web/editor_stems.js @@ -11,7 +11,7 @@ const ACTIVE = ['waiting', 'queued', 'running', 'cancelling']; const FAILURES = { stems_download_failed: ['The separation model could not be downloaded. Check the network and try again.', '分离模型下载失败,请检查网络后重试。'], out_of_memory: ['Not enough graphics memory to separate this sound.', '显存不足,无法分离这段声音。'], - stems_failed: ['The sound could not be separated. Try again.', '声音分离失败,请重试。'], + stems_failed: ['The sound could not be separated. Try again; if it keeps failing, report the problem.', '声音分离失败。请重试;仍然失败时,请提交问题。'], project_changed: ['The edit changed meanwhile. Try again.', '编辑内容已变化,请重试。'], clip_busy: ['This clip is still being made.', '这个片段还在生成。'], clip_locked: ['This clip is locked.', '这个片段已锁定。'], diff --git a/web/editor_text.js b/web/editor_text.js index e5ae7337..359b7cb3 100644 --- a/web/editor_text.js +++ b/web/editor_text.js @@ -74,7 +74,7 @@ export function createEditorText({element,state,t,actions,adjust,player,toolbar, // Once every byte is in, the download is unpacked; the button says so and keeps the width it had, so it does not jump. function speechLabel(fraction,phase=null){speech.shown=fraction;const unpacking=fraction!=null&&speech.loading&&phase==='unpack',p=Math.round(Math.min(1,Math.max(0,Number(fraction)||0))*100),size=Math.max(1,Math.round(speech.need/1e6)),text=fraction==null?(speech.need?t(`Auto subtitles · Download ${size} MB`,`自动字幕 · 下载 ${size} MB`):t('Auto subtitles','自动字幕')):unpacking?t('Cancel · Unpacking','取消 · 正在解压'):speech.loading?t(`Cancel · Downloading ${p}%`,`取消 · 下载 ${p}%`):t(`Cancel · ${p}%`,`取消 · ${p}%`);for(const b of speech.buttons){if(unpacking&&!b.style.minWidth&&b.offsetWidth)b.style.minWidth=`min(${b.offsetWidth}px, 100%)`;else if(!unpacking)b.style.minWidth='';b.textContent=text;b.hidden=!(speech.available||speech.need);}} function speechEnd(text,where=null){speech.stop?.();speech.stop=null;speech.job=null;speech.busy=false;speech.loading=false;speechLabel(null);if(text)actions.notify?.(text,where);} - const speechFailed=()=>t('Could not create subtitles','没能生成字幕'),speechSilent=()=>t('No speech found','没有听到说话声'); + const speechFailed=()=>t('Could not create subtitles. Try again; if it keeps failing, report the problem.','没能生成字幕。请重试;仍然失败时,请提交问题。'),speechSilent=()=>t('No speech found','没有听到说话声'); const speechDisk=()=>t('The disk is full. Free some space, then try again.','磁盘空间不足,请清理出空间后重试。'); // Causes the person can act on are named and carry no issue button; anything else is unexplained. const speechReasons={no_sound:speechSilent,language:()=>t('Language not supported yet','暂不支持这种语言'),too_long:()=>t('Auto subtitles work on up to 2 hours of sound.','自动字幕最多处理 2 小时的声音。'), @@ -106,7 +106,7 @@ export function createEditorText({element,state,t,actions,adjust,player,toolbar, const ability=done===true?await actions.speech.ability():null; if(run!==speech.run)return; if(ability){speech.available=ability.available;speech.need=ability.need;} - if(done!==true||speech.need){speechEnd(done==='disk_space'?speechDisk():t('Could not download. Try again.','没能下载,请再试一次。'),done==='disk_space'?null:SPEECH_ISSUE);return;} + if(done!==true||speech.need){speechEnd(done==='disk_space'?speechDisk():t('The speech model could not be downloaded. Check the connection and try again.','语音模型没能下载。请检查网络后再试一次。'),done==='disk_space'?null:SPEECH_ISSUE);return;} if(!speech.available){speechEnd(speechFailed(),SPEECH_ISSUE);return;} speech.loading=false; } @@ -116,7 +116,7 @@ export function createEditorText({element,state,t,actions,adjust,player,toolbar, if(!job){speechEnd(speechFailed(),SPEECH_ISSUE);return;} speech.job=job.id??null; if(speechResult(job))speech.stop=actions.speech.watch(job.id,value=>{if(run!==speech.run)return false;if(!value){speechEnd(speechFailed(),SPEECH_ISSUE);return false;}return speechResult(value);},()=>{if(run===speech.run)speechEnd(speechFailed(),SPEECH_ISSUE);}); - }catch{if(run===speech.run)speechEnd(speech.loading?t('Could not download. Try again.','没能下载,请再试一次。'):speechFailed(),SPEECH_ISSUE);} + }catch{if(run===speech.run)speechEnd(speech.loading?t('The speech model could not be downloaded. Check the connection and try again.','语音模型没能下载。请检查网络后再试一次。'):speechFailed(),SPEECH_ISSUE);} } function commitDraft(){if(draft){const change=draft.change;apply(t('Text','文字'),change);const c=selectedText();if(c?.text_kind==='text')lastStyle={...styleOf(state.record,c)};}} // Editing a text ended. One left without words is taken away; one that never had any leaves no step behind. diff --git a/web/editor_tracks.js b/web/editor_tracks.js index a82fe0bf..9218d747 100644 --- a/web/editor_tracks.js +++ b/web/editor_tracks.js @@ -699,7 +699,7 @@ export function createTracks(host, {state, sources = {}, t = en => en, actions = if (!mark) { mark = create('span', 'fv-ed-seam-mark'); mark.setAttribute('aria-hidden', 'true'); mark.dataset.kind = seam; mark.append(icon('link')); item.element.append(mark); } } else mark?.remove(); item.element.classList.toggle('fv-ed-seamed', !!item.element.querySelector(':scope > .fv-ed-seam-mark')); - const failureText = visual === 'failed' ? actions.failureText?.(clip.id) || actions.reasonText?.(clip.reason) || clip.reason || t('Generation failed', '生成时出错') : ''; + const failureText = visual === 'failed' ? actions.failureText?.(clip.id) || actions.reasonText?.(clip.reason) || t('Generation failed; the cause was not saved. Retry, or download the report.', '生成失败,原因没有保存下来。请重试,或下载报告。') : ''; if (visual === 'failed') item.status.replaceChildren(icon('warning'), create('span', 'fv-ed-clip-failure-reason', failureText)); else item.status.replaceChildren(); const status = {planned: actions.interrupted?.(clip) ? t('Interrupted', '上次中断') : t('Not generated yet', '还没生成'), running: t('Generating', '正在生成'), @@ -796,7 +796,7 @@ export function createTracks(host, {state, sources = {}, t = en => en, actions = } function failedPopover(item) { failedPopoverId = item.clip.id; - const reason = create('p', '', actions.failureText?.(item.clip.id) || actions.reasonText?.(item.clip.reason) || item.clip.reason || t('Generation failed', '生成时出错')); + const reason = create('p', '', actions.failureText?.(item.clip.id) || actions.reasonText?.(item.clip.reason) || t('Generation failed; the cause was not saved. Retry, or download the report.', '生成失败,原因没有保存下来。请重试,或下载报告。')); const report = create('button', 'fv-ed-clip-report', t('Download report', '下载报告')); report.type = 'button'; applyTip(report, 'report', t); report.onclick = event => { event.stopPropagation(); popover.hidden = true; Promise.resolve(actions.downloadFailure?.(item.clip.id)).catch(error => actions.editError?.(error)); }; diff --git a/web/editor_voice_install.js b/web/editor_voice_install.js index 1322a776..72f185e9 100644 --- a/web/editor_voice_install.js +++ b/web/editor_voice_install.js @@ -27,7 +27,7 @@ export function failureText(code, bytes, t) { switch (code) { case 'disk_space': return {report: true, text: t(`There is not enough disk space. The dubbing model needs about ${sizeText(bytes)}.`, `磁盘空间不足,配音模型需要约 ${sizeText(bytes)}。`)}; case 'download_failed': case 'network': return {report: true, text: t('The dubbing model could not be downloaded. Check the connection and try again.', '配音模型下载失败,请检查网络后重试。')}; - default: return {report: true, text: t('The dubbing model could not be installed. Try again.', '配音模型未能安装,请重试。')}; + default: return {report: true, text: t('The dubbing model could not be installed. Try again; if it keeps failing, report the problem.', '配音模型未能安装。请重试;仍然失败时,请提交问题。')}; } } diff --git a/web/freevideo.js b/web/freevideo.js index 42575cfc..478f5186 100644 --- a/web/freevideo.js +++ b/web/freevideo.js @@ -290,7 +290,7 @@ function mediaPanel(node, mount = null) { try { outcome = await openImageEditor({source, name: source, target: videoSize(), edit: original.edit || agent?.edit || null, role: original.role, t: text, resolve: viewURL, upload: uploadOne, library, tool}); - } catch (error) { message(text('This image cannot be edited right now; choose an image again.', '图片暂时无法编辑,可重新选择图片。'), true); return; } + } catch (error) { message(text('This image could not be opened for editing. Choose another image.', '这张图片无法打开编辑。请重新选择一张。'), true); return; } if (!outcome) return; // The cards may have changed meanwhile; find this one again by its file. const rows = read(), at = rows.findIndex(row => row.file === file); @@ -323,7 +323,7 @@ function mediaPanel(node, mount = null) { try { outcome = await openImageEditor({target: videoSize(), role: role.value, t: text, resolve: viewURL, upload: uploadOne, library}); - } catch { message(text('This image cannot be edited right now; choose an image again.', '图片暂时无法编辑,可重新选择图片。'), true); return; } + } catch { message(text('This image could not be opened for editing. Choose another image.', '这张图片无法打开编辑。请重新选择一张。'), true); return; } if (!outcome?.blob) return; if (read().length >= 32) { message(text('The media list is full (32 items, including disabled ones). Remove some to add more.', '素材已满 32 个(含未启用的),请先移除不用的素材。'), true); return; } node.isUploading = true; add.disabled = addAudio.disabled = generateImage.disabled = true; diff --git a/web/image_view.js b/web/image_view.js index d7e119ef..bb5277fb 100644 --- a/web/image_view.js +++ b/web/image_view.js @@ -851,12 +851,12 @@ export function openImageView(node, {studio = null, client: given = null, poll = } async function editReference(record) { if (record.sketch) { void drawSketch(record); return; } - let outcome; + let outcome, loadFailed = false; try { - const {openImageEditor} = await import('./image_editor.js'); + const {openImageEditor} = await import('./image_editor.js').catch(error => { loadFailed = true; throw error; }); outcome = await openImageEditor({source: record.original?.url || record.url, name: record.original?.file?.name || record.file?.name || 'reference.png', edit: record.edit || null, role: 'reference', t, resolve: url => url, upload: async blob => client.upload(blob), imageGenClient: client}); - } catch { say(t('This picture cannot be edited right now.', '这张图暂时无法编辑。')); return; } + } catch { say(loadFailed ? t('The image editor did not load. Reload the page and try again.', '图片编辑器没有加载出来。请刷新页面后再试。') : t('This picture could not be read. Choose another picture.', '这张图无法读取。请重新选择一张。')); return; } if (!alive || !outcome || !references.includes(record)) return; if (outcome.restore) { restoreReference(record); return; } if (!outcome.blob) return; @@ -999,7 +999,7 @@ export function openImageView(node, {studio = null, client: given = null, poll = kind = 'warn'; parts = [icon('warn'), el('span', 'fv-iv-slot-tx', t('A picture named in the prompt was removed; choose it again with @', '描述里引用的参考图已移除,请用 @ 重新选择'))]; } else if (s.state === 'failed') { - kind = 'warn'; parts = [icon('warn'), el('span', 'fv-iv-slot-tx', [t(`${model.short} download failed.`, `${model.short} 下载失败。`), s.reason].filter(Boolean).join(' '))]; + kind = 'warn'; parts = [icon('warn'), el('span', 'fv-iv-slot-tx', t(`${model.short} download failed${s.reason ? ': ' + s.reason.replace(/[.。]$/, '') : ''}. Retry to continue; if it keeps failing, report the problem.`, `${model.short} 下载失败${s.reason ? ':' + s.reason.replace(/[.。]$/, '') : ''}。请重试以继续下载;仍然失败时,请提交问题。`))]; } else if (s.state === 'downloading') { kind = 'info'; parts = [icon(s.unknown ? 'clock' : 'down'), el('span', 'fv-iv-slot-tx', s.verifying ? (pendingGenerate ? t(`Verifying ${model.short}; it generates when done`, `正在校验 ${model.short},完成后自动生成`) : t(`Verifying ${model.short}`, `正在校验 ${model.short}`)) : pendingGenerate ? t(`Installing ${model.short}; it generates when done`, `正在安装 ${model.short},完成后自动生成`) : t(`Installing ${model.short}`, `正在安装 ${model.short}`))]; @@ -1441,7 +1441,7 @@ export function openImageView(node, {studio = null, client: given = null, poll = if (!await confirmStop(go, {kind: 'image', queued: jobs.get(mine.id)?.status === 'queued'})) return; if (running !== mine) return; mine.cancelled = true; - if (mine.id) { try { await jobs.cancel(mine.id); } catch (error) { say(isNetworkTypeError(error) ? connectionLostText(t) : t('Could not stop. Try again.', '没有停止成功,请重试。')); } return; } + if (mine.id) { try { await jobs.cancel(mine.id); } catch (error) { say(isNetworkTypeError(error) ? connectionLostText(t) : t('Could not stop. Try again; if it keeps failing, report the problem.', '没有停止成功。请重试;仍然失败时,请提交问题。')); } return; } running = null; level.hidden = true; render(); drawWorks(); } // ── end run ── @@ -1496,11 +1496,11 @@ export function openImageView(node, {studio = null, client: given = null, poll = // Crop, paint, add text, or change a part with AI in the image editor; the result comes back as Image 1 and into the library. async function editPicture(file) { if (!file) return; - let outcome; + let outcome, loadFailed = false; try { - const {openImageEditor} = await import('./image_editor.js'); + const {openImageEditor} = await import('./image_editor.js').catch(error => { loadFailed = true; throw error; }); outcome = await openImageEditor({source: file, name: file, role: 'reference', t, resolve: pictureURL, upload: async blob => client.upload(blob), imageGenClient: client}); - } catch { say(t('This picture cannot be edited right now.', '这张图暂时无法编辑。')); return; } + } catch { say(loadFailed ? t('The image editor did not load. Reload the page and try again.', '图片编辑器没有加载出来。请刷新页面后再试。') : t('This picture could not be read. Choose another picture.', '这张图无法读取。请重新选择一张。')); return; } if (!alive || !outcome?.blob) return; try { const edited = new File([outcome.blob], outcome.name || 'edited.png', {type: outcome.blob.type || 'image/png'}); @@ -1510,7 +1510,7 @@ export function openImageView(node, {studio = null, client: given = null, poll = const record = {file: edited, url: URL.createObjectURL(edited), width: outcome.width, height: outcome.height}; if (references.length >= most()) URL.revokeObjectURL(record.url); else { changeRefs(() => references.unshift(record)); promptGroup.open(true); } render(); - } catch { say(t('The edited picture could not be saved.', '编辑后的图片没能保存。')); } + } catch (error) { say(isNetworkTypeError(error) ? connectionLostText(t) : t('The edited picture could not be saved. Try again; if it keeps failing, report the problem.', '编辑后的图片没能保存。请重试;仍然失败时,请提交问题。')); } } asReference.addEventListener('click', () => void useAsReference(shownFile, false)); // Opens downward when it fits inside the stage, otherwise upward over the picture. diff --git a/web/image_view_models.js b/web/image_view_models.js index ca9c5539..ad069a4c 100644 --- a/web/image_view_models.js +++ b/web/image_view_models.js @@ -44,7 +44,7 @@ export function statusLine(state) { switch (state.state) { case 'ready': return t('Installed', '已安装'); case 'downloading': return state.paused ? t('Paused', '已暂停') : state.verifying ? verifyText(state) : `${Math.floor(state.fraction * 100)}%`; - case 'failed': return t('Download failed', '下载失败'); + case 'failed': return t('Download failed. Retry to continue.', '下载失败,请重试以继续。'); case 'missing': return downloadText(state); case 'unavailable': return t('Not on this computer', '这台电脑不支持'); default: return t('Checking…', '正在检查…'); diff --git a/web/notifications.js b/web/notifications.js index 6abba219..d126feb5 100644 --- a/web/notifications.js +++ b/web/notifications.js @@ -73,13 +73,20 @@ export function noteMatchesWorks(note, {ids = [], paths = []} = {}) { // A job that has just finished, failed or been cut off becomes one note. A job first seen already finished (the // page was closed while it ran) counts only when it finished in the last half hour. const NOTE_STATES = new Set(['done', 'failed', 'interrupted']); +// A person-readable cause only: the raw code is never shown, so an unknown one gives nothing and the line says where to look. +const reasonOf = failure => { + const code = failure?.code; + if (code === 'engine_closed') return words(['The engine was closed', '引擎已关闭']); + if (code === 'engine_restarted') return words(['The engine restarted', '引擎已重启']); + return ''; +}; export function noteFromJob(row, previous, now = Date.now()) { if (!row || !NOTE_STATES.has(row.status)) return null; if (previous && previous.status === row.status) return null; if (!previous && (!row.finished_at || now - row.finished_at > LATE_MS)) return null; return {id: `job:${row.id}:${row.status}`, type: 'job', job: row.id, kind: row.kind || 'video', status: row.status, view: row.view || null, prompt: clean(row.meta?.text ?? row.prompt ?? '').slice(0, 140), file: row.result?.file || null, work: row.result?.id || row.result?.work || null, video: row.result?.video || null, - reason: clean(row.failure?.message || row.failure?.code || row.failure || ''), at: row.finished_at || now}; + reason: reasonOf(row.failure), at: row.finished_at || now}; } // The image models' install, between two reads of the image worker's info: a note when one finishes or fails. export function installChanges(before = {}, after = {}) { diff --git a/web/settings_room.js b/web/settings_room.js index e3d213e8..b9bb3cb9 100644 --- a/web/settings_room.js +++ b/web/settings_room.js @@ -991,7 +991,7 @@ export async function openSetup(options) { act.onclick = () => imageAction(id, 'cancel'); tip(act, t('Stop', '停止'), t('Stop the download; the part downloaded is kept', '停止下载,已下载的部分会保留')); } else if (s.state === 'failed') { - r.sub.className = 'is-warn'; r.sub.textContent = s.reason || t('Download failed', '下载失败'); + r.sub.className = 'is-warn'; r.sub.textContent = t(`${item.model.short} download failed${s.reason ? ': ' + s.reason.replace(/[.。]$/, '') : ''}. Retry to continue; if it keeps failing, report the problem.`, `${item.model.short} 下载失败${s.reason ? ':' + s.reason.replace(/[.。]$/, '') : ''}。请重试以继续下载;仍然失败时,请提交问题。`); act.hidden = false; act.className = 'st-btn is-fill'; act.replaceChildren(icon('retry', 'fv-i s'), el('span', 'st-btn-t', t('Retry', '重试'))); act.onclick = () => imageAction(id, 'install'); tip(act, t('Retry', '重试'), t('Download again; the part downloaded is kept', '重新下载,已下载的部分会保留')); diff --git a/web/task_float.js b/web/task_float.js index 58f62e7d..da303071 100644 --- a/web/task_float.js +++ b/web/task_float.js @@ -185,7 +185,9 @@ function reasonLong(row) { if (code === 'engine_closed') return t('FreeVideo stopped answering while this was being made. Start FreeVideo again, then generate again.', '生成过程中 FreeVideo 停止了响应。重新启动 FreeVideo 后再生成一次。'); if (code === 'engine_restarted' || row.status === 'interrupted') return t('FreeVideo restarted while this was being made, so it did not finish. Finished parts are in your works.', 'FreeVideo 在生成过程中重新启动,这次没有完成。已经完成的部分在作品里。'); if (row.kind === 'image') return imageGenError(code, row.failure, t) || t('The picture did not finish.', '这张图没有完成。'); - if (row.failure?.message) return row.failure.message; + // The engine's own text is raw; it goes through the same advice as the create panel, and an unknown cause says so. + const told = row.failure?.message ? failureAdvice(String(row.failure.message), t) : null; + if (told?.summary) return told.summary + t(' ', '') + told.action; // A run closed from the history has no message, only the exception it raised. const advice = row.failure?.detail ? failureAdvice(errorText(row.failure.detail), t) : null; const said = advice && advice.kind !== 'unknown' @@ -853,7 +855,7 @@ export function installTaskFloat() { if (k === 'keep') { ask = null; drawSheet(); card.focus({preventScroll: true}); } else if (k === 'stop') { const id = ask; ask = null; drawSheet(); - try { await jobs.cancel(id); } catch (error) { ask = id; stopError = isNetworkTypeError(error) ? connectionLostText(t) : t('Could not stop. Try again.', '没有停止成功,请重试。'); draw(); } + try { await jobs.cancel(id); } catch (error) { ask = id; stopError = isNetworkTypeError(error) ? connectionLostText(t) : t('Could not stop. Try again; if it keeps failing, report the problem.', '没有停止成功。请重试;仍然失败时,请提交问题。'); draw(); } } else if (k === 'dismiss') { const id = failCard; failCard = null; if (id) jobs.dismiss(id); draw(); } else if (k === 'go') { const target = rows.find(r => r.id === button.dataset.id); if (target) { const visit = failCard === target.id; failCard = null; await expandTo(target, {visit}); } } }); From 1269db06f2b14b666ea8822a7746b16f0e057921 Mon Sep 17 00:00:00 2001 From: Bowen Xue Date: Thu, 19 Nov 2026 09:03:28 +0000 Subject: [PATCH 09/21] LoRA with one alpha for layers of different ranks: the check names the reason before generation... LoRA with one alpha for layers of different ranks: the check names the reason before generation and the failure card explains it, with the ranks listed in the details --- freevideo_engine/lora_cache.py | 4 ++-- freevideo_engine/lora_check.py | 16 +++++++++++----- freevideo_engine/lora_names.py | 3 +++ web/error_panel.js | 7 ++++++- web/lora_check.js | 5 ++++- 5 files changed, 26 insertions(+), 9 deletions(-) diff --git a/freevideo_engine/lora_cache.py b/freevideo_engine/lora_cache.py index 23959696..3027301e 100644 --- a/freevideo_engine/lora_cache.py +++ b/freevideo_engine/lora_cache.py @@ -20,7 +20,7 @@ from safetensors.torch import save_file import torch -from .lora_names import INT8_UNMERGEABLE, MODULATION, _targets, adapter_keys, int8_skip_reason, resolve_target +from .lora_names import INT8_UNMERGEABLE, MIXED_RANK_ALPHA, MODULATION, _targets, adapter_keys, int8_skip_reason, resolve_target from .tensor_io import open_tensors from .media_request import digest, verify_files from .monitoring import save @@ -37,7 +37,7 @@ def index_adapter(row, targets, skipped=None): ranks = {source.get_slice(pair['A']).get_shape()[0] for pair in pairs.values() if 'A' in pair and (row.get('alpha') is not None or 'alpha' not in pair)} if len(ranks) > 1: - raise ValueError('A global alpha cannot identify mixed-rank H3 scaling; provide per-target alpha tensors') + raise ValueError(MIXED_RANK_ALPHA + ' (ranks ' + ', '.join(map(str, sorted(ranks))) + ')') results = [] for name, pair in pairs.items(): if not {'A', 'B'} <= pair.keys(): diff --git a/freevideo_engine/lora_check.py b/freevideo_engine/lora_check.py index 05321610..6e56c93a 100644 --- a/freevideo_engine/lora_check.py +++ b/freevideo_engine/lora_check.py @@ -11,7 +11,7 @@ import struct import threading -from .lora_names import INT8_UNMERGEABLE, _targets, adapter_keys, int8_skip_reason, resolve_target, supported +from .lora_names import INT8_UNMERGEABLE, MIXED_RANK_ALPHA, _targets, adapter_keys, int8_skip_reason, resolve_target, supported MAX_HEADER_BYTES = 64 * 1024 * 1024 BLOCKS, REFINER_BLOCKS = 50, 2 @@ -136,14 +136,16 @@ def _block(target): return int(found[1]) + 1 if found else None -def assess(shapes, *, int8_targets=None, skipped=None): +def assess(shapes, *, int8_targets=None, skipped=None, metadata=None): """None when the adapter fits, else why not: reason 'other-model' (names of another model), 'shape' (our names, a different size), 'acceleration' (a step-distillation adapter that replaces the output heads and needs its own sampler) or 'format' (not a LoRA we can read; 'layer' names the first tensor that is not a LoRA factor). 'layer' and the sizes say where. A layer name the table does not list, in a file that matches no other known model, is let through. With int8_targets, use the installed linear shapes and collect the runtime's - skipped patch categories; 'int8-unmergeable' means every patch was skipped.""" + skipped patch categories; 'int8-unmergeable' means every patch was skipped. + With the file's metadata, 'alpha' means one alpha value is stored for factors of different ranks, which the + engine refuses because the strength cannot be determined; 'ranks' lists them.""" keys = list(shapes) heads = _head_bank(shapes) if heads: @@ -215,6 +217,10 @@ def assess(shapes, *, int8_targets=None, skipped=None): if wrong: layer, expected, actual = wrong[0] return dict(reason='shape', family=None, layer=layer, block=_block(layer), expected=expected, actual=actual, count=len(wrong)) + if metadata and 'alpha' in metadata: + ranks = sorted({shapes[pair['A']][0] for pair in pairs.values() if 'A' in pair and 'alpha' not in pair}) + if len(ranks) > 1: + return _bad('alpha', keys, ranks=ranks) if int8_targets is not None and not applied: return _bad('int8-unmergeable', keys) return None @@ -246,7 +252,7 @@ def check_file(path, *, int8_targets=None): try: shapes, metadata = read_header(path) skipped = [] - problem = assess(shapes, int8_targets=int8_targets, skipped=skipped) + problem = assess(shapes, int8_targets=int8_targets, skipped=skipped, metadata=metadata) result = {'usable': problem is None, 'reason': None, **(problem or {}), 'summary': summarize(shapes, metadata)} if int8_targets is not None: result['partial'] = len(skipped) @@ -286,4 +292,4 @@ def require_usable(path): """Stop a request before generation starts when a LoRA cannot work with the model.""" result = check_installed_file(path) if not result['usable']: - raise ValueError({'int8-unmergeable': INT8_UNMERGEABLE, 'acceleration': ACCELERATION}.get(result['reason'], UNUSABLE)) + raise ValueError({'int8-unmergeable': INT8_UNMERGEABLE, 'acceleration': ACCELERATION, 'alpha': MIXED_RANK_ALPHA}.get(result['reason'], UNUSABLE)) diff --git a/freevideo_engine/lora_names.py b/freevideo_engine/lora_names.py index 41d64837..2bfa25ed 100644 --- a/freevideo_engine/lora_names.py +++ b/freevideo_engine/lora_names.py @@ -7,6 +7,9 @@ INT8_UNMERGEABLE = ('This LoRA changes parts of the model that the int8 version cannot merge yet, ' 'so it cannot be used for now. LoRAs that change only linear layers work.') +MIXED_RANK_ALPHA = ('This LoRA stores one alpha value for layers of different ranks, so its strength cannot be determined. ' + 'Use a copy that stores an alpha for every layer, or one with the same rank on every layer.') + # Factor names trainers write: PEFT lora_A/lora_B, Kohya and diffusers # lora_down/lora_up, each with or without the trailing ".weight". diff --git a/web/error_panel.js b/web/error_panel.js index c2fd7ccc..d0afe2f1 100644 --- a/web/error_panel.js +++ b/web/error_panel.js @@ -86,6 +86,11 @@ const PLAIN_ERRORS = [ title: ['This LoRA cannot be used', '此 LoRA 无法使用'], summary: ['The FreeVideo model is already accelerated and does not need an acceleration LoRA. Turn this LoRA off or remove it, then generate again.', 'FreeVideo 的模型已经加速,无需加速 LoRA。请关闭或移除此 LoRA 后重新生成。']}, + {key: 'lora-alpha', message: 'This LoRA stores one alpha value for layers of different ranks, so its strength cannot be determined. Use a copy that stores an alpha for every layer, or one with the same rank on every layer.', + prefixes: ['This LoRA stores one alpha value for layers of different ranks'], + title: ['This LoRA cannot be used', '此 LoRA 无法使用'], + summary: ['This LoRA stores one alpha value, but its layers have different ranks, so the scale of each layer cannot be determined. Turn it off or remove it, then generate again, or use a version that stores an alpha for every layer.', + '此 LoRA 只记录了一个 alpha 值,而各层的 rank 不同,无法确定每层的缩放比例。请关闭或移除后重新生成,或换用每层都记录了 alpha 的版本。']}, {key: 'lora-int8', message: 'This LoRA changes parts of the model that the int8 version cannot merge yet, so it cannot be used for now. LoRAs that change only linear layers work.', title: ['This LoRA cannot be used', '此 LoRA 无法使用'], summary: ['The int8 version cannot merge the layers this LoRA changes yet. Turn it off or remove it, then generate again.', @@ -850,7 +855,7 @@ export function createErrorPanel(t, route = null) { copy.hidden = generated; copyInside.hidden = !generated; copyInside.textContent = copy.textContent; // For a generation failure the note on removed text sits in the technical details, beside the copy button. privacy.hidden = generated; privacyInside.hidden = !generated; - const lora = ['lora-unusable', 'lora-acceleration', 'lora-int8'].includes(advice.kind); + const lora = ['lora-unusable', 'lora-acceleration', 'lora-alpha', 'lora-int8'].includes(advice.kind); // An int8 limit is not a judgement, so there is no mistake to report. github.hidden = !generated || advice.kind === 'lora-int8'; githubLora = lora; github.textContent = lora ? t('Report a mistake', '报告误判') : t('Report a problem', '提交问题'); diff --git a/web/lora_check.js b/web/lora_check.js index f14b52ee..6c3c1d9e 100644 --- a/web/lora_check.js +++ b/web/lora_check.js @@ -15,6 +15,8 @@ export function describeVerdict(verdict, t) { else if (verdict.reason === 'shape') reason = t('does not match the current model', '和当前模型的结构不匹配'); else if (verdict.reason === 'acceleration') reason = t('an acceleration LoRA made for the original model. The FreeVideo model is already accelerated and does not need one', '这是为原版模型制作的加速 LoRA。FreeVideo 的模型已经加速,无需此类 LoRA'); + else if (verdict.reason === 'alpha') reason = t('the file stores one alpha value but its layers have different ranks, so the scale of each layer cannot be determined', + '文件只记录了一个 alpha 值,而各层的 rank 不同,无法确定每层的缩放比例'); // The model family it was made for stays out of the interface (it is in the report draft below). else reason = family ? t('made for another model', '这是为其他模型制作的 LoRA') : t('not made for the FreeVideo model', '不适用于 FreeVideo 的模型'); const summary = verdict.summary || {}; @@ -24,6 +26,7 @@ export function describeVerdict(verdict, t) { lines.push(where + t(`expected ${size(verdict.expected)}, file has ${size(verdict.actual)}`, `期望 ${size(verdict.expected)},文件是 ${size(verdict.actual)}`)); } if (verdict.layer) lines.push(t('Layer: ', '层:') + verdict.layer); + if (Array.isArray(verdict.ranks) && verdict.ranks.length) lines.push(t('Ranks: ', 'Rank:') + verdict.ranks.join(', ')); if (verdict.count > 1) lines.push(t(`${verdict.count} layers do not match`, `共 ${verdict.count} 层不匹配`)); if (Number.isInteger(summary.keys)) lines.push(t(`${summary.keys} tensors`, `共 ${summary.keys} 个张量`)); for (const [key, shape] of summary.first || []) lines.push(`${key} ${size(shape)}`); @@ -38,7 +41,7 @@ export function feedbackDraft(name, verdict, described, t = (en) => en) { `Check result: ${verdict.reason || 'unknown'}${verdict.family ? ` (${verdict.family})` : ''}${described ? `, ${described.reason}` : ''}`].join('\n'); const summary = verdict.summary || {}; const diagnostics = JSON.stringify({check: {reason: verdict.reason, family: verdict.family, layer: verdict.layer, block: verdict.block, - expected: verdict.expected, actual: verdict.actual, count: verdict.count}, + expected: verdict.expected, actual: verdict.actual, count: verdict.count, ranks: verdict.ranks}, header: {keys: summary.keys, first: summary.first, base: summary.base}}); return {title: (t('[Feedback] LoRA compatibility misjudged: ', '[Feedback] LoRA 兼容判断有误:') + base).slice(0, 120), text, diagnostics}; } From 5b8ae57e6eb776ebe320b60858e64d3f10e44e6c Mon Sep 17 00:00:00 2001 From: Bowen Xue Date: Thu, 19 Nov 2026 09:10:55 +0000 Subject: [PATCH 10/21] Face close-up with new clothes: a too-wide close-up is redrawn larger, a repaint that kept the... Face close-up with new clothes: a too-wide close-up is redrawn larger, a repaint that kept the old clothes is retried, and without a face box the clothes are repainted under a fixed mask --- web/cast_face_crop.js | 69 ++++++++++++++++++++++++++++++++++++++----- web/cast_generate.js | 64 ++++++++++++++++++++++++++++++--------- web/cast_photo.js | 9 ++++-- 3 files changed, 118 insertions(+), 24 deletions(-) diff --git a/web/cast_face_crop.js b/web/cast_face_crop.js index 7ddf3062..f34de891 100644 --- a/web/cast_face_crop.js +++ b/web/cast_face_crop.js @@ -106,15 +106,32 @@ export async function repaintTook({before, after, mask}) { } catch { return true; } } -// The mask for dressMask's part as a PNG file of the close-up's size (white = change), or null. -export async function dressMaskFile({client, fetcher, name}) { +// Where the face cannot be found (an engine without face-box, an illustration it cannot read): a fixed part of a close-up. Measured +// on 40 close-ups of 4 described people (6-20 seeds each): the face box ends at 42-62% of the picture's height and spans 30-70% of +// its width, so everything from 68% down is clothes and shoulders, and an ellipse over the middle keeps the chin. +export const DRESS_FIXED = Object.freeze({top: .68, keep: Object.freeze({cx: .5, cy: .4, rx: .27, ry: .3})}); +export function fixedDressMask(width, height) { + if (!(width > 0 && height > 0)) return null; + const {cx, cy, rx, ry} = DRESS_FIXED.keep; + return {top: Math.round(DRESS_FIXED.top * height), keep: {cx: Math.round(cx * width), cy: Math.round(cy * height), rx: Math.round(rx * width), ry: Math.round(ry * height)}}; +} + +// The mask for dressMask's part as a PNG file of the close-up's size (white = change), or null. Where no face is found, the +// fixed part is used from the picture's own size (`url`) instead of leaving the old clothes on. +export async function dressMaskFile({client, fetcher, name, url}) { try { - const found = await findFaces(client, fetcher, name); - const part = found && dressMask(found.width, found.height, found.faces); + const found = await findFaces(client, fetcher, name).catch(() => null); + let width = found?.width, height = found?.height, part = null; + if (found) part = dressMask(found.width, found.height, found.faces); + if (!part && !found?.faces?.length && url) { + const bitmap = await createImageBitmap(await (await fetcher(url)).blob()); + width = bitmap.width; height = bitmap.height; bitmap.close?.(); + part = fixedDressMask(width, height); + } if (!part) return null; - const canvas = new OffscreenCanvas(found.width, found.height), g = canvas.getContext('2d'), {cx, cy, rx, ry} = part.keep; - g.fillStyle = '#000'; g.fillRect(0, 0, found.width, found.height); - g.fillStyle = '#fff'; g.fillRect(0, part.top, found.width, found.height - part.top); + const canvas = new OffscreenCanvas(width, height), g = canvas.getContext('2d'), {cx, cy, rx, ry} = part.keep; + g.fillStyle = '#000'; g.fillRect(0, 0, width, height); + g.fillStyle = '#fff'; g.fillRect(0, part.top, width, height - part.top); g.fillStyle = '#000'; g.beginPath(); g.ellipse(cx, cy, rx, ry, 0, 0, 2 * Math.PI); g.fill(); return new File([await canvas.convertToBlob({type: 'image/png'})], 'mask.png', {type: 'image/png'}); } catch { return null; } @@ -140,3 +157,41 @@ export function frontalFace(faces) { export async function facesCamera({client, fetcher, name}) { try { const found = await findFaces(client, fetcher, name); return !!found && frontalFace(found.faces); } catch { return false; } } + +// How much of a made close-up the face takes: the largest face box's height over the picture's height, or null where the +// engine cannot tell (no face-box, no face). Measured on 82 close-ups of 5 described people, 6-20 seeds each, and 10 more +// from photos and pictures: 0.26-0.45 (median 0.32, 4% at 0.40 or more); the one cropped at the waist 0.16. The page draws a close-up again under 0.36 (a face about 40% of the height with the margin of the engine's box), and the larger face stays. +export const CLOSEUP_FRAME = Object.freeze({min: .36}); +export function faceShare(height, faces) { + if (!(height > 0) || !Array.isArray(faces)) return null; + const heights = faces.filter(face => Array.isArray(face?.box) && face.box.length === 4 && face.box.every(Number.isFinite)).map(face => face.box[3] - face.box[1]); + return heights.length ? Math.max(...heights) / height : null; +} +export async function closeUpShare({client, fetcher, name}) { + try { const found = await findFaces(client, fetcher, name); return found ? faceShare(found.height, found.faces) : null; } catch { return null; } +} + +// The close-up with everything below the chin painted flat grey, as a PNG file, or null: a repaint of the same garment in +// another colour (a green hoodie to be white) takes the new colour from this base, where it keeps the old one from the +// close-up itself. Measured on a green hoodie to be white, seeds 32-36: 4 of 5 white, against 0 of 6 from the close-up. +export const NEUTRAL_BASE = Object.freeze({grey: 200, chin: .05}); +export async function neutralCloseUp({client, fetcher, name, url}) { + try { + const found = await findFaces(client, fetcher, name); + if (!found?.faces?.length) return null; + const bitmap = await createImageBitmap(await (await fetcher(url)).blob()); + try { + if (bitmap.width !== found.width || bitmap.height !== found.height) return null; + const usable = found.faces.filter(face => Array.isArray(face?.box) && face.box.length === 4 && face.box.every(Number.isFinite)); + if (!usable.length) return null; + const area = face => (face.box[2] - face.box[0]) * (face.box[3] - face.box[1]); + const [, y0, , y1] = usable.reduce((best, face) => area(face) > area(best) ? face : best).box; + const top = Math.round(y1 - NEUTRAL_BASE.chin * (y1 - y0)); + if (top >= found.height) return null; + const canvas = new OffscreenCanvas(found.width, found.height), g = canvas.getContext('2d'); + g.drawImage(bitmap, 0, 0); + g.fillStyle = `rgb(${NEUTRAL_BASE.grey},${NEUTRAL_BASE.grey},${NEUTRAL_BASE.grey})`; g.fillRect(0, top, found.width, found.height - top); + return new File([await canvas.convertToBlob({type: 'image/png'})], 'neutral.png', {type: 'image/png'}); + } finally { bitmap.close?.(); } + } catch { return null; } +} diff --git a/web/cast_generate.js b/web/cast_generate.js index f1abd1b8..bf1d5b69 100644 --- a/web/cast_generate.js +++ b/web/cast_generate.js @@ -46,9 +46,9 @@ const PHOTO_END = 'A real photograph of one person, sharp focus.'; export const PHOTO_PROMPTS = Object.freeze({ // From the whole photo these words keep the likeness best with Qwen (the edit words that turn the head to the front // score lower); kept as measured, "Image 1" included. - face: 'Image 1 shows the person. A tight head-and-shoulders portrait of this person: the head from the top of the hair to the ' - + 'chin fills about 80% of the picture height and a little of the shoulders shows; the person faces the camera at eye level ' - + 'with a neutral expression; the eyes, nose, lips and skin are sharp. The face shape, eyes, nose, mouth, age, hairline, ' + face: 'Image 1 shows the person. A tight close-up portrait of this person: the face from the forehead to the chin fills about ' + + 'half of the picture height, the eyes lie on the upper third line, the top of the hair reaches the top edge, and the neck ' + + 'and the tops of the shoulders fill the lower part; the person faces the camera at eye level with a neutral expression; the eyes, nose, lips and skin are sharp. The face shape, eyes, nose, mouth, age, hairline, ' + 'hairstyle, glasses and accessories match image 1. On a plain light grey studio backdrop with soft even light. One ' + 'photograph of one person.', face_h3: '把改成同一个人的近景正面特写照片:画面从头顶到下巴,再带一点肩膀,人物正对镜头,眼睛平视镜头。' @@ -77,9 +77,9 @@ export function photoFaceModel(info) { // "real photograph" for the picture's style. const STYLE = 'The art style, line work, colours and shading are the same as in .'; export const IMAGE_PROMPTS = Object.freeze({ - face: 'Image 1 shows the character. A tight head-and-shoulders portrait of this character: the head from the top of the hair ' - + 'to the chin fills about 80% of the picture height and a little of the shoulders shows; the character faces the viewer at ' - + 'eye level with a neutral expression. The face shape, eyes, nose, mouth, age, hairline, hairstyle, glasses and accessories ' + face: 'Image 1 shows the character. A tight close-up portrait of this character: the face from the forehead to the chin ' + + 'fills about half of the picture height, the eyes lie on the upper third line, the top of the hair reaches the top edge, and ' + + 'the neck and the tops of the shoulders fill the lower part; the character faces the viewer at eye level with a neutral expression. The face shape, eyes, nose, mouth, age, hairline, hairstyle, glasses and accessories ' + 'match image 1, and the art style, line work, colours and shading are the same as in image 1. On a plain light grey ' + 'backdrop with soft even light. One picture of one character.', face_h3: '把改成同一个角色的近景正面特写:画面从头顶到下巴,再带一点肩膀,角色正对画面,眼睛平视。' @@ -93,9 +93,9 @@ const inStyle = prompt => prompt.replace('a full-body front photograph', 'a full // the front. export const AI_PROMPTS = Object.freeze({ front: `{WHO}. {WEAR}One person stands alone and faces the camera: the whole body from the top of the head to the feet, the arms relaxed at the sides, ${BACKDROP}, sharp focus.`, - face: 'Image 1 shows the person. A tight head-and-shoulders portrait of this person: the head from the top of the hair to the ' - + 'chin fills about 80% of the picture height and a little of the shoulders shows; the person faces the camera at eye level ' - + 'with a neutral expression; the eyes, nose, lips and skin are sharp. The face shape, eyes, nose, mouth, age, hairline, ' + face: 'Image 1 shows the person. A tight close-up portrait of this person: the face from the forehead to the chin fills about ' + + 'half of the picture height, the eyes lie on the upper third line, the top of the hair reaches the top edge, and the neck ' + + 'and the tops of the shoulders fill the lower part; the person faces the camera at eye level with a neutral expression; the eyes, nose, lips and skin are sharp. The face shape, eyes, nose, mouth, age, hairline, ' + 'hairstyle, glasses, accessories and the clothes at the collar match image 1, and the style of the picture is the same as ' + 'image 1. On a plain light grey studio backdrop with soft even light. One picture of one person.', face_h3: '把中的人改成同一个人的近景正面特写:画面从头顶到下巴,再带一点肩膀,人物正对镜头,眼睛平视镜头。' @@ -175,8 +175,11 @@ export function aiPlan(plan, description, {outfitImage = false, faceModel = ''} // The pictures of one set: the engine's views of a description (or a scene's three candidates), or a character's four // views made by the page's plan from a photo, a picture or a description. No DOM: the page below draws its state. // facing: async (made picture) => whether it shows a face toward the camera; a back that does is drawn once more. -// dressTook: async (close-up, repainted, mask) => whether the repaint changed the clothes; one that did not is tried once more. -export function createCastGenerator({client, kind = 'character', views = null, frontAsThird = true, dressMask = null, dressTook = null, facing = null, onChange = () => {}, beforeGenerate = async () => {}, onDiscard = () => {}, schedule = setTimeout, unschedule = clearTimeout}) { +// framing: async (made close-up) => the face's height in the picture's height (null where unknown); a close-up under framingMin +// (cropped at the waist, a half-length portrait) is drawn once more from another seed, and the larger face stays. +// dressTook: async (close-up, repainted, mask) => whether the repaint changed the clothes; one that did not is tried once more, +// from dressNeutral's answer (async close-up => the close-up with its clothes greyed out, '' for none) where there is one. +export function createCastGenerator({client, kind = 'character', views = null, frontAsThird = true, dressMask = null, dressTook = null, dressNeutral = null, facing = null, framing = null, framingMin = .21, onChange = () => {}, beforeGenerate = async () => {}, onDiscard = () => {}, schedule = setTimeout, unschedule = clearTimeout}) { const scene = kind === 'setting' || kind === 'prop', names = views || (scene ? SCENE_CANDIDATES : CAST_VIEWS); const fresh = () => names.map(view => ({view, file: '', fraction: 0})); let state = {pictures: fresh(), running: false, current: -1, error: '', report_id: null, waiting: '', description: '', photo: '', outfit: ''}; @@ -279,7 +282,10 @@ export function createCastGenerator({client, kind = 'character', views = null, f if (!alive()) return null; if (!took) { try { - const again = await runOne(index, alive, {file, mask, again: true}); + let base = ''; + if (dressNeutral) { try { base = await dressNeutral(file); } catch { base = ''; } } + if (!alive()) return null; + const again = await runOne(index, alive, {file: base || file, mask, again: true}); if (again === null) return null; job = null; onDiscard(made); made = again; } catch { const id = job; job = null; if (id) void cancelJob(id); if (!alive()) return null; } @@ -313,9 +319,39 @@ export function createCastGenerator({client, kind = 'character', views = null, f return alive() ? file : null; } } - // A made picture as it goes on the sheet: a close-up dressed in new clothes, a back facing the camera drawn again. + // A face close-up that came out framed too wide (the head small in a half-length picture) is drawn once more from another + // seed; whichever shows the larger face stays, and a failed redraw keeps the first. null: the run was stopped. + async function framed(index, file, alive) { + if (plan[index].view !== 'face' || !framing) return file; + let share = null; + try { share = await framing(file); } catch { share = null; } + if (!alive()) return null; + if (!Number.isFinite(share) || share >= framingMin) return file; + const before = seeds[index]; + seeds[index] = randomSeed(); setPicture(index, {fraction: 0}); + const restore = () => { if (before === undefined) delete seeds[index]; else seeds[index] = before; }; + try { + const again = await runOne(index, alive); + if (again === null) return null; + job = null; + let second = null; + try { second = await framing(again); } catch { second = null; } + if (!alive()) return null; + if (second > share) { onDiscard(file); return again; } + onDiscard(again); restore(); + return file; + } catch { + const id = job; job = null; if (id) void cancelJob(id); + restore(); + return alive() ? file : null; + } + } + // A made picture as it goes on the sheet: a close-up framed again when it came out too wide, then dressed in new clothes; + // a back facing the camera drawn again. async function finished(index, made, alive) { - const file = await dressed(index, made, alive); + const wide = await framed(index, made, alive); + if (wide === null) return null; + const file = await dressed(index, wide, alive); return file === null ? null : turned(index, file, alive); } diff --git a/web/cast_photo.js b/web/cast_photo.js index 5655e59e..e2550c88 100644 --- a/web/cast_photo.js +++ b/web/cast_photo.js @@ -14,7 +14,7 @@ // the card is saved; deleting it there is the only way it goes. The pictures uploaded for the views go when the dialog is left. import {createImageGenClient, imagePackUnavailableMessage, renderImageFailure, IMAGE_GEN_INFO_POLL_MS} from './image_generation.js'; import {createCastGenerator} from './cast_generate.js'; -import {faceCloseUp, dressMaskFile, facesCamera, repaintTook} from './cast_face_crop.js'; +import {faceCloseUp, dressMaskFile, facesCamera, repaintTook, closeUpShare, neutralCloseUp, CLOSEUP_FRAME} from './cast_face_crop.js'; import {createOtherUsageNotice} from './other_usage.js'; // Generation order per source; the order on screen and on the sheet is SHOW. The first view made is the one the others @@ -316,11 +316,14 @@ export function mountCastPhoto({container, api, text, viewURL, onState = () => { // New clothes: the made close-up's collar and shoulders are repainted under a mask drawn from its face box. // The masks drawn here (uploaded name → file), so a repaint can be checked against its own mask. const masks = new Map(); - const dressMask = async file => { const mask = await dressMaskFile({client, fetcher, name: file}); if (!mask) return ''; const name = await referenceOf({file: mask}); masks.set(name, mask); return name; }; + const dressMask = async file => { const mask = await dressMaskFile({client, fetcher, name: file, url: viewURL(file)}); if (!mask) return ''; const name = await referenceOf({file: mask}); masks.set(name, mask); return name; }; const dressTook = (before, after, mask) => masks.has(mask) ? repaintTook({before: viewURL(before), after: viewURL(after), mask: masks.get(mask)}) : true; // A back that came out facing the camera (face-box finds a face looking at it) is drawn once more. const facing = file => facesCamera({client, fetcher, name: file}); - const generator = createCastGenerator({client: draftClient, kind: 'character', views: make, dressMask, dressTook, facing, beforeGenerate: query => otherUsage.check(query), onDiscard: discard, + // A close-up framed too wide is drawn once more; a repaint that kept the old clothes is retried from the close-up with its clothes greyed out. + const framing = file => closeUpShare({client, fetcher, name: file}); + const dressNeutral = async file => { const grey = await neutralCloseUp({client, fetcher, name: file, url: viewURL(file)}); return grey ? referenceOf({file: grey}) : ''; }; + const generator = createCastGenerator({client: draftClient, kind: 'character', views: make, dressMask, dressTook, dressNeutral, facing, framing, framingMin: CLOSEUP_FRAME.min, beforeGenerate: query => otherUsage.check(query), onDiscard: discard, onChange: state => { render(state); }}); From 36ede3fa905dff6a0997d67af01ba03004951728 Mon Sep 17 00:00:00 2001 From: Bowen Xue Date: Thu, 19 Nov 2026 09:12:25 +0000 Subject: [PATCH 11/21] Report a problem: the issue text starts with the display adapter model for every kind of error --- freevideo_engine/launcher_issue.py | 16 ++++++++++++++-- freevideo_engine/modern_launcher.py | 5 +++-- 2 files changed, 17 insertions(+), 4 deletions(-) diff --git a/freevideo_engine/launcher_issue.py b/freevideo_engine/launcher_issue.py index 1d5152cc..b7314f6f 100644 --- a/freevideo_engine/launcher_issue.py +++ b/freevideo_engine/launcher_issue.py @@ -55,7 +55,16 @@ def gib(key): return scrub(' · '.join(part for part in parts if part))[:300] -def issue_url(error, version=None, title=None, zh=False, environment=''): +def adapter_line(): + """The display-adapter line the report ZIP carries: model names only, or that they could not be read.""" + try: + from .display_adapters import adapters, report_line + return scrub(report_line(adapters()))[:300] + except Exception: + return 'Display adapters: not available' + + +def issue_url(error, version=None, title=None, zh=False, environment='', diagnostics=()): lines = _lines(error) # A successful download-tool check can open the text (its Sysnative "not found" is normal); the cause is not that line. from .failure_details import _without_ready_curl_diagnostics @@ -66,7 +75,10 @@ def issue_url(error, version=None, title=None, zh=False, environment=''): report = '\n'.join(lines) # The environment line is for triage, so it stays English in either language and is kept whole; # only the error text gives way to fit the address. - head = (('Environment: ' + scrub(environment).strip() + '\n\n') if str(environment).strip() else '') + # The diagnostic lines (adapter model) come first and are kept whole, whatever the error is. + notes = [scrub(line).strip() for line in diagnostics if str(line).strip()] + head = '\n'.join(([('Environment: ' + scrub(environment).strip())] if str(environment).strip() else []) + notes) + head += '\n\n' if head else '' def fit(limit): return head + (report if len(report) <= limit else report[:limit // 3] + '\n...\n' + report[-(limit - limit // 3 - 5):]) diff --git a/freevideo_engine/modern_launcher.py b/freevideo_engine/modern_launcher.py index 41ff7539..23f0ff3a 100644 --- a/freevideo_engine/modern_launcher.py +++ b/freevideo_engine/modern_launcher.py @@ -425,13 +425,14 @@ def reportProblem(self, error, title): def openReport(self, error, title): from . import __version__ - from .launcher_issue import environment_line, issue_url, machine_hardware, product_version + from .launcher_issue import adapter_line, environment_line, issue_url, machine_hardware, product_version from .windows_ux import open_browser # The release (0.4.x) is named, not the build number; only fields that carry no path or user name travel. version = session.installed_product_version() or product_version(__version__) engine = session.installation_engine() url = issue_url(error, version, title, zh=session.language.startswith('zh'), - environment=environment_line(version, machine_hardware(engine) if engine else {})) + environment=environment_line(version, machine_hardware(engine) if engine else {}), + diagnostics=[adapter_line()]) self.invoke(open_browser, url) @Slot() From e18f9c2171ff2c356bfdc25f6a37f0642817d6ed Mon Sep 17 00:00:00 2001 From: Bowen Xue Date: Thu, 19 Nov 2026 09:15:05 +0000 Subject: [PATCH 12/21] Image warm-up: the package check, read-ahead and planning follow the model's own files, one... Image warm-up: the package check, read-ahead and planning follow the model's own files, one table for MOSS, H3 and Qwen --- freevideo_engine/image_gen/service.py | 25 ++++++++++++++++++++----- freevideo_engine/rewarm.py | 2 +- 2 files changed, 21 insertions(+), 6 deletions(-) diff --git a/freevideo_engine/image_gen/service.py b/freevideo_engine/image_gen/service.py index 87563a2b..e6de7273 100644 --- a/freevideo_engine/image_gen/service.py +++ b/freevideo_engine/image_gen/service.py @@ -1408,7 +1408,7 @@ def skipped(reason): root, machine = self.installation() except (OSError, ValueError): return skipped('pack_missing') - if not image_pack.ready(machine['model_root'], group=H3_GROUP if h3 else 'image'): + if not image_pack.ready(machine['model_root'], group=self.model_group(model) or 'image'): return skipped('pack_missing') from .image_policy import UNIFIED_MIN_TOTAL unified = self.unified_total(machine) @@ -1419,7 +1419,9 @@ def skipped(reason): row['files'] = self.warm_files(machine) row['place_encoder'] = self.h3_resident(machine) elif level == 'light': - row['files'] = self.qwen_files(machine) + row['files'] = self.model_files(machine, model) + elif model == image_model.MOSS: + pass # a MOSS picture is not planned like Qwen's (no preflight): its warm-up is not either else: try: plan = self.preflight(machine, dict(images=[], width=1024, height=1024)) @@ -1520,14 +1522,27 @@ def place_encoder(self, root, machine, env, descriptor, stop=None): stop=stop or self.session_stop) @staticmethod - def qwen_files(machine): - """The picture model's files to read ahead for a light warm-up of the default model.""" + def group_files(machine, group): try: - rows = [image_pack.target(row, machine['model_root']) for row in image_pack.rows(group='image')] + rows = [image_pack.target(row, machine['model_root']) for row in image_pack.rows(group=group)] except Exception: return [] return [str(item) for item in rows if Path(item).is_file()] + @classmethod + def qwen_files(cls, machine): + """The picture model's files to read ahead for a light warm-up of the default model.""" + return cls.group_files(machine, 'image') + + @classmethod + def model_files(cls, machine, model): + """The files to read ahead for a picture model: each model's own, from one table.""" + if model == image_model.H3: + return cls.warm_files(machine) + if model == image_model.MOSS: + return cls.group_files(machine, MOSS_GROUP) + return cls.qwen_files(machine) + @staticmethod def warm_files(machine): """H3 Image's picture model files to read ahead into the OS file cache, in the order a picture reads them. diff --git a/freevideo_engine/rewarm.py b/freevideo_engine/rewarm.py index 01c5ba9a..cb8a559f 100644 --- a/freevideo_engine/rewarm.py +++ b/freevideo_engine/rewarm.py @@ -160,7 +160,7 @@ def need(self, machine): files = encoder_file(machine) else: _, images = self.services() - files = images.warm_files(machine) if self.held == image_model.H3 else images.qwen_files(machine) + files = images.model_files(machine, self.held) size = sum(os.path.getsize(item) for item in files) return size + keep.RESERVE_BYTES if size > 0 else None From 6ca3b93eba2b689f484660b398237991fa731fd3 Mon Sep 17 00:00:00 2001 From: Bowen Xue Date: Thu, 19 Nov 2026 09:21:49 +0000 Subject: [PATCH 13/21] Pictures are also copied into the output folder (Settings: on by default, can be switched off) Pictures are also copied into the output folder (Settings: on by default, can be switched off); the copy is a file of its own and is removed when its picture is deleted for good. Image view: the dice next to Seed fills in a new random seed, so pressing it with an empty box shows a result; empty still draws a new seed for each picture --- freevideo_engine/comfy_progress.py | 2 +- freevideo_engine/comfy_setup.py | 2 +- freevideo_engine/image_gen/service.py | 68 +++++++++++++++++++++++++++ freevideo_engine/output_settings.py | 24 ++++++---- web/image_view.js | 5 +- web/settings_room.js | 22 +++++++-- 6 files changed, 106 insertions(+), 17 deletions(-) diff --git a/freevideo_engine/comfy_progress.py b/freevideo_engine/comfy_progress.py index b7d510f1..9e27dbd8 100644 --- a/freevideo_engine/comfy_progress.py +++ b/freevideo_engine/comfy_progress.py @@ -556,7 +556,7 @@ async def output_settings_route(request): from .output_settings import available, read value = dict(read(installation_root()), available=await asyncio.to_thread(available)) except Exception: - value = dict(ten_bit=False, available=False) + value = dict(ten_bit=False, image_copy=True, available=False) return web.json_response(value, headers={'Cache-Control': 'no-store'}) @server.routes.post('/freevideo/node-view-opened') diff --git a/freevideo_engine/comfy_setup.py b/freevideo_engine/comfy_setup.py index a1045692..07d32bb1 100644 --- a/freevideo_engine/comfy_setup.py +++ b/freevideo_engine/comfy_setup.py @@ -233,7 +233,7 @@ def output_settings(self, value=None): root = installation_root(self.source) if value is None: return dict(read(root), available=available()) - return dict(write(root, value.get('ten_bit')), available=available()) + return dict(write(root, value.get('ten_bit'), value.get('image_copy')), available=available()) def downloads(self, root=None): from .download_settings import read diff --git a/freevideo_engine/image_gen/service.py b/freevideo_engine/image_gen/service.py index e6de7273..329dd8c0 100644 --- a/freevideo_engine/image_gen/service.py +++ b/freevideo_engine/image_gen/service.py @@ -584,6 +584,71 @@ def output_path(self, named=False, suffix='.jpg'): return str(output / (base + suffix)) raise ValueError('invalid_media') + def copy_directory(self): + """Where the copy of a finished picture goes: the output folder of ComfyUI, in a folder named like the one the + pictures are kept in. None when the user switched the copy off or no output folder is known.""" + try: + from ..comfy_bridge import installation_root + from ..output_settings import read + if not read(installation_root())['image_copy']: + return None + output = Path(self.folders.get_output_directory()).resolve() + except Exception: + return None + directory = output / 'freevideo-image' + if directory.is_symlink() or (directory.exists() and not directory.is_dir()): + return None + return directory + + def copy_to_output(self, path): + """Copy a finished picture into the output folder, as a file of its own (a link would let an edit there change + the picture the library keeps). It belongs to the picture: works_deleted removes it. A copy that fails never + fails the picture.""" + try: + directory = self.copy_directory() + if directory is None: + return + source = Path(path) + target = directory / source.name + if source.is_symlink() or not source.is_file() or target.is_symlink(): + return + directory.mkdir(exist_ok=True) + temporary = directory / ('.%s.%s.partial' % (source.name, uuid.uuid4().hex[:8])) + try: + shutil.copyfile(source, temporary) + os.replace(temporary, target) + finally: + temporary.unlink(missing_ok=True) + except Exception: + logging.warning('[FreeVideo] Could not copy a picture into the output folder.', exc_info=True) + + def forget_copies(self, names): + """Remove the copies in the output folder of pictures deleted for good; only the plain file of that name.""" + try: + directory = self.copy_directory_any() + if directory is None: + return + for name in names: + target = directory / name.rpartition('/')[2] + try: + if target.parent == directory and not target.is_symlink() and target.is_file(): + target.unlink() + except OSError: + logging.warning('[FreeVideo] Could not remove a picture copy in the output folder.', exc_info=True) + except Exception: + logging.warning('[FreeVideo] Could not remove the picture copies of deleted pictures.', exc_info=True) + + def copy_directory_any(self): + """The copy folder whether or not copying is on now: a picture copied earlier is removed all the same.""" + try: + output = Path(self.folders.get_output_directory()).resolve() + except Exception: + return None + directory = output / 'freevideo-image' + if directory.is_symlink() or not directory.is_dir(): + return None + return directory + @staticmethod def work_record(value, origin): """What a new picture keeps about where it came from: a picture of the history or a content id, and the content @@ -682,6 +747,7 @@ def history_save(self, value): except (OSError, Image.DecompressionBombError, SyntaxError): raise ValueError('invalid_media') from None self.note_record(target, record) + self.copy_to_output(target) finally: self.remove_uploads([name]) return dict(file='freevideo-image/' + target.name, name=target.name) @@ -805,6 +871,7 @@ def works_deleted(self, names): names = [name for name in names if isinstance(name, str)] if not names: return + self.forget_copies(names) try: output = self.output_directory() rows = self.made_by(output) @@ -2562,6 +2629,7 @@ def infer(self, session, value): self.keep_forecast(context) self.note_model(path, value.get('model') or image_model.QWEN) self.note_record(path, getattr(context, 'work_record', None)) + self.copy_to_output(path) receipts = row.get('receipts') from ..private_refs import hold hold('image:' + path.name, value.get('images') or (), input_root=self.input_directory(), diff --git a/freevideo_engine/output_settings.py b/freevideo_engine/output_settings.py index 5207da8a..fe36b55a 100644 --- a/freevideo_engine/output_settings.py +++ b/freevideo_engine/output_settings.py @@ -1,4 +1,5 @@ -"""Whether a finished video is also saved as a 10-bit copy (see video_10bit.py). Off unless the user turns it on.""" +"""Output choices: whether a finished video is also saved as a 10-bit copy (see video_10bit.py; off unless the user turns it +on) and whether a finished picture is also copied into the output folder (on unless the user turns it off).""" import json from pathlib import Path @@ -20,20 +21,27 @@ def available(): def read(root): - """{'ten_bit': bool}; anything unreadable is off.""" + """{'ten_bit': bool, 'image_copy': bool}; a 10-bit copy that cannot be read is off, a picture copy is on.""" try: value = json.loads((Path(root) / FILE).read_text(encoding='utf-8')) except (OSError, ValueError): - return dict(ten_bit=False) - return dict(ten_bit=isinstance(value, dict) and value.get('ten_bit') is True) + return dict(ten_bit=False, image_copy=True) + value = value if isinstance(value, dict) else {} + return dict(ten_bit=value.get('ten_bit') is True, image_copy=value.get('image_copy') is not False) -def write(root, ten_bit): - if not isinstance(ten_bit, bool): - raise ValueError('The 10-bit copy is switched on or off') +def write(root, ten_bit=None, image_copy=None): + """Change the choices given (None leaves one as it is) and return both.""" + for name, value in (('The 10-bit copy', ten_bit), ('The picture copy in the output folder', image_copy)): + if value is not None and not isinstance(value, bool): + raise ValueError(name + ' is switched on or off') if ten_bit and not available(): raise ValueError('This installation cannot write 10-bit video') - result = dict(ten_bit=ten_bit) + result = read(root) + if ten_bit is not None: + result['ten_bit'] = ten_bit + if image_copy is not None: + result['image_copy'] = image_copy save(Path(root) / FILE, result) return result diff --git a/web/image_view.js b/web/image_view.js index bb5277fb..9f99f165 100644 --- a/web/image_view.js +++ b/web/image_view.js @@ -21,6 +21,7 @@ import { keepViewSwitchPlace } from './view_switch_place.js'; import { openReferenceMenu, removeSavedImages } from './image_library.js'; import { BLANK_CANVAS_AREAS, createImageGenClient, fittedNote, imageGenError, imageRemainingText, imageReportBar, renderImageFailure } from './image_generation.js'; import { duration } from './generation_progress.js'; +import { randomSeed } from './studio_queue.js'; import { createPreviewScene } from './preview_scene.js?v=20261115-still'; import { jobs, ACTIVE, IMAGE_BUSY } from './task_store.js'; import { confirmStop, startJobSources } from './task_float.js'; @@ -336,8 +337,8 @@ export function openImageView(node, {studio = null, client: given = null, poll = const advanced = {get open() { return advGroup.isOpen(); }, set open(value) { advGroup.open(!!value); }}; const seedInput = el('input'); seedInput.type = 'number'; seedInput.min = '0'; seedInput.max = String(2 ** 53 - 1); seedInput.step = '1'; seedInput.placeholder = t('New each run', '每次随机'); tip(seedInput, t('Seed', '种子'), t('Empty: new each time; a number repeats a picture', '留空每次不同;填数字可复现同一张')); - const dice = button('fv-iv-icon-btn', {iconName: 'dice', name: t('Random seed', '随机种子'), use: t('Back to a new seed each run', '恢复每次随机')}); - dice.addEventListener('click', () => { seedInput.value = ''; render(); }); + const dice = button('fv-iv-icon-btn', {iconName: 'dice', name: t('Random seed', '随机种子'), use: t('Fill in a random seed', '填入一个随机种子')}); + dice.addEventListener('click', () => { seedInput.value = String(randomSeed()); render(); }); seedInput.addEventListener('input', () => render()); const seedField = el('label', 'fv-image-seed fv-iv-field fv-iv-field-wide'); seedField.append(el('span', 'fv-iv-field-key', t('Seed', '种子')), seedInput, dice); // LoRA: a button whose panel opens beside it; it answers for the model that takes LoRA files. diff --git a/web/settings_room.js b/web/settings_room.js index b9bb3cb9..db0b93f4 100644 --- a/web/settings_room.js +++ b/web/settings_room.js @@ -485,21 +485,33 @@ export async function openSetup(options) { tenSwitch.setAttribute('aria-label', t('Also save a high color depth copy', '同时保存高色深版本')); const tenRow = row({iconName: 'film', title: t('Also save a high color depth copy', '同时保存高色深版本'), sub: t('Adds a 10-bit video beside it, for color grading', '另存一份 10 位视频,适合调色'), end: [tenSwitch]}); tip(tenSwitch, t('High color depth copy', '高色深版本'), t('Adds a 10-bit video beside it, for color grading', '另存一份 10 位视频,适合调色')); - const outputCard = card(tenRow.element); const outputHead = groupHead(t('Finished video', '成片')); - outputCard.hidden = outputHead.hidden = true; - let tenSaved = false; + // Every finished picture is also copied into the output folder; the user can switch that off. The 10-bit row stays hidden. + const imageSwitch = switchify(el('input')); imageSwitch.type = 'checkbox'; imageSwitch.checked = true; + imageSwitch.setAttribute('aria-label', t('Also save pictures to the output folder', '同时将图片保存到 output 文件夹')); + const imageRow = row({iconName: 'img', title: t('Also save pictures to the output folder', '同时将图片保存到 output 文件夹'), end: [imageSwitch]}); + tip(imageSwitch, t('Also save pictures to the output folder', '同时将图片保存到 output 文件夹')); + tenRow.element.hidden = true; + const outputCard = card(imageRow.element, tenRow.element); const outputHead = groupHead(t('Finished videos and pictures', '成片与图片')); + let tenSaved = false, imageSaved = true; tenSwitch.onchange = async () => { const wanted = tenSwitch.checked; tenSwitch.disabled = true; try { tenSaved = (await request('output-settings', {ten_bit: wanted})).ten_bit === true; } catch { /* The switch returns to the saved state. */ } finally { tenSwitch.checked = tenSaved; tenSwitch.disabled = false; } }; + imageSwitch.onchange = async () => { + const wanted = imageSwitch.checked; imageSwitch.disabled = true; + try { imageSaved = (await request('output-settings', {image_copy: wanted})).image_copy !== false; } + catch { /* The switch returns to the saved state. */ } + finally { imageSwitch.checked = imageSaved; imageSwitch.disabled = false; } + }; (async () => { try { const response = await api.fetchApi('/freevideo/output-settings'); const value = response.ok ? await response.json() : null; - if (value?.available === true) { tenSaved = value.ten_bit === true; tenSwitch.checked = tenSaved; outputCard.hidden = outputHead.hidden = false; } - } catch { /* Without an answer the row stays hidden. */ } + if (value) { imageSaved = value.image_copy !== false; imageSwitch.checked = imageSaved; } + if (value?.available === true) { tenSaved = value.ten_bit === true; tenSwitch.checked = tenSaved; tenRow.element.hidden = false; } + } catch { /* Without an answer the picture row shows its default and the 10-bit row stays hidden. */ } })(); const previewFoot = el('div', 'st-foot'); previewFoot.append(previewStatus); generation.append(groupHead(t('Preview during generation', '生成中的预览')), card(choices, previewFoot), outputHead, outputCard); From 382120310d4b996e3569bec3f9c56fe0f4e0be47 Mon Sep 17 00:00:00 2001 From: Bowen Xue Date: Thu, 19 Nov 2026 09:14:35 +0000 Subject: [PATCH 14/21] Image model downloads no longer pause as "a video is generating" while the image view only keeps... Image model downloads no longer pause as "a video is generating" while the image view only keeps or warms a model; a paused download says what it waits for and can be continued Opening the image view warms the picture model, and the image worker keeps the GPU lease while it waits; a model download took that lease for a running video and stayed paused at 0 %. A download now waits only for a video or a picture being made. When another program holds the graphics card it says so instead of naming a video. The image view, Settings and the launcher show the reason, and Continue download runs it at once, noting that a generation in progress may take longer. --- freevideo_engine/image_gen/image_pack.py | 40 ++++++++++++++++++------ freevideo_engine/image_gen/service.py | 26 +++++++++++++-- freevideo_engine/launcher_session.py | 5 ++- web/image_generation.js | 9 ++++-- web/image_view.js | 13 ++++++-- web/image_view_models.js | 25 ++++++++++----- web/settings_room.js | 18 ++++++++--- 7 files changed, 105 insertions(+), 31 deletions(-) diff --git a/freevideo_engine/image_gen/image_pack.py b/freevideo_engine/image_gen/image_pack.py index ce2fc392..6a28fc3f 100644 --- a/freevideo_engine/image_gen/image_pack.py +++ b/freevideo_engine/image_gen/image_pack.py @@ -68,8 +68,15 @@ def __init__(self, installer, stop): self.resume_at = None self.paused = False self.probed_at, self.probe_gap, self.busy_seen = None, 0., False + self.reason = None def generating(self): + """Why the download waits, or None. Only real work waits it: a video this process runs (generation_busy), + or a holder of engine.lock that is not known to be idle. This process's own image worker that only keeps or + warms its model (lease_idle) holds the lock without using the card for a picture, so the download goes on. + After the user asks to continue (resume_anyway), nothing waits it.""" + if self.installer.resume_anyway.is_set(): + return None if self.installer.generation_busy: if self.probed_at is None or time.monotonic() - self.probed_at >= self.probe_gap: began = time.monotonic() @@ -78,25 +85,27 @@ def generating(self): self.probe_gap = max(GENERATION_PROBE_SECONDS, GENERATION_PROBE_COST_FACTOR * (self.probed_at - began)) if self.busy_seen: - return True + return 'busy_video' # Probe the existing lease exclusively, without borrowing an inherited # descriptor. This also detects shared device work. Release immediately: # downloads never hold engine.lock or delay a generation acquiring it. - # A holder is the only cross-process signal; non-generation holders also - # cause a conservative pause. In-process callers can supply busy(). path = (Path(self.installer.engine_root) / 'engine.lock' if self.installer.engine_root is not None else None) try: with runtime_lock(path, inherit=False): - return False + return None except BlockingIOError: - return True + holder = self.installer.lease_holder() if self.installer.lease_holder else None + if holder == 'idle': + return None + return 'busy_picture' if holder == 'picture' else 'busy_engine' def check(self): if self.stop.is_set(): raise InterruptedError('cancelled') - if self.generating(): - self.paused = True + reason = self.generating() + if reason: + self.paused, self.reason = True, reason self.resume_at = None raise _GenerationPause() @@ -109,14 +118,14 @@ def wait(self): else: if self.paused and self.resume_at is None: self.resume_at = time.monotonic() + GENERATION_RESUME_SECONDS - if not self.paused or time.monotonic() >= self.resume_at: + if not self.paused or time.monotonic() >= self.resume_at or self.installer.resume_anyway.is_set(): self.resume_at = None self.paused = False self.installer._set(state='running', reason=None) return # Reached only after the active transfer has been reaped, or at an # in-process checkpoint, so paused really means no active download. - self.installer._set(state='paused_for_generation', reason='busy_video') + self.installer._set(state='paused_for_generation', reason=self.reason or 'busy_engine') self.stop.wait(GENERATION_POLL_SECONDS) @@ -916,10 +925,15 @@ def remove(root=None, check=None, *, engine_root=None, group='image'): class Installer: """One background action per pack; cancel keeps completed files and prefixes.""" - def __init__(self, root=None, *, engine_root=None, busy=None, group='image'): + def __init__(self, root=None, *, engine_root=None, busy=None, group='image', holder=None): self.root, self.engine_root = root, engine_root self.group = group + # busy(): a video this process runs. holder(): what holds engine.lock in this process -- 'picture' (a picture + # is being made), 'idle' (the image worker only keeps or warms its model) or None (not this process). self.generation_busy = busy + self.lease_holder = holder + # Set when the user asks to continue a paused download: it then runs beside whatever holds the card. + self.resume_anyway = threading.Event() self.lock = threading.Lock() self.stop = threading.Event() self.thread = None @@ -1004,6 +1018,7 @@ def start(self, action='install', *, background=False): if self.busy: return dict(self.value) self.stop = threading.Event() + self.resume_anyway.clear() self.background = background self.samples.clear() self.transferred, self.last_done = 0, None @@ -1020,6 +1035,11 @@ def cancel(self): self.stop.set() return self.state() + def continue_anyway(self): + """The user asked to go on with a paused download: it no longer waits for this run.""" + self.resume_anyway.set() + return self.state() + def _run(self, action, stop, background): def check(): if stop.is_set(): diff --git a/freevideo_engine/image_gen/service.py b/freevideo_engine/image_gen/service.py index 329dd8c0..c45b90fc 100644 --- a/freevideo_engine/image_gen/service.py +++ b/freevideo_engine/image_gen/service.py @@ -286,6 +286,16 @@ def _video_busy(): def busy(self): return self._busy or self.segmenting + def lease_holder(self): + """What holds engine.lock in this process, for a model download deciding whether to wait: 'picture' while a + picture is made, 'idle' while the image worker only keeps or warms its model (its session holds the lock + for its whole life), None when this process's image worker does not hold it.""" + with self.mutex: + worker = self.worker + if self.per_request or worker is None or worker.process.poll() is not None: + return None + return 'picture' if self._busy else 'idle' + @staticmethod def pack_checked(call, *args, **kwargs): """(value, problem): a model folder that cannot be read safely (a link leading nowhere) marks that model as @@ -447,6 +457,9 @@ def pack_row(installer, ready, problem=None): bytes_per_second=round(value.get('bytes_per_second', 0)), **({'phase': 'verify', 'verify_done': value.get('verify_done'), 'verify_total': value.get('verify_total')} if value.get('phase') == 'verify' else {})) + if value['state'] == 'paused_for_generation': + # What it waits for, in the page's own words: a video, a picture, or another task on the card. + row['reason'] = value.get('reason') or 'busy_engine' 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']) @@ -459,7 +472,7 @@ def _pack_installer(self, model, root, engine_root): installer = getattr(self, attribute) if installer is None or installer.root != root or installer.engine_root != engine_root: options = dict(group=self.model_group(model)) if model != image_model.QWEN else {} - installer = image_pack.Installer(root, engine_root=engine_root, busy=self.video_busy, **options) + installer = image_pack.Installer(root, engine_root=engine_root, busy=self.video_busy, holder=self.lease_holder, **options) setattr(self, attribute, installer) return installer @@ -520,10 +533,12 @@ def pack_action(self, action, *, group='image', model=None): if action == 'cancel': if installer is not None: installer.cancel() + elif installer is not None and installer.state()['state'] == 'paused_for_generation': + installer.continue_anyway() elif (not self.pack_checked(image_pack.ready, root, group=group)[0] and not self.pack_checked(image_pack.downloading, root, engine_root)[0]): if installer is None or installer.root != root or installer.engine_root != engine_root: - installer = image_pack.Installer(root, engine_root=engine_root, busy=self.video_busy, group=group) + installer = image_pack.Installer(root, engine_root=engine_root, busy=self.video_busy, holder=self.lease_holder, group=group) self.segment_installer = installer installer.start('install', background=True) return self.info() @@ -538,6 +553,9 @@ def pack_action(self, action, *, group='image', model=None): installer.cancel() elif target in self.pack_queue: pass + elif self._paused_installer(target) is not None: + # Asked again while it waits for the card: the user wants the download now, beside whatever runs. + self._paused_installer(target).continue_anyway() elif not self._pack_ready(target, root): other = self._active_pack() if other is not None and other != target: @@ -549,6 +567,10 @@ def pack_action(self, action, *, group='image', model=None): self._pack_installer(target, root, engine_root).start('install', background=True) return self.info() + def _paused_installer(self, target): + installer = {image_model.H3: self.h3_installer, image_model.MOSS: self.moss_installer}.get(target, self.pack_installer) + return installer if installer is not None and installer.state()['state'] == 'paused_for_generation' else None + def media_path(self, name): """Shared input-name and symlink policy for generation and point selection.""" directory = Path(self.input_directory()).resolve() diff --git a/freevideo_engine/launcher_session.py b/freevideo_engine/launcher_session.py index 4d1c67e5..24493427 100644 --- a/freevideo_engine/launcher_session.py +++ b/freevideo_engine/launcher_session.py @@ -1098,7 +1098,10 @@ def image_pack_view(self, model='image'): if active.get('action') == 'install' and active.get('phase') == 'verify': detail = self.t('Checking', '正在校验') elif active.get('state') == 'paused_for_generation': - detail = self.t('Paused while generating', '生成时暂停') + # What the download waits for: a video, a picture, or another task holding the graphics card. + detail = {'busy_video': self.t('Paused while a video generates', '视频生成中,已暂停'), + 'busy_picture': self.t('Paused while a picture is made', '正在出图,已暂停')}.get( + active.get('reason'), self.t('Paused: the graphics card is busy', '显卡忙,已暂停')) elif active.get('state') == 'cancelled': detail = self.t('Paused', '已暂停') elif active.get('state') == 'failed': diff --git a/web/image_generation.js b/web/image_generation.js index 184c0833..72fc9b97 100644 --- a/web/image_generation.js +++ b/web/image_generation.js @@ -205,8 +205,11 @@ export function packView(info, t) { 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', '视频生成中,已暂停') + // A paused download offers to continue now; the note says what it waits for. + return {loading: true, waiting, button: waiting ? t('Continue download', '继续下载') : t('Pause', '暂停'), fraction: total > 0 ? Math.min(1, (install.done || 0) / total) : 0, + note: waiting ? (install.reason === 'busy_video' ? t('Paused while a video generates', '视频生成中,已暂停') + : install.reason === 'busy_picture' ? t('Paused while a picture is made', '正在出图,已暂停') + : t('Paused while FreeVideo uses the graphics card for another task', 'FreeVideo 正在用显卡做别的任务,已暂停')) : 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; @@ -1102,7 +1105,7 @@ export function createImageGeneration({client, renderer, t, getDoc, getSelection const note = el('div', '', 'fv-ie-opt-note fv-ie-gen-note'); note.setAttribute('role', 'status'); const action = button(t('Generate', '生成'), null, () => { 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'); + if (pack) void session.pack(pack.loading && !pack.waiting ? 'cancel' : 'install'); else if (now.running) void stop(); else void start(); }, 'fv-ie-button fv-ie-primary'); // Stop asks first (the same glass confirm as everywhere); leaving the editor never stops the job. diff --git a/web/image_view.js b/web/image_view.js index 9f99f165..4221e0dd 100644 --- a/web/image_view.js +++ b/web/image_view.js @@ -26,7 +26,7 @@ import { createPreviewScene } from './preview_scene.js?v=20261115-still'; import { jobs, ACTIVE, IMAGE_BUSY } from './task_store.js'; import { confirmStop, startJobSources } from './task_float.js'; import { el, icon, t, cn, tip, button, section, readStore, writeStore, mod } from './image_view_ui.js'; -import { IMAGE_MODELS, modelPicker, modelState, verifyText } from './image_view_models.js'; +import { IMAGE_MODELS, modelPicker, modelState, verifyText, pausedText } from './image_view_models.js'; import { RANGES, RATIOS, areaRange, estimateSeconds, machineLimit, presetAt, ratioValue, sizePicker, sizeFor, sizeText, megapixels } from './image_view_size.js'; import { createMetaStore, createTrash, filterCounts, filterRows, groupRows, historyPanel, sessionPrompts } from './image_view_history.js'; import { brokenMentions, mentionText, mentionsToEngine, posePrompt, promptMentions, renumberMentions, sketchPrompt } from './image_view_mentions.js'; @@ -77,14 +77,17 @@ export function createFakeImageClient({delay = 600, ready = {'minimax-h3-image': references = {'minimax-h3-image': 0, 'qwen-image-2.1-turbo': 4, 'moss-image-sft': 0}, history = [], install = {}, sizes = ['standard', 'high'], fitted = null, bytes = 12.5e9, rate = 5e6} = {}) { const items = history.map(row => typeof row === 'string' ? {file: row, name: row.slice(row.lastIndexOf('/') + 1)} : row); let count = 0; const jobs = new Map(), state = {...ready}; const loading = new Map(), failed = new Set(Object.keys(install).filter(id => install[id] === 'failed')); + // 'paused:' (busy_video, busy_picture, busy_engine): a download waiting for the card, until Continue. + const paused = new Map(Object.keys(install).filter(id => String(install[id]).startsWith('paused')).map(id => [id, install[id].split(':')[1] || 'busy_engine'])); for (const id of Object.keys(install)) { if (install[id] !== 'ready') state[id] = false; if (install[id] === 'downloading') loading.set(id, Date.now() - bytes / rate * .4); } const models = () => IMAGE_MODELS.map(m => ({id: m.id, label: m.name, ready: !!state[m.id], downloading: loading.has(m.id), max_images: references[m.id] ?? 0, bytes_total: bytes, bytes_done: loading.has(m.id) ? Math.min(bytes, (Date.now() - loading.get(m.id)) * rate) : failed.has(m.id) ? bytes * .31 : 0, install: failed.has(m.id) ? {state: 'failed', done: bytes * .31, total: bytes, reason: 'network', message_en: 'The connection dropped.', message_zh: '网络连接中断了。'} + : paused.has(m.id) ? {state: 'paused_for_generation', done: bytes * .2, total: bytes, bytes_per_second: 0, reason: paused.get(m.id)} : loading.has(m.id) ? {state: 'running', done: Math.min(bytes, (Date.now() - loading.get(m.id)) * rate), total: bytes} : null})); return { info: async () => { for (const [id, at] of loading) if (Date.now() - at > bytes / rate) { state[id] = true; loading.delete(id); } return {installed: true, ready: true, max_images: 16, sizes, models: models()}; }, - packInstall: async id => { failed.delete(id); loading.set(id, Date.now()); return {installed: true, sizes, models: models()}; }, + packInstall: async id => { failed.delete(id); if (paused.delete(id)) loading.set(id, Date.now() - bytes / rate * .2); else loading.set(id, Date.now()); return {installed: true, sizes, models: models()}; }, packCancel: async id => { loading.delete(id); return {installed: true, sizes, models: models()}; }, async generate({prompt, width, height, seed, model, images = []}) { if (fail) throw Object.assign(new Error(fail), {code: fail}); @@ -1001,6 +1004,9 @@ export function openImageView(node, {studio = null, client: given = null, poll = } else if (s.state === 'failed') { kind = 'warn'; parts = [icon('warn'), el('span', 'fv-iv-slot-tx', t(`${model.short} download failed${s.reason ? ': ' + s.reason.replace(/[.。]$/, '') : ''}. Retry to continue; if it keeps failing, report the problem.`, `${model.short} 下载失败${s.reason ? ':' + s.reason.replace(/[.。]$/, '') : ''}。请重试以继续下载;仍然失败时,请提交问题。`))]; + } else if (s.state === 'downloading' && s.paused) { + // What the download waits for, and that the model row's Continue download runs it now. + kind = 'info'; parts = [icon('clock'), el('span', 'fv-iv-slot-tx', t(`${model.short}: ${pausedText(s)}`, `${model.short}:${pausedText(s)}`))]; } else if (s.state === 'downloading') { kind = 'info'; parts = [icon(s.unknown ? 'clock' : 'down'), el('span', 'fv-iv-slot-tx', s.verifying ? (pendingGenerate ? t(`Verifying ${model.short}; it generates when done`, `正在校验 ${model.short},完成后自动生成`) : t(`Verifying ${model.short}`, `正在校验 ${model.short}`)) : pendingGenerate ? t(`Installing ${model.short}; it generates when done`, `正在安装 ${model.short},完成后自动生成`) : t(`Installing ${model.short}`, `正在安装 ${model.short}`))]; @@ -1069,7 +1075,8 @@ export function openImageView(node, {studio = null, client: given = null, poll = goLabel.textContent = t('Stop', '停止'); goSub.textContent = ''; tip(go, t('Stop', '停止'), t('Cancel this picture; asks first', '取消这一张,会先确认')); } else if (s.state === 'downloading') { - goLabel.textContent = s.verifying ? verifyText(s) : t(`Installing ${Math.floor(s.fraction * 100)}%`, `正在安装 ${Math.floor(s.fraction * 100)}%`); + goLabel.textContent = s.verifying ? verifyText(s) : s.paused ? t(`Paused ${Math.floor(s.fraction * 100)}%`, `已暂停 ${Math.floor(s.fraction * 100)}%`) + : t(`Installing ${Math.floor(s.fraction * 100)}%`, `正在安装 ${Math.floor(s.fraction * 100)}%`); goSub.textContent = pendingGenerate ? t('then generates', '完成后生成') : ''; tip(go, pendingGenerate ? t('Generates when installed', '安装完自动生成') : t('Generate when installed', '安装完再生成'), pendingGenerate ? t('Press to not generate after it', '再按一次取消自动生成') : t('Press to generate as soon as it is installed', '按下后,安装完成即自动生成')); } else if (s.state === 'missing' || s.state === 'failed') { diff --git a/web/image_view_models.js b/web/image_view_models.js index ad069a4c..8e4707e0 100644 --- a/web/image_view_models.js +++ b/web/image_view_models.js @@ -25,13 +25,23 @@ export function modelState(info, id) { const fraction = verifying ? (install.verify_total > 0 ? Math.min(1, (install.verify_done || 0) / install.verify_total) : 0) : total > 0 ? Math.min(1, done / total) : 0; if (row.downloading || install.state === 'running' || install.state === 'paused_for_generation') - return {state: 'downloading', row, total, done, fraction, verifying, paused: install.state === 'paused_for_generation', rate: install.bytes_per_second || 0}; + return {state: 'downloading', row, total, done, fraction, verifying, paused: install.state === 'paused_for_generation', + waitsFor: install.state === 'paused_for_generation' ? install.reason || 'busy_engine' : '', rate: install.bytes_per_second || 0}; if (install.state === 'failed') return {state: 'failed', row, total, done, fraction, reason: t(install.message_en || '', install.message_zh || '') || install.reason || ''}; return {state: 'missing', row, total, done, fraction, resume: done > 0}; } const gb = bytes => (bytes / 1e9).toFixed(1); +// Why a download waits, as the engine reports it: only a video or a picture being made pauses it, and the user can +// continue it at once. +// What pressing Continue download does: the download runs now, beside the video or picture being made. +export const continueUse = () => t('Download now; a video or picture being made may take longer', '现在就下载;正在进行的生成可能会变慢'); +export function pausedText(state) { + return state.waitsFor === 'busy_video' ? t('Paused while a video generates; resumes after it, or continue now', '视频生成中,下载已暂停,之后自动继续,也可以现在继续下载') + : state.waitsFor === 'busy_picture' ? t('Paused while a picture is made; resumes after it, or continue now', '正在出图,下载已暂停,出完自动继续,也可以现在继续下载') + : t('Paused while FreeVideo uses the graphics card for another task; resumes after it, or continue now', 'FreeVideo 正在用显卡做别的任务,下载已暂停,之后自动继续,也可以现在继续下载'); +} // Checking files already on disk: a percentage only when the engine reports one. export const verifyText = state => state.unknown ? t('Verifying', '正在校验') : t(`Verifying ${Math.floor(state.fraction * 100)}%`, `正在校验 ${Math.floor(state.fraction * 100)}%`); // The size to download, said once: files the video models already have are not fetched again. @@ -62,14 +72,14 @@ function useOf(model, state) { : model.id === 'moss-image-sft' ? t('Pictures from a text prompt', '根据文字提示出图') : t('Fast pictures, up to 4 references', '出图快,最多 4 张参考图'), missing: state.row?.blocked_by ? t('Not installed: another model is downloading; this one installs after it, or when you press Generate', '未安装:另一个模型正在下载,完成后才会安装这个,也可点生成') : t(`Not installed: Generate installs it first, ${size}`, `未安装:点生成会先安装,${size}`), - downloading: state.paused ? t('Paused while a video generates; resumes after it', '视频生成中,下载已暂停,之后自动继续') : state.verifying ? (state.unknown ? t('Verifying the files; usable when done', '正在校验文件,完成后可以使用') : t(`Verifying the files ${Math.floor(state.fraction * 100)}%; usable when done`, `正在校验文件 ${Math.floor(state.fraction * 100)}%,完成后即可使用`)) : t(`Downloading ${Math.floor((state.fraction || 0) * 100)}%; usable when done`, `正在下载 ${Math.floor((state.fraction || 0) * 100)}%,完成后即可使用`), + downloading: state.paused ? pausedText(state) : state.verifying ? (state.unknown ? t('Verifying the files; usable when done', '正在校验文件,完成后可以使用') : t(`Verifying the files ${Math.floor(state.fraction * 100)}%; usable when done`, `正在校验文件 ${Math.floor(state.fraction * 100)}%,完成后即可使用`)) : t(`Downloading ${Math.floor((state.fraction || 0) * 100)}%; usable when done`, `正在下载 ${Math.floor((state.fraction || 0) * 100)}%,完成后即可使用`), failed: state.reason || t('The download stopped; press Retry', '下载中断了,点重试'), unavailable: model.id === 'moss-image-sft' ? t('MOSS-Image needs an NVIDIA graphics card, which this computer does not have. Choose another model', 'MOSS-Image 需要 NVIDIA 显卡,这台电脑没有。请选别的模型') : t('This model needs an NVIDIA graphics card, which this computer does not have. Choose another model', '这个模型需要 NVIDIA 显卡,这台电脑没有。请选别的模型'), checking: t('Asking the engine', '正在询问引擎'), }[state.state]; } -const actionOf = state => state.state === 'missing' ? (state.resume ? t('Resume', '继续') : t('Install', '安装')) : state.state === 'failed' ? t('Retry', '重试') : state.state === 'downloading' && !state.verifying ? t('Pause', '暂停') : ''; +const actionOf = state => state.state === 'missing' ? (state.resume ? t('Resume', '继续') : t('Install', '安装')) : state.state === 'failed' ? t('Retry', '重试') : state.state === 'downloading' && state.paused ? t('Continue download', '继续下载') : state.state === 'downloading' && !state.verifying ? t('Pause', '暂停') : ''; // The picker: one row for the chosen model; the list opens below it (above when there is no room), takes the // arrow keys, Home, End, Enter and Escape, and scrolls when there are more models than fit. @@ -104,8 +114,8 @@ export function modelPicker({host, onPick, onInstall, onPause}) { row.append(icon('check', 'fv-iv-mopt-mark'), text); const act = actionOf(state); if (act) { - const b = button('fv-iv-text-btn fv-iv-mopt-act', {label: act, name: act, use: useOf(model, state)}); - b.addEventListener('click', event => { event.stopPropagation(); if (state.state === 'downloading') onPause(model); else onInstall(model); close(false); }); + const b = button('fv-iv-text-btn fv-iv-mopt-act', {label: act, name: act, use: state.paused ? continueUse() : useOf(model, state)}); + b.addEventListener('click', event => { event.stopPropagation(); if (state.state === 'downloading' && !state.paused) onPause(model); else onInstall(model); close(false); }); row.append(b); } if (state.state === 'downloading') { const p = el('i', 'fv-iv-mpick-bar'); p.style.setProperty('--p', String(state.fraction || 0)); row.append(p); } @@ -125,7 +135,7 @@ export function modelPicker({host, onPick, onInstall, onPause}) { }); document.addEventListener('pointerdown', event => { if (!list.hidden && !list.contains(event.target) && !root.contains(event.target)) close(false); }, true); addEventListener('resize', () => { if (!list.hidden) place(); }); - action.addEventListener('click', () => { const model = IMAGE_MODELS.find(m => m.id === last.chosen); const state = modelState(last.info, last.chosen); if (!model) return; if (state.state === 'downloading') onPause(model); else onInstall(model); }); + action.addEventListener('click', () => { const model = IMAGE_MODELS.find(m => m.id === last.chosen); const state = modelState(last.info, last.chosen); if (!model) return; if (state.state === 'downloading' && !state.paused) onPause(model); else onInstall(model); }); function paint(info, chosen, pending) { last = {info, chosen, pending}; @@ -137,7 +147,8 @@ export function modelPicker({host, onPick, onInstall, onPause}) { status.hidden = state.state === 'ready' || state.state === 'checking'; tip(trigger, t('Model', '模型'), t(`${model.name}: ${useOf(model, state)}. Click to choose another`, `${model.name}:${useOf(model, state)}。点开换别的模型`)); const act = actionOf(state); action.hidden = !act; action.replaceChildren(el('span', 'fv-iv-btn-label', act)); - if (act) tip(action, state.state === 'downloading' ? t('Pause download', '暂停下载') : state.state === 'failed' ? t('Retry download', '重新下载') : t(`Install ${model.short}`, `安装 ${model.short}`), useOf(model, state)); + if (act) tip(action, state.paused ? t('Continue download', '继续下载') : state.state === 'downloading' ? t('Pause download', '暂停下载') : state.state === 'failed' ? t('Retry download', '重新下载') : t(`Install ${model.short}`, `安装 ${model.short}`), + state.paused ? continueUse() : useOf(model, state)); bar.hidden = state.state !== 'downloading'; bar.style.setProperty('--p', String(state.fraction || 0)); if (!list.hidden) { paintList(); place(); } } diff --git a/web/settings_room.js b/web/settings_room.js index db0b93f4..418e9ef0 100644 --- a/web/settings_room.js +++ b/web/settings_room.js @@ -18,7 +18,7 @@ import { setMonitorShown, onMonitorShown } from './monitor_panel.js'; import { preloadMode, setPreloadMode, onPreload } from './preload_setting.js'; import { createUpdateNotice, releaseNotesInto, productVersion } from './updates.js'; import { createImageGenClient } from './image_generation.js'; -import { IMAGE_MODELS, modelState } from './image_view_models.js'; +import { IMAGE_MODELS, modelState, pausedText, continueUse } from './image_view_models.js'; import { swapLoraFailureText } from './swap_lora.js'; import { MODULES } from './health.js'; import { userMessage } from './user_message.js'; @@ -997,11 +997,19 @@ export async function openSetup(options) { } else if (s.state === 'downloading') { meter.hidden = false; meter.set(s.fraction); r.sub.className = 'is-accent'; - r.sub.textContent = s.paused ? t('Paused while a generation runs', '生成进行中,下载已暂停') + r.sub.textContent = s.paused ? pausedText(s) : `${Math.floor(s.fraction * 100)}% · ${gb(s.done)} / ${gb(s.total)} GiB`; - act.hidden = false; act.className = 'st-btn'; act.replaceChildren(icon('stop', 'fv-i s'), el('span', 'st-btn-t', t('Stop', '停止'))); - act.onclick = () => imageAction(id, 'cancel'); - tip(act, t('Stop', '停止'), t('Stop the download; the part downloaded is kept', '停止下载,已下载的部分会保留')); + act.hidden = false; + if (s.paused) { + // Waiting for a video or a picture: the user may go on with the download now. + act.className = 'st-btn is-fill'; act.replaceChildren(icon('down', 'fv-i s'), el('span', 'st-btn-t', t('Continue download', '继续下载'))); + act.onclick = () => imageAction(id, 'install'); + tip(act, t('Continue download', '继续下载'), continueUse()); + } else { + act.className = 'st-btn'; act.replaceChildren(icon('stop', 'fv-i s'), el('span', 'st-btn-t', t('Stop', '停止'))); + act.onclick = () => imageAction(id, 'cancel'); + tip(act, t('Stop', '停止'), t('Stop the download; the part downloaded is kept', '停止下载,已下载的部分会保留')); + } } else if (s.state === 'failed') { r.sub.className = 'is-warn'; r.sub.textContent = t(`${item.model.short} download failed${s.reason ? ': ' + s.reason.replace(/[.。]$/, '') : ''}. Retry to continue; if it keeps failing, report the problem.`, `${item.model.short} 下载失败${s.reason ? ':' + s.reason.replace(/[.。]$/, '') : ''}。请重试以继续下载;仍然失败时,请提交问题。`); act.hidden = false; act.className = 'st-btn is-fill'; act.replaceChildren(icon('retry', 'fv-i s'), el('span', 'st-btn-t', t('Retry', '重试'))); From 5683be0fdc8f30317b20021cc2894295fe101074 Mon Sep 17 00:00:00 2001 From: Bowen Xue Date: Thu, 19 Nov 2026 09:15:06 +0000 Subject: [PATCH 15/21] LoRA choice opens FreeVideo's own menu: long lists scroll, filter as you type, group by folder... LoRA choice opens FreeVideo's own menu: long lists scroll, filter as you type, group by folder, work with the keyboard in dark, light and narrow windows --- web/fv_select.js | 80 ++++++++++++++++++++++++++++++++++++----------- web/image_lora.js | 4 +-- web/lora_menu.js | 14 +++++++++ web/studio.js | 3 +- web/theme.css | 4 +++ 5 files changed, 84 insertions(+), 21 deletions(-) create mode 100644 web/lora_menu.js diff --git a/web/fv_select.js b/web/fv_select.js index e9fd27a5..4b98ade7 100644 --- a/web/fv_select.js +++ b/web/fv_select.js @@ -1,6 +1,10 @@ // The one dropdown of every page: the face of the Resolution select (raised ground, 1 px border, 8 px corners, a drawn chevron). // skinSelect puts the face on a native select, which stays the source of truth; menuSelect also opens a menu in the // editor's context-menu style, with group headings and a tick on the chosen item, in place of the system list. +// `groups` is a map (or a function) from an option's data-group to the heading above its run. `search` ({placeholder, empty}) puts a +// filter box above a long list (more than SEARCH_FROM options): typing narrows the items, Enter takes the first, Down enters the list. +import { listenDialogKey } from './dialog_keys.js'; +const SEARCH_FROM = 12; const el = (tag, cls, label) => { const e = document.createElement(tag); if (cls) e.className = cls; if (label) e.textContent = label; return e; }; export function skinSelect(select) { @@ -12,7 +16,7 @@ export function skinSelect(select) { const CHECK = ''; // `groups` maps an option's data-group to the heading above its run; an option without a group stands alone below a line. -export function menuSelect(select, {groups = {}} = {}) { +export function menuSelect(select, {groups = {}, search = null} = {}) { const wrap = skinSelect(select); wrap.classList.add('fv-select-menu-host'); select.classList.add('fv-select-native'); select.tabIndex = -1; select.setAttribute('aria-hidden', 'true'); @@ -21,7 +25,7 @@ export function menuSelect(select, {groups = {}} = {}) { const face = el('span', 'fv-select-face'); trigger.append(face); const menu = el('div', 'fv-select-menu'); menu.hidden = true; menu.setAttribute('role', 'listbox'); menu.tabIndex = -1; wrap.append(trigger, menu); - let items = []; + let items = [], box = null; const refresh = () => { const label = select.getAttribute('aria-label'); if (label) trigger.setAttribute('aria-label', label); @@ -31,28 +35,34 @@ export function menuSelect(select, {groups = {}} = {}) { const close = (restore = false) => { if (menu.hidden) return; menu.hidden = true; trigger.setAttribute('aria-expanded', 'false'); menu.replaceChildren(); items = []; + if (menu.parentNode !== wrap) wrap.append(menu); document.removeEventListener('pointerdown', outside, true); window.removeEventListener('resize', closeNow); window.removeEventListener('blur', closeNow); if (restore) trigger.focus({preventScroll: true}); }; const closeNow = () => close(); - function outside(event) { if (!wrap.contains(event.target)) close(); } + function outside(event) { if (!wrap.contains(event.target) && !menu.contains(event.target)) close(); } function choose(value) { close(true); if (select.value === value) return; select.value = value; refresh(); select.dispatchEvent(new Event('input', {bubbles: true})); select.dispatchEvent(new Event('change', {bubbles: true})); } - function open() { - if (select.disabled || !menu.hidden) return; - let previous = null, started = false; + // The options still shown for a query, with their group headings and separators. + function fill(query = '') { + for (const child of [...menu.children]) if (child !== box?.parentNode) child.remove(); + items = []; + const needle = query.trim().toLocaleLowerCase(); + let previous = null, started = false, shown = 0; for (const child of select.children) { - if (child.tagName === 'HR') { if (started) menu.append(Object.assign(el('div'), {role: 'separator'})); previous = null; continue; } + if (child.tagName === 'HR') { if (started && !needle) menu.append(Object.assign(el('div'), {role: 'separator'})); previous = null; continue; } if (child.hidden || child.disabled) continue; + if (needle && !child.textContent.toLocaleLowerCase().includes(needle)) continue; const group = child.dataset.group || ''; if (started && group !== (previous ?? group)) menu.append(Object.assign(el('div'), {role: 'separator'})); - if (group && group !== previous && groups[group]) menu.append(el('div', 'fv-select-group', groups[group])); - previous = group; started = true; + const heading = group && group !== previous ? (typeof groups === 'function' ? groups(group) : groups[group]) : ''; + if (heading) menu.append(el('div', 'fv-select-group', heading)); + previous = group; started = true; shown++; const item = el('button', 'fv-select-item'); item.type = 'button'; item.tabIndex = -1; item.setAttribute('role', 'option'); const mark = el('span', 'fv-select-mark'); mark.innerHTML = CHECK; const chosen = child.value === select.value; item.setAttribute('aria-selected', String(chosen)); @@ -62,15 +72,42 @@ export function menuSelect(select, {groups = {}} = {}) { } // Leave a separator only between two things. for (const line of [...menu.querySelectorAll('[role=separator]')]) if (!line.nextElementSibling || line.nextElementSibling.matches('[role=separator]')) line.remove(); + if (!shown && search?.empty) menu.append(el('div', 'fv-select-empty', search.empty)); + } + // Under the trigger, or above it when there is no room; a fixed menu inside a transformed or filtered ancestor is moved back to the wanted spot. + function place() { + const rect = trigger.getBoundingClientRect(), room = window.innerHeight - rect.bottom - 8; + menu.style.minWidth = `${Math.round(rect.width)}px`; + menu.style.maxHeight = `${Math.max(120, Math.max(room, rect.top - 8))}px`; + const height = menu.offsetHeight, above = height > room && room < rect.top - 8; + const wantLeft = Math.max(8, Math.min(rect.left, window.innerWidth - menu.offsetWidth - 8)); + const wantTop = Math.max(8, above ? rect.top - height - 4 : rect.bottom + 4); + menu.style.left = `${wantLeft}px`; menu.style.top = `${wantTop}px`; + const at = menu.getBoundingClientRect(); + if (Math.abs(at.left - wantLeft) > 1 || Math.abs(at.top - wantTop) > 1) { + menu.style.left = `${wantLeft - (at.left - wantLeft)}px`; menu.style.top = `${wantTop - (at.top - wantTop)}px`; + } + } + function open() { + if (select.disabled || !menu.hidden) return; + box = null; menu.replaceChildren(); + // A tray with a glass blur or its own overflow would clip a fixed menu; inside an open dialog it is shown from the dialog itself. + const dialog = wrap.closest('dialog[open]'); + if (dialog && menu.parentNode !== dialog) dialog.append(menu); + if (search && select.querySelectorAll('option').length > SEARCH_FROM) { + const holder = el('div', 'fv-select-search'); box = el('input'); box.type = 'text'; box.autocomplete = 'off'; box.spellcheck = false; + box.placeholder = search.placeholder || ''; box.setAttribute('aria-label', search.placeholder || ''); holder.append(box); menu.append(holder); + box.oninput = () => { fill(box.value); menu.scrollTop = 0; place(); }; + } + fill(); menu.hidden = false; trigger.setAttribute('aria-expanded', 'true'); - const box = trigger.getBoundingClientRect(), height = menu.offsetHeight, room = window.innerHeight - box.bottom - 8; - menu.style.minWidth = `${Math.round(box.width)}px`; - menu.style.left = `${Math.max(8, Math.min(box.left, window.innerWidth - menu.offsetWidth - 8))}px`; - menu.style.top = `${Math.max(8, height <= room || room >= box.top - 8 ? box.bottom + 4 : box.top - height - 4)}px`; - menu.style.maxHeight = `${Math.max(120, Math.max(room, box.top - 8))}px`; + place(); document.addEventListener('pointerdown', outside, true); window.addEventListener('resize', closeNow); window.addEventListener('blur', closeNow); - (items.find(item => item.getAttribute('aria-selected') === 'true') || items[0])?.focus({preventScroll: true}); + const chosen = items.find(item => item.getAttribute('aria-selected') === 'true') || items[0]; + chosen?.focus({preventScroll: true}); + chosen?.scrollIntoView({block: 'center'}); + if (box && !chosen) box.focus({preventScroll: true}); } trigger.onclick = () => menu.hidden ? open() : close(true); const keys = event => { @@ -82,14 +119,21 @@ export function menuSelect(select, {groups = {}} = {}) { event.stopPropagation(); if (event.key === 'Escape') { event.preventDefault(); close(true); } else if (event.key === 'Tab') close(); + else if (box && event.key === 'Enter' && event.target === box) { event.preventDefault(); items[0]?.click(); } + else if (box && event.target !== box && event.key.length === 1 && !event.ctrlKey && !event.metaKey && !event.altKey) box.focus({preventScroll: true}); else if (move || event.key === 'Home' || event.key === 'End') { + if (event.target === box && event.key !== 'ArrowDown' && event.key !== 'ArrowUp') return; event.preventDefault(); - const at = items.indexOf(document.activeElement); - items[event.key === 'Home' ? 0 : event.key === 'End' ? items.length - 1 : (at + move + items.length) % items.length]?.focus({preventScroll: true}); + const ring = box ? [box, ...items] : items, at = ring.indexOf(document.activeElement); + const next = event.key === 'Home' ? 0 : event.key === 'End' ? ring.length - 1 : (at + move + ring.length) % ring.length; + ring[next]?.focus({preventScroll: true}); ring[next]?.scrollIntoView({block: 'nearest'}); } }; - wrap.addEventListener('keydown', keys); + // A modal dialog takes every key at the window and hands it only to listeners registered this way. + listenDialogKey(wrap, 'keydown', keys); listenDialogKey(menu, 'keydown', keys); select.addEventListener('change', refresh); + // A row that is switched on or off sets select.disabled in place; the face follows. + new MutationObserver(() => { refresh(); if (select.disabled) close(); }).observe(select, {attributes: true, attributeFilter: ['disabled']}); refresh(); return {wrap, trigger, refresh, close}; } diff --git a/web/image_lora.js b/web/image_lora.js index 02b4a0ec..e06c89d6 100644 --- a/web/image_lora.js +++ b/web/image_lora.js @@ -3,7 +3,7 @@ // graph node to hold it) and puts trigger words into the prompt the way the video panel does. import {reconcileLoraTriggers} from './lora_triggers.js'; import {createVerdicts} from './lora_check.js'; -import {skinSelect} from './fv_select.js'; +import {loraMenu} from './lora_menu.js'; import {userMessage} from './user_message.js'; export const IMAGE_LORA_LIMIT = 8, IMAGE_LORA_STRENGTH = 2; @@ -137,7 +137,7 @@ export function createImageLoras({t, fetchApi, el = domEl, getPrompt = () => '', catch (error) { note.textContent = userMessage(error, t, t('Could not save the trigger words. Try again.', '没能保存触发词,请重试。')); } }; const check = () => verdicts.get(row.name).then(() => { if (!disposed && wrap.isConnected && select.value === row.name) { show(); drawSummary(); syncPrompt(); onChange(); } }); - wrap.append(on, skinSelect(select), strength, remove, trigger, problem); + wrap.append(on, loraMenu(select, t).wrap, strength, remove, trigger, problem); list.append(wrap); show(); if (!verdicts.peek(row.name)) check(); triggerWords(row.name).then(() => { diff --git a/web/lora_menu.js b/web/lora_menu.js new file mode 100644 index 00000000..1b94ec40 --- /dev/null +++ b/web/lora_menu.js @@ -0,0 +1,14 @@ +// The LoRA choice: our own menu (fv_select.js menuSelect) instead of the system list, which can be hundreds of files long. +// Files are grouped under their folder, the recently used ones sit on top, and a filter box narrows the list. +import {menuSelect} from './fv_select.js'; + +const folderOf = name => { const at = Math.max(name.lastIndexOf('/'), name.lastIndexOf('\\')); return at > 0 ? name.slice(0, at) : ''; }; + +export function loraMenu(select, t, pinned = []) { + const recent = new Set(pinned); + for (const option of select.options) option.dataset.group = recent.has(option.value) ? 'recent' : folderOf(option.value); + return menuSelect(select, { + groups: group => group === 'recent' ? t('Recent', '最近使用') : group, + search: {placeholder: t('Type to filter', '输入文字筛选'), empty: t('No LoRA matches', '没有匹配的 LoRA')}, + }); +} diff --git a/web/studio.js b/web/studio.js index f5975e3c..e3cd0350 100644 --- a/web/studio.js +++ b/web/studio.js @@ -18,6 +18,7 @@ import { createPortNotice } from './port_notice.js'; import { focusReportTip, hideReportTip, reportIssue, reportTipClosed, showReportTip } from './report_issue.js'; import { issueButton } from './issue_button.js'; import { skinSelect } from './fv_select.js'; +import { loraMenu } from './lora_menu.js'; import { createPreviewScene } from './preview_scene.js?v=20261115-still'; import { animateDetails, closeDialog } from './motion.js'; import { openLibrary, setDefaultUpscale, setDefaultUpscaleWork, videoThumbnailURL } from './library.js'; @@ -515,7 +516,7 @@ export function loraPanel(node, panel, {promptNode = null} = {}) { select.disabled = strength.disabled = trigger.disabled = row.enabled === false; const remove = button('×', () => { rows.splice(index, 1); write(rows); }); remove.setAttribute('aria-label', t('Remove LoRA', '移除 LoRA')); remove.dataset.fvTipName = t('Remove LoRA', '移除 LoRA'); remove.dataset.fvTipUse = t('Take it off the list; the file stays', '从列表移除,文件不删'); - wrap.append(enabled, skinSelect(select), strength, remove, trigger, strengthMark); + wrap.append(enabled, loraMenu(select, t, pinned).wrap, strength, remove, trigger, strengthMark); wrap.dataset.index = String(index); wrap.dataset.sortable = String(rows.length > 1); if (rows.length > 1) wrap.prepend(sortGrip(wrap, index)); const problem = el('div', null, 'fv-lora-problem'); problem.hidden = true; wrap.append(problem); diff --git a/web/theme.css b/web/theme.css index 7ac32d23..a9d9334d 100644 --- a/web/theme.css +++ b/web/theme.css @@ -168,3 +168,7 @@ :root[data-fv-look=stage][data-theme=light]:not([data-fv-material=glass]) :where(.fv-phone,.fv-lan,.fv-studio,.fv-setup,.fv-panel,.fv-generation-progress,.fv-view-navigation,.fv-prompt-guide,.fv-failure-dialog,.fv-reference-picker,.fv-release-notes,.fv-whatsnew,.fv-image-editor,.fv-cast-dialog,.fv-tutorial-book,.fv-feature-tour){ --fv-bg:#f4f3f1;--fv-canvas:#f4f3f1;--fv-card:#ffffff;--fv-raised:#eeedea;--fv-hover:#e5e4e0; } +/* A long menu list: a filter box stays on top while the items scroll. */ +.fv-select-search{position:sticky;top:-6px;z-index:1;margin:-6px -6px 4px;padding:6px;background:var(--fv-card)} +.fv-select-search input{box-sizing:border-box;width:100%;min-height:30px;padding:3px 8px;border:1px solid var(--fv-border);border-radius:var(--fv-r-xs);background:var(--fv-raised);color:var(--fv-ink);font:inherit} +.fv-select-empty{padding:8px 10px;color:var(--fv-muted)} From 64a87cc969284ed8ca2f620eed08c555b01d4e68 Mon Sep 17 00:00:00 2001 From: Bowen Xue Date: Thu, 19 Nov 2026 10:16:44 +0000 Subject: [PATCH 16/21] The page check lists every shipped page script, including the LoRA menu, upscale offer, user... The page check lists every shipped page script, including the LoRA menu, upscale offer, user message and workflow drafts ones. --- web/health.js | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/web/health.js b/web/health.js index fb610b63..4aacafb6 100644 --- a/web/health.js +++ b/web/health.js @@ -30,7 +30,8 @@ export const MODULES = ['audio_original.js', 'chat_data.js', 'phone_model.js', ' 'autopilot_panels.js', 'autopilot_tips.js', 'autopilot_history.js', 'a11y.js', 'topbar.js', 'view_switch_place.js', 'view_navigation_fit.js', 'editor_tips.js', 'editor_narration.js', 'editor_narration_model.js', 'editor_beats_model.js', 'empty_frame.js', 'studio_compare.js', 'image_library.js', 'fv_select.js', 'preview_style.js', 'feature_tour_layer.js', 'settings_room.js', 'settings_kit.js', 'settings_words.js', 'image_works.js', 'cast_photo.js', 'editor_opening.js', 'editor_poster.js', 'topbar_state.js', 'preload_setting.js', 'private_offers.js', 'cast_face_crop.js', 'context_fallback.js', 'studio_warm.js', - 'pose_body.js', 'pose_props.js', 'pose_stage.js', 'pose_tool.js', 'release_media.js', 'ui_speed.js']; + 'pose_body.js', 'pose_props.js', 'pose_stage.js', 'pose_tool.js', 'release_media.js', 'ui_speed.js', + 'lora_menu.js', 'upscale_offer.js', 'user_message.js', 'workflow_drafts.js']; const sleep = ms => new Promise(resolve => setTimeout(resolve, ms)); let visibleAt = 0; async function waitForVisible() { From f727e2355b3379bc2a74b64834d23a626e0cd676 Mon Sep 17 00:00:00 2001 From: Bowen Xue Date: Thu, 19 Nov 2026 10:26:46 +0000 Subject: [PATCH 17/21] Image generation: a prompt, size, seed or reference count that is out of range names itself... Image generation: a prompt, size, seed or reference count that is out of range names itself instead of reading as invalid settings, and a picture folder that is missing, read-only or occupied says so The service now names invalid_prompt, invalid_dimensions, invalid_seed and too_many_images in its answer, and turns a failed creation of the picture folder into disk_full or a new output_unwritable code, each with page copy in English and Chinese. --- freevideo_engine/image_gen/failure.py | 11 +++++++++-- freevideo_engine/image_gen/service.py | 7 ++++++- web/image_generation.js | 7 +++++++ 3 files changed, 22 insertions(+), 3 deletions(-) diff --git a/freevideo_engine/image_gen/failure.py b/freevideo_engine/image_gen/failure.py index 017798ee..697cea45 100644 --- a/freevideo_engine/image_gen/failure.py +++ b/freevideo_engine/image_gen/failure.py @@ -21,8 +21,10 @@ ERRORS = frozenset(('no_memory', 'small_memory', 'busy_video', 'busy', 'pack_missing', 'model_unavailable', 'model_unreadable', 'device_unavailable', 'worker_exit', 'timeout', 'cancelled', 'disk_full', - 'invalid_request', 'invalid_media', 'invalid_points', 'segment_not_installed', 'generation_failed')) | LORA_ERRORS -NO_REPORT = frozenset(('small_memory', 'busy', 'invalid_request', 'invalid_media', 'invalid_points', 'segment_not_installed', 'cancelled', + 'invalid_request', 'invalid_prompt', 'invalid_dimensions', 'invalid_seed', 'too_many_images', 'output_unwritable', + 'invalid_media', 'invalid_points', 'segment_not_installed', 'generation_failed')) | LORA_ERRORS +NO_REPORT = frozenset(('small_memory', 'busy', 'invalid_request', 'invalid_prompt', 'invalid_dimensions', 'invalid_seed', + 'too_many_images', 'output_unwritable', 'invalid_media', 'invalid_points', 'segment_not_installed', 'cancelled', 'disk_full')) | LORA_ERRORS STAGES = ('start', 'load', 'text', 'encode', 'denoise', 'decode') KINDS = ('generate', 'edit', 'cast', 'compose', 'download', 'install') @@ -41,6 +43,11 @@ 'disk_full': '保存图片时出错:磁盘空间不够,空出空间后再生成。', 'generation_failed': '图像生成出错了,请再试一次。', 'invalid_request': '图片设置有误,请调整后重试。', + 'invalid_prompt': '提示词为空,或加上图片引用后超过 2000 字。请缩短提示词后重试。', + 'invalid_dimensions': '图片尺寸超出所选模型支持的范围。请调整尺寸后重试。', + 'invalid_seed': '随机种子无效。请清空种子或改用较小的整数后重试。', + 'too_many_images': '参考图超过所选模型支持的数量。请减少参考图后重试。', + 'output_unwritable': '无法写入保存图片的文件夹(ComfyUI 的 input 目录下的 freevideo-image)。请确认该目录存在、可写,且没有同名文件,然后重试。', 'invalid_media': '图片无效,请重新选择输入目录中的图片。点选支持不超过 4096×4096 像素总数的图片。', 'invalid_points': '请选择 1–16 个图片范围内的点,且至少有一个选中点;1 为选中,0 为排除。', 'segment_not_installed': '点选模型未安装,请先下载点选模型(SAM 2.1 small)。', diff --git a/freevideo_engine/image_gen/service.py b/freevideo_engine/image_gen/service.py index c45b90fc..348b348a 100644 --- a/freevideo_engine/image_gen/service.py +++ b/freevideo_engine/image_gen/service.py @@ -23,6 +23,7 @@ from . import image_model, image_pack, keep, progress_model from .. import server_mode from .loras import ERRORS as LORA_ERRORS, resolve_selection +from ..disk_space import ran_out from ..download_settings import observed_speed from ..exit_diagnostics import clean_reading from ..monitoring import save @@ -591,7 +592,11 @@ def output_directory(self): output = directory / 'freevideo-image' if output.is_symlink() or output.resolve().parent != directory: raise ValueError('invalid_media') - output.mkdir(exist_ok=True) + try: + output.mkdir(exist_ok=True) + except OSError as error: + # A full disk is its own answer; a missing, read-only or occupied folder is not a wrong setting. + raise ValueError('disk_full' if ran_out(error) else 'output_unwritable') from None return output def output_path(self, named=False, suffix='.jpg'): diff --git a/web/image_generation.js b/web/image_generation.js index 72fc9b97..8d891e92 100644 --- a/web/image_generation.js +++ b/web/image_generation.js @@ -238,6 +238,13 @@ export function imageGenError(code, info, t) { disk_full: ['Saving the image failed: the disk is full. Free some space, then generate again.', '保存图片时出错:磁盘空间不够,空出空间后再生成。'], cancelled: ['Image generation was cancelled.', '已取消图像生成。'], invalid_request: ['The image settings are invalid. Adjust them and try again.', '图片设置有误,请调整后重试。'], + invalid_prompt: ['The prompt is empty, or longer than 2,000 characters once the picture references are counted. Shorten it and try again.', + '提示词为空,或加上图片引用后超过 2000 字。请缩短提示词后重试。'], + invalid_dimensions: ['The image size is outside what the chosen model supports. Change the size and try again.', '图片尺寸超出所选模型支持的范围。请调整尺寸后重试。'], + invalid_seed: ['The seed is not valid. Clear it or use a smaller whole number, then try again.', '随机种子无效。请清空种子或改用较小的整数后重试。'], + too_many_images: ['There are more reference images than the chosen model supports. Remove some and try again.', '参考图超过所选模型支持的数量。请减少参考图后重试。'], + output_unwritable: ['The folder that keeps the pictures cannot be written (freevideo-image in the ComfyUI input folder). Check that it exists, is writable and has no file of the same name, then try again.', + '无法写入保存图片的文件夹(ComfyUI 的 input 目录下的 freevideo-image)。请确认该目录存在、可写,且没有同名文件,然后重试。'], invalid_media: ['The reference image cannot be read. Choose another image.', '参考图读不出来,请换一张图。'], reload: ['Image generation was interrupted. Try again.', '图片生成中途被打断,请重试。'], engine_error: ['The image engine returned an unreadable answer. Try again; if it keeps failing, report the problem.', '图像引擎返回了无法读取的结果。请重试;仍然失败请提交问题。'], From 75464d80b6781974e83dd57f274621f6cdc7cfe5 Mon Sep 17 00:00:00 2001 From: Bowen Xue Date: Thu, 19 Nov 2026 10:46:15 +0000 Subject: [PATCH 18/21] Image generation: MOSS-Image on Windows no longer stops at the prompt-encoding step when weights... Image generation: MOSS-Image on Windows no longer stops at the prompt-encoding step when weights are streamed from disk Layer streaming now reads each layer at its file offset on platforms that lack positional vectored reads, with the same bytes and the same result as before. --- freevideo_engine/image_gen/layer_stream.py | 24 ++++++++++++++++------ 1 file changed, 18 insertions(+), 6 deletions(-) diff --git a/freevideo_engine/image_gen/layer_stream.py b/freevideo_engine/image_gen/layer_stream.py index e9022cbd..16d3beac 100644 --- a/freevideo_engine/image_gen/layer_stream.py +++ b/freevideo_engine/image_gen/layer_stream.py @@ -37,16 +37,28 @@ def locate(self, key): def read_into(path, offset, length, buffer): """Fill ``buffer`` (a contiguous uint8 tensor view) with ``length`` bytes at ``offset``.""" view = memoryview(buffer.numpy()).cast('B') - descriptor = os.open(path, os.O_RDONLY) - try: + if hasattr(os, 'preadv'): + descriptor = os.open(path, os.O_RDONLY) + try: + got = 0 + while got < length: + count = os.preadv(descriptor, [view[got:length]], offset + got) + if count <= 0: + raise EOFError('short read from %s' % path) + got += count + finally: + os.close(descriptor) + return length + # Platforms without preadv (Windows): each call opens its own unbuffered binary handle, so the reader + # threads never share a file position, and the bytes read are the same. + with open(path, 'rb', buffering=0) as handle: + handle.seek(offset) got = 0 while got < length: - count = os.preadv(descriptor, [view[got:length]], offset + got) - if count <= 0: + count = handle.readinto(view[got:length]) + if not count: raise EOFError('short read from %s' % path) got += count - finally: - os.close(descriptor) return length From 9540e63a5d95a7048bc4a4513ae55eedeb4b3f3e Mon Sep 17 00:00:00 2001 From: Bowen Xue Date: Thu, 19 Nov 2026 11:16:26 +0000 Subject: [PATCH 19/21] Editor: in a narrow window the unsaved-changes words stay inside their card Editor: in a narrow window the unsaved-changes words stay inside their card; the editor browser test follows the ready next part and the redesigned warning --- web/editor.css | 1 - 1 file changed, 1 deletion(-) diff --git a/web/editor.css b/web/editor.css index e12ab287..04139dc9 100644 --- a/web/editor.css +++ b/web/editor.css @@ -281,7 +281,6 @@ .fv-ed-name-menu{position:fixed;top:120px;left:8px} /* Beside the view switch it covered "Editor"; here it sits at the foot of the picture area, in the grid. */ .fv-ed-notice-stack{grid-column:1;grid-row:3;align-self:end;justify-self:end;margin:0 16px 8px;bottom:auto;right:auto;pointer-events:none} - .fv-ed-save-warning{position:absolute;top:60px;left:8px;right:8px;border:1px solid var(--fv-border);background:var(--fv-card);padding:8px 12px;border-radius:var(--fv-r-sm);z-index:9} } .fv-ed-name-menu{max-height:calc(100dvh - 72px);overflow-y:auto} From 620140ee16841c0bcc6080fa29c15c0f3c1a4fa2 Mon Sep 17 00:00:00 2001 From: Bowen Xue Date: Thu, 19 Nov 2026 17:55:31 +0000 Subject: [PATCH 20/21] Create panel: an empty run status takes no room in the line above the console, so a rewrite's... Create panel: an empty run status takes no room in the line above the console, so a rewrite's failure and its report key read whole --- web/glass/studio.css | 3 +++ 1 file changed, 3 insertions(+) diff --git a/web/glass/studio.css b/web/glass/studio.css index 9962894d..6e2698f9 100644 --- a/web/glass/studio.css +++ b/web/glass/studio.css @@ -173,6 +173,9 @@ overflow:hidden;font-size:var(--fv-fs-1);line-height:20px;color:var(--fv-fg3);pointer-events:none} .fvs-console-status>*{pointer-events:auto;min-width:0;margin:0!important;white-space:nowrap;overflow:hidden;text-overflow:ellipsis} .fvs-console-status>[hidden]{display:none!important} +/* The run's status takes no room in the line while it says nothing, so a note beside it (a rewrite's failure and its + report key) reads whole. */ +.fvs-console-status>.fv-status:empty{display:none!important} .fvs-console-status .fv-request-assets{display:flex;gap:var(--fv-sp-12);font-size:var(--fv-fs-1);line-height:20px} .fvs-console-status .fv-request-assets>div{overflow:hidden;text-overflow:ellipsis} .fvs-console-status :is(.fv-add-video-note,.fv-length-why){text-align:left;font-size:var(--fv-fs-1)} From 10b9dd86035adb57fcf6ba654dd18c3d1bcf8ec5 Mon Sep 17 00:00:00 2001 From: Bowen Xue Date: Thu, 19 Nov 2026 20:35:50 +0000 Subject: [PATCH 21/21] Release 0.6.5: update notes --- freevideo_engine/release_notes.json | 84 +++++++++++++++++++---------- 1 file changed, 57 insertions(+), 27 deletions(-) diff --git a/freevideo_engine/release_notes.json b/freevideo_engine/release_notes.json index 2f25c133..181b5b15 100644 --- a/freevideo_engine/release_notes.json +++ b/freevideo_engine/release_notes.json @@ -1,41 +1,71 @@ { "schema": 1, - "product_version": "0.6.4", + "product_version": "0.6.5", + "important": true, "en": { - "summary": "Fixes the error MOSS-Image could end with when making a picture; Creations can upscale a video to 4K; first and last frames can be used together with reference pictures; failures explain more; and the Edit view and the launcher have several improvements.", + "summary": "Image model downloads no longer pause while the image view only warms a model; export supports 48 and 60 fps; pictures are also saved to the output folder; LoRA choice uses FreeVideo's own menu; and face close-ups and failure messages are improved.", "changes": [ - "Images: MOSS-Image makes pictures again; in 0.6.3 it could end with an error instead; when memory is tight, H3 Image loads its model fresh instead of keeping it and then giving it back; while the engine is busy, a picture from Generate with AI in Edit image waits in line and starts once the previous job ends instead of being refused, and each retry uploads its reference pictures again.", - "Creations can upscale a finished 24 fps video by 1.5x or to 4K (3840 wide): the More menu offers it where this computer can generate that size and length, and the picture is kept while the video's own sound is used as it is.", - "Failures give the cause and next step, with the original text in the details: a reference video that cannot become depth, an unfinished assistant or Autopilot task, a failed start from the ComfyUI menu, a failed update, long-video failures, a redo or continue not starting, a delete in Creations blocked by a busy file, no permission or a full disk, and the command palette and phone connection; a failed save says Save failed with the server's words, or that the connection dropped; a narrow window shows the whole failure card; Report a problem on a failure card in the Image view looks like Retry.", - "Deletion and records are cleaner: deleting a picture for good also removes its prompt from the video prompt history, while a prompt another picture or video still uses stays; managed ComfyUI keeps no workflow drafts in the browser; and the record of finished jobs keeps only ids, short codes and times, never the error text.", - "Edit view generation bar: the frame pop-up shows the first-frame reference switch and saves it with the edit's own setting; choosing parts apart on the timeline no longer breaks the bar; on a narrow window Generate stays inside the bar instead of falling under the track toolbar; a blank edit takes the quality level chosen in the creation panel while the editor was away, and a saved edit or one with parts keeps its own.", - "Edit view timeline and panel: Ctrl+wheel zoom keeps the time under the pointer in place; with a part that is not generated yet selected, the side panel says it can be adjusted once generated; and a hidden editor no longer reads its import list every 2 seconds, reading it at once when shown again.", - "Settings improvements: a model folder that was not found is shown on one line at any width, its start giving way with an ellipsis and its last folder whole, and a copy takes the whole path; a save that fails after Settings was closed is shown as a failure notice with a way back to that setting.", - "Launcher and installation: the release-notes button under the notes in the update window wraps at the window's width; the desktop shortcut of a source installation starts the launcher directly; failures in the launcher, installation, downloads and the offline package state the cause, the next step and how to report them; and when another program holds a file that an update or a package installation needs, FreeVideo waits and installs again before reporting an error.", - "Creations and menus: Creations opened over a view keeps the keyboard after its opening fade, so Escape and the arrows work at once; the Info item of a creation's menu shows an information mark instead of the warning triangle; and the undo bar and the selection bar at the bottom of Creations are fully opaque, so thumbnails no longer show through at phone width.", - "At phone width: an attached picture's remove button in Autopilot keeps its corner size, so tapping a picture that failed to upload retries it instead of removing it; and the phone connection panel sits right below its button, aligned to its right edge and at least 8 pixels from the screen edge.", - "Tutorial improvements: after Get started on the featured example the caret is in the Autopilot box, also when the box turns on a moment after the view opens; the System status steps and pictures follow the top bar's status and its Run status panel; and the tutorial book's pictures and text follow the redesigned panels, with Edit view pictures matching the borrowed generation bar, continuing a part adding pictures from Media, and the save-frame notice naming Works.", - "First, last and middle frames work together with reference pictures and videos: one generation can use keyframes and references at the same time, and the guide and the tutorial book say so; length and time estimates count each keyframe as one canvas of the size being made." + "Image models: a download no longer pauses as if a video were generating when the image view only keeps or warms a model, a paused download says why, and Continue download starts it at once; a model folder or its files may be symbolic links (junctions on Windows) to another drive; a link that leads nowhere or to a damaged or different file says why and what to do next, and only that model fails; MOSS-Image warms up from its own files and renders normally on Windows with less than 24 GB of video memory; and when opened from ComfyUI, H3 Image allocates GPU memory as video generation does.", + "Export at 48 or 60 fps: Frame rate in the Export window now offers 48 and 60, with the frames in between made on the graphics card, cuts and still frames kept as they are and the sound copied unchanged; a full disk is reported as a full disk, and plainly too little space is said before the graphics card starts.", + "Face pictures of a character after a change of clothes: a Face picture framed too wide is redrawn larger once, a repaint that kept the old clothes is tried again, and when no face box is found the clothes are repainted inside a fixed area.", + "Pictures and seeds: each picture made or imported is also copied into the output folder as a file of its own, removed when the picture is deleted for good and switchable off in Settings; the dice next to Seed in the Image view fills in a random seed, and an empty Seed still draws a new one each time.", + "Choosing a LoRA: the LoRA choice opens FreeVideo's own menu, where a long list scrolls, typing filters it, LoRAs are grouped by folder and the keyboard works, in the dark and light themes and in narrow windows.", + "Failures say why and what to do next, continued: in the Edit view, the Image view, the Create panel, the generation progress card and notifications a failure states the cause and the next step and offers Report a problem, never a raw failure code; an engine stop, a failed model download and a video closed from its history name their reason, and a full disk during a download is named; a LoRA that stores one alpha for layers of different ranks is marked unusable before generation with the reason; an out-of-range picture setting is named.", + "Report a problem: for a known failure with a clear fix, that fix is shown first and the report can still be sent after it; the issue text the launcher fills in starts with the display adapter model for every kind of error.", + "Edit view subtitles: when the subtitle track holds only an empty line just added, Auto subtitles places the lines it heard without saying they replaced the subtitles there; when the lines there have words, the notice and its Undo are as before." ] }, "zh": { - "summary": "修复 MOSS-Image 出图报错;作品库可将视频放大到 4K,首帧、尾帧可与参考图同用,失败说明更完整,剪辑视图与启动器多项改进。", + "summary": "图像模型下载不再在预热时误停;导出支持 48 和 60 fps;图片同时保存到 output 文件夹;LoRA 选择改用 FreeVideo 自己的菜单,脸部特写与失败说明更完善。", "changes": [ - "图像:修复 0.6.3 中 MOSS-Image 出图时报错的问题;内存紧张时,H3 Image 直接重新载入模型,不再先保留、随后又释放;引擎忙时,编辑图片中的 AI 生成排队等候,前一项完成后自动开始,不再直接拒绝,每次重试都重新上传参考图。", - "已完成的 24 fps 视频可在作品库放大 1.5 倍或放大到 4K(3840 宽):本机能生成该尺寸与时长时,“更多”菜单提供这一项;画面保留,视频原有的声音照原样使用。", - "失败时说明原因和下一步(续),原文保留在详情中:仅深度参考视频无法转成深度、助手或 AI 全自动任务未完成、从 ComfyUI 菜单打开失败、更新失败、长视频失败、重做或续接未开始、作品库删除遇到文件占用、无权限或磁盘已满,以及命令面板和手机连接;保存失败写“保存失败”并接服务器原话,连接断开时直接说明;窄窗口里画面上的失败卡完整显示;图像视图失败卡上的“提交问题”与“重试”样式一致。", - "删除与记录更干净:彻底删除图片时,它的提示词也从视频提示词历史中清除;其他图片或视频仍在使用的提示词保留;受管理的 ComfyUI 不再在浏览器中保存工作流草稿;已完成任务的记录只保留编号、短代码和时间,不含错误文本。", - "剪辑视图的生成栏:帧弹层中显示首帧参考开关,并按所编辑的这一段自己的设置保存;在时间线上分开选取多段时,生成栏不再失效;窄窗下“生成”保持在栏内,不再落到轨道工具栏之下;空白的剪辑沿用离开期间创作面板所选的质量,已保存或已有分段的剪辑保留自己的质量。", - "剪辑视图的时间线与面板:Ctrl+滚轮缩放时,指针下的时间点保持不动;未生成的分段被选中时,右侧面板说明“生成后可调整”;暂时离开的剪辑视图不再每 2 秒读取导入列表,回来时立即读取。", - "设置改进:找不到的模型文件夹在任何宽度下显示为一行,开头以省略号让位、末级文件夹完整,复制时取完整路径;设置关闭后才失败的保存会以失败提示显示,并可一键回到该设置。", - "启动器与安装:更新窗口中说明下方的按钮按窗口宽度换行;源码安装的桌面快捷方式直接打开启动器;启动器、安装、下载与离线包的失败写明原因、下一步和报告方式;更新或安装软件包时遇其他程序占用文件,会等待并重新安装,再报告错误。", - "作品库与菜单:在其他视图上方打开作品库后,淡入结束即获得键盘焦点,Esc 与方向键立即可用;“作品”菜单中的“信息”项显示信息图标,不再显示警告三角;作品库底部的撤销条和“已选”操作条完全不透明,手机宽度下不再透出缩略图。", - "手机宽度的显示:AI 全自动中附加图片的移除按钮保持原有角标大小,点按上传失败的图片时是重试,而不是移除;手机连接面板在入口正下方、右边对齐,离屏幕边至少 8 像素。", - "教程改进:精选示例点“开始使用”后,光标位于 AI 全自动输入框,输入框稍后才打开时也一样;“运行状态”教程的步骤与图片跟随顶栏状态及其运行状态面板;教程书的图文跟随改版后的面板,剪辑视图的图片对应借用的生成栏,续接一段时从“素材”添加图片,保存帧的提示写明“作品库”。", - "首帧、尾帧与中间帧可与参考图、参考视频同用:同一次生成中可以同时使用关键帧和参考图、参考视频,使用说明与教程书已相应更新;长度与时间估算按每个关键帧一张同尺寸画布计算。" + "图像模型:图像视图只是预热或保留模型时,图像模型下载不再以“视频生成中”暂停,暂停时写明实际原因,可用“继续下载”立即开始;模型文件夹、其子文件夹或模型文件通过符号链接(Windows 上也可用目录联接)放在其他磁盘时照常使用,链接失效或指向损坏、不同的文件时说明原因和下一步,图片页只把该模型标为出错;MOSS-Image 预热只读取自己的模型文件,Windows 上显存小于 24 GB 时可以正常出图;由 ComfyUI 打开时,H3 Image 使用与视频生成相同的显存分配方式。", + "导出 48 或 60 fps:导出窗口的“帧率”新增 48 和 60,中间帧在显卡上补出,剪切处和静止画面保持原样,声音原样复制;磁盘写满时直接说明磁盘已满,空间明显不足时在显卡开始工作前就会提示。", + "角色更换服装后的脸部特写:脸部特写取景过宽时放大重画一次;重画后仍是原来的衣服时自动重试;识别不到脸部位置时,在固定区域内重画衣服。", + "图片保存与种子:生成或导入的图片同时复制一份到 output 文件夹,副本是独立文件,图片永久删除时一并删除,可在设置中关闭;图像视图种子旁的骰子会填入一个随机种子,留空时仍每次随机。", + "LoRA 选择:选择 LoRA 时打开 FreeVideo 自己的菜单,长列表可以滚动,输入文字即可筛选,按文件夹分组,可用键盘操作,深色、浅色主题和窄窗口下都能正常使用。", + "失败时说明原因和下一步(续):剪辑视图、图像视图、创作面板、生成进度卡片和通知中的失败都写明原因和下一步并可提交问题,不再显示原始错误代码;引擎停止、模型下载失败、从历史中关闭的视频也说明原因,下载时磁盘已满会直接说明;同一个 alpha 对应不同秩的 LoRA 在生成前即标为不可用并说明原因;图片设置超出范围时分别说明是哪一项。", + "提交问题:已知错误且已有明确建议时,先显示该建议,看完仍可继续提交;启动器预填的问题正文对各类错误都以显示适配器型号开头。", + "剪辑视图的字幕:字幕轨上只有刚添加的空字幕时,自动字幕直接写入识别结果,不再提示“识别出的字幕已替换原有字幕”;原有字幕带文字时,提示与“撤销”照旧。" ] }, "history": [ + { + "product_version": "0.6.4", + "en": { + "summary": "Fixes the error MOSS-Image could end with when making a picture; Creations can upscale a video to 4K; first and last frames can be used together with reference pictures; failures explain more; and the Edit view and the launcher have several improvements.", + "changes": [ + "Images: MOSS-Image makes pictures again; in 0.6.3 it could end with an error instead; when memory is tight, H3 Image loads its model fresh instead of keeping it and then giving it back; while the engine is busy, a picture from Generate with AI in Edit image waits in line and starts once the previous job ends instead of being refused, and each retry uploads its reference pictures again.", + "Creations can upscale a finished 24 fps video by 1.5x or to 4K (3840 wide): the More menu offers it where this computer can generate that size and length, and the picture is kept while the video's own sound is used as it is.", + "Failures give the cause and next step, with the original text in the details: a reference video that cannot become depth, an unfinished assistant or Autopilot task, a failed start from the ComfyUI menu, a failed update, long-video failures, a redo or continue not starting, a delete in Creations blocked by a busy file, no permission or a full disk, and the command palette and phone connection; a failed save says Save failed with the server's words, or that the connection dropped; a narrow window shows the whole failure card; Report a problem on a failure card in the Image view looks like Retry.", + "Deletion and records are cleaner: deleting a picture for good also removes its prompt from the video prompt history, while a prompt another picture or video still uses stays; managed ComfyUI keeps no workflow drafts in the browser; and the record of finished jobs keeps only ids, short codes and times, never the error text.", + "Edit view generation bar: the frame pop-up shows the first-frame reference switch and saves it with the edit's own setting; choosing parts apart on the timeline no longer breaks the bar; on a narrow window Generate stays inside the bar instead of falling under the track toolbar; a blank edit takes the quality level chosen in the creation panel while the editor was away, and a saved edit or one with parts keeps its own.", + "Edit view timeline and panel: Ctrl+wheel zoom keeps the time under the pointer in place; with a part that is not generated yet selected, the side panel says it can be adjusted once generated; and a hidden editor no longer reads its import list every 2 seconds, reading it at once when shown again.", + "Settings improvements: a model folder that was not found is shown on one line at any width, its start giving way with an ellipsis and its last folder whole, and a copy takes the whole path; a save that fails after Settings was closed is shown as a failure notice with a way back to that setting.", + "Launcher and installation: the release-notes button under the notes in the update window wraps at the window's width; the desktop shortcut of a source installation starts the launcher directly; failures in the launcher, installation, downloads and the offline package state the cause, the next step and how to report them; and when another program holds a file that an update or a package installation needs, FreeVideo waits and installs again before reporting an error.", + "Creations and menus: Creations opened over a view keeps the keyboard after its opening fade, so Escape and the arrows work at once; the Info item of a creation's menu shows an information mark instead of the warning triangle; and the undo bar and the selection bar at the bottom of Creations are fully opaque, so thumbnails no longer show through at phone width.", + "At phone width: an attached picture's remove button in Autopilot keeps its corner size, so tapping a picture that failed to upload retries it instead of removing it; and the phone connection panel sits right below its button, aligned to its right edge and at least 8 pixels from the screen edge.", + "Tutorial improvements: after Get started on the featured example the caret is in the Autopilot box, also when the box turns on a moment after the view opens; the System status steps and pictures follow the top bar's status and its Run status panel; and the tutorial book's pictures and text follow the redesigned panels, with Edit view pictures matching the borrowed generation bar, continuing a part adding pictures from Media, and the save-frame notice naming Works.", + "First, last and middle frames work together with reference pictures and videos: one generation can use keyframes and references at the same time, and the guide and the tutorial book say so; length and time estimates count each keyframe as one canvas of the size being made." + ] + }, + "zh": { + "summary": "修复 MOSS-Image 出图报错;作品库可将视频放大到 4K,首帧、尾帧可与参考图同用,失败说明更完整,剪辑视图与启动器多项改进。", + "changes": [ + "图像:修复 0.6.3 中 MOSS-Image 出图时报错的问题;内存紧张时,H3 Image 直接重新载入模型,不再先保留、随后又释放;引擎忙时,编辑图片中的 AI 生成排队等候,前一项完成后自动开始,不再直接拒绝,每次重试都重新上传参考图。", + "已完成的 24 fps 视频可在作品库放大 1.5 倍或放大到 4K(3840 宽):本机能生成该尺寸与时长时,“更多”菜单提供这一项;画面保留,视频原有的声音照原样使用。", + "失败时说明原因和下一步(续),原文保留在详情中:仅深度参考视频无法转成深度、助手或 AI 全自动任务未完成、从 ComfyUI 菜单打开失败、更新失败、长视频失败、重做或续接未开始、作品库删除遇到文件占用、无权限或磁盘已满,以及命令面板和手机连接;保存失败写“保存失败”并接服务器原话,连接断开时直接说明;窄窗口里画面上的失败卡完整显示;图像视图失败卡上的“提交问题”与“重试”样式一致。", + "删除与记录更干净:彻底删除图片时,它的提示词也从视频提示词历史中清除;其他图片或视频仍在使用的提示词保留;受管理的 ComfyUI 不再在浏览器中保存工作流草稿;已完成任务的记录只保留编号、短代码和时间,不含错误文本。", + "剪辑视图的生成栏:帧弹层中显示首帧参考开关,并按所编辑的这一段自己的设置保存;在时间线上分开选取多段时,生成栏不再失效;窄窗下“生成”保持在栏内,不再落到轨道工具栏之下;空白的剪辑沿用离开期间创作面板所选的质量,已保存或已有分段的剪辑保留自己的质量。", + "剪辑视图的时间线与面板:Ctrl+滚轮缩放时,指针下的时间点保持不动;未生成的分段被选中时,右侧面板说明“生成后可调整”;暂时离开的剪辑视图不再每 2 秒读取导入列表,回来时立即读取。", + "设置改进:找不到的模型文件夹在任何宽度下显示为一行,开头以省略号让位、末级文件夹完整,复制时取完整路径;设置关闭后才失败的保存会以失败提示显示,并可一键回到该设置。", + "启动器与安装:更新窗口中说明下方的按钮按窗口宽度换行;源码安装的桌面快捷方式直接打开启动器;启动器、安装、下载与离线包的失败写明原因、下一步和报告方式;更新或安装软件包时遇其他程序占用文件,会等待并重新安装,再报告错误。", + "作品库与菜单:在其他视图上方打开作品库后,淡入结束即获得键盘焦点,Esc 与方向键立即可用;“作品”菜单中的“信息”项显示信息图标,不再显示警告三角;作品库底部的撤销条和“已选”操作条完全不透明,手机宽度下不再透出缩略图。", + "手机宽度的显示:AI 全自动中附加图片的移除按钮保持原有角标大小,点按上传失败的图片时是重试,而不是移除;手机连接面板在入口正下方、右边对齐,离屏幕边至少 8 像素。", + "教程改进:精选示例点“开始使用”后,光标位于 AI 全自动输入框,输入框稍后才打开时也一样;“运行状态”教程的步骤与图片跟随顶栏状态及其运行状态面板;教程书的图文跟随改版后的面板,剪辑视图的图片对应借用的生成栏,续接一段时从“素材”添加图片,保存帧的提示写明“作品库”。", + "首帧、尾帧与中间帧可与参考图、参考视频同用:同一次生成中可以同时使用关键帧和参考图、参考视频,使用说明与教程书已相应更新;长度与时间估算按每个关键帧一张同尺寸画布计算。" + ] + } + }, { "product_version": "0.6.3", "en": {