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.
Cast generate: create a character's pictures with the AI tab of the character dialog
Bowen Xue8562713a87e5
diff --git a/freevideo_engine/image_gen/cast_views.py b/freevideo_engine/image_gen/cast_views.pyindex 9c985ad..a316d03 100644--- a/freevideo_engine/image_gen/cast_views.py+++ b/freevideo_engine/image_gen/cast_views.py@@ -96,3 +96,15 @@ def photo_prompt():'feet. Turn the head and body to face us. Neutral pose with the arms relaxed, %s. Keep exactly ''the same person, face, hair and clothes as in image 1. Preserve all existing accessories; ''add no new accessories.' % BACKDROP)+++def page_views(description):+ """What the page needs to make the pictures of a new character itself: each view's prompt and size.++ The page runs the pictures one by one so each shows when it is done; the prompts stay here, so a+ card made from a description and these pictures are made from the same words."""+ if not isinstance(description, str) or not description.strip() or len(description) > 1000:+ raise ValueError('invalid_prompt')+ card = dict(name=description.strip()[:120], description=description.strip(), kind='character')+ return dict(views=[dict(view=view, prompt=view_prompt(card, view), width=SIZES[view][0],+ height=SIZES[view][1], from_front=uses_front(view)) for view in VIEWS])diff --git a/freevideo_engine/image_gen/service.py b/freevideo_engine/image_gen/service.pyindex 7b36a81..db3d62c 100644--- a/freevideo_engine/image_gen/service.py+++ b/freevideo_engine/image_gen/service.py@@ -730,7 +730,10 @@ def register():if not isinstance(value, dict):raise ValueError('invalid_request')name = request.match_info['action']- if name == 'status':+ if name == 'cast-views':+ from .cast_views import page_views+ result = page_views(value.get('description'))+ elif name == 'status':result = service.status(value.get('job'))elif name == 'cancel':result = service.cancel(value.get('job'))diff --git a/web/cast_generate.css b/web/cast_generate.cssnew file mode 100644index 0000000..bfd453b--- /dev/null+++ b/web/cast_generate.css@@ -0,0 +1,39 @@+.fv-cg{container-type:inline-size;color:var(--fv-ink,#e8ecf3);font-size:13px}+.fv-cg-body{display:grid;grid-template-columns:minmax(0,2fr) minmax(0,3fr);gap:24px;align-items:start}+.fv-cg [hidden]{display:none!important}+.fv-cg-side{display:flex;flex-direction:column;gap:12px;min-width:0;align-self:stretch}+.fv-cg-foot{display:grid;grid-template-columns:auto minmax(0,1fr) auto;align-items:center;gap:8px}+.fv-cg-text{flex:1;box-sizing:border-box;width:100%;min-height:160px;resize:none;padding:12px;border:1px solid var(--fv-border,#ffffff15);border-radius:8px;background:var(--fv-card,#202a38);color:inherit;font:inherit;line-height:1.6;outline:none;transition:border-color .2s}+.fv-cg-text:focus{border-color:color-mix(in srgb,var(--fv-accent,#6db8fa) 60%,transparent)}+.fv-cg-text:read-only{opacity:.7}+.fv-cg-text::placeholder{color:var(--fv-muted,#7d8794)}+.fv-cg-note{grid-column:1/-1;font-size:12px;line-height:1.6;color:var(--fv-muted,#aaaeb9)}+/* A failure is the reason on one line, then the report button left and the retry right on the next. */+.fv-cg-note[data-failed=true],.fv-cg-note[data-failed=true] .fv-result-links,.fv-cg-note[data-failed=true] .fv-actions{display:contents}+.fv-cg-note .fv-image-failure-reason{grid-column:1/-1}+.fv-cg-note .fv-report-tip{grid-column:1/-1}+.fv-cg .fv-actions .fv-action-report{grid-column:1;justify-self:start;height:36px;min-height:36px;padding:0 16px;border-radius:8px;border:1px solid var(--fv-border,#ffffff1f);background:transparent;color:var(--fv-ink,#e8ecf3);font:inherit;font-weight:400}+.fv-cg .fv-actions .fv-action-report:hover{background:#ffffff0d}+.fv-cg-note[data-failed=true]{color:var(--fv-danger,#ff8a80)}+.fv-cg-note .fv-image-failure-reason{color:var(--fv-danger,#ff8a80)}+.fv-cg-action{grid-column:3;justify-self:end;min-height:36px;padding:6px 16px;border:1px solid var(--fv-border,#ffffff1f);border-radius:8px;background:transparent;color:inherit;font:inherit;cursor:pointer;transition:background .18s,border-color .18s}+.fv-cg-action:hover{background:#ffffff0d}+.fv-cg-action[data-primary=true]{border-color:transparent;background:var(--fv-accent,#6db8fa);color:var(--fv-bg,#111720)}+.fv-cg-action[data-primary=true]:hover{background:var(--fv-accent-hover,#91cbff)}+.fv-cg-action:focus-visible,.fv-cg-text:focus-visible{outline:2px solid var(--fv-accent,#6db8fa);outline-offset:2px}+.fv-cg-views{display:grid;grid-template-columns:repeat(3,minmax(0,1fr));gap:8px;min-width:0}+.fv-cg-view{position:relative;aspect-ratio:3/4;box-sizing:border-box;border:1px dashed var(--fv-sheen,#ffffff1f);border-radius:6px;background:var(--fv-raised,#202a38);overflow:hidden;display:flex;flex-direction:column;align-items:center;justify-content:center;gap:6px}+.fv-cg-view img{position:absolute;inset:0;width:100%;height:100%;object-fit:contain;background:#ffffff08}+.fv-cg-view[data-state=done]{border-style:solid}+.fv-cg-view:not([data-state=done]) img{display:none}+.fv-cg-percent{position:relative;font-size:12px;color:var(--fv-muted,#aaaeb9);font-variant-numeric:tabular-nums}+.fv-cg-meter{position:relative;width:64px;height:2px;border-radius:1px;background:#ffffff14;overflow:hidden}+.fv-cg-meter b{position:absolute;inset:0 auto 0 0;width:0;background:var(--fv-accent,#6db8fa);transition:width .4s ease-out}+.fv-cg-view:not([data-state=running]) .fv-cg-meter{display:none}+@container (max-width:520px){+ .fv-cg-body{grid-template-columns:minmax(0,1fr);gap:12px}+ .fv-cg-text{height:108px;min-height:108px;flex:none}+ .fv-cg-views{display:flex;overflow-x:auto;padding-bottom:4px;scrollbar-width:thin}+ .fv-cg-view{flex:none;width:72px}+}+@media(prefers-reduced-motion:reduce){.fv-cg *{transition:none}}diff --git a/web/cast_generate.js b/web/cast_generate.jsnew file mode 100644index 0000000..4eae26f--- /dev/null+++ b/web/cast_generate.js@@ -0,0 +1,234 @@+// "Generate with AI" page of the new-character dialog: one description becomes five pictures of the+// same person (front, three-quarter, side, back, face). Each picture shows as it is finished; the+// dialog's Save waits for all five. Pictures are made one by one through the page's image client+// and stay in the input folder; the dialog puts them on the card.+import {createImageGenClient, imageGenProgress, imagePackUnavailableMessage, renderImageFailure,+ IMAGE_GEN_POLL_MS, IMAGE_GEN_INFO_POLL_MS} from './image_generation.js';++export {imageGenerationSupported as castGenerateSupported} from './image_generation.js';++export const CAST_VIEWS = Object.freeze(['front', 'three_quarter', 'side', 'back', 'face']);+const VIEW_TITLES = Object.freeze({+ front: ['Front', '正面'], three_quarter: ['Three-quarter', '四分之三'], side: ['Side', '侧面'],+ back: ['Back', '背面'], face: ['Face', '脸部'],+});++function el(tag, cls, text) { const e = document.createElement(tag); if (cls) e.className = cls; if (text != null) e.textContent = text; return e; }+const failureOf = error => ({error: error?.code || 'generation_failed', report_id: error?.report_id || null});+const randomSeed = () => crypto.getRandomValues(new Uint32Array(1))[0] >>> 1;++// The five pictures of one description. No DOM: the page below draws its state.+export function createCastGenerator({client, onChange = () => {}, schedule = setTimeout, unschedule = clearTimeout}) {+ const fresh = () => CAST_VIEWS.map(view => ({view, file: '', fraction: 0}));+ let state = {pictures: fresh(), running: false, current: -1, error: '', report_id: null, waiting: '', description: ''};+ let epoch = 0, timer = null, job = null, plan = null, seed = 0, disposed = false;+ const emit = patch => { state = {...state, ...patch}; if (!disposed) onChange(state); };+ const setPicture = (index, patch) => emit({pictures: state.pictures.map((row, i) => i === index ? {...row, ...patch} : row)});+ const cancelJob = id => Promise.resolve().then(() => client.cancel(id)).catch(() => {});+ const done = () => state.pictures.every(row => row.file);++ async function runOne(index, alive) {+ const view = plan[index], front = state.pictures[0].file;+ const row = await client.generate({prompt: view.prompt, width: view.width, height: view.height, seed,+ images: view.from_front ? [front] : []});+ if (!row.job) throw Object.assign(new Error(row.error || 'generation_failed'), {code: row.error, report_id: row.report_id});+ if (!alive()) { await cancelJob(row.job); return null; }+ job = row.job;+ for (;;) {+ await new Promise(resolve => { timer = schedule(() => { timer = null; resolve(); }, IMAGE_GEN_POLL_MS); });+ if (!alive()) return null;+ const status = await client.status(job);+ if (!alive()) return null;+ if (status.state === 'error') {+ throw Object.assign(new Error(status.error), {code: status.error, report_id: status.report_id});+ }+ if (status.state === 'done') {+ if (!status.file) throw new Error('generation_failed');+ return status.file;+ }+ setPicture(index, {fraction: Math.max(state.pictures[index].fraction,+ imageGenProgress(status.stage, status.fraction, view.from_front)), stage: status.stage || ''});+ emit({waiting: status.waiting || ''});+ }+ }++ async function start(description) {+ description = String(description || '').trim();+ if (state.running || disposed || !description) return;+ // After a failure the same description goes on from the picture that failed.+ const resume = !!state.error && description === state.description && plan && !done();+ const current = ++epoch;+ const alive = () => current === epoch && !disposed;+ if (!resume) { seed = randomSeed(); plan = null; }+ emit({running: true, error: '', report_id: null, waiting: '', description,+ ...(resume ? {} : {pictures: fresh(), current: 0})});+ try {+ if (!plan) {+ plan = await client.castViews(description);+ if (!alive()) return;+ }+ for (let index = 0; index < plan.length; index++) {+ if (state.pictures[index].file) continue;+ emit({current: index});+ const file = await runOne(index, alive);+ if (file === null || !alive()) return;+ job = null;+ setPicture(index, {file, fraction: 1});+ }+ emit({running: false, current: -1, waiting: ''});+ } catch (error) {+ if (!alive()) return;+ const id = job; job = null;+ if (id) void cancelJob(id);+ // A failure keeps the pictures already made; the next Generate goes on from the failed one.+ emit({running: false, current: -1, waiting: '', ...failureOf(error),+ pictures: state.pictures.map(row => row.file ? row : {...row, fraction: 0})});+ }+ }++ function stop() {+ const id = job; job = null;+ ++epoch; unschedule(timer); timer = null; plan = null;+ // A stopped run is dropped whole: the next Generate starts again from the description.+ emit({running: false, current: -1, waiting: '', error: '', report_id: null, pictures: fresh()});+ return id ? cancelJob(id) : Promise.resolve();+ }+ // The description changed: pictures made from the old one no longer belong to it.+ function reset() {+ if (state.running || !(state.pictures.some(row => row.file) || state.error)) return;+ plan = null;+ emit({pictures: fresh(), error: '', report_id: null, current: -1});+ }+ return {start, stop, reset, state: () => state, done,+ dispose() { disposed = true; return stop(); }};+}++export function mountCastGenerate({container, api, text, t = text, viewURL, onState = () => {}, fetchApi, client}) {+ const tr = t || ((en) => en);+ const fetcher = fetchApi || (api ? api.fetchApi.bind(api) : globalThis.fetch.bind(globalThis));+ client = client || createImageGenClient(fetcher);+ const url = viewURL || (file => {+ const i = file.lastIndexOf('/');+ const query = new URLSearchParams({filename: file.slice(i + 1), subfolder: file.slice(0, Math.max(0, i)), type: 'input'});+ return (api?.apiURL ? api.apiURL('/view?' + query) : '/view?' + query);+ });+ const cssURL = new URL('./cast_generate.css', import.meta.url).href;+ if (!document.querySelector(`link[href="${cssURL}"]`)) {+ const css = el('link'); css.rel = 'stylesheet'; css.href = cssURL; document.head.append(css);+ }++ const root = el('div', 'fv-cg');+ const body = el('div', 'fv-cg-body');+ const side = el('div', 'fv-cg-side');+ const foot = el('div', 'fv-cg-foot');+ const field = el('textarea', 'fv-cg-text');+ field.placeholder = tr('Describe the character', '描述人物');+ field.setAttribute('aria-label', field.placeholder);+ field.maxLength = 1000;+ const note = el('div', 'fv-cg-note'); note.setAttribute('role', 'status');+ const action = el('button', 'fv-cg-action'); action.type = 'button';+ foot.append(note, action);+ side.append(field, foot);+ const grid = el('div', 'fv-cg-views');+ const cells = CAST_VIEWS.map(view => {+ const cell = el('div', 'fv-cg-view');+ const title = tr(...VIEW_TITLES[view]);+ cell.title = title; cell.setAttribute('role', 'img');+ const image = el('img'); image.alt = ''; image.draggable = false;+ const percent = el('span', 'fv-cg-percent');+ const meter = el('i', 'fv-cg-meter'); const fill = el('b'); meter.append(fill);+ cell.append(image, percent, meter);+ grid.append(cell);+ return {cell, image, percent, fill, title};+ });+ body.append(side, grid);+ root.append(body);+ container.append(root);++ let info = null, infoTimer = null, disposed = false, failureKey = null, attention = null;+ const generator = createCastGenerator({client, onChange: render});+ let last = '';++ function missing() { return info && !info.installed && !info.ready; }+ function render(state = generator.state()) {+ const running = state.running;+ const isMissing = missing();+ root.dataset.state = isMissing ? 'missing' : running ? 'running' : generator.done() ? 'done' : state.error ? 'failed' : 'idle';+ field.readOnly = running;+ action.hidden = !!isMissing;+ // One accent button at a time: Generate until the five pictures exist, then Regenerate is neutral.+ const finishedAll = generator.done() && !running;+ action.textContent = running ? tr('Stop', '停止') : finishedAll ? tr('Regenerate', '重新生成') : tr('Generate', '生成');+ action.dataset.primary = String(!running && !finishedAll);+ const finished = state.pictures.filter(row => row.file).length;+ const currentFraction = running && state.current >= 0 ? state.pictures[state.current]?.fraction || 0 : 0;+ const progress = generator.done() ? 1 : (finished + currentFraction) / CAST_VIEWS.length;+ state.pictures.forEach((row, i) => {+ const cell = cells[i];+ const active = running && i === state.current && !row.file;+ const src = row.file ? url(row.file) : '';+ if (cell.image.getAttribute('src') !== src) src ? cell.image.src = src : cell.image.removeAttribute('src');+ cell.cell.dataset.state = row.file ? 'done' : active ? 'running' : 'empty';+ cell.cell.setAttribute('aria-label', cell.title + (row.file ? '' : active+ ? ' ' + Math.floor(row.fraction * 100) + '%' : ''));+ cell.percent.textContent = active && !state.waiting ? Math.floor(row.fraction * 100) + '%' : '';+ cell.fill.style.width = (active ? row.fraction * 100 : 0) + '%';+ });+ if (state.error) {+ const key = `${state.error}:${state.report_id || ''}`;+ if (failureKey !== key) { renderImageFailure(note, state, tr, {fetchApi: fetcher}); failureKey = key; }+ } else {+ failureKey = null;+ note.textContent = isMissing ? imagePackUnavailableMessage(info, tr)+ : running && state.waiting ? tr('Added to the queue. It starts when the previous one finishes.',+ '已加入队列,前面的完成后自动开始。')+ : attention ? attention : '';+ }+ note.hidden = !note.textContent && !note.firstChild;+ note.dataset.failed = String(!!state.error);+ // The last picture lands a moment before the run ends: done means finished, not just five files.+ const complete = generator.done() && !running;+ const summary = JSON.stringify([running, complete, Math.round(progress * 100)]);+ if (summary !== last) {+ last = summary;+ onState({busy: running, progress, done: complete});+ }+ }++ async function checkInfo() {+ try { info = await client.info(); } catch { info = null; }+ if (disposed) return;+ render();+ clearTimeout(infoTimer);+ if (missing()) infoTimer = setTimeout(checkInfo, IMAGE_GEN_INFO_POLL_MS);+ }++ function begin() {+ if (!field.value.trim()) {+ attention = tr('Describe the character first.', '请先描述人物。');+ render(); field.focus();+ return;+ }+ attention = null;+ void generator.start(field.value);+ }+ action.onclick = () => generator.state().running ? void generator.stop() : begin();+ field.addEventListener('input', () => {+ if (attention) { attention = null; render(); }+ if (field.value.trim() !== generator.state().description) generator.reset();+ });+ // Enter in the description box is a new line; Ctrl/Cmd+Enter generates.+ field.addEventListener('keydown', event => {+ if (event.key === 'Enter' && (event.ctrlKey || event.metaKey) && !generator.state().running) { event.preventDefault(); begin(); }+ });++ render();+ void checkInfo();+ return {+ getPictures: () => generator.done() && !generator.state().running ? generator.state().pictures.map(row => ({file: row.file, label: row.view})) : [],+ isBusy: () => generator.state().running,+ cancel: () => generator.stop(),+ destroy() { disposed = true; clearTimeout(infoTimer); void generator.dispose(); root.remove(); },+ element: root,+ };+}diff --git a/web/health.js b/web/health.jsindex 1b9f2fb..af36a9d 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 = ['agent_activity.js', 'agent_connect.js', 'agent_session.js', 'autopilot.js', 'autopilot_chat.js', 'autopilot_conversations.js', 'browser_extension.js', 'caret_rect.js', 'chain_support.js', 'capability_view.js', 'compatibility.js', 'error_panel.js', 'first_run_guide.js', 'fonts.js', 'freevideo.js', 'generation_progress.js',+export const MODULES = ['agent_activity.js', 'agent_connect.js', 'agent_session.js', 'autopilot.js', 'autopilot_chat.js', 'autopilot_conversations.js', 'browser_extension.js', 'caret_rect.js', 'chain_support.js', 'capability_view.js', 'cast_generate.js', 'compatibility.js', 'error_panel.js', 'first_run_guide.js', 'fonts.js', 'freevideo.js', 'generation_progress.js','editor.js', 'editor_actions.js', 'editor_adjust.js', 'editor_adjust_picture.js', 'editor_picture_fields.js', 'editor_picture_session.js', 'editor_preview_picture.js', 'editor_entry.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', 'frame_sizes.js', 'health.js', 'image_commands.js', 'image_editor.js', 'image_editor_engine.js', 'image_generation.js', 'launcher.js', 'length_plan.js', 'lora_triggers.js', 'library.js', 'motion.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', 'report_issue.js', 'studio_recent.js',diff --git a/web/image_generation.js b/web/image_generation.jsindex d074f3d..1fdba11 100644--- a/web/image_generation.js+++ b/web/image_generation.js@@ -81,6 +81,8 @@ export function createImageGenClient(fetchImpl = globalThis.fetch.bind(globalThi...(phase === 'cancelled' ? {error: 'cancelled'} : {})};},cancel: job => post('cancel', {[p.job]: job}),+ // The prompts and sizes of a new character's five pictures (the Agent's cards use the same ones).+ castViews: async description => (await post('cast-views', {description})).views,async upload(file) {// ComfyUI's existing image upload stores this at input/<unique name>.// FreeVideo's media upload uses subdirectories the image worker rejects.@@ -189,7 +191,7 @@ export function renderImageFailure(host, {error, report_id} = {}, t,bar.append(anchor); card.append(bar);return card;}-function imagePackUnavailableMessage(info, t) {+export function imagePackUnavailableMessage(info, t) {return info?.[IMAGE_GEN_PROTOCOL.downloading]? t('Downloading. Available when finished.', '正在下载,完成后可用。') : imagePackMessage(info, t);}