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.
Let only a missing encoder stop the pre-encoding check
Bowen Xue1f96a89533d1
diff --git a/freevideo_engine/encode_worker.py b/freevideo_engine/encode_worker.pyindex a8c0c37..1ea774d 100644--- a/freevideo_engine/encode_worker.py+++ b/freevideo_engine/encode_worker.py@@ -8,59 +8,11 @@ import argparseimport jsonimport osfrom pathlib import Path-import statimport sysimport timefrom .monitoring import savefrom .processes import worker_signals--PACKAGE = Path(__file__).resolve().parent---def resolve_encoder(folder_paths, name):- files = json.loads((PACKAGE / 'model_files.json').read_text(encoding='utf-8'))- expected = next((row['bytes'] for row in files if row['file'] == 'text_encoders/' + name), None)- path = None- copies = {}- if expected is not None:- folders = folder_paths.get_folder_paths('text_encoders')- models_dir = getattr(folder_paths, 'models_dir', None)- if models_dir is not None:- models_dir = os.path.normcase(os.path.realpath(models_dir))- freevideo, bundled = [], []- # FreeVideo paths stay preferred after a resident worker registers them.- for folder in folders:- resolved = os.path.normcase(os.path.realpath(folder))- try:- in_models = os.path.commonpath([models_dir, resolved]) == models_dir- except ValueError:- in_models = False # Different Windows drives cannot share a model root.- (bundled if in_models else freevideo).append(folder)- folders = freevideo + bundled- for folder in folders:- candidate = os.path.realpath(os.path.join(folder, name))- if candidate in copies:- continue- try:- info = Path(candidate).stat()- except OSError:- continue- if not stat.S_ISREG(info.st_mode):- continue- copies[candidate] = info.st_size- if path is None and info.st_size == expected:- path = candidate- if path is None:- path = folder_paths.get_full_path_or_raise('text_encoders', name)- checkpoint = dict(state='read_only_mmap' if sys.platform == 'win32' else 'native_mmap',- bytes=Path(path).stat().st_size)- if expected is not None:- checkpoint.update(expected_bytes=expected, tested_size=checkpoint['bytes'] == expected)- selected = os.path.realpath(path)- mismatched = sum(size != expected for candidate, size in copies.items() if candidate != selected)- if mismatched:- checkpoint['mismatched_copies'] = mismatched- return path, checkpoint+from .encoder_checkpoint import resolve_encoderdef encoder_on_gpu(clip):diff --git a/freevideo_engine/encoder_checkpoint.py b/freevideo_engine/encoder_checkpoint.pyindex 0e9bf9e..90b6404 100644--- a/freevideo_engine/encoder_checkpoint.py+++ b/freevideo_engine/encoder_checkpoint.py@@ -3,12 +3,82 @@ import jsonimport mathimport mmapimport os+from pathlib import Path+import statimport structimport sysimport warningsimport weakref+PACKAGE = Path(__file__).resolve().parent+++def resolve_encoder(folder_paths, name):+ files = json.loads((PACKAGE / 'model_files.json').read_text(encoding='utf-8'))+ expected = next((row['bytes'] for row in files if row['file'] == 'text_encoders/' + name), None)+ path = None+ copies = {}+ if expected is not None:+ folders = folder_paths.get_folder_paths('text_encoders')+ models_dir = getattr(folder_paths, 'models_dir', None)+ if models_dir is not None:+ models_dir = os.path.normcase(os.path.realpath(models_dir))+ freevideo, bundled = [], []+ # FreeVideo paths stay preferred after a resident worker registers them.+ for folder in folders:+ resolved = os.path.normcase(os.path.realpath(folder))+ try:+ in_models = os.path.commonpath([models_dir, resolved]) == models_dir+ except ValueError:+ in_models = False # Different Windows drives cannot share a model root.+ (bundled if in_models else freevideo).append(folder)+ folders = freevideo + bundled+ for folder in folders:+ candidate = os.path.realpath(os.path.join(folder, name))+ if candidate in copies:+ continue+ try:+ info = Path(candidate).stat()+ except OSError:+ continue+ if not stat.S_ISREG(info.st_mode):+ continue+ copies[candidate] = info.st_size+ if path is None and info.st_size == expected:+ path = candidate+ if path is None:+ path = folder_paths.get_full_path_or_raise('text_encoders', name)+ checkpoint = dict(state='read_only_mmap' if sys.platform == 'win32' else 'native_mmap',+ bytes=Path(path).stat().st_size)+ if expected is not None:+ checkpoint.update(expected_bytes=expected, tested_size=checkpoint['bytes'] == expected)+ selected = os.path.realpath(path)+ mismatched = sum(size != expected for candidate, size in copies.items() if candidate != selected)+ if mismatched:+ checkpoint['mismatched_copies'] = mismatched+ return path, checkpoint+++def preflight_encoder(root, name, model_paths=None):+ """Use the worker's native path configuration without importing its tensor runtime."""+ previous = list(sys.path)+ sys.path.insert(0, str(Path(root).resolve()))+ try:+ import folder_paths+ from utils.extra_config import load_extra_path_config+ if model_paths:+ load_extra_path_config(str(model_paths))+ try:+ return resolve_encoder(folder_paths, name)+ except FileNotFoundError as error:+ raise FileNotFoundError(+ "ENCODER_MODEL_MISSING: Model in folder 'text_encoders' with filename '%s' not found. "+ 'Please repair the installation. 请修复安装。' % name) from error+ finally:+ sys.path[:] = previous++def read_only_state_dict(path, dtypes):"""Only for immutable inference weights; tensors retain their mapping.diff --git a/freevideo_engine/failure_details.py b/freevideo_engine/failure_details.pyindex 177a4e0..14b8531 100644--- a/freevideo_engine/failure_details.py+++ b/freevideo_engine/failure_details.py@@ -878,6 +878,11 @@ def _mac_run(report, run, redactor):return 'Run: ' + '; '.join(parts)+def missing_encoder(text):+ return re.search(r"ENCODER_MODEL_MISSING:|Model in folder ['\"]text_encoders['\"] "+ r"with filename ['\"][^\r\n]+?['\"] not found\.", text, re.I) is not None++def generation_failure(run, exit_code=None, *, repair=None):"""Surface the cause, including a child traceback, even without a report.@@ -967,11 +972,14 @@ def generation_failure(run, exit_code=None, *, repair=None):promoted = bool(causes) and causes[-1] not in knownif promoted:lines.insert(1, 'Cause: ' + causes[-1][:300])+ encoder_missing = missing_encoder('\n'.join(lines))+ if encoder_missing:+ lines.insert(1, 'ENCODER_MODEL_MISSING: The encoder model file is missing. ' + REPAIR_MARK)if len(lines) == 1:lines.append('The worker ended without a readable error report.')summary = _mac_run(report, run, redactor)if summary:- lines.insert(2 if promoted else 1, summary)+ lines.insert(1 + bool(promoted) + bool(encoder_missing), summary)lines.append('\nRetained outputs: ' + str(run))# The table failure can be in a retained child log rather than the report.# Keep its numeric metadata ahead of technical output for all interactive callers.@@ -983,9 +991,9 @@ def generation_failure(run, exit_code=None, *, repair=None):card = sampling_table_failure(marker)first, _, rest = value.partition('\n')value = '\n'.join((first, marker, card['title'], card['detail'], rest))- if explained:+ if explained or encoder_missing:from .runtime_libraries import REINSTALL- value = value.replace(REPAIR_MARK, repair or REINSTALL, 1)+ value = value.replace(REPAIR_MARK, repair or REINSTALL)value = re.sub(r'\x1b(?:\[[0-?]*[ -/]*[@-~]|\][^\x07\x1b]*(?:\x07|\x1b\\))', '', value)value = re.sub(r'[\x00-\x08\x0b-\x1f\x7f]', '', value)return valuediff --git a/freevideo_engine/generate.py b/freevideo_engine/generate.pyindex 3355497..2da7746 100644--- a/freevideo_engine/generate.py+++ b/freevideo_engine/generate.py@@ -20,6 +20,7 @@ from contextlib import nullcontextfrom .locking import runtime_lock, LOCK_ENVfrom .paths import vdn_root, comfy_rootfrom .monitoring import save+from .encoder_checkpoint import preflight_encoderfrom . import tuningfrom . import processesfrom .system import (inference_headroom, inference_memory_sample, inference_environment, memory_sample,@@ -800,6 +801,13 @@ def _run(args):for trimmed in cached.get('reference_trims') or []:print(json.dumps(dict(event='reference_trimmed', **trimmed)), flush=True)else:+ try:+ preflight_encoder(args.comfy_root or comfy_root(), args.encoder, encoding['model_paths'])+ except Exception as error:+ # Only a missing encoder stops the run; the worker stays the judge of anything else.+ if str(error).startswith('ENCODER_MODEL_MISSING:'):+ raise+ print(json.dumps(dict(event='encoder_preflight_skipped', error=repr(error)[:300])), flush=True)encoder_env = dict(env, PYTHONPATH=str(repo))print(json.dumps({'event': 'encoding_start'}), flush=True)encoder_attempt = history.begin(resource_identity, {'encoder': args.encoder},diff --git a/freevideo_engine/model_repair.py b/freevideo_engine/model_repair.pyindex c0b84f0..9738273 100644--- a/freevideo_engine/model_repair.py+++ b/freevideo_engine/model_repair.py@@ -242,3 +242,18 @@ def retain(root, path, approved):del values[str(path)]save(Path(root) / 'logs/model-mismatches.json', values)return target+++def restore(root, path, retained, approved, prior=None):+ """Undo retention after a failed download, preserving any newly present target."""+ if os.path.lexists(path):+ return+ check(retained, approved)+ try:+ rename_noreplace(retained, path)+ except FileExistsError:+ return+ if prior is not None and same_identity(identity(path), prior):+ values = read(root)+ values[str(path)] = prior+ save(Path(root) / 'logs/model-mismatches.json', values)diff --git a/freevideo_engine/provision.py b/freevideo_engine/provision.pyindex 86d6d0b..ac65ae4 100644--- a/freevideo_engine/provision.py+++ b/freevideo_engine/provision.py@@ -61,6 +61,20 @@ def verified(path, row, stamps, *, mode='auto', hf_directory=None, producer_recedef models(plan):+ retained = []+ try:+ _models(plan, retained)+ except BaseException as error:+ # All download/verifier threads have stopped before names are restored.+ for root, path, kept, approved, prior in reversed(retained):+ try:+ model_repair.restore(root, path, kept, approved, prior)+ except (OSError, ValueError) as rollback_error:+ error.add_note('Could not restore retained model %s: %s' % (path, rollback_error))+ raise+++def _models(plan, retained):# Use the same canonical spelling as compact_sources/ownership, including# Windows 8.3 temporary-directory aliases. Keep managed_model's link and# ownership checks intact; a different spelling must not lose the receipt.@@ -109,9 +123,11 @@ def models(plan):from .install_disk import check_modelscheck_models(local_files + missing, replacements=replacements)for name, approved in replacements.items():- retained = model_repair.retain(root, Path(name), approved)+ prior = model_repair.read(root).get(name)+ kept = model_repair.retain(root, Path(name), approved)+ retained.append((root, Path(name), kept, approved, prior))stamps.pop(name, None)- emit('model_retained', file=name, keep_as=approved['keep_as'], retained=str(retained), bytes=approved['bytes'])+ emit('model_retained', file=name, keep_as=approved['keep_as'], retained=str(kept), bytes=approved['bytes'])stopped = threading.Event()failures = []ready = [0]@@ -474,9 +490,10 @@ def prefetch(plan, out):"""Fetch the prepared format an installation is about to switch to, beside the one in use.Generation keeps running on the installed model: only the setup lease is- held (no concurrent setup run), machine.json and prepared-cache.json are- not touched, and nothing is removed. The setup run that switches afterwards- finds every file present and verified.+ held (no concurrent setup run). A shared encoder replacement clears readiness+ while it runs and restores it once it ends with the files back in place;+ otherwise machine.json and prepared-cache.json are not touched.+ The setup run that switches afterwards finds every file present and verified."""from .prepared_model import files as prepared_filesroot = Path(plan['root']).expanduser().resolve()@@ -489,7 +506,24 @@ def prefetch(plan, out):if Path(machine['cache']).resolve() == Path(prepared['cache']).resolve():raise ValueError('This prepared model is already in use')with runtime_lock(root / 'setup.lock', inherit=False):- models(plan)+ encoder_repair = any(Path(row['path']).resolve().is_relative_to(Path(plan['encoder_dir']).resolve())+ for row in plan.get('replace_models', []))+ def readiness(value):+ # Change only the flag: the file may have been updated since it was read.+ current = json.loads((root / 'machine.json').read_text(encoding='utf-8'))+ save(root / 'machine.json', dict(current, ready=value))+ if encoder_repair:+ readiness(False)+ try:+ models(plan)+ except BaseException as error:+ # models() restored every retained file unless it says otherwise.+ if encoder_repair and not any(note.startswith('Could not restore')+ for note in getattr(error, '__notes__', ())):+ readiness(True)+ raise+ if encoder_repair:+ readiness(True)directory = Path(prepared['directory'])rows = prepared_files(prepared)present = [row for row in rows if (directory / row['file']).is_file()diff --git a/web/error_panel.js b/web/error_panel.jsindex c3cd3f2..ac8efa2 100644--- a/web/error_panel.js+++ b/web/error_panel.js@@ -415,7 +415,8 @@ export function failureAdvice(value, t, known = knownError(value)) {return row('output-folder', ['The output folder cannot be written to', '输出目录不可写'],['The video could not be saved.', '视频没能保存。'],['Check that the output folder can be written to, then retry.', '请检查输出文件夹的写入权限后重试。']);- if (/manifest\.json/i.test(text) && /No such file|FileNotFoundError|\[Errno 2\]/i.test(text))+ if (/ENCODER_MODEL_MISSING:|Model in folder ['"]text_encoders['"] with filename ['"][^\r\n]+?['"] not found\./i.test(text)+ || /manifest\.json/i.test(text) && /No such file|FileNotFoundError|\[Errno 2\]/i.test(text))return row('model-files', ['The model is not fully installed', '模型没有装全'],['Some of the model files FreeVideo needs are missing.', 'FreeVideo 需要的部分模型文件缺失。'],repairAction());