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 retries once when a rewrite leaves out an image reference

Bowen Xue5dd7717fdb35
diff --git a/freevideo_engine/prompt_vlm/rules.py b/freevideo_engine/prompt_vlm/rules.py
index f0dfb48..e154bd2 100644
--- a/freevideo_engine/prompt_vlm/rules.py
+++ b/freevideo_engine/prompt_vlm/rules.py
@@ -92,9 +92,22 @@ def sections(text, fields):
return re.sub(r'\n+(?=(?:%s):)' % names, '\n\n', text).strip()
+class InvalidOutput(ValueError):
+ """Stable rejection metadata; never retain the prompt or rejected draft."""
+ def __init__(self, condition, text, value):
+ super().__init__('invalid_output')
+ draft = text if isinstance(text, str) else ''
+ indices = {int(i) for i in re.findall(r'<Picture (\d+)>', draft)}
+ self.details = dict(condition=condition, output_characters=len(draft),
+ missing_pictures=[i for i in range(1, len(value['media']) + 1)
+ if f'<Picture {i}>' not in draft],
+ out_of_range_pictures=sorted(i for i in indices if not 1 <= i <= len(value['media'])),
+ retried=False)
+
+
def validate_output(text, value):
if not isinstance(text, str) or not 100 <= len(text.strip()) <= 20000:
- raise ValueError('invalid_output')
+ raise InvalidOutput('type_or_length', text, value)
text = text.strip()
if text.startswith('```') and text.endswith('```'):
text = '\n'.join(text.splitlines()[1:-1]).strip()
@@ -102,27 +115,27 @@ def validate_output(text, value):
text = sections(text, fields)
found = re.findall(r'(?m)^([a-z_]+):', text)
if found != list(fields) or not text.startswith(fields[0] + ':'):
- raise ValueError('invalid_output')
+ raise InvalidOutput('headings', text, value)
if not re.search(r'\[Shot \d+\]', text):
name = 'detailed_description' if value['mode'] == 'ref2va' else fields[0]
text = text.replace(name + ':', name + ': [Shot 1]', 1)
if '[Shot 1]' not in text:
- raise ValueError('invalid_output')
+ raise InvalidOutput('missing_shot_1', text, value)
for marker in fields:
section = text.split(marker + ':', 1)[1].split('\n\n', 1)[0].strip()
if not section:
- raise ValueError('invalid_output')
+ raise InvalidOutput('empty_section', text, value)
for minutes, seconds in re.findall(r'\bAt (\d{2}):(\d{2}\.\d{3})', text):
if int(minutes) * 60 + float(seconds) >= value['seconds']:
- raise ValueError('invalid_output')
+ raise InvalidOutput('timestamp_not_before_duration', text, value)
for index in re.findall(r'<Picture (\d+)>', text):
if not 1 <= int(index) <= len(value['media']):
- raise ValueError('invalid_output')
+ raise InvalidOutput('picture_index_out_of_range', text, value)
if re.search(r'<(?:Audio|Video) \d+>', text):
- raise ValueError('invalid_output')
+ raise InvalidOutput('unsupported_audio_video_reference', text, value)
for i in range(1, len(value['media']) + 1):
if f'<Picture {i}>' not in text:
- raise ValueError('invalid_output')
+ raise InvalidOutput('missing_picture_reference', text, value)
return dialogue(text, value['text'])
diff --git a/freevideo_engine/prompt_vlm/service.py b/freevideo_engine/prompt_vlm/service.py
index 1a8acbf..b82404b 100644
--- a/freevideo_engine/prompt_vlm/service.py
+++ b/freevideo_engine/prompt_vlm/service.py
@@ -401,11 +401,13 @@ class Service:
self.progress(dict(phase='failed', error='busy'))
except Exception as error:
known = {'disk_space', 'ram_space', 'rewrite_failed', 'split_failed', 'worker_exit', 'timeout', 'worker_cleanup_failed'}
- self.progress(dict(phase='failed', error=str(error) if str(error) in known
+ self.progress(dict(phase='failed', error='invalid_output' if isinstance(error, rules.InvalidOutput)
+ else str(error) if str(error) in known
else 'download_failed' if action == 'install'
else 'ask_failed' if action == 'ask' else 'split_failed' if action == 'split'
else 'rewrite_failed',
- exception=type(error).__name__))
+ exception=type(error).__name__,
+ **({'output_rejection': error.details} if isinstance(error, rules.InvalidOutput) else {})))
finally:
if action != 'install':
self.stop_prestart(self.prewarm_state.get('reason', 'none'))
@@ -413,9 +415,10 @@ class Service:
self.progress(dict(phase='cancelled'))
self.result_expires = time.monotonic() + 600
# Allowlisted metadata only, never original/rewritten text or input paths.
+ # Output rejections contain condition IDs, character counts, picture numbers and retry flags only.
report = {key: item for key, item in self.state.items()
if key in ('phase', 'error', 'exception', 'error_details', 'timings', 'diagnostics',
- 'resources', 'cleanup', 'worker_returncode')}
+ 'resources', 'cleanup', 'worker_returncode', 'output_rejection')}
spec = assets.catalog()
report.update(schema='freevideo.prompt-vlm', schema_version=2, action=action,
created_epoch=time.time(), report_id=uuid.uuid4().hex,
@@ -580,7 +583,13 @@ class Service:
elif value.get('mode') == 'split':
rules.validate_parts(result.get('parts'), value)
else:
- rules.validate_output(result.get('text'), value)
+ try:
+ rules.validate_output(result.get('text'), value)
+ except rules.InvalidOutput as error:
+ stats = result.get('diagnostics') or {}
+ error.details['retried'] = bool(stats.get('picture_retry') or stats.get('dialogue_retry'))
+ self.progress(dict(diagnostics=stats))
+ raise
self.progress(dict(result, worker_returncode=child.returncode))
finally:
releasing = result_received_at[0] if result_received_at else time.monotonic()
diff --git a/freevideo_engine/prompt_vlm/worker.py b/freevideo_engine/prompt_vlm/worker.py
index 3a2b816..d07f2ba 100644
--- a/freevideo_engine/prompt_vlm/worker.py
+++ b/freevideo_engine/prompt_vlm/worker.py
@@ -156,7 +156,11 @@ def failure(error, mode='rewrite'):
code = message if message in allowed else 'out_of_memory' if 'out of memory' in message.lower() else fallback
frames = [dict(module=Path(f.filename).name, function=f.name, line=f.lineno)
for f in traceback.extract_tb(error.__traceback__)]
- return dict(error=code, exception=type(error).__name__, error_details=frames)
+ result = dict(error=code, exception=type(error).__name__, error_details=frames)
+ from .rules import InvalidOutput
+ if isinstance(error, InvalidOutput):
+ result['output_rejection'] = error.details
+ return result
def begin(stats):
@@ -217,7 +221,7 @@ OUTPUT_TOKENS = 1800
def kv_positions(input_tokens):
"""Cache positions reserved for a request: the input and its rewrite, then a
- dialogue retry that resends both with a short correction and writes another.
+ correction retry that resends both with a short instruction and writes another.
A retry that would need more is skipped when the model is held on the GPU."""
return input_tokens + 2 * OUTPUT_TOKENS + 256
@@ -237,7 +241,7 @@ def kv_bytes(stored, input_tokens):
def retry_allowed(tokens, stats):
- """A dialogue retry must fit the context limit and, on the GPU, the reserved cache."""
+ """A correction retry must fit the context limit and, on the GPU, the reserved cache."""
if tokens + OUTPUT_TOKENS > stats.get('kv_positions', tokens + OUTPUT_TOKENS):
stats['dialogue_retry_skipped'] = 'gpu_space'
return False
@@ -363,6 +367,16 @@ def run(folder, value, *, stats=None):
return rewrite(folder, value, stats)
+def validate_rewrite(text, value, stats, retried=False):
+ from .rules import InvalidOutput, validate_output
+ try:
+ return validate_output(text, value)
+ except InvalidOutput as error:
+ error.details['retried'] = retried
+ stats.setdefault('output_rejections', []).append(error.details)
+ raise
+
+
def rewrite(folder, value, stats):
stats.update(stage='imports', pid=os.getpid(), image_count=len(value['media']),
mode=value['mode'], dtype='bfloat16', attention='sdpa', kv_cache='dynamic',
@@ -370,7 +384,7 @@ def rewrite(folder, value, stats):
persistent_model=False)
torch, checkpoint = begin(stats)
from transformers import AutoProcessor
- from .rules import DIALOGUE_RETRY, instruction, language, missing_lines, user_text, validate_output
+ from .rules import DIALOGUE_RETRY, InvalidOutput, instruction, language, missing_lines, user_text
checkpoint('preprocess')
preparing = time.monotonic()
processor = AutoProcessor.from_pretrained(folder, local_files_only=True, trust_remote_code=False)
@@ -405,23 +419,51 @@ def rewrite(folder, value, stats):
raise ValueError('context_length')
text = processor.decode(ids, skip_special_tokens=True)
missing = missing_lines(text, value['text'])
- if missing:
- # One correction turn when the user's dialogue was dropped; keep the better draft.
- retry = messages + [{'role': 'assistant', 'content': text}, {'role': 'user', 'content': DIALOGUE_RETRY + '\n'.join(
- '- [%s] %s' % (language(line), line) for line in missing)}]
+ rewritten, rejected = None, None
+ pictures = []
+ try:
+ rewritten = validate_rewrite(text, value, stats)
+ except InvalidOutput as error:
+ rejected = error
+ if error.details['condition'] == 'missing_picture_reference':
+ pictures = error.details['missing_pictures']
+ if missing or pictures:
+ # Both corrections share one turn and the existing context/cache allowance.
+ correction = ''
+ if pictures:
+ labels = ', '.join(f'<Picture {i}>' for i in pictures)
+ correction = (f'Your rewrite omitted these required image 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 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}]
retry_inputs = tokenize(processor, retry)
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)
- stats.update(dialogue_retry=True, retry_output_tokens=len(again),
- rewrite_seconds=time.monotonic() - loaded)
+ stats.update(retry_output_tokens=len(again), rewrite_seconds=time.monotonic() - loaded)
+ if missing:
+ stats['dialogue_retry'] = True
+ if pictures:
+ stats['picture_retry'] = True
try:
- validate_output(second, value)
- if len(again) < 1800 and len(missing_lines(second, value['text'])) < len(missing):
- text = second
- except ValueError:
- pass
- rewritten = validate_output(text, value)
+ candidate = validate_rewrite(second, value, stats, retried=True)
+ if pictures 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 (pictures or len(missing_lines(second, value['text'])) < len(missing)):
+ rewritten = candidate
+ except InvalidOutput:
+ if pictures:
+ raise
+ elif pictures:
+ stats['picture_retry_skipped'] = stats.get('dialogue_retry_skipped', 'context_length')
+ if rewritten is None:
+ rejected.details = dict(rejected.details, retried=bool(stats.get('picture_retry') or stats.get('dialogue_retry')))
+ raise rejected
stats['stage'] = 'complete'
emit(phase='complete', text=rewritten, diagnostics=dict(stats))