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.
Generate shows what this request will download first: missing sampling tables, upscaler, prompt...
Bowen Xuec9ca1dc712ac
diff --git a/freevideo_engine/comfy_library.py b/freevideo_engine/comfy_library.pyindex d852c22..6c52943 100644--- a/freevideo_engine/comfy_library.py+++ b/freevideo_engine/comfy_library.py@@ -561,6 +561,34 @@ def register():# Estimation is advisory; installation and generation remain usable.return web.json_response({}, headers={'Cache-Control': 'no-store'})+ @server.routes.get('/freevideo/request-assets')+ async def request_assets(request):+ """What this request still needs downloaded; advisory and read-only."""+ from .comfy_bridge import installation+ from .request_assets import inspect+ query = request.query+ try:+ root, machine = installation()+ value = dict(width=int(query['width']), height=int(query['height']), seconds=float(query['seconds']),+ task=query.get('task', 't2va'), base_steps=int(query.get('base_steps', '8')),+ refine_steps=int(query.get('refine_steps', '3')), two_pass=query.get('two_pass', '1') == '1',+ enhance=query.get('enhance') == '1', loras=query.getall('lora', [])[:32])+ refs = []+ for item in query.getall('ref', [])[:32]:+ kind, _, name = item.partition(':')+ parts = Path(name).parts+ if kind in ('image', 'video', 'audio') and parts and not Path(name).is_absolute() and '..' not in parts:+ refs.append(dict(kind=kind, path=name))+ if refs:+ # The generation path's own classification decides the tables (audio track in a video).+ value.update(references=refs, media_base=folder_paths.get_input_directory())+ names = await asyncio.to_thread(folder_paths.get_filename_list, 'loras') if value['loras'] else None+ result = await asyncio.to_thread(inspect, root, machine, value, lora_names=names)+ return web.json_response(result, headers={'Cache-Control': 'no-store'})+ except (OSError, ValueError, TypeError, KeyError):+ # Advisory: generation still reports whatever it needs.+ return web.json_response({}, headers={'Cache-Control': 'no-store'})+@server.routes.get('/freevideo/library')async def library(request):try:diff --git a/freevideo_engine/request_assets.py b/freevideo_engine/request_assets.pynew file mode 100644index 0000000..6c9893a--- /dev/null+++ b/freevideo_engine/request_assets.py@@ -0,0 +1,90 @@+"""What one generation request still needs that setup did not install.++Read-only: nothing is downloaded, written, moved or hashed here, and the+network is not probed. The sources named are the ones the request's own+download would try first, from the same ordering and download settings.+"""+from pathlib import Path+++def _first_source(root, spec):+ """Id of the source the download would start with, or '' when unknown."""+ from . import network+ from .adaln_assets import _download_plan+ try:+ return network.model_urls(_download_plan(root), spec)[0][0]+ except (OSError, ValueError, KeyError, IndexError, TypeError):+ return ''+++def _sampling(root, machine, request):+ from . import sampling_assets+ from .geometry import geometry+ from .two_pass import plan, sampling_canvas+ task = request.get('task', 't2va')+ if request.get('references'):+ # Same rule as generation: a reference video with an audio track selects the audio tables.+ task = sampling_assets.engine_task({'references': request['references']}, request.get('media_base'))+ canvas = sampling_canvas(geometry(request['width'], request['height'], seconds=request['seconds']))[0]+ two_pass = bool(request.get('two_pass', True))+ sampled = plan(canvas, two_pass, task, base_steps=request.get('base_steps', 8),+ refine_steps=request.get('refine_steps', 3))+ rows = sampling_assets.pending(root, machine, sampled, task)+ items = []+ if rows:+ remote = rows[0]['table']['download']+ spec = dict(repo=remote['repo'], revision=remote['revision'],+ file=remote['prefix'] + '/' + rows[0]['row']['file'])+ items.append(dict(id='sampling', kind='sampling', files=len(rows),+ bytes=sum(r['row']['bytes'] for r in rows),+ source=_first_source(root, spec), action='auto'))+ return sampled, items+++def _upscaler(root, sampled):+ from . import two_pass+ if not sampled.get('enabled') or not sampled.get('upscaler_sha256'):+ return []+ try:+ path = two_pass.checkpoint_path()+ if path.is_file() and path.stat().st_size == two_pass.UPSCALER['bytes']:+ return []+ except OSError:+ pass+ spec = dict(repo=two_pass.UPSCALER['repo'], revision=two_pass.UPSCALER['revision'],+ file=two_pass.UPSCALER['file'])+ return [dict(id='upscaler', kind='upscaler', files=1, bytes=two_pass.UPSCALER['bytes'],+ source=_first_source(root, spec), action='auto')]+++def _prompt_vlm(root):+ from .prompt_vlm import assets+ if assets.ready(root):+ return []+ spec = assets.catalog()+ return [dict(id='prompt-vlm', kind='prompt-vlm', files=len(spec['files']),+ bytes=sum(row['bytes'] for row in spec['files']), source='', action='consent')]+++def inspect(root, machine, request, *, lora_names=None):+ """Missing items for one request, in the order generation would need them.++ request: width, height, seconds, task, base_steps, refine_steps, two_pass,+ enhance (the prompt will be rewritten by the local model), loras (names),+ references (kind/path rows; replace task) with media_base for relative paths.+ lora_names: the LoRA files that exist; None skips the LoRA check.+ Every item: id, kind, files, bytes, source (id of the source tried first,+ '' when not applicable) and action: 'auto' is fetched when Generate starts,+ 'consent' asks first, 'manual' means the user adds the file.+ """+ root = Path(root)+ sampled, items = _sampling(root, machine, request)+ items += _upscaler(root, sampled)+ if request.get('enhance'):+ items += _prompt_vlm(root)+ if lora_names is not None:+ absent = [name for name in dict.fromkeys(request.get('loras') or []) if name not in set(lora_names)]+ if absent:+ items.append(dict(id='lora', kind='lora', files=len(absent), bytes=0, source='',+ action='manual', names=absent[:8]))+ return dict(items=items, bytes=sum(item['bytes'] for item in items), ready=not items)diff --git a/freevideo_engine/sampling_assets.py b/freevideo_engine/sampling_assets.pyindex 1020391..2298857 100644--- a/freevideo_engine/sampling_assets.py+++ b/freevideo_engine/sampling_assets.py@@ -221,6 +221,50 @@ def retire_superseded(machine):return result+def select(manifest, sampling, task, catalog=None):+ """The published tables one request samples with; the single selection rule.++ prepare() fetches exactly these and pending() reports them without touching disk.+ """+ from . import adaln_assets as assets+ from .refine_schedule import COMMUNITY+ weights = assets.weight_identity(manifest)+ kind = 'i2va' if task in ('i2va', 'l2va', 'fl2va', 'ref2va') else task+ def needed(table):+ count = len(table['identity']['timesteps'])+ return (count == 3 and sampling.get('refine_schedule') == COMMUNITY if refinement(table)+ else count == sampling['base_steps'])+ return kind, [t for t in (tables() if catalog is None else catalog) if t.get('task') == kind+ and needed(t) and t['identity']['weights'] == weights]+++def pending(root, machine, sampling, task):+ """Read-only: table files this request would download. Nothing is written,+ moved or fetched; a file of the right size counts as present (prepare()+ hashes it once and downloads again if it does not match)."""+ from . import adaln_assets as assets+ cache = Path(machine['cache'])+ try:+ manifest = json.loads(io_path(cache / 'manifest.json').read_text(encoding='utf-8'))+ except (OSError, ValueError):+ return []+ _, selected = select(manifest, sampling, task)+ shared = cache_root(machine['model_root'])+ missing = []+ for table in selected:+ for row in table['files']:+ for folder in (cache, shared):+ path = assets.asset_path(folder, row['file'])+ try:+ if io_path(path).stat().st_size == row['bytes']:+ break+ except OSError:+ pass+ else:+ missing.append(dict(table=table, row=row))+ return missing++def prepare(root, machine, sampling, task, *, progress, interrupted=None, environ=None):"""Fetch only this request's missing tables before starting its timer."""from concurrent.futures import FIRST_EXCEPTION, ThreadPoolExecutor, wait@@ -228,20 +272,12 @@ def prepare(root, machine, sampling, task, *, progress, interrupted=None, enviroimport threadingfrom . import adaln_assets as assets, network, provisionfrom .monitoring import save- from .refine_schedule import COMMUNITYcache = Path(machine['cache'])if not (cache / 'manifest.json').is_file():return dict(seconds=0., downloaded_bytes=0) # Generation reports an invalid installation.manifest = json.loads((cache / 'manifest.json').read_text(encoding='utf-8'))- weights = assets.weight_identity(manifest)- kind = 'i2va' if task in ('i2va', 'l2va', 'fl2va', 'ref2va') else task- def needed(table):- count = len(table['identity']['timesteps'])- return (count == 3 and sampling.get('refine_schedule') == COMMUNITY if refinement(table)- else count == sampling['base_steps'])catalog = tables()- selected = [t for t in catalog if t.get('task') == kind- and needed(t) and t['identity']['weights'] == weights]+ kind, selected = select(manifest, sampling, task, catalog)root = Path(root)shared = cache_root(machine['model_root'])ledger = root / 'verified-models.json'diff --git a/web/health.js b/web/health.jsindex 82f1a2f..a9e07e7 100644--- a/web/health.js+++ b/web/health.js@@ -16,7 +16,7 @@ const launchVisit = query.get('freevideo') === 'launch';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', 'cast_mention.js', 'cast_overlay.js', 'cast_source.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',+ 'progress_connection.js', 'prompt_draft.js', 'prompt_enhance.js', 'prompt_references.js', 'prompt_terms.js', 'request_assets.js', 'report_issue.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','toolbar_position.js', 'updates.js', 'view_navigation.js', 'wordmark.js', 'cast_library.js'];const sleep = ms => new Promise(resolve => setTimeout(resolve, ms));diff --git a/web/request_assets.js b/web/request_assets.jsnew file mode 100644index 0000000..04eb682--- /dev/null+++ b/web/request_assets.js@@ -0,0 +1,76 @@+// One muted line above Generate: what this request will download first.+// LoRA file names this request would load, through the whole `previous` chain.+export function enabledLoras(start, {upstream, widget, value}) {+ const names = [];+ for (let current = start, depth = 0; current && depth < 16; current = upstream(current, 'previous'), depth++) {+ try {+ if (widget(current, 'adapters')) {+ for (const row of JSON.parse(value(current, 'adapters') || '[]')) {+ if (row.enabled !== false && Number(row.strength ?? 1) !== 0 && typeof row.name === 'string') names.push(row.name);+ }+ } else if (widget(current, 'lora')) {+ const name = value(current, 'lora');+ if (name && name !== 'None' && Number(value(current, 'strength') ?? 1) !== 0) names.push(name);+ }+ } catch {}+ }+ return names;+}++// Reference files as `kind:file`, so generation's own rule can tell whether a video has audio.+// A reference that is not a file in the input folder makes the task unknowable here: send none.+export function referenceFiles(refs) {+ return refs.length && refs.every(r => typeof r.file === 'string' && r.kind) ? refs.map(r => `${r.kind}:${r.file}`) : [];+}++// Keep the extension and the end of a long file name; shorten the middle.+const short = name => name.length <= 28 ? name+ : name.slice(0, 12) + '…' + name.slice(-15);++export function createRequestAssets({t, api, request, onError = () => {}}) {+ const element = document.createElement('div');+ element.className = 'fv-request-assets fv-muted';+ element.hidden = true;+ element.setAttribute('aria-live', 'polite');+ let timer = 0, controller = null, key = '', disposed = false;+ const size = bytes => bytes >= 2 ** 30 ? (bytes / 2 ** 30).toFixed(1) + ' GB' : Math.max(1, Math.round(bytes / 2 ** 20)) + ' MB';+ function lines(items) {+ const rows = [];+ // Tables and the upscaler are one download to the user.+ const auto = items.filter(item => item.action === 'auto').reduce((sum, item) => sum + item.bytes, 0);+ if (auto) rows.push(t(`Downloads ${size(auto)} before generating`, `生成前会先下载 ${size(auto)}`));+ for (const item of items) {+ if (item.kind === 'prompt-vlm') {+ rows.push(t(`First prompt rewrite downloads ${size(item.bytes)}`, `首次改写提示词会先下载 ${size(item.bytes)}`));+ } else if (item.kind === 'lora') {+ const names = (item.names || []).map(short);+ rows.push(t(`LoRA not found: ${names.join(', ')}`, `找不到 LoRA:${names.join('、')}`));+ }+ }+ return rows;+ }+ function show(items) {+ const rows = lines(items);+ element.replaceChildren(...rows.map(text => Object.assign(document.createElement('div'), {textContent: text})));+ element.hidden = rows.length === 0;+ }+ function refresh(force = false) {+ const query = request();+ if (!query) { show([]); return; }+ const next = query.toString();+ if (next === key && !force) return;+ key = next;+ clearTimeout(timer); controller?.abort();+ timer = setTimeout(async () => {+ const current = controller = new AbortController();+ try {+ const reply = await api.fetchApi('/freevideo/request-assets?' + next, {signal: current.signal});+ if (!reply.ok) return;+ const result = await reply.json();+ if (disposed || current.signal.aborted || key !== next) return;+ show(Array.isArray(result.items) ? result.items : []);+ } catch (error) { if (error?.name !== 'AbortError') onError(error); } // Advisory; never blocks Generate.+ }, 300);+ }+ return {element, refresh, dispose() { disposed = true; clearTimeout(timer); controller?.abort(); }};+}diff --git a/web/studio.css b/web/studio.cssindex 5f9c822..23d3269 100644--- a/web/studio.css+++ b/web/studio.css@@ -201,3 +201,4 @@.fv-studio .fv-chain-part-tag:empty{display:none}.fv-studio .fv-chain-part-tag[data-kind=error]{color:var(--fv-warning);white-space:normal;max-width:16em;text-align:right}@media(max-width:680px){.fv-studio .fv-chain-part{gap:8px;padding-left:4px}}+.fv-studio .fv-request-assets{font-size:12px;line-height:1.5;margin:0 0 8px}diff --git a/web/studio.js b/web/studio.jsindex fcf91b9..2c1a52d 100644--- a/web/studio.js+++ b/web/studio.js@@ -26,6 +26,7 @@ import { reconcileLoraTriggers } from './lora_triggers.js';import { createSamplingEffort } from './sampling_effort.js';import { resultActions, previewBadge, icon } from './result_actions.js';import { createPromptEnhancer } from './prompt_enhance.js';+import { createRequestAssets, enabledLoras, referenceFiles } from './request_assets.js';import { rememberPromptDraft, trackPromptDraft } from './prompt_draft.js';import { canvasDimensions, imageSizeSelection } from './studio_size.js';import { createCapabilityView } from './capability_view.js';@@ -562,16 +563,20 @@ export function openStudio(node, {extendFrom = null} = {}) {cleanup.push(() => { castLibrary?.destroy?.(); castLibrary = null; window.removeEventListener('freevideo-media', castChanged); prompt.removeEventListener('input', announceCast); castOverlay.dispose(); delete node.freevideoCastOff; });openCastLibrary({api, text: t, viewURL: view, uploadOne: castUpload, onChange: () => { castOverlay.refresh(); references.refresh(); }}).then(library => { if (disposed) library?.destroy?.(); else castLibrary = library; });+ let requestAssets = null;const enhancer = createPromptEnhancer({node, input: prompt, editor: promptEditor, api, t, starter,prepare: text => expandCast(text, mediaRows(node), {active: !extension.source}).text,onReport: row => { node.freevideoReportId = row.report_id; progress.updateReport(row); },- onChange: () => rememberPromptDraft(api, node),+ onChange: () => { rememberPromptDraft(api, node); requestAssets?.refresh(); },setText: text => { set(node, 'text', text || (untouched() ? starter : '')); placeholder(); }, context: () => {const items = referenceItems(node);if (linked(node, 'conditioning') || items.some(row => !row.file || row.kind !== 'image')) throw new Error('unsupported_media');return {seconds: Number(value(node, 'seconds')), media: items.map(row => ({file: row.file, role: row.role || 'reference'}))};}});cleanup.push(() => enhancer.dispose());+ requestAssets = createRequestAssets({t, api, request: () => requestAssetsQuery?.()});+ cleanup.push(() => requestAssets.dispose());+ let requestAssetsQuery = null;const promptChanged = e => { if (String(e.detail) === String(node.id)) { if (prompt.value !== shown(value(node, 'text'))) prompt.value = shown(value(node, 'text')); prompt.disabled = linked(node, 'text'); mention.disabled = prompt.disabled; placeholder(); castOverlay.refresh(); references.refresh(); announceCast(); enhancer.sync(); } };window.addEventListener('freevideo-reference-prompt', promptChanged);cleanup.push(() => window.removeEventListener('freevideo-reference-prompt', promptChanged));@@ -694,8 +699,8 @@ export function openStudio(node, {extendFrom = null} = {}) {else if (loraNode && widget(loraNode, 'lora')) {const select = el('select'); select.setAttribute('aria-label', t('LoRA model', 'LoRA 模型'));for (const name of widget(loraNode, 'lora').options?.values || ['None']) { const o = el('option', name); o.value = name; select.append(o); }- select.value = value(loraNode, 'lora'); select.onchange = () => set(loraNode, 'lora', select.value);- const strength = el('input'); strength.type = 'number'; strength.min = '-4'; strength.max = '4'; strength.step = '.05'; strength.value = value(loraNode, 'strength'); strength.onchange = () => { if (strength.reportValidity()) set(loraNode, 'strength', Number(strength.value)); };+ select.value = value(loraNode, 'lora'); select.onchange = () => { set(loraNode, 'lora', select.value); requestAssets?.refresh(); };+ const strength = el('input'); strength.type = 'number'; strength.min = '-4'; strength.max = '4'; strength.step = '.05'; strength.value = value(loraNode, 'strength'); strength.onchange = () => { if (strength.reportValidity()) { set(loraNode, 'strength', Number(strength.value)); requestAssets?.refresh(); } };loraMount.append(field(t('LoRA', 'LoRA'), select), field(t('Strength', '强度'), strength), el('p', loraWarning(), 'fv-lora-note'));} else loraMount.append(el('p', loraWarning(), 'fv-lora-note'));const [, advanced] = expand(t('Advanced', '高级选项'));@@ -835,9 +840,11 @@ export function openStudio(node, {extendFrom = null} = {}) {function refreshEffortEstimate(force = false) {capabilityView?.update();let task = 'external';+ let requestRefs = [];try {if (!linked(node, 'conditioning')) {const media = referenceItems(node), refs = media.filter(r => !r.role);+ requestRefs = refs;const audio = refs.some(r => r.kind === 'audio'), visual = refs.some(r => r.kind !== 'audio');const first = media.some(r => r.role === 'first'), last = media.some(r => r.role === 'last');task = audio ? visual ? 'ref2va_av' : 'ref2va_audio' : visual ? 'ref2va'@@ -852,6 +859,15 @@ export function openStudio(node, {extendFrom = null} = {}) {lengthControl?.refresh({width: requestWidth, height: requestHeight, task, adapters,settings: {tier: twoPass.checked ? 'light' : ({12: 'medium', 16: 'high', 20: 'max'}[Number(baseSteps.value)] || 'custom'),base_steps: Number(baseSteps.value), refine_steps: Number(refineSteps.value), two_pass: twoPass.checked}}, force);+ requestAssetsQuery = () => {+ const query = new URLSearchParams({width: requestWidth, height: requestHeight, seconds: value(node, 'seconds'), task,+ base_steps: baseSteps.value, refine_steps: refineSteps.value, two_pass: twoPass.checked ? '1' : '0',+ enhance: node.properties?.freevideo_prompt_versions?.enabled ? '1' : '0'});+ for (const name of enabledLoras(loraNode, {upstream, widget, value})) query.append('lora', name);+ for (const row of referenceFiles(requestRefs)) query.append('ref', row);+ return query;+ };+ requestAssets.refresh(force);const query = new URLSearchParams({width: requestWidth, height: requestHeight, seconds: value(node, 'seconds'), task, adapters: adapters ? '1' : '0'}).toString();if (query === effortEstimateKey && !force) { showEffortEstimate(); return; }clearTimeout(effortEstimateTimer);@@ -1176,7 +1192,7 @@ export function openStudio(node, {extendFrom = null} = {}) {finally { stopLoop.disabled = false; }}, 'fv-quiet');queueActions.append(queueDetails, cancelCurrent, stopLoop, resumeChain);- runbar.append(runrow, queueActions); controls.append(runbar);+ runbar.append(requestAssets.element, runrow, queueActions); controls.append(runbar);const queueError = error => ({queue_unavailable: t('Could not read the queue. Any loop has been stopped; already submitted videos stay queued.', '暂时无法读取队列。循环已停止追加,已提交的任务仍在队列中。'),cancel_failed: t('Could not cancel. Try again.', '暂时未能取消,请重试。'),