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.

Convert timed lines and cuts in a description to H3 timed prompt notation

Bowen Xued1c57b46fb42
diff --git a/freevideo_engine/prompt_vlm/rules.py b/freevideo_engine/prompt_vlm/rules.py
index bb1e8ea..569d4e5 100644
--- a/freevideo_engine/prompt_vlm/rules.py
+++ b/freevideo_engine/prompt_vlm/rules.py
@@ -93,6 +93,9 @@ untranslated; each speaker keeps one ID and different speakers get different IDs
The young woman (S1) says softly: <d>[Chinese] 再见了。</d> The man (S2) replies: <d>[English] Wait.</d>
Dialogue belongs only in the first section, not in the sound sections.
"""
+ if TIMED_MARK.search(value['text']):
+ rule += ('The scene has fixed times. Keep every "At MM:SS.mmm" sentence and every [Shot n] At MM:SS.mmm cut '
+ 'exactly as given, in the same order and at the same time; add the picture, camera and sound around them.\n')
if value['mode'] == 'ref2va':
rule += """subject_definitions: Name each visible subject literally <Subject 1>, <Subject 2>, etc.,
with its appearance and source <Picture N> or <Video N>. Preserve the supplied numbering.
@@ -343,10 +346,28 @@ def dialogue(text, scene):
return text
+TIMED_MARK = re.compile(r'\bAt (\d{2}:\d{2}\.\d{3})')
+TAGGED = re.compile(r'<d>(?:\[[A-Za-z]+\])?\s*([^<\n]{1,400}?)\s*</d>')
+
+
def missing_lines(text, scene):
"""The user's spoken lines that the rewrite does not contain at all."""
have = plain(text)
- return [line for line in dict.fromkeys(spoken_lines(scene)) if plain(line) not in have]
+ lines = spoken_lines(scene)
+ if TIMED_MARK.search(scene):
+ # A timed scene already wraps its dialogue as <d>[Language] ...</d>; those lines are as fixed as quoted ones.
+ lines += [line for line in TAGGED.findall(scene) if plain(line)]
+ return [line for line in dict.fromkeys(lines) if plain(line) not in have]
+
+
+def lost_marks(text, scene):
+ """The scene's fixed times (At MM:SS.mmm) that the rewrite dropped or moved out of order."""
+ have = iter(TIMED_MARK.findall(text))
+ return [mark for mark in TIMED_MARK.findall(scene) if mark not in have]
+
+
+TIMING_RETRY = ('Your rewrite lost or reordered these fixed times. Keep every sentence that starts with "At MM:SS.mmm" '
+ 'and every [Shot n] At MM:SS.mmm cut exactly as given, in the same order: ')
DIALOGUE_RETRY = ('Your rewrite left out these spoken lines. Rewrite the whole prompt again in the same format and '
diff --git a/freevideo_engine/prompt_vlm/worker.py b/freevideo_engine/prompt_vlm/worker.py
index 508621f..078078e 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, TIMESTAMP_RETRY, InvalidOutput, fit_time_points, instruction, label, language, missing_lines, user_text
+ from .rules import DIALOGUE_RETRY, TIMESTAMP_RETRY, TIMING_RETRY, InvalidOutput, fit_time_points, instruction, label, language, lost_marks, missing_lines, user_text
checkpoint('preprocess')
preparing = time.monotonic()
processor = AutoProcessor.from_pretrained(folder, local_files_only=True, trust_remote_code=False)
@@ -421,7 +421,7 @@ def rewrite(folder, value, stats):
if len(ids) >= 1800:
raise ValueError('context_length')
text = processor.decode(ids, skip_special_tokens=True)
- missing = missing_lines(text, value['text'])
+ missing, marks = missing_lines(text, value['text']), lost_marks(text, value['text'])
rewritten, rejected = None, None
references, late, last = [], False, text
try:
@@ -434,8 +434,8 @@ def rewrite(folder, value, stats):
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.
+ if missing or marks or references or late:
+ # Every correction shares one turn and the existing context/cache allowance.
correction = ''
if references:
labels = ', '.join(references)
@@ -445,7 +445,9 @@ def rewrite(folder, value, stats):
if late:
correction += TIMESTAMP_RETRY % ((value['seconds'],) * 3)
if missing:
- correction += DIALOGUE_RETRY + '\n'.join('- [%s] %s' % (language(line), line) for line in missing)
+ correction += DIALOGUE_RETRY + '\n'.join('- [%s] %s' % (language(line), line) for line in missing) + '\n'
+ if marks:
+ correction += TIMING_RETRY + ', '.join(marks) + '\n'
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):
@@ -454,7 +456,7 @@ def rewrite(folder, value, stats):
# 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:
+ if missing or marks:
stats['dialogue_retry'] = True
if late:
stats['timestamp_retry'] = True
@@ -469,7 +471,7 @@ def rewrite(folder, value, stats):
error.details['retried'] = True
stats['output_rejections'].append(error.details)
raise error
- if len(again) < 1800 and (references or late 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(lost_marks(second, value['text'])) < len(missing) + len(marks)):
rewritten = candidate
except InvalidOutput:
if references and not late:
@@ -495,6 +497,9 @@ def rewrite(folder, value, stats):
if rewritten is None:
rejected.details = dict(rejected.details, retried=bool(stats.get('media_retry') or stats.get('dialogue_retry') or stats.get('timestamp_retry')))
raise rejected
+ if lost_marks(rewritten, value['text']):
+ # Fixed times that survive neither pass: the caller falls back to the converted original.
+ raise InvalidOutput('timing_lost', rewritten, value)
stats['stage'] = 'complete'
emit(phase='complete', text=rewritten, diagnostics=dict(stats))
diff --git a/freevideo_engine/timed_prompt.py b/freevideo_engine/timed_prompt.py
new file mode 100644
index 0000000..5e9721f
--- /dev/null
+++ b/freevideo_engine/timed_prompt.py
@@ -0,0 +1,115 @@
+"""Subtitle-style timed lines in a description, turned into MiniMax H3's timed prompt notation.
+
+`0:02 Lin: You are late.` becomes `At 00:02.000, Lin (S1) begins saying: <d>[English] You are late.</d>`,
+`0:07 cut: A corridor.` starts `[Shot 2] At 00:07.000, A corridor.` A description without timed lines, or one
+already written in the H3 notation, is returned unchanged. web/timed_prompt.js is the same function; both
+are checked against tests/fixtures/timed_prompt_cases.json.
+"""
+import re
+
+# The same space set as ECMAScript's \s and trim(), written out so Python and JavaScript read a line alike.
+SP = '\t\n\v\f\r \xa0\u1680\u2000-\u200a\u2028\u2029\u202f\u205f\u3000\ufeff'
+SPACES = '\t\n\v\f\r \xa0\u1680\u2000\u2001\u2002\u2003\u2004\u2005\u2006\u2007\u2008\u2009\u200a\u2028\u2029\u202f\u205f\u3000\ufeff'
+TIME = re.compile(r'^[ \t ]*([0-9]{1,3}):([0-5][0-9])(?:\.([0-9]{1,3}))?(?![0-9.:])[ \t ]*(.*)$')
+LOOSE = re.compile(r'^[ \t ]*[0-9]{1,3}:[0-9]{1,2}(?![0-9:])')
+CUT = re.compile(r'^(?:cut|CUT|Cut|切)[ \t ]*[::][ \t ]*(.*)$')
+CUT_BARE = re.compile(r'^(?:cut|CUT|Cut|切)$')
+SPEECH = re.compile(r'^@?([^::' + SP + r'][^::]{0,11}?)[ \t ]*[::][ \t ]*([^' + SP + r'].*)$')
+NAME_BREAK = re.compile(r'[,.;!?,。;!?]')
+WRITTEN = re.compile(r'\[Shot [0-9]+\]|\bAt [0-9]{2,}:[0-9]{2}\.[0-9]{3}', re.ASCII)
+CJK = re.compile('[぀-ヿ㐀-鿿]')
+ENDS = '.!?。!?…"”'
+
+
+def language(words):
+ if re.search('[぀-ヿ]', words):
+ return 'Japanese'
+ if re.search('[가-힯]', words):
+ return 'Korean'
+ if re.search('[一-鿿]', words):
+ return 'Chinese'
+ if re.search('[Ѐ-ӿ]', words):
+ return 'Russian'
+ return 'English'
+
+
+def clock(ms):
+ return '%02d:%02d.%03d' % (ms // 60000, ms // 1000 % 60, ms % 1000)
+
+
+def sentence(words):
+ words = words.strip(SPACES)
+ if not words or words[-1] in ENDS:
+ return words
+ return words + ('。' if CJK.search(words) else '.')
+
+
+def parse(text):
+ """(head lines, timed lines, errors); a timed line is {n, ms, kind, who, words}."""
+ head, lines, errors = [], [], []
+ for n, raw in enumerate(re.split(r'\r\n|\r|\n', text), 1):
+ found = TIME.match(raw)
+ if not found:
+ if LOOSE.match(raw):
+ errors.append({'line': n, 'code': 'bad_time'})
+ elif raw.strip(SPACES):
+ head.append(raw.strip(SPACES))
+ continue
+ minutes, seconds, fraction, rest = found.groups()
+ ms = (int(minutes) * 60 + int(seconds)) * 1000 + int((fraction or '').ljust(3, '0'))
+ rest = rest.strip(SPACES)
+ row = {'n': n, 'ms': ms, 'kind': 'event', 'who': '', 'words': rest}
+ cut, speech = CUT.match(rest), SPEECH.match(rest)
+ if cut or CUT_BARE.match(rest):
+ row.update(kind='cut', words=(cut.group(1) if cut else '').strip(SPACES))
+ elif speech and not NAME_BREAK.search(speech.group(1)):
+ row.update(kind='speech', who=speech.group(1).strip(SPACES), words=speech.group(2).strip(SPACES))
+ if not row['words']:
+ errors.append({'line': n, 'code': 'empty_cut' if row['kind'] == 'cut' else 'bad_time'})
+ continue
+ lines.append(row)
+ return head, lines, errors
+
+
+def convert(text, seconds, speakers=None, offset=0):
+ """{text, errors, timed}: errors name the lines left out ({line, code}); the caller stops on any.
+ Times are read on a ruler that starts `offset` seconds before this text's first second."""
+ if not isinstance(text, str) or WRITTEN.search(text):
+ return {'text': text, 'errors': [], 'timed': False}
+ head, lines, errors = parse(text)
+ if not lines and not errors:
+ return {'text': text, 'errors': [], 'timed': False}
+ limit = round(seconds * 1000)
+ kept = []
+ shift = round(offset * 1000)
+ for row in lines:
+ row['ms'] -= shift
+ if row['ms'] < 0 or row['ms'] >= limit:
+ errors.append({'line': row['n'], 'code': 'out_of_range'})
+ else:
+ kept.append(row)
+ errors.sort(key=lambda e: e['line'])
+ ids = dict(speakers or {})
+ shots = [{'ms': 0, 'open': ' '.join(head), 'parts': []}]
+ for row in sorted(kept, key=lambda r: (r['ms'], r['kind'] != 'cut', r['kind'] == 'speech')):
+ if row['kind'] == 'cut' and row['ms'] > 0:
+ if shots[-1]['ms'] == row['ms']:
+ shots[-1]['open'] = (shots[-1]['open'] + ' ' + sentence(row['words'])).strip(SPACES)
+ else:
+ shots.append({'ms': row['ms'], 'open': sentence(row['words']), 'parts': []})
+ continue
+ at = 'At %s, ' % clock(row['ms']) if row['ms'] > 0 else ''
+ if row['kind'] == 'cut':
+ shots[0]['open'] = (shots[0]['open'] + ' ' + sentence(row['words'])).strip(SPACES)
+ elif row['kind'] == 'event':
+ shots[-1]['parts'].append(at + sentence(row['words']))
+ else:
+ if row['who'] not in ids:
+ ids[row['who']] = max(ids.values(), default=0) + 1
+ shots[-1]['parts'].append('%s%s (S%d) begins saying: <d>[%s] %s</d>'
+ % (at, row['who'], ids[row['who']], language(row['words']), row['words']))
+ out = []
+ for index, shot in enumerate(shots, 1):
+ label = '[Shot 1]' if index == 1 else '[Shot %d] At %s,' % (index, clock(shot['ms']))
+ out.append(' '.join(part for part in (label, shot['open'], *shot['parts']) if part))
+ return {'text': ' '.join(out), 'errors': errors, 'timed': True}
diff --git a/scripts/test_freevideo_entry.mjs b/scripts/test_freevideo_entry.mjs
index 891d378..6c6e6f7 100644
--- a/scripts/test_freevideo_entry.mjs
+++ b/scripts/test_freevideo_entry.mjs
@@ -129,6 +129,7 @@ test('main browser entry registers both views and preserves node hooks', async t
.replace("import { startUpdateChecks } from './updates.js';", 'const {startUpdateChecks} = globalThis.__freevideoEntryTest;')
.replace("import { startDoneNotify, askDesktopPermission, DESKTOP_SETTING } from './done_notify.js';", 'const {startDoneNotify} = globalThis.__freevideoEntryTest; const askDesktopPermission = (...args) => globalThis.__permissionAsks.push(args); const DESKTOP_SETTING = "FreeVideo.DoneNotify.Desktop";')
.replace("import { attachReferencePicker, referenceItems, syncReferencePrompt, referenceInputs, mediaRows, mediaNodeOf } from './prompt_references.js';", 'const {attachReferencePicker,referenceItems,syncReferencePrompt,referenceInputs,mediaRows} = globalThis.__freevideoEntryTest; const mediaNodeOf = () => null;')
+ .replace("import { timedText } from './timed_prompt.js';", 'const timedText = text => text;')
.replace("import { expandCast } from './cast_mention.js';", 'const {expandCast} = globalThis.__freevideoEntryTest;')
.replace("import { outputDownloadURL } from './output_download.js';", 'const {outputDownloadURL} = globalThis.__freevideoEntryTest;')
.replace("import { shareButton } from './share.js';", 'const {shareButton} = globalThis.__freevideoEntryTest;')
diff --git a/web/editor.js b/web/editor.js
index 995545f..815c31c 100644
--- a/web/editor.js
+++ b/web/editor.js
@@ -38,6 +38,7 @@ import {optionalText, clonePrompt, allowEmptyPrompt} from './optional_inputs.js'
import {outputNotWritable} from './error_panel.js';
import {repairAction} from './repair_hint.js';
import {expandCast} from './cast_mention.js';
+import {problem as timedProblem, timedText} from './timed_prompt.js';
const editorStyles = Promise.all(['result_actions.css', 'editor.css', 'editor_expand.css', 'editor_tracks.css', 'editor_frame.css', 'editor_adjust.css', 'editor_adjust_picture.css', 'editor_preview_picture.css', 'editor_select.css', 'editor_menu.css', 'editor_text.css', 'editor_notes.css', 'editor_transport.css'].map(name => {
const style = document.createElement('link'); style.rel = 'stylesheet'; style.href = new URL(name, import.meta.url).href;
const ready = 'sheet' in style ? new Promise(resolve => { style.onload = style.onerror = resolve; }) : Promise.resolve();
@@ -333,6 +334,7 @@ export function openEditor({api, app, from = null, panel = {}, components: given
const text = textLongText(t, Number.isInteger(value.limit) ? value.limit : 8000);
out(text); return {ok: false, reason: code, say: text};
}
+ if (code === 'timed_text') { out(value.say); return {ok: false, reason: code, say: value.say}; }
if (PARTS_LIMIT_CODES.includes(code)) {
const [en, zh] = (value.said || []).map(text => typeof text === 'string' && text ? text.slice(0, 200) : null);
const text = en && zh ? t(en, zh) : partsLimitText(code, t, Number.isInteger(value.limit) ? value.limit : null);
@@ -517,7 +519,7 @@ export function openEditor({api, app, from = null, panel = {}, components: given
// Each part goes with its own description, as written while it waited.
const texts = Object.fromEntries(clips.map(clip => [clip.id, clip.text.trim() || entry.text]));
try { await actions.generate({text: texts[clips[0].id], texts, selection, allowEmpty: entry.allowEmpty === true}); }
- catch (value) { const reason = error(value, 'generate'); if (reason && !PARTS_LIMIT_CODES.includes(reason.reason)) genbar?.say(reason.say); }
+ catch (value) { const reason = error(value, 'generate'); if (reason && !PARTS_LIMIT_CODES.includes(reason.reason) && reason.reason !== 'timed_text') genbar?.say(reason.say); }
}
} finally { startingHeld = false; }
}
@@ -993,6 +995,12 @@ export function openEditor({api, app, from = null, panel = {}, components: given
const full = problem.code === 'chain_too_long' && beforeKeys.some(key => store.knownLineage()[key]?.parts >= model.RULES.maxParts);
throw Object.assign(new Error(full ? 'chain_source_full' : problem.code), {code: full ? 'chain_source_full' : problem.code, limit: problem.limit});
}
+ // Times in a description are read on the ruler; a part that continues keeps its text as typed.
+ const timedSpan = block => ({offset: (model.find(prepared, block.id)?.start ?? 0) / model.FPS, seconds: block.frames / model.FPS});
+ for (const block of request.blocks.filter(block => !block.after)) {
+ const {offset, seconds} = timedSpan(block), say = timedProblem(block.text, seconds, t, offset);
+ if (say) throw Object.assign(new Error('timed_text'), {code: 'timed_text', say});
+ }
const sizes = new Map(store.sources);
for (const key of beforeKeys.filter(key => key?.startsWith('chain:'))) {
const job = await store.chain(key.split(':')[1]);
@@ -1016,7 +1024,8 @@ export function openEditor({api, app, from = null, panel = {}, components: given
// continues carries only the pictures the engine keeps for it, and is numbered among them.
const castRows = panel.references?.available() ? panel.references.rows?.() ?? [] : [];
const blocks = request.blocks.map(({before, ...block}, i) => ({...block, seed: seed + i,
- text: expandCast(block.text, castRows, {continued: Boolean(block.after)}).text}));
+ text: expandCast(block.after ? block.text : (({seconds, offset}) => timedText(block.text, seconds, offset))(timedSpan(block)),
+ castRows, {continued: Boolean(block.after)}).text}));
const job = await store.startChain({...frozen, blocks, queue: true});
if (!job && !store.generationAvailable) {
if (epoch === projectEpoch) {
@@ -1038,7 +1047,7 @@ export function openEditor({api, app, from = null, panel = {}, components: given
if (epoch === projectEpoch) {
if (ids.length) state.settle(record => model.settle(record, ids, 'draft'));
// A length limit is the user's to change and is said once in the notice; there is nothing to report.
- if (!PARTS_LIMIT_CODES.includes(value?.code)) {
+ if (!PARTS_LIMIT_CODES.includes(value?.code) && value?.code !== 'timed_text') {
failures.submission(value, frozen, text); submissionFailure = JSON.stringify(state.selection);
}
genbar?.update(null);
diff --git a/web/editor_genbar.js b/web/editor_genbar.js
index 7a77500..7d2d3e4 100644
--- a/web/editor_genbar.js
+++ b/web/editor_genbar.js
@@ -302,7 +302,7 @@ export function createEditorGenbar(host, {state, t, actions, text = ''}) {
}
// A specific reason is said once; the planning limits are already shown above.
catch (error) { const result = actions.error(error, 'generate'); reason = result?.say || '';
- if (result?.say && !['chain_too_long', 'chain_part_too_short', 'chain_short_parts'].includes(result.reason)) say(result.say, false, ['Editor generation', '剪辑器生成']);
+ if (result?.say && !['chain_too_long', 'chain_part_too_short', 'chain_short_parts', 'timed_text'].includes(result.reason)) say(result.say, false, ['Editor generation', '剪辑器生成']);
else if (!result && !note.textContent) { reason = t('Could not start. Try again.', '没能开始,请重试。'); say(reason, false, ['Editor generation', '剪辑器生成']); } }
finally { pressing.delete(key); render(); }
return reason;
diff --git a/web/freevideo.js b/web/freevideo.js
index dd2e1db..5491d09 100644
--- a/web/freevideo.js
+++ b/web/freevideo.js
@@ -19,6 +19,7 @@ import { agentInterfaceState } from './agent_connect.js';
import { attachReferencePicker, referenceItems, syncReferencePrompt, referenceInputs, mediaRows, mediaNodeOf } from './prompt_references.js';
import { expandCast } from './cast_mention.js';
import { requestText } from './prompt_sections.js';
+import { timedText } from './timed_prompt.js';
import { outputDownloadURL } from './output_download.js';
import { shareButton } from './share.js';
import { reportFileName } from './report_issue.js';
@@ -829,8 +830,11 @@ app.registerExtension({
const owner = this;
// Replace person asks for its prefix here, where every way of running the node reads the text.
prompt.serializeValue = () => {
- const body = expandCast(requestText(prompt.value, owner.properties?.freevideo_prompt_versions),
- mediaRows(owner), {continued: Boolean(owner.freevideoContinues?.())}).text;
+ const continued = Boolean(owner.freevideoContinues?.());
+ // Subtitle-style time lines become H3's timed prompt; a long video made in parts keeps the typed text.
+ const typed = requestText(prompt.value, owner.properties?.freevideo_prompt_versions);
+ const timed = !continued && owner.freevideoSingleRun?.() ? timedText(typed, Number(owner.widgets?.find(w => w.name === 'seconds')?.value)) : typed;
+ const body = expandCast(timed, mediaRows(owner), {continued}).text;
return swapState(mediaNodeOf(owner)) ? withPrefix(body) : body;
};
}
diff --git a/web/health.js b/web/health.js
index d04f2c3..80becef 100644
--- a/web/health.js
+++ b/web/health.js
@@ -13,7 +13,7 @@ const t = (en, zh) => cn ? zh : en;
// launcher.js removes this flag during setup; read it before that.
const launchVisit = query.get('freevideo') === 'launch';
// Every script this folder ships; a test keeps the list in step with web/*.js.
-export const MODULES = ['audio_original.js', 'chat_data.js', 'phone_model.js', 'phone.js', 'lan_access.js', 'qrcodegen.js', 'agent_activity.js', 'agent_confirm_settings.js', 'agent_connect.js', 'agent_session.js', 'autopilot.js', 'autopilot_chat.js', 'chat_attachments.js', 'autopilot_conversations.js', 'browser_extension.js', 'caret_rect.js', 'chain_support.js', 'chain_rules.js', 'capability_view.js', 'cast_generate.js', 'cast_mention.js', 'cast_overlay.js', 'cast_source.js', 'compatibility.js', 'entry_showcase.js', 'error_panel.js', 'first_run_guide.js', 'fonts.js', 'freevideo.js', 'generation_progress.js',
+export const MODULES = ['audio_original.js', 'chat_data.js', 'phone_model.js', 'phone.js', 'lan_access.js', 'qrcodegen.js', 'agent_activity.js', 'agent_confirm_settings.js', 'agent_connect.js', 'agent_session.js', 'autopilot.js', 'autopilot_chat.js', 'chat_attachments.js', 'autopilot_conversations.js', 'browser_extension.js', 'caret_rect.js', 'chain_support.js', 'chain_rules.js', 'timed_prompt.js', 'capability_view.js', 'cast_generate.js', 'cast_mention.js', 'cast_overlay.js', 'cast_source.js', 'compatibility.js', 'entry_showcase.js', 'error_panel.js', 'first_run_guide.js', 'fonts.js', 'freevideo.js', 'generation_progress.js',
'editor.js', 'editor_actions.js', 'editor_lifecycle.js', 'editor_adjust.js', 'editor_adjust_picture.js', 'editor_picture_fields.js', 'editor_picture_session.js', 'editor_preview_picture.js', 'editor_entry.js', 'editor_expand.js', 'editor_export_dialog.js', 'editor_first_frame.js', 'editor_media_references.js', 'editor_references.js', 'editor_genbar.js', 'editor_duration.js', 'editor_geometry.js', 'editor_library.js', 'editor_menu.js', 'editor_model.js', 'editor_frame.js', 'editor_player.js', 'editor_room.js', 'editor_select.js', 'editor_state.js', 'editor_store.js', 'editor_tracks.js', 'editor_generation.js', 'editor_transport.js', 'editor_transport_model.js', 'editor_audio.js', 'editor_audio_model.js', 'editor_audio_notes.js', 'editor_audio_replace.js', 'editor_audio_rules.js', 'editor_music.js', 'editor_music_model.js', 'editor_speed.js', 'editor_speed_model.js', 'editor_failure.js', 'editor_header_fit.js',
'editor_loader.js', 'editor_text_coverage.js', 'editor_text.js', 'editor_toolbar_more.js', 'editor_text_model.js', 'editor_text_layout.js', 'editor_notes.js', 'editor_icons.js', 'dialog_keys.js', 'done_notify.js', 'failure_issue.js', 'feedback.js', 'frame_sizes.js', 'health.js', 'image_commands.js', 'image_editor.js', 'image_editor_engine.js', 'image_generation.js', 'image_lora.js', 'launch_visit.js', 'launcher.js', 'length_plan.js', 'lora_triggers.js', 'lora_check.js', 'library.js', 'motion.js', 'native_errors.js', 'translate_guard.js', 'output_download.js', 'port_notice.js', 'preview_scene.js',
'progress_connection.js', 'prompt_draft.js', 'prompt_enhance.js', 'prompt_references.js', 'prompt_sections.js', 'prompt_terms.js', 'request_assets.js', 'repair_hint.js', 'report_issue.js', 'issue_button.js', 'studio_recent.js',
diff --git a/web/studio.js b/web/studio.js
index fbf9283..59e2075 100644
--- a/web/studio.js
+++ b/web/studio.js
@@ -24,6 +24,7 @@ import { createStudioQueue, randomSeed, turnNodeOn } from './studio_queue.js';
import { isNetworkTypeError, connectionLostText, wrappedFetchOnly } from './browser_extension.js';
import { attachReferencePicker, referenceItems, enhancementMedia, syncReferencePrompt, referenceInputs, mentionAt, handleNames, mediaRows } from './prompt_references.js';
import { attachTermSuggest } from './prompt_terms.js';
+import { problem as timedProblem, timedText } from './timed_prompt.js';
import { castInRows, expandCast, mentionHandle, mentionState, mentionedIds, restoreCast, withCharacter, MAX_PICTURES_EACH } from './cast_mention.js';
import { attachMentionOverlay } from './cast_overlay.js';
import { openCastLibrary } from './cast_source.js';
@@ -820,7 +821,10 @@ export function openStudio(node, {extendFrom = null} = {}) {
const castChanged = event => { if (String(event.detail) === String(mediaNode?.id)) { castOverlay.refresh(); references.refresh(); announceCast(); } };
window.addEventListener('freevideo-media', castChanged);
node.freevideoContinues = () => Boolean(extension.source);
- cleanup.push(() => { castLibrary?.destroy?.(); castLibrary = null; sceneLibrary?.destroy?.(); sceneLibrary = null; window.removeEventListener('freevideo-media', castChanged); prompt.removeEventListener('input', announceCast); castOverlay.dispose(); delete node.freevideoContinues; });
+ // Time lines are read for one video made in a single run; parts of a long video keep the typed text.
+ const timedRun = () => !extension.source && (lengthControl?.plan ? lengthControl.plan.count === 1 : Number(value(node, 'seconds')) <= 15);
+ node.freevideoSingleRun = timedRun;
+ cleanup.push(() => { castLibrary?.destroy?.(); castLibrary = null; sceneLibrary?.destroy?.(); sceneLibrary = null; window.removeEventListener('freevideo-media', castChanged); prompt.removeEventListener('input', announceCast); castOverlay.dispose(); delete node.freevideoContinues; delete node.freevideoSingleRun; });
openCastLibrary({api, text: t, viewURL: view, uploadOne: castUpload, onChange: () => { castOverlay.refresh(); references.refresh(); }})
.then(library => { if (disposed) library?.destroy?.(); else castLibrary = library; });
openCastLibrary({api, text: t, viewURL: view, uploadOne: castUpload, kind: 'setting', onChange: () => { references.refresh(); }})
@@ -828,7 +832,7 @@ export function openStudio(node, {extendFrom = null} = {}) {
let requestAssets = null, rewriteSubjects = [];
const enhancer = createPromptEnhancer({node, input: prompt, editor: promptEditor, api, t, starter, issueButton,
// One rewrite runs at a time, so the subjects of the text it was given are the ones its numbers refer to.
- prepare: text => { const out = expandCast(text, mediaRows(node), {continued: Boolean(extension.source)}); rewriteSubjects = out.subjects; return out.text; },
+ prepare: text => { const out = expandCast(timedRun() ? timedText(text, Number(value(node, 'seconds'))) : text, mediaRows(node), {continued: Boolean(extension.source)}); rewriteSubjects = out.subjects; return out.text; },
restore: text => restoreCast(text, rewriteSubjects), display: text => shownRewrite(text, t('en', 'zh')) ?? text,
// The rewrite has its own report; the video's report entry is not touched.
onReport: row => { node.freevideoPromptReportId = row.rewrite_report_id || row.report_id; },
@@ -1916,6 +1920,8 @@ export function openStudio(node, {extendFrom = null} = {}) {
const missing = swapMissing(swapState(mediaNode));
if (missing) { status.dataset.error = 'true'; status.textContent = swapMissingText(missing, t); return; }
}
+ const timedNote = !prompt.disabled && timedRun() ? timedProblem(prompt.value, Number(value(node, 'seconds')), t) : '';
+ if (timedNote) { status.dataset.error = 'true'; status.textContent = timedNote; prompt.focus(); return; }
const chosenMode = runMode, batchCount = chosenMode === 'batch' ? Number(count.value) : 1;
const originalSeed = value(node, 'seed'), seedMode = mode.value;
// A request that is not accepted leaves the node mode as the user had it; a retry turns it on again.
diff --git a/web/timed_prompt.js b/web/timed_prompt.js
new file mode 100644
index 0000000..9a08cf3
--- /dev/null
+++ b/web/timed_prompt.js
@@ -0,0 +1,115 @@
+// Subtitle-style timed lines in a description, turned into MiniMax H3's timed prompt notation.
+// Same function as freevideo_engine/timed_prompt.py; both are checked against tests/fixtures/timed_prompt_cases.json.
+const TIME = /^[ \t ]*(\d{1,3}):([0-5]\d)(?:\.(\d{1,3}))?(?![\d.:])[ \t ]*([^\r\n]*)$/;
+const LOOSE = /^[ \t ]*\d{1,3}:\d{1,2}(?![\d:])/;
+const CUT = /^(?:cut|CUT|Cut|切)[ \t ]*[::][ \t ]*([^\r\n]*)$/;
+const CUT_BARE = /^(?:cut|CUT|Cut|切)$/;
+const SPEECH = /^@?([^::\s ][^::]{0,11}?)[ \t ]*[::][ \t ]*(\S[^\r\n]*)$/;
+const NAME_BREAK = /[,.;!?,。;!?]/;
+const WRITTEN = /\[Shot \d+\]|\bAt \d{2,}:\d{2}\.\d{3}/;
+const CJK = /[぀-ヿ㐀-鿿]/;
+const ENDS = '.!?。!?…"”';
+
+export function language(words) {
+ if (/[぀-ヿ]/.test(words)) return 'Japanese';
+ if (/[가-힯]/.test(words)) return 'Korean';
+ if (/[一-鿿]/.test(words)) return 'Chinese';
+ if (/[Ѐ-ӿ]/.test(words)) return 'Russian';
+ return 'English';
+}
+
+const pad = (value, width) => String(value).padStart(width, '0');
+export const clock = ms => `${pad(Math.floor(ms / 60000), 2)}:${pad(Math.floor(ms / 1000) % 60, 2)}.${pad(ms % 1000, 3)}`;
+
+function sentence(words) {
+ words = words.trim();
+ if (!words || ENDS.includes(words[words.length - 1])) return words;
+ return words + (CJK.test(words) ? '。' : '.');
+}
+
+export function parse(text) {
+ const head = [], lines = [], errors = [];
+ text.split(/\r\n|\r|\n/).forEach((raw, index) => {
+ const n = index + 1, found = TIME.exec(raw);
+ if (!found) {
+ if (LOOSE.test(raw)) errors.push({line: n, code: 'bad_time'});
+ else if (raw.trim()) head.push(raw.trim());
+ return;
+ }
+ const [, minutes, seconds, fraction, rest0] = found, rest = rest0.trim();
+ const ms = (Number(minutes) * 60 + Number(seconds)) * 1000 + Number((fraction || '').padEnd(3, '0') || 0);
+ const row = {n, ms, kind: 'event', who: '', words: rest};
+ const cut = CUT.exec(rest), speech = SPEECH.exec(rest);
+ if (cut || CUT_BARE.test(rest)) Object.assign(row, {kind: 'cut', words: (cut ? cut[1] : '').trim()});
+ else if (speech && !NAME_BREAK.test(speech[1])) Object.assign(row, {kind: 'speech', who: speech[1].trim(), words: speech[2].trim()});
+ if (!row.words) { errors.push({line: n, code: row.kind === 'cut' ? 'empty_cut' : 'bad_time'}); return; }
+ lines.push(row);
+ });
+ return [head, lines, errors];
+}
+
+export function convert(text, seconds, speakers = null, offset = 0) {
+ if (typeof text !== 'string' || WRITTEN.test(text)) return {text, errors: [], timed: false};
+ const [head, lines, errors] = parse(text);
+ if (!lines.length && !errors.length) return {text, errors: [], timed: false};
+ const limit = Math.round(seconds * 1000), kept = [];
+ const shift = Math.round(offset * 1000);
+ for (const row of lines) {
+ row.ms -= shift;
+ if (row.ms < 0 || row.ms >= limit) errors.push({line: row.n, code: 'out_of_range'});
+ else kept.push(row);
+ }
+ errors.sort((a, b) => a.line - b.line);
+ const ids = Object.assign(Object.create(null), speakers);
+ const shots = [{ms: 0, open: head.join(' '), parts: []}];
+ const rank = row => [row.kind !== 'cut', row.kind === 'speech'];
+ const order = kept.map((row, i) => [row, i]).sort(([a, i], [b, j]) => a.ms - b.ms
+ || rank(a)[0] - rank(b)[0] || rank(a)[1] - rank(b)[1] || i - j);
+ for (const [row] of order) {
+ const last = shots[shots.length - 1];
+ if (row.kind === 'cut' && row.ms > 0) {
+ if (last.ms === row.ms) last.open = `${last.open} ${sentence(row.words)}`.trim();
+ else shots.push({ms: row.ms, open: sentence(row.words), parts: []});
+ continue;
+ }
+ const at = row.ms > 0 ? `At ${clock(row.ms)}, ` : '';
+ if (row.kind === 'cut') shots[0].open = `${shots[0].open} ${sentence(row.words)}`.trim();
+ else if (row.kind === 'event') last.parts.push(at + sentence(row.words));
+ else {
+ if (!(row.who in ids)) ids[row.who] = Math.max(0, ...Object.values(ids)) + 1;
+ last.parts.push(`${at}${row.who} (S${ids[row.who]}) begins saying: <d>[${language(row.words)}] ${row.words}</d>`);
+ }
+ }
+ const out = shots.map((shot, index) => {
+ const label = index === 0 ? '[Shot 1]' : `[Shot ${index + 1}] At ${clock(shot.ms)},`;
+ return [label, shot.open, ...shot.parts].filter(Boolean).join(' ');
+ });
+ return {text: out.join(' '), errors, timed: true};
+}
+
+const shortClock = seconds => `${Math.floor(seconds / 60)}:${pad(Math.floor(seconds % 60), 2)}`;
+
+// The first line the user has to fix, in one sentence; '' when every timed line can be used.
+export function problem(text, seconds, t, offset = null) {
+ const {errors} = convert(text, seconds, null, offset ?? 0);
+ if (!errors.length) return '';
+ const {line, code} = errors[0], raw = text.split(/\r\n|\r|\n/)[line - 1] || '';
+ const time = (/^[ \t ]*(\d{1,3}:\d{1,3}(?:\.\d{1,3})?)/.exec(raw) || [, ''])[1];
+ const length = shortClock(seconds);
+ if (code === 'out_of_range' && offset !== null) {
+ const range = `${shortClock(offset)}\u2060–\u2060${shortClock(offset + seconds)}`;
+ return t(`Line ${line} is at ${time}, outside this part (${range}). Change it to a time within this part.`,
+ `第 ${line} 行的时间 ${time} 超出这一段(${range}),请改为这段内的时间。`);
+ }
+ if (code === 'out_of_range') return t(`Line ${line} is at ${time}, beyond the video length (${length}). Change it to a time within ${length}.`,
+ `第 ${line} 行的时间 ${time} 超出视频时长(${length}),请改为 ${length} 以内的时间。`);
+ if (code === 'empty_cut') return t(`Line ${line} has nothing after the cut. Describe the new shot.`, `第 ${line} 行的“切:”后面没有内容,请写出新镜头的画面。`);
+ return t(`The time "${time}" on line ${line} is not valid. Write it as minutes:seconds, for example 0:05.`,
+ `第 ${line} 行的时间“${time}”无法识别,请按“分:秒”书写,例如 0:05。`);
+}
+
+// What the model and the generator read: the converted text, or the typed text while a line is unusable.
+export function timedText(text, seconds, offset = 0) {
+ const done = convert(text, seconds, null, offset);
+ return done.errors.length ? text : done.text;
+}
diff --git a/web/tutorial/timed-lines-1.webp b/web/tutorial/timed-lines-1.webp
new file mode 100644
index 0000000..f709f45
Binary files /dev/null and b/web/tutorial/timed-lines-1.webp differ
diff --git a/web/tutorial/timed-lines-2.webp b/web/tutorial/timed-lines-2.webp
new file mode 100644
index 0000000..944d66e
Binary files /dev/null and b/web/tutorial/timed-lines-2.webp differ
diff --git a/web/tutorial_book_content.js b/web/tutorial_book_content.js
index 36c7261..2642c27 100644
--- a/web/tutorial_book_content.js
+++ b/web/tutorial_book_content.js
@@ -47,6 +47,29 @@ export const TUTORIAL_CHAPTERS = [
en: ['Higher resolution and longer length take more time and memory.', 'Text named in the prompt may not appear exactly in the picture.', 'With "FreeToken enhancement" on, the prompt is rewritten in more detail on this computer.'],
},
},
+ {
+ id: 'timed-lines',
+ title: {zh: '按时间写台词和镜头', en: 'Write lines and cuts by time'},
+ summary: {zh: '在描述中按时间写台词和切镜,镜头会在写定的时间切换。', en: 'Write lines and cuts with times in the prompt, and the shot changes at the times you set.'},
+ media: {
+ type: 'image',
+ src: {zh: 'timed-lines-1.webp', en: 'timed-lines-2.webp'},
+ alt: {zh: '创作面板:按时间书写台词和切镜的描述已用红框标出。', en: 'The creation panel, with a prompt of timed lines and a cut outlined in red.'},
+ },
+ steps: {
+ zh: ['在描述中另起一行,以“分:秒”开头,例如“0:02”。', '时间后写“名字:台词”,表示这个人按顺序说这句话;直接写一句话,表示这时发生的事。', '时间后写“切:”再写新镜头的画面,镜头会在这个时间切换。'],
+ en: ['Start a new line in the prompt with minutes:seconds, for example "0:02".', 'After the time, write "Name: line" for a line the person says in turn, or a plain sentence for something that happens.', 'After the time, write "Cut:" and the new shot, and the shot changes at that time.'],
+ },
+ example: {
+ assets: [],
+ prompt: ['A small platform at dawn. Lin hurries in with a bag; Jay stands by the bench.\n0:01 Jay: You\'re late.\n0:02 Lin: The train was delayed.\n0:04 Cut: The two walk side by side to the train, tracking from the side.', '清晨的小站台,小林提着包快步走来,阿杰站在长椅旁。\n0:01 阿杰:你迟到了。\n0:02 小林:车晚点了。\n0:04 切:两人并肩走向列车,侧面跟拍'],
+ settings: {seconds: 8},
+ },
+ limits: {
+ zh: ['时间必须在视频时长以内。', '没有写“切:”的地方不会切镜。'],
+ en: ['Each time must be within the video length.', 'Without "Cut:", the shot does not change.'],
+ },
+ },
{
id: 'first-last-frame',
title: {zh: '首帧和尾帧', en: 'First and last frames'},