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.
Let prompt enhancement skip audio and connected media and read reference videos
Bowen Xuecbd1e3c1f86b
diff --git a/freevideo_engine/prompt_vlm/rules.py b/freevideo_engine/prompt_vlm/rules.pyindex e154bd2..8d4e8a6 100644--- a/freevideo_engine/prompt_vlm/rules.py+++ b/freevideo_engine/prompt_vlm/rules.py@@ -23,8 +23,13 @@ def request(value):raise ValueError('too_many_images')roles = []for row in media:- if (not isinstance(row, dict) or set(row) != {'file', 'role'} or- not isinstance(row['file'], str) or row['role'] not in ('first', 'last', 'reference')):+ # kind and number say which <Picture N> / <Video N> label the scene uses for the row; connected+ # nodes and audio are left out of the list, so the numbers can skip.+ if (not isinstance(row, dict) or not {'file', 'role'} <= set(row) <= {'file', 'role', 'kind', 'number'} or+ not isinstance(row['file'], str) or row['role'] not in ('first', 'last', 'reference') or+ row.get('kind', 'image') not in ('image', 'video') or+ (row.get('kind') == 'video' and row['role'] != 'reference') or+ (type(row.get('number', 1)) is not int or not 1 <= row.get('number', 1) <= 99)):raise ValueError('unsupported_media')roles.append(row['role'])if 'reference' in roles and any(r in roles for r in ('first', 'last')):@@ -36,9 +41,40 @@ def request(value):# Anchor numbering must match the encoder even when the UI added last first.if mode != 'ref2va':media = sorted(media, key=lambda r: r['role'] != 'first')+ if len({'number' in row for row in media}) > 1:+ raise ValueError('unsupported_media')+ counters, rows = {}, []+ for row in media:+ kind = row.get('kind', 'image')+ counters[kind] = counters.get(kind, 0) + 1+ rows.append(dict(file=row['file'], role=row['role'], kind=kind, number=row.get('number', counters[kind])))+ media = rows+ if len({label(row) for row in media}) != len(media):+ raise ValueError('unsupported_media')return dict(text=prompt, seconds=float(seconds), media=media, mode=mode)+LABEL = re.compile(r'<(Picture|Video|Audio) (\d+)>')+++def label(row):+ return '<%s %d>' % ('Video' if row['kind'] == 'video' else 'Picture', row['number'])+++def unseen_labels(value):+ """Labels the scene uses for media the model cannot look at (audio, connected nodes)."""+ shown = {label(row) for row in value['media']}+ found = []+ for match in LABEL.finditer(value['text']):+ if match.group(0) not in shown and match.group(0) not in found:+ found.append(match.group(0))+ return found+++def required_labels(value):+ return [label(row) for row in value['media']] + unseen_labels(value)++def instruction(value):rule = """Rewrite the user scene as an English MiniMax H3 video prompt. Follow the requestedactions and camera movement exactly. Image references describe appearance, not whether an@@ -57,7 +93,8 @@ Dialogue belongs only in the first section, not in the sound sections."""if value['mode'] == 'ref2va':rule += """subject_definitions: Name each visible subject literally <Subject 1>, <Subject 2>, etc.,-with its appearance and source <Picture N>. Preserve the supplied picture numbering.+with its appearance and source <Picture N> or <Video N>. Preserve the supplied numbering.+A video is shown as one still frame.summary: [reference generation] State what happens in the requested video.retention_analysis: Mark each subject fully_preserved, partially_preserved, attribute_transfer,or weak_reference. This describes retained visual attributes, not motion restrictions.@@ -65,14 +102,18 @@ detailed_description: [Shot 1] Describe the target video, using <Subject N> iden"""else:rule += 'integrated_multimodal_description: [Shot 1] Describe the target video.\n'- for i, row in enumerate(value['media'], 1):+ for row in value['media']:timestamp = '0.00' if row['role'] == 'first' else f'{value["seconds"]:.2f}'- rule += (f'Anchor <Picture {i}> to the {row["role"]} frame at {timestamp} seconds; '+ rule += (f'Anchor {label(row)} to the {row["role"]} frame at {timestamp} seconds; ''keep its pictured layout at that anchor.\n')rule += """overall_soundscape: Environmental sounds, or N/A.non_diegetic_music: Music only if requested, otherwise N/A.Use only supplied media labels; do not invent audio or video references."""+ unseen = unseen_labels(value)+ if unseen:+ rule += ('The scene also uses ' + ', '.join(unseen) + ', which you cannot see. '+ 'Keep each of those labels exactly as written, where the scene uses it.\n')fields = REF_FIELDS if value['mode'] == 'ref2va' else BASE_FIELDSreturn (rule + f'Cover {value["seconds"]:.3f} seconds. All sections are required, in this order: '+ ', '.join(fields) + f'. Begin with "{fields[0]}:".')@@ -97,11 +138,12 @@ class InvalidOutput(ValueError):def __init__(self, condition, text, value):super().__init__('invalid_output')draft = text if isinstance(text, str) else ''+ required = required_labels(value)+ pictures = [int(each[len('<Picture '):-1]) for each in required if each.startswith('<Picture ')]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'])),+ missing_pictures=sorted(i for i in pictures if f'<Picture {i}>' not in draft),+ out_of_range_pictures=sorted(i for i in indices if i not in pictures),retried=False)@@ -128,13 +170,14 @@ def validate_output(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 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 InvalidOutput('picture_index_out_of_range', text, value)- if re.search(r'<(?:Audio|Video) \d+>', text):- raise InvalidOutput('unsupported_audio_video_reference', text, value)- for i in range(1, len(value['media']) + 1):- if f'<Picture {i}>' not in text:+ # Only the labels the scene itself uses: the media given, plus audio and connected media it cannot see.+ required = required_labels(value)+ for found in LABEL.finditer(text):+ if found.group(0) not in required:+ raise InvalidOutput('picture_index_out_of_range' if found.group(1) == 'Picture'+ else 'unsupported_audio_video_reference', text, value)+ for each in required:+ if each not in text: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.pyindex b82404b..918eb59 100644--- a/freevideo_engine/prompt_vlm/service.py+++ b/freevideo_engine/prompt_vlm/service.py@@ -6,6 +6,7 @@ from pathlib import Pathimport queueimport secretsimport subprocess+import tempfileimport threadingimport timeimport uuid@@ -287,12 +288,13 @@ class Service:raise ValueError('model_missing')value = rules.request(value)from ..comfy_assets import resolve_assets- resolved = resolve_assets(json.dumps(value['media']), self.input_directory())+ resolved = resolve_assets(json.dumps([dict(file=row['file'], role=row['role']) for row in value['media']]),+ self.input_directory())for i, row in enumerate(value['media']):path = (resolved['references'][i]['path'] if row['role'] == 'reference'else resolved[row['role']])from ..comfy_assets import media_kind- if media_kind(path) != 'image':+ if media_kind(path) != row['kind']:raise ValueError('unsupported_media')row['path'] = pathwith self.mutex:@@ -370,6 +372,18 @@ class Service:except Exception:pass+ def video_frames(self, value, folder):+ """The model reads pictures: a reference video is shown as its middle frame."""+ for row in value.get('media', ()):+ if row.get('kind') != 'video':+ continue+ self.check()+ try:+ from ..agent.media import sample_frames+ row['path'] = sample_frames(row['path'], Path(folder) / str(row['number']), count=1)[0]['path']+ except Exception:+ raise ValueError('unreadable_video') from None+def work(self, root, machine, action, value):from ..locking import runtime_lockfrom ..monitoring import save@@ -394,13 +408,15 @@ class Service:self.check()self.progress(dict(phase='complete'))else:- self.infer(root, machine, descriptor, value)+ with tempfile.TemporaryDirectory(prefix='freevideo-prompt-', ignore_cleanup_errors=True) as frames:+ self.video_frames(value, frames)+ self.infer(root, machine, descriptor, value)except InterruptedError:self.progress(dict(phase='cancelled'))except BlockingIOError: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'}+ known = {'disk_space', 'ram_space', 'unreadable_video', 'rewrite_failed', 'split_failed', 'worker_exit', 'timeout', 'worker_cleanup_failed'}self.progress(dict(phase='failed', error='invalid_output' if isinstance(error, rules.InvalidOutput)else str(error) if str(error) in knownelse 'download_failed' if action == 'install'diff --git a/freevideo_engine/prompt_vlm/worker.py b/freevideo_engine/prompt_vlm/worker.pyindex d07f2ba..0b6f97e 100644--- a/freevideo_engine/prompt_vlm/worker.py+++ b/freevideo_engine/prompt_vlm/worker.py@@ -384,14 +384,14 @@ def rewrite(folder, value, stats):persistent_model=False)torch, checkpoint = begin(stats)from transformers import AutoProcessor- from .rules import DIALOGUE_RETRY, InvalidOutput, instruction, language, missing_lines, user_text+ from .rules import DIALOGUE_RETRY, InvalidOutput, instruction, label, language, missing_lines, user_textcheckpoint('preprocess')preparing = time.monotonic()processor = AutoProcessor.from_pretrained(folder, local_files_only=True, trust_remote_code=False)messages = [{'role': 'system', 'content': instruction(value)}]content = []- for index, row in enumerate(value['media'], 1):- content.extend([{'type': 'text', 'text': f'<Picture {index}> ({row["role"]})'},+ for row in value['media']:+ content.extend([{'type': 'text', 'text': f'{label(row)} ({row["role"]})'},{'type': 'image', 'image': open_image(row['path'])}])content.append({'type': 'text', 'text': user_text(value)})messages.append({'role': 'user', 'content': content})diff --git a/web/prompt_enhance.js b/web/prompt_enhance.jsindex 4099f60..a12259a 100644--- a/web/prompt_enhance.js+++ b/web/prompt_enhance.js@@ -129,7 +129,10 @@ export function createPromptEnhancer({node, input, editor, api, context, setTextdownload_failed: t('Download paused. Retry to resume.', '下载已暂停,重试可继续。'),disk_space: t('Not enough disk space for the optional model.', '可选模型的磁盘空间不足,请清理后重试。'),ram_space: t(`This model needs about ${gib(error?.ramBytes || ramBytes)} GiB of available RAM to load. You can keep using the original.`, `此模型加载需约 ${gib(error?.ramBytes || ramBytes)} GiB 可用内存,可先使用原文生成。`),- unsupported_media: t('Use images added in Media for enhancement; connected nodes, video and audio are not supported yet.', '增强暂支持在素材中添加的图片;连接节点、视频和音频暂不支持。'),+ unsupported_media: t('Enhancement can read only images and videos added in Media. You can keep using the original.', '增强只能读取素材中添加的图片和视频,可先使用原文生成。'),+ connected_media: t('Enhancement cannot read connected nodes. Add images or videos in Media, or use the original.', '增强读不到连接节点的素材,请在素材中添加图片或视频,或使用原文。'),+ audio_media: t('Enhancement cannot read audio. Add images or videos in Media, or use the original.', '增强读不到音频,请在素材中添加图片或视频,或使用原文。'),+ unreadable_video: t('Could not read a frame from this video. Replace it with another video or an image, or use the original.', '读不出这个视频的画面,请换一个视频或图片,或使用原文。'),too_many_images: t('Use up to 8 reference images for enhancement.', '增强暂支持最多 8 张参考图。'),invalid_prompt: t('Enter a prompt of up to 12,000 characters.', '请输入不超过 12,000 字符的提示词。'),invalid_output: t('The rewrite was incomplete. Retry or use the original.', '改写结果不完整,请重试或使用原文。'),diff --git a/web/prompt_references.js b/web/prompt_references.jsindex 1096c78..6519641 100644--- a/web/prompt_references.js+++ b/web/prompt_references.js@@ -73,6 +73,17 @@ export function referenceItems(node) {token: `<${titles[item.kind]} ${counters[item.kind]}>`}));}+// What the prompt model can read: pictures and, as one still frame, videos added in Media. Audio and connected+// nodes are left out, and keep their labels in the scene; the error names why only when nothing is left.+export function enhancementMedia(items, conditioningLinked = false) {+ const media = items.filter(row => row.file && ['image', 'video'].includes(row.kind))+ .map(row => ({file: row.file, role: row.role || 'reference', kind: row.kind, number: row.number}));+ if (media.length) return media;+ const connected = conditioningLinked || items.some(row => !row.file);+ if (connected || items.length) throw new Error(connected ? 'connected_media' : 'audio_media');+ return media;+}+export function remapReferences(text, previous, current, removed = '[Removed reference]') {const byKey = new Map(current.map(item => [item.key, item.token]));const replacement = new Map(previous.map(item => [item.token, byKey.get(item.key) || removed]));diff --git a/web/studio.js b/web/studio.jsindex 970cbaf..9893c74 100644--- a/web/studio.js+++ b/web/studio.js@@ -22,7 +22,7 @@ import { createRecentVideos } from './studio_recent.js';import { createAgentActivity } from './agent_activity.js';import { createStudioQueue, randomSeed, turnNodeOn } from './studio_queue.js';import { isNetworkTypeError, connectionLostText } from './browser_extension.js';-import { attachReferencePicker, referenceItems, syncReferencePrompt, referenceInputs, mentionAt, handleNames, mediaRows } from './prompt_references.js';+import { attachReferencePicker, referenceItems, enhancementMedia, syncReferencePrompt, referenceInputs, mentionAt, handleNames, mediaRows } from './prompt_references.js';import { attachTermSuggest } from './prompt_terms.js';import { castInRows, expandCast, mentionHandle, mentionState, mentionedIds, withCharacter, MAX_PICTURES_EACH } from './cast_mention.js';import { attachMentionOverlay } from './cast_overlay.js';@@ -749,9 +749,8 @@ export function openStudio(node, {extendFrom = null} = {}) {onReport: row => { node.freevideoPromptReportId = row.rewrite_report_id || row.report_id; },onChange: () => { rememberPromptDraft(api, node); requestAssets?.refresh(); },setText: text => { set(node, 'text', text || (untouched() ? starter : '')); placeholder(); }, context: () => {- const items = referenceItems(node);- if (linked(node, 'conditioning') || items.some(row => !row.file || row.kind !== 'image')) throw new Error('unsupported_media');- return {seconds: Number(value(node, 'seconds')), media: items.map(row => ({file: row.file, role: row.role || 'reference'}))};+ const media = enhancementMedia(referenceItems(node), linked(node, 'conditioning'));+ return {seconds: Number(value(node, 'seconds')), media};}});cleanup.push(() => enhancer.dispose());requestAssets = createRequestAssets({t, api, request: () => requestAssetsQuery?.()});