diff --git a/.gitignore b/.gitignore index 51d375c5..8e19ac88 100644 --- a/.gitignore +++ b/.gitignore @@ -76,3 +76,8 @@ engine-gpu-*.lock *.gguf /out/ !freevideo_engine/frame_preview_decoder.safetensors + +# Local agent service: address and access token written at run time +/agent/endpoint.json +/agent/token +/agent/.token-*.tmp diff --git a/freevideo_engine/adaptive.py b/freevideo_engine/adaptive.py index 8a39d365..77120834 100644 --- a/freevideo_engine/adaptive.py +++ b/freevideo_engine/adaptive.py @@ -831,7 +831,7 @@ def complete_observation(metrics, canvas, output, artifacts, telemetry): output_frames = expected - hidden original_audio = metrics.get('original_audio') if original_audio is not None: - if (not isinstance(original_audio, dict) or original_audio.get('sample_identical') is not True + if (not isinstance(original_audio, dict) or original_audio.get('mode') not in ('stream_copy', 'aac320') or type(original_audio.get('samples_per_channel')) is not int or type(original_audio.get('sample_rate')) is not int or original_audio['samples_per_channel'] <= 0 or original_audio['sample_rate'] <= 0): diff --git a/freevideo_engine/agent/errors.py b/freevideo_engine/agent/errors.py index 7937f204..55d21cfb 100644 --- a/freevideo_engine/agent/errors.py +++ b/freevideo_engine/agent/errors.py @@ -168,6 +168,16 @@ 'invalid_media': ('The reference image could not be read. Choose another one.', '参考图读不出来,请换一张。'), 'invalid_request': ('The image settings are invalid. Adjust them and try again.', '图片设置有误,请调整后重试。'), + 'invalid_prompt': ('The prompt is empty, or longer than 2,000 characters once the picture references are counted. Shorten it and try again.', + '提示词为空,或加上图片引用后超过 2000 字。请缩短提示词后重试。'), + 'invalid_dimensions': ('The image size is outside what the chosen model supports. Change the size and try again.', + '图片尺寸超出所选模型支持的范围。请调整尺寸后重试。'), + 'invalid_seed': ('The seed is not valid. Clear it or use a smaller whole number, then try again.', + '随机种子无效。请清空种子或改用较小的整数后重试。'), + 'too_many_images': ('There are more reference images than the chosen model supports. Remove some and try again.', + '参考图超过所选模型支持的数量。请减少参考图后重试。'), + 'output_unwritable': ('The folder that keeps the pictures cannot be written (freevideo-image in the ComfyUI input folder). Check that it exists, is writable and has no file of the same name, then try again.', + '无法写入保存图片的文件夹(ComfyUI 的 input 目录下的 freevideo-image)。请确认该目录存在、可写,且没有同名文件,然后重试。'), 'busy': ('Another picture is being generated. Try again when it finishes.', '已有一张图在生成,完成后再试。'), 'cancelled': ('The picture was cancelled.', '已取消这张图片。'), } @@ -181,7 +191,7 @@ def image_failure(code, report_id=None): valid = isinstance(report_id, str) and re.fullmatch(r'[0-9a-f]{32}', report_id) return dict(reason=dict(en=en, zh=zh), report_id=report_id if valid and code not in LORA_ERRORS and code not in ( 'busy', 'cancelled', 'invalid_request', 'invalid_media', 'invalid_prompt', 'invalid_dimensions', - 'invalid_seed', 'too_many_images', 'disk_full') else None) + 'invalid_seed', 'too_many_images', 'disk_full', 'output_unwritable') else None) # Recovery is a function of the committed task and phase, not just an error code. @@ -208,6 +218,7 @@ def image_failure(code, report_id=None): 'generation_failed': IMAGE_REASONS['generation_failed'][0], 'worker_exit': 'The image worker stopped before finishing this picture.', 'disk_full': IMAGE_REASONS['disk_full'][0], + 'output_unwritable': 'The folder that keeps the pictures cannot be written; tell the user to check that the freevideo-image folder in the input directory exists, is writable and has no file of the same name, then submit again with a new ref.', 'cancelled': 'The picture job was cancelled.', } IMAGE_REASONS.update({code: (LORA_MESSAGE_EN[code], LORA_MESSAGE_ZH[code]) for code in LORA_ERRORS}) @@ -342,6 +353,7 @@ def safe_details(value): 'invalid_output': '生成的结果无法读取或保存', 'storage_unavailable': '任务记录或素材无法写入磁盘', 'disk_full': '磁盘空间不够,图片没能保存', + 'output_unwritable': '保存图片的文件夹无法写入', 'submit_interrupted': '提交生成时服务中断,尚未确认任务是否开始', 'timeout': '生成等了太久没有结果', 'invalid_media': '参考素材无法读取', @@ -449,6 +461,7 @@ def safe_details(value): 'invalid_output': 'The result could not be read or saved', 'storage_unavailable': 'The task record or media could not be written to disk', 'disk_full': 'Saving the image failed: the disk is full', + 'output_unwritable': 'The folder that keeps the pictures cannot be written', 'submit_interrupted': 'The service stopped during submission, so it is not confirmed whether the task started', 'timeout': 'Generation took too long without a result', 'invalid_media': 'The reference media could not be read', @@ -547,6 +560,11 @@ def safe_details(value): 'stems_download_failed': '检查网络连接后再试', 'voice_model_missing': '先安装配音模型', 'no_speech': '选择有人说话的一段声音', + 'invalid_prompt': '缩短图片描述后再试', + 'invalid_dimensions': '调整图片尺寸后再试', + 'invalid_seed': '清空种子或改用较小的整数后再试', + 'too_many_images': '减少参考图后再试', + 'output_unwritable': '确认输入目录下的 freevideo-image 文件夹存在、可写且没有同名文件后再试', } FAILURE_NEXT_EN = { 'generation_failed': 'If it happens again, use "Report a problem"', @@ -574,6 +592,11 @@ def safe_details(value): 'stems_download_failed': 'Check the network connection, then try again', 'voice_model_missing': 'Install the dubbing model first', 'no_speech': 'Choose a stretch of sound with someone speaking', + 'invalid_prompt': 'Shorten the description, then try again', + 'invalid_dimensions': 'Change the picture size, then try again', + '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', } 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 d5a6de97..8b01fc7d 100644 --- a/freevideo_engine/agent/mcp.py +++ b/freevideo_engine/agent/mcp.py @@ -498,7 +498,8 @@ def shell_quote(value, *, windows=None): def linux_wrapper_supported(): import platform - return sys.platform.startswith('linux') and platform.machine() == 'x86_64' + from ..environments import linux_machine + return sys.platform.startswith('linux') and linux_machine(platform.machine()) is not None def python_shell_command(config, module): diff --git a/freevideo_engine/bootstrap.py b/freevideo_engine/bootstrap.py index a9ef1704..8ba266c4 100644 --- a/freevideo_engine/bootstrap.py +++ b/freevideo_engine/bootstrap.py @@ -31,7 +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 .environments import (ENVIRONMENTS, environment_names, select_layout, role_pythons, constraints_file, +from .environments import (ENVIRONMENTS, 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 from . import network @@ -655,18 +655,21 @@ def plan(args, *, local_progress=None, stage=None): from .macos_bootstrap import preflight snapshot, resources, errors = preflight(args, fixture, ram_gib=ram_gib, vram_gib=vram_gib) system, windows_target, layout = 'Darwin', False, 'unified' + target_machine = None cache_format = dict(capability=None, scale_granularity='int8_convrot') prepared_format = 'int8_convrot' else: - if not args.hardware_json and (platform.system() not in ('Linux', 'Windows') or platform.machine().lower() not in ('x86_64', 'amd64')): - raise RuntimeError('One-click setup supports Linux x86_64 and native Windows x64.') + if not args.hardware_json and not setup_supported(platform.system(), platform.machine()): + raise RuntimeError('One-click setup supports Linux x86_64 or ARM64 and native Windows x64.') snapshot = json.loads(args.hardware_json.read_text(encoding='utf-8')) if args.hardware_json else inventory(args.gpu) warnings.extend(snapshot.get('warnings', [])) hardware = Hardware.from_dict(snapshot['hardware']) errors = [] - if snapshot.get('machine', '').lower() not in ('x86_64', 'amd64') or hardware.system not in ('Linux', 'Windows'): - errors.append('This installer supports Linux x86_64 and native Windows x64.') + if not setup_supported(hardware.system, snapshot.get('machine', '')): + errors.append('This installer supports Linux x86_64 or ARM64 and native Windows x64.') windows_target = hardware.system == 'Windows' + # A replayed snapshot (--hardware-json) plans for its own processor, not this machine's. + target_machine = snapshot.get('machine') or None if windows_target and layout != 'unified': errors.append('Native Windows uses the unified environment. Rerun with --environment unified.') layout = 'unified' @@ -883,7 +886,7 @@ def plan(args, *, local_progress=None, stage=None): dependencies = dependency_status(root, layout, system) environments_ready = all(r['exists'] and not r['missing'] and not r['mismatched'] for r in dependencies.values()) python_version = None if mac_target else bootstrap_versions( - json.loads((PACKAGE / 'bootstrap_versions.json').read_text(encoding='utf-8')), system)['python'] + json.loads((PACKAGE / 'bootstrap_versions.json').read_text(encoding='utf-8')), system, target_machine)['python'] linux_target = not mac_target and not windows_target environment_gib = environment_allowance_gib(dependencies, mac=mac_target, layout=layout, python_version=python_version, linux=linux_target) @@ -924,7 +927,7 @@ def native_git_available(): if stage: stage('Testing download sources') networking = network.plan(json.loads((PACKAGE / 'dependencies.json').read_text(encoding='utf-8')), - bootstrap_versions(json.loads((PACKAGE / 'bootstrap_versions.json').read_text(encoding='utf-8')), system), layout, + bootstrap_versions(json.loads((PACKAGE / 'bootstrap_versions.json').read_text(encoding='utf-8')), system, target_machine), layout, mode=getattr(args, 'network', 'auto'), timeout=getattr(args, 'network_timeout', 5), offline=bool(args.hardware_json or errors), git_available=not mac_target or bool(args.hardware_json) or native_git_available(), @@ -1276,8 +1279,8 @@ def prepare_uv(system, root, uv_spec, networking, env, fetch): except OSError: shutil.copyfile(previous, archive) fetch(uv_spec['url'], archive, uv_spec['sha256']) - unpack_folder(archive, root / 'tools', 'uv-x86_64-unknown-linux-gnu') - return root / 'tools' / 'uv-x86_64-unknown-linux-gnu' / 'uv' + unpack_folder(archive, root / 'tools', uv_folder()) + return root / 'tools' / uv_folder() / 'uv' def unpack_folder(archive, destination, name): @@ -2185,7 +2188,7 @@ def host_compiler(self, cuda): `env` is empty when the system compiler is used; `identity` names the compiler in the wheel cache key. A portable compiler is only installed when a build is needed (see install_compiler_linux). """ - spec = json.loads((PACKAGE / 'gcc_linux.json').read_text(encoding='utf-8')) + spec = conda_lock(json.loads((PACKAGE / 'gcc_linux.json').read_text(encoding='utf-8'))) below = spec['host_compiler_below'].get(cuda) # Without any system g++, FreeVideo's own compiler builds Sage2. if not shutil.which('g++', path=self.env['PATH']): @@ -2199,9 +2202,9 @@ def host_compiler(self, cuda): def install_compiler_linux(self): """GCC from conda-forge, pinned by package hashes, for a system compiler newer than the toolkit accepts.""" - spec = json.loads((PACKAGE / 'gcc_linux.json').read_text(encoding='utf-8')) + spec = conda_lock(json.loads((PACKAGE / 'gcc_linux.json').read_text(encoding='utf-8'))) prefix = self.root / 'tools' / ('gcc-' + spec['version']) - triple = 'x86_64-conda-linux-gnu' + triple = conda_triple() compilers = {'CC': prefix / 'bin' / (triple + '-gcc'), 'CXX': prefix / 'bin' / (triple + '-g++')} receipt, content = prefix / '.freevideo-gcc.json', {k: spec[k] for k in ('version', 'packages')} if not (receipt.is_file() and json.loads(receipt.read_text(encoding='utf-8')) == content @@ -2258,7 +2261,7 @@ def install_git_linux(self): self.install_git_conda('git_linux.json', 'git-linux', self.fetch_git_linux) def install_git_conda(self, filename, folder, fetch, wrapper=False): - spec = json.loads((PACKAGE / filename).read_text(encoding='utf-8')) + spec = conda_lock(json.loads((PACKAGE / filename).read_text(encoding='utf-8'))) prefix = self.root / 'tools' / ('git-' + spec['version']) executable = prefix / 'bin' / 'git' receipt, content = prefix / '.freevideo-git.json', {k: spec[k] for k in ('version', 'packages')} diff --git a/freevideo_engine/bootstrap_versions.json b/freevideo_engine/bootstrap_versions.json index 6eeb30d4..62879ebb 100644 --- a/freevideo_engine/bootstrap_versions.json +++ b/freevideo_engine/bootstrap_versions.json @@ -29,6 +29,87 @@ "url": "https://github.com/astral-sh/uv/releases/download/0.9.0/uv-x86_64-unknown-linux-gnu.tar.gz", "sha256": "4dadaa5ff5009ccd6a0a43f6ccfa32bf36ed2eff18df7011275a9b1d81950e7b" }, + "linux_aarch64": { + "uv": { + "version": "0.9.0", + "url": "https://github.com/astral-sh/uv/releases/download/0.9.0/uv-aarch64-unknown-linux-gnu.tar.gz", + "sha256": "ca410766024d2d726c937bda2e9441823e2848894ac5a2f8b608902384fc391f" + }, + "cuda_toolkits": { + "12.9": { + "components": { + "cuda_nvcc": { + "relative_path": "cuda_nvcc/linux-sbsa/cuda_nvcc-linux-sbsa-12.9.86-archive.tar.xz", + "sha256": "0aa1fce92dbae76c059c27eefb9d0ffb58e1291151e44ff7c7f1fc2dd9376c0d", + "md5": "1322a14e4d6482f69d4b8a14a7d5f4c5", + "size": "73407012" + }, + "cuda_cudart": { + "relative_path": "cuda_cudart/linux-sbsa/cuda_cudart-linux-sbsa-12.9.79-archive.tar.xz", + "sha256": "8b422a3b2cb8452cb678181b0bf9d7aa7342df168b5319c5488ae3b8514101fc", + "md5": "c4b3e0d206f5dc3aceaddb78a32424d3", + "size": "1521596" + }, + "cuda_cccl": { + "relative_path": "cuda_cccl/linux-sbsa/cuda_cccl-linux-sbsa-12.9.27-archive.tar.xz", + "sha256": "8c3da24801b500f1d9217d191bb4b63e5d2096c8e7d0b7695e876853180ba82f", + "md5": "b39d03cfac57a3b2ded8e9b0a6b0e782", + "size": "997840" + } + }, + "required_files": [ + "bin/nvcc", + "include/cuda_runtime.h", + "include/crt/host_config.h", + "include/cub/cub.cuh", + "nvvm/bin/cicc", + "nvvm/libdevice/libdevice.10.bc" + ] + }, + "13.0": { + "components": { + "cuda_nvcc": { + "relative_path": "cuda_nvcc/linux-sbsa/cuda_nvcc-linux-sbsa-13.0.88-archive.tar.xz", + "sha256": "01b01e10aa2662ad1b3aeab3317151d7d6d4a650eeade55ded504f6b7fced18e", + "md5": "4defe04ac10e7231bfa63cbd72dd8e21", + "size": "22383012" + }, + "cuda_cudart": { + "relative_path": "cuda_cudart/linux-sbsa/cuda_cudart-linux-sbsa-13.0.96-archive.tar.xz", + "sha256": "e2c78564330a09d890f98a066a2082a32c78256ffcc6bccca1696bd2abbaf445", + "md5": "ff3140b2fb00f583295484fe36f77995", + "size": "1489276" + }, + "cuda_cccl": { + "relative_path": "cuda_cccl/linux-sbsa/cuda_cccl-linux-sbsa-13.0.85-archive.tar.xz", + "sha256": "eca22ded176804a78afcba3fe1909e7d473366ee1cb9f3784080df23bc8e74d5", + "md5": "e50b07ae0a9920ce07a107a5c7030157", + "size": "990368" + }, + "cuda_crt": { + "relative_path": "cuda_crt/linux-sbsa/cuda_crt-linux-sbsa-13.0.88-archive.tar.xz", + "sha256": "c03b92941ba7bf58a4992231ceb572477784ef450ce678f6545bed02392cae50", + "md5": "3db54b1fb543f00c1cca085569bffd9e", + "size": "79916" + }, + "libnvvm": { + "relative_path": "libnvvm/linux-sbsa/libnvvm-linux-sbsa-13.0.88-archive.tar.xz", + "sha256": "f94feb1a0da0c55ceb5c7f039c1f0ffad5d162e0fedfb565efb87771187ddcfd", + "md5": "b9730ee7e25db76caa843c858af31d98", + "size": "38570872" + } + }, + "required_files": [ + "bin/nvcc", + "include/cuda_runtime.h", + "include/crt/host_config.h", + "include/cccl/cub/cub.cuh", + "nvvm/bin/cicc", + "nvvm/libdevice/libdevice.10.bc" + ] + } + } + }, "cuda_redist_base": "https://developer.download.nvidia.com/compute/cuda/redist/", "cuda_toolkits": { "12.9": { diff --git a/freevideo_engine/cli.py b/freevideo_engine/cli.py index cb45a889..8c7ac7b5 100644 --- a/freevideo_engine/cli.py +++ b/freevideo_engine/cli.py @@ -108,6 +108,8 @@ def main(): generate.add_argument('--audio', type=Path, help='Audio file; may be combined with image/video references in --media') generate.add_argument('--audio-use', choices=('reference', 'original'), help='Audio use (default: reference); with --media alone, applies to its single audio file') + generate.add_argument('--redo-sound', type=Path, + help='Make new sound for an existing MP4 (absolute path); its picture is kept as it is') generate.add_argument('--continue-from', type=Path, help='Continue an existing MP4 using its absolute path') generate.add_argument('--first-frame-reference', action='store_true', help='With --continue-from: also give the model the first frame of the whole film as a ' @@ -174,6 +176,11 @@ def main(): args = parser.parse_args() if args.command == 'generate': from .continuation import validate_frames, validate_route + if args.redo_sound is not None: + if (args.continue_from is not None or args.refine_from or args.preview or args.audio is not None + or args.media or args.hide_tail): + raise ValueError('--redo-sound cannot be combined with continuing, previewing, refining, hiding a tail or other media') + args.two_pass = False if args.continue_anchor is not None and args.continue_from is None: raise ValueError('--continue-anchor requires --continue-from') if args.continue_from is not None: diff --git a/freevideo_engine/comfy_assets.py b/freevideo_engine/comfy_assets.py index 7ef0cc94..3adef7d4 100644 --- a/freevideo_engine/comfy_assets.py +++ b/freevideo_engine/comfy_assets.py @@ -94,18 +94,22 @@ def resolve_assets(serialized, input_directory): root = Path(input_directory).resolve() result = {} for row in rows: - if not isinstance(row, dict) or set(row) - {'file', 'role', 'enabled', 'cast', 'early_steps', 'sound', 'guide', 'voice_only', 'keep_source_audio', 'depth', + if not isinstance(row, dict) or set(row) - {'file', 'role', 'enabled', 'cast', 'early_steps', 'sound', 'guide', 'voice_only', 'keep_source_audio', 'depth', 'lines', 'use', 'range', 'segment', 'seconds'}: raise ValueError('Invalid media item') if 'seconds' in row and (row.get('role') != 'middle' or type(row['seconds']) not in (int, float) or not math.isfinite(row['seconds']) or row['seconds'] <= 0): raise ValueError('seconds is a positive time on a middle frame') - if 'depth' in row: - if type(row['depth']) is not bool: - raise ValueError('Media depth must be a boolean') - if (row.get('role') != 'reference' or not isinstance(row.get('file'), str) - or media_kind(row['file']) != 'video'): - raise ValueError('depth is only allowed on video references') + # Depth only and lines only: what of a reference video the model follows (one of them at most). + for key in ('depth', 'lines'): + if key in row: + if type(row[key]) is not bool: + raise ValueError('Media %s must be a boolean' % key) + if (row.get('role') != 'reference' or not isinstance(row.get('file'), str) + or media_kind(row['file']) != 'video'): + raise ValueError('%s is only allowed on video references' % key) + if row.get('depth') is True and row.get('lines') is True: + raise ValueError('Choose depth only or lines only, not both') # The character an @ mention added the row for; a continued part keeps one picture per character. if 'cast' in row and (set(row['cast'] if isinstance(row['cast'], dict) else ('?',)) not in ({'id'}, {'id', 'setting'}, {'id', 'prop'}) or not isinstance(row['cast']['id'], str) or not 0 < len(row['cast']['id']) <= 128 @@ -140,6 +144,8 @@ def resolve_assets(serialized, input_directory): reference = {'kind': kind, 'path': str(path), **audio_fields} if row.get('depth') is True: reference.update(depth=True, early_steps=3) + elif row.get('lines') is True: + reference.update(lines=True, early_steps=3) if cast_id(row) is not None: reference['cast'] = cast_id(row) # only a continued part reads it (comfy_media.continued) if is_setting(row): diff --git a/freevideo_engine/comfy_bridge.py b/freevideo_engine/comfy_bridge.py index 1e2b4e8a..f289c2eb 100644 --- a/freevideo_engine/comfy_bridge.py +++ b/freevideo_engine/comfy_bridge.py @@ -1671,7 +1671,8 @@ def poll(): elif export_inputs: send_progress({'label': 'Retaining and checking input media', 'timing_phase': 'encoding'}) extra = export_inputs(run, canvas) or {} - if any(row.get('depth') is True for row in (extra.get('media') or {}).get('references', [])): + from .depth_reference import uses_conversion + if uses_conversion(extra.get('media')): from .depth_reference import prepare_media def release_depth_models(): if release_models: diff --git a/freevideo_engine/comfy_host.py b/freevideo_engine/comfy_host.py index f20bbb99..ecee1ac4 100644 --- a/freevideo_engine/comfy_host.py +++ b/freevideo_engine/comfy_host.py @@ -14,7 +14,7 @@ from .comfy_bridge import installation from .comfy_environment import isolated_environment from .comfy_requirements import managed_requirements -from .environments import uv_build_environment, uv_file_arguments +from .environments import uv_build_environment, uv_file_arguments, uv_folder from .locking import runtime_lock from .monitoring import save from .package_progress import PackageOutput @@ -178,7 +178,7 @@ def git_run(label, command, env): except (OSError, ValueError): saved = None recorded = saved == identity - uv = root / 'tools' / ('uv.exe' if os.name == 'nt' else 'uv' if sys.platform == 'darwin' else 'uv-x86_64-unknown-linux-gnu/uv') + uv = root / 'tools' / ('uv.exe' if os.name == 'nt' else 'uv' if sys.platform == 'darwin' else uv_folder() + '/uv') if not repair and not recorded and isinstance(saved, dict) and dict(saved, nodes=identity['nodes']) == identity: # An update gave our own nodes a package. Add only that: everything this ComfyUI # already runs on stays as it is, so a failure here leaves a working environment. diff --git a/freevideo_engine/depth_reference.py b/freevideo_engine/depth_reference.py index 3d4e92c9..b72b7b0f 100644 --- a/freevideo_engine/depth_reference.py +++ b/freevideo_engine/depth_reference.py @@ -1,7 +1,8 @@ -"""Optional, file-backed depth references. Torch lives only in a disposable worker. +"""Optional, file-backed depth and line references. Torch lives only in a disposable worker. -Small's vendored Apache-2.0 network and preprocessing follow Quinn's fixed -DAV2 experiment. Cache identity deliberately excludes prompt, seed and K. +Depth: Small's vendored Apache-2.0 network and preprocessing follow Quinn's fixed +DAV2 experiment. Lines: a drawing of the clip's edges, made on the CPU with no model. +Cache identity deliberately excludes prompt, seed and K. """ from contextlib import contextmanager from fractions import Fraction @@ -20,6 +21,22 @@ PREPROCESSING_VERSION = 'dav2-small-pyav-torch-bgr-imagenet-lower-bound-14-clay-relief-v1' CODE_VERSION = 'freevideo-depth-reference-v1' STAGE = 'depth_reference' +# Line references: colour edges at a 544-pixel working size (short side), thinned and joined by clip-wide thresholds. +LINES_VERSION = 'colour-canny-short544-sigma3.5-p93-p75-capped-grow1-v2' +LINES_SHORT_SIDE = 544 +LINES_SIGMA = 3.5 +LINES_PERCENTILES = (93, 75) +# Footage is mostly texture, so the percentiles pick out its outlines; a clean picture is mostly outline, so the +# thresholds are also capped at 0.8 and 0.55 of its strongest edges (the 99.5th percentile); on the sample clips they do not bind. +LINES_CAP = (99.5, .8, .55) +# Each line is grown by one working pixel all round before it is drawn, about twice the width of a single-pixel line. +# Thin lines led the video model to paint a stock-footage-like corner logo on one sample clip; thick lines did not +# in 16 samples (gap-08a round 2). +LINES_GROW = 1 +LABELS = {'depth': 'Extracting depth from the reference video', 'lines': 'Drawing lines from the reference video'} +OUTPUT = {'depth': 'depth.mp4', 'lines': 'lines.mp4'} +LINES_SOURCE_CHANGED = ('The reference video changed while it was being turned into lines. Try again, and leave the file ' + 'unchanged until the video is generated.') def catalog(): @@ -153,11 +170,20 @@ def inspect_video(path, check=lambda: None, *, depth=False): frames=len(pts), pts=pts, time_base=str(time_base), rotation=rotation) -def identity(source, video, device, check=lambda: None): - spec = catalog() +def identity(source, video, device, check=lambda: None, mode='depth'): output = {key: video[key] for key in ('width', 'height', 'fps_num', 'fps_den', 'frames')} output.update(fit='source', audio=False) pix_fmt = 'yuv420p' if video['width'] % 2 == video['height'] % 2 == 0 else 'yuv444p' + selection = dict(source_start_pts=video['pts'][0], source_end_pts=video['pts'][-1], source_time_base=video['time_base'], + crop_rect=None, rotation=video['rotation'], tail_policy='none') + if mode == 'lines': + # No model: what identifies the drawing is the source, the recipe and the encoder. A depth key never matches. + return dict(mode='lines', source_sha256=digest(source, check), source_size=Path(source).stat().st_size, + code_version=CODE_VERSION, preprocessing_version=LINES_VERSION, selection_spec=selection, + output_spec=output, inference_spec=dict(render='line-art-v1', short_side=LINES_SHORT_SIDE, + sigma=LINES_SIGMA, percentiles=list(LINES_PERCENTILES), cap=list(LINES_CAP), grow=LINES_GROW, + encoder='gray-to-'+pix_fmt+'/libx264/crf16/threads2', runtime_backend='numpy-cpu')) + spec = catalog() return dict(source_sha256=digest(source, check), source_size=Path(source).stat().st_size, model_id=spec['repo'], weights_sha256=spec['files'][0]['sha256'], source_commit=spec['source_commit'], code_version=CODE_VERSION, preprocessing_version=PREPROCESSING_VERSION, @@ -175,6 +201,10 @@ def cache_key(config): return hashlib.sha256(canonical_json(config).encode('utf-8')).hexdigest() +def output_name(config): + return OUTPUT['lines' if config.get('mode') == 'lines' else 'depth'] + + def _validate(path, expected, check): observed = inspect_video(path, check, depth=True) if any(observed[key] != expected[key] for key in ('width', 'height', 'fps_num', 'fps_den', 'frames')): @@ -185,7 +215,7 @@ def _validate(path, expected, check): def _cached(folder, config, check): try: manifest = json.loads((folder / 'manifest.json').read_text(encoding='utf-8')) - output = folder / 'depth.mp4' + output = folder / output_name(config) if (manifest['config'] != config or manifest['output_sha256'] != digest(output, check) or manifest['output_bytes'] != output.stat().st_size): return None @@ -244,6 +274,142 @@ def _clay_relief(gray): return (np.clip(shade, 0, 1)[..., None] * base * 255).astype(np.uint8) +def _blur(image, sigma): + """Gaussian blur with half-sample symmetric edges (SciPy's "reflect"), radius 3 sigma.""" + import numpy as np + from .app_control import scipy_module + radius = max(1, int(round(sigma * 3))) + return scipy_module('scipy.ndimage').gaussian_filter(np.asarray(image, np.float32), sigma, mode='reflect', + truncate=radius / sigma) + + +def _edge_strength(rgb, sigma): + """Thinned colour-edge strength: per pixel, the strongest channel's gradient, kept only on its ridge.""" + import numpy as np + colour = rgb.astype(np.float32) / 255 + best = np.zeros(colour.shape[:2], np.float32) + gx, gy = np.zeros_like(best), np.zeros_like(best) + for channel in range(3): + smooth = _blur(colour[..., channel], sigma) + x, y = np.zeros_like(smooth), np.zeros_like(smooth) + x[:, 1:-1] = (smooth[:, 2:] - smooth[:, :-2]) / 2 + y[1:-1] = (smooth[2:] - smooth[:-2]) / 2 + strength = x * x + y * y + stronger = strength > best + gx[stronger], gy[stronger], best[stronger] = x[stronger], y[stronger], strength[stronger] + magnitude = np.sqrt(best) + angle = (np.rad2deg(np.arctan2(gy, gx)) + 180) % 180 + padded = np.pad(magnitude, 1) + neighbours = {0: (padded[1:-1, 2:], padded[1:-1, :-2]), 45: (padded[2:, 2:], padded[:-2, :-2]), + 90: (padded[2:, 1:-1], padded[:-2, 1:-1]), 135: (padded[2:, :-2], padded[:-2, 2:])} + direction = np.select([(angle < 22.5) | (angle >= 157.5), angle < 67.5, angle < 112.5], [0, 45, 90], 135) + ridge = np.zeros(magnitude.shape, bool) + for value, (ahead, behind) in neighbours.items(): + ridge |= (direction == value) & (magnitude >= ahead) & (magnitude >= behind) + return np.where(ridge, magnitude, 0).astype(np.float32) + + +def _join(strength, low, high): + """Hysteresis: every weak-edge line (8-connected) that reaches a strong edge anywhere along it.""" + import numpy as np + from .app_control import scipy_module + weak = strength >= low + labels, count = scipy_module('scipy.ndimage').label(weak, structure=np.ones((3, 3), bool)) + if not count: + return weak + keep = np.zeros(count + 1, bool) + keep[np.unique(labels[strength >= high])] = True + keep[0] = False + return keep[labels] + + +def _line_frame(edges, size): + """Soft dark lines on white at the working size, then the output size.""" + import numpy as np + from PIL import Image + from scipy.ndimage import binary_dilation + if LINES_GROW: + edges = binary_dilation(edges, structure=np.ones((2 * LINES_GROW + 1,) * 2, bool)) + ink = np.clip(_blur(edges.astype(np.float32), 1.2) * 2.2, 0, 1) + gray = (255 * (1 - ink)).round().astype(np.uint8) + if gray.shape[::-1] != size: + gray = np.asarray(Image.fromarray(gray).resize(size, Image.BILINEAR)) + return np.repeat(gray[..., None], 3, axis=2) + + +def _lines(source, stage, video, emit, check): + """Two passes over the clip: edge strength per frame, then thresholds from the whole clip and the drawing. + Clip-wide thresholds keep the lines from flickering between frames.""" + import av + import numpy as np + import psutil + from PIL import Image + width, height = video['width'], video['height'] + scale = min(1., LINES_SHORT_SIDE / min(width, height)) + work_size = (max(1, round(width * scale)), max(1, round(height * scale))) + sigma = max(.8, min(work_size) / LINES_SHORT_SIDE * LINES_SIGMA) + shape = (video['frames'], work_size[1], work_size[0]) + from .disk_space import free_bytes + if free_bytes(stage) < shape[0] * shape[1] * shape[2] * 4 + 256 * 2**20: + raise OSError('Not enough disk space to stage line frames; free space and retry') + strength_path = stage / 'edges.f32' + strengths = np.memmap(strength_path, mode='w+', dtype=np.float32, shape=shape) + total = 2 * video['frames'] + try: + with av.open(str(source)) as container: + count = 0 + for frame in container.decode(video=0): + check() + bgr = _upright_bgr(frame) + if (count >= video['frames'] or bgr.shape[:2] != (height, width) + or _rotation(frame) != video['rotation']): + raise ValueError(LINES_SOURCE_CHANGED) + if psutil.virtual_memory().available < 2**30: + raise MemoryError('Turning the reference video into lines stopped to keep 1 GiB of system memory free. Close other ' + 'programs or use a shorter reference video, then try again.') + rgb = np.ascontiguousarray(bgr[..., ::-1]) + if work_size != (width, height): + rgb = np.asarray(Image.fromarray(rgb).resize(work_size, Image.BILINEAR)) + strengths[count] = _edge_strength(rgb, sigma) + count += 1 + emit(done=count, total=total, unit='frames', phase=STAGE, detail='%d/%d frames' % (count, total)) + if count != video['frames']: + raise ValueError(LINES_SOURCE_CHANGED) + strengths.flush() + # Thresholds from the edges of the whole clip, sampled from at most about 64 frames to bound RAM. + step = max(1, video['frames'] // 64) + sample = np.concatenate([row[row > 0] for row in strengths[::step]]) if video['frames'] else np.zeros(0) + if sample.size: + high, low, strongest = (float(value) for value in np.percentile(sample, (*LINES_PERCENTILES, LINES_CAP[0]))) + high, low = min(high, strongest * LINES_CAP[1]), min(low, strongest * LINES_CAP[2]) + else: + high = low = None # a flat clip has no edge, so nothing is drawn + output = stage / OUTPUT['lines'] + emit(phase=STAGE, detail='Encoding line video') + with av.open(str(output), 'w') as container: + stream = container.add_stream('libx264', rate=Fraction(video['fps_num'], video['fps_den'])) + stream.width, stream.height = width, height + stream.pix_fmt = 'yuv420p' if width % 2 == height % 2 == 0 else 'yuv444p' + stream.options = {'crf': '16', 'threads': '2'} + for index, strength in enumerate(strengths): + check() + edges = _join(strength, low, high) if high is not None else np.zeros(strength.shape, bool) + drawn = av.VideoFrame.from_ndarray(_line_frame(edges, (width, height)), format='rgb24') + drawn.pts, drawn.time_base = index, Fraction(video['fps_den'], video['fps_num']) + for packet in stream.encode(drawn): + container.mux(packet) + emit(done=video['frames'] + index + 1, total=total, unit='frames', phase=STAGE, + detail='%d/%d frames' % (video['frames'] + index + 1, total)) + for packet in stream.encode(None): + container.mux(packet) + return dict(low=low, high=high, sigma=sigma, working_size=list(work_size), av=av.__version__, + ffmpeg=av.library_versions, device='cpu') + finally: + strengths._mmap.close() + del strengths + strength_path.unlink(missing_ok=True) + + def _infer(source, stage, video, weights, device, emit, check): import av import numpy as np @@ -325,6 +491,11 @@ def _infer(source, stage, video, weights, device, emit, check): def _convert(request, emit, check): source, root, work = Path(request['source']), Path(request['root']), Path(request['work']) + mode = request.get('mode', 'depth') + if mode not in OUTPUT: + raise ValueError('Reference mode must be depth or lines') + if mode == 'lines': + return _convert_lines(request, source, work, emit, check) device = request.get('device', 'auto') if device == 'auto': import torch @@ -372,8 +543,43 @@ def _convert(request, emit, check): return dict(path=str(target / 'depth.mp4'), cache_hit=False, key=key) +def _convert_lines(request, source, work, emit, check): + """The line drawing: no model, no download, no GPU; same cache, validation and manifest as depth.""" + emit(phase=STAGE, label=LABELS['lines'], detail='Checking line reference cache') + initial_hash, initial_size = digest(source, check), source.stat().st_size + video = inspect_video(source, check) + config = identity(source, video, 'cpu', check, mode='lines') + if config['source_sha256'] != initial_hash or config['source_size'] != initial_size: + raise ValueError(LINES_SOURCE_CHANGED) + cache = Path(request['cache']) + key = cache_key(config) + target = cache / key + with _lock(cache / '.locks' / (key + '.lock'), check): + found = _cached(target, config, check) + if found is not None: + return dict(path=str(found), cache_hit=True, key=key) + emit(phase=STAGE, stage=STAGE, label=LABELS['lines'], done=0, total=2 * video['frames'], unit='frames', + detail='Finding the lines') + stage = work / 'result' + stage.mkdir() + metrics = _lines(source, stage, video, emit, check) + output = stage / OUTPUT['lines'] + observed = _validate(output, video, check) + if digest(source, check) != config['source_sha256'] or source.stat().st_size != config['source_size']: + raise ValueError(LINES_SOURCE_CHANGED) + manifest = dict(config=config, source_pts=video['pts'], source_time_base=video['time_base'], output=observed, + output_sha256=digest(output, check), output_bytes=output.stat().st_size, + normalization=metrics, render='line-art-v1') + (stage / 'manifest.json').write_text(canonical_json(manifest), encoding='utf-8') + check() + if target.exists(): + target.rename(cache / (key + '.rejected-' + uuid.uuid4().hex)) + os.replace(stage, target) + return dict(path=str(target / OUTPUT['lines']), cache_hit=False, key=key) + + def convert(source, *, root=None, cache=None, device='auto', python=None, environ=None, - progress=None, interrupted=None, release_models=None): + progress=None, interrupted=None, release_models=None, mode='depth'): """Convert in a supervised child; return a validated cache path after it exits. Progress carries stage=depth_reference and done/total in frames. Cancellation @@ -389,6 +595,8 @@ def check(): with tempfile.TemporaryDirectory(prefix='.depth-', dir=cache) as directory: work = Path(directory) request = dict(source=str(Path(source).resolve()), root=str(root), cache=str(cache), device=device, work=str(work)) + if mode != 'depth': + request['mode'] = mode # a depth request stays byte-identical to before (work / 'request.json').write_text(canonical_json(request), encoding='utf-8') command = processes.module_command('freevideo_engine.depth_reference', '--request', work / 'request.json') if python is not None: @@ -425,7 +633,8 @@ def poll(): try: error = json.loads((work / 'error.json').read_text(encoding='utf-8'))['error'] except (OSError, ValueError, KeyError): - error = 'Depth reference worker exited with code %s' % child.returncode + error = ('%s reference worker exited with code %s without saying why. Try again; if it happens again, ' + 'send the diagnostic report.' % ('Line' if mode == 'lines' else 'Depth', child.returncode)) raise RuntimeError(error) result = json.loads((work / 'result.json').read_text(encoding='utf-8')) check() @@ -436,21 +645,30 @@ def poll(): raise +def uses_conversion(media): + """Whether a request has a video reference to convert (depth only or lines only).""" + return any(row.get('depth') is True or row.get('lines') is True for row in (media or {}).get('references', [])) + + def prepare_media(media, *, root, machine, environ, progress, interrupted, release_models): - """Execution only. With depth off, return the original object unchanged.""" - if not any(row.get('depth') is True for row in media.get('references', [])): + """Execution only. With depth and lines off, return the original object unchanged.""" + if not uses_conversion(media): return media result = dict(media, references=[]) for row in media.get('references', []): - if 'depth' in row and (type(row['depth']) is not bool or row.get('kind') != 'video'): - raise ValueError('depth must be a boolean on a video reference') - if row.get('depth') is not True: + for key in ('depth', 'lines'): + if key in row and (type(row[key]) is not bool or row.get('kind') != 'video'): + raise ValueError(key + ' must be a boolean on a video reference') + if row.get('depth') is True and row.get('lines') is True: + raise ValueError('Choose depth only or lines only, not both') + mode = 'depth' if row.get('depth') is True else 'lines' if row.get('lines') is True else None + if mode is None: result['references'].append(row) continue converted = convert(row['path'], root=root, python=machine['python'], environ=environ, - device='cpu' if machine.get('device_backend') in ('cpu', 'mps') else 'cuda', - progress=progress, interrupted=interrupted, release_models=release_models) - value = {key: val for key, val in row.items() if key != 'depth'} + device='cpu' if mode == 'lines' or machine.get('device_backend') in ('cpu', 'mps') else 'cuda', + progress=progress, interrupted=interrupted, release_models=release_models, mode=mode) + value = {key: val for key, val in row.items() if key not in ('depth', 'lines')} value['path'] = str(converted) value.setdefault('early_steps', 3) result['references'].append(value) @@ -467,8 +685,8 @@ def main(): work = Path(request['work']) def check(): if (work / 'cancelled').exists(): - raise InterruptedError('Depth reference conversion cancelled') - state = dict(stage=STAGE, phase=STAGE, timing_phase='encoding', label='Extracting depth from the reference video', + raise InterruptedError('Reference conversion cancelled') + state = dict(stage=STAGE, phase=STAGE, timing_phase='encoding', label=LABELS.get(request.get('mode', 'depth'), LABELS['depth']), done=0, total=None, unit='frames', references=True) def emit(**values): state.update(values) diff --git a/freevideo_engine/dubbing/cosyvoice3_pack.json b/freevideo_engine/dubbing/cosyvoice3_pack.json index 9becf958..77446697 100644 --- a/freevideo_engine/dubbing/cosyvoice3_pack.json +++ b/freevideo_engine/dubbing/cosyvoice3_pack.json @@ -96,6 +96,35 @@ "path": "db/f3/3996583dd2906297a637af12114deddf7658af6e683fedb83be061983fb5/protobuf-7.36.2-cp310-abi3-manylinux2014_x86_64.whl" } ], + "linux-aarch64": [ + { + "name": "onnxruntime", + "version": "1.31.1", + "license": "MIT", + "file": "onnxruntime-1.31.1-cp312-cp312-manylinux_2_28_aarch64.whl", + "bytes": 21420803, + "sha256": "0b9a492176886992e0e875f06bc0367e333f5fff11711a2d642e18b02f3009cc", + "path": "ba/e4/1ed1a7a5f4702d899091fa2b976d377995250c307326ec8dc9ae6378aa13/onnxruntime-1.31.1-cp312-cp312-manylinux_2_28_aarch64.whl" + }, + { + "name": "flatbuffers", + "version": "25.12.19", + "license": "Apache-2.0", + "file": "flatbuffers-25.12.19-py2.py3-none-any.whl", + "bytes": 26661, + "sha256": "7634f50c427838bb021c2d66a3d1168e9d199b0607e6329399f04846d42e20b4", + "path": "e8/2d/d2a548598be01649e2d46231d151a6c56d10b964d94043a335ae56ea2d92/flatbuffers-25.12.19-py2.py3-none-any.whl" + }, + { + "name": "protobuf", + "version": "7.36.2", + "license": "BSD-3-Clause", + "file": "protobuf-7.36.2-cp310-abi3-manylinux2014_aarch64.whl", + "bytes": 344219, + "sha256": "e11e1f0180583a2af89db6a2ecd9e8dc40aa6d2988ca175bfd0e6d12ea72d74e", + "path": "b6/ea/91fdf7c2b8bbd49cde056f00a9df6773532987e1c00fe2830b895af95c7e/protobuf-7.36.2-cp310-abi3-manylinux2014_aarch64.whl" + } + ], "windows-x64": [ { "name": "onnxruntime", diff --git a/freevideo_engine/editor_export.py b/freevideo_engine/editor_export.py index c016c760..703fe67e 100644 --- a/freevideo_engine/editor_export.py +++ b/freevideo_engine/editor_export.py @@ -1120,6 +1120,19 @@ def _picture_folder(): return folder +def _copy_to_output(path): + """A saved frame is a picture like the ones the image page makes: with "Also save pictures to the output folder" on, + it is copied there under the same name, by the image service's own copy (its switch, its link checks, its removal + when the picture is deleted for good). Off, or without the service, nothing happens and nothing is said.""" + try: + from .image_gen.service import get_service + service = get_service() + except Exception: + return + if service is not None: + service.copy_to_output(path) + + def store_picture(pixels): """Write a frame as a lossless PNG named like the pictures the image editor lists (image-YYYYMMDD-HHMMSS-NN.png).""" from PIL import Image @@ -1138,6 +1151,7 @@ def store_picture(pixels): publish(temporary, target) except FileExistsError: continue + _copy_to_output(target) return dict(file='freevideo-image/' + target.name, name=target.name, width=int(pixels.shape[1]), height=int(pixels.shape[0])) raise ExportError() diff --git a/freevideo_engine/engine_binding.py b/freevideo_engine/engine_binding.py index 161d1e6e..5a7efb41 100644 --- a/freevideo_engine/engine_binding.py +++ b/freevideo_engine/engine_binding.py @@ -10,7 +10,7 @@ from urllib.request import url2pathname from . import subprocess_output -from .environments import uv_build_environment +from .environments import uv_build_environment, uv_folder from .monitoring import save from .long_paths import io_path, resolved, plain, plain_text, plain_errors from .runtime_alias import checked_real_path @@ -89,7 +89,7 @@ def source_version(source): def _uv(engine_root, machine, restore=None): system = machine.get('system') or ('Windows' if os.name == 'nt' else 'Darwin' if sys.platform == 'darwin' else 'Linux') - relative = {'Windows': 'uv.exe', 'Darwin': 'uv', 'Linux': 'uv-x86_64-unknown-linux-gnu/uv'}.get(system) + relative = {'Windows': 'uv.exe', 'Darwin': 'uv', 'Linux': uv_folder(machine.get('machine')) + '/uv'}.get(system) tool = io_path(engine_root) / 'tools' / relative if relative else None if tool is None or not tool.is_file(): where = 'The engine\'s uv is missing from %s/tools (%s)' % (engine_root, system) diff --git a/freevideo_engine/environments.py b/freevideo_engine/environments.py index 26753c31..fcb827dd 100644 --- a/freevideo_engine/environments.py +++ b/freevideo_engine/environments.py @@ -121,13 +121,52 @@ def uv_file_arguments(command, cwd=None): return result, str(folder) -def bootstrap_versions(value, system=None): +# Linux processors setup installs on, by the names platform.machine() and uname -m give them. +LINUX_MACHINES = {'x86_64': 'x86_64', 'amd64': 'x86_64', 'aarch64': 'aarch64', 'arm64': 'aarch64'} + + +def linux_machine(machine=None): + """'x86_64' or 'aarch64' for a Linux processor setup installs on; None for any other.""" + return LINUX_MACHINES.get(str(platform.machine() if machine is None else machine).lower()) + + +def setup_supported(system, machine): + """Setup installs on Linux x86_64 or ARM64 and on native Windows x64.""" + machine = str(machine or '').lower() + return (system == 'Linux' and linux_machine(machine) is not None + or system == 'Windows' and machine in ('x86_64', 'amd64')) + + +def uv_folder(machine=None): + """The folder the Linux uv archive unpacks to under /tools for this processor.""" + return 'uv-%s-unknown-linux-gnu' % (linux_machine(machine) or 'x86_64') + + +def conda_lock(value, machine=None): + """A conda-forge lock (micromamba and packages) for this Linux processor: its linux_aarch64 section on ARM64.""" + if linux_machine(machine) == 'aarch64' and 'linux_aarch64' in value: + return dict(value, **value['linux_aarch64']) + return value + + +def conda_triple(machine=None): + """The prefix conda-forge's GCC gives its compilers on this Linux processor.""" + return '%s-conda-linux-gnu' % (linux_machine(machine) or 'x86_64') + + +def bootstrap_versions(value, system=None, machine=None): result = dict(value, target_system=system or platform.system()) if result['target_system'] == 'Darwin': from .macos_bootstrap import versions return versions(value) if result['target_system'] == 'Windows': result['uv'] = result['windows']['uv'] + elif result['target_system'] == 'Linux': + result['target_machine'] = linux_machine(machine) or 'x86_64' + if result['target_machine'] == 'aarch64': + # ARM64 servers (and GB10) take NVIDIA's linux-sbsa toolkit archives of the same versions. + result['uv'] = result['linux_aarch64']['uv'] + result['cuda_toolkits'] = result['linux_aarch64']['cuda_toolkits'] return result diff --git a/freevideo_engine/gcc_linux.json b/freevideo_engine/gcc_linux.json index b832a479..577cd43c 100644 --- a/freevideo_engine/gcc_linux.json +++ b/freevideo_engine/gcc_linux.json @@ -111,5 +111,110 @@ "sha256": "b928c30ddcb0e3f544c6eade8352737e6e610e263276b90232db6a578ef899d8", "bytes": 118849 } - ] + ], + "linux_aarch64": { + "micromamba": { + "version": "2.9.0-0", + "url": "https://github.com/mamba-org/micromamba-releases/releases/download/2.9.0-0/micromamba-linux-aarch64", + "sha256": "9f93b974adcb4d166996af969b6cd371287d1a3e52733704727884d9b74cb7a7", + "bytes": 22020296 + }, + "packages": [ + { + "path": "noarch/libgcc-devel_linux-aarch64-14.4.0-ha8b83fe_107.conda", + "sha256": "eb11561edaf5000b9015b7c56e5f820045c49bbdfd4baee4db6e05124601236f", + "bytes": 2351053 + }, + { + "path": "noarch/libstdcxx-devel_linux-aarch64-14.4.0-hc896aa5_107.conda", + "sha256": "553dccd5120898d6827fc2d3401e1451734124c50713b2352ab7d8d5134c7aa5", + "bytes": 17504825 + }, + { + "path": "noarch/kernel-headers_linux-aarch64-5.14.0-h05a177a_3.conda", + "sha256": "2b7a5ee2d377ce1d923870c3e235360ea401fd8a8f086d88ef6b56c986eae725", + "bytes": 1381767 + }, + { + "path": "noarch/tzdata-2026e-h5d301ff_0.conda", + "sha256": "2b7ca858879f183ce2dcc65b300f48a0133d5430550f35b23d80d405a0788dbf", + "bytes": 119208 + }, + { + "path": "noarch/sysroot_linux-aarch64-2.34-h96c1060_3.conda", + "sha256": "5a7bd6d0e34aa517aef68f902659f65090c7a022cb194114cca858efa6faacd0", + "bytes": 40329553 + }, + { + "path": "linux-aarch64/libgomp-16.2.0-h8acb6b2_7.conda", + "sha256": "4406fd67c5beeb99b9372f9bf07aa3e40ca141e337eceebac3ff64aa72799494", + "bytes": 617342 + }, + { + "path": "linux-aarch64/libzlib-1.3.2-hdc9db2a_3.conda", + "sha256": "76efa6cc9d7e6f5ee3bbca0939f64054af2bdfb3c3632531f8e633cf6c2ea41e", + "bytes": 70108 + }, + { + "path": "linux-aarch64/_openmp_mutex-4.5-20_gnu.conda", + "sha256": "a2527b1d81792a0ccd2c05850960df119c2b6d8f5fdec97f2db7d25dc23b1068", + "bytes": 28926 + }, + { + "path": "linux-aarch64/zstd-1.5.7-h9d15635_7.conda", + "sha256": "427fd14bcb3b8659796fecc682716617409350fb5a98e5b7b47558a10d1a2fc7", + "bytes": 615477 + }, + { + "path": "linux-aarch64/libgcc-16.2.0-h205dda4_7.conda", + "sha256": "eae7a3449d5a3b5351c5427137c076cc3fc826645c7bfc42dc10772b783826f1", + "bytes": 627793 + }, + { + "path": "linux-aarch64/ld_impl_linux-aarch64-2.46.1-default_h1979696_103.conda", + "sha256": "516808982ad26ebdc4a9d8f71ee86ea55d0bc95382b7bca80620e0ac220971f3", + "bytes": 905349 + }, + { + "path": "linux-aarch64/libstdcxx-16.2.0-hef695bb_7.conda", + "sha256": "b241a3acfa9cdb1359112864a1241225533c92642de3000d52ae65ef5d3a9786", + "bytes": 6236630 + }, + { + "path": "linux-aarch64/binutils_impl_linux-aarch64-2.46.1-default_h5f4c503_103.conda", + "sha256": "1827893f9d6aa13794196b1820b8003bfff0105774a323a61026a16cec6dc66d", + "bytes": 4911258 + }, + { + "path": "linux-aarch64/libsanitizer-14.4.0-h5c092e3_7.conda", + "sha256": "5ef0faf52db0eada4807e209e1b6d8d4ed554efc1e2e9d4007d7d243dbbac917", + "bytes": 7100341 + }, + { + "path": "linux-aarch64/binutils_linux-aarch64-2.46.1-default_hf1166c9_103.conda", + "sha256": "60e63ac488aac474f8a22ea465d317daa02fccd039cca75e288bd0fc37e8745a", + "bytes": 36474 + }, + { + "path": "linux-aarch64/gcc_impl_linux-aarch64-14.4.0-hcd8d054_7.conda", + "sha256": "e0a3109cb1c8f83704d0b76c5ee8a56bf34fad16f6e884dae416712f753638dc", + "bytes": 69832767 + }, + { + "path": "linux-aarch64/gxx_impl_linux-aarch64-14.4.0-h66ee75d_7.conda", + "sha256": "cb6bdf99cc59dd5916ec55097d26f612ae3899c744270933d8883dd5a80af799", + "bytes": 14385294 + }, + { + "path": "linux-aarch64/gcc_linux-aarch64-14.4.0-hab84b30_4.conda", + "sha256": "5d4694c664cc813f1223ef837101daa10e489f2fd93287a2f7f6e336c717afbb", + "bytes": 29693 + }, + { + "path": "linux-aarch64/gxx_linux-aarch64-14.4.0-h927cbce_4.conda", + "sha256": "6d892017504ef9635e85181136dfdbb749bdd1a487289e7b4fa2208471bbd466", + "bytes": 28134 + } + ] + } } diff --git a/freevideo_engine/generate.py b/freevideo_engine/generate.py index 62059132..e4e1bb19 100644 --- a/freevideo_engine/generate.py +++ b/freevideo_engine/generate.py @@ -523,6 +523,10 @@ def usable_continuation(value, *check): return freeze_continuation(value) if continuation_directory is not None else value frames = getattr(args, 'frames', None) + redo_sound = getattr(args, 'redo_sound', None) + if redo_sound is not None: + from .redo_audio import probe as redo_probe + frames = redo_probe(redo_sound) continue_from = getattr(args, 'continue_from', None) continue_anchor = getattr(args, 'continue_anchor', None) if continue_anchor is not None and continue_from is None: @@ -1156,6 +1160,8 @@ def validate(metrics, telemetry, selected): 'sampling_plan': sampling_plan, 'upscaler_checkpoint': upscaler_checkpoint, 'automatic_pass_cache': not bool(args.profile), 'metrics': str(destination.with_suffix('.engine.json'))} + if redo_sound is not None: + request['redo_audio'] = {'video': str(Path(redo_sound).resolve())} if continuation is not None: request['continuation'] = continuation if hide_tail_frames: diff --git a/freevideo_engine/git_linux.json b/freevideo_engine/git_linux.json index 62c28186..cd310298 100644 --- a/freevideo_engine/git_linux.json +++ b/freevideo_engine/git_linux.json @@ -142,5 +142,145 @@ "sha256": "d5654608f2bed18580fa05e22d80093fc746cc70dea1d6a208e7a9f65b1888e0", "bytes": 11920563 } - ] + ], + "linux_aarch64": { + "micromamba": { + "version": "2.9.0-0", + "url": "https://github.com/mamba-org/micromamba-releases/releases/download/2.9.0-0/micromamba-linux-aarch64", + "sha256": "9f93b974adcb4d166996af969b6cd371287d1a3e52733704727884d9b74cb7a7", + "bytes": 22020296 + }, + "packages": [ + { + "path": "linux-aarch64/libzlib-1.3.2-hdc9db2a_3.conda", + "sha256": "76efa6cc9d7e6f5ee3bbca0939f64054af2bdfb3c3632531f8e633cf6c2ea41e", + "bytes": 70108 + }, + { + "path": "linux-aarch64/libgomp-16.2.0-h8acb6b2_7.conda", + "sha256": "4406fd67c5beeb99b9372f9bf07aa3e40ca141e337eceebac3ff64aa72799494", + "bytes": 617342 + }, + { + "path": "linux-aarch64/zstd-1.5.7-h9d15635_7.conda", + "sha256": "427fd14bcb3b8659796fecc682716617409350fb5a98e5b7b47558a10d1a2fc7", + "bytes": 615477 + }, + { + "path": "linux-aarch64/_openmp_mutex-4.5-20_gnu.conda", + "sha256": "a2527b1d81792a0ccd2c05850960df119c2b6d8f5fdec97f2db7d25dc23b1068", + "bytes": 28926 + }, + { + "path": "linux-aarch64/libgcc-16.2.0-h205dda4_7.conda", + "sha256": "eae7a3449d5a3b5351c5427137c076cc3fc826645c7bfc42dc10772b783826f1", + "bytes": 627793 + }, + { + "path": "linux-aarch64/ncurses-6.6-h2b6f883_1.conda", + "sha256": "d69a04914139627f0a6bfd19412d6c7f1e37edc896af84a6011e07e8bc1e69fa", + "bytes": 955422 + }, + { + "path": "linux-aarch64/libev-4.33-h80f16a2_3.conda", + "sha256": "4475f79a020e9ff2a5a0308c48cb2970a25d55c3dd724a97ab28bfac3be6cd49", + "bytes": 45746 + }, + { + "path": "linux-aarch64/keyutils-1.6.3-h5bc82ec_1.conda", + "sha256": "3999b1472f1e549a0b766428e2823abf20626aac5314b474c9b76bf6eb679def", + "bytes": 129546 + }, + { + "path": "linux-aarch64/bzip2-1.0.8-h4777abc_10.conda", + "sha256": "24eacc8a20fd7c4616566178562bef7f9344eb4a8700cfc3180fa75a6ff9d39f", + "bytes": 194694 + }, + { + "path": "linux-aarch64/c-ares-1.34.9-h29ee22c_0.conda", + "sha256": "76683c88b796b7d72ef5d675e86d3b9959d2af1c78343e9ba2ff041d5029e06d", + "bytes": 246798 + }, + { + "path": "linux-aarch64/libstdcxx-16.2.0-hef695bb_7.conda", + "sha256": "b241a3acfa9cdb1359112864a1241225533c92642de3000d52ae65ef5d3a9786", + "bytes": 6236630 + }, + { + "path": "linux-aarch64/libiconv-1.18-h1ea5142_3.conda", + "sha256": "d22c666eb887afd2119aac2110e23a0e817e9391bda99293421f7c46dab1564c", + "bytes": 785924 + }, + { + "path": "linux-aarch64/libxcrypt-4.4.38-h80f16a2_0.conda", + "sha256": "d3514900e2121972e435f7803763c1843dad6709e48aa02a2b47c4d481f83be7", + "bytes": 133882 + }, + { + "path": "linux-aarch64/libexpat-2.9.0-h4154aff_0.conda", + "sha256": "d3327ab1086334309cab3cf533c95f70c44dcbb8f66a99a92b23fb0f3f20f1da", + "bytes": 80340 + }, + { + "path": "linux-aarch64/libedit-3.1.20260512-pl5321hc48eb74_0.conda", + "sha256": "58fd637d0219016bb69edf2973b089975de283e8a38149d69ef586b8fc4ad90b", + "bytes": 149680 + }, + { + "path": "linux-aarch64/pcre2-10.49-he574923_0.conda", + "sha256": "2c01cc846cfd629ade4792e38e9880266077fc9ffc2c6724016008541893888d", + "bytes": 1209693 + }, + { + "path": "linux-aarch64/icu-79.1-py313h6ffeb17_0.conda", + "sha256": "3a9980bb831de258c56d6861fb7bc5aeaadb7cbc143a684b56b1d178dc9a24e9", + "bytes": 14885952 + }, + { + "path": "linux-aarch64/perl-5.44.0-1_h5bc82ec_perl5.conda", + "sha256": "7cf91a128068608c731df55e9c452cccb179b84df086ebc95f70797092c55d73", + "bytes": 11484751 + }, + { + "path": "linux-aarch64/libpsl-0.23.1-h37fd031_2.conda", + "sha256": "ce9d5d8ab141b55242a4c82f067bbc340fcd0e009218ac30b6d80ee1795666db", + "bytes": 73191 + }, + { + "path": "noarch/ca-certificates-2026.10.23-hbd8a1cb_0.conda", + "sha256": "95619b9c1184be7175392eeb0ee7eeb5ccf25d280951f4225f2d62e725790be3", + "bytes": 130057 + }, + { + "path": "linux-aarch64/openssl-3.6.5-he6ad1d5_0.conda", + "sha256": "238136f1df197ecd89bafd728a34d0642176f3170423d13d8276746d675a9485", + "bytes": 3716078 + }, + { + "path": "linux-aarch64/libssh2-1.11.1-h7572e3e_1.conda", + "sha256": "f6fef76c1c8899d7976030871b8cd8016b0a306d2b8519834cd6491d6a42fb82", + "bytes": 315682 + }, + { + "path": "linux-aarch64/krb5-1.22.2-h095d8e5_2.conda", + "sha256": "601d79af94d9562ba70e2d4947034ba159aae293a3c860855335a7c76c14400e", + "bytes": 1538590 + }, + { + "path": "linux-aarch64/libnghttp2-1.71.0-h0d23a54_0.conda", + "sha256": "27b87291a76284071088204f8d48023cceea870e9e566eee4d1cddd7b08c4a93", + "bytes": 942290 + }, + { + "path": "linux-aarch64/libcurl-8.23.0-h86273da_0.conda", + "sha256": "4a9bc4ef7f6ddaef61a900d360214fb285c6aa474a3d7e1c5e4e42b4b2e36697", + "bytes": 529565 + }, + { + "path": "linux-aarch64/git-2.56.0-pl5440he8b3b7f_1.conda", + "sha256": "8030d33d12bf6f8a8a2814ec85a200c64078f7b57731bf0970d3e51702c7de2c", + "bytes": 17443186 + } + ] + } } diff --git a/freevideo_engine/image_gen/layer_stream.py b/freevideo_engine/image_gen/layer_stream.py index 16d3beac..2be13fd3 100644 --- a/freevideo_engine/image_gen/layer_stream.py +++ b/freevideo_engine/image_gen/layer_stream.py @@ -65,9 +65,13 @@ def read_into(path, offset, length, buffer): class DiskLayerStream: """Serve ``layers`` (modules with the same parameter shapes) from ``index``; ``key(i, name)`` names a tensor.""" - def __init__(self, layers, index, key, device, ahead=READ_AHEAD, threads=READ_THREADS): + def __init__(self, layers, index, key, device, ahead=READ_AHEAD, threads=READ_THREADS, keep=()): self.layers, self.index, self.key, self.device = list(layers), index, key, torch.device(device) self.ahead, self.bytes_read = ahead, 0 + # Layers in ``keep`` are read once and stay on the card; the others are streamed each time they run. + self.keep = {i for i in keep if 0 <= i < len(self.layers)} + self.order = [i for i in range(len(self.layers)) if i not in self.keep] + self.pos = {i: p for p, i in enumerate(self.order)} self.pool = ThreadPoolExecutor(threads) self.ready = {} self.pinned = self.device.type == 'cuda' @@ -78,7 +82,10 @@ def __init__(self, layers, index, key, device, ahead=READ_AHEAD, threads=READ_TH self.slot_kind = [] self.free = {} self.kinds = [] - for layer in self.layers: + for i, layer in enumerate(self.layers): + if i in self.keep: + self.kinds.append(None) + continue params = dict(layer.named_parameters()) kind = tuple((n, tuple(p.shape), p.dtype) for n, p in params.items()) self.kinds.append(kind) @@ -92,6 +99,9 @@ def __init__(self, layers, index, key, device, ahead=READ_AHEAD, threads=READ_TH self.events = {} self.handles = [] for i, layer in enumerate(self.layers): + if i in self.keep: + self._load_kept(i) + continue for module in layer.modules(): for name, param in list(module.named_parameters(recurse=False)): setattr(module, name, torch.nn.Parameter( @@ -99,6 +109,21 @@ def __init__(self, layers, index, key, device, ahead=READ_AHEAD, threads=READ_TH self.handles.append(layer.register_forward_pre_hook(self._before(i))) self.handles.append(layer.register_forward_hook(self._after(i))) + def _load_kept(self, i): + """Read a kept layer's weights straight onto the card; it never leaves.""" + layer = self.layers[i] + for module_name, module in layer.named_modules(): + for name, param in list(module.named_parameters(recurse=False)): + full = name if not module_name else module_name + '.' + name + path, offset, length = self.index.locate(self.key(i, full)) + host = torch.empty(param.shape, dtype=param.dtype) + if length != host.numel() * host.element_size(): + raise ValueError('%s in %s holds %d bytes, the model expects %d; wrong dtype or shape' + % (self.key(i, full), path, length, host.numel() * host.element_size())) + read_into(path, offset, length, host.view(torch.uint8).reshape(-1)) + self.bytes_read += length + setattr(module, name, torch.nn.Parameter(host.to(self.device), requires_grad=False)) + def _read(self, i, slot): out = self.slots[slot] for name, param in self.layers[i].named_parameters(): @@ -119,18 +144,20 @@ def _take_slot(self, i): return slot def _kick(self, j): - if 0 <= j < len(self.layers) and j not in self.ready: + if j not in self.keep and 0 <= j < len(self.layers) and j not in self.ready: slot = self._take_slot(j) self.ready[j] = (slot, self.pool.submit(self._read, j, slot)) def _before(self, i): def hook(module, args, kwargs=None): - for j in [j for j in self.ready if not i <= j <= i + self.ahead]: + window = set(self.order[self.pos[i]:self.pos[i] + self.ahead + 1]) + for j in [j for j in self.ready if j not in window]: slot, future = self.ready.pop(j) future.result() self.free[self.kinds[j]].append(slot) - for j in range(i, i + self.ahead + 1): - if j == i or (0 <= j < len(self.layers) and self.free[self.kinds[j]]): + start = self.pos[i] + for j in self.order[start:start + self.ahead + 1]: + if j == i or self.free[self.kinds[j]]: self._kick(j) slot, future = self.ready.pop(i) future.result() diff --git a/freevideo_engine/image_gen/moss_layout.py b/freevideo_engine/image_gen/moss_layout.py new file mode 100644 index 00000000..3b9d75fd --- /dev/null +++ b/freevideo_engine/image_gen/moss_layout.py @@ -0,0 +1,101 @@ +"""MOSS-Image layout prompts: boxes drawn on the picture, each saying what goes there, written as the JSON MOSS reads. + +The model-facing form is MOSS-Image's own (USERGUIDE "Layout Prompts", Apache-2.0): + + {"summary": {"caption": }, "items": [{"label", "caption", "text"?, "palette"?, "bbox"}], + "bbox_coord_space": "abs_centralized", "bbox_format": "yxyx"} + +``bbox`` is [top, left, bottom, right] in pixels of the picture made, measured from its centre (x to the right, y +down). Boxes come in as fractions of the picture (0..1, from the top-left), so they are written only once the final +width and height are known: a box drawn on the page lands on the same part of the picture whatever size is made. +Fractional edges enclose the box (top/left down, bottom/right up) before the centre is taken off. + +The text is passed to the model as it is: a prompt rewrite would rewrite the JSON as prose and drop the boxes. +""" +import json +import math + +LABELS = ('object', 'character', 'text') +MAX_ITEMS = 16 +MAX_CAPTION = 400 +MAX_TEXT = 200 +MAX_PALETTE = 5 +# The text encoder reads at most 4096 tokens and cuts the rest silently, which would cut the JSON. MOSS's tokenizer +# gives about 3.5 characters a token in English and 1.7 at worst in Chinese layouts, so this stays near 2100 tokens +# at most; ten boxes with a sentence each are 1100-1800 characters. +MAX_CHARS = 3600 + + +class LayoutError(ValueError): + """A layout that cannot be written; ``code`` is the reason the page shows.""" + + def __init__(self, code, index=None): + super().__init__(code if index is None else '%s (box %d)' % (code, index + 1)) + self.code = code + self.index = index + + +def _words(value, limit, code, index, required=True): + if value is None and not required: + return None + if not isinstance(value, str) or (required and not value.strip()) or len(value) > limit: + raise LayoutError(code, index) + return value.strip() + + +def _edges(box, width, height, index): + if not isinstance(box, (list, tuple)) or len(box) != 4: + raise LayoutError('invalid_layout', index) + if not all(type(v) in (int, float) and math.isfinite(v) for v in box): + raise LayoutError('invalid_layout', index) + x0, y0, x1, y1 = box + if not (0 <= x0 < x1 <= 1 and 0 <= y0 < y1 <= 1): + raise LayoutError('invalid_layout', index) + # Rounded first so that a fraction written from whole pixels comes back as those pixels. + top, left = math.floor(round(y0 * height, 6)), math.floor(round(x0 * width, 6)) + bottom, right = math.ceil(round(y1 * height, 6)), math.ceil(round(x1 * width, 6)) + # A box thinner than the rounding keeps no width or height in pixels; MOSS's own compiler refuses it too. + if not (top < bottom and left < right): + raise LayoutError('invalid_layout', index) + return [top - height // 2, left - width // 2, bottom - height // 2, right - width // 2] + + +def compile_layout(caption, items, width, height): + """The MOSS prompt for ``caption`` (the whole picture) and ``items`` on a ``width`` x ``height`` picture. + + Each item: ``label`` (object, character or text), ``caption`` (what it looks like), ``text`` (the exact words, for + a text box), optional ``palette`` (up to five colours) and ``box`` [left, top, right, bottom] as fractions.""" + caption = _words(caption, 2000, 'invalid_prompt', None) + if type(width) is not int or type(height) is not int or width <= 0 or height <= 0: + raise LayoutError('invalid_dimensions') + if not isinstance(items, list) or not items: + raise LayoutError('invalid_layout') + if len(items) > MAX_ITEMS: + raise LayoutError('too_many_boxes') + out = [] + for index, item in enumerate(items): + if not isinstance(item, dict) or not set(item) <= {'label', 'caption', 'text', 'palette', 'box'}: + raise LayoutError('invalid_layout', index) + label = item.get('label', 'object') + if label not in LABELS: + raise LayoutError('invalid_layout', index) + row = {'label': label} + text = _words(item.get('text'), MAX_TEXT, 'invalid_layout', index, required=label == 'text') + # A text box may say only its words; the model still wants a caption, so the words stand in for it. + row['caption'] = _words(item.get('caption') or (text and 'The words "%s".' % text), MAX_CAPTION, + 'invalid_layout', index) + if label == 'text': + row['text'] = text + palette = item.get('palette') + if palette: + if (not isinstance(palette, list) or len(palette) > MAX_PALETTE + or not all(isinstance(c, str) and 0 < len(c) <= 32 for c in palette)): + raise LayoutError('invalid_layout', index) + row['palette'] = palette + row['bbox'] = _edges(item.get('box'), width, height, index) + out.append(row) + prompt = json.dumps({'summary': {'caption': caption}, 'items': out, 'bbox_coord_space': 'abs_centralized', + 'bbox_format': 'yxyx'}, ensure_ascii=False, separators=(',', ':'), allow_nan=False) + if len(prompt) > MAX_CHARS: + raise LayoutError('layout_too_long') + return prompt diff --git a/freevideo_engine/image_gen/moss_pipeline.py b/freevideo_engine/image_gen/moss_pipeline.py index 699ec99d..5454eb69 100644 --- a/freevideo_engine/image_gen/moss_pipeline.py +++ b/freevideo_engine/image_gen/moss_pipeline.py @@ -24,6 +24,9 @@ STEPS = 50 GUIDANCE = 3. SKIP_LAYERS = (22,) +LAYERS = 42 +LAYER_GIB = 0.225 # one bf16 DiT layer +KEEP_MARGIN_GIB = 1.5 SIDE_MULTIPLE = 16 MAX_SIDE = 2048 MIN_SIDE = 256 @@ -61,11 +64,27 @@ def folder_key(folder): return tuple(parts) -def plan(vram_gib): - """Where each part goes for a card budget in GiB: {'dit': 'resident'|'stream', 'encoder': ...}.""" +def keep_layers(vram_gib, width, height, layers=LAYERS, layer_gib=LAYER_GIB): + """How many DiT layers a streamed run keeps on the card: what the budget leaves after the picture's own working + memory (measured about 0.3 GiB plus 2.4 GiB per megapixel, streaming alone) and a margin for the driver.""" + working = 0.3 + 2.4 * width * height / 1e6 + spare = float(vram_gib or 0) - working - KEEP_MARGIN_GIB + return max(0, min(layers - 1, int(spare / layer_gib))) + + +def kept_indices(count, layers=LAYERS): + """``count`` layer indices spread evenly, so the next streamed layer is read while kept ones run.""" + if count <= 0: + return () + return tuple(sorted({int((k + 0.5) * layers / count) for k in range(count)})) + + +def plan(vram_gib, width=1024, height=1024): + """Where each part goes for a card budget in GiB: {'dit': 'resident'|'stream', 'encoder': ..., 'keep': n}.""" vram = float(vram_gib or 0) - return dict(dit='resident' if vram >= DIT_RESIDENT_GIB else 'stream', - encoder='resident' if vram >= ENCODER_RESIDENT_GIB else 'stream') + dit = 'resident' if vram >= DIT_RESIDENT_GIB else 'stream' + return dict(dit=dit, encoder='resident' if vram >= ENCODER_RESIDENT_GIB else 'stream', + keep=0 if dit == 'resident' else keep_layers(vram, width, height)) class PairedForward: @@ -185,7 +204,7 @@ def _one(index, key, device): return handle.get_tensor(key).to(device) -def _build_dit(module, folder, device, placement): +def _build_dit(module, folder, device, placement, keep=0): """The DiT with its non-layer weights on the card; returns (transformer, stream or None).""" import torch from .layer_stream import DiskLayerStream @@ -204,7 +223,8 @@ def _build_dit(module, folder, device, placement): for name, buffer in transformer.named_buffers(): if buffer.is_meta: raise RuntimeError('MOSS-Image: buffer %s was not loaded from the files' % name) - return transformer, DiskLayerStream(transformer.layers, index, layer_key(''), device) + return transformer, DiskLayerStream(transformer.layers, index, layer_key(''), device, + keep=kept_indices(keep, len(transformer.layers))) def generate(prompt, width, height, seed, progress=None, cancel=None, *, folder, vram_gib=None, kept=None, @@ -229,7 +249,7 @@ def check(): kept.key = key free_gib = torch.cuda.mem_get_info()[0] / 2**30 + (torch.cuda.memory_reserved() / 2**30) budget = min(float(vram_gib), free_gib) if vram_gib else free_gib - placement = plan(budget) + placement = plan(budget, width, height) stats['placement'] = placement check() progress('encode', 0, 1) @@ -251,7 +271,7 @@ def check(): if resident and kept.dit is not None: transformer, stream = kept.dit, None else: - transformer, stream = _build_dit(module, folder, device, placement['dit']) + transformer, stream = _build_dit(module, folder, device, placement['dit'], placement.get('keep', 0)) if resident: kept.dit = transformer stats['dit_load_s'] = round(time.time() - started, 2) diff --git a/freevideo_engine/image_gen/service.py b/freevideo_engine/image_gen/service.py index 348b348a..9f9c0d78 100644 --- a/freevideo_engine/image_gen/service.py +++ b/freevideo_engine/image_gen/service.py @@ -92,7 +92,8 @@ # Pictures that may wait behind the running one; a further request is turned away with 'busy'. QUEUE_LIMIT = 8 INVALID_ERRORS = frozenset(('invalid_request', 'invalid_prompt', 'invalid_dimensions', 'invalid_seed', - 'invalid_media', 'invalid_points', 'too_many_images')) | LORA_ERRORS + 'invalid_media', 'invalid_points', 'too_many_images', + 'invalid_layout', 'too_many_boxes', 'layout_too_long')) | LORA_ERRORS def native_allocator(env): @@ -1336,7 +1337,19 @@ def request(self, value): purpose = value.get('purpose') if purpose is not None and purpose not in PURPOSES: raise ValueError('invalid_request') - result = dict(prompt=prompt, width=dimensions[0] // 32 * 32, height=dimensions[1] // 32 * 32, + dimensions = [size // 32 * 32 for size in dimensions] + layout = value.get('layout') + if layout is not None: + # Boxes drawn on the picture (MOSS only): written against the size actually made, so each box covers the + # same part of the picture as on the page. The prompt is the caption of the whole picture. + if model != image_model.MOSS: + raise ValueError('invalid_request') + from .moss_layout import LayoutError, compile_layout + try: + prompt = compile_layout(prompt, layout, *dimensions) + except LayoutError as error: + raise ValueError(error.code) from None + result = dict(prompt=prompt, width=dimensions[0], height=dimensions[1], steps=8, seed=seed, images=paths, **(dict(mask=mask_path) if mask_path else {}), **(dict(cast_view='back') if cast_view == 'back' else {}), path=self.output_path(named=True), @@ -2179,7 +2192,7 @@ def server_keeps_video(self, machine): return False # Which picture model comes is not known yet when the session starts: the larger installed one counts. sizes = [] - for files in (self.warm_files(machine), self.qwen_files(machine)): + for files in (self.model_files(machine, model) for model in image_model.MODELS): try: sizes.append(sum(os.path.getsize(item) for item in files)) except OSError: diff --git a/freevideo_engine/installation_cleanup.py b/freevideo_engine/installation_cleanup.py index 512ba558..cebe9199 100644 --- a/freevideo_engine/installation_cleanup.py +++ b/freevideo_engine/installation_cleanup.py @@ -9,6 +9,7 @@ import sys import threading +from .environments import uv_folder from .locking import runtime_lock from .storage import fingerprint from .long_paths import io_path, resolved, plain @@ -76,7 +77,7 @@ def uv_path(root): root = checked_real_path(root) root = resolved(root) if root != selected else io_path(root) relative = ('uv.exe' if os.name == 'nt' else 'uv' if sys.platform == 'darwin' - else 'uv-x86_64-unknown-linux-gnu/uv') + else uv_folder() + '/uv') path = root / 'tools' / relative return Path(plain(path)) if local_path(root, path) and path.is_file() else None diff --git a/freevideo_engine/network.py b/freevideo_engine/network.py index 83b06457..4b153961 100644 --- a/freevideo_engine/network.py +++ b/freevideo_engine/network.py @@ -312,7 +312,8 @@ def probe(family, name, spec, versions, timeout, env, *, measure_speed=False): url = wheel_link(base + '/packaging/', r'^packaging-26\.3-py3-none-any\.whl$', timeout, env) elif family.startswith('torch-'): _, cuda, version = family.split('-') - target = r'win_amd64' if versions.get('target_system') == 'Windows' else r'(?:manylinux[^/]*|linux)_x86_64' + target = (r'win_amd64' if versions.get('target_system') == 'Windows' + else r'(?:manylinux[^/]*|linux)_' + ('aarch64' if versions.get('target_machine') == 'aarch64' else 'x86_64')) url = wheel_link(base + '/' + cuda + '/torch/', r'^torch-' + re.escape(version + '+' + cuda) + r'-cp312-cp312-' + target + r'\.whl$', timeout, env) elif family == 'models': settings = spec['models'] @@ -1824,6 +1825,22 @@ def remove_earlier_replaced(target, keep): pass # Held by another program; a later replacement tries again. +REPOSITORY_RETRY_SECONDS = (1, 3, 10) + + +def repository_missing(error): + """Git's answer when the folder `git init` just made is not a repository.""" + text = str(error).lower() + return 'not in a git directory' in text or 'not a git repository' in text + + +def repository_missing_message(target): + return ('FreeVideo could not keep the Git repository it created for %s: its files disappeared right after Git ' + 'wrote them. Another program on this computer, such as security software, or the drive may be removing ' + 'or blocking them. Allow FreeVideo\'s folder in that program or install to another drive, then retry ' + 'installation.' % Path(target).name) + + def clone(target, url, commit, *, sparse=None, run=None, network=None, env=None): """Fetch only the pinned commit, atomically; never reset existing checkouts. @@ -1895,7 +1912,31 @@ def execute(label, command): execute(target.name + '-init-' + name, ['git', 'init', '--quiet', work]) # Never depend on a user's global CRLF conversion or long-path # settings when constructing the exact official patched tree. - execute(target.name + '-line-endings', ['git', '-C', work, 'config', 'core.autocrlf', 'false']) + try: + execute(target.name + '-line-endings', ['git', '-C', work, 'config', 'core.autocrlf', 'false']) + except RuntimeError as error: + if not repository_missing(error): + raise + # Git reported success for `init`, yet the repository is not there: something + # removed or blocked its files right after they were written. Start the + # repository again a few times before giving up with a plain explanation. + for pause in REPOSITORY_RETRY_SECONDS: + event(network, category='git', source=name, route=route, file=target.name, action='repository-missing', + commit=commit, wait_seconds=pause) + try: + remove_tree(work) + except OSError: + pass # Held by another program; init below reports it if it matters. + time.sleep(pause) + execute(target.name + '-init-' + name, ['git', 'init', '--quiet', work]) + try: + execute(target.name + '-line-endings', ['git', '-C', work, 'config', 'core.autocrlf', 'false']) + break + except RuntimeError as again: + if not repository_missing(again): + raise + else: + raise RuntimeError(repository_missing_message(target)) from error execute(target.name + '-long-paths', ['git', '-C', work, 'config', 'core.longpaths', 'true']) if sparse: # The patterns file with cone mode off is what `sparse-checkout diff --git a/freevideo_engine/original_audio.py b/freevideo_engine/original_audio.py index f50178fc..1ad495e4 100644 --- a/freevideo_engine/original_audio.py +++ b/freevideo_engine/original_audio.py @@ -318,12 +318,42 @@ def _audio_stream(container, codec, rate, channels, itemsize): stream = container.add_stream(codec, rate=rate, layout='mono' if channels == 1 else 'stereo') fmt = _FORMATS[codec] stream.codec_context.format = fmt + if codec == 'aac': + stream.codec_context.bit_rate = 320000 if codec == 'flac' and itemsize == 4: fmt = stream.codec_context.format = 's32' stream.codec_context.options = {'bits_per_raw_sample': '24'} return stream, fmt +AAC_RATES = frozenset((7350, 8000, 11025, 12000, 16000, 22050, 24000, 32000, 44100, 48000, 64000, 88200, 96000)) +AAC_FALLBACK_RATE = 48000 + + +def _resampled(chunks, rate, channels, target=AAC_FALLBACK_RATE): + """Channel-first float chunks converted from `rate` to `target`, piece by piece.""" + import av + import numpy as np + layout = 'mono' if channels == 1 else 'stereo' + resampler = av.AudioResampler(format='fltp', layout=layout, rate=target) + + def arrays(frames): + for frame in frames or (): + yield np.ascontiguousarray(frame.to_ndarray(), dtype=np.float32) + + for chunk in chunks: + frame = av.AudioFrame.from_ndarray(np.ascontiguousarray(chunk, dtype=np.float32), format='fltp', layout=layout) + frame.sample_rate = rate + yield from arrays(resampler.resample(frame)) + yield from arrays(resampler.resample(None)) + + +def _to_float(data): + """Native samples as 32-bit float amplitudes for the AAC encoder.""" + import numpy as np + return _normalized(data).astype(np.float32, copy=False) + + def _encoded(stream, fmt, chunks, rate): """Packets for channel-first chunks of any length, encoded as they arrive.""" import av @@ -362,7 +392,7 @@ def encode_audio(container, codec, samples, rate): return stream, list(_encoded(stream, fmt, [samples], rate)) -def _mux_streams(picture, target, rate, copy_from=None, encode=None): +def _mux_streams(picture, target, rate, copy_from=None, encode=None, audio_rate=None): """Write picture's video plus one audio track, copied or losslessly encoded. Both tracks are read and written as they go: a long chain's video and @@ -393,19 +423,35 @@ def pictures(): with av.open(str(copy_from)) as audio_reader: audio_source = audio_reader.streams.audio[0] audio = writer.add_stream_from_template(audio_source) + delay = _decoder_delay(audio_source) def sounds(): for packet in audio_reader.demux(audio_source): if packet.dts is None: continue + if delay: + # The MP4 edit list drops the decoder's start delay, as the MP3 reader did. + packet.pts, packet.dts = packet.pts - delay, packet.dts - delay packet.stream = audio yield packet _interleave(writer, pictures(), sounds()) else: codec, chunks, channels, itemsize = encode - stream, fmt = _audio_stream(writer, codec, rate, channels, itemsize) - _interleave(writer, pictures(), _encoded(stream, fmt, chunks, rate)) + audio_rate = audio_rate or rate + stream, fmt = _audio_stream(writer, codec, audio_rate, channels, itemsize) + _interleave(writer, pictures(), _encoded(stream, fmt, chunks, audio_rate)) + + +def _decoder_delay(stream): + """An MP3's start delay in the packets' time base; 0 for other codecs. + + The MP3 reader skips these samples before the first one it returns. A copy + into MP4 keeps them unless the first packet starts that much before zero. + """ + if stream.codec_context.name not in ('mp3', 'mp3float') or not stream.start_time or stream.start_time < 0: + return 0 + return stream.start_time def _interleave(writer, pictures, sounds): @@ -443,8 +489,11 @@ def _decoded(path): return _rate(path), np.concatenate(list(_decoded_chunks(path)), axis=1) -def _same_samples(left, right): - """Whether two chunked tracks hold the same samples, whatever their chunk sizes.""" +def _same_samples(left, right, tail=0): + """Whether two chunked tracks hold the same samples, whatever their chunk sizes. + + The first track may run up to `tail` samples past the second. + """ import numpy as np a = b = None while True: @@ -456,6 +505,8 @@ def _same_samples(left, right): b = next(right, None) if b is None: break + if b is None and a is not None and tail: + return _spare(a, left, tail) if a is None or b is None: return a is None and b is None count = min(a.shape[1], b.shape[1]) @@ -464,6 +515,45 @@ def _same_samples(left, right): a, b = a[:, count:], b[:, count:] +def _close_samples(left, right, tail=2048, share=0.1): + """Whether the first track is the second one within coding error: at most `share` of its energy is error. + + The first track may run up to `tail` samples past the second but not stop short of it. + Tracks are read in pieces of any size, so a long soundtrack is never held whole. + """ + import numpy as np + error = energy = extra = 0.0 + a = b = None + while True: + while a is None or not a.shape[1]: + a = next(left, None) + if a is None: + break + while b is None or not b.shape[1]: + b = next(right, None) + if b is None: + break + if b is None: + rest = (0 if a is None else a.shape[1]) + sum(chunk.shape[1] for chunk in left) + return rest <= tail and (energy == 0 or error <= energy * share) + if a is None or a.shape[0] != b.shape[0]: + return False + count = min(a.shape[1], b.shape[1]) + x, y = a[:, :count].astype(np.float64), b[:, :count].astype(np.float64) + error += float(((x - y) ** 2).sum()) + energy += float((y ** 2).sum()) + a, b = a[:, count:], b[:, count:] + + +def _spare(first, rest, limit): + count = first.shape[1] + for chunk in rest: + count += chunk.shape[1] + if count > limit: + return False + return count <= limit + + def _trim_video(source, target, count, rate, frames=None): """Remux video on a sample-accurate clock, adjusting the last kept frame. @@ -508,13 +598,14 @@ def _trim_video(source, target, count, rate, frames=None): def mux(video, output, info, *, trim_video=True, video_frames=None): - """Copy compatible full tracks; otherwise preserve native PCM in MP4. - - Decode and compare the saved track before making it visible. Never fall - back to lossy audio. Unsupported lossless muxers fail with an actionable - error instead of claiming preservation of a quantized soundtrack. - The selection is read, written and compared a frame at a time, so a - two-hour soundtrack costs no more memory than a short one. + """Copy a full AAC or MP3 track as it is; store any other sound as AAC 320 kbps. + + Decode and compare the saved track before making it visible. A copy must + hold every sample; an AAC track must hold the same length and sound within + AAC's error, and its receipt says so (sample_identical False, stored_as). + The exact samples stay in the source file the work keeps, so editing and + regeneration still read them. The selection is read, written and compared a + frame at a time, so a two-hour soundtrack costs no more memory than a short one. """ import numpy as np import tempfile @@ -526,6 +617,21 @@ def mux(video, output, info, *, trim_video=True, video_frames=None): def saved(path): return _rate(path) == rate and _same_samples(_decoded_chunks(path), map(_normalized, _selected_chunks(info))) + stored_rate = rate if rate in AAC_RATES else AAC_FALLBACK_RATE + + def reference(): + chunks = map(_to_float, _selected_chunks(info)) + return chunks if stored_rate == rate else _resampled(chunks, rate, info['channels'], stored_rate) + + def saved_as_aac(path): + # Lossy: the same length (the last AAC frame may run on) at the same rate, and the same sound within AAC's error. + return _rate(path) == stored_rate and _close_samples(_decoded_chunks(path), reference()) + + def saved_with_padding(path): + # The MP4 cannot carry an MP3's end padding: at most two frames of it follow the last sample. + return _rate(path) == rate and _same_samples(_decoded_chunks(path), map(_normalized, _selected_chunks(info)), + tail=2304) + with tempfile.TemporaryDirectory(prefix='original-audio-', dir=destination.parent) as work: work = Path(work) temporary = work / 'mux.mp4' @@ -535,44 +641,30 @@ def saved(path): else: picture = Path(video) copied = False - if info['full_source'] and info['codec'] in ('aac', 'mp3', 'flac'): + if info['full_source'] and info['codec'] in ('aac', 'mp3', 'mp3float'): try: _mux_streams(picture, temporary, rate, copy_from=info['path']) - copied = saved(temporary) + copied = (saved_with_padding if info['codec'] in ('mp3', 'mp3float') else saved)(temporary) except AudioUseError: raise except (OSError, ValueError, av_errors()): copied = False if not copied: - chunks = _selected_chunks(info) - first = next(chunks) - fits_flac = info.get('flac_compatible') - if fits_flac is None: - # Receipts saved before the browser format check still export losslessly. - fits_flac = all(_fits_flac(data) for data in _selected_chunks(info)) - if first.dtype.kind == 'f' and not fits_flac: - codec, kind = ('pcm_f64le', first.dtype) if first.dtype.itemsize == 8 else ('pcm_f32le', np.dtype(' 32 * max(width, height): + raise ValueError(SIZE_MISMATCH) + total = len(pictures) if abs(rate - FPS) <= .01 else round(len(pictures) * FPS / rate) + frames = usable_frames(total) + picked = (range(frames) if abs(rate - FPS) <= .01 + else [min(len(pictures) - 1, round(index * rate / FPS)) for index in range(frames)]) + target = directory / 'redo-audio-clip.npy' + np.save(target, np.stack([np.asarray(_fit(pictures[index], canvas['width'], canvas['height'])) for index in picked]), + allow_pickle=False) + return {'frames': frames, 'clip': str(target), 'source': {'width': width, 'height': height, 'fps': rate}} + + +def encode(clip, base, *, device='cuda', before_upload=None): + """The clip's video latent (1, C, F, H/16, W/16) as a float tensor on the CPU.""" + import gc + import torch + from .media_encoding import encode_visual + from .vae_weights import load_video_encoder + vae, _ = load_video_encoder(base, before_upload=None if before_upload is None else + lambda model: before_upload(model, False), device=device) + pixels = np.load(clip, mmap_mode='r', allow_pickle=False) + latent = encode_visual(vae, pixels, device=device, posterior='mode') + del vae, pixels + gc.collect() + if torch.device(device).type == 'cuda': + torch.cuda.empty_cache() + return latent + + +def mask_data(latent): + """The sampler's input for sound only: no picture token is redrawn and no sound is held.""" + rows, cols = latent.shape[3] // 2, latent.shape[4] // 2 + return dict(video=latent, video_mask=np.zeros((latent.shape[2], rows, cols), dtype=bool), + audio=None, audio_mask='redo') + + +def decode_sound(audio_latents, base, frames, *, device='cuda'): + """Float samples (2, n) at 32 kHz for `frames` picture frames, from the sampler's sound latents.""" + import gc + import torch + from .vae_weights import load_audio_vae + vae, _ = load_audio_vae(base) + vae.eval().requires_grad_(False) + mean = torch.tensor(vae.config.latents_mean, device=device).view(1, -1, 1) + std = torch.tensor(vae.config.latents_std, device=device).view(1, -1, 1) + sound = vae.decode(audio_latents.to(device) * std + mean, return_dict=False)[0] + sound = sound.float().permute(1, 0, 2)[0].cpu() + rate = vae.config.sampling_rate + del vae, mean, std + gc.collect() + if torch.device(device).type == 'cuda': + torch.cuda.empty_cache() + if rate != AUDIO_RATE: + raise ValueError('New sound requires the pinned 32 kHz H3 VAE') + return sound[:, :math.floor(frames * AUDIO_RATE / FPS)].numpy() + + +def mux(video_path, samples, output, frames): + """The original's picture packets, untouched, with `samples` (2, n) as the sound. + + Packets are kept in decode order up to the last one that shows a frame inside the first `frames` + frames. A kept B-frame may refer to a later frame that the decoder reads first, so a handful of frames + past the cut (at most one group of B-frames) come along; the sound is padded with silence to cover them. + Returns the length of the picture in seconds, whatever the original's frame rate. + """ + import av + from .comfy_metadata import _copy_stream + output = Path(output) + with av.open(str(video_path)) as reader: + source = reader.streams.video[0] + step = Fraction(1, 24) / source.time_base + packets = [packet for packet in reader.demux(source) + if packet.dts is not None and packet.pts is not None and packet.size] + begin = source.start_time if source.start_time is not None else min(packet.pts for packet in packets) + inside = [index for index, packet in enumerate(packets) if (packet.pts - begin) // step < frames] + kept = packets[:inside[-1] + 1] + rate = _rate(source) + last = max(kept, key=lambda packet: packet.pts) + length = (last.pts + (last.duration or round(1 / rate / source.time_base)) - begin) * source.time_base + seconds = float(length) + with av.open(str(output), 'w', format='mp4', options={'movflags': 'use_metadata_tags+faststart'}) as writer: + picture = _copy_stream(writer, source) + audio = writer.add_stream('aac', rate=AUDIO_RATE) + audio.layout = 'stereo' + for packet in kept: + packet.stream = picture + writer.mux(packet) + data = np.ascontiguousarray(samples, dtype=np.float32) + wanted = math.floor(seconds * AUDIO_RATE) + if data.shape[1] < wanted: + data = np.pad(data, ((0, 0), (0, wanted - data.shape[1]))) + chunk, position = 1024, 0 + while position < data.shape[1]: + frame = av.AudioFrame.from_ndarray(data[:, position:position + chunk], format='fltp', layout='stereo') + frame.sample_rate = AUDIO_RATE + frame.pts = position + for packet in audio.encode(frame): + writer.mux(packet) + position += chunk + for packet in audio.encode(None): + writer.mux(packet) + return seconds diff --git a/freevideo_engine/release_notes.json b/freevideo_engine/release_notes.json index 181b5b15..44fdcb61 100644 --- a/freevideo_engine/release_notes.json +++ b/freevideo_engine/release_notes.json @@ -1,34 +1,69 @@ { "schema": 1, - "product_version": "0.6.5", - "important": true, + "product_version": "0.6.6", + "important": false, "en": { - "summary": "Image model downloads no longer pause while the image view only warms a model; export supports 48 and 60 fps; pictures are also saved to the output folder; LoRA choice uses FreeVideo's own menu; and face close-ups and failure messages are improved.", + "summary": "0.6.6 gives more control over MOSS-Image pictures and makes them faster on smaller graphics cards, lets a reference video lend only its layout, explains more failures with a next step, and makes the Edit view easier to use in narrow windows and view switches smoother on slower computers.", "changes": [ - "Image models: a download no longer pauses as if a video were generating when the image view only keeps or warms a model, a paused download says why, and Continue download starts it at once; a model folder or its files may be symbolic links (junctions on Windows) to another drive; a link that leads nowhere or to a damaged or different file says why and what to do next, and only that model fails; MOSS-Image warms up from its own files and renders normally on Windows with less than 24 GB of video memory; and when opened from ComfyUI, H3 Image allocates GPU memory as video generation does.", - "Export at 48 or 60 fps: Frame rate in the Export window now offers 48 and 60, with the frames in between made on the graphics card, cuts and still frames kept as they are and the sound copied unchanged; a full disk is reported as a full disk, and plainly too little space is said before the graphics card starts.", - "Face pictures of a character after a change of clothes: a Face picture framed too wide is redrawn larger once, a repaint that kept the old clothes is tried again, and when no face box is found the clothes are repainted inside a fixed area.", - "Pictures and seeds: each picture made or imported is also copied into the output folder as a file of its own, removed when the picture is deleted for good and switchable off in Settings; the dice next to Seed in the Image view fills in a random seed, and an empty Seed still draws a new one each time.", - "Choosing a LoRA: the LoRA choice opens FreeVideo's own menu, where a long list scrolls, typing filters it, LoRAs are grouped by folder and the keyboard works, in the dark and light themes and in narrow windows.", - "Failures say why and what to do next, continued: in the Edit view, the Image view, the Create panel, the generation progress card and notifications a failure states the cause and the next step and offers Report a problem, never a raw failure code; an engine stop, a failed model download and a video closed from its history name their reason, and a full disk during a download is named; a LoRA that stores one alpha for layers of different ranks is marked unusable before generation with the reason; an out-of-range picture setting is named.", - "Report a problem: for a known failure with a clear fix, that fix is shown first and the report can still be sent after it; the issue text the launcher fills in starts with the display adapter model for every kind of error.", - "Edit view subtitles: when the subtitle track holds only an empty line just added, Auto subtitles places the lines it heard without saying they replaced the subtitles there; when the lines there have words, the notice and its Undo are as before." + "More control over picture layout: draw boxes with Layout in the Image view and give each one a line of description to place each part of the picture. Words in quotation marks are written into the picture.", + "MOSS-Image is faster on smaller graphics cards: a 1024-pixel picture on a 12 GB card is made much faster, with exactly the same result as before.", + "A reference video can lend only its layout: with Composition only, the new video follows the layout of the reference video, not its motion or colours.", + "Original sound plays on phones: an MP3 used as the original sound stays an MP3 in the finished video, so phones and system players can play it.", + "Frames saved in the Edit view also go to the output folder: with Also save pictures to the output folder on in Settings, a frame saved in the Edit view is copied there as well.", + "More failures explain what happened and what to do next, including a task that gets no answer after it is submitted, a picture the assistant cannot start and a Git error during setup.", + "Smoother on slower computers: with fewer processor cores or slow view switches, FreeVideo turns off the switch animation, and the library and short clips play more smoothly.", + "The Edit view is easier to use in a narrow window: the preview and buttons no longer cover each other, and the tracks and the update bar are shown in full.", + "Dialogs and tips are easier to read: their text is no longer disturbed by what lies behind them, and a hover tip appears only when a name is cut short.", + "Fields are easier to fill in: a number typed outside its range is brought back into range with a note under the field. An emptied LoRA strength returns to the strength in use.", + "Tutorial additions: how to export at 48 or 60 fps, and how to use MOSS-Image layout boxes." ] }, "zh": { - "summary": "图像模型下载不再在预热时误停;导出支持 48 和 60 fps;图片同时保存到 output 文件夹;LoRA 选择改用 FreeVideo 自己的菜单,脸部特写与失败说明更完善。", + "summary": "0.6.6 让 MOSS-Image 出图更可控,在显存较小的显卡上也更快;参考视频可以只沿用构图;更多失败会说明原因和下一步;窄窗口下的剪辑视图和低配电脑上的视图切换更顺畅。", "changes": [ - "图像模型:图像视图只是预热或保留模型时,图像模型下载不再以“视频生成中”暂停,暂停时写明实际原因,可用“继续下载”立即开始;模型文件夹、其子文件夹或模型文件通过符号链接(Windows 上也可用目录联接)放在其他磁盘时照常使用,链接失效或指向损坏、不同的文件时说明原因和下一步,图片页只把该模型标为出错;MOSS-Image 预热只读取自己的模型文件,Windows 上显存小于 24 GB 时可以正常出图;由 ComfyUI 打开时,H3 Image 使用与视频生成相同的显存分配方式。", - "导出 48 或 60 fps:导出窗口的“帧率”新增 48 和 60,中间帧在显卡上补出,剪切处和静止画面保持原样,声音原样复制;磁盘写满时直接说明磁盘已满,空间明显不足时在显卡开始工作前就会提示。", - "角色更换服装后的脸部特写:脸部特写取景过宽时放大重画一次;重画后仍是原来的衣服时自动重试;识别不到脸部位置时,在固定区域内重画衣服。", - "图片保存与种子:生成或导入的图片同时复制一份到 output 文件夹,副本是独立文件,图片永久删除时一并删除,可在设置中关闭;图像视图种子旁的骰子会填入一个随机种子,留空时仍每次随机。", - "LoRA 选择:选择 LoRA 时打开 FreeVideo 自己的菜单,长列表可以滚动,输入文字即可筛选,按文件夹分组,可用键盘操作,深色、浅色主题和窄窗口下都能正常使用。", - "失败时说明原因和下一步(续):剪辑视图、图像视图、创作面板、生成进度卡片和通知中的失败都写明原因和下一步并可提交问题,不再显示原始错误代码;引擎停止、模型下载失败、从历史中关闭的视频也说明原因,下载时磁盘已满会直接说明;同一个 alpha 对应不同秩的 LoRA 在生成前即标为不可用并说明原因;图片设置超出范围时分别说明是哪一项。", - "提交问题:已知错误且已有明确建议时,先显示该建议,看完仍可继续提交;启动器预填的问题正文对各类错误都以显示适配器型号开头。", - "剪辑视图的字幕:字幕轨上只有刚添加的空字幕时,自动字幕直接写入识别结果,不再提示“识别出的字幕已替换原有字幕”;原有字幕带文字时,提示与“撤销”照旧。" + "图片构图更可控:在图像视图中用“布局”画框,并为每个框写一句描述,即可指定画面中各部分的位置。引号中的文字会直接写进画面。", + "MOSS-Image 在显存较小的显卡上更快:12 GB 显卡生成 1024 像素的图片明显加快,画面与之前完全相同。", + "参考视频可以只沿用构图:选择“仅参考构图”时,生成的视频沿用参考视频的构图,不沿用其动作和颜色。", + "MP3 原声可在手机上直接播放:作为原声的 MP3 在成片中保持原样,手机和系统播放器均可直接播放。", + "剪辑视图保存的画面也会存入 output 文件夹:开启设置中的“同时将图片保存到 output 文件夹”后,在剪辑视图中保存的画面同样会复制到 output 文件夹。", + "更多失败会说明原因和下一步:任务提交后无应答、助手请求的图片无法开始、安装时 Git 出错,都会说明发生了什么以及接下来该怎么做。", + "低配电脑上更流畅:处理器核心较少或视图切换较慢时,FreeVideo 会自动关闭切换动画,作品库和短视频播放更加顺畅。", + "窄窗口下的剪辑视图更易用:预览与按钮不再互相遮挡,轨道和更新栏均完整显示。", + "对话框和提示更易阅读:对话框与提示的文字不再受背景内容干扰,悬停提示只在名称显示不全时出现。", + "输入更省心:数字框中输入超出范围的值时,会自动改回范围内并给出提示。清空 LoRA 强度后,会恢复为正在使用的强度。", + "教程补充:新增导出 48 或 60 fps 视频的方法,以及 MOSS-Image 布局框的用法。" ] }, "history": [ + { + "product_version": "0.6.5", + "en": { + "summary": "Image model downloads no longer pause while the image view only warms a model; export supports 48 and 60 fps; pictures are also saved to the output folder; LoRA choice uses FreeVideo's own menu; and face close-ups and failure messages are improved.", + "changes": [ + "Image models: a download no longer pauses as if a video were generating when the image view only keeps or warms a model, a paused download says why, and Continue download starts it at once; a model folder or its files may be symbolic links (junctions on Windows) to another drive; a link that leads nowhere or to a damaged or different file says why and what to do next, and only that model fails; MOSS-Image warms up from its own files and renders normally on Windows with less than 24 GB of video memory; and when opened from ComfyUI, H3 Image allocates GPU memory as video generation does.", + "Export at 48 or 60 fps: Frame rate in the Export window now offers 48 and 60, with the frames in between made on the graphics card, cuts and still frames kept as they are and the sound copied unchanged; a full disk is reported as a full disk, and plainly too little space is said before the graphics card starts.", + "Face pictures of a character after a change of clothes: a Face picture framed too wide is redrawn larger once, a repaint that kept the old clothes is tried again, and when no face box is found the clothes are repainted inside a fixed area.", + "Pictures and seeds: each picture made or imported is also copied into the output folder as a file of its own, removed when the picture is deleted for good and switchable off in Settings; the dice next to Seed in the Image view fills in a random seed, and an empty Seed still draws a new one each time.", + "Choosing a LoRA: the LoRA choice opens FreeVideo's own menu, where a long list scrolls, typing filters it, LoRAs are grouped by folder and the keyboard works, in the dark and light themes and in narrow windows.", + "Failures say why and what to do next, continued: in the Edit view, the Image view, the Create panel, the generation progress card and notifications a failure states the cause and the next step and offers Report a problem, never a raw failure code; an engine stop, a failed model download and a video closed from its history name their reason, and a full disk during a download is named; a LoRA that stores one alpha for layers of different ranks is marked unusable before generation with the reason; an out-of-range picture setting is named.", + "Report a problem: for a known failure with a clear fix, that fix is shown first and the report can still be sent after it; the issue text the launcher fills in starts with the display adapter model for every kind of error.", + "Edit view subtitles: when the subtitle track holds only an empty line just added, Auto subtitles places the lines it heard without saying they replaced the subtitles there; when the lines there have words, the notice and its Undo are as before." + ] + }, + "zh": { + "summary": "图像模型下载不再在预热时误停;导出支持 48 和 60 fps;图片同时保存到 output 文件夹;LoRA 选择改用 FreeVideo 自己的菜单,脸部特写与失败说明更完善。", + "changes": [ + "图像模型:图像视图只是预热或保留模型时,图像模型下载不再以“视频生成中”暂停,暂停时写明实际原因,可用“继续下载”立即开始;模型文件夹、其子文件夹或模型文件通过符号链接(Windows 上也可用目录联接)放在其他磁盘时照常使用,链接失效或指向损坏、不同的文件时说明原因和下一步,图片页只把该模型标为出错;MOSS-Image 预热只读取自己的模型文件,Windows 上显存小于 24 GB 时可以正常出图;由 ComfyUI 打开时,H3 Image 使用与视频生成相同的显存分配方式。", + "导出 48 或 60 fps:导出窗口的“帧率”新增 48 和 60,中间帧在显卡上补出,剪切处和静止画面保持原样,声音原样复制;磁盘写满时直接说明磁盘已满,空间明显不足时在显卡开始工作前就会提示。", + "角色更换服装后的脸部特写:脸部特写取景过宽时放大重画一次;重画后仍是原来的衣服时自动重试;识别不到脸部位置时,在固定区域内重画衣服。", + "图片保存与种子:生成或导入的图片同时复制一份到 output 文件夹,副本是独立文件,图片永久删除时一并删除,可在设置中关闭;图像视图种子旁的骰子会填入一个随机种子,留空时仍每次随机。", + "LoRA 选择:选择 LoRA 时打开 FreeVideo 自己的菜单,长列表可以滚动,输入文字即可筛选,按文件夹分组,可用键盘操作,深色、浅色主题和窄窗口下都能正常使用。", + "失败时说明原因和下一步(续):剪辑视图、图像视图、创作面板、生成进度卡片和通知中的失败都写明原因和下一步并可提交问题,不再显示原始错误代码;引擎停止、模型下载失败、从历史中关闭的视频也说明原因,下载时磁盘已满会直接说明;同一个 alpha 对应不同秩的 LoRA 在生成前即标为不可用并说明原因;图片设置超出范围时分别说明是哪一项。", + "提交问题:已知错误且已有明确建议时,先显示该建议,看完仍可继续提交;启动器预填的问题正文对各类错误都以显示适配器型号开头。", + "剪辑视图的字幕:字幕轨上只有刚添加的空字幕时,自动字幕直接写入识别结果,不再提示“识别出的字幕已替换原有字幕”;原有字幕带文字时,提示与“撤销”照旧。" + ] + } + }, { "product_version": "0.6.4", "en": { diff --git a/freevideo_engine/runtime.py b/freevideo_engine/runtime.py index f11720eb..84175e78 100644 --- a/freevideo_engine/runtime.py +++ b/freevideo_engine/runtime.py @@ -566,11 +566,16 @@ def _sample(self, conditioning, seed, frames=243, width=1344, height=768, *, fin step_callback=None, sampling_complete_callback=None, initial_latents=None, refine_steps=None, refine_schedule=None, allow_smaller_canvas=False, progress_offset=0, progress_total=None, pass_cache_budget_bytes=None, gpu_reserve_bytes=0, pass_resident_blocks=None, - budget_refresh=None, continuation=None, refine_resume=None, refine_checkpoint=None): + budget_refresh=None, continuation=None, refine_resume=None, refine_checkpoint=None, + video_mask=None): from src.inference.render import load_prompt, generate_latents from .geometry import geometry, sampler_for_canvas from . import frame_preview refining = initial_latents is not None + if video_mask is not None and (continuation is not None or refining): + raise ValueError('Redrawing part of a clip cannot be combined with a continuation or a refinement') + if video_mask is not None and tuple(video_mask['video'].shape[-2:]) != (height // 16, width // 16): + raise ValueError('The clip to redraw does not match the sampled picture size') if continuation is not None: from .continuation import validate_route # Audio references are admitted below, after inspecting the encoded modalities. @@ -856,6 +861,7 @@ def append(self, value): # offloader and the progress hooks leave. from contextlib import nullcontext from .continuation import sampling + from .video_mask import sampling as mask_sampling planned, watch = self.config, None source = getattr(budget_refresh, 'pressure', None) if source is not None: @@ -882,10 +888,12 @@ def append(self, value): if active_steps == 1: trigger_prefetch() with progress.layers(self.transformer.transformer_blocks), self.device_backend.make_offloader( - self.offload_layers, prefetch=self.prefetch, weight_source=self.stream_weight_source) as offloader, sampling( + self.offload_layers, prefetch=self.prefetch, weight_source=self.stream_weight_source) as offloader, ( + mask_sampling(self.transformer, video_mask, seed, self.device_backend.device) + if video_mask is not None else sampling( self.transformer, continuation, seed, self.device_backend.device, **({'video_offset': continuation_offset} if continuation_offset else {}), - **({'audio_offset': continuation_audio_offset} if continuation_audio_offset else {})) as prefix, \ + **({'audio_offset': continuation_audio_offset} if continuation_audio_offset else {}))) as prefix, \ (watch.layers(self.transformer.transformer_blocks) if watch is not None else nullcontext()), \ frame_preview.observing(latent_frames=canvas.get('latent_frames'), frame_h=height // 32, frame_w=width // 32, step_offset=progress_offset, diff --git a/freevideo_engine/subtitle_pack.py b/freevideo_engine/subtitle_pack.py index 2f792e77..835b00a4 100644 --- a/freevideo_engine/subtitle_pack.py +++ b/freevideo_engine/subtitle_pack.py @@ -45,7 +45,8 @@ def platform_key(): if sys.platform == 'darwin': return 'macos-arm64' if machine in ('arm64', 'aarch64') else 'macos-x86_64' if machine == 'x86_64' else None if sys.platform.startswith('linux'): - return 'linux-x86_64' if machine in ('x86_64', 'amd64') else None + # Linux ARM64 (GB10, GH200): the dubbing runtime has its rows; the speech wheel row comes once it is built. + return 'linux-x86_64' if machine in ('x86_64', 'amd64') else 'linux-aarch64' if machine in ('aarch64', 'arm64') else None return None diff --git a/freevideo_engine/uv_restore.py b/freevideo_engine/uv_restore.py index 061f89e3..3b24e7cc 100644 --- a/freevideo_engine/uv_restore.py +++ b/freevideo_engine/uv_restore.py @@ -8,10 +8,11 @@ from pathlib import Path from . import network +from .environments import uv_folder from .long_paths import io_path PACKAGE = Path(__file__).resolve().parent -TOOL = {'Windows': 'uv.exe', 'Darwin': 'uv', 'Linux': 'uv-x86_64-unknown-linux-gnu/uv'} +TOOL = {'Windows': 'uv.exe', 'Darwin': 'uv', 'Linux': uv_folder() + '/uv'} # The sources each system's pinned uv comes from; nothing else is probed. FAMILIES = {'Windows': ('pypi', 'github'), 'Darwin': ('pypi',), 'Linux': ('github',)} diff --git a/freevideo_engine/video_mask.py b/freevideo_engine/video_mask.py new file mode 100644 index 00000000..ae10bab5 --- /dev/null +++ b/freevideo_engine/video_mask.py @@ -0,0 +1,173 @@ +"""Redraw part of a video: the unselected latent tokens keep the original clip. + +``data`` for :func:`sampling`: + video original clip latent (1, C, F, H/16, W/16), from the continuation's VAE encode path + video_mask bool (F, H/32, W/32); True = redraw. One cell is one 2x2 latent patch (one token). + audio original sound latent (2, 32, ticks) or None + audio_mask 'keep' | 'redo' | bool (ticks,) (True = redo; whole latent frames, both channels) + +Each step the kept tokens are put back on the original's own noised path (same noise as the +sampler's start); redrawn tokens step normally. ``finish`` writes the kept tokens back exactly. +""" +from contextlib import contextmanager + +import numpy as np +from PIL import Image + +PIXELS_PER_TOKEN = 32 +CLEAN_T = 1. + + +def token_mask(frame_masks, latent_frames, width, height, *, grow=24, feather=16, time_grow=1): + """bool (F, H/32, W/32): a cell is redrawn when any selected pixel of the latent frame reaches it. + + The VAE packs 17n+5 pixel frames into 5n+2 latent frames unevenly, so the proportional split below can put a + selection one latent frame early or late. A kept latent frame is written back as it was, so a moving selection + would leave the object there; each redrawn cell also takes ``time_grow`` latent frames before and after it. + """ + from .image_gen import region_edit + count = len(frame_masks) + if count < 1 or latent_frames < 1: + raise ValueError('A video mask needs at least one frame') + rows, cols = height // PIXELS_PER_TOKEN, width // PIXELS_PER_TOKEN + result = np.zeros((latent_frames, rows, cols), dtype=bool) + for frame in range(latent_frames): + start = frame * count // latent_frames + stop = max(start + 1, (frame + 1) * count // latent_frames) + for mask in frame_masks[start:stop]: + if region_edit.selection_is_empty(mask): + continue + base = region_edit.grown_mask(mask.resize((width, height), Image.Resampling.NEAREST), grow + feather) + cells = np.asarray(base, dtype=np.uint8)[:rows * PIXELS_PER_TOKEN, :cols * PIXELS_PER_TOKEN] > 0 + result[frame] |= cells.reshape(rows, PIXELS_PER_TOKEN, cols, PIXELS_PER_TOKEN).any(axis=(1, 3)) + grown = result.copy() + for shift in range(1, max(0, int(time_grow)) + 1): + grown[shift:] |= result[:-shift] + grown[:-shift] |= result[shift:] + return grown + + +def paste_back(original_frames, generated_frames, frame_masks, *, grow=24, feather=16): + """Generated pixels inside each frame's feathered selection, the original's everywhere else.""" + from .image_gen import region_edit + if not len(original_frames) == len(generated_frames) == len(frame_masks): + raise ValueError('Frame counts differ') + out = [] + for original, generated, mask in zip(original_frames, generated_frames, frame_masks): + if region_edit.selection_is_empty(mask): + out.append(original) + continue + alpha = region_edit.blend_alpha(mask, original.size, grow=grow, feather=feather) + out.append(region_edit.composite(original, generated, alpha)) + return out + + +def validate(data, channels, patch=(1, 2, 2)): + video, mask = data['video'], np.asarray(data['video_mask'], dtype=bool) + if video.ndim != 5 or video.shape[0] != 1 or video.shape[1] != channels: + raise ValueError('The original clip latent has the wrong shape') + frames, rows, cols = video.shape[2], video.shape[3] // patch[1], video.shape[4] // patch[2] + if mask.shape != (frames, rows, cols): + raise ValueError(f'The video mask must be {(frames, rows, cols)}, not {mask.shape}') + audio, audio_mask = data.get('audio'), data.get('audio_mask', 'keep') + # Redoing the sound alone leaves every picture token kept. + if not mask.any() and not (isinstance(audio_mask, str) and audio_mask == 'redo'): + raise ValueError('The video mask selects nothing') + if audio is not None: + if audio.ndim != 3 or audio.shape[:2] != (2, 32): + raise ValueError('The original sound latent has the wrong shape') + if not isinstance(audio_mask, str): + audio_mask = np.asarray(audio_mask, dtype=bool) + if audio_mask.shape != (audio.shape[2],): + raise ValueError('The sound mask must have one entry per latent frame') + elif audio_mask not in ('keep', 'redo'): + raise ValueError('The sound mask must be keep, redo or a per-frame list') + return mask + + +class Hold: + def __init__(self, transformer, data, seed, device, *, video_offset=0, audio_offset=0): + import torch + from diffusers.modular_pipelines.minimax_h3.before_denoise import patchify_video_latents + mask = validate(data, transformer.config.in_channels, tuple(transformer.config.patch_size)) + self.video_offset, self.audio_offset = video_offset, audio_offset + self.video = data['video'].to(device=device, dtype=torch.float32) + rows = patchify_video_latents(self.video, tuple(transformer.config.patch_size)) + self.redo_cells = mask + self.keep = torch.from_numpy(~mask.reshape(-1)).to(device) + self.video_rows = rows + self.noise = None + self.audio = None + audio = data.get('audio') + if audio is not None: + self.audio = audio.to(device=device, dtype=torch.float32) + ticks = self.audio.shape[2] + mode = data.get('audio_mask', 'keep') + redo = (np.full(ticks, mode == 'redo') if isinstance(mode, str) else np.asarray(mode, dtype=bool)) + self.audio_keep = torch.from_numpy(np.tile(~redo, 2)).to(device) + self.audio_rows = self.audio.permute(0, 2, 1).reshape(-1, 32).contiguous() + self.audio_noise = None + self.current = None + + def _noised(self, clean, noise, t, device): + import torch + t = torch.as_tensor(float(t), dtype=torch.float32, device=device) + return t * clean + (1 - t) * noise + + def before(self, model, args, kwargs): + import torch + video, audio = kwargs['hidden_states'][0], kwargs['audio_hidden_states'][0] + row_times = kwargs['timestep'][kwargs['timestep_indices']] + count = self.video_rows.shape[0] + window = slice(self.video_offset, self.video_offset + count) + if video.shape[0] < window.stop: + raise ValueError('The video mask does not fit the sampled clip') + ticks = self.audio.shape[2] if self.audio is not None else 0 + if self.audio is not None: + generated = audio.shape[0] - self.audio_offset + if generated // 2 < ticks: + raise ValueError('The sound mask does not fit the sampled clip') + rows = torch.cat([torch.arange(ticks, device=audio.device) + self.audio_offset + channel * (generated // 2) + for channel in range(2)]) + if self.noise is None: + # The first call sees the sampler's own starting noise. + self.noise = video[window].detach().clone() + if self.audio is not None: + self.audio_noise = audio[rows].detach().clone() + t = row_times[kwargs['video_indices'][self.video_offset]] + keep = self.keep + video[window][keep] = self._noised(self.video_rows[keep], self.noise[keep], t, video.device) + if self.audio is not None: + audio_t = row_times[kwargs['audio_indices'][self.audio_offset]] + ak = self.audio_keep + audio[rows[ak]] = self._noised(self.audio_rows[ak], self.audio_noise[ak], audio_t, audio.device) + self.current = video + return args, kwargs + + def restore_video(self): + pass # the next step's pre-hook puts the kept tokens back + + def finish(self, video, audio): + import torch + redo = torch.from_numpy(np.repeat(np.repeat(self.redo_cells, 2, axis=1), 2, axis=2)).to(video.device) + video = torch.where(redo[None, None], video, self.video.to(video.dtype)) + if self.audio is not None: + ticks = self.audio.shape[2] + keep = self.audio_keep.reshape(2, ticks)[:, None, :] + audio = audio.clone() + audio[:, :, :ticks] = torch.where(keep, self.audio.to(audio.dtype), audio[:, :, :ticks]) + return video, audio + + +@contextmanager +def sampling(transformer, data, seed, device, *, video_offset=0, audio_offset=0): + if data is None: + yield None + return + hold = Hold(transformer, data, seed, device, video_offset=video_offset, audio_offset=audio_offset) + handle = transformer.register_forward_pre_hook(hold.before, with_kwargs=True, prepend=True) + try: + yield hold + finally: + handle.remove() + hold.current = None diff --git a/freevideo_engine/worker.py b/freevideo_engine/worker.py index 4a2bbaad..8a5ccaf7 100644 --- a/freevideo_engine/worker.py +++ b/freevideo_engine/worker.py @@ -145,6 +145,13 @@ def released(engine): else ANCHOR_ADALN_TASK if continuation.get('anchor') else ADALN_TASK)) metrics['continuation'] = summary(continuation, hide_tail_frames=hide_tail_frames) metrics['audio_context'] = continuation['audio_context'] + redo_sound = request.get('redo_audio') + if redo_sound is not None: + # New sound for a finished picture: one pass, nothing continued, no sound of its own to keep. + if (continuation is not None or original_audio is not None or request.get('resume') + or request.get('sampling_plan', {}).get('enabled')): + raise ValueError('Making new sound for a video takes a single pass of its own') + metrics['redo_audio'] = dict(frames=request['geometry']['frames']) metrics['gpu_card'] = observed_card(torch) metrics['device_memory'] = device_memory_report(request['gpu_budget_bytes'], request.get('allocator_limit_bytes'), reserve_bytes=request.get('gpu_reserve_bytes', 0), capacity_trial=request.get('capacity_trial', False)) @@ -207,6 +214,17 @@ def release_idle(): continuation, metrics['continuation_encode'] = complete( continuation, request['geometry'], manifest, request.get('sampling_plan'), resident=resident) request['continuation'] = continuation + redo_mask = None + if redo_sound is not None: + from . import redo_audio + from .paths import base_path + tick = time.perf_counter() + clip = redo_audio.read(redo_sound['video'], request['geometry'], Path(request['output']).parent) + if clip['frames'] != request['geometry']['frames']: + raise ValueError('The video does not match the requested length') + redo_mask = redo_audio.mask_data(redo_audio.encode(clip['clip'], redo_sound.get('base') or base_path())) + Path(clip['clip']).unlink(missing_ok=True) + metrics['redo_audio'].update(encode_seconds=time.perf_counter() - tick, source=clip['source']) if manifest.get('precision') not in ('fp8', 'int8', 'bf16'): raise ValueError('The Engine requires an official FP8 or int8 cache') options, decoder = request['engine_options'], request['decoder_options'] @@ -709,7 +727,8 @@ def refine_checkpoint(done, rows, seconds): final_step_callback=None if decoder_cached else read_decoder_ahead, step_callback=memory_diagnostics.complete, sampling_complete_callback=sampling_complete, gpu_reserve_bytes=request.get('gpu_reserve_bytes', 0), - budget_refresh=refresh_budget if live_budget is not None else None) + budget_refresh=refresh_budget if live_budget is not None else None, + **({'video_mask': redo_mask} if redo_mask is not None else {})) finally: frame_preview.clear() metrics['sampling_memory'] = memory_diagnostics.close() @@ -768,15 +787,23 @@ def keep_audio_lead_in(value): continuation_data['audio_lead_in'] = value # Older retained sampling tails predate the predecessor binding. continuation_data['metadata']['source_id'] = continuation['source_id'] - metrics.update(decode_to_file(latents, audio, request['output'], base=base, artifacts_dir=artifacts, - **({'hide_tail_frames': hide_tail_frames} if hide_tail_frames else {}), - **({'output_10bit': request['output_10bit']} if request.get('output_10bit') else {}), - **({'original_audio': original_audio} if original_audio is not None else {}), - **({'continuation': continuation} if continuation is not None else {}), - **({'audio_lead_in_callback': keep_audio_lead_in} - if continuation is not None and continuation_data is not None and original_audio is None else {}), - model_cache=resident, phase_callback=decode_phase, output_size=output_size, - ram_budget_bytes=request.get('ram_budget_bytes'), **decoder)) + if redo_sound is not None: + from . import redo_audio + decode_phase('audio_decode') + sound = redo_audio.decode_sound(audio, base, request['geometry']['frames']) + decode_phase('mp4_save') + seconds = redo_audio.mux(redo_sound['video'], sound, request['output'], request['geometry']['frames']) + metrics['redo_audio'].update(samples=int(sound.shape[1]), picture_seconds=round(seconds, 3)) + else: + metrics.update(decode_to_file(latents, audio, request['output'], base=base, artifacts_dir=artifacts, + **({'hide_tail_frames': hide_tail_frames} if hide_tail_frames else {}), + **({'output_10bit': request['output_10bit']} if request.get('output_10bit') else {}), + **({'original_audio': original_audio} if original_audio is not None else {}), + **({'continuation': continuation} if continuation is not None else {}), + **({'audio_lead_in_callback': keep_audio_lead_in} + if continuation is not None and continuation_data is not None and original_audio is None else {}), + model_cache=resident, phase_callback=decode_phase, output_size=output_size, + ram_budget_bytes=request.get('ram_budget_bytes'), **decoder)) if continuable and continuation_data is not None: if continuation is not None: # Every continuation of a film carries its first frame on, used or not: a later diff --git a/scripts/bootstrap_linux.sh b/scripts/bootstrap_linux.sh index fda7cff9..9adf3448 100644 --- a/scripts/bootstrap_linux.sh +++ b/scripts/bootstrap_linux.sh @@ -4,7 +4,14 @@ FV_UV_VERSION=0.9.0 FV_UV_URL=https://github.com/astral-sh/uv/releases/download/0.9.0/uv-x86_64-unknown-linux-gnu.tar.gz FV_UV_SHA256=4dadaa5ff5009ccd6a0a43f6ccfa32bf36ed2eff18df7011275a9b1d81950e7b +FV_UV_URL_AARCH64=https://github.com/astral-sh/uv/releases/download/0.9.0/uv-aarch64-unknown-linux-gnu.tar.gz +FV_UV_SHA256_AARCH64=ca410766024d2d726c937bda2e9441823e2848894ac5a2f8b608902384fc391f FV_PYTHON_VERSION=3.12.3 +# The processor names uv and the private Python use (x86_64 or aarch64); ARM64 takes its own uv build. +case "$(uname -m 2>/dev/null)" in + aarch64|arm64) FV_ARCH=aarch64; FV_UV_URL=$FV_UV_URL_AARCH64; FV_UV_SHA256=$FV_UV_SHA256_AARCH64 ;; + *) FV_ARCH=x86_64 ;; +esac fv_note() { printf 'FreeVideo: %s\n' "$*" >&2; } fv_fail() { fv_note "$*"; return 1; } @@ -46,7 +53,7 @@ fv_find_python() { return 0 fi for candidate in "$fv_root/envs/unified/bin/python" "$fv_root/envs/engine/bin/python" \ - "$FREEVIDEO_BOOTSTRAP_ROOT/python/cpython-$FV_PYTHON_VERSION-linux-x86_64-gnu/bin/python3.12" \ + "$FREEVIDEO_BOOTSTRAP_ROOT/python/cpython-$FV_PYTHON_VERSION-linux-$FV_ARCH-gnu/bin/python3.12" \ python3 python3.12 python; do if fv_python_ok "$candidate"; then FREEVIDEO_BOOTSTRAP_PYTHON="$(command -v -- "$candidate")" @@ -273,11 +280,11 @@ fv_install_python() ( mkdir -p -- "$FREEVIDEO_BOOTSTRAP_ROOT" exec 9>"$FREEVIDEO_BOOTSTRAP_ROOT/bootstrap.lock" flock -n 9 || { fv_fail 'Another command is preparing Python. Wait for it to finish and retry.'; exit 1; } - if fv_python_ok "$FREEVIDEO_BOOTSTRAP_ROOT/python/cpython-$FV_PYTHON_VERSION-linux-x86_64-gnu/bin/python3.12"; then exit 0; fi + if fv_python_ok "$FREEVIDEO_BOOTSTRAP_ROOT/python/cpython-$FV_PYTHON_VERSION-linux-$FV_ARCH-gnu/bin/python3.12"; then exit 0; fi fv_note "Preparing private Python $FV_PYTHON_VERSION (allow ~400 MiB including retained bootstrap downloads; no Torch or models yet)." fv_note "Files and log: $FREEVIDEO_BOOTSTRAP_ROOT" fv_download_uv || exit 1 - local uv="$FREEVIDEO_BOOTSTRAP_ROOT/tools/uv-x86_64-unknown-linux-gnu/uv" source route attempt=0 + local uv="$FREEVIDEO_BOOTSTRAP_ROOT/tools/uv-$FV_ARCH-unknown-linux-gnu/uv" source route attempt=0 local retry_sources retry_mode timeout retries attempt_log attempt_dir attempt_detail python_exit tee_exit other_failures=0 failed_source local -A fv_denied=() fv_slow=() local -a pipe_status @@ -341,7 +348,7 @@ fv_install_python() ( exit 1 fi if (( python_exit == 0 )); then - fv_python_ok "$UV_PYTHON_INSTALL_DIR/cpython-$FV_PYTHON_VERSION-linux-x86_64-gnu/bin/python3.12" && exit 0 + fv_python_ok "$UV_PYTHON_INSTALL_DIR/cpython-$FV_PYTHON_VERSION-linux-$FV_ARCH-gnu/bin/python3.12" && exit 0 other_failures=1 elif fv_access_denied "$attempt_detail"; then fv_denied[$source]=1 @@ -409,7 +416,7 @@ freevideo_bootstrap_linux() { elif [[ "$mode" == setup ]]; then fv_help; printf '\n'; fi return 0 fi - [[ "$(uname -s)" == Linux && "$(uname -m)" == x86_64 ]] || { fv_fail 'Use native Windows launchers on Windows. Linux setup currently supports x86_64.'; return 1; } + [[ "$(uname -s)" == Linux ]] && [[ "$(uname -m)" == x86_64 || "$(uname -m)" == aarch64 || "$(uname -m)" == arm64 ]] || { fv_fail 'Use native Windows launchers on Windows. Linux setup supports x86_64 and ARM64 (aarch64).'; return 1; } if command -v getconf >/dev/null 2>&1 && ! getconf GNU_LIBC_VERSION >/dev/null 2>&1; then fv_fail 'Linux setup needs glibc (for example Ubuntu/Debian); musl/Alpine CUDA wheels are unsupported.'; return 1 fi diff --git a/scripts/test_freevideo_entry.mjs b/scripts/test_freevideo_entry.mjs index 80e50ef9..20f515f3 100644 --- a/scripts/test_freevideo_entry.mjs +++ b/scripts/test_freevideo_entry.mjs @@ -129,6 +129,8 @@ test('main browser entry registers both views and preserves node hooks', async t source = source.replace("from './user_message.js'", `from '${new URL('../web/user_message.js', import.meta.url).href}'`); source = source.replace("from './prompt_sections.js'", `from '${new URL('../web/prompt_sections.js', import.meta.url).href}'`); source = source.replace("from './fv_select.js'", `from '${new URL('../web/fv_select.js', import.meta.url).href}'`); + source = source.replace("from './tip_words.js'", `from '${new URL('../web/tip_words.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}'`); source = source diff --git a/web/a11y.js b/web/a11y.js index 612aca5a..f76e13e1 100644 --- a/web/a11y.js +++ b/web/a11y.js @@ -217,7 +217,7 @@ let installed = false; export function installA11y() { if (installed || globalThis.__fvA11y || !doc?.addEventListener) return; installed = globalThis.__fvA11y = true; - sheet('a11y'); sheet('selection'); + sheet('a11y'); sheet('selection'); sheet('slider'); // Window capture, registered at start: dialog_keys.js stops keys there for the views that route their own. globalThis.addEventListener('keydown', event => { onTab(event); onEscape(event); onSelectAll(event); }, true); doc.addEventListener('focusin', event => { skipUnseen(event); fitRing(doc.activeElement); markMedia(event); hostRing(doc.activeElement); }, true); diff --git a/web/agent_activity.js b/web/agent_activity.js index 61fb84f4..aa1d3814 100644 --- a/web/agent_activity.js +++ b/web/agent_activity.js @@ -1,3 +1,4 @@ +import { setTip } from './tip_words.js'; import {retryAgentPost} from './agent_session.js'; import {issueButton} from './issue_button.js'; import {tip} from './autopilot_tips.js'; @@ -128,7 +129,7 @@ function row(job, t, api, refresh, open, cancellationErrors) { if (job.project) meta.push(job.project); const foot = el('div', 'fv-agent-foot'); const details = el('p', 'fv-agent-meta', meta.join(' · ')); - if (failed && error.message) details.title = error.message; + if (failed && error.message) setTip(details, {name: error.message}); foot.append(details); // A failed task carries what the engine said, so the report can be acted on. const issue = issueButton(t, () => cancellationErrors.has(job.id) || !failed diff --git a/web/autopilot_chat.js b/web/autopilot_chat.js index 007b0f00..041ad382 100644 --- a/web/autopilot_chat.js +++ b/web/autopilot_chat.js @@ -1,5 +1,7 @@ // The conversation with the connected agent: what the user says, what the agent answers, and the agent's jobs as // cards at the place they happened. Reads and sends use the page session; the agent's token never enters the page. +import { cutTip } from './cut_tip.js'; +import { setTip } from './tip_words.js'; import {agentGet, agentPost, retryAgentPost} from './agent_session.js'; import {emptyFrameIcon} from './empty_frame.js'; import {ATTACH, attachmentURL, pickPictures, pictureGone, picturesOf, releasePicture, releasePictures, thumbnail, uploadPicture} from './chat_attachments.js'; @@ -516,7 +518,7 @@ export function agentChat(t, api, {open, edit, shown = () => true, changed = () // The line says the message is too long until the words fit. let tooLong = false; const TOO_LONG = () => t('This message is too long; shorten it or send it in two parts', '这条消息太长,请缩短或分成两条发送'); - function say(text, failure = false) { if (text !== TOO_LONG()) tooLong = false; quoted(notice, text); notice.title = text || ''; notice.hidden = !text; noticeIssue.hidden = !text || !failure; noticeAction.hidden = true; noticeAction.run = null; } + function say(text, failure = false) { if (text !== TOO_LONG()) tooLong = false; quoted(notice, text); cutTip(notice, text || ''); notice.hidden = !text; noticeIssue.hidden = !text || !failure; noticeAction.hidden = true; noticeAction.run = null; } function receipt(text, label, key, run) { say(text); noticeAction.textContent = label; noticeAction.run = run; noticeAction.hidden = false; tip(noticeAction, key, t); } @@ -1252,7 +1254,7 @@ export function agentChat(t, api, {open, edit, shown = () => true, changed = () const draw = (next, fraction = null) => { put(chip, statusText(next, t, fraction)); chip.dataset.state = statusKey(next); const said = words(); put(prompt, said); prompt.hidden = !said; - prompt.title = said ? t('Prompt', '提示词') : ''; + setTip(prompt, said ? {name: t('Prompt', '提示词')} : {}); put(when, localTime(statusKey(next) === 'done' && next.finished_at ? next.finished_at : next.created_at, t)); when.hidden = !when.textContent; }; return {head, name, meta, chip, draw}; diff --git a/web/autopilot_panels.js b/web/autopilot_panels.js index 042e8d3c..c9b27d34 100644 --- a/web/autopilot_panels.js +++ b/web/autopilot_panels.js @@ -1,6 +1,7 @@ // The Autopilot view's side panels. The conversation stays in the middle column; the right panel lists every task // of the chat being read (what is being made first, then the finished ones, newest first), each with its prompt, // time and state, searchable, and below it the details of the one picked. Pure helpers are exported for tests. +import { setTip } from './tip_words.js'; import {tip} from './autopilot_tips.js'; function el(tag, cls, text) { const e = document.createElement(tag); if (cls) e.className = cls; if (text != null) e.textContent = text; return e; } @@ -247,7 +248,7 @@ export function createSideRail(t, handlers = {}) { dPreview.style.setProperty('--p', String((fraction || 0) * 100)); put(dPrompt, row.prompt || ''); dPrompt.hidden = !row.prompt; dPrompt.dataset.source = row.promptSource || 'request'; - dPrompt.title = row.promptSource === 'job' ? t('Prompt', '提示词') : t('What you asked for', '你提出的要求'); + setTip(dPrompt, {name: row.promptSource === 'job' ? t('Prompt', '提示词') : t('What you asked for', '你提出的要求')}); dFacts.replaceChildren(...fact(t('Kind', '类型'), job.kind === 'image' ? t('Picture', '图片') : job.kind === 'production' ? t('Film', '成片') : t('Video', '视频')), ...fact(t('Size', '尺寸'), job.width > 0 && job.height > 0 ? `${job.width} × ${job.height}` : ''), ...fact(t('Length', '时长'), job.seconds > 0 ? t(`${job.seconds} s`, `${job.seconds} 秒`) : ''), diff --git a/web/browser_extension.js b/web/browser_extension.js index ee9c409b..7d403746 100644 --- a/web/browser_extension.js +++ b/web/browser_extension.js @@ -47,6 +47,20 @@ export function isNetworkTypeError(error) { return (type === 'TypeError' || /^TypeError:\s*/i.test(text)) && /Failed to fetch|fetch failed|NetworkError(?: when attempting to fetch resource)?|network request failed|Load failed/i.test(text); } +// A request the page gave up waiting for: the browser (or ComfyUI's own fetch) aborts it with a TimeoutError, +// e.g. "Fetch timeout" when POST /prompt is not answered in time. The engine may still have taken the request. +export function isRequestTimeout(error) { + const type = error?.name || error?.exception_type; + const text = typeof error === 'string' ? error : string(error?.message) || string(error?.exception_message); + return type === 'TimeoutError' || /^TimeoutError:\s*/i.test(text); +} +export function requestTimeoutText(t) { + return t('The task may already have been accepted.', '任务可能已被接收。'); +} +// What to do next: the engine may already hold the request, so resubmitting blindly would queue it twice. +export function requestTimeoutAction(t) { + return t('Check the queue, and submit again only if the task is not there.', '请先查看队列,任务不在队列中时再重新提交。'); +} // One sentence for a dropped connection (engine closed, network lost); the raw // browser wording stays in the technical details. export function connectionLostText(t) { return t('Lost the connection to FreeVideo. Try again once it is back.', '与 FreeVideo 的连接已断开,恢复后请重试。'); } diff --git a/web/cast_generate.js b/web/cast_generate.js index bf1d5b69..4273c7a2 100644 --- a/web/cast_generate.js +++ b/web/cast_generate.js @@ -2,6 +2,7 @@ // same person (front, three-quarter, side, back, face). Each picture shows as it is finished; the // dialog's Save waits for all five. Pictures are made one by one through the page's image client // and stay in the input folder; the dialog puts them on the card. +import { setTip } from './tip_words.js'; import {createImageGenClient, imageGenProgress, imagePackUnavailableMessage, renderImageFailure, IMAGE_GEN_POLL_MS, IMAGE_GEN_INFO_POLL_MS} from './image_generation.js'; import {createImageLoras} from './image_lora.js'; @@ -521,7 +522,7 @@ export function mountCastGenerate({container, api, text, t = text, viewURL, onSt const cells = names.map((view, index) => { const cell = el('div', 'fv-cg-view'); const title = scene ? tr(`Option ${index + 1}`, `方案 ${index + 1}`) : tr(...VIEW_TITLES[view]); - cell.title = title; cell.setAttribute('role', scene ? 'button' : 'img'); + setTip(cell, {name: title}); cell.setAttribute('aria-label', title); cell.setAttribute('role', scene ? 'button' : 'img'); if (scene) { cell.tabIndex = 0; const pick = () => { if (cell.dataset.state !== 'done') return; chosen = index; render(); }; diff --git a/web/comfy_templates.css b/web/comfy_templates.css new file mode 100644 index 00000000..9acc9c2a --- /dev/null +++ b/web/comfy_templates.css @@ -0,0 +1,8 @@ +/* The ComfyUI windows FreeVideo shows over its views (Templates, Settings, sign-in) keep ComfyUI's dark colours whatever the page theme; in the light + theme it takes the light set of the same names, so the windows match the page. Dark is untouched. */ +html[data-theme=light][data-fv-shell] body>[role=dialog]{color-scheme:light;--modal-panel-background:var(--color-smoke-200);--modal-card-background:#fff;--modal-card-background-hovered:var(--color-smoke-300);--modal-card-tag-background:var(--color-smoke-300);--modal-card-tag-foreground:var(--color-charcoal-700);--modal-card-placeholder-background:var(--color-smoke-300);--modal-card-button-surface:var(--color-smoke-300);--modal-card-border-highlighted:var(--color-azure-400);--fg-color:#000;--bg-color:#fff;--content-bg:#e0e0e0;--content-fg:#000;--content-hover-bg:#adadad;--content-hover-fg:#000;--accent-primary:var(--color-charcoal-700);--backdrop:var(--color-white);--button-surface:var(--color-white);--button-surface-contrast:var(--color-black);--button-hover-surface:var(--color-smoke-200);--button-active-surface:var(--color-smoke-400);--button-icon:var(--color-smoke-600);--dialog-surface:var(--color-neutral-200);--interface-menu-component-surface-hovered:var(--color-smoke-200);--interface-menu-component-surface-selected:var(--color-smoke-400);--interface-menu-keybind-surface-default:var(--color-smoke-500);--interface-menu-surface:var(--color-white);--interface-menu-stroke:var(--color-smoke-600);--interface-panel-surface:var(--color-white);--interface-stroke:var(--color-smoke-300);--nav-background:var(--color-white);--text-secondary:var(--color-smoke-800);--text-primary:var(--color-charcoal-700);--input-surface:#00000026;--muted-foreground:var(--color-charcoal-200);--base-foreground:var(--color-charcoal-800);--secondary-background:var(--color-smoke-200);--secondary-background-hover:var(--color-smoke-400);--secondary-background-selected:var(--color-smoke-600);--tertiary-background:var(--color-smoke-400);--tertiary-background-hover:var(--color-smoke-500);--base-background:var(--color-white);--primary-background:var(--color-azure-400);--primary-background-hover:var(--color-cobalt-800);--destructive-background:var(--color-coral-500);--inverted-background-hover:var(--color-charcoal-600);--warning-background:var(--color-gold-400);--border-default:var(--color-smoke-600);--border-subtle:var(--color-smoke-400);--muted-background:var(--color-smoke-700);--accent-background:var(--color-smoke-800)} +html[data-theme=light][data-fv-shell] body>[role=dialog] :is(h1,h2,h3,h4,label,header>i){color:var(--base-foreground)} +html[data-theme=light][data-fv-shell] body>[role=dialog] .text-muted{color:var(--muted-foreground)} +html[data-theme=light][data-fv-shell] body>[role=dialog] .p-divider-content{background:var(--base-background)} +html[data-theme=light][data-fv-shell] body>[role=dialog] .p-inputtext,html[data-theme=light][data-fv-shell] body>[role=dialog] textarea:not(.bg-transparent){background:#e9e9e9;color:var(--base-foreground);border-color:#d4d4d8} +html[data-theme=light][data-fv-shell] body>[role=dialog] .p-inputtext::placeholder,html[data-theme=light][data-fv-shell] body>[role=dialog] textarea::placeholder{color:var(--muted-foreground)} diff --git a/web/comfy_templates.js b/web/comfy_templates.js new file mode 100644 index 00000000..3f581f7f --- /dev/null +++ b/web/comfy_templates.js @@ -0,0 +1,34 @@ +// 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')); + +// English text of a ComfyUI-made label -> the Chinese FreeVideo shows in its place. +export const LABELS = {Popular: '热门'}; +export const SEARCH = {'搜索占位符': '搜索模板'}; + +export function polish(window_) { + if (!chinese) return; + for (const input of window_.querySelectorAll('input')) if (SEARCH[input.placeholder]) input.placeholder = SEARCH[input.placeholder]; + for (const span of window_.querySelectorAll('span,h2,h3')) { + if (span.children.length) continue; + const text = span.textContent.trim(); + if (LABELS[text] && span.textContent !== LABELS[text]) span.textContent = LABELS[text]; + } +} + +export function watchTemplates(body = document.body) { + if (!body || body.__fvTemplates) return; + body.__fvTemplates = true; + const follow = node => { + if (node.nodeType !== 1 || !node.matches?.('[role=dialog]') || node.__fvWatched) return; + node.__fvWatched = true; polish(node); + const inner = new MutationObserver(() => polish(node)); + inner.observe(node, {childList: true, subtree: true, characterData: true, attributes: true, attributeFilter: ['placeholder']}); + new MutationObserver((_, self) => { if (!node.isConnected) { inner.disconnect(); self.disconnect(); } }).observe(body, {childList: true}); + }; + new MutationObserver(records => { for (const record of records) record.addedNodes.forEach(follow); }).observe(body, {childList: true}); + body.querySelectorAll(':scope>[role=dialog]').forEach(follow); +} diff --git a/web/cut_tip.js b/web/cut_tip.js new file mode 100644 index 00000000..4fd935e0 --- /dev/null +++ b/web/cut_tip.js @@ -0,0 +1,40 @@ +// Words that are already on screen get a tip only when the screen shows them cut short; the tip then carries the whole +// text. The page-wide tooltip (tooltip.js) shows it, so the browser's own title tip never appears next to it. +// The check runs when the pointer or focus arrives, so it follows the width the element has at that moment. +import { setTip } from './tip_words.js'; + +const cutOff = node => !!node && (node.scrollWidth > node.clientWidth + 1 || node.scrollHeight > node.clientHeight + 1); + +export function cutTip(host, full, measure = host, {always = false} = {}) { + if (!host) return host; + host.__fvCutText = String(full ?? ''); + host.__fvCutMeasure = measure; + host.__fvCutAlways = always; + if (host.__fvCutBound) return refresh(host); + host.__fvCutBound = true; + listen(); + return refresh(host); +} + +// One listener on the window, in the capture phase: it runs before the page-wide tooltip (a document capture +// listener) looks at the element, so the very first hover already finds the tip words. +let listening = false; +function listen() { + if (listening || typeof window === 'undefined') return; + listening = true; + const check = event => { + for (let node = event.target; node; node = node.parentNode) { + if (node.__fvCutBound) refresh(node); + } + }; + window.addEventListener('pointerover', check, true); + window.addEventListener('focusin', check, true); +} + +// A tip not yet needed leaves the element without any title and without tip words. +function refresh(host) { + const text = host.__fvCutText; + const cut = text && (host.__fvCutAlways || cutOff(host.__fvCutMeasure || host)); + setTip(host, cut ? {name: text} : {}); + return host; +} diff --git a/web/editor.css b/web/editor.css index 04139dc9..f7e3e9ef 100644 --- a/web/editor.css +++ b/web/editor.css @@ -21,6 +21,10 @@ .fv-editor .fv-ed-genbar>.fv-ed-duration.fv-ed-beside-leaving[hidden]{display:block!important;pointer-events:none} .fv-editor button:where(:not(.fv-header button)){height:36px;min-height:0;border-radius:var(--fv-r-sm);font:500 13px/1.4 var(--fv-font);white-space:nowrap} .fv-editor .fv-header{grid-column:1/-1;position:sticky;top:0;z-index:6;background:var(--fv-bg)} +/* The update bar the creative panel brings along is one more grid row below the timeline: as wide as the window and kept at its bottom edge while the view scrolls, never past it. */ +.fv-studio.fv-editor>.fv-pop-holder>.fv-update-notice,.fv-studio.fv-editor>.fv-update-notice{grid-column:1/-1;grid-row:8;position:sticky;bottom:0;z-index:6} +/* On a narrow window the name and the close button share the first row and the buttons sit on one row below. */ +@media(max-width:680px){.fv-studio.fv-editor>.fv-pop-holder>.fv-update-notice,.fv-studio.fv-editor>.fv-update-notice{padding:8px 14px;justify-content:flex-start}.fv-studio.fv-editor>.fv-pop-holder>.fv-update-notice>span,.fv-studio.fv-editor>.fv-update-notice>span{flex:1 1 calc(100% - 60px);min-width:0;white-space:normal;order:0}.fv-studio.fv-editor>.fv-pop-holder>.fv-update-notice .fv-update-close,.fv-studio.fv-editor>.fv-update-notice .fv-update-close{order:1;margin-left:auto}.fv-studio.fv-editor>.fv-pop-holder>.fv-update-notice>:not(span):not(.fv-update-close),.fv-studio.fv-editor>.fv-update-notice>:not(span):not(.fv-update-close){order:2}} .fv-editor>:not(.fv-header){font-size:13px;line-height:1.4} .fv-editor .fv-brand{position:relative}.fv-editor .fv-brand>.fv-wordmark{flex-shrink:0} .fv-editor .fv-header-actions{min-width:0;height:100%}.fv-editor .fv-header-actions>button,.fv-editor .fv-ed-export-box>button{flex:none} @@ -69,8 +73,9 @@ .fv-ed-source-card .fv-issue-button{font-size:11px;min-height:28px;max-width:100%} .fv-editor .fv-ed-preview{grid-column:2;grid-row:3;min-width:0;min-height:0;display:grid;place-items:center;padding:16px;overflow:hidden;background:var(--fv-bg);container-type:size} .fv-ed-picture{position:relative;width:min(100cqw,calc(100cqh * var(--fv-ed-width,16) / var(--fv-ed-height,9)));aspect-ratio:var(--fv-ed-width,16)/var(--fv-ed-height,9);background:#000;border-radius:var(--fv-r-sm);overflow:hidden} -.fv-ed-picture[data-empty=true]{background:var(--fv-card);border:1px dashed color-mix(in srgb,var(--fv-ink) 28%,transparent)} +.fv-ed-picture[data-empty=true]{container:fv-picture/size;background:var(--fv-card);border:1px dashed color-mix(in srgb,var(--fv-ink) 28%,transparent)} .fv-ed-empty-preview{position:absolute;inset:0;display:flex;flex-direction:column;align-items:center;justify-content:center;gap:12px;color:var(--fv-muted);font-size:13px;text-align:center;padding:16px} +@container fv-picture (max-height:124px){.fv-ed-empty-preview-text{display:none}} .fv-ed-empty-preview svg{width:24px;height:24px;flex:none;fill:none;stroke:currentColor;stroke-width:1.4;stroke-linecap:round;stroke-linejoin:round} .fv-editor .fv-ed-preview-close{position:absolute;top:8px;right:8px;width:28px;height:28px;padding:0;z-index:2;background:var(--fv-card);border:1px solid var(--fv-border);color:var(--fv-muted)} .fv-ed-preview-close svg{width:16px;height:16px;fill:none;stroke:currentColor;stroke-width:1.4;stroke-linecap:round} @@ -255,7 +260,7 @@ @media(min-width:681px) and (max-width:1279px){.fv-ed-notice{right:32px;max-width:min(560px,calc(100vw - 330px))}} .fv-ed-notice .fv-issue-button{margin-left:12px;vertical-align:middle;pointer-events:auto} @media(max-width:680px){ - .fv-studio.fv-editor{--fv-ed-generation-row:calc(96px + var(--fv-ed-description-growth,0px) + var(--fv-ed-note-growth,0px));grid-template-columns:minmax(0,1fr);grid-template-rows:auto var(--fv-ed-project-h) minmax(0,1fr) 40px minmax(var(--fv-ed-generation-row),auto) 40px 236px;overflow:hidden} + .fv-studio.fv-editor{--fv-ed-generation-row:calc(96px + var(--fv-ed-description-growth,0px) + var(--fv-ed-note-growth,0px));grid-template-columns:minmax(0,1fr);grid-template-rows:auto var(--fv-ed-project-h) minmax(0,1fr) 40px minmax(var(--fv-ed-generation-row),auto) 40px 236px;overflow:hidden auto} .fv-editor .fv-header{overflow-x:auto} .fv-editor .fv-ed-name{font-size:13px;max-width:112px;flex:1;padding:0 2px} .fv-editor .fv-ed-icon{width:28px;flex:none;font-size:20px} @@ -325,8 +330,8 @@ /* Narrow window: the picture sits right under the header, the row takes the project's own shape (a 16:9 project is about 200 px tall at 400 px wide), and whatever height is left goes to the timeline. */ @media(max-width:680px){ - .fv-studio.fv-editor{grid-template-rows:auto var(--fv-ed-project-h) minmax(0,auto) 40px minmax(var(--fv-ed-generation-row),auto) 40px minmax(160px,1fr)} - .fv-editor .fv-ed-preview{box-sizing:border-box;align-self:start;width:100%;aspect-ratio:var(--fv-ed-project-width,16)/var(--fv-ed-project-height,9);max-height:max(116px,calc(100dvh - 362px - var(--fv-ed-generation-row)));padding-top:12px;padding-bottom:8px} + .fv-studio.fv-editor{grid-template-rows:auto var(--fv-ed-project-h) minmax(136px,auto) 40px minmax(var(--fv-ed-generation-row),auto) 40px minmax(160px,1fr)} + .fv-editor .fv-ed-preview{box-sizing:border-box;align-self:start;width:100%;aspect-ratio:var(--fv-ed-project-width,16)/var(--fv-ed-project-height,9);max-height:min(100%,max(136px,calc(100dvh - 362px - var(--fv-ed-generation-row))));padding-top:12px;padding-bottom:8px} } /* ── Layout that never moves (Iris E1, E8; CEO 11-14 "生成前会先下载……把下面的轨挤下去") ── @@ -486,7 +491,7 @@ /* ── Phone (≤680 px): this view's own controls are finger-sized (44 px) ── */ @media(max-width:680px){ - .fv-studio.fv-editor{--fv-ed-generation-row:calc(108px + var(--fv-ed-description-growth,0px) + var(--fv-ed-note-growth,0px));grid-template-rows:auto var(--fv-ed-project-h) minmax(0,auto) 44px minmax(var(--fv-ed-generation-row),auto) 48px minmax(160px,1fr)} + .fv-studio.fv-editor{--fv-ed-generation-row:calc(108px + var(--fv-ed-description-growth,0px) + var(--fv-ed-note-growth,0px));grid-template-rows:auto var(--fv-ed-project-h) minmax(136px,auto) 44px minmax(var(--fv-ed-generation-row),auto) 48px minmax(160px,1fr)} .fv-editor .fv-ed-genbar{padding-top:4px;padding-bottom:4px;row-gap:8px} .fv-editor .fv-ed-project-row :is(.fv-ed-name,.fv-ed-export-main,.fv-ed-save-state){height:44px;min-height:44px} .fv-editor .fv-ed-project-row .fv-ed-export-main{min-width:56px} diff --git a/web/editor_frame.css b/web/editor_frame.css index effe7c53..ce23933c 100644 --- a/web/editor_frame.css +++ b/web/editor_frame.css @@ -38,5 +38,7 @@ .fv-studio.fv-editor .fv-ed-picture-tools button[aria-pressed=true]{background:var(--fv-ctl-hover);color:var(--fv-fg)} /* The picture is centred on the window, not on its column (the side panes may differ in width); see editor_player.js. */ .fv-studio.fv-editor .fv-ed-picture{translate:var(--fv-ed-center-shift,0px) 0} -/* The empty picture: one line and the next step, centred, in the caption size. */ -.fv-studio.fv-editor .fv-ed-empty-preview-text{margin:0;max-width:32em;font-size:var(--fv-fs-2,13px);line-height:20px;color:var(--fv-fg3)} +/* The empty picture: the next step, centred, in the caption size; a wrapped line breaks evenly, never leaving one word or character alone. */ +.fv-studio.fv-editor .fv-ed-empty-preview-text{margin:0;max-width:32em;text-wrap:balance;font-size:var(--fv-fs-2,13px);line-height:20px;color:var(--fv-fg3)} +/* A frame too narrow for the hint shows the icon alone instead of a cut-off sentence (too short is handled in editor.css). */ +@container fv-picture (max-width:120px){.fv-studio.fv-editor .fv-ed-empty-preview-text{display:none}} diff --git a/web/editor_genbar.js b/web/editor_genbar.js index f9c4c77c..43707a57 100644 --- a/web/editor_genbar.js +++ b/web/editor_genbar.js @@ -1,4 +1,5 @@ // The editor owns its generation controls; progress can use the optional component. +import { cutTip } from './cut_tip.js'; import {createFirstFrameSwitch} from './editor_first_frame.js'; import {createDurationField} from './editor_duration.js'; import {createEditorReferences} from './editor_references.js'; @@ -364,7 +365,7 @@ export function createEditorGenbar(host, {state, t, actions, text = ''}) { ['fv-ed-gen-stage', stage], ['fv-ed-gen-time', time]]; const shown = spans.filter(([, text]) => text).map(([cls, text], index) => [cls, index ? ` · ${text}` : text]); hint.replaceChildren(...shown.map(([cls, text]) => el('span', cls, text))); - hint.title = shown.map(([, text]) => text).join(''); + cutTip(hint, shown.map(([, text]) => text).join('')); } duration.update(busy); firstFrame.update(busy); diff --git a/web/editor_text.js b/web/editor_text.js index 359b7cb3..fcafc552 100644 --- a/web/editor_text.js +++ b/web/editor_text.js @@ -1,5 +1,7 @@ // Text UI owns its controls, preview overlays and secondary menus. Timeline // editing remains in editor_tracks/model/select and the shared history. +import { cutTip } from './cut_tip.js'; +import { setTip } from './editor_tracks_tips.js'; import * as model from './editor_model.js'; import {FONT_KEYS} from './fonts.js'; import {row, button, slider, number, segmented, toggle} from './editor_adjust.js'; @@ -279,8 +281,8 @@ export function createEditorText({element,state,t,actions,adjust,player,toolbar, let badge=item.element.querySelector('.fv-ed-text-overflow'); const over=ready&&metrics&&c.text_kind==='subtitle'&&textLayout(metrics,c.text,styleOf(r,c),'subtitle',r.width,r.height).overTwo; if(over&&!badge){badge=el('span','fv-ed-text-overflow','⚠\uFE0E');badge.setAttribute('aria-label',overTwoHint(t));item.element.append(badge);} - if(badge){badge.hidden=!over;badge.title=overTwoHint(t);} - item.element.title=over?overTwoHint(t):c.text; + if(badge){badge.hidden=!over;setTip(badge,{name:overTwoHint(t)});} + cutTip(item.element,over?overTwoHint(t):c.text,item.element,{always:!!over}); } actions.textClip=updateClip; // Track switches stay out of undo (Q9); earlier snapshots get the same switch. diff --git a/web/editor_tracks.js b/web/editor_tracks.js index 9218d747..af3d9391 100644 --- a/web/editor_tracks.js +++ b/web/editor_tracks.js @@ -1,3 +1,4 @@ +import { cutTip } from './cut_tip.js'; import {editorIcon} from './editor_icons.js'; import {pageRepair, repairButton} from './repair_hint.js'; import {displayTracks, isText, isTextTrack, textDropLocked} from './editor_text_model.js'; @@ -641,11 +642,11 @@ export function createTracks(host, {state, sources = {}, t = en => en, actions = node.append(empty); const head = create('div', 'fv-ed-track-head'); head.dataset.track = track.id; const glyph = track.kind === 'audio' ? (track.stem ? 'audio' : track.id === MUSIC_TRACK ? 'music' : track.id === 'a3' ? 'mic' : 'audio') : track.kind; - head.title = name; head.append(icon(glyph), create('span', '', name)); + head.append(icon(glyph), create('span', '', name)); cutTip(head, name, head.querySelector('span')); heads.append(head); content.insertBefore(node, overlays); row = {element: node, head, empty}; rows.set(track.id, row); parted ||= !!track.stem; } - row.head.title = name; row.head.querySelector('span').textContent = name; + row.head.querySelector('span').textContent = name; cutTip(row.head, name, row.head.querySelector('span')); // Guide targets ("take me there"): the lanes where a range is dragged out for speech or music, and the // separated music lane where new music replaces the old. const tourId = track.stem === 'music' ? 'audio-music-stem' : track.stem ? '' : {a1: 'audio-a1-track', a2: 'audio-a2-track'}[track.id] || ''; @@ -1304,15 +1305,15 @@ export function createTracks(host, {state, sources = {}, t = en => en, actions = const first = rows.get('a1'), top = first.top + first.height + 6; const row = create('div', 'fv-ed-track-row'); row.dataset.track = 'a2'; row.dataset.preview = 'true'; const head = create('div', 'fv-ed-track-head'); head.dataset.track = 'a2'; head.dataset.preview = 'true'; - const name = t('Audio 2', '声音 2'); head.title = name; head.append(icon('audio'), create('span', '', name)); + const name = t('Audio 2', '声音 2'); head.append(icon('audio'), create('span', '', name)); cutTip(head, name, head.querySelector('span')); row.setAttribute('aria-label', name); row.style.top = head.style.top = `${top}px`; row.style.height = head.style.height = `${laneHeight()}px`; - const oldName = first.head.title, oldTop = addAudio.style.top, oldHeight = content.style.height; + const oldName = first.head.querySelector('span').textContent, oldTop = addAudio.style.top, oldHeight = content.style.height; sourcePreview.restore = () => { - first.head.title = oldName; first.head.querySelector('span').textContent = oldName; + first.head.querySelector('span').textContent = oldName; cutTip(first.head, oldName, first.head.querySelector('span')); addAudio.style.top = oldTop; setTrackHeight(parseFloat(oldHeight) - 34); }; - first.head.title = t('Audio 1', '声音 1'); first.head.querySelector('span').textContent = first.head.title; + first.head.querySelector('span').textContent = t('Audio 1', '声音 1'); cutTip(first.head, first.head.querySelector('span').textContent, first.head.querySelector('span')); addAudio.style.top = `${top + laneHeight() + 6}px`; setTrackHeight(top + laneHeight()); heads.insertBefore(head, addAudio); content.insertBefore(row, overlays); nodes.push(head, row); } diff --git a/web/editor_tracks_tips.js b/web/editor_tracks_tips.js index d8dcccf0..5c2bc9cd 100644 --- a/web/editor_tracks_tips.js +++ b/web/editor_tracks_tips.js @@ -3,21 +3,8 @@ // attributes; the native title is dropped so two tips never show at once. No DOM work happens at import time. export const modKey = typeof navigator !== 'undefined' && /Mac|iPhone|iPad/i.test(navigator.userAgentData?.platform || navigator.platform || '') ? '⌘' : 'Ctrl+'; -export function setTip(element, {name = '', use = '', key = '', why = ''} = {}) { - if (!element) return element; - // Writes only what changed: the transport refreshes on every playback frame. - // (Plain lookups only, so the small test DOM is enough.) - const read = attribute => element.getAttribute?.(attribute) ?? null; - const set = (attribute, value) => { - if (value) { if (read(attribute) !== value) element.setAttribute(attribute, value); } - else if (read(attribute) != null) element.removeAttribute?.(attribute); - }; - set('data-fv-tip-name', name); set('data-fv-tip-use', use); set('data-fv-tip-key', key); set('data-fv-tip-why', why); - // An empty title, never a stale one: the browser's own tip must not show next to this one. - if (element.title !== '') element.title = ''; - return element; -} - +import {setTip} from './tip_words.js'; +export {setTip}; // Each entry: [English name, Chinese name, English purpose (≤ 10 words), Chinese purpose (≤ 20 characters), key]. // Keys use modKey at run time where a modifier is involved. const COPY = { diff --git a/web/error_panel.js b/web/error_panel.js index d0afe2f1..e72c77c2 100644 --- a/web/error_panel.js +++ b/web/error_panel.js @@ -1,7 +1,7 @@ // Shared by the Studio and graph view. Text only; never render exception HTML. import {readOtherUsage, otherUsageText} from './other_usage.js'; import {pageRepair, repairAction, repairButton} from './repair_hint.js'; -import {detectBrowserExtension, browserExtensionAdvice, extensionSteps, isNetworkTypeError, connectionLostText, engineNotRunning, engineNotRunningText} from './browser_extension.js'; +import {detectBrowserExtension, browserExtensionAdvice, extensionSteps, isNetworkTypeError, connectionLostText, engineNotRunning, engineNotRunningText, isRequestTimeout, requestTimeoutText, requestTimeoutAction} from './browser_extension.js'; import {SAMPLING_EFFORTS, STEP_CACHES, UPSCALE_FACTORS, tableLevel} from './sampling_effort.js'; import {failureIssue, failureStage} from './failure_issue.js'; import {knownEngineExit} from './engine_exit.js'; @@ -325,9 +325,13 @@ export function createErrorReport(detail, context = {}) { } if (['this-computer', 'local-network', 'other-address', 'host-name', 'unknown'].includes(detail?.connection?.page_address)) connection.page_address = detail.connection.page_address; + // The ComfyUI page's own version, kept only when it is a plain version number: FreeVideo ships one frontend, and a + // request the page gives up on (a newer frontend stops waiting after a minute) reads differently on another. + const frontendVersion = String(globalThis.__COMFYUI_FRONTEND_VERSION__ ?? ''); const report = { schema: 'freevideo.error-report', schema_version: 1, created_at: new Date().toISOString(), stage, message: clean(message), + ...(/^\d{1,3}(?:\.\d{1,4}){1,3}(?:[-+][0-9A-Za-z.]{1,20})?$/.test(frontendVersion) ? {frontend_version: frontendVersion} : {}), ...(Object.keys(connection).length ? {connection} : {}), // Chosen from the original message before redaction removes any input // text from it, so a card shown again from this report keeps its advice. @@ -354,7 +358,7 @@ export function createErrorReport(detail, context = {}) { // Failures of turning a reference video into depth (freevideo_engine/depth_reference.py), most specific first. const RETRY_REPORT = ['Try again. If it happens again, choose "Report a problem" to send us the report.', '请重试。再次出现时,请点击“提交问题”,把报告发给我们。']; const REFERENCE_FAILURES = [ - [/Source video (?:frame count )?changed during depth (?:conversion|inspection)/i, + [/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', '参考视频在转换时被改动'], ['The reference video file changed while FreeVideo was converting it.', '转换参考视频的过程中,这个文件被改动了。'], ['Try again, and leave the file unchanged until the video is generated.', '请重试,并在生成完成前保持该文件不变。']], @@ -370,11 +374,11 @@ const REFERENCE_FAILURES = [ 'reference-vram', ['Not enough GPU memory for depth', '显存不足,无法提取深度'], ['Extracting depth needs free GPU memory, and other programs were using it.', '提取深度需要空闲显存,当时被其他程序占用。'], ['Close other programs that use the GPU, then try again.', '请关闭其他占用显卡的程序,然后重试。']], - [/Depth reference needs 1 GiB working RAM|Depth reference stopped to preserve 1 GiB/i, + [/Depth reference needs 1 GiB working RAM|Depth reference stopped to preserve 1 GiB|Turning the reference video into lines stopped to keep 1 GiB/i, 'reference-ram', ['Not enough memory to convert the reference video', '内存不足,参考视频未能转换完成'], ['FreeVideo stopped converting the reference video to keep the computer responsive.', '为保证电脑正常运行,FreeVideo 停止了参考视频的转换。'], ['Close other programs or use a shorter reference video, then try again.', '请关闭其他程序或换一段更短的参考视频,然后重试。']], - [/Not enough disk space to stage depth frames/i, + [/Not enough disk space to stage (?:depth|line) frames/i, 'reference-disk', ['Not enough disk space', '磁盘空间不足'], ['Converting the reference video needs temporary space on the drive that holds FreeVideo\'s data.', '转换参考视频需要在 FreeVideo 数据所在的磁盘上临时占用一些空间。'], ['Free some space on that drive, then try again.', '请在该磁盘上腾出一些空间,然后重试。']], @@ -383,9 +387,9 @@ const REFERENCE_FAILURES = [ // Raised when the depth step starts on a computer set up for the GPU, but the graphics driver offers none to it. ['When depth extraction started, the graphics driver did not make the GPU available.', '开始提取深度时,显卡驱动未提供可用的显卡。'], ['Restart FreeVideo and try again. If it happens again, choose "Report a problem" to send us the report.', '请重启 FreeVideo 后重试。再次出现时,请点击“提交问题”,把报告发给我们。']], - [/Depth reference worker exited with code|Depth reference cache unexpectedly contains|Depth reference output dimensions|Depth model returned invalid|Depth reference device must be/i, + [/(?:Depth|Line) reference worker exited with|Depth reference worker exited with code|Depth reference cache unexpectedly contains|Depth reference output dimensions|Depth model returned invalid|Depth reference device must be/i, 'reference-failed', ['The reference video could not be converted', '参考视频未能转换'], - ['Turning the reference video into depth stopped unexpectedly.', '把参考视频转成深度时意外中止。'], RETRY_REPORT], + ['Converting the reference video stopped unexpectedly.', '参考视频转换时意外中止。'], RETRY_REPORT], ]; // Match explicit failure signatures, not a guessed GPU/RAM capacity. Keep the @@ -625,6 +629,11 @@ export function adviceFor(report, t, value) { Object.assign(advice, {kind: 'connection', title: stopped ? t('FreeVideo has stopped', 'FreeVideo 已停止运行') : t('Lost the connection to FreeVideo', '与 FreeVideo 的连接已断开'), summary: stopped ? engineNotRunningText(t) : connectionLostText(t), action: ''}); } + // A request that was not answered in time: the card says so and what to check, instead of a bare title. + if (advice.kind === 'unknown' && ['submission', 'queue'].includes(report.stage) + && (isRequestTimeout(value) || report.exception_type === 'TimeoutError')) { + Object.assign(advice, {kind: 'timeout', title: t('FreeVideo did not answer in time', 'FreeVideo 未在规定时间内应答'), summary: requestTimeoutText(t), action: requestTimeoutAction(t)}); + } if (report.stage === 'submission' && advice.kind === 'unknown') { advice.title = t('The task could not be submitted', '任务提交失败'); advice.summary = ''; diff --git a/web/failure_issue.js b/web/failure_issue.js index 6a2eb998..d48507e1 100644 --- a/web/failure_issue.js +++ b/web/failure_issue.js @@ -56,7 +56,7 @@ export function failureIssue(report, kind, {lora = false, t = en => en, engineEx const summary = JSON.stringify({kind: kind || 'unknown', stage: report?.stage, exception_type: report?.exception_type, known_error: report?.known_error, nodes: types, settings: report?.settings, progress: report?.progress, // Before the long tail: an over-long summary is cut from its end. - engine_exit: engineExit || undefined, connection: report?.connection, run, tail: cause(report)}); + engine_exit: engineExit || undefined, connection: report?.connection, frontend_version: report?.frontend_version, run, tail: cause(report)}); const title = lora ? t('[Feedback] LoRA compatibility misjudged', '[Feedback] LoRA 兼容判断有误') : t('[Feedback] Generation did not finish', '[Feedback] 生成未完成') + (stage ? t(`: ${stage[0]}`, `:${stage[1]}`) : ''); return {title, text, summary}; diff --git a/web/field_note.css b/web/field_note.css new file mode 100644 index 00000000..d6514205 --- /dev/null +++ b/web/field_note.css @@ -0,0 +1,5 @@ +/* The line under a number field that says a typed value was brought into range (field_note.js). */ +.fv-field-why{margin:4px 0 0;font-size:12px;line-height:1.5;color:var(--fv-fg3,var(--fv-muted));text-align:left} +.fv-field-why[hidden]{display:none} +/* In the creation panel's settings tray each number box sits at the right of its row; the line starts under the box. */ +.fv-studio.fv-create .fvs-tray.fv-at .fv-field-why{width:var(--fv-at-w);max-width:100%;margin-left:auto;box-sizing:border-box} diff --git a/web/field_note.js b/web/field_note.js new file mode 100644 index 00000000..8789825e --- /dev/null +++ b/web/field_note.js @@ -0,0 +1,81 @@ +// A number field never raises the browser's own check bubble. A typed value outside the field's range is brought to +// the nearest allowed one, and a line under the field says so ("At most 31"); a value that cannot be brought in (a +// rule between two fields) is said on the same line. The line goes at the next edit. +let styled = false; +function style() { + if (styled || typeof document === 'undefined') return; + styled = true; + const css = document.createElement('link'); css.rel = 'stylesheet'; css.href = new URL('./field_note.css', import.meta.url).href; + document.head.append(css); +} + +const finite = text => text !== '' && text != null && Number.isFinite(Number(text)); +// Enough digits for a step like .05 or .1, without the float noise of the arithmetic. +const tidy = (n, step) => { + const places = Math.min(10, (String(step).split('.')[1] || '').length); + return Number(n.toFixed(places)); +}; + +// The allowed value nearest to the typed one, and which limit moved it: 'max', 'min' or 'step'. Null when the value +// is empty, not a number, or already allowed. +export function nearestAllowed(input) { + if (!finite(input.value)) return null; + const typed = Number(input.value); + const min = finite(input.min) ? Number(input.min) : -Infinity, max = finite(input.max) ? Number(input.max) : Infinity; + let value = typed, kind = null; + if (value > max) { value = max; kind = 'max'; } else if (value < min) { value = min; kind = 'min'; } + if (finite(input.step) && Number(input.step) > 0) { + const step = Number(input.step), base = Number.isFinite(min) ? min : 0; + let snapped = tidy(base + Math.round((value - base) / step) * step, step); + if (snapped > max) snapped = tidy(snapped - step, step); + if (snapped < min) snapped = tidy(snapped + step, step); + if (snapped !== value) { value = snapped; kind ??= 'step'; } + } + return kind && value !== typed ? {value, kind} : null; +} + +// note = fieldNote(input, {t, place, limits}); note.settle() → true when the field holds an allowed value. +// place: the element the line goes after (default: the field's label). limits: {max(n), min(n), step(n)} words. +// className: an extra class, for a line that sits among other lines styled as one (the console's status lines). +export function fieldNote(input, {t = (en, zh) => en, place = null, limits = {}, className = ''} = {}) { + let line = null; + const words = { + max: n => t(`At most ${n}`, `最多 ${n}`), + min: n => t(`At least ${n}`, `最少 ${n}`), + step: n => t(`Changed to ${n}`, `已改为 ${n}`), + ...limits, + }; + function say(text) { + if (!text) { clear(); return; } + style(); + if (!line) { + line = document.createElement('p'); line.className = `fv-field-why ${className}`.trim(); line.setAttribute('role', 'status'); + line.id = `fv-field-why-${Math.random().toString(36).slice(2, 10)}`; + } + const after = (typeof place === 'function' ? place() : place) || input.closest?.('label, .fv-field') || input; + if (line.previousElementSibling !== after) after.after(line); + line.textContent = text; line.hidden = false; + const described = (input.getAttribute('aria-describedby') || '').split(/\s+/).filter(Boolean); + if (!described.includes(line.id)) input.setAttribute('aria-describedby', [...described, line.id].join(' ')); + } + function clear() { if (line && !line.hidden) { line.hidden = true; line.textContent = ''; } } + input.addEventListener('input', clear); + return { + say, clear, + get line() { return line; }, + // Brings an out-of-range value in and says so; a rule it cannot satisfy is said, and false returned. + // An empty field is false and left to the caller, which knows whether empty is allowed. + settle({quiet = false} = {}) { + const moved = nearestAllowed(input); + if (moved) { + input.value = String(moved.value); + if (!quiet) say(words[moved.kind](moved.value)); + } + if (input.value === '') return false; + if (input.checkValidity()) return true; + // A rule of ours carries its own words; anything else gets ours, not the browser's. + if (!quiet) say(input.validity.customError ? input.validationMessage : t('Enter a number in range', '请输入范围内的数')); + return false; + }, + }; +} diff --git a/web/first_frame_row.js b/web/first_frame_row.js index c4a630d0..0a549571 100644 --- a/web/first_frame_row.js +++ b/web/first_frame_row.js @@ -3,17 +3,13 @@ const el = (tag, cls, text) => { const e = document.createElement(tag); if (cls) // Shared by the studio and the editing view; neither pulls in the other. export function firstFrameRow(t, className) { const row = el('label', className, t('First-frame reference', '首帧参考')); - row.title = t('Reduces drift', '减小漂移'); const input = el('input'); input.type = 'checkbox'; input.setAttribute('role', 'switch'); input.setAttribute('aria-label', t('First-frame reference', '首帧参考')); row.append(input); - const purpose = row.title; row.dataset.fvTipName = t('First-frame reference', '首帧参考'); row.dataset.fvTipUse = t('Each part starts from the first frame: less drift', '每段参照首帧,减小画面漂移'); return {row, input, setDisabled(disabled) { if (input.disabled !== disabled) input.disabled = disabled; if (input.title !== '') input.title = ''; - const rowTitle = disabled ? '' : purpose; - if (row.title !== rowTitle) row.title = rowTitle; }}; } diff --git a/web/freevideo.js b/web/freevideo.js index 478f5186..ca66dad8 100644 --- a/web/freevideo.js +++ b/web/freevideo.js @@ -1,3 +1,5 @@ +import { setTip } from './tip_words.js'; +import { cutTip } from './cut_tip.js'; import './has_mirror.js'; import { createErrorPanel, errorText, createErrorReport, adviceFor } from './error_panel.js'; import { installNativeErrorGuard } from './native_errors.js'; @@ -62,7 +64,7 @@ style.textContent = ` .fv-panel[data-freevideo=result]{display:flex;flex-direction:column;justify-content:center}.fv-panel[data-freevideo=result][data-hx-ppr]{justify-content:flex-start}.fv-panel .fv-connected-card{text-align:center;padding:28px 12px;border:1px solid var(--fv-border);border-radius:var(--fv-r-md,12px);color:var(--fv-muted);background:var(--fv-raised)} .fv-panel button,.fv-panel select,.fv-panel a{box-sizing:border-box;min-height:var(--fv-h-sm,32px);border:1px solid var(--fv-border);border-radius:var(--fv-r-sm,8px);background:var(--fv-raised);color:var(--fv-ink);padding:5px 10px;font:inherit;font-weight:var(--fv-medium,500);cursor:pointer;text-decoration:none} .fv-panel button:hover,.fv-panel a:hover{background:var(--fv-hover)}.fv-panel button:disabled{opacity:.45;cursor:wait} -.fv-panel select{max-width:170px}.fv-panel .fv-toolbar>.fv-select{width:auto}.fv-note[hidden]{display:none}.fv-note{color:var(--fv-muted);font-size:var(--fv-micro,12px);margin:8px 0;white-space:pre-wrap}.fv-error{color:var(--fv-danger)}.fv-panel .fv-depth-only input,.fv-panel .fv-sound input{min-height:0;height:16px}.fv-panel .fv-depth-only{display:flex;align-items:center;gap:6px;margin:0 0 8px;white-space:nowrap;font-size:var(--fv-micro);cursor:pointer} +.fv-panel select{max-width:170px}.fv-panel .fv-toolbar>.fv-select{width:auto}.fv-note[hidden]{display:none}.fv-note{color:var(--fv-muted);font-size:var(--fv-micro,12px);margin:8px 0;white-space:pre-wrap}.fv-error{color:var(--fv-danger)}.fv-panel .fv-depth-only input,.fv-panel .fv-lines-only input,.fv-panel .fv-sound input{min-height:0;height:16px}.fv-panel .fv-depth-only,.fv-panel .fv-lines-only{display:flex;align-items:center;gap:6px;margin:0 0 8px;white-space:nowrap;font-size:var(--fv-micro);cursor:pointer} .fv-mode{font-size:var(--fv-micro,12px);color:var(--fv-accent)} .fv-panel .fv-time{display:flex;align-items:center;gap:8px;margin:8px 0 0}.fv-panel .fv-time input{width:92px;min-height:var(--fv-h-sm,32px);padding:4px 8px;border:1px solid var(--fv-border);border-radius:var(--fv-r-sm,8px);background:var(--fv-bg);color:var(--fv-ink);font:inherit;font-size:16px}.fv-panel .fv-time input[aria-invalid=true]{border-color:var(--fv-danger)}.fv-panel .fv-time-error{margin:4px 0 0;color:var(--fv-danger);font-size:var(--fv-micro,12px)} .fv-card{border:1px solid var(--fv-border);border-radius:var(--fv-r-md,12px);padding:10px;margin-top:10px;background:var(--fv-raised)} @@ -429,7 +431,7 @@ function mediaPanel(node, mount = null) { const link = node.graph?.links[node.inputs.find(i => i.name === name).link]; const source = link && node.graph?.getNodeById(link.origin_id); const chip = el('span', `${label} · ${text('Connected', '已连接')}`, 'fv-connection'); - chip.title = source?.title || source?.type || label; connections.append(chip); + setTip(chip, {name: source?.title || source?.type || label}); connections.append(chip); } const middleProblem = middleNotice(active, {first, last, references: refs, seconds: videoSeconds()}, text); const audioUnlinked = node.widgets?.find(w => w.name === 'audio_use')?.value === 'original' && !linked('reference_audio'); @@ -446,7 +448,7 @@ function mediaPanel(node, mount = null) { } rows[index].enabled = enabled.checked; update(rows); }; - const label = el("span", mediaName(row), "fv-file"); label.title = mediaName(row); + const label = el("span", mediaName(row), "fv-file"); cutTip(label, mediaName(row)); const select = el("select"); select.setAttribute("aria-label", text("Media role", "素材用途")); // One width for every role, whatever the options say in the current state: "Middle frame" is the longest usual one. select.style.width = cn ? '7.5em' : '10em'; @@ -506,13 +508,18 @@ function mediaPanel(node, mount = null) { } let showLength = () => {}; if (kind === "video" && row.role === "reference") { - // Off by default: the video itself is the reference. On: its depth picture is, and the picture and colours are not asked for. - const depth = el("label", undefined, "fv-depth-only"), box = el("input"); - box.type = "checkbox"; box.checked = row.depth === true; - box.onchange = () => { if (box.checked) rows[index].depth = true; else delete rows[index].depth; update(rows); }; - depth.append(box, el("span", text("Depth only", "仅参考深度"))); - depth.title = text("Uses a depth version of this video as the reference.", "转成深度视频后再作参考。"); - card.append(depth); + // Off by default: the video itself is the reference. Depth only: its depth picture is; composition only: a + // line drawing of it is, which carries its layout but not its motion (gap-08a A/B, 11-17). Either way its + // picture and colours are not asked for, and at most one is on. + const only = (key, other, words, title) => { + const label = el("label", undefined, `fv-${key}-only`), box = el("input"); + box.type = "checkbox"; box.checked = row[key] === true; + box.onchange = () => { if (box.checked) { rows[index][key] = true; delete rows[index][other]; } else delete rows[index][key]; update(rows); }; + label.append(box, el("span", words)); setTip(label, {name: words, use: title}); + return label; + }; + card.append(only("depth", "lines", text("Depth only", "仅参考深度"), text("Uses a depth version of this video as the reference.", "转成深度视频后再作参考。")), + only("lines", "depth", text("Composition only", "仅参考构图"), text("Uses a line drawing of this video, so the new video follows its layout, not its motion or colours.", "转成线稿后作参考:新视频沿用它的构图,不沿用动作和颜色。"))); } if (kind === "video") { const sound = el("label", undefined, "fv-sound"); const box = el("input"); box.type = "checkbox"; box.checked = row.sound !== false; @@ -579,7 +586,7 @@ function mediaPanel(node, mount = null) { // The run takes only what it uses (and which character a picture belongs to); the editing data of a picture stays in the workflow. const blocked = middleBlock(); if (blocked) throw new Error(blocked); - try { return JSON.stringify(read().map(({file, role, enabled, cast, sound, depth, use, range, seconds}) => ({file, role, enabled, ...(role === 'middle' && Number.isFinite(seconds) ? {seconds} : {}), ...(use === AUDIO_USE.original ? {use, ...(range && typeof range === 'object' ? {range} : {})} : {}), ...(sound === false && mediaKindOrNull(file) === 'video' ? {sound: false} : {}), ...(depth === true && role === 'reference' && mediaKindOrNull(file) === 'video' ? {depth: true} : {}), ...(typeof cast?.id === 'string' && cast.id ? {cast: {id: cast.id, ...(cast.setting === true ? {setting: true} : cast.prop === true ? {prop: true} : {})}} : {})}))); } catch { return serialized.value; } + try { return JSON.stringify(read().map(({file, role, enabled, cast, sound, depth, lines, use, range, seconds}) => ({file, role, enabled, ...(role === 'middle' && Number.isFinite(seconds) ? {seconds} : {}), ...(use === AUDIO_USE.original ? {use, ...(range && typeof range === 'object' ? {range} : {})} : {}), ...(sound === false && mediaKindOrNull(file) === 'video' ? {sound: false} : {}), ...(depth === true && role === 'reference' && mediaKindOrNull(file) === 'video' ? {depth: true} : {}), ...(lines === true && depth !== true && role === 'reference' && mediaKindOrNull(file) === 'video' ? {lines: true} : {}), ...(typeof cast?.id === 'string' && cast.id ? {cast: {id: cast.id, ...(cast.setting === true ? {setting: true} : cast.prop === true ? {prop: true} : {})}} : {})}))); } catch { return serialized.value; } }; // `as` (reference / first / last) places these images without changing the toolbar's choice. async function upload(files, {role: as} = {}) { diff --git a/web/generation_progress.js b/web/generation_progress.js index 8c95e0d0..f8fc92d2 100644 --- a/web/generation_progress.js +++ b/web/generation_progress.js @@ -22,6 +22,7 @@ const SUBACTIVITY = { prompt: ['Processing the prompt', '正在处理提示词'], reference: ['Processing reference images and videos', '正在处理参考图片和视频'], depth: ['Extracting depth from the reference video', '正在提取参考视频的深度'], + lines: ['Drawing lines from the reference video', '正在把参考视频转成线稿'], load: ['Loading the video model', '正在载入视频模型'], first: ['Running the first step (it takes longer the first time a size is used or after an update)', '正在进行第一步(首次使用这个尺寸或更新后,第一步要多花一些时间)'], @@ -40,7 +41,7 @@ const SAMPLING_NAME = { }; const SAMPLING_PASS = {first: ['first pass', '一采'], pass2: ['second pass', '二采'], preview: ['preview', '预览']}; const SUBACTIVITY_LABELS = { - 'Extracting depth from the reference video': 'depth', + 'Extracting depth from the reference video': 'depth', 'Drawing lines from the reference video': 'lines', 'Starting generation process': 'start', 'Starting text encoder': 'libraries', 'Loading text encoder': 'libraries', 'Preparing text encoder GPU': 'gpu', 'Reading text encoder weights': 'weights', 'Preparing text encoder model': 'weights', @@ -125,7 +126,7 @@ const LABEL_ACTIVITY = { 'Preparing prompt data', 'Saving prompt cache', 'Reusing prompt cache', 'Prompt ready', 'Releasing idle models and checking available memory again'], combined: ['Encoding text and images', 'Preparing the prompt and images', 'Preparing text and image tokens'], - reference: ['Extracting depth from the reference video', 'Preparing reference media', 'Retaining and checking input media', 'Encoding input media', + reference: ['Extracting depth from the reference video', 'Drawing lines from the reference video', 'Preparing reference media', 'Retaining and checking input media', 'Encoding input media', 'Encoding reference media', 'Encoding image/video references', 'Encoding reference audio', 'Encoding long references', 'Encoding long references in smaller blocks'], load: ['Loading the video model', 'Loading video model', 'Loading native MPS model', 'Loading cached video model', diff --git a/web/glass/library.css b/web/glass/library.css index 1e9a0b64..af77d28b 100644 --- a/web/glass/library.css +++ b/web/glass/library.css @@ -1,8 +1,8 @@ /* Glass for the dialogs, cards and popovers of settings, versions, what's new, feedback, failures, the tutorial, feature cards, the character editor and phone access. Loaded after each module's own sheet (glass/library.js), it points the old dark tokens (--fv-bg, --fv-ink, …) at the shell's glass tokens inside these surfaces, so their own - rules follow light and dark, and gives every one the same material: a level-3 glass sheet over a veil that covers - the whole window. Solid when transparency is reduced, unsupported or switched off. */ + rules follow light and dark, and gives every one the same material: an opaque sheet in the glass tint over a veil + that covers the whole window, so nothing moving behind a dialog shows through it. */ :root:root :is(.fv-setup,.fv-release-notes,.fv-whatsnew,.fv-feature-tour,.fv-cast-dialog,.fv-failure-dialog,.fv-tutorial-book,.fv-book-zoom, .fv-lan-panel,.fv-lan-tip,.fv-guide-bubble,.fv-health,.fv-report-tip,.phone-confirm){ --fv-bg:rgb(var(--fv-solid3));--fv-canvas:rgb(var(--fv-solid2));--fv-card:var(--fv-ctl-bg);--fv-raised:var(--fv-ctl-hover);--fv-hover:var(--fv-ctl-hover); @@ -19,13 +19,11 @@ /* The sheets: one material, one radius, one shadow. Radii follow the shell's ladder from the outside in: sheets var(--fv-r-lg), popovers and cards on them var(--fv-r-md), buttons, fields and pictures var(--fv-r-sm). */ :root:root :is(dialog.fv-setup,dialog.fv-release-notes,dialog.fv-whatsnew,dialog.fv-feature-tour,dialog.fv-cast-dialog,dialog.fv-failure-dialog,dialog.fv-tutorial-book,dialog.phone-confirm){ - border:1px solid var(--fv-edge);border-radius:var(--fv-r-lg);background:rgb(var(--fv-tint) / var(--fv-a3)); - -webkit-backdrop-filter:blur(var(--fv-glass-blur3,40px)) saturate(175%);backdrop-filter:blur(var(--fv-glass-blur3,40px)) saturate(175%); + border:1px solid var(--fv-edge);border-radius:var(--fv-r-lg);background:rgb(var(--fv-tint));-webkit-backdrop-filter:none;backdrop-filter:none; box-shadow:inset 0 1px 0 var(--fv-edge-hi),var(--fv-sh3);color:var(--fv-fg)} /* Popovers and cards that float over a view. */ :root:root :is(.fv-lan-panel,.fv-guide-bubble,.fv-health,.fv-report-tip){ - border:1px solid var(--fv-edge);border-radius:var(--fv-rad-pop);background:rgb(var(--fv-tint) / var(--fv-a3)); - -webkit-backdrop-filter:blur(var(--fv-glass-blur3,40px)) saturate(175%);backdrop-filter:blur(var(--fv-glass-blur3,40px)) saturate(175%); + border:1px solid var(--fv-edge);border-radius:var(--fv-rad-pop);background:rgb(var(--fv-tint));-webkit-backdrop-filter:none;backdrop-filter:none; box-shadow:inset 0 1px 0 var(--fv-edge-hi),var(--fv-sh3);color:var(--fv-fg)} :root:root .fv-lan-tip{border:1px solid var(--fv-edge);border-radius:var(--fv-r-md);background:rgb(var(--fv-solid3));color:var(--fv-fg);box-shadow:var(--fv-sh2)} /* The veil under a sheet covers the whole window (no grey ring, no ComfyUI showing through). */ diff --git a/web/glass/media_tray.css b/web/glass/media_tray.css index 65f5ba87..26fb138f 100644 --- a/web/glass/media_tray.css +++ b/web/glass/media_tray.css @@ -55,10 +55,10 @@ .fvs-tray .fv-mt .fv-card[data-fv-mt-wide=true]>.fv-row:first-of-type input[type=checkbox]{margin-left:0} .fvs-tray .fv-mt .fv-card[data-fv-mt-wide=true]>.fv-row:first-of-type :is(.fv-select,select){color:var(--fv-fg)!important} .fvs-tray .fv-mt .fv-card[data-fv-mt-wide=true]>.fv-row:first-of-type .fv-select::after{color:var(--fv-fg2)} -.fvs-tray .fv-mt .fv-card[data-fv-mt-wide=true]>:is(.fv-time,.fv-depth-only,.fv-sound,.fv-note,.fv-audio-use-note,.fv-time-error){grid-column:2;margin:0} +.fvs-tray .fv-mt .fv-card[data-fv-mt-wide=true]>:is(.fv-time,.fv-depth-only,.fv-lines-only,.fv-sound,.fv-note,.fv-audio-use-note,.fv-time-error){grid-column:2;margin:0} .fvs-tray .fv-mt .fv-card :is(.fv-note,.fv-audio-use-note,.fv-time-error){padding:0;border:0;background:none;font-size:var(--fv-fs-1);line-height:16px;color:var(--fv-fg3)} -.fvs-tray .fv-mt .fv-card :is(.fv-depth-only,.fv-sound){display:flex;align-items:center;gap:var(--fv-sp-4);min-height:32px;font-size:var(--fv-fs-1);line-height:16px;color:var(--fv-fg2);white-space:normal} -.fvs-tray .fv-mt .fv-card :is(.fv-depth-only,.fv-sound) input{flex:none;margin:0} +.fvs-tray .fv-mt .fv-card :is(.fv-depth-only,.fv-lines-only,.fv-sound){display:flex;align-items:center;gap:var(--fv-sp-4);min-height:32px;font-size:var(--fv-fs-1);line-height:16px;color:var(--fv-fg2);white-space:normal} +.fvs-tray .fv-mt .fv-card :is(.fv-depth-only,.fv-lines-only,.fv-sound) input{flex:none;margin:0} .fvs-tray .fv-mt .fv-card .fv-time{display:flex;align-items:center;gap:var(--fv-sp-4);font-size:var(--fv-fs-1);color:var(--fv-fg2)} .fvs-tray .fv-mt .fv-card .fv-time input{flex:1;min-width:0;width:auto!important;height:32px;min-height:32px;font-size:var(--fv-fs-2)!important} .fvs-tray .fv-mt .fv-card :is(.fv-error,.fv-time-error){color:var(--fv-warning)} diff --git a/web/glass/media_tray.js b/web/glass/media_tray.js index bf8d8eac..466a9718 100644 --- a/web/glass/media_tray.js +++ b/web/glass/media_tray.js @@ -34,12 +34,12 @@ function markCard(card) { } // A tile with more to set than its use (a middle frame's time, a video's depth and sound, audio) is three squares // wide: the picture, and its settings beside it. - card.dataset.fvMtWide = String(Boolean(card.querySelector(':scope > :is(.fv-time,.fv-depth-only,.fv-sound,audio.fv-preview)'))); + card.dataset.fvMtWide = String(Boolean(card.querySelector(':scope > :is(.fv-time,.fv-depth-only,.fv-lines-only,.fv-sound,audio.fv-preview)'))); const rows = [...card.children].filter(child => child.classList.contains('fv-row')); const controls = rows.length > 1 ? rows.at(-1) : null; // Edited is a small mark on the picture; its words stay as the mark's name. const edited = card.querySelector('.fv-edited'); - if (edited && !edited.title) { edited.title = edited.textContent; edited.setAttribute('role', 'img'); edited.setAttribute('aria-label', edited.textContent); } + if (edited && !edited.hasAttribute('role')) { edited.setAttribute('role', 'img'); edited.setAttribute('aria-label', edited.textContent); } if (!controls || controls.classList.contains('fv-mt-rest')) return; controls.classList.add('fv-mt-rest'); const buttons = [...controls.querySelectorAll(':scope > button')], keys = document.createElement('div'); diff --git a/web/glass/player_bar.js b/web/glass/player_bar.js index 13f26fe6..62826d19 100644 --- a/web/glass/player_bar.js +++ b/web/glass/player_bar.js @@ -53,11 +53,18 @@ export function attach(video, host, {compact = false, t = words} = {}) { bar.append(play, track, time, sound); let frame = 0, shownTime = '', shownPercent = '', shownPlay = '', shownSound = ''; - // Runs every frame while the video plays. Only the fill moves each frame; the time and the percentage are written - // when they change (once a second), because each new text node makes the page restyle the whole view around it. + // Runs every frame while the video plays, but writes only what changed: the fill moves once it has moved two pixels + // of the rail and at least 50 ms have passed (at most 20 a second; every write restyles and repaints the view around + // it, ~50 a second when written per frame), and at once when the video is paused, seeks or loops back. The time and + // the percentage are written when their text changes (once a second). + let railWidth = 0, shownAt = -1, shownStamp = 0; + if (typeof ResizeObserver === 'function') new ResizeObserver(() => { railWidth = rail.clientWidth; shownAt = -1; }).observe(rail); const draw = () => { - const at = video.duration ? video.currentTime / video.duration : 0; - fill.style.transform = `scaleX(${at})`; + const now = video.currentTime, stamp = performance.now(); + const at = video.duration ? now / video.duration : 0; + if (!railWidth) railWidth = rail.clientWidth; + const moved = Math.abs(now - shownAt) / (video.duration || 1) * railWidth; + if (video.paused || now < shownAt || shownAt < 0 || (moved >= 2 && stamp - shownStamp >= 50)) { shownAt = now; shownStamp = stamp; fill.style.transform = `scaleX(${at})`; } const percent = String(Math.round(at * 100)); if (percent !== shownPercent) { shownPercent = percent; track.setAttribute('aria-valuenow', percent); } const clockText = `${clock(video.currentTime)} / ${clock(video.duration)}`; @@ -66,12 +73,15 @@ export function attach(video, host, {compact = false, t = words} = {}) { cancelAnimationFrame(frame); if (!video.paused && video.isConnected) frame = requestAnimationFrame(draw); }; + let shownPlayName = '', shownSoundName = ''; const sync = () => { const playGlyph = video.paused ? 'play' : 'pause', soundGlyph = video.muted ? 'muted' : 'sound'; if (playGlyph !== shownPlay) { shownPlay = playGlyph; play.replaceChildren(glyph(playGlyph)); } - const name = video.paused ? t('Play', '播放') : t('Pause', '暂停'); play.setAttribute('aria-label', name); play.dataset.fvTipName = name; + const name = video.paused ? t('Play', '播放') : t('Pause', '暂停'); + if (name !== shownPlayName) { shownPlayName = name; play.setAttribute('aria-label', name); play.dataset.fvTipName = name; } if (soundGlyph !== shownSound) { shownSound = soundGlyph; sound.replaceChildren(glyph(soundGlyph)); } - const what = video.muted ? t('Sound on', '打开声音') : t('Sound off', '关闭声音'); sound.setAttribute('aria-label', what); sound.dataset.fvTipName = what; + const what = video.muted ? t('Sound on', '打开声音') : t('Sound off', '关闭声音'); + if (what !== shownSoundName) { shownSoundName = what; sound.setAttribute('aria-label', what); sound.dataset.fvTipName = what; } }; const seek = event => { const box = track.getBoundingClientRect(); if (video.duration && box.width) video.currentTime = Math.max(0, Math.min(1, (event.clientX - box.left) / box.width)) * video.duration; draw(); }; const down = event => { track.setPointerCapture(event.pointerId); seek(event); track.addEventListener('pointermove', seek); }; diff --git a/web/glass/settings.css b/web/glass/settings.css index 5780d584..f1e673d0 100644 --- a/web/glass/settings.css +++ b/web/glass/settings.css @@ -324,7 +324,8 @@ dialog.fv-set .st-mrow .st-re .st-btn{min-width:72px} /* ── The plan sheet (g3, modal over the room) ── */ dialog.fv-set .st-dlg{position:fixed;inset:0;margin:auto;width:min(600px,calc(100vw - 2 * var(--st-gap)));height:fit-content;max-height:calc(100dvh - 2 * var(--fv-sp-32));padding:0; - flex-direction:column;border-radius:var(--fv-rad-console);overflow:hidden;color:var(--fv-fg)} + flex-direction:column;border-radius:var(--fv-rad-console);overflow:hidden;color:var(--fv-fg); + background:rgb(var(--fv-tint));-webkit-backdrop-filter:none;backdrop-filter:none} dialog.fv-set .st-dlg[open]{display:flex} dialog.fv-set .st-dlg::backdrop{background:var(--fv-scrim,rgb(3 4 6 / .6))} @media (prefers-reduced-motion:no-preference){ diff --git a/web/health.js b/web/health.js index 4aacafb6..990bb522 100644 --- a/web/health.js +++ b/web/health.js @@ -22,7 +22,7 @@ export const MODULES = ['audio_original.js', 'chat_data.js', 'phone_model.js', ' 'empty_prompt_notice.js', 'feature_tour.js', 'feature_tour_content.js', 'howto.js', 'swap_lora.js', 'sound_bubble.js', 'tour_goto.js', 'tour_try.js', 'tutorial_book.js', 'tutorial_book_content.js', 'shell.js', 'tooltip.js', 'tooltip_copy.js', 'library_meta.js', 'cast_room.js', - 'editor_tracks_tips.js', + 'editor_tracks_tips.js', 'tip_words.js', 'cut_tip.js', 'field_note.js', 'image_view_layout.js', 'task_store.js', 'task_float.js', 'image_view_ui.js', 'image_view_size.js', 'image_view_models.js', 'image_view_history.js', 'image_view_prompts.js', 'image_view_compare.js', 'image_view_queue.js', 'image_view_mentions.js', 'image_view_warm.js', 'image_view_viewer.js', 'image_view_lora.js', 'palette.js', 'picture_zoom.js', 'global_search.js', 'notifications.js', 'shortcuts.js', 'context_menu.js', @@ -31,7 +31,7 @@ export const MODULES = ['audio_original.js', 'chat_data.js', 'phone_model.js', ' 'feature_tour_layer.js', 'settings_room.js', 'settings_kit.js', 'settings_words.js', 'image_works.js', 'cast_photo.js', 'editor_opening.js', 'editor_poster.js', 'topbar_state.js', 'preload_setting.js', 'private_offers.js', 'cast_face_crop.js', 'context_fallback.js', 'studio_warm.js', 'pose_body.js', 'pose_props.js', 'pose_stage.js', 'pose_tool.js', 'release_media.js', 'ui_speed.js', - 'lora_menu.js', 'upscale_offer.js', 'user_message.js', 'workflow_drafts.js']; + 'lora_menu.js', 'upscale_offer.js', 'user_message.js', 'workflow_drafts.js', 'comfy_templates.js']; const sleep = ms => new Promise(resolve => setTimeout(resolve, ms)); let visibleAt = 0; async function waitForVisible() { diff --git a/web/image_editor.js b/web/image_editor.js index cb5d211d..dd3a87d2 100644 --- a/web/image_editor.js +++ b/web/image_editor.js @@ -3,6 +3,8 @@ // FreeVideo's own look. The original file is never changed: saving renders a // new image and keeps the document, so the next visit starts from the original // with every layer and step in place. Closing frees every canvas it made. +import { cutTip } from './cut_tip.js'; +import { setTip } from './tip_words.js'; import {BLENDS, emptyAdjust, migrate, blankDocument, orientedSize, orientMatrix, canvasRect, layerMatrix, scaleSelection, rasterKinds, measureText, Renderer, traceOutline, simplifyLoop} from './image_editor_engine.js'; import * as commands from './image_commands.js'; @@ -785,7 +787,7 @@ async function openImageEditorNow({source = null, name = source || '', target = // The options row is one line for every tool, so the picture never moves when the tool changes: what does not fit // goes, in its order, under More at the end of the row (a long hint is cut short instead, with its full text on hover). function fitOptions() { - for (const n of optionsBar.querySelectorAll(':scope > .fv-ie-opt-note')) n.title = n.textContent; + for (const n of optionsBar.querySelectorAll(':scope > .fv-ie-opt-note')) cutTip(n, n.textContent); if (optionsBar.scrollWidth <= optionsBar.clientWidth + 1) return; const more = el('details', null, 'fv-ie-menu fv-ie-more'), summary = el('summary', t('More', '更多')), list = el('div', null, 'fv-ie-menu-list fv-ie-more-list'); summary.dataset.fvTipName = t('More options', '更多选项'); summary.setAttribute('aria-label', summary.dataset.fvTipName); @@ -1060,18 +1062,18 @@ async function openImageEditorNow({source = null, name = source || '', target = e => { e.stopPropagation(); commit(commands.setLayer(doc, l.id, {visible: !l.visible})); }, 'fv-ie-eye'); const thumb = el('canvas', null, 'fv-ie-thumb'); thumb.width = 48; thumb.height = 34; drawThumb(thumb, l); const name = el('span', l.name || t('Layer', '图层'), 'fv-ie-layer-name'); - name.title = t('Double-click to rename', '双击重命名'); + setTip(name, {name: t('Double-click to rename', '双击重命名')}); name.ondblclick = e => { e.stopPropagation(); renameLayer(doc.layers.find(layer => layer.id === l.id), name); }; row.append(eye, thumb); if (l.mask) { const m = el('canvas', null, 'fv-ie-thumb fv-ie-mask-thumb'); m.width = 48; m.height = 34; drawMaskThumb(m, l); - m.title = t('Layer mask: click to paint on it', '图层蒙版:点击后画笔画在蒙版上'); + setTip(m, {name: t('Layer mask', '图层蒙版'), use: t('Click to paint on it', '点击后画笔画在蒙版上')}); m.setAttribute('role', 'img'); m.setAttribute('aria-label', t('Layer mask', '图层蒙版')); m.onclick = e => { e.stopPropagation(); setActive(l.id); maskTarget = true; renderLayers(); renderOptions(); }; row.append(m); if (l.id === doc.active) (maskTarget ? m : thumb).classList.add('fv-ie-target'); } row.append(name); - if (l.locked) { const lk = el('span', null, 'fv-ie-lock'); lk.innerHTML = SVG(ICONS.lock, 14); lk.title = t('Locked', '已锁定'); row.append(lk); } + if (l.locked) { const lk = el('span', null, 'fv-ie-lock'); lk.innerHTML = SVG(ICONS.lock, 14); setTip(lk, {name: t('Locked', '已锁定')}); lk.setAttribute('role', 'img'); lk.setAttribute('aria-label', t('Locked', '已锁定')); row.append(lk); } else if (l.opacity < 1) row.append(el('span', Math.round(l.opacity * 100) + '%', 'fv-ie-layer-opacity')); row.onclick = () => { setActive(l.id); maskTarget = false; diff --git a/web/image_generation.js b/web/image_generation.js index 8d891e92..68a0ae13 100644 --- a/web/image_generation.js +++ b/web/image_generation.js @@ -105,11 +105,11 @@ export function createImageGenClient(fetchImpl = globalThis.fetch.bind(globalThi return { info, offers, // purpose: what the picture is for (for example 'cast-draft'), passed through as given. - async generate({prompt, width, height, images = [], mask, seed, loras, cast_view, model, remember, purpose}) { + async generate({prompt, width, height, images = [], mask, seed, loras, cast_view, model, remember, purpose, layout}) { const value = await post('generate', {...(model ? {model} : {}), [p.prompt]: prompt, [p.width]: width, [p.height]: height, [p.images]: images, ...(mask ? {[p.mask]: mask} : {}), ...(seed === undefined ? {} : {[p.seed]: seed}), ...(loras === undefined ? {} : {[p.loras]: loras}), ...(cast_view === 'back' ? {cast_view} : {}), ...(remember === true ? {remember} : {}), - ...(typeof purpose === 'string' && purpose ? {purpose} : {})}); + ...(typeof purpose === 'string' && purpose ? {purpose} : {}), ...(Array.isArray(layout) && layout.length ? {layout} : {})}); return {...value, job: value[p.job]}; }, async status(job, model) { @@ -245,6 +245,9 @@ export function imageGenError(code, info, t) { too_many_images: ['There are more reference images than the chosen model supports. Remove some and try again.', '参考图超过所选模型支持的数量。请减少参考图后重试。'], output_unwritable: ['The folder that keeps the pictures cannot be written (freevideo-image in the ComfyUI input folder). Check that it exists, is writable and has no file of the same name, then try again.', '无法写入保存图片的文件夹(ComfyUI 的 input 目录下的 freevideo-image)。请确认该目录存在、可写,且没有同名文件,然后重试。'], + invalid_layout: ['A layout box cannot be used. Draw it larger or change its words, then generate again.', '有一个布局框用不了。请把它画大一些或改一下文字,再生成。'], + too_many_boxes: ['A layout takes at most 8 boxes. Delete one, then generate again.', '布局最多 8 个框。请删掉一个,再生成。'], + layout_too_long: ['The words in the layout are too long. Shorten the lines in the boxes, then generate again.', '布局里的文字太长。请把框里的话写短一些,再生成。'], invalid_media: ['The reference image cannot be read. Choose another image.', '参考图读不出来,请换一张图。'], reload: ['Image generation was interrupted. Try again.', '图片生成中途被打断,请重试。'], engine_error: ['The image engine returned an unreadable answer. Try again; if it keeps failing, report the problem.', '图像引擎返回了无法读取的结果。请重试;仍然失败请提交问题。'], diff --git a/web/image_lora.js b/web/image_lora.js index e06c89d6..6c26cf22 100644 --- a/web/image_lora.js +++ b/web/image_lora.js @@ -5,6 +5,7 @@ import {reconcileLoraTriggers} from './lora_triggers.js'; import {createVerdicts} from './lora_check.js'; import {loraMenu} from './lora_menu.js'; import {userMessage} from './user_message.js'; +import {fieldNote} from './field_note.js'; export const IMAGE_LORA_LIMIT = 8, IMAGE_LORA_STRENGTH = 2; const STORE = 'freevideo_image_loras'; @@ -121,13 +122,14 @@ export function createImageLoras({t, fetchApi, el = domEl, getPrompt = () => '', if (verdicts.peek(row.name)?.usable === false) row.enabled = true; on.checked = row.enabled !== false; check(); changed(); }; + // A strength past ±2 becomes ±2 and the line under the row says so; an empty box goes back to the last strength, said the same way. + const strengthNote = fieldNote(strength, {t, place: () => wrap}); strength.onchange = () => { - const value = Number(strength.value); - if (strength.value === '' || !(Math.abs(value) <= IMAGE_LORA_STRENGTH)) { - strength.setCustomValidity(t(`Enter a value from -${IMAGE_LORA_STRENGTH} to ${IMAGE_LORA_STRENGTH}.`, `请输入 -${IMAGE_LORA_STRENGTH} 到 ${IMAGE_LORA_STRENGTH} 之间的数。`)); - strength.reportValidity(); return; + if (!strengthNote.settle()) { + if (strength.value !== '') return; + const kept = row.strength ?? 1; strength.value = String(kept); strengthNote.say(t(`Back to ${kept}`, `已恢复为 ${kept}`)); return; } - strength.setCustomValidity(''); row.strength = value; changed(); + row.strength = Number(strength.value); changed(); }; remove.onclick = () => { rows.splice(index, 1); render(); changed(); }; trigger.onchange = async () => { diff --git a/web/image_view.css b/web/image_view.css index 4df81b6b..061eda74 100644 --- a/web/image_view.css +++ b/web/image_view.css @@ -743,3 +743,61 @@ dialog.fv-studio.fv-image:not([open]){display:none!important} .fv-iv[data-tall=true] .fv-iv-stage[data-state=blank] .fv-iv-frame{width:min(calc(100cqw - var(--iv-cover,0px)),calc((100cqh - 88px) * var(--iv-grid-ar,1)));aspect-ratio:var(--iv-grid-ar,1)} .fv-iv[data-tall=true] .fv-iv-samples{grid-template-columns:repeat(var(--iv-cols,2),minmax(0,1fr));grid-template-rows:repeat(var(--iv-rows,2),minmax(0,1fr))} .fv-iv[data-tall=true] .fv-iv-compare[data-mode=grid] .fv-iv-compare-panes{grid-template-columns:repeat(var(--iv-cols,2),var(--iv-tw,minmax(0,1fr)));grid-template-rows:repeat(var(--iv-rows,2),var(--iv-th,minmax(0,1fr)));justify-content:center;align-content:start} + +/* MOSS layout: boxes on the next picture's empty frame (image_view_layout.js). The frame is the dark draft in both themes, + so the boxes keep one set of colours; what sits on the page (the line's box, the phone bar, the limit hint) follows it. */ +.fv-iv .fv-iv-layout{position:absolute;inset:0;z-index:2;touch-action:none;cursor:crosshair;--lb-line:rgb(220 226 236 / .55);--lb-on:#fff;--lb-chip:#e8edf5;--lb-chip-ink:#101f30; + --lb-text:#fff;--lb-text-shadow:0 1px 2px rgb(7 10 16 / .8);--lb-handle:#fff;--lb-handle-edge:#101f30} +/* Light theme (Iris 11-19): the frame is light too, the boxes dark on it (the dark theme's colours reversed). */ +:root[data-theme=light] .fv-iv .fv-iv-frame[data-state=draft]{background:#dde2e9} +:root[data-theme=light] .fv-iv .fv-iv-draft{color:var(--fv-fg2);text-shadow:none} +:root[data-theme=light] .fv-iv .fv-iv-draft b{color:var(--fv-fg2)} +:root[data-theme=light] .fv-iv .fv-iv-layout{--lb-line:rgb(20 24 32 / .45);--lb-on:#1b2430;--lb-chip:#1b2430;--lb-chip-ink:#fff;--lb-text:var(--fv-fg);--lb-text-shadow:none;--lb-handle:#fff;--lb-handle-edge:#1b2430} +.fv-iv .fv-iv-layout[hidden]{display:none} +.fv-iv .fv-iv-lbox{position:absolute;box-sizing:border-box;border:1px solid var(--lb-line);border-radius:2px;cursor:move} +.fv-iv .fv-iv-lbox[data-empty=true]{border-style:dashed} +.fv-iv .fv-iv-lbox[data-selected=true]{border:2px solid var(--lb-on);--lb-line:var(--lb-on)} +.fv-iv .fv-iv-lbox[data-selected=true][data-empty=true]{border-style:dashed} +.fv-iv .fv-iv-lbox-ghost{border:1px dashed var(--lb-on);pointer-events:none} +.fv-iv .fv-iv-lbox-ghost[hidden]{display:none} +.fv-iv .fv-iv-lbox-head{position:absolute;left:0;top:0;right:0;display:flex;align-items:center;gap:4px;min-width:0;pointer-events:none} +.fv-iv .fv-iv-lbox-no{flex:none;min-width:20px;height:20px;padding:0 4px;box-sizing:border-box;display:inline-grid;place-items:center;background:var(--lb-chip);color:var(--lb-chip-ink); + font-size:var(--fv-fs-2,13px);font-weight:600;line-height:1;font-variant-numeric:tabular-nums} +.fv-iv .fv-iv-lbox-t{position:relative;flex:none;width:20px;height:20px;padding:0;border:0;display:grid;place-items:center;background:var(--lb-chip);color:var(--lb-chip-ink); + font:600 var(--fv-fs-2,13px)/1 var(--fv-font,inherit);cursor:pointer;pointer-events:auto} +/* The T is small to see and large to press: 24 px on a desk, 44 px by touch. */ +.fv-iv .fv-iv-lbox-t::before{content:"";position:absolute;inset:-2px} +@media(pointer:coarse){.fv-iv .fv-iv-lbox-t::before{inset:-12px}} +.fv-iv .fv-iv-lbox-t[aria-pressed=false]{background:transparent;color:var(--lb-chip);box-shadow:inset 0 0 0 1px var(--lb-line);text-decoration:line-through} +:root[data-theme=light] .fv-iv .fv-iv-lbox-t[aria-pressed=false]{color:#1b2430;box-shadow:inset 0 0 0 1px #1b2430;opacity:.6} +.fv-iv .fv-iv-lbox-line{min-width:0;padding:0 4px;color:var(--lb-text);font-size:var(--fv-fs-2,13px);line-height:20px;white-space:nowrap;overflow:hidden;text-overflow:ellipsis; + text-shadow:var(--lb-text-shadow)} +.fv-iv .fv-iv-lbox-h{position:absolute;width:9px;height:9px;margin:-5px 0 0 -5px;background:var(--lb-handle);border:1px solid var(--lb-handle-edge);box-sizing:border-box} +.fv-iv .fv-iv-lbox-h::before{content:"";position:absolute;inset:-6px} +@media(pointer:coarse){.fv-iv .fv-iv-lbox-h{width:14px;height:14px;margin:-7px 0 0 -7px}.fv-iv .fv-iv-lbox-h::before{inset:-15px}} +.fv-iv .fv-iv-lbox-h[data-side=nw]{left:0;top:0;cursor:nwse-resize}.fv-iv .fv-iv-lbox-h[data-side=n]{left:50%;top:0;cursor:ns-resize} +.fv-iv .fv-iv-lbox-h[data-side=ne]{left:100%;top:0;cursor:nesw-resize}.fv-iv .fv-iv-lbox-h[data-side=e]{left:100%;top:50%;cursor:ew-resize} +.fv-iv .fv-iv-lbox-h[data-side=se]{left:100%;top:100%;cursor:nwse-resize}.fv-iv .fv-iv-lbox-h[data-side=s]{left:50%;top:100%;cursor:ns-resize} +.fv-iv .fv-iv-lbox-h[data-side=sw]{left:0;top:100%;cursor:nesw-resize}.fv-iv .fv-iv-lbox-h[data-side=w]{left:0;top:50%;cursor:ew-resize} +.fv-iv .fv-iv-lbox-x{position:absolute;right:2px;top:2px;width:20px;height:20px;padding:0;border:0;display:grid;place-items:center;background:var(--lb-chip);color:var(--lb-chip-ink); + font:600 15px/1 var(--fv-font,inherit);cursor:pointer} +.fv-iv .fv-iv-lbox-x::before{content:"";position:absolute;inset:-2px} +@media(pointer:coarse){.fv-iv .fv-iv-lbox-x::before{inset:-12px}} +.fv-iv .fv-iv-lbox-input{position:absolute;z-index:3;box-sizing:border-box;width:min(320px,90%);height:32px;margin:4px 0;padding:0 10px;border:1px solid var(--fv-line,rgb(255 255 255 / .16)); + border-radius:var(--fv-r-sm,8px);background:var(--fv-shell-bg);color:var(--fv-fg);font:inherit;font-size:var(--fv-fs-2,13px);outline:none;box-shadow:0 6px 20px rgb(0 0 0 / .35)} +.fv-iv .fv-iv-lbox-input[data-side=above]{margin:0 0 4px} +.fv-iv .fv-iv-lbox-input:focus{border-color:var(--fv-accent,#4c8dff)} +.fv-iv .fv-iv-lbox-input[hidden]{display:none} +/* Phone: the line is written in an opaque bar at the foot, which rises with the keyboard. */ +.fv-iv-lbar{position:fixed;left:0;right:0;bottom:var(--fv-kb,0px);z-index:2147483000;display:flex;align-items:center;gap:8px;padding:8px 12px calc(8px + env(safe-area-inset-bottom)); + background:var(--fv-shell-bg,#0b121c);border-top:1px solid var(--fv-line,rgb(255 255 255 / .12));color:var(--fv-fg,#fff)} +.fv-iv-lbar[hidden]{display:none} +.fv-iv-lbar .fv-iv-lbox-no{flex:none;min-width:24px;height:24px;display:inline-grid;place-items:center;background:#e8edf5;color:#101f30;font-weight:600} +.fv-iv-lbar .fv-iv-lbox-input{position:static;flex:1;width:auto;height:44px;margin:0;box-shadow:none;padding:0 12px;border:1px solid var(--fv-line,rgb(255 255 255 / .16)); + border-radius:var(--fv-r-sm,8px);background:var(--fv-ctl-bg,transparent);color:inherit;font:inherit;font-size:16px} +.fv-iv-lbar-done{flex:none;min-width:64px;height:44px;border:0;border-radius:var(--fv-r-sm,8px);background:var(--fv-accent,#4c8dff);color:#fff;font:inherit;font-weight:600} +.fv-iv-lhint{position:fixed;z-index:2147483000;padding:4px 8px;border-radius:6px;background:var(--fv-shell-bg,#0b121c);color:var(--fv-fg,#fff);font-size:var(--fv-fs-1,12px); + box-shadow:0 4px 14px rgb(0 0 0 / .3);pointer-events:none;animation:fv-iv-lhint 1.6s ease forwards} +@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)} diff --git a/web/image_view.js b/web/image_view.js index 4221e0dd..01222cc7 100644 --- a/web/image_view.js +++ b/web/image_view.js @@ -22,6 +22,7 @@ import { openReferenceMenu, removeSavedImages } from './image_library.js'; import { BLANK_CANVAS_AREAS, createImageGenClient, fittedNote, imageGenError, imageRemainingText, imageReportBar, renderImageFailure } from './image_generation.js'; import { duration } from './generation_progress.js'; import { randomSeed } from './studio_queue.js'; +import { createLayout } from './image_view_layout.js'; import { createPreviewScene } from './preview_scene.js?v=20261115-still'; import { jobs, ACTIVE, IMAGE_BUSY } from './task_store.js'; import { confirmStop, startJobSources } from './task_float.js'; @@ -39,6 +40,7 @@ import { preloadMode } from './preload_setting.js'; 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'; export { IMAGE_MODELS, RATIOS }; for (const name of ['./image_view.css']) { @@ -89,10 +91,10 @@ export function createFakeImageClient({delay = 600, ready = {'minimax-h3-image': info: async () => { for (const [id, at] of loading) if (Date.now() - at > bytes / rate) { state[id] = true; loading.delete(id); } return {installed: true, ready: true, max_images: 16, sizes, models: models()}; }, packInstall: async id => { failed.delete(id); if (paused.delete(id)) loading.set(id, Date.now() - bytes / rate * .2); else loading.set(id, Date.now()); return {installed: true, sizes, models: models()}; }, packCancel: async id => { loading.delete(id); return {installed: true, sizes, models: models()}; }, - async generate({prompt, width, height, seed, model, images = []}) { + async generate({prompt, width, height, seed, model, images = [], layout}) { if (fail) throw Object.assign(new Error(fail), {code: fail}); if (images.length > (references[model] ?? 0)) return {error: 'too_many_images'}; - const job = 'fake-' + ++count; jobs.set(job, {at: Date.now(), prompt, width, height, seed, model}); (this.requests ||= []).push({prompt, width, height, seed, model, images}); return {job}; + const job = 'fake-' + ++count; jobs.set(job, {at: Date.now(), prompt, width, height, seed, model}); (this.requests ||= []).push({prompt, width, height, seed, model, images, ...(layout ? {layout} : {})}); return {job}; }, async status(job) { const row = jobs.get(job); if (!row) throw Object.assign(new Error('unknown_job'), {code: 'unknown_job'}); @@ -207,6 +209,8 @@ export function openImageView(node, {studio = null, client: given = null, poll = if (info?.models && !offers(model)) model = IMAGE_MODELS.find(offers) || model; let ratio = sizes.ratio || '1:1', area = sizes[model.id] || RANGES[model.id].presets.standard, locked = sizes.locked !== false, tier = 'standard'; const promptOf = {}; + // The boxes a MOSS picture was made with, while this page is open (as its prompt is). + const layoutOf = {}; // A picture's words: from this page's memory (made while it is open) or the engine's record of it; never the browser's store. const promptFor = file => promptOf[file] || sessionPrompts.get(file) || rows.find(r => r.file === file)?.prompt || ''; // running: the job this page shows ({id} once the store has it); the job itself belongs to the store and outlives the page. @@ -287,11 +291,13 @@ export function openImageView(node, {studio = null, client: given = null, poll = }, restore: text => text.replace(//g, (_, n) => mentionText(n)).replace(//g, (_, n) => subject(Number(n)))}); let enhancerReady = false; - const enhancerOff = () => false; + // A MOSS layout is sent as boxes the engine writes into the prompt: a rewrite would rewrite them as prose and drop + // them (the official template keeps its rewrite off with boxes), so with boxes the words go as written. + const enhancerOff = () => layoutActive(); enhancer.element.classList.add('fv-image-enhance'); // Expand: the same quiet reading and editing panel as the studio and the editing view; it writes back live. const expand = createExpandButton({t, textarea: prompt, onGenerate: () => go.click(), - canGenerate: () => !running && modelState(info, model.id).state === 'ready' && (!!prompt.value.trim() || references.length > 0), onDraft: () => render()}); + canGenerate: () => !running && modelState(info, model.id).state === 'ready' && hasWords(), onDraft: () => render()}); enhancer.model.read().then(value => { enhancerReady = value?.ready === true; render(); fitSoon(); }).catch(() => {}); const promptBar = el('div', 'fv-iv-prompt-bar'); const promptCount = el('span', 'fv-iv-prompt-count'); @@ -302,9 +308,12 @@ export function openImageView(node, {studio = null, client: given = null, poll = const sketchAdd = button('fv-iv-text-btn fv-iv-sketch-tool', {iconName: 'edit', label: t('Sketch', '画草图'), name: t('Draw a sketch', '画草图'), use: t('Draw the layout on a blank canvas of this frame; it becomes Image 1', '在当前画幅的空白画布上画出构图,作为图 1')}); sketchAdd.addEventListener('click', () => void drawSketch()); + // MOSS layout: in the place of References and Sketch (MOSS takes neither), boxes drawn on the next picture's frame. + const layoutAdd = button('fv-iv-text-btn fv-iv-layout-tool', {iconName: 'layout', label: t('Layout', '布局')}); const layoutCount = el('span', 'fv-iv-ref-count'); layoutAdd.append(layoutCount); + 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, enhancer.chip, el('span', 'fv-iv-grow'), promptCount, expand.element); + promptBar.append(refAdd, sketchAdd, layoutAdd, enhancer.chip, el('span', 'fv-iv-grow'), promptCount, 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. @@ -344,6 +353,9 @@ export function openImageView(node, {studio = null, client: given = null, poll = dice.addEventListener('click', () => { seedInput.value = String(randomSeed()); render(); }); seedInput.addEventListener('input', () => render()); const seedField = el('label', 'fv-image-seed fv-iv-field fv-iv-field-wide'); seedField.append(el('span', 'fv-iv-field-key', t('Seed', '种子')), seedInput, dice); + // A seed past its range becomes its end (or a whole number), and the line under the field says so. + const seedNote = fieldNote(seedInput, {t, place: () => seedField}); + seedInput.addEventListener('change', () => { if (seedInput.value !== '') seedNote.settle(); }); // LoRA: a button whose panel opens beside it; it answers for the model that takes LoRA files. const loraRow = imageViewLora({host: dialog, fetchApi: (path, options) => api.fetchApi(path, options), modelName: () => IMAGE_MODELS.find(m => m.id === LORA_MODEL)?.name || 'Qwen-Image 2.1', onChange: () => render()}); @@ -410,6 +422,22 @@ export function openImageView(node, {studio = null, client: given = null, poll = const failHost = el('div', 'fv-image-fail fv-iv-fail fv-glass fv-g3'); failHost.setAttribute('role', 'alert'); const draftNote = el('div', 'fv-iv-draft'), draftSize = el('b'), draftHint = el('span'); draftNote.append(draftSize, draftHint); draftNote.hidden = true; pic.append(sceneHost, picture, stepFrame, block, draftNote, meter); + // MOSS layout: the boxes live on the empty frame of the next picture (the draft), whose shape is the one made. + const MOSS = 'moss-image-sft'; + const isMoss = () => model.id === MOSS; + let layoutOn = false; + const layout = createLayout({host: pic, layer: dialog, onChange: () => render()}); + if (keptDraft?.layout?.length) layout.set(keptDraft.layout); + // Boxes with words go with a MOSS picture; with another model they stay on the page, unseen and unsent. + function layoutActive() { return isMoss() && layout.filled() > 0; } + function hasWords() { return !!prompt.value.trim() || references.length > 0 || layoutActive(); } + function toggleLayout(on = !layoutOn) { + if (!isMoss()) return; + layoutOn = !!on; + if (layoutOn) { if (running && !browsing) leaveRun(); startDraft(); } + else if (shownFile) { draft = false; draftPreview = null; } + render(); + } frame.append(pic, grid, failHost); // The caption row (facts, Edit, reference, star, download, more) is where the hand goes after a picture: the floating window keeps off it. const cap = el('div', 'fv-iv-cap fv-image-actions sgf-avoid'); @@ -429,7 +457,14 @@ export function openImageView(node, {studio = null, client: given = null, poll = 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 usePromptItem = menuItem('prompt', t('Use prompt', '使用提示词'), t('Put its prompt back in the box', '把它的提示词填回描述框'), () => { const text = promptFor(shownFile); if (text) { prompt.value = text; prompt.dispatchEvent(new Event('input', {bubbles: true})); promptGroup.open(true); } }); + 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) { + const text = promptFor(file), boxes = layoutOf[file]; + if (!text && !boxes) return; + prompt.value = text; prompt.dispatchEvent(new Event('input', {bubbles: true})); promptGroup.open(true); + if (boxes) { const moss = IMAGE_MODELS.find(m => m.id === MOSS); if (moss && model.id !== MOSS) chooseModel(moss); layout.set(boxes); } + } more.append(menuItem('folder', t('Open folder', '打开文件夹'), t('Show the pictures on this computer', '在电脑上打开保存图片的文件夹'), () => void openFolder()), menuItem('copy', t('Copy prompt', '复制提示词'), t('Copy the words this picture was made from', '复制这张图的提示词'), copyPrompt), usePromptItem, menuItem('trash', t('Delete', '删除'), t('Move to recently deleted; can be undone', '移到最近删除,可以撤销'), () => deleteFiles([shownFile]), 'fv-iv-danger')); @@ -455,6 +490,8 @@ export function openImageView(node, {studio = null, client: given = null, poll = if (w) parts.push(row(t('Size', '尺寸'), `${w} × ${h} · ${megapixels(w * h)} MP`)); if (m.seconds) parts.push(row(t('Time', '用时'), t(`${m.seconds} s`, `${m.seconds} 秒`))); if (m.seed) parts.push(row(t('Seed', '种子'), String(m.seed))); + const drawn = layoutOf[shownFile]?.length; + if (drawn) parts.push(row(t('Layout', '布局'), t(`${drawn} ${drawn === 1 ? 'box' : 'boxes'}`, `${drawn} 个框`))); // Where it came from (an edit of another work): its thumbnail and name, opening it on the stage. if (m.source) { const name = String(m.source).slice(String(m.source).lastIndexOf('/') + 1), there = rows.find(r => r.file === m.source || r.name === name); @@ -466,13 +503,13 @@ export function openImageView(node, {studio = null, client: given = null, poll = line.append(el('span', 'fv-iv-info-k', t('Source', '来源')), go); parts.push(line); } if (!text) parts.push(el('p', 'fv-iv-info-none', t('Prompts are not kept in this browser; one shows while the page that made the picture is open.', '提示词不保存在浏览器里,只在生成它的页面打开期间显示。'))); - if (text) { + if (text || drawn) { const acts = el('div', 'fv-iv-info-acts'); const copy = button('fv-iv-text-btn', {iconName: 'copy', label: t('Copy prompt', '复制提示词'), name: t('Copy prompt', '复制提示词'), use: t('Copy the words this picture was made from', '复制这张图的提示词')}); copy.addEventListener('click', copyPrompt); const reuse = button('fv-iv-text-btn', {iconName: 'prompt', label: t('Use prompt', '使用提示词'), name: t('Use prompt', '使用提示词'), use: t('Put its prompt back in the box', '把它的提示词填回描述框')}); - reuse.addEventListener('click', () => { prompt.value = text; prompt.dispatchEvent(new Event('input', {bubbles: true})); promptGroup.open(true); if (narrowQuery.matches || tallQuery.matches) setPanel('left', true); }); - acts.append(copy, reuse); parts.push(acts); + reuse.addEventListener('click', () => { usePrompt(shownFile); if (narrowQuery.matches || tallQuery.matches) setPanel('left', true); }); + acts.append(...(text ? [copy] : []), reuse); parts.push(acts); } if (!shownFile) { const e = el('div', 'fv-iv-empty fv-iv-empty-small'); e.append(icon('info'), el('span', '', t('Pick a picture to see its facts', '选一张图片查看信息'))); parts.splice(0, parts.length, e); } infoPop.replaceChildren(...parts); @@ -1086,7 +1123,7 @@ export function openImageView(node, {studio = null, client: given = null, poll = // The size is said once, on its own chip; Generate says only how long it may take. goLabel.textContent = t('Generate', '生成'); goSub.textContent = est ? t(`about ${est} s`, `约 ${est} 秒`) : ''; tip(go, t('Generate', '生成'), t(`Makes a ${sizeText(now)} picture`, `生成一张 ${sizeText(now)} 的图片`), `${mod}+Enter`); - if (!prompt.value.trim() && !references.length) go.dataset.fvTipWhy = t('Describe the picture first', '先写一句描述'); + if (!hasWords()) go.dataset.fvTipWhy = t('Describe the picture first', '先写一句描述'); } // With no time (or size) to say beside it, the word sits alone in the middle of the key. go.dataset.eta = String(!!goSub.textContent); @@ -1118,6 +1155,11 @@ export function openImageView(node, {studio = null, client: given = null, poll = cards.paint(info, model.id, pendingGenerate); loraRow.paint(model.id); drawReferences(); + // MOSS takes neither references nor a sketch: Layout takes their place in the row. + const moss = isMoss(); refAdd.hidden = sketchAdd.hidden = moss; layoutAdd.hidden = !moss; + if (!moss) layoutOn = false; + layoutCount.textContent = layout.count() ? String(layout.count()) : ''; + layoutAdd.setAttribute('aria-pressed', String(layoutOn)); const tooMany = over() > 0, busy = !!running; // No words inside the empty box (the group says what it is for), except beside a sketch: what it shows is known only // from the words (a stick figure is a person when the words say so), so the empty box asks for them. @@ -1168,7 +1210,10 @@ export function openImageView(node, {studio = null, client: given = null, poll = frame.dataset.state = stage.dataset.state = state; paintCover(); frame.dataset.loading = String(state === 'waiting' || (state === 'done' && picture.dataset.loaded !== 'true')); picture.hidden = state !== 'done'; stepFrame.hidden = state !== 'running' || !stepURL; block.hidden = state !== 'running'; failHost.hidden = state !== 'failed'; grid.hidden = state !== 'blank'; - sceneHost.hidden = state !== 'running'; draftNote.hidden = state !== 'draft'; + if (state !== 'draft') layoutOn = false; + layout.show(state === 'draft' && layoutOn && isMoss()); stage.dataset.layout = String(layout.shown); + // With boxes on the frame its size and estimate would be crossed by their lines (Iris 11-19): they show without. + sceneHost.hidden = state !== 'running'; draftNote.hidden = state !== 'draft' || (layout.shown && layout.count() > 0); // While running the caption keeps its room unseen, so a step picture and the finished one sit in the same place. // The caption row also waits for the picture's shape: it takes the frame's width, so it shows at its final one. // A work whose file is gone keeps its row (without the actions that need the picture), so it can still be deleted here. @@ -1216,7 +1261,7 @@ export function openImageView(node, {studio = null, client: given = null, poll = for (const b of [editThis, asReference]) { if (full) b.dataset.fvTipWhy = why; else delete b.dataset.fvTipWhy; } const fav = meta.isFav(shownFile); favBtn.setAttribute('aria-pressed', String(fav)); tip(favBtn, fav ? t('Remove star', '取消收藏') : t('Star', '收藏'), fav ? t('Take it out of favourites', '移出收藏') : t('Keep it in favourites', '加入收藏'), 'F'); - const known = promptFor(shownFile); usePromptItem.hidden = !known; copyInline.hidden = useInline.hidden = !known; + const known = promptFor(shownFile) || layoutOf[shownFile]; usePromptItem.hidden = useInline.hidden = !known; copyInline.hidden = !promptFor(shownFile); // The line under the picture is about the picture shown: the model that made it, its size, its shape and the time it took. const width = picture.naturalWidth && picture.dataset.file === shownFile ? picture.naturalWidth : shown?.width || 0, height = picture.naturalWidth && picture.dataset.file === shownFile ? picture.naturalHeight : shown?.height || 0; const madeBy = IMAGE_MODELS.find(m => m.id === (shown?.model || rows.find(r => r.file === shownFile)?.model))?.name; @@ -1265,7 +1310,7 @@ export function openImageView(node, {studio = null, client: given = null, poll = tip(b, t('Generating', '正在生成'), t('Show its progress', '查看进度')); b.addEventListener('click', () => returnToRun()); return b; })() : null; railThumbs.replaceChildren(...(runThumb ? [runThumb] : []), ...live.slice(0, runThumb ? 5 : 6).map(r => { const b = el('button', 'fv-iv-rail-thumb'); b.type = 'button'; const i = el('img'); i.alt = ''; i.draggable = false; i.src = thumbURL(r.file); b.append(i); b.classList.toggle('fv-iv-current', r.file === shownFile); tip(b, t('Show', '显示'), t('Put it on the stage', '在中间显示')); b.addEventListener('click', () => showFile(r.file)); return b; })); } - function showFile(file) { if (!file) return; if (running && !browsing) leaveRun(); draft = false; draftPreview = null; shownFile = file; if (historyLoaded) queueMicrotask(rememberView); started = 0; if (!running) failure = null; compare = null; render(); drawWorks(); } + function showFile(file) { if (!file) return; if (running && !browsing) leaveRun(); layoutOn = false; draft = false; draftPreview = null; shownFile = file; if (historyLoaded) queueMicrotask(rememberView); started = 0; if (!running) failure = null; compare = null; render(); drawWorks(); } // ← → step through the works shown (not while comparing); the works column follows without jumping. function step(by) { if (compare) return; const list = visible(), at = list.findIndex(r => r.file === shownFile); const target = list[at + by]; if (!target) return; @@ -1332,8 +1377,12 @@ export function openImageView(node, {studio = null, client: given = null, poll = // Uploads and the prompt step stay with the page; once the worker has the job, the store follows it. async function generate() { if (over()) { blockOver(); return; } - if (!seedInput.checkValidity()) { advanced.open = true; seedInput.reportValidity(); return; } + if (seedInput.value !== '' && !seedNote.settle()) { advanced.open = true; return; } + if (!seedInput.checkValidity()) { advanced.open = true; seedNote.say(t('Enter a whole number, or leave it empty', '请输入整数,或留空')); seedInput.focus(); return; } const seed = seedInput.value === '' ? undefined : Number(seedInput.value); + // The boxes as they are now (MOSS only); the frame gives way to the picture being made. + const boxes = layoutActive() ? layout.request() : [], drawn = boxes.length ? layout.snapshot().filter(item => item.line.trim()) : null; + layoutOn = false; say(''); note.dataset.kind = ''; failure = null; const mine = running = {cancelled: false}, withImages = references.length > 0, sent = size(), tierNow = tier; render(); drawWorks(); progressLine.textContent = progressSub.textContent = ''; runReport.replaceChildren(); runReport.dataset.id = ''; doneReport.replaceChildren(); lastReport = null; level.hidden = false; level.dataset.counted = 'false'; level.style.setProperty('--fv-progress', '0'); @@ -1349,8 +1398,10 @@ export function openImageView(node, {studio = null, client: given = null, poll = // 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 { - ({id} = await jobs.submit('image', {prompt: engineText(seed ?? Math.floor(Math.random() * 1e9)), ...sent, model: model.id, remember: true, images: names, ...(seed === undefined ? {} : {seed}), ...(loras.length ? {loras} : {})}, - {view: 'image', client, meta: {text: prompt.value, withImages, tier: tierNow, width: sent.width, height: sent.height}})); + // With boxes and no description, the boxes' lines describe the whole picture. + const words = boxes.length && !prompt.value.trim() ? layout.caption() : engineText(seed ?? Math.floor(Math.random() * 1e9)); + ({id} = await jobs.submit('image', {prompt: words, ...sent, model: model.id, remember: true, images: names, ...(seed === undefined ? {} : {seed}), ...(loras.length ? {loras} : {}), ...(boxes.length ? {layout: boxes} : {})}, + {view: 'image', client, meta: {text: prompt.value, withImages, tier: tierNow, width: sent.width, height: sent.height, ...(drawn ? {layout: drawn} : {})}})); break; } catch (error) { if (error.code !== 'busy') throw error; @@ -1409,7 +1460,7 @@ export function openImageView(node, {studio = null, client: given = null, poll = unwatch?.(); unwatch = null; running = null; level.hidden = true; clearStep(); delete canvas.dataset.fvTaskId; jobs.markSeen(row.id); if (row.status === 'done' && row.result?.file) { - shownFile = row.result.file; promptOf[shownFile] = row.meta?.text ?? row.prompt ?? ''; + shownFile = row.result.file; promptOf[shownFile] = row.meta?.text ?? row.prompt ?? ''; if (row.meta?.layout) layoutOf[shownFile] = row.meta.layout; started = Math.max(1, Math.round(((row.finished_at || Date.now()) - (row.started_at || row.created_at || Date.now())) / 1000)); const reportId = row.meta?.report_id; lastReport = reportId ? {file: shownFile, id: reportId} : null; failure = null; jobs.dismiss(row.id); @@ -1471,13 +1522,13 @@ export function openImageView(node, {studio = null, client: given = null, poll = // The model on show is not one this computer offers (a remembered H3 Image on a Mac): the press moves to the one it offers. else if (!offers(model) && IMAGE_MODELS.some(offers)) { chooseModel(IMAGE_MODELS.find(offers)); go.onclick(); } // A model being installed: Generate says whether the picture follows the install. - else if (loading()) { pendingGenerate = !pendingGenerate && (!!prompt.value.trim() || references.length > 0); if (!prompt.value.trim() && !references.length) { promptGroup.open(true); prompt.focus(); } render(); } + else if (loading()) { pendingGenerate = !pendingGenerate && hasWords(); if (!hasWords()) { promptGroup.open(true); prompt.focus(); } render(); } // A model not installed: installs it, then generates. - else if (missing() || modelState(info, model.id).state === 'failed') { pendingGenerate = !!prompt.value.trim() || references.length > 0; void install(); } - else if (!prompt.value.trim() && !references.length) { promptGroup.open(true); prompt.focus(); } + else if (missing() || modelState(info, model.id).state === 'failed') { pendingGenerate = hasWords(); void install(); } + else if (!hasWords()) { promptGroup.open(true); prompt.focus(); } else void generate(); }; - go.addEventListener('click', () => { if (drawer === 'left' && go.dataset.state === 'ready' && (prompt.value.trim() || references.length)) { drawer = ''; paintPanels(); } }, {capture: true}); + go.addEventListener('click', () => { if (drawer === 'left' && go.dataset.state === 'ready' && hasWords()) { drawer = ''; paintPanels(); } }, {capture: true}); prompt.addEventListener('input', () => { growPrompt(); render(); }); // Getting the model ready before Generate is pressed (nothing of it shows): being here a few seconds loads the model // where the card has free room for it (eager loading; the engine reads the files ahead where it would take the @@ -1585,7 +1636,7 @@ export function openImageView(node, {studio = null, client: given = null, poll = // Keys: the page's own, never while typing. const onKeys = event => { const typing = event.target.closest?.('input,textarea,[contenteditable=true]'); - if (event.key === 'Enter' && (event.ctrlKey || event.metaKey)) { if (!running && (prompt.value.trim() || references.length)) { event.preventDefault(); go.click(); } return; } + if (event.key === 'Enter' && (event.ctrlKey || event.metaKey)) { if (!running && hasWords()) { event.preventDefault(); go.click(); } return; } if ((event.ctrlKey || event.metaKey) && event.key.toLowerCase() === 'f' && !typing) { event.preventDefault(); setPanel('right', true); setRightTab('works'); works.focusSearch(); return; } if ((event.ctrlKey || event.metaKey) && event.key.toLowerCase() === 'z' && !typing && undoNote) { event.preventDefault(); restoreWorks(undoNote.files); undoNote = null; drawWorks(); render(); return; } if ((event.ctrlKey || event.metaKey) && event.key.toLowerCase() === 'a' && selecting && !typing) { event.preventDefault(); visible().forEach(r => picked.add(r.file)); drawWorks(); render(); return; } @@ -1607,6 +1658,7 @@ export function openImageView(node, {studio = null, client: given = null, poll = // Escape steps back one layer at a time; the view itself closes last. dialog.addEventListener('cancel', event => { event.preventDefault(); + if (layout.tookEscape() || layout.escape()) return; if (!more.hidden) more.hidden = true; else if (!keysPop.hidden) { keysPop.hidden = true; keysBtn.setAttribute('aria-pressed', 'false'); } else if (drawer) { drawer = ''; paintPanels(); } @@ -1627,9 +1679,10 @@ export function openImageView(node, {studio = null, client: given = null, poll = window.removeEventListener('freevideo-works-removed', onWorksRemoved); window.removeEventListener('freevideo-works-restored', onWorksRestored); window.removeEventListener('pagehide', onPageHide); window.removeEventListener('freevideo-works-added', onWorksAdded); window.removeEventListener('freevideo-works-removed', onWorksGone); // Kept for the next time the view opens on this page (the pictures as files; their addresses are made again). - keptDraft = {prompt: prompt.value, caret: prompt.selectionStart ?? prompt.value.length, + keptDraft = {prompt: prompt.value, caret: prompt.selectionStart ?? prompt.value.length, layout: layout.snapshot(), references: references.map(({url, original, ...rest}) => ({...rest, ...(original ? {original: {file: original.file, width: original.width, height: original.height}} : {})}))}; references.forEach(r => { if (r.original) URL.revokeObjectURL(r.original.url); }); + layout.dispose(); // Deleted pictures waiting for their undo window go now: nothing is left half-deleted behind a closed page. void trash.flush(); trash.dispose(); loraRow.dispose(); // ── run: tasks owns this block (job store) ── diff --git a/web/image_view_layout.js b/web/image_view_layout.js new file mode 100644 index 00000000..65226571 --- /dev/null +++ b/web/image_view_layout.js @@ -0,0 +1,315 @@ +// MOSS-Image layout: boxes drawn on the empty frame of the next picture, each with one line saying what goes there. +// Boxes are kept as fractions of the frame ([left, top, right, bottom], 0..1, from the top-left), so a change of shape +// moves them with the frame; the engine writes them in pixels of the size actually made (image_gen/moss_layout.py). +// Words in quotes (“…”, 「…」 or "…") are written into the picture: such a box shows a T, which can be switched off when +// the quotes are only emphasis. A box with no words is drawn dashed and is not sent. +import { el, t, tip } from './image_view_ui.js'; +import { listenDialogKey } from './dialog_keys.js'; + +export const LAYOUT_LIMIT = 8; +export const LINE_LIMIT = 400; +export const TEXT_LIMIT = 200; +const SMALLEST = .04; +const QUOTED = /“([^”]*)”|「([^」]*)」|"([^"]*)"/g; + +// The quoted parts of a line, in order (empty quotes say nothing and are left out). +export function quotedParts(line) { + const parts = []; + for (const found of String(line || '').matchAll(QUOTED)) { + const words = (found[1] ?? found[2] ?? found[3] ?? '').trim(); + if (words) parts.push(words); + } + return parts; +} + +const round = value => Math.round(value * 1e4) / 1e4; + +// What the engine gets for one box, or null for a box with no words. With quotes (and the T on) it is a text box: the +// quoted words, several parts on lines of their own, and the rest of the line as its description. +export function boxRequest(item) { + const line = String(item?.line || '').trim(); + if (!line) return null; + const box = item.box.map(round); + const parts = quotedParts(line); + if (parts.length && !item.textOff) { + const caption = line.replace(QUOTED, ' ').replace(/\s+/g, ' ').replace(/^[\s,,、::;;]+|[\s,,、::;;]+$/g, '').trim(); + return {label: 'text', text: parts.join('\n').slice(0, TEXT_LIMIT), ...(caption ? {caption} : {}), box}; + } + return {caption: line.slice(0, LINE_LIMIT), box}; +} + +export function layoutRequest(items) { return (items || []).map(boxRequest).filter(Boolean); } + +// The whole picture's words when the description is left empty: the boxes' lines in their order, within the 2000 +// characters a description may have (eight full lines would pass it). +export const CAPTION_LIMIT = 2000; +export function layoutCaption(items) { + return (items || []).map(item => String(item.line || '').trim()).filter(Boolean).join('; ').slice(0, CAPTION_LIMIT).trim(); +} + +const clamp = (value, low, high) => Math.min(high, Math.max(low, value)); +const copy = items => items.map(item => ({...item, box: [...item.box]})); + +// The box editor over the frame. ``host`` is the frame (the overlay fills it); onChange runs after every change. +export function createLayout({host, layer = document.body, onChange = () => {}, limit = LAYOUT_LIMIT, narrow = () => matchMedia('(max-width: 719px)').matches, + coarse = () => matchMedia('(pointer: coarse)').matches}) { + let items = [], selected = -1, editing = -1, shown = false, nextId = 1; + const undo = [], redo = []; + // The frame takes the keys while a box is chosen (Delete, arrows, undo): focus stays on it, inside the view, so the + // view's own keys (Delete deletes the shown picture) never see them. + const overlay = el('div', 'fv-iv-layout'); overlay.hidden = true; overlay.tabIndex = -1; + const ghost = el('div', 'fv-iv-lbox fv-iv-lbox-ghost'); ghost.hidden = true; + const field = el('input', 'fv-iv-lbox-input'); field.type = 'text'; field.maxLength = LINE_LIMIT; field.placeholder = t('What goes here', '放什么'); + field.setAttribute('aria-label', t('What goes here', '放什么')); field.hidden = true; + // On a phone the line is written in a bar at the foot, opaque, with the box's number at its start. + const bar = el('div', 'fv-iv-lbar'), barNo = el('span', 'fv-iv-lbox-no'), done = el('button', 'fv-iv-lbar-done', t('Done', '完成')); + done.type = 'button'; bar.append(barNo, done); bar.hidden = true; + overlay.append(ghost, field); + host.append(overlay); + // In the view's own layer (a modal dialog shows nothing of the page body above it). + layer.append(bar); + // The bar rises with the on-screen keyboard. + const viewport = window.visualViewport; + const lift = () => { if (viewport) bar.style.setProperty('--fv-kb', `${Math.max(0, window.innerHeight - viewport.height - viewport.offsetTop)}px`); keepInView(); }; + viewport?.addEventListener('resize', lift); viewport?.addEventListener('scroll', lift); + window.addEventListener('resize', lift); + // The box being written stays in sight above the bar (8 px clear, Iris 11-19): the page under it scrolls by what the + // bar covers; a box already clear is left where it is. + function keepInView() { + if (editing < 0 || bar.hidden) return; + requestAnimationFrame(() => { + const node = overlay.querySelector(`.fv-iv-lbox[data-index="${editing}"]`); + if (!node || bar.hidden) return; + const over = node.getBoundingClientRect().bottom - (bar.getBoundingClientRect().top - 8); + if (over <= 0) return; + let scroller = overlay.parentElement; + while (scroller && !(scroller.scrollHeight > scroller.clientHeight + 1 && /auto|scroll/.test(getComputedStyle(scroller).overflowY))) scroller = scroller.parentElement; + (scroller || document.scrollingElement)?.scrollBy({top: over}); + }); + } + let hint = null; + // An Escape the boxes used (closing a line, letting go of a box): the dialog's own cancel still follows it, and the + // view asks here so that it does not also step back a layer. + let tookAt = -Infinity; + const took = () => { tookAt = performance.now(); }; + + const changed = () => { paint(); onChange(); }; + const remember = () => { undo.push(copy(items)); if (undo.length > 100) undo.shift(); redo.length = 0; }; + const frame = () => overlay.getBoundingClientRect(); + const at = event => { const r = frame(); return [clamp((event.clientX - r.left) / r.width, 0, 1), clamp((event.clientY - r.top) / r.height, 0, 1)]; }; + + function say(event) { + // Once, beside the pointer, gone by itself: never a dialog, never left on the page. + hint?.remove(); + hint = el('div', 'fv-iv-lhint', t(`Up to ${limit} boxes`, `最多 ${limit} 个框`)); hint.setAttribute('role', 'status'); + hint.style.left = `${event.clientX + 12}px`; hint.style.top = `${event.clientY + 12}px`; + layer.append(hint); + const mine = hint; setTimeout(() => { mine.remove(); if (hint === mine) hint = null; }, 1600); + } + + let before = null; + function select(index, edit = false) { + if (editing >= 0 && editing !== index) commit(); + selected = index; editing = edit && index >= 0 ? index : -1; + // The line changes as it is typed; undo goes back to how it was when the box was opened. + before = editing >= 0 ? {items: copy(items), line: items[editing].line} : null; + paint(); + if (editing >= 0) { field.value = items[editing].line; queueMicrotask(() => { field.focus(); field.setSelectionRange(field.value.length, field.value.length); }); } + } + function commit() { + if (editing < 0 || !items[editing]) { editing = -1; return; } + const line = field.value.slice(0, LINE_LIMIT), item = items[editing]; + // A T switched off stays off while the line still has quotes; quotes taken out and put back bring it back on. + item.textOff = item.textOff && quotedParts(line).length > 0; + item.line = line; + if (before && before.line !== line) { undo.push(before.items); redo.length = 0; } + before = null; editing = -1; + } + function remove(index) { + if (index < 0 || !items[index]) return; + remember(); if (editing === index) editing = -1; + items.splice(index, 1); selected = -1; editing = -1; changed(); overlay.focus({preventScroll: true}); + } + function step(direction) { + const list = direction < 0 ? undo : redo, other = direction < 0 ? redo : undo; + if (!list.length) return; + other.push(copy(items)); items = list.pop(); selected = editing = -1; changed(); + } + + function paint() { + for (const node of [...overlay.querySelectorAll('.fv-iv-lbox:not(.fv-iv-lbox-ghost)')]) node.remove(); + const handles = coarse() ? ['nw', 'ne', 'sw', 'se'] : ['nw', 'n', 'ne', 'e', 'se', 's', 'sw', 'w']; + items.forEach((item, index) => { + const [x0, y0, x1, y1] = item.box, node = el('div', 'fv-iv-lbox'); + node.dataset.index = String(index); node.dataset.empty = String(!item.line.trim()); + node.dataset.selected = String(index === selected); node.dataset.editing = String(index === editing); + // A chosen box is a layer of the view: Escape lets go of it before it steps the view back (shell.js FLOATING). + if (index === selected) node.dataset.fvLayer = ''; + Object.assign(node.style, {left: `${x0 * 100}%`, top: `${y0 * 100}%`, width: `${(x1 - x0) * 100}%`, height: `${(y1 - y0) * 100}%`}); + const head = el('div', 'fv-iv-lbox-head'), no = el('span', 'fv-iv-lbox-no', String(index + 1)); + head.append(no); + if (quotedParts(item.line).length) { + const T = el('button', 'fv-iv-lbox-t', 'T'); T.type = 'button'; + T.setAttribute('aria-pressed', String(!item.textOff)); T.setAttribute('aria-label', t('Text in the picture', '写进画面的字')); + tip(T, t('Text in the picture', '写进画面的字')); + T.addEventListener('pointerdown', event => event.stopPropagation()); + T.addEventListener('click', event => { event.stopPropagation(); remember(); item.textOff = !item.textOff; changed(); }); + head.append(T); + } + if (index !== editing && item.line.trim()) head.append(el('span', 'fv-iv-lbox-line', item.line.trim())); + node.append(head); + if (index === selected) { + for (const side of handles) { const h = el('span', 'fv-iv-lbox-h'); h.dataset.side = side; node.append(h); } + const x = el('button', 'fv-iv-lbox-x', '×'); x.type = 'button'; x.setAttribute('aria-label', t('Delete box', '删除框')); tip(x, t('Delete box', '删除框')); + x.addEventListener('pointerdown', event => event.stopPropagation()); + x.addEventListener('click', event => { event.stopPropagation(); remove(index); }); + node.append(x); + } + // (The line's box sits after the boxes, above them; on a phone it is in the bar instead.) + if (field.parentNode === overlay) overlay.insertBefore(node, field); else overlay.append(node); + }); + placeField(); + } + function placeField() { + const phone = narrow(); + field.hidden = editing < 0; + if (editing >= 0) field.dataset.fvLayer = ''; else delete field.dataset.fvLayer; + bar.hidden = editing < 0 || !phone || !shown; + if (editing < 0) { if (field.parentNode !== overlay) overlay.append(field); return; } + if (phone) { + if (field.parentNode !== bar) bar.insertBefore(field, done); + barNo.textContent = String(editing + 1); + keepInView(); + return; + } + if (field.parentNode !== overlay) overlay.append(field); + const [x0, , , y1] = items[editing].box, below = y1 < .88; + Object.assign(field.style, {left: `${x0 * 100}%`, top: below ? `${y1 * 100}%` : '', bottom: below ? '' : `${(1 - items[editing].box[1]) * 100}%`}); + field.dataset.side = below ? 'below' : 'above'; + } + + // Draw on empty frame, move by the inside, resize by the handles. + let drag = null; + overlay.addEventListener('pointerdown', event => { + if (event.button !== 0 || event.target === field) return; + const node = event.target.closest('.fv-iv-lbox'), handle = event.target.closest('.fv-iv-lbox-h'); + const point = at(event); + if (editing >= 0) commit(); + if (node && !node.classList.contains('fv-iv-lbox-ghost')) { + const index = Number(node.dataset.index); + drag = {kind: handle ? 'resize' : 'move', side: handle?.dataset.side || '', index, start: point, from: [...items[index].box], moved: false}; + selected = index; paint(); + } else { + if (items.length >= limit) { say(event); select(-1); return; } + drag = {kind: 'draw', start: point, box: [...point, ...point], moved: false}; + } + overlay.setPointerCapture?.(event.pointerId); + event.preventDefault(); overlay.focus({preventScroll: true}); + }); + overlay.addEventListener('pointermove', event => { + if (!drag) return; + const [x, y] = at(event), [sx, sy] = drag.start; + if (Math.abs(x - sx) + Math.abs(y - sy) > .005) drag.moved = true; + if (drag.kind === 'draw') { + drag.box = [Math.min(x, sx), Math.min(y, sy), Math.max(x, sx), Math.max(y, sy)]; + const [x0, y0, x1, y1] = drag.box; + ghost.hidden = !drag.moved; + Object.assign(ghost.style, {left: `${x0 * 100}%`, top: `${y0 * 100}%`, width: `${(x1 - x0) * 100}%`, height: `${(y1 - y0) * 100}%`}); + return; + } + if (!drag.moved) return; + if (!drag.remembered) { remember(); drag.remembered = true; } + const [fx0, fy0, fx1, fy1] = drag.from, dx = x - sx, dy = y - sy, box = items[drag.index].box; + if (drag.kind === 'move') { + const w = fx1 - fx0, h = fy1 - fy0, nx = clamp(fx0 + dx, 0, 1 - w), ny = clamp(fy0 + dy, 0, 1 - h); + box.splice(0, 4, nx, ny, nx + w, ny + h); + } else { + let [x0, y0, x1, y1] = drag.from; + if (drag.side.includes('w')) x0 = clamp(fx0 + dx, 0, fx1 - SMALLEST); + if (drag.side.includes('e')) x1 = clamp(fx1 + dx, fx0 + SMALLEST, 1); + if (drag.side.includes('n')) y0 = clamp(fy0 + dy, 0, fy1 - SMALLEST); + if (drag.side.includes('s')) y1 = clamp(fy1 + dy, fy0 + SMALLEST, 1); + box.splice(0, 4, x0, y0, x1, y1); + } + paint(); + }); + const finish = () => { + if (!drag) return; + const was = drag; drag = null; ghost.hidden = true; + if (was.kind === 'draw') { + const [x0, y0, x1, y1] = was.box; + // Too small to be meant as a box: a click on the empty frame, which lets go of the chosen box. + if (x1 - x0 < SMALLEST || y1 - y0 < SMALLEST) { select(-1); return; } + remember(); items.push({id: nextId++, box: was.box, line: '', textOff: false}); + select(items.length - 1, true); onChange(); + return; + } + if (!was.moved) { select(was.index, true); return; } + changed(); + }; + overlay.addEventListener('pointerup', finish); + overlay.addEventListener('pointercancel', finish); + + const unlistenField = listenDialogKey(field, 'keydown', event => { + // Keys in the box are the words' own: nothing reaches the frame or the view, except Ctrl+Enter (Generate), + // which takes the line as it is. + if ((event.ctrlKey || event.metaKey) && event.key === 'Enter') { commit(); select(-1); return; } + event.stopPropagation(); + if (event.key === 'Enter' && !event.isComposing) { event.preventDefault(); commit(); select(-1); onChange(); } + // Escape closes the line and keeps the box chosen (Delete and the arrows then act on it); a second Escape lets go. + else if (event.key === 'Escape') { event.preventDefault(); took(); const index = editing; commit(); selected = index; paint(); overlay.focus({preventScroll: true}); onChange(); } + }); + field.addEventListener('input', () => { if (editing >= 0) { const item = items[editing]; item.line = field.value.slice(0, LINE_LIMIT); if (!quotedParts(item.line).length) item.textOff = false; onChange(); } }); + done.addEventListener('click', () => { commit(); select(-1); onChange(); }); + + // Delete, arrows and undo act on the boxes only while the frame is shown and no box of words has the keys. + function onKey(event) { + if (!shown || overlay.hidden || !overlay.contains(event.target) || event.target === field) return; + const mod = event.ctrlKey || event.metaKey; + if (mod && event.key.toLowerCase() === 'z') { event.preventDefault(); event.stopPropagation(); step(event.shiftKey ? 1 : -1); return; } + if (selected < 0) return; + if (event.key === 'Delete' || event.key === 'Backspace') { event.preventDefault(); event.stopPropagation(); remove(selected); return; } + if (event.key === 'Escape') { event.preventDefault(); event.stopImmediatePropagation(); took(); select(-1); return; } + const moves = {ArrowLeft: [-1, 0], ArrowRight: [1, 0], ArrowUp: [0, -1], ArrowDown: [0, 1]}[event.key]; + if (moves) { + event.preventDefault(); event.stopPropagation(); remember(); + const by = event.shiftKey ? .05 : .01, box = items[selected].box, w = box[2] - box[0], h = box[3] - box[1]; + const nx = clamp(box[0] + moves[0] * by, 0, 1 - w), ny = clamp(box[1] + moves[1] * by, 0, 1 - h); + box.splice(0, 4, nx, ny, nx + w, ny + h); changed(); + } + } + const unlisten = listenDialogKey(overlay, 'keydown', onKey); + + return { + element: overlay, + show(on) { + shown = !!on; overlay.hidden = !shown; + if (!shown && editing >= 0) { commit(); editing = -1; } + if (!shown) selected = -1; + paint(); + }, + get shown() { return shown; }, + tookEscape: () => performance.now() - tookAt < 400, + // Escape however it arrives (the view's cancel, when the key did not reach the boxes): an open line closes and its + // box stays chosen; else a chosen box is let go. True when it was used here. + escape() { + if (!shown) return false; + if (editing >= 0) { const index = editing; commit(); selected = index; paint(); overlay.focus({preventScroll: true}); onChange(); took(); return true; } + if (selected >= 0) { select(-1); took(); return true; } + return false; + }, + count: () => items.length, + filled: () => items.filter(item => item.line.trim()).length, + request: () => layoutRequest(items), + caption: () => layoutCaption(items), + snapshot: () => copy(items).map(({id, ...rest}) => rest), + set(list) { + if (editing >= 0) commit(); + remember(); + items = (Array.isArray(list) ? list : []).slice(0, limit).filter(item => Array.isArray(item?.box) && item.box.length === 4) + .map(item => ({id: nextId++, box: item.box.map(Number), line: String(item.line || '').slice(0, LINE_LIMIT), textOff: !!item.textOff})); + selected = editing = -1; changed(); + }, + dispose() { unlisten(); unlistenField(); viewport?.removeEventListener('resize', lift); viewport?.removeEventListener('scroll', lift); window.removeEventListener('resize', lift); bar.remove(); hint?.remove(); overlay.remove(); }, + }; +} diff --git a/web/image_view_ui.js b/web/image_view_ui.js index e0b828ec..753669a4 100644 --- a/web/image_view_ui.js +++ b/web/image_view_ui.js @@ -11,6 +11,7 @@ export const el = (tag, cls, text) => { const e = document.createElement(tag); i const PATHS = { model: '', prompt: '', + layout: '', refs: '', size: '', sliders: '', diff --git a/web/library.css b/web/library.css index 60b8c210..1a21bf73 100644 --- a/web/library.css +++ b/web/library.css @@ -417,6 +417,11 @@ dialog.fv-studio.fv-library::backdrop{background:var(--lib-page)} .fv-library .fv-library-player-button{display:grid;place-items:center;flex:none;width:var(--fv-ctl,32px);height:var(--fv-ctl,32px);min-height:var(--fv-ctl,32px);padding:0;border:0;border-radius:var(--fv-r-sm);background:transparent;color:#fff;box-shadow:none} .fv-library .fv-library-player-button:hover{background:rgb(255 255 255 / .14)} .fv-library .fv-library-player-seek{flex:1;min-width:0;height:4px;accent-color:#fff;cursor:pointer} +/* The bar sits on the video (dark in both themes): its track and knob are light (as before), as the shared slider track follows the page theme. */ +.fv-library .fv-library-player-seek::-webkit-slider-runnable-track{background:rgb(255 255 255 / .35)} +.fv-library .fv-library-player-seek::-moz-range-track{background:rgb(255 255 255 / .35)} +.fv-library .fv-library-player-seek::-webkit-slider-thumb{background:#fff} +.fv-library .fv-library-player-seek::-moz-range-thumb{background:#fff} .fv-library .fv-library-player-time{flex:none;font-size:var(--fv-fs-1,12px);font-variant-numeric:tabular-nums;color:rgb(255 255 255 / .9)} .fv-library .fv-library-player-big{position:absolute;left:50%;top:50%;z-index:2;display:grid;place-items:center;width:56px;height:56px;min-height:56px;padding:0;border:0;border-radius:var(--fv-r-pill); transform:translate(-50%,-50%);background:rgb(8 10 14 / .5);-webkit-backdrop-filter:blur(var(--fv-glass-blur1,22px));backdrop-filter:blur(var(--fv-glass-blur1,22px));color:#fff;box-shadow:0 8px 24px rgb(0 0 0 / .3)} diff --git a/web/library.js b/web/library.js index ff4db786..b74e622f 100644 --- a/web/library.js +++ b/web/library.js @@ -1,3 +1,4 @@ +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'; @@ -617,9 +618,9 @@ export function openLibrary(t, options = {}) { const tagRow = el('div', null, 'fv-library-tag-row'); const stats = el('div', null, 'fv-stats'); stats.hidden = true; stats.setAttribute('aria-label', t('Generation statistics', '生成统计')); - const budget = el('div', '', 'fv-budget'); + const budget = el('div', '', 'fv-budget'), sound = el('div', '', 'fv-budget'); const run = el('details', null, 'fv-library-run'); run.hidden = true; - const runSummary = el('summary', t('Run details', '运行详情')); run.append(runSummary, stats, budget); + const runSummary = el('summary', t('Run details', '运行详情')); run.append(runSummary, stats, budget, sound); tip(runSummary, t('Run details', '运行详情'), t('Time and memory this generation used', '这次生成的用时和内存')); const links = el('div', null, 'fv-result-links'); const notice = el('p', '', 'fv-library-message fv-library-notice'); notice.setAttribute('role', 'status'); @@ -755,7 +756,7 @@ export function openLibrary(t, options = {}) { } function clearDetail() { releasePlayer(); selected = null; frame.replaceChildren(); links.replaceChildren(); tagRow.replaceChildren(); date.textContent = geometry.textContent = ''; - stats.hidden = true; stats.replaceChildren(); budget.textContent = ''; run.hidden = true; detail.dataset.empty = 'true'; + stats.hidden = true; stats.replaceChildren(); budget.textContent = ''; sound.textContent = ''; run.hidden = true; detail.dataset.empty = 'true'; } function mountPlayer(row) { releasePlayer(); frame.replaceChildren(); @@ -890,7 +891,7 @@ export function openLibrary(t, options = {}) { const seconds = Number(pictureFacts.get(row.file)?.seconds); stats.replaceChildren(); if (seconds > 0) { const item = el('div', null, 'fv-stat'); item.append(el('strong', t(`${seconds} s`, `${seconds} 秒`)), el('span', t('Time', '用时'))); stats.append(item); } - stats.hidden = !stats.childElementCount; budget.textContent = ''; run.hidden = stats.hidden; + stats.hidden = !stats.childElementCount; budget.textContent = ''; sound.textContent = ''; run.hidden = stats.hidden; if (reveal) dialog.dataset.detail = 'true'; return; } // These are the saved generation's measurements, including when the @@ -911,7 +912,10 @@ export function openLibrary(t, options = {}) { stats.hidden = row.preview || ![row.sample_seconds, row.request_seconds, row.vram_peak_bytes, row.ram_peak_bytes].some(measured); budget.textContent = !row.preview && measured(row.gpu_budget_bytes) ? `${t('VRAM budget', '可用显存预算')} ${number(row.gpu_budget_bytes, 2 ** 30, 'GiB')} · ${t('Device', '显卡总量')} ${number(row.gpu_total_bytes, 2 ** 30, 'GiB')}` : ''; - run.hidden = stats.hidden && !budget.textContent; + // Sound that could not be kept as it was: what it is stored as, and that the original stays. + const stored = row.original_audio?.stored_as; + sound.textContent = typeof stored === 'string' && stored ? `${t('Sound', '声音')} ${stored} · ${t('original kept', '原声已保留')}` : ''; + run.hidden = stats.hidden && !budget.textContent && !sound.textContent; if (reveal) dialog.dataset.detail = 'true'; } // Continue a video into a longer one: the editor opens on it and the room closes. @@ -1069,7 +1073,7 @@ export function openLibrary(t, options = {}) { const key = workKey(row); labelCard(key, sort === 'new' || sort === 'old'); if (selected === key) showPrompt(row); - if (viewing === key) { const name = viewer.querySelector('.fv-library-viewer-name'); if (name) name.title = name.textContent = viewerName(row); } + if (viewing === key) { const name = viewer.querySelector('.fv-library-viewer-name'); if (name) { name.textContent = viewerName(row); cutTip(name, name.textContent); } } } promptWorkers--; } @@ -1284,7 +1288,7 @@ export function openLibrary(t, options = {}) { } // The shelf swaps by a cross-fade: the old cards stay until the new order is there. function transition(change) { - if (!document.startViewTransition || reducedMotion() || !dialog.isConnected) { change(); return; } + if (!document.startViewTransition || document.documentElement.dataset.fvTransitions === 'off' || reducedMotion() || !dialog.isConnected) { change(); return; } grid.style.viewTransitionName = 'fv-library-shelf'; const done = document.startViewTransition(change); done.finished.finally(() => { grid.style.viewTransitionName = ''; }); @@ -2237,7 +2241,7 @@ export function openLibrary(t, options = {}) { full.classList.add('fv-library-viewer-full'); const close = viewerButton(t('Exit full screen', '退出全屏'), t('Back to the library', '回到作品库'), line('close'), () => exitFull(), 'Esc'); close.classList.add('fv-library-viewer-close'); - const name = el('strong', viewerName(row), 'fv-library-viewer-name'); name.title = name.textContent; + const name = el('strong', viewerName(row), 'fv-library-viewer-name'); cutTip(name, name.textContent); const words = el('div', null, 'fv-library-viewer-words'); words.append(name, spec); bottom.append(words, viewerActions(row, key), info, full, close); const main = el('div', null, 'fv-library-viewer-main'), stage = el('div', null, 'fv-library-viewer-stage'); diff --git a/web/notifications.js b/web/notifications.js index d126feb5..59a5bf18 100644 --- a/web/notifications.js +++ b/web/notifications.js @@ -4,6 +4,8 @@ // floating window does (a finished job opens where it was made, a failed one opens its failure card). // The list is kept in this browser (freevideo.notifications, 50 rows, a week). Also here: toast(), one short line // at the bottom of the window for things the command layer has to say. +import { cutTip } from './cut_tip.js'; +import { setTip } from './tip_words.js'; import { t, words, CN, glyph, floatingHost, reducedMotion, EASE, addSheet, openContextMenu } from './context_menu.js'; import { jobs, ACTIVE, FINAL } from './task_store.js'; @@ -485,7 +487,7 @@ function buildToast(item, more) { const icon = document.createElement('span'); icon.className = 'fv-toast-ic'; icon.innerHTML = glyph(spec.icon); box.append(icon); const msg = document.createElement('span'); msg.className = 'fv-toast-msg'; msg.textContent = spec.text; if (spec.detail) { const small = document.createElement('small'); small.textContent = spec.detail; msg.append(small); } - msg.title = [spec.text, spec.detail].filter(Boolean).join(' · '); + cutTip(msg, [spec.text, spec.detail].filter(Boolean).join(' · ')); box.append(msg); if (spec.action) { const act = document.createElement('button'); act.type = 'button'; act.className = 'fv-toast-act'; @@ -495,7 +497,7 @@ function buildToast(item, more) { act.onclick = () => { queue.close(item); try { spec.action.run(); } catch (error) { console.warn('FreeVideo notice action:', error); } }; box.append(act); } - if (more > 0) { const chip = document.createElement('span'); chip.className = 'fv-toast-more'; chip.textContent = `+${more}`; chip.title = t(`${more} more after this`, `后面还有 ${more} 条`); box.append(chip); } + if (more > 0) { const chip = document.createElement('span'); chip.className = 'fv-toast-more'; chip.textContent = `+${more}`; setTip(chip, {name: t(`${more} more after this`, `后面还有 ${more} 条`)}); box.append(chip); } if (!spec.sticky) { const ring = lifeRing(); ring.style.setProperty('--life', `${spec.ms}ms`); box.append(ring); } const close = document.createElement('button'); close.type = 'button'; close.className = 'fv-toast-x'; close.innerHTML = glyph('close', 14); close.setAttribute('aria-label', t('Close', '关闭')); diff --git a/web/private_settings.js b/web/private_settings.js index 566f7d9e..03f71cec 100644 --- a/web/private_settings.js +++ b/web/private_settings.js @@ -3,6 +3,7 @@ // versions put in ComfyUI's input folder under the user's own file names, which cannot be told apart from the user's own // files, so each one goes only when the user chooses it. Built with the settings kit so it reads like the rest of the // page. An engine older than this page has none of these calls: the whole group then stays hidden and nothing is asked. +import { cutTip } from './cut_tip.js'; import { el, icon, tip, button, row, card, groupHead, fold, segmented } from './settings_kit.js'; import { privacyOffered } from './private_offers.js'; @@ -110,7 +111,7 @@ export function privacySettings(t, api) { if (!items.length) { nothingOld(true); return; } for (const item of items) { const cell = el('figure', 'st-private-cell'), image = el('img'), caption = el('figcaption', '', item.name); - image.src = view(item.name); image.alt = ''; image.loading = 'lazy'; caption.title = item.name; + image.src = view(item.name); image.alt = ''; image.loading = 'lazy'; cutTip(caption, item.name); const remove = button(t('Delete', '删除')); confirming(remove, t('Delete', '删除'), t('Confirm', '确认删除'), async () => { try { diff --git a/web/settings_room.js b/web/settings_room.js index 418e9ef0..23caaa08 100644 --- a/web/settings_room.js +++ b/web/settings_room.js @@ -5,6 +5,8 @@ // performance measurement), Version & updates, Getting started. Every function of the earlier settings sheet is here; // the technical parts (folders, access token, speed tables, logs) are folded away. Esc closes and gives focus back. // 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 { api } from "../../scripts/api.js"; import { compatibilityCard } from './compatibility.js'; import { listenDialogKey } from './dialog_keys.js'; @@ -32,6 +34,7 @@ if (typeof document !== 'undefined') { document.head.append(css); } +import { nearestAllowed } from './field_note.js'; import { cn, t, INSTALLED_HINT, gib, bytesText, atLeast, WAIT_REFUSAL, reportable, failureText, setupError, SECTIONS, sectionOf } from './settings_words.js'; export { failureText, sectionOf, SECTIONS, bytesText }; @@ -382,7 +385,7 @@ export async function openSetup(options) { let loraLoaded = false, loraRun = 0; const loraRow = name => { const r = row({iconName: 'layers', title: name.split('/').pop(), sub: t('Checking…', '正在检查…'), cls: 'st-lrow'}); - r.title.title = name; + setTip(r.title, {name}); const chip = el('span', 'st-chip', t('Checking', '检查中')); r.end.append(chip); const more = el('div', 'st-sub st-ldetail'); more.hidden = true; r.paint = verdict => { @@ -1178,7 +1181,17 @@ export async function openSetup(options) { reserve.focus(); return; } - if (!reserveAuto.checked && !reserve.checkValidity()) { reserve.reportValidity(); return; } + // Past the top or between steps: the nearest allowed amount goes in the box and the line says so; Save again keeps it. + const moved = reserveAuto.checked ? null : nearestAllowed(reserve); + if (moved || (!reserveAuto.checked && !reserve.checkValidity())) { + if (moved) reserve.value = String(moved.value); + reserveFailure.className = 'st-slot is-warn'; reserveStep.classList.add('is-bad'); + reserveFailure.textContent = !moved ? t('Enter a number in range', '请输入范围内的数') + : moved.kind === 'max' ? t(`At most ${moved.value}`, `最多 ${moved.value}`) + : moved.kind === 'min' ? t(`At least ${moved.value}`, `最少 ${moved.value}`) : t(`Changed to ${moved.value}`, `已改为 ${moved.value}`); + reserve.focus(); + return; + } saveReserve.disabled = true; try { showResources(await request('resources', {[reserveField]: reserveAuto.checked ? null : Number(reserve.value)})); @@ -1312,7 +1325,7 @@ export async function openSetup(options) { t("No conversion on this computer", "无需本地转换")]); const list = el('dl', 'st-facts'); for (const [key, shownValue, small] of facts) { - const box = el('div'); const dd = el('dd', '', shownValue); dd.title = shownValue; + const box = el('div'); const dd = el('dd', '', shownValue); cutTip(dd, shownValue); if (small) dd.append(el('small', '', small)); box.append(el('dt', '', key), dd); list.append(box); } @@ -1405,7 +1418,7 @@ export async function openSetup(options) { // there is (cut with an ellipsis), the last 26 characters stay; copying takes the whole path. const first = missing[0], cut = Math.max(0, first.length - 26), path = el('span', 'st-path st-path-cut fv-copyable'); path.append(el('span', 'st-path-head', first.slice(0, cut)), el('span', 'st-path-tail', first.slice(cut))); - path.title = first; folderStatus.append(path); + cutTip(path, first); folderStatus.append(path); } return result; } diff --git a/web/shell.js b/web/shell.js index 8bf102cd..3c434e09 100644 --- a/web/shell.js +++ b/web/shell.js @@ -24,6 +24,37 @@ const listeners = new Set(); // The compatibility view (Settings → 兼容界面) counts as reduced motion: views switch at once. const reduced = () => root.dataset.glass === 'solid' || root.classList.contains('lite') || globalThis.matchMedia?.('(prefers-reduced-motion: reduce)').matches === true; +// View transitions (the picture held while a view comes to the front) cost main-thread time on every switch, so they +// are for machines that carry them: "auto" (default) switches them off at four cores or fewer, or when the first two +// switches after the first took over 400 ms to lay out (this session only); a stored "on" or "off" overrides both. Off, a switch just +// runs (no held picture); the pages that name pictures for it (task_float, the library shelf) follow the same flag. +const TRANSITIONS = 'freevideo.transitions', SLOW_CORES = 4, SLOW_SWITCH_MS = 400, SLOW_SAMPLES = 2; +const stored = key => { try { return localStorage.getItem(key); } catch { return null; } }; +const keep = (key, value) => { try { localStorage.setItem(key, value); } catch { /* This page only. */ } }; +export const transitionMode = () => { const mode = stored(TRANSITIONS); return mode === 'on' || mode === 'off' ? mode : 'auto'; }; +export function transitionsOn(mode = transitionMode()) { + if (mode !== 'auto') return mode === 'on'; + const cores = globalThis.navigator?.hardwareConcurrency; + return !(cores > 0 && cores <= SLOW_CORES) && !slowNow; +} +function applyTransitions() { root.dataset.fvTransitions = transitionsOn() ? 'on' : 'off'; } +export function setTransitions(mode) { + if (mode !== 'auto' && mode !== 'on' && mode !== 'off') return; + keep(TRANSITIONS, mode); + if (mode === 'auto') { slowNow = false; slowSeen.length = 0; switchesSeen = 0; } + applyTransitions(); +} +// The second and third switches of an "auto" machine (the first loads modules and is skipped): both slow → off from the +// next switch on, for this session. A fast machine's cold switches measure 150-360 ms, so the bar sits at 400. +const slowSeen = []; +let slowNow = false, switchesSeen = 0; +function noteSwitch(ms) { + if (transitionMode() !== 'auto' || slowNow || slowSeen.length >= SLOW_SAMPLES || !(ms >= 0) || ++switchesSeen < 2) return; + slowSeen.push(ms); + if (slowSeen.length === SLOW_SAMPLES && slowSeen.every(value => value > SLOW_SWITCH_MS)) { slowNow = true; applyTransitions(); } +} +const canTransit = () => typeof document.startViewTransition === 'function' && root.dataset.fvTransitions !== 'off'; + export const currentView = () => view; export function onView(listener) { listeners.add(listener); return () => listeners.delete(listener); } @@ -249,7 +280,7 @@ function riseOver(token, {shift = true} = {}) { // FreeVideoShell.holdWhile(() => openLibrary(...), {ready: libraryShown}) // Without view transitions (or during a view switch) open() simply runs. export function holdWhile(open, {ready = null} = {}) { - if (typeof document.startViewTransition !== 'function' || switching) return Promise.resolve().then(open); + if (!canTransit() || switching) return Promise.resolve().then(open); const mark = {target: 'panel', from: view, press: performance.now()}, log = globalThis.__fvSwitches ||= []; log.push(mark); if (log.length > 10) log.shift(); const token = {target: view, mark, animating: false, panel: true}; @@ -298,11 +329,11 @@ function holdFocus() { // it is ready within a few frames and rises over the held picture at once; what is new arrives in place afterwards. export function switchView(target, run) { - if (switching && !switching.animating && typeof document.startViewTransition === 'function') return retarget(switching, target); + if (switching && !switching.animating) return retarget(switching, target); if (target === view) return run(); const from = view, leaving = markLeaving(from); const unmark = () => { if (leaving) delete leaving.dataset.fvLeaving; }; - if (typeof document.startViewTransition !== 'function') { try { return run(); } finally { unmark(); } } + if (!canTransit()) { switching?.transition?.skipTransition?.(); try { return run(); } finally { unmark(); } } switching?.transition?.skipTransition?.(); // Phase times of the last switches (ms since the press), for tests/shell_switch_check.py. const mark = {target, from, press: performance.now()}, log = globalThis.__fvSwitches ||= []; @@ -350,6 +381,7 @@ export function switchView(target, run) { } nameBar(frontBar()); at('ready'); + noteSwitch(mark.ready); riseOver(token); }, () => {}); token.transition.ready.catch(() => at('skipped')); @@ -511,6 +543,7 @@ export function installShell({cover: wantCover = false} = {}) { if (globalThis.FreeVideoShell?.installed) return globalThis.FreeVideoShell; root.dataset.theme ||= 'dark'; try { if (localStorage.getItem('freevideo.glass') === 'solid') root.dataset.glass = 'solid'; } catch { /* Glass stays on. */ } + applyTransitions(); // Says once, with a button to Settings, when the interface runs slowly here (ui_speed.js); never switches by itself. import('./ui_speed.js').then(({watchSpeed}) => watchSpeed()).catch(() => {}); try { if (localStorage.getItem('freevideo.material') === 'glass' || new URLSearchParams(location.search).get('freevideo_material') === 'glass') root.dataset.fvMaterial = 'glass'; } catch { /* Calm. */ } @@ -527,6 +560,12 @@ export function installShell({cover: wantCover = false} = {}) { import('./glass/stage_light.js').catch(error => console.warn('FreeVideo stage light:', error)); } // FreeVideo's own right-click menu wherever a part has none of its own (text boxes, links, the empty page). + // ComfyUI's Templates window: Chinese words for its search box and first category, and the light theme. + if (!document.querySelector('link[data-fv-sheet="comfy-templates"]')) { + const sheet = document.createElement('link'); sheet.rel = 'stylesheet'; sheet.dataset.fvSheet = 'comfy-templates'; + sheet.href = new URL('./comfy_templates.css', import.meta.url).href; document.head.append(sheet); + } + import('./comfy_templates.js').then(({watchTemplates}) => watchTemplates()).catch(error => console.warn('FreeVideo templates:', error)); import('./context_fallback.js').catch(error => console.warn('FreeVideo menu:', error)); guardTitle(); watchHead(); quietSplash(); for (const type of SWITCH_INPUT) globalThis.addEventListener?.(type, pressDuringSwitch, {capture: true, passive: false}); @@ -573,6 +612,6 @@ export function installShell({cover: wantCover = false} = {}) { event.stopImmediatePropagation(); try { dialog.showModal(); } catch (error) { console.warn('FreeVideo view reopen:', error); } }, true); - globalThis.FreeVideoShell = {installed: true, view: currentView, onView, go, overlayHost, viewDialog, VIEWS, hideCover, settleShell, setTheme, setGlass, setMaterial, setLook, switchView, switching: isSwitching, toastHost, statusAnchor, holdWhile}; + globalThis.FreeVideoShell = {installed: true, view: currentView, onView, go, overlayHost, viewDialog, VIEWS, hideCover, settleShell, setTheme, setGlass, setTransitions, transitionMode, transitionsOn, setMaterial, setLook, switchView, switching: isSwitching, toastHost, statusAnchor, holdWhile}; return globalThis.FreeVideoShell; } diff --git a/web/slider.css b/web/slider.css new file mode 100644 index 00000000..2ac5f397 --- /dev/null +++ b/web/slider.css @@ -0,0 +1,21 @@ +/* One slider look for FreeVideo's own surfaces, on every platform (the browser's own is drawn by the system and differs): + a 4 px track, a round accent knob. Scope as in a11y.css; the zero-specificity :where lets a view's own sizes (the touch 44 px + rows, the image editor's filled track, the chat seek) keep winning. + No filled part (Chrome cannot draw one; Firefox would, so neither does): the knob shows the value. Mixed-value sliders hide the knob in editor_audio.css. */ +:where(body [class^="fv-"],body [class*=" fv-"],body [class^="sgf"],body [class*=" sgf"],body [data-fv-tip-scope]) :where(input[type=range]), +:where(body input[type=range]:is([class^="fv-"],[class*=" fv-"],[class^="sgf"],[class*=" sgf"])){ + -webkit-appearance:none;appearance:none;background:transparent;height:16px;margin:0;cursor:pointer} +:where(body [class^="fv-"],body [class*=" fv-"],body [class^="sgf"],body [class*=" sgf"],body [data-fv-tip-scope]) :where(input[type=range]):disabled, +:where(body input[type=range]:is([class^="fv-"],[class*=" fv-"],[class^="sgf"],[class*=" sgf"])):disabled{opacity:.5;cursor:default} +:where(body [class^="fv-"],body [class*=" fv-"],body [class^="sgf"],body [class*=" sgf"],body [data-fv-tip-scope]) :where(input[type=range])::-webkit-slider-runnable-track, +:where(body input[type=range]:is([class^="fv-"],[class*=" fv-"],[class^="sgf"],[class*=" sgf"]))::-webkit-slider-runnable-track{ + height:4px;border-radius:2px;background:var(--fv-line2,var(--fv-border,rgb(255 255 255 / .14)))} +:where(body [class^="fv-"],body [class*=" fv-"],body [class^="sgf"],body [class*=" sgf"],body [data-fv-tip-scope]) :where(input[type=range])::-moz-range-track, +:where(body input[type=range]:is([class^="fv-"],[class*=" fv-"],[class^="sgf"],[class*=" sgf"]))::-moz-range-track{ + height:4px;border-radius:2px;background:var(--fv-line2,var(--fv-border,rgb(255 255 255 / .14)))} +:where(body [class^="fv-"],body [class*=" fv-"],body [class^="sgf"],body [class*=" sgf"],body [data-fv-tip-scope]) :where(input[type=range])::-webkit-slider-thumb, +:where(body input[type=range]:is([class^="fv-"],[class*=" fv-"],[class^="sgf"],[class*=" sgf"]))::-webkit-slider-thumb{ + -webkit-appearance:none;appearance:none;width:14px;height:14px;margin-top:-5px;border:0;border-radius:50%;background:var(--fv-accent);box-shadow:0 1px 3px rgb(0 0 0 / .35)} +:where(body [class^="fv-"],body [class*=" fv-"],body [class^="sgf"],body [class*=" sgf"],body [data-fv-tip-scope]) :where(input[type=range])::-moz-range-thumb, +:where(body input[type=range]:is([class^="fv-"],[class*=" fv-"],[class^="sgf"],[class*=" sgf"]))::-moz-range-thumb{ + width:14px;height:14px;border:0;border-radius:50%;background:var(--fv-accent);box-shadow:0 1px 3px rgb(0 0 0 / .35)} diff --git a/web/studio.js b/web/studio.js index e3cd0350..519f8568 100644 --- a/web/studio.js +++ b/web/studio.js @@ -1,3 +1,4 @@ +import { cutTip } from './cut_tip.js'; import './has_mirror.js'; import {createLanAccess} from './lan_access.js'; import { createErrorPanel, errorText, createErrorReport } from './error_panel.js'; @@ -78,6 +79,7 @@ import { createCompare, COMPARE_ICON } from './studio_compare.js'; import { toast, toastHeight } from './notifications.js'; import { mediaQueue } from './work_media.js'; import { userMessage } from './user_message.js'; +import { fieldNote } from './field_note.js'; const languageOverride = typeof location !== 'undefined' ? new URLSearchParams(location.search).get('freevideo_lang') : null; @@ -91,15 +93,21 @@ const LORA_USUAL = 4, LORA_LIMIT = 100; let loraRangeCount = 0; function loraStrengthBox(initial, commit) { const input = document.createElement('input'), mark = document.createElement('span'); - input.type = 'number'; input.step = '.05'; input.value = initial; + input.type = 'number'; input.step = '.05'; input.min = String(-LORA_LIMIT); input.max = String(LORA_LIMIT); input.value = initial; + const note = fieldNote(input, {t, place: () => mark.isConnected ? mark : null}); mark.id = 'fv-lora-range-' + ++loraRangeCount; input.setAttribute('aria-describedby', mark.id); mark.className = 'fv-lora-range'; mark.textContent = t('Outside usual range', '超出常用范围'); const sync = () => { const number = Number(input.value), filled = input.value !== ''; mark.hidden = !(filled && Math.abs(number) > LORA_USUAL && Math.abs(number) <= LORA_LIMIT); - input.setCustomValidity(filled && !(Math.abs(number) <= LORA_LIMIT) ? t('Enter a value from -100 to 100.', '请输入 -100 到 100 之间的数。') : ''); }; - input.oninput = sync; input.onchange = () => { sync(); if (input.reportValidity()) commit(); }; + // A strength past ±100 becomes ±100, and the line under it says so. + // An emptied box goes back to the strength in use, and the line says so. + let kept = String(initial); + input.oninput = sync; input.onchange = () => { + if (input.value === '' && kept !== '') { input.value = kept; sync(); note.say(t(`Back to ${kept}`, `已恢复为 ${kept}`)); return; } + const ok = note.settle(); sync(); if (ok) { kept = input.value; commit(); } + }; sync(); return {input, mark}; } @@ -1269,6 +1277,8 @@ export function openStudio(node, {extendFrom = null} = {}) { const [advancedDetails, advanced] = expand(t('Advanced', '高级选项')); const custom = el('div', null, 'fv-fields fvs-wh'); const width = el('input'), height = el('input'); + // Each number field's line for a typed value brought into range (field_note.js); the submit check says through it. + const fieldNotes = new Map(); // Width × height, typed: with the shape kept, the other side follows (32-pixel steps); set free, the shape is custom. let shapeKept = true; // The side the frame panel's width × height left empty: it stays empty until a size is set again. @@ -1288,8 +1298,9 @@ export function openStudio(node, {extendFrom = null} = {}) { input.value = value(node, name); input.disabled = dimensionsLinked; input.setAttribute('aria-label', label); custom.append(field(label, input)); if (name === 'width') custom.append(keepShape); + const note = fieldNote(input, {t}); fieldNotes.set(input, note); input.onchange = () => { - if (!input.value || !input.reportValidity()) return; + if (!note.settle()) return; const kept = shapeKept && selected !== 'custom' && Number.isFinite(ratio) && ratio > 0; let w = name === 'width' ? Number(input.value) : Number(value(node, 'width')); let h = name === 'height' ? Number(input.value) : Number(value(node, 'height')); @@ -1310,6 +1321,7 @@ export function openStudio(node, {extendFrom = null} = {}) { keepShape.disabled = dimensionsLinked; resolutionControl.append(custom); lengthControl = createStudioLength({api, node, seconds, advanced, fields, t, field, promptModel: enhancer.model, + settleSeconds: () => durationNote.settle(), setSeconds: seconds => set(node, 'seconds', seconds), onChange: () => { if (runButtonReady) { updateRunButton(); showEffortEstimate(); updateDuration(); } }, onEditor: toEditor, onAutopilot: toAutopilot, autopilot: !autopilotTab.hidden}); cleanup.push(() => lengthControl.dispose()); @@ -1344,6 +1356,7 @@ export function openStudio(node, {extendFrom = null} = {}) { const samplingWarning = el('p', t('Changing steps may lower quality. Default: 8 + 3 steps.', '改步数可能降低质量。默认 8 + 3 步。'), 'fv-muted'); samplingWarning.id = `fv-sampling-warning-${node.id}`; samplingWarning.style.color = 'var(--fv-warning)'; + // Steps past their range become its end, and the line under the field says so (no browser bubble). for (const [input, name, label, fallback, maximum] of [ [baseSteps, 'base_steps', t('First-pass steps', '一采步数'), 8, 32], [refineSteps, 'refine_steps', t('Second-pass steps', '二采步数'), 3, 31], @@ -1352,22 +1365,29 @@ export function openStudio(node, {extendFrom = null} = {}) { input.value = value(node, name) ?? fallback; input.setAttribute('aria-label', label); input.setAttribute('aria-describedby', samplingWarning.id); input.oninput = () => syncSamplingSteps(); - input.onchange = () => input.reportValidity(); + fieldNotes.set(input, fieldNote(input, {t})); + input.onchange = () => { fieldNotes.get(input).settle(); syncSamplingSteps(); }; samplingFields.append(field(label, input)); } // Typed steps are custom sampling, which has no step cache. baseSteps.oninput = () => { clearStepCache(); syncSamplingSteps(); }; // Apply the two-pass rule to committed values, never while typing. - baseSteps.onchange = () => { - // Before validation: one step is valid only once two-pass is off. + const twoPassRule = () => { const steps = Number(baseSteps.value); if (baseSteps.value !== '' && Number.isInteger(steps) && steps >= 1 && steps <= 32 && !linked(node, 'two_pass') && widget(node, 'two_pass')) { - if (steps !== 8 && twoPass.checked) { twoPass.checked = false; set(node, 'two_pass', false); autoSinglePass = true; } + if (steps !== 8 && twoPass.checked) { twoPass.checked = false; set(node, 'two_pass', false); autoSinglePass = true; baseSteps.min = '1'; } else if (steps === 8 && autoSinglePass && !extension.source) { twoPass.checked = true; set(node, 'two_pass', true); autoSinglePass = false; } } + }; + baseSteps.onchange = () => { + // Before the range is applied: one step is allowed once two-pass is off. A value brought into range is + // checked against that rule again. + twoPassRule(); + const typed = baseSteps.value; + fieldNotes.get(baseSteps).settle(); + if (baseSteps.value !== typed) twoPassRule(); syncSamplingSteps(); - baseSteps.reportValidity(); }; // The run button exists only further down; until then its label is set there. let runButtonReady = false; @@ -1513,7 +1533,8 @@ export function openStudio(node, {extendFrom = null} = {}) { } const seedFields = el('div', null, 'fv-fields'); seedFields.style.marginTop = '14px'; const seed = el('input'); seed.type = 'number'; seed.required = true; seed.min = '0'; seed.max = String(2 ** 53 - 1); seed.step = '1'; seed.value = value(node, 'seed'); seed.disabled = linked(node, 'seed'); seed.setAttribute('aria-label', t('Seed', '种子')); - seed.onchange = () => { if (seed.value && seed.reportValidity()) set(node, 'seed', Number(seed.value)); }; + const seedNote = fieldNote(seed, {t}); fieldNotes.set(seed, seedNote); + seed.onchange = () => { if (seedNote.settle()) set(node, 'seed', Number(seed.value)); }; const mode = el('select'); for (const [v, label] of [['randomize', t('New each run', '每次随机')], ['fixed', t('Keep fixed', '保持固定')], ['increment', t('Increment', '递增')], ['decrement', t('Decrement', '递减')]]) { const o = el('option', label); o.value = v; mode.append(o); } mode.value = value(node, 'control_after_generate') || 'fixed'; mode.onchange = () => set(node, 'control_after_generate', mode.value); mode.dataset.fvTipName = t('After generation', '生成后'); mode.dataset.fvTipUse = t('How the seed changes after each video', '每次生成后种子怎么变'); @@ -1564,7 +1585,7 @@ export function openStudio(node, {extendFrom = null} = {}) { // The floating task window grows out of this picture and returns to it. stage.dataset.fvTaskStage = 'studio'; // Before the first video: one quiet line under the empty frame's icon says where to start. - stage.style.setProperty('--fvs-empty-hint', JSON.stringify(t('Describe a scene below, then Generate', '在下方写一句描述,点“生成视频”'))); + stage.style.setProperty('--fvs-empty-hint', JSON.stringify(t('Describe a scene below to start', '在下方写一句描述,开始生成'))); const stageMedia = el('div', null, 'fv-stage-media'); // The next generation's empty frame: the stage itself, at the chosen (or pointed-at) shape, with its pixels. const nextSize = el('span', null, 'fvs-next-size'); @@ -2219,6 +2240,9 @@ export function openStudio(node, {extendFrom = null} = {}) { } updateRunButton(); }; + // A count past 2–100 becomes that end, and the line under the field says so. + const countNote = fieldNote(count, {t, place: () => countField}); fieldNotes.set(count, countNote); + count.onchange = () => { if (countNote.settle()) count.oninput(); }; runOptions.append(optionsToggle, optionsPanel); runOptions.addEventListener('toggle', () => { if (runOptions.open) updateRunButton(); }); // The run-mode menu opens in the top layer above its button, so it never sits under the prompt's tools. @@ -2534,7 +2558,7 @@ export function openStudio(node, {extendFrom = null} = {}) { // Waiting videos often share every setting; the start of the prompt tells them apart. const summary = String(row.inputs.text ?? '').replace(/\s+/g, ' ').trim(); const description = el('div', null, 'fv-queue-text'); - if (summary) { const line = el('span', summary, 'fv-queue-summary'); line.title = summary; description.append(line); } + if (summary) { const line = el('span', summary, 'fv-queue-summary'); cutTip(line, summary); description.append(line); } description.append(el('span', executing ? `${size} · ${row.inputs.seconds} s` : `${index + 1} · ${size} · ${row.inputs.seconds} s`, 'fv-queue-meta')); if (executing) { @@ -2633,13 +2657,18 @@ export function openStudio(node, {extendFrom = null} = {}) { [refineSteps, t('Fill in the second-pass steps.', '请填写二采步数。')]]).get(invalid); if (message) { status.dataset.error = 'true'; status.textContent = message; } } + // A value out of range is brought in and said under its field (the length: in the console's line); a rule + // between fields is said there too. No browser bubble. + const said = invalid.validity.valueMissing ? null : invalid === seconds ? durationNote : fieldNotes.get(invalid); + if (said) { said.settle(); if (invalid !== seconds) invalid.focus(); return; } + if (!invalid.validity.valueMissing) { status.dataset.error = 'true'; status.textContent = invalid.validationMessage; } // Width and height are typed in the frame panel: it opens at the empty field. const side = (invalid === width || invalid === height) && framePicker?.element.checkVisibility() ? [...framePicker.pop.querySelectorAll('.fvp-dim')][invalid === width ? 0 : 1] : null; if (side) { framePicker.set({empty: emptySide, ask: true}); if (framePicker.pop.dataset.open !== 'true') framePicker.element.click(); side.focus(); return; } // The duration is typed in the stepper's number: it opens for typing. const stepValue = invalid === seconds ? dialog.querySelector('.fvs-step-value') : null; if (stepValue?.checkVisibility()) { stepValue.click(); return; } - invalid.focus(); invalid.reportValidity(); return; + invalid.focus(); return; } // One prompt per line with no lines: say what to write (generating without a prompt is not offered here). if (byLine() && !lineTexts().length) { status.dataset.error = 'true'; status.textContent = t('Write one prompt per line, then add them.', '每行写一条描述后再添加。'); prompt.focus(); return; } @@ -2672,7 +2701,7 @@ export function openStudio(node, {extendFrom = null} = {}) { if (selected === 'input' && !dimensionsLinked) await inputRatio(true); const lengthPlan = await lengthControl.ready(); if (disposed || lengthControl.blocked) return; - if (lengthControl.absent && !seconds.reportValidity()) return; + if (lengthControl.absent && !durationNote.settle()) return; if (originalOn && lengthPlan?.count > 1 && !twoPass.checked) { status.dataset.error = 'true'; status.textContent = partsNeedTwoPassText(t); return; } if (lengthPlan?.count > 1 && chosenMode !== 'single') { status.textContent = t('Videos made in parts cannot use batch or loop.', '分段视频不能批量或循环生成。'); return; } const lengthOptions = lengthControl.options(); @@ -2711,7 +2740,7 @@ export function openStudio(node, {extendFrom = null} = {}) { const chain = await chainController.start(snapshot, lengthOptions, {onAccepted}); if (disposed) return; if (chain && chainController.waiting > waitingBefore) { status.dataset.error = 'false'; status.textContent = addedNote; return; } - if (!chain) { if (source) throw new Error(extendText(t, 'unavailable')); lengthControl.fallback(); if (!seconds.reportValidity()) return; + if (!chain) { if (source) throw new Error(extendText(t, 'unavailable')); lengthControl.fallback(); if (!durationNote.settle()) return; await queueController.start(snapshot, {count: batchCount, repeat: chosenMode === 'loop', seedIndex, onAccepted}); } } else await queueController.start(snapshot, {count: batchCount, repeat: chosenMode === 'loop', seedIndex, onAccepted, ...(texts ? {texts, textIndex: node.widgets.findIndex(w => w.name === 'text')} : {})}); @@ -3167,12 +3196,15 @@ export function openStudio(node, {extendFrom = null} = {}) { // length is made in parts. const longest = () => { try { const one = lengthControl?.absent ? null : lengthControl?.options().singleLimit; return one > 0 ? Math.max(5, Math.floor(one) * 8) : 60; } catch { return 60; } }; // A locked length says what decides it: the audio used as is (the old field's lock shows that) or a connected node. + // The line that says a typed length was brought to the shortest or longest sits with the console's other lines. + const durationNote = fieldNote(seconds, {t, place: () => lengthWhy.isConnected ? lengthWhy : null, className: 'fv-length-why'}); const stepper = durationStepper(t, seconds, {max: longest, lockedBy: () => (!audioLock.hidden ? 'audio' : linked(node, 'seconds') ? 'linked' : null)}); seconds.addEventListener('change', () => { const n = Number(seconds.value), most = longest(), least = 2; if (seconds.value === '' || !Number.isFinite(n) || seconds.disabled) return; - if (most > 0 && n > most) seconds.value = String(most); else if (n < least) seconds.value = String(least); + if (most > 0 && n > most) { seconds.value = String(most); durationNote.say(t(`At most ${most} s`, `最长 ${most} 秒`)); } + else if (n < least) { seconds.value = String(least); durationNote.say(t(`At least ${least} s`, `最短 ${least} 秒`)); } }, true); const stepValue = stepper.element.querySelector('.fvs-step-value'); const paintDuration = () => { diff --git a/web/studio_length.js b/web/studio_length.js index 073eb102..75df6879 100644 --- a/web/studio_length.js +++ b/web/studio_length.js @@ -1,5 +1,6 @@ import {capabilityPoints, interpolate} from './chain_support.js'; import {issueButton} from './issue_button.js'; +import {fieldNote} from './field_note.js'; import {buildPlanRequest, readLengthPlan, classifyPlanError, singleLimitSeconds, defaultBlockSeconds} from './length_plan.js?v=20261027-length'; export const LENGTH_PROPERTIES = Object.freeze({seconds: 'freevideo_seconds', single: 'freevideo_single', block: 'freevideo_block_seconds'}); @@ -28,7 +29,8 @@ export async function readLengthCapability(api, context, signal, onReply = () => // onEditor and onAutopilot are the creation panel's own view-switch actions; autopilot says whether that tab shows. export function createStudioLength({api, node, seconds, advanced, fields, t, field, setSeconds, onChange = () => {}, capability = readLengthCapability, delay = 220, capabilityTimeout = 10000, - onEditor = () => {}, onAutopilot = () => {}, autopilot = false, promptModel = null}) { + onEditor = () => {}, onAutopilot = () => {}, autopilot = false, promptModel = null, + settleSeconds = () => seconds.checkValidity()}) { // Writing a value an element already has still wakes every observer, so only real changes are written. const put = (target, key, value) => { if (target[key] !== value) target[key] = value; }; const el = (tag, cls, text) => { const e = document.createElement(tag); if (cls) e.className = cls; if (text) e.textContent = text; return e; }; @@ -172,7 +174,9 @@ export function createStudioLength({api, node, seconds, advanced, fields, t, fie function schedule() { const version = revision; timer = setTimeout(() => { timer = null; pending = calculate(version); }, delay); } single.onchange = () => { remember(LENGTH_PROPERTIES.single, single.checked); edited = true; invalidate(); schedule(); }; block.oninput = () => { edited = blockEdited = true; invalidate(); schedule(); }; - block.onchange = () => { if (block.reportValidity()) remember(LENGTH_PROPERTIES.block, Number(block.value)); }; + // A part length past its range becomes its end, and the line under the field says so. + const blockNote = fieldNote(block, {t}); + block.onchange = () => { if (blockNote.settle()) remember(LENGTH_PROPERTIES.block, Number(block.value)); }; reset.onclick = () => { delete node.properties[LENGTH_PROPERTIES.block]; node.graph?.change(); submitted = false; planLimits = limits; @@ -181,7 +185,8 @@ export function createStudioLength({api, node, seconds, advanced, fields, t, fie const input = () => { submitted = false; planLimits = limits; edited = false; invalidate(); schedule(); }; seconds.addEventListener('input', input); function commit({report = true, exact = false} = {}) { - const valid = report ? seconds.reportValidity() : seconds.checkValidity(); + // Reported: a length out of range is brought in and said in the console's line (settleSeconds). + const valid = report ? settleSeconds() : seconds.checkValidity(); if (!seconds.value || !valid) return false; const value = !exact && total() > 30 ? Math.round(total()) : total(); seconds.value = value; if (value > 60) remember(LENGTH_PROPERTIES.seconds, value); diff --git a/web/studio_stage.js b/web/studio_stage.js index 0e62e956..e407a8eb 100644 --- a/web/studio_stage.js +++ b/web/studio_stage.js @@ -1,6 +1,7 @@ // The bar under the picture: what the picture is and where it sits in the history on the left, what can be done // with it on the right. The run's numbers and notes fold into Details, so the bar keeps one line and the picture // never moves when a note arrives. +import { cutTip } from './cut_tip.js'; import {tip} from './studio_console.js'; const el = (tag, cls, text) => { const e = document.createElement(tag); if (cls) e.className = cls; if (text != null) e.textContent = text; return e; }; @@ -71,7 +72,7 @@ export function createStageBar(t, {details = [], onStep = () => {}}) { if (parts?.length) summaryMeta.replaceChildren(...parts.map(part => { const block = el('span', 'fvs-summary-part', part.text); block.dataset.part = part.key; return block; })); else summaryMeta.textContent = text || ''; summaryMeta.hidden = !text; fitFacts(); - summary.title = full || [name, text].filter(Boolean).join(' · '); + cutTip(summary, full || [name, text].filter(Boolean).join(' · '), summary, {always: !!full}); }, setHistory(index, count) { history.hidden = !(count > 1) || index < 0; diff --git a/web/task_float.js b/web/task_float.js index da303071..5cdf2a3a 100644 --- a/web/task_float.js +++ b/web/task_float.js @@ -728,7 +728,7 @@ export function installTaskFloat() { // window's card has its own name so its glass can arrive 60 ms late. Names last one switch. const SHARED = 'fv-task-pic', CARD = 'fv-task-card'; let shared = null; // {mode: 'collapse'|'expand', view, picture} - const switching = () => typeof document.startViewTransition === 'function' && !calm(); + const switching = () => typeof document.startViewTransition === 'function' && document.documentElement.dataset.fvTransitions !== 'off' && !calm(); const root = document.documentElement; function clearShared() { if (!shared) return; diff --git a/web/theme.css b/web/theme.css index a9d9334d..9dfaf0a8 100644 --- a/web/theme.css +++ b/web/theme.css @@ -60,7 +60,8 @@ .fv-select[data-hx-seldis]::after{opacity:.5} .fv-select[data-hx-selhid]{display:none} .fv-select-menu-host>.fv-select-native{position:absolute;inset:0;opacity:0;pointer-events:none} -.fv-select-menu-host>.fv-select-trigger{display:flex;align-items:center;width:100%;max-width:100%;min-height:var(--fv-h-sm,32px);padding:4px 34px 4px 10px;border:1px solid var(--fv-border);border-radius:var(--fv-r-sm,8px);background:var(--fv-raised);color:var(--fv-ink);font:inherit;text-align:left;cursor:pointer} +/* The name reads from the left like any field; .fv-studio button would otherwise centre it. */ +.fv-select-menu-host>.fv-select-trigger{display:flex;align-items:center;justify-content:flex-start;width:100%;max-width:100%;min-height:var(--fv-h-sm,32px);padding:4px 34px 4px 10px;border:1px solid var(--fv-border);border-radius:var(--fv-r-sm,8px);background:var(--fv-raised);color:var(--fv-ink);font:inherit;text-align:left;cursor:pointer} .fv-select-menu-host>.fv-select-trigger:hover:not(:disabled){background:var(--fv-hover)}.fv-select-menu-host>.fv-select-trigger:disabled{opacity:.5;cursor:default} .fv-select-face{min-width:0;overflow:hidden;text-overflow:ellipsis;white-space:nowrap} .fv-select-menu{position:fixed;z-index:60;box-sizing:border-box;max-width:calc(100vw - 16px);overflow:auto;padding:6px;background:var(--fv-card);color:var(--fv-ink);border:1px solid var(--fv-border);border-radius:var(--fv-r-sm);font:13px var(--fv-font)} diff --git a/web/tip_words.js b/web/tip_words.js new file mode 100644 index 00000000..3cf0cc31 --- /dev/null +++ b/web/tip_words.js @@ -0,0 +1,17 @@ +// Hover and focus help words on any element: the page-wide tooltip (tooltip.js) reads the data-fv-tip-* attributes this +// writes, and the browser's own title is dropped so two tips never show at once. No DOM work happens at import time. +// Kept apart from the editor's tip catalogue (editor_tracks_tips.js) so the pages loaded first need none of the editor. +export function setTip(element, {name = '', use = '', key = '', why = ''} = {}) { + if (!element) return element; + // Writes only what changed: the transport refreshes on every playback frame. + // (Plain lookups only, so the small test DOM is enough.) + const read = attribute => element.getAttribute?.(attribute) ?? null; + const set = (attribute, value) => { + if (value) { if (read(attribute) !== value) element.setAttribute(attribute, value); } + else if (read(attribute) != null) element.removeAttribute?.(attribute); + }; + set('data-fv-tip-name', name); set('data-fv-tip-use', use); set('data-fv-tip-key', key); set('data-fv-tip-why', why); + // An empty title, never a stale one: the browser's own tip must not show next to this one. + if (element.title !== '') element.title = ''; + return element; +} diff --git a/web/tooltip.css b/web/tooltip.css index 71095243..cb2e8baa 100644 --- a/web/tooltip.css +++ b/web/tooltip.css @@ -2,8 +2,7 @@ It fades in (160 ms, eased out, 2 px towards its place) and out; under reduced motion it only appears. */ .fv-tip{position:fixed;inset:auto;left:0;top:0;margin:0;box-sizing:border-box;width:max-content;max-width:min(320px,calc(100vw - 16px)); padding:var(--fv-sp-8,8px) var(--fv-sp-12,12px);border:1px solid var(--fv-edge);border-radius:var(--fv-rad-ctl,12px); - background:rgb(var(--fv-tint) / var(--fv-a3));color:var(--fv-fg);box-shadow:inset 0 1px 0 var(--fv-edge-hi),var(--fv-sh2); - -webkit-backdrop-filter:blur(var(--fv-glass-blur2)) saturate(165%);backdrop-filter:blur(var(--fv-glass-blur2)) saturate(165%); + background:rgb(var(--fv-solid3));color:var(--fv-fg);box-shadow:inset 0 1px 0 var(--fv-edge-hi),var(--fv-sh2); font:var(--fv-fs-1,12px)/var(--fv-lh,1.45) var(--fv-font,system-ui,sans-serif);white-space:normal;overflow-wrap:anywhere; text-align:left;pointer-events:none;-webkit-user-select:none;user-select:none;z-index:var(--fv-z-tip,3000);overflow:visible; opacity:0;transition:opacity var(--fv-dur-1,160ms) var(--fv-ease-out,ease-out),translate var(--fv-dur-1,160ms) var(--fv-ease-out,ease-out)} @@ -23,8 +22,4 @@ /* A disabled control: why, and what to do; calm, not an error. */ .fv-tip-off{margin-top:var(--fv-sp-2,2px);color:var(--fv-caution,var(--fv-fg))} .fv-tip[data-state=off] .fv-tip-name{color:var(--fv-fg2)} -/* Solid when glass is off, unsupported, or transparency is reduced. */ -:is(:root[data-glass=solid],:root.lite) .fv-tip{-webkit-backdrop-filter:none;backdrop-filter:none;background:rgb(var(--fv-solid3))} -@media(prefers-reduced-transparency:reduce){.fv-tip{-webkit-backdrop-filter:none!important;backdrop-filter:none!important;background:rgb(var(--fv-solid3))!important}} -@supports not ((backdrop-filter:blur(1px)) or (-webkit-backdrop-filter:blur(1px))){.fv-tip{background:rgb(var(--fv-solid3))}} @media (forced-colors:active){.fv-tip{border-color:CanvasText;background:Canvas;color:CanvasText}} diff --git a/web/tutorial_book_content.js b/web/tutorial_book_content.js index 0cd63c90..75c55712 100644 --- a/web/tutorial_book_content.js +++ b/web/tutorial_book_content.js @@ -82,12 +82,12 @@ export const TUTORIAL_CHAPTERS = [ alt: {zh: '图像视图:描述框、比例与清晰度、“生成”和图片下方的“⋯”已用红框标出。', en: 'The Images view, with the prompt, the shape and clarity, "Generate" and the "⋯" below the picture outlined in red.'}, }, steps: { - zh: ['点顶部的“图像视图”。', '在“描述画面”中写下主体、场景和风格;图中要出现的文字,用引号写出原文。', '在“画幅与尺寸”中选择比例,再在“尺寸”中选择“4M”(约 400 万像素)或“16M”(约 1600 万像素)。显存为 8 GB 的显卡,选“4M”。', '点“生成”。图片显示在中间,并加入右侧的作品列表;图片下方一行写明生成它的模型、尺寸和比例。用图片下方一行的图标下载、打开文件夹或复制提示词。', '在“AI 全自动”中,连接助手 后说“画一张……”,助手只生成图片,不生成视频;完成后点“打开”查看,点“下载”保存。'], - en: ['Choose "Images" at the top.', 'In "Describe the picture", write the subject, the place and the style. Put any words that should appear in the picture in quotation marks, exactly as written.', 'Under "Frame & size", choose the shape, then choose "4M" (about 4 megapixels) or "16M" (about 16 megapixels) under "Size". On a graphics card with 8 GB of memory, choose "4M".', 'Choose "Generate". The picture appears in the middle and is added to the works on the right. The line below it names the model that made it, with its size and shape. Use the icons in the line below it to download it, open its folder or copy the prompt.', 'In Autopilot, connect an assistant and say "Draw a picture of …". The assistant makes only the picture, not a video. When it finishes, choose "Open" to view it and "Download" to save it.'], + zh: ['点顶部的“图像视图”。', '在“描述画面”中写下主体、场景和风格;图中要出现的文字,用引号写出原文。', '在“画幅与尺寸”中选择比例,再在“尺寸”中选择“4M”(约 400 万像素)或“16M”(约 1600 万像素)。显存为 8 GB 的显卡,选“4M”。', '点“生成”。图片显示在中间,并加入右侧的作品列表;图片下方一行写明生成它的模型、尺寸和比例。用图片下方一行的图标下载、打开文件夹或复制提示词。图片也会另存一份到 output 文件夹,在“设置”中可以关闭。', '在“AI 全自动”中,连接助手 后说“画一张……”,助手只生成图片,不生成视频;完成后点“打开”查看,点“下载”保存。'], + en: ['Choose "Images" at the top.', 'In "Describe the picture", write the subject, the place and the style. Put any words that should appear in the picture in quotation marks, exactly as written.', 'Under "Frame & size", choose the shape, then choose "4M" (about 4 megapixels) or "16M" (about 16 megapixels) under "Size". On a graphics card with 8 GB of memory, choose "4M".', 'Choose "Generate". The picture appears in the middle and is added to the works on the right. The line below it names the model that made it, with its size and shape. Use the icons in the line below it to download it, open its folder or copy the prompt. A copy of the picture is also saved to the output folder; this can be switched off in Settings.', 'In Autopilot, connect an assistant and say "Draw a picture of …". The assistant makes only the picture, not a video. When it finishes, choose "Open" to view it and "Download" to save it.'], }, limits: { - zh: ['未安装图像模型时,“生成”显示为“下载模型”,点它下载;和视频共用的文件不重复下载。', '加参考图见“用参考图生成图片”。', '“高清”用时更长;显存不足时,出错卡片上可点“改用标准并重试”。'], - en: ['Without a picture model installed, "Generate" reads "Download model"; choose it to download. Files shared with video are not downloaded again.', 'For reference pictures, see "Make a picture from reference pictures".', '"High" takes longer. If memory runs short, choose "Retry at Standard" on the error card.'], + zh: ['未安装图像模型时,“生成”显示为“下载模型”,点它下载;和视频共用的文件不重复下载。', '加参考图见“用参考图生成图片”。选 MOSS 时,点描述框下方的“布局”,在画框上拖出框,每个框写一句放什么。框管位置和大致大小,不会把东西拉伸到填满框。', '“高清”用时更长;显存不足时,出错卡片上可点“改用标准并重试”。'], + en: ['Without a picture model installed, "Generate" reads "Download model"; choose it to download. Files shared with video are not downloaded again.', 'For reference pictures, see "Make a picture from reference pictures". When MOSS is selected, choose "Layout" below the description, drag boxes on the frame and write what goes in each one. A box sets where a thing goes and roughly how big it is; it does not stretch the thing to fill the box.', '"High" takes longer. If memory runs short, choose "Retry at Standard" on the error card.'], }, }, { @@ -752,12 +752,12 @@ export const TUTORIAL_CHAPTERS = [ alt: {zh: '“作品库”:第一条作品已用红框标出。', en: 'Your creations, with the first video outlined in red.'}, }, steps: { - zh: ['点预览下方最近作品开头的“作品库”。', '选择一条视频,可播放,或点“接着生成”在剪辑视图中继续。', '在作品详情中点爱心图标收藏;列表上方选“收⁠藏”只看收藏的作品,选“全⁠部”看所有作品。', '需要成片时,在“剪辑视图”点“导⁠出”。', '在导出窗口选择范围、画质和内容,再点“导⁠出”。'], - en: ['Choose "Creations" at the start of the recent videos below the preview.', 'Pick a video to play it, or choose "Continue" to continue it in the Edit view.', 'In a creation\'s details, choose the heart to add it to favorites. Above the list, choose "Favorites" to see only those, or "All" to see every creation.', 'For a finished file, choose "Export" in the Edit view.', 'In the export window choose the range, quality and content, then choose "Export".'], + zh: ['点预览下方最近作品开头的“作品库”。', '选择一条视频,可播放,或点“接着生成”在剪辑视图中继续。', '在作品详情中点爱心图标收藏;列表上方选“收⁠藏”只看收藏的作品,选“全⁠部”看所有作品。', '需要成片时,在“剪辑视图”点“导⁠出”。', '在导出窗口选择范围、画质和内容;要更流畅的画面时,在“帧率”中选 48 或 60,中间的画面由显卡补出。再点“导⁠出”。'], + en: ['Choose "Creations" at the start of the recent videos below the preview.', 'Pick a video to play it, or choose "Continue" to continue it in the Edit view.', 'In a creation\'s details, choose the heart to add it to favorites. Above the list, choose "Favorites" to see only those, or "All" to see every creation.', 'For a finished file, choose "Export" in the Edit view.', 'In the export window choose the range, quality and content. For smoother motion, choose 48 or 60 under "Frame rate"; the graphics card makes the frames in between. Then choose "Export".'], }, limits: { - zh: ['删除作品前会确认;被剪辑使用的作品不能删除。', '导出窗口每次打开时,“内容”默认选“画面和声音”,“画质”默认选“高”。', '导出过程中取消不会留下不完整的文件。'], - en: ['FreeVideo asks before deleting a video, and a video used in an edit cannot be deleted.', 'The export window always opens with "Video and audio" as the content and "High" as the quality.', 'Cancelling an export leaves no unfinished file.'], + zh: ['删除作品前会确认;被剪辑使用的作品不能删除。', '导出窗口每次打开时,“内容”默认选“画面和声音”,“画质”默认选“高”;窗口里没有“帧率”时,这台电脑不支持 48 和 60 帧导出。', '导出过程中取消不会留下不完整的文件。'], + en: ['FreeVideo asks before deleting a video, and a video used in an edit cannot be deleted.', 'The export window always opens with "Video and audio" as the content and "High" as the quality; when it has no "Frame rate", this computer cannot export at 48 or 60 fps.', 'Cancelling an export leaves no unfinished file.'], }, }, { diff --git a/web/updates.js b/web/updates.js index 9c69d59c..f5a4b9f1 100644 --- a/web/updates.js +++ b/web/updates.js @@ -328,7 +328,7 @@ export function createUpdateNotice(cn) { element.hidden = !text; element.classList.toggle('fv-update-working', busy); label.textContent = text; - if (reason) label.title = reason; else label.removeAttribute('title'); + label.removeAttribute('title'); if (reason) label.setAttribute('data-fv-tip-name', reason); else label.removeAttribute('data-fv-tip-name'); // A cause that does not fit leaves only the prefix; the tooltip still has it. const fit = () => { if (cause && label.textContent === text && label.scrollWidth > label.clientWidth + 1) label.textContent = short; }; if (cause) { fit(); globalThis.requestAnimationFrame?.(fit); }