Skip to content

Make videos on the computer you already own. FreeVideo runs MiniMax H3 in as little as 8 GB of VRAM and 16 GB of RAM, and adapts its acceleration path to your hardware.

Keep failure reasons for full disks and unknown export errors

Bowen Xue1cd6d3a3b57c
diff --git a/freevideo_engine/agent/errors.py b/freevideo_engine/agent/errors.py
index b621f3e..77c55cb 100644
--- a/freevideo_engine/agent/errors.py
+++ b/freevideo_engine/agent/errors.py
@@ -132,6 +132,8 @@ IMAGE_REASONS = {
'显卡暂时用不了,稍后再试。'),
'worker_exit': ('Image generation stopped unexpectedly. Try again.', '图像生成意外停止了,请再试一次。'),
'timeout': ('This image took too long and was stopped. Try again.', '这一张用时太长,已停止。请再试一次。'),
+ 'disk_full': ('Saving the image failed: the disk is full. Free some space, then generate again.',
+ '保存图片时出错:磁盘空间不够,空出空间后再生成。'),
'generation_failed': ('Image generation ran into an error. Try again.', '图像生成出错了,请再试一次。'),
'invalid_media': ('The reference image could not be read. Choose another one.',
'参考图读不出来,请换一张。'),
@@ -149,7 +151,7 @@ def image_failure(code, report_id=None):
valid = isinstance(report_id, str) and re.fullmatch(r'[0-9a-f]{32}', report_id)
return dict(reason=dict(en=en, zh=zh), report_id=report_id if valid and code not in (
'busy', 'cancelled', 'invalid_request', 'invalid_media', 'invalid_prompt', 'invalid_dimensions',
- 'invalid_seed', 'too_many_images') else None)
+ 'invalid_seed', 'too_many_images', 'disk_full') else None)
# Recovery is a function of the committed task and phase, not just an error code.
@@ -172,6 +174,7 @@ IMAGE_ERRORS = {
'timeout': IMAGE_REASONS['timeout'][0],
'generation_failed': IMAGE_REASONS['generation_failed'][0],
'worker_exit': 'The image worker stopped before finishing this picture.',
+ 'disk_full': IMAGE_REASONS['disk_full'][0],
'cancelled': 'The picture job was cancelled.',
}
for _code, _message in IMAGE_ERRORS.items():
@@ -215,6 +218,8 @@ def recovery(code, *, kind=None, stage='request', resumable=True):
return SESSION_GONE[1]
if kind == 'image' and code == 'pack_missing':
return ERRORS[code][3]
+ if kind == 'image' and code == 'disk_full':
+ return 'Tell the user to free disk space, then submit the picture again with a new ref.'
if kind == 'image' and code == 'no_memory':
return 'Lower the picture dimensions or use fewer reference pictures, then submit with a new ref.'
if kind in RECOVERY and stage == 'terminal':
@@ -283,6 +288,7 @@ FAILURE_REASONS_ZH = {
'join_failed': '片段已生成,但拼接成片时出错',
'invalid_output': '生成的结果无法读取或保存',
'storage_unavailable': '任务记录或素材无法写入磁盘',
+ 'disk_full': '磁盘空间不够,图片没能保存',
'submit_interrupted': '提交生成时服务中断,尚未确认任务是否开始',
'timeout': '生成等了太久没有结果',
'invalid_media': '参考素材无法读取',
diff --git a/freevideo_engine/comfy_metadata.py b/freevideo_engine/comfy_metadata.py
index 00e052b..0abafdf 100644
--- a/freevideo_engine/comfy_metadata.py
+++ b/freevideo_engine/comfy_metadata.py
@@ -19,6 +19,11 @@ BACKFILL_MARKER = '.workflow-backfill.json'
BACKUP_NAME = 'video.before-workflow.mp4'
+def _room(path, size):
+ """A rewrite needs the copy and the backup beside the original, plus some headroom."""
+ return disk_space.free_bytes(path.parent) >= 2 * size + 512 * 1024 * 1024
+
+
def embed_comfy_metadata(path, *, prompt=None, workflow=None, backup=None):
"""Rewrite the MP4 at `path` with the graph in its metadata, copying the
streams. The new file replaces the original only after every audio and video
@@ -38,7 +43,7 @@ def embed_comfy_metadata(path, *, prompt=None, workflow=None, backup=None):
if backup is not None and backup.exists():
logging.info('FreeVideo left %s unchanged: %s already exists.', path, backup.name)
return False
- if disk_space.free_bytes(path.parent) < 2 * size + 512 * 1024 * 1024:
+ if not _room(path, size):
logging.info('FreeVideo left %s unchanged: not enough free disk space.', path)
return False
# faststart puts moov, and with it the metadata, before the media data.
@@ -147,7 +152,7 @@ def backfill(output_directory, *, stop=None):
rows.setdefault(json.loads(row.read_text(encoding='utf-8'))['id'], []).append(row)
except (OSError, ValueError, KeyError, TypeError):
continue
- counts = dict(embedded=0, skipped=0, pending=0, failed=0)
+ counts = dict(embedded=0, skipped=0, pending=0, failed=0, no_space=0)
for video in sorted(root.glob('*/*/video.mp4')):
if stop is not None and stop.is_set():
return counts
@@ -172,6 +177,11 @@ def backfill(output_directory, *, stop=None):
continue
if not embed_comfy_metadata(video, workflow=workflow, backup=run / BACKUP_NAME):
counts['failed'] += 1
+ # Space is checked after the attempt too: a write that ran out has already removed its copy.
+ try:
+ counts['no_space'] += not _room(video, video.stat().st_size)
+ except OSError:
+ pass
continue
counts['embedded'] += 1
# Keep saved results reusable: the index records each output's size and hash.
@@ -270,12 +280,12 @@ def register():
def run(output):
try:
- result = backfill(output) or dict(embedded=0, skipped=0, pending=0, failed=0)
+ result = backfill(output) or dict(embedded=0, skipped=0, pending=0, failed=0, no_space=0)
if result['embedded']:
logging.info('FreeVideo stored the workflow in %d earlier videos.', result['embedded'])
- except Exception:
+ except Exception as error:
logging.warning('FreeVideo could not store the workflow in earlier videos.', exc_info=True)
- result = dict(embedded=0, skipped=0, pending=0, failed=1)
+ result = dict(embedded=0, skipped=0, pending=0, failed=1, no_space=int(disk_space.ran_out(error)))
with _job_lock:
_job.update(state='done', result=result)
diff --git a/freevideo_engine/comfy_share.py b/freevideo_engine/comfy_share.py
index c887878..ac1b2ec 100644
--- a/freevideo_engine/comfy_share.py
+++ b/freevideo_engine/comfy_share.py
@@ -10,6 +10,7 @@ import base64
import hashlib
import io
import json
+import logging
import math
from pathlib import Path
import threading
@@ -212,7 +213,12 @@ def register():
try: await asyncio.shield(task)
except (InterruptedError, OSError): pass
raise
- except (ValueError, TypeError, OSError, InterruptedError):
+ except (ValueError, TypeError, OSError, InterruptedError) as error:
+ from .disk_space import ran_out
+ if ran_out(error):
+ raise web.HTTPInsufficientStorage(text='disk_full') from None
+ if not isinstance(error, InterruptedError):
+ logging.warning('FreeVideo sharing export failed.', exc_info=error)
raise web.HTTPBadRequest(text='Sharing export could not complete') from None
@server.routes.get('/freevideo/share/video')
diff --git a/freevideo_engine/disk_space.py b/freevideo_engine/disk_space.py
index ceaaf79..c9575eb 100644
--- a/freevideo_engine/disk_space.py
+++ b/freevideo_engine/disk_space.py
@@ -7,6 +7,7 @@ usage, which Apple recommends for downloads the user asked for. Volumes of
one APFS container share their space, so they are counted as one disk.
Other systems keep shutil.disk_usage, which matches Explorer and df.
"""
+import errno
import os
from pathlib import Path
import re
@@ -195,6 +196,18 @@ def free_bytes(path):
return shutil.disk_usage(io_path(existing(path))).free
+def ran_out(error):
+ """Whether a write failed because the disk (or the user's quota) is full, through wrapper exceptions."""
+ seen = set()
+ while error is not None and id(error) not in seen:
+ seen.add(id(error))
+ if isinstance(error, OSError) and (error.errno in (errno.ENOSPC, getattr(errno, 'EDQUOT', errno.ENOSPC))
+ or getattr(error, 'winerror', None) in (39, 112)):
+ return True
+ error = error.__cause__ or (None if error.__suppress_context__ else error.__context__)
+ return False
+
+
@plain_errors
def disk_key(path):
"""Paths with the same key draw on the same free space."""
diff --git a/freevideo_engine/editor_export.py b/freevideo_engine/editor_export.py
index 01e9519..d73cb8d 100644
--- a/freevideo_engine/editor_export.py
+++ b/freevideo_engine/editor_export.py
@@ -75,7 +75,8 @@ def _seam_call(operation, *args, **kwargs):
def _reason(error):
if isinstance(error, ExportError):
return error.reason
- if isinstance(error, OSError) and error.errno == errno.ENOSPC:
+ from .disk_space import ran_out
+ if ran_out(error):
return 'disk_full'
if isinstance(error, PermissionError) or isinstance(error, OSError) and error.errno in (errno.EACCES, errno.EROFS):
return 'not_writable'
@@ -1100,11 +1101,15 @@ class ExportQueue:
_checked_target(folder, self.root).rmdir()
except (OSError, ExportError):
pass
+ reason = _reason(error)
+ if reason == 'failed' and not isinstance(error, ExportCancelled):
+ # The page only says the export failed; the log keeps why for the diagnostic report.
+ logging.getLogger(__name__).error('Editor export failed.', exc_info=error)
with self.lock:
if isinstance(error, ExportCancelled) or job['stop'].is_set():
job.update(state='cancelled', reason=None)
else:
- job.update(state='failed', reason=_reason(error))
+ job.update(state='failed', reason=reason)
def register():
diff --git a/freevideo_engine/image_gen/failure.py b/freevideo_engine/image_gen/failure.py
index c7cde20..c2b738e 100644
--- a/freevideo_engine/image_gen/failure.py
+++ b/freevideo_engine/image_gen/failure.py
@@ -9,14 +9,16 @@ import time
import traceback
from .. import __version__
+from ..disk_space import ran_out
from ..exit_diagnostics import clean_reading, clean_sample
from ..failure_details import Redactor
ERRORS = frozenset(('no_memory', 'small_memory', 'busy_video', 'busy', 'pack_missing', 'model_unreadable',
- 'device_unavailable', 'worker_exit', 'timeout', 'cancelled',
+ 'device_unavailable', 'worker_exit', 'timeout', 'cancelled', 'disk_full',
'invalid_request', 'invalid_media', 'invalid_points', 'segment_not_installed', 'generation_failed'))
-NO_REPORT = frozenset(('small_memory', 'busy', 'invalid_request', 'invalid_media', 'invalid_points', 'segment_not_installed', 'cancelled'))
+NO_REPORT = frozenset(('small_memory', 'busy', 'invalid_request', 'invalid_media', 'invalid_points', 'segment_not_installed', 'cancelled',
+ 'disk_full'))
STAGES = ('start', 'load', 'text', 'encode', 'denoise', 'decode')
KINDS = ('generate', 'edit', 'cast', 'compose', 'download', 'install')
MESSAGE_ZH = {
@@ -29,6 +31,7 @@ MESSAGE_ZH = {
'device_unavailable': '显卡暂时用不了,稍后再试。',
'worker_exit': '图像生成意外停止了,请再试一次。',
'timeout': '这一张用时太长,已停止。请再试一次。',
+ 'disk_full': '保存图片时出错:磁盘空间不够,空出空间后再生成。',
'generation_failed': '图像生成出错了,请再试一次。',
'invalid_request': '图片设置有误,请调整后重试。',
'invalid_media': '图片无效,请重新选择输入目录中的图片。点选支持不超过 4096×4096 像素总数的图片。',
@@ -76,6 +79,8 @@ def classify_exception(error, *, stage='start', cancelled=False):
names = {cls.__name__ for cls in type(item).__mro__}
if isinstance(item, MemoryError) or 'OutOfMemoryError' in names or _MPS_MEMORY.search(str(item)):
return 'no_memory'
+ if chain and ran_out(chain[0]):
+ return 'disk_full'
for item in chain:
cuda_init = any(frame.f_globals.get('__name__') == 'torch.cuda'
and frame.f_code.co_name in ('_lazy_init', '_check_driver')
diff --git a/freevideo_engine/image_gen/service.py b/freevideo_engine/image_gen/service.py
index 6a0dcb6..1f70c92 100644
--- a/freevideo_engine/image_gen/service.py
+++ b/freevideo_engine/image_gen/service.py
@@ -606,8 +606,10 @@ class Service:
except FailureError as error:
self.discard_queued(error.status)
except Exception as error:
- # A previously valid reference may disappear while waiting.
- code = ('generation_failed' if str(error) in INVALID_ERRORS
+ # A previously valid reference may disappear while waiting; that keeps its
+ # own reason. Other settings were already checked, so a change there is a fault.
+ code = (str(error) if str(error) == 'invalid_media'
+ else 'generation_failed' if str(error) in INVALID_ERRORS
else classify_exception(error))
self.discard_queued(self.failed(code, pending['context'], error=error))
else:
diff --git a/web/image_generation.js b/web/image_generation.js
index bc72090..875a63e 100644
--- a/web/image_generation.js
+++ b/web/image_generation.js
@@ -164,6 +164,7 @@ export function imageGenError(code, info, t) {
device_unavailable: ['The graphics card is not available right now. Try again later.', '显卡暂时用不了,稍后再试。'],
worker_exit: ['Image generation stopped unexpectedly. Try again.', '图像生成意外停止了,请再试一次。'],
timeout: ['This image took too long and was stopped. Try again.', '这一张用时太长,已停止。请再试一次。'],
+ disk_full: ['Saving the image failed: the disk is full. Free some space, then generate again.', '保存图片时出错:磁盘空间不够,空出空间后再生成。'],
cancelled: ['Image generation was cancelled.', '已取消图像生成。'],
invalid_request: ['The image settings are invalid. Adjust them and try again.', '图片设置有误,请调整后重试。'],
invalid_media: ['The reference image cannot be read. Choose another image.', '参考图读不出来,请换一张图。'],
diff --git a/web/library.js b/web/library.js
index 159d37d..495455b 100644
--- a/web/library.js
+++ b/web/library.js
@@ -147,6 +147,9 @@ async function workflowBackfill(collection, t) {
? t('Drag them onto the canvas to restore their workflow. The originals are kept next to them as video.before-workflow.mp4.', '把它们拖到画布上可还原工作流。原视频保留在各自目录,文件名为 video.before-workflow.mp4。')
: t('Videos that could not be checked safely were left as they were.', '无法安全确认的视频都保持原样。');
if (result.failed) text.textContent += ' ' + t(`${result.failed} videos were left unchanged and will be offered again.`, `另有 ${result.failed} 个视频未改动,之后会再次提示。`);
+ const full = Math.min(Number.isSafeInteger(result.no_space) ? result.no_space : 0, result.failed || 0);
+ if (full > 0) text.textContent += ' ' + t(full === result.failed ? 'The disk is full. Free some space first.' : `${full} of them could not be changed because the disk is full. Free some space first.`,
+ full === result.failed ? '磁盘空间不够,请先空出空间。' : `其中 ${full} 个因磁盘空间不够,请先空出空间。`);
actions.replaceChildren(button(t('Got it', '知道了'), () => box.remove(), 'fv-quiet'));
}
if (value.state === 'running') { follow(); return; }
diff --git a/web/share.js b/web/share.js
index 7b66491..100a2df 100644
--- a/web/share.js
+++ b/web/share.js
@@ -159,6 +159,7 @@ export async function openShare(record,t){
const response=await api.fetchApi('/freevideo/share/video',{method:'POST',headers:{'Content-Type':'application/json'},signal:exportRequest.signal,
body:JSON.stringify({id,template,rect:shape.rect})});
if(response.status===409)throw Object.assign(new Error(t('Another export is running. Try again shortly.','已有分享视频正在导出,请稍后再试。')),{reportable:false});
+ if(response.status===507)throw Object.assign(new Error(t('Exporting the share video failed: the disk is full. Free some space, then export again.','导出分享视频时出错:磁盘空间不够,空出空间后再导出。')),{reportable:false});
if(!response.ok)throw new Error(t('Export could not complete. Try again.','分享视频导出未完成,请重试。'));
exported=await response.json();
}