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.

Prompt enhancement fits time points that run past the end of the video

Bowen Xue53a5cc58fb18
diff --git a/freevideo_engine/prompt_vlm/rules.py b/freevideo_engine/prompt_vlm/rules.py
index 2c6384c..bb1e8ea 100644
--- a/freevideo_engine/prompt_vlm/rules.py
+++ b/freevideo_engine/prompt_vlm/rules.py
@@ -170,7 +170,7 @@ def validate_output(text, value):
section = text.split(marker + ':', 1)[1].split('\n\n', 1)[0].strip()
if not section:
raise InvalidOutput('empty_section', text, value)
- for minutes, seconds in re.findall(r'\bAt (\d{2}):(\d{2}\.\d{3})', text):
+ for minutes, seconds in TIME_POINT.findall(text):
if int(minutes) * 60 + float(seconds) >= value['seconds']:
raise InvalidOutput('timestamp_not_before_duration', text, value)
# Only the labels the scene itself uses: the media given, plus audio and connected media it cannot see.
@@ -352,6 +352,30 @@ def missing_lines(text, scene):
DIALOGUE_RETRY = ('Your rewrite left out these spoken lines. Rewrite the whole prompt again in the same format and '
'include each line once, verbatim, at the moment it is spoken, as (S1) <d>[Language] ...</d>:\n')
+TIME_POINT = re.compile(r'\bAt (\d{2}):(\d{2}\.\d{3})')
+# A rewritten prompt that keeps time points from an earlier, longer version ("At 00:07.000" in a 5 s video)
+# is rejected; one correction turn asks for the same story fitted inside the requested length.
+TIMESTAMP_RETRY = ('Your rewrite has time points at or after the end of the %g-second video. Rewrite the whole prompt '
+ 'again in the same format with the same story fitted inside %g seconds: every "At MM:SS.mmm" time '
+ 'point must be earlier than %g seconds, so move later actions earlier or merge them. Keep every '
+ 'other detail and the required section format.\n')
+
+
+def fit_time_points(text, seconds):
+ """The same text with every "At MM:SS.mmm" scaled so the latest one falls at 90% of the video, order kept.
+
+ Used only for a rewrite that was rejected for time points at or after the end of the video and still has
+ them after the correction turn; the story and every other word are untouched.
+ """
+ points = TIME_POINT.findall(text)
+ latest = max((int(minutes) * 60 + float(second) for minutes, second in points), default=0.)
+ if latest < seconds:
+ return text
+ def scaled(match):
+ milliseconds = round((int(match.group(1)) * 60 + float(match.group(2))) * .9 * seconds / latest * 1000)
+ return 'At %02d:%06.3f' % (milliseconds // 60000, milliseconds % 60000 / 1000)
+ return TIME_POINT.sub(scaled, text)
+
def user_text(value):
"""The user's scene, plus the spoken lines the rewrite must keep verbatim."""
diff --git a/freevideo_engine/prompt_vlm/service.py b/freevideo_engine/prompt_vlm/service.py
index 423248f..430b1b4 100644
--- a/freevideo_engine/prompt_vlm/service.py
+++ b/freevideo_engine/prompt_vlm/service.py
@@ -617,7 +617,7 @@ class Service:
except rules.InvalidOutput as error:
stats = result.get('diagnostics') or {}
error.details['retried'] = bool(stats.get('media_retry') or stats.get('picture_retry')
- or stats.get('dialogue_retry'))
+ or stats.get('dialogue_retry') or stats.get('timestamp_retry'))
self.progress(dict(diagnostics=stats))
raise
self.progress(dict(result, worker_returncode=child.returncode))
diff --git a/freevideo_engine/prompt_vlm/worker.py b/freevideo_engine/prompt_vlm/worker.py
index fe358a0..508621f 100644
--- a/freevideo_engine/prompt_vlm/worker.py
+++ b/freevideo_engine/prompt_vlm/worker.py
@@ -387,7 +387,7 @@ def rewrite(folder, value, stats):
persistent_model=False)
torch, checkpoint = begin(stats)
from transformers import AutoProcessor
- from .rules import DIALOGUE_RETRY, InvalidOutput, instruction, label, language, missing_lines, user_text
+ from .rules import DIALOGUE_RETRY, TIMESTAMP_RETRY, InvalidOutput, fit_time_points, instruction, label, language, missing_lines, user_text
checkpoint('preprocess')
preparing = time.monotonic()
processor = AutoProcessor.from_pretrained(folder, local_files_only=True, trust_remote_code=False)
@@ -423,14 +423,18 @@ def rewrite(folder, value, stats):
text = processor.decode(ids, skip_special_tokens=True)
missing = missing_lines(text, value['text'])
rewritten, rejected = None, None
- references = []
+ references, late, last = [], False, text
try:
rewritten = validate_rewrite(text, value, stats)
except InvalidOutput as error:
rejected = error
if error.details['condition'] == 'missing_picture_reference':
references = error.details['missing_references']
- if missing or references:
+ late = error.details['condition'] == 'timestamp_not_before_duration'
+ if late:
+ # Time points are checked first; ask for any media reference the draft also left out.
+ references = error.details['missing_references']
+ if missing or references or late:
# Both corrections share one turn and the existing context/cache allowance.
correction = ''
if references:
@@ -438,6 +442,8 @@ def rewrite(folder, value, stats):
correction = (f'Your rewrite omitted these required media references: {labels}. '
'Preserve all existing content and add each missing reference where it belongs. '
'Return the complete prompt in the same required section format.\n')
+ if late:
+ correction += TIMESTAMP_RETRY % ((value['seconds'],) * 3)
if missing:
correction += DIALOGUE_RETRY + '\n'.join('- [%s] %s' % (language(line), line) for line in missing)
retry = messages + [{'role': 'assistant', 'content': text}, {'role': 'user', 'content': correction}]
@@ -445,31 +451,49 @@ def rewrite(folder, value, stats):
if retry_allowed(retry_inputs.input_ids.shape[-1], stats):
again, _ = generate(torch, model, retry_inputs.to(device), 1800, time.monotonic(), lambda timing: None)
second = processor.decode(again, skip_special_tokens=True)
+ # A cut-off correction is never used, not even to scale: fall back to the first draft.
+ last = second if len(again) < 1800 else text
stats.update(retry_output_tokens=len(again), rewrite_seconds=time.monotonic() - loaded)
if missing:
stats['dialogue_retry'] = True
+ if late:
+ stats['timestamp_retry'] = True
if references:
stats['media_retry'] = True
if any(each.startswith('<Picture ') for each in references):
stats['picture_retry'] = True # Retain the existing image diagnostic.
try:
candidate = validate_rewrite(second, value, stats, retried=True)
- if references and len(again) >= 1800:
+ if (references or late) and len(again) >= 1800:
error = InvalidOutput('output_token_limit', second, value)
error.details['retried'] = True
stats['output_rejections'].append(error.details)
raise error
- if len(again) < 1800 and (references or len(missing_lines(second, value['text'])) < len(missing)):
+ if len(again) < 1800 and (references or late or len(missing_lines(second, value['text'])) < len(missing)):
rewritten = candidate
except InvalidOutput:
- if references:
+ if references and not late:
raise
- elif references:
- stats['media_retry_skipped'] = stats.get('dialogue_retry_skipped', 'context_length')
- if any(each.startswith('<Picture ') for each in references):
- stats['picture_retry_skipped'] = stats['media_retry_skipped']
+ elif late or references:
+ skipped = stats.get('dialogue_retry_skipped', 'context_length')
+ if late:
+ stats['timestamp_retry_skipped'] = skipped
+ if references:
+ stats['media_retry_skipped'] = skipped
+ if any(each.startswith('<Picture ') for each in references):
+ stats['picture_retry_skipped'] = skipped
+ if rewritten is None and late:
+ # Still late after the correction (or no room for one): scale the time points, change nothing else.
+ for each in dict.fromkeys((last, text)):
+ try:
+ rewritten = validate_rewrite(fit_time_points(each, value['seconds']), value, stats,
+ retried=bool(stats.get('timestamp_retry')))
+ except InvalidOutput:
+ continue
+ stats['timestamp_rescaled'] = True
+ break
if rewritten is None:
- rejected.details = dict(rejected.details, retried=bool(stats.get('media_retry') or stats.get('dialogue_retry')))
+ rejected.details = dict(rejected.details, retried=bool(stats.get('media_retry') or stats.get('dialogue_retry') or stats.get('timestamp_retry')))
raise rejected
stats['stage'] = 'complete'
emit(phase='complete', text=rewritten, diagnostics=dict(stats))