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.

Third-party downloads list only the files this computer needs

Bowen Xue17f12c21c284
diff --git a/freevideo_engine/bootstrap.py b/freevideo_engine/bootstrap.py
index e36988f..ead734a 100644
--- a/freevideo_engine/bootstrap.py
+++ b/freevideo_engine/bootstrap.py
@@ -354,6 +354,18 @@ def model_target(row, model_dir, encoder_dir, prepared_dir=None):
return (model_dir if row['repo'].startswith('OpenVDN/') else encoder_dir) / row['file']
+def installation_model_files(prepared, reuse_cache, sampling_caches):
+ """The file selection shared by planning and provisioning."""
+ from . import prepared_model
+ from .sampling_assets import install_files, usable_with
+ files = list(required_models(json.loads((PACKAGE / 'model_files.json').read_text(encoding='utf-8')),
+ reuse_cache or prepared))
+ files += prepared_model.files(prepared)
+ if prepared or (reuse_cache and usable_with(reuse_cache)):
+ files += install_files(bool(sampling_caches))
+ return files
+
+
def resolve_prepared_format(requested, saved, hardware):
"""The prepared model format of this setup run: 'int8_convrot' or 'fp8'.
@@ -530,18 +542,13 @@ def plan(args, *, local_progress=None, stage=None):
prepared_dir = prepared['directory'] if prepared else None
if mac_target and reuse_cache is None and prepared is None:
errors.append('No verified native-compatible prepared model is available. Source conversion is not supported on Mac.')
- files = required_models(json.loads((PACKAGE / 'model_files.json').read_text(encoding='utf-8')), reuse_cache or prepared)
- files += prepared_model.files(prepared)
# New installations prepare every quality level; an existing one keeps its
# earlier choice (off if it predates the option) unless the flag says otherwise.
sampling_caches = getattr(args, 'sampling_caches', None)
if sampling_caches is None:
sampling_caches = prior['sampling_caches'] if isinstance(prior.get('sampling_caches'), bool) else not saved.get('ready')
sampling_caches = bool(sampling_caches)
- from .sampling_assets import install_files, usable_with
- if prepared or (reuse_cache and usable_with(reuse_cache)):
- # Published tables match these weights; other caches compute their own.
- files += install_files(sampling_caches)
+ files = installation_model_files(prepared, reuse_cache, sampling_caches)
local_reuse = None
local_folder = getattr(args, 'reuse_models', None)
local_manifest = getattr(args, 'reuse_models_manifest', None)
@@ -559,9 +566,19 @@ def plan(args, *, local_progress=None, stage=None):
if not isinstance(libraries, dict) or libraries.get('version') != 1 or not isinstance(libraries.get('roots'), list):
raise ValueError('Invalid model library manifest')
directories = ([str(local_folder)] if local_folder else []) + libraries['roots']
- local_reuse = scan_many(directories, needed, prior=previous_reuse, callback=local_progress)
+ scan_library = lambda: scan_many(directories, needed, prior=previous_reuse, callback=local_progress)
else:
- local_reuse = scan(local_folder, needed, prior=previous_reuse, callback=local_progress)
+ scan_library = lambda: scan(local_folder, needed, prior=previous_reuse, callback=local_progress)
+ try:
+ local_reuse = scan_library()
+ except OSError as error:
+ if not getattr(args, 'download_list', False):
+ raise
+ from .model_guidance import DownloadListError
+ original = str(error)
+ if error.__cause__ is not None:
+ original += '\n' + str(error.__cause__)
+ raise DownloadListError('read', original_error=original) from error
local_reuse['copy_mode'] = bool(getattr(args, 'copy_existing_models', False))
local_reuse['copy_bytes'] = local_reuse['linked_bytes'] = 0
for row in needed:
@@ -577,18 +594,27 @@ def plan(args, *, local_progress=None, stage=None):
mismatches = model_repair.read(root)
replace_models = []
reserved = set()
+ check_download_list = bool(getattr(args, 'download_list', False))
+ stamps_path = root / 'verified-models.json'
+ stamps = json.loads(stamps_path.read_text(encoding='utf-8')) if check_download_list and stamps_path.is_file() else {}
for row in files:
path = model_target(row, model_dir, encoder_dir, prepared_dir)
replacement = model_repair.replacement(path, row, mismatches, reserved)
if replacement:
replace_models.append(replacement)
size_matches = not replacement and path.is_file() and path.stat().st_size == row['bytes']
+ if size_matches and check_download_list:
+ # Only the explicit third-party list needs this check during planning.
+ # Normal setup keeps its cheap estimate and deferred verification.
+ from .provision import verified
+ hf_directory = Path(prepared_dir) if row.get('prepared') else model_dir if row['repo'].startswith('OpenVDN/') else encoder_dir
+ size_matches = verified(path, row, stamps, mode=getattr(args, 'verify', 'auto'), hf_directory=hf_directory)
present += row['bytes'] if size_matches else 0
device = existing_parent(path.parent)
entry = groups.setdefault(str(device), {'path': str(device), 'needed_bytes': 0,
'free_bytes': disk_space.free_bytes(device)})
local = (local_reuse or {}).get('matches', {}).get(row['repo'] + '/' + row['file'])
- model_entries.append((row, 'found' if size_matches else 'verified' if local else 'download'))
+ model_entries.append((row, ('verified' if check_download_list else 'found') if size_matches else 'verified' if local else 'download'))
entry['needed_bytes'] += 0 if size_matches or local and local['method'] == 'hardlink' else row['bytes']
partial = path.with_suffix(path.suffix + '.partial')
if not size_matches and not local and partial.is_file() and partial.stat().st_size <= row['bytes']:
@@ -717,6 +743,9 @@ def plan(args, *, local_progress=None, stage=None):
'licenses': ['https://huggingface.co/OpenVDN/vdn-minimax-h3/blob/751739ee5b9e3ac802dca5d5111075fdaeb47885/LICENSE',
'https://huggingface.co/t8star/Vdn-Minimax-H3-Comfy',
'https://docs.nvidia.com/cuda/eula/index.html']}
+ from .model_guidance import download_files
+ value['download_files'] = download_files(model_entries)
+ value['download_files_verified'] = all(status != 'found' for _, status in model_entries)
if mac_target:
from .macos_bootstrap import describe_plan
describe_plan(value)
@@ -2081,6 +2110,7 @@ def run_main(argv, shown):
parser.add_argument('--model-downloader', choices=['auto', 'xet'], default='auto',
help='xet: require official HF Xet for large weights; no ModelScope/HTTP fallback. Small configs use HTTP; existing files/partials retained')
parser.add_argument('--plan', '--check', action='store_true', help='Read-only preflight with small network samples; no installation files are written')
+ parser.add_argument('--download-list', action='store_true', help='Verify existing managed files while planning a third-party download list')
parser.add_argument('--json', action='store_true', help='Print preflight as JSON')
parser.add_argument('--plain', action='store_true', help='Disable live terminal rendering; append readable log lines')
parser.add_argument('--verbose', action='store_true', help='Show full setup details, license links and per-step log paths')
@@ -2118,7 +2148,11 @@ def run_main(argv, shown):
stage=None if args.plan else lambda *step: prepare_step(ui, *step))
except (OSError, RuntimeError, ValueError, subprocess.CalledProcessError) as error:
prepare_end(ui, False)
- print('Preflight failed: ' + str(error), file=sys.stderr)
+ from .model_guidance import DownloadListError
+ if isinstance(error, DownloadListError):
+ print('Download list error: ' + error.key, file=sys.stderr)
+ print('Preflight failed: ' + (error.original_error if isinstance(error, DownloadListError) else str(error)),
+ file=sys.stderr)
return 1
print(json.dumps(value, indent=2)) if args.json else display(value, ui, verbose=args.verbose)
if args.plan:
diff --git a/freevideo_engine/comfy_launcher_runtime.py b/freevideo_engine/comfy_launcher_runtime.py
index 03c9418..7cefc0e 100644
--- a/freevideo_engine/comfy_launcher_runtime.py
+++ b/freevideo_engine/comfy_launcher_runtime.py
@@ -958,7 +958,11 @@ class Controller:
self.selection = dict(descriptor, engine=str(engine), source=str(source), url=url, ready=ready,
repair_comfy=repair_comfy, lan_access=values.get('lan_access') is True)
self.state = dict(self.state, selection=dict(self.selection), host=host)
- if not ready:
+ # Third-party downloads (manual models, no offline packages) are checked
+ # file by file, so files the user downloaded are found on a ready engine too.
+ checked = bool(values.get('download_list') or (
+ values.get('model_method') == 'manual' and not values.get('offline_models')))
+ if not ready or checked:
extra = values.get('model_dirs', [])
if not isinstance(extra, list) or any(not isinstance(p, str) for p in extra):
raise ValueError('Model folders must be a list of directory paths')
@@ -968,10 +972,19 @@ class Controller:
extra = [p for p in dict.fromkeys(extra) if p.strip() and io_path(Path(p).expanduser()).is_dir()]
self.setup.inspect(dict(root=str(engine), extra_libraries=extra, copy=False,
sampling_caches=bool(values.get('sampling_caches')), prepared_format=values.get('prepared_format'),
+ **({'download_list': True} if checked else {}),
frontend=dict(root=descriptor['root'], separate=descriptor['separate'], download=fresh,
repair_python=host['python'] if repair_comfy else None)))
row = self._wait_setup()
self.state = dict(self.state, plan=row['plan'])
+ # A ready receipt covers the engine, not every model file: when the
+ # file-by-file check finds models to place or download, accepting the
+ # plan prepares them before connecting.
+ plan = row['plan']
+ if ready and checked and (
+ plan.get('download_files') or (plan.get('local_models') or {}).get('matches')):
+ self.selection = dict(self.selection, ready=False)
+ self.state = dict(self.state, selection=dict(self.selection))
extra_disk, disks, disk_errors = disk_review(self.state.get('plan', {}), engine, descriptor['root'],
separate=descriptor['separate'], new_comfy=fresh and not io_path(descriptor['root']).exists())
errors = list(self.state.get('plan', {}).get('errors', []))
diff --git a/freevideo_engine/comfy_setup.py b/freevideo_engine/comfy_setup.py
index 9e881cc..77f9104 100644
--- a/freevideo_engine/comfy_setup.py
+++ b/freevideo_engine/comfy_setup.py
@@ -277,6 +277,8 @@ class Setup:
arguments += ['--prepared-format', value['prepared_format']]
if value.get('copy'):
arguments.append('--copy-existing-models')
+ if value.get('download_list'):
+ arguments.append('--download-list')
self.selection = dict(root=str(root), arguments=arguments)
self.plan = None
self.state = dict(status='running', action='plan', libraries=libraries)
diff --git a/freevideo_engine/failure_details.py b/freevideo_engine/failure_details.py
index c9f18d9..455eabf 100644
--- a/freevideo_engine/failure_details.py
+++ b/freevideo_engine/failure_details.py
@@ -9,6 +9,68 @@ from .diagnostics import Redactor
STEP_OUTPUT = '\n\nFull step output:\n'
+QUALITY_LEVELS = (('Light', '轻量'), ('Medium', '标准'), ('High', '精细'), ('Max', '极致'))
+
+
+def sampling_table_details(value):
+ """Read the worker's bounded, numeric sampling-table failure metadata."""
+ from .sampling_assets import UNAVAILABLE
+ for match in re.finditer(r'^(?:(?:[\w.]*(?:Error|Exception)|(?:[\w.]+\.)?SamplingTableUnavailable):\s*)?'
+ + re.escape(UNAVAILABLE) + r'(\{[^\n]*\})$',
+ str(value)[:65536], re.M):
+ try:
+ details = json.loads(match[1])
+ if (type(details['base_steps']) is int and 1 <= details['base_steps'] <= 32
+ and type(details['two_pass']) is bool
+ and type(details['refine_steps']) is int and 0 <= details['refine_steps'] <= 31
+ and type(details['missing_bytes']) is int and details['missing_bytes'] > 0
+ and type(details['decimal_sizes']) is bool and isinstance(details['available'], list)
+ and all(type(i) is int and 0 <= i <= 3 for i in details['available'])):
+ return {key: details[key] for key in
+ ('base_steps', 'two_pass', 'refine_steps', 'missing_bytes', 'available', 'decimal_sizes')}
+ except (ValueError, KeyError, TypeError):
+ pass
+ return None
+
+
+def sampling_table_failure(value, *, zh=False):
+ details = sampling_table_details(value)
+ if details is None:
+ return None
+ from .launcher_copy import size_text
+ language = 1 if zh else 0
+ index = next((i for i, steps in enumerate((8, 12, 16, 20))
+ if details['base_steps'] == steps and details['two_pass'] == (i == 0)
+ and (i != 0 or details['refine_steps'] == 3)), None)
+ names = [('“%s”' if zh else '%s') % QUALITY_LEVELS[i][language] for i in sorted(set(details['available']))]
+ available = ''
+ if names:
+ available = names[0] if len(names) == 1 else ('、' if zh else ', ').join(names[:-1]) + ('或' if zh else ' or ') + names[-1]
+ size = size_text(details['missing_bytes'], details['decimal_sizes'])
+ # A custom step count is not a quality level (Iris): no "档" / "quality level" for it.
+ if zh:
+ if index is None:
+ title = '“自定义(%d 步)”的采样表还没有下载' % details['base_steps']
+ what = '这个步数的采样表'
+ else:
+ title = '“%s”档的采样表还没有下载' % QUALITY_LEVELS[index][1]
+ what = '这一档的采样表'
+ detail = ('这次生成需要先下载%s(约 %s),但这次没能下载。'
+ '请确认网络连接后再生成一次,FreeVideo 会自动下载。') % (what, size)
+ if available:
+ detail += '也可以改用已经可以使用的%s档。' % available
+ else:
+ if index is None:
+ title = 'The sampling table for Custom (%d steps) is not downloaded yet' % details['base_steps']
+ what = 'the sampling table for this step count'
+ else:
+ title = "The %s quality level's sampling table is not downloaded yet" % QUALITY_LEVELS[index][0]
+ what = "that level's sampling table"
+ detail = ('This video first needs %s (about %s), and it could not be downloaded this time. '
+ 'Check the network connection and generate again; FreeVideo downloads it automatically.') % (what, size)
+ if available:
+ detail += ' You can also switch to a quality level that is already available: %s.' % available
+ return dict(kind='sampling-table', title=title, detail=detail, action='')
def redacted_launcher_error(value, replacements=()):
@@ -320,6 +382,9 @@ def launcher_failure(value, *, zh=False, other_disk=False, disk_name='', can_rep
return dict(title='GPU 检查未通过' if zh else 'GPU validation failed', detail=detail,
action='展开详情或导出报告,查看完整检查结果。' if zh else
'Open the details or export the report for the complete results.', kind='kernels')
+ if 'Download list error: read' in text.splitlines():
+ from .model_guidance import DOWNLOAD_COPY
+ return dict(title=DOWNLOAD_COPY['error_read'][zh], detail='', action='', kind='download-list-read')
rules = (
(r'The previous video has no usable continuation data', 'continuation-missing',
('This video cannot be continued', '这个视频暂时不能接续'),
@@ -578,7 +643,16 @@ def generation_failure(run, exit_code=None, *, repair=None):
if len(lines) == 1:
lines.append('The worker ended without a readable error report.')
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.
+ sampling = sampling_table_details('\n'.join(lines))
value = redactor.text('\n'.join(lines))
+ if sampling:
+ from .sampling_assets import UNAVAILABLE
+ marker = UNAVAILABLE + json.dumps(sampling, separators=(',', ':'))
+ card = sampling_table_failure(marker)
+ first, _, rest = value.partition('\n')
+ value = '\n'.join((first, marker, card['title'], card['detail'], rest))
if explained:
from .runtime_libraries import REINSTALL
value = value.replace(REPAIR_MARK, repair or REINSTALL, 1)
diff --git a/freevideo_engine/launcher/Main.qml b/freevideo_engine/launcher/Main.qml
index 1d05b04..22495fb 100644
--- a/freevideo_engine/launcher/Main.qml
+++ b/freevideo_engine/launcher/Main.qml
@@ -9,6 +9,9 @@ ApplicationWindow {
color: unifiedChrome ? theme.canvas : theme.bg
width: 1280; height: 860
property var s: initialState
+ readonly property var downloads: backend.downloadList
+ // Keep expansion by family across language changes and new checked lists.
+ property var downloadExpanded: ({})
Connections { target: backend; function onChanged() { win.s = backend.state } }
property bool settingsOpen: false
property bool terminalOpen: false
@@ -29,7 +32,7 @@ ApplicationWindow {
property string previousReview: ""
property bool compact: width < 1000
property bool shortWindow: height < 700
- property bool otherModelLinksOpen: false
+ onModelInfoOpenChanged: if (modelInfoOpen) backend.prepareDownloadList()
readonly property bool manualEnvironment: s.offline.runtime_supported !== false && s.form.new_comfy && s.form.environment_method === "manual"
readonly property bool usingRuntime: manualEnvironment && s.offline.runtime
readonly property bool needsRuntime: s.page === "comfy" && manualEnvironment && !s.offline.runtime
@@ -597,19 +600,7 @@ ApplicationWindow {
delegate: FButton { required property var modelData; required property int index; objectName: "offlineShare-" + index; text: t("Download from Quark ↗", "打开夸克网盘 ↗"); onClicked: backend.link(modelData.url) }
}
FText { objectName: "offlinePackageGuide"; text: s.offline.guide; color: theme.muted; font.pixelSize: theme.micro; Layout.fillWidth: true }
- FButton { objectName: "otherModelLinks"; text: t("Alternative download sources", "其他下载渠道") + (otherModelLinksOpen ? " −" : " +"); flat: true; implicitHeight: theme.heightSm - 2; leftPadding: 0; font.pixelSize: theme.micro + 1; onClicked: otherModelLinksOpen = !otherModelLinksOpen }
- FText { visible: otherModelLinksOpen; text: t("The same models are also available from Hugging Face or ModelScope.", "同一套模型,也可从 Hugging Face 或魔搭下载。"); color: theme.muted; font.pixelSize: theme.micro; Layout.fillWidth: true }
- Flow {
- visible: otherModelLinksOpen; Layout.fillWidth: true; spacing: 8
- Repeater {
- model: ["video", "encoder", "decoder"]
- delegate: FButton {
- required property string modelData
- text: modelData === "video" ? t("Video model ↗", "视频模型 ↗") : modelData === "encoder" ? t("Text encoder ↗", "文本编码器 ↗") : t("Video & audio decoders ↗", "音视频解码器 ↗")
- implicitHeight: theme.heightSm; font.pixelSize: theme.micro + 1; onClicked: { modelInfo = modelData; modelInfoOpen = true }
- }
- }
- }
+ FButton { objectName: "otherModelLinks"; text: downloads.copy.title + " ›"; flat: true; enabled: !s.busy; implicitHeight: theme.heightSm; leftPadding: 0; font.pixelSize: theme.micro + 1; onClicked: modelInfoOpen = true }
}
ColumnLayout {
Layout.fillWidth: true; Layout.preferredWidth: 1; Layout.alignment: Qt.AlignTop; spacing: 10
@@ -635,7 +626,7 @@ ApplicationWindow {
FText { visible: !!s.offline.detail; text: s.offline.detail + (number(s.offline.total) ? " · " + bytes(s.offline.done) + " / " + bytes(s.offline.total) : ""); color: theme.muted; font.pixelSize: theme.micro; Layout.fillWidth: true }
}
FCard {
- visible: !usingRuntime; Layout.fillWidth: true; padding: 16
+ visible: !manualEnvironment && !offlineSelected; Layout.fillWidth: true; padding: 16
FSwitch {
objectName: "samplingCaches"; Layout.fillWidth: true
text: t("Prepare all quality levels", "提前下载全部质量档位")
@@ -740,7 +731,7 @@ ApplicationWindow {
}
// What this group downloads, as in the plan; nothing for one already here.
FText { objectName: "modelSize-" + modelData.id; visible: modelData.download > 0; text: bytes(modelData.download); font.pixelSize: theme.micro; color: theme.muted; font.features: { "tnum": 1 } }
- FButton { text: t("Download links ↗", "下载地址 ↗"); implicitHeight: theme.heightSm; flat: true; font.pixelSize: theme.micro + 1; visible: s.form.model_method === "manual"; onClicked: { modelInfo = modelData.id === "text" ? "encoder" : modelData.id; modelInfoOpen = true } }
+ FButton { objectName: "modelFiles-" + modelData.id; text: downloads.copy.title + " ›"; implicitHeight: theme.heightSm; flat: true; font.pixelSize: theme.micro + 1; visible: s.form.model_method === "manual"; onClicked: modelInfoOpen = true }
}
}
}
@@ -1278,25 +1269,111 @@ ApplicationWindow {
FPopup {
id: modelDialog; objectName: "modelDialog"
visible: modelInfoOpen; onClosed: modelInfoOpen = false
- width: Math.min(540, win.width-50)
- height: Math.min(modelContents.implicitHeight + padding*2, win.height-48)
- contentItem: ScrollView {
- id: modelScroll; clip: true; contentWidth: availableWidth
- ColumnLayout {
- id: modelContents; width: modelScroll.availableWidth
- spacing: 12
- FText { text: t("Download models", "下载模型"); font.pixelSize: theme.section + 2; font.weight: Font.DemiBold }
- FText { objectName: "videoModelGuide"; text: modelInfo === "video" ? s.video_model_guide : modelInfo === "decoder" ? t("Download the vae and audio_vae folders.", "下载 vae 和 audio_vae 文件夹。") : t("Download the text encoder to your model folder.", "下载文本编码器,放入模型目录。"); color: theme.muted; Layout.fillWidth: true; Layout.bottomMargin: 4 }
- Repeater { model: modelLinks[modelInfo]; delegate: FButton { required property var modelData; required property int index; objectName: "modelLink-" + index; text: t(modelData.label, modelData.label_zh) + " ↗"; Layout.fillWidth: true; onClicked: backend.link(modelData.url) } }
- Repeater { model: cloudLinks; delegate: FButton { required property var modelData; text: t("Quark · ", "夸克 · ") + modelData.label + " ↗"; Layout.fillWidth: true; onClicked: backend.link(modelData.url) } }
- FText { text: t("When your download finishes, import a FreeVideo ZIP or choose the folder containing your models.", "下载完成后,导入 FreeVideo ZIP 或选择存放模型的文件夹。"); color: theme.muted; font.pixelSize: theme.micro; Layout.fillWidth: true; Layout.topMargin: 6 }
+ width: Math.min(940, win.width-50)
+ readonly property real maximumHeight: Math.min(680, win.height-48)
+ implicitHeight: Math.min(maximumHeight, modelContent.implicitHeight + topPadding + bottomPadding)
+ contentItem: ColumnLayout {
+ id: modelContent; spacing: 12
+ ScrollView {
+ id: modelScroll; objectName: "downloadListScroll"
+ Layout.fillWidth: true; Layout.fillHeight: true; Layout.minimumWidth: 0; Layout.minimumHeight: 0
+ implicitHeight: downloadBody.implicitHeight
+ clip: true; contentWidth: availableWidth
+ ColumnLayout {
+ id: downloadBody; width: modelScroll.availableWidth; spacing: 12
+ FText { text: downloads.copy.title; font.pixelSize: theme.section + 2; font.weight: Font.DemiBold; Layout.fillWidth: true }
+ FText { objectName: "downloadListTotal"; visible: downloads.available; text: downloads.total; font.weight: Font.DemiBold; color: theme.accent; Layout.fillWidth: true }
+ FText { objectName: "videoModelGuide"; text: downloads.copy.guide; color: theme.muted; Layout.fillWidth: true; font.pixelSize: theme.micro + 1 }
+ FText { objectName: "downloadListCheck"; visible: !downloads.available && !s.download_list.inspection_error; text: s.download_list.checking ? downloads.copy.checking : downloads.copy.unavailable; Layout.fillWidth: true; color: theme.muted }
+ FText { objectName: "downloadListReuse"; visible: downloads.available && text.length > 0; text: downloads.reused; color: theme.success; Layout.fillWidth: true; font.pixelSize: theme.micro + 1 }
+ ColumnLayout {
+ Layout.fillWidth: true; spacing: 8
+ Repeater {
+ model: downloads.available ? downloads.groups : []
+ delegate: ColumnLayout {
+ id: downloadGroup
+ required property var modelData
+ readonly property bool expanded: !!win.downloadExpanded[modelData.id]
+ Layout.fillWidth: true; spacing: 4
+ FButton {
+ id: groupButton
+ objectName: "downloadGroup-" + downloadGroup.modelData.id
+ text: (downloadGroup.expanded ? "− " : "+ ") + downloadGroup.modelData.title
+ Accessible.name: text + " · " + downloadGroup.modelData.summary
+ Layout.fillWidth: true; flat: true; leftPadding: 8; rightPadding: 8
+ contentItem: RowLayout {
+ spacing: 8
+ FText { objectName: groupButton.objectName + "-title"; text: groupButton.text; font: groupButton.font; Layout.fillWidth: true; horizontalAlignment: Text.AlignLeft; color: groupButton.hovered ? theme.text : theme.muted }
+ FText { objectName: groupButton.objectName + "-summary"; text: downloadGroup.modelData.summary; font: groupButton.font; horizontalAlignment: Text.AlignRight; color: theme.muted }
+ }
+ onClicked: {
+ var expanded = Object.assign({}, win.downloadExpanded)
+ expanded[downloadGroup.modelData.id] = !downloadGroup.expanded
+ win.downloadExpanded = expanded
+ }
+ }
+ Loader {
+ active: downloadGroup.expanded; visible: active; Layout.fillWidth: true
+ sourceComponent: ColumnLayout {
+ spacing: 2
+ Repeater {
+ model: downloadGroup.modelData.files
+ delegate: RowLayout {
+ required property var modelData; required property int index
+ objectName: "downloadFile-" + downloadGroup.modelData.id + "-" + index
+ Layout.fillWidth: true; spacing: 8
+ FText { objectName: parent.objectName + "-name"; text: modelData.name; Layout.fillWidth: true; elide: Text.ElideMiddle; maximumLineCount: 1; font.pixelSize: theme.micro }
+ FText { text: modelData.size; Layout.preferredWidth: 104; font.pixelSize: theme.micro; color: theme.muted; horizontalAlignment: Text.AlignRight }
+ FButton { objectName: "downloadHF-" + downloadGroup.modelData.id + "-" + index; text: "Hugging Face ↗"; flat: true; implicitHeight: theme.heightSm; font.pixelSize: theme.micro; onClicked: backend.link(modelData.hf_url) }
+ Item {
+ id: mirrorSlot
+ readonly property var file: modelData
+ readonly property string suffix: downloadGroup.modelData.id + "-" + index
+ objectName: "downloadMSSlot-" + suffix
+ // Reserve the same width whether a mirror exists or not.
+ implicitWidth: Math.max(80, mirrorMetrics.width + 32, missingMetrics.width + 32)
+ implicitHeight: theme.heightSm
+ TextMetrics { id: mirrorMetrics; text: sourceName("modelscope") + " ↗"; font.pixelSize: theme.micro; font.weight: Font.Medium }
+ TextMetrics { id: missingMetrics; text: downloads.copy.missing_mirror; font.pixelSize: theme.micro }
+ Loader {
+ anchors.fill: parent
+ sourceComponent: mirrorSlot.file.modelscope_url ? mirrorButton : mirrorUnavailable
+ }
+ Component {
+ id: mirrorButton
+ FButton { objectName: "downloadMS-" + mirrorSlot.suffix; text: sourceName("modelscope") + " ↗"; flat: true; implicitHeight: theme.heightSm; font.pixelSize: theme.micro; onClicked: backend.link(mirrorSlot.file.modelscope_url) }
+ }
+ Component {
+ id: mirrorUnavailable
+ FText { objectName: "downloadMSMissing-" + mirrorSlot.suffix; text: downloads.copy.missing_mirror; color: theme.muted; font.pixelSize: theme.micro; horizontalAlignment: Text.AlignHCenter; verticalAlignment: Text.AlignVCenter }
+ }
+ }
+ }
+ }
+ }
+ }
+ }
+ }
+ }
+ RowLayout {
+ visible: s.download_list.folder.length > 0; Layout.fillWidth: true; spacing: 8
+ FText { objectName: "downloadListNotice"; visible: text.length > 0; text: s.download_list.notice; color: theme.success; Layout.fillWidth: true; font.pixelSize: theme.micro + 1 }
+ FButton { objectName: "openDownloadFolder"; text: downloads.copy.open_folder; flat: true; implicitHeight: theme.heightSm; font.pixelSize: theme.micro + 1; onClicked: backend.openDownloadFolder() }
+ }
+ FText { objectName: "downloadListError"; visible: text.length > 0; text: s.download_list.error; color: theme.danger; Layout.fillWidth: true; wrapMode: Text.WordWrap; font.pixelSize: theme.micro + 1 }
+ FText { objectName: "downloadListRawError"; visible: s.error.length > 0 && !s.download_list.inspection_error; text: s.error; color: theme.danger; Layout.fillWidth: true; maximumLineCount: 2; elide: Text.ElideRight; font.pixelSize: theme.micro }
+ }
+ }
RowLayout {
- Layout.fillWidth: true; spacing: 8
- FButton { text: t("Close", "关闭"); flat: true; onClicked: modelInfoOpen = false }
+ objectName: "downloadListActions"; Layout.fillWidth: true; Layout.minimumWidth: 0; spacing: 8
+ // The actions share what the Close button leaves, so a long label wraps instead of leaving the dialog.
+ readonly property int actionCount: checkDownloadList.visible ? 3 : 2
+ readonly property real actionWidth: Math.max(80, Math.floor((width - closeDownloadList.implicitWidth - (actionCount + 1) * spacing) / actionCount))
+ FButton { id: closeDownloadList; text: downloads.copy.close; flat: true; onClicked: modelInfoOpen = false }
Item { Layout.fillWidth: true }
- FButton { text: t("Choose model folder", "选择模型目录"); onClicked: { modelInfoOpen = false; backend.browse("model_dirs") } }
- FButton { text: t("Import ZIPs", "导入 ZIP"); primary: true; onClicked: { modelInfoOpen = false; backend.browsePackages() } }
- }
+ FButton { id: checkDownloadList; objectName: "checkDownloadList"; Layout.maximumWidth: parent.actionWidth; visible: !downloads.available || s.download_list.needs_check; text: downloads.copy.check; enabled: !s.busy; onClicked: backend.prepareDownloadList() }
+ FButton { objectName: "useDownloadedFolder"; Layout.maximumWidth: parent.actionWidth; text: downloads.copy.use_folder; enabled: !s.busy; onClicked: backend.useDownloadedFolder() }
+ FButton { objectName: "exportDownloadList"; Layout.maximumWidth: parent.actionWidth; text: downloads.copy.export; primary: true; enabled: downloads.available && !s.busy; onClicked: backend.exportDownloadList() }
}
}
}
diff --git a/freevideo_engine/launcher_session.py b/freevideo_engine/launcher_session.py
index 16b3bd6..a23e4e8 100644
--- a/freevideo_engine/launcher_session.py
+++ b/freevideo_engine/launcher_session.py
@@ -1,4 +1,5 @@
"""Widget-independent state for the Qt launcher; uses the existing installer."""
+from copy import deepcopy
import json
import os
from pathlib import Path
@@ -17,7 +18,8 @@ from .launcher_settings import Store, default_language
from .launcher_copy import size_text
from .launcher_terminal import Tail
from .model_status import FAMILIES, NAMES
-from .model_guidance import package_instructions, video_instructions, runtime_packages_supported
+from .model_guidance import (package_instructions, video_instructions, runtime_packages_supported, download_view,
+ export_download_list, DownloadListError, DOWNLOAD_COPY)
from .setup_progress import progress_text
from .terminal_ui import clean, duration
from .model_upgrade import TARGET
@@ -109,6 +111,8 @@ class Session:
self.tail = Tail()
self.log_source = None
self.model_groups = []
+ self.download_export = self.download_error = self.download_error_key = ''
+ self._download_view = None
self.browser_attempted = False
self.browser_url = None
self.port_notice_url = None
@@ -258,6 +262,7 @@ class Session:
self.cleaner.state = dict(status='idle', bytes=0, error='')
self.controller.selection = None
self.controller.state = dict(status='idle')
+ self.download_export = self.download_error = self.download_error_key = ''
self.browser_attempted = False
self.port_notice_url = None
self.browser_error = self.error = ''
@@ -284,6 +289,65 @@ class Session:
kept = [p for p in self.form['model_dirs'] if io_path(Path(p).expanduser()).is_dir()]
self.edit('model_dirs', library_roots(kept + [folder]))
+ def prepare_download_list(self):
+ if self.controller.busy or self.importer.busy or self.cleaner.busy:
+ return
+ if (self.controller.state.get('plan', {}).get('download_files_verified')
+ and self.controller.state.get('status') == 'review'
+ and self.download_error_key not in ('unchecked', 'changed')):
+ return
+ self.error = ''
+ self.download_export = self.download_error = self.download_error_key = ''
+ self.persist()
+ self.controller.run('inspect', self.setup_values(download_list=True))
+
+ def export_downloads(self, folder):
+ """The dialog shows a worded error; nothing raises into a traceback."""
+ self.download_export = self.download_error = self.download_error_key = ''
+ if self.controller.busy or self.controller.state.get('status') != 'review':
+ self.download_error = self.t('Wait for the file check to finish.', '请等待文件检查完成。')
+ return
+ preferences = download_preferences(self.engine_root() / 'download-settings.json')
+ try:
+ self.download_export = export_download_list(self.controller.state.get('plan', {}), folder, preferences['source'])
+ except DownloadListError as error:
+ self.download_error_key = error.key
+ reason = ''
+ if error.key == 'write':
+ reason = self.t(*DOWNLOAD_COPY.get('write_' + error.reason, DOWNLOAD_COPY['write_other']))
+ # Session has no log writer; keep the OS detail on stderr, without the user's paths.
+ from .failure_details import redacted_launcher_error
+ print('Download list export failed (%s): %s' % (error.reason, redacted_launcher_error(error.original_error)),
+ file=sys.stderr)
+ self.download_error = self.t(*DOWNLOAD_COPY['error_' + error.key]).format(reason=reason)
+
+ def use_downloaded_folder(self, folder):
+ if self.controller.busy or self.importer.busy or self.cleaner.busy:
+ return
+ self.add_folder(folder)
+ # Even a folder already in the list may have received new downloads.
+ self.controller.state = dict(status='idle')
+ self.prepare_download_list()
+
+ def downloads_view(self):
+ row = self.controller.state
+ plan = row.get('plan', {}) if row.get('status') == 'review' else {}
+ if not plan.get('download_files_verified', True):
+ plan = {}
+ zh = self.language.startswith('zh')
+ decimal_sizes = sys.platform == 'darwin'
+ # Only inputs that affect list content belong here. Disk/progress/notice
+ # updates must not replace the QML model or its file delegates.
+ key = ('download_files' in plan, plan.get('download_files', []),
+ (plan.get('local_models') or {}).get('matches', {}), zh, decimal_sizes)
+ if self._download_view is None or self._download_view[0] != key:
+ view = download_view(plan, zh, decimal_sizes=decimal_sizes)
+ if self._download_view is None or self._download_view[1] != view:
+ self._download_view = (deepcopy(key), view)
+ else:
+ self._download_view = (deepcopy(key), self._download_view[1])
+ return self._download_view[1]
+
def remove_folder(self, index):
removed = self.form['model_dirs'][index]
self.edit('model_dirs', [p for i, p in enumerate(self.form['model_dirs']) if i != index])
@@ -319,10 +383,20 @@ class Session:
if self.archives_busy:
return
if self.form['model_method'] == 'auto' and not self.form['offline_models']:
- self.importer.download(self.form['offline_runtime'], self.source, self.form['sampling_caches'])
+ self.importer.download(self.form['offline_runtime'], self.source, False)
else:
self.importer.prepare(self.form['offline_runtime'], self.form['offline_models'], self.source)
+ def setup_values(self, form=None, **extra):
+ """Only the visible automatic-setup option can request every quality level."""
+ form = self.form if form is None else form
+ values = dict(form, token=self.token, **extra)
+ if (form['model_method'] == 'manual' or
+ (runtime_packages_supported() and form['new_comfy']
+ and form['environment_method'] == 'manual')):
+ values['sampling_caches'] = False
+ return values
+
def activate_offline(self, root):
from .offline_packages import check_runtime_platform
check_runtime_platform()
@@ -370,7 +444,7 @@ class Session:
self.remember(self.selected, persist=False)
self.repair_request = dict(self.form, repair=True)
self.persist()
- self.controller.run('inspect', dict(self.repair_request, token=self.token))
+ self.controller.run('inspect', self.setup_values(self.repair_request))
self.page = 'progress'
self.model_groups = []
self.started = time.monotonic()
@@ -390,7 +464,7 @@ class Session:
# Recompute the plan and live disk space; never install a stale
# failed review or discard completed/resumable downloads.
self.persist()
- self.controller.run('inspect', dict(self.repair_request or self.form, token=self.token))
+ self.controller.run('inspect', self.setup_values(self.repair_request or self.form))
self.page = 'progress'
self.started = time.monotonic()
return
@@ -471,7 +545,7 @@ class Session:
self.controller.run('connect')
else:
self.persist()
- self.controller.run('inspect', dict(self.repair_request or self.form, token=self.token))
+ self.controller.run('inspect', self.setup_values(self.repair_request or self.form))
self.page = 'progress'
self.model_groups = []
self.started = time.monotonic()
@@ -605,7 +679,7 @@ class Session:
self.model_switch = 'inspect'
self.repair_request = None
upgrade.switching()
- self.controller.run('inspect', dict(self.form, token=self.token, repair=True, prepared_format='int8'))
+ self.controller.run('inspect', self.setup_values(repair=True, prepared_format='int8'))
self.page = 'progress'
self.model_groups = []
self.started = time.monotonic()
@@ -944,7 +1018,7 @@ class Session:
self.port_notice_url = None
self.browser_wait = None
self.persist()
- self.controller.run('inspect', dict(self.form, token=self.token))
+ self.controller.run('inspect', self.setup_values())
self.page = 'progress'
self.model_groups = []
self.started = time.monotonic()
@@ -1712,7 +1786,16 @@ class Session:
self.archives_prompt_offer if self.archives_retry_dialog else self.archive_offer())
archives_idle = bool(archive_offer and archive_offer['paths']) and self.archives_idle()
archive_dialog = self.archives_dialog_view(archive_offer, archives_idle, error, update)
- return plain_data(dict(sampling_cache_bytes=total_bytes(), version=__version__,
+ downloads = self.downloads_view()
+ inspection_read_error = (row.get('status') == 'failed' and row.get('action') == 'inspect'
+ and 'Download list error: read' in row.get('error', '').splitlines())
+ download_state = dict(checking=bool(self.controller.busy), error=self.download_error,
+ needs_check=self.download_error_key in ('unchecked', 'changed'), folder=self.download_export,
+ inspection_error=inspection_read_error,
+ notice=downloads['copy']['exported'].format(folder=self.download_export) if self.download_export else '')
+ if inspection_read_error:
+ download_state.update(error=self.t(*DOWNLOAD_COPY['error_read']), needs_check=True)
+ return plain_data(dict(download_list=download_state, sampling_cache_bytes=total_bytes(), version=__version__,
disk=disk, decimal_sizes=sys.platform == 'darwin', zh=self.language.startswith('zh'), form=dict(self.form),
page=self.page, status=row.get('status', 'idle'), busy=self.controller.busy or self.importer.busy or self.cleaner.busy,
cleanup=cleanup,
diff --git a/freevideo_engine/model_files.json b/freevideo_engine/model_files.json
index 51a4513..9e215d8 100644
--- a/freevideo_engine/model_files.json
+++ b/freevideo_engine/model_files.json
@@ -5,7 +5,8 @@
"file": "LICENSE",
"bytes": 17604,
"sha256": null,
- "git_blob": "c389b45855337ccec8ddeb389f4fe902abcd0b19"
+ "git_blob": "c389b45855337ccec8ddeb389f4fe902abcd0b19",
+ "download_sha256": "59b99642b95ea21630e311198ddbfffbfe05aadba0c2f5d884cbdf4efcc90f44"
},
{
"repo": "OpenVDN/vdn-minimax-h3",
@@ -13,7 +14,8 @@
"file": "h3-base/LICENSE",
"bytes": 17604,
"sha256": null,
- "git_blob": "c389b45855337ccec8ddeb389f4fe902abcd0b19"
+ "git_blob": "c389b45855337ccec8ddeb389f4fe902abcd0b19",
+ "download_sha256": "59b99642b95ea21630e311198ddbfffbfe05aadba0c2f5d884cbdf4efcc90f44"
},
{
"repo": "OpenVDN/vdn-minimax-h3",
@@ -21,7 +23,8 @@
"file": "h3-base/README.md",
"bytes": 38391,
"sha256": null,
- "git_blob": "aa9bba6233ed8d0b486fb43e1a35b4fb5ede2a60"
+ "git_blob": "aa9bba6233ed8d0b486fb43e1a35b4fb5ede2a60",
+ "download_sha256": "89a98af9e91fcb54c46cbcb88f8b8aa7aaf3a461714dbf21d2d3ef4b39312ee3"
},
{
"repo": "OpenVDN/vdn-minimax-h3",
@@ -29,7 +32,8 @@
"file": "h3-base/audio_scheduler/scheduler_config.json",
"bytes": 96,
"sha256": null,
- "git_blob": "28a3d4ed602d925031c7e5d6eeb07df8958ff0f1"
+ "git_blob": "28a3d4ed602d925031c7e5d6eeb07df8958ff0f1",
+ "download_sha256": "804780f7133477067bd6bbfbc02dc8b3cf9feeb400f97c08f5b1d5f6cbab3840"
},
{
"repo": "OpenVDN/vdn-minimax-h3",
@@ -37,7 +41,8 @@
"file": "h3-base/audio_vae/config.json",
"bytes": 2271,
"sha256": null,
- "git_blob": "15df6fe0b288b260dca0f2aebf1cd81334d77e96"
+ "git_blob": "15df6fe0b288b260dca0f2aebf1cd81334d77e96",
+ "download_sha256": "9a3c645ff892b376c6f5f4c8685964cd75474731af594ff058492a0000caabb6"
},
{
"repo": "OpenVDN/vdn-minimax-h3",
@@ -53,7 +58,8 @@
"file": "h3-base/model_index.json",
"bytes": 2936,
"sha256": null,
- "git_blob": "454be19164878173a962c39c81633e4377880fca"
+ "git_blob": "454be19164878173a962c39c81633e4377880fca",
+ "download_sha256": "5a587fe13b2371427415ac892463142683aefcd8d322e274a3a095eac37ac7d2"
},
{
"repo": "OpenVDN/vdn-minimax-h3",
@@ -61,7 +67,8 @@
"file": "h3-base/modular_model_index.json",
"bytes": 2935,
"sha256": null,
- "git_blob": "5b69f1e801bd0a7e9733c48704c732339f2002fe"
+ "git_blob": "5b69f1e801bd0a7e9733c48704c732339f2002fe",
+ "download_sha256": "a2b6a210e482ffb78e613b553f570c44e101afce6741bd4ed91429d0559af031"
},
{
"repo": "OpenVDN/vdn-minimax-h3",
@@ -69,7 +76,8 @@
"file": "h3-base/scheduler/scheduler_config.json",
"bytes": 97,
"sha256": null,
- "git_blob": "1d44f95b955a648ad4fab455e4fe11053888c30b"
+ "git_blob": "1d44f95b955a648ad4fab455e4fe11053888c30b",
+ "download_sha256": "8fa6c3aa70dc9e691e1a6df899fd1b6f75f70481a27cee6e18a303817075c304"
},
{
"repo": "OpenVDN/vdn-minimax-h3",
@@ -77,7 +85,8 @@
"file": "h3-base/transformer/config.json",
"bytes": 546,
"sha256": null,
- "git_blob": "c251a4133c81852a150c6668a570e142dc776b6e"
+ "git_blob": "c251a4133c81852a150c6668a570e142dc776b6e",
+ "download_sha256": "74c11bff524336576096993cbfcdcdc2ef4fa2fa4409df693bdcbc6c666282ae"
},
{
"repo": "OpenVDN/vdn-minimax-h3",
@@ -197,7 +206,8 @@
"file": "h3-base/transformer/diffusion_pytorch_model.safetensors.index.json",
"bytes": 64488,
"sha256": null,
- "git_blob": "da038def25abb5a5e4be509816ee55a0b7105e09"
+ "git_blob": "da038def25abb5a5e4be509816ee55a0b7105e09",
+ "download_sha256": "ac30a3b58963f2e735d493475fbb81853a5735ec947619648b3e045acda6783e"
},
{
"repo": "OpenVDN/vdn-minimax-h3",
@@ -205,7 +215,8 @@
"file": "h3-base/vae/config.json",
"bytes": 2011,
"sha256": null,
- "git_blob": "ed4874a5886972f4029fcd99cbbe72de0177b2c9"
+ "git_blob": "ed4874a5886972f4029fcd99cbbe72de0177b2c9",
+ "download_sha256": "78f67deec3d63aae807f2bfe7154bc1e26f6372cb20b63265fcbae1b62bb5745"
},
{
"repo": "OpenVDN/vdn-minimax-h3",
@@ -237,7 +248,8 @@
"file": "h3-base/vae/diffusion_pytorch_model.safetensors.index.json",
"bytes": 74228,
"sha256": null,
- "git_blob": "05dfb255c44daa4f1ac487f57f18210fa5c19439"
+ "git_blob": "05dfb255c44daa4f1ac487f57f18210fa5c19439",
+ "download_sha256": "15f6d44553c3c616b0dc999920aa784f92ecee7e4201f1f99ac405cfbf3061ca"
},
{
"repo": "OpenVDN/vdn-minimax-h3",
@@ -245,7 +257,8 @@
"file": "stage-dmd-step-250/adapters/default/adapter_config.json",
"bytes": 415,
"sha256": null,
- "git_blob": "ef3c876ab5a596a1b6b4b28f3443bbe30c5455d8"
+ "git_blob": "ef3c876ab5a596a1b6b4b28f3443bbe30c5455d8",
+ "download_sha256": "89e0ff8920b9629b826eb99ab6150cce6924a53aa445186d1b493225fd091b96"
},
{
"repo": "OpenVDN/vdn-minimax-h3",
@@ -261,7 +274,8 @@
"file": "stage-dmd-step-250/adapters/turbo/adapter_config.json",
"bytes": 22264,
"sha256": null,
- "git_blob": "dbd7be544c9f3092b229f5cb6487f8da2f4ccc05"
+ "git_blob": "dbd7be544c9f3092b229f5cb6487f8da2f4ccc05",
+ "download_sha256": "627968f670747c29cd7a0d3f8c75166e501d70f9e829b5cd3242a8f14cefbc18"
},
{
"repo": "OpenVDN/vdn-minimax-h3",
@@ -277,7 +291,8 @@
"file": "stage-dmd-step-250/linear_branch/config.json",
"bytes": 465,
"sha256": null,
- "git_blob": "314502a7c9d403f28493ac1cb5054032c8c7b545"
+ "git_blob": "314502a7c9d403f28493ac1cb5054032c8c7b545",
+ "download_sha256": "decb06ac7e664610f677fb445318502b3c51f9c1b8603a2cdd00b16042be5bc8"
},
{
"repo": "OpenVDN/vdn-minimax-h3",
@@ -293,7 +308,8 @@
"file": "stage-dmd-step-250/metadata.json",
"bytes": 463,
"sha256": null,
- "git_blob": "27ec152079222e3f2a83b8ee0bc634a77da0df01"
+ "git_blob": "27ec152079222e3f2a83b8ee0bc634a77da0df01",
+ "download_sha256": "54054ceb1c91b3fdf7fa0278e4a8841c127e8cf666b5e240d69613661f9d3e9e"
},
{
"repo": "OpenVDN/vdn-minimax-h3",
@@ -301,7 +317,8 @@
"file": "stage-dmd-step-250/model_spec.json",
"bytes": 25705,
"sha256": null,
- "git_blob": "e039c13987797f91e11a3477c38fa8fd1f6a506f"
+ "git_blob": "e039c13987797f91e11a3477c38fa8fd1f6a506f",
+ "download_sha256": "4171f4384e952f1f73467981a893440c03298af4956b947e2c8a857ba9f5a62b"
},
{
"repo": "t8star/Vdn-Minimax-H3-Comfy",
diff --git a/freevideo_engine/model_guidance.py b/freevideo_engine/model_guidance.py
index 2c50da5..99dc560 100644
--- a/freevideo_engine/model_guidance.py
+++ b/freevideo_engine/model_guidance.py
@@ -1,9 +1,302 @@
"""User-facing model download destinations, from the installation manifests."""
+from contextlib import ExitStack
+import errno
+import hashlib
import json
-from pathlib import Path
+import os
+from pathlib import Path, PurePosixPath
+import re
+import shutil
import sys
-from urllib.parse import quote, urlsplit
+import tempfile
+import time
+import uuid
+from urllib.parse import urlsplit
+
+from . import network
from .long_paths import io_path, plain_errors
+from .model_status import FAMILIES, NAMES, family
+
+# Iris can replace the third-party download copy here, including export guidance.
+DOWNLOAD_COPY = {
+ 'title': ('Download list', '下载清单'),
+ 'guide': ('The list is filtered for this GPU, so the whole model repository is not needed. '
+ 'When the download finishes, choose "Use downloaded folder"; FreeVideo checks every file before using it.',
+ '清单已按显卡筛选,无需下载整个模型仓库。下载完成后点“使用已下载的文件夹”,FreeVideo 会逐个校验后使用。'),
+ 'export': ('Export download list', '导出下载清单'),
+ 'use_folder': ('Use downloaded folder', '使用已下载的文件夹'),
+ 'checking': ('Checking the hardware and the downloaded files…', '正在检查硬件和已下载的文件…'),
+ 'check': ('Check again', '重新检查'),
+ 'unavailable': ('The download list is not ready yet. Choose "Check again".', '下载清单尚未生成,请点“重新检查”。'),
+ 'total': ('To download: {count} files ({size})', '需要下载:{count} 个文件({size})'),
+ 'total_remaining': ('Still to download: {count} files ({size})', '还需下载:{count} 个文件({size})'),
+ 'group': ('{count} files · {size}', '{count} 个文件 · {size}'),
+ 'reused': ('Checked and ready to use: {count} files ({size})', '已校验、可直接使用:{count} 个文件({size})'),
+ 'exported': ('Download list exported to {folder}', '下载清单已导出到 {folder}'),
+ 'open_folder': ('Open folder', '打开文件夹'),
+ 'close': ('Close', '关闭'),
+ 'missing_mirror': ('Not on ModelScope', '魔搭暂无'),
+ 'error_folder': ('Choose an existing folder to save the download list in.', '请选择一个已有的文件夹来保存下载清单。'),
+ 'error_unchecked': ('Choose "Check again" first, then export the download list.', '请先点“重新检查”,再导出下载清单。'),
+ 'error_changed': ('The required files have changed. Choose "Check again", then export the download list.',
+ '所需文件有变化。请点“重新检查”,再导出下载清单。'),
+ 'error_write': ('The download list could not be saved in this folder: {reason}', '下载清单未能保存到这个文件夹:{reason}'),
+ 'error_read': ('FreeVideo does not have permission to read some files in the selected folder. Choose another folder, or download the files again without administrator rights.',
+ 'FreeVideo 没有权限读取所选文件夹里的部分文件。请选择其他文件夹,或不使用管理员身份重新下载。'),
+ 'write_permission': ('this account cannot write to it. Choose another folder.', '当前账户没有写入权限,请换一个文件夹。'),
+ 'write_disk_full': ('the drive is full.', '磁盘空间不足。'),
+ 'write_path_long': ('the path is too long. Choose a folder closer to the top of the drive.', '路径太长,请选择层级更浅的文件夹。'),
+ 'write_other': ('Choose another folder and try again.', '请换一个文件夹再试一次。'),
+ 'video': NAMES['video'], 'text': NAMES['text'], 'decoder': NAMES['decoder'], 'sampling': NAMES['sampling'],
+ 'readme': (
+ 'FreeVideo download list\n'
+ '\n'
+ 'Run this command in this folder:\n'
+ 'aria2c --input-file=aria2.txt --continue=true --check-integrity=true\n'
+ '\n'
+ 'You can also import urls.txt into another download tool. urls.txt uses the download source chosen in Settings (Automatic uses Hugging Face); a few files are only available from Hugging Face. Keep all downloaded files in this folder or its subfolders.\n'
+ '\n'
+ 'When the download finishes, return to the launcher, choose "Use downloaded folder", then "Check & continue". FreeVideo recognizes files by size and full checksum, so different file names are fine; missing or damaged files are downloaded as usual.\n'
+ '\n'
+ 'The paths in SHA256SUMS are where aria2 saves the files. With urls.txt the file names may differ, which does not matter.\n'
+ '\n'
+ 'There is no need to download the whole model repository. This folder is not an offline package; do not import it with "Choose offline packages".\n',
+ 'FreeVideo 下载清单\n'
+ '\n'
+ '在这个文件夹里运行下面的命令:\n'
+ 'aria2c --input-file=aria2.txt --continue=true --check-integrity=true\n'
+ '\n'
+ '也可以把 urls.txt 导入其他下载工具。urls.txt 用的是设置里选中的下载源(选“自动”时用 Hugging Face);个别文件只能从 Hugging Face 下载。请把下载的文件都放在这个文件夹或它的子文件夹里。\n'
+ '\n'
+ '下载完成后,回到启动器点“使用已下载的文件夹”,再点“检查并继续”。FreeVideo 按文件大小和完整校验值识别文件,文件名不同也可以;缺少或损坏的文件会照常下载。\n'
+ '\n'
+ 'SHA256SUMS 里的路径是 aria2 的存放路径。用 urls.txt 下载时文件名可能不同,不影响使用。\n'
+ '\n'
+ '不必下载整个模型仓库。这个文件夹不是离线包,不要用“选择离线包”导入。\n'
+ '\n'),
+}
+
+
+# The export goes into a folder of its own inside the chosen one, so files the
+# user keeps there (a README.txt, say) are never overwritten.
+EXPORT_FOLDER = 'FreeVideo-download-list'
+GENERATOR = 'FreeVideo download list'
+EXPORT_FILES = ('manifest.json', 'aria2.txt', 'SHA256SUMS', 'urls.txt', 'README.txt')
+
+
+class DownloadListError(ValueError):
+ """key names the DOWNLOAD_COPY 'error_<key>' text the launcher shows."""
+ def __init__(self, key, reason='', original_error=''):
+ self.key, self.reason = key, reason
+ self.original_error = original_error
+ super().__init__(DOWNLOAD_COPY['error_' + key][0].format(reason=reason))
+
+
+def download_write_reason(error, folder):
+ """Stable reason codes; OS messages are retained only for diagnostics."""
+ if isinstance(error, PermissionError) or error.errno in (errno.EACCES, errno.EPERM):
+ return 'permission'
+ winerror = getattr(error, 'winerror', None)
+ if error.errno == errno.ENOSPC or winerror in (112, 39):
+ return 'disk_full'
+ paths = (error.filename, error.filename2, folder)
+ if (error.errno == errno.ENAMETOOLONG or winerror == 206
+ or winerror == 3 and any(path is not None and len(str(path)) > 260 for path in paths)):
+ return 'path_long'
+ return 'other'
+
+
+def download_copy(zh=False):
+ return {key: value[bool(zh)] for key, value in DOWNLOAD_COPY.items()}
+
+
+def download_files(entries):
+ """Project the install plan's placements; never select another GPU variant."""
+ result = []
+ for row, status in entries:
+ if status != 'download':
+ continue
+ mirror = None if row.get('official_only') else network.modelscope_mapping(row)
+ result.append(dict(group=family(row), repo=row['repo'], hf_revision=row['revision'],
+ modelscope_repo=mirror['repo'] if mirror else '', modelscope_revision=mirror['revision'] if mirror else '',
+ file=row['file'], bytes=row['bytes'], sha256=row.get('sha256') or row.get('download_sha256'),
+ relative_path='/'.join(('payload', row['repo'], row['file'])),
+ hf_url=network.model_url(row, 'official', env={}),
+ modelscope_url=network.model_url(row, 'modelscope', env={}) if mirror else ''))
+ return result
+
+
+def download_view(plan, zh=False, *, decimal_sizes=False):
+ from .launcher_copy import size_text
+ def size(value):
+ if value < (10**6 if decimal_sizes else 2**20):
+ unit = 'MB' if decimal_sizes else 'MiB'
+ return ('不到 1 ' if zh else 'under 1 ') + unit
+ return size_text(value, decimal_sizes=decimal_sizes)
+ copy = download_copy(zh)
+ rows = plan.get('download_files', [])
+ groups = []
+ for group in FAMILIES:
+ files = [dict(row, name=row['file'], size=size(row['bytes'])) for row in rows if row['group'] == group]
+ amount = sum(row['bytes'] for row in files)
+ groups.append(dict(id=group, title=copy[group], files=files, count=len(files), bytes=amount,
+ summary=copy['group'].format(count=len(files), size=size(amount))))
+ reused = (plan.get('local_models') or {}).get('matches', {})
+ return dict(available='download_files' in plan, groups=groups, copy=copy,
+ total_bytes=sum(row['bytes'] for row in rows), count=len(rows),
+ total=copy['total_remaining' if reused else 'total'].format(size=size(sum(row['bytes'] for row in rows)), count=len(rows)),
+ reused=copy['reused'].format(count=len(reused), size=size(sum(r['bytes'] for r in reused.values()))) if reused else '')
+
+
+def export_download_list(plan, folder, source='auto'):
+ """Offline export. The imported manifest is never trusted as a hash source."""
+ folder = Path(folder).expanduser().resolve()
+ if not folder.is_dir():
+ raise DownloadListError('folder')
+ if 'download_files' not in plan or not plan.get('download_files_verified', True):
+ raise DownloadListError('unchecked')
+ if source not in ('auto', 'official', 'hf-mirror', 'modelscope'):
+ raise DownloadListError('changed')
+ rows = plan['download_files']
+ outputs = set()
+ aria, sums, urls = [], [], []
+ for row in rows:
+ relative = row['relative_path']
+ path = PurePosixPath(relative)
+ if (path.is_absolute() or any(part in ('', '.', '..') for part in relative.split('/'))
+ or any(char in relative for char in '\\:\r\n\t\x00') or relative in outputs
+ or not re.fullmatch('[0-9a-f]{64}', row.get('sha256') or '')
+ or not re.fullmatch('[0-9a-f]{40}', row['hf_revision'])
+ or type(row['bytes']) is not int or row['bytes'] <= 0):
+ raise DownloadListError('changed')
+ outputs.add(relative)
+ # Use only catalog pins and URLs generated by network.model_url.
+ original = dict(repo=row['repo'], revision=row['hf_revision'], file=row['file'])
+ hf = network.model_url(original, 'official', env={})
+ mirror = network.model_url(original, 'modelscope', env={}) if row['modelscope_url'] else ''
+ if row['hf_url'] != hf or row['modelscope_url'] != mirror:
+ raise DownloadListError('changed')
+ aria.extend(['\t'.join(url for url in (hf, mirror) if url),
+ ' dir=' + path.parent.as_posix(), ' out=' + path.name,
+ ' checksum=sha-256=' + row['sha256']])
+ sums.append(row['sha256'] + ' ' + relative)
+ chosen = 'official' if source == 'auto' or (source == 'modelscope' and not mirror) else source
+ urls.append(network.model_url(original, chosen, env={}))
+ prepared = plan.get('prepared_model') or {}
+ manifest = dict(schema_version=1, generator=GENERATOR, engine_version=plan.get('engine_version'),
+ video_model=dict(format=prepared.get('scale_granularity') or plan.get('model_scale_granularity') or plan.get('prepared_format'),
+ reason=plan.get('model_source_reason', ''), source=plan.get('model_source')),
+ sampling_caches=bool(plan.get('sampling_caches')), source=source,
+ total_bytes=sum(row['bytes'] for row in rows), files=rows)
+ documents = {'manifest.json': json.dumps(manifest, ensure_ascii=False, indent=2) + '\n',
+ 'aria2.txt': '\n'.join(aria) + ('\n' if aria else ''),
+ 'SHA256SUMS': '\n'.join(sums) + ('\n' if sums else ''),
+ 'urls.txt': '\n'.join(urls) + ('\n' if urls else ''),
+ 'README.txt': DOWNLOAD_COPY['readme'][1] + '\n' + DOWNLOAD_COPY['readme'][0]}
+ # Finish every file before anything appears or is replaced. No payload is downloaded.
+ stage = None
+ try:
+ # Not mkdtemp: Python 3.12.4 protects its Windows ACL from inheritance.
+ # Downloads made by an administrator must remain readable by the account
+ # that chose this folder, as with desktop_shortcut's launcher staging.
+ temporary = folder / ('.freevideo-list-' + uuid.uuid4().hex)
+ temporary.mkdir()
+ stage = temporary
+ for name, content in documents.items():
+ (stage / name).write_text(content, encoding='utf-8', newline='\n')
+ # Two launchers exporting into one folder take turns: the five files
+ # always come from the same export.
+ with export_lock(folder):
+ target, earlier = export_target(folder)
+ if earlier:
+ replace_export(stage, target)
+ else:
+ os.rename(stage, target) # One step: the folder appears complete or not at all.
+ stage = None
+ except OSError as error:
+ raise DownloadListError('write', download_write_reason(error, folder), str(error)) from error
+ finally:
+ if stage is not None:
+ shutil.rmtree(stage, ignore_errors=True)
+ return str(target)
+
+
+def export_lock(folder, wait=30.):
+ """Hold the cross-process lock of one export folder; waits for another export.
+
+ The lock file lives in the temporary directory, not in the user's folder.
+ """
+ from .locking import runtime_lock
+ key = hashlib.sha256(os.path.normcase(str(folder)).encode('utf-8')).hexdigest()[:16]
+ path = Path(tempfile.gettempdir()) / ('freevideo-download-list-%s.lock' % key)
+ deadline = time.monotonic() + wait
+ while True:
+ stack = ExitStack()
+ try:
+ stack.enter_context(runtime_lock(path, inherit=False))
+ return stack
+ except BlockingIOError:
+ stack.close()
+ if time.monotonic() > deadline:
+ raise OSError(errno.EBUSY, 'Another download list export into this folder did not finish')
+ time.sleep(.1)
+
+
+def earlier_export(path):
+ """A folder this launcher exported before, identified by its manifest."""
+ try:
+ if path.is_symlink() or not path.is_dir():
+ return False
+ value = json.loads((path / 'manifest.json').read_text(encoding='utf-8'))
+ except (OSError, ValueError):
+ return False
+ return isinstance(value, dict) and value.get('generator') == GENERATOR
+
+
+def export_target(folder):
+ """(folder, earlier): our earlier export is refreshed; anything else is left alone."""
+ for index in range(1, 100):
+ path = folder / (EXPORT_FOLDER if index == 1 else '%s-%d' % (EXPORT_FOLDER, index))
+ if not os.path.lexists(path):
+ return path, False
+ if earlier_export(path):
+ return path, True
+ raise OSError(errno.EEXIST, 'Too many folders named ' + EXPORT_FOLDER)
+
+
+def replace_export(stage, target):
+ """Swap in the five list files; downloads already in the folder stay.
+
+ The files always belong to one export: if any move fails, the earlier ones
+ are put back before the error is raised.
+ """
+ previous, placed = [], []
+ try:
+ for name in EXPORT_FILES:
+ current = target / name
+ if os.path.lexists(current):
+ kept = target / ('.%s.previous-%s' % (name, os.urandom(4).hex()))
+ os.replace(current, kept)
+ previous.append((kept, current))
+ os.replace(stage / name, current)
+ placed.append(current)
+ except OSError:
+ for current in placed:
+ try:
+ os.unlink(current)
+ except OSError:
+ pass
+ for kept, current in previous:
+ try:
+ os.replace(kept, current)
+ except OSError:
+ pass
+ raise
+ for kept, _ in previous:
+ try:
+ os.unlink(kept)
+ except OSError:
+ pass
def runtime_packages_supported():
@@ -48,22 +341,12 @@ def video_instructions(zh=False):
'按模型页说明选择显卡版本,保留下载的目录结构。')[bool(zh)]
-@plain_errors
-def links():
- root = io_path(Path(__file__).parent)
- spec = json.loads((root / 'dependencies.json').read_text(encoding='utf-8'))['models']
- edge = json.loads((root / 'prepared_models.json').read_text(encoding='utf-8'))
- return {
- 'video': [('Hugging Face', 'https://huggingface.co/' + edge['repo']),
- ('ModelScope', 'https://modelscope.ai/models/' + spec['edge_modelscope']['repo'])],
- 'encoder': [('Hugging Face', 'https://huggingface.co/' + spec['encoder_repo'] + '/blob/' +
- spec['encoder_revision'] + '/' + quote(spec['encoder_file'], safe='/'))],
- 'decoder': [('Hugging Face · Video', 'https://huggingface.co/' + spec['vdn_repo'] + '/tree/' +
- spec['vdn_revision'] + '/h3-base/vae'),
- ('Hugging Face · Audio', 'https://huggingface.co/' + spec['vdn_repo'] + '/tree/' +
- spec['vdn_revision'] + '/h3-base/audio_vae'),
- ('ModelScope', 'https://modelscope.ai/models/' + spec['vdn_modelscope']['repo'])],
- }
+def links(plan=None):
+ """Compatibility for the Tk launcher: fixed files from a checked plan only."""
+ return {group: [(row['file'] + ' · ' + source, row[key])
+ for row in (plan or {}).get('download_files', []) if row['group'] == group
+ for source, key in (('Hugging Face', 'hf_url'), ('ModelScope', 'modelscope_url')) if row[key]]
+ for group in FAMILIES}
@plain_errors
@@ -103,7 +386,8 @@ def show_component(app, component):
body = app.ttk.Frame(dialog, padding=24); body.pack(fill='both', expand=True)
app.ttk.Label(body, text=app.t(*titles[component]), style='Heading.TLabel').pack(anchor='w')
app.ttk.Label(body, text=app.t(*instructions[component]), wraplength=490).pack(fill='x', pady=12)
- for title, url in links()[component]:
+ checked = app.controller.state.get('plan', {})
+ for title, url in links(checked)['text' if component == 'encoder' else component]:
app.ttk.Button(body, text=display(title, app.zh) + ' ↗', command=lambda u=url: webbrowser.open(u)).pack(fill='x', pady=4)
for row in cloud_models():
app.ttk.Button(body, text=app.t('Quark model pack · ', '夸克模型包 · ') + row['label'] + ' ↗',
diff --git a/freevideo_engine/modern_launcher.py b/freevideo_engine/modern_launcher.py
index 5122321..a651d0c 100644
--- a/freevideo_engine/modern_launcher.py
+++ b/freevideo_engine/modern_launcher.py
@@ -77,10 +77,12 @@ def create_ui(session, *, show=True):
class Bridge(QObject):
changed = Signal()
+ downloadsChanged = Signal()
def __init__(self):
super().__init__(engine)
self.alerted = None
self.value = session.snapshot()
+ self.download_value = session.downloads_view()
self.timer = QTimer(self)
self.timer.setInterval(250)
self.timer.timeout.connect(self.refresh)
@@ -90,6 +92,10 @@ def create_ui(session, *, show=True):
def state(self):
return self.value
+ @Property('QVariantMap', notify=downloadsChanged)
+ def downloadList(self):
+ return self.download_value
+
def invoke(self, function, *args, **kwargs):
try:
function(*args, **kwargs)
@@ -105,6 +111,10 @@ def create_ui(session, *, show=True):
if value != self.value:
self.value = value
self.changed.emit()
+ downloads = session.downloads_view()
+ if downloads is not self.download_value:
+ self.download_value = downloads
+ self.downloadsChanged.emit()
update = value.get('update') or {}
if update.get('remind') and update.get('key') != self.alerted and engine.rootObjects():
# Flash the taskbar button once per new reminder when the
@@ -166,6 +176,26 @@ def create_ui(session, *, show=True):
if path:
self.invoke(session.add_folder, path) if key == 'model_dirs' else self.invoke(session.edit, key, path)
+ @Slot()
+ def prepareDownloadList(self):
+ self.invoke(session.prepare_download_list)
+
+ @Slot()
+ def exportDownloadList(self):
+ if session.controller.busy:
+ return
+ path = QFileDialog.getExistingDirectory(None, session.downloads_view()['copy']['export'], '', QFileDialog.ShowDirsOnly)
+ if path:
+ self.invoke(session.export_downloads, path)
+
+ @Slot()
+ def useDownloadedFolder(self):
+ if session.controller.busy or session.importer.busy:
+ return
+ path = QFileDialog.getExistingDirectory(None, session.downloads_view()['copy']['use_folder'], '', QFileDialog.ShowDirsOnly)
+ if path:
+ self.invoke(session.use_downloaded_folder, path)
+
@Slot()
def browsePackages(self):
if session.controller.busy or session.importer.busy:
@@ -237,6 +267,13 @@ def create_ui(session, *, show=True):
else:
self.invoke(open_browser, value)
+ @Slot()
+ def openDownloadFolder(self):
+ from PySide6.QtGui import QDesktopServices
+ folder = session.download_export
+ if folder and Path(folder).is_dir():
+ self.invoke(QDesktopServices.openUrl, QUrl.fromLocalFile(str(Path(folder).resolve())))
+
@Slot(str)
def selectSource(self, value):
self.invoke(session.select_source, value)
@@ -292,17 +329,11 @@ def create_ui(session, *, show=True):
self.timer.stop()
session.close()
- from .model_guidance import links, cloud_models
- from .launcher_copy import display
+ from .model_guidance import cloud_models
engine = QQmlApplicationEngine()
bridge = Bridge()
engine.rootContext().setContextProperty('backend', bridge)
engine.rootContext().setContextProperty('initialState', bridge.value)
- # Nested Python tuples remain opaque objects in QML. Named maps become
- # QVariantMaps, so both the displayed label and clicked URL are available.
- engine.rootContext().setContextProperty('modelLinks', {
- component: [dict(label=label, label_zh=display(label, True), url=url) for label, url in rows]
- for component, rows in links().items()})
engine.rootContext().setContextProperty('cloudLinks', cloud_models())
engine.rootContext().setContextProperty('theme', theme())
engine.load(QUrl.fromLocalFile(str(Path(__file__).parent / 'launcher/Main.qml')))
diff --git a/freevideo_engine/offline_packages.py b/freevideo_engine/offline_packages.py
index d304b65..4f6c526 100644
--- a/freevideo_engine/offline_packages.py
+++ b/freevideo_engine/offline_packages.py
@@ -404,9 +404,14 @@ def assemble(runtime, models, source, progress=lambda **kw: None):
except OSError:
copy_progress(src, target, file_progress(progress, 'copy_bytes', src.stat().st_size))
+ included = []
for row in model['files']:
target, src = runtime / row['path'], source_for(row)
if src is None:
+ if pack_name(row['path']) == '采样缓存':
+ total -= row['bytes']
+ progress(done=done, total=total, detail='检查配套包', activity='')
+ continue
raise ValueError('还需导入「%s」包,缺少文件:%s' % (pack_name(row['path']), row['path']))
if row['path'] in here:
if not os.path.samefile(target, src) and hash_file(target,
@@ -414,6 +419,7 @@ def assemble(runtime, models, source, progress=lambda **kw: None):
raise ValueError('离线安装已有不同模型,未覆盖:' + plain(target))
else:
place(src, target)
+ included.append(row)
done += row['bytes']
progress(done=done, total=total, detail='检查配套包', activity='')
listed = {row['path'] for row in model['files']}
@@ -431,7 +437,8 @@ def assemble(runtime, models, source, progress=lambda **kw: None):
place(io_path(root) / row['path'], runtime / row['path'])
listed.add(row['path'])
progress(done=done, total=total, detail='检查配套包', activity='')
- return finish(runtime, config, model, source, here)
+ # Only placed rows are recorded: a skipped Sampling caches table is fetched when needed.
+ return finish(runtime, config, dict(model, files=included), source, here)
def runtime_config(runtime):
diff --git a/freevideo_engine/provision.py b/freevideo_engine/provision.py
index 583b17b..86d6d0b 100644
--- a/freevideo_engine/provision.py
+++ b/freevideo_engine/provision.py
@@ -7,10 +7,10 @@ import time
import threading
from concurrent.futures import ThreadPoolExecutor, CancelledError
-from .bootstrap import PACKAGE, model_target
+from .bootstrap import PACKAGE, model_target, installation_model_files
from .locking import runtime_lock
from .monitoring import save
-from .install_tuning import required_models, hf_receipt, unchanged_before
+from .install_tuning import hf_receipt, unchanged_before
from . import network
from .storage import record_download, compact_sources, fingerprint
from . import model_transfer
@@ -68,13 +68,8 @@ def models(plan):
ledger = root / 'verified-models.json'
stamps = json.loads(ledger.read_text(encoding='utf-8')) if ledger.is_file() else {}
model_dir, encoder_dir = (Path(plan[name]).expanduser().resolve() for name in ('model_dir', 'encoder_dir'))
- from . import prepared_model
prepared = plan.get('prepared_model')
- files = list(required_models(json.loads((PACKAGE / 'model_files.json').read_text(encoding='utf-8')), plan.get('reuse_cache') or prepared))
- files += prepared_model.files(prepared)
- from .sampling_assets import install_files, usable_with
- if prepared or (plan.get('reuse_cache') and usable_with(plan['reuse_cache'])):
- files += install_files(bool(plan.get('sampling_caches')))
+ files = installation_model_files(prepared, plan.get('reuse_cache'), plan.get('sampling_caches'))
mode = plan.get('verification', 'auto')
from .local_models import key as local_key, import_file
lock = threading.RLock()
diff --git a/freevideo_engine/sampling_assets.py b/freevideo_engine/sampling_assets.py
index e6114dd..1020391 100644
--- a/freevideo_engine/sampling_assets.py
+++ b/freevideo_engine/sampling_assets.py
@@ -5,14 +5,82 @@ Uses the installer's catalogs, measurements, connection preferences and verified
resumable transfers. No model import, GPU work or prompt text is needed here.
"""
import json
+import errno
from functools import lru_cache
from pathlib import Path
+import re
+import sys
import time
from . import disk_space
from .long_paths import io_path, plain_errors
COMMUNITY_PREFIX = 'community-sigma3-'
WORKERS = 6
+UNAVAILABLE = 'SAMPLING_TABLE_UNAVAILABLE: '
+
+
+class SamplingTableUnavailable(RuntimeError):
+ """A request's tables could not be downloaded; keep the transfer cause copyable."""
+ def __init__(self, details, cause):
+ self.details = details
+ super().__init__(UNAVAILABLE + json.dumps(details, separators=(',', ':')) + '\n' + str(cause))
+
+
+class _DownloadFailure(Exception):
+ def __init__(self, cause):
+ self.cause = cause
+
+
+def _cancel_or_disk(error):
+ return (isinstance(error, (InterruptedError, KeyboardInterrupt)) or
+ isinstance(error, OSError) and error.errno == errno.ENOSPC or
+ bool(re.search(r'interrupt|cancel', type(error).__name__, re.I)) or
+ bool(re.search(r'cancelled|canceled|interrupted|not enough disk space|insufficient disk space|'
+ r'no space left|\[Errno 28\]|\[WinError 112\]|取消|磁盘空间不足', str(error), re.I)))
+
+
+def available_levels(cache, shared, manifest, kind, catalog):
+ """Complete tables for this task and these weights, including the bundled 8 steps."""
+ from . import adaln_assets as assets
+ weights = assets.weight_identity(manifest)
+ # Bundled tables have no task field; their exact clock identifies the task.
+ # Match its published refinement clock's channels/dtype/modality contract.
+ task_tables = [t for t in catalog if t.get('task') == kind and t['identity']['weights'] == weights]
+ identities = [t['identity'] for t in task_tables]
+ bundled = [t for t in manifest.get('adaln_tables', []) if kind in ('t2va', 'i2va') and
+ t['identity']['weights'] == weights and any(
+ all(t['identity'].get(k) == identity.get(k) for k in ('channels', 'dtype', 'modality_rows'))
+ and len(t['identity']['timesteps'][0]) == len(identity['timesteps'][0])
+ for identity in identities)]
+
+ def ready(table, embedded=False):
+ for row in table['files']:
+ found = False
+ for folder in ((cache,) if embedded else (cache, shared)):
+ path = assets.asset_path(folder, row['file'])
+ try:
+ marker = path.with_suffix('.json')
+ # Imported shared tables need no receipt yet: prepare()
+ # verifies them and writes one without downloading.
+ if not embedded and (folder == cache or marker.is_file()):
+ receipt = json.loads(marker.read_text(encoding='utf-8'))
+ if any(receipt.get(k) != row[k] for k in ('bytes', 'sha256')):
+ continue
+ assets.check_table(path, row, table['identity'])
+ found = True
+ break
+ except (OSError, ValueError, KeyError, TypeError):
+ continue
+ if not found:
+ return False
+ return bool(table['files'])
+
+ def base_ready(steps):
+ return any(len(t['identity']['timesteps']) == steps and ready(t, True) for t in bundled) or any(
+ not refinement(t) and len(t['identity']['timesteps']) == steps and ready(t) for t in task_tables)
+
+ refine_ready = any(refinement(t) and ready(t) for t in task_tables)
+ return [i for i, steps in enumerate((8, 12, 16, 20)) if base_ready(steps) and (i != 0 or refine_ready)]
@plain_errors
@@ -171,7 +239,8 @@ def prepare(root, machine, sampling, task, *, progress, interrupted=None, enviro
count = len(table['identity']['timesteps'])
return (count == 3 and sampling.get('refine_schedule') == COMMUNITY if refinement(table)
else count == sampling['base_steps'])
- selected = [t for t in tables() if t.get('task') == kind
+ catalog = tables()
+ selected = [t for t in catalog if t.get('task') == kind
and needed(t) and t['identity']['weights'] == weights]
root = Path(root)
shared = cache_root(machine['model_root'])
@@ -241,9 +310,14 @@ def prepare(root, machine, sampling, task, *, progress, interrupted=None, enviro
def moved(current, size, speed, **_):
done[index], speeds[index] = current, speed or 0.
emit()
- network.download(network.model_urls(networking, spec, environ), path, row['sha256'], moved,
- network=networking, size=row['bytes'], category=network.model_family(spec), headers_for=headers,
- keep_partial=True, stall_seconds=30, slow_seconds=15, low_speed_limit=64*1024)
+ try:
+ network.download(network.model_urls(networking, spec, environ), path, row['sha256'], moved,
+ network=networking, size=row['bytes'], category=network.model_family(spec), headers_for=headers,
+ keep_partial=True, stall_seconds=30, slow_seconds=15, low_speed_limit=64*1024)
+ except Exception as error:
+ if _cancel_or_disk(error):
+ raise
+ raise _DownloadFailure(error) from error
# network.download already verified the SHA-256.
assets.check_table(path, row, table['identity'], verify_hash=False)
save(path.with_suffix('.json'), dict(bytes=row['bytes'], sha256=row['sha256']))
@@ -254,17 +328,26 @@ def prepare(root, machine, sampling, task, *, progress, interrupted=None, enviro
emit(force=True)
emit(force=True)
# Each table is fifty small files; several transfers hide per-file latency.
+ failure = None
with ThreadPoolExecutor(max_workers=min(WORKERS, len(missing)), thread_name_prefix='sampling-cache') as pool:
futures = [pool.submit(fetch, index, *item) for index, item in enumerate(missing)]
# A cancel reaches one worker (ComfyUI clears its flag once raised): stop
# the rest at once instead of waiting for earlier transfers to finish.
- done, _ = wait(futures, return_when=FIRST_EXCEPTION)
- failed = next((future for future in futures if future in done and future.exception()), None)
+ completed, _ = wait(futures, return_when=FIRST_EXCEPTION)
+ failed = next((future for future in futures if future in completed and future.exception()), None)
if failed is not None:
stop.set()
for future in futures:
future.cancel()
- raise failed.exception()
+ failure = failed.exception()
+ if isinstance(failure, _DownloadFailure):
+ details = dict(base_steps=sampling['base_steps'], two_pass=bool(sampling.get('enabled')),
+ refine_steps=sampling.get('refine_steps', 0), missing_bytes=total,
+ available=available_levels(cache, shared, manifest, kind, catalog),
+ decimal_sizes=sys.platform == 'darwin')
+ raise SamplingTableUnavailable(details, failure.cause) from failure.cause
+ if failure is not None:
+ raise failure
seconds = time.monotonic() - started
retire_superseded(machine)
return dict(seconds=seconds, downloaded_bytes=total)
diff --git a/web/error_panel.js b/web/error_panel.js
index 201756e..dc15853 100644
--- a/web/error_panel.js
+++ b/web/error_panel.js
@@ -50,7 +50,18 @@ const PLAIN_ERRORS = [
function knownError(text) {
const lines = String(text).slice(0, 65536).split(/\r?\n/).map(line => line.trim()).filter(Boolean);
const index = /^FreeVideo generation failed(?: \(exit -?\d+\))?$/.test(lines[0] ?? '') ? 1 : 0;
- const line = (lines[index] ?? '').replace(/^[A-Za-z_][\w.]*(?:Error|Exception):\s*/, '');
+ const line = (lines[index] ?? '').replace(/^(?:[A-Za-z_][\w.]*(?:Error|Exception)|(?:[\w.]+\.)?SamplingTableUnavailable):\s*/, '');
+ if (line.startsWith('SAMPLING_TABLE_UNAVAILABLE: ')) {
+ try {
+ const d = JSON.parse(line.slice('SAMPLING_TABLE_UNAVAILABLE: '.length));
+ if (Number.isInteger(d.base_steps) && d.base_steps >= 1 && d.base_steps <= 32
+ && typeof d.two_pass === 'boolean' && Number.isInteger(d.refine_steps) && d.refine_steps >= 0 && d.refine_steps <= 31
+ && Number.isSafeInteger(d.missing_bytes) && d.missing_bytes > 0 && typeof d.decimal_sizes === 'boolean'
+ && Array.isArray(d.available) && d.available.every(i => Number.isInteger(i) && i >= 0 && i <= 3))
+ return {kind: 'sampling-table', base_steps: d.base_steps, two_pass: d.two_pass, refine_steps: d.refine_steps,
+ missing_bytes: d.missing_bytes, decimal_sizes: d.decimal_sizes, available: [...new Set(d.available)].sort()};
+ } catch { /* Malformed metadata stays in technical details. */ }
+ }
return PLAIN_ERRORS.find(error => line === error.message || error.aliases?.includes(line))?.key ?? null;
}
@@ -230,6 +241,37 @@ export function createErrorReport(detail, context = {}) {
export function failureAdvice(value, t, known = knownError(value)) {
const text = String(value).slice(0, 65536);
const row = (kind, title, summary, action) => ({kind, title: t(...title), summary: t(...summary), action: t(...action)});
+ if (known?.kind === 'sampling-table') {
+ // Names and plan matching follow sampling_effort.js; metadata carries no user text.
+ const levels = [['Light', '轻量'], ['Medium', '标准'], ['High', '精细'], ['Max', '极致']];
+ const index = [8, 12, 16, 20].findIndex((steps, i) => known.base_steps === steps
+ && known.two_pass === (i === 0) && (i !== 0 || known.refine_steps === 3));
+ const custom = index < 0;
+ // Iris: a level name and its 档 never break apart. The summary is set as text,
+ // so word joiners (U+2060) keep each group on one line instead of markup.
+ const keep = value => [...value].join('\u2060');
+ const join = language => {
+ const names = known.available.map(i => language ? `“${levels[i][1]}”` : levels[i][0]);
+ if (language) names[names.length - 1] += '档';
+ const kept = language ? names.map(keep) : names;
+ return kept.length < 2 ? kept[0] || '' : kept.slice(0, -1).join(language ? '、' : ', ') + (language ? '或' : ' or ') + kept.at(-1);
+ };
+ const bytes = known.missing_bytes;
+ // As launcher_copy.size_text: one decimal for GiB, whole MiB; decimal units on macOS.
+ let size = bytes >= 2**30 ? (bytes / 2**30).toFixed(1) + ' GiB' : Math.floor(bytes / 2**20) + ' MiB';
+ if (known.decimal_sizes) {
+ const unit = [[1e12, 'TB', 2], [1e9, 'GB', 2], [1e6, 'MB', 1]].find(([scale]) => bytes >= scale);
+ size = unit ? Number((bytes / unit[0]).toFixed(unit[2])) + ' ' + unit[1] : Math.round(bytes / 1e3) + ' KB';
+ }
+ // A custom step count is not a quality level: no "档" / "quality level" for it.
+ const title = custom
+ ? [`The sampling table for Custom (${known.base_steps} steps) is not downloaded yet`, `“自定义(${known.base_steps} 步)”的采样表还没有下载`]
+ : [`The ${levels[index][0]} quality level's sampling table is not downloaded yet`, `${keep(`“${levels[index][1]}”档`)}的采样表还没有下载`];
+ const what = custom ? ['the sampling table for this step count', '这个步数的采样表'] : ["that level's sampling table", '这一档的采样表'];
+ return {...row('sampling-table', title,
+ [`This video first needs ${what[0]} (about ${size}), and it could not be downloaded this time. Check the network connection and generate again; FreeVideo downloads it automatically.${known.available.length ? ` You can also switch to a quality level that is already available: ${join(0)}.` : ''}`,
+ `这次生成需要先下载${what[1]}(约 ${size}),但这次没能下载。请确认网络连接后再生成一次,FreeVideo 会自动下载。${known.available.length ? `也可以改用已经可以使用的${join(1)}。` : ''}`], ['', '']), plain: true};
+ }
// ComfyUI and worker tracebacks carry English exceptions. Translate these
// actionable failures through the existing signature/advice path.
for (const {key, title, summary} of PLAIN_ERRORS) {
@@ -471,7 +513,7 @@ export function createErrorPanel(t) {
? t('Use Download report in the preview or node panel for the diagnostic report.', '完整诊断请使用预览区或节点面板中的“下载报告”。')
: t('Known input text, paths and common credentials are removed. Export saves a local error summary; review it before sharing.',
'已去除已知输入文本、路径和常见凭据。导出会保存本地错误摘要,分享前可查看内容。');
- copy.textContent = t('Copy error', '复制错误');
+ copy.textContent = advice.kind === 'sampling-table' ? t('Copy full details', '复制完整详情') : t('Copy error', '复制错误');
if (popup) showFailureDialog(report, t);
return report;
}, clear() { currentReport = null; details.value = ''; element.hidden = true; }};