Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
20 commits
Select commit Hold shift + click to select a range
51a3c32
Setup clones the model source on drives where Git cannot see who owns…
KBRASK Dec 2, 2026
0adcf9f
Prompt enhancement: the prompt model runs on CUDA's native allocator …
KBRASK Dec 2, 2026
320cf3d
Launcher: an engine update that waits for a video goes back to how th…
KBRASK Dec 2, 2026
688786f
Fast level on a Mac: choosing it after the Studio opened no longer st…
KBRASK Dec 2, 2026
f28879b
Feedback: the diagnostic info carries why the engine stopped earlier …
KBRASK Dec 2, 2026
cdbb594
Autopilot entry: an assistant interface that could not start this tim…
KBRASK Dec 2, 2026
a7511b8
Settings, Version and updates: release notes fold by change, each sho…
KBRASK Dec 2, 2026
0e4fe09
Take music out of the pauses of a voice sample
KBRASK Dec 2, 2026
febeb5b
Create panel: the Quality title's line carries the time, and the colu…
KBRASK Dec 2, 2026
a8b0f30
Update README and release page wording
KBRASK Dec 2, 2026
d74e6a1
Prompt enhancement for pictures: a <Picture N> of the prompt that the…
KBRASK Dec 2, 2026
9c1b5f4
Editor sound separation and voice changes renew a lost page session i…
KBRASK Dec 2, 2026
6028c17
The GitHub mirror fetches the text encoder's ComfyUI source under its…
KBRASK Dec 2, 2026
93a543a
Git downloads read English messages and move on to the next source wh…
KBRASK Dec 2, 2026
5ead31b
Launcher settings at 400 px: page and choice names stay whole, and a …
KBRASK Dec 2, 2026
4057229
Launcher choices take the keyboard: one Tab stop per set, arrow keys …
KBRASK Dec 2, 2026
72e2650
Launcher choices take all four arrow keys, as radio buttons do: on a …
KBRASK Dec 2, 2026
4aaa70a
Prompt rewrite: when closing the listed programs cannot free enough g…
KBRASK Dec 2, 2026
2907518
Launcher: failed GPU kernel checks name each failed check and its las…
KBRASK Dec 2, 2026
f021827
Release 0.6.21: update notes
KBRASK Dec 2, 2026
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 4 additions & 1 deletion freevideo_engine/agent/cast.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@
import threading
import uuid

from . import assets, errors, operation_receipts, schema, spec
from . import assets, errors, operation_receipts, schema, spec, voice_clean
from .jobs import ACTIVE, DONE, JobError, iso

CARD = re.compile(r'c[0-9a-f]{12}')
Expand Down Expand Up @@ -527,6 +527,9 @@ def _voice(self, identity, value):
'Send voice.media with audio, and voice.start and voice.end 2 to 15 seconds apart.')
if written < end - start - .01:
end = start + written # The audio ended before the requested end: the card shows the clip it has.
separate = voice_clean.separator(self.jobs)
if separate:
voice_clean.clean(port.input_path(clip), separate) # Music under the pauses would be copied into every line.
return dict(media=kept, start=start, end=round(end, 3), clip=dict(file=clip))

# Operations ---------------------------------------------------------------------------------------
Expand Down
5 changes: 3 additions & 2 deletions freevideo_engine/agent/routes.py
Original file line number Diff line number Diff line change
Expand Up @@ -854,8 +854,9 @@ async def discover(request):
from .guide import connection_discovery
root = installation_root()
if root in token_failures:
# No token this startup: the same single answer as when it is off, so the page shows no agent controls.
return reply({'enabled': False})
# No token this startup: not on, but not switched off either. The page keeps its Autopilot entry and says to
# restart (reason not_ready), where an interface switched off (FREEVIDEO_AGENT=0) shows no agent controls.
return reply({'enabled': False, 'reason': 'not_ready'})
return reply(connection_discovery(root, request.scheme + '://' + request.host, request[query_key].get('lang')))

@routes.get('/freevideo/agent/session')
Expand Down
191 changes: 191 additions & 0 deletions freevideo_engine/agent/voice_clean.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,191 @@
"""Music left in the pauses of a voice sample is taken out before the sample is kept.

A generated voice sample sometimes carries a quiet chord under its pauses even when the prompt asks for none. The
sound is separated; the pauses are found on the dialogue track (the mix has music under the speech too, so its own
loudness does not tell speech from pause), and the music track is measured there. Where music is heard the clip becomes the
dialogue track, but only when the pauses of that track are clean and the track still carries the speech (a sung or heavily
processed voice can land on the music track, and the clip must never become silence); otherwise the clip stays as it was.
"""
import logging
import os
from pathlib import Path
import tempfile
import time
import wave

import numpy as np

LOGGER = logging.getLogger(__name__)
FRAME = .02 # seconds per envelope frame
SPEECH_FROM = .05 # a frame is speech above this share of the track's 95th percentile envelope ...
SPEECH_GROW = .15 # ... and so is everything within this many seconds of one
MIN_PAUSE = .4 # seconds a pause must last to be measured
LIMIT = 90. # seconds the separation of one sample may take before the sample is kept as it was
MUSIC_LEVEL = -50. # dBFS of the music track in the pauses at or above which music plays under them
CLEAN_LEVEL = -60. # dBFS of the dialogue track in the pauses (and of the narrow chord band) at or below which it is clean
CLEAN_CHORD = -80.
SPEECH_LEVEL = -40. # dBFS the dialogue track must reach where it speaks, and ...
SPEECH_LOSS = 6. # ... dB below the mix there at most, or the separation lost the speech and the clip is kept
CHORD = (392., 523., 784.)
CHORD_WIDTH = 8.


def _db(x):
return float(20 * np.log10(np.sqrt(np.mean(x.astype(np.float64) ** 2)) + 1e-9)) if len(x) else -99.


def _chord_db(x, rate):
"""Power of the chord bands in x (windows of up to 1 s, half overlapping), dBFS."""
n = min(rate, len(x))
if n < rate // 4:
return -99.
windows = [np.abs(np.fft.rfft(x[i:i + n] * np.hanning(n))) ** 2 for i in range(0, len(x) - n + 1, max(1, n // 2))]
power = np.mean(windows, 0) / (n * .375) / n * 2
bins = np.fft.rfftfreq(n, 1 / rate)
return float(10 * np.log10(sum(power[abs(bins - c) < CHORD_WIDTH].sum() for c in CHORD) + 1e-18))


def pauses(voice, rate):
"""Sample ranges [(a, b)] where the voice track is silent for at least MIN_PAUSE seconds, 0.15 s off the speech."""
frame = int(rate * FRAME)
count = len(voice) // frame
if count == 0:
return []
envelope = np.sqrt((voice[:count * frame].astype(np.float64).reshape(count, frame) ** 2).mean(1))
grow = int(round(SPEECH_GROW / FRAME))
speech = np.convolve(envelope > np.percentile(envelope, 95) * SPEECH_FROM, np.ones(2 * grow + 1), 'same') > 0
found, index = [], 0
while index < count:
if speech[index]:
index += 1
continue
end = index
while end < count and not speech[end]:
end += 1
if (end - index) * FRAME >= MIN_PAUSE:
found.append((index * frame, end * frame))
index = end
return found


def _joined(x, spans):
return np.concatenate([x[a:b] for a, b in spans]) if spans else np.zeros(0, np.float32)


def judge(music, dialogue, rate):
"""(the music track is audible in the pauses, the dialogue track is clean there). Both are False when there is no
pause to measure."""
spans = pauses(dialogue, rate)
if not spans:
return False, False
chord = lambda x: max(_chord_db(x[a:b], rate) for a, b in spans)
heard = _db(_joined(music, spans)) >= MUSIC_LEVEL
left = _joined(dialogue, spans)
return heard, _db(left) <= CLEAN_LEVEL and chord(dialogue) <= CLEAN_CHORD


def speech_kept(mix, dialogue, rate):
"""The dialogue track still carries the speech of the mix: outside its pauses it reaches SPEECH_LEVEL and stays within
SPEECH_LOSS dB of the mix. A track that is empty or only holds leakage, the voice having gone to the music track, fails."""
edges = [0] + [i for a, b in pauses(dialogue, rate) for i in (a, b)] + [len(dialogue)]
speech = [(edges[i], edges[i + 1]) for i in range(0, len(edges), 2) if edges[i + 1] > edges[i]]
level = _db(_joined(dialogue, speech))
return level >= SPEECH_LEVEL and level >= _db(_joined(mix, speech)) - SPEECH_LOSS


def _read(path, rate):
"""Mono float32 samples of an audio file at `rate`."""
import av
chunks = []
with av.open(str(path)) as container:
stream = next(iter(container.streams.audio))
resampler = av.AudioResampler(format='flt', layout='mono', rate=rate)
for frame in container.decode(stream):
chunks.extend(f.to_ndarray().reshape(-1) for f in resampler.resample(frame))
chunks.extend(f.to_ndarray().reshape(-1) for f in resampler.resample(None))
return np.concatenate(chunks).astype(np.float32) if chunks else np.zeros(0, np.float32)


def _read_clip(path):
with wave.open(str(path)) as stream:
rate = stream.getframerate()
samples = np.frombuffer(stream.readframes(stream.getnframes()), '<i2').astype(np.float32) / 32768
return samples, rate


def _write_clip(path, samples, rate):
path = Path(path)
temporary = path.with_name('.%s.clean' % path.name)
try:
with wave.open(str(temporary), 'wb') as stream:
stream.setnchannels(1)
stream.setsampwidth(2)
stream.setframerate(rate)
stream.writeframes((np.clip(samples, -1, 1) * 32767).astype('<i2').tobytes())
os.replace(temporary, path)
finally:
temporary.unlink(missing_ok=True)


def _stopped(error):
"""A video that started, a resident process at work or the time limit stop the separation by design."""
if isinstance(error, InterruptedError):
return True
try:
from ..music.service import Preempted
except ImportError:
return False
return isinstance(error, Preempted)


def clean(clip, separate):
"""Replace the clip (a mono WAV) by its dialogue track when music is heard in its pauses, the dialogue track is
clean there and it kept the speech. `separate(source, out_dir)` writes dialogue.wav and music.wav into out_dir.
Returns True when the clip was replaced; any failure leaves the clip as it was."""
try:
mix, rate = _read_clip(clip)
if len(mix) < rate:
return False
with tempfile.TemporaryDirectory(prefix='voice-clean-') as folder:
separate(Path(clip), Path(folder))
dialogue = _read(Path(folder) / 'dialogue.wav', rate)
music = _read(Path(folder) / 'music.wav', rate)
length = min(len(mix), len(dialogue), len(music))
mix, dialogue, music = mix[:length], dialogue[:length], music[:length]
heard, clean_after = judge(music, dialogue, rate)
if not (heard and clean_after and speech_kept(mix, dialogue, rate)):
return False
_write_clip(clip, dialogue, rate)
return True
except Exception as error: # noqa: BLE001 - the sample is kept as it is whatever the separation did
if _stopped(error):
LOGGER.info('The voice sample was kept as it was; the separation stopped (%s)', type(error).__name__)
else:
LOGGER.warning('The voice sample was kept as it was; its pauses could not be cleaned', exc_info=True)
return False


def separator(jobs):
"""`separate(source, out_dir)` when this machine can split sound now, else None: an NVIDIA card with enough video
memory, the model already on disk (nothing is downloaded for a sample), and no video, image or prompt job running.
A video that starts meanwhile stops the separation and the sample is kept as it was."""
try:
from ..comfy_bridge import installation
from ..stems import service
from .routes import stems_supported
from .stems import _busy
root, machine = installation()
if not stems_supported(machine) or not service.ready(machine['model_root']) or _busy(jobs):
return None
# With the server, the separation first lets an idle image worker hand back the card and unloads ComfyUI's own
# models, as a stems job does; without it the engine lock stays taken after a picture and nothing is cleaned.
server = getattr(jobs.port, 'server', None)

def separate(source, out_dir):
deadline = time.monotonic() + LIMIT
# The model deleted meanwhile would make the service download it: that stops the separation instead.
return service.separate(source, out_dir, server=server, cancelled=lambda: time.monotonic() > deadline
or not service.ready(machine['model_root']))
return separate
except Exception: # noqa: BLE001 - no machine information, or no engine here: no cleaning
return None
18 changes: 18 additions & 0 deletions freevideo_engine/comfy_environment.py
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,24 @@ def configure_control(command, environment):
return [*command, '--cpu'], env


def native_allocator(env):
"""``env`` with CUDA's native caching allocator where ComfyUI had chosen the asynchronous one.

ComfyUI turns ``backend:cudaMallocAsync`` on in its own process and every child inherits it. The video worker
names its allocator itself; the picture and prompt workers take this one, so their card memory is counted by the
allocator their placement plans were measured with."""
selected = env.get('PYTORCH_ALLOC_CONF', env.get('PYTORCH_CUDA_ALLOC_CONF'))
if not selected or 'cudaMallocAsync' not in selected:
return env
options = ['backend:native' if option.strip() == 'backend:cudaMallocAsync' else option
for option in selected.split(',')]
if 'backend:native' not in options:
options.insert(0, 'backend:native')
value = ','.join(option for option in options if 'cudaMallocAsync' not in option)
env.update(PYTORCH_ALLOC_CONF=value, PYTORCH_CUDA_ALLOC_CONF=value)
return env


def isolated_environment(root, source, environ=None):
"""Remove inherited Python/package targets only in the engine's child."""
from .proxy import inherited
Expand Down
24 changes: 23 additions & 1 deletion freevideo_engine/failure_details.py
Original file line number Diff line number Diff line change
Expand Up @@ -447,6 +447,28 @@ def kernel_check_lines(rows, limit=6, width=240):
return ''.join('\n' + line for line in lines)


# The lines kernel_check_lines writes under the cause: one per failed check ("<backend>: <its last line>"), and the summary
# lines around them.
_KERNEL_CHECK_LINE = re.compile(r'(?:Required linear kernel did not pass\.|No attention backend passed\.'
r'|\d+ more failed checks are in the saved details\.|[a-z][a-z0-9-]*: .*)')


def _without_kernel_check_lines(text):
"""The failed kernel checks' cause without the lines kernel_check_lines put under it, when matching failure guidance.

Those lines tell the reader why each check failed; one that mentions memory, a denied file or a missing package must
not turn the card into that failure's guidance. The complete text stays in the caller's retained and copied output.
"""
kept, below_cause = [], False
# A traceback also quotes the raising source line, so every line holding the cause is followed.
for line in text.split('\n'):
if below_cause and _KERNEL_CHECK_LINE.fullmatch(line):
continue
below_cause = KERNEL_CHECKS_FAILED in line
kept.append(line)
return '\n'.join(kept)


def with_kernel_check_lines(error, hardware):
"""The error of failed GPU kernel checks followed by what each failed check reported; any other error as it is."""
if not str(error).startswith(KERNEL_CHECKS_FAILED):
Expand Down Expand Up @@ -1171,7 +1193,7 @@ class names and errno, no text), when the message is that exception's str(); it
"""
if not value:
return dict(title='', detail='', action='', kind='')
text = _without_ready_curl_diagnostics(str(value))
text = _without_kernel_check_lines(_without_ready_curl_diagnostics(str(value)))
# Match only the cause position, never an echoed input or a log line below it.
# Holder diagnostics follow this exact cause; they are not part of its signature.
causes = [line.strip() for line in text.splitlines() if line.strip()]
Expand Down
18 changes: 15 additions & 3 deletions freevideo_engine/feedback.py
Original file line number Diff line number Diff line change
Expand Up @@ -51,13 +51,16 @@ def scrub(value):
return TOKEN.sub('<token>', EMAIL.sub('<email>', value))


def summary(report, machine=None):
def summary(report, machine=None, engine_exit=None):
"""The diagnostic summary: the same redacted fields the report form uses, no prompt or picture.

report is the parsed diagnostic report of the latest generation (or None);
machine is the installation's machine record (or None).
machine is the installation's machine record (or None);
engine_exit is why the ComfyUI before this one stopped (engine_exit.public: numbers and fixed words), or None.
"""
out = {}
if isinstance(engine_exit, dict) and engine_exit:
out['engine_exit'] = engine_exit
hardware = {}
if isinstance(machine, dict) and isinstance(machine.get('hardware'), dict):
hardware.update({k: v for k, v in machine['hardware'].items() if k in HARDWARE_KEYS})
Expand Down Expand Up @@ -126,4 +129,13 @@ def collect(report_id=None):
machine = dict(machine, hardware=setup_hardware(machine))
except Exception: # Setup problems must not stop a suggestion from being sent.
machine = None
return summary(report, machine)
stopped = None
try:
# A failure card's message cannot say why the engine stopped while it is gone; once it answers again, a
# suggestion carries the stop of this launcher run, as a diagnostic report does. An earlier run's is left out.
from .comfy_bridge import installation_root
from .engine_exit import current, public
stopped = public(current(installation_root()))
except Exception:
stopped = None
return summary(report, machine, stopped)
20 changes: 1 addition & 19 deletions freevideo_engine/image_gen/service.py
Original file line number Diff line number Diff line change
Expand Up @@ -114,24 +114,6 @@ def write_refused(error):
'invalid_layout', 'too_many_boxes', 'layout_too_long')) | LORA_ERRORS


def native_allocator(env):
"""``env`` with CUDA's native caching allocator where ComfyUI had chosen the asynchronous one.

ComfyUI turns ``backend:cudaMallocAsync`` on in its own process and every child inherits it. The video worker
names its allocator itself; the picture worker did not, so its card memory was counted by an allocator the
placement plan was never measured with."""
selected = env.get('PYTORCH_ALLOC_CONF', env.get('PYTORCH_CUDA_ALLOC_CONF'))
if not selected or 'cudaMallocAsync' not in selected:
return env
options = ['backend:native' if option.strip() == 'backend:cudaMallocAsync' else option
for option in selected.split(',')]
if 'backend:native' not in options:
options.insert(0, 'backend:native')
value = ','.join(option for option in options if 'cudaMallocAsync' not in option)
env.update(PYTORCH_ALLOC_CONF=value, PYTORCH_CUDA_ALLOC_CONF=value)
return env


def comfy_server():
"""ComfyUI's server in this process, or None (tests, the engine's own command line)."""
try:
Expand Down Expand Up @@ -2521,7 +2503,7 @@ def resident_endpoint(self):

def environment(self, root):
from ..comfy_bridge import source_root
from ..comfy_environment import isolated_environment
from ..comfy_environment import isolated_environment, native_allocator
from .. import processes, resident_process
env = isolated_environment(root, source_root())
for name in ('FREEVIDEO_RUNTIME_LOCK_FD', processes.HANDLE_ENV, resident_process.ENV,
Expand Down
Loading