Skip to content

Make videos on the computer you already own. FreeVideo runs MiniMax H3 in as little as 8 GB of VRAM and 16 GB of RAM, and adapts its acceleration path to your hardware.

Editor: automatic subtitles from the timeline's sound

Bowen Xue7ed3998d022c
diff --git a/__init__.py b/__init__.py
index 43f0a9a..8976603 100644
--- a/__init__.py
+++ b/__init__.py
@@ -29,6 +29,10 @@ async def comfy_entrypoint():
editor_export_routes()
from .freevideo_engine.comfy_capabilities import register as capabilities_routes
capabilities_routes()
+ from .freevideo_engine.subtitle_ears import register as subtitle_ears_routes
+ subtitle_ears_routes()
+ from .freevideo_engine.subtitle_files import register as subtitle_file_routes
+ subtitle_file_routes()
from .freevideo_engine.comfy_share import register as share_routes
share_routes()
from .freevideo_engine.comfy_metadata import register as workflow_backfill
diff --git a/freevideo_engine/editor_export.py b/freevideo_engine/editor_export.py
index d85d504..cac5045 100644
--- a/freevideo_engine/editor_export.py
+++ b/freevideo_engine/editor_export.py
@@ -80,6 +80,13 @@ def _reason(error):
return 'failed'
+def _without_subtitles(project, settings):
+ """`subtitles: none` leaves the subtitle track out of the picture (text clips stay)."""
+ if settings.subtitles != 'none':
+ return project
+ return {**project, 'tracks': [t for t in project['tracks'] if t.get('kind') != 'subtitle']}
+
+
def _check(cancelled):
if cancelled and cancelled():
raise ExportCancelled('cancelled')
@@ -651,11 +658,12 @@ def _render_once(project, resolve, target, *, progress, cancelled, options, repa
complete = False
try:
width, height, total, tracks = _layout(project)
- check_export_text(project)
settings = editor_export_options.effective(options, width, height, total)
width, height, total = settings.width, settings.height, settings.frames
if settings.only == 'sound':
tracks = {key: clips for key, clips in tracks.items() if key != 'v1'}
+ else:
+ check_export_text(_without_subtitles(project, settings))
_check(cancelled)
_checked_target(target)
_checked_target(temporary)
@@ -752,7 +760,7 @@ def _render_once(project, resolve, target, *, progress, cancelled, options, repa
pixels = (decoders['v1'].pixels(clip['in'] + number - clip['start'])
if clip is not None and 'v1' in decoders else black)
# Text is placed on the timeline frame; its layout is proportional to the output size.
- pixels = paint_project(pixels, project, number, width, height)
+ pixels = paint_project(pixels, _without_subtitles(project, settings), number, width, height)
frame = av.VideoFrame.from_ndarray(pixels, format='rgb24')
frame.pts, frame.time_base = number - settings.start, Fraction(1, FPS)
for packet in video.encode(frame):
@@ -1000,8 +1008,9 @@ class ExportQueue:
width, height, frames, _ = _layout(project)
except ExportError:
raise ValueError('Project cannot be exported') from None
- check_export_text(project)
settings = editor_export_options.validate({} if options is None else options, width, height, frames)
+ if settings.only != 'sound':
+ check_export_text(_without_subtitles(project, settings))
job = dict(id='x-' + uuid.uuid4().hex, state='running', fraction=0., work=None, reason=None,
project=project, options=settings, stop=threading.Event())
with self.lock:
diff --git a/freevideo_engine/editor_export_options.py b/freevideo_engine/editor_export_options.py
index 437c17b..89df3bf 100644
--- a/freevideo_engine/editor_export_options.py
+++ b/freevideo_engine/editor_export_options.py
@@ -13,6 +13,7 @@ class ExportOptions:
only: str = 'video'
quality: str = 'high'
sound_format: str = 'm4a'
+ subtitles: str = 'burn'
@property
def filename(self):
@@ -39,18 +40,19 @@ class ExportOptions:
return dict(width=self.width, height=self.height, frames=self.frames,
only=self.only, quality=self.quality if self.only == 'video' else None,
range=dict(start=self.start, frames=self.frames),
- sound_format=self.sound_format if self.only == 'sound' else None)
+ sound_format=self.sound_format if self.only == 'sound' else None,
+ **({'subtitles': 'none'} if self.only == 'video' and self.subtitles == 'none' else {}))
def validate(options, width, height, frames):
"""Validate wire values once; the queue passes the immutable result to render."""
- if not isinstance(options, dict) or set(options) - {'short', 'quality', 'range', 'only', 'sound_format'}:
+ if not isinstance(options, dict) or set(options) - {'short', 'quality', 'range', 'only', 'sound_format', 'subtitles'}:
raise ValueError('Invalid export options')
if 'short' in options and (type(options['short']) is not int
or not 144 <= options['short'] <= 4320 or options['short'] % 2):
raise ValueError('Invalid export short side')
for key, allowed in (('quality', ('high', 'standard', 'small')), ('only', ('sound',)),
- ('sound_format', ('m4a', 'wav'))):
+ ('sound_format', ('m4a', 'wav')), ('subtitles', ('burn', 'none'))):
if key in options and (type(options[key]) is not str or options[key] not in allowed):
raise ValueError('Invalid export ' + key)
start, count = 0, frames
@@ -71,7 +73,8 @@ def validate(options, width, height, frames):
output_width, output_height = (long, short) if width >= height else (short, long)
if max(output_width, output_height) > 8192:
raise ValueError('Export picture is too large')
- return ExportOptions(output_width, output_height, start, count, quality=options.get('quality', 'high'))
+ return ExportOptions(output_width, output_height, start, count, quality=options.get('quality', 'high'),
+ subtitles=options.get('subtitles', 'burn'))
def effective(options, width, height, frames):
diff --git a/freevideo_engine/subtitle_cues.py b/freevideo_engine/subtitle_cues.py
new file mode 100644
index 0000000..d8ddbfb
--- /dev/null
+++ b/freevideo_engine/subtitle_cues.py
@@ -0,0 +1,233 @@
+"""Subtitle cues: timed words -> frame-exact cues, checks, and SRT/WebVTT text.
+
+Pure functions. No models, no files, no network. Times from the alignment or
+recognition step arrive in seconds; cues leave as integer frames on the 24 fps
+editor timeline, ready for the subtitle track.
+"""
+import re
+
+FPS = 24
+WRAP = .86 # editor_text.wrap_text wraps at this share of the picture width
+MIN_FRAMES = 24 # a cue stays up for a second when the next one leaves room
+GAP_BREAK = .35 # a pause this long (seconds) is a natural place to start a new cue
+MAX_CUES = 500 # the subtitle track holds at most this many clips
+
+_CJK = re.compile(r'[\u2e80-\u9fff\u3400-\u4dbf\uf900-\ufaff\uff00-\uffef\u3000-\u303f\U00020000-\U0003ffff]')
+_SOFT_END = ',,、;;::。.!?!?…'
+_TRAILING = ',,、;;::。.'
+
+
+def is_cjk(char):
+ return bool(_CJK.fullmatch(char))
+
+
+def frame_of(seconds, fps=FPS):
+ return int(seconds * fps + .5)
+
+
+def measurer(font):
+ """Width of a line the way editor_text lays it out: per-character advances."""
+ return lambda text: sum(font.getlength(char) for char in text)
+
+
+def _join(parts):
+ """Chinese runs without spaces, Latin words with one space."""
+ result = ''
+ for part in parts:
+ if result and not (is_cjk(result[-1]) or is_cjk(part[:1])) and not result.endswith(' '):
+ result += ' '
+ result += part
+ return result
+
+
+def words_of(text, start, end):
+ """Evenly spread words over one sentence when a model gave no word times."""
+ parts = []
+ for chunk in re.findall(r'\S+', text):
+ run = ''
+ for char in chunk:
+ if is_cjk(char):
+ if run:
+ parts.append(run)
+ run = ''
+ parts.append(char)
+ else:
+ run += char
+ if run:
+ parts.append(run)
+ weights = [max(1, len(p)) for p in parts]
+ total = sum(weights)
+ result, done = [], 0
+ for part, weight in zip(parts, weights):
+ result.append(dict(text=part, start=start + (end - start) * done / total,
+ end=start + (end - start) * (done + weight) / total))
+ done += weight
+ return result
+
+
+def _clean(text):
+ text = text.strip()
+ while text and text[-1] in _TRAILING:
+ text = text[:-1].rstrip()
+ return text
+
+
+def _segments(words, measure, limit):
+ """Indexes where each cue starts; greedy fill, preferring pauses and punctuation."""
+ cuts, begin, best = [0], 0, None
+ for index in range(1, len(words)):
+ previous = words[index - 1]
+ line = _join(w['text'] for w in words[begin:index + 1])
+ soft = previous['text'][-1:] in _SOFT_END or words[index]['start'] - previous['end'] >= GAP_BREAK
+ if soft and index - begin >= 2:
+ best = index
+ if measure(_clean(line)) > limit:
+ cut = best if best is not None and best > begin else index
+ cuts.append(cut)
+ begin, best = cut, None
+ if cut != index:
+ # Re-check what stayed behind the cut with the current word.
+ again = _join(w['text'] for w in words[begin:index + 1])
+ if measure(_clean(again)) > limit:
+ cuts.append(index)
+ begin = index
+ return cuts
+
+
+def build_cues(sentences, measure, width, *, fps=FPS, total_frames=None, min_frames=MIN_FRAMES):
+ """Sentences with times -> [{start, frames, text, sentence}], non-overlapping.
+
+ `sentences`: dicts with text, start, end (seconds), optional words
+ [{text,start,end}] and matched (False sentences are skipped; no time is
+ invented for them). `measure(text)` and `width` come from the picture:
+ each cue fits one line at the project's real font and size.
+ """
+ limit = width * WRAP
+ cues = []
+ for number, sentence in enumerate(sentences):
+ if sentence.get('matched', True) is False or not str(sentence.get('text', '')).strip():
+ continue
+ words = [w for w in (sentence.get('words') or []) if str(w.get('text', '')).strip()] \
+ or words_of(sentence['text'], sentence['start'], sentence['end'])
+ cuts = _segments(words, measure, limit) + [len(words)]
+ groups = [words[first:last] for first, last in zip(cuts, cuts[1:]) if words[first:last]]
+ # A one- or two-character tail reads badly alone: fold it back when it fits,
+ # otherwise hand it words from the piece before it.
+ if len(groups) > 1 and len(_join(w['text'] for w in groups[-1]).replace(' ', '')) <= 2:
+ joined = groups[-2] + groups[-1]
+ if measure(_clean(_join(w['text'] for w in joined))) <= limit:
+ groups[-2:] = [joined]
+ else:
+ while len(groups[-2]) > 3 and len(_join(w['text'] for w in groups[-1]).replace(' ', '')) <= 2:
+ groups[-1].insert(0, groups[-2].pop())
+ pieces = [(_clean(_join(w['text'] for w in g)), g[0]['start'], g[-1]['end']) for g in groups]
+ for text, start, end in pieces:
+ if text:
+ first_frame = frame_of(start, fps)
+ cues.append(dict(start=first_frame, frames=max(1, frame_of(end, fps) - first_frame), text=text, sentence=number))
+ return settle(cues, total_frames=total_frames, min_frames=min_frames)
+
+
+def settle(cues, *, total_frames=None, min_frames=MIN_FRAMES):
+ """Order, remove overlap, hold each cue at least `min_frames` when there is room."""
+ cues = sorted((dict(c) for c in cues), key=lambda c: (c['start'], c['frames']))
+ result = []
+ for cue in cues:
+ if result:
+ last = result[-1]
+ if cue['start'] < last['start'] + last['frames']:
+ last['frames'] = max(1, cue['start'] - last['start'])
+ result.append(cue)
+ for index, cue in enumerate(result):
+ room = result[index + 1]['start'] if index + 1 < len(result) else (total_frames if total_frames is not None else 10 ** 7)
+ if cue['frames'] < min_frames:
+ cue['frames'] = max(cue['frames'], min(min_frames, room - cue['start']))
+ if total_frames is not None:
+ result = [c for c in result if c['start'] < total_frames]
+ for cue in result:
+ cue['frames'] = min(cue['frames'], total_frames - cue['start'])
+ return result[:MAX_CUES]
+
+
+def check_cues(cues, measure, width, *, total_frames=None):
+ """Problems a writer should fix before the track is saved. Empty means fine."""
+ limit = width * WRAP
+ problems, end = [], 0
+ if len(cues) > MAX_CUES:
+ problems.append(dict(index=MAX_CUES, reason='too_many'))
+ for index, cue in enumerate(cues):
+ if not (isinstance(cue.get('start'), int) and isinstance(cue.get('frames'), int)) or cue['start'] < 0 or cue['frames'] < 1:
+ problems.append(dict(index=index, reason='time'))
+ continue
+ if cue['start'] < end:
+ problems.append(dict(index=index, reason='overlap'))
+ end = cue['start'] + cue['frames']
+ if total_frames is not None and end > total_frames:
+ problems.append(dict(index=index, reason='after_end'))
+ text = cue.get('text')
+ if not isinstance(text, str) or not text.strip() or len(text) > 8000:
+ problems.append(dict(index=index, reason='text'))
+ continue
+ lines = text.split('\n')
+ if len(lines) > 2:
+ problems.append(dict(index=index, reason='too_many_lines'))
+ if any(measure(line) > limit for line in lines):
+ problems.append(dict(index=index, reason='too_wide'))
+ return problems
+
+
+def _clock(frame, fps, comma):
+ millis = (frame * 1000 * 2 + fps) // (2 * fps) # nearest millisecond, ties up
+ hours, millis = divmod(millis, 3600000)
+ minutes, millis = divmod(millis, 60000)
+ seconds, millis = divmod(millis, 1000)
+ return '%02d:%02d:%02d%s%03d' % (hours, minutes, seconds, ',' if comma else '.', millis)
+
+
+def _body(text):
+ return '\n'.join(line for line in text.replace('\r\n', '\n').replace('\r', '\n').split('\n') if line.strip())
+
+
+def to_srt(cues, *, fps=FPS, offset=0):
+ """SubRip with a UTF-8 byte order mark, which every common player accepts."""
+ blocks = []
+ for number, cue in enumerate(cues, 1):
+ start = cue['start'] - offset
+ blocks.append('%d\n%s --> %s\n%s\n' % (number, _clock(start, fps, True),
+ _clock(start + cue['frames'], fps, True), _body(cue['text'])))
+ return '\ufeff' + '\n'.join(blocks)
+
+
+def to_vtt(cues, *, fps=FPS, offset=0):
+ blocks = ['WEBVTT\n']
+ for cue in cues:
+ start = cue['start'] - offset
+ text = _body(cue['text']).replace('&', '&amp;').replace('<', '&lt;').replace('>', '&gt;')
+ blocks.append('%s --> %s\n%s\n' % (_clock(start, fps, False), _clock(start + cue['frames'], fps, False), text))
+ return '\n'.join(blocks)
+
+
+def from_srt(text, *, fps=FPS):
+ """Parse SubRip back into cues (the same limits as the page's importer)."""
+ if not isinstance(text, str) or len(text) > 4 * 1024 * 1024:
+ raise ValueError('Invalid subtitles')
+ blocks = re.split(r'\n\s*\n', text.lstrip('\ufeff').replace('\r\n', '\n').replace('\r', '\n').strip())
+ if not blocks or len(blocks) > MAX_CUES:
+ raise ValueError('Invalid subtitles')
+ cues, end = [], 0
+ for block in blocks:
+ lines = block.split('\n')
+ if re.fullmatch(r'\d+', lines[0]):
+ lines.pop(0)
+ match = re.fullmatch(r'(\d{2,3}):([0-5]\d):([0-5]\d)[,.](\d{3}) --> (\d{2,3}):([0-5]\d):([0-5]\d)[,.](\d{3})', lines.pop(0)) if lines else None
+ if not match or not lines:
+ raise ValueError('Invalid subtitles')
+ def at(base):
+ h, m, s, ms = (int(match.group(base + i)) for i in range(4))
+ return frame_of(h * 3600 + m * 60 + s + ms / 1000, fps)
+ start, stop = at(1), at(5)
+ if start < end or stop <= start or stop > 10 ** 7:
+ raise ValueError('Invalid subtitles')
+ end = stop
+ cues.append(dict(start=start, frames=stop - start, text='\n'.join(lines)))
+ return cues
diff --git a/freevideo_engine/subtitle_ears.py b/freevideo_engine/subtitle_ears.py
new file mode 100644
index 0000000..71ae5e7
--- /dev/null
+++ b/freevideo_engine/subtitle_ears.py
@@ -0,0 +1,484 @@
+"""Subtitle "ears": the timeline's sound -> timed text (alignment or recognition).
+
+FreeVideo only listens here. Proofreading, translation, segmentation and
+layout are the brain's job (an Agent, or FreeVideo AI), which then writes the
+subtitle track with ordinary editor commands.
+
+* align: the lines are known; return when each is spoken. A line that
+ cannot be found comes back `matched: false` with no time.
+* transcribe: the lines are unknown; return what is said, with times.
+
+Times are timeline frames (24 fps), given with seconds for reading. The sound
+analysed is the saved timeline's own mix (cuts, moves, volumes and mutes
+included), so frames map straight back onto the project. A model engine is
+pluggable: any object with `align` and/or `transcribe` registered below.
+"""
+import copy
+import logging
+import re
+import shutil
+import threading
+import time
+import uuid
+from collections import deque
+from contextlib import nullcontext
+from pathlib import Path
+
+from . import editor_export as export
+from . import editor_export_options
+
+FPS = 24
+RATE = 16000
+MAX_SECONDS = 2 * 3600 # longest sound analysed in one job
+MAX_LINES = 1000
+MAX_LINE_CHARS = 2000
+MAX_JOBS = 200
+_JOB_ID = re.compile(r's-[0-9a-f]{32}')
+_LANGUAGE = re.compile(r'auto|[a-z]{2,3}(-[A-Za-z0-9]{2,8})?')
+_REASONS = ('no_engine', 'no_sound', 'too_long', 'source_missing', 'unreadable', 'disk_full', 'failed')
+
+
+class EarsError(Exception):
+ """A public reason code; engines and decoders never leak their own messages."""
+ def __init__(self, reason='failed'):
+ self.reason = reason if reason in _REASONS else 'failed'
+ super().__init__(self.reason)
+
+
+class Cancelled(InterruptedError):
+ pass
+
+
+_ENGINES = {}
+
+
+def register_engine(name, factory, *, first=False):
+ """`factory()` returns an engine, or None when its model is not installed.
+
+ An engine offers `align(audio, lines, language, progress, cancelled)` and/or
+ `transcribe(audio, language, progress, cancelled)` and returns seconds on
+ the 16 kHz mono float32 `audio` it was given.
+ """
+ _ENGINES[name] = (factory, first)
+
+
+def unregister_engine(name):
+ _ENGINES.pop(name, None)
+
+
+def engine_for(kind, name=None):
+ order = sorted(_ENGINES, key=lambda n: (not _ENGINES[n][1], n))
+ for candidate in ([name] if name else order):
+ if candidate not in _ENGINES:
+ continue
+ engine = _ENGINES[candidate][0]()
+ if engine is not None and callable(getattr(engine, kind, None)):
+ return engine
+ raise EarsError('no_engine')
+
+
+def available():
+ """Which jobs can run now: {'align': bool, 'transcribe': bool}."""
+ result = {}
+ for kind in ('align', 'transcribe'):
+ try:
+ engine_for(kind)
+ result[kind] = True
+ except EarsError:
+ result[kind] = False
+ return result
+
+
+def _whole(value, minimum=0):
+ return type(value) is int and minimum <= value <= 2 ** 53 - 1
+
+
+def validate_request(body):
+ """Wire body -> clean request dict. ValueError on anything unexpected."""
+ if not isinstance(body, dict) or set(body) - {'kind', 'id', 'revision', 'source', 'lines', 'language', 'range'}:
+ raise ValueError('Invalid request')
+ kind = body.get('kind')
+ if kind not in ('align', 'transcribe'):
+ raise ValueError('Invalid kind')
+ language = body.get('language', 'auto')
+ if not isinstance(language, str) or not _LANGUAGE.fullmatch(language):
+ raise ValueError('Invalid language')
+ request = dict(kind=kind, language=language)
+ if ('id' in body) == ('source' in body):
+ raise ValueError('Give a project or a source')
+ if 'id' in body:
+ if not isinstance(body['id'], str) or not export._PROJECT_ID.fullmatch(body['id']):
+ raise ValueError('Invalid project')
+ if 'revision' in body and not _whole(body['revision']):
+ raise ValueError('Invalid revision')
+ request.update(id=body['id'], revision=body.get('revision'))
+ else:
+ source = body['source']
+ if (not isinstance(source, dict) or set(source) != {'work'} or not isinstance(source['work'], str)
+ or not export._IMPORT_ID.fullmatch(source['work'])):
+ raise ValueError('Invalid source')
+ request['source'] = dict(source)
+ if 'range' in body:
+ span = body['range']
+ if (not isinstance(span, dict) or set(span) != {'start', 'frames'}
+ or not _whole(span['start']) or not _whole(span['frames'], 1)):
+ raise ValueError('Invalid range')
+ request['range'] = dict(start=span['start'], frames=span['frames'])
+ lines = body.get('lines')
+ if kind == 'align':
+ if (not isinstance(lines, list) or not 1 <= len(lines) <= MAX_LINES
+ or any(not isinstance(t, str) or len(t) > MAX_LINE_CHARS or re.search(r'[\x00-\x08\x0b-\x1f\x7f]', t)
+ for t in lines) or not any(t.strip() for t in lines)):
+ raise ValueError('Invalid lines')
+ request['lines'] = list(lines)
+ elif lines is not None:
+ raise ValueError('Lines belong to alignment only')
+ return request
+
+
+# ---- sound ---------------------------------------------------------------
+
+def decode_mono(path, *, cancelled=None):
+ """Any audio/video file -> float32 mono at 16 kHz (the whole sound)."""
+ import av
+ import numpy as np
+ pieces, total = [], 0
+ limit = MAX_SECONDS * RATE
+ try:
+ with av.open(str(path)) as container:
+ stream = next((s for s in container.streams if s.type == 'audio'), None)
+ if stream is None:
+ raise EarsError('no_sound')
+ resampler = av.AudioResampler(format='fltp', layout='mono', rate=RATE)
+
+ def take(frames):
+ nonlocal total
+ for converted in frames:
+ data = converted.to_ndarray().reshape(-1)
+ pieces.append(data)
+ total += data.size
+
+ for frame in container.decode(stream):
+ if cancelled and cancelled():
+ raise Cancelled('cancelled')
+ take(resampler.resample(frame))
+ if total > limit:
+ raise EarsError('too_long')
+ take(resampler.resample(None) or [])
+ except (EarsError, Cancelled):
+ raise
+ except FileNotFoundError:
+ raise EarsError('source_missing') from None
+ except Exception:
+ raise EarsError('unreadable') from None
+ if not total:
+ raise EarsError('no_sound')
+ return np.concatenate(pieces).astype('float32', copy=False)
+
+
+def _silent(audio):
+ import numpy as np
+ return audio.size == 0 or float(np.max(np.abs(audio))) < 1e-4
+
+
+# ---- results -------------------------------------------------------------
+
+def _frame(seconds, offset, bound):
+ return max(offset, min(offset + bound, offset + int(seconds * FPS + .5)))
+
+
+def _timed(item, offset, bound):
+ """One engine span {start,end,...} in seconds -> frames plus seconds, or None."""
+ try:
+ start, end = float(item['start']), float(item['end'])
+ except (KeyError, TypeError, ValueError):
+ return None
+ if not (0 <= start < end) or start * FPS >= bound:
+ return None
+ first = _frame(start, offset, bound)
+ last = max(first + 1, _frame(end, offset, bound))
+ return dict(start=first, end=last, start_seconds=round(offset / FPS + start, 3),
+ end_seconds=round(offset / FPS + min(end, bound / FPS), 3))
+
+
+def _words(items, offset, bound):
+ result, end = [], offset
+ for item in items or ():
+ text = item.get('text') if isinstance(item, dict) else None
+ timed = _timed(item, offset, bound) if text else None
+ if timed is None or timed['start'] < end:
+ continue
+ end = timed['end']
+ result.append(dict(text=str(text), **timed))
+ return result
+
+
+def shape_align(lines, found, offset, bound):
+ """Engine output -> one entry per given line, text untouched, order kept."""
+ by_index = {}
+ for item in found or ():
+ if isinstance(item, dict) and _whole(item.get('index')) and item['index'] < len(lines):
+ by_index.setdefault(item['index'], item)
+ result, end = [], offset
+ for index, text in enumerate(lines):
+ entry = dict(index=index, text=text, matched=False)
+ item = by_index.get(index)
+ timed = _timed(item, offset, bound) if item and item.get('matched', True) and text.strip() else None
+ if timed is not None and timed['start'] >= end:
+ end = timed['end']
+ entry.update(matched=True, words=_words(item.get('words'), offset, bound), **timed)
+ result.append(entry)
+ return result
+
+
+def shape_transcript(found, offset, bound):
+ result, end = [], offset
+ for item in found or ():
+ text = str(item.get('text', '')).strip() if isinstance(item, dict) else ''
+ timed = _timed(item, offset, bound) if text else None
+ if timed is None or timed['start'] < end:
+ continue
+ end = timed['end']
+ result.append(dict(index=len(result), text=text, matched=True,
+ words=_words(item.get('words'), offset, bound), **timed))
+ return result
+
+
+# ---- the job -------------------------------------------------------------
+
+def _mix(project, resolver, root, request, progress, cancelled):
+ """Render the saved timeline's sound range to a scratch wav and decode it."""
+ width, height, frames, _ = export._layout(project)
+ span = request.get('range') or dict(start=0, frames=frames)
+ options = dict(only='sound', sound_format='wav', range=span)
+ settings = editor_export_options.validate(options, width, height, frames)
+ scratch = Path(root) / 'FreeVideo' / '.editor' / 'ears' / uuid.uuid4().hex
+ target = scratch / 'mix.wav'
+ try:
+ export._checked_target(target, root)
+ try:
+ export.render(project, resolver, target, progress=progress, cancelled=cancelled, options=settings)
+ except export.ExportCancelled:
+ raise Cancelled('cancelled') from None
+ except export.ExportError as error:
+ raise EarsError(error.reason) from None
+ return decode_mono(target, cancelled=cancelled), span['start'], span['frames']
+ finally:
+ shutil.rmtree(scratch, ignore_errors=True)
+
+
+def run_job(request, *, root, loader=None, resolver=None, mixer=None, engine=None,
+ progress=None, cancelled=None, gate=None):
+ """Validated request -> result dict. Raises EarsError / Cancelled.
+
+ `gate()` returns a context manager held while the engine runs, so a model
+ waits its turn behind video generation (the integration supplies the lock).
+ """
+ progress = progress or (lambda fraction: None)
+
+ def check():
+ if cancelled and cancelled():
+ raise Cancelled('cancelled')
+
+ kind = request['kind']
+ engine = engine or engine_for(kind)
+ resolver = resolver or export.resolve_source
+ if 'source' in request:
+ key = 'work:' + request['source']['work']
+ try:
+ files = resolver(key)
+ except FileNotFoundError:
+ raise EarsError('source_missing') from None
+ except ValueError:
+ raise EarsError('source_missing') from None
+ path = files.get('audio') or files.get('video')
+ if path is None:
+ raise EarsError('no_sound')
+ audio = decode_mono(path, cancelled=cancelled)
+ offset, bound = 0, int(audio.size * FPS / RATE + .5)
+ if 'range' in request:
+ span = request['range']
+ first = int(span['start'] / FPS * RATE)
+ audio = audio[first:first + int(span['frames'] / FPS * RATE)]
+ offset, bound = span['start'], min(span['frames'], int(audio.size * FPS / RATE + .5))
+ else:
+ loader = loader or export.load_project
+ project = copy.deepcopy(loader(request['id'], request.get('revision')))
+ if mixer is not None:
+ audio, offset, bound = mixer(project, resolver, request, lambda f: progress(f * .3), cancelled)
+ else:
+ audio, offset, bound = _mix(project, resolver, root, request, lambda f: progress(f * .3), cancelled)
+ progress(.3)
+ check()
+ if _silent(audio):
+ raise EarsError('no_sound')
+ if audio.size > MAX_SECONDS * RATE:
+ raise EarsError('too_long')
+ started = time.monotonic()
+ with (gate() if gate else nullcontext()):
+ check()
+ report = lambda fraction: progress(.3 + .69 * max(0., min(1., float(fraction))))
+ try:
+ if kind == 'align':
+ found = engine.align(audio, list(request['lines']), request['language'], report, cancelled)
+ language = request['language']
+ lines = shape_align(request['lines'], found, offset, bound)
+ else:
+ found = engine.transcribe(audio, request['language'], report, cancelled)
+ language = request['language']
+ if isinstance(found, dict):
+ language = found.get('language') or language
+ found = found.get('lines')
+ lines = shape_transcript(found, offset, bound)
+ except (EarsError, Cancelled):
+ raise
+ except MemoryError:
+ raise EarsError('failed') from None
+ except Exception:
+ logging.getLogger(__name__).exception('Subtitle ears (%s) failed', kind)
+ raise EarsError('failed') from None
+ check()
+ return dict(kind=kind, language=language, fps=FPS, range=dict(start=offset, frames=bound),
+ lines=lines, matched=sum(1 for l in lines if l['matched']), total=len(lines),
+ engine=str(getattr(engine, 'name', 'engine')), seconds=round(time.monotonic() - started, 2))
+
+
+class EarsQueue:
+ """One worker, FIFO, cancellable; the same shape as the export queue."""
+ def __init__(self, root, *, runner=None, **kwargs):
+ self.root = Path(root).absolute()
+ self.runner = runner or run_job
+ self.kwargs = kwargs
+ self.lock = threading.RLock()
+ self.jobs = {}
+ self.pending = deque()
+ self.worker = None
+
+ @staticmethod
+ def _view(job):
+ return {key: job[key] for key in ('id', 'kind', 'state', 'fraction', 'reason', 'result')}
+
+ def submit(self, body):
+ request = validate_request(body)
+ job = dict(id='s-' + uuid.uuid4().hex, kind=request['kind'], state='running', fraction=0.,
+ reason=None, result=None, request=request, stop=threading.Event())
+ with self.lock:
+ if len(self.jobs) >= MAX_JOBS:
+ for old in list(self.jobs):
+ if self.jobs[old]['state'] != 'running':
+ del self.jobs[old]
+ if len(self.jobs) < MAX_JOBS:
+ break
+ if len(self.jobs) >= MAX_JOBS:
+ raise EarsError('failed')
+ self.jobs[job['id']] = job
+ self.pending.append(job['id'])
+ initial = self._view(job)
+ if self.worker is None:
+ self.worker = threading.Thread(target=self._run, name='freevideo-subtitle-ears', daemon=True)
+ self.worker.start()
+ return initial
+
+ def get(self, identity):
+ if not isinstance(identity, str) or not _JOB_ID.fullmatch(identity):
+ raise ValueError('Invalid job')
+ with self.lock:
+ if identity not in self.jobs:
+ raise KeyError(identity)
+ return self._view(self.jobs[identity])
+
+ def cancel(self, identity):
+ with self.lock:
+ self.get(identity)
+ job = self.jobs[identity]
+ if job['state'] == 'running':
+ job['stop'].set()
+ if identity in self.pending:
+ self.pending.remove(identity)
+ job['state'] = 'cancelled'
+ return self._view(job)
+
+ def _run(self):
+ while True:
+ with self.lock:
+ if not self.pending:
+ self.worker = None
+ return
+ job = self.jobs[self.pending.popleft()]
+ if job['stop'].is_set():
+ job['state'] = 'cancelled'
+ continue
+
+ def progress(fraction):
+ with self.lock:
+ job['fraction'] = max(job['fraction'], min(.99, float(fraction)))
+
+ try:
+ result = self.runner(job['request'], root=self.root, progress=progress,
+ cancelled=job['stop'].is_set, **self.kwargs)
+ with self.lock:
+ if job['stop'].is_set():
+ job.update(state='cancelled')
+ else:
+ job.update(state='done', fraction=1., result=result)
+ except Exception as error:
+ with self.lock:
+ if isinstance(error, Cancelled) or job['stop'].is_set():
+ job.update(state='cancelled', reason=None)
+ elif isinstance(error, export.ExportConflict):
+ job.update(state='failed', reason='failed')
+ else:
+ job.update(state='failed', reason=export._reason(error) if not isinstance(error, EarsError)
+ else error.reason)
+
+
+def register():
+ """Register the ears endpoints once on the existing ComfyUI server."""
+ from . import subtitle_sherpa # noqa: F401 (registers the speech-model engine)
+ import asyncio
+ from aiohttp import web
+ from server import PromptServer
+ server = PromptServer.instance
+ if server is None or getattr(server, '_freevideo_subtitle_ears', False):
+ return
+ queue = EarsQueue(export._output_root())
+ server._freevideo_subtitle_ears = queue
+
+ def response(value):
+ return web.json_response({'job': value}, headers={'Cache-Control': 'no-store'})
+
+ @server.routes.post('/freevideo/editor/ears')
+ async def start(request):
+ try:
+ body = await request.json()
+ return response(await asyncio.to_thread(queue.submit, body))
+ except export.ExportConflict as error:
+ return web.json_response({'revision': error.revision}, status=409, headers={'Cache-Control': 'no-store'})
+ except (ValueError, TypeError, KeyError):
+ return web.json_response({'reason': 'failed'}, status=400)
+ except EarsError as error:
+ return web.json_response({'reason': error.reason}, status=503)
+
+ @server.routes.get('/freevideo/editor/ears')
+ async def status(request):
+ identity = request.query.get('id')
+ if identity is None:
+ return web.json_response(dict(available=available()), headers={'Cache-Control': 'no-store'})
+ try:
+ return response(queue.get(identity))
+ except KeyError:
+ return web.json_response({'reason': 'failed'}, status=404)
+ except ValueError:
+ return web.json_response({'reason': 'failed'}, status=400)
+
+ @server.routes.post('/freevideo/editor/ears/cancel')
+ async def cancel(request):
+ try:
+ body = await request.json()
+ if not isinstance(body, dict) or set(body) != {'id'}:
+ raise ValueError('Invalid request')
+ return response(queue.cancel(body['id']))
+ except KeyError:
+ return web.json_response({'reason': 'failed'}, status=404)
+ except (ValueError, TypeError):
+ return web.json_response({'reason': 'failed'}, status=400)
diff --git a/freevideo_engine/subtitle_files.py b/freevideo_engine/subtitle_files.py
new file mode 100644
index 0000000..f23b5f2
--- /dev/null
+++ b/freevideo_engine/subtitle_files.py
@@ -0,0 +1,70 @@
+"""Separate subtitle file (SRT or WebVTT) of a saved project's subtitle track.
+
+Pure text out of the saved record; nothing is written to disk. The page offers
+the reply as a download next to the export that burns the subtitles in.
+"""
+from . import editor_export as export
+from . import subtitle_cues
+
+FORMATS = {'srt': ('application/x-subrip', subtitle_cues.to_srt), 'vtt': ('text/vtt', subtitle_cues.to_vtt)}
+
+
+def cues_of(project, start=0, frames=None):
+ """Subtitle clips as cues, clipped to the range; times stay on the project's timeline."""
+ result = []
+ end = None if frames is None else start + frames
+ for track in project.get('tracks', []):
+ if track.get('kind') != 'subtitle' or track.get('hidden'):
+ continue
+ for clip in track['clips']:
+ first, last = clip['start'], clip['start'] + clip['frames']
+ if first < start:
+ first = start
+ if end is not None and last > end:
+ last = end
+ if last > first and clip['text'].strip():
+ result.append(dict(start=first, frames=last - first, text=clip['text']))
+ return result
+
+
+def subtitle_file(project, fmt='srt', *, start=0, frames=None):
+ """-> (media type, text). Times are shifted so the range starts at 00:00:00."""
+ if fmt not in FORMATS:
+ raise ValueError('Invalid subtitle format')
+ if type(start) is not int or start < 0 or frames is not None and (type(frames) is not int or frames < 1):
+ raise ValueError('Invalid range')
+ media, write = FORMATS[fmt]
+ return media, write(cues_of(project, start, frames), offset=start)
+
+
+def register():
+ from aiohttp import web
+ from server import PromptServer
+ server = PromptServer.instance
+ if server is None or getattr(server, '_freevideo_subtitle_files', False):
+ return
+ server._freevideo_subtitle_files = True
+
+ @server.routes.get('/freevideo/editor/subtitles')
+ async def download(request):
+ import asyncio
+ query = request.query
+ try:
+ revision = query.get('revision')
+ if revision is not None and not revision.isdecimal():
+ raise ValueError('Invalid revision')
+ numbers = {key: int(query[key]) for key in ('start', 'frames') if key in query and query[key].isdecimal()}
+ if any(key in query and key not in numbers for key in ('start', 'frames')):
+ raise ValueError('Invalid range')
+ project = await asyncio.to_thread(export.load_project, query.get('id'),
+ None if revision is None else int(revision))
+ media, text = subtitle_file(project, query.get('format', 'srt'), start=numbers.get('start', 0),
+ frames=numbers.get('frames'))
+ except export.ExportConflict as error:
+ return web.json_response({'revision': error.revision}, status=409, headers={'Cache-Control': 'no-store'})
+ except FileNotFoundError:
+ return web.json_response({'reason': 'failed'}, status=404)
+ except (ValueError, TypeError, KeyError):
+ return web.json_response({'reason': 'failed'}, status=400)
+ return web.Response(text=text, content_type=media, charset='utf-8',
+ headers={'Cache-Control': 'no-store', 'X-Content-Type-Options': 'nosniff'})
diff --git a/freevideo_engine/subtitle_sherpa.py b/freevideo_engine/subtitle_sherpa.py
new file mode 100644
index 0000000..03ca47a
--- /dev/null
+++ b/freevideo_engine/subtitle_sherpa.py
@@ -0,0 +1,481 @@
+"""Subtitle ears engine: sherpa-onnx CTC speech recognition, on the CPU.
+
+One small model per language listens to the sound in 24-second windows (2 s of
+overlap, so a word on a seam is heard whole) and returns timed characters or
+words. Alignment then lays the given lines over what was heard, in order:
+a line is `matched` only when most of its words were really heard there, and a
+line nobody said has no time. Recognition groups the heard words into lines at
+pauses. The models are optional files under `<models>/subtitles/<lang>/`
+(`model.int8.onnx`, `tokens.txt`); without them, or without `sherpa_onnx`, the
+engine reports "not installed" and the ears stay off.
+
+An optional shared `subtitles/silero_vad_v5.onnx` gates words by speech time.
+It leaves the CTC windows intact; without the verified VAD file the engine
+continues with unfiltered recognition. No models are downloaded at runtime.
+"""
+import hashlib
+import logging
+import os
+import re
+import threading
+import unicodedata
+
+from .paths import model_root
+from .subtitle_ears import Cancelled, register_engine
+
+RATE = 16000
+CORE = 24.0 # seconds each window owns
+OVERLAP = 2.0 # heard on both sides of a seam, owned by one side
+THRESHOLD = .72 # share of a line's words that must be heard in order
+PAUSE = .7 # silence that ends a recognised line (seconds)
+LINE_UNITS = {'zh': 24, 'en': 14}
+MODELS = {'zh': 'zh', 'en': 'en'}
+VAD_MODEL = 'silero_vad_v5.onnx'
+# Official Silero v5.0 export. The native VAD loader exits the process for some
+# incompatible exports (including faster-whisper's v6); verify before loading.
+VAD_SHA256 = '6b99cbfd39246b6706f98ec13c7c50c6b299181f2474fa05cbc8046acc274396'
+VAD_BYTES = 2313101
+VAD_PAD = .4 # include soft onsets and the delay of CTC token peaks
+_LOG = logging.getLogger(__name__)
+
+_WORD = re.compile(r"[㐀-鿿]|[^\W_㐀-鿿]+(?:['’][^\W_㐀-鿿]+)*", re.UNICODE)
+_CJK = re.compile(r'[㐀-鿿]')
+
+
+def units(text):
+ return _WORD.findall(unicodedata.normalize('NFKC', text))
+
+
+def norm(text):
+ return unicodedata.normalize('NFKC', text).casefold().replace('’', "'")
+
+
+# ---- matching the lines onto what was heard -------------------------------
+
+def _project_compounds(target, heard):
+ """Heard pieces that together spell one camel-case script word become one."""
+ compounds = {norm(x) for x in target if re.search(r'[a-z][A-Z]', x)}
+ result, j = [], 0
+ while j < len(heard):
+ width = next((n for n in range(2, min(4, len(heard) - j) + 1)
+ if norm(''.join(x['text'] for x in heard[j:j + n])) in compounds), None) if compounds else None
+ if width:
+ result.append((j, j + width, {**heard[j], 'text': ''.join(x['text'] for x in heard[j:j + width]),
+ 'end': heard[j + width - 1]['end']}))
+ j += width
+ else:
+ result.append((j, j + 1, heard[j]))
+ j += 1
+ return result
+
+
+def _edit_table(expected, observed):
+ """Edit distance of the whole line against any stretch of what was heard.
+
+ Free audio before and after, costly gaps in the line. Returns the last row
+ and the direction of each cell (0 = both advance, 1 = line word unheard,
+ 2 = heard word not in the line), tie-broken in that order.
+ """
+ import numpy as np
+ n, m = len(expected), len(observed)
+ ids = {}
+ left = np.fromiter((ids.setdefault(x, len(ids)) for x in expected), dtype=np.int32, count=n)
+ right = np.fromiter((ids.setdefault(x, len(ids)) for x in observed), dtype=np.int32, count=m)
+ column = np.arange(m + 1, dtype=np.int32)
+ previous = np.zeros(m + 1, dtype=np.int32)
+ paths = np.zeros((n + 1, m + 1), dtype=np.uint8)
+ paths[0, :] = 0
+ for i in range(1, n + 1):
+ diagonal = np.full(m + 1, np.iinfo(np.int32).max // 2, dtype=np.int32)
+ diagonal[1:] = previous[:-1] + (right != left[i - 1])
+ up = previous + 1
+ best = np.minimum(diagonal, up)
+ best[0] = i
+ row = np.minimum.accumulate(best - column) + column
+ direction = np.where(row == diagonal, 0, np.where(row == up, 1, 2)).astype(np.uint8)
+ direction[0] = 1
+ paths[i] = direction
+ previous = row
+ return previous, paths
+
+
+def _candidate_spans(target, projected, threshold):
+ """Every local alignment of the line that is good enough, one per end."""
+ import numpy as np
+ n, m = len(target), len(projected)
+ if not n or not m:
+ return
+ expected = [norm(x) for x in target]
+ heard = [norm(x[2]['text']) for x in projected]
+ last, paths = _edit_table(expected, heard)
+ seen = set()
+ for endpoint in np.nonzero(last[1:] / n <= 1 - threshold + 1e-9)[0] + 1:
+ endpoint = int(endpoint)
+ cost = last[endpoint] / n
+ pairs, i, j = [], n, endpoint
+ while i:
+ direction = paths[i, j]
+ if j and direction == 0:
+ if expected[i - 1] == heard[j - 1]:
+ pairs.append((i - 1, j - 1))
+ i -= 1
+ j -= 1
+ elif direction == 1 or not j:
+ i -= 1
+ else:
+ j -= 1
+ pairs.reverse()
+ if len(pairs) < min(2, n) or len(pairs) / n < threshold:
+ continue
+ first, final = projected[pairs[0][1]], projected[pairs[-1][1]]
+ begin, end = first[2]['start'], final[2]['end']
+ if not 0 <= begin < end or end - begin > max(4.0, n * 1.5):
+ continue
+ key = (tuple((i, projected[j][0], projected[j][1]) for i, j in pairs), round(float(cost), 8))
+ if key in seen:
+ continue
+ seen.add(key)
+ yield first[0], final[1], float(cost), len(pairs) / n, [(i, projected[j][2]) for i, j in pairs]
+
+
+def match_lines(lines, heard, threshold=THRESHOLD):
+ """Lay the lines over the heard words in their given order.
+
+ A line may be missing and extra speech may sit between lines. A near match
+ now is preferred over an exact repeat that would lose the lines after it.
+ """
+ import numpy as np
+ m = len(heard)
+ costs = np.zeros(m + 1)
+ columns = np.arange(m + 1)
+ parents, chosen, candidates, unit_lists = [], [], [], []
+ for line in lines:
+ words = units(line)
+ unit_lists.append(words)
+ current = costs + (1.0 + len(words) * 1e-6)
+ # cheapest earlier state for every start (earliest on ties)
+ floor = np.minimum.accumulate(costs)
+ fresh = np.ones(m + 1, dtype=bool)
+ fresh[1:] = costs[1:] < floor[:-1]
+ source = np.maximum.accumulate(np.where(fresh, columns, 0))
+ previous = np.arange(m + 1)
+ picked = np.zeros(m + 1, dtype=bool)
+ by_end = {}
+ for start, end, edit, confidence, pairs in _candidate_spans(words, _project_compounds(words, heard), threshold):
+ total = floor[start] + edit
+ if total < current[end] - 1e-12 or (abs(total - current[end]) <= 1e-12 and picked[end]
+ and confidence > by_end[end][1]):
+ current[end] = total
+ previous[end] = source[start]
+ picked[end] = True
+ by_end[end] = (edit, confidence, pairs)
+ costs = current
+ parents.append(previous)
+ chosen.append(picked)
+ candidates.append(by_end)
+ state = int(np.argmin(costs))
+ result = []
+ for index in range(len(lines) - 1, -1, -1):
+ found = bool(chosen[index][state])
+ entry = dict(index=index, matched=found)
+ if found:
+ edit, confidence, pairs = candidates[index][state]
+ timed = dict(pairs)
+ entry.update(start=pairs[0][1]['start'], end=pairs[-1][1]['end'], confidence=round(confidence, 6),
+ words=[dict(text=word, start=timed[i]['start'], end=timed[i]['end'])
+ for i, word in enumerate(unit_lists[index]) if i in timed])
+ result.append(entry)
+ state = int(parents[index][state])
+ result.reverse()
+ return result
+
+
+# ---- listening --------------------------------------------------------------
+
+def _bytes_to_text(pieces):
+ """Byte-level pieces (some Chinese models spell UTF-8 bytes) -> characters."""
+ chars = (list(range(256, 288)) + list(range(32, 127)) + list(range(288, 306)) + list(range(308, 319))
+ + list(range(321, 329)) + list(range(330, 383)) + list(range(384, 423)))
+ inverse = {chr(c): i for i, c in enumerate(chars)}
+ result, pending = [], []
+ for piece in pieces:
+ for ch in piece['raw']:
+ if ch == '▁':
+ # A word boundary also ends a malformed/incomplete byte prefix.
+ # Keeping it would consume the next valid character's first
+ # byte when UTF-8 decoding rejects the combined sequence.
+ pending = []
+ result.append({**piece, 'raw': ' '})
+ continue
+ if ch not in inverse:
+ continue
+ pending.append((inverse[ch], piece['start'], piece['end']))
+ try:
+ text = bytes(x[0] for x in pending).decode('utf-8')
+ except UnicodeDecodeError as error:
+ if error.reason != 'unexpected end of data':
+ pending = []
+ continue
+ for literal in text:
+ result.append({'raw': literal, 'start': pending[0][1], 'end': pending[-1][2]})
+ pending = []
+ return result
+
+
+def heard_words(tokens, timestamps, duration, offset=0.0):
+ """One window's recogniser output -> [{text, start, end}] (characters or words)."""
+ pieces = []
+ for index, (token, at) in enumerate(zip(tokens, timestamps)):
+ at = float(at)
+ if at >= duration or (token.startswith('<') and token.endswith('>')):
+ continue
+ end = min(duration, float(timestamps[index + 1]) if index + 1 < len(timestamps) else at + .24, at + .4)
+ if end <= at:
+ end = min(duration, at + .08)
+ pieces.append({'raw': token, 'start': offset + at, 'end': offset + end})
+ if any(256 <= ord(ch) <= 422 for piece in pieces for ch in piece['raw']):
+ pieces = _bytes_to_text(pieces)
+ result, buffer, begin, end = [], '', None, None
+
+ def flush():
+ nonlocal buffer, begin, end
+ if buffer and units(buffer):
+ result.append({'text': buffer, 'start': begin, 'end': end})
+ buffer, begin, end = '', None, None
+
+ for piece in pieces:
+ raw = piece['raw']
+ if raw.startswith(('▁', 'Ġ')) or raw in (' ', '|'):
+ flush()
+ for ch in raw.replace('▁', ' ').replace('Ġ', ' ').replace('|', ' '):
+ if '㐀' <= ch <= '鿿':
+ flush()
+ result.append({'text': ch, 'start': piece['start'], 'end': piece['end']})
+ elif ch.isalnum() or ch in "'’":
+ if begin is None:
+ begin = piece['start']
+ buffer += ch
+ end = piece['end']
+ else:
+ flush()
+ flush()
+ return result
+
+
+def windows(count, core=CORE, overlap=OVERLAP):
+ """(first, last, own_from, own_to) in samples; each sample is owned by one window."""
+ step, pad = int(core * RATE), int(overlap * RATE)
+ result, start = [], 0
+ while start < count:
+ result.append((max(0, start - pad), min(count, start + step + pad), start, min(count, start + step)))
+ start += step
+ return result
+
+
+def speech_spans(vad, audio, cancelled=None):
+ """Padded speech intervals in window-local seconds; flush even a short tail.
+
+ Drain as we feed the detector so its audio buffer stays bounded. CTC still
+ hears the original window, avoiding a different decode at each VAD edge.
+ """
+ import numpy as np
+ vad.reset()
+ spans = []
+ duration = audio.size / RATE
+
+ def drain():
+ while not vad.empty():
+ segment = vad.front
+ begin = max(0., segment.start / RATE - VAD_PAD)
+ end = min(duration, (segment.start + len(segment.samples)) / RATE + VAD_PAD)
+ if begin < end:
+ if spans and begin <= spans[-1][1]:
+ spans[-1] = (spans[-1][0], max(spans[-1][1], end))
+ else:
+ spans.append((begin, end))
+ vad.pop()
+
+ for first in range(0, audio.size, 512):
+ if cancelled and cancelled():
+ raise Cancelled('cancelled')
+ chunk = audio[first:first + 512]
+ if chunk.size < 512:
+ chunk = np.pad(chunk, (0, 512 - chunk.size))
+ vad.accept_waveform(chunk)
+ drain()
+ vad.flush()
+ drain()
+ return spans
+
+
+def in_speech(word, spans, offset=0.):
+ """Assign each whole word by its midpoint, in the same clock as its window."""
+ at = (word['start'] + word['end']) / 2 - offset
+ return spans is None or any(begin <= at < end for begin, end in spans)
+
+
+class Engine:
+ name = 'sherpa-ctc'
+
+ def __init__(self, directories, threads, vad_model=None):
+ self._directories = directories
+ self._threads = threads
+ self._recognizers = {}
+ self._lock = threading.Lock()
+ self._vad_model = vad_model if vad_model is not None else next(iter(directories.values())).parent / VAD_MODEL
+ self._vad = None
+ self._vad_signature = None
+ self._vad_lock = threading.Lock()
+
+ def languages(self):
+ return sorted(self._directories)
+
+ def _pick(self, language, text=''):
+ if language in self._directories:
+ return language
+ # auto, or a language without a model: judge by the script when there is one
+ wanted = ('zh' if _CJK.search(text) else 'en') if text.strip() else 'zh'
+ return wanted if wanted in self._directories else sorted(self._directories)[0]
+
+ def _recognizer(self, language):
+ with self._lock:
+ if language not in self._recognizers:
+ import sherpa_onnx
+ folder = self._directories[language]
+ make = (sherpa_onnx.OfflineRecognizer.from_zipformer_ctc if language == 'zh'
+ else sherpa_onnx.OfflineRecognizer.from_nemo_ctc)
+ self._recognizers[language] = make(
+ model=str(folder / 'model.int8.onnx'), tokens=str(folder / 'tokens.txt'),
+ num_threads=self._threads, provider='cpu', decoding_method='greedy_search')
+ return self._recognizers[language]
+
+ def _speech_spans(self, audio, cancelled):
+ # The detector is stateful: reset/feed/flush belong to one call. The
+ # separate lock lets other calls decode while this call checks speech.
+ with self._vad_lock:
+ try:
+ stat = self._vad_model.stat()
+ signature = (stat.st_mtime_ns, stat.st_size, stat.st_ino)
+ if signature != self._vad_signature:
+ self._vad = None
+ self._vad_signature = signature
+ data = self._vad_model.read_bytes() if stat.st_size == VAD_BYTES else b''
+ if hashlib.sha256(data).hexdigest() != VAD_SHA256:
+ _LOG.warning('Subtitle speech gate model is unverified; using unfiltered recognition')
+ return None
+ import sherpa_onnx
+ config = sherpa_onnx.VadModelConfig()
+ config.silero_vad.model = str(self._vad_model)
+ config.silero_vad.threshold = .5
+ config.silero_vad.min_speech_duration = .1
+ config.silero_vad.min_silence_duration = .2
+ config.silero_vad.window_size = 512
+ config.silero_vad.max_speech_duration = CORE + 2 * OVERLAP + 1
+ config.sample_rate = RATE
+ config.num_threads = 1
+ config.provider = 'cpu'
+ self._vad = sherpa_onnx.VoiceActivityDetector(config, buffer_size_in_seconds=60)
+ return speech_spans(self._vad, audio, cancelled) if self._vad is not None else None
+ except Cancelled:
+ raise
+ except FileNotFoundError:
+ self._vad = None
+ self._vad_signature = None
+ return None
+ except Exception:
+ self._vad = None
+ _LOG.warning('Subtitle speech gate unavailable; using unfiltered recognition')
+ return None
+
+ def _listen(self, audio, language, progress, cancelled):
+ recognizer = self._recognizer(language)
+ plan = windows(audio.size)
+ words = []
+ for number, (first, last, own_from, own_to) in enumerate(plan):
+ if cancelled and cancelled():
+ raise Cancelled('cancelled')
+ spans = self._speech_spans(audio[first:last], cancelled)
+ if spans == []:
+ progress((number + 1) / len(plan))
+ continue
+ if spans is not None and cancelled and cancelled():
+ raise Cancelled('cancelled')
+ stream = recognizer.create_stream()
+ stream.accept_waveform(RATE, audio[first:last])
+ recognizer.decode_stream(stream)
+ result = stream.result
+ if len(result.timestamps) != len(result.tokens):
+ raise RuntimeError('recogniser returned no times')
+ for word in heard_words(list(result.tokens), list(result.timestamps), (last - first) / RATE, first / RATE):
+ if (own_from / RATE <= (word['start'] + word['end']) / 2 < own_to / RATE
+ and in_speech(word, spans, first / RATE)):
+ words.append(word)
+ progress((number + 1) / len(plan))
+ return words
+
+ def align(self, audio, lines, language, progress, cancelled):
+ language = self._pick(language, ' '.join(lines))
+ words = self._listen(audio, language, lambda f: progress(f * .95), cancelled)
+ result = match_lines(lines, words)
+ progress(1.0)
+ return result
+
+ def transcribe(self, audio, language, progress, cancelled):
+ language = self._pick(language)
+ words = self._listen(audio, language, lambda f: progress(f * .98), cancelled)
+ limit = LINE_UNITS[language]
+ lines, current = [], []
+ for word in words:
+ if current and (word['start'] - current[-1]['end'] >= PAUSE or len(current) >= limit):
+ lines.append(current)
+ current = []
+ current.append(word)
+ if current:
+ lines.append(current)
+ progress(1.0)
+ found = []
+ for group in lines:
+ text = ''
+ for word in group:
+ if text and (word['text'][0].isascii() and word['text'][0].isalnum()) and text[-1].isascii():
+ text += ' '
+ text += word['text']
+ found.append(dict(text=text, start=group[0]['start'], end=group[-1]['end'], words=group))
+ return dict(language=language, lines=found)
+
+
+_CACHE = {}
+
+
+def folders(root=None):
+ base = (root or model_root()) / 'subtitles'
+ found = {}
+ for language, name in MODELS.items():
+ folder = base / name
+ if (folder / 'model.int8.onnx').is_file() and (folder / 'tokens.txt').is_file():
+ found[language] = folder
+ return found
+
+
+def factory():
+ """The ears engine, or None while the models or the runtime are not installed."""
+ try:
+ import sherpa_onnx # noqa: F401
+ import numpy # noqa: F401
+ except ImportError:
+ return None
+ found = folders()
+ if not found:
+ return None
+ key = tuple(sorted(found.items()))
+ if key not in _CACHE:
+ _CACHE.clear()
+ _CACHE[key] = Engine(found, max(1, min(4, os.cpu_count() or 1)))
+ return _CACHE[key]
+
+
+def _lazy():
+ return factory()
+
+
+register_engine(Engine.name, _lazy, first=True)