diff --git a/freevideo b/freevideo index adbcb312..5a9350aa 100755 --- a/freevideo +++ b/freevideo @@ -5,4 +5,4 @@ export PYTHONPATH="$FREEVIDEO_SOURCE_DIR${PYTHONPATH:+:$PYTHONPATH}" source "$FREEVIDEO_SOURCE_DIR/scripts/bootstrap_linux.sh" freevideo_bootstrap_linux cli "$@" (( FREEVIDEO_BOOTSTRAP_DONE == 0 )) || exit 0 -exec "$FREEVIDEO_BOOTSTRAP_PYTHON" -B -X utf8 -m freevideo_engine.managed "${FREEVIDEO_BOOTSTRAP_ARGS[@]}" +exec "$FREEVIDEO_BOOTSTRAP_PYTHON" -B -X utf8 "$FREEVIDEO_SOURCE_DIR/freevideo_engine/installed_entry.py" freevideo_engine.managed "${FREEVIDEO_BOOTSTRAP_ARGS[@]}" diff --git a/freevideo.ps1 b/freevideo.ps1 index aaad2748..97451f97 100644 --- a/freevideo.ps1 +++ b/freevideo.ps1 @@ -188,7 +188,7 @@ try { foreach ($name in @('UV_HTTP_TIMEOUT', 'UV_HTTP_RETRIES')) { [Environment]::SetEnvironmentVariable($name, $freevideoSavedEnvironment[$name], 'Process') } - & $freevideoPython @freevideoPythonPrefix -B -X utf8 -m freevideo_engine.managed @freevideoArguments + & $freevideoPython @freevideoPythonPrefix -B -X utf8 (Join-Path $PSScriptRoot 'freevideo_engine\installed_entry.py') freevideo_engine.managed @freevideoArguments $freevideoExit = $LASTEXITCODE if ($freevideoExit -gt 127 -or $freevideoExit -lt 0) { # A crash or a blocked start prints nothing, so the exit code was all a report held. diff --git a/freevideo_engine/agent/cast.py b/freevideo_engine/agent/cast.py index e83633c2..57ee5f0b 100644 --- a/freevideo_engine/agent/cast.py +++ b/freevideo_engine/agent/cast.py @@ -29,6 +29,7 @@ EDITABLE = ('name', 'description', 'images', 'voice') MAX_IMAGES = 6 MAX_CANDIDATES = 6 +MAX_LORAS = 8 MAX_RECEIPTS = 64 # The FreeVideo input files that cards the user deleted named, by private_store token, with the time noted. RELEASED = 'released.json' @@ -140,6 +141,11 @@ def row_view(card): generate_error=errors.with_reason(card.get('generate_error'))) +def _loras(rows): + """The image LoRAs a card keeps for its own picture maker: file, strength and whether it is on, in the order given.""" + return [dict(name=row['name'], strength=float(row.get('strength', 1.)), enabled=row.get('enabled', True)) for row in rows or []] + + def _plain(item): """The input file an image item names unchanged (a returned card file), else None.""" if isinstance(item, str): @@ -200,6 +206,10 @@ def _check(record, stem): if not isinstance(row['label'], str) or not isinstance(row['media']['file'], str): raise ValueError('Invalid picture') unknown_labels |= row['label'] not in LABELS + loras = card.setdefault('loras', []) + if not isinstance(loras, list) or len(loras) > MAX_LORAS or not all( + isinstance(row, dict) and isinstance(row.get('name'), str) for row in loras): + raise ValueError('Invalid LoRAs') if card['voice'] is not None: if not isinstance(card['voice']['clip']['file'], str) or not ( isinstance(card['voice']['media'].get('file'), str) or isinstance(card['voice']['media'].get('library'), str)): @@ -485,6 +495,7 @@ def create(self, value, *, by='builtin', ref=None, made_for=None, local=True, cl entry = self._picture_at(identity, row['media'], by, index) images.append(dict(entry, label=row.get('label', 'other'))) voice = self._voice(identity, value['voice']) if value.get('voice') else None + loras = _loras(value.get('loras')) with self.changed: digest, replay = self._receipt('cast:create', value, ref, client) if replay is not None: @@ -493,7 +504,7 @@ def create(self, value, *, by='builtin', ref=None, made_for=None, local=True, cl supplied = dict(name=True, description=value.get('description') is not None, images=bool(images), voice=voice is not None) card = dict(id=identity, kind=value['kind'], name=value['name'], description=value.get('description'), - images=images, voice=voice, revision=1, created_at=stamp, updated_at=stamp, by=by, + images=images, voice=voice, loras=loras, revision=1, created_at=stamp, updated_at=stamp, by=by, origin=by, made_for=made_for, used_by=[], edited_by_user={k: by == 'user' and supplied[k] for k in EDITABLE}, candidates=[], generating=None, generate_error=None, generated=None, _user_images=0) @@ -583,7 +594,8 @@ def update(self, identity, value, *, by='builtin', ref=None, revision=None, loca card.update(resolved, revision=card['revision'] + 1, updated_at=self._now(), by=by) if by == 'user': for key in resolved: - card['edited_by_user'][key] = True + if key in card['edited_by_user']: + card['edited_by_user'][key] = True result = view(card) self._remember(record, ref, digest, result, client) if resolved or ref is not None: @@ -634,9 +646,12 @@ def _changes(self, card, value, by): and voice.get('end', current['end']) == current['end'] if not same: changes['voice'] = voice + if 'loras' in value and _loras(value['loras']) != card.get('loras', []): + changes['loras'] = _loras(value['loras']) if by != 'user': for key in changes: - if key != 'images' and card['edited_by_user'][key]: + # The LoRAs are the card's own record of how its picture was made: the card dialog sets them, nobody guards them. + if key not in ('images', 'loras') and card['edited_by_user'][key]: raise self._by_user(card, key) return changes diff --git a/freevideo_engine/agent/cli.py b/freevideo_engine/agent/cli.py index 3d6d1912..b157e919 100644 --- a/freevideo_engine/agent/cli.py +++ b/freevideo_engine/agent/cli.py @@ -7,8 +7,8 @@ Linux x86_64 uses ./freevideo; Windows uses freevideo.cmd. On macOS and other Unix platforms, use the installed interpreter and source folder: - env FREEVIDEO_AGENT=1 PYTHONPATH=/path/to/FreeVideo/engine-source \ - /path/to/installed/python -X utf8 -m freevideo_engine.agent.cli --root /path/to/FreeVideo status + env FREEVIDEO_AGENT=1 PYTHONPATH=/path/to/FreeVideo/engine-source /path/to/installed/python -X utf8 \ + /path/to/FreeVideo/engine-source/freevideo_engine/installed_entry.py freevideo_engine.agent.cli --root /path/to/FreeVideo status """ import argparse import json diff --git a/freevideo_engine/agent/errors.py b/freevideo_engine/agent/errors.py index 353e9626..33b025cd 100644 --- a/freevideo_engine/agent/errors.py +++ b/freevideo_engine/agent/errors.py @@ -320,7 +320,7 @@ def safe_details(value): FAILURE_REASONS_ZH = { **LORA_MESSAGE_ZH, 'too_large': '这条消息太长,请缩短或分成两条发送', - 'lan_unavailable': '局域网设置需要启动器安装记录', + 'lan_unavailable': '手机连接需要用启动器安装的 FreeVideo', 'capabilities_computing': '正在计算这台电脑的生成能力,稍后再试', 'out_of_memory': '生成时显存或内存不足', 'insufficient_memory': '可用显存或内存不足,无法生成这段内容', @@ -565,6 +565,78 @@ def safe_details(value): 'invalid_seed': '清空种子或改用较小的整数后再试', 'too_many_images': '减少参考图后再试', 'output_unwritable': '确认输入目录下的 freevideo-image 文件夹存在、可写且没有同名文件后再试', + 'invalid_lora_strength': '把强度调到 -2 到 2 之间后再试', + 'lan_unavailable': '先用启动器安装 FreeVideo,再打开“手机连接”', + 'turn_abandoned': '需要时重新提交', + 'insufficient_memory': '关闭其他占用显卡的程序,或缩小尺寸、缩短时长后再试', + 'no_memory': '关闭其他占用显卡的程序,或缩小图片尺寸后再试', + 'ram_space': '关闭其他占用内存的程序后再试', + 'model_missing': '在启动器或设置中安装所需模型后再试', + 'pack_missing': '在启动器或设置中安装图片模型后再试', + 'model_unavailable': '换一个图片模型后再试', + 'not_ready': '在启动器或设置中完成安装或修复后再试', + 'cancelled': '需要时重新提交', + 'stopped_by_user': '需要时重新提交', + 'interrupted': '再试一次', + 'worker_exit': '再试一次;再次出现时,请点击“提交问题”', + 'closed': '在启动器里重新启动 FreeVideo 后再试', + 'image_unavailable': '稍等片刻后再试;仍不行时,在启动器里重新启动 FreeVideo', + 'vlm_unavailable': '稍等片刻后再试;仍不行时,在启动器里重新启动 FreeVideo', + 'vlm_failed': '换一张更清晰的图片,或再试一次', + 'vlm_invalid_json': '再试一次', + 'context_length': '缩短描述或减少参考图后再试', + 'dependency_failed': '先处理前面失败的任务,再重新提交', + 'lost': '重新提交一次', + 'unknown_job': '刷新页面后查看任务列表,必要时重新提交', + 'not_found': '刷新页面后确认它还在,再重试', + 'source_missing': '找回或重新生成上一段视频后再接续', + 'chain_missing': '改为从完整视频重新接续', + 'not_resumable': '重新提交一个新任务', + 'chain_unavailable': '在启动器里重新启动 FreeVideo 后再试', + 'continuation_unavailable': '换一种生成方式,或重新生成整段视频', + 'join_failed': '检查磁盘空间后重新导出成片', + 'invalid_output': '检查磁盘空间后再试', + 'storage_unavailable': '检查磁盘空间和文件夹写入权限后再试', + 'disk_full': '清理磁盘空间后再试', + 'submit_interrupted': '查看任务列表确认是否已开始,没有再重新提交', + 'timeout': '再试一次;再次出现时,请缩短时长或降低尺寸', + 'invalid_media': '换一个能正常播放的文件后再试', + 'clip_unreadable': '重新生成这个角色参考视频后再试', + 'invalid_request': '把设置改到可用范围内后再试', + 'invalid_drama': '检查短剧设置后再试', + 'reshoot_limit': '改为选用已有的镜头,或新建一个镜头', + 'production_limit': '继续前,先完成或删除不需要的任务', + 'export_failed': '检查磁盘空间后重新导出', + 'chain_too_long': '缩短接续的内容,或减少段数后再试', + 'chain_short_parts': '把短于 10 秒的段合并或重新生成后再试', + 'chain_rejected': '更换尺寸或时长后再试', + 'local_only': '在运行 FreeVideo 的电脑上操作', + 'page_required': '在浏览器中打开 FreeVideo 页面后再操作', + 'conflict': '等当前任务结束,或刷新页面后再试', + 'invalid_edit': '检查编辑设置后再试', + 'invalid_screenplay': '按提示修改剧本后再试', + 'unsupported_media': '换一张图片后再试', + 'unknown_shot': '刷新页面后选择现有的镜头', + 'unknown_take': '刷新页面后选择这个镜头里现有的一条', + 'take_not_ready': '重新生成这一条,或选另一条', + 'chosen_by_user': '要更换时,请在页面上手动改选', + 'nothing_to_cancel': '无需操作,需要时再提交新任务', + 'not_allowed': '在页面上手动停止或继续这部短剧', + 'already_ended': '需要时新建一部短剧', + 'needs_confirmation': '确认后再执行这项操作', + 'declined_by_user': '需要时重新提出这项操作', + 'stale_revision': '刷新页面查看最新内容后再改', + 'changed_by_user': '按手动修改后的内容继续,或刷新页面后重新操作', + 'card_in_use': '等短剧结束,或先停止它后再改这张卡片', + 'project_changed': '刷新页面查看最新内容后再改', + 'image_changed': '刷新页面查看最新内容后再改', + 'speech_language': '换一段受支持语言的声音,或手动填写字幕', + 'listen_failed': '再试一次,或手动填写字幕', + 'music_failed': '再试一次', + 'stems_failed': '再试一次', + 'sound_failed': '再试一次', + 'voice_failed': '再试一次', + 'small_memory': '在内存 16 GB 及以上的 Mac 上使用图片生成', } FAILURE_NEXT_EN = { 'generation_failed': 'If it happens again, use "Report a problem"', @@ -597,6 +669,78 @@ def safe_details(value): 'invalid_seed': 'Clear the seed or use a smaller whole number, then try again', 'too_many_images': 'Remove some reference pictures, then try again', 'output_unwritable': 'Check that the freevideo-image folder in the input directory exists, is writable and has no file of the same name, then try again', + 'invalid_lora_strength': 'Set the strength between -2 and 2, then try again', + 'lan_unavailable': 'Install FreeVideo with the launcher first, then turn on Phone access', + 'turn_abandoned': 'Submit it again when needed', + 'insufficient_memory': 'Close other programs that use the graphics card, or use a smaller size or a shorter length, then try again', + 'no_memory': 'Close other programs that use the graphics card, or use a smaller picture size, then try again', + 'ram_space': 'Close other programs that use memory, then try again', + 'model_missing': 'Install the required model in the launcher or in Settings, then try again', + 'pack_missing': 'Install the picture model in the launcher or in Settings, then try again', + 'model_unavailable': 'Choose another picture model, then try again', + 'not_ready': 'Finish the installation or repair in the launcher or in Settings, then try again', + 'cancelled': 'Submit it again when needed', + 'stopped_by_user': 'Submit it again when needed', + 'interrupted': 'Try again', + 'worker_exit': 'Try again; if it happens again, use "Report a problem"', + 'closed': 'Restart FreeVideo from the launcher, then try again', + 'image_unavailable': 'Wait a moment and try again; if it still fails, restart FreeVideo from the launcher', + 'vlm_unavailable': 'Wait a moment and try again; if it still fails, restart FreeVideo from the launcher', + 'vlm_failed': 'Try a clearer picture, or try again', + 'vlm_invalid_json': 'Try again', + 'context_length': 'Shorten the description or use fewer reference pictures, then try again', + 'dependency_failed': 'Fix the earlier task that failed, then submit this one again', + 'lost': 'Submit it again', + 'unknown_job': 'Reload the page and check the task list; submit again if needed', + 'not_found': 'Reload the page and make sure it still exists, then try again', + 'source_missing': 'Restore or regenerate the previous video, then continue it', + 'chain_missing': 'Continue again from the finished video instead', + 'not_resumable': 'Submit a new task', + 'chain_unavailable': 'Restart FreeVideo from the launcher, then try again', + 'continuation_unavailable': 'Choose another way of generating, or generate the whole video again', + 'join_failed': 'Check the free disk space, then export the film again', + 'invalid_output': 'Check the free disk space, then try again', + 'storage_unavailable': 'Check the free disk space and the write access to the folder, then try again', + 'disk_full': 'Free up disk space, then try again', + 'submit_interrupted': 'Check the task list to see whether it started; submit again if it did not', + 'timeout': 'Try again; if it happens again, use a shorter length or a smaller size', + 'invalid_media': 'Use a file that plays normally, then try again', + 'clip_unreadable': 'Generate the character reference video again, then try again', + 'invalid_request': 'Change the settings to a supported range, then try again', + 'invalid_drama': 'Check the drama settings, then try again', + 'reshoot_limit': 'Choose one of the existing takes, or add a new shot', + 'production_limit': 'Finish or delete tasks you no longer need before continuing', + 'export_failed': 'Check the free disk space, then export again', + 'chain_too_long': 'Shorten what you continue, or use fewer parts, then try again', + 'chain_short_parts': 'Merge or regenerate the parts shorter than 10 seconds, then try again', + 'chain_rejected': 'Change the size or the length, then try again', + 'local_only': 'Do this on the computer that runs FreeVideo', + 'page_required': 'Open the FreeVideo page in the browser, then do this there', + 'conflict': 'Wait for the current task to end, or reload the page, then try again', + 'invalid_edit': 'Check the edit settings, then try again', + 'invalid_screenplay': 'Change the screenplay as indicated, then try again', + 'unsupported_media': 'Use a picture instead, then try again', + 'unknown_shot': 'Reload the page and choose an existing shot', + 'unknown_take': 'Reload the page and choose a take that this shot has', + 'take_not_ready': 'Generate this take again, or choose another one', + 'chosen_by_user': 'To change it, choose another take on the page', + 'nothing_to_cancel': 'Nothing to do; submit a new task when needed', + 'not_allowed': 'Stop or continue this drama on the page', + 'already_ended': 'Start a new drama when needed', + 'needs_confirmation': 'Confirm first, then run this action', + 'declined_by_user': 'Ask for this action again when needed', + 'stale_revision': 'Reload the page to see the latest content, then change it again', + 'changed_by_user': 'Continue from the content you edited by hand, or reload the page and try again', + 'card_in_use': 'Wait for the drama to end, or stop it first, then change this card', + 'project_changed': 'Reload the page to see the latest content, then change it again', + 'image_changed': 'Reload the page to see the latest content, then change it again', + 'speech_language': 'Use a sound in a supported language, or write the subtitles by hand', + 'listen_failed': 'Try again, or write the subtitles by hand', + 'music_failed': 'Try again', + 'stems_failed': 'Try again', + 'sound_failed': 'Try again', + 'voice_failed': 'Try again', + 'small_memory': 'Use picture generation on a Mac with 16 GB of memory or more', } FAILURE_MESSAGES_ZH = { 'The previous video is too short to continue; it needs to be at least 1.7 s long.': '接续的上一段视频太短,至少需要 1.7 秒', diff --git a/freevideo_engine/agent/mcp.py b/freevideo_engine/agent/mcp.py index 8b01fc7d..8e340366 100644 --- a/freevideo_engine/agent/mcp.py +++ b/freevideo_engine/agent/mcp.py @@ -4,8 +4,8 @@ freevideo.cmd mcp # Windows ./freevideo mcp --print-config # Linux client configuration # macOS / other Unix platforms: use the installed Python and source folder. - env FREEVIDEO_AGENT=1 PYTHONPATH=/path/to/FreeVideo/engine-source \ - /path/to/installed/python -X utf8 -m freevideo_engine.agent.mcp --root /path/to/FreeVideo + env FREEVIDEO_AGENT=1 PYTHONPATH=/path/to/FreeVideo/engine-source /path/to/installed/python -X utf8 \ + /path/to/FreeVideo/engine-source/freevideo_engine/installed_entry.py freevideo_engine.agent.mcp --root /path/to/FreeVideo # Add --print-config to print client configuration. Standard library only; it talks to the running ComfyUI through the agent API. @@ -505,7 +505,7 @@ def linux_wrapper_supported(): def python_shell_command(config, module): """Direct Unix entry using this installation's interpreter, source and root.""" command = list(config['command']) - command[command.index('-m') + 1] = module + command[command.index('freevideo_engine.agent.mcp')] = module command[1:1] = ['-X', 'utf8'] env = ['FREEVIDEO_AGENT=1'] + [key + '=' + value for key, value in config['env'].items()] return 'env ' + ' '.join(shell_quote(value) for value in env + command) @@ -519,14 +519,15 @@ def client_config(root): python = machine['python'] except (OSError, ValueError, KeyError): python = sys.executable - command = [python, '-B', '-m', 'freevideo_engine.agent.mcp', '--root', str(root)] - env = {'PYTHONPATH': str(Path(__file__).resolve().parents[2])} + source = Path(__file__).resolve().parents[2] + command = [python, '-B', str(source / 'freevideo_engine' / 'installed_entry.py'), 'freevideo_engine.agent.mcp', '--root', str(root)] + env = {'PYTHONPATH': str(source)} shell_command = list(command) if sys.platform != 'win32' and not linux_wrapper_supported(): shell_command[1:1] = ['-X', 'utf8'] # Keep JSON argv untouched. Windows command text targets Command Prompt. - assignment = shell_quote('PYTHONPATH=' + env['PYTHONPATH']) if sys.platform == 'win32' else \ - 'PYTHONPATH=' + shell_quote(env['PYTHONPATH']) + assignment = ' --env '.join(shell_quote(key + '=' + value) if sys.platform == 'win32' else key + '=' + shell_quote(value) + for key, value in env.items()) return dict(command=command, env=env, codex='codex mcp add freevideo --env %s -- %s' % ( assignment, ' '.join(shell_quote(p) for p in shell_command)), mcp_json={'mcpServers': {'freevideo': { 'command': command[0], 'args': command[1:], 'env': env}}}, diff --git a/freevideo_engine/agent/schema.py b/freevideo_engine/agent/schema.py index 2a556d8b..8989438d 100644 --- a/freevideo_engine/agent/schema.py +++ b/freevideo_engine/agent/schema.py @@ -775,7 +775,8 @@ def cast_schema(name, *, local=False): sound['oneOf'][1]['allOf'] = sound['oneOf'][1]['allOf'][:1] fields = dict(name=string(120), description=nullable(string(1000)), images=array(obj(dict(media=picture, label=enum(LABELS)), ('media',)), 0, 6), - voice=nullable(obj(dict(media=sound, start=number(0, 3600, default=0), end=number(0, 3600)), ('media',)))) + voice=nullable(obj(dict(media=sound, start=number(0, 3600, default=0), end=number(0, 3600)), ('media',))), + loras=image_loras()) if name == 'create': return obj(dict(kind=enum(('character', 'setting', 'prop', 'image'), default='character'), **fields, ref=REF), ('name',)) if name == 'update': @@ -811,7 +812,8 @@ def cast_view(): images=array(picture, 0, 6), candidates=array(picture, 0, 6), generating=nullable(generating), generated=nullable(generated), generate_error=nullable(obj(dict(code=string(), job=JOB, message=string(), error_zh=string(), error_en=string(), - next_zh=string(), next_en=string()), ('code', 'job', 'message')))), + next_zh=string(), next_en=string()), ('code', 'job', 'message'))), + loras=array(obj(dict(name=string(512), strength=number(-2, 2), enabled={'type': 'boolean'}), ('name', 'strength', 'enabled')), 0, 8)), ('id', 'kind', 'name', 'revision', 'images', 'candidates', 'generating')), additionalProperties=True) diff --git a/freevideo_engine/bootstrap.py b/freevideo_engine/bootstrap.py index d85cc0ae..907c1075 100644 --- a/freevideo_engine/bootstrap.py +++ b/freevideo_engine/bootstrap.py @@ -31,6 +31,7 @@ from .install_tuning import build_parallelism, required_models, cache_compatible, wheel_key from .terminal_ui import TerminalUI, LogProgress from .locking import runtime_lock, LOCK_ENV +from .installed_entry import INSTALLED_ONLY from .environments import (ENVIRONMENTS, environment_spec, windows_arm64, environment_native_arm64, environment_names, select_layout, role_pythons, constraints_file, setup_supported, uv_folder, conda_lock, conda_triple, bootstrap_versions, uv_file_arguments, uv_build_environment) from . import disk_space @@ -836,8 +837,37 @@ def plan(args, *, local_progress=None, stage=None): model_entries = [] from . import model_repair mismatches = model_repair.read(root) + # The picture models' check records the files it found different in its own folder: a file the video install shares + # (the text encoder) is then listed for the review by any plan, not only a picture-only one. + from .image_gen import image_pack + try: + pack_records = model_repair.read(image_pack.base(model_dir)) + except OSError: + pack_records = {} # unreadable now (a scanner, a file where the folder should be): nothing to add, nothing breaks + for key, record in pack_records.items(): + # Both places may hold a record of one file: the one whose identity is the file's now is the current one. + # A path that cannot be looked at (a disk that is not there, no permission, a character it cannot hold) keeps + # the installation folder's record, and the other records are merged all the same. + try: + if key in mismatches: + current = model_repair.identity(Path(key)) + if (not model_repair.same_identity(current, mismatches[key]) + and model_repair.same_identity(current, record)): + mismatches[key] = record + else: + mismatches[key] = record + except (OSError, ValueError): + mismatches.setdefault(key, record) replace_models = [] reserved = set() + if only_image: + # The shared text encoder (the video model's file too) that a picture-only setup would otherwise refuse to + # touch: a file that differs is listed for the review like any model, and replaced only after it. + for row in image_pack.rows(group=image_group): + if row.get('shared'): + replacement = model_repair.replacement(image_pack.target(row, model_dir), row, mismatches, reserved) + if replacement: + replace_models.append(replacement) check_download_list = bool(getattr(args, 'download_list', False)) stamps_path = root / 'verified-models.json' stamps = load_ledger(stamps_path, retain=False) if check_download_list else {} @@ -1793,7 +1823,7 @@ def task(name, run, after=(), writes=()): # This entry imports only stdlib engine code from the bootstrap Python. # It can fetch the exact source trees while large Torch wheels download. task('vdn-source', lambda: self.command('vdn-source', [sys.executable, '-c', - 'from freevideo_engine.install import install; install()']), after=('git',)) + INSTALLED_ONLY + 'from freevideo_engine.install import install; install()']), after=('git',)) task('encoder-source', lambda: self.clone('h3-text-encoder', self.spec['encoder']['comfy_url'], self.spec['encoder']['comfy_commit'], sparse=['/comfy/', '/utils/', '/folder_paths.py', '/node_helpers.py', '/LICENSE']), after=('git',)) @@ -1939,7 +1969,20 @@ def progress(value): self.ui.update(key, done=done, total=total, unit='bytes', activity='download', name='MiniMax H3 Image', detail='%.1f GiB / %.1f GiB' % (done / 2**30, total / 2**30)) try: - image_pack.install(Path(self.plan['model_dir']), progress, engine_root=SOURCE, group=self.plan['image_group']) + # The reviewed and confirmed shared files may be replaced; without any, a file that differs stops the install. + image_pack.install(Path(self.plan['model_dir']), progress, engine_root=SOURCE, group=self.plan['image_group'], + confirm=self.plan.get('replace_models') or None) + except image_pack.PackError as error: + self.ui.end(key, success=False) + from . import model_repair + path = error.details.get('path') + if error.reason == 'shared_mismatch' and path: + raise ValueError(model_repair.MISMATCH + ': ' + Path(path).name + '\n' + + model_repair.MISMATCH_PATH + ': ' + path + '\n' + + model_repair.CLI_FAILURE.format(file=Path(path).name)) from error + if error.reason == 'confirm_replace': + raise ValueError(model_repair.FILE_CHANGED + ' ' + ', '.join(row['path'] for row in error.details['replace'])) from error + raise except BaseException: self.ui.end(key, success=False) raise diff --git a/freevideo_engine/chain_errors.py b/freevideo_engine/chain_errors.py index 666a9d55..f8b31f69 100644 --- a/freevideo_engine/chain_errors.py +++ b/freevideo_engine/chain_errors.py @@ -18,6 +18,11 @@ '长视频文件读写失败。请确认 FreeVideo 文件夹可以打开且不是只读,然后重试。'), 'unknown_chain': ('This long video was not found. Reload the page to see the current list.', '找不到这个长视频。请刷新页面查看当前列表。'), + # The failure card shows it in its own words (web/error_panel.js REDO_CHANGED). + 'redo_request_changed': ('This redo was already submitted with the earlier settings. Check the queue first. ' + 'If you still want the current settings, choose "Redo from here" again.', + '这次重新生成已按之前的设置提交过。请先查看队列;' + '仍需要按现在的设置生成时,再点一次“从这段重新生成”。'), } HOST_UNAVAILABLE = { 'after': ('Extend is not available in this version. Update FreeVideo and try again.', diff --git a/freevideo_engine/chain_runner.py b/freevideo_engine/chain_runner.py index b707e719..43caf9e3 100644 --- a/freevideo_engine/chain_runner.py +++ b/freevideo_engine/chain_runner.py @@ -1,5 +1,6 @@ """Durable chains, submitting ordinary host prompts by dependency.""" from copy import deepcopy +import hashlib import json import logging import math @@ -43,6 +44,29 @@ class ChainBusy(ValueError): pass +class RedoRequestChanged(ValueError): + """A redo came with the name of another one that had other parameters.""" + + +REDO_REQUEST_ID = re.compile(r'[A-Za-z0-9-]{1,64}') + + +def _redo_request(request_id, chain_id, block_id, text): + """What a redone chain keeps of the page's request: its name and a digest of what was asked. None without a + usable name. It stays in the record: no reply, report or log carries it.""" + if not isinstance(request_id, str) or not REDO_REQUEST_ID.fullmatch(request_id): + return None + asked = json.dumps([chain_id, block_id, text], ensure_ascii=True) + return dict(id=request_id, asked=hashlib.sha256(asked.encode('ascii')).hexdigest()) + + +def _is_redo_request(value): + # A record without one, or with anything else in its place, reads as one that has none. + return (isinstance(value, dict) and set(value) == {'id', 'asked'} and isinstance(value['id'], str) + and REDO_REQUEST_ID.fullmatch(value['id']) is not None and isinstance(value['asked'], str) + and re.fullmatch(r'[0-9a-f]{64}', value['asked']) is not None) + + class ChainTooLong(ValueError): """A chain that would continue a video through more parts than a video may have.""" code = 'chain_too_long' @@ -503,16 +527,27 @@ def resume(self, chain_id, client_id=None): self.wake.set() return self._view(record) - def redo(self, chain_id, block_id, text=None, client_id=None): + def redo(self, chain_id, block_id, text=None, client_id=None, request_id=None): """A new chain that keeps the parts before `block_id` and makes that part and every later one again with new seeds. Later parts continue the part before them, so redoing one part alone would - break the next seam. The original chain, its parts and its joined video stay as they are.""" + break the next seam. The original chain, its parts and its joined video stay as they are. + `request_id` names one press of the page: the same one again (its reply was lost) returns the chain it + made, and one that comes with other parameters is refused. The look-up, the new chain and its file are + under one lock, so two presses with one name at the same moment make one chain.""" if text is not None and (not isinstance(text, str) or not text.strip() or len(text) > 20000): raise ValueError('Text must be a nonempty string of at most 20000 characters') if client_id is not None and not isinstance(client_id, str): raise ValueError('Client ID must be a string') from .lora_triggers import apply_chain_triggers with self.lock: + request = _redo_request(request_id, chain_id, block_id, text) + if request is not None: + for row in self.records.values(): + made = row.get('redo_request') + if _is_redo_request(made) and made['id'] == request['id']: + if made != request: + raise RedoRequestChanged('This request was already used for another redo') + return self._view(row) source = self.records[chain_id] start = next((row for row in source['blocks'] if row['id'] == block_id), None) if start is None: @@ -530,9 +565,11 @@ def redo(self, chain_id, block_id, text=None, client_id=None): 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', - *OUTPUT_FIELDS): + 'redo_request', *OUTPUT_FIELDS): record.pop(key, None) now = self.wall() + if request is not None: + record['redo_request'] = request record.update(id=identity, created=now, state='queued', redo_of=dict(chain=chain_id, block=block_id), output=None, output_state='pending' if record['join'] else 'none', output_error=None, output_blocks=0) diff --git a/freevideo_engine/comfy_bridge.py b/freevideo_engine/comfy_bridge.py index 0c63bb1c..9ded062a 100644 --- a/freevideo_engine/comfy_bridge.py +++ b/freevideo_engine/comfy_bridge.py @@ -1385,7 +1385,7 @@ def engine_environment(root, source, environ=None): from .macos_bootstrap import environment else: from .triton_compat import environment - return environment(root, isolated_environment(root, source, environ)) + return dict(environment(root, isolated_environment(root, source, environ)), PYTHONSAFEPATH='1') def generate(prompt, width, height, seconds, seed, output_directory, *, diff --git a/freevideo_engine/comfy_chain.py b/freevideo_engine/comfy_chain.py index 5d285243..cd57dc65 100644 --- a/freevideo_engine/comfy_chain.py +++ b/freevideo_engine/comfy_chain.py @@ -10,7 +10,7 @@ import time from urllib import error, request -from .chain_runner import ChainBusy, ChainPartTooShort, ChainRunner, ChainTooLong +from .chain_runner import ChainBusy, ChainPartTooShort, ChainRunner, ChainTooLong, RedoRequestChanged from . import chain_plan, chain_store from .chain_errors import host_unavailable_body, route_body, storage_code @@ -463,6 +463,8 @@ def refused(failure, invalid_status=400): 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, RedoRequestChanged): # Not 409: the part list reads that as another video generating. + return response(route_body('redo_request_changed', str(failure)), 400) 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) @@ -565,7 +567,8 @@ async def redo(request): if missing: 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'))}) + value.get('text'), value.get('client_id'), + value.get('request_id'))}) except STORED as failure: return refused(failure) diff --git a/freevideo_engine/comfy_console.py b/freevideo_engine/comfy_console.py index 26b447da..a4c56273 100644 --- a/freevideo_engine/comfy_console.py +++ b/freevideo_engine/comfy_console.py @@ -82,9 +82,14 @@ def install(engine): root = Path(engine).resolve() / 'launcher/comfy-runs' managed = os.environ.get('FREEVIDEO_COMFY_LOG') if managed: - path = Path(managed).resolve() - path.relative_to(root) # Only the launcher's own output file is reusable. - return path + # Only the launcher's own output file is reusable. A value left by something else (a user's own + # start script, another tool) must not stop ComfyUI from starting: capture on our own instead. + try: + path = Path(managed).resolve() + path.relative_to(root.resolve()) + return path + except (OSError, ValueError): + pass capture = getattr(sys, '_freevideo_console', None) if capture is None: path = root / ('connected-%s-%s' % (time.time_ns(), os.getpid())) / 'comfy.log' diff --git a/freevideo_engine/comfy_launcher_runtime.py b/freevideo_engine/comfy_launcher_runtime.py index 3447818c..863070b9 100644 --- a/freevideo_engine/comfy_launcher_runtime.py +++ b/freevideo_engine/comfy_launcher_runtime.py @@ -546,6 +546,20 @@ def queue_state(url, timeout=3): return 'idle' if _refused(error) else 'unknown' +RETIRE_IDLE_SECONDS = 30. + + +def work_running(url): + """True while ComfyUI runs or holds a job, or its picture service is making a picture. An unreadable queue + counts as running; a picture service that does not answer (not installed) as not.""" + if not url or queue_state(url) != 'idle': + return bool(url) + try: + return get_json(loopback_url(url) + '/freevideo/image-gen', timeout=3).get('busy') is True + except (OSError, ValueError, AttributeError): + return False + + def queue_busy(url, timeout=3): """Preserve the legacy check; a pool must confirm every executor is idle, so an unreadable pool counts as busy.""" from .gpu_pool import pool_enabled @@ -770,7 +784,8 @@ class LauncherRunner(SetupRunner): def command(self, root, arguments): if arguments and arguments[0] == 'comfy-host': _, machine = installation(self.source, {'FREEVIDEO_HOME': str(root)}) - code = "import runpy,sys;sys.path.insert(0,sys.argv.pop(1));runpy.run_module('freevideo_engine.comfy_host',run_name='__main__')" + from .installed_entry import INSTALLED_ONLY + code = INSTALLED_ONLY + "import runpy;sys.path.insert(0,sys.argv.pop(1));runpy.run_module('freevideo_engine.comfy_host',run_name='__main__')" return [machine['python'], '-B', '-c', code, str(self.source), '--root', str(root), *arguments[1:]] return super().command(root, arguments) @@ -818,6 +833,10 @@ def retire_old_versions(self, selected): if self._old_versions_thread is not None and self._old_versions_thread.is_alive(): return def work(): + # Not while something is being made: removing a package file that is another name of an installed + # model changes that model's metadata under a generation reading it. Wait for an idle server. + while work_running(selected.get('url')): + time.sleep(RETIRE_IDLE_SECONDS) from .desktop_runtime import launcher_root from .launcher_update import current_build from .version_cleanup import run @@ -1532,6 +1551,8 @@ def _connect_comfy(self): env = (self.child_environment() if self.child_environment is not None else isolated_environment(selected['engine'], selected['source'])) env.pop('PYTHONPATH', None) + from .installed_entry import SAFE_PATH + env.pop(SAFE_PATH, None) # ComfyUI's main.py imports from its own folder env['PYTHONDONTWRITEBYTECODE'] = '1' env.update(PYTHONUNBUFFERED='1', PYTHONUTF8='1', PYTHONIOENCODING='utf-8') from .proxy import bypass_local diff --git a/freevideo_engine/comfy_pool.py b/freevideo_engine/comfy_pool.py index fda021e7..dc6abbbd 100644 --- a/freevideo_engine/comfy_pool.py +++ b/freevideo_engine/comfy_pool.py @@ -169,7 +169,8 @@ def _launch(self, device, port): 'FREEVIDEO_BACKGROUND_COMPILE': 'off', 'FREEVIDEO_PROMPT_PRESTART': 'off', 'FREEVIDEO_COMFY_LOG': str(directory / 'comfy.log'), 'PYTHONUNBUFFERED': '1'}) # Insert source explicitly: Windows portable Python ignores PYTHONPATH. - code = ('import runpy,sys;sys.path.insert(0,sys.argv.pop(1));' + from .installed_entry import INSTALLED_ONLY + code = (INSTALLED_ONLY + 'import runpy;sys.path.insert(0,sys.argv.pop(1));' 'p=sys.argv.pop(1);sys.path.insert(0,__import__("os").path.dirname(p));' 'runpy.run_path(p,run_name="__main__")') command = [sys.executable, '-u', '-B', '-c', code, str(self.source), str(comfy / 'main.py'), diff --git a/freevideo_engine/comfy_service.py b/freevideo_engine/comfy_service.py index 14dfab6c..14ee516a 100644 --- a/freevideo_engine/comfy_service.py +++ b/freevideo_engine/comfy_service.py @@ -105,7 +105,8 @@ def loopback(address): def host_setup(root, source, machine, comfy, *, download=False): """Run the ComfyUI environment setup; its exit code.""" # The engine's Python reads the CUDA packages the ComfyUI environment must match. - code = ("import runpy,sys;sys.path.insert(0,sys.argv.pop(1));" + from .installed_entry import INSTALLED_ONLY + code = (INSTALLED_ONLY + "import runpy;sys.path.insert(0,sys.argv.pop(1));" "runpy.run_module('freevideo_engine.comfy_host',run_name='__main__')") command = [machine['python'], '-B', '-c', code, str(source), '--root', str(root), '--comfy', str(comfy)] if download: @@ -283,7 +284,8 @@ def redirect_request(self, *args, **kwargs): def start_proxy(record, *, listen, port, upstream, token_file, tls, hop_secret=None): """Run the access proxy with ComfyUI's Python, which brings aiohttp.""" from . import processes - code = ("import runpy,sys;sys.path.insert(0,sys.argv.pop(1));" + from .installed_entry import INSTALLED_ONLY + code = (INSTALLED_ONLY + "import runpy;sys.path.insert(0,sys.argv.pop(1));" "runpy.run_module('freevideo_engine.access_proxy',run_name='__main__')") command = [record['python'], '-B', '-c', code, record['source'], '--listen', listen, '--port', str(port), '--upstream', upstream, '--token-file', str(token_file)] @@ -422,7 +424,7 @@ def spawn(root, *, port, listen='127.0.0.1', tls=None): 'run', '--port', str(port), '--listen', listen] if tls: command += ['--tls-cert', str(tls[0]), '--tls-key', str(tls[1])] - env = dict(os.environ, PYTHONPATH=str(source_root()), PYTHONNOUSERSITE='1') + env = dict(os.environ, PYTHONPATH=str(source_root()), PYTHONNOUSERSITE='1', PYTHONSAFEPATH='1') for name in ('FREEVIDEO_RUNTIME_LOCK_FD', 'FREEVIDEO_LOCK_PATH', 'PYTHONHOME', 'VIRTUAL_ENV'): env.pop(name, None) with (folder(root) / 'service.log').open('ab') as output: diff --git a/freevideo_engine/comfy_setup.py b/freevideo_engine/comfy_setup.py index 07d32bb1..df777b3e 100644 --- a/freevideo_engine/comfy_setup.py +++ b/freevideo_engine/comfy_setup.py @@ -81,6 +81,8 @@ def inspection_failed(value): else: parts.append('no exit code') parts.append('%d output lines' % int(value.get('lines') or 0)) + if type(value.get('winerror')) is int: + parts.append('Windows error %d' % value['winerror']) # A cancelled run never gets here: only a complete or failed plan is read, so cancelling is not a failure to report. if failed in ('TimeoutExpired', 'TimeoutError'): parts.append('timed out') diff --git a/freevideo_engine/desktop_runtime.py b/freevideo_engine/desktop_runtime.py index 732204cb..e82a14bf 100644 --- a/freevideo_engine/desktop_runtime.py +++ b/freevideo_engine/desktop_runtime.py @@ -420,6 +420,22 @@ def local_model_ui(message): remaining_seconds=(total-done)/rate if total and rate and phase in ('verify', 'copy') else None) +def start_failure_note(failure, command, source): + """One line for a child that could not be started: the system's error number and the files it was given.""" + code = getattr(failure, 'winerror', None) + parts = ['The task could not be started'] + if isinstance(code, int): + parts.append('Windows error %d' % code) + elif isinstance(failure.errno, int): + parts.append('error %d' % failure.errno) + if failure.filename: + parts.append('path %s' % failure.filename) + if command: + parts.append('program %s' % command[0]) + parts.append('folder %s' % source) + return ', '.join(parts) + + class Runner: def __init__(self, source, events, logs=None): self.source, self.events = Path(plain(source)), events @@ -478,7 +494,7 @@ def _run_awake(self, action, root, arguments): run = io_path(self.logs) / (time.strftime('%Y%m%dT%H%M%SZ', time.gmtime()) + '-' + uuid.uuid4().hex[:8]) code, output, error = None, '', None # what a report can say when the child left no text: how much it printed, and what stopped the run - lines, failed_with = 0, None + lines, failed_with, winerror, command, refused = 0, None, None, None, None started = time.monotonic() try: run.mkdir(parents=True) @@ -535,6 +551,9 @@ def progress(message): self.process = processes.popen(command, cwd=self.source, env=env, stdin=subprocess.DEVNULL, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, text=True, encoding='utf-8', errors='replace', start_new_session=True, supervise=True) + except OSError as failure: + refused = failure # only the system's refusal to start the child gets the start note + raise finally: if dll_directory is not None: ctypes.windll.kernel32.SetDllDirectoryW(dll_directory) @@ -558,6 +577,11 @@ def progress(message): except BaseException as failure: failed_with = type(failure).__name__ error = plain_text(repr(failure)) + if failure is refused: + # The system refused to start the child, so repr() alone names neither the code nor the path + # it refused; a report that keeps only the first lines must still say both. + winerror = getattr(failure, 'winerror', None) + error += plain_text('\n' + start_failure_note(failure, command, self.source)) detail = plain_text('\n' + traceback.format_exc()) output += detail try: @@ -571,7 +595,7 @@ def progress(message): finally: result = dict(action=action, status='cancelled' if self.cancelled.is_set() else 'complete' if code == 0 else 'failed', returncode=code, error=error, wall_seconds=time.monotonic()-started, root=str(root), log=plain(run), - lines=lines, failed_with=failed_with) + lines=lines, failed_with=failed_with, winerror=winerror) try: save(run / 'status.json', result) except OSError as failure: diff --git a/freevideo_engine/desktop_shortcut.py b/freevideo_engine/desktop_shortcut.py index 07f7feaa..89f80410 100644 --- a/freevideo_engine/desktop_shortcut.py +++ b/freevideo_engine/desktop_shortcut.py @@ -221,7 +221,8 @@ 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.modern_launcher',run_name='__main__')" + from .installed_entry import INSTALLED_ONLY + code = INSTALLED_ONLY + "import runpy;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' diff --git a/freevideo_engine/diagnostic_summary.py b/freevideo_engine/diagnostic_summary.py index e4311761..fc44b933 100644 --- a/freevideo_engine/diagnostic_summary.py +++ b/freevideo_engine/diagnostic_summary.py @@ -177,6 +177,13 @@ def summary_report(report): result['attempts'] = diagnostic.attempts(request.get('resource_attempts')) result['exception'] = [diagnostic.trace(row) for row in diagnostic.sequence(request.get('exception'))[:4]] result['encoder_failure'] = diagnostic.failure(diagnostic.mapping(request.get('encoding_failure')).get('failure')) + retry = diagnostic.mapping(request.get('encoding_retry')) + # A first encoder worker that failed stays on record even when the second one finished the request. + first = diagnostic.mapping(retry.get('first_attempt')) + result['encoder_retry'] = dict( + overrides={key: value for key, value in diagnostic.mapping(retry.get('overrides')).items() + if key in ('readonly_registration', 'extra_reserve_gib') and type(value) in (bool, int, float)}, + first_attempt=dict(phase=str(first.get('phase'))[:64], failure=diagnostic.failure(first.get('failure')))) if first else {} result['encoder_resources'] = (diagnostic.resources(diagnostic.mapping(report.get('memory')).get('encoding')) if not any(summary.get(k) for k in ('conditioning_cache_hit', 'preencoded', 'conditioning_from_preview')) else {}) diff --git a/freevideo_engine/diagnostics.py b/freevideo_engine/diagnostics.py index 5fc996a4..cb0c511c 100644 --- a/freevideo_engine/diagnostics.py +++ b/freevideo_engine/diagnostics.py @@ -350,7 +350,8 @@ def add_path(name, path): pythons = {str(p) for key in ('python', 'comfy_python') if (p := machine.get(key))} pythons.update(str(p) for name in ('unified', 'engine', 'encoder') if (p := venv_python(root / 'envs' / name)).is_file()) - code = 'import importlib.metadata as m,json,sys; print(json.dumps({"python":sys.version,"packages":{d.metadata["Name"]:d.version for d in m.distributions()}}))' + from .installed_entry import INSTALLED_ONLY + code = INSTALLED_ONLY + 'import importlib.metadata as m,json; print(json.dumps({"python":sys.version,"packages":{d.metadata["Name"]:d.version for d in m.distributions()}}))' for index, python in enumerate(sorted(pythons)): commands.append(('packages-' + str(index), [plain(python), '-B', '-c', code])) for name, command in commands: diff --git a/freevideo_engine/display_adapters.py b/freevideo_engine/display_adapters.py index 836c0f5a..19f0ecc8 100644 --- a/freevideo_engine/display_adapters.py +++ b/freevideo_engine/display_adapters.py @@ -7,7 +7,7 @@ import re import subprocess -DISPLAY_CLASS = r'SYSTEM\CurrentControlSet\Control\Class\{4d36e968-e325-11cf-bfc1-08002be10318}' +DISPLAY_CLASS = r'SYSTEM\CurrentControlSet\Control\Class\{4d36e968-e325-11ce-bfc1-08002be10318}' PCI_ENUM = r'SYSTEM\CurrentControlSet\Enum\PCI' NVIDIA_VENDOR = '10de' # PCI vendors whose cards are never NVIDIA's, for naming a driverless card the display class lists without a vendor. @@ -212,7 +212,14 @@ def line(zh, names): return '检测到:NVIDIA 显卡' if zh else 'Detected: NVIDIA graphics card' if nvidia: return ('检测到:' if zh else 'Detected: ') + nvidia[0] - other = '、'.join(names[:2]) if zh else ', '.join(names[:2]) - if zh: - return '未检测到 NVIDIA 显卡' + ('(%s)' % other if other else '') - return 'No NVIDIA graphics card detected' + (' (%s)' % other if other else '') + # No NVIDIA card: the card's title already says so; the note says what was found, and nothing when nothing was. + if not names: + return '' + return ('检测到:' + '、'.join(names[:2])) if zh else ('Detected: ' + ', '.join(names[:2])) + + +def nvidia_driver_listed(names): + """True on Windows when an NVIDIA card is listed under its model name: that name is the one its NVIDIA driver wrote, so a + driver is installed. A card found only through the PCI list is listed as plain NVIDIA (no driver). Elsewhere the list + names cards whether or not a driver is installed (lspci reads the PCI ID database), so it never says.""" + return os.name == 'nt' and bool(names) and any(NVIDIA_NAME.search(name) and name != NVIDIA for name in names) diff --git a/freevideo_engine/encode_worker.py b/freevideo_engine/encode_worker.py index 1bc005ae..a7ede476 100644 --- a/freevideo_engine/encode_worker.py +++ b/freevideo_engine/encode_worker.py @@ -585,13 +585,22 @@ def attempt(index, failure): finally: guard.disarm() + # A fresh worker after a lost CUDA context (see encoder_retry) leaves the checkpoint's + # read-only pages unregistered and one more GiB of the card free. Values do not change. + register = request.get('readonly_registration') is not False + extra_reserve = request.get('extra_reserve_gib') + if type(extra_reserve) in (int, float) and extra_reserve > 0: + import comfy.model_management as _reserve_manager + _reserve_manager.EXTRA_RESERVED_VRAM += int(extra_reserve * 2**30) + loading['extra_reserve_gib'] = float(extra_reserve) + loading['readonly_registration'] = register clip.load_model = timed_load try: from .encoder_memory import encode_with_recovery from .encoder_pinning import readonly_pinning import comfy.model_management as memory from .encoder_progress import layer_progress - with readonly_pinning(torch, memory, nonlocal_reserve_bytes=_reserve(resident)), \ + with readonly_pinning(torch, memory, nonlocal_reserve_bytes=_reserve(resident), register=register), \ layer_progress(clip.cond_stage_model): encoded, attempts = encode_with_recovery(clip, tokens, memory, torch, phase, max_attempts=4, attempt=attempt) @@ -605,7 +614,7 @@ def attempt(index, failure): tokens = clip.tokenize(prompt, **reference_options(normalized, media_kwargs, step)) size = input_size(tokens) current.clear() - with readonly_pinning(torch, memory, nonlocal_reserve_bytes=_reserve(resident)), \ + with readonly_pinning(torch, memory, nonlocal_reserve_bytes=_reserve(resident), register=register), \ layer_progress(clip.cond_stage_model, 'encoder_compute_reference'): stage_encoded, stage_attempts = encode_with_recovery( clip, tokens, memory, torch, phase, max_attempts=4, attempt=attempt) diff --git a/freevideo_engine/encoder_pinning.py b/freevideo_engine/encoder_pinning.py index 0942fd23..7c1d0a05 100644 --- a/freevideo_engine/encoder_pinning.py +++ b/freevideo_engine/encoder_pinning.py @@ -88,18 +88,20 @@ def _nonlocal_pin_limit(torch, manager, reserve, memory=None): @contextmanager -def readonly_pinning(torch, manager, *, nonlocal_reserve_bytes=None): +def readonly_pinning(torch, manager, *, nonlocal_reserve_bytes=None, register=True): """Adapt native pinning only while the isolated encoder is running. CUDA requires ReadOnly for read-only CPU mappings on platforms without host page tables. Native writable tensors keep the original code path; native registries and unpinning continue to own successful registrations. + With `register=False` no read-only page is registered: the weights are + read from ordinary memory, as when the registration is refused. """ original = manager.pin_memory if getattr(original, '_freevideo_readonly_adapter', False) is True: yield return - unsupported = False + unsupported = not register support_checked = False flags = None pin_limit = None diff --git a/freevideo_engine/encoder_retry.py b/freevideo_engine/encoder_retry.py new file mode 100644 index 00000000..4fe1c201 --- /dev/null +++ b/freevideo_engine/encoder_retry.py @@ -0,0 +1,31 @@ +"""A second text-encoder worker for a first one whose CUDA context was lost. + +An out-of-memory error that surfaces while the encoder's weights are copied to +the card can leave the worker's context unusable: even the cleanup that frees +its weights fails, so the worker exits and the in-process retries (which add +GPU room one GiB at a time) never run. Nothing was wrong with the request +itself, so the controller starts one more worker, in a new process with a new +context, and asks it to ask less of the system: no page-locked registration of +the checkpoint's read-only pages (the weights are then read from ordinary +memory, with no change to any value) and one more GiB left free on the card. +""" + +EXTRA_RESERVE_GIB = 1.0 + + +def fresh_process_retry(failure, metrics): + """Request fields for a second encoder worker, or None when a retry cannot help. + + Only a positively identified GPU out-of-memory failure whose worker could + not clean up after itself qualifies. A worker that cleaned up and returned + the error has already used its own retries with growing reserves, and + every other failure kind (code errors, device-state errors, RAM pressure, + cancellation) is not helped by changing how the encoder is registered. + """ + if not isinstance(failure, dict) or failure.get('kind') != 'gpu_oom' or failure.get('retryable') is not True: + return None + metrics = metrics if isinstance(metrics, dict) else {} + cleanup = metrics.get('failure_cleanup') + if not isinstance(cleanup, dict) or cleanup.get('complete') is not False: + return None + return dict(readonly_registration=False, extra_reserve_gib=EXTRA_RESERVE_GIB) diff --git a/freevideo_engine/environments.py b/freevideo_engine/environments.py index 1a794453..e00cfc91 100644 --- a/freevideo_engine/environments.py +++ b/freevideo_engine/environments.py @@ -102,6 +102,10 @@ def uv_build_environment(command, root, environ): Mark only this child's view: processes.popen translates its paths, while installation settings, cache ownership and the parent's environment stay put. """ + from .installed_entry import SAFE_PATH, without_safe_path + if SAFE_PATH in environ and command and (Path(str(command[0])).name.lower() in ('uv', 'uv.exe') + or list(map(str, command[1:3])) == ['-m', 'pip']): + environ = without_safe_path(environ) # a package build imports from its own folder # `venv` and `python` also write into the cache (interpreter records, downloads) below the same root. # A Python child also needs it: it runs `uv` itself (VDN and ComfyUI packages) and the loader # refuses a DLL such as torch\\lib\\c10.dll whose full path exceeds the limit (WinError 206). diff --git a/freevideo_engine/execution_paths.py b/freevideo_engine/execution_paths.py index 813fc397..bbeb1bdd 100644 --- a/freevideo_engine/execution_paths.py +++ b/freevideo_engine/execution_paths.py @@ -4,6 +4,7 @@ import subprocess from . import launch_view +from .installed_entry import INSTALLED_ONLY def execution_path(path): @@ -76,11 +77,11 @@ def call(function, command, **kwargs): # Run as "python -c": import the engine, leave no trace of that import, then run the script as # python would have. Arguments: the engine's source folder, the script, the script's own arguments. _ENGINE_FIRST = ( - "import os,runpy,sys;source=sys.argv.pop(1);sys.path.insert(0,source);import freevideo_engine;" + INSTALLED_ONLY + "import os,runpy;source=sys.argv.pop(1);sys.path.insert(0,source);import freevideo_engine;" "sys.path.remove(source);" "[sys.modules.pop(name) for name in list(sys.modules) if name.partition('.')[0]=='freevideo_engine'];" "del sys.argv[0];folder=os.path.dirname(sys.argv[0]);" - "sys.path[0:1]=[folder] if sys.path[:1]==[''] else [folder]+sys.path[:1];" + "sys.path.insert(0,folder);" "runpy.run_path(sys.argv[0],run_name='__main__')") diff --git a/freevideo_engine/exit_diagnostics.py b/freevideo_engine/exit_diagnostics.py index 804e8a4e..5cf11dfe 100644 --- a/freevideo_engine/exit_diagnostics.py +++ b/freevideo_engine/exit_diagnostics.py @@ -5,6 +5,7 @@ exit is seen. Only numbers and fixed words leave this module, never text from the worker, so a diagnostic report stays free of user data. """ +import math import os import re import tempfile @@ -246,3 +247,93 @@ def clean_reading(value): if frames: result['native_stack'] = frames return result + + +def _number(value): + return (type(value) is int and value >= 0 + or type(value) is float and math.isfinite(value) and value >= 0) + + +MEMORY_DURING_STAGES = frozenset(('start', 'load', 'text', 'encode', 'denoise', 'decode')) + +_DURING_REQUEST_COUNTS = frozenset(( + 'min_physical_available_bytes', + 'min_commit_available_bytes', + 'peak_worker_private_commit_bytes', + 'peak_worker_working_set_bytes', + 'peak_private_commit_bytes', + 'peak_working_set_bytes', +)) + +_DURING_REQUEST_STAGES = frozenset(( + 'min_physical_available_stage', + 'min_commit_available_stage', + 'peak_worker_private_commit_stage', + 'peak_worker_working_set_stage', + 'peak_private_commit_stage', + 'peak_working_set_stage', +)) + +_WORKER_SAMPLE_COUNTS = frozenset(( + 'worker_private_commit_bytes', + 'worker_working_set_bytes', + 'private_commit_bytes', + 'working_set_bytes', + 'process_private_commit_bytes', + 'process_working_set_bytes', +)) + +_SAMPLE_ROW_COUNTS = _WORKER_SAMPLE_COUNTS | frozenset(( + 'physical_available_bytes', + 'commit_available_bytes', +)) + + +def clean_memory_during_request(value): + """Whitelist cleaner for memory readings sampled during an image request. + + Rejects arbitrary text, unknown keys and invalid values. Keeps only bounded + non-negative integers, finite seconds and fixed stage words. + """ + if not isinstance(value, dict): + return {} + result = {} + for key in _DURING_REQUEST_COUNTS: + if key in value and _count(value[key]) is not None: + result[key] = value[key] + for key in _DURING_REQUEST_STAGES: + if value.get(key) in MEMORY_DURING_STAGES: + result[key] = value[key] + + last = value.get('last_worker_reading') + if isinstance(last, dict): + cleaned_last = {} + if 'seconds' in last and _number(last['seconds']): + cleaned_last['seconds'] = round(float(last['seconds']), 1) + if last.get('stage') in MEMORY_DURING_STAGES: + cleaned_last['stage'] = last['stage'] + for key in _WORKER_SAMPLE_COUNTS: + if key in last and _count(last[key]) is not None: + cleaned_last[key] = last[key] + if cleaned_last: + result['last_worker_reading'] = cleaned_last + + samples = value.get('samples') + if isinstance(samples, (list, tuple)): + cleaned_samples = [] + for row in samples[-5:]: + if isinstance(row, dict): + cleaned_row = {} + if 'seconds' in row and _number(row['seconds']): + cleaned_row['seconds'] = round(float(row['seconds']), 1) + if row.get('stage') in MEMORY_DURING_STAGES: + cleaned_row['stage'] = row['stage'] + for key in _SAMPLE_ROW_COUNTS: + if key in row and _count(row[key]) is not None: + cleaned_row[key] = row[key] + if cleaned_row: + cleaned_samples.append(cleaned_row) + if cleaned_samples: + result['samples'] = cleaned_samples + + return result diff --git a/freevideo_engine/failure_details.py b/freevideo_engine/failure_details.py index 5c050345..785e4950 100644 --- a/freevideo_engine/failure_details.py +++ b/freevideo_engine/failure_details.py @@ -34,6 +34,8 @@ 'busy_setup': ('FreeVideo is being installed, updated or cleaned up; try again when it finishes.', 'FreeVideo 正在安装、更新或清理,完成后再试。'), 'busy_video': ('A video is using the graphics card; try again when it finishes.', '视频正在使用显卡,完成后再试。'), 'needs_repair': ('The image model files are incomplete or damaged; repair them in the launcher.', '图像模型文件不完整或已损坏,请在启动器里修复。'), + # The text is built in image_pack_failure from model_repair's sentence; this row only makes the code known. + 'shared_mismatch': ('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': ("One of FreeVideo's own record files in the image model folder (image_gen) is a link or leads outside that folder, so it was not written; delete that link and try again.", '图像模型目录(image_gen)里 FreeVideo 自己的记录文件是链接或指向目录之外,所以没有写入;请删掉这个链接后重试。'), @@ -100,7 +102,39 @@ def image_pack_error_code(error): return 'failed' -def image_pack_failure(code, *, zh=False): +# A file the video install shares differs from the tested version, shown where there is no Repair button (the picture +# page): the file and how it is renamed are on the confirmation page, so this says only where to go (Lane-5x's wording). +SHARED_MISMATCH_ELSEWHERE = ( + 'A model file differs from the tested version and was left unchanged. ' + 'Select "Repair" in the launcher under Settings > Environment and confirm.', + '一个模型文件与测试过的版本不同,这次没有改动它。请在启动器“设置 → 环境”中点击“修复”并确认。') +# A portable (offline package) installation has no Repair in its launcher. +SHARED_MISMATCH_PORTABLE = ( + 'A model file differs from the tested version and was left unchanged. ' + 'Extract the package again into a new folder and start FreeVideo from there.', + '一个模型文件与测试过的版本不同,这次没有改动它。请把整合包重新解压到新文件夹,再从那里启动 FreeVideo。') + + +def _portable_installation(): + """Installed from an offline package (the launcher has no Repair there); the same test as bootstrap's.""" + try: + from .paths import data_root + return (data_root().parent / 'portable.json').is_file() + except OSError: + return False + + +def shared_mismatch_text(*, zh=False, portable=None): + """The sentence for a differing shared file on the picture page.""" + if portable is None: + portable = _portable_installation() + return (SHARED_MISMATCH_PORTABLE if portable else SHARED_MISMATCH_ELSEWHERE)[bool(zh)] + + +def image_pack_failure(code, *, zh=False, file=None): + if code == 'shared_mismatch': + return dict(kind='image-pack', title=('图像模型操作未完成' if zh else 'Image model operation stopped'), + detail=shared_mismatch_text(zh=zh), action='') return dict(kind='image-pack', title=('图像模型操作未完成' if zh else 'Image model operation stopped'), detail=IMAGE_PACK_FAILURES.get(code, IMAGE_PACK_FAILURES['failed'])[bool(zh)], action='') @@ -575,6 +609,13 @@ def model_mismatch_package(value, zh=False): ('NVIDIA 显卡未安装驱动', '请安装 580 或更新版本的 NVIDIA 显卡驱动,重启电脑后点击“重试安装”。')) +# Windows lists the card under the model name its NVIDIA driver wrote, so a driver is installed, yet none answers. +DRIVER_NOT_WORKING = ( + ('The NVIDIA graphics driver is not working', + 'Reinstall the NVIDIA driver, version 580 or newer, restart the computer, then click "Retry installation".'), + ('NVIDIA 显卡驱动未正常工作', + '请重新安装 580 或更新版本的 NVIDIA 显卡驱动,重启电脑后点击“重试安装”。')) + # What each download source returned, as one short line per host and route on # the failure card. The full lines stay in the copied error and the report. diff --git a/freevideo_engine/generate.py b/freevideo_engine/generate.py index 20d1d229..dd3940ff 100644 --- a/freevideo_engine/generate.py +++ b/freevideo_engine/generate.py @@ -1015,35 +1015,63 @@ def interrupted(signum, frame): raise print(json.dumps(dict(event='encoder_preflight_skipped', error=repr(error)[:300])), flush=True) encoder_env = dict(env, PYTHONPATH=str(repo)) - print(json.dumps({'event': 'encoding_start'}), flush=True) - encoder_attempt = history.begin(resource_identity, {'encoder': args.encoder}, - attempt_geometry(canvas, profile['engine']), purpose='encoding', - evidence={'reason': 'Text conditioning cache miss', - 'request_artifacts': str(artifacts)}) - report['encoding_attempt'] = encoder_attempt - save(destination.with_suffix('.request.json'), report) - try: - report['encoding_resources'] = child( - [args.comfy_python, '-m', 'freevideo_engine.encode_worker', '--request', str(encode_request)], - encoder_env, descriptor, destination.with_suffix('.encoding.log'), - ram_budget_bytes=profile['inference_ram_budget_gb'] * 1e9, - ram_budget_is_estimate=ram_budget_is_estimate(args), - minimum_available_bytes=inference_emergency_floor(profile['inference_ram_budget_gb'] * 1e9, - getattr(args, 'ram_reserve_gib', None)), - on_start=lambda pid: history.attach_worker(encoder_attempt, pid, phase='encoding')) - encoded = json.loads(destination.with_suffix('.encoding.json').read_text(encoding='utf-8')) - if encoded.get('success') is not True or not condition.is_file(): - raise ValueError('Encoder exited without verified conditioning') - except BaseException as error: + from .encoder_retry import fresh_process_retry + encoder_retry = None + for encoder_try in (1, 2): + print(json.dumps({'event': 'encoding_start'}), flush=True) + encoder_attempt = history.begin(resource_identity, {'encoder': args.encoder}, + attempt_geometry(canvas, profile['engine']), purpose='encoding', + evidence={'reason': 'Text conditioning cache miss' if encoder_try == 1 else + 'Encoder worker lost its CUDA context; one fresh worker without read-only registration', + 'request_artifacts': str(artifacts)}) + report['encoding_attempt'] = encoder_attempt + save(destination.with_suffix('.request.json'), report) try: - failed_encoding = json.loads(destination.with_suffix('.encoding.json').read_text(encoding='utf-8')) - except (OSError, ValueError): - failed_encoding = {} - failure = classify_failure(error, failed_encoding) - report['encoding_resources'] = getattr(error, 'telemetry', {}) - report['encoding_failure'] = dict(phase=failed_encoding.get('phase', 'encoding'), failure=failure) - history.finish(encoder_attempt, failure['outcome'], details=failure) - raise + report['encoding_resources'] = child( + [args.comfy_python, '-m', 'freevideo_engine.encode_worker', '--request', str(encode_request)], + encoder_env, descriptor, destination.with_suffix('.encoding.log'), + ram_budget_bytes=profile['inference_ram_budget_gb'] * 1e9, + ram_budget_is_estimate=ram_budget_is_estimate(args), + minimum_available_bytes=inference_emergency_floor(profile['inference_ram_budget_gb'] * 1e9, + getattr(args, 'ram_reserve_gib', None)), + on_start=lambda pid: history.attach_worker(encoder_attempt, pid, phase='encoding')) + encoded = json.loads(destination.with_suffix('.encoding.json').read_text(encoding='utf-8')) + if encoded.get('success') is not True or not condition.is_file(): + raise ValueError('Encoder exited without verified conditioning') + except BaseException as error: + try: + failed_encoding = json.loads(destination.with_suffix('.encoding.json').read_text(encoding='utf-8')) + except (OSError, ValueError): + failed_encoding = {} + failure = classify_failure(error, failed_encoding) + report['encoding_resources'] = getattr(error, 'telemetry', {}) + failed_record = dict(phase=failed_encoding.get('phase', 'encoding'), failure=failure) + history.finish(encoder_attempt, failure['outcome'], details=failure) + overrides = fresh_process_retry(failure, failed_encoding) if encoder_try == 1 else None + if overrides is None: + report['encoding_failure'] = dict(failed_record) + if encoder_retry is not None: + report['encoding_failure']['first_attempt'] = encoder_retry['first_attempt'] + report['encoding_retry'] = encoder_retry + raise + # The first worker's evidence stays beside the second's own files. + for suffix in ('.encoding.log', '.encoding.json'): + try: + os.replace(destination.with_suffix(suffix), + destination.with_suffix('.encoding.attempt-1' + suffix[len('.encoding'):])) + except OSError: + # Only the first worker's evidence is lost; its result must not stand for the second's. + try: + destination.with_suffix(suffix).unlink(missing_ok=True) + except OSError: + pass + encoder_retry = dict(first_attempt=failed_record, overrides=overrides) + report['encoding_retry'] = encoder_retry + encoding.update(overrides) + encode_request.write_text(json.dumps(encoding) + '\n', encoding='utf-8') + print(json.dumps(dict(event='encoder_fresh_retry', overrides=overrides)), flush=True) + continue + break history.finish(encoder_attempt, 'success', details={'reason': 'Encoder exited with conditioning', 'encoding': encoded, 'resources': report.get('encoding_resources'), 'prompt_characters': len(encoding['prompt'])}) diff --git a/freevideo_engine/image_gen/failure.py b/freevideo_engine/image_gen/failure.py index 697cea45..2b936765 100644 --- a/freevideo_engine/image_gen/failure.py +++ b/freevideo_engine/image_gen/failure.py @@ -13,7 +13,7 @@ from .image_model import H3, QWEN MODEL_IDS = (H3, QWEN) -from ..exit_diagnostics import clean_reading, clean_sample +from ..exit_diagnostics import clean_reading, clean_sample, clean_memory_during_request from ..diagnostic_resources import commit_exhausted from ..failure_details import Redactor from .loras import ERRORS as LORA_ERRORS, MESSAGE_ZH as LORA_MESSAGE_ZH @@ -247,6 +247,8 @@ def __init__(self, action, value): self.progress = None # ComfyUI's own models this request unloaded before its worker started (comfy_residency.release_native). self.native_release = None + # Readings taken every few seconds while the worker runs (service.MemorySampler): numbers and fixed words only. + self.memory_sampler = None self.update_request(value) def note_start(self): @@ -390,4 +392,9 @@ def service(self, video_busy, worker_restarts, error): reading = clean_reading(getattr(error, 'exit_reading', None)) if reading: service['worker_exit'] = reading + sampler = self.memory_sampler + if sampler is not None: + cleaned = clean_memory_during_request(sampler.summary(is_failure=error is not None)) + if cleaned: + service['memory_during_request'] = cleaned return service diff --git a/freevideo_engine/image_gen/image_pack.py b/freevideo_engine/image_gen/image_pack.py index 05d34555..74b61856 100644 --- a/freevideo_engine/image_gen/image_pack.py +++ b/freevideo_engine/image_gen/image_pack.py @@ -37,11 +37,17 @@ H3_GROUPS = ('h3-image-core', 'h3-text-encoder') + tuple('h3-image-dit-' + tier for tier in H3_TIERS) LEDGER = 'download-verified.json' OWNERSHIP = 'owned-files.json' +# A swap of a shared file in progress: the kept original's name and identity, written before the first rename. +SWAPS = 'logs/model-swaps.json' RESERVE = 256 * 2**20 FAMILY = 'image-models' BACKGROUND_RESERVE = 2 * 2**30 GENERATION_POLL_SECONDS = .25 GENERATION_RESUME_SECONDS = 10. +# A background download whose lease is refused by a setup, update or cleanup waits for it instead of failing. +SETUP_WAIT_SECONDS = 1800. +SETUP_POLL_SECONDS = 1. +SETUP_LOCKS = ('setup.lock',) # Asking ComfyUI whether it is busy can take seconds (a closed port on Windows # refuses only after about 2 s), and hashing checks once per 4 MiB block. Ask at # most every 2 s, and a slow answer waits four times its own cost before the next. @@ -101,6 +107,12 @@ def generating(self): return None return 'busy_picture' if holder == 'picture' else 'busy_engine' + def wait_for_setup(self): + """Sleep one poll while a setup, update or cleanup holds the lease; a cancel ends the wait at once.""" + self.installer._set(state='paused_for_generation', reason='busy_setup') + if self.stop.wait(SETUP_POLL_SECONDS): + raise InterruptedError('cancelled') + def check(self): if self.stop.is_set(): raise InterruptedError('cancelled') @@ -285,6 +297,13 @@ def shared_root(root=None): return Path(root).expanduser().absolute().parent / 'encoder' +def _same_disk(first, second): + try: + return os.stat(disk_space.existing(first)).st_dev == os.stat(disk_space.existing(second)).st_dev + except OSError: + return True + + def _same_folder(first, second): # Compared as text after normalising (case and slash direction on Windows), not with samefile: the recorded model # folder may sit on a drive that is not mounted right now, and samefile raises for a folder that is not there. @@ -669,6 +688,29 @@ def _lease(root, engine_root=None, destructive=False): yield folder +@contextmanager +def _install_lease(root, engine_root, repair, background): + """The lease for an install. A background download whose lease is held by a setup, update or cleanup (not by + another pack task) waits for it, up to SETUP_WAIT_SECONDS, and goes on once it is free; any other refusal, + and every foreground action, is raised as before.""" + deadline = time.monotonic() + SETUP_WAIT_SECONDS + waited = False + with ExitStack() as held: + while True: + try: + folder = held.enter_context(_lease(root, engine_root, destructive=repair)) + break + except BlockingIOError as error: + setup = Path(getattr(error, 'busy_lock_path', '') or '').name in SETUP_LOCKS + if background is None or repair or not setup or getattr(error, 'pack_lock_held', False) or time.monotonic() >= deadline: + raise + waited = True + background.wait_for_setup() + if waited: + background.installer._set(state='running', reason=None) + yield folder + + def verify(root=None, progress=None, check=None, *, group='image'): """Explicit full integrity check; bad stamps are discarded, files are kept.""" with _lease(root) as folder: @@ -698,9 +740,15 @@ def checked(current, size): progress(dict(phase='diagnostic', diagnostic=dict(file=row['file'], verification='verified' if intact else 'mismatch' if path.exists() else 'missing', method='sha256' if hashed else 'receipt' if intact else 'size'))) + if intact and row.get('shared'): + try: + _swap_record(folder, path) # the file is there and right: a record of an interrupted swap is moot + except OSError: + pass if not intact: ledger.pop(str(path), None) - if path.exists() and not row.get('shared'): + if path.exists(): + # A file shared with the video install is recorded too: repair may replace it only after this record. model_repair.record(folder, path, row, before) todo.append(row) done += row['bytes'] @@ -793,25 +841,160 @@ def resource_check(): raise PackError(reason) from error -def install(root=None, progress=None, check=None, *, engine_root=None, repair=False, _background=None, group='image'): - """Install only missing weights. Repair also hashes and retains bad originals.""" +def _swap_record(folder, path, approved=None): + """Write (or, without approved, drop) the record of a swap that has begun at path.""" + values = _read(folder, SWAPS) + if approved is None: + if str(path) not in values: + return + del values[str(path)] + else: + values[str(path)] = dict({key: approved[key] for key in model_repair.IDENTITY}, keep_as=approved['keep_as']) + save(_path(folder, SWAPS), values) + + +def _put_back(folder, path): + """A swap stopped after it moved the original away and before the new file was in place: the original, found by + the record the swap left (its name and identity), goes back. A .replaced file from a swap that finished has no + record and stays where it is.""" + try: + record = _read(folder, SWAPS).get(str(path)) + if not isinstance(record, dict): + return False + if os.path.lexists(path): + _swap_record(folder, path) # the path has a file again: the record is a leftover + return False + name = record.get('keep_as') + kept = path.with_name(name) if model_repair.valid_name(name) else None + if kept is None or not model_repair.same_identity(model_repair.identity(kept), record): + return False + model_repair.rename_noreplace(kept, path) + _swap_record(folder, path) + return True + except (OSError, ValueError): + return False + + +def _swap_in(folder, path, staged, approved, prior): + """The verified new file takes the place of the original, which is kept as .replaced-. + + A record of the swap is written first and dropped when both renames are done, so a stop in between can be told + from an old .replaced file. If the second rename cannot be done the original goes back, so the path is never left + empty by this function.""" + try: + _swap_record(folder, path, approved) + except PermissionError as error: + raise PackError('write_failed') from error + try: + kept = model_repair.retain(folder, path, approved) + except BaseException as error: + # retain may have failed after its rename (writing the mismatch record): then the original goes back. Only when + # it is still in place was nothing renamed (Windows: another program holds the file open); the verified new + # file waits as .replacing either way. + keep = path.with_name(approved['keep_as']) + if not os.path.lexists(path) and keep.exists(): + try: + model_repair.restore(folder, path, keep, approved, prior) + except (OSError, ValueError): + pass + if os.path.lexists(path): + try: + _swap_record(folder, path) + except OSError: + pass + if isinstance(error, PermissionError): + raise PackError('write_failed') from error + raise + try: + model_repair.rename_noreplace(staged, path) + except BaseException: + try: + model_repair.restore(folder, path, kept, approved, prior) + _swap_record(folder, path) + except (OSError, ValueError): + pass + raise + try: + _swap_record(folder, path) + except OSError: + pass + + +def install(root=None, progress=None, check=None, *, engine_root=None, repair=False, _background=None, group='image', confirm=None): + """Install only missing weights. Repair also hashes and retains bad originals. + + A damaged file the video install shares is renamed only after the user has seen it: with repair or confirm given, + a shared file that differs and is not in confirm stops the run with PackError('confirm_replace', replace=rows) + before anything is touched, and passing those rows as confirm (setup's reviewed plan lists them: bootstrap + replace_models) replaces them. A plain install reports 'shared_mismatch' and changes nothing. + + A call with confirm takes no engine lease of its own (only repair=True does). That holds because its one caller, + bootstrap's Installer.install_image_only, runs inside a setup that holds the installation's engine lease for its + whole run, so no video runs while a file is replaced. Any new caller that passes confirm must do the same.""" progress = progress or (lambda v: None) check = check or (lambda: None) transfer_check = _background.check if _background is not None else check try: - with _lease(root, engine_root, destructive=repair) as folder: + with _install_lease(root, engine_root, repair, _background) as folder: + replacing = repair or confirm is not None + for row in rows(group=group): + if replacing and row.get('shared') and not os.path.lexists(target(row, root)): + new = Path(str(target(row, root)) + '.replacing') + if not (new.is_file() and new.stat().st_size == row['bytes']): + # An earlier swap moved the original away and stopped before the new file was in place: + # a repair puts the original back first (before the check, which then sees it), so the video + # is not left without its file. Only a swap that left its record is undone, and only in a + # repair (which holds the engine lease); a plain install never renames the user's files. + _put_back(folder, target(row, root)) ledger, todo = _verify(folder, root, progress, check, full=repair, group=group) total = sum(r['bytes'] for r in todo) - retained = 0 - for row in todo: - partial = _side(folder, row, root, '.partial') - if partial.is_file() and partial.stat().st_size < row['bytes']: - retained += partial.stat().st_size reserve = BACKGROUND_RESERVE if _background is not None else RESERVE - needed = total - retained + reserve - free = disk_space.free_bytes(folder) - if total and free < needed: - raise PackError('disk_space', needed_bytes=needed, free_bytes=free) + # Each disk a file lands on must hold what lands there: the shared encoder goes to the video encoder + # folder, which may be another disk, also when its file is missing (a failed repair) or kept beside its copy. + disks = [] + for row in todo: + parts = [_side(folder, row, root, '.partial')] + if row.get('shared'): + parts.append(Path(str(target(row, root)) + '.replacing.partial')) + have = max([p.stat().st_size for p in parts if p.is_file() and p.stat().st_size < row['bytes']] or [0]) + if row.get('shared') and Path(str(target(row, root)) + '.replacing').is_file() and \ + Path(str(target(row, root)) + '.replacing').stat().st_size == row['bytes']: + have = row['bytes'] # the new file is already on the disk (an earlier run): only a rename is left + where = target(row, root).parent if row.get('shared') else folder + for entry in disks: + if _same_disk(entry[0], where): + entry[1] += row['bytes'] - have + break + else: + disks.append([where, row['bytes'] - have]) + for where, amount in disks: + if amount <= 0: + continue # only renames are left (a new file already on the disk) + needed, free = amount + reserve, disk_space.free_bytes(where) + if free < needed: + raise PackError('disk_space', needed_bytes=needed, free_bytes=free) + replacements = {} + if replacing: + # Before anything is renamed or downloaded: which shared files would be replaced, and did the user confirm them. + asked = [] + reviewed = {row.get('path'): row for row in confirm or [] if isinstance(row, dict)} + for row in todo: + path = target(row, root) + if not row.get('shared') or not path.exists(): + continue + if _linked(path): + raise PackError('link_mismatch', link=str(path)) + approved = model_repair.replacement(path, row, model_repair.read(folder), set()) + if approved is None: + raise PackError('changed') + prior = reviewed.get(approved['path']) + if prior is not None and model_repair.same_identity(approved, prior): + model_repair.reuse_names([approved], [prior]) + else: + asked.append(approved) + replacements[str(path)] = approved + if asked: + raise PackError('confirm_replace', replace=asked) plan = _download_plan(engine_root) plan.update(quiet=True, resource_check=check) owned = _read(folder, OWNERSHIP) @@ -826,19 +1009,34 @@ def install(root=None, progress=None, check=None, *, engine_root=None, repair=Fa progress(dict(phase='download', done=done + pending_prefixes, total=total)) for row in todo: check() + swap = None path = target(row, root) + # A shared file that is replaced stays where it is while the new one is fetched beside it, as + # .replacing; only a verified new file is swapped in, so no stop leaves the video without it. + staged = path.with_name(path.name + '.replacing') if row.get('shared') else None + download_to = path + if staged is not None and not os.path.lexists(path) and staged.is_file(): + # An earlier swap stopped between its two renames: the verified new file is still waiting. + download_to = staged if path.exists(): - if not row.get('shared') and _linked(path): + if _linked(path) and (replacing or not row.get('shared')): # The user's link leads to a different file: neither the link nor that file is ours to replace. raise PackError('link_mismatch', link=str(path)) - if not repair or row.get('shared'): + if not repair and not (row.get('shared') and replacing): + # A plain install never renames a file the video install shares: setup's repair does, after a review. + if row.get('shared'): + raise PackError('shared_mismatch', file=path.name, path=str(path)) raise PackError('needs_repair') - approved = model_repair.replacement(path, row, model_repair.read(folder), set()) + approved = replacements.get(str(path)) or model_repair.replacement(path, row, model_repair.read(folder), set()) if approved is None: raise PackError('changed') - model_repair.retain(folder, path, approved) - owned.pop(row['file'], None) - save(_path(folder, OWNERSHIP), owned) + if row.get('shared'): + swap = (approved, model_repair.read(folder).get(str(path))) + download_to = staged + else: + model_repair.retain(folder, path, approved) + owned.pop(row['file'], None) + save(_path(folder, OWNERSHIP), owned) partial = _side(folder, row, root, '.partial') if _background is not None and partial.is_file(): pending_prefixes -= min(row['bytes'], partial.stat().st_size) @@ -849,12 +1047,35 @@ def moved(current, size, speed, **kwargs): progress(dict(phase='download', done=done + current + pending_prefixes, total=total)) transfer_check() try: - _transfer(plan, row, path, moved, transfer_check, _background, progress) + try: + _transfer(plan, row, download_to, moved, transfer_check, _background, progress) + except ValueError as error: + # download() refuses to overwrite a finished file that fails its check. A leftover .replacing + # that does not hold the tested bytes is our own staging file: removed, then fetched again, once. + if download_to is not staged or not str(error).startswith('Existing file failed integrity check'): + raise + staged.unlink() + download_to = staged + _transfer(plan, row, download_to, moved, transfer_check, _background, progress) + if swap is not None: + _swap_in(folder, path, staged, *swap) + elif download_to is staged: + model_repair.rename_noreplace(staged, path) + _swap_record(folder, path) # the swap an earlier run began is finished + except BaseException: + if replacing and staged is not None and not os.path.lexists(path): + _put_back(folder, path) # this run could not bring the new file: the original stays the video's + raise finally: # Completed files and cancellable prefixes have separate identities. for artifact in (partial, affinity): if not row.get('shared') and may_own[artifact] and _path(folder, artifact.relative_to(folder).as_posix(), kind='beside').is_file(): _own(folder, owned, artifact) + if staged is not None: + try: + _swap_record(folder, path) # a record an interrupted swap left is moot once the path has its file + except OSError: + pass ledger[str(path)] = provision.file_identity(path, row) save(_path(folder, LEDGER), ledger) if not row.get('shared'): @@ -871,8 +1092,8 @@ def moved(current, size, speed, **kwargs): raise PackError('download_failed') from error -def repair(root=None, progress=None, check=None, *, engine_root=None, group='image'): - return install(root, progress, check, engine_root=engine_root, repair=True, group=group) +def repair(root=None, progress=None, check=None, *, engine_root=None, group='image', confirm=None): + return install(root, progress, check, engine_root=engine_root, repair=True, group=group, confirm=confirm) def _kinds(group): diff --git a/freevideo_engine/image_gen/prompt_cache.py b/freevideo_engine/image_gen/prompt_cache.py index ea644b9d..61845153 100644 --- a/freevideo_engine/image_gen/prompt_cache.py +++ b/freevideo_engine/image_gen/prompt_cache.py @@ -1,7 +1,7 @@ """The same prompt is not encoded twice: image conditioning goes through the input cache the video path uses. -The key is the prompt plus the pixels of every reference, under the identity of the encoder (file content, its code -and libraries, GPU architecture). A hit hands back exactly the tensors the encoder saved, so a cached image equals an +The key is the prompt plus the pixels of every reference, under the identity of the encoder (file content, its encoding +version and libraries, GPU architecture). A hit hands back exactly the tensors the encoder saved, so a cached image equals an uncached one. Anything that cannot be verified (no installation record, other explicit paths, an unreadable or damaged entry) encodes as before.""" import hashlib diff --git a/freevideo_engine/image_gen/service.py b/freevideo_engine/image_gen/service.py index fe7a62b8..e9648600 100644 --- a/freevideo_engine/image_gen/service.py +++ b/freevideo_engine/image_gen/service.py @@ -3,7 +3,7 @@ import contextlib from datetime import datetime, timezone import asyncio -from collections import OrderedDict +from collections import OrderedDict, deque from copy import deepcopy import json import logging @@ -21,7 +21,7 @@ import uuid from . import image_model, image_pack, keep, progress_model -from .. import server_mode +from .. import model_repair, server_mode from .loras import ERRORS as LORA_ERRORS, resolve_selection from ..disk_space import ran_out @@ -221,6 +221,205 @@ def close(self): pass +class MemorySampler: + """Daemon thread sampling memory during an image request (every ~2 seconds). + + Swallows all exceptions so sampling never interferes with inference. + """ + def __init__(self, context, interval=2.0, clock=time.monotonic): + self.session = None + self.context = context + self.interval = interval + self.clock = clock + self.started_at = self.clock() + self.stop_event = threading.Event() + self.lock = threading.Lock() + self.thread = None + self.min_physical = None + self.min_physical_stage = None + self.min_commit = None + self.min_commit_stage = None + self.peak_worker_private_commit = None + self.peak_worker_private_commit_stage = None + self.peak_worker_working_set = None + self.peak_worker_working_set_stage = None + self.last_worker_reading = None + self.samples = deque(maxlen=5) + + def start(self, session): + """Sample the given worker session; a retry on a fresh worker keeps the readings of the first try.""" + self.session = session + self.stop_event = threading.Event() + try: + self.thread = threading.Thread(target=self._run, name='freevideo-image-memory-sampler', daemon=True) + self.thread.start() + except Exception: + pass + return self + + def stop(self): + self.stop_event.set() + try: + if self.thread is not None and self.thread.is_alive(): + self.thread.join(timeout=2.0) + except Exception: + pass + + def is_alive(self): + try: + return self.thread is not None and self.thread.is_alive() + except Exception: + return False + + @staticmethod + def _linux_tree_resident(root_pid, limit=64): + """Resident bytes of a process and its descendants: the worker runs under a supervising host process.""" + try: + page = os.sysconf('SC_PAGE_SIZE') + except Exception: + return None + total, seen, pending = None, set(), [root_pid] + while pending and len(seen) < limit: + pid = pending.pop() + if pid in seen: + continue + seen.add(pid) + try: + with open('/proc/%d/statm' % pid, encoding='ascii') as stream: + pages = int(stream.read().split()[1]) + total = (total or 0) + pages * page + except Exception: + continue + try: + for task in os.listdir('/proc/%d/task' % pid): + with open('/proc/%d/task/%s/children' % (pid, task), encoding='ascii') as stream: + pending.extend(int(child) for child in stream.read().split()) + except Exception: + pass + return total + + def _read_worker_memory(self, pid): + if not pid or not isinstance(pid, int): + return None, None + try: + from ..system import windows + if windows(): + try: + from ..win32 import ProcessMemory + tree = ProcessMemory().sample(pid) + if tree and tree.get('processes', 0) > 0: + rss = tree.get('rss_bytes') + private = tree.get('private_commit_bytes') + count_rss = rss if type(rss) is int and rss >= 0 else None + count_priv = private if type(private) is int and private >= 0 else None + return count_priv, count_rss + except Exception: + return None, None + else: + return None, self._linux_tree_resident(pid) + except Exception: + return None, None + return None, None + + def sample_once(self): + try: + now = self.clock() + elapsed = max(0.0, now - self.started_at) + seconds = round(elapsed, 1) + + stage = getattr(getattr(self.context, 'timing', None), 'stage', 'start') + if stage not in STAGES: + stage = 'start' + + from ..exit_diagnostics import memory_sample + sys_mem = memory_sample() + phys = sys_mem.get('physical_available_bytes') + phys = phys if type(phys) is int and phys >= 0 else None + commit = sys_mem.get('commit_available_bytes') + commit = commit if type(commit) is int and commit >= 0 else None + + pid = None + if self.session is not None: + process = getattr(self.session, 'process', None) + pid = getattr(process, 'pid', None) if process is not None else getattr(self.session, 'pid', None) + if pid is None and isinstance(self.session, int): + pid = self.session + + worker_private, worker_ws = self._read_worker_memory(pid) + + with self.lock: + sample = dict(seconds=seconds, stage=stage) + if phys is not None: + sample['physical_available_bytes'] = phys + if self.min_physical is None or phys < self.min_physical: + self.min_physical = phys + self.min_physical_stage = stage + if commit is not None: + sample['commit_available_bytes'] = commit + if self.min_commit is None or commit < self.min_commit: + self.min_commit = commit + self.min_commit_stage = stage + if worker_private is not None: + sample['worker_private_commit_bytes'] = worker_private + if self.peak_worker_private_commit is None or worker_private > self.peak_worker_private_commit: + self.peak_worker_private_commit = worker_private + self.peak_worker_private_commit_stage = stage + if worker_ws is not None: + sample['worker_working_set_bytes'] = worker_ws + if self.peak_worker_working_set is None or worker_ws > self.peak_worker_working_set: + self.peak_worker_working_set = worker_ws + self.peak_worker_working_set_stage = stage + + if worker_private is not None or worker_ws is not None: + worker_reading = dict(seconds=seconds, stage=stage) + if worker_private is not None: + worker_reading['worker_private_commit_bytes'] = worker_private + if worker_ws is not None: + worker_reading['worker_working_set_bytes'] = worker_ws + self.last_worker_reading = worker_reading + + self.samples.append(sample) + except Exception: + pass + + def _run(self): + while not self.stop_event.is_set(): + try: + self.sample_once() + except Exception: + pass + if self.stop_event.wait(self.interval): + break + + def summary(self, is_failure=False): + with self.lock: + result = {} + if self.min_physical is not None: + result['min_physical_available_bytes'] = self.min_physical + if self.min_physical_stage in STAGES: + result['min_physical_available_stage'] = self.min_physical_stage + if self.min_commit is not None: + result['min_commit_available_bytes'] = self.min_commit + if self.min_commit_stage in STAGES: + result['min_commit_available_stage'] = self.min_commit_stage + if self.peak_worker_private_commit is not None: + result['peak_worker_private_commit_bytes'] = self.peak_worker_private_commit + if self.peak_worker_private_commit_stage in STAGES: + result['peak_worker_private_commit_stage'] = self.peak_worker_private_commit_stage + if self.peak_worker_working_set is not None: + result['peak_worker_working_set_bytes'] = self.peak_worker_working_set + if self.peak_worker_working_set_stage in STAGES: + result['peak_worker_working_set_stage'] = self.peak_worker_working_set_stage + + if is_failure and self.last_worker_reading: + result['last_worker_reading'] = dict(self.last_worker_reading) + + if self.samples: + result['samples'] = list(self.samples) + + return result + + class Service: def __init__(self, installation, input_directory, *, video_busy=None, idle_seconds=45., folders=None): self.installation = installation @@ -341,10 +540,39 @@ def info(self): purposes=list(PURPOSES), **({'unified_memory': True} if machine.get('device_backend') == 'mps' else {})) + def forget_stale_shared_failure(self, root): + """A failure 'a file the video install shares differs' stays in memory until something replaces the installer. + Repair runs in the launcher and may fix the file while this service keeps running (a ComfyUI the launcher did + not start is not restarted), and the page has no button then: so the failure goes once the file is no longer the + one it was recorded for: it is gone, or its identity (size, times, inode) differs from the record the check left. + No record with the file still there (a link, an unreadable record) keeps the failure. No hashing here; the next + download then checks the file for real and either finishes or reports it again.""" + installer = self.h3_installer + if installer is None or getattr(installer, 'busy', False): + return + state = installer.state() + if not isinstance(state, dict) or state.get('state') != 'failed' or state.get('reason') != 'shared_mismatch': + return + try: + records = model_repair.read(image_pack.base(root)) + for row in image_pack.rows(group=H3_GROUP): + if row.get('shared'): + path = image_pack.target(row, root) + record = records.get(str(path)) + if os.path.lexists(path) and (record is None or model_repair.same_identity(model_repair.identity(path), record)): + return # still the file that failed (or no way to tell: a link, no record) + except (OSError, ValueError): + return + with self.mutex: + if self.h3_installer is installer: + self.h3_installer = None + def model_rows(self, machine, qwen_ready, qwen_downloading, qwen_problem=None): """Both picture models for the page: installed, or being fetched with the bytes still to download.""" root = machine['model_root'] mac = sys.platform == 'darwin' + if not mac: + self.forget_stale_shared_failure(root) h3_ready, h3_problem = False, None if not mac: h3_ready, h3_problem = self.pack_checked(image_pack.ready, root, group=H3_GROUP) @@ -2611,6 +2839,23 @@ def worker_gone_error(session, heard, loading=False, requested_stop=False): return error def infer(self, session, value): + # The readings taken while the worker runs are what a report needs when the system ends it. + context = self.context + sampler = None + if context is not None: + try: + sampler = context.memory_sampler or MemorySampler(context) + context.memory_sampler = sampler + sampler.start(session) + except Exception: + sampler = None + try: + return self.run_inference(session, value) + finally: + if sampler is not None: + sampler.stop() + + def run_inference(self, session, value): context = self.context or Context('generate', value) heard = False habit = keep.path(self.habit_root) diff --git a/freevideo_engine/installed_entry.py b/freevideo_engine/installed_entry.py new file mode 100644 index 00000000..b0d73690 --- /dev/null +++ b/freevideo_engine/installed_entry.py @@ -0,0 +1,63 @@ +"""Start a FreeVideo module from this installation, whichever folder the command is run in. + +The command scripts run this file with the module's name and arguments. The module then sees the same ``sys.argv``, +``__main__`` and exit code as under ``python -m``. It has no version requirement: the first step of a setup can run on +the system's Python 3.9 or later, and only the imports this file makes before the module starts matter there. +""" +import os +import sys + +SAFE_PATH = 'PYTHONSAFEPATH' +INSTALLED_ONLY = 'import sys;sys.path[:]=[p for p in sys.path if p];' # first in an inline ``python -c`` program + + +def _key(path): + return os.path.normcase(os.path.realpath(os.path.abspath(path))) + + +def absolute_entries(value): + return [entry for entry in (value or '').split(os.pathsep) if os.path.isabs(entry)] + + +def search_path(path, source, value, entry_folder): + """``(sys.path, PYTHONPATH)``: this installation first, then what was named by a full path.""" + entries = value.split(os.pathsep) if value is not None else [] + named = absolute_entries(value) + kept = {_key(entry) for entry in named} | {_key(source)} + dropped = ({_key(entry) for entry in entries if not os.path.isabs(entry)} - kept) | {_key(entry_folder)} + first = _key(source) + return ([source] + [entry for entry in path if entry and _key(entry) not in dropped and _key(entry) != first], + os.pathsep.join([source] + [entry for entry in named if _key(entry) != first])) + + +def protect(environ=None): + """For a program that was not started through this file: the Python programs it starts use the installed code.""" + environ = os.environ if environ is None else environ + if 'PYTHONPATH' in environ: + named = absolute_entries(environ['PYTHONPATH']) + if named: + environ['PYTHONPATH'] = os.pathsep.join(named) + else: + del environ['PYTHONPATH'] + environ[SAFE_PATH] = '1' + return environ + + +def without_safe_path(environ): + """For a program of another project (ComfyUI, a package build), which imports from its own folder.""" + return {key: value for key, value in environ.items() if key != SAFE_PATH} + + +def main(): + folder = os.path.dirname(os.path.abspath(__file__)) + sys.path[:], os.environ['PYTHONPATH'] = search_path(sys.path, os.path.dirname(folder), + os.environ.get('PYTHONPATH'), folder) + os.environ[SAFE_PATH] = '1' + module = sys.argv[1] + del sys.argv[0] + import runpy + runpy._run_module_as_main(module) # what ``python -m`` itself calls + + +if __name__ == '__main__': + main() diff --git a/freevideo_engine/launcher/Main.qml b/freevideo_engine/launcher/Main.qml index f6956ce5..1dcfce8c 100644 --- a/freevideo_engine/launcher/Main.qml +++ b/freevideo_engine/launcher/Main.qml @@ -1079,20 +1079,29 @@ ApplicationWindow { Layout.fillWidth: true; padding: 22; spacing: 10 color: s.image_pack.install.state === "failed" ? theme.dangerSubtle : theme.surface border.color: s.image_pack.install.state === "failed" ? theme.dangerLine : theme.border - RowLayout { - Layout.fillWidth: true; spacing: 14 + GridLayout { + Layout.fillWidth: true; columnSpacing: 14; rowSpacing: 10; columns: width < 640 ? 1 : 2 ColumnLayout { Layout.fillWidth: true; spacing: 4 FText { objectName: "imagePackTitle"; text: s.image_pack.title; font.weight: Font.DemiBold; Layout.fillWidth: true } FText { objectName: "imagePackStatus"; visible: s.image_pack.install.state !== "failed"; text: s.image_pack.detail; color: theme.muted; Layout.fillWidth: true } } - FText { objectName: "imagePackSize"; text: gb(s.image_pack.total_bytes); color: theme.muted } - FButton { objectName: "imagePackInstall"; visible: !s.image_pack.ready && !s.image_pack.busy; text: s.image_pack.downloaded_bytes > 0 ? t("Resume", "继续") : t("Download", "下载"); enabled: s.image_pack.can_act; onClicked: backend.imagePackAction("install") } - FButton { objectName: "imagePackCancel"; visible: s.image_pack.busy; text: t("Pause", "暂停"); flat: true; onClicked: backend.imagePackAction("cancel") } - FButton { objectName: "imagePackRepair"; visible: s.image_pack.repairable && s.image_pack.downloaded_bytes > 0 && !s.image_pack.busy; text: t("Repair", "修复"); flat: true; enabled: s.image_pack.can_act; unavailable: s.image_pack.engine_state === "running"; onClicked: backend.imagePackAction("repair") } - FButton { objectName: "imagePackRemove"; visible: s.image_pack.removable_bytes > 0 && !s.image_pack.busy; text: t("Remove", "删除"); flat: true; enabled: s.image_pack.can_act; unavailable: s.image_pack.engine_state === "running"; onClicked: backend.imagePackAction("remove") } + Flow { + id: imagePackActions + spacing: 14; Layout.fillWidth: parent.columns === 1; Layout.alignment: Qt.AlignRight | Qt.AlignVCenter + // Wide: one row at its natural width. Narrow: the size takes the first line and the buttons start the next, aligned with it. + property real rowWidth: { var w = 0, n = 0; for (var i = 0; i < children.length; i++) if (children[i].visible) { w += children[i].implicitWidth; n++ } return w + Math.max(0, n - 1) * spacing } + Layout.minimumWidth: parent.columns === 1 ? 0 : rowWidth + Layout.preferredWidth: parent.columns === 1 ? -1 : rowWidth + FText { objectName: "imagePackSize"; width: imagePackActions.parent.columns === 1 ? imagePackActions.width : implicitWidth; text: gb(s.image_pack.total_bytes); color: theme.muted } + FButton { objectName: "imagePackInstall"; visible: !s.image_pack.ready && !(s.image_pack.repairable && s.image_pack.downloaded_bytes > 0) && !s.image_pack.busy; text: s.image_pack.downloaded_bytes > 0 ? t("Resume", "继续") : t("Download", "下载"); enabled: s.image_pack.can_act; onClicked: backend.imagePackAction("install") } + FButton { objectName: "imagePackCancel"; visible: s.image_pack.busy; text: t("Pause", "暂停"); flat: true; onClicked: backend.imagePackAction("cancel") } + FButton { objectName: "imagePackRepair"; visible: s.image_pack.repairable && s.image_pack.downloaded_bytes > 0 && !s.image_pack.busy; text: t("Repair", "修复"); enabled: s.image_pack.can_act; unavailable: s.image_pack.engine_state === "running"; onClicked: backend.imagePackAction("repair") } + FButton { objectName: "imagePackCheck"; visible: s.image_pack.ready && !s.image_pack.busy; text: t("Check files", "检查文件"); flat: true; enabled: s.image_pack.can_act; unavailable: s.image_pack.engine_state === "running"; onClicked: backend.imagePackAction("verify") } + FButton { objectName: "imagePackRemove"; visible: s.image_pack.removable_bytes > 0 && !s.image_pack.busy; text: t("Remove", "删除"); flat: true; enabled: s.image_pack.can_act; unavailable: s.image_pack.engine_state === "running"; onClicked: backend.imagePackAction("remove") } + } } - 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: "imagePackEngineNote"; wrapMode: Text.WordWrap; 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 || "") + (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 { diff --git a/freevideo_engine/launcher_session.py b/freevideo_engine/launcher_session.py index 9393d1bf..1c88a81e 100644 --- a/freevideo_engine/launcher_session.py +++ b/freevideo_engine/launcher_session.py @@ -775,6 +775,10 @@ def action(self, name, accepted=False, *, retry=None): # the editable setup form may currently describe another installation. self.remember(self.selected, persist=False) self.repair_request = dict(self.form, repair=True) + if self.installed_machine().get('video_model') is False: + # Set up with MiniMax H3 Image alone: repair that, whatever the model step's form says now + # (it defaults to the video model, and "Add the video model" sets it to the video model). + self.repair_request['install_model'] = 'image' self.persist() self.controller.run('inspect', self.setup_values(self.repair_request)) self.page = 'progress' @@ -1001,7 +1005,7 @@ def image_pack_action(self, action): return root, engine = self._image_location() # Repair and Remove need the engine lease, which a task (or the idle image session) holds; say why instead of failing a second later. - if action in ('repair', 'remove') and self._image_engine_state(engine, fresh=True) == 'running': + if action in ('repair', 'remove', 'verify') and self._image_engine_state(engine, fresh=True) == 'running': self.image_engine_clicked = True return # Both packs share one lease and one disk: one download at a time. @@ -1089,18 +1093,31 @@ def image_pack_view(self, model='image'): detail = self.t(*labels[value['state']]) if value.get('checking'): detail = self.t('Checking', '正在校验') - # Repair only answers a pack that is ready or known to be damaged; half a download just continues. - repairable = value['state'] in ('ready', 'invalid') + # Repair only answers a pack known to be damaged (or a check that found damage); half a download just continues. + repairable = value['state'] == 'invalid' + # A finished check that found damage is an answer, not a failure: the card says how many files need repair and offers Repair. + if (active.get('action') == 'verify' and active.get('state') == 'failed' + and active.get('reason') in ('needs_repair', 'integrity_failed')): + bad = sum(1 for v in installer.file_checks.values() if v.get('verification') in ('mismatch', 'missing')) or 1 + active = dict(active, state='checked') + repairable = True + detail = self.t('1 file needs repair' if bad == 1 else f'{bad} files need repair', f'有 {bad} 个文件需要修复') if active.get('state') == 'running': labels = {'install': ('Downloading', '正在下载'), 'repair': ('Repairing', '正在修复'), 'remove': ('Removing', '正在删除'), 'verify': ('Checking', '正在检查')} detail = self.t(*labels[active['action']]) + if active['action'] == 'verify' and active.get('verify_total'): + percent = min(100, int(100 * (active.get('verify_done') or 0) / active['verify_total'])) + detail = self.t(f'Checking {percent}%', f'检查中 {percent}%') if active.get('action') == 'install' and active.get('phase') == 'verify': detail = self.t('Checking', '正在校验') + elif active.get('action') == 'verify' and active.get('state') == 'done': + detail = self.t('Files intact', '文件完好') elif active.get('state') == 'paused_for_generation': # What the download waits for: a video, a picture, or another task holding the graphics card. detail = {'busy_video': self.t('Paused while a video generates', '视频生成中,已暂停'), - 'busy_picture': self.t('Paused while a picture is made', '正在出图,已暂停')}.get( + 'busy_picture': self.t('Paused while a picture is made', '正在出图,已暂停'), + 'busy_setup': self.t('Paused while FreeVideo installs, updates or cleans up', 'FreeVideo 正在安装、更新或清理,已暂停')}.get( active.get('reason'), self.t('Paused: the graphics card is busy', '显卡忙,已暂停')) elif active.get('state') == 'cancelled': detail = self.t('Paused', '已暂停') @@ -2778,16 +2795,19 @@ def snapshot(self): model_package=model_mismatch_package(raw_error, zh), exception=row.get('exception') if own else None) if failure.get('kind') == 'gpu-driver-missing': - from .display_adapters import adapters, line, only_other_vendors + from .display_adapters import adapters, line, nvidia_driver_listed, only_other_vendors zh = self.language.startswith('zh') names = adapters() if line(zh, names): failure['note'] = line(zh, names) if only_other_vendors(names): - # No NVIDIA card is listed: the card says what FreeVideo needs, and the note would repeat it. + # No NVIDIA card is listed: the card says what FreeVideo needs; the note names what was found. from .failure_details import UNSUPPORTED_VENDOR failure['title'], failure['action'] = UNSUPPORTED_VENDOR[1 if zh else 0] - failure.pop('note', None) + elif nvidia_driver_listed(names): + # Its driver named the card, so a driver is installed but does not answer: reinstall it. + from .failure_details import DRIVER_NOT_WORKING + failure['title'], failure['action'] = DRIVER_NOT_WORKING[1 if zh else 0] elif names: from .failure_details import DRIVER_FOR_LISTED_CARD failure['title'], failure['action'] = DRIVER_FOR_LISTED_CARD[1 if zh else 0] diff --git a/freevideo_engine/locking.py b/freevideo_engine/locking.py index 147e79bf..bc59e16f 100644 --- a/freevideo_engine/locking.py +++ b/freevideo_engine/locking.py @@ -299,6 +299,40 @@ def failure_frames(error, limit=12): for frame in traceback.extract_tb(error.__traceback__)[-limit:]] +LOCKFILE_FAIL_IMMEDIATELY = 0x1 + + +def windows_byte_lock_call(name, descriptor, *flags): + """kernel32 LockFileEx / UnlockFileEx on the first byte (Offset 0, length 1) of the descriptor's file.""" + import ctypes + import msvcrt + + class Overlapped(ctypes.Structure): # OVERLAPPED: the byte range starts at Offset/OffsetHigh (0 here) + _fields_ = [('Internal', ctypes.c_void_p), ('InternalHigh', ctypes.c_void_p), ('Offset', ctypes.c_uint32), + ('OffsetHigh', ctypes.c_uint32), ('hEvent', ctypes.c_void_p)] + + call = getattr(ctypes.WinDLL('kernel32', use_last_error=True), name) + call.argtypes = [ctypes.c_void_p] + [ctypes.c_uint32] * (len(flags) + 2) + [ctypes.POINTER(Overlapped)] + call.restype = ctypes.c_int + if not call(msvcrt.get_osfhandle(descriptor), *flags, 1, 0, ctypes.byref(Overlapped())): + raise ctypes.WinError(ctypes.get_last_error()) + + +def windows_shared_lock(descriptor): + """A shared lock on the file's first byte, failing at once when it is held exclusively (Windows). + + msvcrt.locking has no shared mode: its LK_NBRLCK is the same as LK_NBLCK, an exclusive LockFile, so two holders + of the "shared" machine lease excluded each other and a generation on a second GPU waited for the first one to + end. LockFileEx without LOCKFILE_EXCLUSIVE_LOCK takes the shared lock; the exclusive leases keep msvcrt.locking, + whose LockFile lock on the same byte excludes it and is excluded by it.""" + windows_byte_lock_call('LockFileEx', descriptor, LOCKFILE_FAIL_IMMEDIATELY, 0) + + +def windows_shared_unlock(descriptor): + """Release the shared lock taken by windows_shared_lock, at the same byte, before the handle is closed.""" + windows_byte_lock_call('UnlockFileEx', descriptor, 0) + + @contextmanager def runtime_lock(path=None, *, inherit=True, shared=False, wait_seconds=0): """Take a lease, optionally waiting a bounded time for acquisition only.""" @@ -315,6 +349,7 @@ def runtime_lock(path=None, *, inherit=True, shared=False, wait_seconds=0): if (actual.st_dev, actual.st_ino) != (expected.st_dev, expected.st_ino): raise ValueError('Inherited runtime lock descriptor does not match the GPU-work lock') stream = os.fdopen(os.dup(descriptor), 'a+b') + windows_shared_held = False try: # An inherited descriptor shares the parent's open-file description. # Close our descriptor on exit; do not unlock the parent's live work. @@ -329,10 +364,13 @@ def runtime_lock(path=None, *, inherit=True, shared=False, wait_seconds=0): stream.flush() stream.seek(0) try: - msvcrt.locking(stream.fileno(), - msvcrt.LK_NBRLCK if shared else msvcrt.LK_NBLCK, 1) + if shared: + windows_shared_lock(stream.fileno()) + windows_shared_held = True + else: + msvcrt.locking(stream.fileno(), msvcrt.LK_NBLCK, 1) except OSError as error: - raise BlockingIOError('Another process holds the installation lease') from error + raise BlockingIOError(ENGINE_BUSY) from error # The parent holds the byte-range lock; its Job Object owns this # worker tree. Closing a duplicated child handle must not unlock it. else: @@ -352,6 +390,12 @@ def runtime_lock(path=None, *, inherit=True, shared=False, wait_seconds=0): # The body is outside the retry loop: a failed request must never rerun. yield stream.fileno() finally: + if windows_shared_held: + try: + windows_shared_unlock(stream.fileno()) + except OSError as error: + # The close below releases the byte range anyway. + print('Could not unlock the shared lease at %s: %s.' % (path, error), file=sys.stderr, flush=True) # Releasing the lease must not discard completed work. Taking it still # fails loudly, but once the request has run, a close that fails has # nothing left to protect: the kernel drops the descriptor when this diff --git a/freevideo_engine/lora_check.py b/freevideo_engine/lora_check.py index 6d0a466e..33d052d6 100644 --- a/freevideo_engine/lora_check.py +++ b/freevideo_engine/lora_check.py @@ -196,6 +196,13 @@ def unreadable(layer): if reason == 'other_layer' and family(keys): return _bad('other-model', keys, layer=name) if reason: + # A layer int8 does not merge is skipped, but a linear layer this model has at another size (a LoRA + # trained for another build, such as the pruned one) is the same mismatch the other precisions report. + known = _find(target) + expected = LAYOUT[known] if known else UNCHECKED + rows = b[0] if split is None else b[0] // 3 + if expected is not UNCHECKED and len(expected) == 2 and list(expected) != [rows, a[1]]: + wrong.append((known, list(expected), [rows, a[1]])) skipped.append((reason, target)) continue if target in applied: @@ -220,6 +227,12 @@ def unreadable(layer): if int8_skip_reason(target, int8_targets, full=True) == 'other_layer' and family(keys): return _bad('other-model', keys, layer=name) skipped.append((int8_skip_reason(target, int8_targets, full=True), target)) + # Skipped either way, but a whole difference for a layer this model has at another size is the same + # mismatch the other precisions report. + known = None if bias else _find(target) + expected = LAYOUT[known] if known else UNCHECKED + if expected is not UNCHECKED and len(expected) == 2 and split is None and list(shape) != list(expected): + wrong.append((known, list(expected), list(shape))) continue found = _find(target) if found is None: diff --git a/freevideo_engine/macos_runtime.py b/freevideo_engine/macos_runtime.py index ae08c090..b576a20d 100644 --- a/freevideo_engine/macos_runtime.py +++ b/freevideo_engine/macos_runtime.py @@ -78,7 +78,9 @@ def load_conditioning(path, device, *, task, canvas, target=None): from .media_conditioning import describe value = torch.load(path, map_location='cpu', weights_only=True) anchors = tuple(value.get('keyframe_anchors', ())) - inferred = {(): 't2va', ('first',): 'i2va', ('last',): 'l2va', ('first', 'last'): 'fl2va'}.get(anchors) + from .mid_keyframes import native_anchors + inferred = {(): 't2va', ('first',): 'i2va', ('last',): 'l2va', + ('first', 'last'): 'fl2va'}.get(native_anchors(anchors)) actual_task = value.get('task', inferred) reference = str(actual_task).startswith('ref2va') if (not reference and (actual_task != task or inferred != task) diff --git a/freevideo_engine/modern_launcher.py b/freevideo_engine/modern_launcher.py index 9653202f..bbd909d4 100644 --- a/freevideo_engine/modern_launcher.py +++ b/freevideo_engine/modern_launcher.py @@ -768,6 +768,8 @@ def step(): def main(session=None): + from .installed_entry import protect + protect() if (getattr(sys, 'frozen', False) and sys.platform == 'darwin' and sys.argv[1:2] == ['--macos-process-host']): from .macos_process_host import main as supervise diff --git a/freevideo_engine/network.py b/freevideo_engine/network.py index 06877ace..eda6dae0 100644 --- a/freevideo_engine/network.py +++ b/freevideo_engine/network.py @@ -1589,6 +1589,53 @@ def writable(function, name, _): shutil.rmtree(io_path(path), onerror=writable) +RENAME_HELD_SECONDS = 8.0 +HELD_FOLDER_ERRORS = (5, 32) # Windows: access denied, sharing violation (a file inside is open elsewhere) + + +def rename_when_released(source, destination, commit, *, sleep=time.sleep, clock=time.monotonic): + """Put a finished Git download in place. + + Windows refuses to rename a folder while a program (a virus scanner, the search indexer) still has + one of the files just written open. Such a hold is usually short, so the rename is tried again for a + few seconds; if the folder stays held, its files are copied instead, and the copy is accepted only + when it holds the pinned commit. Any other error, and a hold that outlasts both, is raised as it came. + """ + source, destination = io_path(source), io_path(destination) + try: + source.rename(destination) + return + except OSError as first: + if getattr(first, 'winerror', None) not in HELD_FOLDER_ERRORS: + raise + failure = first + deadline, pause = clock() + RENAME_HELD_SECONDS, .1 + while clock() < deadline: + sleep(pause) + pause = min(pause * 2, 1.0) + try: + source.rename(destination) + return + except OSError as again: + if getattr(again, 'winerror', None) not in HELD_FOLDER_ERRORS: + raise + failure = again + try: + shutil.copytree(source, destination, symlinks=True, copy_function=shutil.copyfile) + head = io_path(destination / '.git' / 'HEAD').read_text(encoding='utf-8').strip() + if head != commit: + raise OSError('The copied folder is not at the pinned commit') + except BaseException as error: + try: + if destination.exists(): + remove_tree(destination) + except OSError: + pass # Held by another program; the failure below is the one that matters. + if not isinstance(error, Exception): + raise + raise failure from None + + def relocate(source, destination): """Move a finished folder; where a rename cannot (another volume) copy it.""" source, destination = io_path(source), io_path(destination) @@ -2036,7 +2083,7 @@ def execute(label, command): relocate(work, temporary) old = set_aside(target) if replacing else None try: - io_path(temporary).rename(io_path(target)) + rename_when_released(temporary, target, commit) except OSError as error: if old is None: raise diff --git a/freevideo_engine/package_cleanup.py b/freevideo_engine/package_cleanup.py index 58c96637..3320b22f 100644 --- a/freevideo_engine/package_cleanup.py +++ b/freevideo_engine/package_cleanup.py @@ -203,6 +203,11 @@ def discard(path, root, running=None, dry_run=False): if ('.replaced-' in path.name or not local_path(root, path) or started_from(path, running) or (path.is_dir() and not plain_tree(path))): return None + if only_linked_files(path): + # Every file here is another name of a file kept elsewhere (an import linked it into the installation): + # removing it frees nothing, and on Windows it changes that file's NTFS ChangeTime, which a generation + # reading the installed copy treats as the file having changed. + return None freed = unique_bytes(path) if dry_run: return freed @@ -212,7 +217,17 @@ def discard(path, root, running=None, dry_run=False): except OSError: return None if retired.is_dir(): - shutil.rmtree(retired, ignore_errors=True) + # Only the files no other name links to: a linked one stays under the retired name (packages() skips it). + for directory, file in list(unlinked_files(retired)): + try: + os.unlink(os.path.join(directory, file)) + except OSError: + pass + for directory, _, _ in sorted(os.walk(retired, followlinks=False), key=lambda row: len(row[0]), reverse=True): + try: + os.rmdir(directory) + except OSError: + pass else: try: retired.unlink() @@ -221,6 +236,87 @@ def discard(path, root, running=None, dry_run=False): return freed if not retired.exists() else max(0, freed - unique_bytes(retired)) +def finish_remnants(folder, running=None, dry_run=False): + """What an earlier discard left under a retired name: files that then had another name (an installed model). + Each that has no other name now goes, since removing a sole name changes no other file; emptied folders go + with them. Returns [(remnant, bytes freed)] for the remnants that freed something or are gone.""" + from .version_cleanup import started_from, plain_tree + try: + folder = io_path(checked_real_path(folder)) + except AliasUnavailable: + return [] + if not folder.is_dir() or (layout_name(folder.name) in CONTAINERS and redirected(folder)): + return [] + done = [] + for remnant in sorted(folder.iterdir()): + if ('.retired-' not in remnant.name or not remnant.is_dir() or redirected(remnant) + or not local_path(folder, remnant) or started_from(remnant, running) or not plain_tree(remnant)): + continue + freed = 0 + for directory, name in list(unlinked_files(remnant)): + path = os.path.join(directory, name) + try: + size = os.lstat(path).st_size + if not dry_run: + os.unlink(path) + freed += size + except OSError: + continue + if not dry_run: + for directory, _, _ in sorted(os.walk(remnant, followlinks=False), key=lambda row: len(row[0]), reverse=True): + try: + os.rmdir(directory) + except OSError: + pass + if freed or not remnant.exists(): + done.append((remnant, freed)) + return done + + +def only_linked_files(path): + """True when path holds files and every one of them has another name.""" + path = io_path(path) + try: + info = os.lstat(path) + except OSError: + return False + if not stat.S_ISDIR(info.st_mode): + return info.st_nlink > 1 + seen = False + for directory, folders, files in os.walk(path, followlinks=False): + folders[:] = [name for name in folders if not is_junction(Path(directory) / name)] + for name in files: + try: + if os.lstat(os.path.join(directory, name)).st_nlink == 1: + return False + except OSError: + return False + seen = True + return seen + + +def unlinked_files(path): + """(directory, name) of each file below path (or path itself) that no other name links to.""" + path = io_path(path) + try: + info = os.lstat(path) + except OSError: + return + if not stat.S_ISDIR(info.st_mode): + if info.st_nlink == 1: + yield str(path.parent), path.name + return + for directory, folders, files in os.walk(path, followlinks=False): + # os.walk(followlinks=False) still follows Windows directory junctions. + folders[:] = [name for name in folders if not is_junction(Path(directory) / name)] + for name in files: + try: + if os.lstat(os.path.join(directory, name)).st_nlink == 1: + yield directory, name + except OSError: + continue + + def packages(folder): try: folder = checked_real_path(folder) @@ -363,6 +459,11 @@ def prune_packages(engine, comfy_root=None, index=None, running=None, dry_run=Fa result['released_bytes'] += freed result['removed'].append(dict(kind='offline-package', path=plain(pack), bytes=freed, reason='installed and verified' if covered else 'not used by this installation')) + # Files an earlier pass left in place because an installed model shared them, once that name is gone. + for remnant, freed in finish_remnants(folder, running, dry_run): + result['released_bytes'] += freed + result['removed'].append(dict(kind='offline-package', path=plain(remnant), bytes=freed, + reason='no longer linked to the installation')) except BlockingIOError: result['kept'].append(dict(kind='offline-package', path=plain(folder), reason='in use')) return result @@ -391,6 +492,9 @@ def prune_downloads(engine, index=None, running=None, dry_run=False): if (parent / STAGES).is_dir() and (not windows() or local_path(top, parent / STAGES)): stages.add(parent / STAGES) for folder in sorted(stages): + for remnant, freed in finish_remnants(folder, running, dry_run): + result['released_bytes'] += freed + result['removed'].append(dict(kind='download-leftover', path=plain(remnant), bytes=freed)) for stage in sorted(folder.iterdir()): match = STAGE.fullmatch(stage.name) if not match or match['sha'] not in prefixes: diff --git a/freevideo_engine/private_refs.py b/freevideo_engine/private_refs.py index 86fb921d..2b954943 100644 --- a/freevideo_engine/private_refs.py +++ b/freevideo_engine/private_refs.py @@ -28,6 +28,8 @@ ('agent', re.compile(r'freevideo' + SEP + 'agent' + SEP + '([A-Za-z0-9_-]{1,64})')), ) RECORD_LIMIT = 64 * 1024 * 1024 +# How often tidying the draft starts again when the page saved it in between. +DRAFT_TRIES = 5 class ScanIncomplete(OSError): @@ -80,6 +82,63 @@ def _walk(folder, suffixes, *, skip=()): yield os.path.join(parent, leaf) +def _is_draft(path): + """The creation draft the page keeps in the user folder. It names the pictures last set up, only so a start + without the browser's copy can offer them again: it never keeps a file alive, and what is gone leaves it.""" + return Path(path).as_posix().endswith('/freevideo/prompt-draft.json') + + +def scrub_draft(user_root=None, input_root=None): + """Takes the reference pictures that no longer exist out of the saved creation draft, so nothing of a deleted + file stays in it. Never raises; returns how many rows went. + + The page saves the draft through ComfyUI's own file route, so no lock here is shared with it. The file is read, + changed and written back only while its bytes are still the ones that were read; a save that lands in between + makes this start again from the new file, so the user's newer draft is never replaced by an older one.""" + removed = 0 + try: + user_root = user_root if user_root is not None else user_directory() + input_root = input_root if input_root is not None else input_directory() + if user_root is None or input_root is None or not _plain_dir(user_root): + return 0 + base = os.path.realpath(input_root) + + def there(row): + name = re.sub(r' \[(?:input|output|temp)\]$', '', row.get('file', '')) if isinstance(row, dict) else '' + target = os.path.realpath(os.path.join(base, *re.split(r'[\\/]', name))) if name else base + return target != base and target.startswith(base + os.sep) and os.path.exists(target) + + for path in _walk(Path(user_root), ('.json',)): + if not _is_draft(path): + continue + for attempt in range(DRAFT_TRIES): + with open(path, 'rb') as stream: + raw = stream.read() + draft = json.loads(raw.decode('utf-8')) + rows = draft.get('assets') if isinstance(draft, dict) else None + if not isinstance(rows, list): + break + kept = [row for row in rows if there(row)] + if len(kept) == len(rows): + break + draft['assets'] = kept + temporary = path + '.tmp' + with open(temporary, 'w', encoding='utf-8') as stream: + json.dump(draft, stream, ensure_ascii=False) + with open(path, 'rb') as stream: + unchanged = stream.read() == raw + if unchanged: + os.replace(temporary, path) + removed += len(rows) - len(kept) + break + os.unlink(temporary) + else: + logging.warning('[FreeVideo] The saved creation draft kept changing; it was left as it is.') + except Exception: + logging.warning('[FreeVideo] Could not tidy the saved creation draft.', exc_info=True) + return removed + + def scan(*, output_root=None, user_root=None, queue=None, extra=(), roots=()): """Every token a record still names. Raises ScanIncomplete when a record exists but cannot be read. @@ -101,7 +160,8 @@ def scan(*, output_root=None, user_root=None, queue=None, extra=(), roots=()): if user_root is not None: # ComfyUI's saved workflows and FreeVideo's own page records in the user folder. for path in _walk(Path(user_root), ('.json',)): - found |= tokens(_read_text(path)) + if not _is_draft(path): + found |= tokens(_read_text(path)) if queue is not None: try: running, pending = queue.get_current_queue_volatile() @@ -145,6 +205,8 @@ def run_sweep(*, input_root, output_root=None, user_root=None, queue=None, extra type(error).__name__) return None summary = private_store.sweep(input_root, referenced, root=root, now=now, released=released(output_root)) + if not summary.get('dry_run'): + scrub_draft(user_root, input_root) if output_root is not None: # Folders of requests that ended without a video: listed when cleanup only lists, removed otherwise. from .comfy_library import failed_runs @@ -277,6 +339,8 @@ def clean(context, tokens, *, root=None, now=None): size = remove_failed_run(context['output_root'], identity, now=now) removed += size > 0 freed += size + if removed: + scrub_draft(context.get('user_root'), context['input_root']) logging.info('[FreeVideo] Private file cleanup confirmed by the user: %d files, %.1f MB.', removed, freed / 1e6) return dict(removed=removed, freed_bytes=freed) @@ -333,7 +397,8 @@ def _record_texts(context): yield _read_text(path) if user_root is not None: for path in _walk(Path(user_root), ('.json',)): - yield _read_text(path) + if not _is_draft(path): + yield _read_text(path) queue = context.get('queue') if queue is not None: try: @@ -558,8 +623,10 @@ def release_owner(owner_id, context=None, *, input_root=None): except OSError: logging.warning('[FreeVideo] Kept the files of a deleted work: a record could not be read.') return None - return private_store.release(owner_id, input_root=context['input_root'], cache_root=data_root() / 'input-cache', - keep=keep) + released = private_store.release(owner_id, input_root=context['input_root'], cache_root=data_root() / 'input-cache', + keep=keep) + scrub_draft(context.get('user_root'), context['input_root']) + return released except Exception: logging.warning('[FreeVideo] Could not release what a deleted work held.', exc_info=True) return None @@ -604,4 +671,6 @@ def release_tokens(context, tokens): status = private_store.safe_remove(context['input_root'], row['path'], folders=4 if row['kind'] == 'agent' else 1)[0] removed += status == 'removed' + if removed: + scrub_draft(context.get('user_root'), context['input_root']) return removed diff --git a/freevideo_engine/processes.py b/freevideo_engine/processes.py index 0fa00e5b..5fdeacdf 100644 --- a/freevideo_engine/processes.py +++ b/freevideo_engine/processes.py @@ -39,7 +39,8 @@ def module_command(module, *arguments): if getattr(sys, 'frozen', False) and sys.platform.startswith('linux'): # The Linux launcher (AppImage) runs its own helpers; see modern_launcher.main. return [sys.executable, '--freevideo-module', module, *map(str, arguments)] - code = ("import runpy,sys;sys.path.insert(0,sys.argv.pop(1));" + from .installed_entry import INSTALLED_ONLY + code = (INSTALLED_ONLY + "import runpy;sys.path.insert(0,sys.argv.pop(1));" "runpy.run_module(sys.argv.pop(1),run_name='__main__',alter_sys=True)") source = Path(__file__).resolve().parents[1] view = launch_view.current() diff --git a/freevideo_engine/prompt_vlm/rules.py b/freevideo_engine/prompt_vlm/rules.py index 6c41b237..07181af7 100644 --- a/freevideo_engine/prompt_vlm/rules.py +++ b/freevideo_engine/prompt_vlm/rules.py @@ -148,21 +148,107 @@ def sections(text, fields): return re.sub(r'\n+(?=(?:%s):)' % names, '\n\n', text).strip() +# Every output check has one fixed name and one category. Names and categories are the only thing a +# rejection reports: never the prompt, never the rejected draft. The page shows the category and the +# feedback carries both; tests/test_prompt_vlm_checks.py fails when a check has no entry here. +CHECKS = { + 'type_or_length': 'length', 'output_token_limit': 'length', 'split_event_length': 'length', + 'split_shared_length': 'length', 'parts_length': 'length', 'reverse_length': 'length', 'answer_empty': 'length', + 'headings': 'structure', 'missing_shot_1': 'structure', 'empty_section': 'structure', 'json': 'structure', + 'answer_count': 'structure', 'answer_fields': 'structure', 'answer_error': 'structure', + 'split_not_text': 'structure', 'split_sections': 'structure', 'split_event_repeats_shared': 'structure', + 'split_action_placed_twice': 'structure', 'split_empty_part': 'structure', 'parts_count': 'structure', + 'timestamp_not_before_duration': 'timing', 'timing_lost': 'timing', + 'picture_index_out_of_range': 'media', 'unsupported_audio_video_reference': 'media', + 'missing_picture_reference': 'media', + 'missing_text': 'text', 'split_text_changed': 'text', 'reverse_line_missing': 'text', + 'split_lines_order': 'dialogue', +} + + class InvalidOutput(ValueError): """Stable rejection metadata; never retain the prompt or rejected draft.""" - def __init__(self, condition, text, value): + def __init__(self, condition, text=None, value=None): super().__init__('invalid_output') draft = text if isinstance(text, str) else '' - required = required_labels(value) + required = required_labels(value) if isinstance(value, dict) and 'media' in value else [] pictures = [int(each[len('', draft)} - self.details = dict(condition=condition, output_characters=len(draft), + self.details = dict(condition=condition, category=CHECKS[condition], output_characters=len(draft), missing_pictures=sorted(i for i in pictures if f'' not in draft), missing_references=[each for each in required if each not in draft], out_of_range_pictures=sorted(i for i in indices if i not in pictures), retried=False) +def clean_counts(counts): + """The counts as read from the file, rebuilt so that a damaged or hand-edited file still counts on: + only the known actions and checks, only whole numbers (anything else restarts at zero).""" + counts = counts if isinstance(counts, dict) else {} + whole = lambda value: value if type(value) is int and value >= 0 else 0 + jobs, checks = counts.get('jobs'), counts.get('checks') + jobs = jobs if isinstance(jobs, dict) else {} + checks = checks if isinstance(checks, dict) else {} + since = counts.get('since') + clean = dict(schema=1, jobs={}, checks={}) + if isinstance(since, str) and re.fullmatch(r'\d{4}-\d{2}-\d{2}', since): + clean['since'] = since + for action in ('rewrite', 'ask', 'split', 'reverse'): + row = jobs.get(action) + if isinstance(row, dict): + clean['jobs'][action] = {key: whole(row.get(key)) for key in ('total', 'recovered', 'failed')} + for name, category in CHECKS.items(): + row = checks.get(name) + if isinstance(row, dict): + clean['checks'][name] = dict(category=category, **{key: whole(row.get(key)) for key in ('rejected', 'first', 'recovered', 'final')}) + return clean + + +def count_checks(counts, action, state, day=None): + """Add one finished job to the local check counts and return them; numbers only, no text. + + Only jobs that reached a verdict count: a finished answer, or a failure by an output check. A + cancelled job or one that ran out of memory never reached the checks, so it is no denominator. + Per check: first = jobs whose first draft it rejected, recovered = those jobs that then finished + after the single retry, final = jobs it ended with a failure, rejected = every rejection + including the retry's. Read together with the job totals: first / total is how often the model + trips the check, recovered / first how often one retry repairs it, final / total how often a + person sees the message because of it. + """ + done = state.get('phase') == 'complete' + if action not in ('rewrite', 'ask', 'split', 'reverse') or not ( + done or state.get('phase') == 'failed' and (state.get('error') == 'invalid_output' or state.get('output_rejection'))): + return clean_counts(counts) if counts else counts + counts = clean_counts(counts) + if day: + counts.setdefault('since', day) + jobs = counts.setdefault('jobs', {}).setdefault(action, dict(total=0, recovered=0, failed=0)) + checks = counts.setdefault('checks', {}) + rows = [row for row in (state.get('diagnostics') or {}).get('output_rejections') or [] + if isinstance(row, dict) and row.get('condition') in CHECKS] + final = state.get('output_rejection') + final = final if isinstance(final, dict) and final.get('condition') in CHECKS else None + if final is not None and not done and not (rows and rows[-1]['condition'] == final['condition']): + rows.append(final) + jobs['total'] += 1 + if done: + jobs['recovered'] += bool(rows) + else: + jobs['failed'] += 1 + first = set() + for row in rows: + check = checks.setdefault(row['condition'], dict(category=CHECKS[row['condition']], rejected=0, first=0, recovered=0, final=0)) + check['rejected'] += 1 + if not row.get('retried') and row['condition'] not in first: + # One count per check and job, however many first-pass drafts (the time-point rescale is one) it rejected. + first.add(row['condition']) + check['first'] += 1 + check['recovered'] += done + if final is not None and not done: + checks[final['condition']]['final'] += 1 + return counts + + def validate_output(text, value): if not isinstance(text, str) or not 100 <= len(text.strip()) <= 20000: raise InvalidOutput('type_or_length', text, value) @@ -649,14 +735,14 @@ def validate_image(text, value): def validate_answers(answers, value): """Worker output shape for an ask job: one answer per question, in order.""" if not isinstance(answers, list) or len(answers) != len(value['questions']): - raise ValueError('invalid_output') + raise InvalidOutput('answer_count') for answer in answers: if not isinstance(answer, dict) or set(answer) - ANSWER_KEYS or not isinstance(answer.get('text', ''), str): - raise ValueError('invalid_output') + raise InvalidOutput('answer_fields') if 'error' not in answer and not answer.get('text', '').strip(): - raise ValueError('invalid_output') + raise InvalidOutput('answer_empty') if 'error' in answer and answer['error'] not in ('invalid_json', 'context_length'): - raise ValueError('invalid_output') + raise InvalidOutput('answer_error') return answers @@ -772,12 +858,12 @@ def split_user_text(value): def split_answer(text, count): if not isinstance(text, str): - raise ValueError('invalid_output') + raise InvalidOutput('split_not_text') text = text.strip().strip('`').strip() found = list(re.finditer(r'(?m)^[ \t*#]*(Shared|Part[ \t]+(\d+))[ \t*]*[::]', text)) names = [m.group(2) or 'shared' for m in found] if names != ['shared'] + [str(i) for i in range(1, count + 1)] or text[:found[0].start()].strip(' \t\n*#'): - raise ValueError('invalid_output') + raise InvalidOutput('split_sections') ends = [m.start() for m in found[1:]] + [len(text)] values = [' '.join(text[m.end():end].split()).strip('* ') for m, end in zip(found, ends)] return values[0], values[1:] @@ -860,7 +946,7 @@ def validate_split(text, value, *, strict=False): body, sound, lines = part_source(value['text']) shared, events = split_answer(text, len(value['seconds'])) if re.search(r'\[L\d+\]', shared) or wide(body) != wide(shared + ' '.join(events)): - raise ValueError('invalid_output') + raise InvalidOutput('split_text_changed') used = set() def once(match): # A marker written twice stays where it first stands. @@ -870,9 +956,10 @@ def once(match): return match.group(0) events = [' '.join(re.sub(r'\[L\d+\]', once, event).split()) for event in events] keys = [plain(re.sub(r'\[L\d+\]', '', event)) for event in events] - if any(len(event) > 4000 for event in events) or any(key and (key in plain(shared) or key == plain(body)) - for key in keys): - raise ValueError('invalid_output') + if any(len(event) > 4000 for event in events): + raise InvalidOutput('split_event_length') + if any(key and (key in plain(shared) or key == plain(body)) for key in keys): + raise InvalidOutput('split_event_repeats_shared') # Clauses after the opening sentence, each with whether it stands in the first half of the description. told_at, story = 0, [] for index, sentence in enumerate(sentences(body)): @@ -882,14 +969,14 @@ def once(match): story.append((words, told_at < len(body) / 2)) told_at += len(piece) if not 20 <= len(shared) <= 4000: - raise ValueError('invalid_output') + raise InvalidOutput('split_shared_length') def placed_twice(piece): return action(plain(piece)) and any(plain(piece) in key for key in keys) def told(piece): return next((early for words, early in story if action(plain(piece)) and (plain(piece) in words or words in plain(piece))), None) if strict and any(placed_twice(piece) for piece in clauses(shared)): - raise ValueError('invalid_output') + raise InvalidOutput('split_action_placed_twice') join = '' if wide(shared) else ' ' kept = [piece for piece in clauses(shared) if not placed_twice(piece) and told(piece) is None] # Story the model left in Shared alone: its first half opens the video, the rest is not repeated. @@ -908,10 +995,10 @@ def told(piece): events = cleaned if not re.sub(r'\[L\d+\]', '', events[0]).strip() or strict and not all( re.sub(r'\[L\d+\]', '', event).strip() for event in events): - raise ValueError('invalid_output') + raise InvalidOutput('split_empty_part') placed = [int(n) for event in events for n in re.findall(r'\[L(\d+)\]', event)] if placed != list(range(1, len(lines) + 1)) and strict: - raise ValueError('invalid_output') + raise InvalidOutput('split_lines_order') if placed != list(range(1, len(lines) + 1)): # The model lost or reordered a line: keep its events, place the lines by time. events = [' '.join(re.sub(r'\s*\[L\d+\]\s*[::,,]?', ' ', event).split()).rstrip('::,,') for event in events] @@ -1028,9 +1115,10 @@ def units(text, index): def validate_parts(parts, value): """Worker output shape for a split job: one non-empty text per part.""" - if (not isinstance(parts, list) or len(parts) != len(value['seconds']) - or any(not isinstance(part, str) or not 40 <= len(part) <= 20000 for part in parts)): - raise ValueError('invalid_output') + if not isinstance(parts, list) or len(parts) != len(value['seconds']): + raise InvalidOutput('parts_count') + if any(not isinstance(part, str) or not 40 <= len(part) <= 20000 for part in parts): + raise InvalidOutput('parts_length') return parts @@ -1061,7 +1149,7 @@ def validate_parts(parts, value): def reverse_request(value): """A file from ComfyUI's input folder, how many frames to look at, and the spoken lines the caller already has.""" - if not isinstance(value, dict) or set(value) - {'file', 'frames', 'lines', 'mode'} or value.get('mode', 'reverse') != 'reverse': + if not isinstance(value, dict) or set(value) - {'file', 'frames', 'lines', 'mode', 'language'} or value.get('mode', 'reverse') != 'reverse': raise ValueError('invalid_request') name, frames, lines = value.get('file'), value.get('frames', REVERSE_DEFAULT_FRAMES), value.get('lines', []) if not isinstance(name, str) or not name or len(name) > 1024: @@ -1071,7 +1159,22 @@ def reverse_request(value): if (not isinstance(lines, list) or len(lines) > REVERSE_LINES or any(not isinstance(line, str) or not plain(line) or len(line) > 400 for line in lines)): raise ValueError('invalid_request') - return dict(mode='reverse', file=name, frames=frames, lines=[line.strip() for line in lines]) + language = value.get('language', 'en') + if language not in ('en', 'zh'): + raise ValueError('invalid_request') + return dict(mode='reverse', file=name, frames=frames, lines=[line.strip() for line in lines], language=language) + + +REVERSE_IN_CHINESE = ' Write it in Chinese.' + + +def reverse_describe(value): + """The description question, asking for Chinese when the page is in Chinese.""" + return REVERSE_DESCRIBE + (REVERSE_IN_CHINESE if value.get('language') == 'zh' else '') + + +def reverse_camera(value): + return REVERSE_CAMERA + (REVERSE_IN_CHINESE if value.get('language') == 'zh' else '') def reverse_text(description, camera, lines): @@ -1086,8 +1189,8 @@ def reverse_text(description, camera, lines): def validate_reverse(text, value): """Worker output for a reverse job: text of a sensible length that keeps every given spoken line verbatim.""" if not isinstance(text, str) or not 40 <= len(text.strip()) <= 20000: - raise ValueError('invalid_output') + raise InvalidOutput('reverse_length') for line in value.get('lines', ()): if line not in text: - raise ValueError('invalid_output') + raise InvalidOutput('reverse_line_missing') return text diff --git a/freevideo_engine/prompt_vlm/service.py b/freevideo_engine/prompt_vlm/service.py index 078f9da6..e4a9d9c8 100644 --- a/freevideo_engine/prompt_vlm/service.py +++ b/freevideo_engine/prompt_vlm/service.py @@ -22,6 +22,9 @@ EXTRA_VRAM_RESERVE = 2**30 +# What the worker says while it runs, passed on to the page's status; a reverse prompt's describing and camera stages included. +STREAMED_PHASES = ('loading', 'rewriting', 'answering', 'describing', 'camera') + class Worker: """One pipe owner across idle imports and the subsequent rewrite.""" def __init__(self, process): @@ -106,6 +109,7 @@ def __init__(self, installation, input_directory): self.installation = installation self.input_directory = input_directory self.mutex = threading.Lock() + self.counts_lock = threading.Lock() self.stop = threading.Event() self.state = {} self.key = None @@ -515,9 +519,12 @@ def work(self, root, machine, action, value): self.progress(dict(phase='failed', error='busy')) except Exception as error: known = {'disk_space', 'ram_space', 'unreadable_video', 'rewrite_failed', 'split_failed', 'worker_exit', 'timeout', 'worker_cleanup_failed'} - if str(error) not in known and not isinstance(error, rules.InvalidOutput): + # An output check names what failed in `output_rejection`; only a rewrite reports it as invalid_output, + # the other jobs keep their own failure codes. + rejected = isinstance(error, rules.InvalidOutput) and action not in ('ask', 'split', 'reverse') + if str(error) not in known and not rejected: logging.warning('[FreeVideo] Prompt model job %s failed: %s', action, type(error).__name__, exc_info=True) - self.progress(dict(phase='failed', error='invalid_output' if isinstance(error, rules.InvalidOutput) + self.progress(dict(phase='failed', error='invalid_output' if rejected else str(error) if str(error) in known else 'disk_space' if isinstance(error, OSError) and ran_out(error) else 'download_failed' if action == 'install' @@ -531,11 +538,17 @@ def work(self, root, machine, action, value): if self.stop.is_set(): self.progress(dict(phase='cancelled')) self.result_expires = time.monotonic() + 600 + try: + counts = self.count_checks(root, action) + if counts: + self.progress(dict(check_counts=counts)) + except Exception: # the counts are a nicety: whatever is wrong with them must not stop the report below + logging.warning('[FreeVideo] Could not update the prompt check counts', exc_info=True) # Allowlisted metadata only, never original/rewritten text or input paths. # Output rejections contain condition IDs, counts, typed media labels and retry flags only. report = {key: item for key, item in self.state.items() - if key in ('phase', 'error', 'exception', 'error_details', 'timings', 'diagnostics', - 'resources', 'cleanup', 'worker_returncode', 'output_rejection', 'gpu_wait')} + if key in ('phase', 'error', 'exception', 'error_details', 'oom_source', 'timings', 'diagnostics', + 'resources', 'cleanup', 'worker_returncode', 'output_rejection', 'gpu_wait', 'check_counts')} try: spec = assets.catalog() except (OSError, ValueError): @@ -556,6 +569,23 @@ def work(self, root, machine, action, value): except OSError: pass + def count_checks(self, root, action): + """Add this job to the check counts kept beside the model files (numbers only) and return them.""" + from ..monitoring import save + path = Path(root) / 'prompt-vlm-check-counts.json' + with self.counts_lock: + try: + counts = json.loads(path.read_text(encoding='utf-8')) + except (OSError, ValueError): + counts = {} + with self.mutex: + state = dict(self.state) + before = json.dumps(counts, sort_keys=True) + updated = rules.count_checks(counts, action, state, time.strftime('%Y-%m-%d', time.gmtime())) + if updated and json.dumps(updated, sort_keys=True) != before: + save(path, updated) + return updated + def infer(self, root, machine, descriptor, value, *, wait=False): """Run the worker; when the model does not fit the GPU, name the programs holding it and, for a rewrite, wait for them to free enough and run again.""" @@ -589,7 +619,7 @@ def infer(self, root, machine, descriptor, value, *, wait=False): waited['oom_reruns'] = waited.get('oom_reruns', 0) + 1 self.progress(dict(gpu_wait=dict(waited))) with self.mutex: - for key in ('error', 'exception', 'error_details', 'gpu_holders', 'gpu_short_bytes'): + for key in ('error', 'exception', 'error_details', 'oom_source', 'gpu_holders', 'gpu_short_bytes'): self.state.pop(key, None) self.state['phase'] = 'loading' continue @@ -609,7 +639,7 @@ def infer(self, root, machine, descriptor, value, *, wait=False): self.progress(dict(phase='failed', error='out_of_memory', gpu_holders=self.gpu_holders(machine))) return with self.mutex: - for key in ('error', 'exception', 'error_details', 'gpu_holders', 'gpu_short_bytes'): + for key in ('error', 'exception', 'error_details', 'oom_source', 'gpu_holders', 'gpu_short_bytes'): self.state.pop(key, None) self.state['phase'] = 'loading' @@ -749,7 +779,7 @@ def read_rows(): if row.get('phase') in ('complete', 'failed'): result.update(row) result_received_at[:] = [time.monotonic()] - elif row.get('phase') in ('loading', 'rewriting', 'answering'): + elif row.get('phase') in STREAMED_PHASES: self.progress(row) try: writer.start() diff --git a/freevideo_engine/prompt_vlm/worker.py b/freevideo_engine/prompt_vlm/worker.py index 11d6ba4e..e87d9836 100644 --- a/freevideo_engine/prompt_vlm/worker.py +++ b/freevideo_engine/prompt_vlm/worker.py @@ -139,14 +139,39 @@ def gpu_snapshot(stats): if torch is not None and torch.cuda.is_initialized(): try: free, total = torch.cuda.mem_get_info() + memory = torch.cuda.memory_stats() stats.update(gpu_peak_allocated_bytes=torch.cuda.max_memory_allocated(), gpu_peak_reserved_bytes=torch.cuda.max_memory_reserved(), gpu_free_bytes=free, gpu_total_bytes=total, - gpu_allocator_ooms=torch.cuda.memory_stats().get('num_ooms')) + gpu_allocator_ooms=memory.get('num_ooms'), + gpu_alloc_retries=memory.get('num_alloc_retries')) + # Where the card's memory is at this moment: the allocator's pool, the tensors in it, and the + # rest (CUDA context, kernel modules, other programs), which the allocator cannot give back. + reserved, allocated = memory.get('reserved_bytes.all.current'), memory.get('allocated_bytes.all.current') + if type(reserved) is int and type(allocated) is int: + stats.update(gpu_reserved_bytes=reserved, gpu_allocated_bytes=allocated, + gpu_outside_allocator_bytes=max(0, total - free - reserved)) + # Which attention kernels PyTorch may pick at this moment (1 = allowed). With flash and cuDNN + # unavailable the math kernel is the fallback, which needs far more memory for long inputs. + switches = [] + for name in ('flash', 'mem_efficient', 'math', 'cudnn'): + check = getattr(getattr(getattr(torch, 'backends', None), 'cuda', None), name + '_sdp_enabled', None) + if check is not None: + switches.append('%s=%d' % (name, bool(check()))) + if switches: + stats['sdp_switches'] = ','.join(switches) except (RuntimeError, OSError): stats['gpu_sample_unavailable'] = True +def tried_bytes(error): + """The size in the allocator's "Tried to allocate 3.60 GiB" as a number of bytes; None without it.""" + found = re.search(r'tried to allocate ([0-9]{1,12}(?:\.[0-9]{1,6})?) (b|kib|mib|gib)\b', str(error).lower()) + if found: + return int(float(found.group(1)) * {'b': 1, 'kib': 2**10, 'mib': 2**20, 'gib': 2**30}[found.group(2)]) + return None + + def failure(error, mode='rewrite'): """Keep stack locations and typed causes, never arbitrary exception text. @@ -157,9 +182,15 @@ def failure(error, mode='rewrite'): message = str(error) fallback = 'ask_failed' if mode == 'ask' else 'rewrite_failed' code = message if message in allowed else 'out_of_memory' if 'out of memory' in message.lower() else fallback + # Who ran out: the allocator ("Tried to allocate ...", after it gave back its cache) or a CUDA call + # outside it ("CUDA error: out of memory", e.g. loading a kernel). One of two fixed words, never the text. + source = None if code != 'out_of_memory' or message == 'out_of_memory' else \ + 'allocator' if 'tried to allocate' in message.lower() else 'cuda_runtime' frames = [dict(module=Path(f.filename).name, function=f.name, line=f.lineno) for f in traceback.extract_tb(error.__traceback__)] result = dict(error=code, exception=type(error).__name__, error_details=frames) + if source: + result['oom_source'] = source from .rules import InvalidOutput if isinstance(error, InvalidOutput): result['output_rejection'] = error.details @@ -345,7 +376,8 @@ def load_model(folder, torch, stats, checkpoint): from .. import gpu_budget free, total = torch.cuda.mem_get_info() stats.update(gpu_name=torch.cuda.get_device_name(), gpu_free_before_load_bytes=free, gpu_total_bytes=total, - gpu_compute_capability=list(torch.cuda.get_device_capability())) + gpu_compute_capability=list(torch.cuda.get_device_capability()), + gpu_capability='%d.%d' % torch.cuda.get_device_capability()) reading = free admission = gpu_budget.configure(torch, free, reserve_bytes=256 * 2**20) free = min(free, admission.get('effective_allocator_limit_bytes') or free) @@ -579,8 +611,8 @@ def pick_frames(frames, build, budget): def reverse(folder, value, stats): """Describe a video from its frames, ask where the camera moves, and give both back with the caller's spoken lines.""" - from .rules import (REVERSE_CAMERA, REVERSE_CAMERA_TOKENS, REVERSE_DESCRIBE, REVERSE_INPUT_TOKENS, - REVERSE_OUTPUT_TOKENS, reverse_text) + from .rules import (REVERSE_CAMERA_TOKENS, REVERSE_INPUT_TOKENS, REVERSE_OUTPUT_TOKENS, reverse_camera, + reverse_describe, reverse_text) stats.update(stage='imports', pid=os.getpid(), mode='reverse', frame_files=len(value['frame_files']), answer_tokens=REVERSE_OUTPUT_TOKENS, dtype='bfloat16', attention='sdpa', kv_cache='dynamic', backend='transformers', accelerations=[], persistent_model=False) @@ -591,7 +623,7 @@ def reverse(folder, value, stats): processor = AutoProcessor.from_pretrained(folder, local_files_only=True, trust_remote_code=False) # Frames and size are chosen before the model is placed, from the request's token budget: first fewer frames # (down to 8), then smaller ones. The tower stays on the GPU for a video. - chosen = pick_frames(value['frame_files'], lambda rows, side: video_inputs(processor, rows, side, REVERSE_DESCRIBE), + chosen = pick_frames(value['frame_files'], lambda rows, side: video_inputs(processor, rows, side, reverse_describe(value)), REVERSE_INPUT_TOKENS) if chosen is None: raise ValueError('context_length') @@ -616,7 +648,7 @@ def on_token(timing): stats.update(describe_seconds=time.monotonic() - loaded, output_tokens=len(ids)) checkpoint('decode', 'camera') started = time.monotonic() - camera_inputs = video_inputs(processor, picked, side, REVERSE_CAMERA) + camera_inputs = video_inputs(processor, picked, side, reverse_camera(value)) ids, _ = generate(torch, model, camera_inputs.to(device), REVERSE_CAMERA_TOKENS, started, lambda timing: None) camera = processor.decode(ids, skip_special_tokens=True).strip() stats.update(camera_seconds=time.monotonic() - started, stage='complete') @@ -955,6 +987,9 @@ def main(): if not prestarting or requested: gpu_snapshot(stats) mode = value.get('mode') if isinstance(value, dict) else None + tried = tried_bytes(error) + if tried is not None: + stats['oom_tried_bytes'] = tried emit(phase='failed', diagnostics=stats, **failure(error, mode)) return 1 return 0 diff --git a/freevideo_engine/release_notes.json b/freevideo_engine/release_notes.json index 9463e8cc..a6a5e39c 100644 --- a/freevideo_engine/release_notes.json +++ b/freevideo_engine/release_notes.json @@ -1,23 +1,60 @@ { "schema": 1, - "product_version": "0.6.10", + "product_version": "0.6.11", "en": { - "summary": "Fixes generating after opening Presets, makes Preview first follow the step count, and makes update failure reports more complete.", + "summary": "0.6.11 can write a prompt from a picture or a video, makes local network access and first, middle and last frames on the Mac work as expected, and no longer stops a second generation on two graphics cards with an error on Windows. Failure messages now also say what went wrong and what to do next.", "changes": [ - "Generate works after opening Presets: when a setting needs changing, the reason appears next to it and you can fill it in there.", - "Preview first follows the step count: when a workflow's first-pass steps are not 8, Preview first is unavailable with the reason shown, and the key generates the video.", - "More complete update failure reports: \"Report a problem\" on an update failure now adds the last lines of the update log, with file paths, IP addresses and access tokens removed." + "Reverse prompt: in the image view and the create panel, choose a picture or a video and FreeVideo writes the description.", + "Fuller local network access: when FreeVideo is opened through its local network address, you can generate with reference pictures, edit generated pictures and copy prompts.", + "First, middle and last frames on the Mac: generating with a first, middle and last frame works on the Mac.", + "Two graphics cards at once: on Windows, a generation started on the second graphics card no longer stops with an error while the first one is working.", + "Clearer failure messages: every kind of failure says what to do next. When a prompt enhancement result is incomplete, the message says what was wrong.", + "More accurate driver messages: when no working driver is found, the launcher shows the graphics card it detected and tells \"driver not installed\" apart from \"driver not working\".", + "LoRAs and reference pictures are kept: the LoRAs and reference pictures set in the create panel are still there after FreeVideo restarts, and scene and prop cards remember the LoRAs used to make their picture.", + "Steadier running: FreeVideo commands use the installed program from any folder. When graphics memory runs short while the prompt is processed, FreeVideo retries once instead of failing.", + "Easier image models: Repair asks you first and keeps the original shared file under a new name. A download that starts while FreeVideo is installing, updating or cleaning up continues by itself when that finishes.", + "Saved prompts work right after an update: prompts saved before updating FreeVideo do not need to be processed again.", + "More reliable long video redo: after a lost or late reply, choosing \"Redo from here\" again shows the part already started instead of making another one.", + "A steadier first generation after an update: cleaning up old versions no longer changes the model files in use, so the first generation after an update is not interrupted by it." ] }, "zh": { - "summary": "修复了打开“预设”后无法生成的问题,“先出预览”会跟随步数说明是否可用,更新失败的报告也更完整。", + "summary": "0.6.11 新增从图片或视频反推提示词,局域网访问和 Mac 首中尾帧生成可以正常使用,Windows 上两张显卡同时生成也不再报错停下。失败提示会说明原因和下一步。", "changes": [ - "打开“预设”后可正常生成:有设置需要修改时,会在对应位置说明原因,并可直接填写。", - "“先出预览”跟随步数:工作流的一采步数不是 8 时,“先出预览”不可选并写明原因,按键直接生成视频。", - "更新失败的报告更完整:在更新失败提示中点“提交问题”,报告会附上最近几行更新记录,其中的文件路径、IP 地址和访问令牌已移除。" + "反推提示词:在图像视图和创作面板中,可以选一张图片或一段视频,自动写出描述。", + "局域网访问更完整:通过局域网地址打开 FreeVideo 时,可以带参考图生成、编辑已生成的图片,也可以复制提示词。", + "Mac 首中尾帧生成:在 Mac 上同时使用首帧、中间帧和尾帧,可以正常生成。", + "多显卡同时生成:在 Windows 上使用两张显卡时,第二张显卡开始的生成不再因等待第一张而报错停下。", + "失败提示更清楚:各类失败都会说明下一步怎么做。提示词增强的结果不完整时,会写明是哪里不对。", + "显卡驱动提示更准确:缺少可用驱动时,启动器会显示检测到的显卡型号,并区分“未安装驱动”和“驱动未正常工作”。", + "LoRA 和参考图会保留:创作面板设置的 LoRA 和参考图在重启 FreeVideo 后仍在;场景卡和道具卡也会记住生成图片时用的 LoRA。", + "运行更稳定:从任何文件夹运行 FreeVideo 命令,都会使用已安装的程序。处理提示词时显存不足,会自动重试一次,不再直接失败。", + "图像模型更省心:修复时会先请您确认,原有的共用文件改名保留。FreeVideo 正在安装、更新或清理时开始的下载,会在结束后自动继续。", + "更新后可直接使用已保存的提示词:更新 FreeVideo 后,已保存的提示词不需要重新处理。", + "长视频重新生成更可靠:在网络回复丢失或延迟后再次点击“从这段重新生成”,会继续显示已经开始的那一段,不会多生成一段。", + "更新后第一次生成更稳定:清理旧版本时不再改动正在使用的模型文件,更新后的第一次生成不会因此中断。" ] }, "history": [ + { + "product_version": "0.6.10", + "en": { + "summary": "Fixes generating after opening Presets, makes Preview first follow the step count, and makes update failure reports more complete.", + "changes": [ + "Generate works after opening Presets: when a setting needs changing, the reason appears next to it and you can fill it in there.", + "Preview first follows the step count: when a workflow's first-pass steps are not 8, Preview first is unavailable with the reason shown, and the key generates the video.", + "More complete update failure reports: \"Report a problem\" on an update failure now adds the last lines of the update log, with file paths, IP addresses and access tokens removed." + ] + }, + "zh": { + "summary": "修复了打开“预设”后无法生成的问题,“先出预览”会跟随步数说明是否可用,更新失败的报告也更完整。", + "changes": [ + "打开“预设”后可正常生成:有设置需要修改时,会在对应位置说明原因,并可直接填写。", + "“先出预览”跟随步数:工作流的一采步数不是 8 时,“先出预览”不可选并写明原因,按键直接生成视频。", + "更新失败的报告更完整:在更新失败提示中点“提交问题”,报告会附上最近几行更新记录,其中的文件路径、IP 地址和访问令牌已移除。" + ] + } + }, { "product_version": "0.6.9", "en": { @@ -407,43 +444,6 @@ "长视频与报告:接缝记录缺失时,该段重新生成一次;合并时仍缺少记录的接缝按直接拼接保存,不再因此无法保存。长视频提交、聊天发送和高分辨率图片生成失败时,诊断报告记下判断原因所需的信息。" ] } - }, - { - "product_version": "0.5.3", - "en": { - "summary": "Short films are finished for you: the built-in director picks and joins the takes, the film arrives in Autopilot as a card, and an editing project with one part per shot is ready. H3 Image takes up to 16 reference pictures, and consecutive images start sooner. Imported clips can be removed from the editor, and waits, failures, setup and narrow windows read more clearly.", - "changes": [ - "Short films: a screenplay can carry its outline and the blocking of each scene, and the blocking goes into every shot of that scene. With the built-in director, takes are chosen and joined automatically once they are shot, and the work continues after a pause, a resume or a restart. The finished film appears in the Autopilot conversation as a card that plays, opens or goes straight to editing, and it also opens as an editing project with one part per shot.", - "Reference pictures: H3 Image accepts up to 16 reference pictures and Qwen-Image 2.1 accepts four. A note appears when too many pictures are added at once, pictures that cannot fit are refused before the run starts, and Generate points to the pictures to remove when the selected model's limit is exceeded.", - "Image speed: consecutive images keep the models loaded when the graphics card and memory allow, and the same prompt is not encoded again, so the second image onward starts sooner. Results are saved as high-quality JPEG, and temporary uploads are removed after each run.", - "Editor: the Imported tab has a remove button on every clip, including ones that could not be opened. Only FreeVideo's copy is deleted, never the original file, and a clip that an edit uses, even in an earlier version, asks for a second confirmation. Work thumbnails in the media library display correctly, and the Edit button on finished-video cards is visible again.", - "Waits: prompt rewriting counts from the press, the size range shows Estimating while it is worked out, and starting a generation or opening the page from the launcher shows elapsed seconds after 3 s. Automatic subtitles show Unpacking, Autopilot shows Sending and the seconds spent waiting for a reply, and preparing reference media shows which file is in progress.", - "Failures and settings: a missing or damaged model file is explained on the failure card, and cards that suggest a repair have an Open settings button that goes to Detect & review. Offline installations are told to import the offline package again. A damaged reserved memory setting no longer blocks the settings panel or generation, and a refused save is explained under Save. The launcher report form names the real failure.", - "Install and repair: Check and repair list and download again any model file that is missing or damaged, and importing an offline package again completes files left short by an interrupted copy. An installation with a missing model folder no longer stops at the GPU check, and an engine source folder that cannot be read is built again instead of failing every retry. The setup plan shows small sizes in MB or KB, and unavailable buttons share one gray look.", - "Windows and downloads: when Windows application control blocks a component file, the GPU check and generation continue, and the block is recognised in any system language. Cards of 16 GB and more keep copying the next layer while the current one computes when commit headroom is limited. The runtime download keeps retrying the official source when a mirror refuses access, with one more public source added.", - "Narrow windows: the Autopilot conversation scrolls on its own with the header and input in view, and an unsent message shows its reason on its own line. The studio shows the queued count and each run's size and length in full, download size and speed stay together, export choices and the reserved memory title stay on one line, and setup lines wrap between phrases. The Connect an agent card keeps its arrow with its words, and a failed lookup shows only Retry and Report a problem.", - "Nodes view: switching to it no longer leaves a node under the view bar, and the voice reference, dialogue tail and empty prompt switches show Chinese names in the Chinese interface. The media panel says once, not three times, when some saved items cannot be read.", - "Generation: a queue read that receives a web page instead of data is retried like a lost connection, so repeating generation keeps going. A second-pass memory failure that a smaller retry cannot help is reported sooner.", - "Tutorial: new chapters on beat snapping, run status, generating with reference pictures, the outline and staging of a short film, and the editing project a finished film leaves." - ] - }, - "zh": { - "summary": "短剧可以一路做完:内置导演自动选片并接成影片,成片以卡片出现在 AI 全自动对话中,同时建好按镜头分段的剪辑工程。H3 Image 支持最多 16 张参考图,连续出图起步更快。剪辑器可以删除已导入素材,等待、失败、安装和窄窗口的显示更清楚。", - "changes": [ - "短剧:剧本可以写大纲和每场站位,站位自动写进该场每个镜头。选用内置导演时,拍完后自动选片并接成影片,暂停、继续和重启后都会接着做。成片以卡片出现在 AI 全自动对话中,可以播放、打开或直接进入剪辑,同时建好按镜头分段的剪辑工程。", - "参考图:H3 Image 最多可用 16 张参考图,Qwen-Image 2.1 可用 4 张。一次加入过多时显示提示,放不下的参考图在开始前拒绝;超出所选模型上限时,点“生成”会定位到需要移除的图。", - "出图速度:显存和内存允许时,连续生成图片保持模型常驻,同一提示词不再重复编码,第二张起开始得更快。结果保存为高质量 JPEG,每次生成后清理临时上传。", - "剪辑器:“已导入”页的每个素材(包括打不开的)都有删除按钮,只删除软件复制的副本,不删原文件;被剪辑使用的素材(包括只在早先版本中使用的)需再确认一次。素材库中的作品缩略图正常显示,已完成视频卡片上的“剪辑”按钮重新显示。", - "等待:提示词改写从点下就计秒,可生成范围计算时显示“正在估算…”,开始生成和从启动器打开页面超过 3 秒时显示已用秒数。自动字幕解压时显示“正在解压”,AI 全自动显示“正在发送…”和等待回复的秒数,准备参考素材时显示正在处理第几个文件。", - "失败和设置:缺失或损坏的模型文件在失败卡片上说明原因;建议修复的卡片新增“打开设置”,直接定位到“检测并预览”。离线安装改为提示重新导入离线包。预留显存设置文件损坏时,设置面板和生成照常进行;保存被拒时在“保存”下说明原因。启动器的报告表单写出真实的失败原因。", - "安装和修复:检测和修复会列出并重新下载缺失或损坏的模型文件,重新导入离线包会补全复制中断留下的不完整文件。缺少模型文件夹时,安装不再停在 GPU 检查一步;引擎源码目录无法读取时改为重新构建,不再每次重试都失败。安装计划中较小的文件以 MB 或 KB 显示,不可用的按钮统一为灰色。", - "Windows 和下载:Windows 应用控制拦截某个组件文件时,GPU 检查和生成照常继续,在任何系统语言下都能识别该拦截。提交余量受限时,16 GB 及以上显卡在计算当前层的同时仍会拷贝下一层。运行环境下载在镜像拒绝访问时继续重试官方线路,并新增一个公开备用线路。", - "窄窗口:AI 全自动的对话单独滚动,顶栏和输入框始终可见,没发出的消息原因单独显示一行。创作面板完整显示排队数量以及每条的尺寸和时长,下载进度的大小和速度不再拆开,导出选项和预留显存标题保持一行,安装页文字按词组换行。连接 Agent 卡片的箭头不再和文字分开,获取地址失败时只显示重试和提交问题。", - "节点视图:切换过来时节点不再被顶部的视图切换栏遮住,“声音参考”“隐藏对白尾段”“允许空描述”三个开关显示中文名称。素材区有资料读取失败时只提示一次,不再重复三次。", - "生成:队列读取得到网页而不是数据时按断线重试,重复生成不再被停掉。第二遍显存不足且缩小重试也无济于事时,更早报告失败。", - "教程:新增对齐音乐节拍、运行状态、用参考图生成图片、短剧的大纲和站位、短剧成片的剪辑工程五章。" - ] - } } ] } diff --git a/freevideo_engine/subprocess_output.py b/freevideo_engine/subprocess_output.py index 263f8f1c..f45c5a70 100644 --- a/freevideo_engine/subprocess_output.py +++ b/freevideo_engine/subprocess_output.py @@ -20,6 +20,12 @@ def python_command(command): # --freevideo-module entry configures the streams before dispatching. if getattr(sys, 'frozen', False) and str(command[0]) == sys.executable: return command + index = 1 + while index < len(command) and command[index] in ('-B', '-u', '-E', '-s', '-X'): + index += 2 if command[index] == '-X' else 1 + if command[index:index + 1] == ['-c'] and index + 1 < len(command): # (-I already leaves the folder out) + from .installed_entry import INSTALLED_ONLY + command[index + 1] = INSTALLED_ONLY + command[index + 1] # -I/-E and Windows portable ._pth ignore PYTHON* environment settings. # The command-line mode still makes redirected stdout/stderr UTF-8. return [command[0], '-X', 'utf8', *command[1:]] diff --git a/freevideo_engine/support_report.py b/freevideo_engine/support_report.py index 6f345ffd..f9c1019f 100644 --- a/freevideo_engine/support_report.py +++ b/freevideo_engine/support_report.py @@ -270,7 +270,7 @@ def budget(key, fallback): REQUEST_FIELDS = ('seed', 'encoder_mode', 'profile', 'resource_planning', 'compatibility', 'reclaimable_resident_models', 'idle_resources', 'tuning', 'input_cache', 'resource_attempts', 'resource_prediction', 'resource_prediction_error', 'error', 'error_message', 'error_type', - 'resource_error', 'exception', 'encoding_failure', 'phase', 'continuation', 'preflight_memory', + 'resource_error', 'exception', 'encoding_failure', 'encoding_retry', 'phase', 'continuation', 'preflight_memory', 'gpu_card', 'output_10bit') diff --git a/freevideo_engine/tuning.py b/freevideo_engine/tuning.py index 0d7cccc8..fa8f9d97 100644 --- a/freevideo_engine/tuning.py +++ b/freevideo_engine/tuning.py @@ -117,9 +117,17 @@ def identity(machine, hardware): TEXT_SCHEMA = 1 -TEXT_FILES = ('encode_worker.py', 'encoder_lowmem.py', 'encoder_precision.py', 'encoder_checkpoint.py', - 'encoder_pinning.py', 'encoder_workspace.py', 'encoder_memory.py', 'adaptive.py', - 'conditioning.py', 'media_request.py') +# Raised when a change can alter the conditioning a prompt and its references encode to: tokens, vision inputs, +# precision, attention arithmetic, what is kept. Raising it re-encodes every saved prompt once; a change to memory, +# loading or reporting keeps it, so an update does not throw the saved prompts away. +# tests/test_text_encoding_version.py holds the fingerprints of ENCODING_FILES and a tiny encoder's output under +# this number: it fails on any change to them until the ledger records whether the number was raised and why. +# Modules these files call into (original_audio and guide_audio from media_request and media_encoding, ComfyUI +# itself) are not fingerprinted: a change there that alters the conditioning raises the number by hand. +ENCODING_VERSION = 1 +ENCODING_FILES = ('encode_worker.py', 'encoder_lowmem.py', 'encoder_precision.py', 'encoder_checkpoint.py', + 'encoder_workspace.py', 'encoder_memory.py', 'conditioning.py', 'media_request.py', + 'media_encoding.py') TEXT_PACKAGES = ('torch', 'transformers', 'tokenizers', 'comfy-kitchen', 'safetensors', 'numpy') @@ -143,10 +151,11 @@ def encoder_content(path, catalog): def text_identity(machine, hardware): - """What the text conditioning of a prompt depends on: encoder content, its code and arithmetic, nothing else. + """What the text conditioning of a prompt depends on: encoder content, its encoding version and arithmetic. - No git, no timestamps, no video models, no GPU serial number: an unrelated update or a copied folder without - .git keeps the cache; a different encoder file, library, source or GPU architecture does not.""" + No git, no timestamps, no video models, no GPU serial number, no source fingerprints: an update that leaves + ENCODING_VERSION alone or a copied folder without .git keeps the cache; a different encoder file, library, + encoding version or GPU architecture does not.""" package = Path(__file__).parent catalog = json.loads((package / 'model_files.json').read_text(encoding='utf-8')) catalog = catalog['files'] if isinstance(catalog, dict) else catalog @@ -161,7 +170,7 @@ def text_identity(machine, hardware): 'encoder': encoder_content(encoder, catalog), 'encoder_packages': {k: v for k, v in versions.items() if k in TEXT_PACKAGES}, 'comfy_commit': specs['encoder']['comfy_commit'], 'comfy_text_encoders': assets, - 'source_sha256': {name: digest(package / name) for name in TEXT_FILES}} + 'encoding_version': ENCODING_VERSION} def report_identity_errors(inventory, expected): diff --git a/scripts/test_freevideo_entry.mjs b/scripts/test_freevideo_entry.mjs index 61f889bf..512ca4d9 100644 --- a/scripts/test_freevideo_entry.mjs +++ b/scripts/test_freevideo_entry.mjs @@ -134,6 +134,7 @@ test('main browser entry registers both views and preserves node hooks', async t source = source.replace("from './fv_player.js'", `from '${new URL('../web/fv_player.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 './tip_words.js'", `from '${new URL('../web/tip_words.js', import.meta.url).href}'`); + source = source.replace("from './i18n.js'", `from '${new URL('../web/i18n.js', import.meta.url).href}'`); source = source.replace("from './cut_tip.js'", `from '${new URL('../web/cut_tip.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}'`); diff --git a/setup.sh b/setup.sh index 2b36a1f0..5c2a2be3 100755 --- a/setup.sh +++ b/setup.sh @@ -5,4 +5,4 @@ export PYTHONPATH="$FREEVIDEO_SOURCE_DIR${PYTHONPATH:+:$PYTHONPATH}" source "$FREEVIDEO_SOURCE_DIR/scripts/bootstrap_linux.sh" freevideo_bootstrap_linux setup "$@" (( FREEVIDEO_BOOTSTRAP_DONE == 0 )) || exit 0 -exec "$FREEVIDEO_BOOTSTRAP_PYTHON" -B -X utf8 -m freevideo_engine.bootstrap "${FREEVIDEO_BOOTSTRAP_ARGS[@]}" +exec "$FREEVIDEO_BOOTSTRAP_PYTHON" -B -X utf8 "$FREEVIDEO_SOURCE_DIR/freevideo_engine/installed_entry.py" freevideo_engine.bootstrap "${FREEVIDEO_BOOTSTRAP_ARGS[@]}" diff --git a/test.sh b/test.sh index 4dec4499..697a8d0d 100755 --- a/test.sh +++ b/test.sh @@ -5,4 +5,4 @@ export PYTHONPATH="$FREEVIDEO_SOURCE_DIR${PYTHONPATH:+:$PYTHONPATH}" source "$FREEVIDEO_SOURCE_DIR/scripts/bootstrap_linux.sh" freevideo_bootstrap_linux test "$@" (( FREEVIDEO_BOOTSTRAP_DONE == 0 )) || exit 0 -exec "$FREEVIDEO_BOOTSTRAP_PYTHON" -B -X utf8 -m freevideo_engine.test_launcher "${FREEVIDEO_BOOTSTRAP_ARGS[@]}" +exec "$FREEVIDEO_BOOTSTRAP_PYTHON" -B -X utf8 "$FREEVIDEO_SOURCE_DIR/freevideo_engine/installed_entry.py" freevideo_engine.test_launcher "${FREEVIDEO_BOOTSTRAP_ARGS[@]}" diff --git a/web/a11y.css b/web/a11y.css index ef2e9b91..4d22e1ea 100644 --- a/web/a11y.css +++ b/web/a11y.css @@ -59,3 +59,13 @@ html[data-fv-shell=nodes] canvas[tabindex]:not([tabindex="-1"]):focus-visible{ou .fv-studio .fv-iv-sec-head{height:auto!important;min-height:44px!important} .fv-studio .fv-iv-stbar{height:auto!important;min-height:56px!important} } + +/* Number fields carry no browser-drawn up/down arrows (small, hard to hit, white on the dark theme). The value is typed; + ↑/↓ still step it, and a field meant to be stepped by pointer has its own − and + (the creation panel's duration, the + settings steppers). FreeVideo's own surfaces only, as above. */ +:where(body [class^="fv-"],body [class*=" fv-"],body [class^="sgf"],body [class*=" sgf"],body [data-fv-tip-scope]) input[type=number], +:where(body) input[type=number]:is([class^="fv-"],[class*=" fv-"]){-moz-appearance:textfield;appearance:textfield} +:where(body [class^="fv-"],body [class*=" fv-"],body [class^="sgf"],body [class*=" sgf"],body [data-fv-tip-scope]) input[type=number]::-webkit-inner-spin-button, +:where(body [class^="fv-"],body [class*=" fv-"],body [class^="sgf"],body [class*=" sgf"],body [data-fv-tip-scope]) input[type=number]::-webkit-outer-spin-button, +:where(body) input[type=number]:is([class^="fv-"],[class*=" fv-"])::-webkit-inner-spin-button, +:where(body) input[type=number]:is([class^="fv-"],[class*=" fv-"])::-webkit-outer-spin-button{-webkit-appearance:none;appearance:none;margin:0} diff --git a/web/agent_connect.css b/web/agent_connect.css index d0cc75b2..36b6de70 100644 --- a/web/agent_connect.css +++ b/web/agent_connect.css @@ -6,6 +6,7 @@ .fv-agent-connect-body svg{width:24px;height:24px;fill:none;stroke:currentColor;stroke-linecap:round;stroke-linejoin:round} .fv-agent-connect-body>h2{font-size:20px;line-height:1.3;font-weight:700;color:var(--fv-ink)} .fv-agent-connect-body>.fv-agent-connect-intro{margin-top:-8px;font-size:13px;line-height:1.5;color:#a5b3c6} +.fv-agent-connect-body>.fv-agent-connect-note{margin-top:-8px;font-size:12px;line-height:1.5;color:#8796aa} .fv-agent-connect-body>.fv-muted{margin-top:-8px;font-size:13px;color:var(--fv-muted)} .fv-agent-connect-actions{display:flex;align-items:center;gap:12px;margin-top:8px;flex-wrap:wrap} .fv-studio .fv-agent-connect-actions button{padding:8px 20px;font-size:13px}.fv-agent-connect-actions button svg{width:16px;height:16px} diff --git a/web/agent_connect.js b/web/agent_connect.js index 0d2f4b85..1f40489b 100644 --- a/web/agent_connect.js +++ b/web/agent_connect.js @@ -1,5 +1,9 @@ import {issueButton} from './issue_button.js'; import {tip} from './autopilot_tips.js'; +// 0.6.11 only (remove in 0.6.12): the note on updated steps stays away once this card's Copy was used on this computer. +const NOTE_SEEN = 'freevideo.agentConnectNote.0611'; +function noteSeen() { try { return localStorage.getItem(NOTE_SEEN) === '1'; } catch { return false; } } +function markNoteSeen() { try { localStorage.setItem(NOTE_SEEN, '1'); } catch {} } function el(tag, cls, text) { const e = document.createElement(tag); if (cls) e.className = cls; if (text != null) e.textContent = text; return e; } // The one place a page says whether an assistant is connected. Program names (and the ids some programs report) @@ -207,6 +211,10 @@ export function agentConnectCard(t, api, shown = () => true, changed = () => {}) const mark = el('span', 'fv-agent-connect-icon'); mark.append(icon('plug')); const title = el('h2', null, t('Connect an assistant', '连接助手')); const intro = el('p', 'fv-agent-connect-intro', t('Once connected, describe the video you want. It generates and edits it for you.', '连上后,说想做什么视频,它来生成和剪辑。')); + // Whether an assistant was connected before cannot be told here, so everyone sees it until Copy is used. + const note = el('p', 'fv-agent-connect-note', t('The connection steps have been updated. If you connected an assistant before, copy them and paste them to it again.', + '连接说明已更新。以前连接过的助手,请重新复制并粘贴给它。')); + note.hidden = noteSeen(); const actions = el('div', 'fv-agent-connect-actions'); const button = el('button', 'fv-primary'); button.type = 'button'; button.disabled = true; // The button's picture follows what it does: copy, or retry once the lookup has failed. @@ -223,7 +231,7 @@ export function agentConnectCard(t, api, shown = () => true, changed = () => {}) const back = el('button', 'fv-agent-connect-back fv-quiet'); back.type = 'button'; back.hidden = true; // Why the last connection ended, when the card stands in for it (see connectCardReason). const reason = el('p', 'fv-agent-connect-reason'); reason.hidden = true; - body.append(mark, title, intro, reason, actions, sentence, status, back); + body.append(mark, title, intro, note, reason, actions, sentence, status, back); let feedback = false, text = '', failures = 0, refusal = null, noAnswer = null, wantFocus = false; let timer, feedbackTimer, controller, generation = 0; @@ -254,6 +262,7 @@ export function agentConnectCard(t, api, shown = () => true, changed = () => {}) const range = document.createRange(); range.selectNodeContents(sentence); const selection = getSelection(); selection.removeAllRanges(); selection.addRange(range); } + markNoteSeen(); note.hidden = true; if (!active()) return; feedback = true; render(); clearTimeout(feedbackTimer); diff --git a/web/autopilot.js b/web/autopilot.js index b8f2c5b4..9540b136 100644 --- a/web/autopilot.js +++ b/web/autopilot.js @@ -15,12 +15,10 @@ import { wordmark } from './wordmark.js'; import { keepViewSwitchPlace } from './view_switch_place.js'; import { tip } from './autopilot_tips.js'; import { agentPost } from './agent_session.js'; +import { isChinese, translator } from './i18n.js'; -const languageOverride = typeof location !== 'undefined' - ? new URLSearchParams(location.search).get('freevideo_lang') : null; -const cn = languageOverride === 'zh' || (languageOverride !== 'en' - && String(navigator.language || '').toLowerCase().startsWith('zh')); -const t = (en, zh) => cn ? zh : en; +const cn = isChinese(); +const t = translator(cn); const el = (tag, cls, text) => { const e = document.createElement(tag); if (cls) e.className = cls; if (text != null) e.textContent = text; return e; }; let current = null, kept = null; diff --git a/web/cast_generate.js b/web/cast_generate.js index 5145c17b..c152b558 100644 --- a/web/cast_generate.js +++ b/web/cast_generate.js @@ -478,7 +478,9 @@ export function createCastGenerator({client, kind = 'character', views = null, f setPicture(0, {file, fraction: 1, original: true, own: false}); if (before.file && !before.original) onDiscard(before.file); } - return {start, stop, reset, redo, useOriginal, setOwn, state: () => state, done, + // The LoRAs the pictures now on show were made with. + const used = () => Array.isArray(loras) ? structuredClone(loras) : []; + return {start, stop, reset, redo, useOriginal, setOwn, used, state: () => state, done, setOverride(role, name) { if (name) overrides[role] = name; else delete overrides[role]; }, dispose() { disposed = true; return stop(); }}; } @@ -638,6 +640,10 @@ export function mountCastGenerate({container, api, text, t = text, viewURL, onSt : generator.state().pictures.map(row => ({file: row.file, label: row.view})), isBusy: () => generator.state().running, cancel: () => generator.stop(), + /** The LoRAs the pictures now on show were made with; a card keeps them. */ + getLoras: () => generator.used(), + /** Shows a card's own LoRAs in the picker. */ + setLoras: rows => picker ? picker.load(rows) : Promise.resolve(), destroy() { disposed = true; picker?.dispose(); clearTimeout(infoTimer); otherUsage.dispose(); void generator.dispose(); root.remove(); }, element: root, }; diff --git a/web/cast_library.js b/web/cast_library.js index bc7b9c2d..a590a99b 100644 --- a/web/cast_library.js +++ b/web/cast_library.js @@ -131,6 +131,9 @@ export function createCastLibrary({api, text, viewURL, uploadOne, onChange = () const keyOf = tab => scene ? '' : tab === 'upload' ? (!id && makers.image ? 'image' : '') : makers[tab] ? tab : ''; let moved = false; let generator = null, aiState = {busy: false, done: false}, deleteTimer = null, confirming = false, frontless = scene, beyond = []; + // A scene or prop card keeps the LoRAs its chosen picture was made with: savedLoras are the card's own, pickedLoras + // those of a picture chosen in this dialog; only a chosen picture changes what the card keeps. + let savedLoras = [], pickedLoras = null; const slots = Array(SLOTS).fill(null), slotUI = []; skin(); const dialog = el('dialog', 'fv-cast-dialog'); dialog.dataset.kind = prop ? 'prop' : scene ? 'scene' : 'character'; const top = el('div', 'fv-cast-top'); @@ -263,8 +266,12 @@ export function createCastLibrary({api, text, viewURL, uploadOne, onChange = () } remove.hidden = true; if (image?.complete) remove.hidden = false; mark(index); sync(); } + // The first picture of a scene card is the one its LoRAs describe: once the person puts their own picture there, or + // takes it out, the card keeps no LoRAs (only said when there were some to drop). + const firstChanged = index => { if (scene && index === 0) pickedLoras = pickedLoras || savedLoras.length ? [] : null; }; function chooseFiles(index, files) { if (loading || saving || closed) return; + if (files.length) firstChanged(index); for (const file of Array.from(files).slice(0, SLOTS - index)) { release(index); slots[index] = {file, label: index || scene ? 'other' : 'front', preview: URL.createObjectURL(file)}; @@ -277,7 +284,7 @@ export function createCastLibrary({api, text, viewURL, uploadOne, onChange = () const input = el('input'); input.type = 'file'; input.accept = 'image/*'; input.hidden = true; const label = prop ? text('Image', '图片') : scene ? text(`Image ${index + 1}`, `图片 ${index + 1}`) : index ? text(`View ${index}`, `视角 ${index}`) : text('Front image', '正面图片'); const choose = button('fv-cast-choose', '', () => input.click()); choose.setAttribute('aria-label', label); - const remove = button('fv-cast-remove', '×', () => { release(index); paint(index); }); + const remove = button('fv-cast-remove', '×', () => { firstChanged(index); release(index); paint(index); }); remove.setAttribute('aria-label', text('Remove image', '移除图片')); choose.dataset.fvTipName = label; choose.dataset.fvTipUse = text('Choose a picture, or drop one here', '选择图片,或把图片拖到这里'); remove.dataset.fvTipName = text('Remove image', '移除图片'); remove.dataset.fvTipUse = text('Take this picture out', '拿掉这张图片'); @@ -307,6 +314,8 @@ export function createCastLibrary({api, text, viewURL, uploadOne, onChange = () card.images.slice(0, SLOTS).forEach((picture, index) => { slots[index] = {...picture}; }); // The API allows six pictures on a scene card but the dialog shows three: the rest stay as they are. beyond = card.images.slice(SLOTS).map(picture => ({media: picture.media, label: picture.label})); + savedLoras = scene && Array.isArray(card.loras) ? card.loras : []; pickedLoras = null; + if (savedLoras.length) void generator?.setLoras?.(savedLoras); slotUI.forEach((_, index) => paint(index)); generator?.cancel(); aiState = {busy: false, done: false}; select('upload'); resetDelete(); } finally { @@ -352,7 +361,7 @@ export function createCastLibrary({api, text, viewURL, uploadOne, onChange = () } if (id && scene) images.push(...beyond); if (closed) return; - const body = {name: name.value.trim(), images}; + const body = {name: name.value.trim(), images, ...(scene && pickedLoras ? {loras: pickedLoras} : {})}; await value(await (id ? agentSend(api, 'PATCH', path(id), {revision, ...body}) : agentPost(api, '/freevideo/agent/cast', {kind, ...body}))); maker?.markSaved?.(); @@ -396,7 +405,7 @@ export function createCastLibrary({api, text, viewURL, uploadOne, onChange = () name.value = ''; select('upload'); document.body.append(dialog); dialog.showModal(); name.focus(); 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); }; + const pick = file => { if (closed || !scene) return; slots[0] = {media: file, label: 'other'}; pickedLoras = generator?.getLoras?.() ?? null; paint(0); }; // Scenes and props: the description's candidates. Characters: the four views from each source. if (scene) mountGenerator({container: aiPane, api, text, viewURL, kind, onPick: pick, onState: state => { if (closed) return; @@ -404,6 +413,7 @@ export function createCastLibrary({api, text, viewURL, uploadOne, onChange = () }}).then(instance => { if (closed) { instance?.cancel(); instance?.destroy(); return; } generator = instance; aiTab.hidden = !instance; tabs.hidden = !instance; sync(); + if (savedLoras.length) void instance?.setLoras?.(savedLoras); }); else for (const [source, pane] of [['photo', photoPane], ...(id ? [] : [['image', imagePane]]), ['ai', aiPane]]) { mountPhoto({container: pane, api, text, viewURL, uploadOne, source, onState: state => { diff --git a/web/cast_room.js b/web/cast_room.js index 388e521d..d6520d5d 100644 --- a/web/cast_room.js +++ b/web/cast_room.js @@ -8,6 +8,7 @@ import { uploadMedia } from './media_upload.js'; import { issueButton } from './issue_button.js'; import { createPlayBar } from './fv_player.js'; import { userMessage } from './user_message.js'; +import { copyText } from './clipboard_text.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; }; @@ -200,8 +201,7 @@ export function createCastRoom({api, t, viewURL: outputURL}) { async function copyMention() { if (!card) return; const text = '@' + card.name + ' '; - let ok = false; - try { await navigator.clipboard.writeText(text); ok = true; } catch { /* Shown below. */ } + const ok = await copyText(text); notice.textContent = ok ? t(`Copied @${card.name}. Paste it in a prompt.`, `已复制 @${card.name},粘贴到提示词里使用。`) : t('Could not copy. Type the name after @ in a prompt.', '没能复制。可在提示词中输入 @ 加名字。'); } function resetRemove() { clearTimeout(arm); arm = 0; remove.classList.remove('fv-library-arming'); remove.lastElementChild.textContent = t('Delete', '删除'); } diff --git a/web/clipboard_text.js b/web/clipboard_text.js new file mode 100644 index 00000000..79052281 --- /dev/null +++ b/web/clipboard_text.js @@ -0,0 +1,15 @@ +// Writes text to the clipboard; resolves false when neither the clipboard API nor the old copy command is allowed. +// navigator.clipboard exists only in a secure context: a page opened from another device by its LAN address over http +// has none, so the selection copy below is what works there (#1097). +export async function copyText(text) { + try { await navigator.clipboard.writeText(text); return true; } catch { /* fall through to the selection copy */ } + const before = document.activeElement; + const area = document.createElement('textarea'); area.value = text; area.setAttribute('readonly', ''); + area.style.cssText = 'position:fixed;top:0;left:0;opacity:0'; + document.body.append(area); area.select(); + try { return document.execCommand('copy'); } catch { return false; } finally { + area.remove(); + // The keyboard goes back where it was (the button or menu that asked), not to the page body. + if (before && before !== document.body && before.isConnected) before.focus?.({preventScroll: true}); + } +} diff --git a/web/comfy_templates.js b/web/comfy_templates.js index 3f581f7f..eda552f8 100644 --- a/web/comfy_templates.js +++ b/web/comfy_templates.js @@ -1,9 +1,8 @@ // ComfyUI's own Templates window, shown over the Nodes view: FreeVideo says its search box and its first category in the // interface language (ComfyUI's Chinese file reads the search box as "搜索占位符", and the category name is not translated), // and comfy_templates.css brings the window into the light theme. The window is added to the page body when it opens. -const query = new URLSearchParams(globalThis.location?.search || ''); -const asked = query.get('freevideo_lang'); -export const chinese = asked === 'zh' || (asked !== 'en' && String(globalThis.navigator?.language || '').toLowerCase().startsWith('zh')); +import { isChinese } from './i18n.js'; +export const chinese = isChinese(); // English text of a ComfyUI-made label -> the Chinese FreeVideo shows in its place. export const LABELS = {Popular: '热门'}; diff --git a/web/compatibility.js b/web/compatibility.js index 871b72d8..80cc11a3 100644 --- a/web/compatibility.js +++ b/web/compatibility.js @@ -2,6 +2,7 @@ import { api } from '../../scripts/api.js'; import './fv_select.js'; import './glass/library.js'; import {userMessage} from './user_message.js'; +import { isChinese, translator } from './i18n.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.', '没能保存,请重试。')); @@ -9,11 +10,8 @@ const saveFailure = (error, tt) => { const text = userMessage(error, tt, tt('Cou 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; -const cn = languageOverride === 'zh' || (languageOverride !== 'en' - && String(navigator.language || '').toLowerCase().startsWith('zh')); -const t = (en, zh) => cn ? zh : en; +const cn = isChinese(); +const t = translator(cn); const unavailable = () => t('Device information is unavailable; compatibility settings are off.', '无法获取设备信息,兼容性设置已关闭。'); let current; const element = (tag, text) => { const node = document.createElement(tag); if (text) node.textContent = text; return node; }; diff --git a/web/context_menu.js b/web/context_menu.js index b9782ccf..351b0e87 100644 --- a/web/context_menu.js +++ b/web/context_menu.js @@ -8,12 +8,11 @@ // Nothing here runs at import under Node, so the unit tests load it as it is. import { isolateDialogKeys, listenDialogKey } from './dialog_keys.js'; +import { isChinese, translator } from './i18n.js'; const browser = typeof document !== 'undefined'; -const query = browser ? new URLSearchParams(globalThis.location?.search || '') : new URLSearchParams(); -const forced = query.get('freevideo_lang'); -export const CN = forced === 'zh' || (forced !== 'en' && String(globalThis.navigator?.language || '').toLowerCase().startsWith('zh')); -export const t = (en, zh) => CN ? zh : en; +export const CN = isChinese(); +export const t = translator(CN); // [en, zh] pairs, plain strings and functions returning either all read the same way. export const words = (value, cn = CN) => typeof value === 'function' ? words(value(), cn) : Array.isArray(value) ? String(value[cn ? 1 : 0] ?? value[0] ?? '') : String(value ?? ''); export const MAC = /Mac|iPhone|iPad/.test(globalThis.navigator?.platform || globalThis.navigator?.userAgent || ''); diff --git a/web/editor.js b/web/editor.js index 7cd71f53..d1cfa9e0 100644 --- a/web/editor.js +++ b/web/editor.js @@ -57,6 +57,7 @@ import {jobs} from './task_store.js'; import {openingChoice} from './editor_opening.js'; import {CN} from './topbar_state.js'; import {setDisabled} from './dom_quiet.js'; +import {randomUUID} from './random_id.js'; const editorStyles = Promise.all(['result_actions.css', 'editor.css', 'editor_expand.css', 'editor_tracks.css', 'editor_frame.css', 'editor_adjust.css', 'editor_adjust_picture.css', 'editor_preview_picture.css', 'editor_select.css', 'editor_menu.css', 'editor_text.css', 'editor_notes.css', 'editor_transport.css', 'glass/editor.css', 'editor_touch.css'].map(name => { const style = document.createElement('link'); style.rel = 'stylesheet'; style.href = new URL(name, import.meta.url).href; const ready = 'sheet' in style ? new Promise(resolve => { style.onload = style.onerror = resolve; }) : Promise.resolve(); @@ -1044,7 +1045,7 @@ export function openEditor({api, app, from = null, panel = {}, components: given async function replaceProject(record, key = null) { releaseTakes(); rememberView(); viewReady = false; await store.activateProject(record.id).catch(() => {}); - viewKey = record.id || key || 'draft:' + (globalThis.crypto?.randomUUID?.() || `${Date.now()}-${Math.random()}`); + viewKey = record.id || key || 'draft:' + randomUUID(); let remembered = editorViews.get(viewKey); if (!remembered) try { remembered = JSON.parse(localStorage.getItem(viewPrefix + viewKey)); } catch {} initialSelection = offerInitial = extendEntry = null; diff --git a/web/editor_duration.js b/web/editor_duration.js index fecadbea..a0e64f92 100644 --- a/web/editor_duration.js +++ b/web/editor_duration.js @@ -134,7 +134,7 @@ export function createDurationField({state, t, actions}) { }; input.oninput = () => { typing = true; }; input.onblur = () => commit(); - // The browser's own step buttons. + // A value set by a script or by the browser (an autofill) that never typed. input.onchange = () => commit(); // While these parts are made the field stays in place, greyed like the description. function update(busy = false) { diff --git a/web/editor_library.js b/web/editor_library.js index b28bf10e..e1002cfe 100644 --- a/web/editor_library.js +++ b/web/editor_library.js @@ -146,6 +146,12 @@ export function createEditorLibrary(host, {store, t, actions, state}) { const value = metadata(row, kind), key = `${kind}:${row.id}`; event.dataTransfer.effectAllowed = 'copy'; event.dataTransfer.setData('application/x-freevideo-source', JSON.stringify({key, ...value})); + // The picture follows the pointer, not a see-through copy of the whole button; a sound has no picture and keeps the default. + const thumb = picture.querySelector('img'); + if (thumb && !thumb.hidden && thumb.complete && thumb.naturalWidth) { + const box = thumb.getBoundingClientRect(); + event.dataTransfer.setDragImage(thumb, Math.round(box.width / 2), Math.round(box.height / 2)); + } store.getSources([key]).catch(actions.error); }; // Single click previews the source; double click also inserts it. diff --git a/web/editor_stems.js b/web/editor_stems.js index f306950b..7f7901cc 100644 --- a/web/editor_stems.js +++ b/web/editor_stems.js @@ -4,6 +4,7 @@ import {agentGet, agentPost, retryAgentPost} from './agent_session.js'; import {sourceKey} from './editor_store.js'; import {showSoundBubble, markSoundBubbleSeen, isBubbleRemover} from './sound_bubble.js'; import {tip} from './editor_tips.js'; +import {randomUUID} from './random_id.js'; const ROOT = '/freevideo/agent/v1'; const ACTIVE = ['waiting', 'queued', 'running', 'cancelling']; @@ -122,7 +123,7 @@ export function createStemsIntegration({state, api, queue, store, t, error, noti const tool = running = {cancelled: false, job: null}; markSoundBubbleSeen(); sync(); try { if (!await ready()) return false; - const project = state.record.id, ref = globalThis.crypto?.randomUUID?.() || `${Date.now()}-${Math.random()}`; + const project = state.record.id, ref = randomUUID(); const body = {revision: state.record.revision, clip_id: clipId, lay: false, ref}; paint('start', phaseWords()); const response = await retryAgentPost(api, `${ROOT}/projects/${encodeURIComponent(project)}/stems`, body); @@ -165,7 +166,7 @@ export function createStemsIntegration({state, api, queue, store, t, error, noti async function exportStems(clipId) { try { if (!await ready()) return false; - const body = {revision: state.record.revision, clip_id: clipId, ref: globalThis.crypto?.randomUUID?.() || `${Date.now()}-${Math.random()}`}; + const body = {revision: state.record.revision, clip_id: clipId, ref: randomUUID()}; const response = await retryAgentPost(api, `${ROOT}/projects/${encodeURIComponent(state.record.id)}/stems/export`, body); const answer = await response?.json().catch(() => null); if (!response?.ok) { say(answer, 'stems_failed'); return false; } diff --git a/web/editor_store.js b/web/editor_store.js index fcfb7a45..f739a56c 100644 --- a/web/editor_store.js +++ b/web/editor_store.js @@ -1,4 +1,5 @@ import {copyName} from './editor_model.js'; +import {randomUUID} from './random_id.js'; import {generationSize} from './editor_generation.js'; // HTTP and scheduling live here; records and editing stay in the data modules. const clockDefault = {now: () => Date.now(), setTimeout: (fn, ms) => setTimeout(fn, ms), clearTimeout: id => clearTimeout(id)}; @@ -26,7 +27,7 @@ export {chainRoute, createPoller, interpolate, capabilityPoints}; // Writes are serialized; a response supplies metadata to the next snapshot only. const savedContent = record => JSON.stringify({...record, id: null, revision: 0}); const OUTBOX = 'fv-editor-outbox'; -const operationId = () => globalThis.crypto?.randomUUID?.().replaceAll('-', '') || Array.from({length: 32}, () => Math.floor(Math.random() * 16).toString(16)).join(''); +const operationId = () => randomUUID().replaceAll('-', ''); const lockName = session => OUTBOX + ':' + session; function holdSession(session = operationId()) { let release = () => {}; const owner = {session, held: !globalThis.navigator?.locks}; diff --git a/web/editor_voice_store.js b/web/editor_voice_store.js index 34659206..ebd24635 100644 --- a/web/editor_voice_store.js +++ b/web/editor_voice_store.js @@ -2,6 +2,7 @@ // read until it ends. The job leaves the project alone (lay: false); the page puts the new sound in itself, so its own // saves never clash with the job and the change can be undone. import {agentGet, agentPost, retryAgentPost} from './agent_session.js'; +import {randomUUID} from './random_id.js'; const ROOT = '/freevideo/agent/v1'; const ACTIVE = ['waiting', 'queued', 'running', 'cancelling']; @@ -27,7 +28,7 @@ export async function voiceAvailable(api) { return (await voiceFeatures(api)).re export function createVoiceStore({api, state, queue}) { let running = null; - const uuid = () => globalThis.crypto?.randomUUID?.() || `${Date.now()}-${Math.random()}`; + const uuid = () => randomUUID(); const path = name => `${ROOT}/projects/${encodeURIComponent(state.record.id)}/voice/${name}`; const selection = found => ({clip_id: found.clipId, start: found.start, end: found.end}); async function saved() { diff --git a/web/error_panel.js b/web/error_panel.js index d9da4c7a..a4394c27 100644 --- a/web/error_panel.js +++ b/web/error_panel.js @@ -365,6 +365,12 @@ const RETRY_REPORT = ['Try again. If it happens again, choose "Report a problem" const PREVIEW_STEPS = [/A preview uses two-pass generation, which runs only with 8 first-pass steps/, 'preview-steps', ['Preview first needs 8 first-pass steps', '先出预览需一采 8 步'], ['', ''], ['Set the first-pass steps to 8, or turn off Preview first, then generate again.', '请将一采步数改为 8,或关闭“先出预览”,再重新生成。']]; +// A redo whose name was already used with other settings (chain_errors.py redo_request_changed): what happened and where +// to look first, instead of a plain "try again" (Lane, review/chain-redo-lost-reply-duplicate copy_lane). +const REDO_CHANGED = [/This redo was already submitted with the earlier settings\./, + 'redo-request-changed', ['The redo did not start', '没有重新开始生成'], + ['This redo was already submitted with the earlier settings.', '这次重新生成已按之前的设置提交过。'], + ['Check the queue first. If you still want the current settings, choose "Redo from here" again.', '请先查看队列;仍需要按现在的设置生成时,再点一次“从这段重新生成”。']]; const REFERENCE_FAILURES = [ [/Source video (?:frame count )?changed during depth (?:conversion|inspection)|reference video changed while it was being turned into lines/i, 'reference-changed', ['The reference video changed', '参考视频在转换时被改动'], @@ -449,7 +455,7 @@ export function failureAdvice(value, t, known = knownError(value)) { } // 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, PREVIEW_STEPS]) { + for (const [pattern, kind, title, summary, action] of [...REFERENCE_FAILURES, PREVIEW_STEPS, REDO_CHANGED]) { if (pattern.test(text)) return row(kind, title, summary, action); } if (known === 'media-missing') diff --git a/web/feature_tour.js b/web/feature_tour.js index 60d6ac93..2cac9be3 100644 --- a/web/feature_tour.js +++ b/web/feature_tour.js @@ -3,6 +3,7 @@ import {readGuideRecord, saveGuideRecord, guideRecord, CARDS_OFF} from './first_ import './glass/library.js'; import {openAnchor, anchorOpen, closeAnchor} from './feature_tour_layer.js'; import {reducedMotion} from './context_menu.js'; +import { isChinese } from './i18n.js'; export const TOUR_TEXT = { en: {examples: 'Feature examples', use: 'Use example', next: 'Next', goto: 'Take me there', noView: 'Could not open the Edit view. Choose "Edit" at the top.', noTarget: 'This item is not available here. Follow the steps above.', noHidden: 'The timeline has no clip with sound yet. Import or generate one first.', book: 'Read the tutorial', done: 'Done', close: 'Close', gotIt: 'Got it', @@ -291,7 +292,7 @@ function openAnchorCard({api, cn, loaded, owner, automatic = true, badge = ''}) active = {owner, close: () => layer?.close('fade', 'dismiss') || Promise.resolve()}; return true; } -const pageZh = () => { const choice = new URLSearchParams(location.search).get('freevideo_lang'); return choice === 'zh' || (choice !== 'en' && String(navigator.language || '').toLowerCase().startsWith('zh')); }; +const pageZh = () => isChinese(); /** One card on request (the tutorial's examples, a chapter's card): beside its control when that control is on screen, * otherwise centred; the keyboard moves into it. */ export async function showFeatureCard(id, {owner = globalThis.FreeVideoShell?.viewDialog?.() || contextFor()?.dialog || null, cn = contextFor()?.cn ?? pageZh(), api = contextFor()?.api} = {}) { diff --git a/web/feedback.js b/web/feedback.js index 9a918512..30eb0dba 100644 --- a/web/feedback.js +++ b/web/feedback.js @@ -8,6 +8,7 @@ import { closeDialog } from './motion.js'; import { isolateDialogKeys, routeDialogKey } from './dialog_keys.js'; import { productVersion } from './updates.js'; import { skin } from './glass/library.js'; +import { copyText as copySelected } from './clipboard_text.js'; const ISSUE_FORM = 'https://github.com/FlashML-org/FreeVideo/issues/new'; const DRAFT_KEY = 'freevideo.feedback-draft'; @@ -109,7 +110,8 @@ function openPage(address) { } async function copyText(text, clipboard = navigator.clipboard) { - try { await clipboard.writeText(text); return true; } catch { return false; } + // No clipboard API at all (a LAN address over http): the selection copy; one that refuses stays refused. + try { await clipboard.writeText(text); return true; } catch { return clipboard ? false : copySelected(text); } } let current = null; diff --git a/web/freevideo.js b/web/freevideo.js index 4d2d98fb..573256fd 100644 --- a/web/freevideo.js +++ b/web/freevideo.js @@ -47,12 +47,10 @@ import { issueButton } from './issue_button.js'; import { createPlayBar } from './fv_player.js'; import { userMessage } from './user_message.js'; import { AUDIO_USE, usesOriginal, checkOriginal, checkedLength, failureText, multipleText, createUseSwitch, originalBlocked, stuckText, liftBlock } from './audio_original.js'; +import { isChinese, translator } from './i18n.js'; -const languageOverride = typeof location !== 'undefined' - ? new URLSearchParams(location.search).get('freevideo_lang') : null; -const cn = languageOverride === 'zh' || (languageOverride !== 'en' - && String(navigator.language || '').toLowerCase().startsWith('zh')); -const text = (en, zh) => cn ? zh : en; +const cn = isChinese(); +const text = translator(cn); const style = document.createElement("style"); style.textContent = ` .fv-panel{box-sizing:border-box;width:100%;height:100%;padding:16px;background:var(--fv-card);color:var(--fv-ink);border:1px solid var(--fv-border);border-radius:var(--fv-r-md,12px);font:13px/1.6 var(--fv-font);overflow:auto;color-scheme:dark} diff --git a/web/glass/polish.css b/web/glass/polish.css index c7281d73..d8bccc0d 100644 --- a/web/glass/polish.css +++ b/web/glass/polish.css @@ -78,6 +78,8 @@ html:not([data-fv-polish="off"]) :is(.fv-studio,.fv-library) :is(button,input,te /* Scrollbars: thin, quiet, no track. */ html:not([data-fv-polish="off"]) :is(.fv-studio,.fv-library,.fv-select-menu,.fv-tb-pop){scrollbar-width:thin;scrollbar-color:var(--fv-scroll) transparent} html:not([data-fv-polish="off"]) :is(.fv-studio,.fv-library,.fv-select-menu,.fv-tb-pop) *{scrollbar-width:thin;scrollbar-color:var(--fv-scroll) transparent} +/* The same thin bar for every other FreeVideo popup and dialog (outside the views above). Zero specificity: a part that sets its own width or hides its bar keeps it. */ +:where(html:not([data-fv-polish="off"]) :is([class^="fv-"],[class*=" fv-"],:is([class^="fv-"],[class*=" fv-"]) *)){scrollbar-width:thin;scrollbar-color:var(--fv-scroll) transparent} /* Selection and placeholder. */ html:not([data-fv-polish="off"]) :is(.fv-studio,.fv-library) ::selection{background:var(--fv-selection);color:inherit} html:not([data-fv-polish="off"]) :is(.fv-studio,.fv-library) :is(textarea,input)::placeholder{color:var(--fv-fg3);opacity:1;font-weight:var(--fv-fw-1)} diff --git a/web/glass/studio.css b/web/glass/studio.css index 6cc91766..8e876f2c 100644 --- a/web/glass/studio.css +++ b/web/glass/studio.css @@ -187,7 +187,12 @@ .fvs-console-status .fv-enhance-status{display:flex!important;align-items:center;gap:var(--fv-sp-8);padding:0;border:0;background:none;font-size:var(--fv-fs-1);line-height:20px} .fvs-console-status .fv-enhance-status:not([data-state=progress]):not([data-state=error]):not([data-state=note]){display:none!important} /* A failure the user can act on reads as an ordinary note (not a warning colour); nothing else is said here. */ -.fvs-console-status .fv-enhance-status[data-state=error]{color:var(--fv-fg2)} +.fvs-console-status .fv-enhance-status[data-state=error]{color:var(--fv-danger);background:color-mix(in srgb,var(--fv-danger) 7%,transparent);border-radius:var(--fv-r-sm,8px);padding:0 var(--fv-sp-8)} +/* What enhancement says (a failure with its reason, the report key) is said whole: on a narrow line it wraps, the line grows + and so does the band above the console (studio.js sets --fvs-band), instead of cutting the sentence and the key off. */ +.fv-studio.fv-create .fvs-console-status[data-hx-enhsay]{height:auto;min-height:20px} +.fv-studio.fv-create .fvs-console-status[data-hx-enhsay]>.fv-enhance-status{flex-wrap:wrap;white-space:normal;overflow:visible;text-overflow:clip;row-gap:var(--fv-sp-4)} +.fv-studio.fv-create .fvs-console-status[data-hx-enhsay] .fv-enhance-status-text{white-space:normal;flex:0 1 auto;text-wrap:pretty} .fvs-console-status .fv-enhance-meter{width:72px;flex:none;margin:0} .fvs-console-status .fv-enhance-status .fv-issue-button{margin:0;min-height:20px;height:20px;padding:0 var(--fv-sp-8)} @@ -936,3 +941,9 @@ html body .fv-studio.fv-create .fvs-console :is(.fvs-console-prompt,.fv-section, .fv-studio.fv-create .fv-body[data-grid=true] .fvs-rail .fv-recent-card{display:block;min-height:auto;padding:0} .fv-studio.fv-create .fv-body[data-grid=true] .fvs-rail .fv-recent-card .fv-library-picture{height:auto;aspect-ratio:16/9} .fv-studio.fv-create .fv-body[data-grid=true] .fvs-rail .fv-recent-card>:is(span:not(.fv-recent-check),small){display:none} +/* Prompt from a picture or video (the key left of History): Stop while it runs, grey while the queue runs. The report key keeps its border and gap. */ +.fv-studio.fv-create :is(.fv-prompt-tools,.fvs-chips)>.fv-prompt-reverse[aria-disabled=true]{opacity:.4;cursor:not-allowed} +.fv-studio.fv-create :is(.fv-prompt-tools,.fvs-chips)>.fv-prompt-reverse[data-state=running]{color:var(--fv-accent-ink,var(--fv-fg))} +/* In the options row (phone width): the icon key, the same round key as LoRA and Settings at the row's end. */ +.fv-studio.fv-create .fvs-chips>.fv-prompt-reverse{flex:none;width:var(--fv-touch);height:var(--fv-touch);min-height:var(--fv-touch);padding:0} +.fv-studio.fv-create .fvs-console-status .fv-enhance-status .fv-issue-button{border:1px solid var(--fv-line);gap:6px;padding:4px 10px} diff --git a/web/global_search.js b/web/global_search.js index 3296b607..c304c003 100644 --- a/web/global_search.js +++ b/web/global_search.js @@ -7,6 +7,7 @@ // cast /freevideo/agent/cast for characters, scenes and props, when the assistant interface is on. // Moving to an engine search (GET /freevideo/library?q=) replaces the fetchers and nothing else. import { t, words, CN } from './context_menu.js'; +import { copyText } from './clipboard_text.js'; const browser = typeof document !== 'undefined'; export const SEARCH_MIN = 2; @@ -289,8 +290,8 @@ export async function fillPrompt(text, {view = null, fallbackView = 'studio'} = toast(t('The prompt is in. Press Ctrl+Enter to generate.', '描述已填入,按 Ctrl+回车 生成。').replace('Ctrl', /Mac/.test(navigator.platform) ? '⌘' : 'Ctrl'), {tone: 'ok'}); return true; } - try { await navigator.clipboard.writeText(text); toast(t('Prompt copied. Paste it into the prompt box.', '描述已复制,请粘贴到描述框。'), {icon: 'copy'}); } - catch { toast(t('Could not put the prompt in. Try again.', '没有填入描述,请重试。'), {tone: 'warn'}); } + if (await copyText(text)) toast(t('Prompt copied. Paste it into the prompt box.', '已复制提示词,请粘贴到输入框。'), {icon: 'copy'}); + else toast(t('Could not fill in the prompt. Try again.', '未能填入提示词,请重试。'), {tone: 'warn'}); return false; } diff --git a/web/has_mirror.js b/web/has_mirror.js index 5768a504..b71f7e28 100644 --- a/web/has_mirror.js +++ b/web/has_mirror.js @@ -18,6 +18,7 @@ const RULES = [ ['textdis', '.fv-chain-part', host => shown(host, '.fv-chain-part-text:disabled')], ['queued', '.fv-chain-position', host => shown(host, '.fv-chain-queued')], ['note', '.fvs-console-status', host => kid(host, c => c.matches('.fv-add-video-note,.fv-length-why') && !c.hidden)], + ['enhsay', '.fvs-console-status', host => kid(host, c => c.matches('.fv-enhance-status') && !!c.textContent.trim())], ['enh', '.fv-enhance-bar', host => kid(host, c => !c.hidden && !c.matches('.fv-enhance-toggle'))], ['cmp', '.fv-preview-column', host => shown(host, '.fv-stage[data-comparing=true]')], ['nextprog', '.fv-preview-column', host => shown(host, '.fv-stage[data-next=true],.fv-stage .fv-generation-progress:not([hidden])')], diff --git a/web/health.js b/web/health.js index 52d1b54f..534c0e82 100644 --- a/web/health.js +++ b/web/health.js @@ -7,6 +7,8 @@ let extensionUI = null, errorUI = null; const base = new URL('./', import.meta.url); const query = new URLSearchParams(location.search); +// The language rule of web/i18n.js, written out here because this file imports nothing at load: it must still run and +// report when i18n.js itself fails to load. tests/i18n_runtime.mjs checks that the two agree. const language = query.get('freevideo_lang'); const cn = language === 'zh' || (language !== 'en' && String(navigator.language || '').toLowerCase().startsWith('zh')); const t = (en, zh) => cn ? zh : en; @@ -15,7 +17,7 @@ const launchVisit = query.get('freevideo') === 'launch'; // Every script this folder ships; a test keeps the list in step with web/*.js. export const MODULES = ['fv_player.js', 'audio_original.js', 'chat_data.js', 'phone_model.js', 'phone.js', 'lan_access.js', 'monitor_panel.js', 'qrcodegen.js', 'agent_activity.js', 'agent_tasks.js', 'agent_confirm_settings.js', 'private_pin.js', 'private_settings.js', 'agent_connect.js', 'agent_session.js', 'autopilot.js', 'autopilot_chat.js', 'chat_attachments.js', 'autopilot_conversations.js', 'browser_extension.js', 'caret_rect.js', 'chain_support.js', 'chain_rules.js', 'timed_prompt.js', 'capability_view.js', 'cast_generate.js', 'cast_mention.js', 'cast_overlay.js', 'cast_source.js', 'compatibility.js', 'entry_showcase.js', 'engine_exit.js', 'error_panel.js', 'first_run_guide.js', 'fonts.js', 'freevideo.js', 'generation_progress.js', 'editor.js', 'editor_actions.js', 'editor_lifecycle.js', 'editor_adjust.js', 'editor_adjust_picture.js', 'editor_picture_fields.js', 'editor_picture_session.js', 'editor_preview_picture.js', 'editor_entry.js', 'editor_expand.js', 'editor_export_dialog.js', 'editor_first_frame.js', 'editor_media_references.js', 'editor_references.js', 'middle_frames.js', 'editor_genbar.js', 'editor_duration.js', 'editor_geometry.js', 'editor_library.js', 'editor_menu.js', 'editor_stems.js', 'editor_record.js', 'editor_record_model.js', 'editor_voice.js', 'editor_voice_install.js', 'editor_voice_model.js', 'editor_voice_store.js', 'editor_model.js', 'editor_frame.js', 'editor_player.js', 'editor_room.js', 'editor_select.js', 'editor_state.js', 'editor_store.js', 'editor_tracks.js', 'editor_generation.js', 'editor_transport.js', 'editor_transport_model.js', 'editor_audio.js', 'editor_audio_model.js', 'editor_audio_notes.js', 'editor_audio_replace.js', 'editor_audio_rules.js', 'editor_music.js', 'editor_music_model.js', 'editor_speed.js', 'editor_speed_model.js', 'editor_failure.js', 'editor_header_fit.js', 'studio_header_fit.js', - 'editor_loader.js', 'editor_text_coverage.js', 'editor_text.js', 'editor_toolbar_more.js', 'editor_text_model.js', 'editor_text_layout.js', 'editor_notes.js', 'editor_icons.js', 'dialog_keys.js', 'dom_quiet.js', 'done_notify.js', 'file_failure.js', 'has_mirror.js', 'failure_issue.js', 'feedback.js', 'frame_sizes.js', 'health.js', 'image_commands.js', 'image_editor.js', 'image_editor_engine.js', 'image_generation.js', 'image_lora.js', 'image_view.js', 'launch_visit.js', 'launcher.js', 'length_plan.js', 'lora_triggers.js', 'lora_check.js', 'library.js', 'motion.js', 'native_errors.js', 'translate_guard.js', 'output_download.js', 'port_notice.js', 'preview_scene.js', + 'editor_loader.js', 'editor_text_coverage.js', 'editor_text.js', 'editor_toolbar_more.js', 'editor_text_model.js', 'editor_text_layout.js', 'editor_notes.js', 'editor_icons.js', 'dialog_keys.js', 'dom_quiet.js', 'done_notify.js', 'file_failure.js', 'has_mirror.js', 'failure_issue.js', 'feedback.js', 'frame_sizes.js', 'health.js', 'i18n.js', 'image_commands.js', 'random_id.js', 'clipboard_text.js', 'image_editor.js', 'image_editor_engine.js', 'image_generation.js', 'image_lora.js', 'image_view.js', 'launch_visit.js', 'launcher.js', 'length_plan.js', 'lora_triggers.js', 'lora_check.js', 'library.js', 'motion.js', 'native_errors.js', 'translate_guard.js', 'output_download.js', 'port_notice.js', 'preview_scene.js', 'progress_connection.js', 'prompt_draft.js', 'prompt_enhance.js', 'prompt_references.js', 'prompt_sections.js', 'prompt_terms.js', 'request_assets.js', 'repair_hint.js', 'report_issue.js', 'issue_button.js', 'studio_recent.js', 'media_queue.js', 'work_media.js', 'task_groups.js', 'result_actions.js', 'result_reuse.js', 'sampling_effort.js', 'pass_mode.js','setup.js', 'share.js', 'share_layout.js', 'studio.js', 'studio_chain.js', 'studio_extend.js', 'studio_length.js', 'first_frame_row.js', 'replace_person.js', 'replace_state.js', 'optional_inputs.js', 'other_usage.js', 'studio_queue.js', 'studio_size.js', 'toolbar_position.js', 'updates.js', 'video_model.js', 'view_navigation.js', 'whatsnew.js', 'whatsnew_pages.js', 'whatsnew_peaks.js', 'wordmark.js', 'workspace_restore.js', 'cast_library.js', 'media_upload.js', 'whitebox_encode.js', 'whitebox_mp4.js', 'whitebox_recording.js', 'whitebox_render.js', 'whitebox_scenes.js', 'whitebox_worker.js', diff --git a/web/i18n.js b/web/i18n.js new file mode 100644 index 00000000..c9b1e4e2 --- /dev/null +++ b/web/i18n.js @@ -0,0 +1,40 @@ +// The page's interface language, read one way for every module. The launcher passes its language in the address as +// freevideo_lang=zh or freevideo_lang=en; without it the browser's language decides (Chinese when it starts with "zh"). +// Each module still decides when it reads: most read once when they load, the tour and the tutorial when they open. +// No imports and no DOM, so Node tests load it as they load the modules that use it. +export const LANGUAGE_PARAM = 'freevideo_lang'; +export const KEY_SEPARATOR = '␟'; + +// The language asked for in the address, as written there ('zh', 'en', anything else), or null. +export function askedLanguage(search = globalThis.location?.search) { + try { return new URLSearchParams(search || '').get(LANGUAGE_PARAM); } catch { return null; } +} + +// Whether the page shows Chinese: the address decides when it says zh or en, otherwise the browser's language. +export function isChinese(asked = askedLanguage(), browserLanguage = globalThis.navigator?.language) { + return asked === 'zh' || (asked !== 'en' && String(browserLanguage || '').toLowerCase().startsWith('zh')); +} + +// A module's t(en, zh) for the language it read. +export const translator = chinese => (en, zh) => chinese ? zh : en; + +// The address that opens this page in a language (Settings, the command palette, reloading into an update). +export function languageUrl(href, language) { + const url = new URL(href); + url.searchParams.set(LANGUAGE_PARAM, language); + return url; +} + +// A language file's text for a pair: the entry for the English and Chinese together (when the English has more than +// one meaning), then for the English alone, then the English itself. {name} placeholders are filled from values. +// Not used by the pages yet: English and Chinese are written in the code, and other languages come later. A missing +// entry falls back to English, so Simplified Chinese is never read through it: its text is the zh in the code. +export function lookup(catalog, en, zh, values) { + const own = key => catalog && Object.prototype.hasOwnProperty.call(catalog, key) && typeof catalog[key] === 'string' ? catalog[key] : null; + const text = own(en + KEY_SEPARATOR + zh) ?? own(en) ?? en; + return values ? fill(text, values) : text; +} + +export function fill(text, values) { + return String(text).replace(/\{(\w+)\}/g, (whole, name) => Object.prototype.hasOwnProperty.call(values, name) ? String(values[name]) : whole); +} diff --git a/web/image_generation.js b/web/image_generation.js index 3b32514d..a0ae1f26 100644 --- a/web/image_generation.js +++ b/web/image_generation.js @@ -8,6 +8,7 @@ import {skinSelect} from './fv_select.js'; import {about} from './request_assets.js'; import {createImageLoras} from './image_lora.js'; import {createOtherUsageNotice, otherUsageText} from './other_usage.js'; +import {randomUUID} from './random_id.js'; // The page's background loading of works (work_media.js) waits while an upload runs. const uploadRunning = active => { try { globalThis.dispatchEvent?.(new CustomEvent('freevideo-upload', {detail: {active}})); } catch { /* no page */ } }; @@ -174,7 +175,7 @@ export function createImageGenClient(fetchImpl = globalThis.fetch.bind(globalThi const folder = await offers('request_folder'); const ext = folder ? ({'image/jpeg': 'jpg', 'image/webp': 'webp'}[file.type] || 'png') : 'png'; const body = new FormData(); - body.append('image', new File([file], folder ? `${crypto.randomUUID()}.${ext}` : `freevideo-image-reference-${crypto.randomUUID()}.png`, {type: file.type || 'image/png'})); + body.append('image', new File([file], folder ? `${randomUUID()}.${ext}` : `freevideo-image-reference-${randomUUID()}.png`, {type: file.type || 'image/png'})); body.append('type', 'input'); body.append('overwrite', 'false'); if (folder) body.append('subfolder', PAGE_UPLOAD_FOLDER); uploadRunning(true); @@ -209,14 +210,19 @@ export function packView(info, t) { if (own) { const waiting = install.state === 'paused_for_generation'; // A paused download offers to continue now; the note says what it waits for. - return {loading: true, waiting, button: waiting ? t('Continue download', '继续下载') : t('Pause', '暂停'), fraction: total > 0 ? Math.min(1, (install.done || 0) / total) : 0, + // While a setup, update or cleanup holds the installation the download cannot go on at the user's request: no button, only the note. + return {loading: true, waiting, noButton: waiting && install.reason === 'busy_setup', button: waiting ? t('Continue download', '继续下载') : t('Pause', '暂停'), fraction: total > 0 ? Math.min(1, (install.done || 0) / total) : 0, note: waiting ? (install.reason === 'busy_video' ? t('Paused while a video generates', '视频生成中,已暂停') : install.reason === 'busy_picture' ? t('Paused while a picture is made', '正在出图,已暂停') + : install.reason === 'busy_setup' ? t('Paused while FreeVideo installs, updates or cleans up', 'FreeVideo 正在安装、更新或清理,已暂停') : t('Paused while FreeVideo uses the graphics card for another task', 'FreeVideo 正在用显卡做别的任务,已暂停')) : t(`Downloading · ${gb(install.done || 0)}\u00a0GB / ${size}${time}`, `正在下载 · ${gb(install.done || 0)}\u00a0GB / ${size}${time}`)}; } const resume = install.state === 'failed' || install.state === 'cancelled' || install.done > 0; const reason = install.state === 'failed' ? t(install.message_en, install.message_zh) : ''; + // A file the video install shares differs: downloading again would stop at the same place, and the launcher's Repair + // (named in the note) is the way on, so no button is offered here. + if (install.state === 'failed' && install.reason === 'shared_mismatch' && reason) return {loading: false, fraction: null, reason: true, button: '', note: reason}; return {loading: false, fraction: null, reason: !!reason, button: resume ? t('Resume download', '继续下载') : t('Download image generation models', '下载图像生成模型'), note: reason || (resume ? t(`${gb(install.done || 0)}\u00a0GB / ${size}${time}`, `${gb(install.done || 0)}\u00a0GB / ${size}${time}`) : size + time)}; } @@ -446,7 +452,7 @@ export async function uploadGenerationReference(renderer, client, context, alive blob = await new Promise((resolve, reject) => raster.toBlob(b => b ? resolve(b) : reject(failure(undefined, {step: 'encode_reference'})), 'image/png')); } else blob = (await renderer.export(context.doc, 'image/png')).blob; if (!alive()) throw failure('cancelled'); - const file = new File([blob], `freevideo-image-reference-${crypto.randomUUID()}.png`, {type: 'image/png'}); + const file = new File([blob], `freevideo-image-reference-${randomUUID()}.png`, {type: 'image/png'}); return client.upload(file); } @@ -466,7 +472,7 @@ export async function uploadGenerationMask(renderer, client, context, alive = () if (!any) return null; const blob = await new Promise((resolve, reject) => mask.toBlob(b => b ? resolve(b) : reject(failure(undefined, {step: 'encode_mask'})), 'image/png')); if (!alive()) throw failure('cancelled'); - return client.upload(new File([blob], `freevideo-image-mask-${crypto.randomUUID()}.png`, {type: 'image/png'})); + return client.upload(new File([blob], `freevideo-image-mask-${randomUUID()}.png`, {type: 'image/png'})); } // The object under a click, as the name of a black and white picture the size of the layer's pixels. @@ -488,7 +494,7 @@ export async function segmentAt(renderer, client, doc, layer, point, again = fal const blob = await new Promise((resolve, reject) => raster.toBlob(b => b ? resolve(b) : reject(failure(undefined, {step: 'encode_segment'})), 'image/png')); // The layer's previous look is not needed any more: its upload goes. if (known?.name) { segmentNames.delete(known.name); Promise.resolve().then(() => client.discardUploads?.([known.name])).catch(() => {}); } - known = {look, name: await client.upload(new File([blob], `freevideo-image-reference-${crypto.randomUUID()}.png`, {type: 'image/png'})), width: raster.width, height: raster.height}; + known = {look, name: await client.upload(new File([blob], `freevideo-image-reference-${randomUUID()}.png`, {type: 'image/png'})), width: raster.width, height: raster.height}; segmentUploads.set(layer, known); segmentNames.add(known.name); } const x = Math.min(known.width - 1, Math.max(0, Math.floor(point[0] * known.width))), y = Math.min(known.height - 1, Math.max(0, Math.floor(point[1] * known.height))); @@ -525,7 +531,7 @@ export async function uploadExtraReferences(client, references, render, alive = for (const item of references) { const blob = await render(item.file); if (!alive()) throw failure('cancelled'); - names.push(await client.upload(new File([blob], `freevideo-image-reference-${crypto.randomUUID()}.png`, {type: 'image/png'}))); + names.push(await client.upload(new File([blob], `freevideo-image-reference-${randomUUID()}.png`, {type: 'image/png'}))); if (!alive()) throw failure('cancelled'); } return names; @@ -1048,7 +1054,7 @@ export function createImageGeneration({client, renderer, t, getDoc, getSelection action.classList.toggle('fv-ie-primary', !state.running); action.setAttribute('aria-disabled', String(!pack && !state.running && (disabled || !prompt.trim()))); action.title = !pack && !state.running && !prompt.trim() ? t('Enter a prompt first', '请先填写提示词') : ''; - action.hidden = !!missing && !pack; + action.hidden = !!missing && !(pack && pack.button) || !!pack?.noButton; const percent = Math.floor(state.fraction * 100) + '%'; if (state.error && !promptRequired) { const failureKey = `${state.error}:${state.report_id || ''}:${state.stage || ''}:${state.memory || ''}`; @@ -1121,6 +1127,7 @@ export function createImageGeneration({client, renderer, t, getDoc, getSelection const note = el('div', '', 'fv-ie-opt-note fv-ie-gen-note'); note.setAttribute('role', 'status'); const action = button(t('Generate', '生成'), null, () => { const now = session.state(), pack = !now.running && now.info && !now.info.installed ? packView(now.info, t) : null; + if (pack && !pack.button) return; if (pack) void session.pack(pack.loading && !pack.waiting ? 'cancel' : 'install'); else if (now.running) void stop(); else void start(); }, 'fv-ie-button fv-ie-primary'); diff --git a/web/image_library.js b/web/image_library.js index a1d7f398..d1e7baef 100644 --- a/web/image_library.js +++ b/web/image_library.js @@ -3,10 +3,10 @@ import { agentGet, agentPost, agentSend } from './agent_session.js'; import { uploadMedia } from './media_upload.js'; import { listenDialogKey } from './dialog_keys.js'; +import { isChinese, translator } from './i18n.js'; -const languageOverride = typeof location !== 'undefined' ? new URLSearchParams(location.search).get('freevideo_lang') : null; -const cn = languageOverride === 'zh' || (languageOverride !== 'en' && String(navigator.language || '').toLowerCase().startsWith('zh')); -const t = (en, zh) => cn ? zh : en; +const cn = isChinese(); +const t = translator(cn); const el = (tag, cls, text) => { const e = document.createElement(tag); if (cls) e.className = cls; if (text != null) e.textContent = text; return e; }; const LIMIT = 200; const css = document.createElement('link'); css.rel = 'stylesheet'; css.href = new URL('./image_library.css', import.meta.url).href; document.head.append(css); diff --git a/web/image_lora.js b/web/image_lora.js index 6c26cf22..8b4e2f64 100644 --- a/web/image_lora.js +++ b/web/image_lora.js @@ -153,14 +153,17 @@ export function createImageLoras({t, fetchApi, el = domEl, getPrompt = () => '', drawSummary(); } + async function readNames() { + const response = await fetchApi('/models/loras', {cache: 'no-store'}); + if (!response.ok) throw new Error(response.statusText); + const listed = (await response.json()).filter(n => typeof n === 'string'); + skipped = listed.filter(n => /\.(ckpt|pt|pth|bin|sft)$/i.test(n)).length; + names = listed.filter(n => n.toLowerCase().endsWith('.safetensors')); + verdicts.clear(); + } async function refresh() { try { - const response = await fetchApi('/models/loras', {cache: 'no-store'}); - if (!response.ok) throw new Error(response.statusText); - const listed = (await response.json()).filter(n => typeof n === 'string'); - skipped = listed.filter(n => /\.(ckpt|pt|pth|bin|sft)$/i.test(n)).length; - names = listed.filter(n => n.toLowerCase().endsWith('.safetensors')); - verdicts.clear(); render(); changed(); + await readNames(); render(); changed(); } catch (error) { if (!disposed) note.textContent = t('Could not read the LoRA folder.', '无法读取 LoRA 文件夹。'); } @@ -182,6 +185,17 @@ export function createImageLoras({t, fetchApi, el = domEl, getPrompt = () => '', refresh, /** After the prompt box is cleared or replaced, trigger words are put back for the rows still on. */ reconcile: syncPrompt, + /** Puts a saved list in the rows (a card's own LoRAs). A file that is no longer in the folder is left out, no + * empty row stays. */ + async load(saved) { + const wanted = (Array.isArray(saved) ? saved : []).filter(r => r && typeof r.name === 'string') + .slice(0, IMAGE_LORA_LIMIT).map(r => ({name: r.name, strength: Number.isFinite(Number(r.strength)) ? Number(r.strength) : 1, enabled: r.enabled !== false})); + if (!wanted.length) return; + try { await readNames(); } catch { /* The folder cannot be read now: the rows are kept as they were saved. */ } + if (disposed) return; + rows = wanted.filter(r => !names || names.includes(r.name)); + render(); + }, dispose() { disposed = true; }, }; } diff --git a/web/image_view.css b/web/image_view.css index 061eda74..e12d8792 100644 --- a/web/image_view.css +++ b/web/image_view.css @@ -160,7 +160,7 @@ dialog.fv-studio.fv-image:not([open]){display:none!important} .fv-iv .fv-iv-prompt-bar:is([data-compact=true],[data-hx-cnt]) .fv-iv-text-btn .fv-iv-btn-label{display:none} .fv-iv .fv-image-enhance .fv-iv-prompt:focus-visible{box-shadow:inset 0 0 0 1.5px var(--fv-accent-line)} /* the helper's status line (with its report button) only while the helper is on */ -.fv-iv .fv-image-enhance:not([data-hx-chk]) .fv-enhance-status{display:none} +.fv-iv .fv-image-enhance:not([data-hx-chk],[data-reverse=true]) .fv-enhance-status{display:none} .fv-iv .fv-image-enhance[data-off=true] :is(.fv-enhance-bar,.fv-enhance-status,.fv-enhance-install){display:none} .fv-studio .fv-iv .fv-iv-prompt{display:block;width:100%;box-sizing:border-box;height:96px;min-height:96px;max-height:280px;resize:none;padding:12px 12px;border:0;border-radius:var(--fv-r-md); background:var(--iv-well);box-shadow:inset 0 0 0 1px var(--fv-line);color:var(--fv-fg);font:inherit;font-size:var(--fv-fs-3,16px);line-height:1.55; @@ -630,7 +630,7 @@ dialog.fv-studio.fv-image:not([open]){display:none!important} .fv-iv :is(.fv-iv-field,.fv-iv-search){height:var(--fv-touch)} .fv-iv .fv-iv-seg>button{min-height:var(--fv-touch)} .fv-iv .fv-iv-prompt-bar{height:auto} - .fv-iv .fv-iv-prompt-bar .fv-ed-expand{width:var(--fv-touch);height:var(--fv-touch);min-width:var(--fv-touch);min-height:var(--fv-touch)} + .fv-iv.fv-iv .fv-iv-prompt-bar :is(.fv-ed-expand,.fv-iv-reverse-tool){width:var(--fv-touch);height:var(--fv-touch);min-width:var(--fv-touch);min-height:var(--fv-touch);margin-left:0} .fv-iv.fv-iv :is(.fv-iv-size,.fv-iv-lora) button.fvp-chip{height:var(--fv-touch)!important;min-height:var(--fv-touch)!important} .fv-iv .fv-iv-cap .fv-iv-text-btn{min-width:var(--fv-touch)} } @@ -801,3 +801,14 @@ dialog.fv-studio.fv-image:not([open]){display:none!important} @keyframes fv-iv-lhint{0%,70%{opacity:1}100%{opacity:0}} @media(prefers-reduced-motion:reduce){.fv-iv-lhint{animation:none}} :root[data-theme=light] .fv-iv-lbar,:root[data-theme=light] .fv-iv-lhint{box-shadow:0 4px 14px rgb(30 40 60 / .18)} +/* Prompt from a picture or video: the key beside Expand (24 px wide, two closer to the row so the words of References, Sketch and Enhance still fit in Chinese); Stop while it runs; grey while the queue runs. */ +.fv-iv .fv-iv-prompt-bar .fv-iv-reverse-tool{flex:none;width:24px;height:28px;min-width:24px;margin-left:-2px;color:var(--fv-fg2)} +.fv-iv .fv-iv-prompt-bar .fv-iv-reverse-tool[aria-disabled=true]{opacity:.4;cursor:not-allowed} +.fv-iv .fv-iv-prompt-bar .fv-iv-reverse-tool[data-state=running]{color:var(--fv-accent-ink)} +.fv-iv .fv-image-enhance[data-reversing=true] .fv-iv-prompt{opacity:.6} +/* While a description is being written the Stop key is the control; the helper's Cancel row stays away. The report key keeps its border and gap. */ +.fv-iv .fv-enhance-status .fv-issue-button{border:1px solid var(--fv-line);gap:6px;padding:4px 10px;border-radius:var(--fv-r-sm,8px)} +/* The consent card (model not installed) takes the panel's own ground and ink in both themes, at full strength. */ +.fv-iv .fv-image-enhance .fv-enhance-install{background:color-mix(in srgb,var(--fv-fg) 6%,transparent);border-top:1px solid var(--fv-line);color:var(--fv-fg);opacity:1} +.fv-iv .fv-image-enhance .fv-enhance-install .fv-quiet,.fv-iv .fv-image-enhance .fv-enhance-install a{color:var(--fv-fg2);opacity:1} +.fv-iv .fv-image-enhance .fv-enhance-install button{border-radius:var(--fv-rad-ctl,12px)} diff --git a/web/image_view.js b/web/image_view.js index bb675314..07263b9a 100644 --- a/web/image_view.js +++ b/web/image_view.js @@ -19,7 +19,7 @@ import { openAutopilot, viewChanged, viewSwitch } from './view_navigation.js'; import { wordmark } from './wordmark.js'; import { keepViewSwitchPlace } from './view_switch_place.js'; import { openReferenceMenu, removeSavedImages } from './image_library.js'; -import { BLANK_CANVAS_AREAS, createImageGenClient, fittedNote, imageGenError, imageRemainingText, imageReportBar, renderImageFailure } from './image_generation.js'; +import { BLANK_CANVAS_AREAS, createImageGenClient, fittedNote, imageGenError, imageRemainingText, imageReportBar, originStep, renderImageFailure } from './image_generation.js'; import { duration } from './generation_progress.js'; import { randomSeed } from './studio_queue.js'; import { createLayout } from './image_view_layout.js'; @@ -41,6 +41,7 @@ import { openPictureViewer } from './image_view_viewer.js'; import { LORA_MODEL, imageViewLora } from './image_view_lora.js'; import { hasPictureThumbnail, mediaQueue, pictureThumbnailURL } from './work_media.js'; import { fieldNote } from './field_note.js'; +import { copyText } from './clipboard_text.js'; export { IMAGE_MODELS, RATIOS }; for (const name of ['./image_view.css']) { @@ -313,7 +314,10 @@ export function openImageView(node, {studio = null, client: given = null, poll = tip(layoutAdd, t('Layout', '布局')); layoutAdd.addEventListener('click', () => toggleLayout()); // Prompt enhancement is a key in this row beside References and Sketch, lit while on (no switch row of its own). enhancer.chip.classList.add('fv-iv-text-btn', 'fv-iv-enhance-tool'); enhancer.chip.querySelector('span')?.classList.add('fv-iv-btn-label'); - promptBar.append(refAdd, sketchAdd, layoutAdd, enhancer.chip, el('span', 'fv-iv-grow'), promptCount, expand.element); + // Prompt from a picture or video: a key beside Expand; while it runs the same key stops it. The file only feeds the + // description (it is not added to the references). + const reverseKey = button('fv-iv-icon-btn fv-iv-reverse-tool', {iconName: 'reverse', name: t('Prompt from a picture or video', '从图片或视频生成提示词'), use: t("Pick a picture or video; its description fills the box", '选一张图片或一段视频,生成的描述填入描述框')}); + promptBar.append(refAdd, sketchAdd, layoutAdd, enhancer.chip, el('span', 'fv-iv-grow'), promptCount, reverseKey, expand.element); // The row stays on one line inside the panel, Expand at the same inset as the box: when its words do not fit (a // narrow panel, longer words), its keys keep their icons only (their hover cards still name them). Measured again // whenever the row's own contents change (the count near the limit), not only when the panel is resized. @@ -456,7 +460,7 @@ export function openImageView(node, {studio = null, client: given = null, poll = moreButton.setAttribute('aria-haspopup', 'true'); const more = el('div', 'fv-iv-menu fv-image-more fv-glass fv-g3'); more.hidden = true; more.setAttribute('role', 'menu'); const menuItem = (iconName, text, use, onClick, cls = '') => { const b = el('button', 'fv-iv-menu-item ' + cls); b.type = 'button'; b.setAttribute('role', 'menuitem'); b.append(icon(iconName), el('span', '', text)); tip(b, text, use); b.addEventListener('click', () => { more.hidden = true; onClick(); }); return b; }; - const copyPrompt = () => { const text = promptFor(shownFile); try { void navigator.clipboard?.writeText(text); } catch { /* the clipboard may be refused */ } }; + const copyPrompt = () => { void copyText(promptFor(shownFile)); }; // with the selection copy where the clipboard API is missing (LAN over http) const usePromptItem = menuItem('prompt', t('Use prompt', '使用提示词'), t('Put its prompt back in the box', '把它的提示词填回描述框'), () => usePrompt(shownFile)); // For MOSS the boxes are part of the prompt: they come back with the words, and MOSS is chosen. function usePrompt(file) { @@ -959,10 +963,48 @@ export function openImageView(node, {studio = null, client: given = null, poll = function openRefMenu(anchor) { if (refAdd.getAttribute('aria-disabled') === 'true' && anchor === refAdd) return; if (menu?.box.isConnected) { menu.close(); return; } - menu = openReferenceMenu({api, viewURL: pictureURL, anchor: () => anchor.isConnected ? anchor : refAdd, host: dialog, prefer: 'up', onComputer: () => pick.click(), + menu = openReferenceMenu({api, viewURL: pictureURL, anchor: () => anchor.isConnected ? anchor : refAdd, host: dialog, prefer: 'up', onComputer: () => chooseFile(false), onPick: (file, id) => { addFiles([file], id); }, state: () => ({used: new Set(references.map(r => r.card)), full: references.length >= most()})}); } - pick.onchange = () => { addFiles([...pick.files]); pick.value = ''; }; + // The one file box serves both keys; every opening says which, so a cancelled choice leaves nothing behind. + function chooseFile(forReverse) { + pick.dataset.for = forReverse ? 'reverse' : ''; pick.accept = forReverse ? 'image/*,video/*' : 'image/*'; pick.multiple = !forReverse; + pick.click(); + } + pick.onchange = () => { + const files = [...pick.files], forReverse = pick.dataset.for === 'reverse'; + pick.value = ''; pick.dataset.for = ''; pick.accept = 'image/*'; pick.multiple = true; + if (forReverse) { if (files[0]) startReverse(files[0]); } else addFiles(files); + }; + // ───── Prompt from a picture or video ───── + let reverseMenu = null; + const reverseWhy = () => running ? t('Finish the current queue before writing a prompt from media.', '请等待当前队列完成后再生成提示词。') : ''; + function startReverse(file) { + const kind = file.type?.startsWith('video/') ? 'video' : file.type?.startsWith('image/') ? 'image' : 'other'; + promptGroup.open(true); + enhancer.reverse({kind, upload: async () => { if (kind === 'other') throw new Error('unsupported_media'); return client.upload(file); }}, {shapeVideo: false}).catch(() => {}); + } + reverseKey.addEventListener('click', () => { + if (enhancer.reversing) { enhancer.stop(); return; } + if (reverseKey.getAttribute('aria-disabled') === 'true') return; + if (reverseMenu?.box.isConnected) { reverseMenu.close(); return; } + reverseMenu = openReferenceMenu({api, viewURL: pictureURL, anchor: reverseKey, host: dialog, prefer: 'up', onComputer: () => chooseFile(true), + onPick: file => { reverseMenu?.close(); startReverse(file); }, state: () => ({used: new Set(), full: false})}); + }); + // Dropped on the box: the description is written from it. + prompt.addEventListener('dragover', event => { if (event.dataTransfer?.types?.includes('Files')) { event.preventDefault(); event.stopPropagation(); } }); + prompt.addEventListener('drop', event => { const file = event.dataTransfer?.files?.[0]; if (!file) return; event.preventDefault(); event.stopPropagation(); if (!enhancer.reversing && !running) startReverse(file); }); + // The key follows the job: Stop while it runs, grey (with its reason) while the queue runs; the status line shows whether or not the helper is on. + const paintReverse = () => { + const on = enhancer.reversing, why = reverseWhy(); + reverseKey.dataset.state = on ? 'running' : ''; + reverseKey.setAttribute('aria-disabled', String(!on && !!why)); reverseKey.dataset.fvTipWhy = !on && why ? why : ''; if (!why || on) delete reverseKey.dataset.fvTipWhy; + tip(reverseKey, on ? t('Stop', '停止') : t('Prompt from a picture or video', '从图片或视频生成提示词'), on ? '' : t('Pick a picture or video; its description fills the box', '选一张图片或一段视频,生成的描述填入描述框')); + reverseKey.replaceChildren(icon(on ? 'stop' : 'reverse')); + go.disabled = go.disabled || on; + }; + // The line stays when it says why nothing was written (not enabled, stopped), which ends in the idle state. + queueMicrotask(() => enhancer.onReverse(state => { enhancer.element.dataset.reverse = state.state === 'idle' && !state.noted ? 'false' : 'true'; if (alive) render(); })); // The reference pictures the user had when the view was left come back as they were (marks, sketches, originals). if (keptDraft?.references?.length) { for (const kept of keptDraft.references) { @@ -1105,7 +1147,7 @@ export function openImageView(node, {studio = null, client: given = null, poll = function paintGo() { const s = modelState(info, model.id), busy = !!running, now = size(), est = estimateSeconds(meta.samples(), model.id, now.width * now.height); go.className = 'fv-image-go fv-iv-go ' + (failure ? 'fv-image-go-quiet' : 'fv-primary'); - go.disabled = false; go.dataset.state = busy ? 'running' : s.state === 'downloading' ? 'downloading' : (s.state === 'missing' || s.state === 'failed') ? 'install' : 'ready'; + go.disabled = !!enhancer.reversing; if (go.disabled) tip(go, t('Writing the prompt', '正在生成提示词'), ''); go.dataset.state = busy ? 'running' : s.state === 'downloading' ? 'downloading' : (s.state === 'missing' || s.state === 'failed') ? 'install' : 'ready'; goFill.style.setProperty('--p', String(s.state === 'downloading' ? s.fraction : 0)); delete go.dataset.fvTipWhy; if (busy) { @@ -1152,6 +1194,7 @@ export function openImageView(node, {studio = null, client: given = null, poll = // Generate fills the draft frame in place; when the picture is done the stage shows it. if (running && !browsing) { draft = false; draftPreview = null; } enhancer.element.dataset.off = String(enhancerOff()); + paintReverse(); cards.paint(info, model.id, pendingGenerate); loraRow.paint(model.id); drawReferences(); @@ -1403,14 +1446,18 @@ export function openImageView(node, {studio = null, client: given = null, poll = level.hidden = false; level.dataset.counted = 'false'; level.style.setProperty('--fv-progress', '0'); clearStep(); const names = []; + // Where a failure without a reason of its own was caught (#1097: an upload that never left the page said "unreported"). + let reached = 'upload'; try { for (const r of references.slice(0, cap_(model))) names.push(await client.upload(r.file)); if (mine.cancelled) return; + reached = 'prepare'; if (!enhancerOff() && await enhancer.beforeGenerate() === false) { say(''); if (running === mine) running = null; level.hidden = true; render(); drawWorks(); return; } if (!fits()) { if (running === mine) running = null; level.hidden = true; render(); drawWorks(); fits(); prompt.focus(); return; } startJobSources(); const loras = loraRow.value(model.id); let id; + reached = 'submit'; // The engine makes one picture at a time: a second request waits its turn here and starts by itself; Stop cancels the wait. for (;;) { try { @@ -1439,7 +1486,7 @@ export function openImageView(node, {studio = null, client: given = null, poll = running = null; level.hidden = true; clearStep(); // The worker is full: a state of the worker, shown in place, not a failed picture. if (IMAGE_BUSY.has(error.code)) { note.dataset.kind = 'busy'; say(imageGenError(error.code, info, t)); render(); drawWorks(); return; } - failure = {error: error.code || 'generation_failed', report_id: error.report_id, stage: error.stage, step: error.step, fitted: error.fitted, memory: error.memory, other_usage: error.other_usage, retryStandard: tierNow === 'high' && error.code === 'no_memory'}; + failure = {error: error.code || 'generation_failed', report_id: error.report_id, stage: error.stage, step: originStep(error, reached), fitted: error.fitted, memory: error.memory, other_usage: error.other_usage, retryStandard: tierNow === 'high' && error.code === 'no_memory'}; renderFailure(); render(); drawWorks(); } finally { // Pictures sent for a request that never became a job; a job's own go when it ends. diff --git a/web/image_view_models.js b/web/image_view_models.js index 8e4707e0..3fa86680 100644 --- a/web/image_view_models.js +++ b/web/image_view_models.js @@ -26,7 +26,9 @@ export function modelState(info, id) { : total > 0 ? Math.min(1, done / total) : 0; if (row.downloading || install.state === 'running' || install.state === 'paused_for_generation') return {state: 'downloading', row, total, done, fraction, verifying, paused: install.state === 'paused_for_generation', - waitsFor: install.state === 'paused_for_generation' ? install.reason || 'busy_engine' : '', rate: install.bytes_per_second || 0}; + waitsFor: install.state === 'paused_for_generation' ? install.reason || 'busy_engine' : '', rate: install.bytes_per_second || 0, + // A setup, update or cleanup holds the installation: the download goes on by itself and cannot be asked to go on. + locked: install.state === 'paused_for_generation' && install.reason === 'busy_setup'}; if (install.state === 'failed') return {state: 'failed', row, total, done, fraction, reason: t(install.message_en || '', install.message_zh || '') || install.reason || ''}; return {state: 'missing', row, total, done, fraction, resume: done > 0}; @@ -40,6 +42,7 @@ export const continueUse = () => t('Download now; a video or picture being made export function pausedText(state) { return state.waitsFor === 'busy_video' ? t('Paused while a video generates; resumes after it, or continue now', '视频生成中,下载已暂停,之后自动继续,也可以现在继续下载') : state.waitsFor === 'busy_picture' ? t('Paused while a picture is made; resumes after it, or continue now', '正在出图,下载已暂停,出完自动继续,也可以现在继续下载') + : state.waitsFor === 'busy_setup' ? t('Paused while FreeVideo installs, updates or cleans up; resumes after it', 'FreeVideo 正在安装、更新或清理,下载已暂停,结束后自动继续') : t('Paused while FreeVideo uses the graphics card for another task; resumes after it, or continue now', 'FreeVideo 正在用显卡做别的任务,下载已暂停,之后自动继续,也可以现在继续下载'); } // Checking files already on disk: a percentage only when the engine reports one. @@ -79,7 +82,7 @@ function useOf(model, state) { checking: t('Asking the engine', '正在询问引擎'), }[state.state]; } -const actionOf = state => state.state === 'missing' ? (state.resume ? t('Resume', '继续') : t('Install', '安装')) : state.state === 'failed' ? t('Retry', '重试') : state.state === 'downloading' && state.paused ? t('Continue download', '继续下载') : state.state === 'downloading' && !state.verifying ? t('Pause', '暂停') : ''; +const actionOf = state => state.locked ? '' : state.state === 'missing' ? (state.resume ? t('Resume', '继续') : t('Install', '安装')) : state.state === 'failed' ? t('Retry', '重试') : state.state === 'downloading' && state.paused ? t('Continue download', '继续下载') : state.state === 'downloading' && !state.verifying ? t('Pause', '暂停') : ''; // The picker: one row for the chosen model; the list opens below it (above when there is no room), takes the // arrow keys, Home, End, Enter and Escape, and scrolls when there are more models than fit. diff --git a/web/image_view_ui.js b/web/image_view_ui.js index 753669a4..930ae3a4 100644 --- a/web/image_view_ui.js +++ b/web/image_view_ui.js @@ -1,9 +1,9 @@ import { listenDialogKey } from './dialog_keys.js'; +import { isChinese, translator } from './i18n.js'; // Small pieces every part of the picture page builds with: elements, line icons, buttons, and the hover // description (name, one line of purpose, shortcut) that the shell's tooltip reads from data-fv-tip-*. -const languageOverride = typeof location !== 'undefined' ? new URLSearchParams(location.search).get('freevideo_lang') : null; -export const cn = languageOverride === 'zh' || (languageOverride !== 'en' && typeof navigator !== 'undefined' && String(navigator.language || '').toLowerCase().startsWith('zh')); -export const t = (en, zh) => cn ? zh : en; +export const cn = isChinese(); +export const t = translator(cn); export const el = (tag, cls, text) => { const e = document.createElement(tag); if (cls) e.className = cls; if (text != null) e.textContent = text; return e; }; @@ -12,6 +12,7 @@ const PATHS = { model: '', prompt: '', layout: '', + reverse: '', refs: '', size: '', sliders: '', diff --git a/web/library.js b/web/library.js index 1e3f4ea1..2ce41f8c 100644 --- a/web/library.js +++ b/web/library.js @@ -2,6 +2,7 @@ import { cutTip } from './cut_tip.js'; import { api } from '../../scripts/api.js'; import { closeDialog } from './motion.js'; import { resultActions, previewBadge, icon } from './result_actions.js'; +import { copyText } from './clipboard_text.js'; import { videoUnavailableText, canExtend } from './studio_extend.js'; import { savedSettings } from './result_reuse.js'; import { listenDialogKey, topDialog } from './dialog_keys.js'; @@ -635,7 +636,7 @@ export function openLibrary(t, options = {}) { const promptBox = el('div', null, 'fv-library-prompt'); promptBox.hidden = true; const promptHead = el('div', null, 'fv-library-prompt-head'), promptText = el('p', null, 'fv-library-prompt-text'); const promptCopy = button('', async () => { - let ok = false; try { await navigator.clipboard.writeText(promptText.textContent); ok = true; } catch { /* Shown on the button. */ } + const ok = await copyText(promptText.textContent); // shown on the button promptCopy.lastElementChild.textContent = ok ? t('Copied', '已复制') : t('Could not copy', '复制失败'); setTimeout(() => { promptCopy.lastElementChild.textContent = t('Copy', '复制'); }, 1600); }, 'fv-library-prompt-copy'); @@ -1508,7 +1509,7 @@ export function openLibrary(t, options = {}) { const promptOf = one.kind === 'image' ? picturePrompt(one) : prompts.get(one.id); items.push({id: 'copy-prompt', icon: 'copy', label: ['Copy prompt', '复制提示词'], disabled: promptOf ? '' : one.kind === 'image' ? ['This picture kept no prompt', '这张图片没有保存提示词'] : ['This video kept no prompt', '这条视频没有保存提示词'], - run: async () => { try { await navigator.clipboard.writeText(promptOf); say(t('Prompt copied.', '已复制提示词。')); } catch { say(t('Could not copy.', '没能复制。'), true); } }}); + run: async () => { if (await copyText(promptOf)) say(t('Prompt copied.', '已复制提示词。')); else say(t('Could not copy. Try again.', '未能复制,请重试。'), true); }}); } if (one) items.push({id: 'folder', icon: 'folder', label: ['Show in folder', '在文件夹中显示'], run: async () => { diff --git a/web/media_upload.js b/web/media_upload.js index b247d2fe..c3963a27 100644 --- a/web/media_upload.js +++ b/web/media_upload.js @@ -1,9 +1,7 @@ // One media file into ComfyUI's input folder through FreeVideo's streaming upload; every upload place shares it. -const languageOverride = typeof location !== 'undefined' - ? new URLSearchParams(location.search).get('freevideo_lang') : null; -const cn = languageOverride === 'zh' || (languageOverride !== 'en' - && String(navigator.language || '').toLowerCase().startsWith('zh')); -const text = (en, zh) => cn ? zh : en; +import { isChinese, translator } from './i18n.js'; +const cn = isChinese(); +const text = translator(cn); // The page's background loading of works (work_media.js) waits while an upload runs. const uploadRunning = active => { try { globalThis.dispatchEvent?.(new CustomEvent('freevideo-upload', {detail: {active}})); } catch { /* no page */ } }; // The server's limit; a bigger file is turned away before a byte is sent. diff --git a/web/palette.js b/web/palette.js index db3635f5..87b9e0af 100644 --- a/web/palette.js +++ b/web/palette.js @@ -15,6 +15,7 @@ import { openNotifications, latestFinished, toast, visitJob, openWork } from './ import { jobs } from './task_store.js'; import { userMessage } from './user_message.js'; import { openIssue, preloadIssue } from './issue_button.js'; +import { languageUrl } from './i18n.js'; const browser = typeof document !== 'undefined'; addSheet('palette.css', import.meta.url); @@ -206,7 +207,7 @@ function setTheme(theme) { } const solidNow = () => document.documentElement.dataset.glass === 'solid' || document.documentElement.classList.contains('lite'); function reloadIn(lang) { - const url = new URL(location.href); url.searchParams.set('freevideo_lang', lang); + const url = languageUrl(location.href, lang); location.assign(url.href); } diff --git a/web/private_pin.js b/web/private_pin.js index 8f4452cd..781f9834 100644 --- a/web/private_pin.js +++ b/web/private_pin.js @@ -3,6 +3,7 @@ import {api} from '../../scripts/api.js'; import {app} from '../../scripts/app.js'; import {privacyOffered} from './private_offers.js'; +import {randomUUID} from './random_id.js'; const FILE = /freevideo(?:-image(?:-ref)?|-draft)?\/[^"\\\s]+|freevideo-image-(?:reference|mask)-[0-9a-f-]{36}\.png/g; const REFRESH_MS = 6 * 3600 * 1000; @@ -12,7 +13,7 @@ function pageId() { if (page) return page; try { page = sessionStorage.getItem('freevideo.pin.page') || ''; } catch { /* this tab only */ } if (!page) { - page = crypto.randomUUID().replace(/-/g, ''); + page = randomUUID().replace(/-/g, ''); try { sessionStorage.setItem('freevideo.pin.page', page); } catch { /* this tab only */ } } return page; diff --git a/web/prompt_draft.js b/web/prompt_draft.js index b895378e..2360bf78 100644 --- a/web/prompt_draft.js +++ b/web/prompt_draft.js @@ -11,6 +11,56 @@ const STEP_CACHE_OPTIONS = ['none', 'easycache-av', 'fbcache'], UPSCALE_OPTIONS const PROPERTIES = ['freevideo_aspect', 'freevideo_pixels', 'freevideo_seconds', 'freevideo_single', 'freevideo_block_seconds', 'freevideo_run_mode', 'freevideo_batch_count']; const OUTBOX = 'freevideo.prompt-pending'; +// The LoRA list and the reference pictures live on the nodes wired to the generate node, not on it. The draft keeps +// them as plain lists so a start without the browser's own copy of the project (another port, cleared site data) +// brings them back. Only arrays are ever written: a missing node is "not known", never "empty". +// This file stands alone (each tab, and the tests, load it as one module), so the replace-person names of +// replace_state.js (SWAP_LORA, SWAP_KEY) are repeated here; scripts/test_prompt_draft_lists.mjs keeps the two equal. +const SWAP_LORA = 'alissonerdx-v1.1.safetensors', SWAP_KEY = 'freevideo_replace_person'; +const swapLoraNames = names => (Array.isArray(names) ? names : []).filter(name => typeof name === 'string' + && String(name).split(/[\\/]/).pop().toLowerCase() === SWAP_LORA); +const LORA_LIMIT = 100, LIST_MAX = 32; +const finiteNumber = value => typeof value === 'number' && Number.isFinite(value); +function cleanLoras(value) { + let rows = value; + if (typeof rows === 'string') { try { rows = JSON.parse(rows || '[]'); } catch { return null; } } + if (!Array.isArray(rows)) return null; + const names = new Set(swapLoraNames(rows.map(row => row?.name))); + return rows.filter(row => row && typeof row === 'object' && typeof row.name === 'string' && row.name && !names.has(row.name) + && (row.strength === undefined || (finiteNumber(row.strength) && Math.abs(row.strength) <= LORA_LIMIT)) + && (row.enabled === undefined || typeof row.enabled === 'boolean')).slice(0, LIST_MAX) + .map(row => ({name: row.name, ...(row.strength === undefined ? {} : {strength: row.strength}), + ...(row.enabled === undefined ? {} : {enabled: row.enabled})})); +} +// Only what places a picture is kept: its file, its role and the settings of that row. A character card is named by its +// id alone; the card's name and description are read again from the library when the draft is restored. +const ASSET_KEYS = ['file', 'role', 'enabled', 'seconds', 'use', 'range', 'sound', 'depth', 'lines']; +// Rows that stand for a replace-person source (they carry a slot) belong to that panel, not to the list. +// `whole` keeps the card label of a row as it is (a restored row, going into the graph). +function cleanAssets(value, whole = false) { + let rows = value; + if (typeof rows === 'string') { try { rows = JSON.parse(rows || '[]'); } catch { return null; } } + if (!Array.isArray(rows)) return null; + return rows.filter(row => row && typeof row === 'object' && !Array.isArray(row) && typeof row.file === 'string' && row.file + && !row.slot).slice(0, LIST_MAX).map(row => ({...Object.fromEntries(ASSET_KEYS.filter(key => row[key] !== undefined).map(key => [key, clone(row[key])])), + ...(typeof row.cast?.id === 'string' && row.cast.id ? {cast: whole ? clone(row.cast) : {id: row.cast.id, + ...(row.cast.setting === true ? {setting: true} : {}), ...(row.cast.prop === true ? {prop: true} : {})}} : {})})); +} +function liveSource(node, name) { + const link = node.inputs?.find(input => input.name === name)?.link; + const origin = link != null ? node.graph?.links?.[link]?.origin_id : null; + return origin != null ? node.graph?.getNodeById?.(origin) || null : null; +} +const widgetValue = (node, name) => node?.widgets?.find(w => w.name === name)?.value; +// The same pair in a saved workflow: the node that feeds `name` of `node`. +function savedSource(workflow, node, name) { + const link = node.inputs?.find(input => input.name === name)?.link; + const row = link != null ? (workflow.links || []).find(entry => Array.isArray(entry) ? entry[0] === link : entry?.id === link) : null; + const origin = Array.isArray(row) ? row[1] : row?.origin_id; + return origin != null ? workflow.nodes.find(entry => entry.id === origin) || null : null; +} +const isList = value => typeof value === 'string' && value.trim() !== '' && value.trim() !== '[]'; + const clone = value => JSON.parse(JSON.stringify(value)); const equal = (a, b) => JSON.stringify(a) === JSON.stringify(b); const watched = new WeakMap(), dirty = new Set(); @@ -43,6 +93,10 @@ export function promptDraft(node) { versions: String(text ?? '').trim() && versions && typeof versions === 'object' ? clone(versions) : null}; const widgets = Object.fromEntries((node.widgets || []).filter(w => SAVED_WIDGETS.includes(w.name)).map(w => [w.name, w.value])); const properties = Object.fromEntries(PROPERTIES.filter(key => Object.hasOwn(node.properties || {}, key)).map(key => [key, node.properties[key]])); + const loras = cleanLoras(widgetValue(liveSource(node, 'loras'), 'adapters')); + const assets = cleanAssets(widgetValue(liveSource(node, 'media'), 'assets')); + if (loras) draft.loras = loras; + if (assets) draft.assets = assets; if (Object.keys(widgets).length) draft.widgets = clone(widgets); if (Object.keys(properties).length) draft.properties = clone(properties); return draft; @@ -72,9 +126,95 @@ export function applyPromptDraft(workflow, draft) { const versions = draft.versions; if (versions && typeof versions.original === 'string' && typeof versions.rewritten === 'string') node.properties = {...node.properties, freevideo_prompt_versions: clone(versions)}; + keepLists(workflow, node, draft); return workflow; } +// Puts the saved LoRA list and reference pictures back, but only where the graph has none: a project the browser +// still holds, or anything the user already chose, is never replaced by the older copy in the draft. +function keepLists(workflow, node, draft) { + // A card label without the card's name cannot be used: that row waits for a restore that has read the card. + const assets = (cleanAssets(draft.assets, true) || []).filter(row => !row.cast || typeof row.cast.name === 'string'), loras = cleanLoras(draft.loras) || []; + const media = savedSource(workflow, node, 'media'); + if (assets.length && media && Array.isArray(media.widgets_values) && !isList(media.widgets_values[0]) + && !media.properties?.[SWAP_KEY]) media.widgets_values[0] = JSON.stringify(assets); + if (!loras.length) return; + const stack = savedSource(workflow, node, 'loras'); + if (stack) { + if (Array.isArray(stack.widgets_values) && !isList(stack.widgets_values[0])) stack.widgets_values[0] = JSON.stringify(loras); + } else if (!node.inputs?.some(input => input.name === 'loras' && input.link != null)) addLoraStack(workflow, node, loras); +} + +// A LoRA node wired to the generate node's `loras` input, below the bundled layout. No effect without such an input. +// The launcher builds the same node for a project it carries over (launcher.js, currentStudioWorkflow); it cannot import this. +function addLoraStack(graph, node, rows) { + const input = node.inputs?.findIndex(row => row.name === 'loras') ?? -1; + if (!rows.length || input < 0) return false; + graph.links ||= []; + const id = Math.max(graph.last_node_id || 0, ...graph.nodes.map(row => Number(row.id) || 0)) + 1; + const link = Math.max(graph.last_link_id || 0, ...graph.links.map(row => row[0])) + 1; + graph.nodes.push({id, type: 'FreeVideoLoRAStack', pos: [60, 660], size: [460, 200], flags: {}, order: 2, mode: 0, + inputs: [{name: 'adapters', type: 'STRING', widget: {name: 'adapters'}, link: null}, {name: 'previous', type: 'FREEVIDEO_LORAS', link: null}], + outputs: [{name: 'loras', type: 'FREEVIDEO_LORAS', links: [link], slot_index: 0}], + properties: {'Node name for S&R': 'FreeVideoLoRAStack'}, widgets_values: [JSON.stringify(rows)]}); + graph.links.push([link, id, 0, node.id, input, 'FREEVIDEO_LORAS']); + node.inputs[input].link = link; + graph.last_node_id = id; graph.last_link_id = link; + return true; +} + +// What the draft names but this machine no longer has is left out: a LoRA file that is gone from the models folder, +// a reference picture that was deleted with the last work that used it. When a check cannot be made the row stays. +async function stillThere(api, draft) { + const result = {...draft}; + const loras = cleanLoras(draft.loras) || [], assets = cleanAssets(draft.assets) || []; + if (loras.length) { + try { + const reply = await api.fetchApi('/models/loras', {cache: 'no-store'}); + const names = reply.ok ? await reply.json() : null; + if (Array.isArray(names)) { + const have = new Set(names.map(name => String(name).replaceAll('\\', '/'))); + result.loras = loras.filter(row => have.has(row.name.replaceAll('\\', '/'))); + } + } catch { /* Keep the rows: the request line above Generate names a missing LoRA. */ } + } + if (assets.length) { + result.assets = (await Promise.all(assets.map(async row => { + const found = /^(.*?)(?: \[(input|output|temp)\])?$/.exec(row.file), path = found[1], kind = found[2] || 'input'; + const cut = path.lastIndexOf('/'); + const query = new URLSearchParams({filename: path.slice(cut + 1), type: kind, ...(cut > 0 ? {subfolder: path.slice(0, cut)} : {})}); + try { const reply = await api.fetchApi('/view?' + query, {method: 'HEAD', cache: 'no-store'}); return reply.status === 404 ? null : row; } + catch { return row; } + }))).filter(Boolean); + // A row that names a character card gets the card's name and description back from the library; a card that + // cannot be read takes its rows with it. + const ids = [...new Set(result.assets.map(row => row.cast?.id).filter(Boolean))]; + if (ids.length) { + let agent = null; + try { agent = await import('./agent_session.js'); } catch { /* No library: the rows go. */ } + const cards = new Map(await Promise.all(ids.map(async id => { + try { + const reply = await agent.agentGet(api, '/freevideo/agent/cast/' + encodeURIComponent(id)); + const card = reply.ok ? await reply.json() : null; + return [id, card && typeof card.name === 'string' ? card : null]; + } catch { return [id, null]; } + }))); + result.assets = result.assets.flatMap(row => { + if (!row.cast?.id) return [row]; + const card = cards.get(row.cast.id); + return card ? [{...row, cast: {id: card.id || row.cast.id, name: card.name, description: card.description || '', + ...(card.kind === 'setting' ? {setting: true} : card.kind === 'prop' ? {prop: true} : {})}}] : []; + }); + } + // A picture that is gone leaves the draft too, so its name is not kept after the file is. + if (result.assets.length < assets.length) { + addPatch({assets: result.assets.map(row => cleanAssets([row])[0])}); + await savePromptDraft(api); + } + } + return result; +} + // Baseline comes from the configured node, never the shared server draft. A stale // tab therefore contributes only its actual edits, including property resets. export function trackPromptDraft(node, onChange, project) { @@ -86,7 +226,7 @@ export function trackPromptDraft(node, onChange, project) { function combine(base, patch) { const value = {...(patch.project && (base?.schema !== 1 || (base.project && patch.project !== base.project)) ? patch.snapshot : base?.schema === 1 ? base : {schema: 1, text: null, versions: null})}; - for (const key of ['text', 'versions', 'project']) if (Object.hasOwn(patch, key)) value[key] = patch[key]; + for (const key of ['text', 'versions', 'project', 'loras', 'assets']) if (Object.hasOwn(patch, key)) value[key] = patch[key]; for (const group of ['widgets', 'properties']) if (patch[group]) { value[group] = {...value[group]}; for (const [key, entry] of Object.entries(patch[group])) { @@ -113,6 +253,7 @@ function collect(node, notify = true) { if (!equal(next.text, previous.text) || !equal(next.versions, previous.versions)) { patch.text = next.text; patch.versions = next.versions; } + for (const key of ['loras', 'assets']) if (next[key] && !equal(next[key], previous[key] ?? [])) patch[key] = next[key]; for (const group of ['widgets', 'properties']) { for (const key of new Set([...Object.keys(previous[group] || {}), ...Object.keys(next[group] || {})])) { if (!equal(previous[group]?.[key], next[group]?.[key])) { @@ -219,6 +360,6 @@ export async function restorePromptDraft(api, workflow, project = null) { const local = pending || sending ? mergePatches(sending, pending) : null; if (local && (!project || !local.project || local.project === project)) draft = combine(draft, local); // Unscoped schema-1 drafts predate project ownership and must migrate too. - if (!project || !draft?.project || draft.project === project) return applyPromptDraft(workflow, draft); + if (!project || !draft?.project || draft.project === project) return applyPromptDraft(workflow, draft?.schema === 1 ? await stillThere(api, draft) : draft); return workflow; } diff --git a/web/prompt_enhance.css b/web/prompt_enhance.css index bce1faf2..702dd099 100644 --- a/web/prompt_enhance.css +++ b/web/prompt_enhance.css @@ -19,7 +19,7 @@ .fv-enhance-status[data-state=error]{color:var(--fv-danger,#ff8a80);background:color-mix(in srgb,var(--fv-danger,#ff8a80) 7%,transparent)} .fv-enhance-status .fv-issue-button{min-height:28px;margin-top:8px;padding:4px 8px;font-size:12px} .fv-enhance-status .fv-issue-button:not([hidden]){display:flex;width:fit-content} -.fv-enhance-meter{position:relative;height:4px;margin-top:8px;border-radius:var(--fv-r-xs);background:#ffffff12;overflow:hidden} +.fv-enhance-meter{position:relative;height:4px;margin-top:8px;border-radius:var(--fv-r-xs);background:color-mix(in srgb,var(--fv-fg,#fff) 16%,transparent);overflow:hidden} .fv-enhance-meter>i{position:absolute;inset:0 auto 0 0;width:0;border-radius:inherit;background:var(--fv-accent,#6db8fa);transition:width .4s ease-out} .fv-enhance-meter[data-indeterminate=true]>i{width:32%;animation:fv-enhance-sweep 1.4s ease-in-out infinite} @keyframes fv-enhance-sweep{from{transform:translateX(-100%)}to{transform:translateX(320%)}} @@ -32,3 +32,12 @@ .fv-enhance button:focus-visible,.fv-enhance input:focus-visible{outline:2px solid var(--fv-accent,#6db8fa);outline-offset:2px} @keyframes fv-enhance-in{from{opacity:0;transform:translateY(-4px)}to{opacity:1;transform:none}} @media(prefers-reduced-motion:reduce){.fv-enhance *{transition:none;animation:none}} +/* "Undo" after a description was filled in (prompt from a picture or video): a small bordered key like Report a problem, the same in both views. */ +.fv-enhance-status button.fv-enhance-undo{display:inline-flex;align-items:center;min-height:28px;margin:8px 0 0 8px;padding:4px 10px;border:1px solid var(--fv-line,var(--fv-border,#45454a));border-radius:var(--fv-r-sm,8px);background:transparent;color:var(--fv-fg2,#bbb);font:inherit;font-size:12px;cursor:pointer} +.fv-enhance-status button.fv-enhance-undo:hover{color:var(--fv-fg,#eee);border-color:var(--fv-fg2,#bbb)} +.fv-enhance-status button.fv-enhance-undo[hidden]{display:none} +.fvs-console-status .fv-enhance-status button.fv-enhance-undo{margin:0;min-height:20px;height:20px;padding:0 var(--fv-sp-8)} +/* While a description is being written the box is read-only and dimmed in both views. */ +textarea[data-reversing=true]{opacity:.6} +/* The helper's Cancel row stays away while a description is being written: the Stop key is the control. */ +.fv-enhance-bar[data-reversing=true]{display:none!important} diff --git a/web/prompt_enhance.js b/web/prompt_enhance.js index c7699da3..6ff4d27f 100644 --- a/web/prompt_enhance.js +++ b/web/prompt_enhance.js @@ -129,14 +129,17 @@ export function createPromptEnhancer({node, input, editor, api, context, setText meter.setAttribute('role', 'progressbar'); meter.setAttribute('aria-valuemin', '0'); meter.setAttribute('aria-valuemax', '100'); // The shared "Report a problem" button, handed in by the page. // Feedback quotes the line without the names of the user's other programs. - let quoted = ''; + let quoted = '', undoState = null; const report = issueButton ? issueButton(t, () => ({where: ['Prompt enhancement', '提示词增强'], message: quoted, facts: memoryFacts})) : document.createElement('span'); report.hidden = true; - meter.append(fill); status.append(statusText, meter, report); + // "Undo" after a description was filled in (reverse prompt): a text key beside the line (after the report key: the line's children keep their places, and the two are never shown together). + const undoKey = el('button', t('Undo', '撤销'), 'fv-enhance-undo'); undoKey.type = 'button'; undoKey.hidden = true; + meter.append(fill); status.append(statusText, meter, report, undoKey); // One place sets what the status line says and how it looks. function show(text, state = '', fraction = null, quote = text) { if (downloadOnly) { publishModel({text: text || ''}); return; } statusText.textContent = text || ''; + undoKey.hidden = true; undoState = null; quoted = quote || ''; status.dataset.state = text ? state : ''; report.hidden = !text || state !== 'error'; @@ -181,14 +184,16 @@ export function createPromptEnhancer({node, input, editor, api, context, setText if (versions.value.enabled) void prestart.request(); // Available RAM the model needs; the server knows the usual case for this card. let ramBytes = 11 * 2 ** 30; - // Memory readings of a failed rewrite for the feedback form: numbers and states only. + // Readings of a failed rewrite for the feedback form: numbers, states and fixed check names only. let memoryFacts = null; const MEMORY_FACTS = ['gpu_total_bytes', 'gpu_free_before_load_bytes', 'gpu_allocator_budget_bytes', 'gpu_free_needed_text_only_bytes', 'gpu_free_needed_with_images_bytes', 'placement_refused', 'gpu_free_bytes', 'gpu_allocator_ooms', 'idle_release', 'idle_release_seconds', 'idle_release_gpu_free_before_bytes', 'idle_release_gpu_free_after_bytes', 'gpu_peak_allocated_bytes', 'gpu_peak_reserved_bytes', 'image_count', 'input_tokens', 'weights', 'vision_device', 'kv_reserve', 'stage', 'platform', 'gpu_non_allocator_reserve_bytes', 'extra_vram_reserve_bytes', - 'streamed_layers', 'available_memory_at_start_bytes', 'available_memory_before_load_bytes']; + 'streamed_layers', 'available_memory_at_start_bytes', 'available_memory_before_load_bytes', + 'gpu_name', 'gpu_capability', 'torch_version', 'transformers_version', 'cuda_version', + 'gpu_reserved_bytes', 'gpu_allocated_bytes', 'gpu_outside_allocator_bytes', 'gpu_alloc_retries', 'sdp_switches', 'oom_tried_bytes']; const factsOf = diagnostics => Object.fromEntries(MEMORY_FACTS.filter(key => ['number', 'string'].includes(typeof diagnostics?.[key])) .map(key => [key, diagnostics[key]])); // Where the worker failed: exception class and the last stack frames as module:function:line, no paths and no message text. @@ -196,8 +201,21 @@ export function createPromptEnhancer({node, input, editor, api, context, setText const failureOf = row => { const frames = (Array.isArray(row?.error_details) ? row.error_details : []).map(frame => [plainName(frame?.module), plainName(frame?.function), frame?.line]) .filter(([module, name, line]) => module && name && Number.isInteger(line)).slice(-5).map(([module, name, line]) => `${module}:${name}:${line}`); - return Object.assign(plainName(row?.exception) ? {failure_exception: row.exception} : {}, frames.length ? {failure_location: frames.join(' > ')} : {}); + return Object.assign(plainName(row?.exception) ? {failure_exception: row.exception} : {}, ['allocator', 'cuda_runtime'].includes(row?.oom_source) ? {oom_source: row.oom_source} : {}, + frames.length ? {failure_location: frames.join(' > ')} : {}); }; + // The output check that rejected a rewrite: its fixed name and category, never text of the prompt or the draft. + const CHECK_LABELS = {length: ['it came out too long or empty', '过长或为空'], structure: ['some sections were missing or out of place', '分段缺失或错位'], + timing: ['a time point was lost or went past the end of the video', '时间点丢失或超出视频时长'], + media: ['a media reference was left out or wrong', '漏掉或写错了素材引用'], text: ['quoted text was left out or changed', '漏掉或改动了引号里的文字'], + dialogue: ['the spoken lines were out of order', '台词顺序被打乱']}; + const checkOf = row => { + const found = row?.output_rejection, name = found?.condition; + return typeof name === 'string' && /^[a-z0-9_]{1,40}$/.test(name) && Object.hasOwn(CHECK_LABELS, found.category) + ? {name, category: found.category, retried: found.retried === true} : null; + }; + // The feedback carries only the check's name, its category and whether the retry had run; the local counts stay on this computer. + const checkFacts = check => ({check: check.name, check_category: check.category, check_retried: check.retried}); const gib = value => String(Math.round(value / 2 ** 30)); // Mentions are counted as the character descriptions they expand to, so the count can exceed what the box shows. const lengthOf = (error, english) => { @@ -231,7 +249,10 @@ export function createPromptEnhancer({node, input, editor, api, context, setText invalid_prompt: error?.characters ? t(`${lengthOf(error, true)}; enhancement supports up to 12,000. Shorten it or use the original.`, `${lengthOf(error, false)},增强最多支持 12,000 字符,请精简或使用原文。`) : t('Enter a prompt of up to 12,000 characters.', '请输入不超过 12,000 字符的提示词。'), - invalid_output: t('The rewrite was incomplete. Retry or use the original.', '改写结果不完整,请重试或使用原文。'), + invalid_output: error?.check + ? t(`The rewrite was incomplete: ${CHECK_LABELS[error.check.category][0]}. Retry or use the original.`, + `改写结果不完整:${CHECK_LABELS[error.check.category][1]}。请重试或使用原文。`) + : t('The rewrite was incomplete. Retry or use the original.', '改写结果不完整,请重试或使用原文。'), invalid_request: t('Rewriting does not support this model or aspect ratio. Change it or use the original.', '当前模型或画幅不支持改写,请更换或使用原文。'), context_length: t('The scene is too long for this model. Shorten it or use the original.', '内容超出改写模型容量,请精简或使用原文。'), out_of_memory: holderNames(error?.holders) @@ -255,7 +276,10 @@ export function createPromptEnhancer({node, input, editor, api, context, setText invalid_prompt: error?.characters ? t(`${lengthOf(error, true)}; rewriting supports up to 12,000. Shorten it before rewriting again.`, `${lengthOf(error, false)},改写最多支持 12,000 字符,精简后可再改写。`) : t('Rewriting supports prompts of up to 12,000 characters.', '改写只支持不超过 12,000 字符的提示词。'), - invalid_output: t('The rewrite was incomplete.', '改写结果不完整。'), + invalid_output: error?.check + ? t(`The rewrite was incomplete: ${CHECK_LABELS[error.check.category][0]}.`, + `改写结果不完整:${CHECK_LABELS[error.check.category][1]}。`) + : t('The rewrite was incomplete.', '改写结果不完整。'), invalid_request: t('Rewriting does not support this model or aspect ratio.', '当前模型或画幅不支持改写。'), context_length: t('The scene is too long for the rewrite model.', '内容超出改写模型容量。'), out_of_memory: holderNames(error?.holders) @@ -294,7 +318,16 @@ export function createPromptEnhancer({node, input, editor, api, context, setText bar.dataset.enabled = String(Boolean(versions.value.enabled)); bar.dataset.busy = String(Boolean(running)); } function apply() { input.value = versions.text(); setText(input.value); save(); render(); } + let silent = false, undoTimer = 0; function changed() { + if (silent) return; + // Ctrl+Z (or typing the old words back) while Undo is offered brings the saved versions back too, as the Undo key does. + if (undoState && !undoKey.hidden && input.value === undoState.before) { + const {snapshot} = undoState; show(''); + versions.value = snapshot; setText(input.value); save(); render(); + return; + } + if (!undoKey.hidden) show(''); if (waiting) { waiting = false; show(''); } versions.edit(input.value, replacing || !input.value.trim()); replacing = false; save(); render(); } @@ -358,8 +391,9 @@ export function createPromptEnhancer({node, input, editor, api, context, setText } if (row.phase === 'complete') return row; if (row.phase === 'failed') { - memoryFacts = row.error === 'out_of_memory' ? {...factsOf(row.diagnostics), ...failureOf(row)} : null; - throw Object.assign(new Error(row.error || 'rewrite_failed'), {ramBytes: row.diagnostics?.ram_required_bytes, holders: row.gpu_holders}); + const check = row.error === 'invalid_output' ? checkOf(row) : null; + memoryFacts = row.error === 'out_of_memory' ? {...factsOf(row.diagnostics), ...failureOf(row)} : check ? checkFacts(check) : null; + throw Object.assign(new Error(row.error || 'rewrite_failed'), {ramBytes: row.diagnostics?.ram_required_bytes, holders: row.gpu_holders, check}); } if (row.phase === 'cancelled') throw new Error(action === 'install' ? 'download_failed' : 'cancelled'); if (disposed) throw new Error('cancelled'); @@ -373,7 +407,7 @@ export function createPromptEnhancer({node, input, editor, api, context, setText show(names ? t(`Waiting for ${short}\u00a0GiB more graphics memory to rewrite. In use: ${names}.`, `显存不足,再空出 ${short}\u00a0GiB 后自动改写。正在占用:${names}。`) : t(`Waiting for ${short}\u00a0GiB more graphics memory to rewrite.`, `显存不足,再空出 ${short}\u00a0GiB 后自动改写。`), 'progress'); } else if (action !== 'install') { - clock?.set(row.phase === 'rewriting' ? 'rewriting' : 'preparing'); + clock?.set(row.phase === 'rewriting' ? 'rewriting' : 'preparing', row.phase); } await new Promise(resolve => setTimeout(resolve, 400)); } @@ -483,6 +517,138 @@ export function createPromptEnhancer({node, input, editor, api, context, setText render(); return running; } + // ---- Reverse prompt: a picture or a video becomes a description in the box. ---- + // Pictures: one step, the existing ask action. Videos: the reverse action (frames with their times, then the camera), + // and where the view writes video prompts (shapeVideo) the existing rewrite action turns it into the model's format. + const REVERSE_PICTURE = 'Describe this image so that a text-to-image model can recreate it as closely as possible. Cover the main subjects and their appearance, age, clothing, pose and expression; every object and where it is in the frame; the background and setting; lighting and time of day; colour palette; camera angle, shot size and lens feel; and the medium or art style (photo, illustration, 3D render, ink painting and so on). Copy any visible text exactly, inside double quotes. Write one flowing paragraph of plain description, with no lists and no preamble, about 120 to 200 words.'; + const reverseErrorText = error => isNetworkTypeError(error) ? networkText(error) : ({ + busy: t('Finish the current queue before writing a prompt from media.', '请等待当前队列完成后再生成提示词。'), + unreadable_video: t('Could not read frames from this video. Choose another file.', '无法读取这个视频的画面,请换一个文件。'), + unsupported_media: t('Only pictures and videos can be turned into a prompt.', '只能用图片或视频生成提示词。'), + invalid_media: t('Could not read this picture. Choose another file.', '无法读取这张图片,请换一个文件。'), + out_of_memory: holderNames(error?.holders) + ? t(`Not enough graphics memory. In use: ${holderNames(error.holders)}. Close them and try again.`, `显存不足,无法生成提示词。正在占用:${holderNames(error.holders)}。关闭后再试。`) + : t('Not enough graphics memory. Close other GPU apps and try again.', '显存不足,请关闭其他显卡程序后再试。'), + ram_space: t(`Loading needs about ${gib(error?.ramBytes || ramBytes)} GiB of free RAM. Close other programs and try again.`, `加载需约 ${gib(error?.ramBytes || ramBytes)} GiB 可用内存,请关闭其他程序后再试。`), + timeout: t('Took too long. Try again.', '生成提示词超时,请重试。'), + invalid_output: t('The result was incomplete. Try again.', '结果不完整,请重试。'), + context_length: t('The result was incomplete. Try again.', '结果不完整,请重试。'), + download_failed: t('Download paused. Retry to resume.', '下载已暂停,重试可继续。'), + disk_space: t('Not enough disk space for the optional model.', '可选模型的磁盘空间不足,请清理后重试。'), + worker_cleanup_failed: t('The process could not close. Restart FreeVideo before generating.', '生成提示词的进程未能退出,请重启 FreeVideo 后再生成。'), + cancelled: t('Stopped. Your prompt is unchanged.', '已停止,原文已保留。'), + not_enabled: t('Not enabled. Your prompt is unchanged.', '未启用,原文已保留。'), + }[error?.message] || t(`Could not write the prompt${reasonOf(error) ? `: ${reasonOf(error)}` : ''}. Try again.`, `暂时无法生成提示词${reasonOf(error) ? `。原因:${reasonOf(error)}。` : ''}请重试。`)); + const reverseListeners = new Set(); + let reverseState = {state: 'idle', fraction: 0, text: ''}; + const publishReverse = change => { + reverseState = {...reverseState, noted: false, ...change}; for (const listener of reverseListeners) listener(reverseState); + globalThis.dispatchEvent?.(new CustomEvent('freevideo-prompt-job', {detail: {active: reverseState.state === 'running', fraction: reverseState.fraction}})); + }; + // Stage lines and their expected seconds (measured: reading ~2 s, describing ~8 s with the model loaded, camera ~1 s, + // shaping the H3 prompt ~10 s); the bar runs on those and turns to a back-and-forth when they are overrun. + function reverseClock(stages) { + const total = stages.reduce((sum, row) => sum + row.seconds, 0), started = Date.now(); + let stage = stages[0].key, paused = false; + const tick = () => { + if (paused || disposed || cancelling) return; + const elapsed = (Date.now() - started) / 1000; + const row = stages.find(item => item.key === stage) || stages[0]; + const before = stages.slice(0, stages.indexOf(row)).reduce((sum, item) => sum + item.seconds, 0); + const within = Math.min(row.seconds, Math.max(0, elapsed - before)); + const fraction = elapsed > total * 1.5 ? null : Math.min(.95, (before + within) / total); + show(t(row.en, row.zh), 'progress', fraction); + publishReverse({state: 'running', fraction: fraction === null ? null : fraction, text: t(row.en, row.zh)}); + }; + const timer = setInterval(tick, 250); tick(); + return { + set(_, raw) { const next = ({starting: 'read', loading: 'read', preparing: 'read', describing: 'describe', camera: 'camera', rewriting: 'shape'})[raw]; if (next && stages.some(item => item.key === next) && stage !== next) { stage = next; tick(); } }, + pause() { paused = true; }, restart() { paused = false; }, stop() { clearInterval(timer); }, + }; + } + async function reverse(source, {shapeVideo = false} = {}) { + if (running) return running; + // Shaping into the model's format only where enhancement is already on: reversing never changes that switch. + shapeVideo = shapeVideo && Boolean(versions.value.enabled); + const language = t('en', 'zh'); + cancelling = false; memoryFacts = null; + const before = input.value, snapshot = JSON.parse(JSON.stringify(versions.value)); + const video = source.kind === 'video'; + const stages = video + ? [{key: 'read', en: 'Reading the frames…', zh: '正在读取画面…', seconds: 2}, {key: 'describe', en: 'Describing the video…', zh: '正在描述视频…', seconds: 8}, + {key: 'camera', en: 'Looking at the camera movement…', zh: '正在看镜头运动…', seconds: 1}, ...(shapeVideo ? [{key: 'shape', en: 'Shaping it into a video prompt…', zh: '正在整理成视频描述…', seconds: 10}] : [])] + : [{key: 'describe', en: 'Describing the picture…', zh: '正在描述图片…', seconds: 8}]; + // The job is under way: the box is read-only and dimmed, the key says Stop, Generate waits. + const begin = () => { + input.readOnly = true; input.dataset.reversing = 'true'; element.dataset.reversing = 'true'; bar.dataset.reversing = 'true'; + publishReverse({state: 'running', fraction: 0, text: ''}); + }; + const execute = async () => { + if (disposed || cancelling) throw new Error('cancelled'); + let described, shaped = '', clock = null; + try { + const info = await readModel(); + if (disposed || cancelling) throw new Error('cancelled'); + // The consent card (model not installed) is asked while everything is still idle; the job starts when it is accepted. + if (!info.ready) show(''); + // Declining the question is not a stop: nothing was started, so the line says the model is not enabled. + if (!await installModel(info)) throw new Error(disposed || cancelling ? 'cancelled' : 'not_enabled'); + begin(); + clock = reverseClock(stages); + const file = await source.upload(); + if (disposed || cancelling) throw new Error('cancelled'); + if (video) { + described = (await poll('reverse', {file, frames: 16, lines: [], language}, clock)).text; + if (shapeVideo) { + clock.set('', 'rewriting'); + const scene = context(); + shaped = (await poll('rewrite', {text: described, seconds: scene.seconds, media: []}, clock)).text; + } + } else { + const answer = (await poll('ask', {questions: [{text: language === 'zh' ? REVERSE_PICTURE + ' Write the description in Chinese.' : REVERSE_PICTURE, images: [{file}]}], format: 'text', max_tokens: 400}, clock)).answers?.[0]; + if (!answer || answer.error || !String(answer.text || '').trim()) throw new Error('invalid_output'); + described = answer.text.trim(); + } + } finally { clock?.stop(); } + if (disposed || cancelling) throw new Error('cancelled'); + fillFrom(described, shaped); + return true; + }; + function fillFrom(described, shaped) { + versions.adopt(described); + if (shaped) { + // The Original tab holds the readable description, the Enhanced tab the model's own format; Generate uses the latter. + versions.value.useOriginal = false; + const restored = restore(shaped), scene = context(); + versions.accept(versions.key(scene), scene, display(restored), restored); + } + write(versions.text()); + setText(input.value); save(); render(); + if (before.trim()) { + show(t('Description filled in.', '已填入描述。'), 'note'); undoKey.hidden = false; undoState = {before, snapshot}; + undoKey.onclick = () => { versions.value = snapshot; write(before); setText(input.value); save(); render(); show(''); }; + clearTimeout(undoTimer); undoTimer = setTimeout(() => { if (!undoKey.hidden) show(''); }, 10000); + } else show(''); + } + function write(text) { + // Through the editing history, so Ctrl+Z brings the old text back; `silent` keeps the page's own bookkeeping out of it. + silent = true; + try { + input.readOnly = false; input.focus({preventScroll: true}); input.select(); + if (!(globalThis.document?.execCommand?.('insertText', false, text) && input.value === text)) input.value = text; + } finally { silent = false; } + } + running = Promise.resolve().then(execute).then(() => { publishReverse({state: 'done'}); return true; }).catch(error => { + const message = error?.message; + const quiet = message === 'cancelled' || message === 'not_enabled'; + show(reverseErrorText(error), quiet ? 'note' : 'error', null, + reverseErrorText({message, ramBytes: error?.ramBytes})); + publishReverse({state: quiet ? 'idle' : 'error', fraction: 0, noted: quiet}); + throw error; + }).finally(() => { running = null; cancelling = false; install.hidden = true; input.readOnly = false; delete input.dataset.reversing; delete element.dataset.reversing; delete bar.dataset.reversing; render(); }); + render(); + return running; + } toggle.onchange = () => { versions.value.enabled = toggle.checked; if (!toggle.checked) { cancelJob().catch(() => {}); versions.select('original'); apply(); } @@ -497,7 +663,8 @@ export function createPromptEnhancer({node, input, editor, api, context, setText versions.value.selected = 'original'; apply(); show(t(`Generated with the original prompt. ${stale ? errorText(error) : fallbackText(error)}`, `已用原文生成。${stale ? errorText(error) : fallbackText(error)}`), 'note'); } - return {element, chip, bar, model: {read: readModel, download: downloadModel, subscribe(listener) { + return {element, chip, bar, reverse, stop: () => cancelJob().catch(() => {}), get reversing() { return reverseState.state === 'running'; }, + onReverse(listener) { reverseListeners.add(listener); listener(reverseState); return () => reverseListeners.delete(listener); }, model: {read: readModel, download: downloadModel, subscribe(listener) { modelListeners.add(listener); listener(modelState); return () => modelListeners.delete(listener); }}, async beforeGenerate() { diff --git a/web/random_id.js b/web/random_id.js new file mode 100644 index 00000000..58d9698e --- /dev/null +++ b/web/random_id.js @@ -0,0 +1,13 @@ +// A random version 4 UUID that works on every page FreeVideo serves. crypto.randomUUID exists only in a secure context +// (https, localhost, 127.0.0.1); a page opened from another device by its LAN address over http has +// crypto.getRandomValues but not randomUUID, and calling it there failed every upload (#1097). +// No imports and no DOM, so Node tests load it as it is. +export function randomUUID() { + const crypto = globalThis.crypto; + if (typeof crypto?.randomUUID === 'function') return crypto.randomUUID(); + const bytes = crypto.getRandomValues(new Uint8Array(16)); + bytes[6] = (bytes[6] & 0x0f) | 0x40; // version 4 + bytes[8] = (bytes[8] & 0x3f) | 0x80; // the RFC 4122 variant + const hex = Array.from(bytes, byte => byte.toString(16).padStart(2, '0')).join(''); + return `${hex.slice(0, 8)}-${hex.slice(8, 12)}-${hex.slice(12, 16)}-${hex.slice(16, 20)}-${hex.slice(20)}`; +} diff --git a/web/result_actions.js b/web/result_actions.js index 2164c0d4..2f18d8cb 100644 --- a/web/result_actions.js +++ b/web/result_actions.js @@ -7,6 +7,7 @@ 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'; +import { copyText as copyClipboardText } from './clipboard_text.js'; const css = document.createElement('link'); css.rel = 'stylesheet'; css.href = new URL('./result_actions.css', import.meta.url).href; document.head.append(css); @@ -180,14 +181,8 @@ export function actionsUnavailable(bar) { } } -// Writes text to the clipboard; resolves false when neither the clipboard API nor the old copy command is allowed. -export async function copyText(text) { - try { await navigator.clipboard.writeText(text); return true; } catch { /* fall through to the selection copy */ } - const area = document.createElement('textarea'); area.value = text; area.setAttribute('readonly', ''); - area.style.cssText = 'position:fixed;top:0;left:0;opacity:0'; - document.body.append(area); area.select(); - try { return document.execCommand('copy'); } catch { return false; } finally { area.remove(); } -} +// The clipboard copy lives in clipboard_text.js so light modules can use it; callers that import it from here keep working. +export const copyText = text => copyClipboardText(text); // Fills the prompt, size and duration of an earlier video back into the panel. It is offered only when // the video kept its prompt and the panel does not already hold the same settings. Resolves to the button or null. diff --git a/web/selection.css b/web/selection.css index 9b3190b1..96f5557d 100644 --- a/web/selection.css +++ b/web/selection.css @@ -39,3 +39,10 @@ html.fv-dragging,html.fv-dragging *{-webkit-user-select:none!important;user-sele /* FreeVideo's own selection colour. */ :is(.fv-app,dialog.fv-studio,.fv-view-navigation,.fv-setup,.fv-library) ::selection{background:var(--fv-selection,var(--fv-accent-soft,rgb(79 140 255 / .3)));color:inherit} + +/* Reading (this sheet is the one every FreeVideo surface loads): the explanation in a failure card or a notice bar + wraps so its last line is not one or two characters on their own ("试。"). Only the wrapping style is set, not + whether the text wraps, and with zero specificity, so a part's own balance or nowrap stays; browsers without + text-wrap-style wrap as before. */ +:where(.fv-failure p:not(.fv-failure-cause,.fv-failure-location),.fv-image-failure-reason,.fv-ed-failure-reason,.fv-chat-error, + .fv-chat-notice,.fv-chat-job[data-mode=failed]>p,.fv-ed-notice-text,.fv-update-notice>span,.fv-lan-reason){text-wrap-style:pretty} diff --git a/web/settings_room.js b/web/settings_room.js index 3aea953a..86ab3c65 100644 --- a/web/settings_room.js +++ b/web/settings_room.js @@ -7,6 +7,7 @@ // setup.js re-exports openSetup from here, so every caller (top bar, failure cards, palette) opens this room. import { setTip } from './tip_words.js'; import { cutTip } from './cut_tip.js'; +import { copyText } from './clipboard_text.js'; import { api } from "../../scripts/api.js"; import './fv_select.js'; import { compatibilityCard } from './compatibility.js'; @@ -37,6 +38,7 @@ if (typeof document !== 'undefined') { import { nearestAllowed } from './field_note.js'; import { cn, t, INSTALLED_HINT, gib, bytesText, atLeast, WAIT_REFUSAL, reportable, reportText, failureText, setupError, SECTIONS, sectionOf } from './settings_words.js'; +import { languageUrl } from './i18n.js'; export { failureText, sectionOf, SECTIONS, bytesText }; let current; @@ -232,7 +234,7 @@ export async function openSetup(options) { const more = fold({title: t('Details and logs', '详细信息与日志'), sub: t('Kept for reporting a problem', '提交问题时可附上'), cls: 'st-logs'}); const log = el("pre", 'st-pre fv-copyable'); more.body.append(log); const logCopy = button(t('Copy', '复制'), {iconName: 'copy', cls: 'is-sm'}); - logCopy.onclick = event => { event.preventDefault(); event.stopPropagation(); navigator.clipboard?.writeText(log.textContent).then(() => { setText(logCopy, t('Copied', '已复制')); setTimeout(() => setText(logCopy, t('Copy', '复制')), 1500); }, () => {}); }; + logCopy.onclick = event => { event.preventDefault(); event.stopPropagation(); void copyText(log.textContent).then(ok => { if (!ok) return; setText(logCopy, t('Copied', '已复制')); setTimeout(() => setText(logCopy, t('Copy', '复制')), 1500); }); }; tip(logCopy, t('Copy', '复制'), t('Copy the log for a report', '复制日志,用于提交问题')); more.end.append(logCopy); more.element.hidden = true; models.append(hero, more.element); @@ -556,7 +558,7 @@ export async function openSetup(options) { const langNote = slot(); const langReload = button(t('Reload now', '立即重新载入'), {kind: 'fill', cls: 'is-sm'}); langReload.hidden = true; langNote.textContent = t('Changing the language reloads the page; generations keep running.', '切换语言会重新载入页面,正在进行的生成不受影响。'); langSelect.onchange = () => { langReload.hidden = langSelect.value === (cn ? 'zh' : 'en'); }; - langReload.onclick = () => { const url = new URL(location.href); url.searchParams.set('freevideo_lang', langSelect.value); location.replace(url.href); }; + langReload.onclick = () => { const url = languageUrl(location.href, langSelect.value); location.replace(url.href); }; tip(langReload, t('Reload now', '立即重新载入'), t('Reload the page in the chosen language', '以所选语言重新载入页面')); const langRow = row({iconName: 'globe', title: t('Interface language', '界面语言'), end: [segmented(langSelect, {label: t('Language', '语言'), tips: {zh: t('Show the interface in Chinese', '界面显示为中文'), en: t('Show the interface in English', '界面显示为英文')}})]}); const langFoot = el('div', 'st-foot'); langFoot.append(langNote, langReload); @@ -1017,7 +1019,7 @@ export async function openSetup(options) { r.sub.className = 'is-accent'; r.sub.textContent = s.paused ? pausedText(s) : `${Math.floor(s.fraction * 100)}% · ${gb(s.done)} / ${gb(s.total)} GiB`; - act.hidden = false; + act.hidden = !!s.locked; // waiting for a setup, update or cleanup: nothing to press if (s.paused) { // Waiting for a video or a picture: the user may go on with the download now. act.className = 'st-btn is-fill'; act.replaceChildren(icon('down', 'fv-i s'), el('span', 'st-btn-t', t('Continue download', '继续下载'))); diff --git a/web/settings_words.js b/web/settings_words.js index f220cb08..fa1149ab 100644 --- a/web/settings_words.js +++ b/web/settings_words.js @@ -1,10 +1,8 @@ // Settings' words and rules without the page: the language, sizes, what each installer refusal means and what to do // next, and the pages with the old names callers still pass. No DOM, so tests/settings_words.mjs runs them in Node. -const languageOverride = typeof location !== 'undefined' - ? new URLSearchParams(location.search).get('freevideo_lang') : null; -export const cn = languageOverride === 'zh' || (languageOverride !== 'en' - && String(globalThis.navigator?.language || '').toLowerCase().startsWith('zh')); -export const t = (en, zh) => cn ? zh : en; +import { isChinese, translator } from './i18n.js'; +export const cn = isChinese(); +export const t = translator(cn); export const INSTALLED_HINT = {en: 'Already installed. To reinstall, click Check installation first.', zh: '已装好。要重装,请先点“检查安装”。'}; export const gib = n => Number.isFinite(n) ? (n / 2 ** 30).toFixed(1) + " GiB" : "—"; // Plan sizes pick their unit, so a few-MB repair does not read as "0.0 GiB". diff --git a/web/studio.css b/web/studio.css index f3e63326..09692ba5 100644 --- a/web/studio.css +++ b/web/studio.css @@ -269,7 +269,7 @@ .fv-studio .fv-chain-part-tag:empty{display:none} .fv-studio .fv-chain-part-tag[data-kind=error]{color:var(--fv-warning);white-space:normal;max-width:16em;text-align:right} .fv-studio .fv-chain-part-tag[data-kind=failed]{color:var(--fv-danger)} -@media(max-width:680px){.fv-studio .fv-chain-parts{grid-template-columns:auto minmax(0,1fr) auto;column-gap:8px}.fv-studio .fv-chain-part{row-gap:0;padding-left:4px}.fv-studio .fv-chain-part .fv-chain-part-meta{grid-column:1;grid-row:2;align-self:center;min-height:32px;margin:4px 0;padding:0;display:flex;align-items:center}.fv-studio .fv-chain-part :is(.fv-chain-part-text,.fv-chain-part-edit){grid-column:2}.fv-studio .fv-chain-part-tag{grid-column:3;text-align:right}.fv-studio .fv-chain-part .fv-chain-part-redo{grid-column:2/4;grid-row:2;justify-self:end;margin:4px 0}} +@media(max-width:680px){.fv-studio .fv-chain-parts{grid-template-columns:auto minmax(0,1fr) auto;column-gap:8px}.fv-studio .fv-chain-part{row-gap:0;padding-left:4px}.fv-studio .fv-chain-part .fv-chain-part-meta{grid-column:1;grid-row:2;align-self:center;min-height:32px;margin:4px 0;padding:0;display:flex;align-items:center}.fv-studio .fv-chain-part :is(.fv-chain-part-text,.fv-chain-part-edit){grid-column:2}.fv-studio .fv-chain-part-tag{grid-column:3;text-align:right}.fv-studio .fv-chain-part-tag[data-kind=error]{grid-column:1/-1;grid-row:3;max-width:none;padding:0 8px 4px 0;text-align:left}.fv-studio .fv-chain-part .fv-chain-part-redo{grid-column:2/4;grid-row:2;justify-self:end;margin:4px 0}} .fv-studio .fv-request-assets{font-size:12px;line-height:1.5;margin:0 0 8px} .fv-lora-problem{grid-column:var(--lora-lead,2)/span 3;grid-row:4;display:flex;flex-direction:column;align-items:flex-start;gap:6px;font-size:var(--fv-micro)}.fv-lora-problem p{margin:0;color:var(--fv-danger)}.fv-lora-problem.fv-lora-partial{color:var(--fv-muted)}.fv-lora-problem[hidden]{display:none}.fv-lora-why summary{cursor:pointer;color:var(--fv-muted)}.fv-lora-why pre{margin:6px 0 0;white-space:pre-wrap;word-break:break-all;color:var(--fv-muted);font:inherit;font-family:ui-monospace,monospace}.fv-lora-row[data-unusable=true] select{color:var(--fv-muted)} diff --git a/web/studio.js b/web/studio.js index 05e4855a..3b5d92cc 100644 --- a/web/studio.js +++ b/web/studio.js @@ -34,7 +34,7 @@ import { problem as timedProblem, timedText, parse as timedParse } from './timed import { castInRows, expandCast, mentionHandle, mentionState, mentionedIds, restoreCast, withCharacter, MAX_PICTURES_EACH } from './cast_mention.js'; import { attachMentionOverlay } from './cast_overlay.js'; import { openCastLibrary } from './cast_source.js'; -import { uploadMedia } from './media_upload.js'; +import { mediaName, uploadMedia } from './media_upload.js'; import { reconcileLoraTriggers, promptLines } from './lora_triggers.js'; import { createVerdicts, describeVerdict, feedbackDraft } from './lora_check.js'; import { continuationUpscale, createSamplingEffort, effortFor, effortsFrom, passSwitch, stepCacheOf, upscaleOf } from './sampling_effort.js'; @@ -80,12 +80,10 @@ import { toast, toastHeight } from './notifications.js'; import { mediaQueue } from './work_media.js'; import { userMessage } from './user_message.js'; import { fieldNote } from './field_note.js'; +import { isChinese, translator } from './i18n.js'; -const languageOverride = typeof location !== 'undefined' - ? new URLSearchParams(location.search).get('freevideo_lang') : null; -const cn = languageOverride === 'zh' || (languageOverride !== 'en' - && String(navigator.language || '').toLowerCase().startsWith('zh')); -const t = (en, zh) => cn ? zh : en; +const cn = isChinese(); +const t = translator(cn); // A dropped connection gets one plain sentence, not the browser's "Failed to fetch". const shownMessage = error => isNetworkTypeError(error) ? connectionLostText(t) : error.message; // The usual LoRA strength range is -4 to 4; a value the user types by hand may go further, up to 100. @@ -176,7 +174,8 @@ function createChainPartList(t, save, {onShow = () => {}, onHide = () => {}, red 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); + // A redo refused for its changed settings is told on the card; its line stays the short one. + const said = error.code === 'redo_request_changed' ? null : 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); @@ -758,7 +757,7 @@ export function openStudio(node, {extendFrom = null} = {}) { current = {node, dialog}; const cleanup = []; let firstStart = null, exampleFocused = false; // The console (studio_console.js) is put together once every control exists; until then nothing reads it. - let consoleUI = null, promptLibrary = null; + let consoleUI = null, promptLibrary = null, reverseKey = null, reversePick = null; // Set while the editor borrows this panel's bar (current.borrow below). let borrowed = null; // Frame & size picker and the stage's outline of a new frame (set with the size tray). @@ -2512,7 +2511,8 @@ export function openStudio(node, {extendFrom = null} = {}) { ? t('Joining the parts…', '正在接合各段…') : chain?.state === 'queued' ? (chain.waiting ? waitingText(chain.waiting, t) : t('Queued…', '排队中…')) : t(`Generating part ${position.index + 1}…`, `正在生成第 ${position.index + 1} 段…`); - generate.disabled = submitting || chainWait || (lengthControl.blocked && !lengthControl.retryable) || (runMode === 'loop' && queueState?.looping); + generate.disabled = submitting || chainWait || (lengthControl.blocked && !lengthControl.retryable) || (runMode === 'loop' && queueState?.looping) || enhancer.reversing; + paintReverse?.(); // Planning the parts and adding a batch are different waits; a count is only shown when the queue really has one. const adding = queueState?.batch ? t(`Adding ${Math.min(queueState.batch.done + 1, queueState.batch.total)}/${queueState.batch.total}…`, `正在添加 ${Math.min(queueState.batch.done + 1, queueState.batch.total)}/${queueState.batch.total}…`) @@ -2543,6 +2543,7 @@ export function openStudio(node, {extendFrom = null} = {}) { const why = !generate.disabled ? '' : submitting ? t('Adding to the queue. One moment.', '正在加入队列,请稍候') : chainWait ? t('Parts are generating. Wait, or cancel them in the queue.', '分段视频生成中,完成或在队列里取消后可再生成') + : enhancer.reversing ? t('Writing the prompt. One moment.', '正在生成提示词,请稍候') : lengthControl.blocked ? lengthControl.message || '' : t('A loop is running. Stop it to start again.', '正在循环生成,停止后可重新开始'); const lengthSaid = lengthControl.blocked && !videoMissing ? lengthControl.visibleMessage : ''; @@ -3522,6 +3523,37 @@ export function openStudio(node, {extendFrom = null} = {}) { return problems.join(' · '); }}); promptTools.prepend(promptLibrary.button); + // Prompt from a picture or video: the key left of the history key; the file only feeds the description (it is not added to the media). + // A video is read, then shaped into the model's own format (the Original tab keeps the readable description). + reverseKey = el('button', null, 'fvs-library-button fv-prompt-reverse'); reverseKey.type = 'button'; + reversePick = el('input'); reversePick.type = 'file'; reversePick.accept = 'image/*,video/*'; reversePick.hidden = true; + const reverseIcon = ''; + const stopIcon = ''; + const reverseQueueWhy = () => queueState?.running || queueState?.pending?.length ? t('Finish the current queue before writing a prompt from media.', '请等待当前队列完成后再生成提示词。') : ''; + function startReverse(file) { + const kind = file.type?.startsWith('video/') ? 'video' : file.type?.startsWith('image/') ? 'image' : 'other'; + enhancer.reverse({kind, upload: async () => { if (kind === 'other') throw new Error('unsupported_media'); return mediaName(await uploadMedia(api, file)); }}, {shapeVideo: true}).catch(() => {}); + } + function paintReverse() { + if (!reverseKey) return; + const on = enhancer.reversing, why = reverseQueueWhy(); + reverseKey.dataset.state = on ? 'running' : ''; + reverseKey.setAttribute('aria-disabled', String(!on && !!why)); + reverseKey.setAttribute('aria-label', on ? t('Stop', '停止') : t('Prompt from a picture or video', '从图片或视频生成提示词')); + reverseKey.dataset.fvTipName = on ? t('Stop', '停止') : t('Prompt from a picture or video', '从图片或视频生成提示词'); + if (on) delete reverseKey.dataset.fvTipUse; else reverseKey.dataset.fvTipUse = t('Pick a picture or video; its description fills the box', '选一张图片或一段视频,生成的描述填入描述框'); + if (!on && why) reverseKey.dataset.fvTipWhy = why; else delete reverseKey.dataset.fvTipWhy; + reverseKey.title = [reverseKey.dataset.fvTipName, reverseKey.dataset.fvTipUse].filter(Boolean).join(' · '); + const html = on ? stopIcon : reverseIcon; if (reverseKey.dataset.icon !== String(on)) { reverseKey.innerHTML = html; reverseKey.dataset.icon = String(on); } + } + reverseKey.addEventListener('click', () => { if (enhancer.reversing) { enhancer.stop(); return; } if (reverseKey.getAttribute('aria-disabled') !== 'true') reversePick.click(); }); + reversePick.onchange = () => { const file = reversePick.files[0]; reversePick.value = ''; if (file) startReverse(file); }; + paintReverse(); + cleanup.push(enhancer.onReverse(() => { paintReverse(); updateRunButton(); })); + promptTools.prepend(reverseKey); promptEditor.append(reversePick); + // A picture or video dropped on the box writes the description from it. + prompt.addEventListener('dragover', event => { if (event.dataTransfer?.types?.includes('Files')) { event.preventDefault(); event.stopPropagation(); } }); + prompt.addEventListener('drop', event => { const file = event.dataTransfer?.files?.[0]; if (!file) return; event.preventDefault(); event.stopPropagation(); if (!enhancer.reversing && !reverseQueueWhy()) startReverse(file); }); cleanup.push(() => promptLibrary.dispose()); prompt.addEventListener('keydown', event => { if ((event.metaKey || event.ctrlKey) && event.key === 'ArrowUp' && !event.isComposing) { event.preventDefault(); promptLibrary.show('history'); } @@ -3552,6 +3584,17 @@ export function openStudio(node, {extendFrom = null} = {}) { const enhanceStatus = enhancer.element.querySelector('.fv-enhance-status'); if (enhanceStatus) consoleUI.slot.append(enhanceStatus); enhancer.chip.after(enhancer.bar); + // At phone width the prompt tools stand in a column beside the box, and a third key would make the console taller than it + // is without reverse: there the key sits in the options row, right of Enhance, as an icon (same key, same words). + const reversePhone = window.matchMedia?.('(max-width:760px)'); + const placeReverse = () => { + const inRow = Boolean(reversePhone?.matches); + // In the row it is one of the round keys (like LoRA and Settings); in the tools column it is a library-style key. + reverseKey.classList.toggle('fvs-chip', inRow); reverseKey.classList.toggle('fvs-library-button', !inRow); + if (inRow) enhancer.chip.after(reverseKey); else promptTools.prepend(reverseKey); + }; + placeReverse(); reversePhone?.addEventListener?.('change', placeReverse); + cleanup.push(() => reversePhone?.removeEventListener?.('change', placeReverse)); consoleUI.trays.querySelector('[data-tray=size] .fvs-tray-title')?.append(canvasLock); consoleUI.element.classList.add('sgf-avoid'); mention.dataset.fvTipName = t('Mention', '引用'); diff --git a/web/studio_chain.js b/web/studio_chain.js index 02005eaa..344dd13b 100644 --- a/web/studio_chain.js +++ b/web/studio_chain.js @@ -19,6 +19,12 @@ export function chainPosition(chain, message = {}) { return {index: Math.min(Math.max(0, index), Math.max(0, count - 1)), count}; } +// crypto.randomUUID exists on secure pages only; a page opened from another computer has none. +function requestName() { + return globalThis.crypto?.randomUUID?.() + ?? Array.from(globalThis.crypto.getRandomValues(new Uint8Array(16)), byte => byte.toString(16).padStart(2, '0')).join(''); +} + // A fallback part is explicitly distinct from a joined partial result. export function readChainResult(chain) { if (!chain) return null; @@ -97,7 +103,7 @@ export function singleRunSnapshot(snapshot, node, plan) { export function createStudioChain({api, node, onState = () => {}, onProgress = () => {}, onResult = () => {}, onError = () => {}, pollMs = 2000, now = () => Date.now()}) { - let chain = null, poller = null, disposed = false, epoch = 0, submitting = false, promoting = false; + let chain = null, poller = null, disposed = false, epoch = 0, submitting = false, promoting = false, redoRequest = null; // Chains the server took while another was running; the next one is shown when the running one stops. const waiting = []; let previous = {}, lastMessage = {}, delivered = null, errorShown = null, corrected = false, etaAt = 0, lastIndex = -1; @@ -281,6 +287,7 @@ export function createStudioChain({api, node, onState = () => {}, onProgress = ( // The reply carries the whole chain, so the part shows the words the server keeps. async setText(block, text) { if (!chain) throw new Error('chain_missing'); + redoRequest = null; const id = chain.id, version = epoch; const value = (await json(chainRoute(id, `blocks/${encodeURIComponent(block)}/text`), post({text})))?.chain; if (value?.id === id && version === epoch && !disposed) deliver(value); @@ -290,9 +297,22 @@ export function createStudioChain({api, node, onState = () => {}, onProgress = ( async redo(block) { if (!chain || active()) throw new Error('chain_busy'); const id = chain.id, version = epoch; - const value = (await json(chainRoute(id, `blocks/${encodeURIComponent(block)}/redo`), - post(api.clientId ? {client_id: api.clientId} : {})))?.chain; + // One name per press: kept while no reply has come, so pressing again after a lost reply asks for the same + // video; gone once the engine has answered or what is asked has changed. + if (redoRequest?.chain !== id || redoRequest.block !== block) redoRequest = {chain: id, block, name: requestName()}; + const request = redoRequest, answered = () => { if (redoRequest === request) redoRequest = null; }; + let value; + try { + value = (await json(chainRoute(id, `blocks/${encodeURIComponent(block)}/redo`), + post({request_id: request.name, ...(api.clientId ? {client_id: api.clientId} : {})})))?.chain; + } catch (error) { + // The engine's own refusal carries its code in words. A lost or late reply does not (a TimeoutError's + // code is a number), nor does a page a proxy puts in front of the engine. + if (error?.status && typeof error.code === 'string') answered(); + throw error; + } if (!value?.id) throw new Error('chain_missing'); + answered(); if (version !== epoch || disposed) return value; const {id: _, ...metadata} = node.properties?.[CHAIN_PROPERTY] || {}; epoch++; adopt(value, metadata); diff --git a/web/task_float.css b/web/task_float.css index 38a3ea2f..72bc9b2d 100644 --- a/web/task_float.css +++ b/web/task_float.css @@ -19,7 +19,7 @@ .sgf[popover], .sgf-slot[popover], .sgf-fly[popover] { position: fixed; inset: auto; left: 0; top: 0; margin: 0; padding: 0; border: 0; background: transparent; overflow: visible; width: auto; height: auto; max-width: none; max-height: none; color: var(--f-fg); } .sgf[popover]:not(:popover-open), .sgf-slot[popover]:not(:popover-open), .sgf-fly[popover]:not(:popover-open) { display: none; } .sgf { - z-index: var(--fv-z-float, 2000); will-change: transform; font: 400 13px/1.45 "Inter", "Noto Sans SC", "Segoe UI", "PingFang SC", "Microsoft YaHei UI", system-ui, sans-serif; font-feature-settings: "tnum" 1; + z-index: var(--fv-z-float, 2000); will-change: transform; font: 400 13px/1.45 var(--fv-font, "Segoe UI", "PingFang SC", "Microsoft YaHei UI", "Noto Sans SC", system-ui, sans-serif); font-feature-settings: "tnum" 1; -webkit-user-select: none; user-select: none; -webkit-tap-highlight-color: transparent; } .sgf .fv-selectable { -webkit-user-select: text; user-select: text; cursor: text; } diff --git a/web/task_float.js b/web/task_float.js index 7a14ad16..5d737876 100644 --- a/web/task_float.js +++ b/web/task_float.js @@ -9,10 +9,10 @@ import { jobs, imageSource, progressSource, chainSource, queueSource, journalSou import { errorText, failureAdvice } from './error_panel.js'; import { createImageGenClient, imageGenError, imageReportBar } from './image_generation.js'; import { saveGeneratedImage } from './image_library.js'; +import { isChinese, translator } from './i18n.js'; -const languageOverride = typeof location !== 'undefined' ? new URLSearchParams(location.search).get('freevideo_lang') : null; -const cn = languageOverride === 'zh' || (languageOverride !== 'en' && String(globalThis.navigator?.language || '').toLowerCase().startsWith('zh')); -const t = (en, zh) => cn ? zh : en; +const cn = isChinese(); +const t = translator(cn); if (typeof document !== 'undefined') { const css = document.createElement('link'); css.rel = 'stylesheet'; css.href = new URL('./task_float.css', import.meta.url).href; document.head.append(css); } diff --git a/web/tooltip.js b/web/tooltip.js index f48dc615..a290c091 100644 --- a/web/tooltip.js +++ b/web/tooltip.js @@ -14,6 +14,7 @@ // the words a hover shows; the moment a view writes its own attributes, the copy steps aside. import { TIPS, MATCHES, LABELS } from './tooltip_copy.js'; import { installA11y } from './a11y.js'; +import { isChinese } from './i18n.js'; if (globalThis.document?.head && !globalThis.document.head.querySelector?.('link[data-fv-sheet=tooltip]')) { const sheet = document.createElement('link'); @@ -22,8 +23,7 @@ if (globalThis.document?.head && !globalThis.document.head.querySelector?.('link } const query = new URLSearchParams(globalThis.location?.search || ''); -const language = query.get('freevideo_lang'); -const cn = language === 'zh' || (language !== 'en' && String(globalThis.navigator?.language || '').toLowerCase().startsWith('zh')); +const cn = isChinese(); const pick = value => Array.isArray(value) ? value[cn ? 1 : 0] : value; export const SHOW_DELAY = 500, HIDE_DELAY = 100, WARM_FOR = 700, GAP = 8, MARGIN = 8, LONG_PRESS = 500, MAX_WIDTH = 320; diff --git a/web/topbar.css b/web/topbar.css index bc38efea..42149a85 100644 --- a/web/topbar.css +++ b/web/topbar.css @@ -152,9 +152,9 @@ html body .fv-topbar.fv-topbar.fv-topbar[data-fv-fit="2"] .fv-tb-cap .fv-tb-n{di html body .fv-topbar.fv-topbar.fv-topbar[data-fv-fit="2"] .fv-tb-cap.has-n::after{content:"";position:absolute;top:6px;right:8px;width:8px;height:8px;border-radius:var(--fv-r-pill);background:var(--fv-accent-ink);box-shadow:0 0 0 2px rgb(var(--fv-solid2))} html body .fv-topbar.fv-topbar.fv-topbar[data-fv-fit="2"] .fv-tb-cap.is-warn.has-n::after{background:var(--fv-warn)} html body .fv-topbar.fv-topbar.fv-topbar[data-fv-fit="3"] .fv-tb-cap{width:auto;min-width:var(--fv-touch);height:var(--fv-touch);padding:0 var(--fv-sp-12) 0 var(--fv-sp-8);gap:var(--fv-sp-4)} -html body .fv-topbar.fv-topbar.fv-topbar[data-fv-fit="3"] .fv-tb-cap:not([data-state=run],[data-state=dl],[data-state=wait]){width:var(--fv-touch);padding:0} +html body .fv-topbar.fv-topbar.fv-topbar[data-fv-fit="3"] .fv-tb-cap:not([data-state=run],[data-state=dl],[data-state=wait],[data-state=prompt]){width:var(--fv-touch);padding:0} html body .fv-topbar.fv-topbar.fv-topbar[data-fv-fit="3"] .fv-tb-cap :is(.fv-tb-wide,.fv-tb-n){display:none} -html body .fv-topbar.fv-topbar.fv-topbar[data-fv-fit="3"] .fv-tb-cap:not([data-state=run],[data-state=dl],[data-state=wait]) .fv-tb-cap-txt{display:none} +html body .fv-topbar.fv-topbar.fv-topbar[data-fv-fit="3"] .fv-tb-cap:not([data-state=run],[data-state=dl],[data-state=wait],[data-state=prompt]) .fv-tb-cap-txt{display:none} html body .fv-topbar.fv-topbar.fv-topbar[data-fv-fit="3"] .fv-tb-cap.has-n::after{content:"";position:absolute;top:7px;right:7px;width:8px;height:8px;border-radius:var(--fv-r-pill);background:var(--fv-accent-ink);box-shadow:0 0 0 2px rgb(var(--fv-solid2))} html body .fv-topbar.fv-topbar.fv-topbar[data-fv-fit="3"] .fv-tb-cap.is-warn.has-n::after{display:none} diff --git a/web/topbar.js b/web/topbar.js index 17f911c3..dfec82fe 100644 --- a/web/topbar.js +++ b/web/topbar.js @@ -83,7 +83,7 @@ function ringSVG() { return svg; } // The notification centre's unread count (palette's notifications.js), when it is there. -let notices = null; +let notices = null, promptJob = null; // The first time a notice is unread, a one-time hint under the capsule says the notices are there (Parker N2). It goes // for good once "Got it" or the capsule is pressed (kept in this browser). @@ -146,7 +146,7 @@ function renderCapsule(capsule) { const seen = capsule.fvCapsule.seen; if (seen && (active > seen.active || finished > seen.finished)) bump(capsule); capsule.fvCapsule.seen = {active, finished}; - const {t} = capsule.fvCapsule, state = capsuleState(list, online, notices); + const {t} = capsule.fvCapsule, state = capsuleState(list, online, promptJob ? {...(notices || {}), prompt: promptJob} : notices); const [word, number] = capsuleWords(t, state); const figures = state.kind === 'idle' && showFigures() ? machineFigures(machine) : null; capsule.dataset.state = state.kind; @@ -154,7 +154,7 @@ function renderCapsule(capsule) { capsule.classList.toggle('has-n', state.count > 0); capsule.classList.toggle('has-figures', !!figures); const {dot, ring, text, count} = capsule.fvCapsule; - const ringed = state.kind === 'run' || state.kind === 'dl' || state.kind === 'wait'; + const ringed = state.kind === 'run' || state.kind === 'dl' || state.kind === 'wait' || state.kind === 'prompt'; dot.hidden = ringed; ring.style.display = ringed ? '' : 'none'; dot.className = `fv-tb-dot${state.kind === 'off' ? ' is-off' : state.warn ? ' is-warn' : ''}`; if (ringed) ring.lastChild.setAttribute('stroke-dashoffset', (RING * (1 - (state.percent || 0) / 100)).toFixed(2)); @@ -204,6 +204,8 @@ function noteAgentFailures() { for (const job of agentTasks.failed()) addAgentNote(noteFromAgent(job, {title: agentTitle(job, t), reason: failureReason(job, t)})); } // Subscribed once everything it calls is defined (it answers at once with the current state). +// A description being written from a picture or video (prompt_enhance.js): the capsule says so while it runs. +if (browser) globalThis.addEventListener('freevideo-prompt-job', event => { promptJob = event.detail?.active ? {fraction: event.detail.fraction} : null; syncCapsules(); }); if (browser) onNotices(state => { const before = notices?.unread || 0; notices = state; syncCapsules(); if (!before && state.unread) noticeHint(); }); // The engine's monitor reading (the source of the old status capsule: video memory, temperature, disk): one shared diff --git a/web/topbar_state.js b/web/topbar_state.js index 9fd53922..65972d51 100644 --- a/web/topbar_state.js +++ b/web/topbar_state.js @@ -1,10 +1,9 @@ // The top bar's words and its status capsule's state, apart from the page (tests/topbar_state.mjs drives them). import { ACTIVE } from './task_store.js'; +import { isChinese, translator } from './i18n.js'; -const query = new URLSearchParams(globalThis.location?.search || ''); -const language = query.get('freevideo_lang'); -export const CN = language === 'zh' || (language !== 'en' && String(globalThis.navigator?.language || '').toLowerCase().startsWith('zh')); -export const t0 = (en, zh) => CN ? zh : en; +export const CN = isChinese(); +export const t0 = translator(CN); export const MAC = /Mac|iPhone|iPad/i.test(globalThis.navigator?.platform || globalThis.navigator?.userAgent || ''); // The words of the bar, one table (TOPBAR.md §6). Names are what the item is; uses say what it does. @@ -51,6 +50,8 @@ export function capsuleState(list = [], isOnline = true, notices = null) { const percent = Math.max(0, Math.min(100, Math.round(100 * (Number(running.percent) || 0)))); return {kind: 'run', percent, count: failed ? failed : active.length > 1 ? active.length : 0, warn: false, countWarn: failed > 0}; } + // A description being written from a picture or video (notices.prompt: {fraction}, null while not measurable): shown like a task, after real tasks. + if (notices?.prompt) return {kind: 'prompt', percent: Number.isFinite(notices.prompt.fraction) ? Math.max(0, Math.min(100, Math.round(100 * notices.prompt.fraction))) : null, count: failed ? failed : 0, warn: false, countWarn: failed > 0}; // A failure: a warning-coloured dot and "Not finished 1" in plain words; no extra badge. if (failed) return {kind: 'fail', failed, count: 0, warn: true, countWarn: false}; // A model download or install (notices.installing: {fraction}) when nothing else runs. @@ -60,6 +61,7 @@ export function capsuleState(list = [], isOnline = true, notices = null) { } export function capsuleWords(t, state) { return {off: [t('Engine offline', '引擎已断开'), ''], run: [t('Generating', '生成中'), `${state.percent}%`], dl: [t('Downloading', '下载中'), `${state.percent}%`], + prompt: [t('Writing prompt', '生成提示词'), state.percent == null ? '' : `${state.percent}%`], wait: [t('Waiting', '排队'), String(state.waiting || 1)], fail: [t('Not finished', '未完成'), String(state.failed || 1)], idle: [t('Ready', '就绪'), '']}[state.kind]; } diff --git a/web/tutorial_book.js b/web/tutorial_book.js index 982c33fc..49a8cd7d 100644 --- a/web/tutorial_book.js +++ b/web/tutorial_book.js @@ -7,6 +7,7 @@ import {FEATURE_TOUR, readyCards} from './feature_tour_content.js'; import {SHOWCASE_TEXT, SHOWCASE_ASSET} from './entry_showcase.js'; import {isolateDialogKeys, listenDialogKey, routeDialogKey} from './dialog_keys.js'; import {reducedMotion} from './context_menu.js'; +import { isChinese } from './i18n.js'; const COPY = { zh: {book: '教程', chapters: '章节', examples: '示例', contents: '目录', close: '关闭', search: '搜索教程', steps: '步骤', limits: '注意', @@ -86,10 +87,7 @@ const el = (tag, cls, text) => { }; const tip = (node, name, use, key = '') => { node.dataset.fvTipName = name; node.dataset.fvTipUse = use; if (key) node.dataset.fvTipKey = key; return node; }; const button = (cls, label, [name, use, key = ''], ...icons) => { const node = el('button', cls); node.type = 'button'; node.append(...icons); if (label != null) node.append(document.createTextNode(label)); return tip(node, name, use, key); }; -const language = () => { - const choice = new URLSearchParams(location.search).get('freevideo_lang'); - return choice === 'zh' || (choice !== 'en' && navigator.language?.toLowerCase().startsWith('zh')) ? 'zh' : 'en'; -}; +const language = () => isChinese() ? 'zh' : 'en'; const asset = name => new URL(`./assets/tour/${name}`, import.meta.url).href; const poster = name => asset(`${name}.webp`); const READ_KEY = 'freevideo.tutorial.read'; diff --git a/web/updates.js b/web/updates.js index f5a4b9f1..f111f73a 100644 --- a/web/updates.js +++ b/web/updates.js @@ -5,6 +5,7 @@ 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'; +import { LANGUAGE_PARAM, askedLanguage } from './i18n.js'; // Every platform downloads from one release: the latest vX.Y.Z. const releasePage = 'https://github.com/FlashML-org/FreeVideo/releases/latest'; @@ -18,7 +19,7 @@ let loadedVersion, updating = false, offline = false, failure = ''; try { dismissed = sessionStorage.getItem(storageKey); } catch { /* Session memory still works. */ } // The launcher passes its language in the first address, which ComfyUI later // rewrites; keep it when reloading into an updated engine. -const languageHint = (() => { try { return new URLSearchParams(location.search).get('freevideo_lang'); } catch { return null; } })(); +const languageHint = askedLanguage(); const identity = candidate => candidate ? [candidate.version, candidate.revision, candidate.built_at].join(':') : ''; const displayVersion = release => release?.product_version ? 'v' + release.product_version : release?.version || '—'; // The running release's product version ("0.3.4"), once the first check has answered. @@ -157,8 +158,8 @@ export async function checkUpdates() { // The server restarted with another engine; load its matching // interface. ComfyUI keeps the workflow, including the prompt. const url = new URL(location.href); - if (languageHint && !url.searchParams.has('freevideo_lang')) { - url.searchParams.set('freevideo_lang', languageHint); + if (languageHint && !url.searchParams.has(LANGUAGE_PARAM)) { + url.searchParams.set(LANGUAGE_PARAM, languageHint); location.replace(url.href); } else location.reload(); return; diff --git a/web/view_navigation.js b/web/view_navigation.js index a6f595c8..ccbe6a88 100644 --- a/web/view_navigation.js +++ b/web/view_navigation.js @@ -8,12 +8,10 @@ import { installTooltips } from './tooltip.js'; import './palette.js'; import { isLaunchVisit } from './launch_visit.js'; import { topbarActions, adoptWhenPlaced, buildBar } from './topbar.js'; +import { isChinese, translator } from './i18n.js'; -const languageOverride = typeof location !== 'undefined' - ? new URLSearchParams(location.search).get('freevideo_lang') : null; -const cn = languageOverride === 'zh' || (languageOverride !== 'en' - && String(navigator.language || '').toLowerCase().startsWith('zh')); -const t = (en, zh) => cn ? zh : en; +const cn = isChinese(); +const t = translator(cn); const preference = 'freevideo.view'; let toolbar, open, selected, currentView = 'nodes', agentTab = null, opening = null, place = null; const style = document.createElement('link'); diff --git a/web/view_switch_place.js b/web/view_switch_place.js index 14870039..b08c41e1 100644 --- a/web/view_switch_place.js +++ b/web/view_switch_place.js @@ -5,11 +5,10 @@ // beside the tabs (or the window is 480 px or narrower) the tabs move to a second row of their own, centred, and the // first row holds the logo and the entries (or their menu button). // Returns the geometry the views' own fits read: {wrap, inner, gap, left, right} (left === right on one row). +import { isChinese, translator } from './i18n.js'; const LOGO_ROOM = 96; -const query = new URLSearchParams(globalThis.location?.search || ''); -const language = query.get('freevideo_lang'); -const cn = language === 'zh' || (language !== 'en' && String(globalThis.navigator?.language || '').toLowerCase().startsWith('zh')); -const t = (en, zh) => cn ? zh : en; +const cn = isChinese(); +const t = translator(cn); function actionsOf(header) { return header.querySelector(':scope > :is(.fv-header-actions,.fv-view-actions)'); } diff --git a/web/workspace_restore.js b/web/workspace_restore.js index 534facf5..6061e650 100644 --- a/web/workspace_restore.js +++ b/web/workspace_restore.js @@ -1,4 +1,5 @@ import { isLaunchVisit } from './launch_visit.js'; +import { isChinese } from './i18n.js'; // Small, eager startup surface: no editing-module or host imports to delay its first paint. // Provisional copy keys for Iris. Keep project names as text, never markup. export const WORKSPACE_OPENING_COPY = { @@ -7,8 +8,7 @@ export const WORKSPACE_OPENING_COPY = { }; let opening = null; const query = new URLSearchParams(typeof location === 'undefined' ? '' : location.search); -const language = query.get('freevideo_lang'); -const cn = language === 'zh' || language !== 'en' && String(globalThis.navigator?.language || '').toLowerCase().startsWith('zh'); +const cn = isChinese(); let resolveLaunch; const launchReady = query.get('freevideo') === 'launch' ? new Promise(resolve => { resolveLaunch = resolve; }) : null; export const waitForLauncherRestore = () => launchReady;