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 library: scenes next to characters, several AI candidates, @ a scene, light and weather kept
Bowen Xue2d448617f404
diff --git a/freevideo_engine/agent/cast.py b/freevideo_engine/agent/cast.pyindex 51fa615..6b2a2e2 100644--- a/freevideo_engine/agent/cast.py+++ b/freevideo_engine/agent/cast.py@@ -57,8 +57,7 @@ def reference_prompt(card, *, face=False):"""The one place the reference clip prompts are written."""who = (card.get('description') or card['name']).strip().rstrip('.')if card['kind'] == 'setting':- return ('%s. A slow, steady camera pan across the empty place, no people, even daylight, '- 'sharp focus, no text.' % who)+ return ('%s. A slow, steady camera pan across the place, no people, sharp focus, no text.' % who)if face:return ('%s. A close-up of the face and shoulders, looking straight at the camera with a neutral ''expression, in front of a plain light grey studio backdrop. The person stays still. 'diff --git a/freevideo_engine/comfy_assets.py b/freevideo_engine/comfy_assets.pyindex 4628d13..515b934 100644--- a/freevideo_engine/comfy_assets.py+++ b/freevideo_engine/comfy_assets.py@@ -85,8 +85,9 @@ def resolve_assets(serialized, input_directory):or media_kind(row['file']) != 'video'):raise ValueError('depth is only allowed on video references')# 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'}- or not isinstance(row['cast']['id'], str) or not 0 < len(row['cast']['id']) <= 128):+ if 'cast' in row and (set(row['cast'] if isinstance(row['cast'], dict) else ('?',)) not in ({'id'}, {'id', 'setting'})+ or not isinstance(row['cast']['id'], str) or not 0 < len(row['cast']['id']) <= 128+ or row['cast'].get('setting', True) is not True):raise ValueError('Invalid media item')if type(row.get('enabled', True)) is not bool:raise ValueError('Media enabled must be a boolean')@@ -119,6 +120,8 @@ def resolve_assets(serialized, input_directory):reference.update(depth=True, early_steps=3)if cast_id(row) is not None:reference['cast'] = cast_id(row) # only a continued part reads it (comfy_media.continued)+ if is_setting(row):+ reference['scene'] = Trueif 'early_steps' in row:from .media_request import validate_early_stepsvalidate_early_steps(dict(row, kind=kind))@@ -172,7 +175,7 @@ def continued_assets(serialized):image = Falseif image:pictures.append(row)- return json.dumps([_kept_row(row) for row in pick_pictures(pictures, cast_id)] + original)+ return json.dumps([_kept_row(row) for row in pick_pictures(pictures, cast_id, is_setting)] + original)def cast_id(row):@@ -182,10 +185,16 @@ def cast_id(row):return value if isinstance(value, (str, int)) and not isinstance(value, bool) else None+def is_setting(row):+ """Whether a panel row carries the picture of a setting card (an @ mention of a scene)."""+ cast = row.get('cast') if isinstance(row, dict) else None+ return cast_id(row) is not None and cast.get('setting') is True++def _kept_row(row):kept = dict(file=row['file'], role='reference')if cast_id(row) is not None:- kept['cast'] = dict(id=cast_id(row))+ kept['cast'] = dict(id=cast_id(row), **({'setting': True} if is_setting(row) else {}))return keptdiff --git a/freevideo_engine/comfy_media.py b/freevideo_engine/comfy_media.pyindex 5b39686..7dccb65 100644--- a/freevideo_engine/comfy_media.py+++ b/freevideo_engine/comfy_media.py@@ -60,7 +60,8 @@ def continued(exported, notes=None):original = [row for row in media.get('references', []) if row.get('kind') == 'audio' and row.get('use') == 'original']keyframes = [name for name in ('first', 'last') if media.get(name)]# Characters added by an @ mention keep one picture each when there are several (pick_pictures).- chosen = pick_pictures(pictures, lambda row: row.get('cast'))+ chosen = pick_pictures(pictures, lambda row: None if row.get('scene') else row.get('cast'),+ lambda row: row.get('scene') is True)candidates = [_plain(row) for row in chosen] + [{'kind': 'image', 'path': media[name]} for name in keyframes]if candidates or original:kept['references'] = candidates[:PICTURES_MAX] + original@@ -77,8 +78,8 @@ def continued(exported, notes=None):def _plain(row):- """A reference row without the panel's character mark, which the engine's request does not carry."""- return {key: value for key, value in row.items() if key != 'cast'}+ """A reference row without the panel's character or scene mark, which the engine's request does not carry."""+ return {key: value for key, value in row.items() if key not in ('cast', 'scene')}def continued_note(pictures, keyframes, used):diff --git a/freevideo_engine/continuation.py b/freevideo_engine/continuation.pyindex f803fac..c268e91 100644--- a/freevideo_engine/continuation.py+++ b/freevideo_engine/continuation.py@@ -42,22 +42,35 @@ UNSUPPORTED_MEDIA = UNSUPPORTED + ' Connect up to 3 pictures as references, andPICTURES_MAX = 3-def pick_pictures(rows, person):+def pick_pictures(rows, person, scene=None):"""The pictures a continued part keeps from image rows in panel order: at most PICTURES_MAX.person(row) is the id of the character a row belongs to, or None. With two or more characters each keepsonly the last of its rows (the face close-up, or the one picture its card has) so that everyone is seen; the- other pictures follow. With none or one character the first rows are kept."""+ other pictures follow. With none or one character the first rows are kept.+ scene(row) is true for the picture of a setting card: the last such row keeps one place, after the others, so the+ part still shows the same place."""rows = list(rows)+ place = None+ if scene is not None:+ places = [row for row in rows if scene(row)]+ if places:+ place = places[-1]+ rows = [row for row in rows if not scene(row)]last = {}for index, row in enumerate(rows):if person(row) is not None:last[person(row)] = index+ room = PICTURES_MAX - (place is not None)if len(last) < 2:- return rows[:PICTURES_MAX]- faces = [rows[index] for index in sorted(last.values())]- others = [row for row in rows if person(row) is None]- return (faces + others)[:PICTURES_MAX]+ chosen = rows[:room]+ else:+ faces = [rows[index] for index in sorted(last.values())]+ others = [row for row in rows if person(row) is None]+ chosen = (faces + others)[:room]+ return chosen + ([place] if place is not None else [])++INVALID_FRAMES = 'Frame count must be 5 + 17n and at least 39 (39, 56, 73, 90, ...).'INVALID_FILE = 'Choose an existing MP4 video using its absolute path.'diff --git a/freevideo_engine/image_gen/cast_views.py b/freevideo_engine/image_gen/cast_views.pyindex 012b99c..e86d05a 100644--- a/freevideo_engine/image_gen/cast_views.py+++ b/freevideo_engine/image_gen/cast_views.py@@ -69,8 +69,8 @@ def view_prompt(card, view):"""The prompt for one view of a card (a dict with name, description, kind)."""who = _who(card)if card.get('kind') == 'setting':- return ('%s. A wide view of the empty place, no people, even daylight, natural colours, sharp focus, '- 'no text.' % who)+ # The time, weather, light and colour the description gives are the point of a scene: only the people and text are barred.+ return '%s. A wide view of the place, no people, sharp focus, no text.' % whoif view == 'front':return ('%s. The person stands alone, the whole body from head to feet, facing the camera, neutral pose ''with the arms relaxed, %s.' % (who, BACKDROP))@@ -99,13 +99,16 @@ def photo_prompt():'add no new accessories.' % BACKDROP)-def page_views(description):+def page_views(description, kind='character'):"""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 acard 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')+ if kind not in ('character', 'setting'):+ raise ValueError('invalid_request')+ card = dict(name=description.strip()[:120], description=description.strip(), kind=kind)+ views = SETTING_VIEWS if kind == 'setting' else VIEWSreturn 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])+ 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 8889c7e..4c1b57b 100644--- a/freevideo_engine/image_gen/service.py+++ b/freevideo_engine/image_gen/service.py@@ -1256,7 +1256,7 @@ def register():name = request.match_info['action']if name == 'cast-views':from .cast_views import page_views- result = page_views(value.get('description'))+ result = page_views(value.get('description'), value.get('kind', 'character'))elif name == 'status':result = service.status(value.get('job'))elif name == 'cancel':diff --git a/scripts/test_freevideo_entry.mjs b/scripts/test_freevideo_entry.mjsindex f7c357c..891d378 100644--- a/scripts/test_freevideo_entry.mjs+++ b/scripts/test_freevideo_entry.mjs@@ -520,8 +520,10 @@ test('main browser entry registers both views and preserves node hooks', async tawait extension.beforeRegisterNodeDef(MediaNode, {name: 'FreeVideoMedia'});const media = new MediaNode(); media.onNodeCreated();const panel = media.dom.find(row => row.name === 'freevideo_media').element;- const [castRow, toolbar, mode, note, audioHelp, connections] = panel.children;+ const [castRow, sceneRow, toolbar, mode, note, audioHelp, connections] = panel.children;assert.equal(castRow, casts[0].element);+ assert.equal(sceneRow, casts[1].element);+ assert.equal(casts[1].options.kind, 'setting');assert.equal(casts[0].options.api, api);assert.equal(typeof casts[0].options.uploadOne, 'function');assert.equal(typeof casts[0].options.viewURL, 'function');@@ -558,10 +560,11 @@ test('main browser entry registers both views and preserves node hooks', async tawait imagePicker.onchange();assert.deepEqual(JSON.parse(media.widgets[0].value).map(row => row.role), ['reference', 'first']);media.onRemoved();- assert.equal(casts[0].destroyed, true);+ assert.equal(casts[0].destroyed, true); assert.equal(casts[1].destroyed, true);const mounted = new Element('mount'), disposeMedia = media.freevideoCreateMediaEditor(mounted);- assert.equal(mounted.children[0].children[0], casts[1].element);- disposeMedia(); assert.equal(casts[1].destroyed, true);+ assert.equal(mounted.children[0].children[0], casts[2].element);+ assert.equal(mounted.children[0].children[1], casts[3].element);+ disposeMedia(); assert.equal(casts[2].destroyed, true); assert.equal(casts[3].destroyed, true);await t.test('Generate node removal preserves the original hook when setSize throws', async () => {const previousInterval = globalThis.setInterval, previousClear = globalThis.clearInterval;diff --git a/web/cast_generate.css b/web/cast_generate.cssindex 828c679..2dac44d 100644--- a/web/cast_generate.css+++ b/web/cast_generate.css@@ -42,3 +42,15 @@.fv-cg-view{flex:none;width:72px}}@media(prefers-reduced-motion:reduce){.fv-cg *{transition:none}}++.fv-cg[data-kind=scene] .fv-cg-body{grid-template-columns:minmax(0,1fr)}+.fv-cg[data-kind=scene] .fv-cg-text{min-height:96px}+.fv-cg[data-kind=scene] .fv-cg-view{aspect-ratio:16/9;cursor:pointer}+.fv-cg[data-kind=scene] .fv-cg-view:not([data-state=done]){cursor:default}+.fv-cg[data-kind=scene] .fv-cg-view img{object-fit:cover}+.fv-cg[data-kind=scene] .fv-cg-view[aria-pressed=true]{border:2px solid var(--fv-accent,#6db8fa)}+.fv-cg[data-kind=scene] .fv-cg-view:focus-visible{outline:2px solid var(--fv-accent,#6db8fa);outline-offset:2px}+.fv-cg-stage{display:none}+.fv-cg-stage img{display:block;width:100%;aspect-ratio:16/9;object-fit:cover;border-radius:6px;background:#ffffff08}+@container (max-width:520px){.fv-cg[data-kind=scene] .fv-cg-views{display:grid}.fv-cg[data-kind=scene] .fv-cg-view{width:auto}+ .fv-cg[data-kind=scene] .fv-cg-stage:not([hidden]){display:block}}diff --git a/web/cast_generate.js b/web/cast_generate.jsindex 99347dc..07238c7 100644--- a/web/cast_generate.js+++ b/web/cast_generate.js@@ -9,6 +9,8 @@ import {createImageLoras} from './image_lora.js';export {imageGenerationSupported as castGenerateSupported} from './image_generation.js';export const CAST_VIEWS = Object.freeze(['front', 'three_quarter', 'side', 'back', 'face']);+// A scene is not a sheet of views: one description is drawn three times with different seeds and the user picks one.+export const SCENE_CANDIDATES = Object.freeze(['a', 'b', 'c']);const VIEW_TITLES = Object.freeze({front: ['Front', '正面'], three_quarter: ['Three-quarter', '四分之三'], side: ['Side', '侧面'],back: ['Back', '背面'], face: ['Face', '脸部'],@@ -20,8 +22,9 @@ const failureOf = error => ({error: error?.code || 'generation_failed', report_iconst 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}));+export function createCastGenerator({client, kind = 'character', onChange = () => {}, schedule = setTimeout, unschedule = clearTimeout}) {+ const scene = kind === 'setting', names = scene ? SCENE_CANDIDATES : CAST_VIEWS;+ const fresh = () => names.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, loras;const emit = patch => { state = {...state, ...patch}; if (!disposed) onChange(state); };@@ -31,7 +34,7 @@ export function createCastGenerator({client, onChange = () => {}, schedule = setasync 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,+ const row = await client.generate({prompt: view.prompt, width: view.width, height: view.height, seed: scene ? seed + index : seed,images: view.from_front ? [front] : [], ...(view.view === 'back' ? {cast_view: 'back'} : {}),...(loras === undefined ? {} : {loras})});if (!row.job) throw Object.assign(new Error(row.error || 'generation_failed'), {code: row.error, report_id: row.report_id, memory: row.memory});@@ -69,7 +72,8 @@ export function createCastGenerator({client, onChange = () => {}, schedule = set...(resume ? {} : {pictures: fresh(), current: 0})});try {if (!plan) {- plan = await client.castViews(description);+ plan = await client.castViews(description, kind);+ if (scene) plan = names.map(() => plan[0]);if (!alive()) return;}for (let index = 0; index < plan.length; index++) {@@ -108,7 +112,8 @@ export function createCastGenerator({client, onChange = () => {}, schedule = setdispose() { disposed = true; return stop(); }};}-export function mountCastGenerate({container, api, text, t = text, viewURL, onState = () => {}, fetchApi, client, loras}) {+export function mountCastGenerate({container, api, text, t = text, viewURL, onState = () => {}, onPick = () => {}, fetchApi, client, loras, kind = 'character'}) {+ const scene = kind === 'setting', names = scene ? SCENE_CANDIDATES : CAST_VIEWS;const tr = t || ((en) => en);const fetcher = fetchApi || (api ? api.fetchApi.bind(api) : globalThis.fetch.bind(globalThis));client = client || createImageGenClient(fetcher);@@ -123,11 +128,12 @@ export function mountCastGenerate({container, api, text, t = text, viewURL, onSt}const root = el('div', 'fv-cg');+ if (scene) root.dataset.kind = 'scene';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.placeholder = scene ? tr('Describe the scene', '描述场景') : tr('Describe the character', '描述角色');field.setAttribute('aria-label', field.placeholder);field.maxLength = 1000;const note = el('div', 'fv-cg-note'); note.setAttribute('role', 'status');@@ -138,10 +144,16 @@ export function mountCastGenerate({container, api, text, t = text, viewURL, onStfoot.append(note, action);side.append(field, ...(picker ? [picker.element] : []), foot);const grid = el('div', 'fv-cg-views');- const cells = CAST_VIEWS.map(view => {+ const cells = names.map((view, index) => {const cell = el('div', 'fv-cg-view');- const title = tr(...VIEW_TITLES[view]);- cell.title = title; cell.setAttribute('role', 'img');+ const title = scene ? tr(`Option ${index + 1}`, `方案 ${index + 1}`) : tr(...VIEW_TITLES[view]);+ cell.title = title; cell.setAttribute('role', scene ? 'button' : 'img');+ if (scene) {+ cell.tabIndex = 0;+ const pick = () => { if (cell.dataset.state !== 'done') return; chosen = index; render(); };+ cell.onclick = pick;+ cell.onkeydown = event => { if (event.key === 'Enter' || event.key === ' ') { event.preventDefault(); pick(); } };+ }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);@@ -149,12 +161,14 @@ export function mountCastGenerate({container, api, text, t = text, viewURL, onStgrid.append(cell);return {cell, image, percent, fill, title};});- body.append(side, grid);+ // A scene shows the chosen option large on narrow widths, where three small ones cannot show its mood.+ const stage = el('div', 'fv-cg-stage'), stageImage = el('img'); stageImage.alt = ''; stage.append(stageImage); stage.hidden = true;+ body.append(side, ...(scene ? [stage] : []), 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 chosen = 0, picked = '', info = null, infoTimer = null, disposed = false, failureKey = null, attention = null;+ const generator = createCastGenerator({client, kind, onChange: render});let last = '';function missing() { return info && !info.installed && !info.ready; }@@ -171,18 +185,26 @@ export function mountCastGenerate({container, api, text, t = text, viewURL, onStaction.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;+ const progress = generator.done() ? 1 : (finished + currentFraction) / names.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';+ if (scene) cell.cell.setAttribute('aria-pressed', String(!!row.file && i === chosen));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 (scene) {+ const file = generator.done() && !running ? state.pictures[chosen]?.file || '' : '';+ const shown = file ? url(file) : '';+ stage.hidden = !shown; if (stageImage.getAttribute('src') !== shown) shown ? stageImage.src = shown : stageImage.removeAttribute('src');+ if (file && file !== picked) onPick(picked = file);+ if (!file && !running) picked = '';+ }if (state.error) {const key = `${state.error}:${state.report_id || ''}:${state.stage || ''}:${state.memory || ''}`;if (failureKey !== key) { renderImageFailure(note, {...state, info}, tr, {fetchApi: fetcher}); failureKey = key; }@@ -214,13 +236,13 @@ export function mountCastGenerate({container, api, text, t = text, viewURL, onStfunction begin() {if (!field.value.trim()) {- attention = tr('Describe the character first.', '请先描述角色。');+ attention = scene ? tr('Describe the scene first.', '请先描述场景。') : tr('Describe the character first.', '请先描述角色。');render(); field.focus();return;}- attention = null;- const chosen = picker ? picker.value() : loras;- void generator.start(field.value, picker && !chosen.length ? {} : {loras: chosen});+ attention = null; chosen = 0;+ const selected = picker ? picker.value() : loras;+ void generator.start(field.value, picker && !selected.length ? {} : {loras: selected});}action.onclick = () => generator.state().running ? void generator.stop() : begin();field.addEventListener('input', () => {@@ -235,7 +257,9 @@ export function mountCastGenerate({container, api, text, t = text, viewURL, onStrender();void checkInfo();return {- getPictures: () => generator.done() && !generator.state().running ? generator.state().pictures.map(row => ({file: row.file, label: row.view})) : [],+ getPictures: () => !generator.done() || generator.state().running ? []+ : scene ? [{file: generator.state().pictures[chosen].file, label: 'other'}]+ : generator.state().pictures.map(row => ({file: row.file, label: row.view})),isBusy: () => generator.state().running,cancel: () => generator.stop(),destroy() { disposed = true; picker?.dispose(); clearTimeout(infoTimer); void generator.dispose(); root.remove(); },diff --git a/web/cast_library.css b/web/cast_library.cssindex 7028dfe..83f1eec 100644--- a/web/cast_library.css+++ b/web/cast_library.css@@ -48,3 +48,9 @@.fv-cast-dialog [hidden],.fv-cast-library [hidden]{display:none!important}@media(max-width:540px){.fv-cast-dialog{padding:14px}.fv-cast-upload{gap:10px}.fv-cast-views{gap:5px}.fv-cast-actions{gap:5px}.fv-cast-actions button{padding:5px 9px}}.fv-cast-library .fv-cast-avatar.fv-cast-mentioned{border-color:var(--fv-accent);box-shadow:0 0 0 1px var(--fv-accent)}+.fv-cast-library[data-kind=scene] .fv-cast-avatar,.fv-cast-library[data-kind=scene] .fv-cast-add{flex-basis:56px;width:56px;height:32px;border-radius:6px}+.fv-cast-library[data-kind=scene] .fv-cast-avatar img{object-position:50% 50%;object-view-box:none}+.fv-cast-dialog[data-kind=scene] .fv-cast-upload{display:block}+.fv-cast-dialog[data-kind=scene] .fv-cast-views{grid-template-columns:repeat(3,minmax(0,1fr));grid-template-rows:none}+.fv-cast-dialog[data-kind=scene] .fv-cast-slot{aspect-ratio:16/9}+.fv-cast-dialog[data-kind=scene] .fv-cast-choose img{object-fit:cover}diff --git a/web/cast_library.js b/web/cast_library.jsindex 479b4ca..0f21f51 100644--- a/web/cast_library.js+++ b/web/cast_library.js@@ -23,7 +23,10 @@ const button = (className, label, action) => {};const path = id => '/freevideo/agent/cast/' + encodeURIComponent(id);-export function createCastLibrary({api, text, viewURL, uploadOne, onChange = () => {}}) {+// kind 'setting' is the scene row: wide pictures, up to 3 per card, and no front picture.+export function createCastLibrary({api, text, viewURL, uploadOne, onChange = () => {}, kind = 'character'}) {+ const scene = kind === 'setting', SLOTS = scene ? 3 : 6;+ const word = (character, place) => scene ? place : character;if (!document.querySelector('link[data-freevideo-cast]')) {const css = el('link'); css.rel = 'stylesheet'; css.dataset.freevideoCast = '';css.href = new URL('./cast_library.css', import.meta.url).href; document.head.append(css);@@ -34,11 +37,12 @@ export function createCastLibrary({api, text, viewURL, uploadOne, onChange = ()// The row shows, and the page session is asked for, only once /freevideo/agent says the interface is on.let available = false; element.hidden = true;const probe = agentInterfaceEnabled(api).then(on => { available = on && !disposed; element.hidden = !available; return available; });- const heading = el('span', 'fv-cast-heading', text('Characters', '角色'));+ element.dataset.kind = scene ? 'scene' : 'character';+ const heading = el('span', 'fv-cast-heading', word(text('Characters', '角色'), text('Scenes', '场景')));const avatars = el('div', 'fv-cast-avatars');const skipped = el('div', 'fv-cast-unreadable'); skipped.hidden = true;const add = button('fv-cast-add', '+', () => openDialog());- add.setAttribute('aria-label', text('New character', '新建角色'));+ add.setAttribute('aria-label', word(text('New character', '新建角色'), text('New scene', '新建场景')));element.append(heading, avatars, add, skipped);async function value(response) {@@ -77,7 +81,7 @@ export function createCastLibrary({api, text, viewURL, uploadOne, onChange = ()async function refresh() {if (disposed || !await probe) return rows;const serial = ++request;- const data = await value(await agentGet(api, '/freevideo/agent/cast?kind=character&limit=200'));+ const data = await value(await agentGet(api, `/freevideo/agent/cast?kind=${kind}&limit=200`));if (!disposed && serial === request) {rows = data.cards; unreadable = Number.isSafeInteger(data.unreadable) && data.unreadable > 0 ? data.unreadable : 0;render(); onChange(rows);@@ -99,16 +103,16 @@ export function createCastLibrary({api, text, viewURL, uploadOne, onChange = ()if (disposed || !available) return;current?.close();let closed = false, loading = !!id, saving = false, revision, active = 'upload';- let generator = null, aiState = {busy: false, done: false}, deleteTimer = null, confirming = false, frontless = false;- const slots = Array(6).fill(null), slotUI = [];- const dialog = el('dialog', 'fv-cast-dialog');+ let generator = null, aiState = {busy: false, done: false}, deleteTimer = null, confirming = false, frontless = scene, beyond = [];+ const slots = Array(SLOTS).fill(null), slotUI = [];+ const dialog = el('dialog', 'fv-cast-dialog'); dialog.dataset.kind = scene ? 'scene' : 'character';const top = el('div', 'fv-cast-top');- const title = el('h2', '', id ? text('Edit character', '编辑角色') : text('New character', '新建角色'));+ const title = el('h2', '', id ? word(text('Edit character', '编辑角色'), text('Edit scene', '编辑场景')) : word(text('New character', '新建角色'), text('New scene', '新建场景')));dialog.setAttribute('aria-label', title.textContent);const closeButton = button('fv-cast-close', '×', () => close());closeButton.setAttribute('aria-label', text('Close', '关闭')); top.append(title, closeButton);const name = el('input', 'fv-cast-name'); name.type = 'text'; name.maxLength = 120;- name.placeholder = text('Name', '名字'); name.setAttribute('aria-label', text('Name', '名字'));+ name.placeholder = word(text('Name', '名字'), text('Name', '名称')); name.setAttribute('aria-label', name.placeholder);name.oninput = () => sync();name.onkeydown = event => { if (event.key === 'Enter') event.preventDefault(); };const tabs = el('div', 'fv-cast-tabs'); tabs.setAttribute('role', 'tablist');@@ -121,7 +125,7 @@ export function createCastLibrary({api, text, viewURL, uploadOne, onChange = ()const aiPane = el('div', 'fv-cast-generate'); aiPane.hidden = true;const status = el('div', 'fv-cast-message'); status.setAttribute('role', 'status'); status.hidden = true;const actions = el('div', 'fv-cast-actions');- const remove = button('fv-cast-delete', text('Delete character', '删除角色'), () => deleteCard()); remove.hidden = !id;+ const remove = button('fv-cast-delete', word(text('Delete character', '删除角色'), text('Delete scene', '删除场景')), () => deleteCard()); remove.hidden = !id;const cancel = button('', text('Cancel', '取消'), () => close());const save = button('fv-cast-save', text('Save', '保存'), () => saveCard());actions.append(remove, cancel, save);@@ -138,9 +142,9 @@ export function createCastLibrary({api, text, viewURL, uploadOne, onChange = ()// What is still missing before Save works ('' when nothing is); the button says so on hover and when pressed.let missing = '';const missingNow = () => !name.value.trim() ? text('Enter a name first', '先填写名字')- : aiBusy() ? text('Wait for the five pictures to finish', '等待五张图生成完成')- : active === 'upload' ? (frontless ? slots.some(Boolean) : slots[0]) ? '' : frontless ? text('Add an image first', '先添加图片') : text('Add a front image first', '先添加正面图片')- : aiState.done ? '' : text('Generate the images first', '先生成角色图片');+ : aiBusy() ? word(text('Wait for the five pictures to finish', '等待五张图生成完成'), text('Wait for the pictures to finish', '等待图片生成完成'))+ : active === 'upload' || scene ? (frontless ? slots.some(Boolean) : slots[0]) ? '' : frontless ? text('Add an image first', '先添加图片') : text('Add a front image first', '先添加正面图片')+ : aiState.done ? '' : word(text('Generate the images first', '先生成角色图片'), text('Generate the images first', '先生成场景图片'));function sync() {const busy = loading || saving;name.disabled = busy; remove.disabled = busy;@@ -202,23 +206,23 @@ export function createCastLibrary({api, text, viewURL, uploadOne, onChange = ()choose.append(image);} else {choose.append(el('span', 'fv-cast-slot-plus', '+'));- if (!index) choose.append(el('span', '', text('Front image', '正面图片')));+ if (!index && !scene) choose.append(el('span', '', text('Front image', '正面图片')));}remove.hidden = true; if (image?.complete) remove.hidden = false; mark(index); sync();}function chooseFiles(index, files) {if (loading || saving || closed) return;- for (const file of Array.from(files).slice(0, 6 - index)) {+ for (const file of Array.from(files).slice(0, SLOTS - index)) {release(index);- slots[index] = {file, label: index ? 'other' : 'front', preview: URL.createObjectURL(file)};+ slots[index] = {file, label: index || scene ? 'other' : 'front', preview: URL.createObjectURL(file)};paint(index++);}message('');}- for (let index = 0; index < 6; index++) {- const slot = el('div', 'fv-cast-slot' + (index ? '' : ' fv-cast-front'));+ for (let index = 0; index < SLOTS; index++) {+ const slot = el('div', 'fv-cast-slot' + (index || scene ? '' : ' fv-cast-front'));const input = el('input'); input.type = 'file'; input.accept = 'image/*'; input.hidden = true;- const label = index ? text(`View ${index}`, `视角 ${index}`) : text('Front image', '正面图片');+ const label = scene ? text(`Image ${index + 1}`, `图片 ${index + 1}`) : index ? text(`View ${index}`, `视角 ${index}`) : text('Front image', '正面图片');const choose = button('fv-cast-choose', '', () => input.click()); choose.setAttribute('aria-label', label);const remove = button('fv-cast-remove', '×', () => { release(index); paint(index); });remove.setAttribute('aria-label', text('Remove image', '移除图片'));@@ -228,12 +232,12 @@ export function createCastLibrary({api, text, viewURL, uploadOne, onChange = ()const problem = el('div', 'fv-cast-slot-error'); problem.setAttribute('role', 'alert'); problem.hidden = true;// The remove button comes after the text so it stays above it on a narrow tile.slot.append(choose, problem, remove, input); slotUI.push({slot, choose, remove, problem});- (index ? views : uploadPane).append(slot); paint(index);+ (index || scene ? views : uploadPane).append(slot); paint(index);}uploadPane.append(views);function resetDelete() {clearTimeout(deleteTimer); deleteTimer = null; confirming = false;- remove.textContent = text('Delete character', '删除角色'); remove.classList.remove('fv-cast-confirm');+ remove.textContent = word(text('Delete character', '删除角色'), text('Delete scene', '删除场景')); remove.classList.remove('fv-cast-confirm');}async function load() {loading = true; sync();@@ -241,11 +245,13 @@ export function createCastLibrary({api, text, viewURL, uploadOne, onChange = ()const card = await get(id);if (closed) return;revision = card.revision; name.value = card.name;- for (let i = 0; i < 6; i++) release(i);+ for (let i = 0; i < SLOTS; i++) release(i);// A card may have no front picture (the API does not require one): all its pictures stay, in order, and// saving does not ask for a front; the front slot is only reserved while there is a front to keep first.- frontless = card.images.length > 0 && card.images[0].label !== 'front';- card.images.slice(0, 6).forEach((picture, index) => { slots[index] = {...picture}; });+ frontless = scene || card.images.length > 0 && card.images[0].label !== 'front';+ card.images.slice(0, SLOTS).forEach((picture, index) => { slots[index] = {...picture}; });+ // The API allows six pictures on a scene card but the dialog shows three: the rest stay as they are.+ beyond = card.images.slice(SLOTS).map(picture => ({media: picture.media, label: picture.label}));slotUI.forEach((_, index) => paint(index));generator?.cancel(); aiState = {busy: false, done: false}; select('upload'); resetDelete();} finally { loading = false; if (!closed) sync(); }@@ -265,13 +271,14 @@ export function createCastLibrary({api, text, viewURL, uploadOne, onChange = ()saving = true; resetDelete(); message(''); slotUI.forEach((_, index) => mark(index)); sync();let pictures = [];try {- pictures = active === 'upload' ? slots.filter(Boolean) : generator.getPictures().map((picture, index) => ({+ pictures = active === 'upload' || scene ? slots.filter(Boolean) : generator.getPictures().map((picture, index) => ({...(typeof picture.file === 'string' ? {media: picture.file} : {file: picture.file}),label: picture.label || (index ? 'other' : 'front'),}));- const frontNeeded = active === 'ai' || !frontless;- if (!pictures.length || pictures.length > 6 || (frontNeeded && !pictures.some(picture => picture.label === 'front'))) {- message(text('Choose one front image and up to 5 more angles', '选一张正面图片,再加最多 5 张其他角度的图片'), true); return;+ const frontNeeded = !scene && (active === 'ai' || !frontless);+ if (!pictures.length || pictures.length > SLOTS || (frontNeeded && !pictures.some(picture => picture.label === 'front'))) {+ message(word(text('Choose one front image and up to 5 more angles', '选一张正面图片,再加最多 5 张其他角度的图片'),+ text('Choose up to 3 images', '最多选 3 张图片')), true); return;}const images = [];for (const picture of pictures) {@@ -280,14 +287,15 @@ export function createCastLibrary({api, text, viewURL, uploadOne, onChange = ()if (picture.file && !picture.media) picture.media = (await uploadOne(picture.file)).file;images.push({media: picture.media, label: picture.label});}+ if (id && scene) images.push(...beyond);if (closed) return;const body = {name: name.value.trim(), images};await value(await (id ? agentSend(api, 'PATCH', path(id), {revision, ...body})- : agentPost(api, '/freevideo/agent/cast', {kind: 'character', ...body})));+ : agentPost(api, '/freevideo/agent/cast', {kind, ...body})));close(); await saved();} catch (error) {const at = /^\/images\/(\d+)\/media$/.exec(error.field || '');- const index = at && active === 'upload' ? slots.indexOf(pictures[Number(at[1])]) : -1;+ const index = at && (active === 'upload' || scene) ? slots.indexOf(pictures[Number(at[1])]) : -1;if (index >= 0 && !closed) mark(index, error.message); else await failure(error);}finally { saving = false; if (!closed) sync(); }@@ -309,7 +317,7 @@ export function createCastLibrary({api, text, viewURL, uploadOne, onChange = ()if (closed) return;closed = true; clearTimeout(deleteTimer);generator?.cancel(); generator?.destroy();- for (let index = 0; index < 6; index++) release(index);+ for (let index = 0; index < SLOTS; index++) release(index);if (dialog.open) dialog.close(); dialog.remove();if (current?.element === dialog) current = null;add.focus();@@ -321,7 +329,9 @@ export function createCastLibrary({api, text, viewURL, uploadOne, onChange = ()current = {element: dialog, message, close};name.value = ''; select('upload'); document.body.append(dialog); dialog.showModal(); name.focus();if (id) load().catch(error => message(error.message));- mountGenerator({container: aiPane, api, text, viewURL, onState: state => {+ // A scene has one set of pictures: the chosen option takes the first place, where the Upload tab shows it.+ const pick = file => { if (closed || !scene) return; slots[0] = {media: file, label: 'other'}; paint(0); };+ mountGenerator({container: aiPane, api, text, viewURL, kind, onPick: pick, onState: state => {if (closed) return;aiState = state; sync();}}).then(instance => {diff --git a/web/cast_mention.js b/web/cast_mention.jsindex e6364f8..382f3f6 100644--- a/web/cast_mention.js+++ b/web/cast_mention.js@@ -44,10 +44,15 @@ function pictureNumbers(rows, continued = false) {});let kept = picked;if (continued) {+ // The picture of a scene keeps its place after the others (continuation.pick_pictures).+ const places = picked.filter(index => rows[index].cast?.setting === true);+ const place = places.length ? places[places.length - 1] : null;+ const rest = place === null ? picked : picked.filter(index => rows[index].cast?.setting !== true);const last = new Map();- picked.forEach(index => { if (rows[index].cast?.id) last.set(rows[index].cast.id, index); });- kept = last.size < 2 ? picked : [...last.values()].sort((a, b) => a - b).concat(picked.filter(index => !rows[index].cast?.id));- kept = kept.slice(0, CONTINUE_PICTURES);+ rest.forEach(index => { if (rows[index].cast?.id) last.set(rows[index].cast.id, index); });+ kept = last.size < 2 ? rest : [...last.values()].sort((a, b) => a - b).concat(rest.filter(index => !rows[index].cast?.id));+ kept = kept.slice(0, CONTINUE_PICTURES - (place === null ? 0 : 1));+ if (place !== null) kept.push(place);}return new Map(kept.map((index, at) => [index, at + 1]));}@@ -59,7 +64,7 @@ export function castInRows(rows) {if (!enabled(row) || !row.cast?.id || row.role !== 'reference' || !IMAGE.test(row.file || '')) return;const name = row.cast.name || '';// `handle` is what the text says after the @: the name, or "name (2)" when another present character has the same name.- const person = people.get(row.cast.id) || {id: row.cast.id, name, handle: row.cast.handle || name, description: row.cast.description || '', rows: []};+ const person = people.get(row.cast.id) || {id: row.cast.id, name, handle: row.cast.handle || name, description: row.cast.description || '', setting: row.cast.setting === true, rows: []};person.rows.push(index); people.set(row.cast.id, person);});return [...people.values()];@@ -101,6 +106,7 @@ export function expandCast(text, rows, {active = true, continued = false} = {})const people = castInRows(list);const ranges = mentionRanges(text, people);if (!ranges.length) return {text, subjects: []};+ const placed = [];if (!continued && list.some(row => enabled(row) && (row.role === 'first' || row.role === 'last'))) active = false;const numbers = pictureNumbers(list, continued);const order = [];@@ -108,6 +114,11 @@ export function expandCast(text, rows, {active = true, continued = false} = {})for (const range of ranges) {result += text.slice(at, range.start); at = range.end;const person = people.find(p => (p.handle ?? p.name) === range.name);+ if (person?.setting) {+ // A scene is not a subject: its name stays in the sentence and one line says which pictures show the place.+ if (active && !placed.includes(person) && person.rows.some(index => numbers.has(index))) placed.push(person);+ result += person.name; continue;+ }if (!active || !person || !person.rows.some(index => numbers.has(index))) { result += person ? person.name : range.name; continue; }let number = order.indexOf(person) + 1;if (!number) {@@ -117,7 +128,12 @@ export function expandCast(text, rows, {active = true, continued = false} = {})result += `<Subject ${number}>`;}result += text.slice(at);- if (!order.length) return {text: result, subjects: []};+ const places = placed.slice(0, 1).map(place => {+ const number = place.rows.map(index => numbers.get(index)).filter(Boolean)[0];+ const description = String(place.description || '').trim().replace(/\.+$/, '');+ return `setting: ${place.name}${description ? ': ' + description : ''}. <Picture ${number}> shows the place.`;+ });+ if (!order.length && !places.length) return {text: result, subjects: []};const subjects = order.map(person => {// Consecutive picture numbers make one range; a person whose pictures are apart gets several.const ranges = [];@@ -127,7 +143,8 @@ export function expandCast(text, rows, {active = true, continued = false} = {})}return {name: person.name, handle: person.handle ?? person.name, description: person.description, pictures: ranges, audio: null};});- return {text: subjectDefinitions(subjects) + '\n\n' + result, subjects};+ const definitions = [...(subjects.length ? [subjectDefinitions(subjects)] : []), ...places].join(' ');+ return {text: definitions + '\n\n' + result, subjects};}// The rewrite of an expanded prompt, written back with the names the box had: <Subject N> becomes "@handle" of the@@ -166,7 +183,9 @@ export function mentionState(rows, card, count = cardPictures(card).length, {conconst people = castInRows(list);if (people.some(person => person.id === card.id)) return {ok: true, present: true};if (!continued && list.some(row => enabled(row) && (row.role === 'first' || row.role === 'last'))) return {ok: false, reason: 'frames'};- if (people.length >= MAX_PEOPLE) return {ok: false, reason: 'people'};+ if (card.kind === 'setting' ? people.some(person => person.setting) : people.filter(person => !person.setting).length >= MAX_PEOPLE) {+ return {ok: false, reason: card.kind === 'setting' ? 'place' : 'people'};+ }if (continued && pictureNumbers(list).size >= CONTINUE_PICTURES) return {ok: false, reason: 'continued'};if (list.filter(enabled).length + count > MAX_REFERENCES) return {ok: false, reason: 'full'};return {ok: true, present: false};@@ -190,6 +209,6 @@ export function withCharacter(rows, card, typed = '') {const list = Array.isArray(rows) ? rows.map(row => ({...row})) : [];if (castInRows(list).some(person => person.id === card.id)) return list;const handle = typed || mentionHandle(list, card);- const cast = {id: card.id, name: card.name, description: card.description || '', ...(handle === card.name ? {} : {handle})};+ const cast = {id: card.id, name: card.name, description: card.description || '', ...(card.kind === 'setting' ? {setting: true} : {}), ...(handle === card.name ? {} : {handle})};return [...list, ...cardPictures(card).map(file => ({file, role: 'reference', enabled: true, cast}))];}diff --git a/web/editor_references.js b/web/editor_references.jsindex 1dfc1d6..8747935 100644--- a/web/editor_references.js+++ b/web/editor_references.js@@ -7,13 +7,18 @@ const MAX = 32;// The engine keeps three references of a part that continues: the first three, or, with two or more characters,// the last picture of each (the face) and then the others (continuation.pick_pictures).const CONTINUE_MAX = 3;-const personOf = ({row}) => typeof row.cast?.id === 'string' && row.cast.id ? row.cast.id : null;+const personOf = ({row}) => typeof row.cast?.id === 'string' && row.cast.id && row.cast.setting !== true ? row.cast.id : null;+const placeOf = ({row}) => row.cast?.setting === true;function pickContinued(list) {+ // A scene's picture keeps one place after the others (continuation.pick_pictures).+ const places = list.filter(placeOf), place = places[places.length - 1];+ if (place) list = list.filter(entry => !placeOf(entry));+ const room = CONTINUE_MAX - (place ? 1 : 0);const last = new Map();list.forEach((entry, at) => { const person = personOf(entry); if (person) last.set(person, at); });- if (last.size < 2) return list.slice(0, CONTINUE_MAX);- const faces = [...last.values()].sort((a, b) => a - b).map(at => list[at]);- return [...faces, ...list.filter(entry => !personOf(entry))].slice(0, CONTINUE_MAX);+ const chosen = last.size < 2 ? list.slice(0, room)+ : [...[...last.values()].sort((a, b) => a - b).map(at => list[at]), ...list.filter(entry => !personOf(entry))].slice(0, room);+ return place ? [...chosen, place] : chosen;}export function createEditorReferences({t, source, size = () => null, error = () => {}, notify = () => {}}) {const root = el('div', 'fv-ed-refs'), chips = el('div', 'fv-ed-ref-chips');diff --git a/web/freevideo.js b/web/freevideo.jsindex 4b696b9..dd2e1db 100644--- a/web/freevideo.js+++ b/web/freevideo.js@@ -161,7 +161,8 @@ function mediaPanel(node, mount = null) {role.value = 'reference';toolbar.append(add, generateImage, addAudio, role, picker, audioPicker); panel.append(toolbar, mode, note, audioHelp, connections, cards);const cast = createCastLibrary({api, text, viewURL, uploadOne});- panel.prepend(cast.element);+ const places = createCastLibrary({api, text, viewURL, uploadOne, kind: 'setting'});+ panel.prepend(cast.element, places.element);const read = () => {const rows = JSON.parse(serialized.value || "[]");if (!Array.isArray(rows) || rows.length > 32) throw new Error(text("Use at most 32 media items", "最多使用 32 个素材"));@@ -419,7 +420,7 @@ function mediaPanel(node, mount = null) {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, depth, use, range}) => ({file, role, enabled, ...(use === AUDIO_USE.original ? {use, ...(range && typeof range === 'object' ? {range} : {})} : {}), ...(sound === false && mediaKindOrNull(file) === 'video' ? {sound: false} : {}), ...(depth === true && role === 'reference' && mediaKindOrNull(file) === 'video' ? {depth: true} : {}), ...(typeof cast?.id === 'string' && cast.id ? {cast: {id: cast.id}} : {})}))); } catch { return serialized.value; }+ try { return JSON.stringify(read().map(({file, role, enabled, cast, sound, depth, use, range}) => ({file, role, enabled, ...(use === AUDIO_USE.original ? {use, ...(range && typeof range === 'object' ? {range} : {})} : {}), ...(sound === false && mediaKindOrNull(file) === 'video' ? {sound: false} : {}), ...(depth === true && role === 'reference' && mediaKindOrNull(file) === 'video' ? {depth: true} : {}), ...(typeof cast?.id === 'string' && cast.id ? {cast: {id: cast.id, ...(cast.setting === true ? {setting: true} : {})}} : {})}))); } catch { return serialized.value; }};async function upload(files) {if (node.isUploading || !files.length) return;@@ -446,7 +447,7 @@ function mediaPanel(node, mount = null) {panel.ondragover = event => { event.preventDefault(); event.stopPropagation(); };panel.ondrop = event => { event.preventDefault(); event.stopPropagation(); upload(event.dataTransfer.files); };panel.onpaste = event => { if (event.clipboardData?.files.length) { event.preventDefault(); event.stopPropagation(); upload(event.clipboardData.files); } };- const dispose = () => { window.removeEventListener('freevideo-media', changed); cast.destroy(); };+ const dispose = () => { window.removeEventListener('freevideo-media', changed); cast.destroy(); places.destroy(); };if (mount) { mount.append(panel); render(); return dispose; }node.freevideoCreateMediaEditor = target => mediaPanel(node, target);node.addDOMWidget("freevideo_media", "freevideo_media", panel, {serialize: false, getMinHeight: () => 300, getMaxHeight: () => 520});diff --git a/web/image_generation.js b/web/image_generation.jsindex fbb81bd..2358116 100644--- a/web/image_generation.js+++ b/web/image_generation.js@@ -110,7 +110,7 @@ export function createImageGenClient(fetchImpl = globalThis.fetch.bind(globalThiasync historyDeleteMany(files) { const answer = await post('history-delete-many', {files}); return {items: answer.items || [], failed: answer.failed || []}; },historyOpen: () => post('history-open', {}),// 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,+ castViews: async (description, kind = 'character') => (await post('cast-views', {description, kind})).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.diff --git a/web/prompt_references.css b/web/prompt_references.cssindex b92ca2c..a4285de 100644--- a/web/prompt_references.css+++ b/web/prompt_references.css@@ -22,6 +22,7 @@.fv-reference-group{padding:6px 8px 3px;font-size:11px;color:var(--fv-muted,#a9b3c4)}.fv-reference-person{min-height:36px;padding:5px 8px;gap:10px}.fv-reference-face{width:24px;height:24px;flex:none;border-radius:50%;object-fit:cover;object-position:50% 15%;object-view-box:inset(0 20% 40% 20%);background:var(--fv-raised,#252e39)}+.fv-reference-face[data-place]{width:40px;height:24px;border-radius:4px;object-position:50% 50%;object-view-box:none}.fv-reference-person strong{font-size:13px;font-weight:550;min-width:0;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}.fv-reference-person[aria-disabled=true]{opacity:.5;cursor:not-allowed}.fv-mention-mirror{position:absolute;box-sizing:border-box;overflow:hidden;pointer-events:none;white-space:pre-wrap;overflow-wrap:break-word;word-break:normal;color:var(--fv-ink,#eee);z-index:1}diff --git a/web/prompt_references.js b/web/prompt_references.jsindex 83919bd..fbddd0a 100644--- a/web/prompt_references.js+++ b/web/prompt_references.js@@ -214,7 +214,9 @@ export function attachReferencePicker(input, {items, t = en => en, view, host, alet available = [], invalid = false;try { available = items(); } catch { invalid = true; }const media = available.filter(item => `${item.name} ${item.token} ${t(item.kind, {image:'图片',video:'视频',audio:'音频'}[item.kind])} ${item.number}`.toLowerCase().includes(range.query));- const people = everyone.filter(person => person.name.toLowerCase().includes(range.query));+ const found = everyone.filter(person => person.name.toLowerCase().includes(range.query));+ const people = [...found.filter(person => !person.setting), ...found.filter(person => person.setting)];+ const plain = people.filter(person => !person.setting).length;matches = [...people.map(character => ({character})), ...media];list.replaceChildren();if (!matches.length) {@@ -229,17 +231,18 @@ export function attachReferencePicker(input, {items, t = en => en, view, host, a}}const heading = (en, zh) => { const h = document.createElement('div'); h.className = 'fv-reference-group'; h.setAttribute('role', 'presentation'); h.textContent = t(en, zh); list.append(h); };- if (people.length) heading('Characters', '角色');+ if (plain) heading('Characters', '角色');for (const [index, item] of matches.entries()) {+ if (index === plain && index < people.length) heading('Scenes', '场景');if (index === people.length && people.length && media.length) heading('Media', '素材');const option = document.createElement('div'); option.id = `${list.id}-${index}`;option.className = 'fv-reference-option'; option.setAttribute('role', 'option');if (item.character) {const person = item.character, face = document.createElement('img');- face.className = 'fv-reference-face'; face.alt = ''; face.src = person.thumb || '';+ face.className = 'fv-reference-face'; face.alt = ''; if (person.setting) face.dataset.place = ''; face.src = person.thumb || '';const name = document.createElement('strong'); name.textContent = person.name;option.className += ' fv-reference-person'; option.append(face, name);- if (person.blocked) { option.setAttribute('aria-disabled', 'true'); option.title = person.blocked; }+ if (person.blocked) { option.setAttribute('aria-disabled', 'true'); if (typeof person.blocked === 'string') option.title = person.blocked; }option.onpointerdown = e => e.preventDefault(); option.onclick = () => choose(index);option.onpointermove = () => { if (usable(index)) select(index); }; list.append(option);continue;diff --git a/web/studio.js b/web/studio.jsindex e30040a..0e0c136 100644--- a/web/studio.js+++ b/web/studio.js@@ -698,7 +698,7 @@ export function openStudio(node, {extendFrom = null} = {}) {prompt.disabled = linked(node, 'text'); prompt.oninput = () => { set(node, 'text', prompt.value); placeholder(); };const promptEditor = el('div', null, 'fv-prompt-editor'); promptEditor.append(prompt);// Library characters offered in the @ list; a mention puts the character's pictures in the media list.- let castLibrary = null;+ let castLibrary = null, sceneLibrary = null;const castAssets = () => { const owner = upstream(node, 'media'); const field = owner && widget(owner, 'assets'); return field ? {owner, field} : null; };// The library's own upload of a picture goes to the same streaming upload the media panel uses.const castUpload = file => uploadMedia(api, file);@@ -749,20 +749,23 @@ export function openStudio(node, {extendFrom = null} = {}) {function castChoices() {if (!castLibrary || linked(node, 'text') || !castAssets()) return [];const rows = mediaRows(node);- return castLibrary.list().filter(card => card.name).map(card => {+ const places = (sceneLibrary?.list() || []).map(card => ({...card, kind: 'setting'}));+ return [...castLibrary.list(), ...places].filter(card => card.name).map(card => {const state = mentionState(rows, card, Math.min(MAX_PICTURES_EACH, Number(card.images) || 0), {continued: Boolean(extension.source)});return {id: card.id, name: card.name, handle: mentionHandle(rows, card, castPending), thumb: card.thumbnail?.file ? view(card.thumbnail.file) : card.thumbnail?.url || '',- blocked: state.ok ? '' : castBlocked(state.reason)};+ ...(card.kind === 'setting' ? {setting: true} : {}), blocked: state.ok ? '' : castBlocked(state.reason) || true};});}// The name goes into the text at once; the card's pictures follow when the full card has been read.function mentionCharacter(person) {if (!castLibrary) return false;if (castInRows(mediaRows(node)).some(entry => entry.id === person.id)) return true;- if (!mentionState(mediaRows(node), {id: person.id}, 1, {continued: Boolean(extension.source)}).ok) return false;+ const library = person.setting ? sceneLibrary : castLibrary;+ if (!library) return false;+ if (!mentionState(mediaRows(node), {id: person.id, ...(person.setting ? {kind: 'setting'} : {})}, 1, {continued: Boolean(extension.source)}).ok) return false;const typed = person.handle || person.name;castPending.set(person.id, typed);- castLibrary.get(person.id).then(card => {+ library.get(person.id).then(card => {if (disposed) return;const rows = mediaRows(node), target = castAssets();if (!target || !mentionState(rows, card, undefined, {continued: Boolean(extension.source)}).ok) return;@@ -816,9 +819,11 @@ 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; window.removeEventListener('freevideo-media', castChanged); prompt.removeEventListener('input', announceCast); castOverlay.dispose(); delete node.freevideoContinues; });+ cleanup.push(() => { castLibrary?.destroy?.(); castLibrary = null; sceneLibrary?.destroy?.(); sceneLibrary = null; window.removeEventListener('freevideo-media', castChanged); prompt.removeEventListener('input', announceCast); castOverlay.dispose(); delete node.freevideoContinues; });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(); }})+ .then(library => { if (disposed) library?.destroy?.(); else sceneLibrary = library; });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.