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.

Add Replace person to the Studio media section

Bowen Xuee7f0e9611c8c
diff --git a/freevideo_engine/comfy_assets.py b/freevideo_engine/comfy_assets.py
index 0ed3b95..5c3db2d 100644
--- a/freevideo_engine/comfy_assets.py
+++ b/freevideo_engine/comfy_assets.py
@@ -75,7 +75,7 @@ def resolve_assets(serialized, input_directory):
root = Path(input_directory).resolve()
result = {}
for row in rows:
- if not isinstance(row, dict) or set(row) - {'file', 'role', 'enabled', 'cast', 'early_steps', 'sound', 'guide'}:
+ if not isinstance(row, dict) or set(row) - {'file', 'role', 'enabled', 'cast', 'early_steps', 'sound', 'guide', 'keep_source_audio'}:
raise ValueError('Invalid media item')
# The character an @ mention added the row for; a continued part keeps one picture per character.
if 'cast' in row and (set(row['cast'] if isinstance(row['cast'], dict) else ('?',)) != {'id'}
@@ -122,6 +122,11 @@ def resolve_assets(serialized, input_directory):
validate_guide(dict(row, kind=kind))
if row['guide']:
reference['guide'] = True
+ if 'keep_source_audio' in row:
+ from .media_request import validate_keep_source_audio
+ validate_keep_source_audio(dict(row, kind=kind), path)
+ if row['keep_source_audio']:
+ reference['keep_source_audio'] = True
result.setdefault('references', []).append(reference)
else:
raise ValueError('Media role must be first, last or reference')
@@ -227,6 +232,8 @@ def output_summary(report, relative_video):
video=relative_video.as_posix(), report=relative_video.with_suffix(
'.debug.json' if report.get('diagnostic_file') == relative_video.with_suffix('.debug.json').name
else '.request.json').as_posix())
+ if report.get('keep_source_audio_failed'):
+ result['keep_source_audio_failed'] = True
if type(report.get('output_frames')) is int and report['output_frames'] > 0:
# Resource reports keep the generated canvas; result cards show only saved frames.
result['geometry'].update(frames=report['output_frames'],
diff --git a/freevideo_engine/comfy_upload.py b/freevideo_engine/comfy_upload.py
index cc7b408..175afa8 100644
--- a/freevideo_engine/comfy_upload.py
+++ b/freevideo_engine/comfy_upload.py
@@ -55,7 +55,15 @@ async def receive(reader, input_directory):
except BaseException:
shutil.rmtree(folder, ignore_errors=True)
raise
- return {'file': destination.relative_to(base).as_posix(), 'bytes': size}
+ result = {'file': destination.relative_to(base).as_posix(), 'bytes': size}
+ if media_kind(name) == 'video':
+ # Whether the clip has a sound track; the Replace person option is greyed out without one.
+ try:
+ from .guide_audio import has_audio
+ result['audio'] = await asyncio.to_thread(has_audio, destination)
+ except Exception:
+ pass
+ return result
def register():
diff --git a/web/freevideo.js b/web/freevideo.js
index a539278..7512ac5 100644
--- a/web/freevideo.js
+++ b/web/freevideo.js
@@ -6,7 +6,7 @@ import { api } from "../../scripts/api.js";
import { openEditorView } from './editor_loader.js';
import { beginWorkspaceRestore, finishWorkspaceRestore, waitForLauncherRestore } from './workspace_restore.js';
import { openStudio, loraPanel, loraWarning, promptGuide } from "./studio.js";
-import { createGenerationProgress, referenceTrimText, thermalText, sharedGpuText, encoderFileText, encoderFilePath } from './generation_progress.js';
+import { createGenerationProgress, referenceTrimText, thermalText, sharedGpuText, keepSoundText, encoderFileText, encoderFilePath } from './generation_progress.js';
import { createProgressConnection } from './progress_connection.js';
import { notifyCompatibility } from './compatibility.js';
import { startUpdateChecks } from './updates.js';
@@ -16,7 +16,7 @@ import { installNavigation, refreshNavigation, preferredView, collapseWorkspaces
import { isLaunchVisit } from './launch_visit.js';
import { openFreeVideoWorkflow } from './launcher.js';
import { agentInterfaceState } from './agent_connect.js';
-import { attachReferencePicker, referenceItems, syncReferencePrompt, referenceInputs, mediaRows } from './prompt_references.js';
+import { attachReferencePicker, referenceItems, syncReferencePrompt, referenceInputs, mediaRows, mediaNodeOf } from './prompt_references.js';
import { expandCast } from './cast_mention.js';
import { outputDownloadURL } from './output_download.js';
import { shareButton } from './share.js';
@@ -29,6 +29,8 @@ import { openImageEditor, icon } from './image_editor.js';
import { imageGenerationSupported } from './image_generation.js';
import { createCastLibrary } from './cast_library.js';
import { uploadMedia } from './media_upload.js';
+import { swapState, requestRows, swapMissing, withPrefix } from './replace_state.js';
+import { swapMissingText } from './replace_person.js';
import { issueButton } from './issue_button.js';
const languageOverride = typeof location !== 'undefined'
@@ -366,6 +368,12 @@ function mediaPanel(node, mount = null) {
let uploading = false;
serialized.serializeValue = () => {
if (node.isUploading) throw new Error(text("Wait for media uploads to finish before running", "请等待素材上传完成后再生成"));
+ // Replace person: the two slots are the media, and both are needed.
+ if (swapState(node)) {
+ const missing = swapMissing(swapState(node));
+ if (missing) throw new Error(swapMissingText(missing, text));
+ return JSON.stringify(requestRows(swapState(node)));
+ }
// The run takes only what it uses (and which character a picture belongs to); the editing data of a picture stays in the workflow.
try { return JSON.stringify(read().map(({file, role, enabled, cast, sound}) => ({file, role, enabled, ...(sound === false && mediaKindOrNull(file) === 'video' ? {sound: false} : {}), ...(typeof cast?.id === 'string' && cast.id ? {cast: {id: cast.id}} : {})}))); } catch { return serialized.value; }
};
@@ -578,6 +586,7 @@ function resultPanel(node) {
if (value.thermal && !value.result_cache_hit) resultNotes.push(el("div", thermalText(value.thermal, text), "fv-note"));
const shared = value.shared_gpu && !value.result_cache_hit ? sharedGpuText(value.shared_gpu, text) : '';
if (shared) resultNotes.push(el("div", shared, "fv-note"));
+ if (value.keep_source_audio_failed) resultNotes.push(el("div", keepSoundText(text), "fv-note"));
if (value.encoder_file) {
const note = el("div", encoderFileText(value.encoder_file, text), "fv-note");
const path = encoderFilePath(value.encoder_file);
@@ -754,7 +763,14 @@ app.registerExtension({
}
// Characters mentioned with @ travel as <Subject N> plus their definitions; the draft keeps the typed names.
const prompt = this.widgets?.find(w => w.name === 'text');
- if (prompt) { const owner = this; prompt.serializeValue = () => expandCast(prompt.value, mediaRows(owner), {continued: Boolean(owner.freevideoContinues?.())}).text; }
+ if (prompt) {
+ 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(prompt.value, mediaRows(owner), {continued: Boolean(owner.freevideoContinues?.())}).text;
+ return swapState(mediaNodeOf(owner)) ? withPrefix(body) : body;
+ };
+ }
const quality = this.widgets?.find(w => w.name === 'two_pass');
if (quality) {
quality.label = text('Two-pass acceleration', '二次采样加速');
diff --git a/web/generation_progress.js b/web/generation_progress.js
index d72fde4..ae7429d 100644
--- a/web/generation_progress.js
+++ b/web/generation_progress.js
@@ -270,6 +270,11 @@ export function sharedGpuText(shared, t) {
`其他程序占用了约 ${percent}% 的显卡。`);
}
+// Replace person: the source video's sound was asked for and could not be put into the video.
+export function keepSoundText(t) {
+ return t('The source video sound could not be kept. The video uses generated sound.', '未能保留源视频声音,成片使用生成的声音。');
+}
+
export function encoderFilePath(file) {
return file?.offline_installation === true && typeof file.path === 'string' ? file.path : '';
}
diff --git a/web/health.js b/web/health.js
index c511e8d..468ad2f 100644
--- a/web/health.js
+++ b/web/health.js
@@ -17,7 +17,7 @@ export const MODULES = ['chat_data.js', 'phone_model.js', 'phone.js', 'lan_acces
'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_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_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', '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_terms.js', 'request_assets.js', 'repair_hint.js', 'report_issue.js', 'issue_button.js', 'studio_recent.js',
- 'result_actions.js', 'sampling_effort.js', 'setup.js', 'share.js', 'share_layout.js', 'studio.js', 'studio_chain.js', 'studio_extend.js', 'studio_length.js', 'first_frame_row.js', 'optional_inputs.js', 'studio_queue.js', 'studio_size.js',
+ 'result_actions.js', 'sampling_effort.js', 'setup.js', 'share.js', 'share_layout.js', 'studio.js', 'studio_chain.js', 'studio_extend.js', 'studio_length.js', 'first_frame_row.js', 'replace_person.js', 'replace_state.js', 'optional_inputs.js', 'studio_queue.js', 'studio_size.js',
'toolbar_position.js', 'updates.js', 'view_navigation.js', 'wordmark.js', 'workspace_restore.js', 'cast_library.js', 'media_upload.js', 'whitebox_encode.js', 'whitebox_mp4.js', 'whitebox_recording.js', 'whitebox_render.js', 'whitebox_scenes.js', 'whitebox_worker.js'];
const sleep = ms => new Promise(resolve => setTimeout(resolve, ms));
let visibleAt = 0;
diff --git a/web/prompt_references.js b/web/prompt_references.js
index 483e381..83919bd 100644
--- a/web/prompt_references.js
+++ b/web/prompt_references.js
@@ -1,6 +1,7 @@
// H3 numbers each reference kind separately, in the order of comfy_media.export.
import {caretRect} from './caret_rect.js';
import {listenDialogKey} from './dialog_keys.js';
+import {effectiveRows} from './replace_state.js';
const titles = {image: 'Picture', video: 'Video', audio: 'Audio'};
const widget = (node, name) => node?.widgets?.find(w => w.name === name);
const linkFor = (node, name) => node?.graph?.links?.[node.inputs?.find(i => i.name === name)?.link];
@@ -14,8 +15,9 @@ export function referenceKind(file) {
}
// The raw media list a generate node reads, [] when there is none or it cannot be read.
+export const mediaNodeOf = node => sourceFor(node, 'media');
export function mediaRows(node) {
- try { const rows = JSON.parse(widget(sourceFor(node, 'media'), 'assets')?.value || '[]'); return Array.isArray(rows) ? rows : []; } catch { return []; }
+ try { const owner = sourceFor(node, 'media'), rows = effectiveRows(owner, widget(owner, 'assets')); return Array.isArray(rows) ? rows : []; } catch { return []; }
}
export function referenceItems(node) {
@@ -31,14 +33,14 @@ export function referenceItems(node) {
if (['first','last','references'].some(name => linkFor(node, name))) throw new Error('invalid_media');
const serialized = widget(media, 'assets');
if (!serialized) throw new Error('unknown_references');
- const rows = JSON.parse(serialized.value || '[]'), counts = new Map();
+ const rows = effectiveRows(media, serialized), counts = new Map();
if (!Array.isArray(rows)) throw new Error('invalid_media');
for (const row of rows) {
const occurrence = counts.get(row.file) || 0; counts.set(row.file, occurrence + 1);
if (row.enabled === false) continue;
const kind = referenceKind(row.file);
if (!kind) throw new Error('invalid_media');
- const item = {key: `file:${media.id}:${row.file}:${occurrence}`, kind, file: row.file,
+ const item = {key: row.slot ? `swap:${media.id}:${row.slot}` : `file:${media.id}:${row.file}:${occurrence}`, kind, file: row.file,
name: row.cast?.name || row.file.split('/').pop(), assetIndex: rows.indexOf(row),
...(row.sound === false && kind === 'video' ? {sound: false} : {})};
if (row.role === 'reference') refs.push(item);
diff --git a/web/replace_person.js b/web/replace_person.js
new file mode 100644
index 0000000..a627b77
--- /dev/null
+++ b/web/replace_person.js
@@ -0,0 +1,128 @@
+// Replace person: a source video and a person image in the Media section.
+// The state lives in the Media node's properties, so the ordinary media list is never touched
+// and comes back unchanged when the option is turned off.
+import { referenceKind } from './prompt_references.js';
+import { uploadMedia } from './media_upload.js';
+import { firstFrameRow } from './first_frame_row.js';
+import { swapState, swapRows, effectiveRows, keepsSound, withPrefix, swapMissing, SWAP_LORA, SWAP_PREFIX, MIN_SOURCE_SECONDS, SWAP_KEY } from './replace_state.js';
+
+export {swapState, swapRows, effectiveRows, keepsSound, withPrefix, swapMissing, SWAP_LORA, SWAP_PREFIX, MIN_SOURCE_SECONDS};
+const KEY = SWAP_KEY;
+
+// A first or last frame, in the media list or on a connected input, rules the option out.
+export function framesPresent(media) {
+ try {
+ const rows = JSON.parse(media?.widgets?.find(w => w.name === 'assets')?.value || '[]');
+ if (rows.some(row => row.enabled !== false && (row.role === 'first' || row.role === 'last'))) return true;
+ } catch {}
+ return Boolean(media?.inputs?.some(input => (input.name === 'first' || input.name === 'last') && input.link != null));
+}
+
+// What is still missing, in one line (t picks the language).
+export const swapMissingText = (missing, t) => missing === 'source' ? t('Add a source video first.', '请先添加源视频。')
+ : missing === 'person' ? t('Add a person image first.', '请先添加人物图。') : t('Add a source video and a person image first.', '请先添加源视频和人物图。');
+
+const el = (tag, cls, text) => { const e = document.createElement(tag); if (cls) e.className = cls; if (text != null) e.textContent = text; return e; };
+
+function videoSeconds(file) {
+ return new Promise(resolve => {
+ const url = URL.createObjectURL(file), probe = document.createElement('video');
+ const done = value => { clearTimeout(timer); probe.removeAttribute('src'); probe.load(); URL.revokeObjectURL(url); resolve(value); };
+ const timer = setTimeout(() => done(null), 5000);
+ probe.preload = 'metadata'; probe.muted = true;
+ probe.onloadedmetadata = () => done(Number.isFinite(probe.duration) ? probe.duration : null);
+ probe.onerror = () => done(null);
+ probe.src = url;
+ });
+}
+
+// mount: the Media section body. onChange runs after any change to the state.
+export function createReplacePerson({t, api, media, mount, view, onChange = () => {}}) {
+ const stored = () => media.properties?.[KEY];
+ const state = () => { media.properties ??= {}; return media.properties[KEY] ??= {on: false, source: null, person: null, keepSound: false}; };
+ const save = info => { media.graph?.change?.(); onChange(info); paint(); };
+ const toggle = firstFrameRow(t, 'fv-first-frame fv-replace-person');
+ toggle.row.firstChild.textContent = t('Replace person', '替换人物');
+ toggle.input.setAttribute('aria-label', t('Replace person', '替换人物'));
+ toggle.row.title = '';
+ const slots = el('div', 'fv-swap-slots'), note = el('div', 'fv-note fv-swap-note'); note.setAttribute('role', 'status');
+ const blockedTitle = t('Not available with first and last frames', '首尾帧不能和替换人物同时使用');
+ function slot(kind) {
+ const box = el('div', 'fv-swap-slot'), title = el('div', 'fv-swap-title', kind === 'video' ? t('Source video', '源视频') : t('Person image', '人物图'));
+ const body = el('button', 'fv-swap-drop'); body.type = 'button';
+ const input = el('input'); input.type = 'file'; input.hidden = true;
+ input.accept = kind === 'video' ? 'video/*,.mp4,.mov,.webm,.mkv,.m4v' : 'image/*,.png,.jpg,.jpeg,.webp,.bmp,.tif,.tiff';
+ body.onclick = () => input.click();
+ input.onchange = () => { const [file] = input.files; input.value = ''; if (file) choose(kind, file); };
+ for (const name of ['dragover', 'dragenter']) box.addEventListener(name, event => { event.preventDefault(); event.stopPropagation(); });
+ box.addEventListener('drop', event => {
+ event.preventDefault(); event.stopPropagation();
+ const file = Array.from(event.dataTransfer?.files || []).find(f => referenceKind(f.name) === (kind === 'video' ? 'video' : 'image'));
+ if (file) choose(kind, file);
+ });
+ box.append(title, body, input);
+ return {box, body, kind};
+ }
+ const source = slot('video'), person = slot('image');
+ const sound = el('label', 'fv-swap-sound', t('Keep source video sound', '保留源视频声音'));
+ const soundInput = el('input'); soundInput.type = 'checkbox'; sound.prepend(soundInput);
+ soundInput.onchange = () => { state().keepSound = soundInput.checked; save(); };
+ source.box.classList.add('fv-swap-source'); person.box.classList.add('fv-swap-person');
+ slots.append(source.box, person.box, sound);
+ mount.prepend(toggle.row, slots, note);
+ let busy = false;
+ async function choose(kind, file) {
+ if (busy || media.isUploading) return;
+ note.textContent = '';
+ if (referenceKind(file.name) !== (kind === 'video' ? 'video' : 'image')) {
+ note.textContent = kind === 'video' ? t('Choose a video file.', '请选择视频文件。') : t('Choose an image file.', '请选择图片文件。');
+ paint(); return;
+ }
+ if (kind === 'video') {
+ const seconds = await videoSeconds(file);
+ if (seconds !== null && seconds < MIN_SOURCE_SECONDS) { note.textContent = t('The source video must be at least 1 second long.', '源视频至少需要 1 秒。'); return; }
+ }
+ busy = true; media.isUploading = true; paint();
+ try {
+ const result = await uploadMedia(api, file);
+ const next = state();
+ if (kind === 'video') { next.source = {file: result.file, audio: result.audio === true}; if (!next.source.audio) next.keepSound = false; }
+ else next.person = {file: result.file};
+ save();
+ } catch (error) { note.textContent = error.message; }
+ finally { busy = false; media.isUploading = false; paint(); }
+ }
+ function fill(part, entry, empty) {
+ part.body.replaceChildren();
+ part.body.classList.toggle('fv-swap-filled', Boolean(entry));
+ if (!entry) { part.body.append(el('span', 'fv-swap-plus', '+'), el('span', 'fv-swap-sub', empty)); part.body.title = empty; return; }
+ const thumb = part.kind === 'video' ? el('video', 'fv-swap-thumb') : el('img', 'fv-swap-thumb');
+ if (part.kind === 'video') { thumb.muted = true; thumb.preload = 'metadata'; thumb.src = view(entry.file) + '#t=0.1'; }
+ else { thumb.alt = ''; thumb.src = view(entry.file); }
+ part.body.append(thumb, el('span', 'fv-swap-name', entry.file.split('/').pop()));
+ part.body.title = entry.file.split('/').pop();
+ }
+ function paint() {
+ const current = stored(), on = current?.on === true, blocked = framesPresent(media);
+ toggle.input.checked = on;
+ toggle.setDisabled(Boolean(busy) || (blocked && !on));
+ toggle.input.title = blocked && !on ? blockedTitle : '';
+ toggle.row.classList.toggle('fv-swap-blocked', blocked && !on);
+ slots.hidden = !on; note.hidden = !on || !note.textContent;
+ mount.classList.toggle('fv-swap-on', on);
+ fill(source, current?.source, t('Add video', '添加视频'));
+ fill(person, current?.person, t('Add image', '添加图片'));
+ const audio = current?.source?.audio === true;
+ sound.hidden = !on; soundInput.disabled = busy || !audio; soundInput.checked = audio && current?.keepSound === true;
+ }
+ toggle.input.onchange = () => {
+ if (toggle.input.checked && framesPresent(media)) { toggle.input.checked = false; return; }
+ state().on = toggle.input.checked; note.textContent = '';
+ save({toggled: true});
+ };
+ paint();
+ const changed = event => { if (String(event.detail) === String(media.id)) paint(); };
+ window.addEventListener('freevideo-media', changed);
+ return {paint, notify(message) { note.textContent = message || ''; paint(); }, get on() { return swapState(media) !== null; }, element: toggle.row,
+ dispose() { window.removeEventListener('freevideo-media', changed); }};
+}
diff --git a/web/replace_state.js b/web/replace_state.js
new file mode 100644
index 0000000..e9b8db8
--- /dev/null
+++ b/web/replace_state.js
@@ -0,0 +1,85 @@
+// Replace person: the saved state and the rules built on it. No imports, so any module (the media list, the prompt
+// numbering, the request) can read it without a cycle; the panel itself is in replace_person.js.
+export const SWAP_LORA = 'alissonerdx-v1.1.safetensors';
+export const SWAP_PREFIX = 'body_swap:';
+export const MIN_SOURCE_SECONDS = 22 / 24; // the engine needs 22 frames
+export const SWAP_KEY = 'freevideo_replace_person';
+
+export const swapState = media => {
+ const state = media?.properties?.[SWAP_KEY];
+ return state && typeof state === 'object' && state.on === true ? state : null;
+};
+export const keepsSound = state => Boolean(state?.keepSound && state.source?.audio === true);
+
+// Person image first (it is Picture 1), then the source video as a guide clip. `slot` keeps the number of each when the
+// file in it is replaced.
+export function swapRows(state) {
+ const rows = [];
+ if (state?.person?.file) rows.push({file: state.person.file, role: 'reference', enabled: true, slot: 'person'});
+ if (state?.source?.file) rows.push({file: state.source.file, role: 'reference', enabled: true, guide: true, slot: 'source',
+ ...(keepsSound(state) ? {keep_source_audio: true} : {})});
+ return rows;
+}
+
+// What the request carries: the rows without the editor-only slot marker.
+export const requestRows = state => swapRows(state).map(({slot, ...row}) => row);
+
+// 'both', 'source', 'person' for what is still missing, null when the two slots are filled.
+export function swapMissing(state) {
+ const source = Boolean(state?.source?.file), person = Boolean(state?.person?.file);
+ return source && person ? null : !source && !person ? 'both' : source ? 'person' : 'source';
+}
+
+// The media list a request reads: the two slots while Replace person is on, else the ordinary list.
+export function effectiveRows(media, serialized) {
+ const state = swapState(media);
+ return state ? swapRows(state) : JSON.parse(serialized?.value || '[]');
+}
+
+export const withPrefix = text => {
+ const body = String(text ?? '').trim();
+ return body ? `${SWAP_PREFIX} ${body}` : SWAP_PREFIX;
+};
+
+// The replace-person adapter as ComfyUI registers it: the same file may sit in a subfolder of models/loras.
+const baseName = name => String(name).split(/[\\/]/).pop().toLowerCase();
+export const swapLoraNames = names => (Array.isArray(names) ? names : []).filter(name => typeof name === 'string' && baseName(name) === SWAP_LORA);
+const active = row => row.enabled !== false && Number(row.strength) > 0;
+
+// Makes the adapters list carry one working replace-person row. Returns {ok, adapters, record}; record says how to undo
+// what was done (a row added, or a row of the user's switched on) and stays as it was when the row is already working.
+// ok is false with reason 'missing' (not installed), 'ambiguous' (several installed, none chosen) or 'unreadable'.
+export function prepareSwapLora(adapters, names, previous = null) {
+ let rows; try { rows = JSON.parse(adapters || '[]'); } catch { return {ok: false, reason: 'unreadable'}; }
+ if (!Array.isArray(rows)) return {ok: false, reason: 'unreadable'};
+ const found = swapLoraNames(names);
+ if (!found.length) return {ok: false, reason: 'missing'};
+ let name = found.length === 1 ? found[0] : null;
+ if (!name) {
+ const used = [...new Set(rows.filter(row => found.includes(row.name) && active(row)).map(row => row.name))];
+ const listed = [...new Set(rows.filter(row => found.includes(row.name)).map(row => row.name))];
+ const pick = used.length ? used : listed;
+ if (pick.length !== 1) return {ok: false, reason: 'ambiguous'};
+ name = pick[0];
+ }
+ const index = rows.findIndex(row => row.name === name), keep = previous?.name === name ? previous : null;
+ if (index < 0) return {ok: true, adapters: JSON.stringify([...rows, {name, strength: 1, enabled: true}]), record: keep || {name, added: true}};
+ const row = rows[index];
+ if (active(row)) return {ok: true, adapters: JSON.stringify(rows), record: keep};
+ const record = keep || {name, restore: {...('enabled' in row ? {enabled: row.enabled} : {}), ...('strength' in row ? {strength: row.strength} : {})}};
+ rows[index] = {...row, enabled: true, strength: Number(row.strength) > 0 ? row.strength : 1};
+ return {ok: true, adapters: JSON.stringify(rows), record};
+}
+
+// Undoes prepareSwapLora: a row it added goes, a row it switched on goes back to how the user had it.
+export function releaseSwapLora(adapters, record) {
+ let rows; try { rows = JSON.parse(adapters || '[]'); } catch { return adapters; }
+ if (!Array.isArray(rows) || !record?.name) return adapters;
+ if (record.added) rows = rows.filter(row => row.name !== record.name);
+ else if (record.restore) rows = rows.map(row => {
+ if (row.name !== record.name) return row;
+ const {enabled, strength, ...rest} = row;
+ return {...rest, ...record.restore};
+ });
+ return JSON.stringify(rows);
+}
diff --git a/web/studio.css b/web/studio.css
index 993a7ce..91a98ee 100644
--- a/web/studio.css
+++ b/web/studio.css
@@ -240,3 +240,20 @@
/* The queued count follows the part number; when the line is too narrow it wraps out of sight. */
.fv-studio .fv-chain-position:has(.fv-chain-queued){display:flex;flex-wrap:wrap;column-gap:0;line-height:1.4;max-height:1.4em;overflow:hidden}
.fv-studio .fv-chain-position .fv-chain-queued{white-space:pre}
+.fv-studio .fv-replace-person{margin-top:0;margin-bottom:12px}
+.fv-studio .fv-replace-person.fv-swap-blocked{cursor:not-allowed}
+.fv-studio .fv-swap-on>.fv-panel{display:none}
+.fv-studio .fv-swap-slots{display:grid;grid-template-columns:1fr 1fr;gap:12px}
+.fv-studio .fv-swap-slots[hidden],.fv-studio .fv-swap-note[hidden],.fv-studio .fv-swap-sound[hidden]{display:none}
+.fv-studio .fv-swap-slot{min-width:0}
+.fv-studio .fv-swap-title{font-size:var(--fv-micro);color:var(--fv-muted);margin:0 0 7px}
+.fv-studio .fv-swap-drop{box-sizing:border-box;width:100%;height:112px;flex-direction:column;gap:2px;padding:6px;border:1px dashed var(--fv-border);background:var(--fv-card);color:var(--fv-muted);border-radius:var(--fv-r-sm);overflow:hidden}
+.fv-studio .fv-swap-drop.fv-swap-filled{border-style:solid;gap:4px}
+.fv-studio .fv-swap-plus{font-size:20px;line-height:1;color:var(--fv-ink)}
+.fv-studio .fv-swap-sub{font-size:var(--fv-micro)}
+.fv-studio .fv-swap-thumb{width:100%;height:68px;min-height:0;object-fit:cover;border-radius:4px;background:#0003}
+.fv-studio .fv-swap-name{max-width:100%;line-height:1.3;flex:none;font-size:var(--fv-micro);overflow:hidden;text-overflow:ellipsis;white-space:nowrap}
+.fv-studio .fv-swap-sound{display:flex;align-items:center;gap:8px;grid-column:1/-1;white-space:nowrap;font-size:var(--fv-small,13px)}
+.fv-studio .fv-swap-sound:has(input:disabled){opacity:.4}
+.fv-studio .fv-swap-note{margin-top:8px}
+@media (max-width:480px){.fv-studio .fv-swap-slots{grid-template-columns:1fr}.fv-studio .fv-swap-source{order:1}.fv-studio .fv-swap-sound{order:2}.fv-studio .fv-swap-person{order:3}}
diff --git a/web/studio.js b/web/studio.js
index 7225363..f24686d 100644
--- a/web/studio.js
+++ b/web/studio.js
@@ -7,7 +7,7 @@ import { api } from '../../scripts/api.js';
import { openSetup } from './setup.js';
import { feedbackButton, feedbackIssueURL } from './feedback.js';
import { wordmark } from './wordmark.js';
-import { createGenerationProgress, referenceTrimText, thermalText, sharedGpuText, encoderFileText, encoderFilePath } from './generation_progress.js';
+import { createGenerationProgress, referenceTrimText, thermalText, sharedGpuText, keepSoundText, encoderFileText, encoderFilePath } from './generation_progress.js';
import { viewSwitch, viewChanged, agentTabReady, openAutopilot } from './view_navigation.js';
import { agentInterfaceState } from './agent_connect.js';
import { createUpdateNotice, createVersionInfo, productVersion } from './updates.js';
@@ -42,6 +42,8 @@ import { createFirstRunGuide } from './first_run_guide.js';
import { SHOWCASE_SCENE } from './entry_showcase.js';
import { createStudioLength, savedSeconds } from './studio_length.js?v=20261011-length';
import { firstFrameRow } from './first_frame_row.js';
+import { createReplacePerson, swapMissingText } from './replace_person.js';
+import { swapState, swapMissing, effectiveRows, prepareSwapLora, releaseSwapLora, SWAP_LORA } from './replace_state.js';
import { createStudioChain, chainPosition, chainParts, chainSplit, composePartText, readChainResult, sumPartEstimates, singleRunSnapshot } from './studio_chain.js?v=20261019-words';
import { waitingText } from './chain_support.js';
import { createExtendState, extendText, extendSourceProblem, extendSourceState, readExtendRecord, extendSnapshot, mountExtendThumbnail, videoUnavailableText } from './studio_extend.js';
@@ -909,7 +911,7 @@ export function openStudio(node, {extendFrom = null} = {}) {
canvas.append(samplingSettings); cleanup.push(() => effort.dispose());
cleanup.push(() => { clearTimeout(effortEstimateTimer); effortEstimateRequest?.abort(); });
const mediaNode = upstream(node, 'media');
- const mediaFilled = () => JSON.parse(value(mediaNode, 'assets') || '[]').some(r => r.enabled !== false)
+ const mediaFilled = () => swapState(mediaNode) ? Boolean(swapState(mediaNode).source || swapState(mediaNode).person) : JSON.parse(value(mediaNode, 'assets') || '[]').some(r => r.enabled !== false)
|| Boolean(mediaNode.inputs?.some(input => ['first', 'last', ...referenceInputs, 'reference_audio'].includes(input.name) && input.link != null));
// The line beside the closed title says what the section is for, until something is added.
// The guide opens the section it points at; the ring stays on the title row.
@@ -932,6 +934,49 @@ export function openStudio(node, {extendFrom = null} = {}) {
controls.addEventListener('change', paintMediaHint, true); controls.addEventListener('input', paintMediaHint, true);
const connectedLora = upstream(node, 'loras');
const loraNode = connectedLora?.properties?.[CREATED_BY_PANEL] ? pendingLoras(node, connectedLora) : connectedLora || pendingLoras(node);
+ // Replace person: its LoRA row is found among the registered names (it may sit in a subfolder), a row the user had
+ // switched off is switched on for the run, and everything done is undone when the option goes off.
+ // Returns '' when all is well, else the line to show; runs one at a time.
+ let swapLoraBusy = Promise.resolve('');
+ const swapLoraText = reason => reason === 'missing'
+ ? t(`Replace person needs the ${SWAP_LORA} LoRA in the models/loras folder.`, `替换人物需要把 ${SWAP_LORA} 放进 models/loras 文件夹。`)
+ : reason === 'ambiguous' ? t(`More than one ${SWAP_LORA} was found in models/loras. Add the one to use in LoRA.`, `models/loras 中有多个 ${SWAP_LORA},请在 LoRA 中添加要使用的那个。`)
+ : t('Could not read the LoRA list. Try again.', '没能读取 LoRA 列表,请重试。');
+ async function applySwapLora() {
+ const state = mediaNode?.properties?.freevideo_replace_person;
+ if (!state || !loraNode || !widget(loraNode, 'adapters')) return '';
+ const current = value(loraNode, 'adapters') || '[]';
+ const record = state.lora && typeof state.lora === 'object' ? state.lora : null;
+ if (!state.on) {
+ state.lora = null;
+ if (record) { set(loraNode, 'adapters', releaseSwapLora(current, record)); window.dispatchEvent(new CustomEvent('freevideo-loras', {detail: loraNode.id})); }
+ return '';
+ }
+ let names;
+ try { const response = await api.fetchApi('/models/loras', {cache: 'no-store'}); if (!response.ok) throw new Error(response.statusText); names = await response.json(); }
+ catch { return swapLoraText('unreadable'); }
+ if (!state.on) return '';
+ const now = value(loraNode, 'adapters') || '[]';
+ const result = prepareSwapLora(now, names, record);
+ if (!result.ok) return swapLoraText(result.reason);
+ state.lora = result.record;
+ if (result.adapters !== now) { set(loraNode, 'adapters', result.adapters); window.dispatchEvent(new CustomEvent('freevideo-loras', {detail: loraNode.id})); }
+ return '';
+ }
+ const ensureSwapLora = () => (swapLoraBusy = swapLoraBusy.then(applySwapLora, applySwapLora));
+ let swapPanel = null;
+ function swapChanged(info) {
+ mediaHint.textContent = swapState(mediaNode) ? t('Source video, person image', '源视频、人物图') : t('Reference images, first and last frames', '参考图、首帧、尾帧');
+ // Switching the option only changes which media the prompt reads: its pictures are re-bound, never renumbered.
+ syncReferencePrompt(node, t, info?.toggled === true); paintMediaHint();
+ ensureSwapLora().then(problem => { if (problem) swapPanel?.notify(problem); });
+ window.dispatchEvent(new CustomEvent('freevideo-media', {detail: mediaNode.id}));
+ }
+ if (mediaNode?.freevideoCreateMediaEditor) {
+ const swap = swapPanel = createReplacePerson({t, api, media: mediaNode, mount: mediaMount, view, onChange: swapChanged});
+ cleanup.push(() => swap.dispose());
+ if (swapState(mediaNode)) { mediaHint.textContent = t('Source video, person image', '源视频、人物图'); mediaDetails.open = true; }
+ }
const [loraDetails, loraMount] = expand(t('LoRA', 'LoRA'));
if (loraNode && widget(loraNode, 'adapters')) {
const stop = loraPanel(loraNode, loraMount, {promptNode: node}); cleanup.push(stop);
@@ -1314,7 +1359,8 @@ export function openStudio(node, {extendFrom = null} = {}) {
const thermalNote = el('div', '', 'fv-note'); thermalNote.hidden = true;
const sharedGpuNote = el('div', '', 'fv-note'); sharedGpuNote.hidden = true;
const encoderNote = el('div', '', 'fv-note'); encoderNote.hidden = true;
- output.append(status, reuseRow, trimNote, memoryNote, thermalNote, sharedGpuNote, encoderNote, links, stats, budget, progress.stall, progress.report, prewarm);
+ const keepSoundNote = el('div', keepSoundText(t), 'fv-note'); keepSoundNote.hidden = true;
+ output.append(status, reuseRow, trimNote, memoryNote, thermalNote, sharedGpuNote, keepSoundNote, encoderNote, links, stats, budget, progress.stall, progress.report, prewarm);
const failure = createErrorPanel(t, reportRoute); output.append(failure.element);
// With the picture, the result's actions and numbers form one block, centred below the header.
output.append(el('div', null, 'fv-preview-end'));
@@ -1360,6 +1406,7 @@ export function openStudio(node, {extendFrom = null} = {}) {
memoryNote.hidden = !r.low_memory || !!r.result_cache_hit;
thermalNote.textContent = r.thermal ? thermalText(r.thermal, t) : ''; thermalNote.hidden = !r.thermal || !!r.result_cache_hit;
sharedGpuNote.textContent = r.shared_gpu ? sharedGpuText(r.shared_gpu, t) : ''; sharedGpuNote.hidden = !sharedGpuNote.textContent || !!r.result_cache_hit;
+ keepSoundNote.hidden = !r.keep_source_audio_failed;
encoderNote.textContent = r.encoder_file ? encoderFileText(r.encoder_file, t) : ''; encoderNote.hidden = !r.encoder_file;
const encoderPath = encoderFilePath(r.encoder_file);
if (encoderPath) encoderNote.append(el('pre', encoderPath, 'fv-encoder-path'));
@@ -1724,7 +1771,11 @@ export function openStudio(node, {extendFrom = null} = {}) {
}
invalid.focus(); invalid.reportValidity(); return;
}
- if (!extension.source && !prompt.disabled && !prompt.value.trim() && !untouched()) { prompt.focus(); status.textContent = t('Describe your scene first.', '请先描述画面。'); return; }
+ if (!extension.source && !prompt.disabled && !prompt.value.trim() && !untouched() && !swapState(mediaNode)) { prompt.focus(); status.textContent = t('Describe your scene first.', '请先描述画面。'); return; }
+ if (swapState(mediaNode)) {
+ const missing = swapMissing(swapState(mediaNode));
+ if (missing) { status.dataset.error = 'true'; status.textContent = swapMissingText(missing, t); 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.
@@ -1735,7 +1786,7 @@ export function openStudio(node, {extendFrom = null} = {}) {
stopNote = ''; lastQueueError = null; failure.clear(); node.freevideoFailure = ''; node.freevideoFailureReport = null;
capturing = true; updateRunButton(); status.dataset.error = 'false'; runOptions.open = false;
lengthControl.freeze();
- if ((!extension.source || prompt.value.trim()) && await enhancer.beforeGenerate() === false) return;
+ if ((!extension.source || prompt.value.trim()) && !swapState(mediaNode) && await enhancer.beforeGenerate() === false) return;
if (disposed) return;
if (selected === 'input' && !dimensionsLinked) await inputRatio(true);
const lengthPlan = await lengthControl.ready();
@@ -1747,6 +1798,8 @@ export function openStudio(node, {extendFrom = null} = {}) {
const sourceState = source ? await extendSourceState(api, source) : 'ok';
if (sourceState !== 'ok') throw new Error(extendSourceProblem(t, sourceState));
if (source && lengthPlan?.count > 1) lengthOptions.after = {work: source.video};
+ const swapProblem = await ensureSwapLora();
+ if (swapProblem) { status.dataset.error = 'true'; status.textContent = swapProblem; return; }
// Only serialization briefly locks the editor. Network submission
// and all GPU execution leave the next draft fully editable.
for (const section of controls.querySelectorAll('.fv-section')) section.inert = true;
@@ -1824,7 +1877,7 @@ export function openStudio(node, {extendFrom = null} = {}) {
set(node, 'width', w); set(node, 'height', h); node.properties.freevideo_aspect = selected; node.properties.freevideo_pixels = pixels; syncCanvasSize();
}
async function inputRatio(required = false) {
- const rows = mediaNode ? JSON.parse(value(mediaNode, 'assets') || '[]') : [];
+ const rows = mediaNode ? effectiveRows(mediaNode, widget(mediaNode, 'assets')) : [];
const active = rows.filter(r => r.enabled !== false);
const source = active.find(r => r.role === 'first') || active.find(r => r.role === 'last') || active.find(r => /\.(png|jpe?g|webp|bmp|tiff?)$/i.test(r.file));
if (!source) { if (required) throw new Error(t('Add an image in Media to follow its aspect ratio.', '请先在素材中添加图片,再跟随输入比例。')); return; }