diff --git a/THIRD_PARTY_NOTICES.md b/THIRD_PARTY_NOTICES.md index 442cb2be..01052663 100644 --- a/THIRD_PARTY_NOTICES.md +++ b/THIRD_PARTY_NOTICES.md @@ -6,6 +6,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) | | 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/__init__.py b/__init__.py index aecf6e3f..0662a8b0 100644 --- a/__init__.py +++ b/__init__.py @@ -1,7 +1,9 @@ """Optional ComfyUI custom-node entry point; the engine also runs standalone.""" from .freevideo_engine.comfy_logging import configure_managed_logging +from .freevideo_engine.comfy_privacy import configure_managed_privacy configure_managed_logging() +configure_managed_privacy() WEB_DIRECTORY = './web' diff --git "a/docs/zh-CN/\344\275\277\347\224\250\350\257\264\346\230\216.md" "b/docs/zh-CN/\344\275\277\347\224\250\350\257\264\346\230\216.md" index 9aefd83d..8b3d4243 100644 --- "a/docs/zh-CN/\344\275\277\347\224\250\350\257\264\346\230\216.md" +++ "b/docs/zh-CN/\344\275\277\347\224\250\350\257\264\346\230\216.md" @@ -32,7 +32,7 @@ | 参考 | 图里的内容出现在视频中,但不规定哪一帧 | 保持人物、物品、场景的样子 | - 首帧和尾帧可以同时使用,会按输出画幅居中裁切。 -- 首帧、尾帧暂不能与参考图、参考视频同时使用;同时给了两类,先保留其中一类。 +- 首帧、尾帧和中间帧可以与参考图、参考视频同时使用;Mac 上暂不支持,请只保留其中一类。 - 参考图保持原有比例,按输出像素面积缩小。参考视频只取与成片等长的一段,最长 15 秒,生成用时约为只用图片时的两倍。 ## 作品库和收藏 diff --git a/freevideo.ps1 b/freevideo.ps1 index 94bf99bf..38f0338c 100644 --- a/freevideo.ps1 +++ b/freevideo.ps1 @@ -158,7 +158,7 @@ try { if ($pythonReason) { $pythonDetail = " uv reported: $pythonReason." } if (-not $installed) { throw "Python installation failed (uv exit $pythonExit).$pythonDetail Check your network or connection mode in Downloads. See $bootstrapLog and retry." } $freevideoPython = (& $uv python find --managed-python $versions.python | Select-Object -Last 1).Trim() - if ($LASTEXITCODE -ne 0 -or -not (Test-Path -LiteralPath $freevideoPython)) { throw 'Managed Python could not be located.' } + if ($LASTEXITCODE -ne 0 -or -not (Test-Path -LiteralPath $freevideoPython)) { throw "Python was installed but could not be found (uv exit $LASTEXITCODE). See $bootstrapLog, then run the same command again." } } finally { if ($patientDownloadNotice -and $env:FREEVIDEO_UI_EVENTS -eq '1') { Write-Host '{"event":"freevideo_ui","kind":"progress","key":"download-patient-python","label":"Download","detail":"","state":"complete"}' @@ -177,6 +177,9 @@ try { } catch { Write-Host ("FreeVideo could not start: " + $_.Exception.Message) -ForegroundColor Red Write-Host 'Existing files are retained. Retry the same command after resolving the reported issue.' + $freevideoReportLog = '' + if ($bootstrapLog -and (Test-Path -LiteralPath $bootstrapLog)) { $freevideoReportLog = " and attach $bootstrapLog" } + Write-Host ("To report it: open a new issue at https://github.com/FlashML-org/FreeVideo/issues/new with this message" + $freevideoReportLog + '.') } finally { [Console]::OutputEncoding = $freevideoConsoleEncoding foreach ($name in $freevideoSavedEnvironment.Keys) { diff --git a/freevideo_engine/agent/schema.py b/freevideo_engine/agent/schema.py index a7db7b77..2a556d8b 100644 --- a/freevideo_engine/agent/schema.py +++ b/freevideo_engine/agent/schema.py @@ -184,17 +184,20 @@ def common(): def generation_media(*, local=False, enhance=False): properties = {'first': nullable(media(True, local=local)), 'last': nullable(media(True, local=local)), 'references': nullable(array(media(enhance, local=local, early=not enhance), high=8 if enhance else 32))} - rules = [{'if': {'required': ['references'], 'properties': {'references': {'type': 'array', 'minItems': 1}}}, - 'then': {'properties': {'first': {'type': 'null'}, 'last': {'type': 'null'}}}}] + # A video takes keyframes and references together (each keyframe becomes a still guide on its frame); + # the prompt enhancer still describes one layout. + rules = [] if not enhance else [{'if': {'required': ['references'], 'properties': {'references': {'type': 'array', 'minItems': 1}}}, + 'then': {'properties': {'first': {'type': 'null'}, 'last': {'type': 'null'}}}}] if not enhance: from ..media_request import MAX_MIDDLE properties['middle'] = nullable(array(media(True, local=local, timed=True), high=MAX_MIDDLE, description= 'Still pictures the video passes through between its first and last frame, each at a time in seconds. ' - 'Needs both first and last, and no references.')) + 'Needs both first and last; references may be given too.')) present = {'required': ['middle'], 'properties': {'middle': {'type': 'array', 'minItems': 1}}} rules.append({'if': present, 'then': {'required': ['first', 'last'], 'properties': { - 'first': {'not': {'type': 'null'}}, 'last': {'not': {'type': 'null'}}, 'references': {'type': ['null', 'array'], 'maxItems': 0}}}}) - return obj(properties, description='A first or last frame request does not take a voice reference.', allOf=rules) + 'first': {'not': {'type': 'null'}}, 'last': {'not': {'type': 'null'}}}}}) + return obj(properties, description=('First, last and middle frames may be given with references; on a Mac use one of the two.' + if not enhance else 'A first or last frame request does not take a voice reference.'), allOf=rules) def generate(*, local=False): diff --git a/freevideo_engine/bootstrap.py b/freevideo_engine/bootstrap.py index cde09614..a9ef1704 100644 --- a/freevideo_engine/bootstrap.py +++ b/freevideo_engine/bootstrap.py @@ -1814,7 +1814,7 @@ def environment(folder=venv, executable=python, label=name): elif folder.exists(): command.append('--clear') try: - return self.packages(label + '-venv', [*command, folder]) + return self.packages(label + '-venv', [*command, folder], wait_busy=False) except RuntimeError as error: # Another program (usually security software scanning the # Python file just unpacked) held it open while uv copied it. @@ -2007,11 +2007,23 @@ def notice(message): if active: self.ui.event('progress', key=key, label='Download', detail='', state='complete') - def packages(self, label, args, family='pypi'): - with self.download_notice('download-patient-' + label) as notice: - return network.package_command(self.network, family, - lambda env, source: self.command(label if source == 'official' else label + '-' + source, args, env=env), - self.env, notice=notice) + def packages(self, label, args, family='pypi', *, wait_busy=True): + from .failure_details import file_in_use + for wait in (*ENVIRONMENT_BUSY_WAITS, None): + try: + with self.download_notice('download-patient-' + label) as notice: + return network.package_command(self.network, family, + lambda env, source: self.command(label if source == 'official' else label + '-' + source, args, env=env), + self.env, notice=notice) + except RuntimeError as error: + # Security software or an indexer can hold a file uv has just + # written or is about to run (the build environment's Python). + # No other download source helps; the file is free again shortly. + if wait is None or not wait_busy or not file_in_use(error) or self.cancel.is_set(): + raise + self.ui.write('A file is in use by another program; trying again in %d s.\n' % wait) + if self.cancel.wait(wait): + raise def python_sources(self, names): """The GitHub mirror refuses the Python runtime files, so it is tried after a mirror that serves them.""" @@ -2646,13 +2658,25 @@ def progress(value): try: image_pack.install(Path(model_root), progress, engine_root=Path(engine_root)) except image_pack.PackError as error: - print('The image model was not downloaded (%s). Download it later from the launcher.' % error.reason, file=sys.stderr) + from .failure_details import IMAGE_PACK_FAILURES + reason = IMAGE_PACK_FAILURES.get(error.reason, IMAGE_PACK_FAILURES['failed'])[0] + print('The image model was not downloaded: %s The video model is ready; download the image model later from ' + 'the launcher.' % reason, file=sys.stderr) except (OSError, ValueError, RuntimeError) as error: - print('The image model was not downloaded (%s). Download it later from the launcher.' % type(error).__name__, file=sys.stderr) + print('The image model was not downloaded: %s The video model is ready; download the image model later from ' + 'the launcher.' % (str(error).strip() or type(error).__name__), file=sys.stderr) else: print('Image model ready.') +def report_hint(): + """How to report a failed command-line setup: the report command and where to send it.""" + from .launcher_issue import ISSUE_FORM + entry = '.\\freevideo.ps1 diagnose' if platform.system() == 'Windows' else './freevideo diagnose' + return ('To report it: run %s and attach the ZIP it saves to a new issue at %s\n' + '如需报告:请运行 %s,并将生成的 ZIP 附在 %s 的新问题中。' % (entry, ISSUE_FORM, entry, ISSUE_FORM)) + + def run_main(argv, shown): parser = argparse.ArgumentParser(description=__doc__) parser.add_argument('--root', type=Path, default=Path(os.environ.get('FREEVIDEO_HOME', DEFAULT_ROOT))) @@ -2786,7 +2810,9 @@ def curl_progress(message): return 1 except (OSError, ValueError) as error: prepare_end(ui, False) - print('Setup could not start: ' + str(error), file=sys.stderr) + print('Setup could not start: %s\nCheck that the installation folder exists, is writable and has free space, ' + 'then run the same command again.\n%s' % (str(error).strip() or type(error).__name__, report_hint()), + file=sys.stderr) return 1 def interrupted(signum, frame): raise KeyboardInterrupt('Setup interrupted by signal %s' % signum) @@ -2828,8 +2854,9 @@ def interrupted(signum, frame): print('\nSetup complete. Next: %s --root "%s"' % (entry, installer.root)) return 0 ui.event('failure', error=installer.state.get('resource_guard') or installer.state['error']) - print('\nSetup failed: %s\nAll files retained. Logs: %s\nRerun the same setup command to resume.' % - (installer.state.get('resource_guard') or installer.state['error'], installer.run_dir), file=sys.stderr) + print('\nSetup failed: %s\nAll files retained. Logs: %s\nRerun the same setup command to resume.\n%s' % + (installer.state.get('resource_guard') or installer.state['error'], installer.run_dir, report_hint()), + file=sys.stderr) return 1 diff --git a/freevideo_engine/capabilities.py b/freevideo_engine/capabilities.py index a0a10877..3e087737 100644 --- a/freevideo_engine/capabilities.py +++ b/freevideo_engine/capabilities.py @@ -36,6 +36,10 @@ UNAVAILABLE = {'version': 1, 'status': 'unavailable'} +# A still guide's normalized row: no picture size of its own, one canvas grid on every size row. +GUIDE = ('guide', None, None, None, None) + + def normalize_references(task, references=None): """Panel metadata, never tokens or file identities; immutable cache key. @@ -53,6 +57,12 @@ def normalize_references(task, references=None): if not isinstance(row, dict): raise ValueError('Invalid reference metadata.') kind = row.get('kind') + if kind == 'image' and row.get('guide') is True: + # A keyframe next to references: a still guide of the canvas size, counted on each size row. + if set(row) != {'kind', 'guide'}: + raise ValueError('A still guide takes the canvas size; give no width or height.') + rows.append(GUIDE) + continue allowed = {'kind', 'seconds', 'use'} if kind == 'audio' else {'kind', 'width', 'height'} if kind == 'video': allowed |= {'seconds', 'audio_seconds', 'guide'} @@ -91,6 +101,8 @@ def normalize_references(task, references=None): if seconds > MAX_SECONDS: raise AudioUseError('audio_original_long') rows.append((kind, width, height, seconds, audio) + (('original',) if use else ())) + if rows and all(row == GUIDE for row in rows): + raise ValueError('Still guides go with references; keyframes alone have their own task.') if sum(len(row) == 6 for row in rows) > 1: raise AudioUseError('audio_original_multiple') visual = any(r[0] != 'audio' for r in rows) @@ -110,8 +122,9 @@ def reference_parameters(references): """JSON form of a normalized cache key, also used in notifications.""" if references is None: return None - return [{k: v for k, v in zip(('kind', 'width', 'height', 'seconds', 'audio_seconds', 'use'), row) - if v is not None} for row in references] + return [{'kind': 'image', 'guide': True} if row == GUIDE else + {k: v for k, v in zip(('kind', 'width', 'height', 'seconds', 'audio_seconds', 'use'), row) if v is not None} + for row in references] def valid_reference_rows(value): @@ -139,6 +152,11 @@ def _material(canvas, task, references): duration = 0. limit = reference_frames(canvas) for row in references: + if row == GUIDE: + # Cropped to the canvas and encoded like a still (media_encoding.reference_load). + video_rows += patch + duration += 5. + continue kind, width, height, seconds, soundtrack = row[:5] if len(row) == 6: # Original audio occupies the existing target rows. Keep all diff --git a/freevideo_engine/chain_errors.py b/freevideo_engine/chain_errors.py new file mode 100644 index 00000000..666a9d55 --- /dev/null +++ b/freevideo_engine/chain_errors.py @@ -0,0 +1,113 @@ +"""Readable reasons for long-video (chain) failures: a code, an English and a Chinese sentence. + +The original exception text is never one of the sentences; it goes to `detail` (routes) or stays in the +record's own `error`/`output_error` field, for the technical details and the report.""" +import errno +import re + +# code: (English, Chinese). Each sentence says what happened and what to do next. +ROUTE = { + 'busy': ('This long video is busy with another action. Wait until it finishes, then try again.', + '这个长视频正在进行另一项操作。请等它完成后再试。'), + 'invalid': ('The long video request is not valid. Reload the page and try again; if it happens again, send a report.', + '长视频请求无效。请刷新页面后重试;如果再次出现,请发送诊断报告。'), + 'disk_full': ('The disk is full, so the long video could not be saved. Free up disk space and try again.', + '磁盘空间不足,长视频没能保存。请清理磁盘空间后重试。'), + 'storage_unreadable': ('FreeVideo could not read or write the long video files. Check that the FreeVideo folder ' + 'can be opened and is not read-only, then try again.', + '长视频文件读写失败。请确认 FreeVideo 文件夹可以打开且不是只读,然后重试。'), + 'unknown_chain': ('This long video was not found. Reload the page to see the current list.', + '找不到这个长视频。请刷新页面查看当前列表。'), +} +HOST_UNAVAILABLE = { + 'after': ('Extend is not available in this version. Update FreeVideo and try again.', + '当前版本不支持接着生成。请更新 FreeVideo 后重试。'), + 'other': ('Generating a new part before an existing part is not available in this version. Update FreeVideo and try again.', + '当前版本不支持在已有片段前面生成新的一段。请更新 FreeVideo 后重试。'), +} +BLOCK = { + 'generation_failed': ('This part could not be generated. Continue from this part; if it fails again, send a report.', + '这一段没能生成。请从这段继续;如果再次失败,请发送诊断报告。'), + 'disk_full': ('The disk is full, so this part could not be saved. Free up disk space, then continue from this part.', + '磁盘空间不足,这一段没能保存。请清理磁盘空间,然后从这段继续。'), + 'storage_unreadable': ('FreeVideo could not read or write the long video files, so this part did not start. ' + 'Check that the FreeVideo folder can be opened and is not read-only, then continue from this part.', + '长视频文件读写失败,这一段没能开始。请确认 FreeVideo 文件夹可以打开且不是只读,然后从这段继续。'), +} +JOIN = { + 'join_failed': ('The parts could not be joined into one video. Try again; if it fails again, send a report.', + '各段没能接合成一个视频。请重试;如果再次失败,请发送诊断报告。'), + 'disk_full': ('The disk is full, so the joined video could not be saved. Free up disk space and try again.', + '磁盘空间不足,接合后的视频没能保存。请清理磁盘空间后重试。'), +} +# The same causes when only the text of an error is left, as from a prompt that failed in the host. +DISK_FULL_TEXT = re.compile(r'no space left on device|disk quota exceeded|winerror 112\b|errno 28\b|errno 122\b' + r'|not enough space on the disk|磁盘空间不足', re.I) + + +def _causes(error): + seen = set() + while error is not None and id(error) not in seen: + seen.add(id(error)) + yield error + error = error.__cause__ or (None if error.__suppress_context__ else error.__context__) + + +def disk_full(error): + if isinstance(error, str): + return bool(DISK_FULL_TEXT.search(error)) + return any(isinstance(item, OSError) and (item.errno in (errno.ENOSPC, getattr(errno, 'EDQUOT', errno.ENOSPC)) + or getattr(item, 'winerror', None) == 112) for item in _causes(error)) + + +def storage_code(error): + """'disk_full' or 'storage_unreadable' for an OSError (or one in its causes), else None.""" + if disk_full(error): + return 'disk_full' + if any(isinstance(item, OSError) for item in _causes(error)): + return 'storage_unreadable' + return None + + +def route_body(code, detail=None, **extra): + english, chinese = ROUTE[code] + body = dict(error=english, error_zh=chinese, code=code) + if detail: + body['detail'] = str(detail)[:2000] + body.update(extra) + return body + + +def host_unavailable_body(direction): + english, chinese = HOST_UNAVAILABLE['after' if direction == 'after' else 'other'] + return dict(error=english, error_zh=chinese, code='host_unavailable') + + +def block_failure(error): + """The fields a failed part keeps next to its original `error` text: the engine's own code and sentences + when the error carries them, else disk_full, storage_unreadable or generation_failed.""" + if isinstance(error, dict): # a host status: {'error': text, 'code'?, 'error_en'?, 'error_zh'?} + code, text = error.get('code'), error.get('error') or '' + english, chinese = error.get('error_en'), error.get('error_zh') + else: + code, text = getattr(error, 'code', None), str(error) + english = getattr(error, 'message_en', None) or getattr(error, 'error_en', None) + chinese = getattr(error, 'message_zh', None) or getattr(error, 'error_zh', None) + if not english and isinstance(chinese, str): + english = text # an engine error with a Chinese sentence says its English one as its message + if not (isinstance(code, str) and re.fullmatch(r'[a-z][a-z0-9_]{0,63}', code)): + code = (storage_code(error) if not isinstance(error, dict) else None) or ( + 'disk_full' if disk_full(text) else 'generation_failed') + if not (isinstance(english, str) and english and isinstance(chinese, str) and chinese): + english, chinese = BLOCK.get(code, BLOCK['generation_failed']) + return dict(code=code, error_en=english, error_zh=chinese) + + +def join_failure(error): + code = 'disk_full' if disk_full(error) or disk_full(str(error)) else 'join_failed' + english, chinese = JOIN[code] + return dict(output_error_code=code, output_error_en=english, output_error_zh=chinese) + + +BLOCK_FIELDS = ('code', 'error_en', 'error_zh') +OUTPUT_FIELDS = ('output_error_code', 'output_error_en', 'output_error_zh') diff --git a/freevideo_engine/chain_runner.py b/freevideo_engine/chain_runner.py index 0acedeea..b707e719 100644 --- a/freevideo_engine/chain_runner.py +++ b/freevideo_engine/chain_runner.py @@ -11,6 +11,7 @@ import uuid from . import chain_leads, chain_plan +from .chain_errors import BLOCK_FIELDS, OUTPUT_FIELDS, block_failure, join_failure from . import chain_store as store REPORT_ID = re.compile(r'[a-f0-9]{32}') @@ -132,6 +133,7 @@ def __init__(self, store_dir, host, clock=time.monotonic, wall=time.time, estima # block is made again once, because the engine did not leave the record. self.checking, self.redo_lead = set(), set() self.progress_messages = {} + self.recorded = set() # chains already written to the finished-job record by this process # While a chain's parts are joined: the part being written (0 before the first) and how many there are. self.joins = {} self.estimates, self.queue, self.active = {}, [], None @@ -157,6 +159,12 @@ def _save(self, record): record['updated'] = self.wall() store.save(self.store_dir, record) self._index_receipt(record, latest=True) + if record['state'] in ('done', 'failed', 'cancelled', 'interrupted') and record['id'] not in self.recorded: + from . import job_record + # Once per chain while this process runs: the finished-job record keeps the time it first ended. + if record['state'] != 'done' or record['output_state'] not in ('pending', 'joining'): + self.recorded.add(record['id']) + job_record.chain(record, self.store_dir) def _receipts(self): if self.work_receipts is None: @@ -464,6 +472,8 @@ def resume(self, chain_id, client_id=None): seconds=None, output=None, report_id=None, error=None, fraction=0., remaining_seconds=None, continuation=None, skip_frames=0, skip_audio_samples=0) + for key in BLOCK_FIELDS: + block.pop(key, None) split = record.get('split') whole = record['snapshot']['prompt'][record['node']]['inputs'].get('text') if (split is not None and split['state'] == 'failed' and split['reason'] in ('busy', 'memory') @@ -479,6 +489,8 @@ def resume(self, chain_id, client_id=None): record['state'] = 'queued' if record['join']: record['output_error'] = None + for key in OUTPUT_FIELDS: + record.pop(key, None) if all(row['state'] == 'done' for row in record['blocks']): self._finish_blocks(record) elif record['output'] is None: @@ -517,7 +529,8 @@ def redo(self, chain_id, block_id, text=None, client_id=None): identity = source['id'] while identity in self.records or (Path(self.store_dir) / (identity + '.json')).exists(): identity = 'c-' + uuid.uuid4().hex[:12] - for key in ('last_report_id', 'last_heartbeat_at', 'output_seams', 'output_unrepaired', 'join_final_state'): + for key in ('last_report_id', 'last_heartbeat_at', 'output_seams', 'output_unrepaired', 'join_final_state', + *OUTPUT_FIELDS): record.pop(key, None) now = self.wall() record.update(id=identity, created=now, state='queued', redo_of=dict(chain=chain_id, block=block_id), @@ -536,6 +549,8 @@ def redo(self, chain_id, block_id, text=None, client_id=None): seconds=None, output=None, report_id=None, error=None, fraction=0., remaining_seconds=None, continuation=None, skip_frames=0, skip_audio_samples=0) + for key in BLOCK_FIELDS: + block.pop(key, None) if text is not None: # Only the new words take the LoRA triggers; the other parts keep their texts as written. probe = dict(node=record['node'], snapshot=deepcopy(record['snapshot']), @@ -662,6 +677,11 @@ def _find(self, prompt_id, node): return record, block return None, None + def part_of(self, prompt_id): + """True when a chain block submitted this host request, in any state: the chain is the job, not the part.""" + with self.lock: + return any(row.get('prompt_id') == prompt_id for record in self.records.values() for row in record['blocks']) + def owns(self, prompt_id): """True while a chain block submitted this host request; its order is the chain's.""" with self.lock: @@ -824,6 +844,8 @@ def _finish_blocks(self, record, final_state='done'): if not record['join']: return final_state blocks = store.leading_blocks(record) + for key in OUTPUT_FIELDS: # each path below clears output_error or keeps a done output, which has none + record.pop(key, None) if not blocks: record.update(output=None, output_blocks=0, output_state='pending', output_error=None) return final_state @@ -848,6 +870,8 @@ def _complete(self, record, block, status): block.update(state='pending', prompt_id=None, started=None, finished=None, seconds=None, output=None, report_id=None, error=None, fraction=0., remaining_seconds=None, continuation=None, skip_frames=0, skip_audio_samples=0) + for key in BLOCK_FIELDS: + block.pop(key, None) record['state'] = 'running' self.starts.pop(prompt_id, None) self.success.pop(prompt_id, None) @@ -872,6 +896,8 @@ def _complete(self, record, block, status): else: block['state'], next_state = 'failed', 'failed' block['error'] = status.get('error') or 'Prompt execution failed' + # The original text stays in `error` for the technical details and the report; these say it plainly. + block.update(block_failure(dict(status, error=block['error']))) next_state = 'cancelled' if record['state'] == 'cancelling' else next_state record['state'] = self._finish_blocks(record, next_state) if next_state in ('cancelled', 'failed') else next_state if record['state'] not in store.ACTIVE: @@ -1027,7 +1053,7 @@ def _step_chain(self, identity): self._start(block) self._save(record) elif status['state'] != 'pending': - self._complete(record, block, dict(state='error', error=str(error))) + self._complete(record, block, dict(state='error', error=str(error), **block_failure(error))) return if action == 'cancel': try: @@ -1120,7 +1146,7 @@ def lead_reader(following, previous): texts = [row['inputs']['text'] for row in snapshot['blocks']] texts += [row['inputs'].get('text') for row in snapshot['snapshot']['prompt'].values() if isinstance(row, dict) and isinstance(row.get('inputs'), dict)] - failure = None + failure = failure_fields = None promised = kept = 0 reasons, join_result = [], {} try: @@ -1138,7 +1164,7 @@ def lead_reader(following, previous): raise ValueError('Joining did not return a video path') except Exception as error: message = str(error) - failure = message[:300] + failure, failure_fields = message[:300], join_failure(error) if 'workflow' in message.lower() or any(isinstance(value, str) and value and any( part in message for part in (value, repr(value)[1:-1], json.dumps(value)[1:-1])) for value in texts): failure = 'Joining failed' @@ -1150,13 +1176,15 @@ def lead_reader(following, previous): elif cancelled(): record['state'] = self._finish_blocks(record, 'cancelled') elif failure is not None: - record.update(state=final_state, output_state='failed', output_error=failure) + record.update(state=final_state, output_state='failed', output_error=failure, **failure_fields) logging.warning('[FreeVideo] Chain joining failed: %s', identity) else: # Only the blocks the joined video is made of count, as `_work_lineage` counts them for a record without these fields. lineage, leading = self._lineage(snapshot), store.leading_blocks(snapshot) output_parts = max((lineage[row['id']][0] for row in leading), default=1) output_short = any(lineage[row['id']][1] for row in leading) + for key in OUTPUT_FIELDS: + record.pop(key, None) record.update(state=final_state, output=output, output_blocks=len(leading), output_state='done', output_error=None, output_seams=dict(expected=promised, kept=kept), output_parts=output_parts, output_short=output_short) diff --git a/freevideo_engine/chain_store.py b/freevideo_engine/chain_store.py index 7e7f5464..801f0a91 100644 --- a/freevideo_engine/chain_store.py +++ b/freevideo_engine/chain_store.py @@ -11,6 +11,7 @@ import uuid from . import chain_plan +from .chain_errors import BLOCK_FIELDS as BLOCK_ERROR_FIELDS, OUTPUT_FIELDS as OUTPUT_ERROR_FIELDS ACTIVE = ('queued', 'running', 'cancelling') CHAIN_STATES = (*ACTIVE, 'cancelled', 'failed', 'interrupted', 'done') @@ -215,6 +216,7 @@ def summary(record): output_seams=deepcopy(record.get('output_seams')), output_unrepaired=deepcopy(record.get('output_unrepaired')), split=deepcopy(record.get('split')), redo_of=deepcopy(record.get('redo_of')), + **{key: record[key] for key in OUTPUT_ERROR_FIELDS if isinstance(record.get(key), str)}, count=len(blocks), done=sum(row['state'] == 'done' for row in blocks), current=current, elapsed_seconds=sum(row['seconds'] or 0 for row in blocks if row['state'] == 'done'), last_report_id=record.get('last_report_id') or next((row['report_id'] for row in reversed(blocks) @@ -359,6 +361,11 @@ def load_all(directory, limit=200, *, identity=None, visitor=None): raise ValueError('Invalid chain output state') if any(record[key] is not None and not isinstance(record[key], str) for key in ('output', 'output_error')): raise ValueError('Invalid chain output') + # The readable failure sentences are only words for the page: a malformed one is dropped, not the chain. + for row in (record, *(row for row in record.get('blocks') or () if isinstance(row, dict))): + for key in OUTPUT_ERROR_FIELDS if row is record else BLOCK_ERROR_FIELDS: + if key in row and not isinstance(row[key], str): + row.pop(key) record.setdefault('output_blocks', len(record['blocks']) if record['output_state'] == 'done' else 0) if (type(record['output_blocks']) is not int or not 0 <= record['output_blocks'] <= len(record['blocks']) or record['output'] is None and record['output_blocks'] != 0): diff --git a/freevideo_engine/cli.py b/freevideo_engine/cli.py index ff8d76b4..cb45a889 100644 --- a/freevideo_engine/cli.py +++ b/freevideo_engine/cli.py @@ -148,6 +148,10 @@ def main(): upscale.add_argument('--refine-from', type=Path, metavar='PREVIEW.mp4', help="Upscale a finished preview: reuse its first pass, then the latent upscale, the refinement " "steps and a full-resolution decode. Use the preview's own prompt, seed, size and inputs") + upscale.add_argument('--upscale-from', type=Path, metavar='VIDEO.mp4', + help='Upscale a finished 24 fps video by 1.5x: its frames are the first pass, then the latent ' + 'upscale and three light refinement steps; its own sound is used as is. Give ' + '--width/--height at 1.5x and --upscale-factor 1.5') generate.add_argument('--out', type=Path, required=True) generate.add_argument('--width', type=int, default=1344) generate.add_argument('--height', type=int, default=768) @@ -178,6 +182,8 @@ def main(): validate_route(task=args.task or ('ref2va' if args.continue_anchor else 't2va'), anchor=args.continue_anchor is not None, two_pass=args.two_pass, preview=args.preview, refine_from=args.refine_from) + if sys.platform == 'darwin' and args.command == 'generate' and args.upscale_from is not None: + raise ValueError('Upscaling a finished video is not available on Mac yet') if sys.platform == 'darwin' and args.command in ('plan', 'generate', 'encode', 'doctor'): if args.command == 'generate': from .media_request import read diff --git a/freevideo_engine/comfy_bridge.py b/freevideo_engine/comfy_bridge.py index fbadeb70..1e2b4e8a 100644 --- a/freevideo_engine/comfy_bridge.py +++ b/freevideo_engine/comfy_bridge.py @@ -1256,10 +1256,129 @@ def without_upscale(graph, node_id, refine_from): return graph +def without_work_upscale(graph, node_id, upscale_from): + """The embedded workflow of an upscaled video names no file of this machine.""" + import copy + graph = copy.deepcopy(graph) + inputs = ((graph.get('prompt') or {}).get(str(node_id)) or {}).get('inputs') + if isinstance(inputs, dict) and 'upscale_from' in inputs: + inputs['upscale_from'] = '' + if isinstance(inputs, dict) and 'upscale_to' in inputs: + inputs['upscale_to'] = '' + for node in (graph.get('workflow') or {}).get('nodes') or []: + values = node.get('widgets_values') + if str(node.get('id')) == str(node_id) and isinstance(values, list) and values: + # Upscale video and Upscale size are the node's last two widgets (a workflow saved before the size has one). + if values[-1] == upscale_from: + values[-1] = '' + elif len(values) > 1 and values[-2] == upscale_from: + values[-2:] = ['', ''] + return graph + + def argument(arguments, flag, default=None): return arguments[arguments.index(flag) + 1] if flag in arguments else default +def upscale_frames(upscale_from, output_directory, *, source=None, environ=None, progress=None, interrupted=None, + release_models=None, comfy_metadata=None): + """A finished 24 fps video made a new work at the 4K size by frame_upscale: its own description, seed and length, + every frame enlarged by the small model, its sound copied as is. Returns the new video's path.""" + from .comfy_continuation import optional_text + from . import frame_upscale + upscale_from = optional_text(upscale_from) + video, saved = frame_upscale.work_request(output_directory, upscale_from) + width, height = frame_upscale.size(saved['geometry']['width'], saved['geometry']['height']) + source = Path(source or source_root()).resolve() + root, machine = installation(source, environ) + backend = machine.get('device_backend', 'cuda') + if backend not in ('cuda', 'mps'): + raise ValueError('Upscaling to 4K needs a graphics card') + environment = engine_environment(root, source, environ) + environment.update(FREEVIDEO_HOME=str(root), PYTHONPATH=str(source), PYTHONUNBUFFERED='1', + PYTHONUTF8='1', PYTHONIOENCODING='utf-8', NO_COLOR='1') + for key in ('FREEVIDEO_RUNTIME_LOCK_FD', 'FREEVIDEO_RUNTIME_LOCK_HANDLE'): + environment.pop(key, None) + run = Path(output_directory).resolve() / 'FreeVideo' / time.strftime('%Y-%m-%d', time.gmtime()) / uuid.uuid4().hex + run.mkdir(parents=True, exist_ok=False) + output = run / 'video.mp4' + saved_prompt = video.parent / 'prompt.txt' + (run / 'prompt.txt').write_text(saved_prompt.read_text(encoding='utf-8') if saved_prompt.is_file() else '', + encoding='utf-8') + canvas = dict(saved['geometry'], width=width, height=height) + state = {'status': 'starting', 'geometry': canvas, 'seed': saved.get('seed'), 'installation': str(root), + 'output': str(output), 'source': str(source), 'upscaled_work': str(video), 'upscale': '4k'} + try: + from server import PromptServer + prompt_id = getattr(PromptServer.instance, 'last_prompt_id', None) + if isinstance(prompt_id, str) and 0 < len(prompt_id) <= 128: + state['comfy_prompt_id'] = prompt_id + except (ImportError, AttributeError): + pass + save(run / 'comfy-request.json', state) + from .comfy_progress import REPORTS + report_id = REPORTS.register(output) + started = time.monotonic() + frames = saved['geometry'].get('frames') or 0 + label = 'Upscaling to %d × %d' % (width, height) + + def send(message): + if not progress: + return + # The download is the first twentieth, the frames the rest; the time left follows the frames done. + done, total = message.get('done'), message.get('total') + elapsed = time.monotonic() - started + fraction, remaining = 0., None + if message.get('downloading') and total: + fraction = .05 * done / total + elif message.get('unit') == 'frames' and total: + fraction = .05 + .95 * done / total + if done: + remaining = elapsed / done * (total - done) + progress(dict({key: value for key, value in message.items() if key != 'downloading'}, report_id=report_id, + label=label if message.get('unit') == 'frames' else message.get('label', label), + phase=frame_upscale.STAGE, overall=dict(status='running', estimated=True, fraction=min(fraction, .99), + remaining_seconds=remaining, elapsed_seconds=elapsed))) + + def release(): + # Only when the small model does not fit beside what other requests keep in the GPU. + if release_models: + release_models() + from .encoder_prewarm import IDLE + from .resident_process import OWNER + IDLE.stop() + OWNER.release(frame_upscale.STAGE) + try: + send({'label': label, 'done': 0, 'total': frames, 'unit': 'frames'}) + result = frame_upscale.upscale(video, output, root=root, device=backend, python=machine['python'], + environ=environment, progress=send, interrupted=interrupted, release_models=release) + if comfy_metadata: + from .comfy_metadata import embed_comfy_metadata + state['workflow_in_video'] = embed_comfy_metadata(output, **comfy_metadata) + seconds = time.monotonic() - started + canvas = dict(canvas, frames=result['frames'], seconds=result['frames'] / 24) + state.update(status='complete', geometry=canvas, request_seconds=seconds, frame_upscale=result) + save(output.with_suffix('.request.json'), dict(geometry=canvas, request_seconds=seconds, output_frames=result['frames'], + upscaled_work=str(video), frame_upscale=result, + video=dict(torch_peak_reserved_bytes=result.get('torch_peak_reserved_bytes')))) + if progress: + progress({'label': 'Video + audio saved', 'phase': 'complete', 'done': result['frames'], 'total': result['frames'], + 'unit': 'frames', 'report_id': report_id, + 'overall': dict(status='complete', fraction=1., remaining_seconds=0., elapsed_seconds=seconds)}) + return output + except BaseException as error: + cancelled = isinstance(error, KeyboardInterrupt) or type(error).__name__ in ('InterruptProcessingException', 'CancelledError') + state.update(status='cancelled' if cancelled else 'failed', error=repr(error)) + if getattr(error, 'code', None): + state['error_code'] = error.code + raise + finally: + state['bridge_seconds'] = time.monotonic() - started + save(run / 'comfy-request.json', state) + from .support_report import write as write_debug + write_debug(output, bridge=state) + + def engine_environment(root, source, environ=None): if sys.platform == 'darwin': from .macos_bootstrap import environment @@ -1274,10 +1393,16 @@ def generate(prompt, width, height, seconds, seed, output_directory, *, force_regenerate=False, base_steps=8, refine_steps=3, comfy_metadata=None, prompt_rewrite_report=None, preview=False, refine_from=None, report_extra=None, continue_from=None, frames=None, first_frame_reference=False, voice_reference=False, hide_tail=False, - step_cache=None, upscale_factor=2, allow_empty_prompt=False): + step_cache=None, upscale_factor=2, allow_empty_prompt=False, upscale_from=None, upscale_to=None): from .comfy_environment import control_process if control_process(environ): raise RuntimeError('Generation requires a dispatched executor') + if upscale_to not in (None, '', '4k'): + raise ValueError('Upscale size must be 4k') + if upscale_to: + # The 4K size: a small frame-wise model, not a generation (frame_upscale). + return upscale_frames(upscale_from, output_directory, source=source, environ=environ, progress=progress, + interrupted=interrupted, release_models=release_models, comfy_metadata=comfy_metadata) from .tiers import STEP_CACHES from .two_pass import SCALES if upscale_factor not in SCALES: @@ -1330,6 +1455,25 @@ def generate(prompt, width, height, seconds, seed, output_directory, *, if preview or upscale: # A preview stays the quick half-size first pass, and its upscale continues that same pass. upscale_factor = 2 + upscale_from = optional_text(upscale_from) + work = None + if isinstance(upscale_from, str) and upscale_from.strip(): + # A finished video made larger by one step: its own description, seed and length, + # its frames as the first pass and its own sound used as is (work_upscale). + if upscale or preview or continue_from is not None: + raise ValueError('An upscale of a finished video is a request of its own') + from .work_upscale import FACTOR, size as upscaled_size, work_request + work = work_request(output_directory, upscale_from) + saved = work[0].parent / 'prompt.txt' + prompt = saved.read_text(encoding='utf-8') if saved.is_file() else '' + allow_empty_prompt = allow_empty_prompt or not prompt.strip() + width, height = upscaled_size(work[1]['geometry']['width'], work[1]['geometry']['height']) + seconds, seed = work[1]['geometry']['seconds'], work[1]['seed'] + two_pass, upscale_factor, base_steps, refine_steps, step_cache = True, FACTOR, 8, 3, None + frames, first_frame_reference, voice_reference, hide_tail = None, False, False, False + staged = bool(preview or upscale or work) + from .refine_schedule import UPSCALE + schedule = UPSCALE if work else None from .preview import validate_flags validate_flags(preview, upscale, two_pass, base_steps) from .two_pass import validate_steps @@ -1343,7 +1487,7 @@ def generate(prompt, width, height, seconds, seed, output_directory, *, def check_ending(): from .continuation_tail import check from .two_pass import sampling_canvas - check(continue_from, sampling_canvas(canvas, staged=bool(preview or upscale))[0]) + check(continue_from, sampling_canvas(canvas, staged=staged)[0]) if step_cache == 'fbcache' and machine.get('device_backend') == 'mps': # Only the audio-video EasyCache is ported to Mac: the request samples every step, @@ -1356,7 +1500,7 @@ def check_ending(): from .two_pass import sampling_canvas # A continuation takes no media, so its sampled size is known here; the snapshot # of the previous segment was written for that canvas, not for the requested size. - started = sampling_canvas(canvas, staged=bool(preview or upscale))[0] + started = sampling_canvas(canvas, staged=staged)[0] preview_encoded = False if upscale: from .preview import continuation_snapshot, source as preview_source @@ -1451,6 +1595,8 @@ def check_ending(): state['preview'] = True if upscale: state['upscaled_preview'] = str(upscale[0]) + if work: + state['upscaled_work'] = str(work[0]) from .diagnostic_resources import encoder_prewarm as prewarm_summary state['encoder_prewarm'] = prewarm_summary(encoder_prewarm) save(run / 'comfy-request.json', state) @@ -1515,6 +1661,13 @@ def poll(): extra['media'] = json.loads(Path(argument(arguments, '--media')).read_text(encoding='utf-8')) if '--conditioning' in arguments: extra['conditioning'] = argument(arguments, '--conditioning') + elif work: + # The video's own sound, used as is: it sets the length and is copied into the result. + from .work_upscale import media as work_media, source as work_source + extra['media'] = work_media(None, work_source(work[0])) + save(run / 'media.json', extra['media']) + command += ['--media', str(run / 'media.json'), '--upscale-from', str(work[0])] + state['command'] = command elif export_inputs: send_progress({'label': 'Retaining and checking input media', 'timing_phase': 'encoding'}) extra = export_inputs(run, canvas) or {} @@ -1577,11 +1730,11 @@ def release_depth_models(): hide_tail, preview=bool(preview or upscale)) hide_tail_frames = hidden['frames'] if hidden and hidden['used'] else 0 # The engine samples this canvas; results, cache keys and labels keep the requested size. - sampled, output_size = sampling_canvas(generated_canvas, staged=bool(preview or upscale), media=extra.get('media'), + sampled, output_size = sampling_canvas(generated_canvas, staged=staged, media=extra.get('media'), conditioned=bool(extra.get('conditioning'))) planned = plan(sampled, two_pass, 'ref2va' if anchored or pictured else task_for(extra.get('media', {})), - base_steps=base_steps, refine_steps=refine_steps, staged=bool(preview or upscale), - scale=upscale_factor) + base_steps=base_steps, refine_steps=refine_steps, staged=staged, + scale=upscale_factor, schedule=schedule) if continue_from is not None: from .continuation import ADALN_TASK, ANCHOR_ADALN_TASK, MISSING, validate_snapshot, summary validate_route(task='ref2va' if anchored or pictured else task_for(extra.get('media', {})), @@ -1605,7 +1758,7 @@ def release_depth_models(): # An encoded ending carries no first frame of the film, so nothing anchors this run. anchored = False planned = plan(sampled, two_pass, task_for(extra.get('media', {})), - base_steps=base_steps, refine_steps=refine_steps, staged=bool(preview or upscale), + base_steps=base_steps, refine_steps=refine_steps, staged=staged, scale=upscale_factor) if continuation is None: from .continuation import OVERLAP_FRAMES @@ -1708,15 +1861,15 @@ def asset_progress(message): # estimate. Validate the ordinary plan and don't cache it as a hidden-tail result. # After encoding the conditioning is tied to the longer canvas, so a later refusal # fails like any other request. - sampled, output_size = sampling_canvas(canvas, staged=bool(preview or upscale), + sampled, output_size = sampling_canvas(canvas, staged=staged, media=extra.get('media'), conditioned=bool(extra.get('conditioning'))) hidden, hide_tail_frames = report['hide_tail'], 0 cache_key = None from .two_pass import steps, plan completed_steps = steps(report.get('sampling_plan')) expected_plan = plan(sampled, two_pass, report.get('profile', {}).get('engine', {}).get('task', 't2va'), - base_steps=base_steps, refine_steps=refine_steps, staged=bool(preview or upscale), - scale=upscale_factor) + base_steps=base_steps, refine_steps=refine_steps, staged=staged, + scale=upscale_factor, schedule=schedule) shown = sampled if preview: # A preview decodes its first pass at the planned smaller canvas. @@ -1728,6 +1881,7 @@ def asset_progress(message): or engine.get('sampling_plan') != report.get('sampling_plan') or report.get('sampling_plan') != expected_plan or bool(report.get('preview')) != preview or bool(report.get('upscaled_preview')) != bool(upscale) + or bool(report.get('upscaled_work')) != bool(work) or (hide_tail and report.get('hide_tail') != hidden) or any(engine.get('geometry', {}).get(k) != shown[k] for k in ('width', 'height', 'frames')) or (report.get('output_size') or None) != output_size): diff --git a/freevideo_engine/comfy_chain.py b/freevideo_engine/comfy_chain.py index 51874eee..5d285243 100644 --- a/freevideo_engine/comfy_chain.py +++ b/freevideo_engine/comfy_chain.py @@ -12,6 +12,7 @@ from .chain_runner import ChainBusy, ChainPartTooShort, ChainRunner, ChainTooLong from . import chain_plan, chain_store +from .chain_errors import host_unavailable_body, route_body, storage_code RUNNER = None CONTINUE_INPUTS = {'after': 'continue_from', 'before': 'continue_to'} @@ -451,6 +452,34 @@ async def plan(request): except ValueError as failure: return response({'error': str(failure), 'code': 'invalid'}, 400) + def refused(failure, invalid_status=400): + """Every refusal of a chain route as JSON: a code, an English and a Chinese sentence, and the original text + only in `detail` (technical details and reports). Codes the engine already gives are kept as they are.""" + if isinstance(failure, KeyError): + return response(route_body('unknown_chain', 'Unknown chain or part: %s' % failure), 404) + if isinstance(failure, OSError): + code = storage_code(failure) + logging.warning('[FreeVideo] Long video storage failed (%s): %s', code, failure) + return response(route_body(code, '%s: %s' % (type(failure).__name__, failure)), 507 if code == 'disk_full' else 500) + if isinstance(failure, ChainBusy): + return response(route_body('busy', str(failure)), 409) + if isinstance(failure, ChainTooLong): + return response({'error': str(failure), 'error_zh': failure.message_zh, 'code': failure.code, + 'parts': failure.parts, 'max_parts': failure.limit}, 400) + if isinstance(failure, ChainPartTooShort): + return response({'error': str(failure), 'error_zh': failure.message_zh, 'code': failure.code, + 'min_seconds': failure.limit}, 400) + if isinstance(failure, chain_plan.PlanError): + return response({'error': str(failure), 'code': failure.code}, 400) + if hasattr(failure, 'as_dict'): + value = failure.as_dict() + if isinstance(value.get('message_zh'), str): + value.setdefault('error_zh', value['message_zh']) + return response({'error': str(failure), **value}, 400) + return response(route_body('invalid', str(failure)), invalid_status) + + STORED = (KeyError, ValueError, OSError) + @server.routes.post('/freevideo/chain/lineage') async def lineage(request): try: @@ -466,8 +495,8 @@ async def lineage(request): parts, short, known = runner.work_lineage(work['work']) result.append(dict(parts=parts, short=short, known=known)) return response({'lineage': result}) - except ValueError as failure: - return response({'error': str(failure)}, 400) + except (ValueError, OSError) as failure: + return refused(failure) @server.routes.post('/freevideo/chain') async def create(request): @@ -482,23 +511,11 @@ async def create(request): if not fake and os.environ.get('FREEVIDEO_CHAIN_INDEPENDENT') != '1': missing = {key for row in normalized['blocks'] for key in CONTINUE_INPUTS if row[key] is not None} - continuation_directions() - if 'after' in missing: - return response({'error': 'Continuing a video is not available in this version'}, 409) if missing: - return response({'error': 'Extending backwards or filling a gap is not available in this version'}, 409) + return response(host_unavailable_body('after' if 'after' in missing else 'other'), 409) return response({'chain': await asyncio.to_thread(runner.create, value)}) - except ChainBusy as failure: - return response({'error': str(failure)}, 409) - except ChainTooLong as failure: - return response({'error': str(failure), 'error_zh': failure.message_zh, 'code': failure.code, - 'parts': failure.parts, 'max_parts': failure.limit}, 400) - except ChainPartTooShort as failure: - return response({'error': str(failure), 'error_zh': failure.message_zh, 'code': failure.code, - 'min_seconds': failure.limit}, 400) - except chain_plan.PlanError as failure: - return response({'error': str(failure), 'code': failure.code}, 400) - except ValueError as failure: - return response({'error': str(failure), **(failure.as_dict() if hasattr(failure, 'as_dict') else {})}, 400) + except (ValueError, OSError) as failure: + return refused(failure) def asking(request): # ?client_id=... marks each chain as this page's own or not. @@ -517,15 +534,15 @@ async def listing(request): async def get(request): try: return response({'chain': runner.get(request.match_info['id'], asking(request))}) - except KeyError: - return response({'error': 'Unknown chain'}, 404) + except KeyError as failure: + return refused(failure) @server.routes.post('/freevideo/chain/{id}/cancel') async def cancel(request): try: return response({'chain': runner.cancel(request.match_info['id'])}) - except KeyError: - return response({'error': 'Unknown chain'}, 404) + except (KeyError, OSError) as failure: + return refused(failure) @server.routes.post('/freevideo/chain/{id}/blocks/{block}/text') async def text(request): @@ -533,12 +550,8 @@ async def text(request): value = await body(request) return response({'chain': runner.set_text(request.match_info['id'], request.match_info['block'], value.get('text') if isinstance(value, dict) else None)}) - except KeyError: - return response({'error': 'Unknown chain or part'}, 404) - except ChainBusy as failure: - return response({'error': str(failure)}, 409) - except ValueError as failure: - return response({'error': str(failure)}, 400) + except STORED as failure: + return refused(failure) @server.routes.post('/freevideo/chain/{id}/blocks/{block}/redo') async def redo(request): @@ -550,28 +563,17 @@ async def redo(request): missing = {key for row in runner.get(identity)['blocks'] for key in CONTINUE_INPUTS if row[key] is not None} - continuation_directions() if missing: - return response({'error': 'Continuing a video is not available in this version'}, 409) + return response(host_unavailable_body('after'), 409) return response({'chain': await asyncio.to_thread(runner.redo, identity, block, value.get('text'), value.get('client_id'))}) - except KeyError: - return response({'error': 'Unknown chain or part'}, 404) - except ChainBusy as failure: - return response({'error': str(failure)}, 409) - except ChainTooLong as failure: - return response({'error': str(failure), 'error_zh': failure.message_zh, 'code': failure.code, - 'parts': failure.parts, 'max_parts': failure.limit}, 400) - except ChainPartTooShort as failure: - return response({'error': str(failure), 'error_zh': failure.message_zh, 'code': failure.code, - 'min_seconds': failure.limit}, 400) - except ValueError as failure: - return response({'error': str(failure)}, 400) + except STORED as failure: + return refused(failure) @server.routes.post('/freevideo/chain/{id}/resume') async def resume(request): try: value = await body(request) if request.can_read_body else {} return response({'chain': runner.resume(request.match_info['id'], value.get('client_id'))}) - except KeyError: - return response({'error': 'Unknown chain'}, 404) - except ValueError as failure: - return response({'error': str(failure)}, 409) + except STORED as failure: + # A chain that cannot be resumed was answered 409, as a conflict with its state; it still is. + return refused(failure, invalid_status=409) diff --git a/freevideo_engine/comfy_front.py b/freevideo_engine/comfy_front.py index f042659f..a6adcfc4 100644 --- a/freevideo_engine/comfy_front.py +++ b/freevideo_engine/comfy_front.py @@ -284,6 +284,7 @@ def _finish(self, row, kind, detail): messages=[[kind, dict(detail, prompt_id=row.task.id)]]), freevideo_dispatch=self.receipt(row)) self.scheduler.finished(row.task.id, False) + self._record(row) if kind == 'execution_error': # No executor will report this failure, so the page hears it from here. node = next((key for key, value in row.prompt.items() if value.get('class_type') == 'FreeVideoGenerate'), None) @@ -321,6 +322,7 @@ def cancel(self, prompt_id, node=None): status=dict(status_str='error', completed=False, messages=[['execution_interrupted', {'prompt_id': prompt_id}]]), freevideo_dispatch=self.receipt(row)) + self._background_record(row) elif state == 'running': row.state, row.cancelled = 'cancelling', True if row.worker_prompt_id is not None: @@ -546,6 +548,7 @@ async def _poll(self, row): with self.lock: row.result, row.state = result, 'finished' self.scheduler.finished(row.task.id, status.get('status_str') == 'success') + self._record(row) self.updated() def _event_row(self, worker, data): @@ -607,6 +610,38 @@ def event(self, worker, event): else: self.server.send_sync(kind, data, row.task.client_id or None) + def _record(self, row): + """The finished-job record for a creation-panel video run on a worker; a long video's parts are left to + their chain, which is recorded once.""" + try: + from .comfy_chain import RUNNER + if RUNNER is not None and RUNNER.part_of(row.task.id): + return + from . import job_record + result = row.result or {} + status = result.get('status') or {} + kinds = [m[0] for m in status.get('messages') or () if isinstance(m, (list, tuple)) and m] + video = None + for output in (result.get('outputs') or {}).values(): + summary = ((output or {}).get('freevideo_summary') or [None])[0] if isinstance(output, dict) else None + if isinstance(summary, dict) and summary.get('video'): + video = summary['video'] + if status.get('status_str') == 'success': + state, failure = 'done', None + elif 'execution_interrupted' in kinds or row.cancelled: + state, failure = 'cancelled', None + else: + state, failure = 'failed', kinds[-1] if kinds and isinstance(kinds[-1], str) else 'execution_error' + client = str(getattr(row.task, 'client_id', '') or '') + job_record.ended(row.task.id, 'video', state, origin='agent' if client.startswith('agent:') else 'page', + result=job_record.library_id(video) if state == 'done' else None, failure=failure) + except Exception: + logging.getLogger(__name__).warning('A finished run could not be recorded.', exc_info=True) + + def _background_record(self, row): + # Called under the front's lock: the record file is written off it. + threading.Thread(target=self._record, args=(row,), daemon=True, name='freevideo-job-record').start() + def _chain_finished(self, row, node, data): if row.chain_notified: return diff --git a/freevideo_engine/comfy_launcher.py b/freevideo_engine/comfy_launcher.py index c571c708..a4d861d5 100644 --- a/freevideo_engine/comfy_launcher.py +++ b/freevideo_engine/comfy_launcher.py @@ -1,921 +1,4 @@ -"""Small native launcher: choose ComfyUI, prepare FreeVideo, open its workflow.""" -import json -import locale -import os -from pathlib import Path -import sys -import time -import traceback -import webbrowser -from urllib.parse import parse_qsl, urlencode, urlsplit, urlunsplit - -from .long_paths import io_path, resolved, plain, plain_text, plain_errors -from . import __version__ -from . import branding -from .comfy_launcher_runtime import Controller -from .desktop_runtime import launcher_root, materialize_source -from .monitoring import save -from .terminal_ui import clean, duration -from .setup_progress import number, progress_text - - -FIREWALL_HINT = ('Windows will ask for permission. Check "Private networks", then click "Allow access".', 'Windows 会弹出确认框,请勾选“专用网络”,再点“允许访问”。') -BROWSER_STARTING = ('Still starting. Your browser will open automatically when ready.', '还在启动,好了会自动打开') - - -class Launcher: - def __init__(self, window, source=None, controller=None, update_client=None): - import tkinter as tk - from tkinter import ttk - self.tk, self.ttk, self.window = tk, ttk, window - self.source = Path(source or materialize_source()) - self.controller = controller or Controller(self.source) - from .launcher_settings import Store - self.settings_store = Store(launcher_root(), documents=launcher_root() / 'smoke-documents' if '--smoke-test' in sys.argv else None) - self.settings_path = self.settings_store.primary - settings = self.settings_store.read() - self.zh = settings.get('language', (locale.getlocale()[0] or '').lower()).startswith('zh') - self.comfy = tk.StringVar(value=settings.get('comfy', '')) - self.mode = tk.StringVar(value='new' if settings.get('new_comfy', not bool(settings.get('comfy'))) else 'existing') - default_folder = Path(os.environ.get('USERPROFILE') or os.environ.get('HOME') or launcher_root().parent) / 'FreeVideo' - self.destination = tk.StringVar(value=settings.get('destination', str(default_folder))) - self.engine = tk.StringVar(value=os.environ.get('FREEVIDEO_HOME') or settings.get('engine', '')) - self.model_dirs = settings.get('model_dirs', []) - if not isinstance(self.model_dirs, list) or any(not isinstance(v, str) for v in self.model_dirs): - self.model_dirs = [] - if isinstance(settings.get('models'), str) and settings['models'].strip(): - self.model_dirs = list(dict.fromkeys(self.model_dirs + [settings['models']])) - self.models = tk.StringVar() # Legacy callers can still provide one folder. - self.model_method = tk.StringVar(value=settings.get('model_method', 'reuse' if self.model_dirs else 'auto')) - self.wizard_step = 0 - self.launch_selection = settings.get('installation') - self.save_timer = None - self.loading_settings = False - self.saved_setup = settings.get('setup', {}) - self.last_model_groups = [] - self.error_text = '' - self.python = tk.StringVar(value=settings.get('python', '')) - self.url = tk.StringVar(value=settings.get('url', 'http://127.0.0.1:8188')) - self.lan_access = tk.BooleanVar(value=settings.get('lan_access', False)) - self.lan_message = tk.StringVar() - self.access_link = tk.StringVar() - self.token = tk.StringVar() # Never stored in settings, commands or receipts. - self.separate = tk.BooleanVar(value=settings.get('separate', False)) - self.repair, self.accept = tk.BooleanVar(), tk.BooleanVar() - self.status = tk.StringVar() - self.details = tk.StringVar() - self.meta = tk.StringVar() - self.phase = tk.StringVar() - self.overall_text = tk.StringVar() - self.current_text = tk.StringVar() - self.folder_label, self.folder_hint = tk.StringVar(), tk.StringVar() - self.last_state = None - self.opened = False - self.browser_attempted = False - self.browser_error = '' - self.browser_address = tk.StringVar() - self.closing = False - self.started = None - self.labels = [] - self.terminal_operation = None - self.options = None - self.options_inputs = [] - self.listen_entry = None - self.download_dialog = None - self.download_probes = {} - if self.controller.restore(dict(settings, engine=self.engine.get())): - self.launch_selection = dict(self.controller.selection) - self.wizard_step = 3 - elif self.saved_setup.get('action') == 'install' and self.saved_setup.get('status') in ('running', 'failed', 'cancelled'): - self.wizard_step = 2 - self.controller.state = dict(status='cancelled') - from .launcher_view import build - build(self) - self.updates = None - if update_client is None and '--smoke-test' not in sys.argv: - from .launcher_update import current_build, UpdateClient - identity = current_build() - if identity: - update_client = UpdateClient(identity, launcher_root(), language='zh' if self.zh else 'en') - if update_client is not None: - from .launcher_update_ui import UpdateUI - self.updates = UpdateUI(self, update_client, self.update_row) - for variable in (self.mode, self.destination, self.comfy, self.engine, self.models, self.model_method, self.python, self.url, self.lan_access, self.token, self.separate, self.repair): - variable.trace_add('write', self.changed) - window.protocol('WM_DELETE_WINDOW', self.close) - window.bind('', self.cancel_timers, add='+') - window.report_callback_exception = self.callback_error - window.bind('', lambda _: self.act() if 'disabled' not in self.primary.state() else None) - self.refresh() - self.poll_timer = window.after(120, self.poll) - self.update_timer = None - if self.updates: - self.update_timer = window.after(300, self.updates.start) - self.compatibility_timer = window.after(500, self.compatibility_notice) - self.reported_setup = None - - def t(self, en, zh): - return zh if self.zh else en - - def label(self, parent, en, zh, **kwargs): - widget = self.ttk.Label(parent, text=self.t(en, zh), **kwargs) - self.labels.append((widget, en, zh)) - return widget - - def button(self, parent, en, zh, command): - widget = self.ttk.Button(parent, text=self.t(en, zh), command=command) - self.labels.append((widget, en, zh)) - return widget - - def language(self): - from .launcher_copy import follow_language - self.zh = not self.zh - self.browser_error = follow_language(self.browser_error, self.zh) - for widget, en, zh in self.labels: - if widget.winfo_exists(): - widget.configure(text=self.t(en, zh)) - self.refresh() - self.queue_save() - - def values(self): - return dict({name: getattr(self, name).get() for name in ('comfy', 'destination', 'engine', 'models', 'python', 'url', 'lan_access', 'token', 'separate', 'repair')}, - new_comfy=self.mode.get() == 'new', model_dirs=list(self.model_dirs), model_method=self.model_method.get()) - - def model_download_link(self, component): - from .model_guidance import show_component - show_component(self, component) - - def select_model_source(self, _=None): - from .download_settings import CHOICES, preference - try: - root = self.compatibility_root() - if root is None: - return - preference(root, CHOICES[self.model_source.current()]) - self.model_source_status.configure(text=self.t('Saved. You can change sources during download too.', '已保存,下载过程中也可切换。')) - except (OSError, ValueError) as error: - self.model_source_status.configure(text=str(error)) - - def refresh_model_choices(self): - from .download_settings import CHOICES, read - method = self.model_method.get() - instructions = { - 'auto': ('FreeVideo selects compatible models, reuses matches in ComfyUI and downloads only missing files.', - '自动选择适配模型、复用 ComfyUI 内已有模型,只下载缺少的部分。'), - 'manual': ('Choose a component below to open its download links. After downloading, extract ZIP files and select their folder.', - '点击下方组件获取下载链接。下载完成后先解压 ZIP,再选择模型文件夹。'), - 'reuse': ('Choose your model folders. Subfolders are scanned automatically; the next page shows what is reusable and what is still missing.', - '选择已有模型的总目录,会自动扫描子文件夹。下一页会列出可复用和仍缺少的组件。'), - } - self.model_help.configure(text=self.t(*instructions[method])) - if method == 'auto': - self.model_source_row.pack(fill='x', pady=(8, 0), before=self.model_components) - else: - self.model_source_row.pack_forget() - if method == 'reuse': - self.model_library.pack(fill='x', pady=(12, 0)) - self.model_reuse_button.pack_forget() - else: - self.model_library.pack_forget() - self.model_reuse_button.configure(text=self.t('Downloaded / already have models · choose folders…', '已下载或已有模型,选择文件夹…')) - self.model_reuse_button.pack(fill='x', pady=(12, 0)) - self.model_source.configure(values=(self.t('Automatic', '自动选择'), 'Hugging Face', 'HF Mirror', 'ModelScope')) - try: - root = self.compatibility_root() - self.model_source.current(CHOICES.index(read(root / 'download-settings.json')['source']) if root else 0) - except (OSError, ValueError): - self.model_source.current(0) - for widget in self.model_method_buttons: - widget.state(['disabled'] if self.controller.busy else ['!disabled']) - - def selected_folder(self): - return self.destination if self.mode.get() == 'new' else self.comfy - - def changed(self, *_): - if self.loading_settings: - return - self.queue_save() - if self.launch_selection and _ and _[0] in (str(self.url), str(self.lan_access)): - return # Apply a valid listening change after the saved draft settles. - if self.controller.busy: - return - self.controller.selection = None - self.controller.state = dict(status='idle') - self.accept.set(False) - self.reset_browser() - self.last_model_groups = [] - if self.wizard_step == 2: - self.wizard_step = 1 - elif self.wizard_step == 3: - self.wizard_step = 0 - self.refresh() - - def browse(self, variable, file=False): - from tkinter import filedialog - parent = self.options if self.options and self.options.winfo_exists() else self.window - path = (filedialog.askopenfilename if file else filedialog.askdirectory)(parent=parent) - if path: - variable.set(path) - - def show_options(self): - if self.options and self.options.winfo_exists(): - self.options.lift(); return - dialog = self.tk.Toplevel(self.window); self.options = dialog - dialog.title(self.t('FreeVideo · Options', 'FreeVideo · 选项')) - dialog.transient(self.window) - dialog.geometry('640x620'); dialog.minsize(580, 560) - body = self.ttk.Frame(dialog, padding=24); body.pack(fill='both', expand=True) - self.options_inputs = [] - fixed_environment = getattr(self.controller, 'fixed_environment', False) - for name, en, zh in ( - ('engine', 'Engine folder (blank = automatic)', '引擎目录(留空自动选择)'), - ('python', 'ComfyUI Python (auto-detected when blank)', 'ComfyUI Python(留空自动检测)'), - ('url', 'ComfyUI address', 'ComfyUI 地址')): - if fixed_environment and name != 'url': - continue - self.label(body, en, zh).pack(anchor='w', pady=(0, 4)) - row = self.ttk.Frame(body); row.pack(fill='x', pady=(0, 10)) - entry = self.ttk.Entry(row, textvariable=getattr(self, name), show='•' if name == 'token' else '') - entry.pack(side='left', fill='x', expand=True) - self.options_inputs.append(entry) - if name in ('engine', 'models', 'python'): - browse = self.button(row, '…', '…', lambda n=name: self.browse(getattr(self, n), n == 'python')) - browse.pack(side='right', padx=(6, 0)); self.options_inputs.append(browse) - if name == 'url': - self.listen_entry = entry - self.label(body, "With 0.0.0.0 or this computer's LAN IP, devices on the same network can open FreeVideo without the access link.", - '填 0.0.0.0 或本机的局域网 IP 后,同一网络中的设备不需要访问链接就能打开 FreeVideo。', - style='Muted.TLabel', wraplength=580).pack(fill='x') - if sys.platform == 'win32': - self.label(body, FIREWALL_HINT[0], FIREWALL_HINT[1], style='Muted.TLabel', wraplength=580).pack(fill='x') - for variable, en, zh in ( - (self.lan_access, 'LAN access', '局域网访问'), - (self.separate, 'Use a separate ComfyUI environment', '使用独立 ComfyUI 环境'), - (self.repair, 'Repair the engine environment', '修复引擎环境')): - if fixed_environment and variable is not self.lan_access: - continue - check = self.ttk.Checkbutton(body, variable=variable, text=self.t(en, zh)) - self.labels.append((check, en, zh)); check.pack(anchor='w', pady=(3, 3)) - self.options_inputs.append(check) - if variable is self.lan_access: - self.ttk.Label(body, textvariable=self.lan_message, style='Muted.TLabel').pack(fill='x') - self.label(body, 'When on, other devices on the same network can open FreeVideo with the link below. Anyone with the link can use it, so keep it private.', - '开启后,同一网络中的其他设备可以用下面的链接打开 FreeVideo。拿到链接的人都能使用,请勿公开。', - style='Muted.TLabel', wraplength=580).pack(fill='x') - if sys.platform == 'win32': - self.label(body, FIREWALL_HINT[0], FIREWALL_HINT[1], style='Muted.TLabel', wraplength=580).pack(fill='x') - self.ttk.Entry(body, textvariable=self.access_link, state='readonly').pack(fill='x', pady=(8, 0)) - self.button(body, 'Copy link', '复制链接', self.copy_access_link).pack(anchor='w') - self.button(body, 'Done', '完成', dialog.destroy).pack(side='bottom', anchor='e', pady=(10, 0)) - compatibility = self.button(body, 'Compatibility settings', '兼容性设置', self.compatibility_settings) - compatibility.pack(side='bottom', anchor='w'); self.options_inputs.append(compatibility) - self.button(body, 'Download sources', '下载源', self.download_settings).pack(side='bottom', anchor='w') - self.label(body, 'Saved settings: ', '设置保存位置:', style='Muted.TLabel').pack(anchor='w', pady=(8, 0)) - self.ttk.Label(body, text=str(self.settings_path), style='Muted.TLabel', wraplength=580).pack(fill='x') - for widget in self.options_inputs: - widget.state(['disabled'] if self.controller.busy else ['!disabled']) - - @plain_errors - def download_settings(self): - from .download_settings import Probe - from .download_settings_ui import DownloadSettings - from tkinter import messagebox - try: - selected = self.controller.selection - root = Path(selected['engine']) if selected else self.compatibility_root() - if root is None: - raise ValueError(self.t('Choose the installation folder first.', '请先选择安装位置。')) - root = Path(plain(resolved(root))) - old = self.download_dialog - if old and old.window.winfo_exists(): - if old.root == root: - old.window.lift(); return - old.window.destroy() - probe = self.download_probes.setdefault(root, Probe()) - self.download_dialog = DownloadSettings(self.window, root, self.zh, probe, - token=self.token, busy=lambda: self.controller.busy) - except (OSError, ValueError) as error: - messagebox.showerror('FreeVideo', plain_text(error), parent=self.window) - - def compatibility_root(self): - if self.engine.get().strip(): - return Path(self.engine.get()).expanduser() - if self.mode.get() == 'new': - return Path(self.destination.get())/'FreeVideo-engine' if self.destination.get().strip() else None - from .comfy_launcher_runtime import layout - if self.comfy.get().strip(): - return Path(layout(self.comfy.get())['root'])/'FreeVideo-engine' - return None - - def compatibility_notice(self): - from .compatibility_ui import notify - try: - root = self.compatibility_root() - except (OSError, ValueError): - return - if root is not None: - notify(self.window, root, self.zh) - - def compatibility_settings(self): - from .compatibility_ui import open_settings - from tkinter import messagebox - try: - root = self.compatibility_root() - if root is None or not (io_path(root)/'machine.json').is_file(): - raise ValueError(self.t('Choose an installed FreeVideo engine first.', '请先选择已安装的 FreeVideo 引擎。')) - open_settings(self.window, root, self.zh) - except (OSError, ValueError) as error: - messagebox.showerror('FreeVideo', plain_text(error), parent=self.window) - - @plain_errors - def save_settings(self): - if self.save_timer is not None: - self.window.after_cancel(self.save_timer) - self.save_timer = None - row = self.controller.state - if self.launch_selection and self.mode.get() == 'existing': - selected = self.launch_selection - if (self.comfy.get() == selected.get('root') and self.engine.get() == selected.get('engine')): - from .comfy_launcher_runtime import local_url - try: - selected['url'] = local_url(self.url.get()) - selected['lan_access'] = self.lan_access.get() - if self.python.get() and io_path(self.python.get()).is_file(): - selected['python'] = self.python.get() - except ValueError: - pass # Keep an editable draft without breaking the saved launcher. - if row.get('action') == 'install': - self.saved_setup = dict(status=row.get('status', ''), action='install', - phase=row.get('overall', {}).get('label', '')) - written, failures = self.settings_store.write(self.values(), 'zh' if self.zh else 'en', - self.launch_selection, self.saved_setup) - self.settings_path = written[0] - if (self.launch_selection and row.get('status') == 'open' and not self.controller.busy - and self.launch_selection != self.controller.selection): - if self.launch_selection['url'] != self.controller.selection['url']: - self.browser_attempted = False - self.controller.run('configure_access', dict(url=self.launch_selection['url'], - lan_access=self.launch_selection.get('lan_access') is True)) - - def queue_save(self): - if self.save_timer is not None: - self.window.after_cancel(self.save_timer) - self.save_timer = self.window.after(200, self.persist_settings) - - def persist_settings(self): - try: - self.save_settings() - except (OSError, ValueError) as error: - self.callback_error(type(error), error, error.__traceback__) - - def remember_installation(self, selection): - if not selection or not selection.get('ready'): - return - self.launch_selection = dict(selection) - self.loading_settings = True - try: - for name, key in (('comfy', 'root'), ('engine', 'engine'), ('python', 'python'), ('url', 'url')): - getattr(self, name).set(selection.get(key) or '') - self.mode.set('existing') - self.separate.set(selection.get('separate', False)) - self.lan_access.set(selection.get('lan_access', False)) - self.repair.set(False) - finally: - self.loading_settings = False - self.persist_settings() - - def show_launcher(self): - if self.controller.busy or not self.launch_selection: - return - if not self.controller.restore({'installation': self.launch_selection}): - self.controller.state = dict(status='failed', error=self.t( - 'The saved installation is unavailable. Return to Installation settings to locate or repair it.', - '保存的安装暂时不可用,请返回安装设置重新定位或修复。')) - self.wizard_step = 3 - self.refresh() - - def update_engine(self): - if not self.launch_selection: - from .launcher_copy import ACTION_COPY - self.status.set(self.t(*ACTION_COPY['installation_missing'])) - return - if self.controller.busy: - return - self.remember_installation(self.launch_selection) - self.wizard_step = 2 - self.controller.state = dict(status='idle') - self.act() - - def add_model_folder(self, path=None): - if self.controller.busy: - return - if path is None: - from tkinter import filedialog - path = filedialog.askdirectory(parent=self.window, title=self.t('Choose a model folder', '选择模型总目录')) - if path: - from .local_models import library_roots - try: - self.model_dirs = library_roots(self.model_dirs + [str(path)]) - self.model_method.set('reuse') - self.changed() - except (OSError, ValueError) as error: - self.status.set(str(error)) - - def remove_model_folders(self): - if self.controller.busy: - return - selected = set(self.model_list.curselection()) - self.model_dirs = [p for i, p in enumerate(self.model_dirs) if i not in selected] - self.changed() - - def back(self): - if not self.controller.busy and self.wizard_step: - if self.wizard_step == 3: - self.wizard_step = 0 - self.controller.state = dict(status='idle') - else: - self.wizard_step -= 1 - self.accept.set(False) - self.refresh() - - def act(self): - if self.controller.busy: - return - state = self.controller.state.get('status') - try: - if self.wizard_step == 3: - self.terminal.show() - self.reset_browser() - self.save_settings() - self.controller.run('launch', {'installation': self.launch_selection}) - self.refresh() - return - if self.wizard_step == 0: - from .comfy_launcher_runtime import layout, new_layout - if self.mode.get() == 'new': - new_layout(self.destination.get()) - else: - layout(self.comfy.get()) - self.wizard_step = 1 - self.refresh() - return - self.terminal.show() - if self.wizard_step == 2 and state == 'review': - if not self.accept.get() or self.controller.state.get('errors'): - return - self.reset_browser() - self.controller.run('install', True) - elif self.wizard_step == 2 and state in ('restart-required', 'open'): - self.reset_browser() - self.controller.run('connect') - else: - if not self.selected_folder().get().strip(): - self.browse(self.selected_folder()) - if not self.selected_folder().get().strip(): - return - values = self.values() - self.save_settings() - self.last_model_groups = [] - self.controller.run('inspect', values) - self.wizard_step = 2 - self.started = time.monotonic() - self.bar.stop(); self.bar.configure(mode='determinate', maximum=1, value=0) - self.overall_bar.stop(); self.overall_bar.configure(mode='determinate', maximum=1, value=0) - self.refresh() - except (ValueError, OSError) as error: - self.status.set(str(error)) - - def reset_browser(self): - self.opened = self.browser_attempted = False - self.browser_error = '' - - def open_browser(self): - if self.controller.state.get('status') != 'open': - # The controller can change state before the next GUI refresh. - # A click on the previous enabled button still gets a response. - if self.controller.busy and self.controller.state.get('action') in ('launch', 'connect', 'install'): - self.browser_attempted = False - self.status.set(self.t(*BROWSER_STARTING)) - else: - self.refresh() - return - from .windows_ux import open_browser - self.browser_attempted = True - self.browser_error = '' - address = self.controller.state['url'] - if self.zh: - parsed = urlsplit(address) - query = dict(parse_qsl(parsed.query, keep_blank_values=True)) - query['freevideo_lang'] = 'zh' - address = urlunsplit((parsed.scheme, parsed.netloc, parsed.path, - urlencode(query), parsed.fragment)) - try: - self.opened = bool(open_browser(address)) - refused = not self.opened - except Exception as error: - # Browser failures must not terminate the GUI poll loop or claim - # the server failed. Keep the URL and a one-click manual retry. - self.opened, refused, detail = False, False, str(error) - if not self.opened: - from .launcher_copy import Phrase - # Both languages are kept so the message follows a language switch. - self.browser_error = Phrase.build(lambda t: t( - 'ComfyUI is ready, but the browser did not open. Use Open browser or copy the address.\n', - 'ComfyUI 已就绪,但浏览器未能打开。请点击“打开浏览器”,或复制地址手动打开。\n') + ( - t('The system did not accept the browser request.', '系统未接受打开浏览器的请求。') if refused else detail), - self.zh) - self.refresh() - - def copy_browser_address(self): - self.window.clipboard_clear() - self.window.clipboard_append(self.browser_address.get()) - - def copy_access_link(self): - self.window.clipboard_clear() - self.window.clipboard_append(self.access_link.get()) - - def create_shortcut(self): - if self.controller.busy or not self.controller.selection: - return - self.controller.run('shortcut', self.controller.state.get('status')) - self.refresh() - - def refresh(self): - from .launcher_view import show_page - row = self.controller.state - state, busy = row.get('status', 'idle'), self.controller.busy - fresh = self.mode.get() == 'new' - self.entry.configure(textvariable=self.selected_folder()) - self.folder_label.set(self.t('Install location', '安装位置') if fresh else self.t('Your ComfyUI folder', 'ComfyUI 安装目录')) - self.folder_hint.set(self.t('ComfyUI, Python and FreeVideo install here.', 'ComfyUI、Python 和 FreeVideo 都安装在这里。') if fresh else - self.t('Your ComfyUI folder, or its portable package folder.', '选择 ComfyUI 或整合包所在文件夹。')) - headings = [('Set up FreeVideo', '开始使用 FreeVideo'), ('Get your models', '准备模型'), - ('Ready to install', '准备安装'), ('FreeVideo', 'FreeVideo')] - # One line each. What a control does is stated once, next to the control. - descriptions = [('Choose how you want to use ComfyUI.', '选择 ComfyUI 的使用方式。'), - ('Download automatically, download yourself, or reuse existing models.', '自动下载、手动下载,或复用已有模型。'), - ('Review, then install.', '确认后开始安装。'), - ('Start ComfyUI and open the FreeVideo workflow.', '启动 ComfyUI 并打开 FreeVideo 工作流。')] - if self.wizard_step == 3: - descriptions[3] = { - 'running': BROWSER_STARTING, - 'open': ('ComfyUI is ready. Open FreeVideo in your browser.', 'ComfyUI 已就绪,可在浏览器中打开 FreeVideo。'), - 'failed': ('Could not start. Details below.', '启动未完成,原因见下方。'), - 'restart-required': ('Restart your running ComfyUI, then connect again.', '请重启正在运行的 ComfyUI,然后重新连接。'), - 'cancelled': ('Startup stopped. Your installation is retained.', '已停止启动,安装文件已保留。'), - }.get(state, descriptions[3]) - if busy and row.get('action') == 'shortcut': - descriptions[3] = ('Creating desktop shortcut…', '正在创建桌面快捷方式…') - if self.wizard_step == 2: - headings[2], descriptions[2] = { - 'running': (('Finding your models', '正在查找模型'), ('Scanning folders…', '正在扫描模型目录…')) if row.get('action') == 'inspect' else - (('Installing FreeVideo', '正在安装 FreeVideo'), ('Preparing models and dependencies.', '正在准备模型和运行环境。')), - 'failed': (('Installation paused', '安装已暂停'), ('Files retained. Details below.', '文件已保留,原因见下方。')), - 'cancelled': (('Installation paused', '安装已暂停'), ('Downloaded files are reused.', '已下载文件会复用。')), - 'open': (('You’re ready', '准备完成'), ('ComfyUI is ready. Open FreeVideo in your browser.', 'ComfyUI 已就绪,可在浏览器中打开 FreeVideo。')), - 'restart-required': (('One last step', '最后一步'), ('Restart ComfyUI, then connect below.', '请重启 ComfyUI,然后点击下方连接。')), - }.get(state, (headings[2], descriptions[2])) - self.heading.configure(text=self.t(*headings[self.wizard_step])) - self.status.set(self.t(*descriptions[self.wizard_step])) - self.model_list.delete(0, 'end') - for folder in self.model_dirs: - self.model_list.insert('end', folder) - # As tall as the folders it holds, so an empty or short list is not - # five rows of blank well. - self.model_list.configure(height=max(2, min(6, len(self.model_dirs)))) - self.error_text = '\n'.join(str(e) for e in row.get('errors', [])) - if row.get('error'): - from .launcher_copy import lan_error - self.error_text += ('\n' if self.error_text else '') + lan_error(row['error'], self.zh) - if self.browser_error: - self.error_text += ('\n' if self.error_text else '') + self.browser_error - if row.get('shortcut', {}).get('status') == 'failed': - self.error_text += ('\n' if self.error_text else '') + self.t( - row['shortcut']['error'], '安装已完成,但无法创建桌面快捷方式。可继续使用启动器。\n' + row['shortcut']['error']) - if self.error_text: - self.copy_error_button.pack(side='left', padx=6) - self.report_error_button.pack(side='left', padx=6) - self.review_card.pack(fill='x', pady=12) - else: - self.copy_error_button.pack_forget(); self.report_error_button.pack_forget(); self.review_card.pack_forget() - self.review.configure(state='normal'); self.review.delete('1.0', 'end') - self.review.insert('1.0', self.error_text) - # Only as tall as the retained text, so a one-line failure is one line. - self.review.configure(height=min(4, max(1, len(self.error_text.splitlines()))), state='disabled') - self.launch_error.configure(text=self.error_text) - if row.get('engine_update_available'): - self.engine_update_row.pack(fill='x', pady=(12, 0)) - else: - self.engine_update_row.pack_forget() - self.engine_update_button.state(['disabled'] if busy else ['!disabled']) - selected = self.launch_selection or {} - self.launch_paths.configure(text='ComfyUI · ' + selected.get('root', '') + '\n' + - self.t('Engine', '引擎') + ' · ' + selected.get('engine', '')) - self.browser_address.set(row.get('url', '') if state == 'open' else '') - links = self.controller.access_links - self.lan_message.set(self.t('LAN access has stopped. Turn it on again.', '局域网访问已停止,请重新开启。') - if row.get('lan_status') == 'stopped' else - self.t('No LAN address found. Connect to Wi-Fi or a wired network first.', '未找到局域网地址,请先连接 Wi-Fi 或有线网络。') - if row.get('lan_status') == 'no-address' else '') - self.access_link.set(links[0] if state == 'open' and links else '') - if state == 'open': - self.browser_controls.pack(fill='x', pady=(16, 0)) - else: - self.browser_controls.pack_forget() - self.browser_button.state(['disabled'] if busy or state != 'open' else ['!disabled']) - self.shortcut_button.state(['!disabled'] if not busy and self.controller.selection and - self.controller.selection.get('ready') else ['disabled']) - shortcut = row.get('shortcut', {}) - self.shortcut_status.configure(text=self.t('Desktop shortcut ready', '桌面快捷方式已就绪') - if shortcut.get('status') in ('created', 'present') else '') - if self.wizard_step == 3: - action = self.t('Start & open FreeVideo', '启动并打开 FreeVideo') - elif self.wizard_step < 2: - action = self.t('Next →', '下一步 →') if self.wizard_step == 0 else self.t('Scan & continue →', '扫描并继续 →') - else: - action = self.t('Install & open ComfyUI', '安装并打开 ComfyUI') if state == 'review' else self.t('Connect', '连接') if state == 'restart-required' else self.t('Open FreeVideo', '打开 FreeVideo') if state == 'open' else self.t('Check & resume', '检查并继续') - self.primary.configure(text=action) - if busy: - self.primary.configure(text=self.t('Starting…', '启动中…') if self.wizard_step == 3 else - self.t('Checking…', '检查中…') if row.get('action') == 'inspect' else self.t('Installing…', '安装中…')) - allowed = not busy and (self.wizard_step != 2 or state != 'review' or (self.accept.get() and not row.get('errors'))) - self.primary.state(['!disabled'] if allowed else ['disabled']) - self.back_button.state(['disabled'] if busy or self.wizard_step == 0 else ['!disabled']) - self.back_button.configure(text=self.t('Installation settings', '安装设置') if self.wizard_step == 3 else self.t('Back', '上一步')) - if self.launch_selection and self.wizard_step != 3: - self.launcher_button.pack(side='left', padx=12) - self.launcher_button.state(['disabled'] if busy else ['!disabled']) - else: - self.launcher_button.pack_forget() - self.stop_button.configure(text=self.t('Stop startup', '停止启动') if self.wizard_step == 3 else self.t('Pause installation', '暂停安装')) - for widget in (self.entry, self.browse_button, self.add_model_button, self.remove_model_button, *self.mode_buttons, *self.options_inputs): - if widget.winfo_exists(): - widget.state(['disabled'] if busy else ['!disabled']) - if self.listen_entry is not None and self.listen_entry.winfo_exists(): - self.listen_entry.state(['readonly'] if self.lan_access.get() else ['!readonly']) - if busy: - self.stop_button.pack(side='right', padx=(0, 10)) - else: - self.stop_button.pack_forget() - self.consent.configure(text=self.t('I accept the installation plan and model / toolkit licenses.', '我同意本安装计划及模型/工具许可证。')) - if state == 'review' and not busy and self.wizard_step == 2: - self.consent.pack(anchor='w', pady=(0, 12), before=self.update_row) - else: - self.consent.pack_forget() - plan = row.get('plan', {}) - hardware = plan.get('inventory', {}).get('hardware', {}) - summary = [] - if plan.get('disk_mode') == 'extreme': - summary.append(self.t('Space saver (automatic)', '极限省空间(自动启用)')) - if hardware.get('gpu_name'): - summary.append(hardware['gpu_name']) - if 'model_download_bytes' in plan: - from .bootstrap import download_bytes - summary.append(self.t('To download ', '需下载 ') + '%.1f GiB' % (download_bytes(plan)/2**30)) - if state == 'review' and row.get('disks'): - needed = sum(d.get('needed_bytes', 0) for d in row['disks']) - summary.append(self.t('Peak disk space ~', '预计磁盘峰值 ~') + '%.1f GiB' % (needed/2**30)) - self.summary.configure(text=' · '.join(summary)) - if state == 'review': - self.progress_card.pack_forget() - elif not self.progress_card.winfo_manager(): - self.progress_card.pack(fill='x', before=self.review_card if self.review_card.winfo_manager() else None) - self.render_models(row) - self.refresh_model_choices() - show_page(self) - - def render_models(self, row): - groups = row.get('task', {}).get('model_groups') or row.get('model_groups') - if groups: - self.last_model_groups = groups - groups = self.last_model_groups or row.get('plan', {}).get('model_groups', []) - by_name = {item['id']: item for item in groups} - ready = row.get('selection', {}).get('ready') or row.get('status') == 'open' - for name, card in self.model_cards.items(): - card.update(by_name.get(name), ready=ready) - - def copy_error(self): - if self.error_text: - self.window.clipboard_clear() - self.window.clipboard_append(self.error_text) - - def report_error(self): - if self.error_text: - from .launcher_issue import environment_line, issue_url, product_version - from .windows_ux import open_browser - version = product_version(__version__) - open_browser(issue_url(self.error_text, version, None, zh=self.zh, environment=environment_line(version))) - - def show_details(self): - dialog = self.tk.Toplevel(self.window); dialog.title(self.t('FreeVideo · Details', 'FreeVideo · 详情')) - dialog.configure(bg=branding.BACKGROUND) - dialog.geometry('720x440') - text = self.tk.Text(dialog, wrap='word', padx=16, pady=16, font=('Consolas', 10), - bg=branding.SURFACE, fg=branding.TEXT, relief='flat', - selectbackground=branding.RAISED, selectforeground=branding.TEXT) - text.pack(fill='both', expand=True) - row = self.controller.state - safe = {k: v for k, v in row.items() if k != 'host'} - text.insert('1.0', json.dumps(safe, ensure_ascii=False, indent=2)); text.configure(state='disabled') - self.button(dialog, 'Model licenses', '模型许可证', lambda: webbrowser.open('https://huggingface.co/OpenVDN/vdn-minimax-h3-edge/blob/main/LICENSE')).pack(pady=8) - - def poll(self): - if not self.controller.busy: - self.controller.poll_access_proxy() - if self.poll_timer is not None: - self.window.after_cancel(self.poll_timer) - self.poll_timer = None - row = self.controller.state - if self.controller.busy and row.get('action') != 'shortcut' and id(self.controller.thread) != self.terminal_operation: - self.terminal_operation = id(self.controller.thread) - self.terminal.show() - self.terminal.poll() - task = row.get('task', {}) - progress = task.get('progress', {}) - self.render_progress(row, task, progress) - self.render_models(row) - if not self.controller.busy: - self.bar.stop() - if self.closing: - self.controller.close() - self.window.destroy(); return - selected = row.get('selection') - if (selected and selected.get('ready') and - (row.get('deployed') or row.get('lan_status') == 'stopped' or row.get('status') in ('open', 'restart-required')) and - row.get('status') != 'running'): - if selected != self.launch_selection: - self.remember_installation(selected) - if row.get('action') == 'install' or row.get('status') in ('open', 'restart-required'): - self.wizard_step = 3 - if row.get('status') == 'open': - self.bar.configure(mode='determinate', maximum=1, value=1) - if not self.browser_attempted: - self.open_browser() - # Include busy separately: the task's final state arrives just before - # the thread exits, and the action must become enabled at that boundary. - key = (row.get('status'), self.controller.busy, row.get('error'), id(row.get('plan')), - row.get('overall', {}).get('label'), row.get('lan_status'), tuple(self.controller.access_links)) - if key != self.last_state: - self.last_state = key - if row.get('action') == 'install': - self.queue_save() - self.refresh() - if row.get('action') == 'install' and not self.controller.busy and self.started and row.get('status') in ('open','failed','cancelled','restart-required'): - event_key = 'setup-%s-%s' % (self.started, row['status']) - if event_key != self.reported_setup: - self.reported_setup = event_key - from .installation_diagnostics import write - write(self.compatibility_root(), time.time()-(time.monotonic()-self.started), - {'summary': {'status': 'complete' if row['status'] in ('open','restart-required') else 'incomplete', - 'hardware': row.get('plan', {}).get('inventory', {}).get('hardware', {}), - 'stages': [{'stage':'installation', 'seconds':time.monotonic()-self.started}]}, - 'request': {'exception': row.get('exception', []), 'phase': self.controller.section or 'installation'}, - 'log_tails': {'installation': row.get('error', '')}}) - self.poll_timer = self.window.after(120, self.poll) - - def render_progress(self, row, task, progress): - from .launcher_copy import display, progress_view - overall = row.get('overall') or task.get('phase_progress') or dict(done=0, total=1) - total, done = overall.get('total'), overall.get('done') - valid = number(total) and total > 0 and number(done) and done <= total - if valid: - self.overall_bar.stop() - self.overall_bar.configure(mode='determinate', maximum=total, value=done) - self.overall_text.set('%d / %d ' % (done, total) + self.t('stages', '阶段') + - ' · %.0f%%' % (100 * done / total)) - else: - # An unmeasured plan sweeps rather than showing an empty track. - self.overall_bar.start() - self.overall_text.set('') - label = clean(progress.get('label') or overall.get('label') or self.t('Checking configuration', '正在检查配置')) - self.phase.set(display(label, self.zh)) - self.current_text.set(progress_text(progress_view(progress, self.zh), self.zh, decimal_sizes=sys.platform == 'darwin')) - total, done = progress.get('total'), progress.get('done') - valid = number(total) and total > 0 and number(done) and done <= total - self.bar.stop() - self.bar.configure(mode='determinate', maximum=total if valid else 1, value=done if valid else 0) - details = [display(progress.get('detail', ''), self.zh)] - others = [display(p.get('label', ''), self.zh) for p in task.get('active_tasks', [])[1:]] - if others: - details.append('+ ' + ' / '.join(others[:2])) - self.details.set(' · '.join(p for p in details if p)) - if self.started: - self.meta.set(self.t('Elapsed ', '已用 ') + duration(time.monotonic() - self.started)) - - def close(self): - try: - self.persist_settings() - finally: - self.controller.close() - for timer in (self.update_timer, self.compatibility_timer): - if timer is not None: - self.window.after_cancel(timer) - if self.updates: - self.updates.stop() - if self.controller.busy: - self.closing = True - self.controller.cancel() - self.status.set(self.t('Stopping installation; retaining files…', '正在停止安装,保留文件…')) - else: - if self.poll_timer is not None: - self.window.after_cancel(self.poll_timer) - self.poll_timer = None - self.bar.stop() - self.window.destroy() - - def cancel_timers(self, event): - if event.widget != self.window: - return - self.controller.close() - for name in ('poll_timer', 'save_timer', 'compatibility_timer', 'update_timer', 'layout_timer'): - timer = getattr(self, name, None) - if timer is not None: - try: - self.window.after_cancel(timer) - except self.tk.TclError: - pass - setattr(self, name, None) - - @plain_errors - def callback_error(self, kind, value, trace): - path = launcher_root() / 'errors' / ('launcher-' + str(time.time_ns()) + '.log') - io_path(path.parent).mkdir(parents=True, exist_ok=True) - io_path(path).write_text(plain_text(''.join(traceback.format_exception(kind, value, trace))), encoding='utf-8') - self.status.set(plain_text(value)) - - -def legacy_main(): - if '--smoke-test' not in sys.argv: - from .launcher_update import current_build, forward_approved - identity = current_build() - if identity and forward_approved(identity, launcher_root()): - return - import tkinter as tk - if os.name == 'nt': - import ctypes - try: - ctypes.windll.shcore.SetProcessDpiAwareness(2) - except (AttributeError, OSError): - pass - lib = ctypes.windll.kernel32 - lib.GetConsoleWindow.restype = ctypes.c_void_p - if not lib.GetConsoleWindow(): - lib.AllocConsole(); ctypes.windll.user32.ShowWindow(ctypes.c_void_p(lib.GetConsoleWindow()), 0) - window = tk.Tk() - app = Launcher(window) - if '--smoke-test' in sys.argv: - import queue - from .desktop_runtime import Runner, check_launcher_payload, check_launcher_reopen - destination = Path(sys.argv[sys.argv.index('--smoke-test') + 1]) - destination.mkdir(parents=True, exist_ok=True) - try: - payload = check_launcher_payload(app.source, destination) - payload['reopen'] = check_launcher_reopen(destination) - for step in range(len(app.pages)): - app.wizard_step = step - app.refresh(); window.update_idletasks() - if not app.pages[step].winfo_ismapped(): - raise ValueError('Packaged setup wizard page did not open') - payload['wizard_pages'] = 3 - payload['launcher_page'] = True - app.wizard_step = 0 - app.refresh() - # Exercise frozen-only imports before any real installation exists. - app.engine.set(str(destination / 'engine')) - app.download_settings() - if app.download_dialog is None or not app.download_dialog.window.winfo_exists(): - raise ValueError('Packaged download controls could not open') - payload['download_controls'] = True - app.download_dialog.window.destroy() - from .launcher_update import current_build - build = current_build() - if getattr(sys, 'frozen', False) and build is None: - raise ValueError('Packaged launcher update identity is missing') - except Exception: - save(destination / 'smoke.json', dict(success=False, error=traceback.format_exc(), - interface='ComfyUI launcher', model_modules_imported=[])) - window.destroy() - return - events = queue.Queue(); runner = Runner(app.source, events, destination / 'help') - runner.start('help', destination / 'engine', ['--help']) - deadline = time.monotonic() + 240 - def finish(): - window.update_idletasks() - if runner.busy and time.monotonic() < deadline: - window.after(100, finish); return - result = None - while not events.empty(): - kind, value = events.get_nowait() - if kind == 'done': result = value - imported = [p for p in ('torch', 'triton', 'transformers') if p in sys.modules] - save(destination / 'smoke.json', dict(success=bool(result and result['status'] == 'complete' and not imported), - task=result, interface='ComfyUI launcher', window_geometry=window.geometry(), - build=build, - source=str(app.source), payload=payload, model_modules_imported=imported)) - if runner.busy: runner.cancel() - window.destroy() - window.after(100, finish) - window.mainloop() +"""Entry point for the desktop launcher.""" def main(): diff --git a/freevideo_engine/comfy_launcher_runtime.py b/freevideo_engine/comfy_launcher_runtime.py index 844cb693..4b1dec44 100644 --- a/freevideo_engine/comfy_launcher_runtime.py +++ b/freevideo_engine/comfy_launcher_runtime.py @@ -1131,7 +1131,8 @@ def work(): args[0].get('engine') if args and isinstance(args[0], dict) else None) roots = [('INSTALL', engine)] if engine else [] self.state = dict(self.state, status='cancelled' if self.cancelled.is_set() else status, - error=str(error), exception=exception_details(error), denied=describe(error, roots)) + error=str(error).strip() or type(error).__name__, + exception=exception_details(error), denied=describe(error, roots)) self.thread = threading.Thread(target=work, daemon=True) self.thread.start() @@ -1162,7 +1163,8 @@ def _wait_setup(self): self.setup.runner.cancel() if not row['busy'] and row['status'] != 'running': if row['status'] != 'complete' and not (row.get('action') == 'plan' and row.get('plan')): - raise RuntimeError(row.get('error') or row.get('tail', '') or 'Installation stopped; completed files are retained.') + raise RuntimeError(row.get('error') or row.get('tail', '') or 'Installation stopped before it finished; completed files are retained. ' + 'Select Continue to resume.') if self.cancelled.is_set(): raise RuntimeError('Stopped; files retained') return row diff --git a/freevideo_engine/comfy_library.py b/freevideo_engine/comfy_library.py index b5a0dabc..6e334b45 100644 --- a/freevideo_engine/comfy_library.py +++ b/freevideo_engine/comfy_library.py @@ -952,6 +952,14 @@ def _kept_facts(root): prompts.add(name('prompt', text)) except (OSError, ValueError, AttributeError): continue + # A picture that still has the same prompt keeps it in the history too. + try: + import folder_paths + records = json.loads((Path(folder_paths.get_input_directory()) / 'freevideo-image' / 'image-records.json').read_text(encoding='utf-8')) + prompts.update(row['prompt_hash'] for row in records.values() + if isinstance(row, dict) and isinstance(row.get('prompt_hash'), str)) + except Exception: + pass return receipts, prompts diff --git a/freevideo_engine/comfy_media.py b/freevideo_engine/comfy_media.py index 7aed27bd..54f41216 100644 --- a/freevideo_engine/comfy_media.py +++ b/freevideo_engine/comfy_media.py @@ -138,9 +138,7 @@ def export(run, canvas, *, first=None, last=None, references=None, loras=None, c if media.get('middle'): media['middle'] = _middle(media['middle'], canvas, has_first=first is not None or 'first' in media, has_last=last is not None or 'last' in media) - keyframes = first is not None or last is not None or any(name in media for name in ('first', 'last')) - if not continuing and keyframes and (references or media.get('references')): - raise ValueError('Choose keyframes or experimental references; mixed layouts are not supported') + # Keyframes next to references become still guides when the request is read (media_request.keyframes_as_guides). result = {} run = Path(run) for anchor, value in (('first', first), ('last', last)): diff --git a/freevideo_engine/comfy_nodes.py b/freevideo_engine/comfy_nodes.py index b0061f39..ab99ae52 100644 --- a/freevideo_engine/comfy_nodes.py +++ b/freevideo_engine/comfy_nodes.py @@ -4,7 +4,7 @@ from comfy_api.latest import ComfyExtension, InputImpl, io, ui -from . import comfy_bridge, usage_habit, workflow_repairs +from . import comfy_bridge, job_record, usage_habit, workflow_repairs from .comfy_continuation import node_frames, optional_text, part_steps, request_options from .default_prompt import DEFAULT_PROMPT from .original_audio import audio_use_option @@ -159,6 +159,12 @@ def define_schema(cls): tooltip='Two-pass only: a smaller factor starts from a larger first pass, for more detail and a longer run.'), io.Boolean.Input('allow_empty_prompt', display_name='Allow empty prompt', default=False, optional=True, advanced=True, tooltip='Generates from an empty prompt instead of asking for one.'), + io.String.Input('upscale_from', display_name='Upscale video', default='', optional=True, advanced=True, + socketless=True, tooltip='Set by Upscale in Creations: the finished video to make larger. ' + "The upscale uses the video's own prompt, seed, length and sound."), + io.String.Input('upscale_to', display_name='Upscale size', default='', optional=True, advanced=True, + socketless=True, tooltip='Set by Upscale in Creations: empty for one 1.5x step, 4k for the 4K size ' + 'made frame by frame by a small upscale model.'), ], outputs=[io.Video.Output('video'), io.String.Output('report', display_name='Report JSON')], hidden=[io.Hidden.unique_id, io.Hidden.prompt, io.Hidden.extra_pnginfo], @@ -168,12 +174,15 @@ def define_schema(cls): @classmethod def validate_inputs(cls, text, width, height, seconds, seed, continue_from='', frames=0, two_pass=True, preview=False, refine_from='', base_steps=8, refine_steps=3, step_cache='none', - upscale_factor='2', allow_empty_prompt=False): + upscale_factor='2', allow_empty_prompt=False, upscale_from='', upscale_to=''): # ComfyUI marks every input named here when a check fails, so only the checked widgets are # listed. Linked pictures, media and conditioning have no value before the run anyway. # step_cache and upscale_factor are named so ComfyUI skips their option lists: an older saved # workflow puts '' there, and execute uses no cache and the 2x upscale for a value that is not an option. refine_from = optional_text(refine_from) + if optional_text(upscale_from): + # The bridge reads the finished video's own request; the node's widgets do not apply. + return True if optional_text(upscale_to) in (None, '', '4k') else 'Upscale size must be empty or 4k' try: options = request_options(continue_from, node_frames(frames)) if options.get('continue_from'): @@ -207,11 +216,12 @@ def fingerprint_inputs(cls, **kwargs): return float('nan') @classmethod + @job_record.video_node def execute(cls, text, width, height, seconds, seed, first=None, last=None, references=None, loras=None, conditioning=None, media=None, two_pass=True, force_regenerate=False, base_steps=8, refine_steps=3, preview=False, refine_from='', continue_from='', frames=0, first_frame_reference=False, voice_reference=False, hide_tail=False, - step_cache='none', upscale_factor='2', allow_empty_prompt=False): + step_cache='none', upscale_factor='2', allow_empty_prompt=False, upscale_from='', upscale_to=''): from .comfy_environment import control_process from .gpu_pool import pool_enabled if control_process() and pool_enabled(): @@ -219,6 +229,15 @@ def execute(cls, text, width, height, seconds, seed, first=None, last=None, from server import PromptServer from .comfy_chain import block_context, block_finished, report_fields refine_from, continue_from = optional_text(refine_from), optional_text(continue_from) + upscale_from = optional_text(upscale_from) + upscale_to = optional_text(upscale_to) if upscale_from else None + # The 4K size is made by a small frame-wise model beside whatever else is loaded (frame_upscale). + frames_upscale = upscale_to == '4k' + if upscale_from: + # Upscaling a finished video is its own request: three refinement steps, no preview or continuation. + two_pass, preview, base_steps, refine_steps, step_cache = True, False, 8, 3, 'none' + refine_from = continue_from = '' + frames = 0 node_id = cls.hidden.unique_id chain = block_context(PromptServer.instance, node_id) options = request_options(continue_from, node_frames(frames)) @@ -237,7 +256,7 @@ def execute(cls, text, width, height, seconds, seed, first=None, last=None, preview = False notes.append('A continued part is made in full, without stopping at the preview.') from .two_pass import validate_steps - if not refine_from: + if not refine_from and not upscale_from: validate_steps(base_steps, refine_steps, two_pass) from .background_compile import COMPILE # Returns once the idle compile released the GPU and the engine lease. @@ -253,39 +272,41 @@ def execute(cls, text, width, height, seconds, seed, first=None, last=None, from .encoder_prewarm import IDLE from .resident_process import OWNER from .prompt_vlm.service import stop_prestart_for_generation - stop_prestart_for_generation(PromptServer.instance) - try: # the image option must never keep a video from starting - from .image_gen.service import stop_prestart_for_generation as stop_image_for_generation - # An idle picture model stays when the planner places this video the same beside it; only a plain - # text-to-video request is planned here, anything with media or a continuation stops it as before. - plain = not any((first, last, references, loras, conditioning, media, refine_from, - options.get('continue_from'), chain is not None and chain.get('count', 1) > 1)) - video = dict(width=width, height=height, seconds=seconds, steps=base_steps, two_pass=two_pass, - refine=refine_steps, step_cache=step_cache_option(step_cache).get('step_cache'), - upscale=upscale_option(upscale_factor).get('upscale_factor', 2)) if plain else None - stop_image_for_generation(PromptServer.instance, video=video) - except Exception as error: - logging.warning('[FreeVideo] Could not stop image generation before the video: %s', error) - try: # nor music for a cut, which composes again after the video - from .music.service import stop_for_generation as stop_music_for_generation - stop_music_for_generation(PromptServer.instance) - except Exception as error: - logging.warning('[FreeVideo] Could not stop music before the video: %s', error) - try: # the picture worker keeps the card longer only for people who mostly make pictures - from .image_gen.keep import note, path - note('video', path(comfy_bridge.installation_root())) - except Exception as error: - logging.warning('[FreeVideo] Could not record the video for the picture worker: %s', error) - try: # nor splitting a clip's sound, which starts again after the video - from .stems.service import stop_for_generation as stop_stems_for_generation - stop_stems_for_generation(PromptServer.instance) - except Exception as error: - logging.warning('[FreeVideo] Could not stop sound separation before the video: %s', error) + if not frames_upscale: + # Pictures, prompt help, music and sound separation keep their models for the 4K upscale. + stop_prestart_for_generation(PromptServer.instance) + try: # the image option must never keep a video from starting + from .image_gen.service import stop_prestart_for_generation as stop_image_for_generation + # An idle picture model stays when the planner places this video the same beside it; only a plain + # text-to-video request is planned here, anything with media or a continuation stops it as before. + plain = not any((first, last, references, loras, conditioning, media, refine_from, upscale_from, + options.get('continue_from'), chain is not None and chain.get('count', 1) > 1)) + video = dict(width=width, height=height, seconds=seconds, steps=base_steps, two_pass=two_pass, + refine=refine_steps, step_cache=step_cache_option(step_cache).get('step_cache'), + upscale=upscale_option(upscale_factor).get('upscale_factor', 2)) if plain else None + stop_image_for_generation(PromptServer.instance, video=video) + except Exception as error: + logging.warning('[FreeVideo] Could not stop image generation before the video: %s', error) + try: # nor music for a cut, which composes again after the video + from .music.service import stop_for_generation as stop_music_for_generation + stop_music_for_generation(PromptServer.instance) + except Exception as error: + logging.warning('[FreeVideo] Could not stop music before the video: %s', error) + try: # the picture worker keeps the card longer only for people who mostly make pictures + from .image_gen.keep import note, path + note('video', path(comfy_bridge.installation_root())) + except Exception as error: + logging.warning('[FreeVideo] Could not record the video for the picture worker: %s', error) + try: # nor splitting a clip's sound, which starts again after the video + from .stems.service import stop_for_generation as stop_stems_for_generation + stop_stems_for_generation(PromptServer.instance) + except Exception as error: + logging.warning('[FreeVideo] Could not stop sound separation before the video: %s', error) prewarm = {} result_reused = [False] result_report = [None] - total_steps = base_steps + (refine_steps if two_pass and not preview else 0) - if two_pass and not preview and not refine_from: + total_steps = 1 if frames_upscale else refine_steps if upscale_from else base_steps + (refine_steps if two_pass and not preview else 0) + if two_pass and not preview and not refine_from and not upscale_from: # A small canvas runs in one pass even with two-pass on. from .geometry import geometry from .two_pass import plan, sampling_canvas @@ -307,7 +328,7 @@ def execute(cls, text, width, height, seconds, seed, first=None, last=None, if notice: logging.warning('[FreeVideo] %s', notice) PromptServer.instance.send_progress_text(notice, node_id) - if two_pass and not refine_from and not preview: + if two_pass and not refine_from and not preview and not upscale_from: from .two_pass import one_pass_note step_note = one_pass_note(base_steps) if step_note: @@ -360,6 +381,8 @@ def release(): # The upscaled video is the full request's result: embed that # workflow, not one that points at this machine's preview file. graph = comfy_bridge.without_upscale(graph, node_id, refine_from) + if graph and upscale_from: + graph = comfy_bridge.without_work_upscale(graph, node_id, upscale_from) output_root = Path(folder_paths.get_output_directory()).resolve() def kept(exported): @@ -391,6 +414,8 @@ def kept(exported): **({'voice_reference': True} if voice_reference is True and options.get('continue_from') else {}), **({'hide_tail': True} if hide_tail is True else {}), **({'allow_empty_prompt': True} if allow_empty_prompt is True else {}), + **({'upscale_from': upscale_from} if upscale_from else {}), + **({'upscale_to': '4k'} if frames_upscale else {}), **step_cache_option(step_cache), **upscale_option(upscale_factor), **({'report_extra': {'chain': report_fields(chain)}} if chain is not None else {})) diff --git a/freevideo_engine/comfy_privacy.py b/freevideo_engine/comfy_privacy.py new file mode 100644 index 00000000..88df81cb --- /dev/null +++ b/freevideo_engine/comfy_privacy.py @@ -0,0 +1,45 @@ +"""Privacy defaults for the ComfyUI host launched in our managed environment.""" +import json +import logging +import os +from pathlib import Path + +from .comfy_logging import MANAGED_HOST_ENV + +PERSIST = 'Comfy.Workflow.Persist' + + +def keep_no_workflow_drafts(user_root): + """Turn off the ComfyUI page's workflow drafts once, unless the user already chose. + + With drafts on, the page copies every open workflow, prompts included, into the + browser's storage, where it stays after the work is deleted. A value the user set, + either way, is left alone; so is a settings file we cannot read as an object. + Returns True when the setting was written. + """ + path = Path(user_root) / 'default' / 'comfy.settings.json' + try: + settings = json.loads(path.read_text(encoding='utf-8')) + except FileNotFoundError: + settings = {} + except (OSError, ValueError): + return False + if not isinstance(settings, dict) or PERSIST in settings: + return False + settings[PERSIST] = False + path.parent.mkdir(parents=True, exist_ok=True) + temporary = path.with_name(path.name + '.freevideo-tmp') + temporary.write_text(json.dumps(settings, indent=4), encoding='utf-8') + os.replace(temporary, path) + return True + + +def configure_managed_privacy(): + """Applied only in the ComfyUI FreeVideo installed; a user's own ComfyUI keeps its settings.""" + if os.environ.get(MANAGED_HOST_ENV) != '1': + return + try: + import folder_paths + keep_no_workflow_drafts(folder_paths.get_user_directory()) + except Exception as error: # The page still works; drafts keep their old setting. + logging.warning('[FreeVideo] Workflow draft setting not applied: %s', error) diff --git a/freevideo_engine/compatibility_ui.py b/freevideo_engine/compatibility_ui.py deleted file mode 100644 index afb4d2dc..00000000 --- a/freevideo_engine/compatibility_ui.py +++ /dev/null @@ -1,73 +0,0 @@ -"""Small native compatibility controls shared by the EXE and portable launcher.""" -from pathlib import Path - -from .long_paths import io_path, plain_text, plain_errors -from .compatibility import Store, installed_identity, check_installation, LEVELS - - -@plain_errors -def notify(window, root, zh=True): - from tkinter import messagebox - root = Path(root) - if not (io_path(root)/'machine.json').is_file(): - return - try: - value = check_installation(root) - if value.get('notice'): - from .compatibility_copy import notice_text - messagebox.showinfo('FreeVideo', notice_text(value, zh), parent=window) - Store(root).acknowledge(installed_identity(root), value['notice']['id']) - except Exception as error: - messagebox.showerror('FreeVideo', plain_text(error), parent=window) - - -def open_settings(window, root, zh=True): - import tkinter as tk - from tkinter import ttk, messagebox - root = Path(root) - try: - identity = installed_identity(root) - state = check_installation(root) - except Exception as error: - messagebox.showerror('FreeVideo', str(error), parent=window) - return - if not state['available']: - messagebox.showinfo('FreeVideo', - '尚未识别到设备信息,兼容性设置暂不可用。可继续正常使用 FreeVideo。' if zh else - 'Device information is unavailable. Compatibility settings are disabled; you can continue using FreeVideo.', - parent=window) - return - dialog = tk.Toplevel(window) - dialog.title('FreeVideo · '+('兼容性设置' if zh else 'Compatibility')) - dialog.transient(window) - dialog.geometry('520x330') - body = ttk.Frame(dialog, padding=24); body.pack(fill='both', expand=True) - text = tk.StringVar() - level = tk.DoubleVar(value=state['level']) - automatic = tk.BooleanVar(value=state['automatic']) - ttk.Label(body, textvariable=text, anchor='center').pack(fill='x', pady=(8, 14)) - def changed(value=None): - selected = int(round(level.get())) - text.set(LEVELS[selected]['zh' if zh else 'en']) - if value is not None and selected == 0: - automatic.set(False) - scale = ttk.Scale(body, from_=0, to=3, variable=level, command=changed) - scale.pack(fill='x', pady=(0, 16)); changed() - def released(_): - level.set(round(level.get())); changed() - if int(level.get()) == 0: automatic.set(False) - scale.bind('', released) - ttk.Checkbutton(body, variable=automatic, text='异常中断后自动提高兼容档位' if zh else - 'Raise the level automatically after an unexpected interruption').pack(anchor='w') - ttk.Label(body, text='从下一次生成起生效。档位越高,显卡每次处理的数据越少,生成越慢,画面也会有细微差别;' - '分辨率、时长和步数不变。' if zh else - 'Applies from the next generation. Higher levels have the GPU handle less at a time, so generation is slower ' - 'and the picture differs slightly; resolution, duration and steps stay the same.', - style='Muted.TLabel', wraplength=460).pack(fill='x', pady=16) - def save(): - try: - Store(root).set(identity, int(round(level.get())), automatic.get()) - dialog.destroy() - except Exception as error: - messagebox.showerror('FreeVideo', str(error), parent=dialog) - ttk.Button(body, text='保存' if zh else 'Save', command=save, style='Primary.TButton').pack(anchor='e') diff --git a/freevideo_engine/component_licenses.py b/freevideo_engine/component_licenses.py index 6dc6990e..56246938 100644 --- a/freevideo_engine/component_licenses.py +++ b/freevideo_engine/component_licenses.py @@ -40,8 +40,17 @@ def row(key, name, licence, link, text=None, terms=None): 'https://github.com/DepthAnything/Depth-Anything-V2/blob/a561b849ebae10a6f5ef49e26c83cbbcd36c71bf/LICENSE') +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') + + def depth_license(): return local(DEPTH, HERE / 'licenses/Depth-Anything-V2-Apache-2.0.txt') + + +def upscale_license(): + return local(UPSCALE, HERE / 'licenses/Real-ESRGAN-BSD-3-Clause.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. @@ -123,6 +132,9 @@ def bundle(root, value): if any('depth_anything_v2/' in entry['path'].replace('\\', '/') or entry['path'].endswith('depth_anything_v2_vits.pth') for entry in value['files']): rows.append(depth_license()) + 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()) return rows diff --git a/freevideo_engine/desktop_shortcut.py b/freevideo_engine/desktop_shortcut.py index 2b0dea9a..07f7feaa 100644 --- a/freevideo_engine/desktop_shortcut.py +++ b/freevideo_engine/desktop_shortcut.py @@ -221,7 +221,7 @@ def launcher_target(engine, source, portable_root=None, *, prepare=True): python = resolved(sys.executable) if python.with_name('pythonw.exe').is_file(): python = python.with_name('pythonw.exe') - code = "import runpy,sys;sys.path.insert(0,sys.argv[1]);runpy.run_module('freevideo_engine.comfy_launcher',run_name='__main__')" + code = "import runpy,sys;sys.path.insert(0,sys.argv[1]);runpy.run_module('freevideo_engine.modern_launcher',run_name='__main__')" return Path(plain(python)), ['-c', code, plain(resolved(source))], Path(plain(source)) / 'freevideo_engine/assets/icon.ico' @@ -330,7 +330,10 @@ def _failure(error, menu_ready): zh.append('Windows 不允许 FreeVideo 写入桌面。如果在“Windows 安全中心”里开启了“受控文件夹访问”,' '请允许 FreeVideo,然后点击“创建桌面快捷方式”。') else: - en.append(text); zh.append(text) + # The system's own words are the cause; the next step is the same button. + cause = text.strip().rstrip('.。') + en.append(cause + '. Click Create desktop shortcut to try again.') + zh.append(cause + '。请点击“创建桌面快捷方式”重试。') if menu_ready: en.append('FreeVideo is in the Start menu.'); zh.append('开始菜单里可以找到 FreeVideo。') return ' '.join(en), ''.join(zh) @@ -541,5 +544,6 @@ def create_after_install(engine, source, portable_root=None): try: return create(engine, source, portable_root) except (OSError, ValueError) as error: - return dict(status='failed', error='Installed successfully, but the desktop shortcut could not be created: ' + str(error), - error_zh='安装已完成,但桌面快捷方式没有创建成功:' + str(error)) + # A shortcut failure is its own kind, with the same cause and next step as the shortcut button. + en, zh = _failure(error, menu_ready=False) + return dict(status='failed', kind='shortcut', error='Installed successfully. ' + en, error_zh='安装已完成。' + zh) diff --git a/freevideo_engine/download_settings.py b/freevideo_engine/download_settings.py index 6f0e431a..dc620bce 100644 --- a/freevideo_engine/download_settings.py +++ b/freevideo_engine/download_settings.py @@ -12,6 +12,34 @@ CHOICES = ('auto', 'official', 'hf-mirror', 'modelscope') # Shown as is by the Tk window and mapped to Chinese by the setup page. SPEED_TEST_FAILED = 'The speed test did not finish. Click "Test source speeds".' +# The launcher's own words, by rough cause; the raw error is not kept (it can carry request headers). +SPEED_TEST_REASONS = { + 'offline': ('The speed test could not reach any download source. Check the network or proxy, then click "Test speed" again.', + '测速无法连接任何下载源。请检查网络或代理,再点击“测速”。'), + 'timeout': ('The speed test timed out. The network may be slow; click "Test speed" again.', + '测速超时,网络可能较慢。请再点击“测速”。'), + 'other': ('The speed test did not finish. Click "Test speed" again.', '测速未完成,请再点击“测速”。'), +} + + +def speed_test_reason(error): + """'timeout', 'offline' or 'other' for a failed speed test, from the exception type only.""" + import socket + import urllib.error + seen = set() + while error is not None and id(error) not in seen: + seen.add(id(error)) + if isinstance(error, (TimeoutError, socket.timeout)): + return 'timeout' + if isinstance(error, (ConnectionError, socket.gaierror)): + return 'offline' + if isinstance(error, urllib.error.URLError) and not isinstance(error, urllib.error.HTTPError): + error = error.reason if isinstance(error.reason, BaseException) else None + if error is None: + return 'offline' + continue + error = error.__cause__ or error.__context__ + return 'other' FAMILIES = ('edge-models', 'vdn-models', 'encoder-models', 'models', 'image-models') @@ -172,7 +200,7 @@ def progress(value): with self.lock: # Provider exceptions can contain request headers/URLs. self.state=dict(status='failed',root=str(root), - error=SPEED_TEST_FAILED) + error=SPEED_TEST_FAILED,reason=speed_test_reason(error)) self.thread=threading.Thread(target=work,daemon=True) self.thread.start() return dict(self.state) diff --git a/freevideo_engine/download_settings_ui.py b/freevideo_engine/download_settings_ui.py deleted file mode 100644 index d30cc032..00000000 --- a/freevideo_engine/download_settings_ui.py +++ /dev/null @@ -1,156 +0,0 @@ -"""Native download controls, usable before ComfyUI or the engine is installed.""" -from pathlib import Path - -from .download_settings import CHOICES, MODES, SPEED_TEST_FAILED, Probe, read, speed_text - - -class DownloadSettings: - def __init__(self, parent, root, zh=False, probe=None, token=None, busy=None): - import tkinter as tk - from tkinter import ttk - self.root, self.zh = Path(root), zh - self.probe = probe or Probe() - self.token = token if token is not None else tk.StringVar(parent) - self.busy = busy or (lambda: False) - self.window = window = tk.Toplevel(parent) - window.title(self.t('FreeVideo · Download sources', 'FreeVideo · 下载源')) - window.transient(parent) - window.geometry('640x770'); window.minsize(550, 710) - self.timer = None - body = ttk.Frame(window, padding=24); body.pack(fill='both', expand=True) - ttk.Label(body, text=self.t('Connection', '连接模式')).pack(anchor='w') - self.proxy_mode = ttk.Combobox(body, state='readonly', values=( - self.t('Auto (recommended)', '自动(推荐)'), self.t('Proxy only', '仅代理'), self.t('Direct only', '仅直连'))) - self.proxy_mode.pack(fill='x', pady=(8, 4)) - self.proxy_mode.bind('<>', self.select_mode) - self.mode_help = tk.StringVar() - ttk.Label(body, textvariable=self.mode_help, wraplength=560, style='Muted.TLabel').pack(fill='x', pady=(0, 12)) - ttk.Label(body, text=self.t('Model download source', '模型下载源')).pack(anchor='w') - self.names = (self.t('Automatic', '自动选择'), 'Hugging Face', 'HF Mirror', 'ModelScope') - self.source = ttk.Combobox(body, values=self.names, state='readonly') - self.source.pack(fill='x', pady=(8, 12)) - self.source.bind('<>', self.select) - from .hf_auth import HELP_EN, HELP_ZH, TOKEN_URL - import webbrowser - auth = ttk.LabelFrame(body, text=self.t('Hugging Face token · optional', 'Hugging Face Token · 可选'), padding=12) - auth.pack(fill='x', pady=(0, 12)) - ttk.Label(auth, text=self.t(HELP_EN, HELP_ZH), wraplength=520, style='Muted.TLabel').pack(fill='x') - self.token_input = tk.StringVar(value=self.token.get()) - self.token_entry = ttk.Entry(auth, textvariable=self.token_input, show='•') - self.token_entry.pack(fill='x', pady=8) - actions = ttk.Frame(auth); actions.pack(fill='x') - self.token_apply = ttk.Button(actions, text=self.t('Apply token', '应用 Token'), command=self.apply_token) - self.token_apply.pack(side='left') - ttk.Button(actions, text=self.t('Get a read token ↗', '获取读取 Token ↗'), - command=lambda: webbrowser.open(TOKEN_URL)).pack(side='left', padx=8) - self.token_status = tk.StringVar() - ttk.Label(auth, textvariable=self.token_status, wraplength=520, style='Muted.TLabel').pack(fill='x', pady=(6, 0)) - self.status = tk.StringVar() - self.probe_button = ttk.Button(body, text=self.t('Test source speeds', '重新测速'), command=self.start_probe) - self.probe_button.pack(anchor='w') - ttk.Label(body, textvariable=self.status, wraplength=560, style='Muted.TLabel').pack(fill='x', pady=8) - self.speeds = ttk.Treeview(body, columns=('model', 'source', 'speed'), show='headings', height=4) - for key, en, cn, width in (('model', 'Files', '文件', 120), ('source', 'Source / route', '来源/连接', 235), - ('speed', 'HTTP transfer', 'HTTP 传输速度', 150)): - self.speeds.heading(key, text=self.t(en, cn)); self.speeds.column(key, width=width, minwidth=80) - self.speeds.pack(fill='both', expand=True) - ttk.Label(body, text=self.t( - 'Switching takes effect at once. Downloads resume where possible; otherwise the file restarts. Testing speeds does not switch.', - '切换后马上生效,能续传的接着下载,不能的重新下载这个文件。只测速不会切换。'), - wraplength=560, style='Muted.TLabel').pack(fill='x', pady=(12, 4)) - ttk.Label(body, text=str(self.root), wraplength=560, style='Muted.TLabel').pack(fill='x') - ttk.Button(body, text=self.t('Done', '完成'), command=window.destroy).pack(anchor='e', pady=(8, 0)) - window.bind('', self.destroyed, add='+') - self.rendered = None - self.poll() - - def t(self, en, zh): - return zh if self.zh else en - - def select(self, _=None): - try: - self.probe.select(self.root, CHOICES[self.source.current()]) - self.status.set(self.t('Source saved; switching any active model download…', '已保存,正在切换当前模型下载…')) - except (OSError, ValueError) as error: - self.status.set(str(error)) - - def start_probe(self): - self.probe.start(self.root, self.token.get()) - self.refresh() - - def select_mode(self, _=None): - try: - self.probe.select(self.root, proxy_mode=MODES[self.proxy_mode.current()]) - self.refresh() - except (OSError, ValueError) as error: - self.status.set(str(error)) - - def apply_token(self): - from .hf_auth import validate - if self.busy(): - self.token_status.set(self.t('Stop setup before changing the token, then resume.', '先停止安装,再修改 Token 并继续安装。')) - return - try: - self.token.set(validate(self.token_input.get())) - self.token_status.set(self.t('Applied for this session. Review the installation again to continue.', - '已应用到本次会话,重新检测安装即可继续。') if self.token.get() else - self.t('Session token cleared. Existing environment credentials still apply.', '已清除本次填写的 Token;仍可使用环境中已有的凭据。')) - except ValueError: - self.token_status.set(self.t('Enter a token beginning with hf_, or leave it empty.', '请输入以 hf_ 开头的 Token,或留空。')) - - def refresh(self): - value = read(self.root / 'download-settings.json') - self.source.current(CHOICES.index(value['source'])) - mode = value['proxy_mode'] - self.proxy_mode.current(MODES.index(mode)) - self.mode_help.set(self.t(*{ - 'auto': ('Compare proxy and direct connections automatically.', '自动测速,择优使用代理或直连。'), - 'proxy': ('Use the current proxy. No direct fallback.', '沿用当前代理,不尝试直连。'), - 'direct': ('Download directly, ignoring proxies.', '忽略代理,直接下载。')}[mode])) - state = self.probe.snapshot() - busy = state['status'] == 'running' - installing = self.busy() - self.token_apply.state(['disabled'] if installing else ['!disabled']) - self.token_entry.state(['disabled'] if installing else ['!disabled']) - if installing: - self.token_status.set(self.t('Stop setup to change credentials; downloaded files will be kept.', '如需修改 Token,请先停止安装;已下载文件会保留。')) - self.probe_button.state(['disabled'] if busy else ['!disabled']) - if busy: - progress = state.get('progress', {}) - self.status.set(self.t('Testing sources… ', '正在测速… ') + - ('%s/%s · %s' % (progress.get('done', 0), progress.get('total', '?'), progress.get('source', '')))) - elif state.get('error'): - self.status.set(self.t(SPEED_TEST_FAILED, '测速没有完成,请点“重新测速”。') - if state['error'] == SPEED_TEST_FAILED else state['error']) - elif state.get('network_unavailable'): - self.status.set(self.t('No sources reachable. Check your network or connection mode.', '下载源均无法连接,请检查网络或切换连接模式。')) - measured = value.get('probe') - if measured != self.rendered: - self.rendered = measured - self.speeds.delete(*self.speeds.get_children()) - families = {'edge-models': self.t('Video model', '视频模型'), 'vdn-models': self.t('Decoder', '解码器'), - 'encoder-models': self.t('Text encoder', '文本编码器'), - 'models': self.t('Prompt model', '提示词模型'), 'pypi': self.t('Python packages', 'Python 依赖'), - 'github': self.t('Tools', '安装工具'), 'git': 'Git', 'cuda': 'CUDA'} - for family, rows in (measured or {}).get('sources', {}).items(): - if family.startswith('torch-'): - families[family] = self.t('GPU packages', 'GPU 依赖') - for row in rows: - speed = speed_text(row, self.zh) - route = self.t('Direct', '直连') if row.get('route') == 'direct' else self.t('Current connection', '当前连接') - self.speeds.insert('', 'end', values=(families.get(family, family), row['id'] + ' · ' + route, speed)) - if measured and not busy and not state.get('network_unavailable'): - self.status.set(self.t('Speeds are a guide. Choose a source above to switch.', - '测速只作参考。在上方选择下载源来切换。')) - - def poll(self): - try: - self.refresh() - except (OSError, ValueError) as error: - self.status.set(str(error)) - self.timer = self.window.after(400, self.poll) - - def destroyed(self, event): - if event.widget == self.window and self.timer is not None: - self.window.after_cancel(self.timer) - self.timer = None diff --git a/freevideo_engine/failure_details.py b/freevideo_engine/failure_details.py index 6c9f37e0..23ba6590 100644 --- a/freevideo_engine/failure_details.py +++ b/freevideo_engine/failure_details.py @@ -26,7 +26,8 @@ 'offline': ('The network is unavailable; the image model could not be downloaded.', '网络不通,无法下载图像模型。'), 'source_failed': ("The image model download didn't finish. Check your network and try again.", '图像模型没有下载完成,请检查网络后重试。'), 'integrity_failed': ('The image model files are incomplete or damaged. Repair them in the launcher.', '图像模型文件不完整或已损坏,请在启动器里修复。'), - 'write_failed': ('The image model files are in use or cannot be written or deleted.', '图像模型文件被占用,或无法写入/删除。'), + 'write_failed': ('The image model files are in use or cannot be written or deleted. Close programs that may be using them (for example an antivirus scan), check that the model folder can be written to, then try again.', + '图像模型文件被占用,或无法写入/删除。请关闭可能正在使用它们的程序(例如杀毒软件扫描),确认模型文件夹可以写入,然后重试。'), 'invalid_catalog': ('The image model package version is incompatible; update FreeVideo and try again.', '图像模型包版本不匹配,请更新 FreeVideo 后重试。'), 'busy': ('Another task is using the image model package; try again when it finishes.', '图像模型包被其他任务占用,完成后再试。'), 'busy_engine': ('FreeVideo is busy with a task or keeping the image model ready, so the image model cannot be repaired or removed now. Wait for it to finish, or close FreeVideo, then try again.', 'FreeVideo 正在执行任务或保持图像模型就绪,暂时无法修复或删除图像模型。请等待其结束,或关闭 FreeVideo 后再试。'), @@ -35,7 +36,8 @@ '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.', '图像模型目录含有无法安全修改的链接。'), - 'failed': ('The image model operation stopped; see the diagnostic report for details.', '图像模型操作已停止,详情见诊断报告。'), + 'failed': ('The image model operation stopped because of an unexpected error. Export the report, then use "Report a problem" and attach it.', + '图像模型操作因意外错误停止。请先导出报告,再点击“提交问题”并附上报告。'), } @@ -738,6 +740,12 @@ class names and errno, no text), when the message is that exception's str(); it 'If ComfyUI is not installed yet, choose "Install ComfyUI".') return dict(title='这不是 ComfyUI 文件夹' if zh else "This isn't a ComfyUI folder", detail='', action=action, kind='comfy-folder') + if re.search(r'Mac GPU check did not pass|Native GPU checks did not complete', summary): + # The native check on macOS (Metal) failed: say so plainly; the report holds what it measured. + return dict(title='这台 Mac 的 GPU 检查未通过' if zh else 'This Mac’s GPU check did not pass', + detail=('这台 Mac 的图形处理器未通过 FreeVideo 的运行检查。请先导出报告,再点击“提交问题”并附上报告。' if zh else + 'The graphics processor of this Mac did not pass FreeVideo’s check. Export the report, ' + 'then use "Report a problem" and attach it.'), action='', kind='mac-gpu-check') for pattern, kind, title, action in PLACE_RULES: if re.search(pattern, summary): return dict(title=title[zh], detail='', action=action[zh], kind=kind) @@ -825,11 +833,11 @@ class names and errno, no text), when the message is that exception's str(); it ("This computer can't continue a video", '这台电脑无法接续视频'), ('Continuing a video needs an NVIDIA GPU or a Mac. To make a new video, clear "Continue from video".', '接续视频需要 NVIDIA 显卡或 Mac。要生成新视频,请清空“接着生成”。')), (r'Continue from video cannot be used with these settings\. Turn on "Two-pass', 'continuation-passes', - ('Continuing needs two-pass acceleration', '接续需要二次采样加速'), - ('Turn on "Two-pass acceleration" and turn off the first-pass preview.', '请打开“二次采样加速”,并关闭先出预览。')), + ('Continuing needs two-pass acceleration', '接续需要二采加速'), + ('Turn on "Two-pass acceleration" and turn off the first-pass preview.', '请打开“二采加速”,并关闭先出预览。')), (r'audio_original_passes: ', 'audio-original-passes', - ('This audio needs two-pass acceleration', '这段音频需要二次采样加速'), - ('Turn on "Two-pass acceleration" or set the audio to "Reference".', '请打开“二次采样加速”,或把音频改选“参考”。')), + ('This audio needs two-pass acceleration', '这段音频需要二采加速'), + ('Turn on "Two-pass acceleration" or set the audio to "Reference".', '请打开“二采加速”,或把音频改选“参考”。')), (r'audio_original_route: ', 'audio-original-route', ('"Use as is" is not available here', '这里还不能用“原样使用”'), ('Set the audio to "Reference".', '请把音频改选“参考”。')), @@ -1098,7 +1106,13 @@ class names and errno, no text), when the message is that exception's str(); it # The check printed nothing but its own summary line (once per place that kept it); that line # is for the report, not the card. The next step goes under it, as for an unexpected failure. return dict(title='暂时未能完成' if zh else 'Couldn’t complete this step', - detail=CHECK_UNFINISHED[zh] + '\n' + UNKNOWN_NEXT_STEP[zh], action='', kind='unknown') + detail=inspection_reason(lines[0], zh) + '\n' + UNKNOWN_NEXT_STEP[zh], action='', kind='unknown') + if len(lines) == 1 and re.fullmatch(r'[A-Za-z_][\w.]*(?:Error|Exception|Exit|Interrupt)', lines[0]): + # An exception without a message: its name is the only cause there is, so say that and give the next step. + name = lines[0].rsplit('.', 1)[-1] + detail = ('程序意外停止(%s,无附带说明)。' if zh else 'The program stopped unexpectedly (%s, with no message).') % name + return dict(title='暂时未能完成' if zh else 'Couldn’t complete this step', + detail=detail + '\n' + UNKNOWN_NEXT_STEP[zh], action='', kind='unknown') causes = [line for line in lines if re.match(r'^(?:[\w.]+(?:Error|Exception):|ERROR[: ]|Failed step:|Setup failed:)', line)] detail = causes[-1] if causes else next((line for line in reversed(lines) if not line.startswith(('File ', 'Traceback', '^', 'All files retained.', 'Existing files are retained.', 'Rerun the same setup command'))), '') @@ -1212,6 +1226,20 @@ def _plain_cause(text, exception=None): return PLAIN_CAUSES[kind] +def inspection_reason(summary, zh): + """How the check ended, from its summary line (comfy_setup.inspection_failed): timed out, crashed, or quiet.""" + if 'timed out' in summary: + return '检查超时,未完成。' if zh else 'The check timed out before it finished.' + crashed = re.search(r'exit \d+ \((0x[0-9A-F]{8})\)', summary) + if crashed: + return (('检查程序崩溃(代码 %s)。' if zh else 'The check program crashed (code %s).') % crashed.group(1)) + code = re.search(r'exit (-?\d+)', summary) + if code and code.group(1) != '0': + return (('检查程序退出且无输出(退出码 %s)。' if zh else 'The check program exited without output (exit code %s).') + % code.group(1)) + return CHECK_UNFINISHED[zh] + + def _step_name(label, zh): """The name the progress card showed for a setup step, in the interface language, or ''.""" try: diff --git a/freevideo_engine/frame_upscale.py b/freevideo_engine/frame_upscale.py new file mode 100644 index 00000000..b41391f6 --- /dev/null +++ b/freevideo_engine/frame_upscale.py @@ -0,0 +1,462 @@ +"""Upscaling a finished 24 fps video to the 4K size with a small frame-wise model. + +realesr-general-x4v3 (Real-ESRGAN's SRVGGNetCompact network, BSD-3-Clause, (c) 2021 Xintao Wang) makes each frame four +times larger; the result is scaled to the 4K size and written with the video's own sound copied packet for packet. The +model is a 4.9 MB optional download (frame_upscale_model.json). Torch lives only in a disposable worker, as for depth +references: the bridge supervises it, passes its progress on and stops it on cancel. + +The 4K size (Iris, 11-18): the long side is 3840 and the other side follows the picture's shape on an 8-pixel grid; +a picture over 36864 16x16 macroblocks (the usual H.264 decoding limit, 4096 x 2304) is scaled down in proportion +until it fits, so a square becomes 3072 x 3072 and 4:3 becomes 3544 x 2656. +""" +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 + +STAGE = 'frame_upscale' +LONG_SIDE = 3840 +MAX_MACROBLOCKS = 36864 +SCALE = 4 +# Input tiles overlap by the network's reach (34 3x3 convolutions): the same pixels as one whole frame, with about +# 0.5 GiB of GPU memory at any input size. +TILE, PAD = 512, 34 +# GPU memory the worker needs; below it the bridge first frees idle models. +NEEDED_GPU_BYTES = 3 * 2**30 // 2 +NOT_A_WORK = 'Choose a finished FreeVideo video to upscale' + + +class UpscaleError(RuntimeError): + """code: 'upscale_download' (the model could not be fetched), 'upscale_disk' (no room for the result) or + 'upscale_memory' (not enough memory).""" + def __init__(self, code, message=''): + super().__init__(message or code) + self.code = code + + +def catalog(): + return json.loads(Path(__file__).with_name('frame_upscale_model.json').read_text(encoding='utf-8')) + + +def _grid(value): + # Half up, as Math.round in upscale_offer.js (Python's round would go to even). + return int(math.floor(value / 8 + .5)) * 8 + + +def size(width, height): + """The 4K size for a width x height picture, or None when that would not make it larger.""" + if any(type(n) is not int or n <= 0 for n in (width, height)): + return None + longest = max(width, height) + for side in range(LONG_SIDE, 7, -8): + target = _grid(width * side / longest), _grid(height * side / longest) + if min(target) >= 8 and math.ceil(target[0] / 16) * math.ceil(target[1] / 16) <= MAX_MACROBLOCKS: + break + else: + return None + return target if max(target) > longest else None + + +def work_request(output_directory, relative): + """A finished, non-preview 24 fps FreeVideo work in this output folder that the 4K size makes larger: + (video, saved state).""" + if not isinstance(relative, str) or not relative.strip(): + raise ValueError(NOT_A_WORK) + output_root = Path(output_directory).resolve() + video = (output_root / relative).resolve() + try: + video.relative_to(output_root / 'FreeVideo') + except ValueError: + raise ValueError(NOT_A_WORK) from None + path = video.parent / 'comfy-request.json' + try: + state = json.loads(path.read_text(encoding='utf-8')) if path.is_file() else {} + except (OSError, ValueError): + state = {} + geometry = state.get('geometry') if isinstance(state, dict) else None + if (not isinstance(state, dict) or state.get('status') != 'complete' or state.get('preview') + or Path(state.get('output', '')).resolve() != video or not isinstance(geometry, dict) + or geometry.get('fps') != 24 or size(geometry.get('width'), geometry.get('height')) is None + or not video.is_file()): + raise ValueError(NOT_A_WORK) + return video, state + + +def inspect(path): + """One 24 fps picture stream (and any sound, copied as is): its size and frame count.""" + import av + try: + with av.open(str(path)) as container: + if len(container.streams.video) != 1: + raise ValueError(NOT_A_WORK) + stream = container.streams.video[0] + rate = stream.average_rate or stream.guessed_rate + width, height = stream.codec_context.width, stream.codec_context.height + frames = sum(1 for packet in container.demux(stream) if packet.size) + sound = bool(container.streams.audio) + except (av.error.FFmpegError, OSError) as error: + raise ValueError(NOT_A_WORK) from error + if rate is None or Fraction(rate) != 24 or frames <= 0 or size(width, height) is None: + raise ValueError(NOT_A_WORK) + return dict(width=width, height=height, frames=frames, sound=sound) + + +def needed_bytes(frames): + # 4K at CRF 18 measured about 0.1 MB a frame; four times that, and room for the file system. + return frames * 400_000 + 256 * 2**20 + + +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, *, inherit=False): + from .locking import runtime_lock + while True: + check() + try: + lease = runtime_lock(path, inherit=inherit) + lease.__enter__() + break + except BlockingIOError: + time.sleep(.1) + try: + yield + finally: + lease.__exit__(None, None, None) + + +def remote(spec, row): + """Every source for the weights, the ones reachable from China first (Parker 11-18). None of them is the + authors' own model hub: each copy is pinned and accepted only with the catalog's size and SHA-256.""" + from .network import source_url + hf = '/%s/resolve/%s/%s' % (spec['repo'], spec['revision'], row['file']) + mirror = spec['modelscope'] + return dict(repo=spec['repo'], revision=spec['revision'], file=row['file'], family='image', sources=[ + dict(id='modelscope', url=source_url('image-models', 'modelscope') + '/models/%s/resolve/%s/%s' % ( + mirror['repo'], mirror['revision'], row['file'])), + dict(id='hf-mirror', url=source_url('models', 'hf-mirror') + hf), + dict(id='github', url=spec['github']), + dict(id='official', url=source_url('models', 'official') + hf)]) + + +def ensure_weights(root, emit, check): + """The 4.9 MB weights in models/frame-upscale, fetched with the same transfer and source settings as other + optional models; a wrong size or SHA-256 is refused.""" + from . import network + from .adaln_assets import _download_plan + spec = catalog() + row = spec['files'][0] + folder = Path(root) / 'models' / 'frame-upscale' + path = folder / row['file'] + folder.mkdir(parents=True, exist_ok=True) + 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'] = [{'id': 'modelscope'}, {'id': 'hf-mirror'}, {'id': 'github'}, {'id': 'official'}] + plan.update(quiet=True, resource_check=check) + + def moved(current, total, speed, **_): + emit(stage=STAGE, label='Downloading the upscale model', done=current, total=row['bytes'], unit='bytes', + bytes_per_second=speed, downloading=True) + 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=16 * 1024) + except Exception as error: + from .sampling_assets import _cancel_or_disk + if _cancel_or_disk(error): + raise + check() + raise UpscaleError('upscale_download', 'The 4K upscale model could not be downloaded. Check the connection or ' + 'choose another download source in Settings, then try again. Or put the official ' + 'realesr-general-x4v3.pth (%d bytes, SHA-256 %s) in %s' % (row['bytes'], row['sha256'], folder)) from error + if path.stat().st_size != row['bytes'] or _digest(path, check) != row['sha256']: + raise UpscaleError('upscale_download', 'The 4K upscale model failed its size/SHA-256 check: ' + str(path)) + return path + + +def network_model(): + """SRVGGNetCompact as in Real-ESRGAN (realesrgan/archs/srvgg_arch.py at the catalog's source_commit), + inference only: 64 features, 32 convolutions with PReLU, x4 by pixel shuffle over a nearest-neighbour base.""" + import torch + from torch import nn + from torch.nn import functional + + class SRVGGNetCompact(nn.Module): + def __init__(self, num_feat=64, num_conv=32, upscale=SCALE): + super().__init__() + self.upscale = upscale + body = [nn.Conv2d(3, num_feat, 3, 1, 1), nn.PReLU(num_parameters=num_feat)] + for _ in range(num_conv): + body += [nn.Conv2d(num_feat, num_feat, 3, 1, 1), nn.PReLU(num_parameters=num_feat)] + body.append(nn.Conv2d(num_feat, 3 * upscale * upscale, 3, 1, 1)) + self.body = nn.ModuleList(body) + self.upsampler = nn.PixelShuffle(upscale) + + def forward(self, x): + out = x + for layer in self.body: + out = layer(out) + return self.upsampler(out) + functional.interpolate(x, scale_factor=self.upscale, mode='nearest') + + return SRVGGNetCompact() + + +def load(weights, device): + import torch + model = network_model() + model.load_state_dict(torch.load(weights, map_location='cpu', weights_only=True)['params'], strict=True) + model = model.eval().to(device) + return model.half() if device != 'cpu' else model + + +def enlarge(model, picture, scale=SCALE, tile=TILE, pad=PAD): + """picture: 1x3xHxW in [0, 1]; tiles of tile x tile with pad pixels of overlap, joined without seams.""" + import torch + _, _, height, width = picture.shape + if height <= tile and width <= tile: + return model(picture) + out = torch.empty((1, 3, height * scale, width * scale), dtype=picture.dtype, device=picture.device) + for top in range(0, height, tile): + for left in range(0, width, tile): + bottom, right = min(top + tile, height), min(left + tile, width) + y0, x0, y1, x1 = max(top - pad, 0), max(left - pad, 0), min(bottom + pad, height), min(right + pad, width) + piece = model(picture[:, :, y0:y1, x0:x1]) + oy, ox = (top - y0) * scale, (left - x0) * scale + out[:, :, top * scale:bottom * scale, left * scale:right * scale] = \ + piece[:, :, oy:oy + (bottom - top) * scale, ox:ox + (right - left) * scale] + return out + + +def write(source, target, video, frame, emit, check): + """Read the 24 fps source frame by frame, write frame(rgb) at the 4K size with libx264, copy its sound packets + unchanged and interleaved. Memory: one source and one output frame.""" + import av + import numpy as np + width, height = size(video['width'], video['height']) + with av.open(str(source)) as reader, av.open(str(source)) as sound_reader: + stream = reader.streams.video[0] + 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: + picture_stream = output.add_stream('libx264', rate=24) + picture_stream.width, picture_stream.height, picture_stream.pix_fmt = width, height, 'yuv420p' + picture_stream.options = {'crf': '18', 'preset': 'fast'} + 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): + 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 + + count = 0 + for decoded in reader.decode(stream): + check() + if count >= video['frames']: + raise ValueError('The source video changed while it was being upscaled') + pixels = frame(decoded.to_ndarray(format='rgb24'), width, height) + if pixels.shape != (height, width, 3): + raise ValueError('The upscale model returned a picture of the wrong size') + picture = av.VideoFrame.from_ndarray(np.ascontiguousarray(pixels), format='rgb24') + picture.pts, picture.time_base = count, Fraction(1, 24) + sound_until(count / 24) + for packet in picture_stream.encode(picture): + output.mux(packet) + count += 1 + emit(done=count, total=video['frames'], unit='frames', downloading=False) + for packet in picture_stream.encode(None): + check() + output.mux(packet) + sound_until(None) + if count != video['frames']: + raise ValueError('The source video changed while it was being upscaled') + return count + + +def model_frame(weights, device): + """frame(rgb uint8 HxWx3, width, height) -> uint8 at width x height, by the model in this process.""" + import torch + from torch.nn import functional + model = load(weights, device) + dtype = torch.float16 if device != 'cpu' else torch.float32 + + @torch.inference_mode() + def frame(rgb, width, height): + try: + picture = torch.from_numpy(rgb).to(device).permute(2, 0, 1)[None].to(dtype).div_(255) + larger = enlarge(model, picture) + fitted = functional.interpolate(larger.float(), size=(height, width), mode='bicubic', antialias=True, + align_corners=False) + return fitted.clamp_(0, 1).mul_(255).round_().to(torch.uint8)[0].permute(1, 2, 0).contiguous().cpu().numpy() + except torch.OutOfMemoryError as error: + raise UpscaleError('upscale_memory', 'Not enough GPU memory to upscale to 4K. Close other programs that use ' + 'the GPU, then try again') from error + return frame + + +def _convert(request, emit, check): + from .disk_space import free_bytes + source, root, work, target = Path(request['source']), Path(request['root']), Path(request['work']), Path(request['target']) + device = request.get('device', 'cuda') + video = inspect(source) + if free_bytes(target.parent) < needed_bytes(video['frames']): + raise UpscaleError('upscale_disk', 'Not enough disk space to save the 4K video (about %d MB is needed). Free some ' + 'space on the drive that holds the output folder, then try again' + % (needed_bytes(video['frames']) // 10**6)) + weights = ensure_weights(root, emit, check) + import torch + if device == 'cuda': + if not torch.cuda.is_available(): + raise RuntimeError('CUDA is unavailable for the 4K upscale') + # Models other requests keep in the GPU stay unless this small one does not fit beside them. + if torch.cuda.mem_get_info()[0] < NEEDED_GPU_BYTES: + emit(stage=STAGE, label='Upscaling to 4K', waiting_for_device=True) + while not (work / 'device-ready').is_file(): + check() + time.sleep(.05) + elif device == 'mps' and not torch.backends.mps.is_available(): + raise RuntimeError('Metal is unavailable for the 4K upscale') + torch.set_num_threads(min(8, os.cpu_count() or 1)) + emit(stage=STAGE, label='Upscaling to 4K', done=0, total=video['frames'], unit='frames', waiting_for_device=False) + frame = model_frame(weights, device) + started = time.monotonic() + if device == 'cuda': + torch.cuda.reset_peak_memory_stats() + frames = write(source, target, video, frame, emit, check) + return dict(frames=frames, width=size(video['width'], video['height'])[0], height=size(video['width'], video['height'])[1], + seconds=round(time.monotonic() - started, 2), device=device, model='realesr-general-x4v3', + weights_sha256=catalog()['files'][0]['sha256'], tile=TILE, sound=video['sound'], + torch_peak_reserved_bytes=torch.cuda.max_memory_reserved() if device == 'cuda' else None, + torch=torch.__version__) + + +def upscale(source, target, *, root, device='cuda', python=None, environ=None, progress=None, interrupted=None, + release_models=None): + """Upscale in a supervised child, writing target; returns the child's summary. + + progress receives {stage, label, done, total, unit}: bytes while the model downloads, then frames. Cancelling + stops the whole child tree; a partly written target is removed. + """ + root, target = Path(root).resolve(), Path(target) + + def check(): + if interrupted: + interrupted() + check() + with tempfile.TemporaryDirectory(prefix='.frame-upscale-', dir=target.parent) as directory: + work = Path(directory) + request = dict(source=str(Path(source).resolve()), root=str(root), work=str(work), target=str(target), device=device) + (work / 'request.json').write_text(json.dumps(request), encoding='utf-8') + command = processes.module_command('freevideo_engine.frame_upscale', '--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, released = None, False + + def poll(): + nonlocal last, released + check() + try: + value = json.loads((work / 'progress.json').read_text(encoding='utf-8')) + except (OSError, ValueError): + return + if value.get('waiting_for_device') and not released: + if release_models: + release_models() + check() + (work / 'device-ready').touch() + released = True + if progress and value != last: + progress({key: val for key, val in value.items() if key != 'waiting_for_device'}) + 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 = {} + message = error.get('error') or 'The 4K upscale worker exited with code %s' % child.returncode + if error.get('code'): + raise UpscaleError(error['code'], message) + raise RuntimeError(message) + return json.loads((work / 'result.json').read_text(encoding='utf-8')) + except BaseException: + (work / 'cancelled').touch() + processes.stop(child) + target.unlink(missing_ok=True) + raise + + +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('4K upscale cancelled') + state = dict(stage=STAGE, phase=STAGE, label='Upscaling to 4K', done=0, total=None, unit='frames') + + def emit(**values): + state.update(values) + save(work / 'progress.json', state) + try: + with processes.worker_signals(): + result = _convert(request, emit, check) + save(work / 'result.json', result) + except Exception as error: + save(work / 'error.json', dict(error=str(error) if isinstance(error, UpscaleError) else type(error).__name__ + ': ' + str(error), + code=getattr(error, 'code', None))) + return 1 + return 0 + + +if __name__ == '__main__': + raise SystemExit(main()) diff --git a/freevideo_engine/frame_upscale_model.json b/freevideo_engine/frame_upscale_model.json new file mode 100644 index 00000000..5579bee7 --- /dev/null +++ b/freevideo_engine/frame_upscale_model.json @@ -0,0 +1,13 @@ +{ + "repo": "jhj0517/realesr-general-x4v3", + "revision": "7692becfa754463a664911bad7dee11f7ee1ddbb", + "source_commit": "685d429c81888252bdb10f56c7754baededc3823", + "license": "BSD-3-Clause", + "modelscope": {"repo": "muse/realesr-general-x4v3", "revision": "20240108175051"}, + "github": "https://github.com/xinntao/Real-ESRGAN/releases/download/v0.2.5.0/realesr-general-x4v3.pth", + "files": [{ + "file": "realesr-general-x4v3.pth", + "bytes": 4885111, + "sha256": "8dc7edb9ac80ccdc30c3a5dca6616509367f05fbc184ad95b731f05bece96292" + }] +} diff --git a/freevideo_engine/generate.py b/freevideo_engine/generate.py index e67c11b8..62059132 100644 --- a/freevideo_engine/generate.py +++ b/freevideo_engine/generate.py @@ -538,6 +538,13 @@ def usable_continuation(value, *check): from .media_request import read as read_media, task_for, cache_key from .original_audio import cli_media, prepare_request media = cli_media(args, read_media(getattr(args, 'media', None))) + upscale_work = None + if getattr(args, 'upscale_from', None): + # A finished video upscaled by one step: its own frames are the first pass + # and its own sound, cut to its pictures, is used as is (work_upscale). + from .work_upscale import media as work_media, source as work_source + upscale_work = work_source(args.upscale_from) + media = work_media(media, upscale_work) original_audio, original_canvas = prepare_request(media, getattr(args, 'width', 1344), getattr(args, 'height', 768), continuation=continue_from is not None) if continue_from is not None and frames is not None: @@ -564,6 +571,15 @@ def usable_continuation(value, *check): from .preview import validate_flags, source as preview_source validate_flags(preview, getattr(args, 'refine_from', None), two_pass, requested_steps) refine_source = preview_source(args.refine_from) if getattr(args, 'refine_from', None) else None + if upscale_work: + if preview or getattr(args, 'refine_from', None) or continue_from is not None or not two_pass: + raise ValueError('An upscale of a finished video is a request of its own') + if upscale_factor(args) != 1.5 or (requested_steps or 8) != 8 or refine_steps != 3: + raise ValueError('A finished video is upscaled with --upscale-factor 1.5 and the default steps') + if getattr(args, 'step_cache', None) not in (None, 'none'): + raise ValueError('An upscale of a finished video samples every step') + if original_audio is None or Path(original_audio['path']) != Path(upscale_work['output']): + raise ValueError("An upscale keeps the video's own sound") if requested_steps is not None: validate_steps(requested_steps, refine_steps, two_pass) if requested_steps != 8: @@ -582,7 +598,7 @@ def usable_continuation(value, *check): # Too small to sample cleanly: render larger, scale the picture down. Decided before anything # compares or stores the canvas, so every later check sees the size that is sampled. from .two_pass import sampling_canvas - canvas, output_size = sampling_canvas(canvas, staged=bool(preview or refine_source), media=media, + canvas, output_size = sampling_canvas(canvas, staged=bool(preview or refine_source or upscale_work), media=media, conditioned=bool(args.conditioning)) if continue_from is not None: validate_route(task=getattr(args, 'task', None) or ('ref2va' if anchored else 't2va'), @@ -689,7 +705,7 @@ def usable_continuation(value, *check): # The optional tail must fit this size/step tier too. Re-admit the # original duration before encoding anything; never shorten it. canvas, output_size = sampling_canvas(dict(canvas, **visible_canvas), - staged=bool(preview or refine_source), media=media, conditioned=bool(args.conditioning)) + staged=bool(preview or refine_source or upscale_work), media=media, conditioned=bool(args.conditioning)) hardware, resident_credit, profile = automatic_profile(args, canvas, stage='before-encoding', evidence=planning) hide_tail, hide_tail_frames = dict(requested=True, used=False, reason='too_long'), 0 if continuation is not None: @@ -729,7 +745,7 @@ def usable_continuation(value, *check): validate_route(task=profile['engine'].get('task', 't2va'), anchor=anchored, original_audio=original_audio is not None) planned = continuation_plan(canvas, two_pass, base_steps=base_steps, refine_steps=refine_steps, - staged=bool(preview or refine_source), scale=upscale_factor(args)) + staged=bool(preview or refine_source or upscale_work), scale=upscale_factor(args)) if two_pass and not planned['enabled'] and base_steps != 8: raise ValueError(planned['reason'] + ' A continuation needs two-pass generation.') continuation_first = planned['first'] @@ -1027,10 +1043,16 @@ def interrupted(signum, frame): if not condition.is_file(): raise FileNotFoundError(condition) from .two_pass import plan as plan_sampling, ensure_checkpoint + from .refine_schedule import UPSCALE sampling_plan = plan_sampling(canvas, two_pass, profile['engine'].get('task', 't2va'), base_steps=base_steps, refine_steps=refine_steps, - staged=bool(preview or refine_source), scale=upscale_factor(args)) + staged=bool(preview or refine_source or upscale_work), scale=upscale_factor(args), + schedule=UPSCALE if upscale_work else None) report['sampling_plan'] = sampling_plan + if upscale_work: + from .work_upscale import check as check_upscale + check_upscale(upscale_work, canvas, sampling_plan) + report['upscaled_work'] = dict(output=upscale_work['output']) if continuation is not None: validate_route(task=profile['engine'].get('task', 't2va'), anchor=anchored, original_audio=original_audio is not None, @@ -1149,6 +1171,8 @@ def validate(metrics, telemetry, selected): if original_audio is not None: request['original_audio'] = original_audio report['original_audio'] = original_audio + if upscale_work: + request['upscale_source'] = upscale_work if preview: request['preview'] = True if allocator_limit_bytes is not None: diff --git a/freevideo_engine/image_gen/h3_pipeline.py b/freevideo_engine/image_gen/h3_pipeline.py index 76c334f8..6a04162f 100644 --- a/freevideo_engine/image_gen/h3_pipeline.py +++ b/freevideo_engine/image_gen/h3_pipeline.py @@ -44,7 +44,7 @@ class KeptModels: Keeping them saves loading the 21 GB of weights and the pinned planes again, so the next request starts sampling after its encoding. A model is kept only while the host can still hold it without squeezing the shared encoder and the video model: the cgroup (or the machine) must keep ``HOST_MARGIN`` free after the - weights, and a card below ``MIN_KEEP_VRAM`` gives its resident blocks back to the shared GPU (the host copy + weights, and at least the floor the next picture asks for (``host_floor``), and a card below ``MIN_KEEP_VRAM`` gives its resident blocks back to the shared GPU (the host copy stays). Anything that does not fit is closed, which is what every request did before. """ HOST_MARGIN = 10 * 2**30 @@ -97,7 +97,8 @@ def keep(self, role, key, value, stack): small = min(total, self.budget or total) < self.MIN_KEEP_VRAM if role == 'vae' and small: return False - if role == 'dit' and self.host_room() + held < held + self.HOST_MARGIN: + # The same floor take() applies: a model the next picture would give back anyway is not kept. + if role == 'dit' and self.host_room() < max(self.HOST_MARGIN, host_floor()): return False if role == 'dit': if small: diff --git a/freevideo_engine/image_gen/service.py b/freevideo_engine/image_gen/service.py index 2feaef79..5129c77f 100644 --- a/freevideo_engine/image_gen/service.py +++ b/freevideo_engine/image_gen/service.py @@ -747,6 +747,16 @@ def history_delete(self, name): self.works_deleted([name]) return self.history() + @staticmethod + def video_prompts(): + """The prompt hashes the library's videos still use: a prompt a video keeps stays in the history.""" + try: + import folder_paths + from .. import comfy_library + return comfy_library._kept_facts(Path(folder_paths.get_output_directory()) / 'FreeVideo')[1] + except Exception: + return set() + def works_deleted(self, names): """What only a deleted picture had goes with it: its model record, the files and caches it held, and (through the hook the server sets) its library card and ComfyUI's record of the request.""" @@ -764,7 +774,7 @@ def works_deleted(self, names): if gone & set(records): kept = {name: row for name, row in records.items() if name not in gone} save(output / RECORDS_FILE, kept) - kept_prompts = {row.get('prompt_hash') for row in kept.values()} + kept_prompts = {row.get('prompt_hash') for row in kept.values()} | self.video_prompts() private_store.forget_prompts({row.get('prompt_hash') for name, row in records.items() if name in gone} - kept_prompts - {None}) except (OSError, ValueError): @@ -1499,6 +1509,7 @@ def begin(self, key, root, machine, value, context): if self.key is not None: self.remember(self.key, self.state) self.key = key + self.started_at = time.time() self.stop.clear() self.state = dict(phase='starting', stage='start') self.preview = None @@ -1521,6 +1532,9 @@ def discard_queued(self, state, pending=None): pending = pending or self.pending[0] self.drop_uploads(pending['key']) self.remember(pending['key'], state) + # Every way a waiting picture ends without running comes here: cancelled, failed, timed out, or closed. + from .. import job_record + job_record.image(pending['key'], state) self.pending.remove(pending) for place, other in enumerate(self.pending, 1): other['state']['queue_position'] = place @@ -2294,6 +2308,8 @@ def respawn(): self.preview = None self._busy = False self.context = None + from .. import job_record + job_record.image(self.key, self.state, started_at=getattr(self, 'started_at', None)) # The worker is gone, so nothing reads the job's pictures any more. self.drop_uploads(self.key) elif failure_error is not None: @@ -2513,6 +2529,8 @@ def infer(self, session, value): self.state = result self.preview = None self._busy = False + from .. import job_record + job_record.image(self.key, result, started_at=getattr(self, 'started_at', None)) self.context = None # Remove the job's uploads now, not when the page next asks: a page that was stopped, # closed or reloaded never asks again. diff --git a/freevideo_engine/image_gen/worker.py b/freevideo_engine/image_gen/worker.py index 9368a994..ace2e0e9 100644 --- a/freevideo_engine/image_gen/worker.py +++ b/freevideo_engine/image_gen/worker.py @@ -296,6 +296,7 @@ def serve(pack_dir, *, device='cuda', idle_seconds=45., stream=None, output=None h3_factory = h3_factory or load_h3_runner moss_factory = moss_factory or load_moss_runner runner_model = None + factories = {'minimax-h3-image': h3_factory, 'moss-image-sft': moss_factory} output_mutex = threading.Lock() def send(**row): @@ -337,7 +338,7 @@ def send(**row): runner = drop(runner) if load and runner is None: # No progress rows: nothing on the page is waiting for this. - runner = (h3_factory if model == 'minimax-h3-image' else factory)(pack_dir, device) + runner = factories.get(model, factory)(pack_dir, device) runner_model = model warm_up(runner, value, should_stop, send) except Exception as error: @@ -366,7 +367,7 @@ def progress(stage, fraction): runner = drop(runner) if runner is None: context.timing.enter('load') - runner = {'minimax-h3-image': h3_factory, 'moss-image-sft': moss_factory}.get(model, factory)(pack_dir, device, progress=progress) + runner = factories.get(model, factory)(pack_dir, device, progress=progress) runner_model = model if hasattr(runner, 'last_plan'): runner.last_plan = None diff --git a/freevideo_engine/installation_cleanup.py b/freevideo_engine/installation_cleanup.py index bb88a0bd..512ba558 100644 --- a/freevideo_engine/installation_cleanup.py +++ b/freevideo_engine/installation_cleanup.py @@ -195,7 +195,10 @@ def work(): except BlockingIOError: self.state = dict(status='busy', bytes=0, error='') except Exception as error: - self.state = dict(status='error', bytes=0, error=redacted_launcher_error(str(error))) + from .package_cleanup import failure_reason + # The code picks the sentence; the redacted text stays for "Copy details" and the report. + self.state = dict(status='error', bytes=0, reason=failure_reason(error), + error=redacted_launcher_error(str(error))) # If the window closes, finish the current tool operation and release # its leases before Python exits; do not abandon a half-cleaned cache. self.thread = threading.Thread(target=work, name='freevideo-storage') diff --git a/freevideo_engine/job_record.py b/freevideo_engine/job_record.py new file mode 100644 index 00000000..2454eeda --- /dev/null +++ b/freevideo_engine/job_record.py @@ -0,0 +1,151 @@ +"""Where a generation ends, write its line in the finished-job record (jobs_journal.py). + +Three things run generations outside the Agent's job store, and each ends here once: a video the creation panel +queued in ComfyUI (the FreeVideo node, or the multi-GPU front when the node runs in a worker), a long video's chain, +and a picture. The Agent's own jobs keep their own durable records and are not written twice; a long video the Agent +asked for is still recorded once, as its chain. + +Only ids, short codes, times and a saved video's library id are passed on, and jobs_journal drops anything else. +Nothing here ever raises: a record that cannot be written never touches the job. +""" +import functools +import logging +import re +import time +from pathlib import Path, PurePosixPath + +_LOG = logging.getLogger(__name__) +LIBRARY = re.compile(r'[0-9]{4}-[0-9]{2}-[0-9]{2}') + + +def output_root(): + """The output folder the /freevideo/jobs route reads the record from, or None outside ComfyUI.""" + try: + import folder_paths + return Path(folder_paths.get_output_directory()) + except Exception: + return None + + +def library_id(relative): + """'YYYY-MM-DD/' for a saved video under FreeVideo///..., else None.""" + try: + parts = PurePosixPath(str(relative).replace('\\', '/')).parts + except (TypeError, ValueError): + return None + if len(parts) >= 3 and parts[0] == 'FreeVideo' and LIBRARY.fullmatch(parts[1]): + return parts[1] + '/' + parts[2] + return None + + +def ended(identity, kind, status, *, origin='page', created_at=None, started_at=None, result=None, failure=None, + root=None): + """Record that a job ended. status: done, failed, cancelled or interrupted.""" + try: + root = root if root is not None else output_root() + if root is None or not identity: + return + from . import jobs_journal + jobs_journal.append(dict(id=str(identity), kind=kind, origin=origin, status=status, created_at=created_at, + started_at=started_at, finished_at=time.time(), result=result, failure=failure), + root=Path(root)) + except Exception: + _LOG.warning('A finished job could not be recorded.', exc_info=True) + + +def failure_code(error): + """A short code for an exception: its class name, never its message (which may hold a prompt or a path).""" + name = type(error).__name__ + return name if re.fullmatch(r'[A-Za-z0-9_]{1,64}', name) else 'error' + + +def interrupted(error): + """ComfyUI's stop button raises this; it is a cancellation, not a failure.""" + return type(error).__name__ in ('InterruptProcessingException', 'KeyboardInterrupt') + + +def _summary_video(output): + """The saved video's path from the node's result, read defensively.""" + try: + ui = getattr(output, 'ui', None) or {} + summary = (ui.get('freevideo_summary') or [None])[0] or {} + return summary.get('video') + except (AttributeError, TypeError, IndexError): + return None + + +def video_node(execute): + """Wrap the FreeVideo node's execute: one record per creation-panel video, written by the server process. + + Not written: a part of a long video (its chain is recorded once), and a run in a multi-GPU worker (the front in + the control process records it).""" + @functools.wraps(execute) + def run(cls, *args, **kwargs): + context = _video_start(cls) + try: + output = execute(cls, *args, **kwargs) + except BaseException as error: + if context is not None: + ended(context['id'], 'video', 'cancelled' if interrupted(error) else 'failed', origin=context['origin'], + started_at=context['started_at'], failure=None if interrupted(error) else failure_code(error)) + raise + if context is not None: + ended(context['id'], 'video', 'done', origin=context['origin'], started_at=context['started_at'], + result=library_id(_summary_video(output))) + return output + return run + + +def _video_start(cls): + try: + from .comfy_environment import executor_device + if executor_device(): + return None + from server import PromptServer + server = PromptServer.instance + prompt_id = getattr(server, 'last_prompt_id', None) + if not prompt_id: + return None + from .comfy_chain import block_context + if block_context(server, cls.hidden.unique_id) is not None: + return None + agent = str(getattr(server, 'client_id', '') or '').startswith('agent:') + return dict(id=str(prompt_id), origin='agent' if agent else 'page', started_at=time.time()) + except Exception: + return None + + +CHAIN_STATUS = dict(done='done', failed='failed', cancelled='cancelled', interrupted='interrupted') + + +def chain(record, store_dir): + """A chain that reached its end. Its parts are not recorded on their own.""" + status = CHAIN_STATUS.get(record.get('state')) + if status is None or record.get('output_state') == 'joining' or status == 'done' and record.get('output_state') == 'pending': + return + if status == 'done' and record.get('output_state') == 'failed': + status = 'failed' + client = str(record.get('client_id') or '') + try: + root = Path(store_dir).parents[1] # /FreeVideo/.chains + except IndexError: + return + created = record.get('created') + ended(record.get('id'), 'chain', status, origin='agent' if client.startswith('agent:') else 'page', + created_at=created if isinstance(created, (int, float)) else None, + result=library_id(record.get('output')) if status == 'done' else None, + failure='join_failed' if status == 'failed' and record.get('output_error') else None, + root=root) + + +IMAGE_STATUS = dict(complete='done', failed='failed', cancelled='cancelled') + + +def image(key, state, started_at=None, root=None): + """A picture job that ended: complete, failed or cancelled.""" + status = IMAGE_STATUS.get((state or {}).get('phase')) + if status is None: + return + error = state.get('error') + code = error if isinstance(error, str) and re.fullmatch(r'[A-Za-z0-9_]{1,64}', error) else 'error' + ended(key, 'image', status, started_at=started_at, failure=code if status == 'failed' else None, root=root) diff --git a/freevideo_engine/launcher/Main.qml b/freevideo_engine/launcher/Main.qml index c4206828..f28e5c35 100644 --- a/freevideo_engine/launcher/Main.qml +++ b/freevideo_engine/launcher/Main.qml @@ -469,6 +469,11 @@ ApplicationWindow { Layout.fillWidth: true; spacing: 8; Layout.bottomMargin: shortWindow ? 0 : 10 FText { objectName: "pageHeading"; horizontalAlignment: Text.AlignHCenter; text: s.page === "launcher" ? t("Your workspace", "工作空间") : s.page === "comfy" ? t("Set up FreeVideo", "安装 FreeVideo") : s.page === "models" ? t("Set up your models", "准备模型") : s.status === "review" ? t("Ready to install", "确认安装") : s.busy ? t("Setting things up", "正在准备 FreeVideo") : t("Continue your setup", "继续安装"); font.pixelSize: win.compact ? 26 : theme.hero; font.weight: Font.DemiBold; font.letterSpacing: -0.6; Layout.fillWidth: true } FText { objectName: "actionNotice"; visible: !!s.action_notice; text: s.action_notice || ""; color: theme.muted; Layout.fillWidth: true; horizontalAlignment: Text.AlignHCenter } + RowLayout { + objectName: "mainPageAddress"; visible: s.action_notice_key === "update_page_failed" && !!(s.update && s.update.release_page); Layout.fillWidth: true; spacing: 8 + FText { text: (s.update && s.update.release_page) || ""; color: theme.text; elide: Text.ElideMiddle; Layout.fillWidth: true } + FButton { text: t("Copy address", "复制地址"); flat: true; implicitHeight: theme.heightSm; onClicked: backend.copy(s.update.release_page) } + } } FText { objectName: "operationBusyReason"; visible: !s.can_manage && !s.action_notice; text: s.busy_reason; color: theme.muted; Layout.fillWidth: true; horizontalAlignment: Text.AlignHCenter } @@ -488,7 +493,7 @@ ApplicationWindow { } ColumnLayout { id: failureBody; x: 18; y: 18; width: parent.width - 36; spacing: 10 - FText { text: s.failure.title || t("Something went wrong", "出现问题"); color: theme.danger; font.weight: Font.DemiBold; Layout.fillWidth: true } + FText { text: s.failure.title || t("Couldn’t complete this step", "暂时未能完成"); color: theme.danger; font.weight: Font.DemiBold; Layout.fillWidth: true } FText { visible: !!(s.failure.detail || s.failure.action); text: s.failure.detail || s.failure.action; color: theme.text; Layout.fillWidth: true } FText { visible: !!s.failure.note; text: s.failure.note || ""; color: theme.muted; Layout.fillWidth: true } // What each download source returned: one short line per source. @@ -1082,7 +1087,7 @@ ApplicationWindow { } FText { objectName: "imagePackEngineNote"; visible: s.image_pack.engine_state === "running"; text: s.image_pack.engine_note; color: s.image_pack.engine_clicked ? theme.danger : theme.muted; Layout.fillWidth: true } FText { objectName: "imagePackFailureReason"; visible: s.image_pack.install.state === "failed"; text: s.image_pack.detail; color: theme.danger; Layout.fillWidth: true } - FButton { objectName: "imagePackReport"; visible: s.image_pack.install.state === "failed"; text: reportOpened(s.image_pack.detail || "", t("Image pack", "图像模型包")) ? t("Opened", "已打开") : t("Report a problem", "提交问题"); widthText: t("Report a problem", "提交问题"); enabled: !reportOpened(s.image_pack.detail || "", t("Image pack", "图像模型包")); onClicked: backend.reportProblem(s.image_pack.detail || "", t("Image pack", "图像模型包")) } + FButton { objectName: "imagePackReport"; visible: s.image_pack.install.state === "failed"; text: reportOpened((s.image_pack.detail || "") + (s.image_pack.report_line ? "\n" + s.image_pack.report_line : ""), t("Image pack", "图像模型包")) ? t("Opened", "已打开") : t("Report a problem", "提交问题"); widthText: t("Report a problem", "提交问题"); enabled: !reportOpened((s.image_pack.detail || "") + (s.image_pack.report_line ? "\n" + s.image_pack.report_line : ""), t("Image pack", "图像模型包")); onClicked: backend.reportProblem((s.image_pack.detail || "") + (s.image_pack.report_line ? "\n" + s.image_pack.report_line : ""), t("Image pack", "图像模型包")) } Flow { visible: s.image_pack.install.state === "failed" && !!s.image_pack.report_id Layout.fillWidth: true; spacing: 8 @@ -1449,7 +1454,7 @@ ApplicationWindow { s.cleanup.status === "ready" ? (s.cleanup.bytes > 0 ? t("About ", "约 ") + bytes(s.cleanup.bytes) + t(" can be freed. Models, environments and videos are kept.", " 可清理,保留模型、运行环境和视频。") : t("Nothing to clean.", "暂无可清理的下载缓存。")) : s.cleanup.status === "complete" ? t("Freed ", "已释放 ") + bytes(s.cleanup.released_bytes || 0) + (s.cleanup.skipped ? t(". Some files changed; check again.", "。部分文件已变化,请重新检查。") : t(".", "。")) : s.cleanup.status === "busy" ? t("Another task is using these files. Try again when it finishes.", "其他任务正在使用这些文件,完成后可重试。") : - s.cleanup.status === "error" ? t("Cleanup could not finish. Check again to retry.", "清理未完成,可重新检查后再试。") : + s.cleanup.status === "error" ? (s.cleanup.message || t("Cleanup could not finish. Check again to retry.", "清理未完成,可重新检查后再试。")) : t("Installation files kept for repairs. Models, environments and videos are never removed.", "安装时缓存的文件,清理时不会删除模型、运行环境和视频。") } } @@ -1738,7 +1743,12 @@ ApplicationWindow { } FText { objectName: "downloadActionNotice"; visible: !!s.action_notice && s.action_notice !== s.busy_reason; text: s.action_notice || ""; color: theme.muted; Layout.fillWidth: true } FText { objectName: "downloadListError"; visible: text.length > 0; text: s.download_list.error; color: theme.danger; Layout.fillWidth: true; wrapMode: Text.WordWrap; font.pixelSize: theme.micro + 1 } - FText { objectName: "downloadListRawError"; visible: s.error.length > 0 && !s.download_list.inspection_failed; text: s.error; color: theme.danger; Layout.fillWidth: true; maximumLineCount: 2; elide: Text.ElideRight; font.pixelSize: theme.micro } + // The failure card's own sentence, never the raw error (a traceback's first lines); the card below the dialog has the rest. + RowLayout { + visible: s.error.length > 0 && !s.download_list.inspection_failed; Layout.fillWidth: true; spacing: 8 + FText { objectName: "downloadListRawError"; text: (s.failure && (s.failure.detail || s.failure.title)) || t("Couldn’t complete this step", "暂时未能完成"); color: theme.danger; Layout.fillWidth: true; maximumLineCount: 2; elide: Text.ElideRight; font.pixelSize: theme.micro } + FButton { objectName: "downloadListFailureDetails"; text: t("Details and report", "详情与提交问题"); flat: true; implicitHeight: theme.heightSm; font.pixelSize: theme.micro + 1; onClicked: modelInfoOpen = false } + } } } FText { objectName: "downloadBusyReason"; visible: !s.can_manage && (!s.action_notice || s.action_notice === s.busy_reason); text: s.busy_reason; color: theme.muted; Layout.fillWidth: true } @@ -1849,6 +1859,11 @@ ApplicationWindow { id: updateContents; width: updateScroll.availableWidth - updateScroll.ScrollBar.vertical.width spacing: 14 FText { objectName: "updateActionNotice"; visible: !!s.action_notice; text: s.action_notice || ""; color: theme.muted; Layout.fillWidth: true } + RowLayout { + objectName: "updatePageAddress"; visible: s.action_notice_key === "update_page_failed" && !!(s.update && s.update.release_page); Layout.fillWidth: true; spacing: 8 + FText { text: (s.update && s.update.release_page) || ""; color: theme.text; elide: Text.ElideMiddle; Layout.fillWidth: true } + FButton { text: t("Copy address", "复制地址"); flat: true; implicitHeight: theme.heightSm; onClicked: backend.copy(s.update.release_page) } + } RowLayout { Layout.fillWidth: true // An update is named by its version in the notes below; the window has no title for it. @@ -1867,7 +1882,7 @@ ApplicationWindow { } FMeter { Layout.fillWidth: true; visible: s.update.status === "downloading"; active: true; fraction: s.update.progress && s.update.progress.total ? s.update.progress.done/s.update.progress.total : -1 } FReleaseNotes { objectName: "updateReleaseNotes"; visible: !!availableRelease; Layout.fillWidth: true; room: updateDialog.availableWidth; release: availableRelease; earlier: availableEarlier; zh: s.zh; heading: releaseVersion(availableRelease) } - FButton { text: t("Version & release notes", "版本与更新说明"); flat: true; onClicked: releaseNotesOpen = true } + FButton { text: t("Version & release notes", "版本与更新说明"); flat: true; Layout.maximumWidth: updateContents.width; onClicked: releaseNotesOpen = true } } } FScrollFade { objectName: "updateDialogFade"; view: updateScroll; barWidth: updateScroll.ScrollBar.vertical.width } diff --git a/freevideo_engine/launcher_copy.py b/freevideo_engine/launcher_copy.py index f543545a..967bc8f5 100644 --- a/freevideo_engine/launcher_copy.py +++ b/freevideo_engine/launcher_copy.py @@ -18,7 +18,10 @@ 'checking_update': ('Checking for updates. Please wait.', '正在检查更新,请稍候'), 'update_install_failed': ('The update could not be installed. You can keep using the current version.', '无法安装更新。当前版本可以照常使用。'), - 'update_page_failed': ('Couldn\'t open the download page. Please try again later.', '无法打开下载页,请稍后再试。'), + 'drop_local_zip': ('Only ZIP files saved on this computer can be imported. Download the package first, then drag it here.', + '只能导入已保存到本机的 ZIP 文件。请先下载离线包,再把它拖到这里。'), + 'update_page_failed': ('The browser did not open. Copy the release page address below and open it in your browser.', + '浏览器未能打开。请复制下面的发布页地址,在浏览器里打开。'), 'busy': ('The background task is busy. You can do this when it finishes.', '后台正在忙,完成后可以操作'), 'import_queued': ('Saved. Importing will start when the current task finishes.', diff --git a/freevideo_engine/launcher_session.py b/freevideo_engine/launcher_session.py index 5ba9a38a..4d1c67e5 100644 --- a/freevideo_engine/launcher_session.py +++ b/freevideo_engine/launcher_session.py @@ -38,6 +38,27 @@ # a newer release reminds at once. SNOOZE_SECONDS = 365 * 24 * 3600 QUEUE_POLL_SECONDS = 3 + + +_last_logged = [None] + + +def log_error(trace, root=None): + """Keep every launcher failure on disk, errors/launcher-.log, so one that is dismissed or never read still leaves a trace. + + Returns the file, or None when the same failure was just written (a refresh that fails every tick) or the disk refuses. + """ + text = plain_text(trace) + if not text or text == _last_logged[0]: + return None + try: + path = Path(root or launcher_root()) / 'errors' / ('launcher-' + str(time.time_ns()) + '.log') + io_path(path.parent).mkdir(parents=True, exist_ok=True) + io_path(path).write_text(text, encoding='utf-8') + except OSError: + return None + _last_logged[0] = text + return path RECEIPT_POLL_SECONDS = 5 @@ -46,7 +67,19 @@ 'changed': ('The file changed after the check, so it was kept.', '文件在检查后有改动,已保留。'), 'busy': ('An installation or a video is in progress. Try again when it finishes.', '有安装或生成正在进行,完成后可以再删除。'), 'in-use': ('Another program is using it, or this account does not have permission to delete it.', '正被其他程序使用,或当前账户没有删除权限。'), - 'failed': ('It could not be deleted.', '未能删除。'), + 'failed': ('It could not be deleted. Check again; if it happens again, use "Report a problem".', + '未能删除。请重新检查;如果再次出现,请点击“提交问题”。'), +} +# Storage cleanup by package_cleanup.failure_reason code. +CLEANUP_FAILURES = { + 'changed': ('Cleanup stopped because files changed after the check. Check again, then clean.', + '检查之后文件有变化,清理已停止。请重新检查后再清理。'), + 'busy': ('An installation or a video is in progress. Try again when it finishes.', '有安装或生成正在进行,请在完成后再清理。'), + 'in-use': ('Cleanup could not finish: some files are in use by another program, or this account cannot delete them. ' + 'Close the programs using them, then check again.', + '清理未完成:部分文件正被其他程序使用,或当前账户没有删除权限。请关闭正在使用它们的程序,再重新检查。'), + 'failed': ('Cleanup could not finish because of an unexpected error. Check again; if it happens again, use ' + '"Report a problem".', '清理因意外错误未完成。请重新检查;如果再次出现,请点击“提交问题”。'), } # Report exports that failed for a reason the user can act on; anything else keeps its own words. EXPORT_FAILURES = { @@ -56,6 +89,8 @@ 'Close that program, or choose another name.', '原文件正被其他程序打开或为只读,未被替换。请关闭该程序,或换一个文件名。'), 'disk': ('Not enough disk space. Free up space, then export again.', '磁盘空间不足,请释放空间后再导出。'), + 'other': ('The report could not be saved. Choose another folder, or use "Copy details" and paste them into the issue.', + '报告未能保存。请换一个文件夹,或改用“复制详情”,把内容贴到问题里。'), } @@ -1035,7 +1070,7 @@ def image_pack_view(self, model='image'): return dict(installable=False, ready=False, state='missing', visible=False, busy=False, downloaded_bytes=0, verified_bytes=0, total_bytes=total, bytes=total, title=self.t(*title), detail=self.t('Not installed', '未安装'), - install={}, can_act=False, removable_bytes=0, repairable=False, failure={}, report_id=None, + install={}, can_act=False, removable_bytes=0, repairable=False, failure={}, report_id=None, report_line='', engine_state='unknown', engine_note='', engine_clicked=False) root, engine = self._image_location() try: @@ -1081,10 +1116,20 @@ def image_pack_view(self, model='image'): detail=detail, busy=busy, install=active, can_act=not (blocked or busy or value.get('checking')), removable_bytes=removable, repairable=repairable, failure=failure, report_id=active.get('report_id'), + report_line=self._image_pack_report_line(), engine_state=engine_state, engine_note=image_pack_failure('busy_engine', zh=self.language.startswith('zh'))['detail'] if running else '', engine_clicked=running and self.image_engine_clicked) + def _image_pack_report_line(self): + """Where and how the pack operation stopped, for the issue form: stage, code and exception class only.""" + report = self.image_pack_report() + if not report: + return '' + error = report.get('error') or {} + parts = [str(report.get('stage_at_failure') or ''), str(error.get('code') or ''), str(error.get('class') or '')] + return 'Image pack: ' + ', '.join(part for part in parts if part) + def image_pack_report(self): if self.image_installer: root, engine = self._image_location() @@ -1303,7 +1348,9 @@ def _tick_model_upgrade(self, row, busy): else: # Setup marks the installation unfinished when it starts; then # Retry on the setup page restores the previous model. - upgrade.switch_failed(row.get('error') or self.t('The switch stopped.', '切换未完成。'), + upgrade.switch_failed(row.get('error') or self.t( + 'The model switch stopped before it finished. Select Retry on the setup page; if it cannot finish, ' + 'the previous model is restored.', '模型切换未完成。请在安装页点击“重试”;无法完成时会恢复原来的模型。'), kept=self._installation_ready()) def _browser_url(self, address): @@ -1884,7 +1931,10 @@ def update_view(self): view['release_page'] = release_page(self.updater.current) if self.updater else '' if self.updater and self.updater.install_failed and view.get('candidate'): # The new app did not go in and the old one is back: the reminder says so. - view['status'], view['error'] = 'error', self.t(*ACTION_COPY['update_install_failed']) + from .launcher_update import mac_install_failure + reason = mac_install_failure(self.updater.install_failed_reason, self.language.startswith('zh')) + view['status'], view['error'] = 'error', self.t(*ACTION_COPY['update_install_failed']) + ( + ('' if self.language.startswith('zh') else ' ') + reason if reason else '') key = self.update_key() view.update(engine=self.engine_update_pending(), current=__version__, current_release=public_details(self.updater.current) if self.updater else self.release_details, @@ -2699,6 +2749,9 @@ def snapshot(self): estimate.append(self.t('Peak disk ~', '磁盘峰值约 ')+disk_space.size_text(sum(d.get('needed_bytes', 0) for d in row['disks']))) update = self.update_view() probe = self.probe.snapshot() + if probe.get('status') == 'failed' and probe.get('error'): + from .download_settings import SPEED_TEST_REASONS + probe = dict(probe, error=self.t(*SPEED_TEST_REASONS.get(probe.get('reason'), SPEED_TEST_REASONS['other']))) speeds = [] for group, entries in probe.get('sources', {}).items(): for entry in entries: @@ -2752,7 +2805,7 @@ def snapshot(self): if (self.importer.state.get('status') == 'error' and reasons and self.error == self.importer.state.get('error') and failure.get('kind') != 'runtime-alias'): from .offline_errors import guidance - failure = dict(title=guidance('title', zh), + failure = dict(title=guidance('import-title', zh), detail=guidance(reasons[0], zh), action='', kind='offline-write') disk = self.disk_view(row, failure) if disk and str(failure.get('kind', '')).startswith('disk'): @@ -2770,6 +2823,8 @@ def snapshot(self): from .offline_errors import alias_failure if alias_failure(cleanup.get('error', '')): cleanup['error'] = display_launcher_error(cleanup['error'], zh=zh) + elif cleanup.get('status') == 'error': + cleanup['message'] = self.t(*CLEANUP_FAILURES.get(cleanup.get('reason'), CLEANUP_FAILURES['failed'])) model_upgrade = dict(self.upgrade.state, busy=self.upgrade.busy) if alias_failure(model_upgrade.get('error', '')): model_upgrade['error'] = display_launcher_error(model_upgrade['error'], zh=zh) @@ -2797,6 +2852,7 @@ def snapshot(self): page=self.page, status=('review' if offline_review else self.importer.state['status'] if offline_progress else row.get('status', 'idle')), busy=busy, working=working, action_notice=self.t(*ACTION_COPY[self.action_notice]) if self.action_notice else '', + action_notice_key=self.action_notice or '', setup_pending=bool(self.pending_action) or self.setup_job_wait, setup_job_wait=self.setup_job_wait, setup_wait_text=self.t(*ACTION_COPY['setup_job' if self.setup_job_wait else 'setup_queued']), can_manage=self.can_manage(), busy_reason=self.t(*ACTION_COPY['busy']), @@ -2813,8 +2869,9 @@ def snapshot(self): field_error=dict(self.field_error or {}), retry_kind=self.retry_kind(), notice=self.notice, # Qt reads a list as an array; LEVELS is a tuple. compatibility=dict(self.compatibility, levels=list(self.compatibility.get('levels') or ())), - report=dict(self.report, error=self.t(*EXPORT_FAILURES[self.report['reason']]) - if self.report.get('reason') in EXPORT_FAILURES else self.report.get('error', '')), + report=dict(self.report, error=self.t(*EXPORT_FAILURES.get(self.report.get('reason') or 'other', + EXPORT_FAILURES['other'])) + if self.report.get('status') == 'error' else self.report.get('error', '')), models=models, overall=overall, progress=progress, detail=detail, progress_text=file_text, remaining_seconds=remaining, # The elapsed row is only shown while working. An idle clock would diff --git a/freevideo_engine/launcher_update.py b/freevideo_engine/launcher_update.py index e605864b..ad04c3f2 100644 --- a/freevideo_engine/launcher_update.py +++ b/freevideo_engine/launcher_update.py @@ -134,7 +134,29 @@ def failure_kind(error): return 'missing' if error.code in (401, 403): return 'blocked' - return 'connection' if isinstance(error, OSError) else 'invalid' + if isinstance(error, OSError): + return 'connection' + # Bad JSON, a manifest that does not validate or a checksum mismatch say the files are wrong; anything + # else is a fault in FreeVideo itself, not in what was downloaded. + return 'invalid' if isinstance(error, ValueError) else 'unexpected' + + +# The reasons mac_app_update's swap script records, as a cause and the next step. +MAC_INSTALL_FAILURES = { + 'old app did not exit': ('The previous FreeVideo did not close within 10 minutes. Quit FreeVideo completely, then update again.', + '旧版 FreeVideo 在 10 分钟内未退出。请完全退出 FreeVideo 后再更新。'), + 'could not set the old app aside': ('macOS did not allow the app in its folder to be replaced. Move FreeVideo to the Applications folder, or download the new version from the release page.', + 'macOS 不允许替换所在文件夹里的应用。请把 FreeVideo 移到“应用程序”文件夹,或去发布页下载新版本。'), + 'the new app did not open': ('The new version did not start on this Mac, so the previous version was put back. Download the new version from the release page; if it does not start either, use "Report a problem".', + '新版本在这台 Mac 上未能启动,已换回原来的版本。请去发布页下载新版本;如果仍然无法启动,请点击“提交问题”。'), +} +MAC_INSTALL_FAILURES['could not put the new app in place'] = MAC_INSTALL_FAILURES['could not set the old app aside'] +MAC_INSTALL_FAILURES['the new app did not stay open'] = MAC_INSTALL_FAILURES['the new app did not open'] + + +def mac_install_failure(reason, zh=False): + """Cause and next step for a recorded swap failure, or '' when the reason is not one of ours.""" + return MAC_INSTALL_FAILURES.get(reason, ('', ''))[bool(zh)] def error_text(row, zh=False): @@ -146,6 +168,8 @@ def error_text(row, zh=False): 'connection': ('Could not connect to the download server.', '无法连接下载服务器。'), 'invalid': ('The downloaded update files are incomplete or damaged.', '下载的更新文件不完整或已损坏。'), 'disk': ('There is not enough disk space to download the update.', '磁盘空间不足,无法下载更新。'), + 'unexpected': ('The update stopped because of an error in FreeVideo. If it happens again, use "Report a problem".', + '更新因 FreeVideo 自身的错误而中断。如果再次出现,请点击“提交问题”。'), } message = messages.get(row.get('error_code')) if message is None: @@ -918,11 +942,17 @@ def __init__(self, current, root, token=None, *, language=None): self.failures = 0 # The swap of an earlier run put the old app back: say so once, and # leave the release page as the way to update this time. - self.install_failed = False + self.install_failed, self.install_failed_reason = False, '' if self.current.get('packaging') == 'app': marker = io_path(self.root) / 'updates' / 'mac-update-failed.json' try: self.install_failed = marker.is_file() + if self.install_failed: + # Read why before the marker goes: the swap script records one fixed reason. + try: + self.install_failed_reason = str(json.loads(marker.read_text(encoding='utf-8')).get('reason') or '') + except (OSError, ValueError, AttributeError): + pass marker.unlink(missing_ok=True) except OSError: pass @@ -1017,6 +1047,8 @@ def progress(value): row = dict(status='cancelled' if stopped else 'error', candidate=selected or self.available) if not stopped: row['error_code'] = failure_kind(error) + if row['error_code'] == 'unexpected': + log.exception('Launcher update %s stopped unexpectedly', operation) if (not stopped and row['error_code'] not in ('invalid', 'disk') and (operation == 'check' or self.failures <= MAX_DOWNLOAD_RETRIES)): delay = max(min(MAX_RETRY_SECONDS, RETRY_SECONDS * 2**min(self.failures - 1, 4)), diff --git a/freevideo_engine/launcher_update_ui.py b/freevideo_engine/launcher_update_ui.py deleted file mode 100644 index 890f8614..00000000 --- a/freevideo_engine/launcher_update_ui.py +++ /dev/null @@ -1,156 +0,0 @@ -"""Tk update prompt; networking is delegated to a background client.""" -import time -import webbrowser - -from . import branding -from .launcher_update import error_text, manual_install, release_page, launch_download, DownloadedLauncherUnavailable - - -class UpdateUI: - def __init__(self, app, client, footer): - self.app, self.client = app, client - self.dialog = None - self.notified = None - self.last_state = None - self.closed = False - self.timer = None - self.snoozed = False - self.button = app.ttk.Button(footer, text=app.t('Check updates', '检查更新'), command=self.open) - self.button.pack(side='left') - app.window.bind('', self.destroyed, add='+') - - def start(self): - self.client.run('check') - self.poll() - - def open(self): - app = self.app - if self.dialog and self.dialog.winfo_exists(): - self.dialog.lift(); return - d = self.dialog = app.tk.Toplevel(app.window) - d.title(app.t('FreeVideo · Update', 'FreeVideo · 更新')); d.transient(app.window) - d.geometry('560x380'); d.minsize(440, 340) - d.configure(bg=branding.BACKGROUND) - body = app.ttk.Frame(d, padding=24); body.pack(fill='both', expand=True) - self.heading = app.ttk.Label(body, text='', wraplength=480) - self.heading.pack(anchor='w', pady=(0, 10)) - self.detail = app.tk.Text(body, height=5, wrap='word', relief='flat', - bg=branding.BACKGROUND, fg=branding.TEXT, state='disabled') - self.detail.pack(fill='both', expand=True) - self.progress = app.ttk.Progressbar(body, maximum=1); self.progress.pack(fill='x', pady=8) - self.rate = app.ttk.Label(body, text=''); self.rate.pack(anchor='w') - actions = app.ttk.Frame(body); actions.pack(fill='x', pady=(14, 0)) - self.primary = app.ttk.Button(actions, command=self.accept); self.primary.pack(side='left') - self.dismiss_button = app.ttk.Button(actions, command=self.dismiss) - self.dismiss_button.pack(side='left', padx=8) - app.ttk.Button(actions, text=app.t('Download manually', '手动下载'), - command=lambda: webbrowser.open(release_page(self.client.current))).pack(side='right') - d.protocol('WM_DELETE_WINDOW', self.dismiss) - self.render() - if self.client.state['status'] in ('idle', 'current', 'cancelled'): - self.client.run('check') - - def dismiss(self): - self.snoozed = True - if self.client.state['status'] == 'downloading' or self.client.state.get('retry_operation') == 'download': - self.client.stop() - if self.dialog: - self.dialog.destroy(); self.dialog = None - - def accept(self): - app, row = self.app, self.client.state - if self.client.busy or app.controller.busy: - return - try: - if row['status'] == 'ready': - app.save_settings() - launch_download(row['candidate'], self.client.root, token=self.client.token) - self.closed = True - app.close() - elif row['status'] == 'available' or (row['status'] in ('error', 'cancelled') and row.get('candidate')): - if manual_install(getattr(self.client, 'current', {}), self.client): - webbrowser.open(release_page(self.client.current)) - else: - self.client.run('download', row['candidate']) - else: - self.client.run('check') - except DownloadedLauncherUnavailable: - self.client.run('download', row['candidate']) - except Exception as error: - from .diagnostics import Redactor - self.client.state = dict(status='error', error=Redactor([(self.client.token, '')]).text(str(error)), - candidate=row.get('candidate')) - - def render(self): - if not self.dialog or not self.dialog.winfo_exists(): - return - app, row = self.app, self.client.state - state = row['status'] - headings = {'checking': ('Checking for updates…', '正在检查更新…'), - 'available': ('A FreeVideo update is available', '发现 FreeVideo 新版本'), - 'downloading': ('Downloading update…', '正在下载更新…'), - 'ready': ('Update ready', '更新已就绪'), - 'current': ('You have the current release', '当前已是最新发布版本'), - 'error': ('Update check / download failed', '更新检查/下载失败'), - 'cancelled': ('Update paused', '更新已停止')} - self.heading.configure(text=app.t(*headings.get(state, headings['checking']))) - candidate = row.get('candidate') - description = error_text(row, app.zh) - if candidate: - description += ('\n\n' if description else '') + '%s · %s · %s\n%.1f MiB\n\n%s' % (candidate['version'], - time.strftime('%Y-%m-%d %H:%M UTC', time.gmtime(candidate['built_at'])), candidate['revision'][:8], - candidate['asset']['bytes']/2**20, - app.t('Your models, environments and settings are kept. Restart the launcher after downloading.', - '保留已有模型、环境和设置。下载后重启启动器即可。')) - self.notified = candidate['revision'] - if getattr(self.client, 'current', {}).get('packaging') == 'onedir': - description += '\n' + app.t('Download and extract the updated folder ZIP; keep all files together.', - '请下载并解压新版文件夹包,保留包内完整文件。') - if app.controller.busy: - description += '\n' + app.t('Finish the current installation before updating.', '请等待当前安装完成后再更新。') - self.detail.configure(state='normal'); self.detail.delete('1.0', 'end') - self.detail.insert('1.0', description); self.detail.configure(state='disabled') - progress = row.get('progress', {}) - self.progress.configure(maximum=progress.get('total', 1), value=progress.get('done', 0)) - self.rate.configure(text=('%.0f%% · %.1f MiB/s · ~%ds' % - (100*progress['done']/progress['total'], progress['bytes_per_second']/2**20, - progress['remaining_seconds'])) if progress else '') - downloadable = state == 'available' or (state in ('error', 'cancelled') and candidate) - self.primary.configure(text=app.t('Restart & update', '重启并更新') if state == 'ready' else - app.t('Download folder ZIP', '下载文件夹版') if downloadable and - getattr(self.client, 'current', {}).get('packaging') == 'onedir' else - app.t('Download update', '下载更新') if downloadable else app.t('Check again', '重新检查')) - self.primary.state(['disabled'] if self.client.busy or app.controller.busy else ['!disabled']) - self.dismiss_button.configure(text=app.t('Later', '稍后更新') if candidate else app.t('Close', '关闭')) - - def poll(self): - if self.timer is not None: - self.app.window.after_cancel(self.timer) - self.timer = None - if self.closed: - return - self.client.poll(allow_download=not self.app.controller.busy) - row = self.client.state - state = row['status'] - self.button.configure(text=self.app.t('Update available', '有可用更新') if row.get('candidate') else - self.app.t('Update check failed', '更新检查失败') if state == 'error' else self.app.t('Check updates', '检查更新')) - if (row.get('candidate') and state in ('available', 'ready', 'error') and not self.snoozed and not self.client.busy and not self.app.controller.busy - and row['candidate']['revision'] != self.notified): - self.open() - key = (id(row), self.client.busy, self.app.controller.busy, self.app.zh) - if key != self.last_state: - self.last_state = key - self.app.refresh() - self.render() - self.timer = self.app.window.after(150, self.poll) - - def stop(self): - self.closed = True - self.client.stop() - if self.timer is not None: - self.app.window.after_cancel(self.timer) - self.timer = None - - def destroyed(self, event): - if event.widget == self.app.window: - self.stop() diff --git a/freevideo_engine/launcher_view.py b/freevideo_engine/launcher_view.py deleted file mode 100644 index 5342ca54..00000000 --- a/freevideo_engine/launcher_view.py +++ /dev/null @@ -1,407 +0,0 @@ -"""Native setup wizard: compact navigation, rounded cards and live model status. - -Every size, gap and hue comes from `branding`. Copy stays short here: a card -states what it needs and nothing else, and the full explanation lives in the -dialog the user opens for it. -""" -import tkinter as tk -from tkinter import ttk - -from . import branding as b -from .model_status import FAMILIES, NAMES -from .widgets import Card, PillButton, Progress, Radio, StepRail - - -class Choice(Card): - """One of two mutually exclusive setups. The dot sits beside its title so - the card stays one text block tall on a 480-pixel-high window.""" - - def __init__(self, parent, app, value, title, detail): - super().__init__(parent, takefocus=1, cursor='hand2') - self.app, self.value, self.disabled, self.hovered = app, value, False, False - head = ttk.Frame(self.body, style='Card.TFrame') - head.pack(fill='x') - self.mark = Radio(head) - self.mark.pack(side='left', padx=(0, b.space(2))) - app.label(head, *title, style='Heading.Card.TLabel').pack(side='left') - label = app.label(self.body, *detail, style='Muted.Card.TLabel', wraplength=310) - label.pack(fill='x', pady=(b.space(1), 0)) - self.body.bind('', lambda e: label.configure(wraplength=max(100, e.width)), add='+') - for widget in (self, self.body, head, self.mark, *self.body.winfo_children(), *head.winfo_children()): - widget.bind('', self.choose) - widget.bind('', self.hover, add='+') - widget.bind('', self.leave, add='+') - self.bind('', self.choose); self.bind('', self.choose) - self.bind('', lambda _: self.state()); self.bind('', lambda _: self.state()) - - def choose(self, _=None): - if not self.disabled: - self.app.mode.set(self.value) - self.focus_set() - return 'break' - - def hover(self, _=None): - self.hovered = True - self.state() - - def leave(self, _=None): - # Tk reports Leave when the pointer crosses onto a child of this card, - # so confirm it actually left the card before dropping the highlight. - x, y = self.winfo_pointerxy() - if (self.winfo_rootx() <= x < self.winfo_rootx() + self.winfo_width() - and self.winfo_rooty() <= y < self.winfo_rooty() + self.winfo_height()): - return - self.hovered = False - self.state() - - def state(self, states=None): - if states is not None: - self.disabled = 'disabled' in states - selected = self.app.mode.get() == self.value - focused = self.focus_get() is self - self.tint(b.ACCENT if selected or focused else b.HOVER if self.hovered and not self.disabled else b.BORDER) - self.mark.select(selected, self.disabled) - self.resize() - return ('disabled',) if self.disabled else () - - -class ModelCard(Card): - """One model family. The state line names the phase; a single metadata - line carries the numbers, so three cards stay one block tall.""" - - STATES = {'waiting': b.BORDER, 'pending': b.ACCENT, 'downloading': b.ACCENT, - 'verifying': b.ACCENT, 'ready': b.SUCCESS, 'paused': b.WARNING} - - def __init__(self, parent, app, name): - super().__init__(parent, padding=b.space(4), radius=b.RADIUS_MD) - self.resize_timer = None - self.bind('', self.cancel_resize, add='+') - self.app, self.name = app, name - self.title = app.label(self.body, *NAMES[name], style='Heading.Card.TLabel') - self.title.pack(anchor='w') - self.state = ttk.Label(self.body, style='Accent.Card.TLabel') - self.state.pack(anchor='w', pady=(b.space(1), b.space(2))) - self.bar = Progress(self.body, height=b.space(1) + 2); self.bar.pack(fill='x') - self.detail = ttk.Label(self.body, style='Meta.Card.TLabel', justify='left') - self.detail.pack(fill='x', pady=(b.space(2), 0)) - self.body.bind('', self.wrap, add='+') - - def wrap(self, event): - for label in (self.title, self.state, self.detail): - label.configure(wraplength=max(100, event.width)) - # Wrapping changes the required height, so measure again once Tk has - # applied it; otherwise a two-line title clips the line below it. - self.cancel_resize() - self.resize_timer = self.after_idle(self.finish_wrap) - - def finish_wrap(self): - self.resize_timer = None - self.resize() - - def cancel_resize(self, event=None): - if event is not None and event.widget != self: - return - if self.resize_timer is not None: - self.after_cancel(self.resize_timer) - self.resize_timer = None - - def update(self, item, *, ready=False): - t = self.app.t - size = lambda n: ('%.1f GiB' % (n/2**30)) if n >= 2**30 else ('%.0f MiB' % (n/2**20)) - if not item or ready and item.get('state') != 'ready': - self.state.configure(text=t('Ready locally', '本地已就绪') if ready else t('Waiting for scan', '等待扫描'), - foreground=b.SUCCESS if ready else b.MUTED) - self.detail.configure(text='' if ready else t('Scan first', '先查找已有模型')) - self.bar.configure(maximum=1, value=1 if ready else 0, tint=b.SUCCESS if ready else None) - self.tint(b.SUCCESS if ready else b.BORDER) - return - state = item['state'] - labels = {'waiting': ('To download', '待下载') if item['download_bytes'] else ('Found locally', '已在本地找到'), - 'pending': ('Waiting for remaining files', '等待补齐剩余文件'), - 'downloading': ('Downloading', '下载中'), - 'verifying': ('Transfer complete · verifying (no re-download)', '传输完成 · 正在校验(不会重复下载)'), - 'ready': ('Ready', '已就绪'), 'paused': ('Paused · files retained', '已暂停 · 文件已保留')} - hue = self.STATES.get(state, b.ACCENT) - self.state.configure(text=t(*labels[state]), foreground=b.MUTED if state == 'waiting' else hue) - self.tint(hue) - existing, total, done = item['existing_bytes'], item['download_bytes'], item['downloaded_bytes'] - # The state line already names the phase, so these are numbers only. - parts = [] - if state == 'ready': - parts.append(size(item['total_bytes'])) - else: - if total: - parts.append('%s / %s' % (size(done), size(total))) - elif existing: - parts.append(size(existing)) - if item.get('ready_files'): - parts.append(t('%d / %d files', '%d / %d 个文件') % (item['ready_files'], item['files'])) - rate = item.get('bytes_per_second') - if rate: - parts.append('%.1f MiB/s' % (rate/2**20)) - elif state == 'waiting' and existing > item.get('verified_bytes', 0): - parts.append(t('verify first', '待校验')) - if state == 'verifying': - parts.append(t('Checksum is running; the next file may already be downloading', - '正在校验完整性;下一个文件可能已经开始下载')) - self.detail.configure(text=' · '.join(parts)) - maximum = item['total_bytes'] or 1 - self.bar.configure(maximum=maximum, value=maximum if state == 'ready' else - min(maximum, item.get('verified_bytes', 0)+done), - tint=b.WARNING if state == 'paused' else None) - - -def build(app): - window, t = app.window, app.t - from .windows_ux import window_size, work_area - width, height = window_size(window) - left, top, screen_width, screen_height = work_area(window) - window.title('FreeVideo') - window.geometry('%dx%d%+d%+d' % (width, height, left+(screen_width-width)//2, top+(screen_height-height)//2)) - # Tall enough for the pages whose content is fixed: both choice pages and - # the review page. At 540 every one of them clipped its last line, review - # by 34 px, and a wizard that hides part of what it asks you to accept is - # not a wizard. Installing, paused and ready pages still scroll: live task - # lists, a retained error and the install path have no bounded height. - window.minsize(min(680, width), min(600, height)) - b.theme(window) - shell = ttk.Frame(window, padding=(b.space(7), b.space(4))); shell.pack(fill='both', expand=True) - header = ttk.Frame(shell); header.pack(fill='x', pady=(0, b.space(4))) - # Sized so the three header actions still fit their labels at 680 px, - # the narrowest window this wizard allows. - app.logo = b.wordmark(header, 170); app.logo.pack(side='left') - app.language_button = app.button(header, '中文', 'EN', app.language) - app.language_button.configure(style='Quiet.TButton'); app.language_button.pack(side='right') - app.option_button = app.button(header, 'Settings', '设置', app.show_options) - app.option_button.configure(style='Quiet.TButton'); app.option_button.pack(side='right', padx=b.space(1)) - app.download_button = app.button(header, 'Download sources', '下载源', app.download_settings) - app.download_button.configure(style='Quiet.TButton'); app.download_button.pack(side='right', padx=b.space(1)) - app.steps_frame = StepRail(shell, app, (('ComfyUI', 'ComfyUI'), ('Models', '模型'))) - app.steps_frame.pack(fill='x', pady=(0, b.space(3))) - # A hairline, not ttk's two-pixel separator: the rail already divides. - app.steps_separator = tk.Frame(shell, height=1, background=b.BORDER) - app.steps_separator.pack(fill='x') - footer = ttk.Frame(shell, padding=(0, b.space(2), 0, 0)); footer.pack(side='bottom', fill='x') - app.consent = ttk.Checkbutton(footer, variable=app.accept, command=app.refresh) - actions = app.action_row = ttk.Frame(footer); actions.pack(side='bottom', fill='x') - app.back_button = app.button(actions, 'Back', '上一步', app.back) - app.back_button.configure(style='Quiet.TButton'); app.back_button.pack(side='left') - app.launcher_button = app.button(actions, 'Return to launcher', '返回启动器', app.show_launcher) - app.launcher_button.configure(style='Quiet.TButton') - app.primary = PillButton(actions, app.act) - app.primary.pack(side='right') - app.stop_button = app.button(actions, 'Pause installation', '暂停安装', app.controller.cancel) - app.stop_button.configure(style='Quiet.TButton') - app.stop_button.pack(side='right', padx=(0, b.space(2))) - tools = ttk.Frame(footer); tools.pack(side='bottom', fill='x', pady=(0, b.space(1))) - app.detail_button = app.button(tools, 'Details', '详情', app.show_details) - app.detail_button.configure(style='Quiet.TButton'); app.detail_button.pack(side='left') - app.copy_error_button = app.button(tools, 'Copy error', '复制错误', app.copy_error) - app.copy_error_button.configure(style='Quiet.TButton') - app.report_error_button = app.button(tools, 'Report a problem', '提交问题', app.report_error) - app.report_error_button.configure(style='Quiet.TButton') - from . import __version__ - ttk.Label(tools, text=__version__, style='Meta.TLabel').pack(side='right') - app.update_row = tools - from .launcher_terminal import Terminal - app.terminal = Terminal(shell, app, footer) - app.terminal_button = app.button(tools, 'Terminal', '终端', app.terminal.toggle) - app.terminal_button.configure(style='Quiet.TButton'); app.terminal_button.pack(side='left', padx=b.space(1)) - viewport = ttk.Frame(shell); viewport.pack(fill='both', expand=True, pady=(b.space(4), 0)) - app.canvas = canvas = tk.Canvas(viewport, background=b.BACKGROUND, highlightthickness=0, width=1) - scrollbar = ttk.Scrollbar(viewport, command=canvas.yview, style='Wizard.Vertical.TScrollbar') - scrollbar.pack(side='right', fill='y'); canvas.pack(side='left', fill='both', expand=True) - def scroll_state(first, last): - scrollbar.set(first, last) - if float(first) == 0 and float(last) == 1: - scrollbar.pack_forget() - elif not scrollbar.winfo_manager(): - scrollbar.pack(side='right', fill='y', before=canvas) - canvas.configure(yscrollcommand=scroll_state) - app.content = content = ttk.Frame(canvas) - app.layout_timer = None - handle = canvas.create_window(0, 0, window=content, anchor='nw') - def place_content(_=None): - if app.layout_timer is not None: - window.after_cancel(app.layout_timer) - app.layout_timer = None - width = max(1, canvas.winfo_width()) - canvas.itemconfigure(handle, width=width) - # Centre a page that fits; a taller one starts at the top and scrolls. - height, needed = canvas.winfo_height(), content.winfo_reqheight() - top = max(0, (height - needed)//2) - canvas.coords(handle, 0, top) - # Anchor the region at zero. Taking it from bbox('all') starts it at - # the centring offset, and yview_moveto(0) then scrolls that offset - # away, so a page was centred or flush to the top depending on - # whether it had been shown before. - canvas.configure(scrollregion=(0, 0, width, max(height, top + needed))) - app.place_content = place_content - canvas.bind('', place_content) - content.bind('', place_content) - def wheel(event): - if str(event.widget).startswith(str(content)) or event.widget == canvas: - canvas.yview_scroll(-1 if getattr(event, 'num', 0) == 4 else 1 if getattr(event, 'num', 0) == 5 else -int(event.delta/120), 'units') - for name in ('', '', ''): - window.bind(name, wheel, add='+') - app.heading = ttk.Label(content, style='Title.TLabel', anchor='center') - app.heading.pack(fill='x') - app.status_label = ttk.Label(content, textvariable=app.status, style='Muted.TLabel', - anchor='center', justify='center', wraplength=800) - # Leave room for font-dependent wrapping at the declared minimum size. - app.status_label.pack(fill='x', pady=(b.space(1), b.space(3))) - content.bind('', lambda e: app.status_label.configure(wraplength=max(100, e.width)), add='+') - app.pages = [ttk.Frame(content) for _ in range(4)] - app.inputs = app.pages[0] - choices = ttk.Frame(app.inputs); choices.pack(fill='x', pady=(0, b.space(4))) - choices.columnconfigure((0, 1), weight=1, uniform='choices') - app.mode_buttons = [] - for index, (value, title, detail) in enumerate(( - ('existing', ('Use existing ComfyUI', '使用已有 ComfyUI'), ('Connect your installation.', '接入现有安装。')), - ('new', ('Install ComfyUI for me', '帮我安装 ComfyUI'), ('ComfyUI, Python and FreeVideo together.', '一并准备 ComfyUI、Python 和 FreeVideo。')))): - choice = Choice(choices, app, value, title, detail) - choice.grid(row=0, column=index, sticky='nsew', padx=(0, b.space(2)) if index == 0 else (b.space(2), 0)) - app.mode_buttons.append(choice) - folder = Card(app.inputs); folder.pack(fill='x') - ttk.Label(folder.body, textvariable=app.folder_label, style='Heading.Card.TLabel').pack(anchor='w') - row = ttk.Frame(folder.body, style='Card.TFrame'); row.pack(fill='x', pady=(b.space(3), b.space(2))) - app.entry = ttk.Entry(row, textvariable=app.selected_folder(), style='Well.TEntry') - app.entry.pack(side='left', fill='x', expand=True) - app.browse_button = app.button(row, 'Browse…', '浏览…', lambda: app.browse(app.selected_folder())) - app.browse_button.configure(style='Card.TButton') - app.browse_button.pack(side='right', padx=(b.space(2), 0)) - ttk.Label(folder.body, textvariable=app.folder_hint, style='Meta.Card.TLabel', wraplength=760).pack(fill='x') - models = Card(app.pages[1], padding=b.space(4)); models.pack(fill='x') - methods = ttk.Frame(models.body, style='Card.TFrame'); methods.pack(fill='x') - app.model_method_buttons = [] - for value, en, zh in (('auto', 'Automatic download', '自动下载'), - ('manual', 'Download myself', '手动下载'), ('reuse', 'Use existing models', '复用已有模型')): - button = ttk.Radiobutton(methods, text=app.t(en, zh), value=value, variable=app.model_method) - button.pack(side='left', padx=(0, b.space(3))) - app.labels.append((button, en, zh)); app.model_method_buttons.append(button) - app.model_help = ttk.Label(models.body, style='Meta.Card.TLabel', wraplength=660) - app.model_help.pack(fill='x', pady=(b.space(2), b.space(1))) - models.body.bind('', lambda e: app.model_help.configure(wraplength=max(100, e.width)), add='+') - app.model_source_row = ttk.Frame(models.body, style='Card.TFrame') - app.label(app.model_source_row, 'Download source', '下载源', style='Meta.Card.TLabel').pack(side='left', padx=(0, 8)) - app.model_source = ttk.Combobox(app.model_source_row, state='readonly', width=18) - app.model_source.pack(side='left'); app.model_source.bind('<>', app.select_model_source) - app.token_link = app.button(app.model_source_row, 'Test speeds / settings', '测速/设置', app.download_settings) - app.token_link.configure(style='Card.TButton'); app.token_link.pack(side='left', padx=8) - app.model_source_status = ttk.Label(models.body, style='Meta.Card.TLabel', wraplength=660) - app.model_source_status.pack(fill='x') - app.model_components = ttk.Frame(models.body, style='Card.TFrame') - app.model_components.pack(fill='x', pady=(b.space(3), 0)) - app.label(app.model_components, 'Download links by component', '按组件查看下载链接', style='Meta.Card.TLabel').pack(anchor='w', pady=(0, 6)) - component_row = ttk.Frame(app.model_components, style='Card.TFrame'); component_row.pack(fill='x') - app.component_buttons = {} - for component, en, zh in (('video', 'Video model ↗', '视频模型 ↗'), - ('encoder', 'Prompt model ↗', '提示词模型 ↗'), ('decoder', 'Decoders ↗', '解码器 ↗')): - button = app.button(component_row, en, zh, lambda name=component: app.model_download_link(name)) - button.configure(style='Card.TButton'); button.pack(side='left', padx=(0, 8)) - app.component_buttons[component] = button - app.model_reuse_button = app.button(models.body, 'Choose model folders…', '选择模型文件夹…', - lambda: app.model_method.set('reuse')) - app.model_reuse_button.configure(style='Card.TButton') - app.model_library = library = ttk.Frame(models.body, style='Card.TFrame') - app.model_list = tk.Listbox(library, height=2, selectmode='extended', background=b.BACKGROUND, - foreground=b.TEXT, selectbackground=b.ACCENT_SUBTLE, selectforeground=b.TEXT, - highlightthickness=0, relief='flat', borderwidth=0, - font=(b.FAMILY, b.BODY), activestyle='none', exportselection=False) - app.model_list.pack(fill='x', ipady=b.space(1)) - row = ttk.Frame(library, style='Card.TFrame'); row.pack(fill='x', pady=(8, 0)) - app.add_model_button = app.button(row, '+ Add folder', '+ 添加目录', app.add_model_folder) - app.add_model_button.configure(style='Card.TButton'); app.add_model_button.pack(side='left') - app.remove_model_button = app.button(row, 'Remove selected', '移除所选', app.remove_model_folders) - app.remove_model_button.configure(style='Card.TButton') - app.remove_model_button.pack(side='left', padx=b.space(2)) - # The plan figures and the disclosure share the centred title axis. - app.summary = ttk.Label(app.pages[2], style='Muted.TLabel', wraplength=800, - anchor='center', justify='center') - app.summary.pack(fill='x', pady=(0, b.space(2))) - grid = ttk.Frame(app.pages[2]); grid.pack(fill='x', pady=(0, b.space(3))) - grid.columnconfigure((0, 1, 2), weight=1, uniform='models') - app.model_cards = {} - # Optional pack controls live in the Qt launcher; keep this legacy setup - # grid limited to the families setup itself provisions. - for index, name in enumerate(name for name in FAMILIES if name != 'image'): - card = ModelCard(grid, app, name) - card.grid(row=0, column=index, sticky='nsew', - padx=(0 if index == 0 else b.space(2), 0 if index == 2 else b.space(2))) - app.model_cards[name] = card - # The phase is the headline; stage counts and elapsed time are metadata. - app.progress_card = Card(app.pages[2], padding=b.space(4)); app.progress_card.pack(fill='x') - app.progress_box = app.progress_card.body - ttk.Label(app.progress_box, textvariable=app.phase, style='ProgressTitle.Card.TLabel', - anchor='center', wraplength=760).pack(fill='x') - app.overall_bar = Progress(app.progress_box, height=b.space(2)); app.overall_bar.pack(fill='x', pady=(b.space(3), b.space(2))) - counters = ttk.Frame(app.progress_box, style='Card.TFrame'); counters.pack(fill='x') - ttk.Label(counters, textvariable=app.overall_text, style='Meta.Card.TLabel').pack(side='left') - ttk.Label(counters, textvariable=app.meta, style='Meta.Card.TLabel').pack(side='right') - app.bar = Progress(app.progress_box, height=b.space(1) - 1, subdued=True) - app.bar.pack(fill='x', pady=(b.space(4), 0)) - current = ttk.Frame(app.progress_box, style='Card.TFrame'); current.pack(fill='x', pady=(b.space(2), 0)) - ttk.Label(current, textvariable=app.current_text, style='Meta.Card.TLabel').pack(side='left') - ttk.Label(current, textvariable=app.details, style='Meta.Card.TLabel').pack(side='right') - app.review_card = Card(app.pages[2], padding=b.space(4), radius=b.RADIUS_MD, - fill=b.DANGER_SUBTLE, body_style='Alert.Card.TFrame') - app.review_card.tint(b.DANGER) - app.review = tk.Text(app.review_card.body, height=3, wrap='word', relief='flat', - background=b.DANGER_SUBTLE, foreground=b.DANGER, highlightthickness=0, - borderwidth=0, font=(b.FAMILY, b.BODY), state='disabled') - app.review.pack(fill='x') - launch = Card(app.pages[3], padding=b.space(7)); launch.pack(fill='x', pady=(b.space(3), b.space(5))) - badge = tk.Canvas(launch.body, width=44, height=44, bg=b.SURFACE, highlightthickness=0) - badge.pack(pady=(0, b.space(4))) - badge.create_oval(1, 1, 43, 43, fill=b.SUCCESS_SUBTLE, outline='') - badge.create_line(14, 23, 20, 30, 31, 16, fill=b.SUCCESS, width=3, capstyle='round', joinstyle='round') - app.label(launch.body, 'Ready to launch', '安装已就绪', style='Hero.Card.TLabel', anchor='center').pack(fill='x', pady=(0, b.space(4))) - app.launch_paths = ttk.Label(launch.body, style='Meta.Card.TLabel', anchor='center', justify='center', wraplength=680) - app.launch_paths.pack(fill='x', pady=(0, b.space(3))) - app.label(launch.body, 'Already running ComfyUI? FreeVideo connects automatically.', - 'ComfyUI 已在运行?会自动连接。', style='Meta.Card.TLabel', anchor='center', justify='center', wraplength=680).pack(fill='x') - app.browser_controls = ttk.Frame(launch.body, style='Card.TFrame') - ttk.Entry(app.browser_controls, textvariable=app.browser_address, state='readonly', justify='center').pack(fill='x') - browser_buttons = ttk.Frame(app.browser_controls, style='Card.TFrame'); browser_buttons.pack(pady=(8, 0)) - app.browser_button = app.button(browser_buttons, 'Open browser', '打开浏览器', app.open_browser) - app.browser_button.pack(side='left', padx=4) - app.button(browser_buttons, 'Copy address', '复制地址', app.copy_browser_address).pack(side='left', padx=4) - shortcuts = ttk.Frame(launch.body, style='Card.TFrame'); shortcuts.pack(pady=(16, 0)) - app.shortcut_button = app.button(shortcuts, 'Create desktop shortcut', '创建桌面快捷方式', app.create_shortcut) - app.shortcut_button.pack(side='left', padx=4) - app.shortcut_status = ttk.Label(shortcuts, style='Meta.Card.TLabel'); app.shortcut_status.pack(side='left', padx=4) - launch.body.bind('', lambda e: app.launch_paths.configure(wraplength=max(100, e.width))) - app.launch_error = ttk.Label(app.pages[3], style='Danger.TLabel', wraplength=760, justify='left') - app.launch_error.pack(fill='x') - app.engine_update_row = ttk.Frame(app.pages[3]) - app.label(app.engine_update_row, 'Engine update available', '引擎有可用更新').pack(side='left') - app.engine_update_button = app.button(app.engine_update_row, 'Update', '更新', app.update_engine) - app.engine_update_button.pack(side='right') - app.pages[3].bind('', lambda e: app.launch_error.configure(wraplength=max(100, e.width))) - - -def show_page(app): - if app.wizard_step == 3: - app.primary.configure(width=32) - app.primary.pack(side='top', anchor='center', pady=(0, b.space(2)), before=app.back_button) - app.back_button.pack_configure(side='top', anchor='center') - app.steps_frame.pack_forget() - else: - app.primary.configure(width=0) - app.primary.pack(side='right', pady=0) - app.back_button.pack_configure(side='left', anchor='w') - if app.wizard_step != 3 and not app.steps_frame.winfo_manager(): - app.steps_frame.pack(fill='x', pady=(0, b.space(3)), before=app.steps_separator) - app.heading.pack_configure(fill='x') - for index, page in enumerate(app.pages): - if index == app.wizard_step: - if not page.winfo_manager(): - page.pack(fill='x'); app.canvas.yview_moveto(0) - else: - page.pack_forget() - app.steps_frame.show(min(app.wizard_step, 1)) - if app.layout_timer is not None: - app.window.after_cancel(app.layout_timer) - # The root owns this callback so its Destroy handler can cancel it before - # Tk deletes the registered command, even when a page closes before idle. - app.layout_timer = app.window.after_idle(app.place_content) diff --git a/freevideo_engine/licenses/Real-ESRGAN-BSD-3-Clause.txt b/freevideo_engine/licenses/Real-ESRGAN-BSD-3-Clause.txt new file mode 100644 index 00000000..552a1eea --- /dev/null +++ b/freevideo_engine/licenses/Real-ESRGAN-BSD-3-Clause.txt @@ -0,0 +1,29 @@ +BSD 3-Clause License + +Copyright (c) 2021, Xintao Wang +All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + +1. Redistributions of source code must retain the above copyright notice, this + list of conditions and the following disclaimer. + +2. Redistributions in binary form must reproduce the above copyright notice, + this list of conditions and the following disclaimer in the documentation + and/or other materials provided with the distribution. + +3. Neither the name of the copyright holder nor the names of its + contributors may be used to endorse or promote products derived from + this software without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE +FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR +SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER +CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, +OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. diff --git a/freevideo_engine/macos_setup.py b/freevideo_engine/macos_setup.py index b51c5763..591115bd 100644 --- a/freevideo_engine/macos_setup.py +++ b/freevideo_engine/macos_setup.py @@ -88,7 +88,9 @@ def check_kernels(self, python, kernel_report): '--out', kernel_report]) result = json.loads(kernel_report.read_text(encoding='utf-8')) if not result.get('ready') or result.get('device_backend') != 'mps': - raise RuntimeError('Native GPU checks did not complete; see the retained report') + # launcher_failure turns this line into the card; the report lives in this run's folder. + raise RuntimeError('Mac GPU check did not pass (backend %s). Report: %s' % + (result.get('device_backend') or 'none', kernel_report)) save(self.root / 'kernel-capabilities.json', result) def record_kernel_validation(self, results, kernel_report): diff --git a/freevideo_engine/media_encoding.py b/freevideo_engine/media_encoding.py index 5c50f8cb..c03f8889 100644 --- a/freevideo_engine/media_encoding.py +++ b/freevideo_engine/media_encoding.py @@ -216,12 +216,23 @@ def prepare(media, canvas, directory): ref['early_steps'] = row['early_steps'] if row.get('guide'): ref['guide'] = True + if kind == 'image': + # A keyframe next to references: a still guide on its frame of the generated clip. + from .media_request import guide_index + ref['guide_index'] = guide_index(row, canvas['frames']) if row.get('voice_only'): ref['voice_only'] = True numbers[kind] += 1 longer, length, used = False, None, limit / 24. target = directory / ('reference-%02d.npy' % index) - if kind == 'image': + if kind == 'image' and row.get('guide'): + # Cropped to the canvas like a keyframe; like a guide clip, not described to the vision-language encoder. + with Image.open(path) as source: + image = ImageOps.fit(ImageOps.exif_transpose(source).convert('RGB'), + (canvas['width'], canvas['height']), method=Image.Resampling.LANCZOS) + np.save(target, np.array(image)[None], allow_pickle=False) + ref.update(pixels=str(target), frames=1, width=canvas['width'], height=canvas['height'], crop_mode='fit') + elif kind == 'image': with Image.open(path) as source: image = ImageOps.exif_transpose(source).convert('RGB') target_w, target_h = reference_size(*image.size, canvas) @@ -559,7 +570,7 @@ def encode_latents(normalized, value, base, canvas, *, resident=None, device='cu if torch.device(device).type not in ('cuda', 'mps'): raise ValueError('Media encoding requires a CUDA or MPS device') empty_cache = torch.mps.empty_cache if torch.device(device).type == 'mps' else torch.cuda.empty_cache - refs = [{key: row[key] for key in ('kind', 'early_steps', 'guide') if key in row} for row in normalized] + refs = [{key: row[key] for key in ('kind', 'early_steps', 'guide', 'guide_index') if key in row} for row in normalized] keys, cache, hits = {}, None, set() cache_root = cache_root or (data_root() / 'input-cache') if cache_root and any(row.get('pixels') for row in normalized): diff --git a/freevideo_engine/media_request.py b/freevideo_engine/media_request.py index e10119cb..bcea2e99 100644 --- a/freevideo_engine/media_request.py +++ b/freevideo_engine/media_request.py @@ -119,9 +119,8 @@ def file_info(name): from .original_audio import original original(result) if result['references'] and any(result.get(k) for k in ('first', 'last')): - raise ValueError('Reference and first/last keyframe layouts cannot be mixed in one request; ' - 'mark the clip that carries the motion with "guide": true instead') - guides = [row for row in result['references'] if row.get('guide')] + keyframes_as_guides(result) + guides = [row for row in result['references'] if row.get('guide') and row['kind'] == 'video'] if len(guides) > 1: raise ValueError('At most one guide clip per request') # The packed layout needs the guide after the other references. @@ -134,9 +133,40 @@ def file_info(name): return result +def keyframes_as_guides(result): + """First, last and middle frames next to references become still guides at their frame. + + A reference request has no keyframe anchors; like the native AddGuide node, each keyframe is + packed as a one-frame guide on the generated clip's own time origin, after the references. + The last frame's index depends on the length, so it is resolved when the media are encoded. + The Mac engine has no guide layout and keeps refusing the mix. + """ + import sys + if sys.platform == 'darwin': + raise ValueError('Reference and first/last keyframe layouts cannot be mixed in one request on this Mac; ' + 'keep one of the two') + rows = [('first', result.pop('first', None), 0)] + \ + [('middle', row, row['frame']) for row in result.pop('middle', [])] + [('last', result.pop('last', None), LAST)] + for keyframe, row, index in rows: + if row: + info = {k: v for k, v in row.items() if k != 'frame'} + result['references'].append(dict(info, kind='image', guide=True, guide_index=index, keyframe=keyframe)) + + +# The guide index of a last frame next to references, resolved to frames - 1 once the length is known. +LAST = 'last' + + +def guide_index(row, frames): + """The frame a still guide sits on.""" + return frames - 1 if row.get('guide_index') == LAST else row.get('guide_index', 0) + + def validate_middle(media, frames): """Each middle keyframe sits strictly between the first frame (0) and the last (frames - 1).""" - for row in media.get('middle', []): + middle = media.get('middle', []) + [dict(row, frame=row['guide_index']) for row in media.get('references', []) + if row.get('keyframe') == 'middle'] + for row in middle: if not 1 <= row['frame'] <= frames - 2: raise ValueError('Middle keyframe frame %d is outside the %d-frame video; use 1 to %d' % (row['frame'], frames, frames - 2)) diff --git a/freevideo_engine/model_guidance.py b/freevideo_engine/model_guidance.py index fd93a263..7407d1c1 100644 --- a/freevideo_engine/model_guidance.py +++ b/freevideo_engine/model_guidance.py @@ -47,9 +47,11 @@ 'error_read': ('FreeVideo does not have permission to read some files in the selected folder. Choose another folder, or download the files again without administrator rights.', 'FreeVideo 没有权限读取所选文件夹里的部分文件。请选择其他文件夹,或不使用管理员身份重新下载。'), 'write_permission': ('this account cannot write to it. Choose another folder.', '当前账户没有写入权限,请换一个文件夹。'), - 'write_disk_full': ('the drive is full.', '磁盘空间不足。'), + 'write_disk_full': ('the drive is full. Free up space, or choose a folder on another drive.', '磁盘空间不足。请腾出空间,或换一个其他磁盘上的文件夹。'), + 'write_in_use': ('a file there is in use by another program. Close that program, then try again.', '该文件夹中有文件被其他程序占用。请关闭该程序后再试。'), + 'write_missing': ('the folder is no longer there, or its drive was disconnected. Choose the folder again.', '这个文件夹已不存在,或所在磁盘已断开。请重新选择文件夹。'), 'write_path_long': ('the path is too long. Choose a folder closer to the top of the drive.', '路径太长,请选择层级更浅的文件夹。'), - 'write_other': ('Choose another folder and try again.', '请换一个文件夹再试一次。'), + 'write_other': ('the system did not allow the file to be written. Choose another folder and try again.', '系统不允许写入文件。请换一个文件夹再试一次。'), 'video': NAMES['video'], 'text': NAMES['text'], 'decoder': NAMES['decoder'], 'sampling': NAMES['sampling'], 'readme': ( 'FreeVideo download list\n' @@ -106,6 +108,10 @@ def download_write_reason(error, folder): if (error.errno == errno.ENAMETOOLONG or winerror == 206 or winerror == 3 and any(path is not None and len(str(path)) > 260 for path in paths)): return 'path_long' + if winerror in (32, 33) or error.errno in (errno.EBUSY, errno.ETXTBSY): + return 'in_use' + if winerror in (2, 3) or error.errno == errno.ENOENT: + return 'missing' return 'other' diff --git a/freevideo_engine/modern_launcher.py b/freevideo_engine/modern_launcher.py index 0ac36fb5..41ff7539 100644 --- a/freevideo_engine/modern_launcher.py +++ b/freevideo_engine/modern_launcher.py @@ -136,6 +136,7 @@ def ready(socket=socket, pending=pending): def create_ui(session, *, show=True, instance=None): + from .launcher_session import log_error from .windows_ux import taskbar_identity taskbar_identity() from PySide6.QtCore import QObject, Property, QTimer, QUrl, Signal, Slot, Qt @@ -195,6 +196,7 @@ def invoke(self, function, *args, **kwargs): function(*args, **kwargs) except Exception: session.error = traceback.format_exc() + log_error(session.error) self.refresh() @Slot() @@ -228,6 +230,7 @@ def refresh(self): except Exception: # A failed status read must remain copyable and not kill the UI. session.error = traceback.format_exc() + log_error(session.error) from .offline_errors import alias_failure if alias_failure(session.error): # The card says what to do; the details keep the cause. @@ -350,7 +353,8 @@ def importPackages(self, urls): for value in urls: url = value if isinstance(value, QUrl) else QUrl(str(value)) if not url.isLocalFile(): - session.error = session.t('Drop downloaded ZIP files here.', '请拖入已下载到本机的 ZIP 文件。') + # A hint, not a failure: the card stays as it was. + session.action_notice = 'drop_local_zip' self.refresh() return paths.append(url.toLocalFile()) diff --git a/freevideo_engine/offline_errors.py b/freevideo_engine/offline_errors.py index ade3d1b8..1abbdea1 100644 --- a/freevideo_engine/offline_errors.py +++ b/freevideo_engine/offline_errors.py @@ -20,8 +20,18 @@ 'path': ('The offline package could not be imported: the path of the chosen folder is too long to save some of ' 'the files. Choose a folder with a shorter path%s and import again.', '离线包未能导入:所选文件夹的路径太长,部分文件无法保存。请换一个路径更短的文件夹再导入%s。'), + 'in-use': ('The offline package could not be imported: a file is in use by another program. Close programs that ' + 'may be using the folder (for example an antivirus scan), then import again.', + '离线包未能导入:有文件被其他程序占用。请关闭可能正在使用该文件夹的程序(例如杀毒软件扫描),再导入。'), + 'missing': ('The offline package could not be imported: a file disappeared during the import, or the drive was ' + 'disconnected. Check that the package and the folder are still there, then import again.', + '离线包未能导入:导入过程中有文件不见了,或磁盘已断开。请确认离线包和文件夹都还在,再导入。'), + 'read': ('The offline package could not be imported: reading it failed, so the file or the drive may be damaged. ' + 'Download the package again or copy it to another drive, then import again.', + '离线包未能导入:读取时出错,文件或磁盘可能已损坏。请重新下载离线包,或复制到其他磁盘后再导入。'), 'other': ('The offline package could not be imported. Choose another folder and import again.', '离线包未能导入。请换一个文件夹再导入。'), + 'import-title': ('The offline package was not imported', '离线包未能导入'), } # The example folder is a Windows path; other systems leave it out. PATH_EXAMPLE = (', such as D:\\FreeVideo,', ',例如 D:\\FreeVideo') @@ -44,6 +54,10 @@ def write_reason(error, *, windows=None): if code is not None: if code in (5, 19): return 'permission' + if code in (32, 33): # sharing and lock violations + return 'in-use' + if code in (23, 1392, 1117): # data error (CRC), corrupt file, device I/O error + return 'read' if code in (39, 112): return 'disk' if code == 206: @@ -56,6 +70,10 @@ def write_reason(error, *, windows=None): return 'disk' if error.errno == errno.ENAMETOOLONG: return 'path' + if error.errno in (errno.EBUSY, errno.ETXTBSY): + return 'in-use' + if error.errno == errno.EIO: + return 'read' missing = error.errno == errno.ENOENT if win and missing: try: @@ -65,7 +83,8 @@ def write_reason(error, *, windows=None): return 'path' except Exception: pass - return 'other' + # A missing file that is not explained by a long path: moved, deleted or a disconnected drive. + return 'missing' if missing else 'other' def guidance(reason, zh=False, *, windows=None): diff --git a/freevideo_engine/original_audio.py b/freevideo_engine/original_audio.py index 417b3506..f50178fc 100644 --- a/freevideo_engine/original_audio.py +++ b/freevideo_engine/original_audio.py @@ -18,7 +18,7 @@ 'audio_original_long': ('This audio is longer than 30 seconds. Generate it in the Create view, or use an audio file of 30 seconds or less.', '这段音频超过 30 秒,请到创作面板里生成,或换一段 30 秒以内的音频。'), 'audio_original_limit': ('This audio is longer than 2 hours. Use an audio file of 2 hours or less.', '这段音频超过 2 小时,请换一段 2 小时以内的音频。'), 'audio_original_part': ('With "Use as is", each part can be up to 30 seconds.', '用“原样使用”时,每一段最长 30 秒。'), - 'audio_original_passes': ('Audio longer than 30 seconds used as is is made in parts, which needs "Two-pass acceleration". Turn it on or set the audio to "Reference".', '超过 30 秒的音频选“原样使用”时会分段生成,需要“二次采样加速”。请打开“二次采样加速”,或把音频改选“参考”。'), + 'audio_original_passes': ('Audio longer than 30 seconds used as is is made in parts, which needs "Two-pass acceleration". Turn it on or set the audio to "Reference".', '超过 30 秒的音频选“原样使用”时会分段生成,需要“二采加速”。请打开“二采加速”,或把音频改选“参考”。'), 'audio_original_route': ('"Use as is" is not available here yet. Set the audio to "Reference".', '这里还不能用“原样使用”的音频,请改选“参考”。'), 'audio_original_backend': ('"Use as is" is not available on this computer yet.', '这台电脑上还不能用“原样使用”。'), 'audio_original_lead': ('To continue a video with audio used as is, select audio that starts at least 1 second into the file: the first second overlaps the saved video.', '续接已保存的视频并原样使用音频时,所选音频要从文件第 1 秒之后开始:前 1 秒与已保存的视频重叠。'), diff --git a/freevideo_engine/pool_resources.py b/freevideo_engine/pool_resources.py index 59c229c4..a182b8e8 100644 --- a/freevideo_engine/pool_resources.py +++ b/freevideo_engine/pool_resources.py @@ -149,9 +149,10 @@ def _estimate(self, prompt): allowed = {'text', 'width', 'height', 'seconds', 'seed', 'two_pass', 'base_steps', 'refine_steps', 'force_regenerate', 'preview', 'frames', 'step_cache', 'upscale_factor', 'refine_from', 'continue_from', 'first_frame_reference', - 'voice_reference', 'hide_tail', 'allow_empty_prompt'} + 'voice_reference', 'hide_tail', 'allow_empty_prompt', 'upscale_from'} if (set(inputs) - allowed or any(isinstance(v, (list, dict)) for v in inputs.values()) - or inputs.get('refine_from') or inputs.get('step_cache', 'none') != 'none'): + or inputs.get('refine_from') or inputs.get('upscale_from') + or inputs.get('step_cache', 'none') != 'none'): return None from .geometry import geometry canvas = geometry(inputs.get('width', 1344), inputs.get('height', 768), diff --git a/freevideo_engine/portable_launcher.py b/freevideo_engine/portable_launcher.py index e05c4c82..a1aa5da3 100644 --- a/freevideo_engine/portable_launcher.py +++ b/freevideo_engine/portable_launcher.py @@ -6,7 +6,6 @@ import time from . import component_licenses, launch_view, portable, processes -from .comfy_launcher import Launcher from .comfy_launcher_runtime import Controller, local_url, loopback_url, matches_listener, matches_server, server_info from .monitoring import save from .long_paths import io_path, resolved, plain, plain_text @@ -320,71 +319,6 @@ def cancel(self): processes.stop(self.child) -class PortableLauncher(Launcher): - def __init__(self, window, root): - self.bundle_root = Path(plain(resolved(root))) - self.consent_path = io_path(self.bundle_root)/'engine/portable-consent.json' - controller = PortableController(self.bundle_root) - super().__init__(window, controller.source, controller=controller) - self.loading_settings = True - for name, key in (('comfy', 'root'), ('engine', 'engine'), ('python', 'python'), ('url', 'url')): - getattr(self, name).set(controller.selection[key]) - self.loading_settings = False - from .launcher_view import Card, Progress - from . import branding as b - self.bundle_progress = Card(self.pages[3], padding=b.space(4)) - body = self.bundle_progress.body - self.ttk.Label(body, textvariable=self.phase, style='ProgressTitle.Card.TLabel', anchor='center').pack(fill='x') - self.overall_bar = Progress(body); self.overall_bar.pack(fill='x', pady=b.space(2)) - self.ttk.Label(body, textvariable=self.overall_text, style='Meta.Card.TLabel', anchor='center').pack(fill='x') - self.bar = Progress(body, subdued=True); self.bar.pack(fill='x', pady=b.space(2)) - self.ttk.Label(body, textvariable=self.details, style='Meta.Card.TLabel', wraplength=530).pack(fill='x') - self.ttk.Label(body, textvariable=self.current_text, style='Meta.Card.TLabel').pack(fill='x') - self.bundle_note = self.ttk.Label(self.pages[3], style='Meta.TLabel', wraplength=600, anchor='center') - self.bundle_note.pack(fill='x') - self.refresh() - - def changed(self, *_): - if self.loading_settings: - return - self.queue_save() - if self.launch_selection and _ and _[0] in (str(self.url), str(self.lan_access)): - return # The shared settings saver applies the connection change. - if not self.controller.busy: - self.controller.restore({'url': self.url.get(), 'lan_access': self.lan_access.get()}) - self.launch_selection = dict(self.controller.selection) - self.reset_browser() - self.refresh() - - def refresh(self): - self.wizard_step = 3 - super().refresh() - self.back_button.configure(text=self.t('Settings', '设置')) - if not self.consent_path.exists() and not self.controller.busy: - self.primary.configure(text=self.t('Accept licenses & start', '同意许可证并启动')) - if hasattr(self, 'bundle_progress'): - if self.controller.busy: - self.bundle_progress.pack(fill='x', before=self.bundle_note) - else: - self.bundle_progress.pack_forget() - note = self.t('Python, ComfyUI and models are included.', '已包含 Python、ComfyUI 和模型。') - if not self.consent_path.exists(): - note += '\n' + self.t('Licenses: models/edge/LICENSE', '许可证:models/edge/LICENSE') - self.bundle_note.configure(text=note) - - def act(self): - if self.controller.busy: - return - if not self.consent_path.exists(): - save(self.consent_path, dict(source_commit=self.controller.bundle['source_commit'], accepted_at=time.time())) - self.started = time.monotonic() - super().act() - - def back(self): - self.show_options() - - - def gui(root): from .modern_launcher import main main(portable_session(root)) diff --git a/freevideo_engine/refine.py b/freevideo_engine/refine.py index b5165d95..0750da58 100644 --- a/freevideo_engine/refine.py +++ b/freevideo_engine/refine.py @@ -36,8 +36,8 @@ def generate_latents(transformer, prompt_embeds, text_token_tags, num_frames, nu from src.inference.render import KEYFRAME_NOISE_AUG if refine_schedule is not None: - from .refine_schedule import COMMUNITY - if refine_schedule != COMMUNITY or refine_steps != 3: + from .refine_schedule import SIGMAS + if refine_schedule not in SIGMAS or refine_steps != 3: raise ValueError('Independent refinement requires the exact three-step schedule') else: validate_tail(num_steps, refine_steps) @@ -97,7 +97,7 @@ def generate_latents(transformer, prompt_embeds, text_token_tags, num_frames, nu if refine_schedule is not None: from .refine_schedule import schedulers - video_scheduler, audio_scheduler = schedulers(device) + video_scheduler, audio_scheduler = schedulers(device, refine_schedule) start = 1 else: video_scheduler, audio_scheduler = scheduler(shift=video_shift), scheduler(shift=audio_shift) diff --git a/freevideo_engine/refine_schedule.py b/freevideo_engine/refine_schedule.py index f9101fd4..f4ee86db 100644 --- a/freevideo_engine/refine_schedule.py +++ b/freevideo_engine/refine_schedule.py @@ -6,14 +6,25 @@ COMMUNITY = 'community-sigma3-v1' VIDEO_SIGMAS = (0.9035, 0.6316, 0.3158, 0.) +# Upscaling a finished video: the community clocks scaled to start at 0.30, so +# three steps add detail at the larger size while the picture keeps its content. +UPSCALE = 'upscale-sigma3-v1' +UPSCALE_SIGMAS = (0.30, 0.2097, 0.1049, 0.) +SIGMAS = {COMMUNITY: VIDEO_SIGMAS, UPSCALE: UPSCALE_SIGMAS} -def schedulers(device): +def sigmas(schedule): + if schedule not in SIGMAS: + raise ValueError('Unsupported refinement schedule') + return SIGMAS[schedule] + + +def schedulers(device, schedule=COMMUNITY): import torch from diffusers import MiniMaxH3Scheduler # Keep the leading 1.0 used by the verified community workflow. It is # initialization only: the three executed calls start at index one. - sigma = torch.tensor((1.,) + VIDEO_SIGMAS, device=device, dtype=torch.float32) + sigma = torch.tensor((1.,) + sigmas(schedule), device=device, dtype=torch.float32) raw = sigma / (12. + (1. - 12.) * sigma) audio_sigma = 3. * raw / (1. + 2. * raw) video, audio = MiniMaxH3Scheduler(shift=12.), MiniMaxH3Scheduler(shift=3.) @@ -22,9 +33,9 @@ def schedulers(device): return video, audio -def timesteps(device, task): +def timesteps(device, task, schedule=COMMUNITY): from .adaln import modality_timesteps - video, audio = schedulers(device) + video, audio = schedulers(device, schedule) return modality_timesteps(video.timesteps[1:], audio.timesteps[1:], task) @@ -34,8 +45,7 @@ def modulation(engine, schedule): if schedule is None: yield None return - if schedule != COMMUNITY: - raise ValueError('Unsupported refinement schedule') + sigmas(schedule) import torch from .adaln import CachedModulation, ScheduleCursor, TableCache from .adaln_assets import restore_projections @@ -49,7 +59,7 @@ def modulation(engine, schedule): return manifest = json.loads((Path(engine.cache) / 'manifest.json').read_text(encoding='utf-8')) task = getattr(engine, 'adaln_task', engine.task) - times = timesteps(device, task) + times = timesteps(device, task, schedule) cursor = ScheduleCursor(times) fetch = getattr(engine, 'fetch_tables', True) cache = TableCache(engine.cache, manifest['source_id'], 3, task=task, diff --git a/freevideo_engine/release_notes.json b/freevideo_engine/release_notes.json index 5bb0978f..2f25c133 100644 --- a/freevideo_engine/release_notes.json +++ b/freevideo_engine/release_notes.json @@ -1,41 +1,78 @@ { "schema": 1, - "product_version": "0.6.3", + "product_version": "0.6.4", "en": { - "summary": "Image generation adds the MOSS-Image model, failures state the cause and the next step, touch and portrait screens are improved, and a number of problems are fixed.", + "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": [ - "Image generation adds the MOSS-Image model, installed in one click, and better queueing and model loading: several pictures can wait in line and the status shows the place; models that made room for another program load again once the room is free; opening the image view loads the image model where it fits; when another program holds the graphics card, H3 Image plans against the memory actually free and no longer runs short at the first step; and the second-pass upscale no longer reloads the video model when memory suffices, so the wait is shorter.", - "Failures say why and what to do next: a launcher crash, an incomplete installation file, a failed model upgrade, an unfinished assistant task, a ComfyUI start failure, an unreadable folder or undeletable video in the library or when sharing, a prompt rewrite cancelled before generation, release notes that cannot be loaded, a tutorial example that cannot be filled in, and a stopped FreeVideo on this computer each state the cause and the next step instead of a raw error or no response. When an update fails, both buttons sit under the reason, and a full disk comes with the step to free space.", - "The computer stays awake while a video is made: Windows and Linux no longer go to sleep on their own during generation, except on battery.", - "Touch and portrait screen improvements: actions that a mouse reveals on hover are shown on touch screens; tall portrait windows use their full height; on touch screens wider than a phone the editor's and the image view's controls are larger and top-bar links and number steppers have larger tap areas; on a phone Creations in the top bar opens the works without a second entry under the picture; on a narrow screen Generate and Cancel stay whole and easy to tap; and the phone page no longer comes up blank when opened over the local network or a remote link.", - "The library opens the folder that holds the videos: a Video folder button, and Show in folder for every video; when the folder cannot be opened, the reason is stated.", - "The creation panel and the editor share one generation bar: the editor uses the same description, size, length and quality settings as the creation panel, prefilled for the work; the description box grows with its text; a cleared length, width or height stays empty, and Generate names the value to fill in and opens that field; the empty-description check sits right above Generate and the progress word is no longer cut short; with audio used as it is, a lock before the length says on hover or tap why it is fixed; and the creation panel no longer flickers at certain window widths.", - "Your own pictures for a new character: each of the four views takes a picture of your own, and Generate fills only the views still empty.", - "Image editor and library improvements: on a narrow screen every tool's options fit and the rest go under More; after a batch delete, Escape still leaves selecting and the next delete removes only the works picked then; a failed library read clears the loading placeholders and offers Retry before Report a problem; the recent-works strip on the creation page states the reason when it cannot be read and can be read again; in the image view a failure card keeps its reason line and buttons in place when reporting is unavailable, and every reference picture shows its number in full.", - "Assistant improvements: audio can be used as it is to continue a saved video, Tab stays inside the drawer and dialogs and a deleted chat stays gone, and the connection light opens a menu whose main action is Reconnect.", - "Deletion removes more related records: deleting a work also removes its report number from the report index, managed ComfyUI keeps no file names in its logs, with old run folders pruned, and stopping the image editor while reference pictures are uploading removes the ones already sent at once.", - "Fixes: after a continued part finishes, the next part is ready as on opening the work; the editor writes only what changes as the playhead moves; remote visits load faster; cards below the minimum show as unsupported; model download continues when the mount table is unreadable; the launcher reads the set card number by CUDA's rules and names it if unmatched; launcher notices change language with the interface; long labels in the update notes fit a narrow launcher window; editor exports leave out unsent planned parts; a second pass that fails to start shows its error in the tooltip and report.", - "Editor improvements: the top-bar tabs stay in place and keep focus when the editor opens; menus close with Escape and move with the arrow keys; on a narrow screen the Subtitles track name fits and the project menu opens below the name; jumping with the arrow keys keeps the playhead in view, and near 0 s the playhead handle no longer covers the track header; Escape stops a drag without adding an undo step; menus, floating panels, the Fill/Fit switch and a failed part's card are solid; and leaving the editor stops a media preview, and late previews or clips no longer land in the hidden editor." + "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 模型,失败时说明原因和下一步,触屏与竖屏显示改进,并修复了多项问题。", + "summary": "修复 MOSS-Image 出图报错;作品库可将视频放大到 4K,首帧、尾帧可与参考图同用,失败说明更完整,剪辑视图与启动器多项改进。", "changes": [ - "图片生成新增 MOSS-Image 模型,可一键安装;排队与模型载入改进:可同时排队多张图片,状态显示排队位置;为其他程序让出显存的模型在空间恢复后重新载入;打开图像视图时,显存够用就载入图像模型;显卡被其他程序占用时,H3 Image 按实际空闲显存安排,不再在第一步显存不足;二采放大时,显存足够则不再重新载入视频模型,等待更短。", - "失败时说明原因和下一步:启动器意外退出、安装文件不完整、模型升级失败、助手任务未完成、ComfyUI 启动失败、作品库与分享中无法读取的文件夹或无法删除的视频、生成前被取消的提示词改写、更新说明读取不到、教程示例无法填入、本机上的 FreeVideo 已停止,都写明原因和下一步,不再显示原始错误行或没有反应。更新失败时,两个按钮排在原因下方;磁盘空间不足时提示清理后重试。", - "生成视频时电脑不再自行睡眠:Windows 与 Linux 在制作视频期间不会自动进入睡眠;使用电池时不启用。", - "触屏与竖屏显示改进:触屏上显示原本要鼠标悬停才出现的操作;竖屏窗口使用全部高度;比手机宽的触屏上,剪辑视图和图像视图的按键加大,顶栏链接和数值调节按钮的点按范围也加大,更易点中;手机上从顶栏的“作品库”进入作品,画面下方不再重复显示入口;窄屏下生成与取消按钮保持完整、易于点按;通过局域网或远程链接打开手机页时不再空白。", - "作品库可直接打开视频所在文件夹:新增“视频文件夹”按钮,每个视频都能“在文件夹中显示”;无法打开时说明原因。", - "创作面板与剪辑视图使用同一个生成栏:剪辑视图里的生成栏使用与创作面板相同的描述、尺寸、时长和质量设置,并按当前作品预填;描述框随文字增高;清空的时长、宽、高保持为空,点击生成时提示需填写的项并打开该项;描述为空时的确认提示显示在“生成”正上方,进度词不再被截断;音频原样使用时,时长前的锁形图标在悬停或点按时说明时长为何固定;创作面板在各种窗口宽度下都不再闪动。", - "新建角色时可上传自己的四个视角图片,生成只补还空着的视角。", - "图片编辑与作品库改进:窄屏下每个工具的选项都能完整显示,其余收入“更多”;批量删除后,按 Esc 仍可退出选择,下次删除只删除当时选中的作品;作品库读取失败时清除加载占位,并在“提交问题”前提供“重试”;创作页的最近作品栏读取失败时也说明原因,可重新读取;图像视图的失败卡在报告不可用时,原因行和按钮不再左移,参考图每张都完整显示编号。", - "AI 助手改进:音频可原样用于续接已保存的视频;Tab 键停留在抽屉和对话框内,已删除的对话不再出现;连接指示灯可打开菜单,主要操作为“重新连接”。", - "删除时清除更多相关记录:删除作品时,其报告编号也从报告索引中移除;受管理的 ComfyUI 日志不再记录文件名,旧的运行目录会被清理;图片编辑中途停止时,已上传的参考图立即从服务器删除。", - "问题修复:续接的一段生成完成后,下一段与打开作品时一样就绪;剪辑视图在播放头移动时只写入变化的内容;远程访问时页面加载更快;低于最低配置的显卡一律显示为不支持;模型下载在无法读取挂载表时仍可继续;启动器按 CUDA 的规则读取所设的显卡序号,对不上时说明所设的值;切换界面语言时,已显示的启动器提示一并换语言;启动器窗口较窄时,更新说明里的长标签不再超出窗口;剪辑导出时不再包含从未发送的计划段;二采未能开始时,提示与报告写明错误。", - "剪辑视图改进:打开剪辑视图时顶栏标签保持原位、焦点不丢失;菜单可用 Esc 关闭、用方向键切换选项;窄屏下轨道名“Subtitles”完整显示,项目菜单在名字下方打开;用方向键跳转时播放线保持在可见范围内,靠近 0 秒时播放头把手不盖住轨道头;拖动中按 Esc 停止拖动,不多出一步撤销;菜单与浮动面板、画面上的“铺满/完整显示”切换和失败段的说明卡改为实色;离开剪辑视图后素材预览不再出声,晚到的预览和素材不会写进隐藏的剪辑。" + "图像:修复 0.6.3 中 MOSS-Image 出图时报错的问题;内存紧张时,H3 Image 直接重新载入模型,不再先保留、随后又释放;引擎忙时,编辑图片中的 AI 生成排队等候,前一项完成后自动开始,不再直接拒绝,每次重试都重新上传参考图。", + "已完成的 24 fps 视频可在作品库放大 1.5 倍或放大到 4K(3840 宽):本机能生成该尺寸与时长时,“更多”菜单提供这一项;画面保留,视频原有的声音照原样使用。", + "失败时说明原因和下一步(续),原文保留在详情中:仅深度参考视频无法转成深度、助手或 AI 全自动任务未完成、从 ComfyUI 菜单打开失败、更新失败、长视频失败、重做或续接未开始、作品库删除遇到文件占用、无权限或磁盘已满,以及命令面板和手机连接;保存失败写“保存失败”并接服务器原话,连接断开时直接说明;窄窗口里画面上的失败卡完整显示;图像视图失败卡上的“提交问题”与“重试”样式一致。", + "删除与记录更干净:彻底删除图片时,它的提示词也从视频提示词历史中清除;其他图片或视频仍在使用的提示词保留;受管理的 ComfyUI 不再在浏览器中保存工作流草稿;已完成任务的记录只保留编号、短代码和时间,不含错误文本。", + "剪辑视图的生成栏:帧弹层中显示首帧参考开关,并按所编辑的这一段自己的设置保存;在时间线上分开选取多段时,生成栏不再失效;窄窗下“生成”保持在栏内,不再落到轨道工具栏之下;空白的剪辑沿用离开期间创作面板所选的质量,已保存或已有分段的剪辑保留自己的质量。", + "剪辑视图的时间线与面板:Ctrl+滚轮缩放时,指针下的时间点保持不动;未生成的分段被选中时,右侧面板说明“生成后可调整”;暂时离开的剪辑视图不再每 2 秒读取导入列表,回来时立即读取。", + "设置改进:找不到的模型文件夹在任何宽度下显示为一行,开头以省略号让位、末级文件夹完整,复制时取完整路径;设置关闭后才失败的保存会以失败提示显示,并可一键回到该设置。", + "启动器与安装:更新窗口中说明下方的按钮按窗口宽度换行;源码安装的桌面快捷方式直接打开启动器;启动器、安装、下载与离线包的失败写明原因、下一步和报告方式;更新或安装软件包时遇其他程序占用文件,会等待并重新安装,再报告错误。", + "作品库与菜单:在其他视图上方打开作品库后,淡入结束即获得键盘焦点,Esc 与方向键立即可用;“作品”菜单中的“信息”项显示信息图标,不再显示警告三角;作品库底部的撤销条和“已选”操作条完全不透明,手机宽度下不再透出缩略图。", + "手机宽度的显示:AI 全自动中附加图片的移除按钮保持原有角标大小,点按上传失败的图片时是重试,而不是移除;手机连接面板在入口正下方、右边对齐,离屏幕边至少 8 像素。", + "教程改进:精选示例点“开始使用”后,光标位于 AI 全自动输入框,输入框稍后才打开时也一样;“运行状态”教程的步骤与图片跟随顶栏状态及其运行状态面板;教程书的图文跟随改版后的面板,剪辑视图的图片对应借用的生成栏,续接一段时从“素材”添加图片,保存帧的提示写明“作品库”。", + "首帧、尾帧与中间帧可与参考图、参考视频同用:同一次生成中可以同时使用关键帧和参考图、参考视频,使用说明与教程书已相应更新;长度与时间估算按每个关键帧一张同尺寸画布计算。" ] }, "history": [ + { + "product_version": "0.6.3", + "en": { + "summary": "Image generation adds the MOSS-Image model, failures state the cause and the next step, touch and portrait screens are improved, and a number of problems are fixed.", + "changes": [ + "Image generation adds the MOSS-Image model, installed in one click, and better queueing and model loading: several pictures can wait in line and the status shows the place; models that made room for another program load again once the room is free; opening the image view loads the image model where it fits; when another program holds the graphics card, H3 Image plans against the memory actually free and no longer runs short at the first step; and the second-pass upscale no longer reloads the video model when memory suffices, so the wait is shorter.", + "Failures say why and what to do next: a launcher crash, an incomplete installation file, a failed model upgrade, an unfinished assistant task, a ComfyUI start failure, an unreadable folder or undeletable video in the library or when sharing, a prompt rewrite cancelled before generation, release notes that cannot be loaded, a tutorial example that cannot be filled in, and a stopped FreeVideo on this computer each state the cause and the next step instead of a raw error or no response. When an update fails, both buttons sit under the reason, and a full disk comes with the step to free space.", + "The computer stays awake while a video is made: Windows and Linux no longer go to sleep on their own during generation, except on battery.", + "Touch and portrait screen improvements: actions that a mouse reveals on hover are shown on touch screens; tall portrait windows use their full height; on touch screens wider than a phone the editor's and the image view's controls are larger and top-bar links and number steppers have larger tap areas; on a phone Creations in the top bar opens the works without a second entry under the picture; on a narrow screen Generate and Cancel stay whole and easy to tap; and the phone page no longer comes up blank when opened over the local network or a remote link.", + "The library opens the folder that holds the videos: a Video folder button, and Show in folder for every video; when the folder cannot be opened, the reason is stated.", + "The creation panel and the editor share one generation bar: the editor uses the same description, size, length and quality settings as the creation panel, prefilled for the work; the description box grows with its text; a cleared length, width or height stays empty, and Generate names the value to fill in and opens that field; the empty-description check sits right above Generate and the progress word is no longer cut short; with audio used as it is, a lock before the length says on hover or tap why it is fixed; and the creation panel no longer flickers at certain window widths.", + "Your own pictures for a new character: each of the four views takes a picture of your own, and Generate fills only the views still empty.", + "Image editor and library improvements: on a narrow screen every tool's options fit and the rest go under More; after a batch delete, Escape still leaves selecting and the next delete removes only the works picked then; a failed library read clears the loading placeholders and offers Retry before Report a problem; the recent-works strip on the creation page states the reason when it cannot be read and can be read again; in the image view a failure card keeps its reason line and buttons in place when reporting is unavailable, and every reference picture shows its number in full.", + "Assistant improvements: audio can be used as it is to continue a saved video, Tab stays inside the drawer and dialogs and a deleted chat stays gone, and the connection light opens a menu whose main action is Reconnect.", + "Deletion removes more related records: deleting a work also removes its report number from the report index, managed ComfyUI keeps no file names in its logs, with old run folders pruned, and stopping the image editor while reference pictures are uploading removes the ones already sent at once.", + "Fixes: after a continued part finishes, the next part is ready as on opening the work; the editor writes only what changes as the playhead moves; remote visits load faster; cards below the minimum show as unsupported; model download continues when the mount table is unreadable; the launcher reads the set card number by CUDA's rules and names it if unmatched; launcher notices change language with the interface; long labels in the update notes fit a narrow launcher window; editor exports leave out unsent planned parts; a second pass that fails to start shows its error in the tooltip and report.", + "Editor improvements: the top-bar tabs stay in place and keep focus when the editor opens; menus close with Escape and move with the arrow keys; on a narrow screen the Subtitles track name fits and the project menu opens below the name; jumping with the arrow keys keeps the playhead in view, and near 0 s the playhead handle no longer covers the track header; Escape stops a drag without adding an undo step; menus, floating panels, the Fill/Fit switch and a failed part's card are solid; and leaving the editor stops a media preview, and late previews or clips no longer land in the hidden editor." + ] + }, + "zh": { + "summary": "图片生成新增 MOSS-Image 模型,失败时说明原因和下一步,触屏与竖屏显示改进,并修复了多项问题。", + "changes": [ + "图片生成新增 MOSS-Image 模型,可一键安装;排队与模型载入改进:可同时排队多张图片,状态显示排队位置;为其他程序让出显存的模型在空间恢复后重新载入;打开图像视图时,显存够用就载入图像模型;显卡被其他程序占用时,H3 Image 按实际空闲显存安排,不再在第一步显存不足;二采放大时,显存足够则不再重新载入视频模型,等待更短。", + "失败时说明原因和下一步:启动器意外退出、安装文件不完整、模型升级失败、助手任务未完成、ComfyUI 启动失败、作品库与分享中无法读取的文件夹或无法删除的视频、生成前被取消的提示词改写、更新说明读取不到、教程示例无法填入、本机上的 FreeVideo 已停止,都写明原因和下一步,不再显示原始错误行或没有反应。更新失败时,两个按钮排在原因下方;磁盘空间不足时提示清理后重试。", + "生成视频时电脑不再自行睡眠:Windows 与 Linux 在制作视频期间不会自动进入睡眠;使用电池时不启用。", + "触屏与竖屏显示改进:触屏上显示原本要鼠标悬停才出现的操作;竖屏窗口使用全部高度;比手机宽的触屏上,剪辑视图和图像视图的按键加大,顶栏链接和数值调节按钮的点按范围也加大,更易点中;手机上从顶栏的“作品库”进入作品,画面下方不再重复显示入口;窄屏下生成与取消按钮保持完整、易于点按;通过局域网或远程链接打开手机页时不再空白。", + "作品库可直接打开视频所在文件夹:新增“视频文件夹”按钮,每个视频都能“在文件夹中显示”;无法打开时说明原因。", + "创作面板与剪辑视图使用同一个生成栏:剪辑视图里的生成栏使用与创作面板相同的描述、尺寸、时长和质量设置,并按当前作品预填;描述框随文字增高;清空的时长、宽、高保持为空,点击生成时提示需填写的项并打开该项;描述为空时的确认提示显示在“生成”正上方,进度词不再被截断;音频原样使用时,时长前的锁形图标在悬停或点按时说明时长为何固定;创作面板在各种窗口宽度下都不再闪动。", + "新建角色时可上传自己的四个视角图片,生成只补还空着的视角。", + "图片编辑与作品库改进:窄屏下每个工具的选项都能完整显示,其余收入“更多”;批量删除后,按 Esc 仍可退出选择,下次删除只删除当时选中的作品;作品库读取失败时清除加载占位,并在“提交问题”前提供“重试”;创作页的最近作品栏读取失败时也说明原因,可重新读取;图像视图的失败卡在报告不可用时,原因行和按钮不再左移,参考图每张都完整显示编号。", + "AI 助手改进:音频可原样用于续接已保存的视频;Tab 键停留在抽屉和对话框内,已删除的对话不再出现;连接指示灯可打开菜单,主要操作为“重新连接”。", + "删除时清除更多相关记录:删除作品时,其报告编号也从报告索引中移除;受管理的 ComfyUI 日志不再记录文件名,旧的运行目录会被清理;图片编辑中途停止时,已上传的参考图立即从服务器删除。", + "问题修复:续接的一段生成完成后,下一段与打开作品时一样就绪;剪辑视图在播放头移动时只写入变化的内容;远程访问时页面加载更快;低于最低配置的显卡一律显示为不支持;模型下载在无法读取挂载表时仍可继续;启动器按 CUDA 的规则读取所设的显卡序号,对不上时说明所设的值;切换界面语言时,已显示的启动器提示一并换语言;启动器窗口较窄时,更新说明里的长标签不再超出窗口;剪辑导出时不再包含从未发送的计划段;二采未能开始时,提示与报告写明错误。", + "剪辑视图改进:打开剪辑视图时顶栏标签保持原位、焦点不丢失;菜单可用 Esc 关闭、用方向键切换选项;窄屏下轨道名“Subtitles”完整显示,项目菜单在名字下方打开;用方向键跳转时播放线保持在可见范围内,靠近 0 秒时播放头把手不盖住轨道头;拖动中按 Esc 停止拖动,不多出一步撤销;菜单与浮动面板、画面上的“铺满/完整显示”切换和失败段的说明卡改为实色;离开剪辑视图后素材预览不再出声,晚到的预览和素材不会写进隐藏的剪辑。" + ] + } + }, { "product_version": "0.6.2", "en": { @@ -218,43 +255,6 @@ "教程:新增对齐音乐节拍、运行状态、用参考图生成图片、短剧的大纲和站位、短剧成片的剪辑工程五章。" ] } - }, - { - "product_version": "0.5.2", - "en": { - "summary": "The editor shows its preview and timeline again, and Mac installs no longer stop at the GPU check. Images show each step while they generate, have a Seed field and clearer failure cards, and narrow windows fit better.", - "changes": [ - "Editor: the edit page keeps its layout again, so the preview and the timeline are no longer pushed off the screen by the media library.", - "Mac install: an installation or repair no longer stops at the GPU check step when every check has passed.", - "Install and update: a first installation offers H3 Video or H3 Image, and an image-only installation adds the video model later. Graphics package downloads keep trying through a slow connection, a model download that cannot resume starts again, an update restores a missing tool, and setup waits briefly for another running installation and names it.", - "Images view: the picture is shown after each step while it generates, and progress follows time with one percentage and the remaining time. A Seed field under Advanced keeps a number, or draws a new seed for each picture when empty.", - "Picture failures: the reason and Retry sit inside the card, Autopilot cards open technical details as video cards do, and memory reasons use formal wording. The report button reads \"Download report\" on the image page, in Autopilot and in the editor.", - "Edit page: the quality setting sits beside Generate and shows the number of steps. Music on the second sound track starts from its own description box.", - "Output: an Output setting can write a separate 10-bit copy of each generated video; the regular file and the page preview are unchanged.", - "Narrow windows: the node view top bar steps entries aside and then wraps, the view switch sits in the same place in every view, and Escape in the phone panel closes only the panel. At 400 px the image model name and ratio menu show whole, image editor tools wrap, the result menu opens upward when needed, and editor track names show in full.", - "Autopilot: Enter, Ctrl+Enter and paste work in the chat and image pages, the message hint fits one line on phones, the header keeps a readable job title, and long titles stay inside the job card.", - "Progress: long quiet stages of a video run show real counts, such as frames, layers or files, after the stage text.", - "Generation: the text encoder loads faster from slow drives when memory is short, and a loaded engine is reused when only the tiling changes. A library character's voice comes into the shot with its pictures, and prompt enhancement reads the picture or video of a connected load node.", - "Tutorial and messages: the tutorial adds chapters on making pictures, middle frames and saving a frame. A refusal caused by Reserved VRAM names that setting, the connection card names the localhost address to open, and a long-video join failure says whether the seam record is missing or unreadable." - ] - }, - "zh": { - "summary": "编辑页重新显示预览和时间线,Mac 安装不再停在 GPU 检查一步;图片生成时逐步显示画面,新增种子输入,失败卡片更清楚,窄窗口排版更合适。", - "changes": [ - "编辑页:版面恢复正常,预览和时间线不再被素材库挤出屏幕。", - "Mac 安装:安装或修复时,各项检查都已通过却仍停在 GPU 检查一步的问题已修复。", - "安装和更新:首次安装可选 H3 Video 或 H3 Image,只装图像模型的以后可再加视频模型。GPU 组件下载在网络慢时持续重试,无法续传的模型下载重新开始,更新补回缺失的工具,另一个安装进行中时稍等并说明是哪一个。", - "图像视图:生成时每一步都显示当前画面,进度按时间推进,只显示一个百分比和剩余时间。“高级”里新增“种子”,填数字固定种子,留空则每张图重新取种子。", - "图片失败:原因和“重试”放在卡片内,AI 全自动中的卡片和视频卡片一样可展开技术详情,内存不足的原因改为书面措辞。图像页、AI 全自动和编辑页的报告按钮统一为“下载报告”。", - "编辑页:画质设置放在“生成”旁边,并显示步数。第二条声音轨上的音乐从自己的描述框开始填写。", - "输出:可在设置中另外写一份 10 位视频,原有文件和页面预览不变。", - "窄窗口:节点视图顶栏的入口先依次让位再折行,各视图的切换位置一致,手机面板里按 Esc 只关闭面板。400 宽下图像模型名称和比例菜单完整显示,图像编辑工具折行,结果菜单放不下时向上展开,剪辑轨道名称完整显示。", - "AI 全自动:对话页和图像页的 Enter、Ctrl+Enter 和粘贴恢复正常,手机上的输入提示一行放下,顶栏保留可读的任务名,长标题不再超出任务卡片。", - "进度:视频生成中较长的无变化阶段,在阶段文字后显示真实计数,例如帧数、层数或文件数。", - "生成:内存紧张时,文本编码器从慢速硬盘加载更快;只有分块变化时复用已加载的引擎。素材库角色的声音随其图片一起带入镜头,提示词增强会读取所连加载节点中的图片或视频。", - "教程和提示:教程新增生成图片、中间帧和保存帧三章。只因“预留显存”导致的拒绝会指出该设置,连接卡片会给出应打开的 localhost 地址,长视频拼接失败时说明接缝记录是缺失还是无法读取。" - ] - } } ] } diff --git a/freevideo_engine/two_pass.py b/freevideo_engine/two_pass.py index 22444daf..938ece62 100644 --- a/freevideo_engine/two_pass.py +++ b/freevideo_engine/two_pass.py @@ -119,7 +119,8 @@ def side(length): return dict(width=w, height=h, frames=target['frames']), dict(width=lift_w, height=lift_h, frames=target['frames']) -def plan(canvas, enabled=True, task='t2va', *, base_steps=8, refine_steps=3, staged=False, scale=2): +def plan(canvas, enabled=True, task='t2va', *, base_steps=8, refine_steps=3, staged=False, scale=2, + schedule=None): """Align the smaller canvas, lift, center-crop, then refine at the target. Odd multiples of 32 need up to 32 extra pixels before the latent crop. @@ -128,7 +129,8 @@ def plan(canvas, enabled=True, task='t2va', *, base_steps=8, refine_steps=3, sta refinement), unless the first pass itself is wanted (a preview or its upscale: staged). Memory pressure never changes this math. `scale` below 2 samples a larger first pass (SCALES) on canvases of at least 512 on the short side; 2 is the - original plan, byte for byte. + original plan, byte for byte. `schedule` names another three-step refinement + clock (refine_schedule.SIGMAS); None is the community one. """ from .geometry import geometry from .media_request import TASKS @@ -192,10 +194,20 @@ def plan(canvas, enabled=True, task='t2va', *, base_steps=8, refine_steps=3, sta if default: result['reason'] = '8 steps on a smaller canvas, learned latent upscale, then the original DMD8 schedule tail (2 steps).' if refine_steps == 3: - from .refine_schedule import COMMUNITY, VIDEO_SIGMAS + from .refine_schedule import COMMUNITY, UPSCALE, sigmas result.update(version=3, mode='vdn%d-lbh-community3' % base_steps, - refine_schedule=COMMUNITY, video_sigmas=list(VIDEO_SIGMAS), + refine_schedule=COMMUNITY, video_sigmas=list(sigmas(COMMUNITY)), reason='%d steps on a smaller canvas, learned latent upscale, then three independent refinement steps.' % base_steps) + if schedule not in (None, COMMUNITY): + # Only a finished video is upscaled this way; its first pass is the video itself. + if schedule != UPSCALE or not staged: + raise ValueError('Unsupported refinement schedule') + # Only the three refinement steps are sampled. + result.update(staged=True, mode='vdn%d-lbh-upscale3' % base_steps, refine_schedule=UPSCALE, + video_sigmas=list(sigmas(UPSCALE)), total_steps=refine_steps, + reason='A finished video, learned latent upscale, then three light refinement steps.') + elif schedule is not None: + raise ValueError('Unsupported refinement schedule') if scale != 2 and upscaling: # Recorded only off the original factor, so 2x plans (and their cache keys) are unchanged. result.update(scale=scale, mode=result['mode'] + '-x%g' % scale, @@ -225,11 +237,14 @@ def steps(sampling_plan=None): base, refine = sampling_plan.get('base_steps'), sampling_plan.get('refine_steps') validate_steps(base, refine if enabled else 2, enabled) expected = base + refine if enabled else base + if enabled and sampling_plan.get('refine_schedule') == 'upscale-sigma3-v1': + expected = refine # a finished video is the first pass: only the refinement is sampled if (type(sampling_plan.get('version')) is not int or sampling_plan['version'] not in (1, 2, 3) or (sampling_plan['version'] == 1 and (base != 8 or refine != (2 if enabled else 0))) or (sampling_plan['version'] == 3 and (not enabled or refine != 3 - or sampling_plan.get('refine_schedule') != 'community-sigma3-v1' - or sampling_plan.get('video_sigmas') != [0.9035, 0.6316, 0.3158, 0.])) + or (sampling_plan.get('refine_schedule'), sampling_plan.get('video_sigmas')) not in ( + ('community-sigma3-v1', [0.9035, 0.6316, 0.3158, 0.]), + ('upscale-sigma3-v1', [0.30, 0.2097, 0.1049, 0.])))) or (not enabled and (type(refine) is not int or refine != 0)) or type(sampling_plan.get('total_steps')) is not int or sampling_plan['total_steps'] != expected): raise ValueError('Invalid sampling step plan') diff --git a/freevideo_engine/windows_bootstrap.ps1 b/freevideo_engine/windows_bootstrap.ps1 index f6efb6fd..f0b838ba 100644 --- a/freevideo_engine/windows_bootstrap.ps1 +++ b/freevideo_engine/windows_bootstrap.ps1 @@ -128,7 +128,7 @@ function Get-FreeVideoUv { [switch]$OfficialOnly) $wheel = $Catalog.windows if ($Catalog.version -ne $Spec.version -or $wheel.legacy_sha256 -ne $Spec.sha256) { - throw 'The uv download catalog does not match the pinned bootstrap version' + throw "The uv download catalog does not match the pinned bootstrap version: this copy of FreeVideo is incomplete or mixes two versions. Download FreeVideo again from https://github.com/FlashML-org/FreeVideo/releases/latest. Log: $LogPath" } $destination = Join-Path $BootstrapRoot ('uv-' + $Spec.version + '\uv.exe') $artifacts = @( diff --git a/freevideo_engine/work_upscale.py b/freevideo_engine/work_upscale.py new file mode 100644 index 00000000..7a353d56 --- /dev/null +++ b/freevideo_engine/work_upscale.py @@ -0,0 +1,185 @@ +"""Upscaling a finished 24 fps video by one 1.5x step. + +The video's own frames, encoded by the video VAE, take the place of a first +pass: the learned latent upscale and three light refinement steps follow +(refine_schedule.UPSCALE), and the original sound is copied as is (the +"Use as is" audio path). Torch is imported only where frames are encoded. +""" +import hashlib +import json +from fractions import Fraction +from pathlib import Path + +FACTOR = 1.5 +NOT_A_WORK = ('Choose a finished FreeVideo video to upscale', '请选择一个已完成的 FreeVideo 视频来放大。') + + +def size(width, height): + """The upscaled size, or None: both sides must be multiples of 64 so the larger + size stays on the 32-pixel grid with the same shape.""" + if any(type(n) is not int or n <= 0 or n % 64 for n in (width, height)): + return None + return width * 3 // 2, height * 3 // 2 + + +def work_request(output_directory, relative): + """A finished, non-preview FreeVideo work in this output folder: (video, saved state).""" + if not isinstance(relative, str) or not relative.strip(): + raise ValueError(NOT_A_WORK[0]) + output_root = Path(output_directory).resolve() + video = (output_root / relative).resolve() + try: + video.relative_to(output_root / 'FreeVideo') + except ValueError: + raise ValueError(NOT_A_WORK[0]) from None + path = video.parent / 'comfy-request.json' + try: + state = json.loads(path.read_text(encoding='utf-8')) if path.is_file() else {} + except (OSError, ValueError): + state = {} + geometry = state.get('geometry') if isinstance(state, dict) else None + if (not isinstance(state, dict) or state.get('status') != 'complete' or state.get('preview') + or Path(state.get('output', '')).resolve() != video or not isinstance(geometry, dict) + or geometry.get('fps') != 24 or size(geometry.get('width'), geometry.get('height')) is None + or type(state.get('seed')) is not int): + raise ValueError(NOT_A_WORK[0]) + if not video.is_file(): + raise ValueError(NOT_A_WORK[0]) + return video, state + + +def _digest(path): + value = hashlib.sha256() + with open(path, 'rb') as stream: + for block in iter(lambda: stream.read(1 << 20), b''): + value.update(block) + return value.hexdigest() + + +def source(path): + """Inspect a finished MP4: one 24 fps picture stream whose sides are multiples + of 64, and a sound track (copied as is). Returns its identity and size.""" + import av + path = Path(path).expanduser().resolve() + if path.suffix.lower() != '.mp4' or not path.is_file(): + raise ValueError(NOT_A_WORK[0]) + try: + with av.open(str(path)) as container: + if len(container.streams.video) != 1 or not container.streams.audio: + raise ValueError(NOT_A_WORK[0]) + stream = container.streams.video[0] + rate = stream.average_rate or stream.guessed_rate + width, height = stream.codec_context.width, stream.codec_context.height + frames = sum(1 for _ in container.demux(stream) if _.size) + except (av.error.FFmpegError, OSError) as error: + raise ValueError(NOT_A_WORK[0]) from error + if rate is None or Fraction(rate) != 24 or size(width, height) is None or frames <= 0: + raise ValueError(NOT_A_WORK[0]) + return dict(output=str(path), sha256=_digest(path), bytes=path.stat().st_size, + width=width, height=height, frames=frames, fps=24) + + +def audio_row(source_info): + """The video's own sound, used as is and cut where its pictures end: an encoder pads + the last sound packet, which would otherwise add a block of repeated frames.""" + from .original_audio import inspect + row = dict(path=source_info['output'], sha256=source_info['sha256'], bytes=source_info['bytes'], + kind='audio', use='original') + info = inspect(row) + end = min(info['end_sample'], source_info['frames'] * info['sample_rate'] // 24) + if end * 24 < (source_info['frames'] - 1) * info['sample_rate']: + raise ValueError("The video's sound is shorter than its pictures; it cannot be upscaled") + return dict(row, range=dict(start_sample=0, end_sample=end)) + + +def media(requested, source_info): + """The request's media: only the video's own sound (audio_row).""" + row = audio_row(source_info) + rows = (requested or {}).get('references') or [] + if (requested or {}).get('loras') or any(value != row for value in rows): + raise ValueError('An upscale of a finished video takes no other inputs') + return {'version': 1, 'references': [row], 'loras': []} + + +def check(source_info, canvas, sampling_plan): + """The request samples exactly this video's frames at 1.5x its size.""" + first = sampling_plan.get('first') or {} + from .geometry import geometry + from .refine_schedule import UPSCALE + if (sampling_plan.get('refine_schedule') != UPSCALE or sampling_plan.get('scale') != FACTOR + or (first.get('width'), first.get('height')) != (source_info['width'], source_info['height']) + or (canvas['width'], canvas['height']) != size(source_info['width'], source_info['height']) + or canvas.get('requested_frames') != source_info['frames'] + or canvas['frames'] != geometry(frames=source_info['frames'])['frames']): + raise ValueError('The upscale request does not match the video it upscales') + + +def _frames(path, width, height, count): + """All frames as RGB uint8, the last one repeated up to the aligned count.""" + import av + import numpy as np + pixels = np.empty((count, height, width, 3), dtype=np.uint8) + index = 0 + with av.open(str(path)) as container: + for frame in container.decode(video=0): + if index == count: + break + image = frame.to_ndarray(format='rgb24') + if image.shape != (height, width, 3): + raise ValueError('The video changed size; it cannot be upscaled') + pixels[index] = image + index += 1 + if not index: + raise ValueError(NOT_A_WORK[0]) + pixels[index:] = pixels[index - 1] + return pixels, index + + +def first_pass(request, torch, *, base, progress=None): + """Encode the finished video as the request's first pass on the CPU. + + Returns (video latents, audio latents, first-pass record, receipt). The audio + latents are the clean "Use as is" track from the request's conditioning, so + the sound is never resampled by the model. + """ + import time + info = request['upscale_source'] + path = Path(info['output']) + if path.stat().st_size != info['bytes'] or _digest(path) != info['sha256']: + raise ValueError('The video changed after it was chosen; choose it again to upscale') + first = request['sampling_plan']['first'] + width, height, frames = first['width'], first['height'], first['frames'] + if (width, height) != (info['width'], info['height']): + raise ValueError('The upscale request does not match the video it upscales') + started = time.perf_counter() + pixels, used = _frames(path, width, height, frames) + from .vae_weights import load_video_encoder + from .media_encoding import encode_visual + vae, _ = load_video_encoder(base) + try: + if hasattr(torch, 'cuda') and torch.cuda.is_available(): + torch.cuda.reset_peak_memory_stats() + video = encode_visual(vae, pixels, posterior='mode', progress=progress) + peak = torch.cuda.max_memory_allocated() if torch.cuda.is_available() else 0 + finally: + del vae + if torch.cuda.is_available(): + torch.cuda.empty_cache() + del pixels + from .fixed_track import split + value = torch.load(request['conditioning'], map_location='cpu', weights_only=True) + _, fixed = split(list(value.get('references') or []), frames, 'cpu') + del value + if fixed is None: + raise ValueError('An upscale copies the video\'s own sound; it was not in the request') + ticks = fixed.shape[0] // 2 + audio = fixed.reshape(2, ticks, 32).permute(0, 2, 1).contiguous() + expected = (1, 24, (frames - 5) // 17 * 5 + 2, height // 16, width // 16) + if tuple(video.shape) != expected or not bool(torch.isfinite(video).all()): + raise ValueError('The encoded video does not match the planned first pass') + seconds = time.perf_counter() - started + record = dict(source='finished_video', step_seconds=[], sample_seconds=seconds, encode_seconds=seconds, + frames_read=used, torch_peak_allocated_bytes=peak, torch_peak_reserved_bytes=peak) + receipt = dict(first_pass_reused=False, first_pass_source='finished_video', + first_pass_source_output=info['output'], upscale_source_sha256=info['sha256']) + return video, audio, record, receipt diff --git a/freevideo_engine/worker.py b/freevideo_engine/worker.py index 5fdef416..4a2bbaad 100644 --- a/freevideo_engine/worker.py +++ b/freevideo_engine/worker.py @@ -100,7 +100,8 @@ def released(engine): base_steps=request['engine_options'].get('steps', 8), refine_steps=request['sampling_plan']['refine_steps'] if request['sampling_plan']['enabled'] else 3, staged=request['sampling_plan'].get('staged', False), - scale=request['sampling_plan'].get('scale', 2)) + scale=request['sampling_plan'].get('scale', 2), + schedule=request['sampling_plan'].get('refine_schedule') if request.get('upscale_source') else None) if request['sampling_plan'] != expected: raise ValueError('Sampling plan does not match the requested canvas and task') metrics['sampling_plan'] = expected @@ -322,6 +323,19 @@ def capture_first(video): allocation = metrics['device_memory'].get('effective_allocator_limit_bytes') or request['gpu_budget_bytes'] if sampling_limit: allocation = min(allocation, sampling_limit) + upscale_first = None + if request.get('upscale_source'): + # Upscale a finished video: its frames, encoded before the video model takes the card, + # are the first pass; the latent upscale and the light refinement follow. + from .paths import base_path + from .work_upscale import first_pass as encode_first_pass + metrics.update(sample_stage='video_encode') + save(request['metrics'], metrics) + print(json.dumps({'event': 'model_load_phase', 'phase': 'Reading the video', 'stage': 'video_encode', + 'epoch': time.time(), 'seconds': time.perf_counter() - started}), flush=True) + upscale_first = encode_first_pass(request, torch, base=Path(options.get('base') or base_path())) + metrics.update(upscale_first[3], first_pass_load_seconds=upscale_first[2]['encode_seconds']) + save(request['metrics'], metrics) factory = lambda: Engine(request['cache'], input_cache_dir=request.get('input_cache_dir'), gpu_allocation_bytes=int(allocation), **dict(options, canvas=request.get('geometry'))) @@ -446,7 +460,13 @@ def sampling_complete(latents, audio, sampled): completed_steps=sampling_plan['base_steps'], total=sampling_plan['total_steps'])), flush=True) else: - if request.get('resume_first_pass'): + if upscale_first is not None: + latents, audio, first, _ = upscale_first + upscale_first = None + latents, audio = latents.to('cuda'), audio.to('cuda') + print(json.dumps(dict(event='first_pass_reused', source='finished_video', + completed_steps=0, total=sampling_plan['total_steps'])), flush=True) + elif request.get('resume_first_pass'): # Upscale a finished preview: its retained first pass # replaces sampling it again; upscale and refine follow. from .decode_resume import load_first_pass @@ -498,11 +518,11 @@ def sampling_complete(latents, audio, sampled): else: metrics['sample_stage'] = 'latent_upscale' save(request['metrics'], metrics) - print(json.dumps(dict(event='latent_upscale', completed_steps=sampling_plan['base_steps'], + print(json.dumps(dict(event='latent_upscale', completed_steps=sampling_plan['total_steps'] - sampling_plan['refine_steps'], total=sampling_plan['total_steps'])), flush=True) from .sampling_progress import elapsed_reports with elapsed_reports(lambda event: print(json.dumps(event), flush=True), - dict(event='latent_upscale', completed_steps=sampling_plan['base_steps'], + dict(event='latent_upscale', completed_steps=sampling_plan['total_steps'] - sampling_plan['refine_steps'], total=sampling_plan['total_steps'])): tick = time.perf_counter() if live_budget is not None: @@ -649,7 +669,7 @@ def refined_complete(video, sound, receipt): refine_options['refine_resume'] = dict(step=resumed_progress[0], rows=resumed_progress[1]) metrics['refine_resume'] = dict(steps_reused=resumed_progress[0], source='progress', scope='Seconds of the reused steps belong to the failed attempt that ran them.') - print(json.dumps(dict(event='refine_resumed', completed_steps=sampling_plan['base_steps'] + resumed_progress[0], + print(json.dumps(dict(event='refine_resumed', completed_steps=sampling_plan['total_steps'] - sampling_plan['refine_steps'] + resumed_progress[0], total=sampling_plan['total_steps'])), flush=True) if artifacts: def refine_checkpoint(done, rows, seconds): @@ -673,7 +693,7 @@ def refine_checkpoint(done, rows, seconds): compute_options=second_compute, final_step_callback=None if decoder_cached else read_decoder_ahead, step_callback=memory_diagnostics.complete, sampling_complete_callback=refined_complete, - progress_offset=sampling_plan['base_steps'], progress_total=sampling_plan['total_steps'], + progress_offset=sampling_plan['total_steps'] - sampling_plan['refine_steps'], progress_total=sampling_plan['total_steps'], gpu_reserve_bytes=request.get('gpu_reserve_bytes', 0), budget_refresh=refresh_budget if live_budget is not None else None) sampled = refined(second) diff --git a/freevideo_engine/workflow_repairs.py b/freevideo_engine/workflow_repairs.py index 37c2b2f6..aca6bba3 100644 --- a/freevideo_engine/workflow_repairs.py +++ b/freevideo_engine/workflow_repairs.py @@ -15,6 +15,8 @@ 'force_regenerate': ('bool', False, None), 'preview': ('bool', False, None), 'refine_from': ('text', '', None), + 'upscale_from': ('text', '', None), + 'upscale_to': ('text', '', None), 'continue_from': ('text', '', None), 'first_frame_reference': ('bool', False, None), 'voice_reference': ('bool', False, None), diff --git a/pyproject.toml b/pyproject.toml index 9abbf074..7db0915b 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", "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", "swap_lora.json"] diff --git a/scripts/test_freevideo_entry.mjs b/scripts/test_freevideo_entry.mjs index baf99d3f..80e50ef9 100644 --- a/scripts/test_freevideo_entry.mjs +++ b/scripts/test_freevideo_entry.mjs @@ -7,7 +7,7 @@ if (modules.registerHooks) modules.registerHooks({resolve}); else modules.register('./editor_test_hooks.mjs', import.meta.url); import {mediaName, uploadMedia} from '../web/media_upload.js'; import {outputDownloadURL, checkedDownload, anchoredNotice, unreadableVideoText} from '../web/output_download.js'; -import {regenerateResult, upscaleResult, createSecondPassQueue, enableNode} from '../web/studio_queue.js'; +import * as studioQueue from '../web/studio_queue.js'; import {referenceInputs, mediaRows} from '../web/prompt_references.js'; import {expandCast} from '../web/cast_mention.js'; import {cleanAudioUse, cleanOptionalPrompt, cleanOptionalWidgets, optionalInputValue} from '../web/optional_inputs.js'; @@ -64,7 +64,7 @@ test('main browser entry registers both views and preserves node hooks', async t createElementNS: (namespaceURI, tag) => Object.assign(new Element(tag), {namespaceURI}), createRange: () => ({createContextualFragment: () => new Element('span')})}; const dependencies = { - app, api, mediaName, uploadMedia, outputDownloadURL, checkedDownload, anchoredNotice, unreadableVideoText, regenerateResult, upscaleResult, createSecondPassQueue, enableNode, referenceInputs, mediaRows, expandCast, cleanAudioUse, cleanOptionalPrompt, cleanOptionalWidgets, optionalInputValue, + app, api, mediaName, uploadMedia, outputDownloadURL, checkedDownload, anchoredNotice, unreadableVideoText, ...studioQueue, referenceInputs, mediaRows, expandCast, cleanAudioUse, cleanOptionalPrompt, cleanOptionalWidgets, optionalInputValue, createCastLibrary: options => { // notice: the could-not-read line the real library returns for the page to place. const cast = {element: new Element('cast'), notice: new Element('notice'), options, destroyed: false, destroy() { this.destroyed = true; }}; @@ -126,9 +126,11 @@ test('main browser entry registers both views and preserves node hooks', async t source = source.replace("import { beginWorkspaceRestore, finishWorkspaceRestore, waitForLauncherRestore } from './workspace_restore.js';", 'const {beginWorkspaceRestore,finishWorkspaceRestore,waitForLauncherRestore} = globalThis.__freevideoEntryTest;'); source = source.replace("import { openEditorView } from './editor_loader.js';", 'const openEditorView = (...args) => globalThis.__freevideoEntryTest.openEditorView?.(...args);'); source = source.replace("from './issue_button.js'", `from '${new URL('../web/issue_button.js', import.meta.url).href}'`); + source = source.replace("from './user_message.js'", `from '${new URL('../web/user_message.js', import.meta.url).href}'`); source = source.replace("from './prompt_sections.js'", `from '${new URL('../web/prompt_sections.js', import.meta.url).href}'`); source = source.replace("from './fv_select.js'", `from '${new URL('../web/fv_select.js', import.meta.url).href}'`); source = source.replace("from './middle_frames.js'", `from '${new URL('../web/middle_frames.js', import.meta.url).href}'`); + source = source.replace("from './workflow_drafts.js'", `from '${new URL('../web/workflow_drafts.js', import.meta.url).href}'`); source = source .replace("import { createErrorPanel, errorText, createErrorReport, adviceFor } from './error_panel.js';", 'const {createErrorPanel,errorText,createErrorReport,adviceFor} = globalThis.__freevideoEntryTest;') .replace('import { app } from "../../scripts/app.js";', 'const {app} = globalThis.__freevideoEntryTest;') @@ -151,8 +153,9 @@ test('main browser entry registers both views and preserves node hooks', async t .replace("import { reportFileName } from './report_issue.js';", 'const {reportFileName} = globalThis.__freevideoEntryTest;') .replace("import { rememberPromptDraft, savePromptDraft, trackPromptDraft, watchPromptHistory, promptHistoryRestoring } from './prompt_draft.js';", 'const {rememberPromptDraft,savePromptDraft} = globalThis.__freevideoEntryTest; const trackPromptDraft = () => {}; const watchPromptHistory = () => {}; const promptHistoryRestoring = () => false;') .replace("import { cleanOptionalWidgets, cleanOptionalPrompt, optionalInputValue, cleanAudioUse } from './optional_inputs.js';", 'const {cleanOptionalWidgets,cleanOptionalPrompt,optionalInputValue,cleanAudioUse} = globalThis.__freevideoEntryTest;') - .replace("import { regenerateResult, upscaleResult } from './studio_queue.js';", 'const {regenerateResult,upscaleResult} = globalThis.__freevideoEntryTest;') - .replace("import { regenerateResult, createSecondPassQueue, enableNode } from './studio_queue.js';", 'const {regenerateResult,createSecondPassQueue,enableNode} = globalThis.__freevideoEntryTest;') + // The queue helpers come from the real module whatever names the page imports: matched by the module, not + // by the list of names, which changes with the page. + .replace(/import\s*\{([^}]*)\}\s*from\s*'\.\/studio_queue\.js';/, (_, names) => `const {${names}} = globalThis.__freevideoEntryTest;`) .replace("import { secondPassAction } from './result_actions.js';", 'const {secondPassAction} = globalThis.__freevideoEntryTest;') .replace("import { openImageEditor, icon } from './image_editor.js';", 'const {openImageEditor,icon} = globalThis.__freevideoEntryTest;') .replace("import { installNavigation, refreshNavigation, preferredView, collapseWorkspaces, openImage } from './view_navigation.js';", 'const {installNavigation,refreshNavigation,preferredView} = globalThis.__freevideoEntryTest; const collapseWorkspaces = () => { globalThis.__freevideoEntryTest.collapsed = (globalThis.__freevideoEntryTest.collapsed || 0) + 1; }; const openImage = async () => false;') @@ -349,14 +352,14 @@ test('main browser entry registers both views and preserves node hooks', async t dependencies.openFreeVideoWorkflow = async () => { throw new Error('workflow fixture unavailable'); }; const warn = console.warn; console.warn = () => {}; try { await entry.function(); } finally { console.warn = warn; } - const menuFailure = document.body.children.find(child => child.className?.includes('fv-menu-failure')); - assert.ok(menuFailure.open); - const menuIssue = menuFailure.children[1].children[0]; - assert.ok(menuIssue.className.includes('fv-issue-button')); assert.notEqual(menuIssue.hidden, true); - await menuIssue.onclick(); - assert.match(issueURLs.at(-1).searchParams.get('feedback'), /Error: Could not complete\. Try again\./); + // A failure goes to the page check's card (health.js), which says why and what to do and carries the error to + // the report; the entry opens no dialog of its own (W12). + const reported = (window.__freevideoHealth || []).filter(row => row.where === 'menu'); + assert.equal(reported.length, 1); assert.equal(reported[0].type, 'error'); + assert.equal(reported[0].error.message, 'workflow fixture unavailable'); + assert.equal(document.body.children.some(child => child.className?.includes('fv-menu-failure')), false); app.graph._nodes = nodes; await entry.function(); - assert.equal(document.body.children.includes(menuFailure), false, 'successful opening clears the failure and its report button'); + assert.equal((window.__freevideoHealth || []).filter(row => row.where === 'menu').length, 1, 'a successful opening reports nothing'); rememberedView = 'editor'; const restored = []; let finishLaunch, finishEditor; @@ -576,8 +579,9 @@ test('main browser entry registers both views and preserves node hooks', async t // The stored file may have a plain name; the item keeps the name the user's file had, for the label. assert.deepEqual(JSON.parse(media.widgets[0].value), [{file: 'freevideo/' + 'a'.repeat(32) + '/media.wav', name: 'voice.wav', role: 'reference', enabled: true}]); assert.equal(media.isUploading, false); + // A connected first frame next to a reference is used together with it. media.inputs = [{name: 'first', link: 1}]; media.onConnectionsChange(); await Promise.resolve(); - assert.match(note.textContent, /Choose keyframes or references/); + assert.equal(note.textContent, ''); media.widgets[0].value = '[]'; media.inputs = []; media.onConnectionsChange(); await Promise.resolve(); assert.equal(note.textContent, ''); const imageRole = toolbar.children.find(e => e.tag === 'div' && e.className === 'fv-select')?.children.find(e => e.tag === 'select'); diff --git a/web/agent_activity.js b/web/agent_activity.js index a4a6a382..be611c3b 100644 --- a/web/agent_activity.js +++ b/web/agent_activity.js @@ -1,6 +1,7 @@ import {retryAgentPost} from './agent_session.js'; import {issueButton} from './issue_button.js'; import {tip} from './autopilot_tips.js'; +import {failureAdvice} from './error_panel.js'; // What agents connected to this FreeVideo are doing. Their requests share the // studio's queue, so people can see them, follow progress and stop them. const css = document.createElement('link'); css.rel = 'stylesheet'; css.href = new URL('./agent_activity.css', import.meta.url).href; document.head.append(css); @@ -34,9 +35,19 @@ const REASONS = { dependency_failed: ['An earlier step did not succeed', '前序任务未成功'], }; -// Failures without a known cause: the row offers the problem report. -const UNEXPECTED = ['internal_error', 'generation_failed']; - +// The engine's own sentence when it wrote one; otherwise the same advice the studio gives for that error, +// and for an error nobody has a sentence for yet, its first line, so the row never says only "Did not finish". +function failureLine(error, t) { + // The engine's reason, then its next step when it has one. + const next = (said, step, zh) => said && step ? said.replace(/[。.]$/, '') + (zh ? '。' : '. ') + step : said; + if (error.error_en && error.error_en !== 'Did not finish') + return t(next(error.error_en, error.next_en), next(error.error_zh || error.error_en, error.next_zh, !!error.error_zh)); + const message = String(error.message || '').trim(); + const advice = message && failureAdvice(message, t); + if (advice && advice.kind !== 'unknown') return [advice.title, advice.action].filter(Boolean).join(t('. ', ',')); + const line = message.split(/\r?\n/).find(text => text.trim() && !/^Traceback/.test(text))?.trim().slice(0, 160); + return line ? t(`Did not finish: ${line}`, `没有完成:${line}`) : t('Did not finish', '没有完成'); +} function el(tag, cls, text) { const e = document.createElement(tag); if (cls) e.className = cls; if (text != null) e.textContent = text; return e; } function glyph(path) { const svg = document.createElementNS('http://www.w3.org/2000/svg', 'svg'); @@ -110,21 +121,21 @@ function row(job, t, api, refresh, open, cancellationErrors) { const phase = job.status === 'running' ? phaseText(p, t, job.kind) : ''; if (phase && phase !== status(job, t)) meta.push(phase); if (job.status === 'running' && p.remaining_seconds > 0) meta.push(left(p.remaining_seconds, t)); - const reason = job.status === 'failed' && REASONS[job.error?.code]; + const failed = job.status === 'failed', error = job.error || {}; + const reason = failed && REASONS[error.code]; if (reason) meta.push(t(...reason)); - else if (job.status === 'failed') { - // The engine's reason, then its next step when it has one. - const e = job.error || {}, next = (said, step, zh) => said && step ? said.replace(/[。.]$/, '') + (zh ? '。' : '. ') + step : said; - meta.push(t(next(e.error_en, e.next_en) || 'Did not finish', next(e.error_zh, e.next_zh, true) || '没有完成')); - } + else if (failed) meta.push(failureLine(error, t)); if (job.project) meta.push(job.project); const foot = el('div', 'fv-agent-foot'); const details = el('p', 'fv-agent-meta', meta.join(' · ')); - if (reason && job.error?.message) details.title = job.error.message; + if (failed && error.message) details.title = error.message; foot.append(details); - const issue = issueButton(t, () => ({where: ['Assistant tasks', '助手任务'], message: details.textContent})); - // An unexpected failure can be reported from its row, as its next step says. - issue.hidden = !cancellationErrors.has(job.id) && !(job.status === 'failed' && UNEXPECTED.includes(job.error?.code)); foot.append(issue); + // A failed task carries what the engine said, so the report can be acted on. + const issue = issueButton(t, () => cancellationErrors.has(job.id) || !failed + ? {where: ['Assistant tasks', '助手任务'], message: details.textContent} + : {where: ['Assistant tasks', '助手任务'], message: error.message || details.textContent, + kind: [error.code, error.report_id && `report ${error.report_id}`].filter(Boolean).join(' · ') || null}); + issue.hidden = !failed && !cancellationErrors.has(job.id); foot.append(issue); if (['waiting', 'queued', 'running'].includes(job.status)) { const stop = el('button', 'fv-agent-stop', t('Stop', '停止')); stop.type = 'button'; stop.setAttribute('aria-label', t('Stop ', '停止 ') + title(job, t)); tip(stop, 'stop', t); diff --git a/web/agent_confirm_settings.js b/web/agent_confirm_settings.js index 4607a5f3..30e812da 100644 --- a/web/agent_confirm_settings.js +++ b/web/agent_confirm_settings.js @@ -57,7 +57,7 @@ export function agentConfirmSettings(t, api) { }; async function save(patch) { // The control keeps what the user just chose while the save runs; it then shows what the server holds. - busy = true; startBox.disabled = longBox.disabled = minutesField.disabled = true; status.textContent = ''; + busy = true; startBox.disabled = longBox.disabled = minutesField.disabled = true; status.textContent = ''; status.classList.remove('is-warn'); try { const response = await agentSend(api, 'PUT', PATH, patch); if (!response.ok) throw new Error('Not saved'); @@ -69,6 +69,7 @@ export function agentConfirmSettings(t, api) { shown = await read(); status.textContent = t('Could not save. The setting shown is the one in effect.', '保存失败,下面显示的是当前生效的设置。'); } catch { status.textContent = t('Could not confirm whether the change was saved.', '无法确认这次修改是否已保存。'); } + status.classList.add('is-warn'); } busy = false; render(); } diff --git a/web/autopilot_chat.js b/web/autopilot_chat.js index a32d3998..e5bd1473 100644 --- a/web/autopilot_chat.js +++ b/web/autopilot_chat.js @@ -9,7 +9,7 @@ export {emptyChat, chatMerge, chatEntries, canSend} from './chat_data.js'; import {isolateDialogKeys, listenDialogKey, routeDialogKey} from './dialog_keys.js'; import {closeDialog} from './motion.js'; import { estimatedFraction, remainingAbove, remainingShown, createDiagnosticReportControl } from './generation_progress.js'; -import {createErrorReport, failureFold} from './error_panel.js'; +import {createErrorReport, failureAdvice, failureFold} from './error_panel.js'; import {canDeleteConversation, canRenameConversation, conversationMenu, emptyConversations, hasConversations, mergeConversations, removeConversation, runningElsewhere, selectConversation} from './autopilot_conversations.js'; import {renderImageFailure} from './image_generation.js'; import {issueButton} from './issue_button.js'; @@ -89,10 +89,17 @@ function failureReason(value, t) { // A failed job's one reason line. The engine's classified sentence (both languages) is for people; anything else is // program text and goes to the technical details, so the card then says only that the generation did not finish. -function failureCardReason(value, t) { +export function failureCardReason(value, t) { const error = value.error, zh = error?.error_zh || value.error_zh, en = error?.error_en || value.error_en; const said = zh && en && zh !== GENERIC_FAILURE_ZH && en !== 'Did not finish' && zh !== '生成没有完成'; - return said || error?.code === 'session_full' ? failureReason(value, t) : t('Generation did not finish.', '生成未完成。'); + if (said || error?.code === 'session_full') return failureReason(value, t); + // Unclassified: the creation panel's reading of the original text (memory, a missing file, a component that + // did not load...) says the cause and the next step; only what it cannot place stays "did not finish". + const raw = [error?.code, error?.message].filter(value => typeof value === 'string' && value).join('\n'); + const advice = raw ? failureAdvice(raw, t) : null; + if (advice && advice.kind !== 'unknown' && advice.title) + return [advice.title, advice.summary || advice.action].filter(Boolean).join(t('. ', '。')); + return t('Generation did not finish.', '生成未完成。'); } export {about}; diff --git a/web/autopilot_glass.css b/web/autopilot_glass.css index eec0a42f..9947f8e9 100644 --- a/web/autopilot_glass.css +++ b/web/autopilot_glass.css @@ -553,10 +553,11 @@ dialog.fv-studio.fv-autopilot:not([open]){display:none!important} /* The strip keeps the connection at its foot even with no chats listed. */ .fv-autopilot .fv-chat-rail-foot{margin-top:auto} -/* Phones: every control is a finger-sized target (44 px); the look is unchanged where the control is drawn smaller. */ +/* Phones: every control is a finger-sized target (44 px); the look is unchanged where the control is drawn smaller. + An attached picture's remove × keeps its corner size: at 44 px it would cover the 52 px picture, whose own tap is retry. */ @media(max-width:719px){ - :root .fv-studio.fv-autopilot.fv-autopilot :is(button,[role=button]):not(.fv-chat-play){min-height:var(--fv-touch,44px)} - :root .fv-studio.fv-autopilot.fv-autopilot :is(button,[role=button]):not(.fv-chat-play){min-width:var(--fv-touch,44px)} + :root .fv-studio.fv-autopilot.fv-autopilot :is(button,[role=button]):not(.fv-chat-play,.fv-chat-attached-x){min-height:var(--fv-touch,44px)} + :root .fv-studio.fv-autopilot.fv-autopilot :is(button,[role=button]):not(.fv-chat-play,.fv-chat-attached-x){min-width:var(--fv-touch,44px)} :root .fv-studio.fv-autopilot.fv-autopilot .fv-chat-send{height:var(--fv-touch,44px)} } .fv-studio.fv-autopilot .fv-chat-log .fv-chat-edit-row .fv-chat-edit{min-height:var(--fv-ctl,32px);padding:0 var(--fv-sp-8,8px)} @@ -568,7 +569,7 @@ dialog.fv-studio.fv-autopilot:not([open]){display:none!important} and its picture grows with it; the words keep their 720 px measure and the connection card keeps its size. */ @media (orientation:portrait) and (min-width:700px){ .fv-autopilot .fv-chat-scroll{container-type:inline-size} - .fv-autopilot .fv-chat-scroll .fv-chat-job[data-mode=done]:has(.fv-chat-preview){--ap-wide:min(960px,100cqw);width:var(--ap-wide);margin-inline:calc((100% - var(--ap-wide)) / 2)} + .fv-autopilot .fv-chat-scroll .fv-chat-job[data-mode=done][data-hx-prev]{--ap-wide:min(960px,100cqw);width:var(--ap-wide);margin-inline:calc((100% - var(--ap-wide)) / 2)} .fv-autopilot .fv-chat-job[data-mode=done] .fv-chat-preview{width:calc(var(--ap-wide,720px) * .5)} .fv-autopilot .fv-chat-job[data-mode=done] .fv-chat-preview[data-shape=tall]{width:calc(var(--ap-wide,720px) * .25)} } diff --git a/web/capability_view.js b/web/capability_view.js index b5f73204..ad66b894 100644 --- a/web/capability_view.js +++ b/web/capability_view.js @@ -58,7 +58,19 @@ export function capabilityContext(node, state) { return row; }); const audio = refs.some((r, i) => r.kind === 'audio' || positive(rows[i].audio_seconds)); - const visual = refs.some(r => r.kind !== 'audio'); + let visual = refs.some(r => r.kind !== 'audio'); + if (refs.length) { + // Next to references each keyframe is a still guide of the canvas size; the server counts one canvas grid for + // each on every size it lists. referenceItems names only the references then, so the keyframes are read from + // the panel and its sockets. + const mediaNode = upstream(node, 'media'), socket = name => mediaNode?.inputs?.some(i => i.name === name && i.link != null); + const used = role => assets.some(r => r.enabled !== false && r.role === role) || socket(role); + const middle = assets.filter(r => r.enabled !== false && r.role === 'middle').length; + for (let n = Number(used('first')) + Number(used('last')) + (used('first') && used('last') ? middle : 0); n > 0; n--) + rows.push({kind: 'image', guide: true}); + // The engine counts a still guide as a picture: a sound reference with keyframes is an audio-video request. + visual ||= rows.some(r => r.guide); + } const task = audio ? visual ? 'ref2va_av' : 'ref2va_audio' : visual ? 'ref2va' : first && last ? 'fl2va' : first ? 'i2va' : last ? 'l2va' : 't2va'; const lora = upstream(node, 'loras'); @@ -71,7 +83,7 @@ export function capabilityContext(node, state) { const query = new URLSearchParams({task, adapters: adapters ? '1' : '0'}); if (state.custom) { query.set('width', value(node, 'width')); query.set('height', value(node, 'height')); } else { if (!positive(state.ratio)) return null; query.set('aspect', `${state.ratio}:1`); } - const complete = rows.length && rows.every(r => (r.kind === 'audio' || [r.width, r.height].every(n => Number.isInteger(n) && n > 0 && n <= 65536)) + const complete = rows.length && rows.every(r => r.guide || (r.kind === 'audio' || [r.width, r.height].every(n => Number.isInteger(n) && n > 0 && n <= 65536)) && (r.kind === 'image' || positive(r.seconds))); if (complete) query.set('references', JSON.stringify(rows)); return query.toString(); diff --git a/web/cast_library.js b/web/cast_library.js index 0d52d5b3..bc7b9c2d 100644 --- a/web/cast_library.js +++ b/web/cast_library.js @@ -2,6 +2,7 @@ import {agentGet, agentPost, agentSend} from './agent_session.js'; import {agentInterfaceEnabled} from './agent_connect.js'; import {issueButton} from './issue_button.js'; import { skin } from './glass/library.js'; +import {userMessage} from './user_message.js'; const CAST_ISSUE = ['Character library', '角色库']; // The optional generator owns its UI and job lifecycle; keep its contract here. @@ -64,7 +65,7 @@ export function createCastLibrary({api, text, viewURL, uploadOne, onChange = () // The dialog only sends pictures, so unreadable media here is always one of them. const unreadable = data?.error?.code === 'invalid_media' && text('Could not read this picture. Please choose another one.', '无法读取这张图片,请换一张。'); const error = new Error(unreadable || data?.error?.message || (typeof data?.error === 'string' && data.error) - || data?.message || response.statusText || text('Did not finish. Try again.', '没有完成,请重试。')); + || data?.message || `HTTP ${response.status} ${response.statusText}`.trim()); error.status = response.status; // Which picture it was, as /images//media of the request. if (unreadable) error.field = data.error.details?.find(detail => typeof detail?.field === 'string')?.field; @@ -110,7 +111,7 @@ export function createCastLibrary({api, text, viewURL, uploadOne, onChange = () return rows; } const changed = () => { - if (!broadcasting) refresh().catch(error => current?.message(error.message)); + if (!broadcasting) refresh().catch(error => current?.message(userMessage(error, text, text('Could not refresh the list. Try again.', '没能刷新列表,请重试。')))); }; async function saved() { broadcasting = true; @@ -323,8 +324,8 @@ export function createCastLibrary({api, text, viewURL, uploadOne, onChange = () try { await load(); message(text('Changed elsewhere. Showing the latest version.', '已在别处修改,已显示最新内容'), true); - } catch (error) { message(error.message); } - } else message(error.message); + } catch (error) { message(userMessage(error, text, text('Could not show the latest version. Close and open it again.', '没能显示最新内容,请关闭后重新打开。'))); } + } else message(userMessage(error, text)); } async function saveCard() { if (closed || save.disabled) return; @@ -393,7 +394,7 @@ export function createCastLibrary({api, text, viewURL, uploadOne, onChange = () dialog.onclose = close; current = {element: dialog, message, close}; name.value = ''; select('upload'); document.body.append(dialog); dialog.showModal(); name.focus(); - if (id) load().catch(error => message(error.message)); + if (id) load().catch(error => message(userMessage(error, text, text('Could not open it. Try again.', '没能打开,请重试。')))); // A scene has one set of pictures: the chosen option takes the first place, where the Upload tab shows it. const pick = file => { if (closed || !scene) return; slots[0] = {media: file, label: 'other'}; paint(0); }; // Scenes and props: the description's candidates. Characters: the four views from each source. diff --git a/web/cast_mention.js b/web/cast_mention.js index 9b359ac3..f32eba6e 100644 --- a/web/cast_mention.js +++ b/web/cast_mention.js @@ -115,8 +115,9 @@ export function mentionRanges(text, people) { } // The prompt a request carries. Characters mentioned in the text are numbered in order of first mention; one whose -// pictures are gone is written as a plain name. `active: false` (first/last frames) leaves every name plain too, since -// pictures of people cannot go with those. `continued` (the part continues a video) lets the characters stay: the part +// pictures are gone is written as a plain name. `active: false` leaves every name plain too. First and last frames do +// not change the numbers: next to references they go after them as guides the prompt does not name (a Mac engine refuses +// the combination with its own message). `continued` (the part continues a video) lets the characters stay: the part // keeps three reference pictures (see pictureNumbers) and its frames come after them, so a character whose pictures are // not among those three is written as a plain name. export function expandCast(text, rows, {active = true, continued = false} = {}) { @@ -126,7 +127,6 @@ export function expandCast(text, rows, {active = true, continued = false} = {}) const ranges = mentionRanges(text, people); if (!ranges.length) return {text, subjects: []}; const placed = [], placedProps = []; - if (!continued && list.some(row => enabled(row) && (row.role === 'first' || row.role === 'last'))) active = false; const numbers = pictureNumbers(list, continued); const order = []; let result = '', at = 0; @@ -214,7 +214,6 @@ export function mentionState(rows, card, count = cardPictures(card).length, {con const list = Array.isArray(rows) ? rows : []; const people = castInRows(list); if (people.some(person => person.id === card.id)) return {ok: true, present: true}; - if (!continued && list.some(row => enabled(row) && (row.role === 'first' || row.role === 'last'))) return {ok: false, reason: 'frames'}; if (card.kind === 'prop') { if (people.filter(person => person.prop).length >= MAX_PROPS) return {ok: false, reason: 'props'}; } else if (card.kind === 'setting' ? people.some(person => person.setting) : people.filter(person => !person.setting && !person.prop).length >= MAX_PEOPLE) { diff --git a/web/cast_room.js b/web/cast_room.js index f87cf6c3..f671f6a3 100644 --- a/web/cast_room.js +++ b/web/cast_room.js @@ -6,6 +6,7 @@ import { agentInterfaceState } from './agent_connect.js'; import { agentSend } from './agent_session.js'; import { uploadMedia } from './media_upload.js'; import { issueButton } from './issue_button.js'; +import { userMessage } from './user_message.js'; const css = document.createElement('link'); css.rel = 'stylesheet'; css.href = new URL('./cast_room.css', import.meta.url).href; document.head.append(css); const el = (tag, text, cls) => { const e = document.createElement(tag); if (text != null) e.textContent = text; if (cls) e.className = cls; return e; }; @@ -166,7 +167,7 @@ export function createCastRoom({api, t, viewURL: outputURL}) { const full = await libraries[row.kind].get(row.id); if (disposed || selected !== row.id) return; card = {...full, kind: full.kind || row.kind}; paint(); - } catch (error) { if (selected === row.id) notice.textContent = error.message; } + } catch (error) { if (selected === row.id) notice.textContent = userMessage(error, t, t('Could not open it. Try again.', '没能打开,请重试。')); } } function paint() { if (!card) return; @@ -216,7 +217,7 @@ export function createCastRoom({api, t, viewURL: outputURL}) { window.dispatchEvent(new CustomEvent('freevideo-cast-changed')); clearDetail(); await refresh(); } catch (error) { - notice.textContent = error.message; + notice.textContent = userMessage(error, t, t('Could not delete. Try again.', '没能删除,请重试。')); notice.append(issueButton(t, () => ({where: ['Character library', '角色库'], message: error.message}))); } finally { remove.disabled = false; } } diff --git a/web/compatibility.js b/web/compatibility.js index b4983cfd..a0fb66a8 100644 --- a/web/compatibility.js +++ b/web/compatibility.js @@ -1,5 +1,12 @@ import { api } from '../../scripts/api.js'; import './glass/library.js'; +import {userMessage} from './user_message.js'; + +// FreeVideo's own reason keeps the lead-in that says what failed; browser or program wording becomes a plain sentence. +const saveFailure = (error, tt) => { const text = userMessage(error, tt, tt('Could not save. Try again.', '没能保存,请重试。')); + return text === String(error?.message ?? '').trim() ? tt('Save failed: ', '保存失败:') + text : text; }; +const readFailure = (error, tt) => { const text = userMessage(error, tt, tt('Could not read the setting. Try again.', '没能读取设置,请重试。')); + return text === String(error?.message ?? '').trim() ? tt('The setting could not be read: ', '无法读取设置:') + text : text; }; const languageOverride = typeof location !== 'undefined' ? new URLSearchParams(location.search).get('freevideo_lang') : null; @@ -114,7 +121,7 @@ export function compatibilityCard({t: tt = t, api: client0 = api} = {}) { value = {...value, ...saved, level: Number(level.value), automatic: automatic.checked}; say(tt('Saved · applies to the next generation', '已保存 · 下次生成生效'), 'ok'); setTimeout(() => { if (status.dataset.kind === 'ok') say(''); paint(); }, 2400); - } catch (error) { say(tt('Save failed: ', '保存失败:') + error.message, 'warn'); } + } catch (error) { say(saveFailure(error, tt), 'warn'); } finally { saving = false; paint(); } }; (async () => { @@ -123,7 +130,7 @@ export function compatibilityCard({t: tt = t, api: client0 = api} = {}) { if (disposed) return; if (!value.available) { line.textContent = unavailable(); say(''); paint(); return; } level.value = String(value.level); automatic.checked = Boolean(value.automatic); paint(); - } catch (error) { line.textContent = tt('The setting could not be read: ', '无法读取设置:') + error.message; line.className = 'is-warn'; paint(); } + } catch (error) { line.textContent = readFailure(error, tt); line.className = 'is-warn'; paint(); } })(); return { element, @@ -176,7 +183,7 @@ async function openCompatibilitySheet() { if (!saved.available) { status.className = 'fv-failure'; status.textContent = unavailable(); return; } panel.close(); } - catch (error) { status.className = 'fv-failure'; status.textContent = t('Save failed: ', '保存失败:') + error.message; } + catch (error) { status.className = 'fv-failure'; status.textContent = saveFailure(error, t); } finally { saving = false; for (const control of [slider, automatic, save, cancel, close]) control.disabled = false; @@ -187,7 +194,7 @@ async function openCompatibilitySheet() { } }, true); } catch (error) { - status.textContent = error.message; + status.textContent = readFailure(error, t); button(panel, t('Close', '关闭'), () => panel.close(), true).focus(); } } diff --git a/web/context_menu.js b/web/context_menu.js index 14faaa9e..b9782ccf 100644 --- a/web/context_menu.js +++ b/web/context_menu.js @@ -83,6 +83,7 @@ const PATHS = { check: '', close: '', alert: '', + info: '', download: '', person: '', play: '', @@ -100,6 +101,8 @@ const PATHS = { reload: '', history: '', paste: '', + enlarge: '', + upscale: '', 'select-all': '', external: '', }; diff --git a/web/editor.css b/web/editor.css index 596a09a0..e12ab287 100644 --- a/web/editor.css +++ b/web/editor.css @@ -255,7 +255,7 @@ @media(min-width:681px) and (max-width:1279px){.fv-ed-notice{right:32px;max-width:min(560px,calc(100vw - 330px))}} .fv-ed-notice .fv-issue-button{margin-left:12px;vertical-align:middle;pointer-events:auto} @media(max-width:680px){ - .fv-studio.fv-editor{--fv-ed-generation-row:calc(96px + var(--fv-ed-description-growth,0px) + var(--fv-ed-note-growth,0px));grid-template-columns:minmax(0,1fr);grid-template-rows:auto var(--fv-ed-project-h) minmax(0,1fr) 40px var(--fv-ed-generation-row) 40px 236px;overflow:hidden} + .fv-studio.fv-editor{--fv-ed-generation-row:calc(96px + var(--fv-ed-description-growth,0px) + var(--fv-ed-note-growth,0px));grid-template-columns:minmax(0,1fr);grid-template-rows:auto var(--fv-ed-project-h) minmax(0,1fr) 40px minmax(var(--fv-ed-generation-row),auto) 40px 236px;overflow:hidden} .fv-editor .fv-header{overflow-x:auto} .fv-editor .fv-ed-name{font-size:13px;max-width:112px;flex:1;padding:0 2px} .fv-editor .fv-ed-icon{width:28px;flex:none;font-size:20px} @@ -297,7 +297,7 @@ /* Keep the editor's controls visible instead of clipping them at phone widths. */ @media(max-width:480px){ - .fv-studio.fv-editor{grid-template-rows:auto var(--fv-ed-project-h) minmax(0,1fr) 40px var(--fv-ed-generation-row) 40px minmax(160px,236px)} + .fv-studio.fv-editor{grid-template-rows:auto var(--fv-ed-project-h) minmax(0,1fr) 40px minmax(var(--fv-ed-generation-row),auto) 40px minmax(160px,236px)} .fv-studio.fv-editor .fv-header[data-hx-vs]{grid-template-columns:minmax(0,1fr) auto} /* One row: undo, split, delete and zoom; editor_toolbar_more.js moves the rest behind ⋯. */ .fv-ed-duration-word{display:none} @@ -326,7 +326,7 @@ /* Narrow window: the picture sits right under the header, the row takes the project's own shape (a 16:9 project is about 200 px tall at 400 px wide), and whatever height is left goes to the timeline. */ @media(max-width:680px){ - .fv-studio.fv-editor{grid-template-rows:auto var(--fv-ed-project-h) minmax(0,auto) 40px var(--fv-ed-generation-row) 40px minmax(160px,1fr)} + .fv-studio.fv-editor{grid-template-rows:auto var(--fv-ed-project-h) minmax(0,auto) 40px minmax(var(--fv-ed-generation-row),auto) 40px minmax(160px,1fr)} .fv-editor .fv-ed-preview{box-sizing:border-box;align-self:start;width:100%;aspect-ratio:var(--fv-ed-project-width,16)/var(--fv-ed-project-height,9);max-height:max(116px,calc(100dvh - 362px - var(--fv-ed-generation-row)));padding-top:12px;padding-bottom:8px} } @@ -487,7 +487,7 @@ /* ── Phone (≤680 px): this view's own controls are finger-sized (44 px) ── */ @media(max-width:680px){ - .fv-studio.fv-editor{--fv-ed-generation-row:calc(108px + var(--fv-ed-description-growth,0px) + var(--fv-ed-note-growth,0px));grid-template-rows:auto var(--fv-ed-project-h) minmax(0,auto) 44px var(--fv-ed-generation-row) 48px minmax(160px,1fr)} + .fv-studio.fv-editor{--fv-ed-generation-row:calc(108px + var(--fv-ed-description-growth,0px) + var(--fv-ed-note-growth,0px));grid-template-rows:auto var(--fv-ed-project-h) minmax(0,auto) 44px minmax(var(--fv-ed-generation-row),auto) 48px minmax(160px,1fr)} .fv-editor .fv-ed-genbar{padding-top:4px;padding-bottom:4px;row-gap:8px} .fv-editor .fv-ed-project-row :is(.fv-ed-name,.fv-ed-export-main,.fv-ed-save-state){height:44px;min-height:44px} .fv-editor .fv-ed-project-row .fv-ed-export-main{min-width:56px} diff --git a/web/editor.js b/web/editor.js index 6f80cd26..985d7000 100644 --- a/web/editor.js +++ b/web/editor.js @@ -787,8 +787,8 @@ export function openEditor({api, app, from = null, panel = {}, components: given } } if (disposed || closing || epoch !== projectEpoch) return; - if (picture) notify(t('Saved the current frame to Edit image > Generate with AI > History.', - '已保存当前帧,位于“编辑图片 > AI 生成 > 历史”。')); + if (picture) notify(t('Saved the current frame to Edit image > Generate with AI > Works.', + '已保存当前帧,位于“编辑图片 > AI 生成 > 作品库”。')); } catch (value) { if (disposed || epoch !== projectEpoch) return; const said = {no_picture: t('There is no picture at this position. Move the playhead onto a clip.', '这个位置没有画面,请把播放头移到片段上。'), @@ -1801,9 +1801,13 @@ export function openEditor({api, app, from = null, panel = {}, components: given attachBar = () => { if (bar) return; bar = panel.borrowBar({mount: genHost, onSeconds: value => { const field = genbar.duration; if (!field || field.element.hidden || field.input.disabled || !(value > 0)) return; field.input.value = String(Math.round(value)); field.commit(); }, label: () => barLabel || null, disabled: () => !genbar.canGenerate(), - submit: async options => { genbar.setText(bar.prompt.value); await genbar.press(options?.allowEmpty === true); }}); + submit: async options => { genbar.setText(bar.prompt.value); await genbar.press(options?.allowEmpty === true); }, + onFirstFrame: value => genbar.firstFrame?.set(value)}); if (bar) { genHost.classList.add('fv-ed-genbar-borrowed'); + // The editor's own first-frame switch is hidden with its bar; the borrowed bar's switch (in its frame pop-up, + // where the creation panel keeps it) follows the editor's rule and saves to the edit. + genbar.firstFrame?.mirror(next => bar?.firstFrame?.(next)); element.dataset.barBorrowed = 'true'; // The guide's editor steps ring the borrowed bar's prompt, media and Generate, not the editor's hidden ones. guideBack = [['editor-describe', '[data-fv-guide="describe"]'], ['editor-refs', '.fvs-chip[data-chip="media"]'], ['editor-generate', '[data-fv-guide="generate"]']].flatMap(([mine, selector]) => { @@ -1830,7 +1834,9 @@ export function openEditor({api, app, from = null, panel = {}, components: given if (!bar) return; const selection = state.selection, clips = selection?.kind === 'clip' ? selection.ids.map(id => model.find(state.record, id)).filter(Boolean) : []; const edit = capability.generationSize || generationSize(state.record), again = clips.some(clip => clip.source); - const continuing = !again && clips.length > 0 && model.generationBefore(state.record, clips.map(clip => clip.id)).some(Boolean); + // Parts that cannot be generated together (apart on the timeline) continue nothing: the bar shows their span unlocked. + const continuing = !again && clips.length > 0 && (() => { try { return model.generationBefore(state.record, clips.map(clip => clip.id)).some(Boolean); } + catch (value) { if (value instanceof model.EditError) return false; throw value; } })(); const range = selectionRange(), length = range ? range.frames / model.FPS : null; // the span, not a sum: a part's picture and sound are two linked clips over the same frames echo = true; if (clips.length) lent = true; @@ -1844,7 +1850,7 @@ export function openEditor({api, app, from = null, panel = {}, components: given } }; // Hidden, the editor gives the panel its bar back; shown again, it takes it once more. - detachBar = () => { observer?.disconnect(); observer = null; unlisten?.(); unlisten = null; for (const back of guideBack.splice(0)) back(); bar?.release(); bar = null; panel.barActive = false; genHost.classList.remove('fv-ed-genbar-borrowed'); delete element.dataset.barBorrowed; }; + detachBar = () => { genbar.firstFrame?.mirror(null); observer?.disconnect(); observer = null; unlisten?.(); unlisten = null; for (const back of guideBack.splice(0)) back(); bar?.release(); bar = null; panel.barActive = false; genHost.classList.remove('fv-ed-genbar-borrowed'); delete element.dataset.barBorrowed; }; cleanupBar = detachBar; attachBar(); } @@ -2285,10 +2291,21 @@ export function openEditor({api, app, from = null, panel = {}, components: given return closePromise; }, // Hidden and kept: the dialog closes (its sheet keeps a closed editor out of sight) and turns inert; saving, - // progress and the job watchers go on, so coming back needs nothing redrawn. + // progress and the job watchers go on, so coming back needs nothing redrawn. The import list waits (it is + // read again on coming back), unless an import it waits for is still on its way. kept: false, panel, reopen() { handle.kept = false; + // A blank edit of this tab that nothing was done in follows the creation panel's quality as it is now: a level + // chosen there while this view was away applies here too, as one chosen here goes there. An edit with parts, + // a saved one, or one with a part queued or generating keeps its own settings. The blank edit stays unsaved. + const now = panel.sampling?.(), set = state.record.settings || {}; + if (now && !state.record.id && state.record.tracks.every(track => !track.clips.length) && !held.length && !jobActive() + && Object.entries(now).some(([key, value]) => set[key] !== value)) { + panel.settings = {...panel.settings, ...now}; + suppressSave = true; try { state.settle(record => model.setSampling(record, now)); } finally { suppressSave = false; } + savedContent = content(state.record); + } resumeCanvasPointer = suspendCanvasPointer(app?.canvas); // What the last switch left on the dialog (its fade, the leaving mark) goes, so it shows as it was. element.getAnimations?.().forEach(animation => animation.cancel()); @@ -2297,7 +2314,7 @@ export function openEditor({api, app, from = null, panel = {}, components: given const later = [...document.querySelectorAll('dialog[open]')].some(dialog => dialog !== element && element.compareDocumentPosition(dialog) & Node.DOCUMENT_POSITION_FOLLOWING); if (!element.isConnected || later) document.body.append(element); element.inert = false; - attachBar?.(); + attachBar?.(); library?.resume?.(); if (!element.open) element.showModal(); viewChanged('editor'); globalThis.FreeVideoStageLight?.refresh(); // The tab takes focus after the first frame: focusing now would lay the whole view out a second time before it shows. @@ -2315,6 +2332,8 @@ export function openEditor({api, app, from = null, panel = {}, components: given // The microphone is let go with the view: an open record bar closes, and a take in progress lands as Stop would. recording.hide(); detachBar?.(); + // The import list is not read while out of sight, unless an import it waits for is still on its way. + library?.suspend?.(); if (element.open) element.close(); element.inert = true; resumeCanvasPointer(); resumeCanvasPointer = () => {}; diff --git a/web/editor_adjust.js b/web/editor_adjust.js index dee604f9..56c89633 100644 --- a/web/editor_adjust.js +++ b/web/editor_adjust.js @@ -17,7 +17,8 @@ export const busyReason = t => t('Cancel generation before changing this part.', export function disabledReason(context, {needs, single = false} = {}) { const {t} = context; if (context.busy) return busyReason(t); - if (!context.single && !context.multiple) return t('Select a part first', '先选中一段'); + // A part that is not generated yet is selected, but has nothing to adjust. + if (!context.single && !context.multiple) return context.clips?.length ? t('Available after this part is generated', '这一段生成后才能调整') : t('Select a part first', '先选中一段'); if (single && context.multiple) return t('Only for a single part', '只能对单独一段调整'); if (needs === 'video' && !context.hasVideo) return t('This part has no video', '这一段没有画面'); if (needs === 'audio' && !context.hasAudio) return t('This part has no audio', '这一段没有声音'); diff --git a/web/editor_first_frame.js b/web/editor_first_frame.js index 7c9a6378..9a420281 100644 --- a/web/editor_first_frame.js +++ b/web/editor_first_frame.js @@ -10,16 +10,20 @@ export function createFirstFrameSwitch(host, {state, t, actions}) { const {row, input, setDisabled} = firstFrameRow(t, 'fv-ed-first-frame'); row.dataset.tourId = 'editor-first-frame'; host.append(row); tip(row, {name: t('First-frame reference', '首帧参考'), use: t('Start from the last frame of the part before', '从上一段的最后一帧接着生成')}); - let shown = false; + let shown = false, mirror = null, busyNow = false; // While generating the row stays as it was and cannot be changed. function update(busy = false) { + busyNow = busy; if (!busy) shown = !!actions.firstFrameVisible?.(); row.hidden = !shown; input.checked = firstFrameOn(state.record); setDisabled(busy); tip(row, {name: t('First-frame reference', '首帧参考'), use: t('Start from the last frame of the part before', '从上一段的最后一帧接着生成'), why: busy ? t('This part is generating', '这一段正在生成') : ''}); + mirror?.({shown, checked: input.checked, disabled: busy}); } input.onchange = () => { try { actions.setFirstFrame(input.checked); } catch (error) { actions.error?.(error); } finally { input.checked = firstFrameOn(state.record); } }; update(); - return {element: row, update}; + // A borrowed bar shows its own switch: it is told when to show and what is on, and its change is saved here. + const set = value => { try { actions.setFirstFrame(value); } catch (error) { actions.error?.(error); } finally { update(); } }; + return {element: row, update, mirror(next) { mirror = next; if (next) next({shown, checked: input.checked, disabled: busyNow}); }, set}; } diff --git a/web/editor_genbar.js b/web/editor_genbar.js index 61c8417f..9897a1d7 100644 --- a/web/editor_genbar.js +++ b/web/editor_genbar.js @@ -672,7 +672,7 @@ export function createEditorGenbar(host, {state, t, actions, text = ''}) { event.preventDefault(); event.stopPropagation(); passMenu.open = false; passMenu.querySelector('summary').focus(); return true; } - return {element: host, duration, tray, say, downloadFailure, commit, dismiss, press: allowEmpty => press(allowEmpty === true), canGenerate: () => !generate.disabled, + return {element: host, duration, firstFrame, tray, say, downloadFailure, commit, dismiss, press: allowEmpty => press(allowEmpty === true), canGenerate: () => !generate.disabled, service(value) { service = value; if (!value && note.contains(retryService)) { retryService.remove(); note.hidden = true; } diff --git a/web/editor_library.js b/web/editor_library.js index 94f06205..b28bf10e 100644 --- a/web/editor_library.js +++ b/web/editor_library.js @@ -88,6 +88,7 @@ export function createEditorLibrary(host, {store, t, actions, state}) { if (row.state === 'failed') { actions.notify?.(...importFailure(row.reason)); return; } const key = `${kind}:${row.id}`; if (!pendingAdds.has(key)) pendingAdds.set(key, {plus, project: actions.projectToken?.()}); + watchImports(); actions.notify?.(preparing()); } function startPending(items) { @@ -378,7 +379,7 @@ export function createEditorLibrary(host, {store, t, actions, state}) { } } async function importFiles(files, {at, track, replace = false} = {}) { - choose('import'); + choose('import'); watchImports(); const place = Number.isSafeInteger(at) && at >= 0 ? {at, ...(['a1', 'a2', 'a3'].includes(track) ? {track, replace} : {})} : null; for (const value of files) { if (disposed) break; @@ -400,13 +401,26 @@ export function createEditorLibrary(host, {store, t, actions, state}) { } } file.onchange = () => { importFiles([...file.files]); file.value = ''; }; - const stop = store.watchImports(items => { - for (const item of items) recentImports.delete(item.id); - // A list request started before an upload may finish after it. - imported = [...recentImports.values(), ...items]; importUnread = items.unreadable || 0; render(); - placeReady(imported); startPending(imported); - }); + // The import list is read every 2 s while the editor is shown. A hidden (kept) editor reads it only while an + // import it waits for is still on its way (sent, asked to be placed, or dropped on the tracks), then stops; it + // reads it again at once when it is shown again. + let stopImports = null, suspended = false; + const waiting = () => uploading.size > 0 || pendingAdds.size > 0 || placing.length > 0; + function watchImports() { + if (stopImports || disposed) return; + stopImports = store.watchImports(items => { + for (const item of items) recentImports.delete(item.id); + // A list request started before an upload may finish after it. + imported = [...recentImports.values(), ...items]; importUnread = items.unreadable || 0; render(); + placeReady(imported); startPending(imported); + if (suspended && !waiting()) { stopImports?.(); stopImports = null; } + }); + } + watchImports(); const stopUsed = state?.subscribe(event => { if (event.type === 'record') updateUsed(); }); render(); load(); - return {element: host, importFiles, refresh, dispose() { disposed = true; pendingAdds.clear(); window.removeEventListener('freevideo-result', generated); window.removeEventListener('freevideo-library-deleted', deleted); window.removeEventListener('freevideo-library-restored', restored); host.removeEventListener('scroll', scheduleMore); resize.disconnect(); cancelAnimationFrame(moreFrame); stop(); stopUsed?.(); clearTimeout(retryTimer); finishRetry?.(); }}; + return {element: host, importFiles, refresh, + suspend() { suspended = true; if (!waiting()) { stopImports?.(); stopImports = null; } }, + resume() { suspended = false; watchImports(); }, + dispose() { disposed = true; pendingAdds.clear(); window.removeEventListener('freevideo-result', generated); window.removeEventListener('freevideo-library-deleted', deleted); window.removeEventListener('freevideo-library-restored', restored); host.removeEventListener('scroll', scheduleMore); resize.disconnect(); cancelAnimationFrame(moreFrame); stopImports?.(); stopImports = null; stopUsed?.(); clearTimeout(retryTimer); finishRetry?.(); }}; } diff --git a/web/editor_media_references.js b/web/editor_media_references.js index ede740e3..2e55c30d 100644 --- a/web/editor_media_references.js +++ b/web/editor_media_references.js @@ -31,7 +31,6 @@ export function mediaReferences(node) { const node = media(), linked = name => node?.inputs?.find(i => i.name === name)?.link != null; const count = role => rows.filter(row => row.role === role).length; const references = count('reference') + ['reference', ...Array.from({length: 7}, (_, i) => 'reference_' + (i + 2)), 'reference_audio'].filter(linked).length; - if (references) return t('Choose keyframes or references. Disable unused cards.', '首尾帧与参考模式不能混用,请关闭本次不用的素材。'); return middleNotice(rows, {first: count('first') + Number(linked('first')), last: count('last') + Number(linked('last')), references, seconds}, t); }, // The length of the video these pictures are for; null while no generate node is connected. diff --git a/web/editor_touch.css b/web/editor_touch.css index f9e7f850..9a92d42a 100644 --- a/web/editor_touch.css +++ b/web/editor_touch.css @@ -3,7 +3,7 @@ A mouse never matches this block, and phones (≤ 480 px) keep their own layout. ── */ @media (pointer:coarse) and (min-width:481px){ /* Rows: play row 48, tool row 52. */ - .fv-studio.fv-editor,.fv-studio.fv-editor:has(.fv-ed-genbar[data-voice=true]){grid-template-rows:auto var(--fv-ed-project-h) minmax(96px,1fr) 48px var(--fv-ed-generation-row) 52px var(--fv-ed-timeline-h)} + .fv-studio.fv-editor,.fv-studio.fv-editor[data-hx-voice]{grid-template-rows:auto var(--fv-ed-project-h) minmax(96px,1fr) 48px var(--fv-ed-generation-row) 52px var(--fv-ed-timeline-h)} .fv-ed-notice-stack{bottom:calc(var(--fv-ed-timeline-h) + 52px + var(--fv-ed-generation-row) + 56px)} .fv-ed-gen-tray{bottom:calc(100% + 56px)} @@ -92,6 +92,6 @@ .fv-studio.fv-editor .fv-ed-track-view .fv-ed-track-heads>.fv-ed-add-audio::after{display:none} .fv-studio.fv-editor .fv-ed-track-view .fv-ed-track-head>[class$=-track-controls]{display:none} .fv-studio.fv-editor .fv-ed-track-view .fv-ed-track-head[data-open=true]>[class$=-track-controls]{display:flex;position:absolute;left:calc(100% + 4px);top:50%;transform:translateY(-50%);gap:0;padding:2px;background:var(--fv-card);border:1px solid var(--fv-border);border-radius:var(--fv-r-sm)} - .fv-studio.fv-editor .fv-ed-track-view .fv-ed-track-heads:has(>[data-open=true]){z-index:9} + .fv-studio.fv-editor .fv-ed-track-view .fv-ed-track-heads[data-hx-open]{z-index:9} .fv-studio.fv-editor .fv-ed-track-view :is(.fv-ed-audio-track-switch,.fv-ed-text-track-controls button){width:44px;min-width:44px;height:44px;min-height:44px} } diff --git a/web/editor_tracks.js b/web/editor_tracks.js index 7670ebf0..a82fe0bf 100644 --- a/web/editor_tracks.js +++ b/web/editor_tracks.js @@ -1391,10 +1391,11 @@ export function createTracks(host, {state, sources = {}, t = en => en, actions = // Time zero sits a little in from the scrolling area's left edge (the content's margin, editor_tracks.css), so a // frame's place in the scrolled area is its pixels plus that lead. function scrolledX(frames) { return pixels(frames) + content.offsetLeft; } + // The time under the anchor stays under it: time zero sits the content's lead in from the scrolled area's edge. function zoom(value, anchor = scroll.clientWidth / 2) { - const center = (scroll.scrollLeft + anchor) / state.zoom; + const lead = content.offsetLeft, center = (scroll.scrollLeft + anchor - lead) / state.zoom; state.setZoom(clamp(value, Number(slider.min), Number(slider.max))); - scroll.scrollLeft = Math.max(0, center * state.zoom - anchor); + scroll.scrollLeft = Math.max(0, center * state.zoom + lead - anchor); } function fitAll() { if (fit.disabled) return; diff --git a/web/error_panel.js b/web/error_panel.js index bdb1b527..a4f4e0b4 100644 --- a/web/error_panel.js +++ b/web/error_panel.js @@ -47,8 +47,9 @@ const PLAIN_ERRORS = [ {key: 'continuation-media', message: 'Continue from video cannot be used with these settings. Connect up to 3 pictures as references, and remove video, audio and pre-encoded inputs.', title: ['A continued part takes picture references only', '接续段只能用图片参考'], summary: ['Connect up to 3 pictures as references, and remove video, audio and pre-encoded inputs.', '最多接 3 张图片作为参考图,并移除视频、音频参考和预编码输入。']}, - {key: 'media-mixed-layout', message: 'Choose keyframes or experimental references; mixed layouts are not supported', - title: ['First and last frames cannot be used with references', '首尾帧不能和参考素材同时使用'], + // Only the Mac engine still refuses keyframes next to references; elsewhere they become still guides. + {key: 'media-mixed-layout', message: 'Reference and first/last keyframe layouts cannot be mixed in one request on this Mac; keep one of the two', + title: ['On this Mac, first and last frames cannot be used with references', '这台 Mac 上首尾帧不能与参考素材同时使用'], summary: ['Turn off the media cards or inputs you are not using, then generate again.', '请关闭本次不用的素材卡片或输入,再重新生成。']}, {key: 'audio-original-passes', prefixes: ['audio_original_passes:'], title: ['This audio needs two-pass acceleration', '这段音频需要二采加速'], @@ -345,6 +346,43 @@ export function createErrorReport(detail, context = {}) { return report; } +// Failures of turning a reference video into depth (freevideo_engine/depth_reference.py), most specific first. +const RETRY_REPORT = ['Try again. If it happens again, choose "Report a problem" to send us the report.', '请重试。再次出现时,请点击“提交问题”,把报告发给我们。']; +const REFERENCE_FAILURES = [ + [/Source video (?:frame count )?changed during depth (?:conversion|inspection)/i, + 'reference-changed', ['The reference video changed', '参考视频在转换时被改动'], + ['The reference video file changed while FreeVideo was converting it.', '转换参考视频的过程中,这个文件被改动了。'], + ['Try again, and leave the file unchanged until the video is generated.', '请重试,并在生成完成前保持该文件不变。']], + [/Depth reference (?:needs a decodable video|video has no valid frame rate|video changes display rotation|video changes dimensions|video has no decodable frames)/i, + 'reference-unreadable', ['The reference video cannot be read', '无法读取参考视频'], + ['FreeVideo could not read this reference video frame by frame.', 'FreeVideo 无法逐帧读取这段参考视频。'], + ['Convert it to a standard MP4 with one fixed size, or choose another video, then try again.', '请把它转成尺寸固定的标准 MP4,或换一段视频,然后重试。']], + [/Depth reference weights are unavailable|Depth reference weight size\/SHA-256 verification failed/i, + 'reference-model', ['The depth model could not be downloaded', '深度模型未能下载'], + ['Depth only uses a small model, which could not be downloaded or verified.', '“仅参考深度”需要一个小模型,这次未能下载或校验未通过。'], + ['Check the network connection or choose another download source in Settings, then try again.', '请检查网络,或在设置里换一个下载源,然后重试。']], + [/Not enough free GPU memory for depth reference/i, + 'reference-vram', ['Not enough GPU memory for depth', '显存不足,无法提取深度'], + ['Extracting depth needs free GPU memory, and other programs were using it.', '提取深度需要空闲显存,当时被其他程序占用。'], + ['Close other programs that use the GPU, then try again.', '请关闭其他占用显卡的程序,然后重试。']], + [/Depth reference needs 1 GiB working RAM|Depth reference stopped to preserve 1 GiB/i, + 'reference-ram', ['Not enough memory to convert the reference video', '内存不足,参考视频未能转换完成'], + ['FreeVideo stopped converting the reference video to keep the computer responsive.', '为保证电脑正常运行,FreeVideo 停止了参考视频的转换。'], + ['Close other programs or use a shorter reference video, then try again.', '请关闭其他程序或换一段更短的参考视频,然后重试。']], + [/Not enough disk space to stage depth frames/i, + 'reference-disk', ['Not enough disk space', '磁盘空间不足'], + ['Converting the reference video needs temporary space on the drive that holds FreeVideo\'s data.', '转换参考视频需要在 FreeVideo 数据所在的磁盘上临时占用一些空间。'], + ['Free some space on that drive, then try again.', '请在该磁盘上腾出一些空间,然后重试。']], + [/CUDA is unavailable for depth reference/i, + 'reference-gpu', ['The GPU is not available for depth', '暂时无法用显卡提取深度'], + // Raised when the depth step starts on a computer set up for the GPU, but the graphics driver offers none to it. + ['When depth extraction started, the graphics driver did not make the GPU available.', '开始提取深度时,显卡驱动未提供可用的显卡。'], + ['Restart FreeVideo and try again. If it happens again, choose "Report a problem" to send us the report.', '请重启 FreeVideo 后重试。再次出现时,请点击“提交问题”,把报告发给我们。']], + [/Depth reference worker exited with code|Depth reference cache unexpectedly contains|Depth reference output dimensions|Depth model returned invalid|Depth reference device must be/i, + 'reference-failed', ['The reference video could not be converted', '参考视频未能转换'], + ['Turning the reference video into depth stopped unexpectedly.', '把参考视频转成深度时意外中止。'], RETRY_REPORT], +]; + // Match explicit failure signatures, not a guessed GPU/RAM capacity. Keep the // original error separately so an explanation never replaces diagnostic data. // known: a report's known_error. Pass null when the report has none, so an @@ -392,6 +430,11 @@ export function failureAdvice(value, t, known = knownError(value)) { if (key === known) return {...row(key, title, summary, ['', '']), plain: true}; } + // A reference video turned into depth (depth_reference.py) failed: the cause in people's words and the + // next step, in both languages; the engine's own sentence stays in the details below. + for (const [pattern, kind, title, summary, action] of REFERENCE_FAILURES) { + if (pattern.test(text)) return row(kind, title, summary, action); + } if (known === 'media-missing') return {...row('media-missing', ['A media file is missing', '找不到素材'], ['Upload or select the missing media file again, then generate.', '请重新上传或选择缺少的素材后再生成。'], ['', '']), plain: true}; @@ -474,6 +517,23 @@ export function failureAdvice(value, t, known = knownError(value)) { return row('encoder-files', ['The text encoder is not fully installed', '文本编码器没有装全'], ['Some of the text encoder files FreeVideo needs are missing.', 'FreeVideo 需要的部分文本编码器文件缺失。'], repairAction()); + // Upscaling to 4K (frame_upscale.py): its own small model, disk need and GPU memory. + if (/The 4K upscale model (?:could not be downloaded|failed its size\/SHA-256 check)/.test(text)) + return row('upscale-download', ['The upscale model could not be downloaded', '放大模型未能下载'], + ['Upscaling uses a small model (about 5 MB), which could not be downloaded or verified this time.', '放大要用一个约 5 MB 的小模型,这次没能下载,或下载后校验未通过。'], + ['Check the network connection or choose another download source in Settings, then try again. If it happens again, choose "Report a problem" to send us the report.', + '请检查网络,或在设置里换一个下载源,然后重试。再次出现时,请点击“提交问题”,把报告发给我们。']); + if (/Not enough disk space to save the 4K video/.test(text)) { + const megabytes = /about (\d+) MB is needed/.exec(text)?.[1]; + return row('upscale-disk', ['Not enough disk space for the upscaled video', '磁盘空间不足,放大后的视频没能保存'], + megabytes ? [`The upscaled video needs about ${megabytes} MB on the drive of the output folder.`, `放大后的视频需要输出文件夹所在磁盘约 ${megabytes} MB 空间。`] + : ['The upscaled video needs more space on the drive of the output folder.', '放大后的视频需要输出文件夹所在磁盘更多空间。'], + ['Free some space on that drive, then try again.', '请在该磁盘上腾出空间后重试。']); + } + if (/Not enough GPU memory to upscale to 4K/.test(text)) + return row('upscale-memory', ['Not enough GPU memory to upscale', '显存不足,放大没能完成'], + ['Upscaling needs about 1.5 GB of free GPU memory, and other programs were using it.', '放大需要约 1.5 GB 空闲显存,当时被其他程序占用。'], + ['Close other programs that use the GPU, then try again.', '请关闭其他占用显卡的程序,然后重试。']); if (/No space left on device|WinError 112|disk (?:is )?full/i.test(text)) return row('disk', ['Disk space is insufficient', '磁盘空间不足'], ['FreeVideo could not write a required file.', 'FreeVideo 无法写入所需文件。'], diff --git a/web/freevideo.js b/web/freevideo.js index 2704d4e2..42575cfc 100644 --- a/web/freevideo.js +++ b/web/freevideo.js @@ -11,6 +11,7 @@ import { openStudio, loraPanel, loraWarning } from "./studio.js"; import { createGenerationProgress, referenceTrimText, thermalText, sharedGpuText, keepSoundText, encoderFileText, encoderFilePath } from './generation_progress.js'; import { createProgressConnection } from './progress_connection.js'; import { notifyCompatibility } from './compatibility.js'; +import { clearWorkflowDrafts, workflowPersist } from './workflow_drafts.js'; import { startUpdateChecks, productVersion } from './updates.js'; import { startWhatsNew } from './whatsnew.js'; import { startWhiteboxWorker } from './whitebox_worker.js'; @@ -31,7 +32,7 @@ import { shareButton } from './share.js'; import { reportFileName } from './report_issue.js'; import { rememberPromptDraft, savePromptDraft, trackPromptDraft, watchPromptHistory, promptHistoryRestoring } from './prompt_draft.js'; import { cleanOptionalWidgets, cleanOptionalPrompt, optionalInputValue, cleanAudioUse } from './optional_inputs.js'; -import { regenerateResult, createSecondPassQueue, enableNode } from './studio_queue.js'; +import { regenerateResult, createSecondPassQueue, enableNode, upscaleWork } from './studio_queue.js'; import { secondPassAction } from './result_actions.js'; import { openImageEditor, icon } from './image_editor.js'; import { imageGenerationSupported } from './image_generation.js'; @@ -41,6 +42,7 @@ import { MAX_MIDDLE, secondsOf, defaultTime, timeProblems, timeRange, problemTex import { swapState, requestRows, swapMissing, withPrefix, peopleOf } from './replace_state.js'; import { swapMissingText } from './replace_person.js'; import { issueButton } from './issue_button.js'; +import { userMessage } from './user_message.js'; import { AUDIO_USE, usesOriginal, checkOriginal, checkedLength, failureText, multipleText, createUseSwitch, originalBlocked, stuckText, liftBlock } from './audio_original.js'; const languageOverride = typeof location !== 'undefined' @@ -60,7 +62,6 @@ style.textContent = ` .fv-panel[data-freevideo=result]{display:flex;flex-direction:column;justify-content:center}.fv-panel[data-freevideo=result][data-hx-ppr]{justify-content:flex-start}.fv-panel .fv-connected-card{text-align:center;padding:28px 12px;border:1px solid var(--fv-border);border-radius:var(--fv-r-md,12px);color:var(--fv-muted);background:var(--fv-raised)} .fv-panel button,.fv-panel select,.fv-panel a{box-sizing:border-box;min-height:var(--fv-h-sm,32px);border:1px solid var(--fv-border);border-radius:var(--fv-r-sm,8px);background:var(--fv-raised);color:var(--fv-ink);padding:5px 10px;font:inherit;font-weight:var(--fv-medium,500);cursor:pointer;text-decoration:none} .fv-panel button:hover,.fv-panel a:hover{background:var(--fv-hover)}.fv-panel button:disabled{opacity:.45;cursor:wait} -.fv-menu-failure{width:min(460px,calc(100vw - 32px));height:auto}.fv-menu-failure::backdrop{background:#0009} .fv-panel select{max-width:170px}.fv-panel .fv-toolbar>.fv-select{width:auto}.fv-note[hidden]{display:none}.fv-note{color:var(--fv-muted);font-size:var(--fv-micro,12px);margin:8px 0;white-space:pre-wrap}.fv-error{color:var(--fv-danger)}.fv-panel .fv-depth-only input,.fv-panel .fv-sound input{min-height:0;height:16px}.fv-panel .fv-depth-only{display:flex;align-items:center;gap:6px;margin:0 0 8px;white-space:nowrap;font-size:var(--fv-micro);cursor:pointer} .fv-mode{font-size:var(--fv-micro,12px);color:var(--fv-accent)} .fv-panel .fv-time{display:flex;align-items:center;gap:8px;margin:8px 0 0}.fv-panel .fv-time input{width:92px;min-height:var(--fv-h-sm,32px);padding:4px 8px;border:1px solid var(--fv-border);border-radius:var(--fv-r-sm,8px);background:var(--fv-bg);color:var(--fv-ink);font:inherit;font-size:16px}.fv-panel .fv-time input[aria-invalid=true]{border-color:var(--fv-danger)}.fv-panel .fv-time-error{margin:4px 0 0;color:var(--fv-danger);font-size:var(--fv-micro,12px)} @@ -310,7 +311,7 @@ function mediaPanel(node, mount = null) { latest[index] = {...latest[index], file: result.file, ...(hasOriginal ? {source} : {}), edit: outcome.edit}; update(latest); message(hasOriginal ? text('The edited image is saved, and the original is kept.', '编辑后的图片已保存,原图已保留。') : ''); - } catch (error) { message(error.message, true); } + } catch (error) { message(userMessage(error, text, text('Could not save the image. Try again.', '没能保存图片,请重试。')), true); } finally { node.isUploading = false; add.disabled = false; addAudio.disabled = false; } } async function newImage() { @@ -334,7 +335,7 @@ function mediaPanel(node, mount = null) { const latest = read(); latest.push({file: result.file, name: outcome.name, role: role.value, enabled: true, edit: outcome.edit}); update(latest); - } catch (error) { message(error.message, true); } + } catch (error) { message(userMessage(error, text, text('Could not save the image. Try again.', '没能保存图片,请重试。')), true); } finally { node.isUploading = false; add.disabled = addAudio.disabled = generateImage.disabled = false; } } function restoreImage(file) { @@ -406,7 +407,10 @@ function mediaPanel(node, mount = null) { } cards.replaceChildren(); let rows; - try { rows = read(); } catch (error) { message(error.message, true); return; } + try { rows = read(); } catch (error) { + const unreadable = text('The media list cannot be read. Add the media again.', '素材列表无法读取,请重新添加素材。'); + message(error?.name === 'SyntaxError' ? unreadable : userMessage(error, text, unreadable), true); return; + } const active = rows.filter(row => row.enabled !== false); const linked = name => node.inputs?.find(i => i.name === name)?.link != null; // A Generate node that continues a video takes these keyframes as pictures, so they may sit beside references. @@ -429,7 +433,7 @@ function mediaPanel(node, mount = null) { } const middleProblem = middleNotice(active, {first, last, references: refs, seconds: videoSeconds()}, text); const audioUnlinked = node.widgets?.find(w => w.name === 'audio_use')?.value === 'original' && !linked('reference_audio'); - message(audioUnlinked ? text('Connect audio to "Reference audio", or set "Audio use" to "reference", before generating.', '请连接“参考音频”,或把“音频用途”改为“参考”后再生成。') : refs > 32 ? text('There are more than 32 references; remove some before generating.', '参考素材超过 32 个,可移除部分后再生成。') : continuing && active.filter(row => row.role === 'reference' && mediaKind(row.file) === 'image').length > 3 ? text('When continuing, only the first 3 images are used.', '接续时只用前 3\u00a0张图片。') : (first || last || middle.length) && continuing ? (middle.length ? middleLabels.continuing(text) : text("When continuing a video, the first and last frames are used as references.", "接续视频时,首尾帧会用作参考图。")) : refs && (first || last || middle.length) ? text("Choose keyframes or references. Disable unused cards.", "首尾帧与参考模式不能混用,请关闭本次不用的素材。") : first > 1 || last > 1 ? text("Keep only one first frame and one last frame enabled.", "首帧和尾帧各只能启用一张图片。") : middleProblem ? middleProblem : middleInfo(active, videoSeconds(), text) ? middleInfo(active, videoSeconds(), text) : "", Boolean(audioUnlinked || refs > 32 || refs && (first || last || middle.length) && !continuing || first > 1 || last > 1 || middleProblem && !continuing)); + message(audioUnlinked ? text('Connect audio to "Reference audio", or set "Audio use" to "reference", before generating.', '请连接“参考音频”,或把“音频用途”改为“参考”后再生成。') : refs > 32 ? text('There are more than 32 references; remove some before generating.', '参考素材超过 32 个,可移除部分后再生成。') : continuing && active.filter(row => row.role === 'reference' && mediaKind(row.file) === 'image').length > 3 ? text('When continuing, only the first 3 images are used.', '接续时只用前 3\u00a0张图片。') : (first || last || middle.length) && continuing ? (middle.length ? middleLabels.continuing(text) : text("When continuing a video, the first and last frames are used as references.", "接续视频时,首尾帧会用作参考图。")) : first > 1 || last > 1 ? text("Keep only one first frame and one last frame enabled.", "首帧和尾帧各只能启用一张图片。") : middleProblem ? middleProblem : middleInfo(active, videoSeconds(), text) ? middleInfo(active, videoSeconds(), text) : "", Boolean(audioUnlinked || refs > 32 || first > 1 || last > 1 || middleProblem && !continuing)); if (!rows.length && !connections.childElementCount) cards.append(el("div", text("Drop images or video here", "拖入图片或视频"), "fv-empty")); if (!rows.length && connections.childElementCount) cards.append(el('div', text('Media comes from the connected inputs; no upload is needed.', '素材来自已连接的输入,无需上传。'), 'fv-connected-card')); rows.forEach((row, index) => { @@ -562,7 +566,6 @@ function mediaPanel(node, mount = null) { if (continues) return ''; const count = role => rows.filter(row => row.role === role).length; const references = count('reference') + referenceInputs.filter(linked).length + Number(linked('reference_audio')); - if (references) return text("Choose keyframes or references. Disable unused cards.", "首尾帧与参考模式不能混用,请关闭本次不用的素材。"); return middleNotice(rows, {first: count('first') + Number(linked('first')), last: count('last') + Number(linked('last')), references, seconds: videoSeconds()}, text); } serialized.serializeValue = () => { @@ -598,7 +601,7 @@ function mediaPanel(node, mount = null) { rows.push({file: result.file, ...(result.name || file.name ? {name: result.name || file.name} : {}), role: kind === "image" ? use : "reference", enabled: true}); update(rows); } if (skipped.length) message(skippedNote(skipped), !usable.length); - } catch (error) { message(error.message, true); } + } catch (error) { message(userMessage(error, text, text('Could not upload. Try again.', '没能上传,请重试。')), true); } finally { uploading = false; node.isUploading = false; add.disabled = false; addAudio.disabled = false; picker.value = ""; audioPicker.value = ''; } } picker.onchange = () => upload(picker.files); @@ -826,6 +829,7 @@ function resultPanel(node) { fitPanel(); }; node.freevideoUpscaleResult = createSecondPassQueue(api, () => node.id, async () => { enableNode(node); return cleanOptionalPrompt(await app.graphToPrompt()); }); + node.freevideoUpscaleWork = (value, options) => upscaleWork(api, node.id, value, async () => { enableNode(node); return cleanOptionalPrompt(await app.graphToPrompt()); }, options); node.freevideoRegenerateResult = async value => { if (node.freevideoRegenerating) return; node.freevideoRegenerating = true; @@ -921,24 +925,15 @@ const isFreeVideoNode = id => /^FreeVideo/.test(String(app.graph?.getNodeById(id const launchVisit = isLaunchVisit(globalThis.location?.search, globalThis.sessionStorage); const inFront = freeVideoInFront(launchVisit); -let menuFailure; +// A failure here goes to the page check's card, which names the cause, says what to do, and carries the error for the report. async function openFromMenu() { - menuFailure?.close(); try { const node = (app.graph?._nodes || []).find(isGenerate) || await openFreeVideoWorkflow(); - if (!node) throw new Error('FreeVideo workflow unavailable'); + if (!node) throw new Error('The FreeVideo workflow loaded without a FreeVideoGenerate node'); showStudio(node); } catch (error) { console.warn('FreeVideo menu:', error); - const message = text('Could not complete. Try again.', '没有完成,请重试'); - const dialog = el('dialog', undefined, 'fv-panel fv-menu-failure'); menuFailure = dialog; - dialog.setAttribute('aria-label', 'FreeVideo'); - const actions = el('div', undefined, 'fv-row'); - actions.append(issueButton(text, () => ({where: ['Open FreeVideo', '打开 FreeVideo'], message})), - button(text('Close', '关闭'), '', () => dialog.close())); - dialog.append(el('p', message), actions); - dialog.onclose = () => { dialog.remove(); if (menuFailure === dialog) menuFailure = null; }; - document.body.append(dialog); dialog.showModal(); + health({type: 'error', where: 'menu', error}); } } @@ -959,7 +954,7 @@ app.registerExtension({ for (const [where, start] of [['progress', () => progressConnection.start()], ['navigation', () => installNavigation(showStudio, agentInterfaceState(api), {openWorkflow: openFreeVideoWorkflow, recheck: () => agentInterfaceState(api)})], ['updates', startUpdateChecks], ['whatsnew', () => startWhatsNew({api, cn, productVersion, inFront})], ['done-notify', () => startDoneNotify({api, text, desktop: desktopNoticeEnabled, isFreeVideoNode, isFreeVideoWorkflow: () => (app.graph?._nodes || []).some(isGenerate)})], - ['whitebox', () => startWhiteboxWorker({api})]]) { + ['whitebox', () => startWhiteboxWorker({api})], ['workflow-drafts', () => clearWorkflowDrafts({persist: workflowPersist(app)})]]) { try { start(); } catch (error) { health({type: 'error', where, error}); } } window.addEventListener('pagehide', () => savePromptDraft(api, true)); diff --git a/web/glass/settings.css b/web/glass/settings.css index e0bf72ac..5780d584 100644 --- a/web/glass/settings.css +++ b/web/glass/settings.css @@ -251,6 +251,10 @@ dialog.fv-set .st-bar.is-ind>i{transform:none;width:30%;animation:st-ind 1.3s va @media (prefers-reduced-motion:reduce){dialog.fv-set .st-bar.is-ind>i{animation:none;width:100%;opacity:.5}} /* copyable path and text */ dialog.fv-set .st-path{font-family:var(--fv-font-mono);font-size:var(--fv-fs-1);line-height:var(--fv-lh-1);color:var(--fv-fg2);overflow-wrap:anywhere} +/* a path cut in the middle on one line: its start gives way with an ellipsis, its last folder stays (whole monospace + characters, so no gap is left between the ellipsis and the last folder) */ +dialog.fv-set .st-path-cut{display:block;min-width:0;max-width:100%;white-space:nowrap;overflow:hidden;overflow-wrap:normal} +dialog.fv-set .st-path-cut>.st-path-head{display:inline-block;max-width:calc(100% - 26ch);max-width:round(down,calc(100% - 26ch),1ch);overflow:hidden;text-overflow:ellipsis;vertical-align:top} dialog.fv-set .st-pre{margin:0;padding:var(--fv-sp-12);border-radius:var(--fv-rad-ctl);background:var(--fv-ctl-bg);font-family:var(--fv-font-mono);font-size:var(--fv-fs-1);line-height:var(--fv-lh-1);color:var(--fv-fg2); white-space:pre-wrap;overflow-wrap:anywhere;max-height:168px;overflow:auto} /* folds */ diff --git a/web/glass/studio.css b/web/glass/studio.css index d6fe59a9..9962894d 100644 --- a/web/glass/studio.css +++ b/web/glass/studio.css @@ -909,7 +909,7 @@ html body .fv-studio.fv-create .fvs-console :is(.fvs-console-prompt,.fv-section, .fv-studio.fv-create .fvs-step::after{content:"";position:absolute;top:0;bottom:0;left:calc(50% - var(--fv-touch) / 2);right:calc(50% - var(--fv-touch) / 2)} .fv-studio.fv-create .fvs-stepper{height:var(--fv-touch)} .fv-studio.fv-create .fvs-console .fv-key-more{width:var(--fv-touch)} - .fv-studio.fv-create .fvs-console .fv-runrow:has(>.fv-key-more:not([hidden]))>.fv-primary{padding-right:calc(var(--fv-touch) + var(--fv-sp-4))}} + .fv-studio.fv-create .fvs-console .fv-runrow[data-hx-more]>.fv-primary{padding-right:calc(var(--fv-touch) + var(--fv-sp-4))}} @media(min-width:761px){ .fv-studio.fv-create .fvs-console .fv-runrow.fv-at-moved>.fv-key-more{height:calc(2 * var(--fvs-row) + var(--fv-sp-8))} .fv-studio.fv-create .fvs-console .fv-runrow.fv-at-moved>.fv-key-more>summary{border-radius:0 var(--fv-rad-ctl) var(--fv-rad-ctl) 0} diff --git a/web/health.js b/web/health.js index 987de15c..fb610b63 100644 --- a/web/health.js +++ b/web/health.js @@ -483,9 +483,10 @@ function reportText(item) { navigation: t('The FreeVideo toolbar could not be added', 'FreeVideo 工具栏没有加载'), progress: t('Live progress could not start', '生成进度无法更新'), updates: t('Update checks could not start', '更新检查无法启动'), - launch: t('The FreeVideo workflow did not open', 'FreeVideo 工作流没有打开')}[item.where] || t('FreeVideo reported an error', 'FreeVideo 报错'); + launch: t('The FreeVideo workflow did not open', 'FreeVideo 工作流没有打开'), + menu: t('FreeVideo could not be opened from the menu', '从菜单打开 FreeVideo 失败')}[item.where] || t('FreeVideo reported an error', 'FreeVideo 报错'); // The script's own words go to the technical details and the report, not into the sentence the card shows. - return {text: where, detail: describe(item.error), error: item.error, advice: item.where === 'launch' ? 'relaunch' : 'reload'}; + return {text: where, detail: describe(item.error), error: item.error, advice: item.where === 'launch' ? 'relaunch' : 'reload', asked: item.where === 'menu'}; } function extensionProblem(problem) { @@ -612,10 +613,10 @@ window.addEventListener('keydown', event => { if (event.key !== 'Escape' || !card?.isConnected) return; event.preventDefault(); event.stopImmediatePropagation(); dismiss(); }, true); -function show(problems) { +function show(problems, asked = false) { opening?.finish(); opening = null; lastProblems = problems; - if (dismissed(problems)) { card?.remove(); card = null; return; } + if (!asked && dismissed(problems)) { card?.remove(); card = null; return; } addQuoteFaces(); card?.remove(); card = document.createElement('section'); @@ -629,7 +630,9 @@ function show(problems) { const extension = problems.map(extensionProblem).find(Boolean); const extensionAdvice = extension && extensionUI.browserExtensionAdvice(extension, t, {blocked: problems.some(p => p.advice === 'blocked')}); - title.textContent = extensionAdvice?.title || t('FreeVideo did not load completely', 'FreeVideo 没有完整加载'); + // Only what the user just asked for failed (opening from the menu): the page itself loaded. + title.textContent = extensionAdvice?.title || (problems.every(p => p.asked) ? t('FreeVideo ran into a problem', 'FreeVideo 出错了') + : t('FreeVideo did not load completely', 'FreeVideo 没有完整加载')); Object.assign(title.style, {color: '#f09aa2', fontWeight: '600', fontSize: '16px', marginBottom: '8px'}); const list = document.createElement('ul'); Object.assign(list.style, {margin: '0 0 10px', paddingLeft: '18px'}); @@ -803,8 +806,10 @@ async function check() { // Later failures, such as the workspace failing to open from a node. listener = item => { if (item.type !== 'error') return; - const problems = distinct([...lastProblems, reportText(item)]); - show(problems); send('error', problems); + // Opening from the menu is a click the user just made: its failure leads the card and shows even after an earlier card was closed. + const asked = item.where === 'menu', fresh = reportText(item); + const problems = distinct(asked ? [fresh, ...lastProblems] : [...lastProblems, fresh]); + show(problems, asked); send('error', problems); }; if (document.hidden && problems.length) { // File and extension diagnostics still run at startup. Only their diff --git a/web/image_editor.css b/web/image_editor.css index 9848934e..0076e944 100644 --- a/web/image_editor.css +++ b/web/image_editor.css @@ -117,7 +117,7 @@ button.fv-ie-size:hover{background:var(--fv-hover);color:var(--fv-ink)} .fv-ie-gen-box[data-folded=true]>.fv-ie-gen-prompt{color:transparent} .fv-ie-gen-prompt:disabled{opacity:.5} .fv-ie-gen-note{align-self:center;min-width:0;overflow-wrap:anywhere;font-variant-numeric:tabular-nums} -.fv-ie-generation[data-running=true]>.fv-ie-gen-note{white-space:nowrap} +.fv-ie-generation[data-running=true]:not([data-waiting=true])>.fv-ie-gen-note{white-space:nowrap} .fv-ie-generation>.fv-ie-button{grid-column:4;min-height:32px} .fv-ie-generation[data-message=true]>.fv-ie-gen-note{max-width:260px} /* Image failures use the video's report button and submission card on their own row. */ diff --git a/web/image_editor.js b/web/image_editor.js index 31be2c56..cb5d211d 100644 --- a/web/image_editor.js +++ b/web/image_editor.js @@ -15,6 +15,7 @@ import {confirmStop, startJobSources} from './task_float.js'; import {saveToWorks} from './image_works.js'; import {listenDialogKey} from './dialog_keys.js'; import {issueButton} from './issue_button.js'; +import {userMessage} from './user_message.js'; import {skinSelect} from './fv_select.js'; const css = document.createElement('link'); @@ -1155,7 +1156,7 @@ async function openImageEditorNow({source = null, name = source || '', target = else { const result = await upload(file); name = typeof result === 'string' ? result : result?.file; } done(); await addImageLayer(name, file.name); } - catch (error) { message(error.message || t('Upload failed.', '上传失败。'), ['Image editor upload', '图片编辑器上传']); } + catch (error) { message(userMessage(error, t, t('Could not upload. Try again.', '没能上传,请重试。')), ['Image editor upload', '图片编辑器上传'], error); } }; function duplicateLayer() { const layer = active(); @@ -1905,10 +1906,11 @@ async function openImageEditorNow({source = null, name = source || '', target = let resolveResult; const result = new Promise(r => { resolveResult = r; }); let messageTimer = null, workingTimer = null; - function message(text, where = null) { + // `error`, when given, is what the report sends instead of the plain sentence shown. + function message(text, where = null, error = null) { clearInterval(workingTimer); workingTimer = null; status.textContent = text; - if (text && where) status.append(issueButton(t, () => ({where, message: text}))); + if (text && where) status.append(issueButton(t, () => ({where, message: error?.message || text}))); clearTimeout(messageTimer); if (text) messageTimer = setTimeout(() => { status.textContent = ''; }, where ? 20000 : 5000); } diff --git a/web/image_generation.js b/web/image_generation.js index a12261fd..76c4cd71 100644 --- a/web/image_generation.js +++ b/web/image_generation.js @@ -291,6 +291,7 @@ const FAILED_AT = Object.freeze({ // wording belong to report_issue.js, shared with video reports. // Queue and size-fit notes, kept with the failure copy for editorial review. export const QUEUE_LABELS = Object.freeze({ + busy: ['Another image is generating. This one starts when it finishes.', '前面有 1 张在生成,完成后自动开始。'], image: ['Added to the queue. It starts when the previous one finishes.', '已加入队列,前面的完成后自动开始。'], video: ['Queued. It starts when the video finishes.', '已排队,视频生成完后自动开始。'], }); @@ -319,7 +320,9 @@ export function imageReportBar(card, report_id, t, {productVersion = () => null, const anchor = doc.createElement('button'); anchor.type = 'button'; anchor.className = 'fv-action fv-action-secondary fv-action-report' + (quiet ? ' fv-image-report-quiet' : ''); anchor.textContent = t(...download); anchor.title = t(...REPORT_LABELS.description); - const issue = issueButton(t, () => ({where: ['Image diagnostic report', '生图诊断报告'], message: t(...REPORT_LABELS.unavailable)})); + // On a failure card it is drawn as the card's actions; beside a quiet report link it stays as it was. + const issue = issueButton(t, () => ({where: ['Image diagnostic report', '生图诊断报告'], message: t(...REPORT_LABELS.unavailable)}), + quiet ? {} : {className: 'fv-action'}); issue.hidden = true; anchor.onclick = async () => { if (anchor.disabled) return; @@ -373,9 +376,10 @@ export function renderImageFailure(host, {error, report_id, stage, step, fitted, let bar; if (report_id) ({bar} = imageReportBar(card, report_id, t, {productVersion, fetchApi})); else { - const facts = [[['Error code', '错误码'], error], [['Stage', '阶段'], stage], [['Step', '步骤'], step], [['Memory', '内存'], memory]].filter(([, v]) => v); + const facts = [[['Error code', '错误码'], error], [['Stage', '阶段'], stage], [['Step', '步骤'], step || (stage ? '' : 'unreported')], [['Memory', '内存'], memory]].filter(([, v]) => v); bar = doc.createElement('div'); bar.className = 'fv-actions'; - bar.append(issueButton(t, () => ({where: ['Image generation', '图像生成'], message: facts.map(([[en, zh], v]) => `${t(en, zh)}: ${v}`).join('\n')}))); + // Drawn as the card's other actions (Retry, Download report): their border, focus ring and press. + bar.append(issueButton(t, () => ({where: ['Image generation', '图像生成'], message: facts.map(([[en, zh], v]) => `${t(en, zh)}: ${v}`).join('\n')}), {className: 'fv-action'})); if (again) bar.prepend(again); card.append(bar); const details = doc.createElement('details'); details.className = 'fv-image-failure-details'; @@ -554,11 +558,13 @@ export function imageRemainingText(seconds, t) { // An epoch rejects late uploads/status/results. A generate response arriving // after Stop still has to be cancelled, even though its job was not known yet. +const IMAGE_GEN_BUSY_RETRY_MS = 2000; + export function createImageGenSession({client, prepare, apply, onChange = () => {}, beforeGenerate = async () => {}, schedule = setTimeout, unschedule = clearTimeout, store = null, visible = () => globalThis.document?.visibilityState !== 'hidden', tasks = null}) { - let epoch = 0, timer = null, infoTimer = null, disposed = false, checking = null, unwatch = null; + let epoch = 0, timer = null, infoTimer = null, disposed = false, checking = null, unwatch = null, wake = null; let state = {info: null, checking: false, running: false, job: null, fraction: 0, remaining: null, stage: '', error: '', report_id: null, waiting: '', fitted: null}; const emit = patch => { state = {...state, ...patch}; if (!disposed) onChange(state); }; @@ -589,7 +595,7 @@ export function createImageGenSession({client, prepare, apply, onChange = () => // With the page's job store (tasks): the store polls the engine and keeps the job when the editor closes; the // session only follows its row. Done: the result is placed (when this editor is still the one that asked); // the store files the picture in the works either way. - function follow(current, id, context) { + function follow(current, id, context, onBusy = null) { const alive = () => current === epoch && !disposed; unwatch?.(); let ended = false, off = null; const stop = () => { ended = true; off?.(); off = null; if (unwatch === stop) unwatch = null; }; @@ -614,6 +620,7 @@ export function createImageGenSession({client, prepare, apply, onChange = () => }, error => { if (alive()) { forget(); emit({running: false, job: null, waiting: '', stopping: false, ...failed(error)}); } }); return; } + if (onBusy && row.status === 'failed' && row.failure?.code === 'busy') { tasks.placed?.(row); onBusy(); return; } forget(); tasks.placed?.(row); if (row.status === 'cancelled') emit({running: false, job: null, stage: '', fraction: 0, waiting: '', stopping: false, error: '', report_id: null, memory: ''}); else { const reason = row.failure || {}; emit({running: false, job: null, waiting: '', stopping: false, ...failed({...reason, code: reason.code || 'generation_failed', step: reason.step || (reason.code ? '' : 'task_row')})}); } @@ -623,12 +630,13 @@ export function createImageGenSession({client, prepare, apply, onChange = () => } // One job from its first status to the result. A job taken up again after the page was // reloaded (``resumed``) that the service no longer knows ends quietly: there is nothing to say. - function track(current, job, context, withImages, resumed = false) { + function track(current, job, context, withImages, resumed = false, onBusy = null) { const alive = () => current === epoch && !disposed; async function poll() { try { const row = await client.status(job); if (!alive()) return; + if (onBusy && row.state === 'error' && row.error === 'busy') throw failure('busy', row); const fraction = imageGenProgress(row.stage, row.fraction, withImages, row.overall); emit({fraction: Math.max(state.fraction, fraction), stage: row.stage || '', waiting: row.waiting || '', remaining: Number.isFinite(row.remaining_seconds) ? row.remaining_seconds : null, @@ -642,6 +650,7 @@ export function createImageGenSession({client, prepare, apply, onChange = () => else timer = schedule(() => { timer = null; void poll(); }, IMAGE_GEN_POLL_MS); } catch (error) { if (alive()) { + if (onBusy && error.code === 'busy') { void cancelJob(job); onBusy(); return; } forget(); if (resumed && (error.code === 'unknown_job' || error.code === 'reload')) { emit({running: false, job: null, fraction: 0, stage: '', waiting: ''}); @@ -654,6 +663,22 @@ export function createImageGenSession({client, prepare, apply, onChange = () => } timer = schedule(() => { timer = null; void poll(); }, IMAGE_GEN_POLL_MS); } + // The engine makes one picture at a time: a request that finds it busy waits its turn here and starts by itself. + // Stop (a new epoch) ends the wait. + // Ends a wait for the engine at once (Stop, closing): the waiting start() then returns instead of hanging. + const release = () => { const done = wake; wake = null; done?.(); }; + async function whenFree(submit, alive, resend = null) { + for (;;) { + try { return await submit(); } catch (error) { + if (error.code !== 'busy') throw error; + if (!alive()) return null; + emit({waiting: 'busy'}); + await new Promise(done => { wake = done; timer = schedule(() => { timer = null; wake = null; done(); }, IMAGE_GEN_BUSY_RETRY_MS); }); + if (!alive()) return null; + if (resend && !await resend()) return null; + } + } + } async function start(request) { if (state.running || disposed || !request.prompt.trim() || !state.info?.installed) return; const current = ++epoch; @@ -661,8 +686,16 @@ export function createImageGenSession({client, prepare, apply, onChange = () => emit({running: true, job: null, fraction: 0, stage: request.mode === 'edit' ? 'upload' : '', error: '', report_id: null, memory: '', waiting: '', fitted: null}); const alive = () => current === epoch && !disposed; let sent = [], submitted = false; + const gone = new Set(); // Every picture the page sends is noted as it arrives: a stop after one has gone up still removes it. - const uploaded = [], sender = {upload: async file => { const name = await client.upload(file); uploaded.push(name); return name; }}; + const uploaded = []; + // The service has not taken these pictures: they go (once each), whichever path ends the request. + const discard = () => { + const names = [...new Set([...uploaded, ...sent])].filter(name => !gone.has(name)); + for (const name of names) gone.add(name); + if (names.length) Promise.resolve().then(() => client.discardUploads?.(names)).catch(() => {}); + }; + const sender = {upload: async file => { const name = await client.upload(file); uploaded.push(name); return name; }}; try { const {context, images = [], mask} = await prepare(request, alive, sender); sent = [...images, ...(mask ? [mask] : [])]; @@ -675,34 +708,68 @@ export function createImageGenSession({client, prepare, apply, onChange = () => ...(request.seed === undefined ? {} : {seed: request.seed}), ...(request.loras === undefined ? {} : {loras: request.loras}), ...(tasks?.purpose ? {purpose: tasks.purpose} : {})}; - if (tasks) { - tasks.startJobSources?.(); - const {id} = await tasks.jobs.submit('image', request_, {view: tasks.view || 'image-editor', - meta: {...(tasks.meta?.(request, context) || {}), text: request.text ?? request.prompt, withImages, width: context.width, height: context.height}, - ...(tasks.client ? {client: tasks.client} : {})}); - submitted = true; + // The engine can turn a request away as busy at submit or while following it: wait and send it again. + // A turned-away request has its uploaded pictures removed by the service, so they are sent again before each retry. + const resend = async () => { + if (!sent.length) return true; + const next = await prepare(request, alive, sender); + if (!alive()) return false; + request_.images = next.images || []; request_.mask = next.mask; + sent = [...request_.images, ...(request_.mask ? [request_.mask] : [])]; + return true; + }; + const again = () => { if (!alive()) return; - emit({job: id}); - try { store?.save({job: id, context, withImages, task: true}); } catch { /* the job is only not picked up again here */ } - follow(current, id, context); - return; - } - const row = await client.generate(request_); - const {job} = row; - if (!job) throw failure(row.error, row.error ? row : {...row, step: 'submit'}); - submitted = true; - if (row.fitted) emit({fitted: row.fitted}); - if (!alive()) { await cancelJob(job); return; } - emit({job}); - try { store?.save({job, context, withImages}); } catch { /* the job is only not resumed after a reload */ } - track(current, job, context, withImages); + emit({job: null, waiting: 'busy'}); + timer = schedule(() => { timer = null; if (alive()) void go(true); }, IMAGE_GEN_BUSY_RETRY_MS); + }; + const go = async (retry = false) => { + // The pictures of this attempt are the page's until the service takes the request: a stop or an error + // before that, on a first send or a resend alike, removes them. + let taken = false; + try { + if (retry && !await resend()) return; + if (tasks) { + tasks.startJobSources?.(); + const sent_ = await whenFree(() => tasks.jobs.submit('image', request_, {view: tasks.view || 'image-editor', + meta: {...(tasks.meta?.(request, context) || {}), text: request.text ?? request.prompt, withImages, width: context.width, height: context.height}, + ...(tasks.client ? {client: tasks.client} : {})}), alive, resend); + if (!sent_) return; + const {id} = sent_; + submitted = taken = true; + if (!alive()) return; + emit({job: id, waiting: ''}); + try { store?.save({job: id, context, withImages, task: true}); } catch { /* the job is only not picked up again here */ } + follow(current, id, context, again); + return; + } + const row = await whenFree(async () => { + const answer = await client.generate(request_); + if (!answer.job) throw failure(answer.error, answer.error ? answer : {...answer, step: 'submit'}); + return answer; + }, alive, resend); + if (!row) return; + const {job} = row; + submitted = taken = true; + emit({waiting: ''}); + if (row.fitted) emit({fitted: row.fitted}); + if (!alive()) { await cancelJob(job); return; } + emit({job}); + try { store?.save({job, context, withImages}); } catch { /* the job is only not resumed after a reload */ } + track(current, job, context, withImages, false, again); + } catch (error) { + if (alive()) emit({running: false, job: null, ...failed(error)}); + } finally { + if (!taken) discard(); + } + }; + await go(); } catch (error) { if (alive()) emit({running: false, job: null, ...failed(error)}); } finally { // Stopped, turned away or failed before the service took the request: its pictures go now (a job removes // its own when it ends). - const names = [...new Set([...uploaded, ...sent])]; - if (!submitted && names.length) Promise.resolve().then(() => client.discardUploads?.(names)).catch(() => {}); + if (!submitted) discard(); } } // The page was reloaded while a picture was being made: follow the same job and place its result. @@ -726,11 +793,11 @@ export function createImageGenSession({client, prepare, apply, onChange = () => if (tasks) { const id = state.job; if (!state.running) return Promise.resolve(); - if (!id) { ++epoch; forget(); emit({running: false, job: null, stage: '', fraction: 0, waiting: '', stopping: false}); return Promise.resolve(); } + if (!id) { ++epoch; release(); forget(); emit({running: false, job: null, stage: '', fraction: 0, waiting: '', stopping: false}); return Promise.resolve(); } emit({stopping: true}); return Promise.resolve(tasks.jobs.cancel(id)).catch(() => { emit({stopping: false}); }); } - ++epoch; unschedule(timer); timer = null; + ++epoch; unschedule(timer); timer = null; release(); const job = state.job; forget(); emit({running: false, job: null, stage: '', fraction: 0, error: '', report_id: null, memory: '', waiting: '', fitted: null}); @@ -745,7 +812,7 @@ export function createImageGenSession({client, prepare, apply, onChange = () => return {check, start, resume, cancel, pack, clearError: () => emit({error: '', report_id: null, memory: ''}), state: () => state, // Closing the editor only stops watching: the picture keeps going on the engine, and the job record stays so // opening the same picture again picks it up (resume). Only Stop cancels. - dispose() { disposed = true; unschedule(infoTimer); infoTimer = null; ++epoch; unschedule(timer); timer = null; unwatch?.(); unwatch = null; return Promise.resolve(); }}; + dispose() { disposed = true; unschedule(infoTimer); infoTimer = null; ++epoch; unschedule(timer); timer = null; release(); unwatch?.(); unwatch = null; return Promise.resolve(); }}; } // The job being made, kept for this tab only so that a reloaded page can follow it and place the @@ -986,6 +1053,8 @@ export function createImageGeneration({client, renderer, t, getDoc, getSelection } note.hidden = !note.textContent; bar.dataset.running = String(state.running); + // A queue note is a sentence, not a progress figure: it may wrap (image_editor.css). + bar.dataset.waiting = String(!!(state.running && state.waiting) && !pack && !missing && !promptRequired); bar.dataset.message = String(!!missing || promptRequired || !!state.error || !!note.textContent); bar.dataset.failed = String(!!state.error && !promptRequired); bar.dataset.pack = String(!!pack && !pack.reason && !state.error); diff --git a/web/image_lora.js b/web/image_lora.js index e40a0d29..02b4a0ec 100644 --- a/web/image_lora.js +++ b/web/image_lora.js @@ -4,6 +4,7 @@ import {reconcileLoraTriggers} from './lora_triggers.js'; import {createVerdicts} from './lora_check.js'; import {skinSelect} from './fv_select.js'; +import {userMessage} from './user_message.js'; export const IMAGE_LORA_LIMIT = 8, IMAGE_LORA_STRENGTH = 2; const STORE = 'freevideo_image_loras'; @@ -133,7 +134,7 @@ export function createImageLoras({t, fetchApi, el = domEl, getPrompt = () => '', const name = row.name, draft = trigger.value; drafts.set(name, draft); try { await saveWords(name, draft); drafts.delete(name); note.textContent = ''; syncPrompt(); save(); onChange(); } - catch (error) { note.textContent = error.message; } + 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); @@ -142,7 +143,7 @@ export function createImageLoras({t, fetchApi, el = domEl, getPrompt = () => '', triggerWords(row.name).then(() => { if (!disposed && trigger.isConnected && !drafts.has(row.name)) trigger.value = words.get(row.name) ?? ''; syncPrompt(); save(); drawSummary(); onChange(); - }, error => { note.textContent = error.message; }); + }, error => { note.textContent = userMessage(error, t, t('Could not read the trigger words. Try again.', '没能读取触发词,请重试。')); }); }); add.disabled = rows.length >= IMAGE_LORA_LIMIT; if (!note.textContent || !rows.some(r => drafts.has(r.name))) note.textContent = skipped diff --git a/web/issue_button.js b/web/issue_button.js index abbb72f7..48066053 100644 --- a/web/issue_button.js +++ b/web/issue_button.js @@ -30,6 +30,17 @@ let modules = null; const load = () => modules || (modules = Promise.all([import('./feedback.js'), import('./updates.js')]) .then(([feedback, updates]) => ({feedback, updates})).catch(() => null)); +// Opens the prefilled form for `value` ({where, message, kind, facts}); also used by a notice's "Report a problem". +export async function openIssue(t, value, open = (url, features) => globalThis.open?.(url, '_blank', features)) { + const ready = await load(); + const draft = issueDraft(value, t); + // Modules that did not load still leave the blank form reachable. + if (!ready) return open(`${ISSUE_FORM}?${new URLSearchParams({template: 'feedback.yml', title: draft.title, feedback: draft.text})}`, 'noopener'); + open(ready.feedback.feedbackIssueURL(draft.text, ready.updates.productVersion(), draft.summary, draft.title), 'noopener'); +} +// Starts loading the form's modules ahead of a click. +export const preloadIssue = () => { load(); }; + function icon() { const svg = document.createElementNS('http://www.w3.org/2000/svg', 'svg'); svg.setAttribute('viewBox', '0 0 16 16'); svg.setAttribute('aria-hidden', 'true'); svg.setAttribute('focusable', 'false'); @@ -72,11 +83,7 @@ export function issueButton(t, source, {className = '', route = null, open = (ur showReportTip(button.parentElement, button, t, {mode: 'downloaded', submit: () => reportIssue(route.fetch, route.version(), {save: false})}); return; } - const ready = await load(); - const draft = issueDraft(value, t); - // Modules that did not load still leave the blank form reachable. - if (!ready) return open(`${ISSUE_FORM}?${new URLSearchParams({template: 'feedback.yml', title: draft.title, feedback: draft.text})}`, 'noopener'); - open(ready.feedback.feedbackIssueURL(draft.text, ready.updates.productVersion(), draft.summary, draft.title), 'noopener'); + await openIssue(t, value, open); }; return button; } diff --git a/web/lan_access.js b/web/lan_access.js index 5d44a80f..e4172d83 100644 --- a/web/lan_access.js +++ b/web/lan_access.js @@ -3,6 +3,7 @@ import {agentGet, agentPost} from './agent_session.js'; import {qrcodegen} from './qrcodegen.js'; import {listenDialogKey} from './dialog_keys.js'; import { skin } from './glass/library.js'; +import {userMessage} from './user_message.js'; const css = document.createElement('link'); css.rel = 'stylesheet'; css.href = new URL('./lan_access.css', import.meta.url).href; document.head.append(css); const seenKey = 'freevideo.phone.opened'; export function qrMatrix(link) { return qrcodegen.QrCode.encodeText(link, qrcodegen.QrCode.Ecc.MEDIUM); } @@ -29,7 +30,7 @@ export function createLanAccess(t, api) { if (navigator.clipboard?.writeText) await navigator.clipboard.writeText(state.link); else { const area = el('textarea'); area.value = state.link; panel.append(area); area.select(); const ok = document.execCommand('copy'); area.remove(); if (!ok) throw new Error(); } copy.textContent = t('Copied', '已复制'); clearTimeout(copied); copied = setTimeout(() => { copy.textContent = t('Copy link', '复制链接'); }, 1500); - } catch { fail(); } + } catch { fail(t('Could not copy the link. Try again.', '没能复制链接,请重试。')); } }); const passwordRow = el('div', 'fv-lan-password'), passwordState = el('span'), set = button('fv-lan-set', t('Set', '设置'), () => { form.hidden = false; password.focus(); }); passwordRow.append(passwordState, set); @@ -58,7 +59,8 @@ export function createLanAccess(t, api) { let state = {enabled: false, link: '', password_set: false}, seen = false, disposed = false, writing = false, desired = null, reading = false, timer = null, copied = null, drawn = '', since = 0; try { seen = localStorage.getItem(seenKey) === '1'; } catch {} const windows = /Win/i.test(globalThis.navigator?.platform || globalThis.navigator?.userAgent || ''); - function fail() { error.hidden = false; } + // The panel's one error line: why the last step failed (a lost connection, or FreeVideo's HTTP status). + function fail(text) { error.textContent = text; error.hidden = false; } // A toolbar with a transform or blur becomes the frame of fixed children; take its offset back out so they sit by the button. function place(node, top, left) { node.style.right = ''; node.style.top = `${top}px`; node.style.left = `${left}px`; @@ -67,8 +69,9 @@ export function createLanAccess(t, api) { } function position() { if (panel.hidden) return; - const box = trigger.getBoundingClientRect(); - place(panel, box.bottom + 8, Math.max(8, Math.min(box.right - 264, window.innerWidth - 272))); + // The panel's own width: the glass layer sets it (web/glass/library.css), so the right edge meets the entry's. + const box = trigger.getBoundingClientRect(), width = panel.offsetWidth; + place(panel, box.bottom + 8, Math.max(8, Math.min(box.right - width, window.innerWidth - 8 - width))); } function render() { // No launcher installation: the switch cannot work from this page, so say why instead of "Please try again". @@ -86,17 +89,17 @@ export function createLanAccess(t, api) { } else if (pending) starting.textContent = t('Opening…', '正在打开…'); passwordState.textContent = state.password_set ? t('Password: on', '密码:已设置') : t('Password: not set', '密码:未设置'); set.textContent = state.password_set ? t('Change', '修改') : t('Set', '设置'); - if (!content.hidden && state.link !== drawn) { try { drawQr(qr, state.link); drawn = state.link; } catch { fail(); } } + if (!content.hidden && state.link !== drawn) { try { drawQr(qr, state.link); drawn = state.link; } catch { fail(t('Could not show the QR code. Use Copy link.', '没能显示二维码,请用“复制链接”。')); } } position(); } async function read() { clearTimeout(timer); if (disposed || panel.hidden || reading) return; reading = true; try { const response = await agentGet(api, '/freevideo/lan', {signal: AbortSignal.timeout(10000)}); - if (!response.ok) throw new Error(); const value = await response.json(); if (disposed || writing) return; + if (!response.ok) throw Object.assign(new Error(), {status: response.status}); const value = await response.json(); if (disposed || writing) return; state = value; if (state.reason || desired === state.enabled && (!desired || state.link)) desired = null; error.hidden = true; render(); - } catch { if (!disposed) fail(); } + } catch (failure) { if (!disposed) fail(userMessage(failure?.name === 'TimeoutError' ? new TypeError('Failed to fetch') : failure, t, t('Could not read the phone access status. Try again.', '没能读取手机连接状态,请重试。'))); } finally { reading = false; if (!disposed && !panel.hidden) timer = setTimeout(read, document.hidden ? 10000 : 2000); } } trigger.onpointerenter = trigger.onfocus = () => { if (!panel.hidden) return; const box = trigger.getBoundingClientRect(); tip.hidden = false; place(tip, box.bottom + 8, Math.max(8, Math.min(box.right, window.innerWidth - 8) - tip.offsetWidth)); }; @@ -115,10 +118,10 @@ export function createLanAccess(t, api) { try { const response = await agentPost(api, '/freevideo/lan', body); if (response.status === 409 && (await response.json().catch(() => null))?.error?.code === 'lan_unavailable') { if (!disposed) state = {...state, available: false}; return false; } - if (!response.ok) throw new Error(); + if (!response.ok) throw Object.assign(new Error(), {status: response.status}); const value = await response.json(); if (disposed) return false; if (typeof value.enabled === 'boolean') state = {...state, ...value}; return true; - } catch { if (!disposed) fail(); return false; } + } catch (failure) { if (!disposed) fail(userMessage(failure, t, t('Could not change phone access. Try again.', '没能更改手机连接设置,请重试。'))); return false; } finally { writing = false; if (!disposed) render(); } } async function changeEnabled() { await open(!(state.enabled || state.starting)); } diff --git a/web/library.css b/web/library.css index 1e802a80..60b8c210 100644 --- a/web/library.css +++ b/web/library.css @@ -157,8 +157,8 @@ dialog.fv-studio.fv-library::backdrop{background:var(--lib-page)} .fv-library .fv-library-dock{position:sticky;bottom:var(--fv-sp-16,16px);z-index:5;display:flex;flex-direction:column;align-items:center;gap:var(--fv-sp-8,8px);margin:var(--fv-sp-16,16px) 0 0;pointer-events:none} .fv-library .fv-library-dock:not([data-hx-kids]){display:none} .fv-library .fv-library-dock>*{pointer-events:auto} -.fv-library :is(.fv-library-selection,.fv-library-undo){background:rgb(var(--fv-tint) / var(--fv-a2));-webkit-backdrop-filter:blur(var(--fv-glass-blur2,30px)) saturate(165%); - backdrop-filter:blur(var(--fv-glass-blur2,30px)) saturate(165%);border:1px solid var(--fv-edge);box-shadow:inset 0 1px 0 var(--fv-edge-hi),var(--fv-sh2)} +.fv-library :is(.fv-library-selection,.fv-library-undo){background:rgb(var(--fv-solid2));-webkit-backdrop-filter:none; + backdrop-filter:none;border:1px solid var(--fv-edge);box-shadow:inset 0 1px 0 var(--fv-edge-hi),var(--fv-sh2)} .fv-library .fv-library-selection{display:flex;align-items:center;gap:var(--fv-sp-12,12px);width:min(100%,720px);min-height:56px;margin:0;padding:var(--fv-sp-8,8px) var(--fv-sp-8,8px) var(--fv-sp-8,8px) var(--fv-sp-16,16px); border-radius:var(--fv-r-lg);text-align:left} .fv-library .fv-library-selection[hidden],.fv-library .fv-library-undo[hidden]{display:none} diff --git a/web/library.js b/web/library.js index 3a50e363..ff4db786 100644 --- a/web/library.js +++ b/web/library.js @@ -6,6 +6,8 @@ import { savedSettings } from './result_reuse.js'; import { listenDialogKey } from './dialog_keys.js'; import { isNetworkTypeError, connectionLostText } from './browser_extension.js'; import { issueButton } from './issue_button.js'; +import { fileFailureText, responseFileReason } from './file_failure.js'; +import { userMessage } from './user_message.js'; import { applyTasks, toggledTask } from './task_groups.js'; import { outputDownloadURL } from './output_download.js'; import { attachContextMenu, openContextMenu, contextMenuOpen, compatView, reducedMotion } from './context_menu.js'; @@ -15,6 +17,8 @@ import { createMetaStore, promptOfRow } from './image_view_history.js'; import { attach as attachPlayerBar } from './glass/player_bar.js'; import { hasPictureThumbnail, mediaQueue, pictureThumbnailURL, watchCards } from './work_media.js'; import { zoomable } from './picture_zoom.js'; +import { createUpscaleOffer, upscale4kOffer } from './upscale_offer.js'; +import { capabilityPoints } from './chain_support.js'; const style = document.createElement('link'); style.rel = 'stylesheet'; style.href = new URL('./library.css', import.meta.url).href; document.head.append(style); @@ -388,21 +392,37 @@ function libraryHost() { // (a notification, the palette, search, a chat or autopilot job) carries none, so the studio registers its own as the default. let defaultUpscale = null; export function setDefaultUpscale(run) { defaultUpscale = typeof run === 'function' ? run : null; } +// ``upscaleWork`` makes a larger copy of a finished video; registered by the studio like the second pass. +let defaultUpscaleWork = null; +export function setDefaultUpscaleWork(run) { defaultUpscaleWork = typeof run === 'function' ? run : null; } +// The longest single request at a size, as the planner admits it now; null when it cannot be told. +async function admittedFrames(width, height) { + for (let tries = 0; tries < 5; tries++) { + const response = await api.fetchApi('/freevideo/capabilities?' + new URLSearchParams({width, height})); + if (!response.ok) return null; + const reply = await response.json(); + if (reply?.status === 'computing') { await new Promise(done => setTimeout(done, 1000)); continue; } + return reply && (!reply.status || reply.status === 'ready') ? capabilityPoints(reply, {width, height}).maxRequestFrames : null; + } + return null; +} // ``reuse`` is the creation panel's {now, apply}: given, Reuse settings fills that panel from a creation. export function openLibrary(t, options = {}) { if (parked?.dialog.isConnected !== false && parked && !parked.dialog.open) return parked.reopen(options); if (parked?.dialog.open) { parked.reopen(options); return; } let {upscale = null, selectedWork = null, extend = null, reuse = null, back: backLabel = null} = options; const secondPassRunner = () => upscale || defaultUpscale; + const upscaleOffer = createUpscaleOffer(admittedFrames); const dialog = el('dialog', null, 'fv-studio fv-library'); opened = dialog; let host = libraryHost(); const hostClosed = () => { if (dialog.open) dialog.close(); }; // Closing gives the keyboard back to the control that opened the room. const opener = document.activeElement instanceof HTMLElement && document.activeElement !== document.body ? document.activeElement : null; // `kind` (text, or a function read when the button is clicked) tells the feedback what the sentence alone cannot. - const fault = (target, text, where = ['Creations', '作品库'], kind = null) => { + // `error`, when given, is what the report sends instead of the plain sentence shown. + const fault = (target, text, where = ['Creations', '作品库'], kind = null, error = null) => { target.textContent = text; - target.append(issueButton(t, () => ({where, message: text, kind: typeof kind === 'function' ? kind() : kind}))); + target.append(issueButton(t, () => ({where, message: error?.message || text, kind: typeof kind === 'function' ? kind() : kind}))); }; dialog.setAttribute('aria-label', t('Creations', '作品库')); const header = el('header', null, 'fv-library-header'); @@ -906,7 +926,7 @@ export function openLibrary(t, options = {}) { if (editor && !disposed) { dialog.close(); editor.element?.focus({preventScroll: true}); } return editor; } - catch (error) { fault(notice, error.message, ['Continue video', '延长视频']); } + catch (error) { fault(notice, userMessage(error, t, t('Could not open the editor. Try again.', '无法打开剪辑,请重试。')), ['Continue video', '延长视频'], null, error); } } // Fill the creation panel with a video's prompt, size, length and seed, then go back to it. async function reuseSaved(row) { @@ -958,7 +978,7 @@ export function openLibrary(t, options = {}) { await secondPassRunner()(row); if (!disposed && selected === workKey(row)) notice.textContent = t('Queued. It appears in "Creations" when done.', '已加入队列,完成后在“作品”里。'); } catch (error) { - if (!disposed && selected === workKey(row)) fault(notice, t('Could not start the second pass: ', '无法继续二采:') + error.message, ['Second pass', '二采']); + if (!disposed && selected === workKey(row)) fault(notice, userMessage(error, t, t('Could not start the second pass. Try again.', '没能开始二采,请重试。')), ['Second pass', '二采'], null, error); throw error; } } @@ -976,8 +996,8 @@ export function openLibrary(t, options = {}) { const result = await removeKeys([key]); if (result.removed.has(key)) { notice.textContent = ''; return; } const skipped = result.skipped.find(item => item.id === row.id); - throw Object.assign(new Error(skipped ? refusal(skipped.reason, skipped.kept || []) : t('Could not delete this creation.', '无法删除这条作品。')), { - reportable: !skipped || !['foreign-files', 'editor-in-use', 'continuation-in-use', 'in-use'].includes(skipped.reason), + throw Object.assign(new Error(skipped ? refusal(skipped.reason, skipped.kept || []) : result.why || t('Could not delete this creation.', '无法删除这条作品。')), { + reportable: skipped ? !['foreign-files', 'editor-in-use', 'continuation-in-use', 'in-use'].includes(skipped.reason) : !result.why, }); } // --- Selecting several creations --- @@ -1430,6 +1450,17 @@ export function openLibrary(t, options = {}) { use: ['Finish the full-resolution video', '从预览继续生成全分辨率视频'], disabled: secondPassRunner() ? '' : ['Open the create view first, then run the second pass', '请先打开创作页,再继续二采'], run: () => secondPass(one).then(() => say(t('Queued. It appears in "Creations" when done.', '已加入队列,完成后在“作品”里。')), error => say(t('Could not start the second pass: ', '无法继续二采:') + error.message, true))}); + // One 1.5× step where this computer can generate it (gap-04a), and the 4K size by a small model (gap-04b): + // each shown on its own, the same way. + for (const [id, larger, options] of [['upscale', defaultUpscaleWork && upscaleOffer.offer(one), {}], + ['upscale-4k', defaultUpscaleWork && upscale4kOffer(one), {to: '4k'}]]) { + if (!larger) continue; + const size = `${larger.width} × ${larger.height}`; + items.push({id, icon: 'upscale', label: [`Upscale to ${size}`, `放大到 ${size}`], + use: ['Make a larger copy as a new creation', '生成一个更大的新作品,原作品不变'], + run: () => defaultUpscaleWork(one, options).then(() => say(t('Queued. It appears in "Creations" when done.', '已加入队列,完成后在“作品”里。')), + error => say(t('Could not start upscaling: ', '无法开始放大:') + error.message, true))}); + } items.push({id: 'reuse', icon: 'reuse', label: ['Reuse settings', '复用设置'], disabled: one.preview ? ['A first-pass preview: finish it first', '这是一采预览,先继续二采'] : '', run: () => reuseSaved(one)}); @@ -1798,8 +1829,8 @@ export function openLibrary(t, options = {}) { // A held picture stays known (the shelf hides it while held), so Undo puts its card straight back; it leaves for // good only when the engine has deleted it (freevideo-pictures-deleted). const skipped = []; - let failed = false, unsaved = false; - if (!videoKeys.length) return {removed, skipped, failed}; + let failed = false, unsaved = false, why = ''; + if (!videoKeys.length) return {removed, skipped, failed, why}; const idOf = new Map(videoKeys.map(key => [key, works.get(key)?.id])), ids = videoKeys.map(key => idOf.get(key)).filter(Boolean); // Windows keeps a streamed video open; release it before deleting. const selectedRow = works.get(selected); @@ -1835,7 +1866,7 @@ export function openLibrary(t, options = {}) { // or a lost connection may still have been carried out, so the batch is looked up again. const response = await api.fetchApi('/freevideo/library/delete-batch', {method: 'POST', headers: jsonHeaders, body: JSON.stringify({ids: part, batch: name, extend: earlier})}); - if (!response.ok) { forgetUndo([name]); throw new Error('failed'); } + if (!response.ok) { why = fileFailureText(await responseFileReason(response), t); forgetUndo([name]); throw new Error('failed'); } const value = await response.json(); const gone = new Set(value.deleted || []); // A creation that is already gone from disk only needs to leave the page. @@ -1865,12 +1896,12 @@ export function openLibrary(t, options = {}) { if (selected && !works.has(selected)) clearDetail(); else if (selectedRow && works.has(selected) && !player && selectedRow.kind !== 'image') mountPlayer(selectedRow); } - return {removed, skipped, failed}; + return {removed, skipped, failed, why}; } async function removeSelected() { deleting = true; syncSelection(); const keys = [...picked]; - const {removed, skipped, failed} = await removeKeys(keys); + const {removed, skipped, failed, why} = await removeKeys(keys); deleting = false; if (disposed) return; const kept = new Set(skipped.map(row => row.id)); @@ -1882,7 +1913,7 @@ export function openLibrary(t, options = {}) { confirming = false; undoFailure = removed.size ? t(`${picked.size} could not be deleted. Try again.`, `还有 ${picked.size} 个没能删除,请重试。`) - : t('Could not delete. Try again.', '没能删除,请重试。'); + : why || t('Could not delete. Try again.', '没能删除,请重试。'); if (!picked.size) setSelecting(false); } else { undoFailure = ''; setSelecting(false); } render(); @@ -2029,7 +2060,7 @@ export function openLibrary(t, options = {}) { if (appendPage) tailState = 'failed'; else if (error.restart) message.textContent = error.message; else { - fault(message, isNetworkTypeError(error) ? connectionLostText(t) : error.message); retryRead(message); + fault(message, userMessage(error, t, t('Could not read the creations. Try again.', '没能读取作品,请重试。')), undefined, null, error); retryRead(message); for (const ghost of grid.querySelectorAll(':scope > .fv-library-ghost')) ghost.remove(); } } @@ -2042,6 +2073,8 @@ export function openLibrary(t, options = {}) { if (ok && !disposed && round === loadRound) { if (selected && works.has(selected)) select(selected, false); render(); + if (!appendPage) upscaleOffer.forget(); + void upscaleOffer.prepare(works.values()); if (!appendPage) { gatherIfNeeded(); if (filter.favorites) void gatherFavorites(); } if (filter.query) fetchPrompts(); } @@ -2147,7 +2180,7 @@ export function openLibrary(t, options = {}) { function viewerMenu(row, key, anchorNode) { const outside = new Set(['open', 'select', 'download', 'reuse', 'extend', 'use-prompt', 'image-view']); const items = (cardMenuItems(anchorNode, [key], null) || []).filter(item => typeof item === 'string' || !outside.has(item.id)); - const extra = [{id: 'info', icon: 'alert', label: infoOpen ? ['Hide info', '收起信息'] : ['Info', '信息'], use: ['Prompt and run details', '提示词和运行详情'], key: 'I', run: () => toggleInfo()}]; + const extra = [{id: 'info', icon: 'info', label: infoOpen ? ['Hide info', '收起信息'] : ['Info', '信息'], use: ['Prompt and run details', '提示词和运行详情'], key: 'I', run: () => toggleInfo()}]; if (row.kind !== 'image') { const share = links.querySelector('.fv-share-trigger'), copy = links.querySelector('.fv-action-copy'); if (share) extra.unshift({id: 'share', icon: 'globe', label: ['Share', '分享'], use: ['Make a picture or clip to share', '生成可分享的图片或短片'], run: () => share.click()}); diff --git a/web/middle_frames.js b/web/middle_frames.js index 09f665f2..9a9a0af8 100644 --- a/web/middle_frames.js +++ b/web/middle_frames.js @@ -69,7 +69,6 @@ export function middleNotice(rows, {first, last, references, seconds}, t) { if (!middle.length) return ''; if (middle.length > MAX_MIDDLE) return labels.tooMany(t); if (!first || !last) return labels.needsBoth(t); - if (references) return ''; const problem = timeProblems(middle.map(secondsOf), seconds)[0]; return problem ? problemText(problem, seconds, t) : ''; } diff --git a/web/monitor_panel.css b/web/monitor_panel.css deleted file mode 100644 index 3089cb12..00000000 --- a/web/monitor_panel.css +++ /dev/null @@ -1,38 +0,0 @@ -.fv-monitor{position:relative;display:inline-flex;flex:none;font-size:var(--fv-body);color:var(--fv-ink)}.fv-monitor[hidden]{display:none} -.fv-monitor button{font:inherit;cursor:pointer;color:inherit;border:0;touch-action:manipulation}.fv-monitor button:disabled{opacity:.45;cursor:default} -.fv-monitor .fv-monitor-trigger{display:inline-flex;align-items:center;gap:6px;height:32px;padding:0 10px 0 8px;border-radius:var(--fv-r-pill);background:var(--fv-raised);border:1px solid var(--fv-border);white-space:nowrap} -.fv-monitor-trigger:hover,.fv-monitor-trigger[aria-expanded=true]{background:var(--fv-hover)!important} -.fv-monitor svg{width:16px;height:16px;fill:none;stroke:var(--fv-muted);stroke-width:1.7;stroke-linecap:round;stroke-linejoin:round;display:block;flex:none} -.fv-monitor-text[hidden]{display:none}.fv-monitor .fv-monitor-warn{color:var(--fv-danger)} -.fv-monitor-panel{position:fixed;z-index:1000;box-sizing:border-box;width:280px;max-width:calc(100vw - 16px);padding:16px;background:var(--fv-card);border:1px solid var(--fv-border);border-radius:var(--fv-r-md);box-shadow:0 12px 36px #0006;text-align:left} -.fv-monitor-name{display:block;font-size:calc(var(--fv-body) + 1px);font-weight:var(--fv-semibold)}.fv-monitor-name[hidden]{display:none} -.fv-monitor-rows{display:flex;flex-direction:column;gap:12px;margin-top:12px}.fv-monitor-rows:empty{display:none} -.fv-monitor-line{display:flex;justify-content:space-between;gap:12px}.fv-monitor-title{color:var(--fv-muted)} -.fv-monitor-bar{height:4px;margin-top:6px;border-radius:var(--fv-r-pill);background:var(--fv-hover);overflow:hidden}.fv-monitor-bar i{display:block;height:100%;background:var(--fv-accent)}.fv-monitor-bar i.fv-monitor-warn{background:var(--fv-danger)} -.fv-monitor-stopped button{white-space:nowrap;flex:none}.fv-monitor-stopped{display:flex;align-items:center;justify-content:space-between;gap:8px;margin-top:14px;color:var(--fv-muted)}.fv-monitor-stopped[hidden]{display:none} -.fv-monitor .fv-monitor-resume{background:none;color:var(--fv-accent);height:32px;padding:0 4px} -.fv-monitor .fv-monitor-stop{display:block;width:100%;height:36px;margin-top:14px;border-radius:var(--fv-r-sm);background:transparent;border:1px solid var(--fv-danger);color:var(--fv-danger);font-weight:var(--fv-semibold)} -.fv-monitor .fv-monitor-stop:disabled{border-color:var(--fv-border);color:var(--fv-muted);opacity:1} -.fv-monitor .fv-monitor-stop.fv-monitor-confirm{background:var(--fv-danger);color:var(--fv-bg)} -.fv-monitor :focus-visible{outline:2px solid var(--fv-accent);outline-offset:2px} -@media(pointer:coarse){.fv-monitor .fv-monitor-trigger{height:44px}.fv-monitor-panel button{min-height:44px}} -/* Glass layer (the creative panel's tokens): the capsule keeps one width from the first frame (numbers in tabular figures, - a placeholder before the first reading), and the panel is a glass popover. */ -.fv-monitor .fv-monitor-trigger{gap:var(--fv-sp-8,8px);height:var(--fv-ctl,32px);padding:0 var(--fv-sp-12,12px) 0 var(--fv-sp-8,8px);border:1px solid var(--fv-edge,var(--fv-border));border-radius:var(--fv-rad-pill,99px); - background:rgb(var(--fv-tint,20 23 30) / var(--fv-a1,.54));color:var(--fv-fg2,var(--fv-ink));font-variant-numeric:tabular-nums;-webkit-backdrop-filter:blur(var(--fv-glass-blur1,22px));backdrop-filter:blur(var(--fv-glass-blur1,22px))} -.fv-monitor-text{display:inline-block;min-width:11.5em;text-align:left} -.fv-monitor-text[data-waiting=true]{color:var(--fv-fg3,var(--fv-muted))} -.fv-monitor-panel{width:288px;padding:var(--fv-sp-16,16px);border:1px solid var(--fv-edge,var(--fv-border));border-radius:var(--fv-rad-pop,18px);color:var(--fv-fg,var(--fv-ink)); - background:rgb(var(--fv-tint,20 23 30) / var(--fv-a3,.8));box-shadow:inset 0 1px 0 var(--fv-edge-hi,transparent),var(--fv-sh3,0 12px 36px #0006); - -webkit-backdrop-filter:blur(var(--fv-glass-blur3,40px)) saturate(175%);backdrop-filter:blur(var(--fv-glass-blur3,40px)) saturate(175%)} -.fv-monitor-name{font-size:var(--fv-fs-3,16px)} -.fv-monitor-title{color:var(--fv-fg3,var(--fv-muted));font-size:var(--fv-fs-2,13px)} -.fv-monitor-value{font-variant-numeric:tabular-nums;font-size:var(--fv-fs-2,13px)} -.fv-monitor-bar{background:var(--fv-ctl-bg,var(--fv-hover))}.fv-monitor-bar i{background:var(--fv-accent-fill,var(--fv-accent))} -.fv-monitor .fv-monitor-stop{height:var(--fv-ctl-l,40px);border-radius:var(--fv-rad-ctl,8px);border-color:transparent;background:var(--fv-warn-soft,transparent);color:var(--fv-warn,var(--fv-danger))} -.fv-monitor .fv-monitor-stop.fv-monitor-confirm{background:var(--fv-warn-fill,#c42f35);color:#fff} -.fv-monitor .fv-monitor-stop:disabled{background:var(--fv-ctl-bg,transparent);color:var(--fv-fg3,var(--fv-muted))} -:is(:root[data-glass=solid],:root.lite) :is(.fv-monitor .fv-monitor-trigger,.fv-monitor-panel){-webkit-backdrop-filter:none;backdrop-filter:none} -:is(:root[data-glass=solid],:root.lite) .fv-monitor .fv-monitor-trigger{background:rgb(var(--fv-solid1,24 27 34))} -:is(:root[data-glass=solid],:root.lite) .fv-monitor-panel{background:rgb(var(--fv-solid3,35 39 48))} -@media(prefers-reduced-transparency:reduce){:is(.fv-monitor .fv-monitor-trigger,.fv-monitor-panel){-webkit-backdrop-filter:none!important;backdrop-filter:none!important}.fv-monitor-panel{background:rgb(var(--fv-solid3,35 39 48))!important}} diff --git a/web/monitor_panel.js b/web/monitor_panel.js index 4fbee39c..f8026b6e 100644 --- a/web/monitor_panel.js +++ b/web/monitor_panel.js @@ -1,7 +1,7 @@ -const css = document.createElement('link'); css.rel = 'stylesheet'; css.href = new URL('./monitor_panel.css', import.meta.url).href; document.head.append(css); +// Whether this computer's figures show in the status (Settings › Appearance). The top bar reads the same key +// (topbar_state.js FIGURES_KEY) and draws the figures in its own status capsule; the old header capsule that this +// module also built is gone since the redesign, and with it its second reading of /freevideo/monitor. const shownKey = 'freevideo.monitor.shown', changed = 'freevideo-monitor-shown'; -const el = (tag, cls, text) => { const e = document.createElement(tag); if (cls) e.className = cls; if (text != null) e.textContent = text; return e; }; -const GIB = 2 ** 30, memoryLimit = 95, temperatureLimit = 85; export function monitorShown() { try { return localStorage.getItem(shownKey) === '1'; } catch { return false; } } export function setMonitorShown(value) { try { localStorage.setItem(shownKey, value ? '1' : '0'); } catch {} @@ -12,104 +12,3 @@ export function onMonitorShown(listener) { window.addEventListener(changed, listener); window.addEventListener('storage', storage); return () => { window.removeEventListener(changed, listener); window.removeEventListener('storage', storage); }; } -const gib = bytes => (bytes / GIB).toFixed(1); -const svg = d => { - const root = document.createElementNS('http://www.w3.org/2000/svg', 'svg'), path = document.createElementNS(root.namespaceURI, 'path'); - root.setAttribute('viewBox', '0 0 24 24'); root.setAttribute('aria-hidden', 'true'); path.setAttribute('d', d); root.append(path); return root; -}; -// The top-bar capsule and its panel. Nothing is read from the server while the setting is off. -export function createMonitor(t, api) { - const element = el('div', 'fv-monitor'), trigger = el('button', 'fv-monitor-trigger'), text = el('span', 'fv-monitor-text'), panel = el('section', 'fv-monitor-panel'); - const label = t('System status', '运行状态'); - trigger.type = 'button'; trigger.setAttribute('aria-label', label); trigger.setAttribute('aria-expanded', 'false'); trigger.setAttribute('aria-haspopup', 'dialog'); - trigger.append(svg('M3 12h4l3-8 4 16 3-8h4'), text); - trigger.dataset.fvTipName = label; trigger.dataset.fvTipUse = t('Graphics memory, heat, and what is running', '看显存、温度和正在跑的任务'); - panel.hidden = true; panel.setAttribute('role', 'dialog'); panel.setAttribute('aria-label', label); - const name = el('strong', 'fv-monitor-name'), rows = el('div', 'fv-monitor-rows'), stop = el('button', 'fv-monitor-stop', t('Stop now', '立即停止')); - stop.type = 'button'; - stop.dataset.fvTipName = t('Stop now', '立即停止'); stop.dataset.fvTipUse = t('Stop the running job; asks once more first', '停止正在运行的任务,会再确认一次'); - stop.dataset.fvTipWhy = t('Nothing is running', '现在没有任务在运行'); - const stopped = el('div', 'fv-monitor-stopped'), stoppedText = el('span', '', t('Stopped. The queue is paused.', '已停止,队列已暂停。')), resume = el('button', 'fv-monitor-resume', t('Resume queue', '继续队列')); - resume.type = 'button'; stopped.append(stoppedText, resume); stopped.hidden = true; - panel.append(name, rows, stopped, stop); element.append(trigger, panel); element.hidden = true; - let state = {}, timer = null, reading = false, disposed = false, confirming = null, active = false; - const row = (title, value, bar, warn) => { - const line = el('div', 'fv-monitor-row'), head = el('div', 'fv-monitor-line'); - const number = el('span', warn ? 'fv-monitor-value fv-monitor-warn' : 'fv-monitor-value', value); - head.append(el('span', 'fv-monitor-title', title), number); line.append(head); - if (bar != null) { const track = el('div', 'fv-monitor-bar'), fill = el('i'); fill.style.width = `${Math.min(100, bar)}%`; if (warn) fill.className = 'fv-monitor-warn'; track.append(fill); line.append(track); } - return line; - }; - const percent = value => state.memory_total ? Math.round(100 * state.memory_used / state.memory_total) : null; - function render() { - const memory = state.memory_total ? percent() : null, hot = state.temperature >= temperatureLimit, full = memory != null && memory >= memoryLimit; - text.replaceChildren(); - const parts = []; - const waiting = !state.memory_total && state.temperature == null && !state.read; - if (waiting) parts.push([`${t('VRAM', '显存')} `, '—', false], ['', '— °C', false]); - if (memory != null) parts.push([`${t('VRAM', '显存')} `, `${memory}%`, full]); - if (state.temperature != null) parts.push(['', `${state.temperature} °C`, hot]); - text.dataset.waiting = String(waiting); - parts.forEach(([label, value, warn], index) => { - if (index) text.append(document.createTextNode(' · ')); - if (label) text.append(document.createTextNode(label)); - text.append(el('span', warn ? 'fv-monitor-warn' : '', value)); - }); - text.hidden = !parts.length; - name.textContent = state.name || ''; name.hidden = !state.name; - const list = []; - if (memory != null) list.push(row(t('VRAM', '显存'), `${gib(state.memory_used)} / ${gib(state.memory_total)} GiB`, memory, full)); - if (state.utilization != null) list.push(row(t('Utilization', '使用率'), `${state.utilization}%`)); - if (state.temperature != null) list.push(row(t('Temperature', '温度'), `${state.temperature} °C`, null, hot)); - if (state.disk_free != null) list.push(row(t('Disk', '硬盘'), t(`${gib(state.disk_free)} GiB free`, `剩余 ${gib(state.disk_free)} GiB`))); - rows.replaceChildren(...list); - stopped.hidden = !state.paused; - stop.disabled = !state.busy; - if (!confirming) stop.textContent = t('Stop now', '立即停止'); - } - async function read() { - clearTimeout(timer); - if (disposed || !active || reading) return; - reading = true; - try { - const response = await api.fetchApi('/freevideo/monitor', {signal: AbortSignal.timeout(10000)}); - if (response.ok && !disposed && active) { state = {...await response.json(), read: true}; render(); } - } catch {} - finally { reading = false; if (!disposed && active) timer = setTimeout(read, document.hidden ? 10000 : 2000); } - } - function position() { - if (panel.hidden) return; - const box = trigger.getBoundingClientRect(); panel.style.top = `${box.bottom + 8}px`; - panel.style.left = `${Math.max(8, Math.min(box.left, window.innerWidth - 288))}px`; - } - function revert() { clearTimeout(confirming); confirming = null; stop.classList.remove('fv-monitor-confirm'); stop.textContent = t('Stop now', '立即停止'); } - function close() { panel.hidden = true; trigger.setAttribute('aria-expanded', 'false'); revert(); } - trigger.onclick = () => { if (panel.hidden) { panel.hidden = false; trigger.setAttribute('aria-expanded', 'true'); position(); } else close(); }; - stop.onclick = async () => { - if (stop.disabled) return; - if (!confirming) { - stop.classList.add('fv-monitor-confirm'); stop.textContent = t('Confirm stop', '确认停止'); - confirming = setTimeout(revert, 4000); return; - } - revert(); stop.disabled = true; - try { await api.fetchApi('/freevideo/monitor/stop', {method: 'POST'}); } catch {} - state = {...state, paused: true, busy: false}; render(); read(); - }; - resume.onclick = async () => { - resume.disabled = true; - try { await api.fetchApi('/freevideo/monitor/resume', {method: 'POST'}); state = {...state, paused: false}; } catch {} - resume.disabled = false; render(); read(); - }; - const outside = event => { if (!element.contains(event.target)) close(); }; - // Escape reaches the panel only through the dialog's cancel: the studio routes its keys itself. - const dismiss = () => { if (panel.hidden) return false; close(); trigger.focus(); return true; }; - document.addEventListener('pointerdown', outside, true); window.addEventListener('resize', position); - function apply() { - const wanted = monitorShown(); - if (wanted === active) return; - active = wanted; element.hidden = !wanted; - if (wanted) { render(); read(); } else { clearTimeout(timer); close(); state = {}; } - } - const stopWatching = onMonitorShown(apply); apply(); - return {element, dismiss, dispose() { disposed = true; active = false; clearTimeout(timer); revert(); stopWatching(); document.removeEventListener('pointerdown', outside, true); window.removeEventListener('resize', position); }}; -} diff --git a/web/palette.js b/web/palette.js index c47beb6a..a86157c7 100644 --- a/web/palette.js +++ b/web/palette.js @@ -13,6 +13,8 @@ import { openShortcuts, shortcutsOpen, closeShortcuts, VIEW_NAMES } from './shor import { searchEverything, searchSettled, warmSearch, fillPrompt } from './global_search.js'; import { openNotifications, latestFinished, toast, visitJob, openWork } from './notifications.js'; import { jobs } from './task_store.js'; +import { userMessage } from './user_message.js'; +import { openIssue, preloadIssue } from './issue_button.js'; const browser = typeof document !== 'undefined'; addSheet('palette.css', import.meta.url); @@ -588,9 +590,22 @@ function execute(command) { // The palette is gone and focus is back where it was before the action runs. queueMicrotask(async () => { try { await command.run({view: currentView(), source: 'palette'}); } - catch (error) { console.warn('FreeVideo command:', error); toast(t('Could not complete. Try again.', '没有完成,请重试。'), {tone: 'warn'}); } + catch (error) { console.warn('FreeVideo command:', error); commandFailed(command, error); } }); } +// A known cause (offline, an extension, FreeVideo's own sentence) is the whole notice. An unknown one or a server +// error names the command and offers a report that carries the raw error and the command id. +export function commandFailure(command, error, report = openIssue) { + const name = words(command.title); + const reason = userMessage(error, t, ''); + const server = /\bHTTP\s*\d{3}\b/.test(String(error?.message ?? error ?? '')) || Number.isInteger(error?.status); + if (reason && !server) return [reason, {tone: 'fail'}]; + // The pill holds one short line beside the button; the server's sentence goes in the detail (the bell keeps both). + return [t(`Failed: “${name}”`, `“${name}”没有完成`), {tone: 'fail', ...(reason ? {detail: reason} : {}), action: { + label: t('Report', '提交问题'), use: t('Open the feedback form with this error filled in', '打开反馈表,已填好这条错误'), + run: () => report(t, {where: ['Command palette', '命令面板'], message: `${name}: ${String(error?.message ?? error ?? '')}`, kind: 'command', facts: {command: command.id}})}}]; +} +function commandFailed(command, error) { const notice = commandFailure(command, error); if (notice[1].action) preloadIssue(); toast(...notice); } function accept() { const command = confirming; confirming = null; drawConfirm(); if (command) execute(command); } function drawConfirm() { ui.confirm.hidden = !confirming; ui.list.hidden = Boolean(confirming); ui.scopes.hidden = Boolean(confirming); diff --git a/web/phone.js b/web/phone.js index aa0100fe..358d795a 100644 --- a/web/phone.js +++ b/web/phone.js @@ -1,5 +1,5 @@ import {chatData, chatPoller, chatDelay, chatReadRequest, emptyChat, chatMerge, chatEntries, newId} from './chat_data.js'; -import {phoneText, jobGroups, mergePhoneJobs, retryWords, queueWords, remainingWords, mediaPath, saveVideo, applyPhoneChain, phonePartWords, phoneJobKey} from './phone_model.js'; +import {phoneText, phoneFailure, jobGroups, mergePhoneJobs, retryWords, queueWords, remainingWords, mediaPath, saveVideo, applyPhoneChain, phonePartWords, phoneJobKey} from './phone_model.js'; import {wordmark} from './wordmark.js'; import {applyPreviewStyle, previewStyle, hintWanted, markHintSeen, onPreviewStyle} from './preview_style.js'; import { skin } from './glass/library.js'; @@ -28,7 +28,7 @@ function renderSheet() { const fresh = button('phone-sheet-new', t('New chat', '新对话'), async () => { fresh.disabled = true; try { const data = await json(await dataLayer.create()); if (!data.session) throw new Error(); closeSheet(); choose(data.session); } - catch { closeSheet(); notice(t('Could not start a new chat. Try again.', '没有新建成功,请重试。')); } + catch (error) { closeSheet(); notice(phoneFailure(error, t, ['start a new chat', '新建对话'])); } }); const list = el('ul', 'phone-sheet-list'); for (const row of convRows.some(row => row.id === convCurrent) || !convCurrent ? convRows : [{id: convCurrent}, ...convRows]) { @@ -134,10 +134,11 @@ compose.onsubmit = async event => { try { body.attempts = 0; const response = await dataLayer.sendMessage(body, {stopped: () => locked || stopped}); - if (!response?.ok) throw new Error(); + if (!response) throw Object.assign(new Error(), {unreachable: true}); + if (!response.ok) throw Object.assign(new Error(), {status: response.status, data: await response.json().catch(() => null)}); if (version === revision && input.value.trim() === text) { input.value = ''; lastSend = null; } await poller.poll(); - } catch { notice(t('Could not send. Please try again.', '没有发送成功,请重试。')); } + } catch (error) { notice(phoneFailure(error, t, ['send', '发送'])); } finally { sending = false; grow(); } }; // Large previews play their strip forward as a loop, 4 to 8 frames a second over the video's length. The position @@ -205,7 +206,7 @@ function renderChat() { const b = button('phone-quiet', approve ? t('Start', '开始') : t('Cancel', '取消'), async () => { const version = revision, session = chat.session; row.querySelectorAll('button').forEach(e => e.disabled = true); try { const answer = await json(await dataLayer.confirm({id: entry.id, approve, ...(session ? {session} : {})})); if (revision === version) { chat.confirms[entry.id] = answer.state; renderChat(); } await poller.poll(); } - catch { row.querySelectorAll('button').forEach(e => e.disabled = false); notice(t('Please try again.', '请重试。')); } + catch (error) { row.querySelectorAll('button').forEach(e => e.disabled = false); notice(phoneFailure(error, t, approve ? ['start', '开始'] : ['cancel', '取消'])); } }); row.append(b); } } else continue; @@ -276,7 +277,7 @@ function openResult(job) { const download = button('phone-primary', t('Download', '下载'), async () => { download.disabled = true; error.hidden = true; try { await saveVideo(job, {fetch: api.fetchApi, download(path, filename) { const a = el('a'); a.href = path; a.download = filename; document.body.append(a); a.click(); a.remove(); }}); } - catch { error.textContent = t('Please try again.', '请重试。'); error.hidden = false; } + catch (failure) { error.textContent = phoneFailure(failure, t, ['download', '下载']); error.hidden = false; } finally { download.disabled = false; } }); actions.append(el('p', 'phone-prompt', job.label), download, error); viewer.append(stage, actions); renderShell(); diff --git a/web/phone_model.js b/web/phone_model.js index 7d4f11a4..05455ddb 100644 --- a/web/phone_model.js +++ b/web/phone_model.js @@ -47,7 +47,7 @@ export async function saveVideo(job, {navigator: nav = globalThis.navigator, fet const path = mediaPath(job.play); if (!path) throw new Error('Video unavailable'); if (isIOS(nav) && nav.share && FileType) { const response = await get(path, {credentials: 'same-origin'}); - if (!response.ok) throw new Error('Video unavailable'); + if (!response.ok) throw Object.assign(new Error('Video unavailable'), {status: response.status}); const file = new FileType([await response.blob()], 'FreeVideo.mp4', {type: 'video/mp4'}); if (!nav.canShare || nav.canShare({files: [file]})) { try { await nav.share({files: [file]}); return 'shared'; } @@ -86,3 +86,21 @@ export function longGeneration(value) { const p = value.progress || value; return Number(p.remaining_seconds ?? p.overall?.remaining_seconds) > 120 || Number(p.elapsed_seconds ?? p.overall?.elapsed_seconds) >= 120; } + +// Why a request from the phone failed, in one sentence: the computer could not be reached (no reply at all), or +// FreeVideo on it returned an error (its own sentence when it wrote one, otherwise the HTTP status). +// `what` is the action as [English, Chinese], e.g. ['send', '发送']. +const RAW_REPLY = /^(?:HTTP\s*)?\d{3}\b|^[a-z][a-z0-9]*(?:[_.:-][a-z0-9]+)+$|Error\b|Traceback|Unexpected token|JSON/; +export function phoneFailure(error, t, [en, zh]) { + const status = Number(error?.status); + if (!(Number.isInteger(status) && status >= 100 && status < 600)) { + if (error?.name === 'TypeError' || error?.unreachable) + return t(`Could not ${en}: the phone cannot reach FreeVideo on the computer. Check that the computer is on and connected to the same Wi-Fi.`, + `没能${zh}:手机连不上电脑上的 FreeVideo。请确认电脑已开机,并与手机连接同一个 Wi-Fi。`); + return t(`Could not ${en}. Try again.`, `没能${zh},请重试。`); + } + const said = error?.data?.error?.message ?? error?.data?.message ?? (typeof error?.data?.error === 'string' ? error.data.error : ''); + if (typeof said === 'string' && said.trim() && !RAW_REPLY.test(said.trim())) return said.trim(); + return t(`Could not ${en}: FreeVideo on the computer returned an error (HTTP ${status}). Try again.`, + `没能${zh}:电脑上的 FreeVideo 返回了错误(HTTP ${status})。请重试。`); +} diff --git a/web/prompt_library.js b/web/prompt_library.js index becde433..3d636402 100644 --- a/web/prompt_library.js +++ b/web/prompt_library.js @@ -49,6 +49,10 @@ if (typeof window !== 'undefined') { // When the page opens, and after a creation is deleted for good (the engine notes its prompt once the undo time is over). setTimeout(() => { void forgetDeletedPrompts().catch(() => {}); }, 4000); window.addEventListener('freevideo-library-deleted', () => setTimeout(() => { void forgetDeletedPrompts().catch(() => {}); }, 16000)); + // A picture deleted for good takes its words from this history as well: the same words may have made a video. + window.addEventListener('freevideo-works-removed', event => { + if (event.detail?.undoable === false) setTimeout(() => { void forgetDeletedPrompts().catch(() => {}); }, 2000); + }); } export function presets(storage) { return read(PRESET_KEY, storage).filter(row => row && typeof row.name === 'string' && row.settings && typeof row.settings === 'object'); } diff --git a/web/prompt_references.js b/web/prompt_references.js index 2748e1f8..0b5d25c2 100644 --- a/web/prompt_references.js +++ b/web/prompt_references.js @@ -88,7 +88,7 @@ export function referenceItems(node) { } stack(sourceFor(node, 'references')); } - if (refs.length && Object.keys(anchors).length) throw new Error('invalid_media'); + // Next to references the keyframes are still guides that the prompt does not name: the pictures it names are the references. const ordered = refs.length ? refs : ['first','last'].filter(k => anchors[k]).map(k => ({...anchors[k], role: k})); const counters = {image: 0, video: 0, audio: 0}; return ordered.map(item => ({...item, number: ++counters[item.kind], diff --git a/web/replace_person.js b/web/replace_person.js index 43693d54..ad56191b 100644 --- a/web/replace_person.js +++ b/web/replace_person.js @@ -3,6 +3,7 @@ // and comes back unchanged when the option is turned off. import { referenceKind } from './prompt_references.js'; import { uploadMedia } from './media_upload.js'; +import { userMessage } from './user_message.js'; import { firstFrameRow } from './first_frame_row.js'; import { swapState, swapRows, effectiveRows, keepsSound, withPrefix, swapMissing, peopleOf, withPeople, MAX_PEOPLE, SWAP_LORA, SWAP_PREFIX, MIN_SOURCE_SECONDS, SWAP_KEY } from './replace_state.js'; @@ -98,7 +99,7 @@ export function createReplacePerson({t, api, media, mount, view, onChange = () = if (kind === 'video') { next.source = {file: result.file, audio: result.audio === true}; if (!next.source.audio) next.keepSound = false; } else { const list = peopleOf(next).slice(); list[Math.min(index, list.length)] = {file: result.file}; withPeople(next, list.slice(0, MAX_PEOPLE)); } save(); - } catch (error) { note.textContent = error.message; } + } catch (error) { note.textContent = userMessage(error, t, t('Could not upload. Try again.', '没能上传,请重试。')); } finally { busy = false; media.isUploading = false; paint(); } } function dropPerson(index) { diff --git a/web/result_actions.js b/web/result_actions.js index 14ab9741..7d09f8bd 100644 --- a/web/result_actions.js +++ b/web/result_actions.js @@ -6,6 +6,7 @@ import { issueButton } from './issue_button.js'; import { savedSettings, differs } from './result_reuse.js'; import { REPORT_GONE } from './report_issue.js'; import { listenDialogKey } from './dialog_keys.js'; +import { userMessage } from './user_message.js'; const css = document.createElement('link'); css.rel = 'stylesheet'; css.href = new URL('./result_actions.css', import.meta.url).href; document.head.append(css); @@ -151,9 +152,9 @@ function deleteAction(t, remove) { confirm.disabled = cancel.disabled = true; confirm.lastElementChild.textContent = t('Deleting…', '正在删除…'); try { await remove(); menu.open = false; } catch (error) { - problem.textContent = error.message; problem.hidden = false; + problem.textContent = userMessage(error, t, t('Could not delete. Try again.', '没能删除,请重试。')); problem.hidden = false; if (error.reportable !== false) { - problemIssue = issueButton(t, () => ({where: ['Delete creation', '删除作品'], message: problem.textContent})); + problemIssue = issueButton(t, () => ({where: ['Delete creation', '删除作品'], message: error?.message || problem.textContent})); problem.after(problemIssue); } } @@ -339,7 +340,7 @@ export function resultActions(record, t, {diagnostic = null, secondPass = null, if (!available(await extendSourceState(api, record))) return; if (await extend(record) === null) throw new Error(t('Could not open the editor. Try again.', '无法打开剪辑,请重试。')); } catch (error) { - label.textContent = error.message || t('Could not open the editor. Try again.', '无法打开剪辑,请重试。'); + label.textContent = userMessage(error, t, t('Could not open the editor. Try again.', '无法打开剪辑,请重试。')); button.title = label.textContent; fault(); } finally { button.disabled = false; } diff --git a/web/settings_room.js b/web/settings_room.js index e8632f12..e3d213e8 100644 --- a/web/settings_room.js +++ b/web/settings_room.js @@ -21,6 +21,7 @@ import { createImageGenClient } from './image_generation.js'; import { IMAGE_MODELS, modelState } from './image_view_models.js'; import { swapLoraFailureText } from './swap_lora.js'; import { MODULES } from './health.js'; +import { userMessage } from './user_message.js'; import { createVerdicts, describeVerdict, feedbackDraft } from './lora_check.js'; import { feedbackIssueURL } from './feedback.js'; import { el, icon, tip, button, setText, row, card, groupHead, groupNote, slot, fold, switchify, checkify, segmented, radioList, stepper, field, bar } from './settings_kit.js'; @@ -31,12 +32,42 @@ if (typeof document !== 'undefined') { document.head.append(css); } -import { cn, t, INSTALLED_HINT, gib, bytesText, atLeast, WAIT_REFUSAL, reportable, failureText, SECTIONS, sectionOf } from './settings_words.js'; +import { cn, t, INSTALLED_HINT, gib, bytesText, atLeast, WAIT_REFUSAL, reportable, failureText, setupError, SECTIONS, sectionOf } from './settings_words.js'; export { failureText, sectionOf, SECTIONS, bytesText }; let current; export const settingsOpen = () => Boolean(current?.open); +// Esc closes Settings at once and a save already sent is not taken back, so it can fail with Settings gone. A warning +// that lands in one of the closed room's status lines after it closed is shown as a failure notice instead: the +// setting's name with the line's own words, and a way back to its page (failures also stay in the notification list). +// Watching starts as Settings starts to close (a failure during the fade is not seen either) and stops after ten +// minutes; every save answers well before that. +const LATE_WATCH_MS = 10 * 60 * 1000; +const lineText = line => { const copy = line.cloneNode(true); copy.querySelectorAll('button, a').forEach(node => node.remove()); return copy.textContent.trim(); }; +function watchLateFailures(room) { + const seen = new Map([...room.querySelectorAll('[role=status]')].map(line => [line, lineText(line)])); + const report = async (line, text) => { + const page = line.closest('section.st-pane'), box = line.closest('.st-card'); + let head = box?.previousElementSibling; + while (head && !head.matches('h3.st-gh')) head = head.previousElementSibling; + // The setting's name, then the line's own words; "Open Settings" goes back to its page. + const name = head?.textContent.trim() || page?.getAttribute('aria-label') || t('Settings', '设置'); + const {toast} = await import('./notifications.js'); + toast(`${name} · ${text}`, {tone: 'fail', action: {label: t('Open Settings', '打开设置'), use: t('Go back to this setting', '回到这项设置'), + run: () => openSetup({section: page?.dataset.pane || null})}}); + }; + const observer = new MutationObserver(() => { + for (const line of room.querySelectorAll('[role=status]')) { + const text = lineText(line), before = seen.get(line); + seen.set(line, text); + if (text && text !== before && /\bis-(warn|fail)\b/.test(line.className)) report(line, text); + } + }); + observer.observe(room, {subtree: true, childList: true, characterData: true, attributes: true, attributeFilter: ['class']}); + setTimeout(() => observer.disconnect(), LATE_WATCH_MS); +} + export async function openSetup(options) { // A click passes its event here; only a plain object can name a section to show. const section = options?.constructor === Object ? options.section : null; @@ -149,9 +180,12 @@ export async function openSetup(options) { // The shared report button, with this room's hover words. const reportTip = node => tip(node, t('Report a problem', '提交问题'), t('Send the problem with its diagnostics', '附上诊断信息提交问题')); - const fault = (target, message) => { - const text = failureText(message); target.textContent = text; - if (text && reportable(message)) target.append(reportTip(issueButton(t, () => ({where: ['Settings / installation', '设置/安装'], message: text})))); + // With the caught error passed too, text that only a browser or a program would say is replaced by a plain sentence; + // the report keeps what was said before. + const fault = (target, message, error, fallback) => { + const known = failureText(message), text = error && known === String(message || '') ? userMessage(error, t, fallback) : known; + target.textContent = text; + if (text && reportable(message)) target.append(reportTip(issueButton(t, () => ({where: ['Settings / installation', '设置/安装'], message: known})))); }; // ════════════ Models ════════════ @@ -438,7 +472,8 @@ export async function openSetup(options) { const saved = await request('preview-style', {style: wanted}); applyPreviewStyle(saved.style, saved.chosen === true); } catch (error) { - previewStatus.textContent = failureText(error.message); previewStatus.className = 'st-slot is-warn'; + const known = failureText(error.message); + previewStatus.textContent = known === String(error.message || '') ? userMessage(error, t, t('Could not save. Try again.', '没能保存,请重试。')) : known; previewStatus.className = 'st-slot is-warn'; } finally { loopSwitch.disabled = false; choices.removeAttribute('aria-busy'); paintPreview(); } }; previewStatus.textContent = t('Applies at once to the preview on screen, also on the phone page.', '立即应用到屏幕上的预览,手机页面也一样。'); @@ -787,11 +822,13 @@ export async function openSetup(options) { dialog.addEventListener('pointerdown', event => { if (!pickerMenu.hidden && !phoneHead.contains(event.target)) closePicker(); }); // ── Closing: Esc (unless a menu inside takes it first) or the close buttons; focus goes back to where it was ── - let closing = null; + let closing = null, watching = false; + const watchAfterClose = () => { if (!watching) { watching = true; watchLateFailures(dialog); } }; function close() { if (closing) return closing; closing = new Promise(resolve => { if (!dialog.open) { resolve(); return; } + watchAfterClose(); if (sheet.open) sheet.close(); dialog.dataset.closing = 'true'; const finish = () => { if (dialog.open) dialog.close(); resolve(); }; @@ -1029,7 +1066,7 @@ export async function openSetup(options) { let lastTask = {}, loaded = false, readFailed = false, wantSheet = false, busyLabel = ''; // A click names what is happening at once, before the server has answered. const doing = (en, zh) => { waitSince ??= Date.now(); state.className = 'st-state'; state.textContent = t(en, zh); paintHero(); }; - const fail = error => { waitSince = undefined; fault(state, error.message); state.className = "st-state is-fail"; if (shown !== 'models' && !busy) { /* The dot on Models says where to look. */ } paintHero(); }; + const fail = error => { waitSince = undefined; fault(state, error.message, error); state.className = "st-state is-fail"; if (shown !== 'models' && !busy) { /* The dot on Models says where to look. */ } paintHero(); }; const request = async (action, value) => { const response = await api.fetchApi("/freevideo/setup" + (action ? "/" + action : root.value ? '?root='+encodeURIComponent(root.value) : ""), action ? { method: "POST", headers: { "Content-Type": "application/json", "X-FreeVideo-Setup": token }, body: JSON.stringify(value || {}), @@ -1103,7 +1140,7 @@ export async function openSetup(options) { // so the progress it points to is visible. calibrateWait = WAIT_REFUSAL.test(String(error.message || '')); calibrateStatus.className = calibrateWait ? 'st-slot' : 'st-slot is-warn'; - fault(calibrateStatus, error.message); + fault(calibrateStatus, error.message, error, t('Could not start the measurement. Try again.', '没能开始测量,请重试。')); if (calibrateWait) poll(); } finally { calibrateButton.disabled = busy; } }; @@ -1130,7 +1167,16 @@ export async function openSetup(options) { reserveStatus.replaceChildren(icon('check', 'fv-i'), document.createTextNode(t('Saved · applies to the next generation', '已保存 · 下次生成生效'))); // The note fades after two seconds. savedTimer = setTimeout(() => { reserveStatus.classList.add('is-fade'); savedTimer = setTimeout(clearReserveStatus, 400); }, 2000); - } catch (error) { reserveFailure.className = 'st-slot is-warn'; fault(reserveFailure, error.message); } + } catch (error) { + // As on the compatibility card: a known refusal is already a sentence, a server's own words follow "Save + // failed", and a lost connection or browser wording becomes a plain sentence; the report keeps what was said. + reserveFailure.className = 'st-slot is-warn'; + fault(reserveFailure, error.message, error, t('Could not save. Try again.', '没能保存,请重试。')); + const said = String(error.message || '').trim(), shown = reserveFailure.firstChild; + if (said && setupError(said) === undefined && shown?.nodeType === Node.TEXT_NODE && shown.data === said) { + shown.data = t('Save failed: ', '保存失败:') + said; + } + } finally { saveReserve.disabled = false; } }; const SOURCE_NAMES = {official: t('International source', '国际源'), huggingface: t('International source', '国际源'), 'hf-mirror': t('International mirror', '国际镜像'), modelscope: t('China source', '国内源')}; @@ -1335,8 +1381,10 @@ export async function openSetup(options) { folderStatus.className = savedMissing ? 'st-slot is-caution' : 'st-slot is-ok'; folderStatus.replaceChildren(savedFolders); if (savedMissing) { - // The full path is in the box above; show its start and last folder on one line. - const first = missing[0], path = el('span', 'st-path fv-copyable', first.length > 44 ? `${first.slice(0, 14)}…${first.slice(-26)}` : first); + // The full path is in the box above; show its start and last folder on one line. The start gives way to the room + // there is (cut with an ellipsis), the last 26 characters stay; copying takes the whole path. + const first = missing[0], cut = Math.max(0, first.length - 26), path = el('span', 'st-path st-path-cut fv-copyable'); + path.append(el('span', 'st-path-head', first.slice(0, cut)), el('span', 'st-path-tail', first.slice(cut))); path.title = first; folderStatus.append(path); } return result; @@ -1345,7 +1393,7 @@ export async function openSetup(options) { invalidate(true); busy = true; controls(); const before = [[...state.childNodes], state.className]; doing('Saving model folders…', '正在保存模型文件夹…'); try { await saveModelFolders(); } - catch (error) { savedFolders = ''; savedMissing = false; fault(folderStatus, error.message); folderStatus.className = 'st-slot is-warn'; } + catch (error) { savedFolders = ''; savedMissing = false; fault(folderStatus, error.message, error, t('Could not save the model folders. Try again.', '没能保存模型文件夹,请重试。')); folderStatus.className = 'st-slot is-warn'; } finally { busy = false; waitSince = undefined; state.replaceChildren(...before[0]); state.className = before[1]; controls(); } }; headInspect.onclick = () => { if (!busy) inspect.click(); }; @@ -1370,6 +1418,7 @@ export async function openSetup(options) { clearTimeout(pollTimer); clearTimeout(monitorTimer); clearTimeout(imageTimer); clearTimeout(swapTimer); for (const dispose of disposers) { try { dispose(); } catch { /* Gone already. */ } } compat.dispose?.(); + watchAfterClose(); dialog.remove(); if (current === dialog) current = undefined; if (returnFocus?.isConnected) { try { returnFocus.focus({preventScroll: true}); } catch { /* Focus stays where the browser put it. */ } } }); diff --git a/web/share.js b/web/share.js index a7af6105..a2738f7e 100644 --- a/web/share.js +++ b/web/share.js @@ -5,6 +5,7 @@ import {fontCSS as bundledFontCSS, fontLoaded, loadFont} from './fonts.js'; import {shareLayout} from './share_layout.js'; import {videoUnavailableText} from './studio_extend.js'; import {issueButton} from './issue_button.js'; +import {userMessage} from './user_message.js'; import {exportKeepsWorkflow, workflowToggle} from './output_download.js'; import {fileFailureText, responseFileReason} from './file_failure.js'; import {isNetworkTypeError, connectionLostText} from './browser_extension.js'; @@ -209,5 +210,5 @@ export async function openShare(record,t){ preview.style.aspectRatio=`${shape.width}/${shape.height}`; player.style.cssText=`left:${shape.rect[0]/shape.width*100}%;top:0;width:${shape.rect[2]/shape.width*100}%;height:${shape.rect[3]/shape.height*100}%`; ready=true;choose(kind);save.disabled=false; - }catch(error){if(!disposed)say(error.message||t('Preview unavailable. Close and try again.','预览暂时无法读取,请关闭后重试。'),true);} + }catch(error){if(!disposed)say(userMessage(error,t,t('Preview unavailable. Close and try again.','预览暂时无法读取,请关闭后重试。')),true);} } diff --git a/web/shell.js b/web/shell.js index f207b5a6..8bf102cd 100644 --- a/web/shell.js +++ b/web/shell.js @@ -256,13 +256,14 @@ export function holdWhile(open, {ready = null} = {}) { switching = token; root.dataset.fvSwitching = reduced() ? 'instant' : 'fade'; nameBar(frontBar()); uniqueNames(); - let result; - const done = () => { if (switching === token) { switching = null; delete root.dataset.fvSwitching; nameBar(null); } }; + let result, release = () => {}; + const done = () => { release(); if (switching === token) { switching = null; delete root.dataset.fvSwitching; nameBar(null); } }; try { token.transition = document.startViewTransition(async () => { mark.captured = +(performance.now() - mark.press).toFixed(1); try { result = open(); } catch (error) { result = Promise.reject(error); } await Promise.race([Promise.resolve(result).catch(() => null), sleep(SWITCH_HOLD)]); + release = holdFocus(); }); } catch (error) { done(); return Promise.resolve().then(open); } token.transition.ready.then(async () => { @@ -278,6 +279,19 @@ export function holdWhile(open, {ready = null} = {}) { return token.transition.updateCallbackDone.then(() => result, () => result); } +// When the held picture starts fading over a panel just opened as a modal dialog, the browser drops the panel's focus +// to the page and will not take it back until the fade has ended, so its keys (Escape, the arrows) would go nowhere. +// When the fade ends, focus that fell to the page goes back to what the panel had focused; focus moved on purpose +// (to another element) is left alone. +function holdFocus() { + const held = document.activeElement; + if (!held || held === document.body || held === document.documentElement) return () => {}; + return () => { + const now = document.activeElement; + if ((!now || now === document.body) && held.isConnected && !held.closest('[inert]') && (held.tagName !== 'DIALOG' || held.open)) held.focus({preventScroll: true}); + }; +} + // ── No placeholder at a press ───────────────────────────────────────────────────────────────────── // A press lights its tab at once (no slide); the picture held while the view comes to the front is the view the user // was on, never a placeholder. A view comes back as it was left (the views are kept, or draw from what they kept), so diff --git a/web/studio.css b/web/studio.css index e16083cc..3b50c76b 100644 --- a/web/studio.css +++ b/web/studio.css @@ -322,8 +322,5 @@ .fv-studio:not(.fv-editor):not(.fv-autopilot) .fv-header[data-fit~=least] .fv-guide-entry{display:none} /* The first row matches the edit view's (its name field is 40 px), so the wrapped switch stays put when the view changes. */ .fv-studio:not(.fv-editor):not(.fv-autopilot) .fv-header[data-fit~=small] .fv-wordmark{width:150px} -.fv-studio:not(.fv-editor):not(.fv-autopilot) .fv-header[data-fit~=compact] .fv-monitor-text{display:none} -.fv-studio:not(.fv-editor):not(.fv-autopilot) .fv-header[data-fit~=gone] .fv-monitor{display:none} -.fv-studio:not(.fv-editor):not(.fv-autopilot) .fv-header[data-fit~=compact] .fv-monitor .fv-monitor-trigger{padding:0 8px} .fv-studio .fv-run-menu .fv-batch-lines{display:flex;align-items:center;justify-content:space-between;gap:8px;padding:10px 8px 0;cursor:pointer}.fv-studio .fv-run-menu .fv-batch-lines[hidden]{display:none} .fv-studio .fv-run-menu .fv-batch-lines input{margin:0;accent-color:var(--fv-accent)} diff --git a/web/studio.js b/web/studio.js index f72522eb..f5975e3c 100644 --- a/web/studio.js +++ b/web/studio.js @@ -1,6 +1,5 @@ import './has_mirror.js'; import {createLanAccess} from './lan_access.js'; -import {createMonitor} from './monitor_panel.js'; import { createErrorPanel, errorText, createErrorReport } from './error_panel.js'; import {createExpandButton} from './editor_expand.js'; import {allowEmptyPrompt, cleanOptionalPrompt, clonePrompt} from './optional_inputs.js'; @@ -21,7 +20,7 @@ import { issueButton } from './issue_button.js'; import { skinSelect } from './fv_select.js'; import { createPreviewScene } from './preview_scene.js?v=20261115-still'; import { animateDetails, closeDialog } from './motion.js'; -import { openLibrary, setDefaultUpscale, videoThumbnailURL } from './library.js'; +import { openLibrary, setDefaultUpscale, setDefaultUpscaleWork, videoThumbnailURL } from './library.js'; import { createRecentVideos } from './studio_recent.js'; import { createAgentActivity } from './agent_activity.js'; import { createStudioQueue, randomSeed, turnNodeOn } from './studio_queue.js'; @@ -63,7 +62,7 @@ import { firstFrameRow } from './first_frame_row.js'; import { createReplacePerson, swapMissingText } from './replace_person.js'; import { swapState, swapMissing, effectiveRows, prepareSwapLora, releaseSwapLora, peopleOf } from './replace_state.js'; import { swapLoraDownload } from './swap_lora.js'; -import { createStudioChain, chainPosition, chainParts, chainSplit, composePartText, readChainResult, sumPartEstimates, singleRunSnapshot } from './studio_chain.js?v=20261113-connection'; +import { createStudioChain, chainPosition, chainParts, chainSplit, composePartText, readChainResult, sumPartEstimates, singleRunSnapshot } from './studio_chain.js?v=20261117-chain-errors'; import { activeOriginal, checkOriginal, lockMark, blockOriginal, originalBlocked, usesOriginal, referenceRow, partsNeedTwoPassText } from './audio_original.js'; import { joiningText, waitingText } from './chain_support.js'; import { createExtendState, extendText, extendSourceProblem, extendSourceState, readExtendRecord, extendSnapshot, mountExtendThumbnail, videoUnavailableText } from './studio_extend.js'; @@ -77,6 +76,7 @@ import { createPromptLibrary, rememberPrompt } from './prompt_library.js'; import { createCompare, COMPARE_ICON } from './studio_compare.js'; import { toast, toastHeight } from './notifications.js'; import { mediaQueue } from './work_media.js'; +import { userMessage } from './user_message.js'; const languageOverride = typeof location !== 'undefined' ? new URLSearchParams(location.search).get('freevideo_lang') : null; @@ -114,7 +114,7 @@ const el = (tag, label, cls) => { const e = document.createElement(tag); if (lab // One line per part of a long video, under the preview. A part that has not started opens in // place for editing and saves when it loses focus; the server's reply decides what stays. // After the video stops, an ended part can be made again from there on as a new video. -function createChainPartList(t, save, {onShow = () => {}, onHide = () => {}, redo = async () => {}, resume = async () => {}, playSeam = null} = {}) { +function createChainPartList(t, save, {onShow = () => {}, onHide = () => {}, redo = async () => {}, resume = async () => {}, onError = () => {}, playSeam = null} = {}) { const element = el('div', null, 'fv-chain-parts'); element.hidden = true; const rows = new Map(), timers = new Map(); let editing = null, showing = null; @@ -157,8 +157,15 @@ function createChainPartList(t, save, {onShow = () => {}, onHide = () => {}, red row.starting = true; row.redo.disabled = true; tag(row, t('Starting…', '正在开始…')); try { await (row.part.action === 'resume' ? resume() : redo(row.part.id)); } catch (error) { - if (rows.get(row.part.id) === row) flash(row, error.status === 409 ? t('Another video is generating. Try again when it finishes.', '正在生成别的视频,完成后再试。') - : t('Could not start. Try again.', '没能开始,请重试。'), 'error'); + if (error.status === 409) { + if (rows.get(row.part.id) === row) flash(row, t('Another video is generating. Try again when it finishes.', '正在生成别的视频,完成后再试。'), 'error'); + return; + } + // The line says the server's own sentence when it gave one; the card carries what failed and a report. + const said = (error.said || error.cause?.said); + if (rows.get(row.part.id) === row) flash(row, said ? t(said[0], said[1]) + : t('Could not start. See the details on the picture.', '没能开始,原因见画面上的说明。'), 'error'); + onError(error); } finally { row.starting = false; row.redo.disabled = false; } } function flash(row, text, kind) { @@ -366,6 +373,11 @@ export function loraPanel(node, panel, {promptNode = null} = {}) { const verdicts = createVerdicts((path, options) => api.fetchApi(path, options)); let rowChecks = []; let focusGrip = null; + // The list lives in the node as JSON; a broken list is not a reply from FreeVideo, so it gets its own sentence. + const listProblem = error => { + const unreadable = t('The LoRA list cannot be read. Add the LoRAs again.', 'LoRA 列表无法读取,请重新添加 LoRA。'); + return error?.name === 'SyntaxError' ? unreadable : userMessage(error, t, unreadable); + }; const read = () => { const rows = JSON.parse(value(node, 'adapters') || '[]'); if (!Array.isArray(rows) || rows.length > 32) throw new Error(t('Use at most 32 LoRAs', '最多使用 32 个 LoRA')); return rows; }; function syncPrompt(rows) { const targets = new Set([promptNode, ...(node.graph?._nodes || []).filter(target => @@ -403,7 +415,7 @@ export function loraPanel(node, panel, {promptNode = null} = {}) { if (trigger.dataset.name === name && !drafts.has(name)) trigger.value = triggerEntry(name).data?.words ?? ''; } note.textContent = rows.map(row => errors.get(row.name)).find(Boolean) || idleNote(); - } catch (error) { note.textContent = error.message; } + } catch (error) { note.textContent = listProblem(error); } } const write = rows => { if (set(node, 'adapters', JSON.stringify(rows))) { syncPrompt(rows); window.dispatchEvent(new CustomEvent('freevideo-loras', {detail: node.id})); } }; // A LoRA the model cannot take is switched off here, so it is not sent with the request. @@ -413,7 +425,7 @@ export function loraPanel(node, panel, {promptNode = null} = {}) { const rows = read(); let changed = false; for (const row of rows) if (row.name === name && row.enabled !== false && verdicts.peek(name)?.usable === false) { row.enabled = false; changed = true; } if (changed) write(rows); - } catch (error) { note.textContent = error.message; } + } catch (error) { note.textContent = listProblem(error); } } const reorder = order => { const rows = read(); @@ -547,14 +559,14 @@ export function loraPanel(node, panel, {promptNode = null} = {}) { if (known) mark(known); else check(false); list.append(wrap); - loadTriggers(row.name).catch(error => { if (!disposed && trigger.isConnected) note.textContent = error.message; }); + loadTriggers(row.name).catch(error => { if (!disposed && trigger.isConnected) note.textContent = userMessage(error, t, t('Could not read the trigger words. Try again.', '没能读取触发词,请重试。')); }); }); if (rows.length > 1) actions.append(clear); if (focusGrip != null) { list.querySelector(`.fv-lora-row[data-index="${focusGrip}"] .fv-lora-grip`)?.focus(); focusGrip = null; } note.textContent = rows.map(row => errors.get(row.name)).find(Boolean) || idleNote(); } catch (error) { if (error instanceof DOMException) throw error; - note.textContent = error.message; + note.textContent = listProblem(error); } finally { rendering = false; @@ -735,7 +747,6 @@ export function openStudio(node, {extendFrom = null} = {}) { brand.append(wordmark()); const tools = el('div', null, 'fv-header-actions'); const agents = createAgentActivity(t, api, dialog); tools.append(agents.element); cleanup.push(agents.dispose); - const monitor = createMonitor(t, api); tools.append(monitor.element); cleanup.push(monitor.dispose); const phoneAccess = createLanAccess(t, api); tools.append(phoneAccess.element); cleanup.push(phoneAccess.dispose); const versionInfo = createVersionInfo(cn); tools.append(versionInfo.element); cleanup.push(versionInfo.dispose); tools.append(guideButton(t), feedbackButton(t), button(t('Settings', '设置'), openSetup, 'fv-quiet')); @@ -781,8 +792,7 @@ export function openStudio(node, {extendFrom = null} = {}) { const castAssets = () => { const owner = upstream(node, 'media'); const field = owner && widget(owner, 'assets'); return field ? {owner, field} : null; }; // The library's own upload of a picture goes to the same streaming upload the media panel uses. const castUpload = file => uploadMedia(api, file); - const castBlocked = reason => ({frames: t('Not available with first and last frames', '首尾帧不能和角色同时使用'), - people: t('Up to 3 characters', '最多 3 个角色'), props: t('Up to 2 props', '最多 2 个道具'), full: t('Up to 32 references', '参考素材最多 32 个'), + const castBlocked = reason => ({people: t('Up to 3 characters', '最多 3 个角色'), props: t('Up to 2 props', '最多 2 个道具'), full: t('Up to 32 references', '参考素材最多 32 个'), continued: t('No room left when continuing', '接续段位置已满')}[reason] || ''); const castPending = new Map(); // The feature tour's "try it": one example into this panel's media list, prompt and settings. @@ -1041,7 +1051,7 @@ export function openStudio(node, {extendFrom = null} = {}) { if (![...mp.options].some(option => Number(option.value) === pixels)) { const option = el('option', `${pixels.toFixed(2)} MP`); option.value = pixels; mp.append(option); } mp.value = String(pixels); try { applySize(); if (pixels !== 1) legacyOption?.remove(); status.dataset.error = 'false'; } - catch (error) { pixels = previous; mp.value = String(previous); syncResolutionLabel(); status.dataset.error = 'true'; status.textContent = error.message; } + catch (error) { pixels = previous; mp.value = String(previous); syncResolutionLabel(); status.dataset.error = 'true'; status.textContent = userMessage(error, t, t('Could not change the resolution. Try again.', '没能更改清晰度,请重试。')); } } for (const preset of PRESET_PIXELS) { const mark = button(String(preset), () => choosePixels(preset), 'fvs-res-tick'); @@ -1309,9 +1319,18 @@ export function openStudio(node, {extendFrom = null} = {}) { const firstFrame = firstFrameRow(t, 'fv-first-frame'); firstFrame.row.hidden = true; fields.after(firstFrame.row); firstFrame.input.checked = value(node, 'first_frame_reference') === true; - firstFrame.input.onchange = () => { set(node, 'first_frame_reference', firstFrame.input.checked); firstFrame.input.checked = value(node, 'first_frame_reference') === true; }; + firstFrame.input.onchange = () => { + if (borrowed?.firstFrame) { borrowed.onFirstFrame?.(firstFrame.input.checked); return; } // the edit keeps it, not this panel + set(node, 'first_frame_reference', firstFrame.input.checked); firstFrame.input.checked = value(node, 'first_frame_reference') === true; + }; let manyParts = false, originalOn = false; function updateFirstFrame() { + // While the editor borrows the bar, the editor says when the switch applies and what is on. + const lent = borrowed?.firstFrame; + if (lent) { + if (firstFrame.row.hidden !== !lent.shown) firstFrame.row.hidden = !lent.shown; + firstFrame.input.checked = lent.checked; firstFrame.setDisabled(Boolean(lent.disabled)); return; + } // While a new plan is being worked out the row keeps its place. const plan = lengthControl.plan; if (plan || !lengthControl.needsPlan) manyParts = plan?.count > 1; { const gone = !widget(node, 'first_frame_reference') || !(manyParts || extension.source); if (firstFrame.row.hidden !== gone) firstFrame.row.hidden = gone; } @@ -1447,7 +1466,12 @@ export function openStudio(node, {extendFrom = null} = {}) { if (!linked(node, 'conditioning')) { const media = referenceItems(node), refs = media.filter(r => !r.role); requestRefs = refs; - const audio = refs.some(r => r.kind === 'audio'), visual = refs.some(r => r.kind !== 'audio'); + const audio = refs.some(r => r.kind === 'audio'); + // Next to references, keyframes are still guides, which the engine counts as pictures. + const keyframes = (() => { try { return JSON.parse(value(upstream(node, 'media'), 'assets') || '[]') + .some(r => r.enabled !== false && ['first', 'last'].includes(r.role)); } catch { return false; } })() + || ['first', 'last'].some(name => linked(upstream(node, 'media'), name)); + const visual = refs.some(r => r.kind !== 'audio') || refs.length > 0 && keyframes; const first = media.some(r => r.role === 'first'), last = media.some(r => r.role === 'last'); task = audio ? visual ? 'ref2va_av' : 'ref2va_audio' : visual ? 'ref2va' : first && last ? 'fl2va' : first ? 'i2va' : last ? 'l2va' : 't2va'; @@ -1497,6 +1521,7 @@ export function openStudio(node, {extendFrom = null} = {}) { const previewTools = el('div', null, 'fv-preview-tools'); // Creations opened from a notification, the palette or search finish a first-pass preview through this node too. setDefaultUpscale(value => node.freevideoUpscaleResult(value)); + setDefaultUpscaleWork((value, options) => node.freevideoUpscaleWork(value, options)); const worksButton = button('', () => { stage.querySelector('video')?.pause(); openLibrary(t, {upscale: value => node.freevideoUpscaleResult(value), extend: (saved, options) => openExtendEditor(saved, node, {studio: dialog, ...options}), @@ -1521,6 +1546,7 @@ export function openStudio(node, {extendFrom = null} = {}) { const partList = createChainPartList(t, (block, text) => chainController.setText(block, composePartText(chainController.state, block, text)), { redo: block => { failure.clear(); return chainController.redo(block); }, resume: () => { failure.clear(); return chainController.resume(); }, + onError: error => showChainActionError(error), playSeam: seconds => playAround(seconds)}); // Set once the queue buttons exist: "Continue generating" stays hidden while a listed part offers the same. let syncResume = () => {}; @@ -1662,6 +1688,8 @@ export function openStudio(node, {extendFrom = null} = {}) { const TALL_EDGE = 48, TALL_RAIL = 122, GRID_MIN = 320; let recentCount = () => 0; let consoleSnap = {shape: '', held: false}; + // Set once the failure card exists (below): whether it is on the picture, and the height it needs to read whole. + let failureShown = () => false, failureNeed = () => 0; const tallChange = () => fitPreview(); tall?.addEventListener?.('change', tallChange); cleanup.push(() => tall?.removeEventListener?.('change', tallChange)); function fitTall(gap) { @@ -1688,20 +1716,26 @@ export function openStudio(node, {extendFrom = null} = {}) { if (!(width > 0) || !(room > 0) || !Number.isFinite(previewRatio) || previewRatio <= 0) return; const height = Math.max(Math.min(room, 160), Math.min(room, width / previewRatio)); const fittedWidth = Math.min(width, height * previewRatio), fittedHeight = fittedWidth / previewRatio; - stage.style.width = `${fittedWidth}px`; stage.style.height = `${fittedHeight}px`; + // A failure card on the picture keeps its cause, next step and buttons whole: the picture widens to the card + // (560 px at most) and grows to its height, and the column scrolls if that is taller than the room. + const failed = failureShown(); + const stageWidth = failed ? Math.max(fittedWidth, Math.min(width, 560 + 32)) : fittedWidth; + stage.style.width = `${stageWidth}px`; + const stageHeight = failed ? Math.max(fittedHeight, failureNeed()) : fittedHeight; + stage.style.height = `${stageHeight}px`; // The picture, its bar and the status line sit as one block in the middle of the column. - previewSpace.style.height = `${fittedHeight}px`; + previewSpace.style.height = `${stageHeight}px`; // The bar and the status line under the picture keep its width, so their ends line up with the picture's edges. - output.style.setProperty('--fvs-stage-w', `${Math.round(fittedWidth)}px`); + output.style.setProperty('--fvs-stage-w', `${Math.round(stageWidth)}px`); // On a phone the picture block sits just above the console (no empty band between them); wider windows centre it. - const free = Math.max(0, Math.floor(room - fittedHeight)); + const free = Math.max(0, Math.floor(room - stageHeight)); const marginTop = fit?.grid ? 0 : phone?.matches ? free : Math.floor(free / 2); previewSpace.style.marginTop = `${marginTop}px`; // The next generation's empty frame stays whole while a tray floats over the picture's lower part: it is fitted // and centred in the part left free, and takes the full stage again when the tray closes (200 ms). stage.style.translate = ''; // (A tray shown as a small window beside its button, glass/tray_pop.js, floats over the stage and takes no room.) - const openTray = nextShown && body.dataset.traySide !== 'true' ? controls.querySelector('.fvs-tray[open]:not([data-closing]):not([data-fv-pop])') : null; + const openTray = nextShown && !failed && body.dataset.traySide !== 'true' ? controls.querySelector('.fvs-tray[open]:not([data-closing]):not([data-fv-pop])') : null; if (openTray) { const spaceTop = output.getBoundingClientRect().top + parseFloat(style.paddingTop) + marginTop; const freeHeight = Math.min(fittedHeight, openTray.getBoundingClientRect().top - spaceTop - 16); @@ -1711,13 +1745,13 @@ export function openStudio(node, {extendFrom = null} = {}) { stage.style.translate = `0 ${Math.round((freeHeight - fittedHeight) / 2)}px`; } } - stage.dataset.narrow = String((parseFloat(stage.style.width) || fittedWidth) < 220); + stage.dataset.narrow = String((parseFloat(stage.style.width) || stageWidth) < 220); // The history rail centres on the picture and is never taller than it (read from the layout, not the // animated boxes). const pictureTop = output.getBoundingClientRect().top - body.getBoundingClientRect().top + parseFloat(style.paddingTop) + marginTop; body.style.setProperty('--fvs-stage-top', `${Math.round(pictureTop)}px`); - body.style.setProperty('--fvs-stage-h', `${Math.round(fittedHeight)}px`); - if (fit?.grid) body.style.setProperty('--fvs-grid-top', `${Math.round(pictureTop + fittedHeight + fit.barRoom + 16)}px`); + body.style.setProperty('--fvs-stage-h', `${Math.round(stageHeight)}px`); + if (fit?.grid) body.style.setProperty('--fvs-grid-top', `${Math.round(pictureTop + stageHeight + fit.barRoom + 16)}px`); else body.style.removeProperty('--fvs-grid-top'); // The console and the picture are either the same width or clearly apart (at least 24 px a side), never a // few pixels off. @@ -1728,11 +1762,13 @@ export function openStudio(node, {extendFrom = null} = {}) { // The console takes the picture's width when a window or picture shape is first fitted, and lets go for good // (until that shape changes) once they are 48 px apart: the console's own height moves the picture (the room // left under it), so a row of chips right at a wrap would otherwise flip it between the two widths every frame. - const shape = `${body.clientWidth}x${body.clientHeight}:${previewRatio}`; + // A failure card widens the picture, so the console is matched to the picture as shown, and fitted afresh + // when the card comes or goes. + const shape = `${body.clientWidth}x${body.clientHeight}:${previewRatio}:${failed}`; if (consoleSnap.shape !== shape) consoleSnap = {shape, held: true}; - consoleSnap.held &&= Math.abs(fittedWidth - natural) < 48 && fittedWidth <= room; + consoleSnap.held &&= Math.abs(stageWidth - natural) < 48 && stageWidth <= room; const same = consoleSnap.held; - if (same) controls.style.setProperty('--fvs-console-w', `${Math.round(fittedWidth)}px`); else controls.style.removeProperty('--fvs-console-w'); + if (same) controls.style.setProperty('--fvs-console-w', `${Math.round(stageWidth)}px`); else controls.style.removeProperty('--fvs-console-w'); } else controls.style.removeProperty('--fvs-console-w'); stage.dataset.short = String(fittedHeight < 150); // The history rail centres itself on the stage, above the console. @@ -1840,8 +1876,25 @@ export function openStudio(node, {extendFrom = null} = {}) { failureClose.append(glyph('close', 14)); failureClose.setAttribute('aria-label', t('Close', '关闭')); tip(failureClose, t('Close', '关闭'), t('Hide the card and show the picture', '收起这张卡片,显示画面')); failureLayer.append(failure.element, failureClose); stage.append(failureLayer); - const failureWatch = new MutationObserver(() => { failureLayer.hidden = failure.element.hidden; }); - failureWatch.observe(failure.element, {attributes: true, attributeFilter: ['hidden']}); cleanup.push(() => failureWatch.disconnect()); + failureShown = () => !failureLayer.hidden; + // The card's whole height (its content, border and the layer's padding), read at the picture's final width. + failureNeed = () => { const card = failure.element, pad = parseFloat(getComputedStyle(failureLayer).paddingTop) || 0; + return Math.ceil(card.scrollHeight + card.offsetHeight - card.clientHeight + 2 * pad); }; + let failureFit = 0; + const refitFailure = () => { if (!failureFit) failureFit = requestAnimationFrame(() => { failureFit = 0; fitPreview(); }); }; + cleanup.push(() => cancelAnimationFrame(failureFit)); + const failureWatch = new MutationObserver(() => { + const hidden = failure.element.hidden; + if (failureLayer.hidden !== hidden) failureLayer.hidden = hidden; + refitFailure(); + }); + failureWatch.observe(failure.element, {attributes: true, attributeFilter: ['hidden'], childList: true, subtree: true, characterData: true}); + cleanup.push(() => failureWatch.disconnect()); + // Opening its details changes the card's height; a width change is read again once the picture has finished it. + failure.element.addEventListener('toggle', refitFailure, true); + stage.addEventListener('transitionend', event => { if (event.target === stage && event.propertyName === 'width' && failureShown()) refitFailure(); }); + const layerWatch = new MutationObserver(refitFailure); + layerWatch.observe(failureLayer, {attributes: true, attributeFilter: ['hidden']}); cleanup.push(() => layerWatch.disconnect()); // With the picture, the result's actions and numbers form one block, centred below the header. output.append(el('div', null, 'fv-preview-end')); if (node.freevideoFailure) failure.show(node.freevideoFailureReport || node.freevideoFailure, false); @@ -2260,7 +2313,8 @@ export function openStudio(node, {extendFrom = null} = {}) { const otherUsage = createOtherUsageNotice(runbar, t, api.fetchApi.bind(api)); cleanup.push(() => otherUsage.dispose()); runbar.append(requestAssets.element, runrow, addVideoNote, queueActions); controls.append(runbar); - const queueError = error => ({ + // A chain action the server refused with its own sentence says that sentence, not the general "could not continue". + const queueError = error => (error?.action && error.said ? t(error.said[0], error.said[1]) : null) || ({ queue_unavailable: t('Could not read the queue. The loop has stopped; videos already added stay queued.', '暂时读不到队列,循环已停止;已加入的视频还在队列中。'), cancel_failed: t('Could not cancel. Try again.', '没有取消成功,请重试。'), move_failed: t('Could not move it. Try again.', '没有移动成功,请重试。'), @@ -2271,7 +2325,7 @@ export function openStudio(node, {extendFrom = null} = {}) { missing_node: t('This node is disabled or no longer in the workflow.', '该节点已禁用或已从工作流移除。'), chain_cancel_failed: t('Could not cancel. Refresh the page and try again.', '没有取消成功,请刷新页面后再试。'), chain_resume_failed: t('Could not continue. Refresh the page and try again.', '没有继续生成,请刷新页面后再试。'), - }[error?.message] || (error?.said ? t(error.said[0], error.said[1]) : null) || (isNetworkTypeError(error) ? connectionLostText(t) : error?.message) || String(error)); + }[error?.message] || (error?.said ? t(error.said[0], error.said[1]) : null) || userMessage(error, t)); let lastQueueError = null, connectionNotice = false; watchEngineExit(api).catch(() => {}); function showQueueError(error) { @@ -2307,11 +2361,20 @@ export function openStudio(node, {extendFrom = null} = {}) { if (record && !disposed && !status.textContent) status.textContent = engineExitText(record, t); }).catch(() => {}); } + // A part that did not start says so on its own line; what the server said goes in the card, with a report. + function showChainActionError(error) { + if (disposed) return; + lastQueueError = null; + const report = failure.show(error?.cause || error, false, {stage: 'queue', node, graph: app.graph}); + node.freevideoFailureReport = report; node.freevideoFailure = errorText(report); + } // A part that stopped is one sentence on the status line; what ComfyUI said goes in the card, as a generation failure. function showPartError(error) { if (disposed) return; status.dataset.error = 'true'; - status.textContent = error.joining ? t('Could not join the parts. See the details on the picture.', '未能接合各段,原因见画面上的说明。') + // The server's plain sentence (a full disk, unreadable storage) when it has one; what failed stays in the card. + status.textContent = error.said ? (error.joining ? '' : t(`Part ${error.index + 1}: `, `第 ${error.index + 1} 段:`)) + t(error.said[0], error.said[1]) + : error.joining ? t('Could not join the parts. See the details on the picture.', '未能接合各段,原因见画面上的说明。') : t(`Part ${error.index + 1} could not be generated. See the details on the picture.`, `第 ${error.index + 1} 段未能生成,原因见画面上的说明。`); if (lastQueueError === error.message) return; lastQueueError = error.message; @@ -2916,7 +2979,7 @@ export function openStudio(node, {extendFrom = null} = {}) { if (!open) return false; open.open = false; open.querySelector(':scope>summary')?.focus({preventScroll: true}); return true; }; - dialog.addEventListener('cancel', e => { e.preventDefault(); if (!closeMenu() && !compare.close() && !promptLibrary?.hide() && !consoleUI?.dismiss() && !monitor.dismiss() && !recent.dismiss()) closeDialog(dialog); }); + dialog.addEventListener('cancel', e => { e.preventDefault(); if (!closeMenu() && !compare.close() && !promptLibrary?.hide() && !consoleUI?.dismiss() && !recent.dismiss()) closeDialog(dialog); }); const dispose = () => { if (disposed) return; disposed = true; borrowed?.release({disposing: true}); blockOriginal('extend', false); blockOriginal('preview', false); for (const f of cleanup) f(); stage.querySelector('video')?.pause(); dialog.remove(); if (current?.dialog === dialog) { current = null; viewChanged('nodes', node); } }; const onClose = () => { // Parked behind the node view: everything stays as it is (closeDialog may have taken this handler while a @@ -2929,7 +2992,7 @@ export function openStudio(node, {extendFrom = null} = {}) { // same chips and their rules stay in one place. Pressing Generate runs the editor's submission instead; the values // come from the same node the bar edits. Release puts everything back as it was. let popHolder = null; - current.borrow = ({mount, submit, label = null, disabled = null, onSeconds = null, initial = {}, locked = []}) => { + current.borrow = ({mount, submit, label = null, disabled = null, onSeconds = null, onFirstFrame = null, initial = {}, locked = []}) => { if (borrowed || disposed) return null; const outer = mount.closest('dialog') || document.body; const home = {parent: controls.parentNode, next: controls.nextSibling}; @@ -2952,10 +3015,12 @@ export function openStudio(node, {extendFrom = null} = {}) { // Every setting changed in the bar while it is borrowed (the request is built from these). overrides: () => Object.fromEntries(shadow?.get(node) || []), setLabel: next => { state.labelFn = next; updateRunButton(); }, + // {shown, checked, disabled} from the editor; null gives the switch back to this panel's own rule. + firstFrame: next => { if (!borrowed) return; borrowed.firstFrame = next || null; updateFirstFrame(); }, release({disposing = false} = {}) { if (!borrowed) return; borrowed = null; shadow = null; - unlock(); + unlock(); updateFirstFrame(); shell.remove(); if (!disposing) { if (home.next?.parentNode === home.parent) home.parent.insertBefore(controls, home.next); else home.parent.append(controls); @@ -2964,7 +3029,7 @@ export function openStudio(node, {extendFrom = null} = {}) { updateRunButton(); }}; shadow = new Map(); - borrowed = {submit, label: () => (state.labelFn ?? label)?.(), disabled, onSeconds, applying: false, release: state.release}; + borrowed = {submit, label: () => (state.labelFn ?? label)?.(), disabled, onSeconds, onFirstFrame, firstFrame: null, applying: false, release: state.release}; const unlock = () => { for (const control of lockedNow.splice(0)) { control.disabled = false; delete control.dataset.fvLocked; } for (const element of [framePicker?.element, stepper?.element]) delete element?.dataset.fvLocked; diff --git a/web/studio_chain.js b/web/studio_chain.js index 270c87f5..02005eaa 100644 --- a/web/studio_chain.js +++ b/web/studio_chain.js @@ -28,8 +28,16 @@ export function readChainResult(chain) { const last = chain.blocks?.filter(block => block.state === 'done' && block.output).at(-1); const joined = chain.output_state === 'done' && typeof chain.output === 'string' && Boolean(chain.output); const video = joined ? chain.output : !joining && (failedJoin || stopped) ? last?.output || null : null; + const failedBlock = failedJoin || chain.error ? null : chain.blocks?.find(block => block.state === 'failed'); return {video, joined, joining, partial: Boolean(video) && (!joined || stopped), - error: failedJoin ? chain.output_error || 'join_failed' : chain.error || chain.blocks?.find(block => block.state === 'failed')?.error || null}; + error: failedJoin ? chain.output_error || 'join_failed' : chain.error || failedBlock?.error || null, + said: failedJoin ? chainSaid(chain.output_error_code, chain.output_error_en, chain.output_error_zh) + : chainSaid(failedBlock?.code, failedBlock?.error_en, failedBlock?.error_zh)}; +} +// The server's plain sentence for a failure, [English, Chinese], when it has one. A part that only failed to generate +// keeps the page's own reading of the original error (the error card names the cause better than a general sentence). +export function chainSaid(code, en, zh) { + return code !== 'generation_failed' && typeof en === 'string' && en && typeof zh === 'string' && zh ? [en, zh] : null; } // Before the first part starts the server writes one description per part; until then no part can be changed. @@ -105,7 +113,9 @@ export function createStudioChain({api, node, onState = () => {}, onProgress = ( if (response.status === 404 && allowMissing) return null; const value = await response.json().catch(() => ({})); if (!response.ok) throw Object.assign(new Error(value.error || 'chain_request_failed'), {code: value.code, status: response.status, - ...(value.error_zh ? {said: [value.error, value.error_zh]} : {})}); + ...(value.error_zh ? {said: [value.error, value.error_zh]} : {}), + // The original text goes to the technical details of the error card, never to the sentence. + ...(typeof value.detail === 'string' && value.detail ? {details: value.detail} : {})}); return value; } function progress(message = {}, fresh = false) { @@ -141,7 +151,8 @@ export function createStudioChain({api, node, onState = () => {}, onProgress = ( if (active()) progress({}, fresh); else if (waiting.length) void promote(); if (result.error && errorShown !== result.error) { - errorShown = result.error; onError(Object.assign(new Error(result.error), {joining: chain.output_state === 'failed', ...chainPosition(chain)})); + errorShown = result.error; onError(Object.assign(new Error(result.error), {joining: chain.output_state === 'failed', ...chainPosition(chain), + ...(result.said ? {said: result.said} : {})})); } // Continuing a stopped chain can write the joined video to the path already shown. const version = `${chain.blocks?.filter(block => block.state === 'done').length || 0}-${result.joined ? 'joined' : 'part'}`; @@ -235,7 +246,8 @@ export function createStudioChain({api, node, onState = () => {}, onProgress = ( } } catch {} // Keep the last known state; the action still fails visibly. } - throw Object.assign(new Error(`chain_${action}_failed`), {cause, action, status: cause.status}); + throw Object.assign(new Error(`chain_${action}_failed`), {cause, action, status: cause.status, + ...(cause?.said ? {said: cause.said} : {}), ...(cause?.details ? {details: cause.details} : {})}); } } recover(); diff --git a/web/studio_header_fit.js b/web/studio_header_fit.js index 40b827b5..89182bd1 100644 --- a/web/studio_header_fit.js +++ b/web/studio_header_fit.js @@ -1,9 +1,8 @@ import {placeViewSwitch} from './view_switch_place.js'; // The view switch takes the place every view shares (view_switch_place.js). Beside it, the creation panel's logo takes -// its smaller size when its side is narrower; the entries give way in order: the status capsule's words, the capsule, -// the phone entry, the feedback entry, and the Tutorial entry last. On two rows the capsule starts gone and the same -// entries leave in that order. +// its smaller size when its side is narrower; the entries give way in order: the phone entry, the feedback entry, and +// the Tutorial entry last. On two rows the same entries leave in that order. export function fitStudioHeader(header, brand, navigation, actions) { if (typeof ResizeObserver !== 'function' || typeof getComputedStyle !== 'function' || typeof matchMedia !== 'function') return {check() {}, dispose() {}}; const px = value => parseFloat(value) || 0; @@ -16,8 +15,7 @@ export function fitStudioHeader(header, brand, navigation, actions) { const need = shown.reduce((sum, child) => sum + Math.max(child.getBoundingClientRect().width, child.scrollWidth), 0) + apart * Math.max(0, shown.length - 1); const width = selector => { const found = actions.querySelector(selector); return found && found.offsetWidth > 0 ? found.offsetWidth + apart : 0; }; const away = width('.fv-lan'), spare = width('.fv-feedback-entry:not(.fv-guide-entry)'), last = width('.fv-guide-entry'); - const capsule = width('.fv-monitor'), label = actions.querySelector('.fv-monitor-text'), words = label && label.offsetWidth > 0 ? label.offsetWidth + px(getComputedStyle(label.parentElement).columnGap) : 0; - const order = [['compact', words], ['gone', capsule - words], ['tight', away], ['lean', spare], ['least', last]]; + const order = [['tight', away], ['lean', spare], ['least', last]]; const tokens = []; let room, left = need; if (place.wrap) { @@ -25,8 +23,8 @@ export function fitStudioHeader(header, brand, navigation, actions) { const items = [...brand.children].filter(child => child.offsetWidth > 0); const mark = items.reduce((sum, child) => sum + child.getBoundingClientRect().width, 0) + px(getComputedStyle(brand).columnGap) * Math.max(0, items.length - 1); room = place.inner - mark - place.gap; - tokens.push('wrap', 'gone'); left -= capsule; - for (const [token, saved] of order.slice(2)) { if (left <= room) break; left -= saved; tokens.push(token); } + tokens.push('wrap'); + for (const [token, saved] of order) { if (left <= room) break; left -= saved; tokens.push(token); } } else { const logo = brand.querySelector('.fv-wordmark'); if (logo && logo.offsetWidth > place.left) tokens.push('small'); diff --git a/web/studio_queue.js b/web/studio_queue.js index b0222d30..c68d7b1f 100644 --- a/web/studio_queue.js +++ b/web/studio_queue.js @@ -96,6 +96,22 @@ export async function upscaleResult(api, nodeId, result, currentPrompt) { return reply.prompt_id; } +// Upscale a finished video by one step into a new creation. The bridge reads the source's own saved +// description and length; the node's current settings only carry the request through the queue. +// {to: '4k'} asks for the 4K size, made frame by frame by a small model instead of one 1.5× step. +export async function upscaleWork(api, nodeId, result, currentPrompt, {to = ''} = {}) { + nodeId = String(nodeId); + if (!result?.video || result.preview) throw new Error('not_finished'); + if (to !== '' && to !== '4k') throw new Error('unknown_size'); + const snapshot = clone(await currentPrompt()); + if (!snapshot.output?.[nodeId]) throw new Error('missing_node'); + Object.assign(snapshot.output[nodeId].inputs, {preview: false, refine_from: '', upscale_from: result.video, upscale_to: to, force_regenerate: true}); + const reply = await api.queuePrompt(0, snapshot); + if (!reply?.prompt_id) throw new Error('submit_failed'); + api.dispatchCustomEvent?.('promptQueued', {number: 0, batchCount: 1}); + return reply.prompt_id; +} + // Each preview owns its submission outcome; another preview waits its turn. // Only duplicate clicks for the same pending preview share a promise. export function createSecondPassQueue(api, nodeId, currentPrompt) { diff --git a/web/task_float.js b/web/task_float.js index 0f0e5b77..791f9739 100644 --- a/web/task_float.js +++ b/web/task_float.js @@ -5,7 +5,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, ACTIVE, FINAL } from './task_store.js'; +import { jobs, imageSource, progressSource, chainSource, queueSource, journalSource, ACTIVE, FINAL } from './task_store.js'; import { createImageGenClient, imageGenError, imageReportBar } from './image_generation.js'; import { saveGeneratedImage } from './image_library.js'; @@ -54,6 +54,8 @@ export function startJobSources() { }).catch(() => {}); chainSource(jobs, {fetchJson: async path => { const response = await api.fetchApi(path, {cache: 'no-store'}); if (!response.ok) throw new Error('chains'); return response.json(); }, cancel: row => api.fetchApi(`/freevideo/chain/${encodeURIComponent(row.id.slice('chain:'.length))}/cancel`, post({})).then(sent)}); + // Jobs that ended while this page was closed or the engine restarted, from the server's own record. + journalSource(jobs, {storage, fetchJson: async path => { const response = await api.fetchApi(path, {cache: 'no-store'}); if (!response.ok) throw new Error('jobs'); return response.json(); }}); // A finished picture is filed by the store, not by the page that started it, so it lands even with that page closed. // (Until the engine files it itself, a tab closed mid-run still misses the card; the picture is in the history.) // Two tabs of the same page both follow a picture started in one of them; only the first to see it end files it. diff --git a/web/task_store.js b/web/task_store.js index a61108d7..e6a73792 100644 --- a/web/task_store.js +++ b/web/task_store.js @@ -5,9 +5,10 @@ // eta_seconds, created_at, started_at, finished_at, prompt, result, failure, cancellable, position, model. // Three local fields ride along and are kept in this browser only: view (where to go back to), meta, seen. // -// That endpoint does not exist yet, so the rows come from sources that read today's interfaces: the picture -// worker's status (imageSource), the progress stream the page already receives (progressSource) and the list -// of long videos (chainSource). Moving to /freevideo/jobs replaces those three and nothing else. +// Running and waiting rows come from the live sources: the picture worker's status (imageSource), the progress stream +// the page already receives (progressSource), the engine's queue (queueSource) and the list of long videos +// (chainSource). Finished jobs come from one place, the server's own record behind GET /freevideo/jobs +// (journalSource): it outlives a reload and a restart, and another device sees the same jobs end. // No imports: the store and its sources run under Node for the unit tests. export const LOCAL_KEY = 'freevideo.jobs.local'; @@ -74,7 +75,8 @@ export function createJobStore({now = () => Date.now(), storage = null} = {}) { // Merges what a source knows into the row. A finished row stays finished unless the source says it runs // again (a long video continued after a stop); a late progress message cannot revive it. // force: the store itself puts a row back (a cancel the engine refused). - function upsert(patch, {revive = false, force = false} = {}) { + // quiet: a job that ended before this page knew of it (journalSource) is listed without a done or failed event. + function upsert(patch, {revive = false, force = false, quiet = false} = {}) { if (!patch?.id) throw new Error('job_id_required'); let previous = rows.get(patch.id); const before = previous; @@ -102,8 +104,8 @@ export function createJobStore({now = () => Date.now(), storage = null} = {}) { if (patch.view != null) { local[row.id] = plain({...mine, at, view: patch.view}); saveLocal(); } const frozen = rows.get(row.id); publish({type: before ? 'update' : 'add', row: frozen, previous: before}); - if (ended && row.status === 'done') fire('done', Object.freeze({...row})); - if (ended && row.status === 'failed') fire('failed', Object.freeze({...row})); + if (ended && !quiet && row.status === 'done') fire('done', Object.freeze({...row})); + if (ended && !quiet && row.status === 'failed') fire('failed', Object.freeze({...row})); return frozen; } // Only this browser's fields: where the job came from, what to show for it, whether it was seen. @@ -454,4 +456,47 @@ export function chainSource(store, {fetchJson, interval = 3000, idle = 0, setTim } // The page's one store. Sources are attached by task_float.js, which runs in the page. +// ---------- Jobs that ended, from the server's record (GET /freevideo/jobs) ---------- +// The server writes one line when a generation ends (freevideo_engine/job_record.py): no prompt, no file name, only +// ids, codes, times and a saved video's library id. A job this page has no row for, that ended within maxAgeMs and that +// this browser has not seen, is listed as finished, quietly (no notification for news the person already missed). Rows +// this page already has keep their live source, which ends them itself. The Agent's jobs stay in its own view. +export function journalSource(store, {fetchJson, storage = null, interval = 30000, maxAgeMs = 6 * 3600e3, now = store.now, + setTimer = setTimeout, clearTimer = clearTimeout} = {}) { + let timer = 0, disposed = false, reading = null; + const PREFIX = {video: 'video:', chain: 'chain:'}; + function idOf(entry) { + if (entry.kind === 'image') { + // A picture started on this browser keeps its worker key beside the row id (imageSource). + const local = Object.entries(readJSON(storage, IMAGE_KEY)).find(([, value]) => value?.job === entry.id); + return local ? local[0] : 'image:' + entry.id; + } + return PREFIX[entry.kind] ? PREFIX[entry.kind] + entry.id : null; + } + function apply(entry) { + if (!entry || typeof entry.id !== 'string' || !FINAL.has(entry.status) || entry.origin === 'agent') return; + const id = idOf(entry); + if (!id || store.get(id) || store.localOf(id)?.seen) return; + const finished = finite(entry.finished_at) ? entry.finished_at * 1000 : null; + if (!finished || now() - finished > maxAgeMs) return; + store.upsert({id, kind: entry.kind, source: entry.kind, status: entry.status, origin: 'page', cancellable: false, prompt: '', + finished_at: finished, ...(finite(entry.created_at) ? {created_at: entry.created_at * 1000} : {}), + ...(finite(entry.started_at) ? {started_at: entry.started_at * 1000} : {}), + ...(typeof entry.result === 'string' ? {result: {work: entry.result}} : {}), + ...(typeof entry.failure === 'string' ? {failure: {code: entry.failure}} : {})}, {quiet: true}); + } + async function read() { + if (reading) return reading; + reading = (async () => { + try { const value = await fetchJson('/freevideo/jobs'); for (const entry of value?.jobs || []) apply(entry); } + catch { /* An older engine or a passing error: the live sources still list what runs. */ } + })().finally(() => { reading = null; if (!disposed && interval) { clearTimer(timer); timer = setTimer(read, interval); } }); + return reading; + } + const source = {refresh: read, dispose() { disposed = true; clearTimer(timer); }}; + store.addSource('journal', source); + void read(); + return source; +} + export const jobs = createJobStore({storage: (() => { try { return globalThis.localStorage || null; } catch { return null; } })()}); diff --git a/web/tooltip_copy.js b/web/tooltip_copy.js index 4d50e691..1d0416b0 100644 --- a/web/tooltip_copy.js +++ b/web/tooltip_copy.js @@ -23,9 +23,6 @@ export const TIPS = { 'top.feedback': {name: ['Feedback', '反馈'], use: ['Tell us what went wrong or could be better', '告诉我们问题或建议']}, 'top.settings': {name: ['Settings', '设置'], use: ['Models, storage, language and notifications', '模型、存储位置、语言和通知']}, 'top.assistant': {name: ['Assistant activity', '助手动态'], use: ['What the connected AI assistant is doing', '已连接的 AI 助手正在做什么']}, - 'top.monitor': {name: ['Status', '运行状态'], use: ['Graphics memory, memory and the queue, live', '显存、内存和排队的实时情况']}, - 'monitor.resume': {name: ['Resume queue', '继续队列'], use: ['Start the waiting videos again', '让排队的视频接着生成']}, - 'monitor.stop': {name: ['Stop now', '立即停止'], use: ['Stop this video and pause the queue', '停掉当前视频并暂停队列']}, 'update.notes': {name: ['What’s new', '更新内容'], use: ['See what this update changes', '查看这次更新改了什么']}, 'update.later': {name: ['Later', '稍后'], use: ['Keep this version for now', '暂不更新,继续用当前版本']}, 'update.cancel': {name: ['Cancel update', '取消更新'], use: ['Stop downloading this update', '停止下载这次更新']}, @@ -254,7 +251,6 @@ export const MATCHES = [ ['.fv-guide-entry', 'top.guide'], ['.fv-feedback-entry:not(.fv-guide-entry)', 'top.feedback'], ['.fv-settings-entry', 'top.settings'], ['.fv-agent-activity button,.fv-agent-activity,.fv-agent-pill', 'top.assistant'], - ['.fv-monitor-trigger', 'top.monitor'], ['.fv-monitor-resume', 'monitor.resume'], ['.fv-monitor-stop', 'monitor.stop'], // Create. ['.fv-runrow>.fv-primary', 'studio.generate'], ['.fv-run-options>summary', 'studio.mode'], diff --git a/web/tutorial/autopilot-1.webp b/web/tutorial/autopilot-1.webp index f38fdadc..2a03bd5f 100644 Binary files a/web/tutorial/autopilot-1.webp and b/web/tutorial/autopilot-1.webp differ diff --git a/web/tutorial/autopilot-2.webp b/web/tutorial/autopilot-2.webp index d67aa684..ea688aa5 100644 Binary files a/web/tutorial/autopilot-2.webp and b/web/tutorial/autopilot-2.webp differ diff --git a/web/tutorial/beat-snap-1.webp b/web/tutorial/beat-snap-1.webp index 07198a58..a9c1b183 100644 Binary files a/web/tutorial/beat-snap-1.webp and b/web/tutorial/beat-snap-1.webp differ diff --git a/web/tutorial/beat-snap-2.webp b/web/tutorial/beat-snap-2.webp index 2cc28345..9eb099c3 100644 Binary files a/web/tutorial/beat-snap-2.webp and b/web/tutorial/beat-snap-2.webp differ diff --git a/web/tutorial/cast-sheet-1.webp b/web/tutorial/cast-sheet-1.webp index 70d177c2..37751439 100644 Binary files a/web/tutorial/cast-sheet-1.webp and b/web/tutorial/cast-sheet-1.webp differ diff --git a/web/tutorial/cast-sheet-2.webp b/web/tutorial/cast-sheet-2.webp index b536311d..0878a915 100644 Binary files a/web/tutorial/cast-sheet-2.webp and b/web/tutorial/cast-sheet-2.webp differ diff --git a/web/tutorial/continue-or-new-shot-1.webp b/web/tutorial/continue-or-new-shot-1.webp index 67138dcd..d8890606 100644 Binary files a/web/tutorial/continue-or-new-shot-1.webp and b/web/tutorial/continue-or-new-shot-1.webp differ diff --git a/web/tutorial/continue-or-new-shot-2.webp b/web/tutorial/continue-or-new-shot-2.webp index 085023e4..1d5fdd3b 100644 Binary files a/web/tutorial/continue-or-new-shot-2.webp and b/web/tutorial/continue-or-new-shot-2.webp differ diff --git a/web/tutorial/drama-outline-1.webp b/web/tutorial/drama-outline-1.webp index 694631a7..d0765b38 100644 Binary files a/web/tutorial/drama-outline-1.webp and b/web/tutorial/drama-outline-1.webp differ diff --git a/web/tutorial/drama-outline-2.webp b/web/tutorial/drama-outline-2.webp index ac3cf1dd..6c96a8af 100644 Binary files a/web/tutorial/drama-outline-2.webp and b/web/tutorial/drama-outline-2.webp differ diff --git a/web/tutorial/edit-image-1.webp b/web/tutorial/edit-image-1.webp index 35a8f438..81eb6cbb 100644 Binary files a/web/tutorial/edit-image-1.webp and b/web/tutorial/edit-image-1.webp differ diff --git a/web/tutorial/edit-image-2.webp b/web/tutorial/edit-image-2.webp index f3e09298..e6176746 100644 Binary files a/web/tutorial/edit-image-2.webp and b/web/tutorial/edit-image-2.webp differ diff --git a/web/tutorial/editor-1.webp b/web/tutorial/editor-1.webp index 75f87148..d75e3ecd 100644 Binary files a/web/tutorial/editor-1.webp and b/web/tutorial/editor-1.webp differ diff --git a/web/tutorial/editor-2.webp b/web/tutorial/editor-2.webp index cde732a8..6494ad77 100644 Binary files a/web/tutorial/editor-2.webp and b/web/tutorial/editor-2.webp differ diff --git a/web/tutorial/editor-extend-refs-1.webp b/web/tutorial/editor-extend-refs-1.webp index 3fbc5ec3..cbb1f755 100644 Binary files a/web/tutorial/editor-extend-refs-1.webp and b/web/tutorial/editor-extend-refs-1.webp differ diff --git a/web/tutorial/editor-extend-refs-2.webp b/web/tutorial/editor-extend-refs-2.webp index 74ccf99b..4db068a9 100644 Binary files a/web/tutorial/editor-extend-refs-2.webp and b/web/tutorial/editor-extend-refs-2.webp differ diff --git a/web/tutorial/extend-video-1.webp b/web/tutorial/extend-video-1.webp index f3f48287..270a1866 100644 Binary files a/web/tutorial/extend-video-1.webp and b/web/tutorial/extend-video-1.webp differ diff --git a/web/tutorial/extend-video-2.webp b/web/tutorial/extend-video-2.webp index 40214207..883fb5ec 100644 Binary files a/web/tutorial/extend-video-2.webp and b/web/tutorial/extend-video-2.webp differ diff --git a/web/tutorial/film-project-1.webp b/web/tutorial/film-project-1.webp index b1f7101a..502c4c81 100644 Binary files a/web/tutorial/film-project-1.webp and b/web/tutorial/film-project-1.webp differ diff --git a/web/tutorial/film-project-2.webp b/web/tutorial/film-project-2.webp index 82e8980c..09e37eac 100644 Binary files a/web/tutorial/film-project-2.webp and b/web/tutorial/film-project-2.webp differ diff --git a/web/tutorial/first-last-frame-1.webp b/web/tutorial/first-last-frame-1.webp index 0d123e60..57469fcf 100644 Binary files a/web/tutorial/first-last-frame-1.webp and b/web/tutorial/first-last-frame-1.webp differ diff --git a/web/tutorial/first-last-frame-2.webp b/web/tutorial/first-last-frame-2.webp index 840531da..b480c24e 100644 Binary files a/web/tutorial/first-last-frame-2.webp and b/web/tutorial/first-last-frame-2.webp differ diff --git a/web/tutorial/image-gen-1.webp b/web/tutorial/image-gen-1.webp index f0c38b15..49f8dec5 100644 Binary files a/web/tutorial/image-gen-1.webp and b/web/tutorial/image-gen-1.webp differ diff --git a/web/tutorial/image-gen-2.webp b/web/tutorial/image-gen-2.webp index 5c946c11..2bedc81e 100644 Binary files a/web/tutorial/image-gen-2.webp and b/web/tutorial/image-gen-2.webp differ diff --git a/web/tutorial/image-references-1.webp b/web/tutorial/image-references-1.webp index d2ac57bf..3c91452c 100644 Binary files a/web/tutorial/image-references-1.webp and b/web/tutorial/image-references-1.webp differ diff --git a/web/tutorial/image-references-2.webp b/web/tutorial/image-references-2.webp index dd13728f..2147f4e8 100644 Binary files a/web/tutorial/image-references-2.webp and b/web/tutorial/image-references-2.webp differ diff --git a/web/tutorial/library-export-1.webp b/web/tutorial/library-export-1.webp index e73840c9..f6b23c2a 100644 Binary files a/web/tutorial/library-export-1.webp and b/web/tutorial/library-export-1.webp differ diff --git a/web/tutorial/library-export-2.webp b/web/tutorial/library-export-2.webp index 0326548b..f6b23c2a 100644 Binary files a/web/tutorial/library-export-2.webp and b/web/tutorial/library-export-2.webp differ diff --git a/web/tutorial/library-reuse-1.webp b/web/tutorial/library-reuse-1.webp index 7e0fc681..9b20dcc9 100644 Binary files a/web/tutorial/library-reuse-1.webp and b/web/tutorial/library-reuse-1.webp differ diff --git a/web/tutorial/library-reuse-2.webp b/web/tutorial/library-reuse-2.webp index e63f856d..41233ca6 100644 Binary files a/web/tutorial/library-reuse-2.webp and b/web/tutorial/library-reuse-2.webp differ diff --git a/web/tutorial/local-image-edit-1.webp b/web/tutorial/local-image-edit-1.webp index dee59486..4ce45502 100644 Binary files a/web/tutorial/local-image-edit-1.webp and b/web/tutorial/local-image-edit-1.webp differ diff --git a/web/tutorial/local-image-edit-2.webp b/web/tutorial/local-image-edit-2.webp index de87c9fc..c3a9289b 100644 Binary files a/web/tutorial/local-image-edit-2.webp and b/web/tutorial/local-image-edit-2.webp differ diff --git a/web/tutorial/long-video-1.webp b/web/tutorial/long-video-1.webp index 2cc8bd60..cc5d01dd 100644 Binary files a/web/tutorial/long-video-1.webp and b/web/tutorial/long-video-1.webp differ diff --git a/web/tutorial/long-video-2.webp b/web/tutorial/long-video-2.webp index 046a8fa9..b6910a84 100644 Binary files a/web/tutorial/long-video-2.webp and b/web/tutorial/long-video-2.webp differ diff --git a/web/tutorial/lora-1.webp b/web/tutorial/lora-1.webp index 471a314e..c6780d8b 100644 Binary files a/web/tutorial/lora-1.webp and b/web/tutorial/lora-1.webp differ diff --git a/web/tutorial/lora-2.webp b/web/tutorial/lora-2.webp index f1ea4d14..452ac6b8 100644 Binary files a/web/tutorial/lora-2.webp and b/web/tutorial/lora-2.webp differ diff --git a/web/tutorial/middle-frames-1.webp b/web/tutorial/middle-frames-1.webp index b5bbd693..3a46018f 100644 Binary files a/web/tutorial/middle-frames-1.webp and b/web/tutorial/middle-frames-1.webp differ diff --git a/web/tutorial/middle-frames-2.webp b/web/tutorial/middle-frames-2.webp index c0f468ad..c77283b0 100644 Binary files a/web/tutorial/middle-frames-2.webp and b/web/tutorial/middle-frames-2.webp differ diff --git a/web/tutorial/narration-1.webp b/web/tutorial/narration-1.webp index 24202b0f..858e2200 100644 Binary files a/web/tutorial/narration-1.webp and b/web/tutorial/narration-1.webp differ diff --git a/web/tutorial/narration-2.webp b/web/tutorial/narration-2.webp index 6f8fd361..09dc8f6d 100644 Binary files a/web/tutorial/narration-2.webp and b/web/tutorial/narration-2.webp differ diff --git a/web/tutorial/new-image-shape-1.webp b/web/tutorial/new-image-shape-1.webp index e3dbcf6c..683af774 100644 Binary files a/web/tutorial/new-image-shape-1.webp and b/web/tutorial/new-image-shape-1.webp differ diff --git a/web/tutorial/new-image-shape-2.webp b/web/tutorial/new-image-shape-2.webp index 84b9d921..15a55aeb 100644 Binary files a/web/tutorial/new-image-shape-2.webp and b/web/tutorial/new-image-shape-2.webp differ diff --git a/web/tutorial/offline-reimport-1.webp b/web/tutorial/offline-reimport-1.webp index 07428441..215fc6f8 100644 Binary files a/web/tutorial/offline-reimport-1.webp and b/web/tutorial/offline-reimport-1.webp differ diff --git a/web/tutorial/offline-reimport-2.webp b/web/tutorial/offline-reimport-2.webp index 8a674808..14b26ef1 100644 Binary files a/web/tutorial/offline-reimport-2.webp and b/web/tutorial/offline-reimport-2.webp differ diff --git a/web/tutorial/quality-tiers-1.webp b/web/tutorial/quality-tiers-1.webp index b45b119e..58cabae0 100644 Binary files a/web/tutorial/quality-tiers-1.webp and b/web/tutorial/quality-tiers-1.webp differ diff --git a/web/tutorial/quality-tiers-2.webp b/web/tutorial/quality-tiers-2.webp index 85e2744f..049a76f0 100644 Binary files a/web/tutorial/quality-tiers-2.webp and b/web/tutorial/quality-tiers-2.webp differ diff --git a/web/tutorial/quick-start-1.webp b/web/tutorial/quick-start-1.webp index 83a8362f..ba469268 100644 Binary files a/web/tutorial/quick-start-1.webp and b/web/tutorial/quick-start-1.webp differ diff --git a/web/tutorial/quick-start-2.webp b/web/tutorial/quick-start-2.webp index 670dfa31..ca2ebe0d 100644 Binary files a/web/tutorial/quick-start-2.webp and b/web/tutorial/quick-start-2.webp differ diff --git a/web/tutorial/reference-video-1.webp b/web/tutorial/reference-video-1.webp index a7008987..fcf5f5a0 100644 Binary files a/web/tutorial/reference-video-1.webp and b/web/tutorial/reference-video-1.webp differ diff --git a/web/tutorial/reference-video-2.webp b/web/tutorial/reference-video-2.webp index 034a6a9d..d31c2256 100644 Binary files a/web/tutorial/reference-video-2.webp and b/web/tutorial/reference-video-2.webp differ diff --git a/web/tutorial/refine-1.webp b/web/tutorial/refine-1.webp index c929b9f4..8dc16cae 100644 Binary files a/web/tutorial/refine-1.webp and b/web/tutorial/refine-1.webp differ diff --git a/web/tutorial/refine-2.webp b/web/tutorial/refine-2.webp index 8e90e172..58296c7f 100644 Binary files a/web/tutorial/refine-2.webp and b/web/tutorial/refine-2.webp differ diff --git a/web/tutorial/replace-music-1.webp b/web/tutorial/replace-music-1.webp index 0eac9704..f7e8f144 100644 Binary files a/web/tutorial/replace-music-1.webp and b/web/tutorial/replace-music-1.webp differ diff --git a/web/tutorial/replace-music-2.webp b/web/tutorial/replace-music-2.webp index da930710..6938ff41 100644 Binary files a/web/tutorial/replace-music-2.webp and b/web/tutorial/replace-music-2.webp differ diff --git a/web/tutorial/replace-two-people-1.webp b/web/tutorial/replace-two-people-1.webp index c984c073..329c3a55 100644 Binary files a/web/tutorial/replace-two-people-1.webp and b/web/tutorial/replace-two-people-1.webp differ diff --git a/web/tutorial/replace-two-people-2.webp b/web/tutorial/replace-two-people-2.webp index 354e88e3..97b41eb1 100644 Binary files a/web/tutorial/replace-two-people-2.webp and b/web/tutorial/replace-two-people-2.webp differ diff --git a/web/tutorial/save-frame-1.webp b/web/tutorial/save-frame-1.webp index be098a8b..74227785 100644 Binary files a/web/tutorial/save-frame-1.webp and b/web/tutorial/save-frame-1.webp differ diff --git a/web/tutorial/save-frame-2.webp b/web/tutorial/save-frame-2.webp index 9935b21d..b9ad01a1 100644 Binary files a/web/tutorial/save-frame-2.webp and b/web/tutorial/save-frame-2.webp differ diff --git a/web/tutorial/scenes-props-1.webp b/web/tutorial/scenes-props-1.webp index 3098fcc5..ba669867 100644 Binary files a/web/tutorial/scenes-props-1.webp and b/web/tutorial/scenes-props-1.webp differ diff --git a/web/tutorial/scenes-props-2.webp b/web/tutorial/scenes-props-2.webp index b799292b..b2dfaf90 100644 Binary files a/web/tutorial/scenes-props-2.webp and b/web/tutorial/scenes-props-2.webp differ diff --git a/web/tutorial/segment-prompt-1.webp b/web/tutorial/segment-prompt-1.webp index 25d32c5e..6e16cf96 100644 Binary files a/web/tutorial/segment-prompt-1.webp and b/web/tutorial/segment-prompt-1.webp differ diff --git a/web/tutorial/segment-prompt-2.webp b/web/tutorial/segment-prompt-2.webp index 15f563e7..e558ded0 100644 Binary files a/web/tutorial/segment-prompt-2.webp and b/web/tutorial/segment-prompt-2.webp differ diff --git a/web/tutorial/separate-tracks-1.webp b/web/tutorial/separate-tracks-1.webp index 2893c62d..7c47ede2 100644 Binary files a/web/tutorial/separate-tracks-1.webp and b/web/tutorial/separate-tracks-1.webp differ diff --git a/web/tutorial/separate-tracks-2.webp b/web/tutorial/separate-tracks-2.webp index 7b675dee..6fb6a246 100644 Binary files a/web/tutorial/separate-tracks-2.webp and b/web/tutorial/separate-tracks-2.webp differ diff --git a/web/tutorial/sound-to-picture-1.webp b/web/tutorial/sound-to-picture-1.webp index 5503d943..303bb538 100644 Binary files a/web/tutorial/sound-to-picture-1.webp and b/web/tutorial/sound-to-picture-1.webp differ diff --git a/web/tutorial/sound-to-picture-2.webp b/web/tutorial/sound-to-picture-2.webp index bbf81967..c9cdb863 100644 Binary files a/web/tutorial/sound-to-picture-2.webp and b/web/tutorial/sound-to-picture-2.webp differ diff --git a/web/tutorial/system-status-1.webp b/web/tutorial/system-status-1.webp index 60a76480..c2a4bb98 100644 Binary files a/web/tutorial/system-status-1.webp and b/web/tutorial/system-status-1.webp differ diff --git a/web/tutorial/system-status-2.webp b/web/tutorial/system-status-2.webp index 79b8fb4b..4c9b6101 100644 Binary files a/web/tutorial/system-status-2.webp and b/web/tutorial/system-status-2.webp differ diff --git a/web/tutorial/text-subtitles-1.webp b/web/tutorial/text-subtitles-1.webp index 40b7a143..9e384917 100644 Binary files a/web/tutorial/text-subtitles-1.webp and b/web/tutorial/text-subtitles-1.webp differ diff --git a/web/tutorial/text-subtitles-2.webp b/web/tutorial/text-subtitles-2.webp index 578cb2cb..45d9c1f1 100644 Binary files a/web/tutorial/text-subtitles-2.webp and b/web/tutorial/text-subtitles-2.webp differ diff --git a/web/tutorial/text-to-video-1.webp b/web/tutorial/text-to-video-1.webp index 125bfead..2b1f120c 100644 Binary files a/web/tutorial/text-to-video-1.webp and b/web/tutorial/text-to-video-1.webp differ diff --git a/web/tutorial/text-to-video-2.webp b/web/tutorial/text-to-video-2.webp index cd9c17d0..eab4895b 100644 Binary files a/web/tutorial/text-to-video-2.webp and b/web/tutorial/text-to-video-2.webp differ diff --git a/web/tutorial/timed-lines-1.webp b/web/tutorial/timed-lines-1.webp index f709f45b..67b0e623 100644 Binary files a/web/tutorial/timed-lines-1.webp and b/web/tutorial/timed-lines-1.webp differ diff --git a/web/tutorial/timed-lines-2.webp b/web/tutorial/timed-lines-2.webp index 944d66ec..bc79b44a 100644 Binary files a/web/tutorial/timed-lines-2.webp and b/web/tutorial/timed-lines-2.webp differ diff --git a/web/tutorial/troubleshoot-1.webp b/web/tutorial/troubleshoot-1.webp index c4ee8808..9d0e3a54 100644 Binary files a/web/tutorial/troubleshoot-1.webp and b/web/tutorial/troubleshoot-1.webp differ diff --git a/web/tutorial/troubleshoot-2.webp b/web/tutorial/troubleshoot-2.webp index e8b27602..a0e7a244 100644 Binary files a/web/tutorial/troubleshoot-2.webp and b/web/tutorial/troubleshoot-2.webp differ diff --git a/web/tutorial/voice-recording-1.webp b/web/tutorial/voice-recording-1.webp index 3badd6ad..ee0de8c2 100644 Binary files a/web/tutorial/voice-recording-1.webp and b/web/tutorial/voice-recording-1.webp differ diff --git a/web/tutorial/voice-recording-2.webp b/web/tutorial/voice-recording-2.webp index 4ea0f537..fac6b832 100644 Binary files a/web/tutorial/voice-recording-2.webp and b/web/tutorial/voice-recording-2.webp differ diff --git a/web/tutorial_book.js b/web/tutorial_book.js index 83952b05..6237e0b8 100644 --- a/web/tutorial_book.js +++ b/web/tutorial_book.js @@ -306,6 +306,19 @@ export function openTutorialBook({chapter = TUTORIAL_CHAPTERS[0].id, tab = 'chap } if (!result.ok && dialog.isConnected) { state.note = text[{view: 'noView', hidden: 'noHidden'}[result.reason] || 'noTarget']; const note = page.querySelector('.fv-book-note'); if (note) { note.textContent = state.note; note.hidden = false; note.scrollIntoView({block: 'nearest'}); } } } + // A view that has just opened may not have turned its box on yet (the chat does once it has read the conversation); + // the caret goes there as soon as it is on, unless the user has put focus somewhere else meanwhile. + function focusWhenOn(box) { + if (!box.disabled) { box.focus(); return; } + const watch = new MutationObserver(() => { + if (box.disabled) return; + watch.disconnect(); clearTimeout(stop); + const at = document.activeElement; + if (!at || at === document.body || at.closest('.fv-view-switch')) box.focus(); + }); + const stop = setTimeout(() => watch.disconnect(), 5000); + watch.observe(box, {attributes: true, attributeFilter: ['disabled']}); + } function drawExamples() { const box = el('div', 'fv-book-ex'); const hero = el('div', 'fv-book-hero'), art = el('div', 'fv-book-art'), img = el('img'); img.alt = ''; img.src = SHOWCASE_ASSET; art.append(img); @@ -315,7 +328,7 @@ export function openTutorialBook({chapter = TUTORIAL_CHAPTERS[0].id, tab = 'chap dialog.close(); await globalThis.FreeVideoShell?.go?.('autopilot'); const box = document.querySelector('dialog.fv-autopilot[open] textarea'); - if (box && !box.value.trim()) { box.value = L(SHOWCASE_TEXT.example); box.dispatchEvent(new Event('input', {bubbles: true})); box.focus(); } + if (box && !box.value.trim()) { box.value = L(SHOWCASE_TEXT.example); box.dispatchEvent(new Event('input', {bubbles: true})); focusWhenOn(box); } }; words.append(begin); hero.append(art, words); box.append(hero); const grid = el('div', 'fv-book-grid'), ready = new Set(readyCards().map(c => c.id)); diff --git a/web/tutorial_book_content.js b/web/tutorial_book_content.js index 995e758f..0cd63c90 100644 --- a/web/tutorial_book_content.js +++ b/web/tutorial_book_content.js @@ -29,15 +29,15 @@ export const TUTORIAL_CHAPTERS = [ id: 'text-to-video', goto: ['prompt-box'], title: {zh: '文字生成视频', en: 'Make a video from text'}, - summary: {zh: '用文字描述镜头,并选择画幅、清晰度和时长。', en: 'Describe the shot, then choose the shape, resolution and length.'}, + summary: {zh: '用文字描述镜头,并选择画幅、尺寸和时长。', en: 'Describe the shot, then choose the shape, size and length.'}, media: { type: 'image', src: {zh: 'text-to-video-1.webp', en: 'text-to-video-2.webp'}, alt: {zh: '创作面板:描述、画幅与尺寸区域已用红框标出。', en: 'The creation panel, with the prompt and the Frame & size fields outlined in red.'}, }, steps: { - zh: ['在“描述画面”中写明主体、动作、场景和镜头,例如“镜头缓缓推近”。', '在“画幅与尺寸”中选择横屏、竖屏或方形,并设置“清晰度”。', '点底栏的秒数,直接修改时长;“可⁠生⁠成⁠范⁠围”中可查看各尺寸的最长时长和预计用时。', '点“生⁠成⁠视⁠频”。描述为空时会先提示,点“继⁠续⁠生⁠成”仍可生成。'], - en: ['Write the subject, action, place and camera in the prompt, for example "the camera slowly moves closer".', 'Under "Frame & size", choose landscape, portrait or square and set "Resolution".', 'Click the seconds in the bottom bar to change the length. "Available sizes and lengths" shows the longest length and the estimated time for each size.', 'Choose "Generate video". With an empty prompt, a note appears first; choose "Generate anyway" to go ahead.'], + zh: ['在“描述画面”中写明主体、动作、场景和镜头,例如“镜头缓缓推近”。', '在“画幅与尺寸”中选择横屏、竖屏或方形,再在“尺寸”一行选择大小。', '点底栏的秒数,直接修改时长;“可⁠生⁠成⁠范⁠围”中可查看各尺寸的最长时长和预计用时。', '点“生⁠成⁠视⁠频”。描述为空时会先提示,点“继⁠续⁠生⁠成”仍可生成。'], + en: ['Write the subject, action, place and camera in the prompt, for example "the camera slowly moves closer".', 'Under "Frame & size", choose landscape, portrait or square, then choose a size in the "Size" row.', 'Click the seconds in the bottom bar to change the length. "Available sizes and lengths" shows the longest length and the estimated time for each size.', 'Choose "Generate video". With an empty prompt, a note appears first; choose "Generate anyway" to go ahead.'], }, example: { assets: [], @@ -45,8 +45,8 @@ export const TUTORIAL_CHAPTERS = [ settings: {quality: 'High', width: 960, height: 544, seconds: 5}, }, limits: { - zh: ['清晰度越高、时长越长,用时和显存占用越多。', '描述中的文字内容不一定能准确显示在画面里。', '开启“提示词增强”后,描述会在本机被改写得更详细。'], - en: ['Higher resolution and longer length take more time and memory.', 'Text named in the prompt may not appear exactly in the picture.', 'With "Prompt enhancement" on, the prompt is rewritten in more detail on this computer.'], + zh: ['尺寸越大、时长越长,用时和显存占用越多。', '描述中的文字内容不一定能准确显示在画面里。', '开启“提示词增强”后,描述会在本机被改写得更详细。'], + en: ['A larger size and a longer length take more time and memory.', 'Text named in the prompt may not appear exactly in the picture.', 'With "Prompt enhancement" on, the prompt is rewritten in more detail on this computer.'], }, }, { @@ -82,8 +82,8 @@ export const TUTORIAL_CHAPTERS = [ alt: {zh: '图像视图:描述框、比例与清晰度、“生成”和图片下方的“⋯”已用红框标出。', en: 'The Images view, with the prompt, the shape and clarity, "Generate" and the "⋯" below the picture outlined in red.'}, }, steps: { - zh: ['点顶部的“图像视图”。', '在“描述画面”中写下主体、场景和风格;图中要出现的文字,用引号写出原文。', '选择比例,再选择清晰度:“标准”约 400 万像素,“高清”约 1600 万像素。显存为 8 GB 的显卡,选“标准”。', '点“生成”。图片显示在中间,并加入右侧的作品列表;图片下方一行写明生成它的模型、尺寸和比例。点图片下方的“⋯”,可下载、打开文件夹或复制提示词。', '在“AI 全自动”中,连接助手 后说“画一张……”,助手只生成图片,不生成视频;完成后点“打开”查看,点“下载”保存。'], - en: ['Choose "Images" at the top.', 'In "Describe the picture", write the subject, the place and the style. Put any words that should appear in the picture in quotation marks, exactly as written.', 'Choose the shape, then the clarity: "Standard" is about 4 megapixels and "High" about 16 megapixels. On a graphics card with 8 GB of memory, choose "Standard".', 'Choose "Generate". The picture appears in the middle and is added to the works on the right. The line below it names the model that made it, with its size and shape. Choose "⋯" below it to download it, open its folder or copy the prompt.', 'In Autopilot, connect an assistant and say "Draw a picture of …". The assistant makes only the picture, not a video. When it finishes, choose "Open" to view it and "Download" to save it.'], + zh: ['点顶部的“图像视图”。', '在“描述画面”中写下主体、场景和风格;图中要出现的文字,用引号写出原文。', '在“画幅与尺寸”中选择比例,再在“尺寸”中选择“4M”(约 400 万像素)或“16M”(约 1600 万像素)。显存为 8 GB 的显卡,选“4M”。', '点“生成”。图片显示在中间,并加入右侧的作品列表;图片下方一行写明生成它的模型、尺寸和比例。用图片下方一行的图标下载、打开文件夹或复制提示词。', '在“AI 全自动”中,连接助手 后说“画一张……”,助手只生成图片,不生成视频;完成后点“打开”查看,点“下载”保存。'], + en: ['Choose "Images" at the top.', 'In "Describe the picture", write the subject, the place and the style. Put any words that should appear in the picture in quotation marks, exactly as written.', 'Under "Frame & size", choose the shape, then choose "4M" (about 4 megapixels) or "16M" (about 16 megapixels) under "Size". On a graphics card with 8 GB of memory, choose "4M".', 'Choose "Generate". The picture appears in the middle and is added to the works on the right. The line below it names the model that made it, with its size and shape. Use the icons in the line below it to download it, open its folder or copy the prompt.', 'In Autopilot, connect an assistant and say "Draw a picture of …". The assistant makes only the picture, not a video. When it finishes, choose "Open" to view it and "Download" to save it.'], }, limits: { zh: ['未安装图像模型时,“生成”显示为“下载模型”,点它下载;和视频共用的文件不重复下载。', '加参考图见“用参考图生成图片”。', '“高清”用时更长;显存不足时,出错卡片上可点“改用标准并重试”。'], @@ -100,8 +100,8 @@ export const TUTORIAL_CHAPTERS = [ alt: {zh: '图像视图:描述框和其下方的参考图(图 1、图 2 和“+”)已用红框标出。', en: 'The Images view, with the description and the reference pictures below it (Image 1, Image 2 and "+") outlined in red.'}, }, steps: { - zh: ['点顶部的“图像视图”,点描述框下方的“+”,选“从电脑选择…”或作品中的一张图片;也可以把图片拖到左侧,或粘贴到描述框中。', '参考图按加入的顺序编号为“图 1”“图 2”……在描述中写明每张图的用途,例如“图 1 的人物手里托着图 2 的怀表”。点参考图的缩略图,会在光标处插入它的编号。', '比例默认为“与图 1 相同”,也可以改选其他比例;然后点“生成”。', '在结果下方点“改这张”,它会成为图 1,接着描述要改的地方;点“用作参考图”,它会加到参考图的最后。', '把鼠标移到缩略图上,点右上角的“×”,可移除这张参考图。'], - en: ['Choose "Images" at the top, then "+" below the description, and pick "From this computer…" or a picture from your works. You can also drag pictures onto the left side or paste them into the description.', 'Reference pictures are numbered in the order they were added: "Image 1", "Image 2" and so on. Say in the description what each one is for, for example "the person in Image 1 holds the pocket watch from Image 2". Choosing a thumbnail inserts its number at the cursor.', 'The shape is "Same as Image 1" unless you choose another. Then choose "Generate".', 'Below the result, choose "Edit this" to make it Image 1 and describe what to change, or "Use as reference" to add it after the other reference pictures.', 'To remove a reference picture, point to its thumbnail and choose "×" at its top right.'], + zh: ['点顶部的“图像视图”,点描述框下方的“参考图”,选“从电脑选择…”或作品中的一张图片;也可以把图片拖到左侧,或粘贴到描述框中。', '参考图按加入的顺序编号为“图 1”“图 2”……在描述中写明每张图的用途,例如“图 1 的人物手里托着图 2 的怀表”。点参考图的缩略图,可以裁剪或修图。', '比例默认为“跟随图片”,也可以改选其他比例;然后点“生成”。', '在结果下方点“编辑”,它会成为图 1,接着描述要改的地方;点“用作参考图”,它会加到参考图的最后。', '把鼠标移到缩略图上,点右上角的“×”,可移除这张参考图。'], + en: ['Choose "Images" at the top, then "References" below the description, and pick "From this computer…" or a picture from your works. You can also drag pictures onto the left side or paste them into the description.', 'Reference pictures are numbered in the order they were added: "Image 1", "Image 2" and so on. Say in the description what each one is for, for example "the person in Image 1 holds the pocket watch from Image 2". Choose a thumbnail to crop or retouch it.', 'The shape is "Match image" unless you choose another. Then choose "Generate".', 'Below the result, choose "Edit" to make it Image 1 and describe what to change, or "Use as reference" to add it after the other reference pictures.', 'To remove a reference picture, point to its thumbnail and choose "×" at its top right.'], }, limits: { zh: ['描述中没有写编号时,所有参考图按顺序一起使用。', 'H3 Image 最多使用 16 张参考图;换用其他图像模型后超出其上限时,会提示需要移除几张。'], @@ -127,8 +127,8 @@ export const TUTORIAL_CHAPTERS = [ settings: {}, }, limits: { - zh: ['图片会按所选画幅居中裁切。', '首帧、尾帧不能与参考图、角色同时使用。'], - en: ['Images are center-cropped to the chosen shape.', 'First and last frames cannot be used with reference images or characters.'], + zh: ['图片会按所选画幅居中裁切。', 'Mac 上首帧、尾帧暂不能与参考图、角色同时使用。'], + en: ['Images are center-cropped to the chosen shape.', 'On a Mac, first and last frames cannot be used with reference images or characters yet.'], }, }, { @@ -168,8 +168,8 @@ export const TUTORIAL_CHAPTERS = [ settings: {}, }, limits: { - zh: ['参考图生成仍在试验中,人物外观可能每次不同;清晰的正面图效果更稳定。', '首帧和尾帧可同时使用,会按画幅居中裁切;暂不能与参考图、参考视频同时使用。', '参考视频只取与成片等长的一段,最长 15 秒;生成用时约为只用图片时的两倍。'], - en: ['Reference generation is experimental, so a character may look different between runs. A clearer, front-facing image helps.', 'First and last frames can be used together and are center-cropped to the frame shape. They cannot be used with reference images or videos yet.', 'A reference video is trimmed to the length of the result, up to 15 seconds, and generation takes about twice as long as with images only.'], + zh: ['参考图生成仍在试验中,人物外观可能每次不同;清晰的正面图效果更稳定。', '首帧和尾帧可同时使用,会按画幅居中裁切;也可以与参考图、参考视频同时使用(Mac 上暂不支持)。', '参考视频只取与成片等长的一段,最长 15 秒;生成用时约为只用图片时的两倍。'], + en: ['Reference generation is experimental, so a character may look different between runs. A clearer, front-facing image helps.', 'First and last frames can be used together and are center-cropped to the frame shape. They can also be used with reference images or videos (not yet on a Mac).', 'A reference video is trimmed to the length of the result, up to 15 seconds, and generation takes about twice as long as with images only.'], }, }, { @@ -180,11 +180,11 @@ export const TUTORIAL_CHAPTERS = [ media: { type: 'image', src: {zh: 'cast-sheet-1.webp', en: 'cast-sheet-2.webp'}, - alt: {zh: '角色窗口:名字、正面图片和其他角度图片已用红框标出。', en: 'The character window, with the name, front image and other angles outlined in red.'}, + alt: {zh: '角色窗口:名字和正面、侧面、背面三格已用红框标出。', en: 'The character window, with the name and the front, side and back slots outlined in red.'}, }, steps: { - zh: ['展开创作面板的“素材”,在“角色”一行点“+”新建角色。', '填写“名字”,设置“正面图片”:可“上⁠传⁠图⁠片”,也可“AI 生成”,后者会按描述一次生成 5 张供选。', '可再添加最多 5 张其他角度的图片,然后点“保⁠存”。', '之后在描述中输入 @ 选择该角色,并写明其动作。'], - en: ['Expand "Media" in the creation panel and, on the "Characters" row, choose + to create a character.', 'Enter a "Name" and set the "Front image": choose "Upload images", or "Generate with AI", which makes 5 pictures from a description to pick from.', 'Add up to 5 images from other angles, then choose "Save".', 'In later prompts, type @ to pick the character and describe what the character does.'], + zh: ['展开创作面板的“素材”,在“角色”一行点“+”新建角色。', '填写“名字”,设置图片:可“上⁠传⁠图⁠片”,也可“AI 生成”或“从照片生成”,会生成脸部特写、正面、侧面和背面四张。', '在脸部特写、正面、侧面、背面四格中添加或替换图片,四张齐了再点“保⁠存”。', '之后在描述中输入 @ 选择该角色,并写明其动作。'], + en: ['Expand "Media" in the creation panel and, on the "Characters" row, choose + to create a character.', 'Enter a "Name" and add pictures: choose "Upload images", or "Generate with AI" or "From a photo", which make a face close-up, front, side and back view.', 'Add or replace images in the face close-up, front, side and back slots; when all four are filled, choose "Save".', 'In later prompts, type @ to pick the character and describe what the character does.'], }, example: { assets: [{file: 'fox-sheet.webp', role: 'reference'}], @@ -261,8 +261,8 @@ export const TUTORIAL_CHAPTERS = [ alt: {zh: '图片编辑窗口:工具栏中的裁剪、文字和“保存”已用红框标出。', en: 'The picture editor, with the crop and text tools and Save outlined in red.'}, }, steps: { - zh: ['展开创作面板的“素材”,上传图片后点缩略图,或点图片下方的“编辑”。', '在左侧工具栏选择工具:“裁剪与画布”调整构图,“画笔”“污点修复”“仿制图章”修图,“文字”添加文字。', '改错了可点“撤销”,或按 Ctrl+Z。', '点“保存”。修改后的图片用于生成,原图仍保留,点“恢复原图”可改回。'], - en: ['Expand "Media" in the creation panel, upload a picture, then choose its thumbnail or the "Edit" button below it.', 'Choose a tool on the left: "Crop and canvas" to recompose, "Brush", "Spot healing" or "Clone stamp" to retouch, "Text" to add words.', 'To undo a change, choose "Undo" or press Ctrl+Z.', 'Choose "Save". The edited picture is used for generation and the original is kept; choose "Original" to switch back.'], + zh: ['展开创作面板的“素材”,上传图片后点图片,或点图片上方的“编辑”。', '在左侧工具栏选择工具:“裁剪与画布”调整构图,“画笔”“污点修复”“仿制图章”修图,“文字”添加文字。', '改错了可点“撤销”,或按 Ctrl+Z。', '点“保存”。修改后的图片用于生成,原图仍保留;要改回,在图片的下拉菜单中选“改回原图”。'], + en: ['Expand "Media" in the creation panel, upload a picture, then choose the picture, or "Edit" at its top.', 'Choose a tool on the left: "Crop and canvas" to recompose, "Brush", "Spot healing" or "Clone stamp" to retouch, "Text" to add words.', 'To undo a change, choose "Undo" or press Ctrl+Z.', 'Choose "Save". The edited picture is used for generation and the original is kept. To switch back, choose "Use the original image again" in the picture\'s drop-down.'], }, limits: { zh: ['视频的裁剪另在“调整裁剪”中设置。', '“AI 生成”和“点选”需要图片生成功能可用时才显示。'], @@ -279,8 +279,8 @@ export const TUTORIAL_CHAPTERS = [ alt: {zh: '编辑图片:图片上框出了一块选区,“选框”工具、描述栏和“生成”按钮已用红框标出。', en: 'The image editor, with an area selected on the picture and the Marquee tool, the description field and the "Generate" button outlined in red.'}, }, steps: { - zh: ['展开创作面板的“素材”,点图片(或右上角的“编辑”),打开“编辑图片”。', '点左上角的“AI 生成”,选择“改这张”。', '用“选框”“套索”或“魔棒”在图片上选出要修改的区域;按住 Shift 拖动可以添加区域,按住 Alt 拖动可以减去一块。', '在描述栏中写下选区要改成什么样。', '点“生⁠成”。结果出现后选区仍然保留,可以直接再改;满意后点“保存”。'], - en: ['Expand "Media" in the creation panel, click the picture (or "Edit" at its top right) to open "Edit image".', 'Click "Generate with AI" at the top left and choose "Edit this".', 'Select the area to change on the picture with "Marquee", "Lasso" or "Magic wand". Hold Shift while dragging to add an area, or Alt to take one away.', 'In the description field, describe how the selection should change.', 'Click "Generate". The selection stays after the result appears, so it can be changed again; click "Save" when satisfied.'], + zh: ['展开创作面板的“素材”,点图片(或图片上方的“编辑”),打开“编辑图片”。', '点左上角的“AI 生成”,选择“改这张”。', '用“选框”“套索”或“魔棒”在图片上选出要修改的区域;按住 Shift 拖动可以添加区域,按住 Alt 拖动可以减去一块。', '在描述栏中写下选区要改成什么样。', '点“生⁠成”。结果出现后选区仍然保留,可以直接再改;满意后点“保存”。'], + en: ['Expand "Media" in the creation panel, click the picture (or "Edit" at its top) to open "Edit image".', 'Click "Generate with AI" at the top left and choose "Edit this".', 'Select the area to change on the picture with "Marquee", "Lasso" or "Magic wand". Hold Shift while dragging to add an area, or Alt to take one away.', 'In the description field, describe how the selection should change.', 'Click "Generate". The selection stays after the result appears, so it can be changed again; click "Save" when satisfied.'], }, limits: { zh: ['没有选区时,“改这张”会按描述修改整张图片。', '“点选”需要先下载一次选区模型,面板会显示进度。', '图片生成需要所用的图片模型已经下载完成。'], @@ -316,8 +316,8 @@ export const TUTORIAL_CHAPTERS = [ alt: {zh: '创作面板:“LoRA”中的“添加”按钮、模型下拉列表、强度和左侧把手已用红框标出。', en: 'The creation panel, with the "Add" button under "LoRA", the model list, the strength and the handle on the left outlined in red.'}, }, steps: { - zh: ['把 LoRA 文件(.safetensors)放进 models/loras 文件夹。', '展开创作面板的“LoRA”,点“添加”,在下拉列表中选择文件。', '需要时修改右边的强度,默认是 1;取消行首的勾选可暂时停用;有多个 LoRA 时,拖动左侧的把手调整顺序。', '模型要求触发词时,填在“触发词”一栏,它会自动加进描述;移除这个 LoRA 时一并去掉。', '点“生⁠成⁠视⁠频”。'], - en: ['Put the LoRA file (.safetensors) in the models/loras folder.', 'Expand "LoRA" in the creation panel, choose "Add" and pick the file from the list.', 'Change the strength on the right if needed; the default is 1. Clear the checkbox at the start of the row to switch the LoRA off for now. With more than one LoRA, drag the handle on the left to change the order.', 'If the LoRA asks for trigger words, enter them in "Trigger words". They are added to the prompt, and removed again with the LoRA.', 'Choose "Generate video".'], + zh: ['把 LoRA 文件(.safetensors)放进 models/loras 文件夹。', '点创作面板的“LoRA”,再点“添加 LoRA”,在下拉列表中选择文件。', '需要时修改右边的强度,默认是 1;取消行首的勾选可暂时停用;有多个 LoRA 时,拖动左侧的把手调整顺序。', '模型要求触发词时,填在“触发词”一栏,它会自动加进描述;移除这个 LoRA 时一并去掉。', '点“生⁠成⁠视⁠频”。'], + en: ['Put the LoRA file (.safetensors) in the models/loras folder.', 'Choose "LoRA" in the creation panel, then "Add LoRA", and pick the file from the list.', 'Change the strength on the right if needed; the default is 1. Clear the checkbox at the start of the row to switch the LoRA off for now. With more than one LoRA, drag the handle on the left to change the order.', 'If the LoRA asks for trigger words, enter them in "Trigger words". They are added to the prompt, and removed again with the LoRA.', 'Choose "Generate video".'], }, limits: { zh: ['一次最多使用 32 个 LoRA。', '只列出 .safetensors 格式的文件。', 'FreeVideo 无需添加加速 LoRA。'], @@ -331,11 +331,11 @@ export const TUTORIAL_CHAPTERS = [ media: { type: 'image', src: {zh: 'quality-tiers-1.webp', en: 'quality-tiers-2.webp'}, - alt: {zh: '创作面板:质量滑块上的轻量、标准、精细、极致已用红框标出。', en: 'The creation panel, with the quality slider and its four names outlined in red.'}, + alt: {zh: '创作面板:底栏的质量按钮和展开的质量滑块(轻量、标准、精细、极致)已用红框标出。', en: 'The creation panel, with the quality button in the bottom bar and the quality slider it opens (with its four names) outlined in red.'}, }, steps: { - zh: ['在“质量”滑块上选择“轻量”“标准”“精细”或“极⁠致”。', '构思阶段用“轻量”,快速确认画面和动作。', '定稿时改用“精细”或“极⁠致”。', '选好档位后,“质量”旁会显示预计用时;然后点“生⁠成⁠视⁠频”。'], - en: ['Move the "Quality" slider to Light, Medium, High or Max.', 'While exploring, use Light to check the picture and motion quickly.', 'For the final video, switch to High or Max.', 'The estimated time for the chosen level appears next to "Quality". Then choose "Generate video".'], + zh: ['点底栏的质量按钮(显示当前档位,如“轻量”),在滑块上选择“轻量”“标准”“精细”或“极⁠致”。', '构思阶段用“轻量”,快速确认画面和动作。', '定稿时改用“精细”或“极⁠致”。', '选好档位后,“生⁠成⁠视⁠频”按钮下方会显示预计用时;然后点它开始生成。'], + en: ['Choose the quality button in the bottom bar (it shows the current level, such as Light) and move the slider to Light, Medium, High or Max.', 'While exploring, use Light to check the picture and motion quickly.', 'For the final video, switch to High or Max.', 'The estimated time for the chosen level appears under "Generate video". Then choose it to start.'], }, example: { assets: [], @@ -343,8 +343,8 @@ export const TUTORIAL_CHAPTERS = [ settings: {quality: 'High'}, }, limits: { - zh: ['预计用时因显卡而异,以面板显示为准。', '不同档位各自生成,画面构图可能不同,不宜逐帧对比。'], - en: ['Time depends on the graphics card; use the estimate shown in the panel.', 'Each level is generated on its own, so the composition may differ and the results should not be compared frame by frame.'], + zh: ['预计用时因显卡而异,以生成按钮上显示的为准。', '不同档位各自生成,画面构图可能不同,不宜逐帧对比。'], + en: ['Time depends on the graphics card; use the estimate shown on the Generate button.', 'Each level is generated on its own, so the composition may differ and the results should not be compared frame by frame.'], }, }, { @@ -354,11 +354,11 @@ export const TUTORIAL_CHAPTERS = [ media: { type: 'image', src: {zh: 'refine-1.webp', en: 'refine-2.webp'}, - alt: {zh: '创作面板:二采选项“先出预览”已用红框标出。', en: 'The creation panel, with the "Preview first" option outlined in red.'}, + alt: {zh: '创作面板:“生⁠成⁠视⁠频”右侧的箭头已用红框标出,展开的菜单中有“生⁠成⁠视⁠频”和“生⁠成⁠预⁠览”。', en: 'The creation panel, with the arrow beside "Generate video" outlined in red and its menu open on "Generate video" and "Generate preview".'}, }, steps: { - zh: ['在二采中选择“先出预览”,按钮变为“生⁠成⁠预⁠览”。', '点“生⁠成⁠预⁠览”,等待预览完成。', '画面满意时,点结果中的“继续二采”。', '不满意时,修改描述或种子,再生成新的预览。'], - en: ['Under two-pass sampling choose "Preview first". The button changes to "Generate preview".', 'Choose "Generate preview" and wait for it to finish.', 'When the picture is right, choose "Run second pass" in the result.', 'Otherwise change the prompt or the seed and generate a new preview.'], + zh: ['点“生⁠成⁠视⁠频”右侧的箭头,选“生⁠成⁠预⁠览”。', '点“生⁠成⁠预⁠览”,等待预览完成。', '画面满意时,点结果中的“继续二采”。', '不满意时,修改描述或种子,再生成新的预览。'], + en: ['Choose the arrow beside "Generate video" and pick "Generate preview".', 'Choose "Generate preview" and wait for it to finish.', 'When the picture is right, choose "Run second pass" in the result.', 'Otherwise change the prompt or the seed and generate a new preview.'], }, example: { assets: [], @@ -377,11 +377,11 @@ export const TUTORIAL_CHAPTERS = [ media: { type: 'image', src: {zh: 'long-video-1.webp', en: 'long-video-2.webp'}, - alt: {zh: '创作面板:时长输入框和“可⁠生⁠成⁠范⁠围”入口已用红框标出。', en: 'The creation panel, with the duration field and "Available sizes and lengths" control outlined in red.'}, + alt: {zh: '创作面板:时长输入框和“生⁠成⁠视⁠频”按钮已用红框标出。', en: 'The creation panel, with the duration field and the "Generate video" button outlined in red.'}, }, steps: { - zh: ['填写更长的时长,会自动分段生成;“可⁠生⁠成⁠范⁠围”中可查看各尺寸的最长时长和预计用时。', '点“生⁠成⁠视⁠频”。', '在生成好的视频下方点“接着生成”,继续下一段。', '更长的多镜头视频,可在“剪辑视图”中另起新的镜头,或使用“AI 全自动”。'], - en: ['Enter a longer duration. It is made in parts automatically. "Available sizes and lengths" shows how long each size can be and about how long it takes.', 'Choose "Generate video".', 'Choose "Extend" below a finished video to continue it.', 'For a longer video with several shots, start new shots in "Edit", or use "Autopilot".'], + zh: ['填写更长的时长,会自动分段生成;点画幅按钮(如“16:9 · 1M”),在“可⁠生⁠成⁠范⁠围”中可查看各尺寸的最长时长和预计用时。', '点“生⁠成⁠视⁠频”。', '在生成好的视频下方点“接着生成”,继续下一段。', '更长的多镜头视频,可在“剪辑视图”中另起新的镜头,或使用“AI 全自动”。'], + en: ['Enter a longer duration. It is made in parts automatically. Choose the frame button (such as "16:9 · 1M"); "Available sizes and lengths" there shows how long each size can be and about how long it takes.', 'Choose "Generate video".', 'Choose "Extend" below a finished video to continue it.', 'For a longer video with several shots, start new shots in "Edit", or use "Autopilot".'], }, example: { assets: [], @@ -475,8 +475,8 @@ export const TUTORIAL_CHAPTERS = [ alt: {zh: '剪辑视图:时间线上的播放头和预览下方的“保存当前帧”按钮已用红框标出。', en: 'The Edit view, with the playhead on the timeline and the "Save current frame" button below the preview outlined in red.'}, }, steps: { - zh: ['点顶部的“剪辑视图”。', '把播放头拖到想要的画面上,也可按空格播放、暂停后停在该处。', '点预览右下方的“保存当前帧”按钮(相机图标)。', '保存后,在“编辑图片 > AI 生成 > 历史”中找到这张图片。'], - en: ['Choose "Edit" at the top.', 'Drag the playhead to the picture you want, or press Space to play and pause there.', 'Choose the "Save current frame" button (camera icon) at the lower right of the preview.', 'Find the saved picture under "Edit image > Generate with AI > History".'], + zh: ['点顶部的“剪辑视图”。', '把播放头拖到想要的画面上,也可按空格播放、暂停后停在该处。', '点预览右下方的“保存当前帧”按钮(相机图标)。', '保存后,在“编辑图片 > AI 生成 > 作品库”中找到这张图片。'], + en: ['Choose "Edit" at the top.', 'Drag the playhead to the picture you want, or press Space to play and pause there.', 'Choose the "Save current frame" button (camera icon) at the lower right of the preview.', 'Find the saved picture under "Edit image > Generate with AI > Works".'], }, limits: { zh: ['保存的图片与导出视频中这一刻的画面相同。', '播放头下方须有片段;正在生成的一段完成后才能保存。', '时间线为空时按钮不可用。'], @@ -491,11 +491,11 @@ export const TUTORIAL_CHAPTERS = [ media: { type: 'image', src: {zh: 'editor-extend-refs-1.webp', en: 'editor-extend-refs-2.webp'}, - alt: {zh: '剪辑视图:选中的接续段和描述框旁的参考图入口已用红框标出。', en: 'The Edit view, with the selected continuation and the reference image control beside the prompt outlined in red.'}, + alt: {zh: '剪辑视图:选中的接续段和“素材”按钮已用红框标出。', en: 'The Edit view, with the selected continuation and the Media button outlined in red.'}, }, steps: { - zh: ['选中要接续的一段。', '点描述框旁的 +,上传或生成图片,最多 3 张。', '填写描述,然后点“生⁠成”。'], - en: ['Select the part to continue.', 'Click + next to the prompt to upload or generate images, up to 3.', 'Describe it, then choose "Generate".'], + zh: ['选中要接续的一段。', '点“素材”,上传或生成图片,最多 3 张。', '填写描述,然后点“生⁠成”。'], + en: ['Select the part to continue.', 'Choose "Media" to upload or generate images, up to 3.', 'Describe it, then choose "Generate".'], }, example: { assets: [], @@ -616,11 +616,11 @@ export const TUTORIAL_CHAPTERS = [ media: { type: 'image', src: {zh: 'narration-1.webp', en: 'narration-2.webp'}, - alt: {zh: '剪辑视图:生成条中的“音色”和“生成”已用红框标出。', en: 'The Edit view, with "Voice" and "Generate" in the generation bar outlined in red.'}, + alt: {zh: '剪辑视图:右栏的“音色”和生成按钮已用红框标出。', en: 'The Edit view, with "Voice" in the right panel and the generate button outlined in red.'}, }, steps: { - zh: ['在声音轨的空白处点右键,选“配⁠音”。', '配音放在“录⁠音”轨上(分离过音轨时放在“人⁠声”轨),没有录音轨时会自动加上;选区从点击处到下一个片段,最长 5 秒。', '在“音⁠色”中选说话人、导入的片段或录音。“选一个声音片段…”可在时间线上点选,▶ 可试听。', '写下要说的话,点“生⁠成”。'], - en: ['Right-click an empty spot on a sound track and choose "Narration".', 'The line goes on the Voice track (or on the Dialogue track after separating tracks), which is added if missing. The range runs from the click to the next clip, up to 5 s.', 'Under "Voice", choose a speaker, an imported clip or a recording. "Pick a sound clip…" lets you click one on the timeline, and ▶ plays a sample.', 'Write what to say and choose "Generate".'], + zh: ['在声音轨的空白处点右键,选“配⁠音”。', '配音放在“录⁠音”轨上(分离过音轨时放在“人⁠声”轨),没有录音轨时会自动加上;选区从点击处到下一个片段,最长 5 秒。', '在“音⁠色”中选说话人、导入的片段或录音。“选一个声音片段…”可在时间线上点选,▶ 可试听。', '写下要说的话,点生成按钮。'], + en: ['Right-click an empty spot on a sound track and choose "Narration".', 'The line goes on the Voice track (or on the Dialogue track after separating tracks), which is added if missing. The range runs from the click to the next clip, up to 5 s.', 'Under "Voice", choose a speaker, an imported clip or a recording. "Pick a sound clip…" lets you click one on the timeline, and ▶ plays a sample.', 'Write what to say and choose the generate button.'], }, limits: { zh: ['话比选区长时,后面有空位就按完整长度放入;会盖住后面的片段时不放入,选区和文字保留。', '放入后可以撤销,也可在“台⁠词”中点“重⁠新⁠配⁠音”改写。'], @@ -677,8 +677,8 @@ export const TUTORIAL_CHAPTERS = [ alt: {zh: 'AI 全自动:连接助手 的按钮已用红框标出。', en: 'Autopilot, with the button that connects an assistant outlined in red.'}, }, steps: { - zh: ['点顶部的“AI 全自动”。', '点“连接助手”卡片中的按钮复制连接信息,粘贴给所使用的助手。', '状态显示“已连接”或所连助手的名字后,在“对助手说…”中描述想做的视频,例如“做一条 1 分钟的竖屏短片:咖啡店的一天”。', '点“发送”,助手会生成并剪辑;可随时点“停止”,完成后点“打开”或“剪辑”。', '在对话列表中点对话旁的“更多”,选“重命名”可修改对话名称。'], - en: ['Choose "Autopilot" at the top.', 'On the "Connect an assistant" card, choose the button to copy the connection details and paste them to the assistant you use.', 'When it shows "Connected" or the assistant\'s name, describe the video under "Tell the assistant…", for example "Make a 1-minute vertical short film: a day in a coffee shop".', 'Choose "Send". The assistant generates and edits it. Choose "Stop" at any time, and "Open" or "Edit" when it finishes.', 'In the chat list, choose "More" next to a chat, then "Rename" to change its name.'], + zh: ['点顶部的“AI 全自动”。', '点“连接助手”卡片中的按钮复制连接信息,粘贴给所使用的助手。', '状态显示“助手已连接”或所连助手的名字后,在“对助手说…”中描述想做的视频,例如“做一条 1 分钟的竖屏短片:咖啡店的一天”。', '点“发送”,助手会生成并剪辑;可随时点“停止”,完成后点“打开”或“剪辑”。', '在对话列表中点对话旁的“更多”,选“重命名”可修改对话名称。'], + en: ['Choose "Autopilot" at the top.', 'On the "Connect an assistant" card, choose the button to copy the connection details and paste them to the assistant you use.', 'When it shows "Assistant connected" or the assistant\'s name, describe the video under "Tell the assistant…", for example "Make a 1-minute vertical short film: a day in a coffee shop".', 'Choose "Send". The assistant generates and edits it. Choose "Stop" at any time, and "Open" or "Edit" when it finishes.', 'In the chat list, choose "More" next to a chat, then "Rename" to change its name.'], }, limits: { zh: ['需要先连接助手,未连接时只显示连接说明。', '镜头越多,用时越长。', '助手开拍整部片前、重拍耗时较长时是否先询问,可在“设置”的“AI 助手”中选择。'], @@ -733,8 +733,8 @@ export const TUTORIAL_CHAPTERS = [ alt: {zh: '预览区下方的按钮:“复用设置”已用红框标出。', en: 'The buttons below the preview, with "Reuse settings" outlined in red.'}, }, steps: { - zh: ['点预览区右上角“作品”左边的图标,选一条以前的视频。', '点“复⁠用⁠设⁠置”,描述、尺寸、时长和种子会填回创作面板。', '改动需要变化的内容,再点“生⁠成⁠视⁠频”。', '填入有误时,10 秒内点“撤⁠销”,恢复原来的内容。'], - en: ['Choose the icon to the left of "Creations" above the preview and pick an earlier video.', 'Choose "Reuse settings". Its prompt, size, duration and seed are filled into the creation panel.', 'Change what should be different, then choose "Generate video".', 'If the fill was a mistake, choose "Undo" within 10 seconds to bring back what was there.'], + zh: ['在预览下方的最近作品中点一条以前的视频,或点开头的“作品库”从中选择。', '点“复⁠用⁠设⁠置”,描述、尺寸、时长和种子会填回创作面板。', '改动需要变化的内容,再点“生⁠成⁠视⁠频”。', '填入有误时,10 秒内点“撤⁠销”,恢复原来的内容。'], + en: ['Pick an earlier video in the recent videos below the preview, or choose "Creations" at its start and pick one there.', 'Choose "Reuse settings". Its prompt, size, duration and seed are filled into the creation panel.', 'Change what should be different, then choose "Generate video".', 'If the fill was a mistake, choose "Undo" within 10 seconds to bring back what was there.'], }, limits: { zh: ['没有保存描述的视频不提供“复用设置”。'], @@ -749,11 +749,11 @@ export const TUTORIAL_CHAPTERS = [ media: { type: 'image', src: {zh: 'library-export-1.webp', en: 'library-export-2.webp'}, - alt: {zh: '“我的作品”:第一条作品已用红框标出。', en: 'Your creations, with the first video outlined in red.'}, + alt: {zh: '“作品库”:第一条作品已用红框标出。', en: 'Your creations, with the first video outlined in red.'}, }, steps: { - zh: ['点预览区的“作品”,打开“我的作品”。', '选择一条视频,可播放,或点“接着生成”在剪辑视图中继续。', '在作品详情中点爱心图标收藏;列表上方选“收⁠藏”只看收藏的作品,选“全⁠部”看所有作品。', '需要成片时,在“剪辑视图”点“导⁠出”。', '在导出窗口选择范围、画质和内容,再点“导⁠出”。'], - en: ['Choose "Creations" in the preview area to open the library.', 'Pick a video to play it, or choose "Extend" to continue it in the Edit view.', 'In a creation\'s details, choose the heart to add it to favorites. Above the list, choose "Favorites" to see only those, or "All" to see every creation.', 'For a finished file, choose "Export" in the Edit view.', 'In the export window choose the range, quality and content, then choose "Export".'], + zh: ['点预览下方最近作品开头的“作品库”。', '选择一条视频,可播放,或点“接着生成”在剪辑视图中继续。', '在作品详情中点爱心图标收藏;列表上方选“收⁠藏”只看收藏的作品,选“全⁠部”看所有作品。', '需要成片时,在“剪辑视图”点“导⁠出”。', '在导出窗口选择范围、画质和内容,再点“导⁠出”。'], + en: ['Choose "Creations" at the start of the recent videos below the preview.', 'Pick a video to play it, or choose "Continue" to continue it in the Edit view.', 'In a creation\'s details, choose the heart to add it to favorites. Above the list, choose "Favorites" to see only those, or "All" to see every creation.', 'For a finished file, choose "Export" in the Edit view.', 'In the export window choose the range, quality and content, then choose "Export".'], }, limits: { zh: ['删除作品前会确认;被剪辑使用的作品不能删除。', '导出窗口每次打开时,“内容”默认选“画面和声音”,“画质”默认选“高”。', '导出过程中取消不会留下不完整的文件。'], @@ -763,19 +763,19 @@ export const TUTORIAL_CHAPTERS = [ { id: 'system-status', title: {zh: '运行状态', en: 'System status'}, - summary: {zh: '在顶栏查看显存、温度和硬盘空间,必要时立即停止生成。', en: 'Watch VRAM, temperature and disk space from the top bar, and stop a generation at once when needed.'}, + summary: {zh: '在顶栏看显存和显卡温度,在“运行状态”面板里看本机详情,必要时停止生成。', en: 'See the video memory and graphics card temperature in the top bar and this computer in the Run status panel, and stop a generation when needed.'}, media: { type: 'image', src: {zh: 'system-status-1.webp', en: 'system-status-2.webp'}, - alt: {zh: '顶栏的运行状态和展开的面板:运行状态和“立即停止”按钮已用红框标出。', en: 'The system status in the top bar with its panel open; the status and the "Stop now" button are outlined in red.'}, + alt: {zh: '一个视频正在生成时,顶栏的运行状态和展开的“运行状态”面板:顶栏的运行状态和面板底部的“停止”按钮已用红框标出。', en: 'The status in the top bar while a video is being generated, with the Run status panel open; the status and the Stop button at the bottom of the panel are outlined in red.'}, }, steps: { - zh: ['点顶部的“设置”,在“运行状态”下勾选“在顶栏显示运行状态”。', '顶栏出现运行状态,显示显存占用和显卡温度;顶栏放不下时只显示图标。', '点运行状态打开面板,查看显卡名称、显存、使用率、温度和硬盘剩余空间,数值每 2 秒更新一次。', '要马上停下正在进行的生成时,点“立即停止”,再在 4 秒内点“确认停止”;队列随之暂停,点“继续队列”恢复。'], - en: ['Choose "Settings" at the top, and under "System status" turn on "Show system status in the top bar".', 'The status appears in the top bar, with the VRAM in use and the graphics card temperature. When the top bar is short of room, only its icon is shown.', 'Choose the status to open its panel: the graphics card name, VRAM, utilization, temperature and free disk space, updated every 2 seconds.', 'To stop the running generation at once, choose "Stop now", then "Confirm stop" within 4 seconds. The queue is paused; choose "Resume queue" to continue.'], + zh: ['点顶部的“设置”,在“外观”里打开“在运行状态中显示本机数据”。', '没有任务时,顶栏的运行状态显示显存占用和显卡温度;有任务时改为显示任务进度。', '点顶栏的运行状态打开“运行状态”面板:上面是进行中的任务,“本机”下是显存、温度、显卡占用和硬盘剩余,面板开着时每 2 秒更新一次。', '要停下正在生成的视频,点面板底部的“停止”(有任务进行或排队时才有),再在提问下点“停止”确认;正在生成的不会保留,排队的任务会暂停,点“继续队列”恢复。'], + en: ['Choose "Settings" at the top, and under "Appearance" turn on "Show this computer in the status".', 'With no task running, the status in the top bar shows the video memory in use and the graphics card temperature; while a task runs it shows the task\'s progress instead.', 'Choose the status in the top bar to open the Run status panel: running tasks at the top, and under "This computer" the video memory, temperature, graphics card load and free disk, updated every 2 seconds while the panel is open.', 'To stop the video being generated, choose "Stop" at the bottom of the panel (there while a task runs or waits), then "Stop" again under the question. What is being made is not kept and waiting tasks pause; choose "Resume queue" to go on.'], }, limits: { - zh: ['显存达到 95% 或温度达到 85 °C 时,数值以红色显示。', '“立即停止”只在有生成正在进行时可用。', '窗口很窄时,顶栏不显示运行状态。'], - en: ['VRAM at 95% or more, or a temperature of 85 °C or more, is shown in red.', '"Stop now" is available only while a generation is running.', 'In a very narrow window, the top bar does not show the status.'], + zh: ['显存达到 95% 或温度达到 85 °C 时,数值以红色显示。', '顶栏变窄时先只留显存数字,再只留图标;点图标仍能打开面板。', '不打开这项设置时,顶栏不显示本机数据,也不在后台读取;“运行状态”面板里的“本机”照常显示。'], + en: ['Video memory at 95% or more, or a temperature of 85 °C or more, is shown in red.', 'As the top bar narrows, it first keeps only the video memory figure, then only the icon; choosing the icon still opens the panel.', 'With this setting off, the top bar shows no figures for this computer and nothing is read in the background; "This computer" in the Run status panel is shown as usual.'], }, }, { diff --git a/web/updates.js b/web/updates.js index 3fda12ec..9c69d59c 100644 --- a/web/updates.js +++ b/web/updates.js @@ -1,6 +1,7 @@ import { api } from '../../scripts/api.js'; import { setLauncherPresent, setOfflineInstall } from './repair_hint.js'; import { issueButton } from './issue_button.js'; +import { userMessage } from './user_message.js'; import './glass/library.js'; import { hasWhatsNew } from './whatsnew_pages.js'; import { releaseMedia, mediaKind, mediaPath, splitChange } from './release_media.js'; @@ -237,7 +238,8 @@ export function createUpdateNotice(cn) { const element = document.createElement('aside'); element.className = 'fv-update-notice fv-update-bar'; element.hidden = true; element.setAttribute('role', 'status'); const label = document.createElement('span'); - let problem; + // Read by the issue button when clicked, so the report carries the latest render's reason. + let problem, issueText = ''; const details = document.createElement('button'); details.type = 'button'; details.textContent = t("What's new", '更新内容'); let closeNotes = () => {}; @@ -288,7 +290,8 @@ export function createUpdateNotice(cn) { // The last model state seen stays while ComfyUI is away. const model = launcher?.model || ''; const busy = updating && (working.has(phase) || !!model || offline); - let text = '', actions = false; + let text = '', actions = false, reason = '', cause = '', short = ''; + issueText = ''; if (failure === 'cancel') { text = t(CANCEL_FAILURE.en, CANCEL_FAILURE.zh); } else if (busy) { @@ -307,16 +310,36 @@ export function createUpdateNotice(cn) { actions = true; } else if (candidate && dismissed !== identity(candidate)) { text = t('FreeVideo update available', 'FreeVideo 有新版本') + ' · ' + displayVersion(candidate); - if (launcher?.status === 'error' && launcher.error) text += ' · ' + t('last attempt failed', '上次更新未完成'); + // The launcher's own reason (its copy, in the user's language) follows “last attempt failed”: its first + // sentence, the cause, like the other parts without a full stop. The whole reason is the tooltip and goes in + // the issue; program text from the launcher leaves only the prefix. + if (launcher?.status === 'error' && launcher.error) { + const prefix = t('Last attempt failed', '上次更新未完成'); + reason = userMessage(launcher.error, t, ''); + const first = (/^.+?(?:[。!?]|[.!?](?=\s|$))/u.exec(reason)?.[0] || reason).replace(/[。!?.!?]+$/u, ''); + // Lower-case the first word unless it is a name (FreeVideo, GitHub). + cause = first && t(first.replace(/^[A-Z][a-z]*\b/, w => w.toLowerCase()), first); + text += ' · ' + prefix; short = text; + if (cause) text += t(': ', ':') + cause; + issueText = short + (reason ? t(': ', ':') + reason : ''); + } actions = true; } element.hidden = !text; element.classList.toggle('fv-update-working', busy); label.textContent = text; + if (reason) label.title = reason; else label.removeAttribute('title'); + // A cause that does not fit leaves only the prefix; the tooltip still has it. + const fit = () => { if (cause && label.textContent === text && label.scrollWidth > label.clientWidth + 1) label.textContent = short; }; + if (cause) { fit(); globalThis.requestAnimationFrame?.(fit); } const failed = failure === 'cancel' || failure === 'launcher' && !busy && phase !== 'review' || actions && launcher?.status === 'error' && !!launcher.error; if (failed) { - problem ||= issueButton(t, () => ({where: ['Update FreeVideo', '更新 FreeVideo'], message: label.textContent})); + problem ||= issueButton(t, () => { + const launcher = value?.launcher; + return {where: ['Update FreeVideo', '更新 FreeVideo'], message: issueText || label.textContent, + facts: launcher?.error ? {launcher_error: String(launcher.error), launcher_status: launcher.status, launcher_phase: launcher.phase || ''} : null}; + }); element.append(problem); } else problem?.remove(); details.hidden = !actions; diff --git a/web/upscale_offer.js b/web/upscale_offer.js new file mode 100644 index 00000000..0cbb3462 --- /dev/null +++ b/web/upscale_offer.js @@ -0,0 +1,66 @@ +// "Upscale to W × H" on a finished video: one 1.5× step, offered only when this computer can generate +// that size and length. Menus are built synchronously, so answers are read ahead and kept per size. + +// 1.5× keeps the aspect exactly and lands on the engine's 32-pixel grid only for sides that are multiples of 64. +export function upscaleSize(width, height) { + if (![width, height].every(n => Number.isSafeInteger(n) && n > 0 && n % 64 === 0)) return null; + return {width: width * 3 / 2, height: height * 3 / 2}; +} + +// The work's own picture: finished (not a preview), 24 fps and of a known length. +export function upscaleSource(row) { + const g = row?.geometry || {}; + if (!row || row.kind === 'image' || row.preview) return null; + if ((g.fps ?? 24) !== 24 || !Number.isSafeInteger(g.frames) || g.frames < 1) return null; + const size = upscaleSize(g.width, g.height); + return size && {...size, frames: g.frames}; +} + +// The 4K size (frame_upscale.size): the long side 3840 and the other side in proportion on an 8-pixel grid, scaled down +// in proportion until the picture has at most 36864 16 × 16 macroblocks (H.264's usual limit); null when that would +// not make the picture larger. +const LONG_SIDE = 3840, MAX_MACROBLOCKS = 36864; +const grid = value => Math.floor(value / 8 + .5) * 8; +export function upscale4kSize(width, height) { + if (![width, height].every(n => Number.isSafeInteger(n) && n > 0)) return null; + const longest = Math.max(width, height); + for (let side = LONG_SIDE; side >= 8; side -= 8) { + const w = grid(width * side / longest), h = grid(height * side / longest); + if (Math.min(w, h) >= 8 && Math.ceil(w / 16) * Math.ceil(h / 16) <= MAX_MACROBLOCKS) + return Math.max(w, h) > longest ? {width: w, height: h} : null; + } + return null; +} + +// A finished 24 fps video the 4K size makes larger. The small model runs on any card, so nothing is asked first. +export function upscale4kOffer(row) { + const g = row?.geometry || {}; + if (!row || row.kind === 'image' || row.preview) return null; + if ((g.fps ?? 24) !== 24 || !Number.isSafeInteger(g.frames) || g.frames < 1) return null; + return upscale4kSize(g.width, g.height); +} + +// `read(width, height)` resolves to the longest single request in frames at that size, or null when not known. +export function createUpscaleOffer(read) { + const answers = new Map(), pending = new Map(); + const key = size => `${size.width}x${size.height}`; + function prepare(rows) { + const sizes = new Map(); + for (const row of rows) { const size = upscaleSource(row); if (size) sizes.set(key(size), size); } + return Promise.all([...sizes].map(([name, size]) => { + if (answers.has(name)) return answers.get(name); + if (!pending.has(name)) pending.set(name, Promise.resolve().then(() => read(size.width, size.height)).catch(() => null) + .then(frames => { pending.delete(name); answers.set(name, Number.isSafeInteger(frames) ? frames : null); return answers.get(name); })); + return pending.get(name); + })); + } + // The target size when this work can be upscaled here now; null hides the row. + function offer(row) { + const size = upscaleSource(row); + const frames = size && answers.get(key(size)); + return size && Number.isSafeInteger(frames) && size.frames <= frames ? {width: size.width, height: size.height} : null; + } + // A change of free memory or engine state can change every answer. + const forget = () => answers.clear(); + return {prepare, offer, forget}; +} diff --git a/web/user_message.js b/web/user_message.js new file mode 100644 index 00000000..012d407e --- /dev/null +++ b/web/user_message.js @@ -0,0 +1,44 @@ +// One sentence a person can act on for any caught error. Text FreeVideo wrote for people (already in the user's +// language) is kept; what only a browser or a program would say (“Failed to fetch”, “Unexpected token '<'”, an +// error code, “HTTP 500”) is replaced by the cause in plain words and what to do next. The raw text stays in the +// error itself for reports and technical details. +import {browserExtensionAdvice, connectionLostText, detectBrowserExtension, isNetworkTypeError, wrappedFetchOnly} from './browser_extension.js'; + +// Wording a browser, a JavaScript engine or a server produces, never FreeVideo's own sentences. +const RAW = [ + /^(?:[A-Z][A-Za-z]*)?(?:Error|Exception)\b|\[(?:Errno|WinError) -?\d+\]/, // TypeError…, OSError, [Errno 28] + /Failed to fetch|fetch failed|NetworkError|network request failed|Load failed|ERR_[A-Z_]+/i, + /Unexpected (?:token|end of (?:JSON )?input|non-whitespace)|is not valid JSON|JSON\.parse|JSON at position/i, + /Cannot read propert|Cannot set propert|is not a function|is not defined|is not iterable|undefined is not|null is not/, + /^(?:HTTP\s*)?\d{3}(?:\s+[A-Za-z ]+)?$/i, + /^[a-z][a-z0-9]*(?:[_.:-][a-z0-9]+)+$/, // a code such as editor_request or generation_failed + /^\[object \w+\]$|Traceback \(most recent call last\)|\bat (?:\S+ \()?\S*[/.]\S*:\d+:\d+\)?$/m, +]; +export const isRawErrorText = text => RAW.some(pattern => pattern.test(String(text).trim())); + +const statusOf = error => { + const status = Number(error?.status ?? error?.response?.status); + if (Number.isInteger(status) && status >= 100 && status < 600) return status; + const said = /\bHTTP\s*(\d{3})\b/.exec(typeof error === 'string' ? error : String(error?.message ?? '')); + return said ? Number(said[1]) : null; +}; + +export function userMessage(error, t, fallback = t('Did not finish. Try again.', '没有完成,请重试。')) { + if (error == null || error === '') return fallback; + const network = isNetworkTypeError(error) || error?.notEngineReply === true; + // A recent console line from an extension is weighed only when this error is itself a failed request; + // otherwise only this error's own text and stack can name an extension. + const extension = detectBrowserExtension(error, network ? {} : {logs: []}); + if (extension && !wrappedFetchOnly(extension)) return browserExtensionAdvice(extension, t).summary; + if (network) return connectionLostText(t); + const status = statusOf(error); + if (error?.name === 'SyntaxError') { + return status ? t(`FreeVideo sent a reply this page could not read (HTTP ${status}). Try again, and report the problem if it happens again.`, + `FreeVideo 的回复无法读取(HTTP ${status})。请重试,再次出现请提交问题。`) + : t('FreeVideo sent a reply this page could not read. Try again, and report the problem if it happens again.', + 'FreeVideo 的回复无法读取。请重试,再次出现请提交问题。'); + } + const said = (typeof error === 'string' ? error : typeof error?.message === 'string' ? error.message : '').trim(); + if (said && !isRawErrorText(said)) return said; + return status ? t(`FreeVideo returned an error (HTTP ${status}). `, `FreeVideo 返回了错误(HTTP ${status})。`) + fallback : fallback; +} diff --git a/web/workflow_drafts.js b/web/workflow_drafts.js new file mode 100644 index 00000000..4d81e9be --- /dev/null +++ b/web/workflow_drafts.js @@ -0,0 +1,30 @@ +// With ComfyUI's workflow drafts off, the copies an older session left in this +// browser are never read again, but they still hold the prompts. Remove them. +// Nothing changes while drafts are on: that ComfyUI is the user's to run. + +const PERSIST = 'Comfy.Workflow.Persist'; +// Drafts (current and older formats), their index and order, the last open path, +// and the two single-workflow keys older frontends kept. +const PREFIXES = ['Comfy.Workflow.Draft', 'Comfy.Workflow.LastActivePath']; +const EXACT = new Set(['Comfy.PreviousWorkflow', 'workflow']); + +export const isWorkflowDraftKey = key => typeof key === 'string' && (EXACT.has(key) || PREFIXES.some(prefix => key.startsWith(prefix))); + +// Returns how many keys were removed; storage errors leave the rest in place. +export function clearWorkflowDrafts({storage = globalThis.localStorage, persist} = {}) { + if (persist !== false || !storage) return 0; + let removed = 0; + try { + const keys = []; + for (let i = 0; i < storage.length; i++) { const key = storage.key(i); if (isWorkflowDraftKey(key)) keys.push(key); } + for (const key of keys) { storage.removeItem(key); removed++; } + } catch { /* No storage access: nothing more to remove. */ } + return removed; +} + +// ComfyUI's settings store, or the older settings dialog. +export function workflowPersist(app) { + const store = app?.extensionManager?.setting; + if (typeof store?.get === 'function') return store.get(PERSIST); + return app?.ui?.settings?.getSettingValue?.(PERSIST); +}