From bc83800911f654be6ec33a4226212303abd8a724 Mon Sep 17 00:00:00 2001 From: Bowen Xue Date: Wed, 25 Nov 2026 01:42:28 +0000 Subject: [PATCH 01/12] Engine: record what every thread was doing when the event loop stops answering, and ignore a gap... Engine: record what every thread was doing when the event loop stops answering, and ignore a gap in the watchdog's own ticks --- freevideo_engine/comfy_launcher_api.py | 9 + freevideo_engine/loop_stall.py | 241 +++++++++++++++++++++++++ freevideo_engine/support_report.py | 9 + web/engine_exit.js | 22 +++ web/error_panel.js | 4 +- web/failure_issue.js | 4 +- web/studio.js | 4 +- 7 files changed, 288 insertions(+), 5 deletions(-) create mode 100644 freevideo_engine/loop_stall.py diff --git a/freevideo_engine/comfy_launcher_api.py b/freevideo_engine/comfy_launcher_api.py index 952f5acc..ac301ee7 100644 --- a/freevideo_engine/comfy_launcher_api.py +++ b/freevideo_engine/comfy_launcher_api.py @@ -156,6 +156,15 @@ def register(): async def launcher(request): return web.json_response(info) + # Observes the event loop only: when it stops answering for five seconds, what every thread was doing is written down once. + from . import loop_stall + server._freevideo_loop_watchdog = loop_stall.install(getattr(server, 'loop', None), info['engine_root']) + + @server.routes.get('/freevideo/launcher/loop-stalls') + async def loop_stalls(request): + """The latest times the engine's loop was held up: when, how long, the loop thread's innermost calls.""" + return web.json_response(dict(stalls=loop_stall.public(loop_stall.read(info['engine_root']))), headers={'Cache-Control': 'no-store'}) + @server.routes.get('/freevideo/launcher/last-exit') async def last_exit(request): """When the ComfyUI before this one stopped by itself: numbers and fixed words, never log text.""" diff --git a/freevideo_engine/loop_stall.py b/freevideo_engine/loop_stall.py new file mode 100644 index 00000000..4d53f322 --- /dev/null +++ b/freevideo_engine/loop_stall.py @@ -0,0 +1,241 @@ +"""A record of the moments when the engine's event loop stopped answering. + +The page, the launcher and every request go through one event loop. When it is +held up (a long call on it, a lock another thread keeps, a computer that pages +heavily) the engine looks stopped from outside, and afterwards nothing says +where the time went. The watchdog only observes: a small thread posts a ping to +the loop once a second. A ping that is not answered within five seconds starts a +stall; the calls of every thread at that moment are written to a small file, once +per stall, and the length is added when the loop answers again. It changes +nothing about how requests are handled and does not touch placement, memory or +the GPU. + +The file lives next to the launcher's other records, is capped in size and keeps +only function names, line numbers and file names (every folder is replaced by +````), never source lines, arguments or values. +""" +import json +import math +import os +import sys +import threading +import time +import traceback + +from .long_paths import ABSOLUTE_PATH, io_path, path_match, path_placeholder +from .monitoring import save + +FILE = 'loop-stalls.json' +INTERVAL = 1.0 +THRESHOLD = 5.0 +MAX_BYTES = 48 * 1024 +MAX_RECORDS = 8 +MAX_THREADS = 24 +MAX_FRAMES = 14 +TEXT_CHARS = 120 +SWITCH = 'FREEVIDEO_LOOP_WATCHDOG' +PUBLIC_RECORDS = 2 +PUBLIC_FRAMES = 5 + + +def location(engine): + return io_path(engine) / 'launcher' / FILE + + +def enabled(environment=None): + """Off only when the switch is set to 0, so that a run can be compared with and without it.""" + return str((os.environ if environment is None else environment).get(SWITCH, '1')).strip() != '0' + + +def _text(value): + return str(value).replace('\r', ' ').replace('\n', ' ')[:TEXT_CHARS] + + +def _folderless(value): + """Text of a stored field with any folder in it replaced by .""" + return ABSOLUTE_PATH.sub(path_match, _text(value)) + + +def frames_of(frame, limit=MAX_FRAMES): + """The innermost calls of one thread, outermost first: ``/file.py:12 function``.""" + rows = [f'{path_placeholder(item.filename)}:{item.lineno} {_text(item.name)}' for item in traceback.extract_stack(frame)] + return rows[-limit:] + + +def snapshot(frames, names, loop_ident, skip, *, threads=MAX_THREADS, depth=MAX_FRAMES): + """Every thread's calls, the loop's thread first; the watchdog's own thread is left out.""" + rows = [] + for ident, frame in frames.items(): + if ident == skip: + continue + rows.append(dict(name=_text(names.get(ident, 'unknown')), loop=ident == loop_ident, frames=frames_of(frame, depth))) + rows.sort(key=lambda row: not row['loop']) + return rows[:threads] + + +def _fits(records): + return len(json.dumps(dict(stalls=records), ensure_ascii=False, indent=2).encode('utf-8')) <= MAX_BYTES + + +def capped(records): + """The newest records that fit the size cap: older ones go first, then the other threads' calls of the newest.""" + records = list(records)[-MAX_RECORDS:] + while len(records) > 1 and not _fits(records): + records.pop(0) + last = records[-1] if records else None + for threads, depth in ((MAX_THREADS, 8), (6, 6), (1, 6), (0, 0)): + if _fits(records) or last is None: + break + last['threads'] = [dict(row, frames=row['frames'][-depth:]) for row in last['threads'][:threads]] if depth else [] + return records if _fits(records) else [] + + +def sanitized(rows): + """Only the known fields, with their types, lengths and counts held and any folder replaced: a file that was edited + or damaged can never put anything else into a report.""" + result = [] + for row in rows if isinstance(rows, list) else (): + if not isinstance(row, dict): + continue + at, seconds = row.get('at'), row.get('seconds') + if type(at) not in (int, float) or type(seconds) not in (int, float) or not math.isfinite(at) or not math.isfinite(seconds): + continue + threads = [] + for item in (row.get('threads') if isinstance(row.get('threads'), list) else ())[:MAX_THREADS]: + if not isinstance(item, dict): + continue + calls = [_folderless(call) for call in (item.get('frames') if isinstance(item.get('frames'), list) else ()) + if isinstance(call, str)][-MAX_FRAMES:] + threads.append(dict(name=_folderless(item.get('name', '')), loop=item.get('loop') is True, frames=calls)) + result.append(dict(at=at, seconds=seconds, recovered=row.get('recovered') is True, threads=threads)) + return capped(result) + + +def read(engine): + """The stored records, oldest first, as sanitized(); none when the file is missing or cannot be read.""" + try: + value = json.loads(location(engine).read_text(encoding='utf-8')) + except (OSError, ValueError, TypeError): + return [] + return sanitized(value.get('stalls') if isinstance(value, dict) else None) + + +def public(records, *, count=PUBLIC_RECORDS, frames=PUBLIC_FRAMES): + """What goes into a feedback message: when, how long and the loop thread's innermost calls. Strings only as stored.""" + result = [] + for row in reversed(records or []): + at, seconds = row.get('at'), row.get('seconds') + if type(at) not in (int, float) or not math.isfinite(at) or type(seconds) not in (int, float) or not math.isfinite(seconds): + continue + loop = next((item for item in row.get('threads') or () if isinstance(item, dict) and item.get('loop')), None) + calls = [_text(call) for call in (loop or {}).get('frames') or () if isinstance(call, str)][-frames:] + result.append(dict(at=at, seconds=seconds, recovered=row.get('recovered') is True, loop=calls)) + if len(result) >= count: + break + return result + + +class Watchdog: + def __init__(self, loop, path, *, records=(), threshold=THRESHOLD, interval=INTERVAL, clock=time.monotonic, wall=time.time, + frames=sys._current_frames, names=None): + self.loop, self.path, self.records = loop, path, list(records) + self.threshold, self.interval = threshold, interval + self.clock, self.wall, self.frames = clock, wall, frames + self.names = names or (lambda: {thread.ident: thread.name for thread in threading.enumerate()}) + self.lock = threading.Lock() + self.pending = None # when the unanswered ping was posted + self.loop_ident = None + self.answered = None # when the loop last answered + self.open = None # the record of the stall in progress + self.started = None # when the ping of that stall was posted + self.last_tick = None + self.stop_event = threading.Event() + self.thread = None + + def start(self): + if self.thread is None: + self.thread = threading.Thread(target=self.run, name='freevideo-loop-watchdog', daemon=True) + self.thread.start() + return self + + def stop(self): + self.stop_event.set() + + def pong(self): + """Runs on the loop: it answered.""" + with self.lock: + self.loop_ident = threading.get_ident() + self.answered = self.clock() + self.pending = None + + def run(self): + while not self.stop_event.wait(self.interval): + try: + if not self.tick(): + return + except Exception: + # The watchdog never takes the engine down; the next tick tries again. + continue + + def tick(self): + """One check; False once the loop is gone.""" + if self.loop.is_closed(): + return False + if not self.loop.is_running(): + with self.lock: + self.pending = None + return True + now = self.clock() + gap, self.last_tick = (None if self.last_tick is None else now - self.last_tick), now + if gap is not None and gap >= self.threshold: + # This thread itself did not run for that long (the computer slept, or a call held every thread): what it + # would record is not a stall of the loop, so start again without writing anything. + with self.lock: + self.pending, self.open, self.started = None, None, None + return True + with self.lock: + pending, answered, opened, started = self.pending, self.answered, self.open, self.started + if pending is None: + self.pending = now + if pending is None: + if opened is not None: + self.close(opened, started, answered) + try: + self.loop.call_soon_threadsafe(self.pong) + except RuntimeError: + return False + elif opened is None and now - pending >= self.threshold: + self.begin(pending, now) + return True + + def begin(self, posted, now): + """The ping has gone unanswered for the threshold: write down what every thread is doing, once.""" + with self.lock: + ident = self.loop_ident + record = dict(at=round(self.wall() - (now - posted), 3), seconds=round(now - posted, 1), recovered=False, + threads=snapshot(self.frames(), self.names(), ident, threading.get_ident())) + with self.lock: + self.open, self.started = record, posted + self.write(record) + + def close(self, record, posted, answered): + """The loop answered again: add how long it was held up.""" + with self.lock: + self.open = self.started = None + record['recovered'] = True + record['seconds'] = round(max(record['seconds'], (answered or posted) - posted), 1) + self.write(record) + + def write(self, record): + try: + self.records = capped([row for row in self.records if row is not record] + [record]) + save(self.path, dict(stalls=self.records), plain_paths=False) + except Exception: + pass + + +def install(loop, engine, **options): + """Start the watchdog for the engine's loop, unless the switch turned it off. Returns it, or None.""" + if loop is None or not enabled(): + return None + return Watchdog(loop, location(engine), records=read(engine), **options).start() diff --git a/freevideo_engine/support_report.py b/freevideo_engine/support_report.py index f9c1019f..8507478d 100644 --- a/freevideo_engine/support_report.py +++ b/freevideo_engine/support_report.py @@ -665,6 +665,15 @@ def clean(value, key=''): cleaned['engine_exit'] = stopped except Exception: pass + try: + # When the engine's event loop was held up: what every thread was doing (file names, lines and functions only). + from .comfy_bridge import installation_root + from .loop_stall import read as read_stalls + stalls = read_stalls(installation_root()) + if stalls: + cleaned['loop_stalls'] = stalls + except Exception: + pass save(target, cleaned) return target except Exception: diff --git a/web/engine_exit.js b/web/engine_exit.js index ffc43e47..e3a96db4 100644 --- a/web/engine_exit.js +++ b/web/engine_exit.js @@ -48,3 +48,25 @@ export function engineExitText(record, t = en => en) { return t(`The engine stopped unexpectedly at ${clock(record.at)} and has been restarted.`, `引擎于 ${clock(record.at)} 意外停止,已重新启动。`); } + +// When the engine's loop was held up: times, lengths and the loop thread's innermost calls, as written by the engine +// (file names and functions only). A feedback message carries what the page has read; the page reads it once at load +// and again when a lost connection comes back, since a silent engine cannot be asked. +let stalls = []; + +async function loadStalls(api) { + try { + const response = await api.fetchApi('/freevideo/launcher/loop-stalls', {cache: 'no-store'}); + if (!response.ok) return; + const rows = (await response.json())?.stalls; + stalls = Array.isArray(rows) ? rows.filter(row => row && Number.isFinite(row.at) && Number.isFinite(row.seconds)) + .slice(0, 2).map(row => ({at: row.at, seconds: row.seconds, recovered: row.recovered === true, + loop: (Array.isArray(row.loop) ? row.loop : []).filter(call => typeof call === 'string').slice(-5).map(call => call.slice(0, 120))})) : []; + } catch { /* The report only loses these facts. */ } +} + +/** Read the engine's record of held-up moments; never throws. */ +export function refreshLoopStalls(api) { return loadStalls(api); } + +/** The newest records this page has read, for a feedback message; empty when there are none. */ +export function knownLoopStalls() { return stalls; } diff --git a/web/error_panel.js b/web/error_panel.js index a4394c27..e8fcc101 100644 --- a/web/error_panel.js +++ b/web/error_panel.js @@ -4,7 +4,7 @@ import {pageRepair, repairAction, repairButton} from './repair_hint.js'; import {detectBrowserExtension, browserExtensionAdvice, extensionSteps, isNetworkTypeError, connectionLostText, engineNotRunning, engineNotRunningText, engineNotResponding, engineNotRespondingText, 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'; +import {knownEngineExit, knownLoopStalls} from './engine_exit.js'; import {focusReportTip, hideReportTip, reportIssue, showReportTip} from './report_issue.js'; import { skin } from './glass/library.js'; const reports = new WeakSet(); @@ -799,7 +799,7 @@ export function createErrorPanel(t, route = null) { const openFeedback = async () => { if (!issueModules) await loadIssueModules(); if (!issueModules) return; - const draft = failureIssue(currentReport, element.freevideoKind, {lora: githubLora, t, engineExit: knownEngineExit()}); + const draft = failureIssue(currentReport, element.freevideoKind, {lora: githubLora, t, engineExit: knownEngineExit(), loopStalls: knownLoopStalls()}); const url = issueModules.feedback.feedbackIssueURL(draft.text, issueModules.updates.productVersion(), draft.summary, draft.title); globalThis.open?.(url, '_blank', 'noopener'); }; diff --git a/web/failure_issue.js b/web/failure_issue.js index d48507e1..2c70f686 100644 --- a/web/failure_issue.js +++ b/web/failure_issue.js @@ -43,7 +43,7 @@ function cause(report) { /** Title, text and summary for the prefilled issue. `lora` marks a LoRA the check judged wrongly; `engineExit` is the * record of the engine's last unexpected stop, when the launcher saw one. */ -export function failureIssue(report, kind, {lora = false, t = en => en, engineExit = null} = {}) { +export function failureIssue(report, kind, {lora = false, t = en => en, engineExit = null, loopStalls = []} = {}) { const stage = failureStage(report); const lines = String(report?.message || '').split(/\r?\n/).filter(line => line.trim()); // A traceback ends with the line that names the error; any other message starts with it. @@ -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, frontend_version: report?.frontend_version, run, tail: cause(report)}); + engine_exit: engineExit || undefined, loop_stalls: loopStalls?.length ? loopStalls : 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/studio.js b/web/studio.js index 3b5d92cc..d266d917 100644 --- a/web/studio.js +++ b/web/studio.js @@ -27,7 +27,7 @@ import { createUpscaleOffer, upscaleChoices, UPSCALE_USE, UPSCALE_QUEUED, UPSCAL import { createRecentVideos } from './studio_recent.js'; import { createStudioQueue, randomSeed, turnNodeOn } from './studio_queue.js'; import { isNetworkTypeError, connectionLostText, wrappedFetchOnly } from './browser_extension.js'; -import { newEngineExit, engineExitText, watchEngineExit } from './engine_exit.js'; +import { newEngineExit, engineExitText, watchEngineExit, refreshLoopStalls } from './engine_exit.js'; import { attachReferencePicker, referenceItems, enhancementMedia, syncReferencePrompt, referenceInputs, mentionAt, handleNames, mediaRows } from './prompt_references.js'; import { attachTermSuggest } from './prompt_terms.js'; import { problem as timedProblem, timedText, parse as timedParse } from './timed_prompt.js'; @@ -2437,6 +2437,7 @@ export function openStudio(node, {extendFrom = null} = {}) { }[error?.message] || (error?.said ? t(error.said[0], error.said[1]) : null) || userMessage(error, t)); let lastQueueError = null, connectionNotice = false; watchEngineExit(api).catch(() => {}); + refreshLoopStalls(api); function showQueueError(error) { if (disposed) return; status.dataset.error = 'true'; @@ -2469,6 +2470,7 @@ export function openStudio(node, {extendFrom = null} = {}) { newEngineExit(api).then(record => { if (record && !disposed && !status.textContent) status.textContent = engineExitText(record, t); }).catch(() => {}); + refreshLoopStalls(api); } // A part that did not start says so on its own line; what the server said goes in the card, with a report. function showChainActionError(error) { From 6791c93954069ff10e70f2f59b9a9d322cf7827e Mon Sep 17 00:00:00 2001 From: Bowen Xue Date: Wed, 25 Nov 2026 01:43:27 +0000 Subject: [PATCH 02/12] Video encoding: a fixed libx264 thread count, so the file does not depend on how many CPUs the... Video encoding: a fixed libx264 thread count, so the file does not depend on how many CPUs the computer has --- freevideo_engine/agent/media.py | 3 +- freevideo_engine/chain_join.py | 8 ++-- freevideo_engine/decode.py | 2 +- freevideo_engine/frame_upscale.py | 4 +- freevideo_engine/macos_decode.py | 2 +- freevideo_engine/video_threads.py | 69 +++++++++++++++++++++++++++++++ 6 files changed, 80 insertions(+), 8 deletions(-) create mode 100644 freevideo_engine/video_threads.py diff --git a/freevideo_engine/agent/media.py b/freevideo_engine/agent/media.py index 502ca4f8..1c0b7048 100644 --- a/freevideo_engine/agent/media.py +++ b/freevideo_engine/agent/media.py @@ -5,6 +5,7 @@ from pathlib import Path import uuid +from .. import video_threads from ..comfy_assets import media_kind_of FPS = 24 @@ -248,7 +249,7 @@ def emit(writer, stream, array, sound, limit): progress(dict(done=written, total=total)) try: with av.open(str(temporary), 'w', format='mp4', options={'movflags': 'faststart'}) as writer: - stream = writer.add_stream('libx264', rate=FPS) + stream = video_threads.pin(writer.add_stream('libx264', rate=FPS)) stream.width, stream.height, stream.pix_fmt = width, height, 'yuv420p' stream.options = dict(VIDEO_OPTIONS) sound = _Audio(writer, rate) if rate else None diff --git a/freevideo_engine/chain_join.py b/freevideo_engine/chain_join.py index c76f82bf..9bac285c 100644 --- a/freevideo_engine/chain_join.py +++ b/freevideo_engine/chain_join.py @@ -17,6 +17,8 @@ import shutil import uuid +from . import video_threads + FPS = 24 SEAM_TAIL = 12000 SEAM_HEAD = 240 @@ -110,10 +112,10 @@ def _exact_tail(source, target, wanted, cancelled=None): # Seek to the preceding key frame; only the remaining shown frames are encoded. container.seek(begin + prefix * step, stream=video, backward=True) with av.open(str(temporary), 'w', format='mp4') as output: - tail = output.add_stream('libx264', rate=FPS) + tail = video_threads.pin(output.add_stream('libx264', rate=FPS)) tail.width, tail.height, tail.pix_fmt = shape[1:4] tail.time_base = shape[4] - # decode_to_file's encode_video uses these libx264 defaults and yuv420p. + # decode_to_file's encode_video uses these libx264 defaults (and its fixed thread count) and yuv420p. encoded = 0 for frame in container.decode(video): _check(cancelled) @@ -221,7 +223,7 @@ def _conform(source, shape, directory, cancelled): video = container.streams.video[0] if abs(float(video.average_rate or 0) - FPS) > .01: return None - picture = output.add_stream('libx264', rate=FPS) + picture = video_threads.pin(output.add_stream('libx264', rate=FPS)) picture.width, picture.height, picture.pix_fmt = shape[1:4] picture.time_base = shape[4] sound = container.streams.audio[0] if container.streams.audio else None diff --git a/freevideo_engine/decode.py b/freevideo_engine/decode.py index 95045206..c4a7f364 100644 --- a/freevideo_engine/decode.py +++ b/freevideo_engine/decode.py @@ -43,7 +43,7 @@ def phase(name): wide_path.parent.mkdir(parents=True, exist_ok=True) phase('vae_load') from diffusers import AutoencoderKLMiniMaxH3 - from diffusers.utils.export_utils import encode_video + from .video_threads import encode_video from src.inference.render import PIXEL_MEAN, PIXEL_STD, FPS started = time.perf_counter() diff --git a/freevideo_engine/frame_upscale.py b/freevideo_engine/frame_upscale.py index e262cd7b..664d2f78 100644 --- a/freevideo_engine/frame_upscale.py +++ b/freevideo_engine/frame_upscale.py @@ -20,7 +20,7 @@ import tempfile import time -from . import processes +from . import processes, video_threads STAGE = 'frame_upscale' LONG_SIDE = 3840 @@ -303,7 +303,7 @@ def write(source, target, video, frame, emit, check): sound = sound_reader.streams.audio[0] if sound_reader.streams.audio else None with av.open(str(target), 'w', format='mp4', options={'movflags': 'use_metadata_tags+faststart', 'movie_timescale': '48000'}) as output: - picture_stream = output.add_stream('libx264', rate=24) + picture_stream = video_threads.pin(output.add_stream('libx264', rate=24)) picture_stream.width, picture_stream.height, picture_stream.pix_fmt = width, height, 'yuv420p' picture_stream.options = {'crf': '18', 'preset': 'fast'} audio = output.add_stream_from_template(sound) if sound is not None else None diff --git a/freevideo_engine/macos_decode.py b/freevideo_engine/macos_decode.py index f73cf8aa..71072ae8 100644 --- a/freevideo_engine/macos_decode.py +++ b/freevideo_engine/macos_decode.py @@ -54,7 +54,7 @@ def decode_to_file(latents, audio_latents, output, *, base, artifacts_dir, import torch import numpy as np from diffusers import AutoencoderKLMiniMaxH3 - from diffusers.utils.export_utils import encode_video + from .video_threads import encode_video from src.inference.render import PIXEL_MEAN, PIXEL_STD, FPS from .backends import get_backend from .vae_weights import skeleton, load_parameters, load_audio_vae diff --git a/freevideo_engine/video_threads.py b/freevideo_engine/video_threads.py new file mode 100644 index 00000000..47cb67ca --- /dev/null +++ b/freevideo_engine/video_threads.py @@ -0,0 +1,69 @@ +"""A fixed libx264 thread count, so a video's bytes do not depend on how many CPUs the process may use. + +libx264 splits its work into frame threads, and what it writes depends on how many: with the count left to the +encoder it takes the CPUs the process may use (at most 12 for a 1344x768 picture, more for a taller one), so the same frames gave a different mp4 on a computer +with 8 CPUs than on one with 48, or when a process was limited to fewer CPUs. The pictures were identical; only +the encoding differed (mean difference about 1.5 of 255). Every encode that left the count open goes through here +and gets 12. For a landscape picture of 1344x768 or smaller that is what a computer with 12 or more CPUs always +chose, so those files do not change. A taller or larger picture (768x1344, 2560x1440) lets the encoder use more than +12 threads when the computer has more than 12 CPUs (13 or more), so on such computers its file changes once, to the +fixed one. +""" +import importlib +import threading + +X264_THREADS = 12 + +_lock = threading.Lock() + + +def pin(stream, count=X264_THREADS): + """Give a libx264 stream the fixed thread count (before its first frame is encoded).""" + stream.codec_context.thread_count = count + return stream + + +class _Container: + """An output container whose libx264 streams get the fixed thread count.""" + + def __init__(self, container, count): + self._container = container + self._count = count + + def add_stream(self, codec, *args, **kwargs): + stream = self._container.add_stream(codec, *args, **kwargs) + if codec == 'libx264': + pin(stream, self._count) + return stream + + def __getattr__(self, name): + return getattr(self._container, name) + + +class _Av: + """The av module, except that av.open hands out containers as above.""" + + def __init__(self, av, count): + self._av = av + self._count = count + + def open(self, *args, **kwargs): + container = self._av.open(*args, **kwargs) + return _Container(container, self._count) if kwargs.get('mode', args[1] if len(args) > 1 else 'r') == 'w' else container + + def __getattr__(self, name): + return getattr(self._av, name) + + +def encode_video(*args, count=X264_THREADS, **kwargs): + """diffusers' encode_video with the libx264 thread count fixed; its arguments and result are unchanged.""" + export = importlib.import_module('diffusers.utils.export_utils') + original = getattr(export, '_import_av', None) + if original is None: # a library version (or a test double) that does not open the file through av + return export.encode_video(*args, **kwargs) + with _lock: + export._import_av = lambda: _Av(original(), count) + try: + return export.encode_video(*args, **kwargs) + finally: + export._import_av = original From 740cb6676c87e0db1585278d71ffaa4200c98b2d Mon Sep 17 00:00:00 2001 From: Bowen Xue Date: Wed, 25 Nov 2026 01:43:27 +0000 Subject: [PATCH 03/12] Editor: with the adjust drawer open below 1280 px, the transport keeps the time and the play... Editor: with the adjust drawer open below 1280 px, the transport keeps the time and the play controls in view --- web/editor_adjust.css | 12 ++++++++++++ 1 file changed, 12 insertions(+) diff --git a/web/editor_adjust.css b/web/editor_adjust.css index 563b5be7..3e5c7e99 100644 --- a/web/editor_adjust.css +++ b/web/editor_adjust.css @@ -47,3 +47,15 @@ .fv-ed-adjust[data-empty=false] .fv-ed-adjust-pane:not([hidden]){animation:fv-ed-adjust-in 160ms cubic-bezier(.2,.8,.2,1)} @keyframes fv-ed-adjust-in{from{opacity:0;transform:translateY(4px)}} @media(prefers-reduced-motion:reduce){.fv-ed-adjust[data-empty=false] .fv-ed-adjust-pane:not([hidden]){animation:none}} +/* Below 1280 px the panel is a drawer over the picture. While it is open the transport keeps only the time and the + play button (Iris): beside the drawer the full row runs into itself from about 900 px down; the rest comes back when + the drawer closes. A fullscreen picture has the whole screen and keeps every control. */ +@media(max-width:1279px){ + .fv-studio.fv-editor[data-adjust-open=true] .fv-ed-fullscreen-host:not(:fullscreen) .fv-ed-transport>:not(.fv-ed-time,.fv-ed-transport-center), + .fv-studio.fv-editor[data-adjust-open=true] .fv-ed-fullscreen-host:not(:fullscreen) .fv-ed-transport-center>:not(.fv-ed-play){display:none!important} /* the Media button is display:inline-flex!important up to 680 px (editor.css) */ + /* The drawer opens under the project row so the name and Export stay whole beside it (editor.css says so for the + library too; the base rule above, loaded later at the same weight, kept the drawer on the project row). */ + .fv-studio.fv-editor .fv-ed-adjust-host{grid-row:3/5} +} +/* Up to 680 px the drawer has no margin of its own: the same 8 px gap under Export as wider windows (Iris). */ +@media(max-width:680px){.fv-studio.fv-editor .fv-ed-adjust-host{margin-top:8px}} From 5267b6680fb0a6c6935788273227145b021d1d74 Mon Sep 17 00:00:00 2001 From: Bowen Xue Date: Wed, 25 Nov 2026 02:06:25 +0000 Subject: [PATCH 04/12] Prompt rewriting keeps the spoken lines of a scene written in any language --- freevideo_engine/prompt_vlm/rules.py | 57 ++++++++++++++++++++++++++-- 1 file changed, 54 insertions(+), 3 deletions(-) diff --git a/freevideo_engine/prompt_vlm/rules.py b/freevideo_engine/prompt_vlm/rules.py index 07181af7..f0dcf94e 100644 --- a/freevideo_engine/prompt_vlm/rules.py +++ b/freevideo_engine/prompt_vlm/rules.py @@ -289,9 +289,11 @@ def validate_output(text, value): # Spoken lines ------------------------------------------------------------------------------------------- # H3 reads double-quoted text as writing visible on screen; speech must be (S1) [Language] .... -QUOTES = {'\u201c': '\u201d', '\u300c': '\u300d', '\u300e': '\u300f', '"': '"', '\uff02': '\uff02'} -QUOTED = re.compile('|'.join('%s([^%s\n]{1,400})%s' % (re.escape(a), re.escape(b), re.escape(b)) - for a, b in QUOTES.items())) +# Opening and closing marks: “…” 「…」 『…』 "…" "…", and «…» „…“ „…” »…« as Russian, Ukrainian, French, German and +# others write them. +QUOTES = (('\u201c', '\u201d'), ('\u300c', '\u300d'), ('\u300e', '\u300f'), ('"', '"'), ('\uff02', '\uff02'), + ('\u00ab', '\u00bb'), ('\u201e', '\u201c'), ('\u201e', '\u201d'), ('\u00bb', '\u00ab')) +QUOTED = re.compile('|'.join('%s([^%s\n]{1,400})%s' % (re.escape(a), re.escape(b), re.escape(b)) for a, b in QUOTES)) # Verbs that end the words right before a spoken quote. Bare 叫/道/喝 also mean "named", # "road" or "drink", so only their speech compounds count; the strong verbs may be followed # by a few characters (说了一句:). @@ -335,9 +337,49 @@ def plain(words): return re.sub(r'[\W_]+', '', words).lower() +# A scene written in another language than Chinese, Japanese, Korean or English: its speech verbs are not listed above, +# so a quoted span counts as speech when it follows a colon or ends like a sentence (говорит: «…», dice: "¿…?", +# ruft: „…!“); a quoted name or sign without either (вывеска «Кафе») does not. A sign after a colon (une enseigne : +# « Café de la Gare ») is taken as speech: keeping a few words too many costs less than losing a line. +EN_WORDS = frozenset('the and of with is are was were she he his her him they their them this that from into while ' + 'for an as by its then there who which says said a in on at to it you we i be not no up down ' + 'over under out off my your our me us do does did have has had will would can could'.split()) +# Only words no English prompt uses (son, die, Dan, la, le ... are left out). +OTHER_WORDS = frozenset('el los las un una unos unas al y que por con dos su sus es esta este pero muy como para les une ' + 'des du et avec dans sa il elle ils elles je nous vous pas sont der das ein eine und ist mit im ' + 'sie ich nicht auf uma não gli che ile yang dengan dit répond demande murmure crie sagt ruft ' + 'fragt flüstert antwortet dice responde pregunta grita susurra diz pergunta risponde chiede'.split()) +# Speech verbs that follow the quote: « Je reviens demain », dit la femme; „Ich komme morgen“, sagt sie. +AFTER_SPEECH = re.compile(r'[\s,.!?…\u2014\u2013-]*(?:\w+\s+){0,3}?(?Pdit|répond|demande|murmure|crie|sagt|ruft|fragt|' + r'flüstert|antwortet|dice|responde|pregunta|grita|susurra|diz|pergunta|risponde|chiede|' + r'говорит|сказал|сказала|кричит|спрашивает|отвечает|шепчет|каже|сказав|кричить|питає|' + r'відповідає|шепоче|dedi|diyor|sordu|nói)\b', re.I) +# Of those, the ones that are also English words (dice) count when the scene or the quoted words are in another +# language, or when the quote has the shape of a Spanish speech tag: a comma or dash, dice, then a word that follows it +# in Spanish or the end of the sentence ("Hola", dice la mujer.). The English noun does not take that shape +# ("Seven", dice spill across the table). +AFTER_SPEECH_ENGLISH = frozenset(('dice',)) +SPANISH_DICE = re.compile(r'\s*[,\u2014\u2013-]\s*dice(?=\s+(?:el|la|ella|él|un|una|ya|mientras|con|y)\b|\s*[.,!?…]|\s*$)') + + +def other_language(scene): + """Whether the scene, outside its quotes, is written in another language than Chinese, Japanese, Korean or + English: at least two of its words, and more than are common English words, are not English (a letter outside + ASCII, or a common Spanish, French, German, Portuguese, Italian, Turkish or Indonesian word). One accented name + or loanword (José, café, résumé) in an English scene is not enough.""" + outside = QUOTED.sub(' ', scene) + if re.search('[\u3040-\u30ff\u3400-\u9fff\uac00-\ud7af]', outside): + return False + words = re.findall(r'[^\W\d_]+', outside.lower()) + english = sum(word in EN_WORDS for word in words) + other = sum(not word.isascii() or word in OTHER_WORDS for word in words) + return other >= 2 and other > english + + def spoken_lines(scene): """Quoted spans the user introduced as speech (not signs or captions), in order.""" lines = [] + other = other_language(scene) for match in QUOTED.finditer(scene): words = next(group for group in match.groups() if group is not None).strip() before = scene[max(0, match.start() - 40):match.start()] @@ -360,6 +402,15 @@ def spoken_lines(scene): % '|'.join(CJK_SPEECH + CJK_STRONG), after) or re.match(r'[\s,]*(?:\w+\s+){0,3}(?:says|said|asks|asked|replies|replied|shouts|shouted|' r'whispers|whispered|calls|called|cries|cried)\b', after, re.I)) + if not speech and writing < 0: + # Speech verbs of other languages after the quote; English and CJK scenes do not use them, except the + # few that are English words too (rolls the dice), which count when the scene or the quoted words + # themselves are in another language ("Volveré mañana", dice la mujer). + verb = AFTER_SPEECH.match(scene[match.end():match.end() + 40]) + speech = bool(verb) and (verb.group('verb').lower() not in AFTER_SPEECH_ENGLISH or other or + other_language(words) or bool(SPANISH_DICE.match(scene[match.end():]))) + if not speech and other and writing < 0: + speech = bool(re.search(r'[::]\s*$', before)) or words[-1] in '.!?…' if speech: lines.append(words) return lines From 32169c41a778a30706ee3cc114ed770c734ec6f2 Mon Sep 17 00:00:00 2001 From: Bowen Xue Date: Wed, 25 Nov 2026 02:06:25 +0000 Subject: [PATCH 05/12] Prompt rewriting: a quote after a sign word in another language is read as written text, not... Prompt rewriting: a quote after a sign word in another language is read as written text, not dialogue --- freevideo_engine/prompt_vlm/rules.py | 35 +++++++++++++++++++++------- 1 file changed, 26 insertions(+), 9 deletions(-) diff --git a/freevideo_engine/prompt_vlm/rules.py b/freevideo_engine/prompt_vlm/rules.py index f0dcf94e..0fa41f21 100644 --- a/freevideo_engine/prompt_vlm/rules.py +++ b/freevideo_engine/prompt_vlm/rules.py @@ -313,9 +313,18 @@ def validate_output(text, value): r'名为|名字|称为|号称|看板|書かれ|表示|간판|\bsigns?|\bbanners?|\bcaptions?|\btitles?|\bposters?|' r'\bscreens?|\blabels?|\bboards?|\bneon|\btext|\bplacards?|\bgraffiti|\bheadlines?|\bsubtitles?|' r'\blettering|\bnamed|\bcalled|\btitled|\bnicknamed|\bbrand\w*|\breads?|\breading|\bwritten|' - r'\bprinted|\bpainted|\bspelled') + r'\bprinted|\bpainted|\bspelled|' + # Signs in other languages: German, French, Spanish, Russian, Ukrainian, Turkish, Vietnamese. + r'\bschild(?:er|ern)?\b|\baufschrift\w*|\bplakat\w*|\bschriftzug\w*|\benseignes?\b|\bpanneaux?\b|' + r'\baffiches?\b|\bletreros?\b|\bвывеск\w*|\bнадпис\w*|\bтабличк\w*|\bвивіск\w*|' + r'\bнапис\w*|\blevha\w*|\bafiş\w*|biển hiệu|bảng hiệu|tấm biển|\bécriteaux?\b|\bpancartes?\b|' + r'\btafel\w*|\binschrift\w*|\bbeschriftung\w*|\brótulos?\b|\bpancartas?\b|\bплакат\w*|\bафиш\w*|\bбаннер\w*') # Writing, not speech: a sign "OPEN", 写着“老街馄饨”, a sign that says "OPEN", a shop called "Kiko". WRITING = re.compile(NOUNS, re.I) +# Sign words that are English words too (a drug cartel, an inscription): writing only in a scene written in another +# language; tabela (Turkish sign, Portuguese and Polish table) only when the scene has a Turkish letter. +OTHER_WRITING = re.compile(r'\bcartel(?:es)?\b|\binscriptions?\b', re.I) +TURKISH_WRITING = re.compile(r'\btabela\w*', re.I) SIGN_SAYS = re.compile(r'(?:%s)\w*\s+(?:that\s+|which\s+)?(?:says|said|reads|shows|displays)$' % NOUNS, re.I) @@ -347,13 +356,14 @@ def plain(words): # Only words no English prompt uses (son, die, Dan, la, le ... are left out). OTHER_WORDS = frozenset('el los las un una unos unas al y que por con dos su sus es esta este pero muy como para les une ' 'des du et avec dans sa il elle ils elles je nous vous pas sont der das ein eine und ist mit im ' - 'sie ich nicht auf uma não gli che ile yang dengan dit répond demande murmure crie sagt ruft ' + 'sie ich nicht auf uma não ela ele elas eles gli che ile yang dengan dit répond demande murmure crie sagt ruft ' 'fragt flüstert antwortet dice responde pregunta grita susurra diz pergunta risponde chiede'.split()) # Speech verbs that follow the quote: « Je reviens demain », dit la femme; „Ich komme morgen“, sagt sie. -AFTER_SPEECH = re.compile(r'[\s,.!?…\u2014\u2013-]*(?:\w+\s+){0,3}?(?Pdit|répond|demande|murmure|crie|sagt|ruft|fragt|' - r'flüstert|antwortet|dice|responde|pregunta|grita|susurra|diz|pergunta|risponde|chiede|' - r'говорит|сказал|сказала|кричит|спрашивает|отвечает|шепчет|каже|сказав|кричить|питає|' - r'відповідає|шепоче|dedi|diyor|sordu|nói)\b', re.I) +SPEECH_VERBS = (r'dit|répond|demande|murmure|crie|sagt|ruft|fragt|flüstert|antwortet|dice|responde|pregunta|grita|' + r'susurra|diz|pergunta|risponde|chiede|говорит|сказал|сказала|кричит|спрашивает|отвечает|шепчет|каже|' + r'сказав|кричить|питає|відповідає|шепоче|dedi|diyor|sordu|nói') +AFTER_SPEECH = re.compile(r'[\s,.!?…\u2014\u2013-]*(?:\w+\s+){0,3}?(?P%s)\b' % SPEECH_VERBS, re.I) +SPEECH_VERB = re.compile(r'\b(?:%s)\b' % SPEECH_VERBS, re.I) # Of those, the ones that are also English words (dice) count when the scene or the quoted words are in another # language, or when the quote has the shape of a Spanish speech tag: a comma or dash, dice, then a word that follows it # in Spanish or the end of the sentence ("Hola", dice la mujer.). The English noun does not take that shape @@ -380,6 +390,7 @@ def spoken_lines(scene): """Quoted spans the user introduced as speech (not signs or captions), in order.""" lines = [] other = other_language(scene) + turkish = bool(re.search('[\u0131\u0130\u015f\u015e\u011f\u011e]', scene)) for match in QUOTED.finditer(scene): words = next(group for group in match.groups() if group is not None).strip() before = scene[max(0, match.start() - 40):match.start()] @@ -389,7 +400,8 @@ def spoken_lines(scene): lead = before.rstrip(' ::,,\u3000') if SIGN_SAYS.search(lead): continue - writing = max((m.end() for m in WRITING.finditer(lead)), default=-1) + writing = max((m.end() for m in (*WRITING.finditer(lead), *(OTHER_WRITING.finditer(lead) if other else ()), + *(TURKISH_WRITING.finditer(lead) if turkish else ()))), default=-1) cues = [len(lead) for verb in CJK_SPEECH if lead.endswith(verb)] cues += [lead.rfind(verb) + len(verb) for verb in CJK_STRONG if verb in lead[-6:]] cues += [m.start() + 1 for m in EN_SPEECH.finditer(lead)] @@ -402,14 +414,19 @@ def spoken_lines(scene): % '|'.join(CJK_SPEECH + CJK_STRONG), after) or re.match(r'[\s,]*(?:\w+\s+){0,3}(?:says|said|asks|asked|replies|replied|shouts|shouted|' r'whispers|whispered|calls|called|cries|cried)\b', after, re.I)) - if not speech and writing < 0: + # A sign word in the same clause as the quote, with no speech verb after it, makes the quote writing + # (une enseigne lumineuse : « … », Ein Schild an der Tür: „…“); a sign word before a sentence end or before + # the speaker's verb does not (Под вывеской стоит мужчина и говорит: «…»). + tail = lead[writing:] if writing >= 0 else '' + near_writing = writing >= 0 and not re.search(r'[.!?…]', tail) and not SPEECH_VERB.search(tail) + if not speech and not near_writing: # Speech verbs of other languages after the quote; English and CJK scenes do not use them, except the # few that are English words too (rolls the dice), which count when the scene or the quoted words # themselves are in another language ("Volveré mañana", dice la mujer). verb = AFTER_SPEECH.match(scene[match.end():match.end() + 40]) speech = bool(verb) and (verb.group('verb').lower() not in AFTER_SPEECH_ENGLISH or other or other_language(words) or bool(SPANISH_DICE.match(scene[match.end():]))) - if not speech and other and writing < 0: + if not speech and other and not near_writing: speech = bool(re.search(r'[::]\s*$', before)) or words[-1] in '.!?…' if speech: lines.append(words) From e3841442eec5b24291e56e38334ac4106096c33a Mon Sep 17 00:00:00 2001 From: Bowen Xue Date: Wed, 25 Nov 2026 02:07:26 +0000 Subject: [PATCH 06/12] Editor: from 681 to 1279 px the open adjust drawer also starts 8 px under Export --- web/editor_adjust.css | 3 +++ 1 file changed, 3 insertions(+) diff --git a/web/editor_adjust.css b/web/editor_adjust.css index 3e5c7e99..4d18c904 100644 --- a/web/editor_adjust.css +++ b/web/editor_adjust.css @@ -56,6 +56,9 @@ /* The drawer opens under the project row so the name and Export stay whole beside it (editor.css says so for the library too; the base rule above, loaded later at the same weight, kept the drawer on the project row). */ .fv-studio.fv-editor .fv-ed-adjust-host{grid-row:3/5} + /* Export is centred in the project row, so the row ends (row height - 32 px) / 2 under it: the drawer's top margin + takes that off, for the same 8 px gap under Export as up to 680 px (Iris 11-25: 8 px is a spacing step, 14 is not). */ + .fv-studio.fv-editor .fv-ed-adjust-host{margin-top:calc(8px - (var(--fv-ed-project-h) - 32px) / 2)} } /* Up to 680 px the drawer has no margin of its own: the same 8 px gap under Export as wider windows (Iris). */ @media(max-width:680px){.fv-studio.fv-editor .fv-ed-adjust-host{margin-top:8px}} From 795ae37e065f647a0e9326b208f1b5613567d304 Mon Sep 17 00:00:00 2001 From: Bowen Xue Date: Wed, 25 Nov 2026 02:16:24 +0000 Subject: [PATCH 07/12] Editor: a number typed for a part is kept when the selection moves, the right-rail Adjust key... Editor: a number typed for a part is kept when the selection moves, the right-rail Adjust key closes its own drawer, and up to 680 px the preview uses the space the drawer leaves --- web/editor.js | 1 + web/editor_adjust.css | 4 +++- web/editor_adjust.js | 2 ++ web/editor_adjust_picture.js | 8 +++++++- 4 files changed, 13 insertions(+), 2 deletions(-) diff --git a/web/editor.js b/web/editor.js index d1cfa9e0..6c9345b4 100644 --- a/web/editor.js +++ b/web/editor.js @@ -1910,6 +1910,7 @@ export function openEditor({api, app, from = null, panel = {}, components: given const adjust = adjustPanel = createAdjustPanel(adjustHost, {state, t, actions}); { const adjustRail = button('', () => adjust.toggleButton.click(), 'fv-ed-rail-button'); + adjustRail.dataset.adjustRail = 'true'; adjustRail.append(railGlyph('M3 1v14M8 1v14M13 1v14M1 5h4M6 11h4M11 5h4'), el('span', 'fv-ed-rail-label', t('Adjust', '调整'))); tip(adjustRail, {name: t('Adjust', '调整'), use: t('Volume, speed, picture and text of the selection', '调整选中片段的声音、速度、画面和文字')}); rightRail.append(adjustRail); diff --git a/web/editor_adjust.css b/web/editor_adjust.css index 4d18c904..562d3266 100644 --- a/web/editor_adjust.css +++ b/web/editor_adjust.css @@ -26,7 +26,9 @@ stays centered in the visible preview, without moving any lower rows. */ .fv-editor[data-adjust-open=true] .fv-ed-preview,.fv-editor[data-adjust-open=true] .fv-ed-transport{margin-right:264px} } -@media(max-width:680px){.fv-editor .fv-ed-adjust-host{grid-column:1}} +@media(max-width:680px){.fv-editor .fv-ed-adjust-host{grid-column:1} + /* The phone preview is width:100% (editor.css); beside the open drawer it takes the room the margin leaves, not its full width. */ + .fv-editor[data-adjust-open=true] .fv-ed-preview{width:auto}} @media(min-width:681px) and (max-width:800px){ .fv-editor[data-adjust-available=true] .fv-ed-toolbar{gap:4px} .fv-editor[data-adjust-available=true] .fv-ed-toolbar button{padding-left:4px;padding-right:4px} diff --git a/web/editor_adjust.js b/web/editor_adjust.js index 56c89633..1c058969 100644 --- a/web/editor_adjust.js +++ b/web/editor_adjust.js @@ -174,6 +174,8 @@ export function createAdjustPanel(host, {state, t, actions}) { // Only a press outside the editor's working areas (the header, the library) folds it away. const outside = event => { if (!overlay || host.contains(event.target) || toggleButton.contains(event.target)) return; + // The right rail's Adjust button is the drawer's switch from 681 to 1279 px: its press must not close the drawer first and its click then reopen it. + if (event.target.closest('[data-adjust-rail]')) return; if (event.target.closest('.fv-ed-preview, .fv-ed-transport, .fv-ed-tracks, .fv-ed-toolbar, .fv-ed-genbar, .fv-ed-project-row, .fv-ed-notice-stack, .fv-ed-record, [role=menu], .fv-select-menu, .fv-ed-clip-popover')) return; if (!event.target.closest('.fv-editor')) return; close(); diff --git a/web/editor_adjust_picture.js b/web/editor_adjust_picture.js index ff0e7951..df5a5b8a 100644 --- a/web/editor_adjust_picture.js +++ b/web/editor_adjust_picture.js @@ -51,7 +51,13 @@ export function createAdjustPicture({state, sources, t, player, notes = null}) { function update(ctx = context) { if (!ctx || !container) return; context = ctx; notes?.update(ctx); - clip = ctx.clips.find(c => c.track.kind === 'video' && c.source); + const next = ctx.clips.find(c => c.track.kind === 'video' && c.source); + // A number typed for one part is kept for that part when the selection moves on while its box still has the focus + // (a key that selects another part, say): it commits to the part it was typed for, never to the new one and never lost. + if (clip && next?.id !== clip.id) for (const {control} of Object.values(numbers)) { + if (control.input.dataset.editing === 'true' && control.input.dataset.editClip === clip.id) control.input.onblur?.(); + } + clip = next; const seen = new Set(); let count = 0; for (const item of ctx.clips) { if (!seen.has(item.id)) count++; seen.add(item.id); if (item.link) seen.add(item.link); } const reason = disabledReason({...ctx, multiple: ctx.multiple || count > 1}, {needs: 'video', single: true}) || session.editReason(clip); From 30c82b17e103ac0a1f6fd0cd210798ed370f1e21 Mon Sep 17 00:00:00 2001 From: Bowen Xue Date: Wed, 25 Nov 2026 02:26:27 +0000 Subject: [PATCH 08/12] Feedback and report redaction: a short input is hidden only as a whole word, so numbers and... Feedback and report redaction: a short input is hidden only as a whole word, so numbers and symbols stay readable --- freevideo_engine/diagnostics.py | 38 ++++++++++++++++++++++++++++- web/error_panel.js | 42 +++++++++++++++++++++++++++------ 2 files changed, 72 insertions(+), 8 deletions(-) diff --git a/freevideo_engine/diagnostics.py b/freevideo_engine/diagnostics.py index cb0c511c..c698f886 100644 --- a/freevideo_engine/diagnostics.py +++ b/freevideo_engine/diagnostics.py @@ -44,6 +44,19 @@ ABSOLUTE_PATH = long_paths.ABSOLUTE_PATH +SHORT_PROMPT = 4 +# Scripts written without spaces between words (Myanmar, Hangul, Khmer, CJK, kana, Thai, +# Lao and others): a short prompt in one is removed at any position. web/error_panel.js +# has the same ranges (NO_WORD_BOUNDARY); a test compares the two. +NO_WORD_BOUNDARY_RANGES = ( + (0x0e00, 0x0eff), (0x1000, 0x109f), (0x1100, 0x11ff), (0x1780, 0x17ff), (0x19e0, 0x19ff), + (0x2e80, 0x2fdf), (0x3005, 0x3007), (0x3021, 0x3029), (0x3038, 0x303b), (0x3040, 0x30ff), + (0x3130, 0x318f), (0x31f0, 0x31ff), (0x3400, 0x4dbf), (0x4e00, 0x9fff), (0xa960, 0xa97f), + (0xa9e0, 0xa9ff), (0xaa60, 0xaa7f), (0xac00, 0xd7ff), (0xf900, 0xfaff), (0xff66, 0xff9f), + (0xffa0, 0xffdc), (0x1b000, 0x1b16f), (0x20000, 0x3134f)) +NO_WORD_BOUNDARY = re.compile('[%s]' % ''.join('%s-%s' % (chr(low), chr(high)) for low, high in NO_WORD_BOUNDARY_RANGES)) + + class Redactor: def __init__(self, replacements=()): self.replacements = sorted(((str(a), b) for a, b in replacements if len(str(a)) > 1), @@ -76,7 +89,7 @@ def structured(self, value): def text(self, value): value = plain_text(value) for prompt in sorted(self.prompts, key=len, reverse=True): - value = value.replace(prompt, '') + value = self._hide_prompt(value, prompt) for secret in sorted(self.secrets, key=len, reverse=True): value = value.replace(secret, '') for source, target in self.replacements: @@ -93,6 +106,29 @@ def text(self, value): value = ABSOLUTE_PATH.sub(self._path_match, value) return value + @staticmethod + def _hide_prompt(value, prompt): + """Remove a prompt; one under 4 characters only as a whole word. + + "2" must not turn "2.00 GiB" into ".00 GiB". A short prompt is + not removed next to a letter (digits and underscores do not protect it: + "cat_0001", "Li2024@example.com"); a prompt of digits only is not removed next + to a digit or inside a decimal number. A side that is itself a symbol ("@xy", + "C++") has no such limit; a prompt in a script without word boundaries goes + everywhere, and so does any prompt of 4 characters or more.""" + if len(prompt) >= SHORT_PROMPT or NO_WORD_BOUNDARY.search(prompt): + return value.replace(prompt, '') + if not any(ch.isalnum() for ch in prompt): + return value # spaces, ".", "-": nothing to hide, and removing them would ruin the text + digits = prompt.isascii() and prompt.strip('0123456789.,') == '' and any(ch.isdigit() for ch in prompt) + near = r'\d' if digits else r'[^\W\d_]' + left = '(?', value) + @staticmethod def _path_match(match): return long_paths.path_match(match) diff --git a/web/error_panel.js b/web/error_panel.js index e8fcc101..844289e0 100644 --- a/web/error_panel.js +++ b/web/error_panel.js @@ -198,6 +198,37 @@ export function errorText(detail) { return rows.join('\n'); } +// Scripts written without spaces between words (Myanmar, Hangul, Khmer, CJK, kana, +// Thai, Lao and others): a short input in one is removed at any position. The same +// ranges are in freevideo_engine/diagnostics.py (NO_WORD_BOUNDARY_RANGES); a test +// compares the two. +const NO_WORD_BOUNDARY = /[\u0e00-\u0eff\u1000-\u109f\u1100-\u11ff\u1780-\u17ff\u19e0-\u19ff\u2e80-\u2fdf\u3005-\u3007\u3021-\u3029\u3038-\u303b\u3040-\u30ff\u3130-\u318f\u31f0-\u31ff\u3400-\u4dbf\u4e00-\u9fff\ua960-\ua97f\ua9e0-\ua9ff\uaa60-\uaa7f\uac00-\ud7ff\uf900-\ufaff\uff66-\uff9f\uffa0-\uffdc\u{1b000}-\u{1b16f}\u{20000}-\u{3134f}]/u; +const WORD_CHARACTER = /^[\p{L}\p{N}_]$/u; + +// A short input (under 4 characters, such as "2" or "a") is removed as a whole word: +// not next to a letter, digit or underscore. A side that is itself a symbol ("@xy", +// "C++") has no such limit. An input with no letter or digit (spaces, ".", "-") says +// nothing and is not removed, or every dot of the report would go. An input of digits (and . or ,) only is also kept inside a decimal +// number ("2.00", "1,5"), so the engine's own figures stay readable. +function hideShortInput(text, secret) { + const characters = Array.from(secret); + const left = WORD_CHARACTER.test(characters[0]), right = WORD_CHARACTER.test(characters[characters.length - 1]); + const digits = /^[0-9.,]*[0-9][0-9.,]*$/.test(secret); + let result = '', from = 0, at; + while ((at = text.indexOf(secret, from)) !== -1) { + const end = at + secret.length; + const before = Array.from(text.slice(Math.max(0, at - 2), at)), after = Array.from(text.slice(end, end + 2)); + const previous = before[before.length - 1] ?? '', next = after[0] ?? ''; + let keep = (left && WORD_CHARACTER.test(previous)) || (right && WORD_CHARACTER.test(next)); + if (!keep && digits) + keep = (/^[.,]$/.test(previous) && /^[0-9]$/.test(before[before.length - 2] ?? '')) + || (/^[.,]$/.test(next) && /^[0-9]$/.test(after[1] ?? '')); + result += text.slice(from, at) + (keep ? secret : ''); + from = end; + } + return result + text.slice(from); +} + function reportRedactor(detail, context) { // Input values are used only to remove echoed private content. They are // never included in the report, nor are workflow/inputs/extra_info objects. @@ -240,13 +271,10 @@ function reportRedactor(detail, context) { const removeInputs = value => { let text = scalar(value); for (const secret of values) { - // Short widget values (e.g. "a") must not erase every occurrence - // inside exception names. Still remove standalone/quoted values. - if (secret.length >= 4) text = text.split(secret).join(''); - else { - const escaped = secret.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'); - text = text.replace(new RegExp(`(^|[^\\p{L}\\p{N}_])${escaped}(?=$|[^\\p{L}\\p{N}_])`, 'gu'), '$1'); - } + // Short values (under 4 characters) must not erase fragments of the + // engine's own sentences or numbers ("2.00 GiB"): see hideShortInput. + if (secret.length >= 4 || NO_WORD_BOUNDARY.test(secret)) text = text.split(secret).join(''); + else if (/[\p{L}\p{N}]/u.test(secret)) text = hideShortInput(text, secret); } return text; }; From 60b79c18540178f05cab9e9aa4cc4960a1227aca Mon Sep 17 00:00:00 2001 From: Bowen Xue Date: Wed, 25 Nov 2026 02:30:50 +0000 Subject: [PATCH 09/12] Image generation on Windows: the text encoder stays inside the system commit headroom and... Image generation on Windows: the text encoder stays inside the system commit headroom and retries once --- freevideo_engine/encode_worker.py | 16 ++++++ freevideo_engine/encoder_commit.py | 61 +++++++++++++++++++++++ freevideo_engine/image_gen/h3_pipeline.py | 18 ++++++- freevideo_engine/resident_models.py | 10 +++- 4 files changed, 101 insertions(+), 4 deletions(-) create mode 100644 freevideo_engine/encoder_commit.py diff --git a/freevideo_engine/encode_worker.py b/freevideo_engine/encode_worker.py index a7ede476..4efc9e38 100644 --- a/freevideo_engine/encode_worker.py +++ b/freevideo_engine/encode_worker.py @@ -253,6 +253,12 @@ def _reserve(resident): def encode(args, request, resident=None, diagnostics=None): from .encoder_diagnostics import EncoderTrace trace = diagnostics or EncoderTrace(request, resident=resident is not None) + if resident is not None and hasattr(resident, 'commit_cap'): + # The retained models are counted against the commit headroom too: what does not fit beside it goes + # (make_room) before the encoder is placed, instead of the encoder running the headroom out. + import torch + from .encoder_commit import live_cap + resident.commit_cap = lambda: live_cap(torch, resident.gpu_budget or 0) if resident.gpu_budget else None try: metrics = _encode(args, request, resident, trace) except BaseException: @@ -261,6 +267,9 @@ def encode(args, request, resident=None, diagnostics=None): stop_model_read_ahead(trace) trace.finish(False) raise + finally: + if resident is not None and hasattr(resident, 'commit_cap'): + resident.commit_cap = None stop_read_ahead(trace) stop_model_read_ahead(trace) result = trace.finish(True, metrics) @@ -338,6 +347,13 @@ def phase(name, **metrics): # a fixed 128 GB ceiling refused the request before encoding started. # Clamp to the capacity the reserve is computed against. budget = min(budget, total / 1e9) + # Windows commit backs the card's allocations: the encoder is placed within the headroom, and the layers + # beyond it stream from the checkpoint (not charged to commit) instead of taking the headroom to the guard. + from .encoder_commit import live_cap + commit_cap = live_cap(torch, budget * 1e9) + if commit_cap is not None: + loading['encoder_commit_gpu_cap_bytes'] = commit_cap + budget = commit_cap / 1e9 # Let the native model manager leave space for CUDA and live activations. # This is placement guidance, not an enforced capacity result. reserve_gib = max(0.5, (available - budget * 1e9 + 1e9) / 2**30) diff --git a/freevideo_engine/encoder_commit.py b/freevideo_engine/encoder_commit.py new file mode 100644 index 00000000..7f5eda8c --- /dev/null +++ b/freevideo_engine/encoder_commit.py @@ -0,0 +1,61 @@ +"""GPU bytes Windows commit headroom can back while the text encoder is placed. + +Windows charges every byte the CUDA allocator reserves to system commit. A native encoder that fits the card can +still take the commit headroom to the RAM guard's floor while its weights are placed (weights it leaves on the host +are read-only file mappings, which are not charged), and the request then stops with commit exhausted although +physical RAM is free. The sampling plan already keeps its GPU allocation inside the headroom (policy.commit_gpu_limit); +the encoder stage did not, because the budget it is given is the card's alone. + +The cap here is the same idea for the encoder: the GPU the process already holds, plus the commit headroom, less what +its own CUDA context and working set add beside the weights and a spare for other programs. The encoder streams the +layers beyond the cap, so the arithmetic is unchanged; only the resident share of the weights gives way. +""" +GiB = 2**30 +# The process's CUDA context, tokenizer, working set and encoder workspace beside the weights. +ENCODER_HOST_BYTES = 2 * GiB +# Growth of other programs during the stage. +ENCODER_SPARE_BYTES = GiB +# Below this the card's own budget stays: a smaller placement is slower than the failure it avoids. +ENCODER_GPU_FLOOR = 8 * GiB + + +def encoder_commit_gpu_cap(commit_available, held_gpu_bytes, request_budget): + """Total GPU bytes (those the process already holds included) the commit headroom backs for the encoder; + None when it does not bind or is not known.""" + if type(commit_available) is not int or commit_available < 0 or type(request_budget) is not int: + return None + held = held_gpu_bytes if type(held_gpu_bytes) is int and held_gpu_bytes > 0 else 0 + limit = max(commit_available + held - ENCODER_HOST_BYTES - ENCODER_SPARE_BYTES, + min(request_budget, ENCODER_GPU_FLOOR)) + return int(limit) if limit < request_budget else None + + +def live_commit_available(): + """Windows commit headroom now; None elsewhere or when it cannot be read.""" + from .system import windows + if not windows(): + return None + try: + from .win32 import memory_status + value = memory_status()['commit_available_bytes'] + except Exception: + return None + return value if type(value) is int else None + + +def live_cap(torch, request_budget): + """encoder_commit_gpu_cap from the live commit headroom and what this process holds on the card.""" + commit = live_commit_available() + if commit is None: + return None + try: + held = int(torch.cuda.memory_reserved()) + except Exception: + held = 0 + return encoder_commit_gpu_cap(commit, held, int(request_budget)) + + +def commit_exhausted(error): + """Whether a RAM-guard failure is Windows commit exhaustion (physical RAM may be free).""" + text = str(error) + return isinstance(error, MemoryError) and 'commit headroom' in text and 'RAM guard' in text diff --git a/freevideo_engine/image_gen/h3_pipeline.py b/freevideo_engine/image_gen/h3_pipeline.py index 6a04162f..d05f10a5 100644 --- a/freevideo_engine/image_gen/h3_pipeline.py +++ b/freevideo_engine/image_gen/h3_pipeline.py @@ -384,8 +384,22 @@ def _encode(prompt, *, encoder, comfy_root, comfy_python, model_paths, vram_gib, if resident_endpoint: os.environ[ENV] = resident_endpoint try: - return _encode_once(prompt, encoder, comfy_root, comfy_python, model_paths, vram_gib, ram_gib, vision_images, - release_gpu=release_gpu) + try: + return _encode_once(prompt, encoder, comfy_root, comfy_python, model_paths, vram_gib, ram_gib, vision_images, + release_gpu=release_gpu) + except MemoryError as error: + import json + from ..encoder_commit import ENCODER_GPU_FLOOR, commit_exhausted + if not commit_exhausted(error): + raise + # Windows commit ran out while the weights were placed (physical RAM may be free). Once more with the + # card's share of the weights cut to the floor: the layers beyond it stream from the checkpoint, which + # commit does not charge, and the arithmetic is the same. + retry_gib = ENCODER_GPU_FLOOR / 2**30 + print(json.dumps({'event': 'encoder_commit_retry', 'vram_gib': retry_gib}), flush=True) + return _encode_once(prompt, encoder, comfy_root, comfy_python, model_paths, + min(vram_gib, retry_gib) if vram_gib else retry_gib, ram_gib, vision_images, + release_gpu=release_gpu) except BaseException as error: # The caller's classifier keeps only a code; the text of the failure goes to the worker's log. print('H3 encode failed: %s: %s' % (type(error).__name__, str(error)[-2000:]), file=sys.stderr, flush=True) diff --git a/freevideo_engine/resident_models.py b/freevideo_engine/resident_models.py index d2df067f..6ea51278 100644 --- a/freevideo_engine/resident_models.py +++ b/freevideo_engine/resident_models.py @@ -292,6 +292,9 @@ def __init__(self): # does not. self.device_free = None self.device_reserve = 0 + # While the text encoder is placed on Windows: a callable giving the GPU bytes the commit headroom backs + # (what this process holds included), or None. Other stages plan with their own budgets. + self.commit_cap = None def configure(self, gpu_budget, ram_budget=None, *, gpu_reserve=0, ram_budget_is_estimate=None): self.gpu_budget = int(gpu_budget) @@ -414,8 +417,11 @@ def clear(self, reason='Request failed or session configuration changed'): def available(self): free, _ = torch.cuda.mem_get_info() allocated = torch.cuda.memory_allocated() - return max(0, min(free + torch.cuda.memory_reserved() - allocated - self.gpu_reserve, - self.gpu_budget - allocated)) + room = min(free + torch.cuda.memory_reserved() - allocated - self.gpu_reserve, self.gpu_budget - allocated) + cap = self.commit_cap() if self.commit_cap is not None else None + if cap is not None: + room = min(room, cap - allocated) + return max(0, room) def ram_fits(self, need=2*GiB, *, bounded=False): """Whether live RAM takes `need` more bytes beside what this process holds. From 73510157a5e87ff0a3c8fd04f1b8633f747d4b5a Mon Sep 17 00:00:00 2001 From: Bowen Xue Date: Wed, 25 Nov 2026 02:35:16 +0000 Subject: [PATCH 10/12] Launcher process hosts pass on the environment they are given, so ComfyUI starts from the Linux... Launcher process hosts pass on the environment they are given, so ComfyUI starts from the Linux and Mac apps --- freevideo_engine/modern_launcher.py | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/freevideo_engine/modern_launcher.py b/freevideo_engine/modern_launcher.py index bbd909d4..05f7902f 100644 --- a/freevideo_engine/modern_launcher.py +++ b/freevideo_engine/modern_launcher.py @@ -769,7 +769,12 @@ def step(): def main(session=None): from .installed_entry import protect - protect() + # The process hosts below start other programs (ComfyUI, install steps) with the environment the launcher gave them; + # PYTHONSAFEPATH would stop ComfyUI's main.py from importing from its own folder, so only the launcher itself is protected. + frozen = getattr(sys, 'frozen', False) + if not (frozen and (sys.platform == 'darwin' and sys.argv[1:2] == ['--macos-process-host'] + or sys.platform.startswith('linux') and sys.argv[1:2] == ['--freevideo-module'])): + protect() if (getattr(sys, 'frozen', False) and sys.platform == 'darwin' and sys.argv[1:2] == ['--macos-process-host']): from .macos_process_host import main as supervise From 5e54980f8f0e62eae51695cefe1d9438e693ec07 Mon Sep 17 00:00:00 2001 From: Bowen Xue Date: Wed, 25 Nov 2026 02:54:08 +0000 Subject: [PATCH 11/12] Dialogue in Ukrainian is passed to the video model as Ukrainian, while Russian lines that name a... Dialogue in Ukrainian is passed to the video model as Ukrainian, while Russian lines that name a Ukrainian place keep their Russian tag --- freevideo_engine/prompt_vlm/rules.py | 13 +------- freevideo_engine/timed_prompt.py | 48 +++++++++++++++++++++++++++- web/timed_prompt.js | 33 ++++++++++++++++++- 3 files changed, 80 insertions(+), 14 deletions(-) diff --git a/freevideo_engine/prompt_vlm/rules.py b/freevideo_engine/prompt_vlm/rules.py index 0fa41f21..2844b384 100644 --- a/freevideo_engine/prompt_vlm/rules.py +++ b/freevideo_engine/prompt_vlm/rules.py @@ -7,6 +7,7 @@ import re from ..music_request import asks_for_no_music, writes_own_music +from ..timed_prompt import language # the tag timed lines get, so both paths agree BASE_FIELDS = ('integrated_multimodal_description', 'overall_soundscape', 'non_diegetic_music') REF_FIELDS = ('subject_definitions', 'summary', 'retention_analysis', 'detailed_description', @@ -328,18 +329,6 @@ def validate_output(text, value): SIGN_SAYS = re.compile(r'(?:%s)\w*\s+(?:that\s+|which\s+)?(?:says|said|reads|shows|displays)$' % NOUNS, re.I) -def language(words): - if re.search('[\u3040-\u30ff]', words): - return 'Japanese' - if re.search('[\uac00-\ud7af]', words): - return 'Korean' - if re.search('[\u4e00-\u9fff]', words): - return 'Chinese' - if re.search('[\u0400-\u04ff]', words): - return 'Russian' - return 'English' - - def plain(words): """Comparable form: no tags, speaker IDs, quotes, punctuation, spacing or case.""" words = re.sub(r'<[^>]{1,24}>|\(S\d+(?:,S\d+)*\)|\[[A-Za-z]+\]', '', words) diff --git a/freevideo_engine/timed_prompt.py b/freevideo_engine/timed_prompt.py index 5e9721fb..6c5323ab 100644 --- a/freevideo_engine/timed_prompt.py +++ b/freevideo_engine/timed_prompt.py @@ -21,6 +21,52 @@ ENDS = '.!?。!?…"”' +# Cyrillic lines: Ukrainian or Russian, decided by weighing the words (tests/test_prompt_vlm_dialogue.py lists cases). +# Ukrainian words: those with і ї є ґ, and common words only Ukrainian writes (що, цей, вже, дуже ...). Russian words: +# those with ы э ъ ё, and common Russian words (и, что, это, как, он, нет ...). The line is Ukrainian only when it has +# more Ukrainian words; a tie is Russian. A name inside a sentence (a capitalised word after no sentence end, colon or +# semicolon: "Завтра я еду в Київ") and a Roman numeral (Пётр І, Екатерина ІІ) count for neither side; a line written +# in capitals is read in lower case first, so its words are not names. Belarusian ў, Kazakh ә ғ қ ң ө ұ ү һ and the +# Serbian and Macedonian ђ ѓ ѕ ј љ њ ћ ќ џ keep the Russian tag, the closest of the two. +# Known limits: Ukrainian with neither kind of word (Я тебе кохаю, Я чекаю на тебе) reads as Russian, and Belarusian or +# Kazakh with і but none of their own letters (Мен білемін) as Ukrainian. +UKRAINIAN_LETTERS = re.compile('[\u0404\u0406\u0407\u0454\u0456\u0457\u0490\u0491]') +RUSSIAN_LETTERS = re.compile('[\u042b\u044b\u042d\u044d\u042a\u044a\u0401\u0451]') +OTHER_CYRILLIC = re.compile('[\u040e\u045e\u0492\u0493\u049a\u049b\u04a2\u04a3\u04ae\u04af\u04b0\u04b1\u04ba\u04bb\u04d8\u04d9' + '\u04e8\u04e9\u0402\u0403\u0405\u0408-\u040c\u040f\u0452\u0453\u0455\u0458-\u045c\u045f]') +UKRAINIAN_WORDS = frozenset('що щоб цей цього ця цю ці вже дуже щось немає тобі зараз дякую'.split()) +RUSSIAN_WORDS = frozenset('и что чтобы это этот эта как он она они его меня тебя где когда если нет есть но или только ' + 'еще мне с к'.split()) +CYRILLIC_WORD = re.compile("[\u0400-\u04ff](?:['\u2019\u02bc]?[\u0400-\u04ff])*") +# What may stand between the end of a sentence (or a colon) and the next word. +OPENING = ' \t\n\r"\'\u00ab\u00bb\u201c\u201d\u201e\u2018\u2019()[]\u2014\u2013-' +ROMAN = frozenset('\u0406\u0425') + + +def ukrainian(words): + if OTHER_CYRILLIC.search(words): + return False + if not re.search('[\u0430-\u045f\u0491]', words): + words = words.lower() + ukrainian_words = russian_words = 0 + for match in CYRILLIC_WORD.finditer(words): + word = match.group(0) + lower = word.lower() + if RUSSIAN_LETTERS.search(word) or lower in RUSSIAN_WORDS: + russian_words += 1 + elif lower in UKRAINIAN_WORDS: + ukrainian_words += 1 + elif UKRAINIAN_LETTERS.search(word): + before = words[:match.start()].rstrip(OPENING) + inside = bool(before) and before[-1] not in '.!?:;\u2026' + if set(word) <= ROMAN and before: + continue + if inside and word[0].isupper() and (len(word) == 1 or any(c.islower() for c in word[1:])): + continue + ukrainian_words += 1 + return ukrainian_words > russian_words + + def language(words): if re.search('[぀-ヿ]', words): return 'Japanese' @@ -29,7 +75,7 @@ def language(words): if re.search('[一-鿿]', words): return 'Chinese' if re.search('[Ѐ-ӿ]', words): - return 'Russian' + return 'Ukrainian' if ukrainian(words) else 'Russian' return 'English' diff --git a/web/timed_prompt.js b/web/timed_prompt.js index 9a08cf3e..3df509f9 100644 --- a/web/timed_prompt.js +++ b/web/timed_prompt.js @@ -10,11 +10,42 @@ const WRITTEN = /\[Shot \d+\]|\bAt \d{2,}:\d{2}\.\d{3}/; const CJK = /[぀-ヿ㐀-鿿]/; const ENDS = '.!?。!?…"”'; +// Cyrillic lines: Ukrainian or Russian, by weighing the words; the same rule as freevideo_engine/timed_prompt.py, which says why. +const UKRAINIAN_LETTERS = /[\u0404\u0406\u0407\u0454\u0456\u0457\u0490\u0491]/; +const RUSSIAN_LETTERS = /[\u042b\u044b\u042d\u044d\u042a\u044a\u0401\u0451]/; +const OTHER_CYRILLIC = /[\u040e\u045e\u0492\u0493\u049a\u049b\u04a2\u04a3\u04ae\u04af\u04b0\u04b1\u04ba\u04bb\u04d8\u04d9\u04e8\u04e9\u0402\u0403\u0405\u0408-\u040c\u040f\u0452\u0453\u0455\u0458-\u045c\u045f]/; +const UKRAINIAN_WORDS = new Set('що щоб цей цього ця цю ці вже дуже щось немає тобі зараз дякую'.split(' ')); +const RUSSIAN_WORDS = new Set('и что чтобы это этот эта как он она они его меня тебя где когда если нет есть но или только еще мне с к'.split(' ')); +const CYRILLIC_WORD = /[\u0400-\u04ff](?:['\u2019\u02bc]?[\u0400-\u04ff])*/g; +const OPENING = /[ \t\n\r"'\u00ab\u00bb\u201c\u201d\u201e\u2018\u2019()[\]\u2014\u2013-]+$/; +const ROMAN = /^[\u0406\u0425]+$/; +const isUpper = ch => ch !== ch.toLowerCase(); +const isLower = ch => ch !== ch.toUpperCase(); + +function ukrainian(words) { + if (OTHER_CYRILLIC.test(words)) return false; + if (!/[\u0430-\u045f\u0491]/.test(words)) words = words.toLowerCase(); + let ukrainianWords = 0, russianWords = 0; + for (const match of words.matchAll(CYRILLIC_WORD)) { + const word = match[0], lower = word.toLowerCase(); + if (RUSSIAN_LETTERS.test(word) || RUSSIAN_WORDS.has(lower)) russianWords += 1; + else if (UKRAINIAN_WORDS.has(lower)) ukrainianWords += 1; + else if (UKRAINIAN_LETTERS.test(word)) { + const before = words.slice(0, match.index).replace(OPENING, ''); + const inside = Boolean(before) && !'.!?:;\u2026'.includes(before[before.length - 1]); + if (ROMAN.test(word) && before) continue; + if (inside && isUpper(word[0]) && (word.length === 1 || [...word.slice(1)].some(isLower))) continue; + ukrainianWords += 1; + } + } + return ukrainianWords > russianWords; +} + export function language(words) { if (/[぀-ヿ]/.test(words)) return 'Japanese'; if (/[가-힯]/.test(words)) return 'Korean'; if (/[一-鿿]/.test(words)) return 'Chinese'; - if (/[Ѐ-ӿ]/.test(words)) return 'Russian'; + if (/[Ѐ-ӿ]/.test(words)) return ukrainian(words) ? 'Ukrainian' : 'Russian'; return 'English'; } From 965232e9939554cf244d619f8ec705e63f666d9e Mon Sep 17 00:00:00 2001 From: Bowen Xue Date: Wed, 25 Nov 2026 05:41:16 +0000 Subject: [PATCH 12/12] Release 0.6.12: update notes --- freevideo_engine/release_notes.json | 114 +++++++++++++--------------- 1 file changed, 52 insertions(+), 62 deletions(-) diff --git a/freevideo_engine/release_notes.json b/freevideo_engine/release_notes.json index a6a5e39c..79040d13 100644 --- a/freevideo_engine/release_notes.json +++ b/freevideo_engine/release_notes.json @@ -1,41 +1,66 @@ { "schema": 1, - "product_version": "0.6.11", + "product_version": "0.6.12", "en": { - "summary": "0.6.11 can write a prompt from a picture or a video, makes local network access and first, middle and last frames on the Mac work as expected, and no longer stops a second generation on two graphics cards with an error on Windows. Failure messages now also say what went wrong and what to do next.", + "summary": "0.6.12 fixes the Linux and Mac launchers failing to open ComfyUI in 0.6.11, keeps dialogue in more languages when prompts are enhanced, and voices Ukrainian dialogue in Ukrainian.", "changes": [ - "Reverse prompt: in the image view and the create panel, choose a picture or a video and FreeVideo writes the description.", - "Fuller local network access: when FreeVideo is opened through its local network address, you can generate with reference pictures, edit generated pictures and copy prompts.", - "First, middle and last frames on the Mac: generating with a first, middle and last frame works on the Mac.", - "Two graphics cards at once: on Windows, a generation started on the second graphics card no longer stops with an error while the first one is working.", - "Clearer failure messages: every kind of failure says what to do next. When a prompt enhancement result is incomplete, the message says what was wrong.", - "More accurate driver messages: when no working driver is found, the launcher shows the graphics card it detected and tells \"driver not installed\" apart from \"driver not working\".", - "LoRAs and reference pictures are kept: the LoRAs and reference pictures set in the create panel are still there after FreeVideo restarts, and scene and prop cards remember the LoRAs used to make their picture.", - "Steadier running: FreeVideo commands use the installed program from any folder. When graphics memory runs short while the prompt is processed, FreeVideo retries once instead of failing.", - "Easier image models: Repair asks you first and keeps the original shared file under a new name. A download that starts while FreeVideo is installing, updating or cleaning up continues by itself when that finishes.", - "Saved prompts work right after an update: prompts saved before updating FreeVideo do not need to be processed again.", - "More reliable long video redo: after a lost or late reply, choosing \"Redo from here\" again shows the part already started instead of making another one.", - "A steadier first generation after an update: cleaning up old versions no longer changes the model files in use, so the first generation after an update is not interrupted by it." + "Linux and Mac: the 0.6.11 launcher failed to open ComfyUI; it now opens normally.", + "Prompt enhancement keeps dialogue in more languages: when a scene is written in Russian, Ukrainian, Spanish, French, German, Turkish, Vietnamese or a similar language, the quoted lines are passed to the voice word for word instead of being left out, and text on signs and posters stays on screen.", + "Ukrainian dialogue is voiced more accurately: lines are passed to the model as Ukrainian instead of Russian, so they no longer take on a Russian accent, while Russian lines that mention a Ukrainian place are still spoken as Russian.", + "Picture editing on Windows: when Windows has little memory left to commit, FreeVideo now places less of the text encoder on the graphics card and tries once more if that is still not enough, so editing with several reference pictures is less likely to stop at the text step for lack of memory.", + "More complete diagnostic reports: when the engine stops answering for more than five seconds, FreeVideo records what each part was doing at the time and includes it in feedback and diagnostic reports, to help find the cause.", + "Feedback and diagnostic reports keep numbers such as \"2.00 GiB\" intact when a field holds a short value." ] }, "zh": { - "summary": "0.6.11 新增从图片或视频反推提示词,局域网访问和 Mac 首中尾帧生成可以正常使用,Windows 上两张显卡同时生成也不再报错停下。失败提示会说明原因和下一步。", + "summary": "0.6.12 修复了 0.6.11 在 Linux 和 Mac 上无法打开 ComfyUI 的问题;提示词改写会保留更多语言的台词,乌克兰语台词按乌克兰语配音。", "changes": [ - "反推提示词:在图像视图和创作面板中,可以选一张图片或一段视频,自动写出描述。", - "局域网访问更完整:通过局域网地址打开 FreeVideo 时,可以带参考图生成、编辑已生成的图片,也可以复制提示词。", - "Mac 首中尾帧生成:在 Mac 上同时使用首帧、中间帧和尾帧,可以正常生成。", - "多显卡同时生成:在 Windows 上使用两张显卡时,第二张显卡开始的生成不再因等待第一张而报错停下。", - "失败提示更清楚:各类失败都会说明下一步怎么做。提示词增强的结果不完整时,会写明是哪里不对。", - "显卡驱动提示更准确:缺少可用驱动时,启动器会显示检测到的显卡型号,并区分“未安装驱动”和“驱动未正常工作”。", - "LoRA 和参考图会保留:创作面板设置的 LoRA 和参考图在重启 FreeVideo 后仍在;场景卡和道具卡也会记住生成图片时用的 LoRA。", - "运行更稳定:从任何文件夹运行 FreeVideo 命令,都会使用已安装的程序。处理提示词时显存不足,会自动重试一次,不再直接失败。", - "图像模型更省心:修复时会先请您确认,原有的共用文件改名保留。FreeVideo 正在安装、更新或清理时开始的下载,会在结束后自动继续。", - "更新后可直接使用已保存的提示词:更新 FreeVideo 后,已保存的提示词不需要重新处理。", - "长视频重新生成更可靠:在网络回复丢失或延迟后再次点击“从这段重新生成”,会继续显示已经开始的那一段,不会多生成一段。", - "更新后第一次生成更稳定:清理旧版本时不再改动正在使用的模型文件,更新后的第一次生成不会因此中断。" + "Linux 和 Mac:0.6.11 的启动器打开 ComfyUI 时会失败,现在可以正常打开。", + "提示词改写能保留更多语言的台词:用俄语、乌克兰语、西班牙语、法语、德语、土耳其语、越南语等写场景时,引号里的台词会原样交给模型配音,不再被漏掉;招牌、海报上的文字仍作为画面中的文字。", + "乌克兰语台词的配音更准:台词按乌克兰语交给模型,不再标成俄语,发音不再带俄语腔;俄语台词里提到乌克兰地名时仍按俄语念。", + "Windows 上编辑图片:当 Windows 可提交的内存所剩不多时,FreeVideo 在文本编码时少放一部分到显卡上,仍不足时再试一次,带多张参考图编辑时,文本这一步不容易再因内存不足停下。", + "诊断报告更完整:引擎停止应答超过五秒时,FreeVideo 会记下各部分当时在做什么,并随反馈和诊断报告一起带出,便于找出原因。", + "反馈和诊断报告里,输入框中的短内容不再改坏“2.00 GiB”这类数字。" ] }, "history": [ + { + "product_version": "0.6.11", + "en": { + "summary": "0.6.11 can write a prompt from a picture or a video, makes local network access and first, middle and last frames on the Mac work as expected, and no longer stops a second generation on two graphics cards with an error on Windows. Failure messages now also say what went wrong and what to do next.", + "changes": [ + "Reverse prompt: in the image view and the create panel, choose a picture or a video and FreeVideo writes the description.", + "Fuller local network access: when FreeVideo is opened through its local network address, you can generate with reference pictures, edit generated pictures and copy prompts.", + "First, middle and last frames on the Mac: generating with a first, middle and last frame works on the Mac.", + "Two graphics cards at once: on Windows, a generation started on the second graphics card no longer stops with an error while the first one is working.", + "Clearer failure messages: every kind of failure says what to do next. When a prompt enhancement result is incomplete, the message says what was wrong.", + "More accurate driver messages: when no working driver is found, the launcher shows the graphics card it detected and tells \"driver not installed\" apart from \"driver not working\".", + "LoRAs and reference pictures are kept: the LoRAs and reference pictures set in the create panel are still there after FreeVideo restarts, and scene and prop cards remember the LoRAs used to make their picture.", + "Steadier running: FreeVideo commands use the installed program from any folder. When graphics memory runs short while the prompt is processed, FreeVideo retries once instead of failing.", + "Easier image models: Repair asks you first and keeps the original shared file under a new name. A download that starts while FreeVideo is installing, updating or cleaning up continues by itself when that finishes.", + "Saved prompts work right after an update: prompts saved before updating FreeVideo do not need to be processed again.", + "More reliable long video redo: after a lost or late reply, choosing \"Redo from here\" again shows the part already started instead of making another one.", + "A steadier first generation after an update: cleaning up old versions no longer changes the model files in use, so the first generation after an update is not interrupted by it." + ] + }, + "zh": { + "summary": "0.6.11 新增从图片或视频反推提示词,局域网访问和 Mac 首中尾帧生成可以正常使用,Windows 上两张显卡同时生成也不再报错停下。失败提示会说明原因和下一步。", + "changes": [ + "反推提示词:在图像视图和创作面板中,可以选一张图片或一段视频,自动写出描述。", + "局域网访问更完整:通过局域网地址打开 FreeVideo 时,可以带参考图生成、编辑已生成的图片,也可以复制提示词。", + "Mac 首中尾帧生成:在 Mac 上同时使用首帧、中间帧和尾帧,可以正常生成。", + "多显卡同时生成:在 Windows 上使用两张显卡时,第二张显卡开始的生成不再因等待第一张而报错停下。", + "失败提示更清楚:各类失败都会说明下一步怎么做。提示词增强的结果不完整时,会写明是哪里不对。", + "显卡驱动提示更准确:缺少可用驱动时,启动器会显示检测到的显卡型号,并区分“未安装驱动”和“驱动未正常工作”。", + "LoRA 和参考图会保留:创作面板设置的 LoRA 和参考图在重启 FreeVideo 后仍在;场景卡和道具卡也会记住生成图片时用的 LoRA。", + "运行更稳定:从任何文件夹运行 FreeVideo 命令,都会使用已安装的程序。处理提示词时显存不足,会自动重试一次,不再直接失败。", + "图像模型更省心:修复时会先请您确认,原有的共用文件改名保留。FreeVideo 正在安装、更新或清理时开始的下载,会在结束后自动继续。", + "更新后可直接使用已保存的提示词:更新 FreeVideo 后,已保存的提示词不需要重新处理。", + "长视频重新生成更可靠:在网络回复丢失或延迟后再次点击“从这段重新生成”,会继续显示已经开始的那一段,不会多生成一段。", + "更新后第一次生成更稳定:清理旧版本时不再改动正在使用的模型文件,更新后的第一次生成不会因此中断。" + ] + } + }, { "product_version": "0.6.10", "en": { @@ -409,41 +434,6 @@ "教程:新增关闭启动器、修复模型文件、在画布上做不同比例图片三章。" ] } - }, - { - "product_version": "0.5.4", - "en": { - "summary": "Closing the launcher offers Exit or Run in background. Offline installation saves disk space and reuses an existing model folder. An interrupted second pass resumes from its last completed step, the second pass uses less graphics memory, and extending the same video again starts sooner. Picture shape can be chosen on a canvas with pictures, and several installation stops are fixed.", - "changes": [ - "Closing the launcher: a choice appears with Exit, which stops generation and quits, and Run in background, which hides the window while generation continues and can be reopened or quit from the tray icon (the menu bar icon on Mac).", - "Second pass: after an interruption by a lack of system memory, the retry continues from the last completed step instead of starting again, and the result is identical to an uninterrupted run. At high resolution the second pass uses up to about 2 GB less graphics memory, which leaves 8 GB cards more room. With a long reference video, a refused locked-page copy falls back to ordinary memory instead of failing the second pass at its start.", - "Extending videos: memory for the ending clip is estimated from its real size, so a loaded model is no longer released and read from disk again. Extending the same video again does not encode its ending a second time, so the next extension starts sooner.", - "Offline installation: importing the runtime package again in place counts model packs that are already installed, without unpacking them again or keeping two copies. An existing model folder can be chosen when installing from the runtime package, and matching models are used directly, which saves a download of about 49 GiB. After a move, model pack status follows the new location, and imported folders have shorter paths, so an installation in an ordinary folder starts from where it is.", - "Model files: when a model file differs from the tested version, the failure card names the package to import again, and the original file is kept under a new name while the version from the package replaces it.", - "Pictures: choose the shape of a new picture on a canvas that already holds pictures; with another shape the new picture is placed on a new canvas and can be undone in one step. A long description expands only while focused and shows on one line otherwise, so a multi-line description no longer moves the canvas in narrow windows. Prompt rewriting without pictures keeps the unused vision part in main memory when it would leave little graphics memory to spare.", - "Launcher and image models: while an image model is in use, Repair and Delete are gray, with the reason and what to do written beside them.", - "Linux installation: the chosen drive is checked first, and FAT32, exFAT or a location that does not allow running programs stops the installation with an explanation and a request to choose another drive.", - "Windows installation: setup no longer stops at a PowerShell debugger prompt, and the launcher no longer stops at the check step with Access denied when Windows briefly holds a file that was just written; it retries for a few seconds and then copies the folder into place. Installing node dependencies and updating the engine also use short paths.", - "Export and dubbing: several calculations no longer depend on a component that Windows application control can block, and the output is unchanged.", - "Long videos and reports: when the record of a seam is missing, that part is generated again once; a seam that still has no record at join time is joined directly, so the video can still be saved. Failed long video requests, chat sends and high-resolution image runs leave the diagnostic report the facts needed to find the cause." - ] - }, - "zh": { - "summary": "关闭启动器时可选“退出”或“后台运行”。离线安装更省空间,并可直接使用已有模型文件夹。第二遍被中断后从已完成的步骤继续,第二遍少占显存,再次续写同一个视频起步更快。已有图片的画布可以选择新图比例,Windows 和 Linux 的若干安装中断问题已修复。", - "changes": [ - "关闭启动器:弹出选择,“退出”停止生成并退出,“后台运行”隐藏窗口、生成继续,可从托盘图标(Mac 为菜单栏图标)重新打开或退出。", - "第二遍:因系统内存不足中断后,重试从已完成的步骤继续,不再全部重做,结果与不中断时完全一致。高分辨率时第二遍最多少占约 2 GB 显存,8 GB 显卡的余量更大。带长参考视频时,锁页内存被系统拒绝就改用普通内存,不再在第二遍开始时整个失败。", - "续写:按结尾片段的实际大小估算内存,已载入的模型不再被放掉、重新读盘。续写同一个视频时不再重复编码它的结尾,再次续写起步更快。", - "离线安装:原地重新导入运行环境包时,已装好的模型包直接算数,不再重新解压,也不再占双份空间。用运行环境包安装时也能选已有的模型文件夹,对得上的模型直接使用,免下约 49 GiB。换了安装位置后,模型包状态按新位置显示;导入后的文件夹路径变短,放在普通文件夹里的安装直接从原位置启动。", - "模型文件:模型文件与测试过的版本不一致时,出错卡片写明重新导入哪个包;原文件改名保留,再换成包里的版本。", - "图片:画布已有图片时可选择新图的比例;选了别的比例,新图放在新画布上,可一次撤销。较长的描述只在输入框获得焦点时展开,否则以一行加省略号显示,窄窗口里输入多行描述时画布不再被顶动。无图的提示词改写在显存余量不大时,把用不到的视觉部分留在内存。", - "启动器与图像模型:图像模型正在使用时,“修复”“删除”变灰,旁边写明原因和怎么做。", - "Linux 安装:安装前检查所选硬盘,FAT32、exFAT 或不允许运行程序的位置会先停下并说明,请选择其他硬盘。", - "Windows 安装:安装不再停在 PowerShell 调试提示符;Windows 短暂占用刚写好的文件时,启动器不再停在检查步骤报“访问被拒绝”,改为重试数秒再复制到位。安装节点依赖、更新引擎时也使用短路径。", - "导出和配音:几处计算不再依赖可能被 Windows 应用控制拦截的组件,输出不变。", - "长视频与报告:接缝记录缺失时,该段重新生成一次;合并时仍缺少记录的接缝按直接拼接保存,不再因此无法保存。长视频提交、聊天发送和高分辨率图片生成失败时,诊断报告记下判断原因所需的信息。" - ] - } } ] }