diff --git a/.github/workflows/install.yml b/.github/workflows/install.yml index 086a21c0..5c8e32e5 100644 --- a/.github/workflows/install.yml +++ b/.github/workflows/install.yml @@ -2,6 +2,10 @@ name: Installation and launchers # Pull requests run the installation checks. The launchers are built and published only when this # workflow is run with "release" checked: main becomes the stable release vX.Y.Z and users get an # update notice; Windows signing then waits for the release environment. A merge to main builds nothing. +# A release can also go in two runs, so that what users get is the file that was tested: "stage" builds and +# signs the launchers and keeps them (and their SHA-256 list) for 7 days without publishing anything; the +# release checks test those files; then "promote_run" (that run's ID) with "expected_sha256" (the tested +# files) publishes the same files from that run, rebuilding nothing, and stops if any byte differs. on: pull_request: paths-ignore: @@ -16,11 +20,23 @@ on: description: 'Also diagnose the currently published package before rebuilding' type: boolean default: false + stage: + description: 'Build and sign the launchers for the release checks and keep them for 7 days; nothing is published' + type: boolean + default: false + promote_run: + description: 'Publish main as the stable release from the launchers of this earlier stage run (its run ID); nothing is rebuilt' + type: string + default: '' + expected_sha256: + description: 'With promote_run: the tested files, one " " line each; any other bytes stop the release' + type: string + default: '' permissions: contents: read # Stable runs have their own group: a later merge must not replace a pending release. concurrency: - group: freevideo-public-${{ github.event.pull_request.number || github.ref }}-${{ github.event_name == 'workflow_dispatch' && inputs.release && 'stable' || 'build' }} + group: freevideo-public-${{ github.event.pull_request.number || github.ref }}-${{ github.event_name == 'workflow_dispatch' && (inputs.release || inputs.stage || inputs.promote_run != '') && 'stable' || 'build' }} cancel-in-progress: ${{ github.event_name == 'pull_request' }} jobs: installation: @@ -49,9 +65,25 @@ jobs: run: | python -m pip install build python -m build + - name: Check that one kind of release run was asked for + if: github.event_name == 'workflow_dispatch' + env: + RELEASE: ${{ inputs.release }} + STAGE: ${{ inputs.stage }} + PROMOTE: ${{ inputs.promote_run }} + EXPECTED: ${{ inputs.expected_sha256 }} + run: | + kinds=0 + [ "$RELEASE" = true ] && kinds=$((kinds + 1)) + [ "$STAGE" = true ] && kinds=$((kinds + 1)) + [ -n "$PROMOTE" ] && kinds=$((kinds + 1)) + if [ "$kinds" -gt 1 ]; then echo "::error::Choose one of release, stage and promote_run."; exit 1; fi + if [ -n "$PROMOTE" ] && { ! [[ "$PROMOTE" =~ ^[0-9]+$ ]] || [ -z "$EXPECTED" ]; }; then + echo "::error::promote_run is a run ID and needs expected_sha256 (the tested files)."; exit 1 + fi # Fail a stable run before anyone is asked to approve signing. - name: Check that this version is not released yet - if: github.event_name == 'workflow_dispatch' && inputs.release + if: github.event_name == 'workflow_dispatch' && (inputs.release || inputs.stage || inputs.promote_run != '') env: GH_TOKEN: ${{ github.token }} run: | @@ -63,7 +95,7 @@ jobs: echo "Publishing v$version" windows: # Built only for a release; pull requests run the installation checks only. - if: github.event_name == 'workflow_dispatch' && inputs.release + if: github.event_name == 'workflow_dispatch' && (inputs.release || inputs.stage) needs: [installation] runs-on: windows-2025 timeout-minutes: 60 @@ -71,7 +103,7 @@ jobs: contents: read id-token: write # Only stable releases are signed. They use the release environment, whose reviewers decide who can mint the OIDC token Azure trusts for signing. - environment: ${{ github.event_name == 'workflow_dispatch' && inputs.release && github.repository == 'FlashML-org/FreeVideo' && 'release' || '' }} + environment: ${{ github.event_name == 'workflow_dispatch' && (inputs.release || inputs.stage) && github.repository == 'FlashML-org/FreeVideo' && 'release' || '' }} env: PYTHONUTF8: '1' PYTHONIOENCODING: utf-8 @@ -101,7 +133,7 @@ jobs: # new final bytes must pass the mandatory protection gate below. exit 0 - name: Azure login (OIDC) - if: github.event_name == 'workflow_dispatch' && inputs.release && github.repository == 'FlashML-org/FreeVideo' + if: github.event_name == 'workflow_dispatch' && (inputs.release || inputs.stage) && github.repository == 'FlashML-org/FreeVideo' uses: azure/login@a641126d1b8aa4d1fa005f4f92df94a3a4c4c906 # v3.1.0 with: client-id: ${{ vars.AZURE_CLIENT_ID }} @@ -109,13 +141,13 @@ jobs: subscription-id: ${{ vars.AZURE_SUBSCRIPTION_ID }} # The GitHub OIDC assertion behind the login expires after 5 minutes (azure-cli#29063). A signing token fetched now is cached by az for the whole job. - name: Fetch the signing token - if: github.event_name == 'workflow_dispatch' && inputs.release && github.repository == 'FlashML-org/FreeVideo' + if: github.event_name == 'workflow_dispatch' && (inputs.release || inputs.stage) && github.repository == 'FlashML-org/FreeVideo' run: | az account get-access-token --scope https://codesigning.azure.net/.default --output none if ($LASTEXITCODE -ne 0) { throw 'Could not get a codesigning.azure.net token' } # The launcher runs these scripts from its unpacked tree, where the executable's signature does not cover them. Sign the checkout's copies before the build bundles them. - name: Sign bundled PowerShell scripts - if: github.event_name == 'workflow_dispatch' && inputs.release && github.repository == 'FlashML-org/FreeVideo' + if: github.event_name == 'workflow_dispatch' && (inputs.release || inputs.stage) && github.repository == 'FlashML-org/FreeVideo' uses: azure/trusted-signing-action@c7ab2a863ab5f9a846ddb8265964877ef296ee82 # v2.0.0 with: endpoint: https://eus.codesigning.azure.net/ @@ -136,7 +168,7 @@ jobs: python scripts/build_windows.py --out build/windows-exe if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE } - name: Sign Windows launchers - if: github.event_name == 'workflow_dispatch' && inputs.release && github.repository == 'FlashML-org/FreeVideo' + if: github.event_name == 'workflow_dispatch' && (inputs.release || inputs.stage) && github.repository == 'FlashML-org/FreeVideo' uses: azure/trusted-signing-action@c7ab2a863ab5f9a846ddb8265964877ef296ee82 # v2.0.0 with: endpoint: https://eus.codesigning.azure.net/ @@ -150,7 +182,7 @@ jobs: timestamp-digest: SHA256 # Check the copies that ship: the folder layout exposes every bundled script on disk, and the one-file launcher is built from the same inputs. - name: Verify signatures and rebuild the folder ZIP around the signed launcher - if: github.event_name == 'workflow_dispatch' && inputs.release && github.repository == 'FlashML-org/FreeVideo' + if: github.event_name == 'workflow_dispatch' && (inputs.release || inputs.stage) && github.repository == 'FlashML-org/FreeVideo' shell: pwsh run: | $scripts = @(Get-ChildItem build/windows-folder/dist -Recurse -Filter *.ps1 | ForEach-Object FullName) @@ -188,9 +220,9 @@ jobs: build/windows-exe/dist/FreeVideo.exe build/windows-exe/dist/launcher-build.json if-no-files-found: error - retention-days: 1 + retention-days: ${{ inputs.stage && 7 || 1 }} macos: - if: github.event_name == 'workflow_dispatch' && inputs.release + if: github.event_name == 'workflow_dispatch' && (inputs.release || inputs.stage) needs: [installation] runs-on: macos-15 timeout-minutes: 30 @@ -230,7 +262,7 @@ jobs: name: macos-launcher path: build/macos-publish/ if-no-files-found: error - retention-days: 1 + retention-days: ${{ inputs.stage && 7 || 1 }} - name: Keep failure diagnostics if: failure() uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7.0.1 @@ -243,7 +275,7 @@ jobs: if-no-files-found: ignore retention-days: 1 linux: - if: github.event_name == 'workflow_dispatch' && inputs.release + if: github.event_name == 'workflow_dispatch' && (inputs.release || inputs.stage) needs: [installation] runs-on: ubuntu-24.04 timeout-minutes: 40 @@ -291,7 +323,7 @@ jobs: name: linux-launcher path: build/linux-publish/ if-no-files-found: error - retention-days: 1 + retention-days: ${{ inputs.stage && 7 || 1 }} - name: Keep failure diagnostics if: failure() uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7.0.1 @@ -334,3 +366,105 @@ jobs: run: >- python scripts/publish_release.py --track stable --windows build/windows --macos build/macos --linux build/linux --sha ${{ github.sha }} + stage-sums: + # A stage run ends here. The release checks download these launchers with this list and test them; promote_run + # later publishes the same files from this run. + if: github.event_name == 'workflow_dispatch' && inputs.stage + needs: [windows, macos, linux] + runs-on: ubuntu-24.04 + timeout-minutes: 10 + permissions: + contents: read + steps: + - uses: actions/download-artifact@37930b1c2abaa49bbe596cd826c3c89aef350131 # v7.0.0 + with: + name: windows-launcher + path: build/windows + - uses: actions/download-artifact@37930b1c2abaa49bbe596cd826c3c89aef350131 # v7.0.0 + with: + name: macos-launcher + path: build/macos + - uses: actions/download-artifact@37930b1c2abaa49bbe596cd826c3c89aef350131 # v7.0.0 + with: + name: linux-launcher + path: build/linux + - name: List the launchers of this stage run + run: | + cd build + sha256sum windows/FreeVideo.exe macos/FreeVideo-Mac-arm64.dmg linux/FreeVideo-Linux-x86_64.AppImage \ + | sed 's# [a-z]*/# #' > stage-SHA256SUMS.txt + cat stage-SHA256SUMS.txt + { echo '```'; cat stage-SHA256SUMS.txt; echo '```'; } >> "$GITHUB_STEP_SUMMARY" + - name: Keep the list with the launchers + uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7.0.1 + with: + name: stage-sums + path: build/stage-SHA256SUMS.txt + if-no-files-found: error + retention-days: 7 + promote: + # Publishing without rebuilding: the launchers of the stage run in promote_run, only if they are the tested files. + if: github.event_name == 'workflow_dispatch' && inputs.promote_run != '' && github.repository == 'FlashML-org/FreeVideo' && github.ref == 'refs/heads/main' + needs: [installation] + runs-on: ubuntu-24.04 + timeout-minutes: 30 + # Publishing waits for the release environment: that approval is the decision to release. The stage run's own + # approval only signed a candidate for the release checks. + environment: release + permissions: + contents: write + actions: read + steps: + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + - uses: actions/setup-python@5fda3b95a4ea91299a34e894583c3862153e4b97 # v7.0.0 + with: + python-version: '3.12' + - name: Check that the stage run built this commit and finished + env: + GH_TOKEN: ${{ github.token }} + RUN: ${{ inputs.promote_run }} + run: | + gh api "repos/${{ github.repository }}/actions/runs/$RUN" --jq '[.path, .event, .status, .conclusion, .head_sha] | @tsv' > run.tsv + IFS=$'\t' read -r path event status conclusion head < run.tsv + if [ "$path" != .github/workflows/install.yml ] || [ "$event" != workflow_dispatch ] || [ "$status" != completed ] \ + || [ "$conclusion" != success ] || [ "$head" != "${{ github.sha }}" ]; then + echo "::error::Run $RUN is not a finished run of this workflow on ${{ github.sha }}: $path $event $status $conclusion $head" + exit 1 + fi + # stage-sums exists only in a stage run. + - uses: actions/download-artifact@37930b1c2abaa49bbe596cd826c3c89aef350131 # v7.0.0 + with: + name: stage-sums + path: build/stage + run-id: ${{ inputs.promote_run }} + github-token: ${{ github.token }} + - uses: actions/download-artifact@37930b1c2abaa49bbe596cd826c3c89aef350131 # v7.0.0 + with: + name: windows-launcher + path: build/windows + run-id: ${{ inputs.promote_run }} + github-token: ${{ github.token }} + - uses: actions/download-artifact@37930b1c2abaa49bbe596cd826c3c89aef350131 # v7.0.0 + with: + name: macos-launcher + path: build/macos + run-id: ${{ inputs.promote_run }} + github-token: ${{ github.token }} + - uses: actions/download-artifact@37930b1c2abaa49bbe596cd826c3c89aef350131 # v7.0.0 + with: + name: linux-launcher + path: build/linux + run-id: ${{ inputs.promote_run }} + github-token: ${{ github.token }} + - name: Write the list of tested files + env: + EXPECTED: ${{ inputs.expected_sha256 }} + run: printf '%s\n' "$EXPECTED" > build/tested-SHA256SUMS.txt + - name: Publish the tested launchers + env: + GH_TOKEN: ${{ github.token }} + GH_REPO: ${{ github.repository }} + run: >- + python scripts/publish_release.py --track stable + --windows build/windows --macos build/macos --linux build/linux --sha ${{ github.sha }} + --expected-sha256 build/tested-SHA256SUMS.txt diff --git a/THIRD_PARTY_NOTICES.md b/THIRD_PARTY_NOTICES.md index 5f591f69..4c429a11 100644 --- a/THIRD_PARTY_NOTICES.md +++ b/THIRD_PARTY_NOTICES.md @@ -42,6 +42,11 @@ FreeVideo code uses [Apache-2.0](LICENSE). Its dependencies and models retain th | [Noto Sans CJK SC and Noto Sans Mono CJK SC](https://github.com/notofonts/noto-cjk) 2.004, © 2014-2021 Adobe: subsets renamed FreeVideo Sans SC and FreeVideo Mono SC (image editor text, editor text and subtitles / 剪辑视图的文字和字幕, share card, Linux launcher) | [SIL OFL 1.1](freevideo_engine/licenses/Noto-CJK-Sans-OFL.txt) | | [Noto Serif CJK SC](https://github.com/notofonts/noto-cjk) 2.003, © 2017-2024 Adobe: subset renamed FreeVideo Serif SC (image editor text, editor text and subtitles / 剪辑视图的文字和字幕) | [SIL OFL 1.1](freevideo_engine/licenses/Noto-CJK-Serif-OFL.txt) | | [LXGW WenKai](https://github.com/lxgw/LxgwWenKai) v1.522, © 2021-2026 LXGW, © 2020 The Klee Project Authors: subset renamed FreeVideo Kai SC (image editor text, editor text and subtitles / 剪辑视图的文字和字幕) | [SIL OFL 1.1](freevideo_engine/licenses/LXGW-WenKai-OFL.txt) | +| [Noto Sans CJK TC and Noto Sans CJK KR](https://github.com/notofonts/noto-cjk) 2.004, © 2014-2021 Adobe: subsets renamed FreeVideo Sans TC and FreeVideo Sans KR (image editor text, share card) | [SIL OFL 1.1](freevideo_engine/licenses/Noto-CJK-Sans-OFL.txt) | +| [Noto Sans](https://github.com/notofonts/latin-greek-cyrillic) 2.015, © 2022 The Noto Project Authors: subset renamed FreeVideo Sans Vietnamese (image editor text, share card) | [SIL OFL 1.1](freevideo_engine/licenses/Noto-Sans-OFL.txt) | +| [Noto Sans Arabic](https://github.com/notofonts/arabic) 2.013, © 2022 The Noto Project Authors: subset renamed FreeVideo Sans Arabic (image editor text, share card) | [SIL OFL 1.1](freevideo_engine/licenses/Noto-Sans-Arabic-OFL.txt) | +| [Noto Sans Thai](https://github.com/notofonts/thai) 2.002, © 2022 The Noto Project Authors: subset renamed FreeVideo Sans Thai (image editor text, share card) | [SIL OFL 1.1](freevideo_engine/licenses/Noto-Sans-Thai-OFL.txt) | +| [Noto Sans Devanagari](https://github.com/notofonts/devanagari) 2.007, © 2022 The Noto Project Authors: subset renamed FreeVideo Sans Devanagari (image editor text, share card) | [SIL OFL 1.1](freevideo_engine/licenses/Noto-Sans-Devanagari-OFL.txt) | Original launcher license texts are included in Windows packages. Other runtime dependencies are listed in [constraints](constraints), with their license information in the installed packages. diff --git a/__init__.py b/__init__.py index cdb0437b..5113de6a 100644 --- a/__init__.py +++ b/__init__.py @@ -1,7 +1,9 @@ """Optional ComfyUI custom-node entry point; the engine also runs standalone.""" +from .freevideo_engine.system import comfy_node_process from .freevideo_engine.comfy_logging import configure_managed_logging from .freevideo_engine.comfy_privacy import configure_managed_privacy +comfy_node_process() # before anything reads the installation folder configure_managed_logging() configure_managed_privacy() diff --git a/docs/community-results.md b/docs/community-results.md index f5492bab..840055a5 100644 --- a/docs/community-results.md +++ b/docs/community-results.md @@ -150,6 +150,8 @@ Thanks to the community members who sent diagnostic reports. FreeVideo already r | 5060 Ti | 16 GB | 32 GB | 1344×768 | 10 s | Light | 0.5.1 | 716 s | 0.5.1 | Already optimal | | 4060 Laptop | 8 GB | 16 GB | 1344×768 | 10 s | Light | 0.5.1 | 882 s | 0.5.1 | Already optimal | | M4 Max | Unified | 128 GB | 1344×768 | 10.1 s | Light | 0.5.4 | 3399 s | 0.5.4 | Already optimal | +| RTX Spark N1X | 110 GB | 32 GB | 832×640 | 15.1 s | Light | 0.6.12 | 1298 s | 0.6.12 | GPU shared¹⁶ | +| RTX Spark N1X | 110 GB | 32 GB | 1920×1088 | 15.1 s | Medium | 0.6.12 | 4400 s¹² | 0.6.12 | Power limited¹⁷ | - Time: end to end, from submission until the video is saved. - After: the estimated time, derived from the report's stage times and from complete planned runs on our test machines (RTX 3090 and RTX 5060 Ti on Windows, RTX PRO 6000 on Linux) under the reporting machine's VRAM and RAM limits, not from reruns on that machine. @@ -169,3 +171,5 @@ Thanks to the community members who sent diagnostic reports. FreeVideo already r - ¹³ Preview (first pass only). - ¹⁴ Compatibility level 3 was set manually; it is the slowest level and made each step about 2.4 times slower than the automatic setting for this request, and the GPU core clock also stayed at 900 MHz against the 1815 MHz it reached. With the level off, the same request takes about 1100 s. - ¹⁵ The video model is read from the drive again at every step, at about 110 MB/s on this machine; the graphics card was busy for about 9–13% of the first pass and 36% of the second pass. +- ¹⁶ GPU shared: another program was using about 40% of the graphics card during the first nine of the eleven steps, which took 103–128 s each against about 55 s once it stopped. With the card free, the same request is estimated at about 830 s. +- ¹⁷ Power-limited: the system's power limit lowered the graphics card's clock as the run went on, from about 1943 MHz at 49 W in the first step to about 1285 MHz at 23 W in the ninth and about 995 MHz while decoding. Without this slowdown, the same request is estimated at about 2500 s. diff --git a/docs/zh-CN/community-results.md b/docs/zh-CN/community-results.md index 1f5eeb45..de38e756 100644 --- a/docs/zh-CN/community-results.md +++ b/docs/zh-CN/community-results.md @@ -150,6 +150,8 @@ | 5060 Ti | 16 GB | 32 GB | 1344×768 | 10 s | 轻⁠量 | 0.5.1 | 716 s | 0.5.1 | 已⁠是⁠最⁠优 | | 4060 笔⁠记⁠本 | 8 GB | 16 GB | 1344×768 | 10 s | 轻⁠量 | 0.5.1 | 882 s | 0.5.1 | 已⁠是⁠最⁠优 | | M4 Max | 统⁠一⁠内⁠存 | 128 GB | 1344×768 | 10.1 s | 轻⁠量 | 0.5.4 | 3399 s | 0.5.4 | 已⁠是⁠最⁠优 | +| RTX Spark N1X | 110 GB | 32 GB | 832×640 | 15.1 s | 轻⁠量 | 0.6.12 | 1298 s | 0.6.12 | 显⁠卡⁠被⁠占⁠用¹⁶ | +| RTX Spark N1X | 110 GB | 32 GB | 1920×1088 | 15.1 s | 标⁠准 | 0.6.12 | 4400 s¹² | 0.6.12 | 功⁠耗⁠受⁠限¹⁷ | - 用时:从提交到视频保存完成的端到端用时。 - 优化后:预估用时,根据报告中的分段用时,结合测试机(Windows RTX 3090 和 RTX 5060 Ti、Linux RTX PRO 6000)在报告机器的显存和内存上限下运行完整规划的实测推算,不是在报告机器上重跑。 @@ -169,3 +171,5 @@ - ¹³ 预览(只做第一遍)。 - ¹⁴ 兼容等级 3 为手动设置,是最慢的等级,对这个请求每步比自动设置慢约 2.4 倍;显卡核心时钟同时固定在 900 MHz(本次运行曾达到 1815 MHz)。关闭该等级后,同样的请求约需 1100 秒。 - ¹⁵ 视频模型每一步都要从硬盘重新读取,这台机器上读取速度约 110 MB/s;显卡在第一遍约 9–13% 的时间在工作,第二遍约 36%。 +- ¹⁶ 显卡被占用:11 步中的前 9 步里,另有程序占用了约 40% 的显卡,这些步每步 103–128 秒,占用消失后每步约 55 秒;显卡空出来时,同样的请求估计约需 830 秒。 +- ¹⁷ 功耗受限:运行中系统的功耗上限让显卡频率越来越低,从第 1 步约 1943 MHz、49 W 降到第 9 步约 1285 MHz、23 W,解码时约 995 MHz;不降频时,同样的请求估计约需 2500 秒。 diff --git a/freevideo.ps1 b/freevideo.ps1 index 97451f97..0f3d12b7 100644 --- a/freevideo.ps1 +++ b/freevideo.ps1 @@ -95,19 +95,23 @@ try { $env:UV_PYTHON_INSTALL_DIR = Join-Path $bootstrapRoot 'python' $env:UV_NO_CONFIG = '1' $installed = $false - $pythonRoutes = @($routes | ForEach-Object { "$_/astral-sh/python-build-standalone/releases/download" }) - if (-not $officialOnly) { - # The GitHub mirror refuses the Python runtime files: the public npmmirror copy - # (same SHA-256 that uv pins) is tried before it. Keep in sync with network.py. - $pythonRoutes = @($pythonRoutes[0]) + @('https://registry.npmmirror.com/-/binary/python-build-standalone') + @($pythonRoutes | Select-Object -Skip 1) - } + # Python sources: begin (scripts/test_windows_python_sources.ps1 runs this block with a stand-in for uv) + # The GitHub mirror (ghfast) refuses the Python runtime files (403), so it is not a Python source: + # GitHub, then the public npmmirror copy (same SHA-256 that uv pins). Keep in sync with + # bootstrap.python_sources. + $pythonRoutes = @('https://github.com/astral-sh/python-build-standalone/releases/download') + if (-not $officialOnly) { $pythonRoutes += 'https://registry.npmmirror.com/-/binary/python-build-standalone' } if (-not $officialOnly -and $freevideoSavedEnvironment['UV_PYTHON_INSTALL_MIRROR']) { $pythonRoutes = @($freevideoSavedEnvironment['UV_PYTHON_INSTALL_MIRROR']) + $pythonRoutes } + # Security software or a policy that stops a Python file from being written: the same table as the launcher. + $blockedTable = Get-FreeVideoBlockedTable (Join-Path $PSScriptRoot 'freevideo_engine\windows_blocked.json') $attempt = 0 $otherFailures = $false $slowRoutes = @{} $deniedRoutes = @{} + $blockedRoutes = @{} + $sourceResults = @() # Keep these defaults and the notice in sync with network.py (CPU tests). $pythonRetryProfiles = @( @{Mode='fast'; UV_HTTP_TIMEOUT='20'; UV_HTTP_RETRIES='1'}, @@ -115,9 +119,11 @@ try { ) foreach ($profile in $pythonRetryProfiles) { if ($installed) { break } + # A source that refused access (HTTP 401/403) or whose file Windows blocked says nothing + # about a source that timed out: neither cancels its slow retry. if ($profile.Mode -eq 'patient') { if ($otherFailures) { break } - $retryRoutes = @($slowRoutes.Keys | Where-Object { -not $deniedRoutes.ContainsKey($_) }) + $retryRoutes = @($slowRoutes.Keys | Where-Object { -not $deniedRoutes.ContainsKey($_) -and -not $blockedRoutes.ContainsKey($_) }) if ($retryRoutes.Count -eq 0) { break } Write-Host 'The network is slow. Downloading again; this may take a while.' $patientDownloadNotice = $true @@ -131,7 +137,7 @@ try { [Environment]::SetEnvironmentVariable($name, $value, 'Process') } foreach ($route in $pythonRoutes) { - if ($profile.Mode -eq 'patient' -and $deniedRoutes.ContainsKey($route)) { continue } + if ($profile.Mode -eq 'patient' -and ($deniedRoutes.ContainsKey($route) -or $blockedRoutes.ContainsKey($route))) { continue } foreach ($proxyRoute in $proxyRoutes) { if ($installed) { break } $attempt++ @@ -160,19 +166,64 @@ try { $pythonOutput = $originalOutput } } + # The download arrived but Windows did not let uv write a file of it (security software + # still examining it, or another program holding it): the same source again after each wait. + $blocked = $null + if ($pythonExit -ne 0) { $blocked = Get-FreeVideoUnpackBlocked $pythonOutput $blockedTable } + foreach ($wait in $blockedTable.Waits) { + if (-not $blocked -or $blockedTable.Retry -notcontains $blocked.Code) { break } + Write-Host "Windows did not let setup write $($blocked.File) (Windows error $($blocked.Code)). Trying the same source again in $wait s." + Start-Sleep -Seconds $wait + $pythonOutput = '' + $pythonExit = Invoke-FreeVideoBootstrapCommand -Executable $uv ` + -Arguments @('python', 'install', '--no-bin', '--no-registry', '--no-progress', '--color', 'never', $versions.python) ` + -LogPath $bootstrapLog -Label ($pythonLabel + ", again after $wait s") ` + -Direct:($proxyRoute -eq 'direct') -OutputTail ([ref]$pythonOutput) + $blocked = $null + if ($pythonExit -ne 0) { $blocked = Get-FreeVideoUnpackBlocked $pythonOutput $blockedTable } + } if ($pythonExit -eq 0) { $installed = $true; break } - if (Test-FreeVideoAccessDenied $pythonOutput) { $deniedRoutes[$route] = $true } - elseif (Test-FreeVideoSlowDownloadFailure $pythonOutput) { $slowRoutes[$route] = $true } - else { $otherFailures = $true } + if ($blocked) { $blockedRoutes[$route] = $true; $kind = 'blocked' } + elseif (Test-FreeVideoAccessDenied $pythonOutput) { $deniedRoutes[$route] = $true; $kind = 'refused' } + elseif (Test-FreeVideoSlowDownloadFailure $pythonOutput) { $slowRoutes[$route] = $true; $kind = 'slow' } + else { $otherFailures = $true; $kind = 'other' } Write-Host "Python install source $attempt returned exit code $pythonExit. Details retained in $bootstrapLog" $pythonReason = Get-FreeVideoFailureReason $pythonOutput if ($pythonReason) { Write-Host "uv reported: $pythonReason" } + $sourceHost = '' + try { $sourceHost = ([Uri]$route).Host } catch { $sourceHost = 'custom' } + $sourceResults += ,@{Attempt = $attempt; Host = $sourceHost; Kind = $kind; Exit = $pythonExit; Reason = $pythonReason; Blocked = $blocked} } } } - $pythonDetail = '' - if ($pythonReason) { $pythonDetail = " uv reported: $pythonReason." } - if (-not $installed) { throw "Python installation failed (uv exit $pythonExit).$pythonDetail Check your network or connection mode in Downloads. See $bootstrapLog and retry." } + if (-not $installed) { + # Every source's result reaches the console (and so the launcher's report) and the log; the + # message leads with the failure that matters most: a file Windows blocked on this computer, + # then any other error, then a slow network, then a source that refused access. + $resultsLine = 'Python install sources: ' + (($sourceResults | ForEach-Object { "$($_.Attempt) $($_.Host) $($_.Kind)" }) -join '; ') + Write-Host $resultsLine + [IO.File]::AppendAllText($bootstrapLog, ('[' + [DateTime]::UtcNow.ToString('o') + '] ' + $resultsLine + [Environment]::NewLine), (New-Object System.Text.UTF8Encoding($false))) + $lead = $null + foreach ($kind in @('blocked', 'other', 'slow', 'refused')) { + $lead = $sourceResults | Where-Object { $_.Kind -eq $kind } | Select-Object -First 1 + if ($lead) { break } + } + if (-not $lead) { throw "Python installation failed (uv exit $pythonExit). Check your network or connection mode in Downloads. See $bootstrapLog and retry." } + if ($lead.Kind -eq 'blocked') { + # failure_details reads the marker and the reason in brackets (windows_blocked.python_file_message). + throw ("Python installation failed: Windows did not let setup write a Python file [PYTHON_FILE_BLOCKED $($lead.Blocked.Reason)] (Windows error $($lead.Blocked.Code)): $($lead.Blocked.File). " + + "Allow the FreeVideo folder in the security software, then retry. See $bootstrapLog.") + } + $leadDetail = '' + if ($lead.Reason) { $leadDetail = " uv reported for source $($lead.Attempt) ($($lead.Host)): $($lead.Reason)." } + if ($lead.Kind -eq 'slow' -or $lead.Kind -eq 'refused') { + # Every source failed on the network (nothing blocked, no other error): the launcher's download card, + # with its source switch, reads this sentence (failure_details, as for setup in Python). + throw "Python download failed on every route (uv exit $($lead.Exit)).$leadDetail Check your network or connection mode in Downloads. See $bootstrapLog and retry." + } + throw "Python installation failed (uv exit $($lead.Exit)).$leadDetail Check your network or connection mode in Downloads. See $bootstrapLog and retry." + } + # Python sources: end $freevideoPython = (& $uv python find --managed-python $versions.python | Select-Object -Last 1).Trim() if ($LASTEXITCODE -ne 0 -or -not (Test-Path -LiteralPath $freevideoPython)) { throw "Python was installed but could not be found (uv exit $LASTEXITCODE). See $bootstrapLog, then run the same command again." } } finally { diff --git a/freevideo_engine/adaln.py b/freevideo_engine/adaln.py index b45a56f4..90b8360c 100644 --- a/freevideo_engine/adaln.py +++ b/freevideo_engine/adaln.py @@ -7,7 +7,10 @@ import contextlib import hashlib import json +import os from pathlib import Path +import time +import uuid from safetensors.torch import load_file, save_file import torch @@ -166,6 +169,7 @@ def __init__(self, root, source_id, steps, task='t2va', *, manifest=None, # nothing; a table that is not there is not fetched (see load). return self.root.mkdir(parents=True, exist_ok=True) + self.drop_stale_staging() marker = self.root / 'identity.json' if marker.exists(): if json.loads(marker.read_text(encoding='utf-8')) != self.identity: @@ -174,6 +178,12 @@ def __init__(self, root, source_id, steps, task='t2va', *, manifest=None, save(marker, self.identity) if manifest is not None: self.optional_asset = assets.optional_table(self.identity, manifest) + # An installation with the original projections computed the upscale clock's table from them, offline, before + # that table was published; it keeps doing so rather than now needing the network for it. + from .sampling_assets import UPSCALE_PREFIX + if (self.optional_asset is not None and self.optional_asset['download']['prefix'].startswith(UPSCALE_PREFIX) + and assets.sources_present(root, manifest)): + self.optional_asset = None def load(self, index, steps): from . import adaln_assets as assets @@ -181,6 +191,7 @@ def load(self, index, steps): raise ValueError('AdaLN cache schedule length mismatch') path = self.root / f'{index:02d}.safetensors' marker = path.with_suffix('.json') + checked = False if self.asset is None and not (path.is_file() and marker.is_file()) and self.shared is not None: path = self.shared / path.name marker = path.with_suffix('.json') @@ -198,8 +209,24 @@ def load(self, index, steps): self.optional_downloaded.add(index) self.optional_download_bytes += row['bytes'] else: - row = json.loads(marker.read_text(encoding='utf-8')) - assets.check_table(path, row, self.identity) + # Only a table this cache computed itself; published tables setup installed beside it keep failing loudly. + local = path.parent == self.root + try: + row = json.loads(marker.read_text(encoding='utf-8')) + assets.check_table(path, row, self.identity) + except (OSError, ValueError): + if not local: + raise + # Another process can be between renaming this table into place and writing its record. Read the + # record once more; a table that still does not match is computed again rather than failing. + try: + row = json.loads(marker.read_text(encoding='utf-8')) + assets.check_table(path, row, self.identity) + except (OSError, ValueError): + return self.placeholder(index) if not self.fetch else None + checked = True + if not checked: + assets.check_table(path, row, self.identity) if self.optional_asset is not None: published = next(r for r in self.optional_asset['files'] if r['index'] == index) if row['sha256'] == published['sha256']: @@ -227,21 +254,68 @@ def placeholder(self, index): return [torch.zeros(len(times) * self.identity['modality_rows'], width, dtype=torch.bfloat16, device=self.device).chunk(6, dim=-1) for times in self.identity['timesteps']] + def drop_stale_staging(self, age_seconds=3600): + """Remove staging files a killed writer left here. A table takes seconds to write, so a staging file older + than an hour belongs to no running writer; this is decided by age, not by process number, since a process + number can be reused (and probing one on Windows signals it).""" + cutoff = time.time() - age_seconds + for staging in self.root.glob('*.partial'): + try: + if staging.stat().st_mtime < cutoff: + staging.unlink() + except OSError: + pass + def save(self, index, module, *, producer_device=None): from . import adaln_assets as assets from .monitoring import save if self.asset is not None: raise ValueError('Published AdaLN model assets are immutable') path = self.root / f'{index:02d}.safetensors' - temporary = path.with_suffix('.partial') + # Two processes can compute the same table at the same moment (two engines or installations sharing one model + # folder). Each writes its own staging file and renames it into place whole; a shared staging name let one + # overwrite the other's half-written file. + temporary = path.with_name(f'{path.name}.{os.getpid()}.{uuid.uuid4().hex}.partial') state = {name: tensor.cpu() for name, tensor in module.state_dict().items()} if any(not all_finite(tensor) for tensor in state.values()): raise ValueError('Cannot save nonfinite AdaLN constants') - save_file(state, temporary) - row = {'bytes': temporary.stat().st_size, 'sha256': assets.file_hash(temporary)} - assets.check_table(temporary, row, self.identity, verify_hash=False) - temporary.replace(path) - save(path.with_suffix('.json'), row) + try: + save_file(state, temporary) + row = {'bytes': temporary.stat().st_size, 'sha256': assets.file_hash(temporary)} + assets.check_table(temporary, row, self.identity, verify_hash=False) + # Windows refuses the rename while another process has the table open (hashing or loading it); wait a + # little as monitoring.save does. A table this request computed is already in use in memory, so a cache + # that cannot take it now never fails the request: the table in place (or none) stays as it is. + for attempt in range(8): + try: + temporary.replace(path) + break + except PermissionError: + from .system import windows + if attempt == 7 or not windows(): + return # elsewhere a refusal is the folder's permissions, which waiting does not change + time.sleep(.1 * (attempt + 1)) + finally: + temporary.unlink(missing_ok=True) + # The table and its record are two files: another writer's table can land between this rename and this record. + # The record always describes the table that is there, so a later load never finds a mismatched pair. + marker = path.with_suffix('.json') + try: + for _ in range(8): + save(marker, row) + there = {'bytes': path.stat().st_size, 'sha256': assets.file_hash(path)} + if there == row: + break + assets.check_table(path, there, self.identity, verify_hash=False) + row = there + else: + # Still changing under other writers: leave no record rather than one that may not match, so the next + # load treats the table as missing and computes it again. + marker.unlink(missing_ok=True) + except PermissionError: + # Held open on Windows past monitoring.save's own retries: a load that finds the pair mismatched reads the + # record again and otherwise computes the table again. + return provenance = self.root / 'producer.json' if not provenance.exists(): from diffusers.models.transformers import transformer_minimax_h3 diff --git a/freevideo_engine/adaln_assets.py b/freevideo_engine/adaln_assets.py index dfa3f81a..9b57a260 100644 --- a/freevideo_engine/adaln_assets.py +++ b/freevideo_engine/adaln_assets.py @@ -82,6 +82,16 @@ def projection_groups(manifest): return sorted(rows, key=lambda r: r['group']) +def sources_present(cache, manifest): + """Whether the original projections are in this cache (a full installation, or a slim one that fetched them): + every listed file at its size. Size only, no hashing; computing from them checks them as before.""" + rows = projection_groups(manifest) + try: + return bool(rows) and all(asset_path(Path(cache), row['file']).stat().st_size == row['bytes'] for row in rows) + except (OSError, ValueError, KeyError, TypeError): + return False + + def weight_identity(manifest): roots = [r for r in manifest['groups'] if r['group'] == 'root'] if len(roots) != 1: diff --git a/freevideo_engine/agent/cast.py b/freevideo_engine/agent/cast.py index 57ee5f0b..6c1c9337 100644 --- a/freevideo_engine/agent/cast.py +++ b/freevideo_engine/agent/cast.py @@ -41,7 +41,7 @@ # Reference pictures made by the server (POST /cast/{id}/generate). Remy's consistency tests set the # defaults; the clip prompts live in reference_prompt and the labels follow its half turn. COUNT = 4 -PROMPT_VERSION = 1 +PROMPT_VERSION = 2 # 2: the face close-up fills the picture with the head TURN = dict(aspect='9:16', seconds=6) CLOSE_UP = dict(aspect='1:1', seconds=4) SCENE = dict(aspect='16:9', seconds=6) @@ -60,6 +60,52 @@ _SHEETS_SEEN = set() +# A close-up of the head keeps who the person is (name, age, sex, origin, build, face, hair) and leaves out what they wear +# and carry. Each clause is cut where its clothes or things carried begin (a whole clause dropped would take +# "A young woman wearing a yellow raincoat" down to nothing); a clause that is only clothes goes; whatever names part of +# the head in the part cut away (glasses, hair) stays. +_GARMENT = (r'(?:coats?|raincoats?|jackets?|blazers?|trench|parkas?|hoodies?|sweaters?|jumpers?|cardigans?|shirts?|' + r't-shirts?|tees?|blouses?|vests?|dress(?:es)?|skirts?|gowns?|sarees?|saris?|suits?|uniforms?|scrubs|gear|' + r'overalls|trousers|pants|jeans|shorts|leggings|shoes|sneakers|trainers|boots|heels|sandals|socks|belts?|' + r'bags?|backpacks?|handbags?|purses?|satchels?|briefcases?|umbrellas?|gloves|caps?|hats?|bears?)') +_GARMENT_ZH = r'(?:风衣|外套|大衣|夹克|西装|衬衫|衫|T恤|毛衣|卫衣|马甲|旗袍|校服|工装|裙|裤|牛仔|鞋|靴|袜|腰带|背包|书包|挎包|手提包|公文包|伞|手套|拐杖)' +_WORN = re.compile( + r'\b(?:wearing|wears|wore|dressed|clad|carrying|carries|holding|holds)\b' + # "in a yellow raincoat", "and a red hoodie": up to three words before the garment, none of them another of these + # words ("in her 40s wearing blue scrubs" is cut at "wearing", not at "in"). + r'|\b(?:in|and|with)\s+(?:a|an|the|his|her|their)?\s*' + r'(?:(?!(?:wearing|wears|wore|dressed|clad|carrying|carries|holding|holds|in|and|with)\b)[\w-]+\s+){0,3}' + _GARMENT + r'\b' + r'|身穿|穿着|穿|背着|拿着|提着|拎着|挎着|拄着|手拿', re.IGNORECASE) +# 穿着红色旗袍的上海女人, 背着书包的男孩: the clothes or the thing carried as a modifier before the noun go, the noun stays. +_WORN_BEFORE = re.compile(r'(?:身穿|穿着|穿|拿着|手拿|背着|提着|拎着|挎着|拄着)[^,。;、的]{1,16}的') +_DRESS = re.compile(r'\b' + _GARMENT + r'\b|' + _GARMENT_ZH, re.IGNORECASE) +_HEAD = re.compile( + r'\b(?:hair|haired|face|faced|eyes?|eyebrows?|brows?|beard|bearded|moustache|mustache|stubble|freckles?|skin|lips?|' + r'nose|ears?|earrings?|glasses|eyeglasses|sunglasses|scar|mole|bangs|fringe|ponytail|bun|braids?|braided|curls?|curly|bald)\b' + r'|头发|白发|黑发|发型|短发|长发|卷发|马尾|刘海|辫|脸|眼|眉|胡|雀斑|皮肤|肤色|嘴唇|鼻|耳|眼镜|疤|痣|光头', + re.IGNORECASE) +# A full stop ends a sentence only at the end or before a capital, and not after a title or an initial ("Dr. Okafor"). +_SENTENCE = re.compile(r'[;;。!?!?]|(?= 550 else 400 # fontWeight() of web/fonts.js - files = [FONTS[key][weight]] + ([FONTS['sans'][weight]] if key != 'sans' else []) + [FONT_BOX] + extra = [name for name in FONT_EXTRA if name not in SHAPED_EXTRA or _raqm()] + files = [FONTS[key][weight]] + ([FONTS['sans'][weight]] if key != 'sans' else []) + extra + [FONT_BOX] return [str(FONT_DIR / name) for name in files] +class _Runs: + """A text no single file covers: browsers fall back per character, so each run of + characters is drawn with the first file of the stack that has them.""" + + def __init__(self, fonts): + self.fonts = fonts # character -> font + + def runs(self, line): + out = [] + for ch in line: + font = self.fonts.get(ch) or self.fonts[None] + if out and out[-1][1] is font: + out[-1][0].append(ch) + else: + out.append(([ch], font)) + return [(''.join(chars), font) for chars, font in out] + + def getlength(self, line): + return sum(font.getlength(run) for run, font in self.runs(line)) + + def draw(self, draw, xy, line, anchor, **options): + x, y = xy + width = self.getlength(line) + x -= width / 2 if anchor[0] == 'm' else width if anchor[0] == 'r' else 0 + for run, font in self.runs(line): + draw.text((x, y), run, font=font, anchor='l' + anchor[1], **options) + x += font.getlength(run) + + +def _line_length(font, line): + return font.getlength(line) + + +def _draw_line(draw, xy, line, font, anchor, **options): + if isinstance(font, _Runs): + font.draw(draw, xy, line, anchor, **options) + else: + draw.text(xy, line, font=font, anchor=anchor, **options) + + def font_for(key, weight, size, text=''): """The bundled font that draws this text, and its file. - Browsers fall back per character; here the first file of the stack that has - every character draws the whole text, and the box font draws what none has.""" + Browsers fall back per character. The first file of the stack that has every character + draws the whole text; when none has them all, each run of characters takes the first file + that has it; when some character is in none of them, or the line has a letter written right to left and no + single file has the whole line, the box font draws the whole text (runs would come out in the wrong order).""" stack = font_stack(key, weight) if (tuple(stack), text) not in _CHOSEN: - _CHOSEN[(tuple(stack), text)] = next( - (path for path in stack[:-1] if _covers(ImageFont.truetype(path, 32), text)), stack[-1]) + whole = next((path for path in stack[:-1] if _covers(ImageFont.truetype(path, 32), text)), None) + if whole is None: + probes = [(path, ImageFont.truetype(path, 32)) for path in stack[:-1]] + owners = {} + for ch in set(text): + if ch != '\n': + owners[ch] = next((path for path, probe in probes if _covers(probe, ch)), stack[-1]) + # A character no file has keeps the old result: the box draws the whole text. So does a line with a letter + # written right to left: its runs would be put in order from the left. + right_to_left = any(unicodedata.bidirectional(ch) in ('R', 'AL') for ch in text) + whole = stack[-1] if right_to_left or stack[-1] in owners.values() else tuple(sorted(owners.items())) + _CHOSEN[(tuple(stack), text)] = whole chosen = _CHOSEN[(tuple(stack), text)] - return ImageFont.truetype(chosen, max(1, round(size))), chosen + pixels = max(1, round(size)) + if isinstance(chosen, tuple): + faces = {} + for path in set(owner for _, owner in chosen) | {stack[-1]}: + faces[path] = ImageFont.truetype(path, pixels) + fonts = {ch: faces[owner] for ch, owner in chosen} + fonts[None] = faces[stack[-1]] + return _Runs(fonts), stack[0] + return ImageFont.truetype(chosen, pixels), chosen def _top_ascent(size): @@ -841,7 +922,7 @@ def measure_text(text): """measureText of the editor: the native size of a text block.""" lines = str(text.get('content') or ' ').split('\n') font, _ = font_for(text.get('font'), text.get('weight'), text['size'], str(text.get('content') or '')) - width = max(font.getlength(line or ' ') for line in lines) + width = max(_line_length(font, line or ' ') for line in lines) size, height = text['size'], text.get('lineHeight') or 1.25 return dict(nw=math.ceil(width + size * .4), nh=math.ceil(size * (.4 + (len(lines) - 1) * height + 1.1))) @@ -865,11 +946,11 @@ def _text_raster(layer, path): shapes = [] if outline: mask = Image.new('L', (w, h)) - ImageDraw.Draw(mask).text((x, y), line, font=font, fill=255, anchor=anchor, - stroke_width=max(1, round(stroke / 2)), stroke_fill=255) + _draw_line(ImageDraw.Draw(mask), (x, y), line, font, anchor, fill=255, + stroke_width=max(1, round(stroke / 2)), stroke_fill=255) shapes.append((np.asarray(mask, np.float32) / 255, _color(outline, path + '/text/outline'))) mask = Image.new('L', (w, h)) - ImageDraw.Draw(mask).text((x, y), line, font=font, fill=255, anchor=anchor) + _draw_line(ImageDraw.Draw(mask), (x, y), line, font, anchor, fill=255) shapes.append((np.asarray(mask, np.float32) / 255, fill)) for alpha, color in shapes: if t.get('shadow'): diff --git a/freevideo_engine/agent/errors.py b/freevideo_engine/agent/errors.py index 59309d34..23651928 100644 --- a/freevideo_engine/agent/errors.py +++ b/freevideo_engine/agent/errors.py @@ -162,11 +162,11 @@ '显卡暂时用不了,稍后再试。'), 'gpu_kernels_failed': ("The graphics card's computation check did not pass. Update the graphics card driver, then restart FreeVideo. If the check still does not pass, download the report and report the problem.", '显卡的计算检查未通过。请更新显卡驱动后重新启动 FreeVideo;如仍未通过,请下载报告并提交问题。'), - 'worker_exit': ('Image generation stopped unexpectedly. Try again.', '图像生成意外停止了,请再试一次。'), - 'timeout': ('This image took too long and was stopped. Try again.', '这一张用时太长,已停止。请再试一次。'), + '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.', '图像生成出错了,请再试一次。'), + 'generation_failed': ('Image generation ran into an error. Try again.', '图像生成时出错,请重试。'), 'invalid_media': ('This image cannot be read or is larger than 4096×4096 pixels. Choose another image.', '这张图片读不出来,或超过 4096×4096 像素。请换一张图片。'), 'invalid_request': ('The image settings are invalid. Adjust them and try again.', '图片设置有误,请调整后重试。'), @@ -366,7 +366,7 @@ def safe_details(value): 'context_length': ('The prompt and reference images are too long', '提示词和参考图太长'), 'dependency_failed': ('A task this one depends on did not finish', - '前面依赖的任务没有完成'), + '前面依赖的任务未完成'), 'lost': ('The generation service no longer has the result of this task', '生成服务没有保留这次任务的结果'), 'unknown_job': ('The image generation service cannot find this task', @@ -537,10 +537,10 @@ def safe_details(value): # What a person can do next, for the reasons above whose remedy is not just running the task again. Shown after the # reason only while the reason itself is the code's sentence (a more specific message keeps its own meaning). FAILURE_NEXT = { - 'generation_failed': ('If it happens again, use "Report a problem"', - '再次出现时,请点击“提交问题”'), - 'internal_error': ('If it happens again, use "Report a problem"', - '再次出现时,请点击“提交问题”'), + 'generation_failed': ('If it happens again, choose "Report a problem".', + '再次出现时,请点击“提交问题”。'), + 'internal_error': ('If it happens again, choose "Report a problem".', + '再次出现时,请点击“提交问题”。'), 'unreachable': ('Make sure FreeVideo is running, then try again', '确认 FreeVideo 已经启动后再试'), 'session_full': ('Click "New chat" to continue', @@ -779,7 +779,7 @@ def failure_reason(error): return FAILURE_MESSAGES_ZH[line] if line.startswith(('CUDA out of memory', 'MPS backend out of memory')): return FAILURE_REASONS_ZH['out_of_memory'] - return FAILURE_REASONS_ZH.get(error.get('code'), '没有完成') + return FAILURE_REASONS_ZH.get(error.get('code'), '未完成') # The same lookup in English for the page: the specific sentences are already written for people. diff --git a/freevideo_engine/agent/jobs.py b/freevideo_engine/agent/jobs.py index 6482218d..7b0b1997 100644 --- a/freevideo_engine/agent/jobs.py +++ b/freevideo_engine/agent/jobs.py @@ -2319,6 +2319,15 @@ def generation_failure(self, row, chain): failure = dict(chain_error(code, errors.ERRORS[code][2], next_action, details=[detail], retryable=code != 'insufficient_memory').view(), **errors.reasons(dict(code=code, message=message))) + # The program's own text (paths and prompts already taken out, then the shared redaction) stays with the job: + # the page shows it under the reason and a problem report carries it, never only "Generation failed". + from ..diagnostics import Redactor + redactor = Redactor() + redactor.prompts.update(value for value in (prompt, ((block or {}).get('inputs') or {}).get('text')) + if isinstance(value, str) and value) + cause = redactor.text(message).strip()[:2000] + if cause and cause != errors.ERRORS[code][2]: + failure['message'] = cause if isinstance(report_id, str) and re.fullmatch(r'[a-f0-9]{32}', report_id): failure['report_id'] = report_id return failure diff --git a/freevideo_engine/agent/production.py b/freevideo_engine/agent/production.py index 041c1520..8f5ad4cd 100644 --- a/freevideo_engine/agent/production.py +++ b/freevideo_engine/agent/production.py @@ -792,9 +792,10 @@ def _public(value): # Keep prose slashes, URLs and bare roots. Once a path starts, use # the shared matcher, which includes spaces through the full filename. # A file URL (file:///home/..., file://localhost/C:/...) starts one too; the shared matcher reads it whole. + # A path right after a colon ("error:/home/...") starts one as well, not a URL's "://". starts = re.compile(r'''(?]*)?(?:/+|(?=[A-Za-z]:[\\/]))''' r'''|(?|])|\\\\[^\\/\s"'<>]+[\\/])''' - r'''|(?;|\r\n]+/(?![/\s])''') + r'''|(?;|\r\n]+/(?![/\s])''') parts, cursor = [], 0 for start in starts.finditer(value): if start.start() < cursor: @@ -805,6 +806,8 @@ def _public(value): span = found.group().split(' | ', 1)[0].rstrip() parts.extend((value[cursor:start.start()], '[local path]')) cursor = start.start() + len(span) + # Only local paths: this is the user's own assistant and screenplay, not a report that leaves the + # machine, so an email address or an "Authorization:" line in a character's words stays as written. return ''.join(parts) + value[cursor:] return value diff --git a/freevideo_engine/background_compile.py b/freevideo_engine/background_compile.py index 652b38c2..fe8acbd1 100644 --- a/freevideo_engine/background_compile.py +++ b/freevideo_engine/background_compile.py @@ -95,10 +95,12 @@ def start(self, command, *, environment, cwd, log, lock, busy, delay=START_DELAY self.thread.start() return True - def stop(self, *, final=False): + def stop(self, *, final=False, lease_held=None): """Stop a running compile and return once its processes, GPU memory and lease are gone. - `final` when a generation starts: the session compiles nothing more. + `final` when a generation starts: the session compiles nothing more. `lease_held`, when given, says whether + other work of this process holds the lease (the video warm-up): the compile then cannot hold it, and a wait + for it would be a wait for the very work the starting video stops next, up to RELEASE_SECONDS. """ if final: self.closed.set() @@ -132,24 +134,38 @@ def stop(self, *, final=False): return dict(row) elif gave_way(process): return None + if held_here(lease_held): + row.update(released=None, release_seconds=time.monotonic() - tick, lease='warm_up') + if not row.get('stopped'): + return None + logging.info('[FreeVideo] Background compile stopped in %.1f s; the warm-up holds the GPU lease.', + row['release_seconds']) + return dict(row) # Every process of the tree holds the lease; once it is free the # tree is gone, even when the top process had already exited. On a # timeout the request reports the busy lease. One deadline for all. - row['released'] = self._released(tick + RELEASE_SECONDS) + row['released'] = self._released(tick + RELEASE_SECONDS, lease_held) row['release_seconds'] = time.monotonic() - tick + if row['released'] is None: + # The warm-up took the lease while this waited (BackgroundCompile.stop's lease_held). + row['lease'] = 'warm_up' if not row.get('stopped'): return None - logging.info('[FreeVideo] Background compile stopped in %.1f s; the GPU lease is %s.', - row['release_seconds'], 'free' if row['released'] else 'still held') + logging.info('[FreeVideo] Background compile stopped in %.1f s; the GPU lease is %s.', row['release_seconds'], + 'free' if row['released'] else 'held by the warm-up' if row['released'] is None else 'still held') return dict(row) - def _released(self, deadline): + def _released(self, deadline, lease_held=None): + """True once the lease is free, False at the deadline, None as soon as `lease_held` says this process's warm-up + holds it (asked again after every busy try: the warm-up may take it only while this waits).""" from .locking import runtime_lock while True: try: with runtime_lock(io_path(self.lock), inherit=False): return True except BlockingIOError: + if held_here(lease_held): + return None if time.monotonic() >= deadline: return False time.sleep(.1) @@ -239,6 +255,17 @@ def _work(self, command, environment, cwd, log, busy, delay): record(self.root, 'not_started') +def held_here(lease_held): + """True when `lease_held` (BackgroundCompile.stop) says this process's own work holds the lease; a failing check + counts as no, so the stop waits for the lease as before.""" + if lease_held is None: + return False + try: + return lease_held() is True + except Exception: + return False + + def gave_way(process): """The compile exited because the card or the memory was taken (BUSY_EXIT). diff --git a/freevideo_engine/background_room.py b/freevideo_engine/background_room.py index d054a753..c43fd725 100644 --- a/freevideo_engine/background_room.py +++ b/freevideo_engine/background_room.py @@ -159,9 +159,11 @@ def parents(): return found -def family(root): - """`root` and every process descended from it; OSError when processes cannot be listed.""" - table = parents() +def family(root, table=None): + """`root` and every process descended from it; OSError when processes cannot be listed. + + `table`, a parents() reading, lets several families come from one listing.""" + table = parents() if table is None else table pids, frontier = {root}, {root} while frontier: frontier = {pid for pid, parent in table.items() if parent in frontier} - pids diff --git a/freevideo_engine/bootstrap.py b/freevideo_engine/bootstrap.py index 907c1075..2f201f8d 100644 --- a/freevideo_engine/bootstrap.py +++ b/freevideo_engine/bootstrap.py @@ -684,13 +684,16 @@ def plan(args, *, local_progress=None, stage=None): # An unreadable version is left to the later checks instead of blocking setup. major = re.match(r'\d+', driver) cuda_api = snapshot.get('cuda_driver_api_version') - if cuda_api < 13000 if cuda_api is not None else (major and int(major.group()) < 580): + compatibility = hardware.cuda_compatibility() + # A card below the hardware floor is the reason, and a driver update cannot help it: only that is said (its own line + # names the driver too). An unknown capability keeps the driver line, as an old driver can be why it is unknown. + below_floor = compatibility['status'] == 'CUDA_ARCH_UNSUPPORTED' + if not below_floor and (cuda_api < 13000 if cuda_api is not None else (major and int(major.group()) < 580)): # The card names the graphics card too; brackets would end its pattern early. model = re.sub(r'[()\r\n]', '', str(snapshot['selected_gpu'].get('name') or '')).strip() # The CUDA fallback reads no driver version; leave it out instead of printing a gap. errors.append('NVIDIA driver%s%s is older than 580, the minimum for the CUDA 13 encoder; update the driver first.' % (' ' + driver if driver else '', ' (%s)' % model if model else '')) - compatibility = hardware.cuda_compatibility() if compatibility['error']: errors.append(compatibility['error']) snapshot['cuda_compatibility'] = compatibility @@ -1935,6 +1938,7 @@ def encoder_packages(): (encoder_after, 'encoder-source'), ('environment:unified' if self.layout == 'unified' else 'environment:encoder',)) if self.system == 'Windows': task('windows-check', lambda: self.command('windows-runtime-check', [python, '-c', + 'from freevideo_engine.vc_runtime import require_in_child; require_in_child(); ' 'import torch,triton,safetensors,comfy_kitchen,comfy_aimdo; ' 'assert torch.cuda.is_available(), "CUDA unavailable; check NVIDIA driver and Windows DLL errors above"; ' 'print("Windows runtime imports passed; GPU kernel probes follow")']), ('runtime',), ('environment:' + name,)) @@ -2068,27 +2072,47 @@ def notice(message): def packages(self, label, args, family='pypi', *, wait_busy=True): from .failure_details import file_in_use - for wait in (*ENVIRONMENT_BUSY_WAITS, None): + from . import windows_blocked + tries = 0 + while True: try: with self.download_notice('download-patient-' + label) as notice: return network.package_command(self.network, family, lambda env, source: self.command(label if source == 'official' else label + '-' + source, args, env=env), self.env, notice=notice) except RuntimeError as error: + if not wait_busy: + raise # Security software or an indexer can hold a file uv has just - # written or is about to run (the build environment's Python). + # written or is about to run (the build environment's Python), + # or still be examining a file it refused uv. # No other download source helps; the file is free again shortly. - if wait is None or not wait_busy or not file_in_use(error) or self.cancel.is_set(): + blocked = windows_blocked.package_blocked(str(error)) if self.system == 'Windows' else None + waits = (ENVIRONMENT_BUSY_WAITS if file_in_use(error) else + windows_blocked.RETRY_WAITS if blocked and blocked[0] in windows_blocked.RETRYABLE else ()) + if tries >= len(waits) or self.cancel.is_set(): + if blocked: + # The launcher shows the blocked-file card, not "choose a folder you can write to": + # the folder is FreeVideo's own, and uv has just written to it. + raise windows_blocked.blocked_failure(blocked, error) from error raise - self.ui.write('A file is in use by another program; trying again in %d s.\n' % wait) + wait = waits[tries] + tries += 1 + if file_in_use(error): + self.ui.write('A file is in use by another program; trying again in %d s.\n' % wait) + else: + self.ui.write('Windows did not let setup write a file of %s (Windows error %d). Trying again in %d s.\n' + % (blocked[1] or 'a package', blocked[0], wait)) if self.cancel.wait(wait): raise def python_sources(self, names): - """The GitHub mirror refuses the Python runtime files, so it is tried after a mirror that serves them.""" + """The GitHub mirror (ghfast) refuses the Python runtime files (403), so it is not a Python source: GitHub, + then the public mirror that serves them (freevideo.ps1 keeps the same order).""" + names = [n for n in names if n != 'ghfast'] if self.network.get('mode') == 'official': return names - return [*[n for n in names if n != 'ghfast'], *network.PYTHON_MIRRORS, *[n for n in names if n == 'ghfast']] + return [*names, *network.PYTHON_MIRRORS] def python_request(self): """What uv is asked for: the version, or on Windows on Arm the aarch64 build of it.""" @@ -2132,16 +2156,35 @@ def attempt(source, route, retry_mode, native_tls=False): network.source_url('github', source, self.env) + '/astral-sh/python-build-standalone/releases/download') return self.command('python-' + source + '-' + route, [uv, 'python', 'install', *isolation, self.python_request()], env=env) - try: - with self.download_notice('download-patient-python') as notice: - return network.download_command(self.network, 'github', attempt, self.env, category='python', - extra_sources=['user-python'] if custom else [], notice=notice, - reorder=self.python_sources) - except network.PackageSourcesError as error: - failure = RuntimeError('Python download failed on every route; see retained logs' - + network.sources_text(error.attempts)) - failure.package_attempts = error.attempts - raise failure from error + from . import windows_blocked + for wait in (*windows_blocked.RETRY_WAITS, None): + try: + with self.download_notice('download-patient-python') as notice: + return network.download_command(self.network, 'github', attempt, self.env, category='python', + extra_sources=['user-python'] if custom else [], notice=notice, + reorder=self.python_sources) + except network.PackageSourcesError as error: + # A file Windows blocked leads, whichever source it came from. + blocked = next(filter(None, (windows_blocked.unpack_blocked(str(row.get('detail', ''))) + for row in error.attempts)), None) + failure = RuntimeError((windows_blocked.python_file_message(*blocked) + '\n' if blocked else '') + + 'Python download failed on every route; see retained logs' + + network.sources_text(error.attempts)) + failure.package_attempts = error.attempts + raise failure from error + except RuntimeError as error: + # The download arrived but Windows did not let uv write one of its files: security software + # still examining it, or another program holding it, may let go shortly. Another source brings + # the same file to the same folder, so the same download is tried again (as freevideo.ps1 does). + blocked = windows_blocked.unpack_blocked(str(error)) + if not blocked: + raise + if wait is None or blocked[0] not in windows_blocked.RETRYABLE or self.cancel.is_set(): + raise RuntimeError(windows_blocked.python_file_message(*blocked) + '\n' + str(error)) from error + self.ui.write('Windows did not let setup write %s (Windows error %d). Trying again in %d s.\n' + % (blocked[1], blocked[0], wait)) + if self.cancel.wait(wait): + raise def install_sage_optional(self, uv, python): """Sage2 is an optional speed-up: where FreeVideo's own compiler builds it, a failure leaves it out.""" @@ -2675,7 +2718,7 @@ def __init__(self, value, ui=None): def run(self): out = self.run_dir / 'prefetch.json' - self.ui.phase('Download the faster model', 1, 2) + self.ui.phase('Download the new model', 1, 2) self.command('models', [self.pythons['engine'], '-m', 'freevideo_engine.provision', '--plan', self.run_dir / 'plan.json', '--prefetch', '--out', out]) result = json.loads(out.read_text(encoding='utf-8')) diff --git a/freevideo_engine/capabilities.py b/freevideo_engine/capabilities.py index 5304f9a5..c9e28ae8 100644 --- a/freevideo_engine/capabilities.py +++ b/freevideo_engine/capabilities.py @@ -31,11 +31,21 @@ FAST2_STEPS = 2 +# A Mac is offered the fastest mode from this much unified memory: on 8 GB its admission left 0.12 GiB, so a request +# would run out of memory first and then start over with the slowest partitions. +MAC_FAST_RAM_FLOOR = 16 * GiB + + def _fast_mode_listing(machine): - """Whether this machine is offered the fastest mode at all, and why not: the adapter replaces int8 layers and runs - on NVIDIA's CUDA build only.""" + """Whether this machine is offered the fastest mode at all, and why not: the adapter replaces int8 layers, so the + int8 model is needed, on NVIDIA's CUDA build or on a Mac (M5 and newer run those layers as int8, earlier Apple chips + read them as BF16) with at least MAC_FAST_RAM_FLOOR of unified memory.""" if machine['mac']: - return dict(listed=False, unlisted_reason='mac') + if machine['precision'] != 'int8': + return dict(listed=False, unlisted_reason='engine') + if machine['ram'] < MAC_FAST_RAM_FLOOR: + return dict(listed=False, unlisted_reason='memory') + return dict(listed=True, unlisted_reason=None) # Setup's vendor first, then the torch build (a ROCm build passes the capability check but saves no CUDA version); # a record without either is told by the card's name. Older NVIDIA drivers name a card without the vendor # ("GeForce RTX 3090"), so the name rules out AMD's words rather than asking for NVIDIA's. @@ -44,8 +54,24 @@ def _fast_mode_listing(machine): or any(word in name for word in ('amd', 'radeon', 'instinct'))): return dict(listed=False, unlisted_reason='gpu') if machine['precision'] != 'int8': + # An FP8 installation: where the launcher offers the int8 model (model_upgrade.offer, read by the page's server + # as model_switch), the page shows the fastest mode as unavailable and points there, with the launcher's own + # download size and, on cards where FP8 is the faster arithmetic (purpose 'fast-level'), that cost too. + switch = machine.get('model_switch') + if switch: + return dict(listed=False, unlisted_reason='engine', needs='int8_model', download_bytes=switch['download_bytes'], + int8_slower=switch['purpose'] == 'fast-level') return dict(listed=False, unlisted_reason='engine') return dict(listed=True, unlisted_reason=None) + + +def _model_switch(value): + """The launcher's offer of the int8 model as the page's server read it, or None when nothing is offered.""" + if (not isinstance(value, dict) or value.get('status') not in ('available', 'low-disk') + or value.get('purpose') not in ('faster', 'fast-level') or type(value.get('download_bytes')) is not int + or value['download_bytes'] < 0): + return None + return dict(status=value['status'], purpose=value['purpose'], download_bytes=value['download_bytes']) # WholeVideoProgress.for_request starts an ordinary new-prompt request with # these flags. Unobserved encoder/model residency stays cold; compilation is # unknown (the prior's half-cold default), even later in the same session. @@ -284,7 +310,8 @@ def _machine(machine, in_use=None): # Setup's vendor, and whether the saved torch build is a CUDA one: a ROCm build saves no CUDA version. # A record from before either was saved has neither, and is judged by the card's name as before. vendor=str(machine['gpu_vendor']).casefold() if machine.get('gpu_vendor') else None, - cuda_missing='cuda_version' in observed and not observed['cuda_version']) + cuda_missing='cuda_version' in observed and not observed['cuda_version'], + model_switch=None if mac or precision == 'int8' else _model_switch(machine.get('model_switch'))) def _request(width, height, frames, steps, two_pass, task='t2va', refine=3, @@ -330,10 +357,11 @@ def _admit(machine, width, height, frames, steps, two_pass, task='t2va', refine= from .macos_compute import request_admission, plan as mac_plan resource = mac_policy(SimpleNamespace(), dict(total_bytes=machine['ram'], available_bytes=machine['ram'])) - admission = request_admission(resource, sampling, working_set_bytes=machine['metal']) + admission = request_admission(resource, sampling, working_set_bytes=machine['metal'], fast_mode=fast_mode) if admission['state'] == 'refuse': return None, -1, 'memory' - plans = [mac_plan(min(resource['allocator_bytes'], machine['metal'] or resource['allocator_bytes']), + from .macos_compute import fast_budget + plans = [mac_plan(fast_budget(min(resource['allocator_bytes'], machine['metal'] or resource['allocator_bytes']), fast_mode), geometry(**g)['video_tokens'] + 1024 + rows['video'] + rows['audio'], frames=geometry(**g)['latent_frames'], allow_bounded=True) for g in (sampling['first'], sampling['second'] or sampling['first'])] diff --git a/freevideo_engine/cli.py b/freevideo_engine/cli.py index 9bdbc34c..c5c60cb3 100644 --- a/freevideo_engine/cli.py +++ b/freevideo_engine/cli.py @@ -191,9 +191,6 @@ def main(): validate_route(task=args.task or ('ref2va' if args.continue_anchor else 't2va'), anchor=args.continue_anchor is not None, two_pass=args.two_pass, preview=args.preview, refine_from=args.refine_from) - if sys.platform == 'darwin' and args.command == 'generate' and args.fast_mode is not None: - # The Mac route below has its own engine, which would otherwise run the default steps. - raise ValueError('The fastest mode is not available on Mac') if sys.platform == 'darwin' and args.command == 'generate' and args.upscale_from is not None: raise ValueError('Upscaling a finished video is not available on Mac yet') if sys.platform == 'darwin' and args.command in ('plan', 'generate', 'encode', 'doctor'): diff --git a/freevideo_engine/comfy_assets.py b/freevideo_engine/comfy_assets.py index 3adef7d4..530b13ef 100644 --- a/freevideo_engine/comfy_assets.py +++ b/freevideo_engine/comfy_assets.py @@ -5,7 +5,7 @@ from pathlib import Path, PurePosixPath, PureWindowsPath from . import launcher_bridge from .comfy_continuation import optional_text -from .monitoring import thermal_slowdown, shared_gpu_note, worker_gpu +from .monitoring import power_limited, thermal_slowdown, shared_gpu_note, worker_gpu from .paths import data_root from .support_report import encoder_sizes @@ -311,6 +311,7 @@ def output_summary(report, relative_video): sampling_plan=sampling_plan(report), low_memory=bool(report.get('low_memory_mode')), thermal=thermal_slowdown(worker_gpu(report)), + power_limit=power_limited(worker_gpu(report)), shared_gpu=shared_gpu_note(worker_gpu(report)), reference_trims=report.get('encoding', {}).get('reference_trims') or [], preview=bool(report.get('preview')), upscaled_preview=bool(report.get('upscaled_preview')), diff --git a/freevideo_engine/comfy_bridge.py b/freevideo_engine/comfy_bridge.py index 7b6aa5f1..d6ed057b 100644 --- a/freevideo_engine/comfy_bridge.py +++ b/freevideo_engine/comfy_bridge.py @@ -884,6 +884,22 @@ def installation_root(source=None, environ=None): return Path(plain(resolved(root))) +def engine_model_root(source=None, environ=None): + """The model folder the engine process reads (paths.installed_model_root under FREEVIDEO_HOME=installation_root). + + ComfyUI started without the launcher has no FREEVIDEO_HOME, so the installation is the one comfyui.json names; + code in the ComfyUI process that reads or writes the engine's models resolves the folder here, not with paths. + """ + environ = os.environ if environ is None else environ + if environ.get('FREEVIDEO_MODEL_ROOT'): + return Path(environ['FREEVIDEO_MODEL_ROOT']).expanduser() + root = installation_root(source, environ) + try: + return Path(json.loads((io_path(root) / 'machine.json').read_text(encoding='utf-8'))['model_root']).expanduser() + except (OSError, ValueError, KeyError, TypeError): + return root / 'models' + + @plain_errors def installation(source=None, environ=None): from .comfy_launcher_api import repair_hint @@ -1281,6 +1297,16 @@ def argument(arguments, flag, default=None): return arguments[arguments.index(flag) + 1] if flag in arguments else default +def work_upscale_media(run, video): + """The media of a finished video's 1.5x upscale (its own sound, work_upscale.media) and the generate arguments + that carry it: media.json holds the rows as a request gives them, which the engine reads back and checks + against the row it computes itself, as on the command line.""" + from .work_upscale import media, request, source + value = media(None, source(video)) + save(Path(run) / 'media.json', request(value)) + return value, ['--media', str(Path(run) / 'media.json'), '--upscale-from', str(video)] + + def upscale_frames(upscale_from, output_directory, *, source=None, environ=None, progress=None, interrupted=None, release_models=None, comfy_metadata=None): """A finished 24 fps video made a new work at the 4K size by frame_upscale: its own description, seed and length, @@ -1464,14 +1490,14 @@ def generate(prompt, width, height, seconds, seed, output_directory, *, # its frames as the first pass and its own sound used as is (work_upscale). if upscale or preview or continue_from is not None: raise ValueError('An upscale of a finished video is a request of its own') - from .work_upscale import FACTOR, size as upscaled_size, work_request + from .work_upscale import PLAN, size as upscaled_size, work_request work = work_request(output_directory, upscale_from) saved = work[0].parent / 'prompt.txt' prompt = saved.read_text(encoding='utf-8') if saved.is_file() else '' allow_empty_prompt = allow_empty_prompt or not prompt.strip() width, height = upscaled_size(work[1]['geometry']['width'], work[1]['geometry']['height']) seconds, seed = work[1]['geometry']['seconds'], work[1]['seed'] - two_pass, upscale_factor, base_steps, refine_steps, step_cache = True, FACTOR, 8, 3, None + two_pass, upscale_factor, base_steps, refine_steps, step_cache = (PLAN[k] for k in ('two_pass', 'upscale_factor', 'base_steps', 'refine_steps', 'step_cache')) frames, first_frame_reference, voice_reference, hide_tail = None, False, False, False staged = bool(preview or upscale or work) from .refine_schedule import UPSCALE @@ -1488,8 +1514,6 @@ def generate(prompt, width, height, seconds, seed, output_directory, *, allow_empty_prompt=allow_empty_prompt) source = Path(source or source_root()).resolve() root, machine = installation(source, environ) - if fast_mode is not None and machine.get('device_backend') == 'mps': - raise ValueError('The fastest mode is not available on Mac') continuation = None def check_ending(): @@ -1536,6 +1560,8 @@ def check_ending(): environment = engine_environment(root, source, environ) environment.update(FREEVIDEO_HOME=str(root), PYTHONPATH=str(source), PYTHONUNBUFFERED='1', PYTHONUTF8='1', PYTHONIOENCODING='utf-8', NO_COLOR='1', FREEVIDEO_UI_EVENTS='1') + # The GPU monitor counts this process's other children (prompt model, pictures, music) as FreeVideo's own work. + environment['FREEVIDEO_HOST_PID'] = str(os.getpid()) for key in ('FREEVIDEO_RUNTIME_LOCK_FD', 'FREEVIDEO_RUNTIME_LOCK_HANDLE'): environment.pop(key, None) # No attention, placement or capacity override: managed CLI uses the @@ -1561,8 +1587,9 @@ def check_ending(): if step_cache is not None: command += ['--step-cache', step_cache] if fast_mode is not None: - # The folder the engine process resolves (paths.installed_model_root). Before queueing, so a missing file is named at once. - fast_tier.files(environment.get('FREEVIDEO_MODEL_ROOT') or machine['model_root']) + # The folder the engine process resolves, as the page's download does (fast_pack.model_folder). Before queueing, so a + # missing file is named at once. + fast_tier.files(engine_model_root(source, environment)) command += ['--fast-mode', fast_mode] if two_pass and upscale_factor != 2: command += ['--upscale-factor', '%g' % upscale_factor] @@ -1675,10 +1702,8 @@ def poll(): extra['conditioning'] = argument(arguments, '--conditioning') elif work: # The video's own sound, used as is: it sets the length and is copied into the result. - from .work_upscale import media as work_media, source as work_source - extra['media'] = work_media(None, work_source(work[0])) - save(run / 'media.json', extra['media']) - command += ['--media', str(run / 'media.json'), '--upscale-from', str(work[0])] + extra['media'], arguments = work_upscale_media(run, work[0]) + command += arguments state['command'] = command elif export_inputs: send_progress({'label': 'Retaining and checking input media', 'timing_phase': 'encoding'}) diff --git a/freevideo_engine/comfy_capabilities.py b/freevideo_engine/comfy_capabilities.py index 677c7b19..9f622776 100644 --- a/freevideo_engine/comfy_capabilities.py +++ b/freevideo_engine/comfy_capabilities.py @@ -52,6 +52,14 @@ def _machine_context(): machine['hardware'] = observed # Receipt read only: tells the page the first run still compiles. machine['compile_owed'] = compile_owed(root) + if machine.get('device_backend') != 'mps' and not str(machine.get('prepared_format', 'int8')).startswith('int8'): + # An FP8 installation: whether the launcher offers the int8 model, and its download (the Fast level needs it). + try: + from .model_upgrade import offer + offered = offer(root) + machine['model_switch'] = {k: offered.get(k) for k in ('status', 'purpose', 'download_bytes')} + except Exception: + logging.debug('[FreeVideo] The model switch could not be read for the capability grid.', exc_info=True) return machine @@ -64,6 +72,27 @@ def _context(output_directory): return machine, rows +def mac_fast_grid(): + """What a Mac's page gets from the capabilities route: no grid (status stays unavailable, so the length, + size and estimate readers keep their own Mac behavior), only whether the fastest mode is listed and why not, + marked fast_only. A machine that cannot be read gets the plain unavailable answer.""" + from .capabilities import _fast_mode_listing, _machine + try: + context = _machine_context() + # This route asks only on Apple silicon: an installation whose setup run (and its plan's system) is gone is + # still a Mac. + if not context.get('system') and not (context.get('hardware') or {}).get('system'): + context['system'] = 'Darwin' + machine = _machine(context) + except Exception: + logging.debug('[FreeVideo] The fastest mode listing could not be read on this Mac.', exc_info=True) + machine = None + if machine is None or not machine['mac']: + return dict(UNAVAILABLE) + return dict(UNAVAILABLE, fast_only=True, machine=dict(system=machine['system']), + fast_mode=_fast_mode_listing(machine)) + + def _apple_silicon(): return platform.system() == 'Darwin' and platform.machine().lower() in ('arm64', 'aarch64') @@ -351,7 +380,7 @@ async def other_usage(request): @server.routes.get('/freevideo/capabilities') async def capabilities(request): if mac: - return web.json_response(dict(UNAVAILABLE), headers={'Cache-Control': 'no-store'}) + return web.json_response(await asyncio.to_thread(mac_fast_grid), headers={'Cache-Control': 'no-store'}) try: key = _query(request.query) except (ValueError, TypeError, OverflowError, RecursionError) as error: diff --git a/freevideo_engine/comfy_nodes.py b/freevideo_engine/comfy_nodes.py index 33c8012a..93940668 100644 --- a/freevideo_engine/comfy_nodes.py +++ b/freevideo_engine/comfy_nodes.py @@ -288,9 +288,10 @@ def execute(cls, text, width, height, seconds, seed, first=None, last=None, if not refine_from and not upscale_from: validate_steps(base_steps, refine_steps, two_pass) from .background_compile import COMPILE - # Returns once the idle compile released the GPU and the engine lease. - COMPILE.stop(final=True) from . import video_warm + # Returns once the idle compile released the GPU and the engine lease; a lease the warm-up holds is not waited + # for, as the warm-up is stopped just below. + COMPILE.stop(final=True, lease_held=video_warm.lease_held) # A warm-up for this video gives the lease back; the worker and the encoder it placed stay for the video. video_warm.stop() from .comfy_media import continued, export diff --git a/freevideo_engine/comfy_setup.py b/freevideo_engine/comfy_setup.py index df777b3e..a148e309 100644 --- a/freevideo_engine/comfy_setup.py +++ b/freevideo_engine/comfy_setup.py @@ -13,6 +13,7 @@ import threading import uuid +from . import windows_names from .long_paths import io_path, resolved, plain, plain_text, plain_errors from .comfy_bridge import installation, installation_root, source_root from .environments import ENVIRONMENTS @@ -281,6 +282,7 @@ def compatibility_settings(self, value, action): def validate_root(self, value): if not isinstance(value, str) or not value.strip() or len(value) > 4096: raise ValueError('Choose an engine installation folder') + windows_names.check(value) root = resolved(Path(value).expanduser()) host = resolved(self.folder_paths.base_path) if root == Path(root.anchor) or root == host or (root in host.parents and not owned_comfy(root, host)): diff --git a/freevideo_engine/comfy_source.py b/freevideo_engine/comfy_source.py index fc1da2e5..d2ff6ddb 100644 --- a/freevideo_engine/comfy_source.py +++ b/freevideo_engine/comfy_source.py @@ -4,7 +4,7 @@ from pathlib import Path from .long_paths import io_path, resolved, plain, plain_errors -from . import network +from . import network, windows_names from .monitoring import save RECEIPT = '.freevideo-comfy-source.json' @@ -36,6 +36,7 @@ def validate_target(target): def new_layout(directory): if not isinstance(directory, str) or not directory.strip(): raise ValueError('Choose a folder for the new ComfyUI installation') + windows_names.check(directory) parent = resolved(Path(directory).expanduser()) if parent.exists() and not parent.is_dir(): raise ValueError('The installation folder is a file: ' + plain(parent)) diff --git a/freevideo_engine/curl_windows.py b/freevideo_engine/curl_windows.py index e6b97f46..6694b973 100644 --- a/freevideo_engine/curl_windows.py +++ b/freevideo_engine/curl_windows.py @@ -279,8 +279,10 @@ def emit(detail, **fields): raise CurlError(check['status'], 'The verified download tool could not start.') target = cache / ('curl-' + spec['version']) if target.exists(): - target.rename(cache / ('curl-rejected-' + uuid.uuid4().hex)) + target.rename(cache / (target.name + '.rejected-' + uuid.uuid4().hex)) folder.rename(target) + from . import failed_copies + failed_copies.prune(target, keep=0) # the new tool passed its probe; the old ones go report.update(selected=str(target / 'bin/curl.exe'), status='ready', repair='complete') attempt['status'] = 'ready' emit('Download tool ready', done=spec['bytes'], total=spec['bytes']) diff --git a/freevideo_engine/decode_resume.py b/freevideo_engine/decode_resume.py index e52adf29..e4524b87 100644 --- a/freevideo_engine/decode_resume.py +++ b/freevideo_engine/decode_resume.py @@ -71,6 +71,25 @@ def _digest(path): return digest.hexdigest() +def _upscaler_digest(path): + """The upscaler's content digest, from the verified-models ledger when it covers this copy. + + Each two-pass request names the upscaler in two retained identities (the + second pass's input and the final latents). Hashing the whole checkpoint + for each kept the GPU idle between the passes and before decoding. The + ledger knows a copy only while its size and times are unchanged since its + content was hashed; any other copy, or an unreadable ledger, is hashed here. + """ + from .two_pass import UPSCALER, verified_checkpoint + path = Path(path) + try: + if verified_checkpoint(path): + return UPSCALER['sha256'] + except (OSError, ValueError): + pass + return _digest(path) + + def _plan_without_staged(plan): return {k: v for k, v in plan.items() if k != 'staged'} if isinstance(plan, dict) else plan @@ -133,7 +152,7 @@ def sampling_provenance(request): steps(request['sampling_plan']) result.update(version=2, sampling_plan=request['sampling_plan']) if request['sampling_plan'].get('upscaler_sha256'): - result['upscaler_sha256'] = _digest(request['upscaler_checkpoint']) + result['upscaler_sha256'] = _upscaler_digest(request['upscaler_checkpoint']) if result['upscaler_sha256'] != request['sampling_plan']['upscaler_sha256']: raise ValueError('Latent upscaler differs from the planned checkpoint') if request.get('hide_tail_frames'): diff --git a/freevideo_engine/depth_reference.py b/freevideo_engine/depth_reference.py index b72b7b0f..e9412b5a 100644 --- a/freevideo_engine/depth_reference.py +++ b/freevideo_engine/depth_reference.py @@ -18,6 +18,13 @@ from . import processes from .paths import data_root + +def _forget_rejected(target): + """The new result is in place, validated: the invalid ones kept beside it go.""" + from . import network + network.forget_failed(target) + + PREPROCESSING_VERSION = 'dav2-small-pyav-torch-bgr-imagenet-lower-bound-14-clay-relief-v1' CODE_VERSION = 'freevideo-depth-reference-v1' STAGE = 'depth_reference' @@ -91,7 +98,7 @@ def ensure_weights(root, emit, check): if path.is_file() and path.stat().st_size == row['bytes'] and digest(path, check) == row['sha256']: return path if path.exists(): - network.retain_partial(path, 'rejected') + network.retain_partial(path, 'set-aside') plan = _download_plan(Path(root)) sources = plan['sources'] = dict(plan.get('sources', {})) if not sources.get('image-models'): @@ -540,6 +547,7 @@ def _convert(request, emit, check): # Retain invalid old artifacts separately; never accept a partial directory. target.rename(cache / (key + '.rejected-' + uuid.uuid4().hex)) os.replace(stage, target) + _forget_rejected(target) return dict(path=str(target / 'depth.mp4'), cache_hit=False, key=key) @@ -575,6 +583,7 @@ def _convert_lines(request, source, work, emit, check): if target.exists(): target.rename(cache / (key + '.rejected-' + uuid.uuid4().hex)) os.replace(stage, target) + _forget_rejected(target) return dict(path=str(target / OUTPUT['lines']), cache_hit=False, key=key) diff --git a/freevideo_engine/diagnostic_resources.py b/freevideo_engine/diagnostic_resources.py index c5f321c8..5fc95547 100644 --- a/freevideo_engine/diagnostic_resources.py +++ b/freevideo_engine/diagnostic_resources.py @@ -571,8 +571,9 @@ def resources(value): result['gpu'][key] = clean if isinstance(gpu.get('other_programs'), dict): result['gpu']['other_programs'] = numbers(gpu['other_programs'], ('checks', 'shared_checks', 'check_seconds', - 'share_percent', 'other_mean_percent', 'other_peak_percent', 'own_mean_percent')) - for key in ('supported', 'own_reported'): + 'share_percent', 'other_mean_percent', 'other_peak_percent', 'own_mean_percent', + 'helpers_shared_checks', 'helpers_mean_percent', 'helpers_peak_percent')) + for key in ('supported', 'own_reported', 'helpers_counted'): if type(gpu['other_programs'].get(key)) is bool: result['gpu']['other_programs'][key] = gpu['other_programs'][key] return result @@ -583,7 +584,8 @@ def resources(value): # Whole-device NVML samples inside one sampling step (monitoring.step_activity). STEP_ACTIVITY = ('samples', 'busy_samples', 'gpu_util_mean_percent', 'sm_clock_mean_mhz', 'power_mean_mw', 'device_used_peak_bytes', 'device_used_minimum_bytes', 'device_total_bytes', - 'other_programs_checks', 'other_programs_percent_mean', 'other_programs_percent_peak') + 'other_programs_checks', 'other_programs_percent_mean', 'other_programs_percent_peak', + 'freevideo_helpers_checks', 'freevideo_helpers_percent_mean', 'freevideo_helpers_percent_peak') def dynamic_budget(value): diff --git a/freevideo_engine/diagnostics.py b/freevideo_engine/diagnostics.py index c698f886..789ea15b 100644 --- a/freevideo_engine/diagnostics.py +++ b/freevideo_engine/diagnostics.py @@ -19,7 +19,8 @@ from . import execution_paths from . import long_paths from . import host_arch -from .long_paths import io_path, resolved, plain, plain_text +from .long_paths import io_path, resolved, plain, plain_text, AUTHORIZATION, EMAIL +from . import report_addresses from . import __version__ from .bootstrap import DEFAULT_ROOT from .system import windows, venv_python, system_memory, nvidia_smi, bootstrap_root @@ -94,7 +95,12 @@ def text(self, value): value = value.replace(secret, '') for source, target in self.replacements: value = value.replace(source, target) + # An address keeps the path report_addresses keeps (on a repository host only FreeVideo's own + # repositories), with no query or fragment; then no user or password, authorization or email. + value = report_addresses.URL.sub(report_addresses.record, value) value = re.sub(r'(?i)(https?://)[^\s/@]+:[^\s/@]+@', r'\1@', value) + value = AUTHORIZATION.sub(r'\1\2\3', value) + value = EMAIL.sub('', value) value = re.sub(r'\bhf_[A-Za-z0-9_-]{8,}\b', '', value) value = re.sub(r'(?i)(Bearer\s+)[A-Za-z0-9._~+/-]+', r'\1', value) value = re.sub(r'(?i)(\b[\w-]{0,64}(?:token|password|secret|api[_-]?key)\s*[=:]\s*)[^\s,;&]+', diff --git a/freevideo_engine/dwd_decode.py b/freevideo_engine/dwd_decode.py index b9a65a0f..a361d7d7 100644 --- a/freevideo_engine/dwd_decode.py +++ b/freevideo_engine/dwd_decode.py @@ -19,8 +19,11 @@ @torch.no_grad() def pixels_to_file(features, grid, audio_latents, out_path, *, base, adapter, artifacts_dir=None, phase_callback=None, - model_cache=None, output_size=None, **_decoder_options): - """features, grid: Features.take() of the fastest mode's Engine. Decoder placement options do not apply.""" + model_cache=None, output_size=None, device='cuda', **_decoder_options): + """features, grid: Features.take() of the fastest mode's Engine. Decoder placement options do not apply. + + device: where the pixel head and the audio decoder run ('cuda', or 'mps' on a Mac). + """ from .video_threads import encode_video from src.inference.render import FPS from . import dwd_head @@ -32,11 +35,11 @@ def phase(name, label=None): started = time.perf_counter() phase('video_decode', HEAD_LABEL) gc.collect() - torch.cuda.empty_cache() # what sampling left cached is not the head's to count - frames, head = dwd_head.render(features, grid, adapter, torch.device('cuda')) + dwd_head.empty_cache(device) # what sampling left cached is not the head's to count + frames, head = dwd_head.render(features, grid, adapter, torch.device(device)) del features gc.collect() - torch.cuda.empty_cache() + dwd_head.empty_cache(device) video_decode_seconds = time.perf_counter() - started artifact_seconds = 0. if artifacts_dir: @@ -58,14 +61,14 @@ def phase(name, label=None): audio_cache_hit = audio_vae is not None if audio_vae is None: from .vae_weights import load_audio_vae - audio_vae, _ = load_audio_vae(base) + audio_vae, _ = load_audio_vae(base, device=device) if model_cache is not None: model_cache.put('audio_vae', audio_key, audio_vae) audio_vae.eval().requires_grad_(False) - audio_mean = torch.tensor(audio_vae.config.latents_mean, device='cuda').view(1, -1, 1) - audio_std = torch.tensor(audio_vae.config.latents_std, device='cuda').view(1, -1, 1) + audio_mean = torch.tensor(audio_vae.config.latents_mean, device=device).view(1, -1, 1) + audio_std = torch.tensor(audio_vae.config.latents_std, device=device).view(1, -1, 1) print(json.dumps({'event': 'decode_phase', 'phase': 'Decoding audio'}), flush=True) - audio = audio_vae.decode(audio_latents * audio_std + audio_mean, return_dict=False)[0] + audio = audio_vae.decode(audio_latents.to(device) * audio_std + audio_mean, return_dict=False)[0] audio = audio.float().permute(1, 0, 2)[0].cpu() rate = audio_vae.config.sampling_rate audio_level = {'audio_rms': float(audio.square().mean().sqrt()) if audio.numel() else 0., @@ -73,7 +76,7 @@ def phase(name, label=None): 'audio_samples': int(audio.shape[-1])} del audio_vae, audio_mean, audio_std gc.collect() - torch.cuda.empty_cache() + dwd_head.empty_cache(device) audio_seconds = time.perf_counter() - audio_start if artifacts_dir: import numpy as np diff --git a/freevideo_engine/dwd_head.py b/freevideo_engine/dwd_head.py index a8050cb0..66519a23 100644 --- a/freevideo_engine/dwd_head.py +++ b/freevideo_engine/dwd_head.py @@ -182,13 +182,37 @@ def __call__(self, features, grid): yield torch.cat(parts).float() +def synchronize(device): + """Wait for the device's queued work (CUDA, MPS); nothing to wait for on the CPU.""" + device = torch.device(device) + if device.type == 'cuda': + torch.cuda.synchronize(device) + elif device.type == 'mps': + torch.mps.synchronize() + + +def empty_cache(device): + """Return the device allocator's cached, unused blocks (CUDA, MPS).""" + device = torch.device(device) + if device.type == 'cuda': + torch.cuda.empty_cache() + elif device.type == 'mps': + torch.mps.empty_cache() + + def render(features, grid, adapter, device): - """uint8 frames (count, height, width, 3) on the CPU and the head's timings and peak.""" + """uint8 frames (count, height, width, 3) on the CPU and the head's timings and peak. + + The peak is the CUDA allocator's (reserved and allocated) or, on a Mac, what the Metal driver held at the end + (unified memory has no separate reserved peak); the CPU reports none. + """ import time from .fast_tier_runtime import adapter_tensors + device = torch.device(device) started = time.perf_counter() weights = adapter_tensors(adapter, lambda name: name.startswith(PREFIX)) - torch.cuda.reset_peak_memory_stats(device) + if device.type == 'cuda': + torch.cuda.reset_peak_memory_stats(device) head = Head(weights, device) loaded = time.perf_counter() mean = torch.tensor(PIXEL_MEAN, device=device).view(3, 1, 1) @@ -196,10 +220,14 @@ def render(features, grid, adapter, device): frames = [] for pixels in head(features.to(device), grid): frames.append((((pixels * std + mean).clamp(-1, 1) * .5 + .5) * 255).round().byte().permute(0, 2, 3, 1).cpu()) - torch.cuda.synchronize(device) + synchronize(device) result = torch.cat(frames) report = dict(head_load_seconds=round(loaded - started, 3), head_seconds=round(time.perf_counter() - loaded, 3), - head_peak_reserved_bytes=torch.cuda.max_memory_reserved(device), - head_peak_allocated_bytes=torch.cuda.max_memory_allocated(device), frames=len(result)) + frames=len(result)) + if device.type == 'cuda': + report.update(head_peak_reserved_bytes=torch.cuda.max_memory_reserved(device), + head_peak_allocated_bytes=torch.cuda.max_memory_allocated(device)) + elif device.type == 'mps': + report.update(head_driver_bytes=torch.mps.driver_allocated_memory()) del head, weights return result, report diff --git a/freevideo_engine/encode_worker.py b/freevideo_engine/encode_worker.py index 4efc9e38..2d66c817 100644 --- a/freevideo_engine/encode_worker.py +++ b/freevideo_engine/encode_worker.py @@ -99,6 +99,11 @@ def main(): args = parser.parse_args() if not args.check_library and not args.request: parser.error('--request is required for encoding') + if args.check_library: + # The setup check is the first import of torch on this computer: a missing Visual C++ runtime says so here. + # (In a child process: this one imports torch next and must find the libraries exactly where torch would.) + from .vc_runtime import require_in_child + require_in_child() request = json.loads(args.request.read_text(encoding='utf-8')) if args.request else {} started = time.perf_counter() if request.get('metrics'): diff --git a/freevideo_engine/engine_exit.py b/freevideo_engine/engine_exit.py index 4bac7c93..63e457ee 100644 --- a/freevideo_engine/engine_exit.py +++ b/freevideo_engine/engine_exit.py @@ -229,4 +229,4 @@ def describe(value, zh): cause = (': the computer ran out of memory' if memory else ', possibly because the computer ran out of memory' if maybe else ': the system or another program ended it' if ended else ': it crashed' if crashed else '') - return 'FreeVideo stopped unexpectedly at %s%s. Click "Connect again" to restart it; if it stops again, export the report and use "Report a problem".' % (clock, cause) + return 'FreeVideo stopped unexpectedly at %s%s. Choose "Connect again" to restart it; if it stops again, export the report and choose "Report a problem".' % (clock, cause) diff --git a/freevideo_engine/failed_copies.py b/freevideo_engine/failed_copies.py new file mode 100644 index 00000000..b1b3aacd --- /dev/null +++ b/freevideo_engine/failed_copies.py @@ -0,0 +1,156 @@ +"""Copies of a file that did not pass: at most the newest one stays, none once the right file is in place. + +``network.retain_partial`` (and a few renames of the same kind) keep a whole file or a prefix that failed its +check, as ``[.partial].-``. Each failure used to leave one more, and nothing removed them, so +a file that failed again and again filled the disk with whole copies of itself. + +One rule, applied only at the two moments the code knows the state: + +* a new copy has just been kept: the older ones of the same file go, the newest stays for diagnosis; +* the right file has just passed its sha256: every copy of it goes. + +Only the exact name of the file the caller is working on is ever matched (never a glob over a folder), a link is +never followed, and a file that has another hard link is left alone: removing it would change the installed file's +change time (the link count is on the file, not on the name). +""" +import os +from pathlib import Path +import re +import stat + +# What network.retain_partial is called with; ``rejected`` is also what a few callers rename by hand. +# Not here, so never removed by this module: ``set-aside``, a file that was already on the install path and is not the +# pinned one (it may be the user's own), moved aside before the right one is fetched. +REASONS = ('hash-rejected', 'rejected', 'oversized-response', 'oversized', 'restart-approved', 'switch-retained') +# The tag is the time in nanoseconds (retain_partial), ticks (Windows scripts) or a uuid (cache folders). +_TAG = r'(?P[0-9a-f]{6,})' +_SUFFIX = re.compile(r'(?:\.partial)?\.(?:%s)-%s' % ('|'.join(REASONS), _TAG)) + + +def _junction(path): + """A Windows directory junction (os.walk and Path.is_dir follow it like a folder, and it is not a symlink).""" + try: + from .runtime_alias import is_junction + return bool(is_junction(Path(path))) + except Exception: + return False + + +def base_name(path): + """The file a retained name belongs to: the name without a trailing ``.partial``.""" + name = Path(path).name + return name[:-len('.partial')] if name.endswith('.partial') else name + + +def copies(path): + """Copies of the file at path that did not pass, newest first. Never follows a link.""" + path = Path(path) + name = base_name(path) + found = [] + try: + entries = list(path.parent.iterdir()) + except OSError: + return [] + for entry in entries: + if not entry.name.startswith(name): + continue + match = _SUFFIX.fullmatch(entry.name[len(name):]) + if not match: + continue + try: + info = entry.lstat() + except OSError: + continue + if stat.S_ISLNK(info.st_mode) or not (stat.S_ISREG(info.st_mode) or stat.S_ISDIR(info.st_mode)): + continue + tag = match['tag'] + # Newest first by the time the copy was last written (names carry nanoseconds, ticks or a uuid, which do not compare). + found.append((info.st_mtime_ns, int(tag) if tag.isdigit() else 0, entry.name, entry)) + return [row[3] for row in sorted(found, reverse=True)] + + +def size_of(entry): + """Bytes a copy holds (a folder: its regular files).""" + entry = Path(entry) + try: + if entry.is_file(): + return entry.lstat().st_size + total = 0 + for directory, folders, files in os.walk(entry, followlinks=False): + folders[:] = [name for name in folders if not _junction(os.path.join(directory, name))] + for name in files: + try: + info = os.lstat(os.path.join(directory, name)) + except OSError: + continue + if stat.S_ISREG(info.st_mode): + total += info.st_size + return total + except OSError: + return 0 + + +def _clear(folder): + """Remove what a copy's folder holds that may go: regular files with one link and the folders emptied by that. + Links and junctions are never followed or removed; what cannot go stays, and so does the folder around it.""" + try: + names = os.listdir(folder) + except OSError: + return + for name in names: + member = os.path.join(folder, name) + try: + info = os.lstat(member) + if stat.S_ISREG(info.st_mode): + if info.st_nlink == 1: + os.unlink(member) + elif stat.S_ISDIR(info.st_mode) and not _junction(member): + _clear(member) + os.rmdir(member) + except OSError: + pass + + +def _remove(entry): + """Delete one copy; True when it is gone. A file with another hard link, or a link, stays.""" + entry = Path(entry) + try: + info = entry.lstat() + if stat.S_ISREG(info.st_mode): + if info.st_nlink > 1: + return False + entry.unlink() + return True + if not stat.S_ISDIR(info.st_mode) or _junction(entry): + return False + _clear(entry) + entry.rmdir() + return True + except OSError: + return False + + +def prune(path, keep=1): + """Remove the copies of the file at path beyond the newest `keep`. Returns what went, as event rows. + + Only called when a new copy was kept (keep=1) or the right file has passed its sha256 (keep=0).""" + removed = [] + for entry in copies(path)[keep:]: + size = size_of(entry) + if _remove(entry): + removed.append(dict(copy=entry.name, bytes=size)) + return removed + + +def describe(entry, observed=None, algorithm='sha256'): + """What a diagnostic report may say about a kept copy: its name, size, time and the digest it actually had. + + The name only, never a folder: a path would carry the user's home directory.""" + entry = Path(entry) + row = dict(copy=entry.name, bytes=size_of(entry)) + match = _SUFFIX.search(entry.name) + if match and match['tag'].isdigit() and len(match['tag']) >= 16: + row['kept_ns'] = int(match['tag']) + if observed: + row.update(observed_digest=observed, algorithm=algorithm) + return row diff --git a/freevideo_engine/failure_details.py b/freevideo_engine/failure_details.py index 4fa581c2..77ba7296 100644 --- a/freevideo_engine/failure_details.py +++ b/freevideo_engine/failure_details.py @@ -133,12 +133,177 @@ def shared_mismatch_text(*, zh=False, portable=None): return (SHARED_MISMATCH_PORTABLE if portable else SHARED_MISMATCH_ELSEWHERE)[bool(zh)] -def image_pack_failure(code, *, zh=False, file=None): +# A write that failed (write_failed), by the step it failed in (image_pack._step). +IMAGE_PACK_WRITE_STEPS = { + 'folder': ('FreeVideo could not write to the image model folder', 'FreeVideo 未能写入图像模型文件夹'), + 'check': ('FreeVideo could not read or record an image model file while checking it', 'FreeVideo 检查图像模型文件时未能读取或记录该文件'), + 'download': ('The image model download could not be saved', '图像模型的下载内容未能保存'), + 'replace': ('The old model file could not be renamed, so the new file could not be put in place', '旧模型文件未能改名,新文件因此未能放入'), + 'record': ('FreeVideo could not save a record file', 'FreeVideo 未能保存记录文件'), + 'remove': ('An image model file could not be deleted', '一个图像模型文件未能删除'), + None: ('An image model file could not be written', '一个图像模型文件未能写入'), +} +# What the system answered, in words of our own: the system's text is in its own language. +IMAGE_PACK_WRITE_ANSWERS = { + 'denied': ('access denied', '拒绝访问'), + 'permission': ('permission denied', '权限不足'), + 'read-only': ('the disk is read-only', '磁盘为只读'), + 'in-use': ('the file is in use by another program', '文件被其他程序占用'), + 'threat': ('security software reported the file as a threat', '安全软件将文件报为威胁'), + 'policy': ('a policy on this computer does not allow it', '这台电脑上的策略不允许'), + 'smart-app-control': ('Smart App Control in Windows stopped it', 'Windows 的“智能应用控制”阻止了写入'), +} +IMAGE_PACK_WRITE_ERRNOS = {'EACCES': 'permission', 'EPERM': 'permission', 'EROFS': 'read-only', 'EBUSY': 'in-use', 'ETXTBSY': 'in-use'} +# The next step by what the system answered; the Windows reasons are windows_blocked's ('permission' is the errno of +# Linux and macOS, where no security software is the usual cause). +IMAGE_PACK_WRITE_NEXT = { + 'denied': ('Check that this account can write to the model folder, or allow the FreeVideo folder in the security software ' + '(for Windows Security: Virus & threat protection → Manage ransomware protection → Controlled folder access), then try again.', + '请确认当前账户可以写入模型文件夹,或在安全软件中允许 FreeVideo 所在的文件夹(Windows 安全中心:病毒和威胁防护 → ' + '管理勒索软件防护 → 受控文件夹访问),然后重试。'), + 'permission': ('Check that this account can write to the model folder (its owner and permissions), then try again.', + '请确认当前账户可以写入模型文件夹(检查文件夹的所有者和权限)后重试。'), + 'read-only': ('Make the disk or folder writable, or connect it again if it is a removable or network drive, then try again.', + '请把磁盘或文件夹改为可写入;如果是移动硬盘或网络盘,请重新连接后重试。'), + 'in-use': ('Close the programs that may be using it (for example an antivirus scan), or restart the computer, then try again.', + '请关闭可能正在使用它的程序(例如杀毒软件扫描),或重新启动电脑,然后重试。'), + 'threat': ('Allow the file in the security software (for Windows Security: Virus & threat protection → Protection history, ' + 'select the entry and allow it) and add the FreeVideo folder to the exclusions, then try again.', + '请在安全软件中允许这个文件(Windows 安全中心:病毒和威胁防护 → 保护历史记录,选中这条记录后允许),' + '并把 FreeVideo 所在的文件夹加入排除项,然后重试。'), + 'policy': ('Ask the administrator of this computer to allow the FreeVideo folder, then try again.', + '请联系这台电脑的管理员允许 FreeVideo 所在的文件夹,然后重试。'), + 'smart-app-control': ('Search Windows for "Smart App Control", or open Windows Security → App & browser control → Smart App ' + 'Control settings, then try again.', + '在 Windows 中搜索“智能应用控制”,或打开“Windows 安全中心 → 应用和浏览器控制 → 智能应用控制设置”,然后重试。'), + None: ('Close programs that may be using the model files (for example an antivirus scan), check that the model folder can be ' + 'written to, then try again.', + '请关闭可能正在使用模型文件的程序(例如杀毒软件扫描),确认模型文件夹可以写入,然后重试。'), +} +# FreeVideo's own check after curl 23 made a file it could not delete again (image_pack._write_answer). +IMAGE_PACK_WRITE_CHECK_LEFT = ('While checking, FreeVideo left an empty file, {file}; you can delete it.', + 'FreeVideo 检查时留下了一个空文件 {file},可以删除。') +# What is kept, where a retry continues from it. +IMAGE_PACK_WRITE_KEPT = { + 'download': ('The downloaded part is kept, and the download resumes from it when you try again.', + '已下载的部分会保留,重试时从中断处继续下载。'), + 'kept_new': ('The original file is unchanged and the new file is kept beside it, so trying again only renames it; ' + 'nothing is downloaded again.', + '原文件没有改动,新文件保留在旁边;重试时只需完成改名,无需重新下载。'), +} + + +def _write_chain(error): + seen = set() + while error is not None and id(error) not in seen: + seen.add(id(error)) + yield error + error = error.__cause__ or (None if error.__suppress_context__ else error.__context__) + + +def image_pack_write_details(error, folders=()): + """What a write_failed carries for the card and the report line: the step (image_pack._step or the PackError's + own), the file and what the system answered (errno name, Windows error, curl's exit). The file is named from the + first of folders it lies in (fixed names only: image_gen/..., text_encoders/...), else with its folders removed as + every report removes them. Nothing else of the error is kept.""" + step = path = curl = kept_new = check_left = None + answer = None + for item in _write_chain(error): + details = getattr(item, 'details', None) or {} + step = step or details.get('step') or getattr(item, 'pack_step', None) + path = path or details.get('path') + curl = curl or details.get('curl') + kept_new = kept_new or details.get('kept_new') + check_left = check_left or details.get('check_left') + if answer is None and isinstance(item, OSError) and (item.errno is not None or getattr(item, 'winerror', None)): + answer = item + if answer is not None: + path = path or answer.filename + value = {} + if step in IMAGE_PACK_WRITE_STEPS: + value['step'] = step + if path: + value['file'] = _pack_file_name(str(path), folders) + winerror = getattr(answer, 'winerror', None) + if type(winerror) is int: + value['winerror'] = winerror # Windows' own code; the errno Python maps it to says less (5 and 32 are both EACCES) + elif answer is not None and answer.errno in errno.errorcode: + value['errno'] = errno.errorcode[answer.errno] + if type(curl) is int: + value['curl'] = curl + if kept_new: + value['kept_new'] = True + if check_left: + value['check_left'] = _pack_file_name(str(check_left), folders) + return value + + +def _pack_file_name(path, folders): + from .long_paths import plain + # monitoring.save writes .<8 random characters>.tmp and renames it: the file it was saving is the one named. + path = re.sub(r'\.[a-z0-9_]{8}\.tmp$', '', path) + for folder in folders: + try: + inside = Path(plain(path)).relative_to(Path(plain(str(folder)))) + except (ValueError, TypeError, OSError): + continue + if inside.parts and '..' not in inside.parts: + return inside.as_posix() + return redacted_launcher_error(path) + + +def _write_answer_kind(write): + from . import windows_blocked + if write.get('winerror') in windows_blocked.REASONS: + return windows_blocked.REASONS[write['winerror']] + return IMAGE_PACK_WRITE_ERRNOS.get(write.get('errno')) + + +def image_pack_write_known(write): + """The system's answer names a cause with a next step of its own (access, a read-only disk, a file in use, the + Windows reasons): the card then offers the report export only, not "Report a problem".""" + return bool(write) and _write_answer_kind(write) is not None + + +def image_pack_write_text(write, *, zh=False): + """The card for a write_failed that knows its step, file or answer; None leaves the general sentence.""" + if not write: + return None + language = 1 if zh else 0 + kind = _write_answer_kind(write) + said = [] + if write.get('file'): + said.append(('文件:' if zh else 'file: ') + write['file']) + answer = [] + if kind: + answer.append(IMAGE_PACK_WRITE_ANSWERS[kind][language]) + if write.get('errno'): + answer.append(write['errno']) + if write.get('winerror') is not None: + answer.append(('Windows 错误 %d' if zh else 'Windows error %d') % write['winerror']) + if not answer and write.get('curl'): + answer.append(('curl 错误 %d' if zh else 'curl error %d') % write['curl']) + if answer: + said.append(('原因:' if zh else 'reason: ') + ((',' if zh else ', ').join(answer))) + text = IMAGE_PACK_WRITE_STEPS[write.get('step')][language] + if said: + text += ('(%s)' % ';'.join(said)) if zh else ' (%s)' % '; '.join(said) + text += '。' if zh else '.' + kept = IMAGE_PACK_WRITE_KEPT['kept_new' if write.get('kept_new') else write.get('step')] \ + if write.get('kept_new') or write.get('step') in IMAGE_PACK_WRITE_KEPT else None + parts = [text, IMAGE_PACK_WRITE_NEXT[kind][language]] + ([kept[language]] if kept else []) + if write.get('check_left'): + parts.append(IMAGE_PACK_WRITE_CHECK_LEFT[language].replace('{file}', write['check_left'])) + return ('' if zh else ' ').join(parts) + + +def image_pack_failure(code, *, zh=False, file=None, write=None): if code == 'shared_mismatch': return dict(kind='image-pack', title=('图像模型操作未完成' if zh else 'Image model operation stopped'), detail=shared_mismatch_text(zh=zh), action='') + detail = image_pack_write_text(write, zh=zh) if code == 'write_failed' else None return dict(kind='image-pack', title=('图像模型操作未完成' if zh else 'Image model operation stopped'), - detail=IMAGE_PACK_FAILURES.get(code, IMAGE_PACK_FAILURES['failed'])[bool(zh)], action='') + detail=detail or IMAGE_PACK_FAILURES.get(code, IMAGE_PACK_FAILURES['failed'])[bool(zh)], action='') def sampling_table_details(value): @@ -155,10 +320,11 @@ def sampling_table_details(value): 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']) - and details.get('step_cache') in STEP_CACHES and details.get('scale', 2) in SCALES): + and details.get('step_cache') in STEP_CACHES and details.get('scale', 2) in SCALES + and details.get('upscale', True) is True): return {key: details[key] for key in ('base_steps', 'two_pass', 'refine_steps', 'missing_bytes', 'available', 'decimal_sizes', 'step_cache', - 'scale') + 'scale', 'upscale') if key in details} except (ValueError, KeyError, TypeError): pass @@ -171,6 +337,15 @@ def sampling_table_failure(value, *, zh=False): return None from .launcher_copy import size_text language = 1 if zh else 0 + if details.get('upscale'): + # An upscale of a finished video: not a quality level, and no other level would do instead. + size = size_text(details['missing_bytes'], details['decimal_sizes']) + if zh: + return dict(kind='sampling-table', title='放大所需的采样缓存尚未下载', + detail='第一次放大需要先下载采样缓存(约 %s),这次未能完成。请检查网络后再放大一次。' % size, action='') + return dict(kind='sampling-table', title='Sampling caches for upscaling are not downloaded yet', + detail='The first upscale needs to download sampling caches (about %s), and the download did not finish this ' + 'time. Check the network connection, then upscale again.' % size, action='') # Tables follow the step count: 16 steps is high, 20 steps is max. level = table_level(details['base_steps'], details['two_pass'], details['refine_steps'], details.get('step_cache'), on_mac(), details.get('scale', 2)) @@ -300,7 +475,7 @@ def setup_command_failure(label, log, exit_code, report=None): probes = report.get('kernel_probes', []) probes = [row for row in probes if isinstance(row, dict)] if isinstance(probes, list) else [] linear_ok = any(row.get('backend') == 'linear' and row.get('status') == 'complete' for row in probes) - attention_ok = any(row.get('backend') not in (None, 'linear') and row.get('status') == 'complete' for row in probes) + attention_ok = any(row.get('backend') not in (None, 'linear', 'linear-int8') and row.get('status') == 'complete' for row in probes) if probes and not linear_ok: lines.append('Required linear kernel did not pass.') if probes and not attention_ok: @@ -407,6 +582,12 @@ def file_in_use(text): ('This location cannot be used', '无法使用这个位置'), ('Windows does not let this account create folders in this location. Choose a folder in the user folder or on another drive.', 'Windows 不允许当前账户在这个位置创建文件夹。请改选用户文件夹或其他硬盘上的文件夹。')), + (r'Windows does not accept a folder name in the installation folder path', 'folder-name-invalid', + ('A folder name in the install location is not valid', '安装位置中有无效的文件夹名'), + ('A folder name in the install location contains a character Windows does not allow, is a name Windows ' + 'reserves for devices, or ends with a space or a dot. Rename it or choose another folder.', + '安装位置中有一个文件夹名含有 Windows 不允许的字符、是 Windows 为设备保留的名称,或以空格或句点结尾。' + '请修改该名称,或另选一个文件夹。')), (r'Missing or incomplete bundled file: ', 'missing-file', ('The installation files are incomplete', '安装文件不完整'), ('Extract the whole package again, and check that security software has not removed any files.', @@ -504,6 +685,39 @@ def _model_unchanged(tail): # Windows refused to load a file (Smart App Control or another application control policy). APPLICATION_CONTROL = r'WinError 4551|Application Control policy has blocked' +# vc_runtime.require() before the first import of torch, or torch's own error when c10.dll (which needs only the +# Visual C++ runtime beside Windows' own libraries) could not be loaded or did not initialize (Windows error 126 or 1114). +# The codes are matched, not the text, which Windows writes in the system language. +VC_RUNTIME = (r'\[VC_RUNTIME_UNAVAILABLE (?:x64|ARM64)\]' + r'|\[WinError (?:126|1114)\][^"]{0,400}?Error loading "[^"\r\n]*[\\/]c10\.dll"') +VC_RUNTIME_TITLE = ('The Microsoft Visual C++ runtime is missing or not working', 'Microsoft Visual C++ 运行库缺失或无法使用') +# The card's "Download runtime" key opens Microsoft's page (Main.qml, vcRuntimeLink); the person installs it there. +VC_RUNTIME_NEXT = ('Choose "Download runtime", download and install the {arch} version from the Microsoft page, then choose "Retry installation".', + '请点击“下载运行库”,在微软页面下载并安装 {arch} 版本,然后点击“重试安装”。') +VC_RUNTIME_FILES = ('Not loaded: %s', '未能加载:%s') +VC_RUNTIME_FILE = ('%s (Windows error %s)', '%s(Windows 错误 %s)') +VC_RUNTIME_JOIN = ('; ', ';') +# The one package that fits every FreeVideo computer. Microsoft's page: "The X64 +# Redistributable package contains both ARM64 and X64 binaries. This package makes it easy to install required Visual C++ +# ARM64 binaries when the X64 Redistributable is installed on an ARM64 device." So on Windows on Arm it serves a native ARM64 +# Python and an x64 one alike, and the card never has to guess which one failed; the ARM64 package has no x64 files. +VC_RUNTIME_PACKAGE = 'x64' + + +def vc_runtime_failure(text, zh=False): + """The card for a Visual C++ runtime that did not load, or None. Its detail names the files and Windows' codes.""" + marked = re.search(r'\[VC_RUNTIME_UNAVAILABLE (x64|ARM64)\]: ([^\r\n]+)', text) + if marked: + rows = re.findall(r'([\w.-]+\.dll) \(Windows error (\w+)\)', marked.group(2)) + else: + found = re.search(r'\[WinError (126|1114)\][^"]{0,400}?Error loading "[^"\r\n]*[\\/](c10\.dll)"', text) + if not found: + return None + rows = [(found.group(2), found.group(1))] + files = VC_RUNTIME_JOIN[zh].join(VC_RUNTIME_FILE[zh] % row for row in rows) + return dict(title=VC_RUNTIME_TITLE[zh], detail=VC_RUNTIME_FILES[zh] % files + '\n' + VC_RUNTIME_NEXT[zh].format(arch=VC_RUNTIME_PACKAGE), + action='', kind='vc-runtime') + # Error lines ComfyUI may end on, as a sentence for the card; any other line stays in the technical details. STARTUP_ERRORS = ( @@ -767,6 +981,24 @@ class names and errno, no text), when the message is that exception's str(); it 'Open FreeVideo from its desktop shortcut, or download the latest launcher.') return dict(title='启动器比已安装的 FreeVideo 旧' if zh else 'This launcher is older than the installed FreeVideo', detail=detail, action='', kind='older-launcher', manual=True) + blocked = re.search(r'\[UPDATE_START_BLOCKED ([\w-]+)\]', summary) + if blocked: + # launcher_update.LauncherStartBlocked: the update is downloaded and this launcher keeps working; a folder + # someone can write to has nothing to do with it. The session adds the folder of the downloaded launcher. + cause = UPDATE_START_BLOCKED.get(blocked[1], UPDATE_START_BLOCKED['denied']) + # reason: the card leads with the releases page when waiting or starting the same file again will not help. + then = UPDATE_START_BLOCKED_NEXT_RELEASE_FIRST if blocked[1] in UPDATE_START_REFUSED else UPDATE_START_BLOCKED_NEXT + return dict(title=UPDATE_START_BLOCKED_TITLE[zh], detail=cause[zh] + '\n' + then[zh], + action='', kind='update-start-blocked', manual=True, + reason=blocked[1] if blocked[1] in UPDATE_START_BLOCKED else 'denied') + python_blocked = re.search(r'\[PYTHON_FILE_BLOCKED ([\w-]+)\]', text) + if python_blocked: + # windows_blocked.python_file_message (setup) and freevideo.ps1: Windows did not let setup write a Python file, + # already tried again after short waits. Leads before the step's other lines (a timed-out source, a 403). + reason = python_blocked[1] if python_blocked[1] in PYTHON_FILE_BLOCKED else 'denied' + title = PYTHON_FILE_BLOCKED_TITLE.get(reason, PYTHON_FILE_BLOCKED_TITLE['default']) + return dict(title=title[zh], detail=PYTHON_FILE_BLOCKED[reason][zh] + '\n' + PYTHON_FILE_BLOCKED_NEXT[reason][zh], + action='', kind='python-file-blocked', reason=reason) from .model_repair import MISMATCH, MISMATCH_PATH, FAILURE_TITLE, FAILURE, CHANGED_TITLE, CHANGED_REPAIR mismatches = re.findall(MISMATCH + r': ([^\r\n]+)', text) bundled_models = re.findall(r'Bundled (?:file failed verification|model file has incorrect size): (models/[^\r\n]+)', summary) @@ -847,7 +1079,7 @@ class names and errno, no text), when the message is that exception's str(); it detail=_startup_cause(summary, zh) + '\n' + action, action='', kind='comfy-startup') # A file Windows refused to load is no GPU result: the app-control guidance below applies, and the # code the engine adds to the message makes it recognisable in any system language. - if ('Failed step: kernels (' in summary and not re.search(APPLICATION_CONTROL, summary) + if ('Failed step: kernels (' in summary and not re.search(APPLICATION_CONTROL, summary) and not re.search(VC_RUNTIME, text) and not re.search(ORPHANED_PYTHON, summary)): detail = summary[summary.index('Failed step: kernels ('):] detail = detail.partition('\nRetained step log:')[0] @@ -936,7 +1168,7 @@ class names and errno, no text), when the message is that exception's str(); it '安装已停止,以免打断正在生成的视频。视频生成完成后,请点击“重试安装”,并再次确认安装。已完成的步骤会保留。')), # Moving the engine's editable install to the new source failed and was undone (engine_binding). (r'Editable install failed for|Editable verification failed for|The engine.s uv is missing', 'update-unfinished', - ('The update did not finish', '这次更新没有完成'), + ('The update did not finish', '这次更新未完成'), ('FreeVideo is back on the previous version and works as before. Click Repair to reinstall the engine environment and update again; the details give the reason.', 'FreeVideo 已退回原来的版本,可以照常使用。点“修复”可以再次更新,原因在详情里。')), (r'Git \d+\.\d+ is too old to download the pinned sources', 'git-version', @@ -958,7 +1190,7 @@ class names and errno, no text), when the message is that exception's str(); it '请只导入模型包并继续安装,FreeVideo 会自动下载 Mac 的运行环境。')), # Both carry ComfyUI's log, whose unrelated lines must not pick the card. (r'ComfyUI is still starting or could not load FreeVideo', 'comfy-nodes', - ('ComfyUI did not load FreeVideo', 'ComfyUI 没有加载 FreeVideo'), + ('ComfyUI did not load FreeVideo', 'ComfyUI 未加载 FreeVideo'), ('Click Retry. If it stops here again, the ComfyUI log in the details shows why the FreeVideo nodes did not load; export the report to send it.', '请点“重试”。仍然停在这里时,可以导出报告。')), (r'ComfyUI is already running\. Restart it once', 'comfy-restart', @@ -1051,7 +1283,7 @@ class names and errno, no text), when the message is that exception's str(); it ('Switching the download source or connection mode gives the same result. Choose "Export report", then "Report a problem", and attach the report.', '更换下载源或连接方式后结果相同。请先点击“导出报告”,再点击“提交问题”并附上报告。')), (r'Model download paused|unexpected-transfer-size|ConnectionError|ConnectTimeout|ReadTimeout|HTTP probe failed|Could not resolve host|SSL certificate|Every download source failed|All Git sources failed|All package sources failed|Python download failed on every route', 'download', - ('Download interrupted', '下载中断了'), + ('Download interrupted', '下载已中断'), ('Check your network or change the source or connection mode in Settings → Downloads, then retry.', '检查网络,或在“设置 → 下载”中切换下载源、连接模式后重试。')), (r'FreeVideo cannot read its program files', 'unreadable-files', ('FreeVideo cannot read its own files', 'FreeVideo 读不到自己的程序文件'), @@ -1134,6 +1366,9 @@ class names and errno, no text), when the message is that exception's str(); it or re.search(r'\[CUDA_CAPABILITY_UNKNOWN\] Could not determine the CUDA architecture of (.+?) \(SM', text) if named and named.group(1) and BELOW_COMPUTE_FLOOR.search(named.group(1)): text += '\n[CUDA_ARCH_UNSUPPORTED] %s (SMunknown; compute capability unknown; driver unknown)' % named.group(1) + vc_runtime = vc_runtime_failure(text, zh) + if vc_runtime: + return vc_runtime for pattern, kind, title, action in rules: if re.search(pattern, text, re.I): if kind in WITHOUT_REPAIR and not can_repair: @@ -1208,7 +1443,7 @@ class names and errno, no text), when the message is that exception's str(); it # The internal step id never reaches the card; the exit code stays in the technical details. name = _step_name(step.group(1), zh) if name: - title = ('“%s”这一步没有完成' if zh else 'The step "%s" did not finish') % name + title = ('“%s”这一步未完成' if zh else 'The step "%s" did not finish') % name # The step's own line is internal. The last other error line is raw text, so it shows only # when it has a known sentence in this language; otherwise it stays in the technical details. other = [line for line in causes if not line.startswith(('Failed step:', 'Setup failed:'))] @@ -1240,7 +1475,71 @@ class names and errno, no text), when the message is that exception's str(); it # comfy_setup.inspection_failed: the first line of a failed check. INSPECTION_SUMMARY = r'Setup inspection failed(?: \([^()\r\n]*(?:\([^()\r\n]*\)[^()\r\n]*)*\))?' -CHECK_UNFINISHED = ('The check did not finish.', '这次检查没有完成。') +CHECK_UNFINISHED = ('The check did not finish.', '这次检查未完成。') +# Windows did not let the downloaded launcher start (launcher_update.START_BLOCKED), by its reason. +UPDATE_START_BLOCKED_TITLE = ('The new version could not start', '新版本未能启动') +UPDATE_START_BLOCKED = { + 'denied': ('Windows or security software stopped the downloaded launcher from starting. This version of FreeVideo keeps working.', + 'Windows 或安全软件阻止了下载的启动器启动。当前版本的 FreeVideo 照常可用。'), + 'in-use': ('Another program kept the downloaded launcher open, so it could not start. This version of FreeVideo keeps working.', + '下载的启动器被其他程序占用,未能启动。当前版本的 FreeVideo 照常可用。'), + 'threat': ('Security software reported the downloaded launcher as a threat and stopped it. This version of FreeVideo keeps working.', + '安全软件把下载的启动器报为威胁并阻止了它。当前版本的 FreeVideo 照常可用。'), + 'policy': ('A policy on this computer does not allow the downloaded launcher to start. This version of FreeVideo keeps working.', + '这台电脑上的策略不允许下载的启动器启动。当前版本的 FreeVideo 照常可用。'), + 'smart-app-control': ('Smart App Control in Windows stopped the downloaded launcher. This version of FreeVideo keeps working.', + 'Windows 的“智能应用控制”阻止了下载的启动器。当前版本的 FreeVideo 照常可用。'), +} +UPDATE_START_BLOCKED_NEXT = ('Open the download location and start the new launcher by hand, or download the latest version from the releases page.', + '请打开下载位置手动启动新启动器,或到发布页下载最新版本。') +# A threat report, a policy or Smart App Control stops the same file again from that folder: the releases page comes first, +# in the order of the card's buttons (Main.qml updateStartRefused). +UPDATE_START_REFUSED = ('threat', 'policy', 'smart-app-control') +UPDATE_START_BLOCKED_NEXT_RELEASE_FIRST = ( + 'Download the latest version from the releases page, or open the download location and start the new launcher by hand.', + '请到发布页下载最新版本,或打开下载位置手动启动新启动器。') +# Windows did not let setup write a Python file (windows_blocked.PYTHON_FILE_MARKER), by its reason. Each reason has its +# own next step: allowing the folder does not help a file in use, a policy or Smart App Control. +# One card for a Python file and a package file such as a PyTorch DLL: it says "file", which is what the +# security software's records name. +PYTHON_FILE_BLOCKED_TITLE = { + 'default': ('A file was blocked during setup', '安装中的文件被拦截'), + 'in-use': ('A file was in use during setup', '安装中的文件被其他程序占用'), +} +PYTHON_FILE_BLOCKED = { + 'denied': ('Security software or a Windows protection feature did not let setup write a file into the FreeVideo folder.', + '安全软件或 Windows 的保护功能不允许安装程序把文件写入 FreeVideo 所在的文件夹。'), + 'in-use': ('Another program kept a file in the FreeVideo folder open, so setup could not write it.', + '其他程序占用了 FreeVideo 文件夹中的文件,安装程序无法写入。'), + 'threat': ('Security software reported a file as a threat and stopped setup from writing it.', + '安全软件把一个文件报为威胁,阻止了安装程序写入。'), + 'policy': ('A policy on this computer does not allow setup to write files into the FreeVideo folder.', + '这台电脑上的策略不允许安装程序把文件写入 FreeVideo 所在的文件夹。'), + 'smart-app-control': ('Smart App Control in Windows stopped setup from writing a file.', + 'Windows 的“智能应用控制”阻止了安装程序写入文件。'), +} +# Windows Security's menu names as Microsoft's support pages give them (zh-CN: 病毒和威胁防护, 保护历史记录). +PYTHON_FILE_BLOCKED_NEXT = { + 'denied': ('Allow the FreeVideo folder in the security software (for Windows Security: Virus & threat protection → Manage ' + 'ransomware protection → Controlled folder access, and the exclusions list), then choose "Retry installation". ' + 'You can also install FreeVideo in another folder.', + '请在安全软件中允许 FreeVideo 所在的文件夹(Windows 安全中心:病毒和威胁防护 → 管理勒索软件防护 → 受控文件夹访问,' + '以及排除项),然后点击“重试安装”。也可以把 FreeVideo 安装到其他文件夹。'), + 'threat': ('Allow the file in the security software (for Windows Security: Virus & threat protection → Protection history, ' + 'select the entry and allow it) and add the FreeVideo folder to the exclusions, then choose "Retry installation".', + '请在安全软件中允许这个文件(Windows 安全中心:病毒和威胁防护 → 保护历史记录,选中这条记录后允许),' + '并把 FreeVideo 所在的文件夹加入排除项,然后点击“重试安装”。'), + 'in-use': ('Close the programs that may be using files in the FreeVideo folder, or restart the computer, then choose ' + '"Retry installation".', + '请关闭可能正在使用 FreeVideo 文件夹中文件的程序,或重新启动电脑,然后点击“重试安装”。'), + 'policy': ('Ask the administrator of this computer to allow the FreeVideo folder, or install FreeVideo in another folder, ' + 'then choose "Retry installation".', + '请联系这台电脑的管理员允许 FreeVideo 所在的文件夹,或把 FreeVideo 安装到其他文件夹,然后点击“重试安装”。'), + 'smart-app-control': ('Search Windows for "Smart App Control", or open Windows Security → App & browser control → Smart ' + 'App Control settings, then choose "Retry installation".', + '在 Windows 中搜索“智能应用控制”,或打开“Windows 安全中心 → 应用和浏览器控制 → 智能应用控制设置”,' + '然后点击“重试安装”。'), +} # The way to send a failure to us, by the launcher's own button names (Main.qml: "Export report", "Report a problem"). REPORT_STEP = ('If it fails again, select "Export report", then select "Report a problem" and attach the report.', '仍然失败时,请先点击“导出报告”,再点击“提交问题”并附上报告。') diff --git a/freevideo_engine/fast_pack.py b/freevideo_engine/fast_pack.py index 4117cc53..2f89defc 100644 --- a/freevideo_engine/fast_pack.py +++ b/freevideo_engine/fast_pack.py @@ -39,8 +39,19 @@ def rows(spec=None): def model_folder(): - from .paths import installed_model_root - return installed_model_root() + """The model folder the queue check and the engine process read (comfy_bridge.engine_model_root). + + ComfyUI started without the launcher has no FREEVIDEO_HOME, where paths would name the default installation folder + instead of the one comfyui.json selects: the files would land where the engine never looks. + """ + from .comfy_bridge import engine_model_root + return engine_model_root() + + +def engine_folder(): + """The installation whose download settings, measured sources and lock the download uses.""" + from .comfy_bridge import installation_root + return installation_root() def remote(spec, row): @@ -319,7 +330,8 @@ def check(): def progress(value): self._set(done=value.get('done', 0), total=value.get('total', 0)) try: - install(self.root(), progress, check, engine_root=self.engine_root) + install(self.root(), progress, check, + engine_root=self.engine_root if self.engine_root is not None else engine_folder()) self._set(state='done', reason=None) except InterruptedError: self._set(state='cancelled', reason=None) diff --git a/freevideo_engine/fast_tier.py b/freevideo_engine/fast_tier.py index 717e0716..1ae59bf1 100644 --- a/freevideo_engine/fast_tier.py +++ b/freevideo_engine/fast_tier.py @@ -16,7 +16,6 @@ import json from pathlib import Path import stat -import sys from .long_paths import io_path @@ -70,8 +69,6 @@ def request(args): return None if mode not in MODES: raise ValueError('Fast mode must be one of ' + ', '.join(MODES)) - if sys.platform == 'darwin': - raise ValueError('The fastest mode is not available on Mac') for name, label in (('continue_from', 'a continued part'), ('continue_anchor', 'a continued part'), ('preview', 'a preview'), ('refine_from', 'finishing a preview'), ('upscale_from', 'an upscale'), ('redo_sound', 'redoing the sound'), diff --git a/freevideo_engine/fast_tier_runtime.py b/freevideo_engine/fast_tier_runtime.py index 13f7a0f9..806d9b71 100644 --- a/freevideo_engine/fast_tier_runtime.py +++ b/freevideo_engine/fast_tier_runtime.py @@ -107,7 +107,11 @@ def begin(self, grid): self.grid, self.count, self.hidden, self.value = grid, 0, None, None def keep_hidden(self, _module, _args, output): - self.hidden = output + # With residual offload the block hands back its ResidualState; the model + # takes the stream out of it and closes it before after_forward runs, so + # keep the device tensor it holds now. + from .residual import ResidualState + self.hidden = output.tensor if isinstance(output, ResidualState) else output def after_forward(self, _module, _args, kwargs, _output): self.count += 1 diff --git a/freevideo_engine/feedback.py b/freevideo_engine/feedback.py index a5911220..eba763f6 100644 --- a/freevideo_engine/feedback.py +++ b/freevideo_engine/feedback.py @@ -5,12 +5,11 @@ """ import json import re -from functools import lru_cache -from pathlib import Path -from urllib.parse import urlsplit from .exit_diagnostics import OWN_MEMORY_KEYS -from .long_paths import AUTHORIZATION, EMAIL +from .long_paths import AUTHORIZATION, EMAIL, ends_at_user_folder +# What of a web address stays is one rule for every report (report_addresses); these names stay here too. +from .report_addresses import DOWNLOAD_CONFIGS, URL, own_repositories, public_hosts, site # The summary travels in a GitHub page address, which has to stay short. MAX_DIAGNOSTICS = 3000 @@ -22,38 +21,9 @@ PATH = re.compile(r'''(?]*)?(?:/+|(?=[A-Za-z]:[\\/]))[^'"<>|\r\n]*''' r'|(?:(?|\r\n]+|(?|\r\n]+)+') AFTER_FILE_NAME = re.compile(r'\.[A-Za-z0-9]{1,8}(?=[\s:,;)])') -USER_FOLDERS = ('users', 'home', 'documents and settings') TOKEN = re.compile(r'\b[A-Za-z0-9_\-]{32,}\b') -# A web address loses its user, password, query and fragment. On a public download host FreeVideo uses -# (public_hosts) it keeps its path, which names the file that failed; on any other host, or an IP -# address (replaced too), only the scheme, host and port stay. The reason after it stays as well. -URL = re.compile(r'''\b(?P[A-Za-z][A-Za-z0-9+.-]*://)(?P[^\s/?#'"<>]*)(?P[^\s'"<>]*)''') -IP_HOST = re.compile(r'^(?:\[[^\]]*\]|\d{1,3}(?:\.\d{1,3}){3})(?=:\d+$|$)') # One pass, so a path inside a kept address ("/-/binary/...") is not taken for a local one. PLACE = re.compile(PATH.pattern + '|' + URL.pattern) -# The shipped files that name download addresses and repositories; their hosts are public_hosts. -DOWNLOAD_CONFIGS = ('bootstrap_versions.json', 'curl_windows.json', 'dependencies.json', 'depth_reference_model.json', - 'frame_preview_weights.json', 'frame_upscale_model.json', 'gcc_linux.json', 'git_linux.json', - 'git_macos.json', 'macos_reference_catalog.json', 'model_files.json', 'model_shares.json', - 'prepared_models.json', 'rife_interp_model.json', 'subtitle_pack.json', 'swap_lora.json', - 'torch_downloads.json', 'uv_downloads.json', 'windows_arm64.json') -# Hosts that keep anyone's repositories, shares or channels: the first part of a path there is usually -# its owner's name, so only the repositories FreeVideo itself uses (own_repositories: "owner/name", or the -# channel alone on conda.anaconda.org, after the parts the host puts before it; "x.git" is "x") keep -# their path. Package hosts (pypi.org, files.pythonhosted.org, -# download.pytorch.org ...) hold public packages only and keep any path. -REPOSITORY_HOSTS = { - 'huggingface.co': r'(?:api/)?(?:models/|datasets/|spaces/)?', - 'hf-mirror.com': r'(?:api/)?(?:models/|datasets/|spaces/)?', - 'modelscope.cn': r'(?:api/v1/)?(?:models/|datasets/)?', - 'www.modelscope.cn': r'(?:api/v1/)?(?:models/|datasets/)?', - 'github.com': '', - 'api.github.com': r'(?:repos/)?', - 'ghfast.top': r'(?:https?:/+github\.com/)?', - 'pan.quark.cn': '', - 'conda.anaconda.org': '', -} -ONE_PART_HOSTS = frozenset(('conda.anaconda.org',)) HARDWARE_KEYS = ('gpu_name', 'vram_total', 'ram_total', 'system', 'architecture', 'driver_version', 'torch_version', 'cuda_version') @@ -64,102 +34,15 @@ def _place(match): value = match.group(0) - parts = re.split(r'[\\/]', value) - last = parts[-1] - # The last part right under the users' folders is a user's own folder: its name may hold a dot and a - # space ("J.R Smith") and goes as a whole. - name = None if len(parts) > 1 and parts[-2].lower() in USER_FOLDERS else AFTER_FILE_NAME.search(last) + last = re.split(r'[\\/]', value)[-1] + # A user's own folder (under Users, /home, /var/home, a profiles share ...) goes as a whole: its name + # may hold a dot and a space ("J.R Smith"). + name = None if ends_at_user_folder(value) else AFTER_FILE_NAME.search(last) return '' + (value[len(value) - len(last) + name.end():] if name else '') -@lru_cache(maxsize=1) -def _shipped(): - """The download addresses FreeVideo names and the repository values ("owner/name") of its configuration.""" - addresses, repositories = [], [] - try: - from . import network - addresses += [url for table in network.SOURCES.values() for url in table.values()] - addresses += list(network.PYTHON_MIRRORS.values()) - except Exception: - pass - try: - from . import launcher_update - addresses += [launcher_update.MIRROR_BASE, launcher_update.API, launcher_update.WEB] - repositories.append(launcher_update.REPOSITORY) - except Exception: - pass - - def walk(value, key=''): - if isinstance(value, dict): - for name, item in value.items(): - walk(item, str(name)) - elif isinstance(value, list): - for item in value: - walk(item, key) - elif isinstance(value, str) and 'repo' in key.lower() and re.fullmatch(r'[\w.-]+/[\w.-]+', value): - repositories.append(value) - for name in DOWNLOAD_CONFIGS: - try: - text = (Path(__file__).parent / name).read_text(encoding='utf-8') - addresses += re.findall(r'''https?://[^\s"'<>\\]+''', text) - walk(json.loads(text)) - except (OSError, ValueError, RecursionError): - continue - return tuple(addresses), tuple(repositories) - - -def _host(address): - try: - host = urlsplit(address).hostname - except ValueError: - return None - return host.lower() if host and not IP_HOST.match(host) else None - - -@lru_cache(maxsize=1) -def public_hosts(): - """The public hosts FreeVideo downloads from: the download sources and mirrors, the release hosts and - every host in the shipped download configuration. A host that cannot be read is simply not on it.""" - return frozenset(filter(None, map(_host, _shipped()[0]))) - - -def _repository(host, path): - """"owner/name" (a channel on a one-part host) of an address's path on a repository host, or None.""" - parts = r'([^/]+)' if host in ONE_PART_HOSTS else r'([^/]+/[^/]+)' - found = re.match(r'/*' + REPOSITORY_HOSTS[host] + parts, path, flags=re.IGNORECASE) - return _repository_name(found.group(1)) if found else None - - -def _repository_name(value): - return re.sub(r'\.git$', '', value.lower()) - - -@lru_cache(maxsize=1) -def own_repositories(): - """The repositories, shares and channels FreeVideo itself uses on the repository hosts.""" - addresses, repositories = _shipped() - own = {_repository_name(value) for value in repositories} - for address in addresses: - host = _host(address) - if host in REPOSITORY_HOSTS: - own.add(_repository(host, urlsplit(address).path)) - own.discard(None) - return frozenset(own) - - -def _site(match): - host = match.group('authority').rpartition('@')[2] - if IP_HOST.match(host): - return match.group('scheme') + IP_HOST.sub('', host) - rest = re.split(r'[?#]', match.group('rest'), maxsplit=1)[0] - name = re.sub(r':\d*$', '', host).lower() - if name not in public_hosts() or (name in REPOSITORY_HOSTS and _repository(name, rest) not in own_repositories()): - rest = '' - return match.group('scheme') + host + rest - - def _found(match): - return _site(match) if match.group('scheme') else _place(match) + return site(match) if match.group('scheme') else _place(match) def scrub(value): diff --git a/freevideo_engine/fp8.py b/freevideo_engine/fp8.py index 917f3fe4..a6c644c3 100644 --- a/freevideo_engine/fp8.py +++ b/freevideo_engine/fp8.py @@ -21,6 +21,20 @@ from .tensor_io import open_tensors +def retain_corrupt_group(destination, progress): + """A prepared group that failed its check is kept (the newest only) while it is rebuilt.""" + from .network import retain_partial + retain_partial(destination, 'hash-rejected') + retain_partial(progress, 'hash-rejected') + + +def forget_corrupt_group(destination, progress): + """The group is in place and verified: the corrupt ones kept for it go.""" + from .network import forget_failed + forget_failed(destination) + forget_failed(progress) + + def input_dtype(module): """Input dtype of an ordinary Linear or a cached official FP8 Linear.""" return module.input_dtype if hasattr(module, 'input_dtype') else module.weight.dtype @@ -119,6 +133,7 @@ def prepare_streamed(base, checkpoint, cache_root): 'index': index, 'total': len(group_names)}), flush=True) saved = reusable_group(output, group) if saved is not None: + forget_corrupt_group(destination, progress) reused_groups += 1 records.append(saved) linears.update(saved['linears']) @@ -126,9 +141,7 @@ def prepare_streamed(base, checkpoint, cache_root): 'index': index, 'total': len(group_names), 'reused': True}), flush=True) continue if destination.is_file() and progress.is_file(): - rejected = '.hash-rejected-' + str(time.time_ns()) - destination.rename(destination.with_name(destination.name + rejected)) - progress.rename(progress.with_name(progress.name + rejected)) + retain_corrupt_group(destination, progress) print(json.dumps({'event': 'rebuild_fp8_group', 'group': group, 'reason': 'Corrupt group retained before rebuilding'}), flush=True) print(json.dumps({'event': 'prepare_fp8_phase', 'phase': 'read_source_weights', 'group': group, @@ -328,15 +341,14 @@ def prepare(source, cache_root, *, base, checkpoint): progress = destination.with_suffix('.json') saved = reusable_group(output, group['group']) if saved is not None: + forget_corrupt_group(destination, progress) groups.append(saved) linears.update(saved['linears']) print(json.dumps({'event': 'prepared_fp8_group', 'group': group['group'], 'index': index, 'total': len(manifest['groups']), 'reused': True}), flush=True) continue if destination.is_file() and progress.is_file(): - rejected = '.hash-rejected-' + str(time.time_ns()) - destination.rename(destination.with_name(destination.name + rejected)) - progress.rename(progress.with_name(progress.name + rejected)) + retain_corrupt_group(destination, progress) path = source / group['file'] if path.stat().st_size != group['bytes'] or sha256(path) != group['sha256']: raise ValueError('Source cache failed integrity check: ' + str(path)) diff --git a/freevideo_engine/frame_interp.py b/freevideo_engine/frame_interp.py index 0d2744b0..cb98550d 100644 --- a/freevideo_engine/frame_interp.py +++ b/freevideo_engine/frame_interp.py @@ -114,7 +114,7 @@ def ensure_weights(root, emit, check): if path.is_file() and path.stat().st_size == row['bytes'] and _digest(path, check) == row['sha256']: return path if path.exists(): - network.retain_partial(path, 'rejected') + network.retain_partial(path, 'set-aside') plan_ = _download_plan(Path(root)) sources = plan_['sources'] = dict(plan_.get('sources', {})) if not sources.get('image-models'): diff --git a/freevideo_engine/frame_upscale.py b/freevideo_engine/frame_upscale.py index 664d2f78..32d04622 100644 --- a/freevideo_engine/frame_upscale.py +++ b/freevideo_engine/frame_upscale.py @@ -211,7 +211,7 @@ def ensure_weights(root, emit, check): if path.is_file() and path.stat().st_size == row['bytes'] and _digest(path, check) == row['sha256']: return path if path.exists(): - network.retain_partial(path, 'rejected') + network.retain_partial(path, 'set-aside') plan = _download_plan(Path(root)) sources = plan['sources'] = dict(plan.get('sources', {})) if not sources.get('image-models'): diff --git a/freevideo_engine/generate.py b/freevideo_engine/generate.py index d2a96160..c08bbbe9 100644 --- a/freevideo_engine/generate.py +++ b/freevideo_engine/generate.py @@ -67,6 +67,20 @@ def recorded(self): return self.found +# The FreeVideo process that started this request (the ComfyUI bridge sets it): the rest of its process tree is +# FreeVideo's own other work, which the GPU monitor counts apart from other programs. +HOST_PID_ENV = 'FREEVIDEO_HOST_PID' + + +def host_pid(env): + """The starting FreeVideo process from the request's environment, or None when it is not one of ours.""" + try: + value = int((env or {}).get(HOST_PID_ENV) or os.environ.get(HOST_PID_ENV) or 0) + except (TypeError, ValueError): + return None + return value if value > 0 and value != os.getpid() else None + + def child(command, env, descriptor, log, *, ram_budget_bytes=None, gpu=None, on_start=None, minimum_available_bytes=None, ram_budget_is_estimate=False): from .ram import ProcessMemory @@ -99,7 +113,7 @@ def child(command, env, descriptor, log, *, ram_budget_bytes=None, gpu=None, on_ on_start(process.pid) if gpu: from .monitoring import Monitor - monitor = Monitor(log.with_suffix('.gpu.csv'), device=gpu, pid=process.pid).start() + monitor = Monitor(log.with_suffix('.gpu.csv'), device=gpu, pid=process.pid, host=host_pid(env)).start() while process.poll() is None: if memory: sample = memory.sample(process.pid) diff --git a/freevideo_engine/gpu_pool.py b/freevideo_engine/gpu_pool.py index c9aff5b9..4da43c0f 100644 --- a/freevideo_engine/gpu_pool.py +++ b/freevideo_engine/gpu_pool.py @@ -49,10 +49,91 @@ def enumerate_devices(env=None): return devices +# A launch that pins CUDA_VISIBLE_DEVICES to the card setup checked (the environment package's host) names the +# value it set in OWN_PIN and keeps what the user had set, if anything, in USER_VISIBLE, with the user's +# CUDA_DEVICE_ORDER (the pin sets PCI_BUS_ID) in USER_ORDER: the order the user's indexes were written for. +OWN_PIN = 'FREEVIDEO_OWN_VISIBLE_DEVICES' +USER_VISIBLE = 'FREEVIDEO_USER_VISIBLE_DEVICES' +USER_ORDER = 'FREEVIDEO_USER_DEVICE_ORDER' + + +def pin_visible_device(environ, uuid): + """Show only `uuid` to this process and its children, in bus order, keeping the user's own + CUDA_VISIBLE_DEVICES and CUDA_DEVICE_ORDER for the pool. + + A second pin (another start attempt) keeps the user's values from the first. + """ + current = environ.get('CUDA_VISIBLE_DEVICES') + if environ.get(OWN_PIN) is None or current != environ.get(OWN_PIN): + for name, value in ((USER_VISIBLE, current), (USER_ORDER, environ.get('CUDA_DEVICE_ORDER'))): + if value is None: + environ.pop(name, None) + else: + environ[name] = value + environ['CUDA_VISIBLE_DEVICES'] = environ[OWN_PIN] = uuid + environ['CUDA_DEVICE_ORDER'] = 'PCI_BUS_ID' + + +def _pinned(env): + """Whether CUDA_VISIBLE_DEVICES is FreeVideo's own pin, not the user's value.""" + value = env.get('CUDA_VISIBLE_DEVICES') + return value is not None and env.get(OWN_PIN) is not None and value == env.get(OWN_PIN) + + +def requested_visibility(env): + """The CUDA_VISIBLE_DEVICES the user chose, None when it is not set (every device). + + FreeVideo's own pin stands for the value it replaced. + """ + return env.get(USER_VISIBLE) if _pinned(env) else env.get('CUDA_VISIBLE_DEVICES') + + +def requested_order(env): + """The CUDA_DEVICE_ORDER the user's CUDA_VISIBLE_DEVICES was written for (under FreeVideo's pin, the user's own).""" + return env.get(USER_ORDER) if _pinned(env) else env.get('CUDA_DEVICE_ORDER') + + +def visible_devices(devices, value, order=None): + """The listed devices CUDA shows for this CUDA_VISIBLE_DEVICES value, or None when that cannot be told. + + As CUDA reads it: entries are indexes, whole-GPU UUIDs or a unique prefix of one (with or without + "GPU-"); the list ends at the first entry that names no device, names one twice or is ambiguous, so an + empty value or -1 shows none. An index counts in CUDA's order: nvidia-smi's (PCI bus) order when + CUDA_DEVICE_ORDER is PCI_BUS_ID or when every device is the same model (the default fastest-first + order then keeps the bus order); otherwise, and for a MIG instance, the devices CUDA shows are not known. + """ + if value is None: + return list(devices) + by_bus = len({(d.name, d.capability) for d in devices}) <= 1 or (order or '').strip().upper() == 'PCI_BUS_ID' + chosen = [] + for entry in value.split(','): + entry = entry.strip() + if entry.upper().startswith('MIG-'): + return None + if entry.isdigit(): + if not by_bus: + return None + matches = [d for d in devices if d.index == int(entry)] + elif entry: + wanted = entry.lower() + matches = [d for d in devices if d.uuid.lower() == wanted] or [ + d for d in devices if any(d.uuid.lower().startswith(p) for p in (wanted, 'gpu-' + wanted))] + else: + matches = [] + if len(matches) != 1 or matches[0] in chosen: + break + chosen.append(matches[0]) + return [d for d in devices if d in chosen] + + def eligible_devices(env=None): - """Devices generation may use: FREEVIDEO_GPU_ALLOW lists indexes or UUIDs, absent means all.""" + """Devices generation may use: those CUDA_VISIBLE_DEVICES shows (all when it is not set), and of them those + FREEVIDEO_GPU_ALLOW lists by index or UUID (absent means all). None of them when the visible devices cannot be + told.""" env = os.environ if env is None else env - devices = enumerate_devices(env) + devices = visible_devices(enumerate_devices(env), requested_visibility(env), requested_order(env)) + if devices is None: + return [] # no pool: the single-device path runs on whatever CUDA shows this process allowed = {item.strip() for item in env.get('FREEVIDEO_GPU_ALLOW', '').split(',') if item.strip()} if not allowed: return devices diff --git a/freevideo_engine/image_gen/cast_views.py b/freevideo_engine/image_gen/cast_views.py index 9049edd8..359f0d66 100644 --- a/freevideo_engine/image_gen/cast_views.py +++ b/freevideo_engine/image_gen/cast_views.py @@ -34,8 +34,16 @@ 'back': ('将图1中的同一个人整个身体转过180度,完全背对镜头。' '头、肩膀、躯干、臀部和双脚一起转过去,后脑勺、发旋、颈后、背部、肩胛骨、臀部和脚后跟朝向镜头。' '头和身体方向一致。看不到脸、胸口、衣服前襟、前面的扣子或衣领开口,耳朵只露边缘。只展示衣服背面。'), - 'face': 'front-facing face close-up, framed from shoulders upward, centered head, eyes looking at the camera, neutral expression', + 'face': None, # its own prompt below: a close-up has no turn, no body and no clothes to keep } +# The face close-up: the head fills the picture. The old words ("framed from shoulders upward", with the turned views' +# "head, shoulders, torso and feet" and "clothing details") came back as a half-length picture, the face a quarter of the +# width; "the top of the head to just below the chin", edited from the same front picture, is a close-up. +FACE = ('Same person as image 1: the same face and hair. A tight close-up headshot of this person: the face fills most ' + 'of the frame, from the top of the head to just below the chin, the head centred and facing the camera, the eyes ' + 'looking at the camera, a neutral expression. Treat image 1 as the identity reference and preserve the facial ' + 'proportions, age, skin tone, hairline, hairstyle and %s. Plain light grey studio backdrop, even soft studio ' + 'light, sharp focus. One photograph of one person, no text, no collage.') _HAS_GLASSES = re.compile(r'\b(?:eye|sun)?glasses\b|眼镜|太阳镜', re.IGNORECASE) _NO_GLASSES = re.compile( @@ -83,13 +91,7 @@ def view_prompt(card, view): raise ValueError('unknown view') eyewear = _eyewear(card) if view == 'face': - return ('Same person as image 1: same face, hair, clothes and body; plain light grey studio backdrop; ' - '%s. Treat image 1 as the identity and wardrobe reference. Photograph this exact person ' - 'from the requested camera angle. The head, shoulders, torso and feet must all follow ' - 'that angle; do not keep a frontal head on a rotated body. Preserve the facial proportions, ' - 'age, hairline, hairstyle, %s, clothing details and accessories from image 1. Keep even ' - 'soft studio light. Show only one person in one photograph, no text, no collage.' - % (_VIEW_TEXT[view], eyewear)) + return FACE % eyewear if view == 'side': return (_VIEW_TEXT[view] + eyewear + '.保持同一张脸、发型、衣服和配件。全身站立,双脚入画,' '浅灰纯色背景,均匀柔光,只画一个人的一张照片。') diff --git a/freevideo_engine/image_gen/failure.py b/freevideo_engine/image_gen/failure.py index 00486847..32d52586 100644 --- a/freevideo_engine/image_gen/failure.py +++ b/freevideo_engine/image_gen/failure.py @@ -52,13 +52,13 @@ 'FreeVideo. If the check still does not pass, download the report and report the problem.', '显卡的计算检查未通过。请更新显卡驱动后重新启动 FreeVideo;如仍未通过,请下载报告并提交问题。'), '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_request': ('The image settings are invalid. Adjust them and try again.', '图片设置有误,请调整后重试。'), 'invalid_prompt': ('The prompt is empty, or longer than 2,000 characters once the image references are counted. Shorten it and try again.', diff --git a/freevideo_engine/image_gen/image_pack.py b/freevideo_engine/image_gen/image_pack.py index 74b61856..e77ecd2b 100644 --- a/freevideo_engine/image_gen/image_pack.py +++ b/freevideo_engine/image_gen/image_pack.py @@ -20,6 +20,7 @@ import re import signal import sys +import tempfile import threading import time import traceback @@ -29,7 +30,8 @@ from .. import disk_space, model_repair, network, provision from ..locking import runtime_lock from ..monitoring import save -from ..failure_details import Redactor, image_pack_busy_lock, image_pack_error_code, redacted_launcher_error +from ..failure_details import (Redactor, image_pack_busy_lock, image_pack_error_code, image_pack_write_details, + redacted_launcher_error) H3_TIERS = ('int8',) MOSS_GROUP = 'moss-image' @@ -65,6 +67,18 @@ def __init__(self, reason, **details): self.details = details +@contextmanager +def _step(name): + """Names the step a write failed in: an OSError raised inside keeps the innermost step (failure_details + image_pack_write_details reads it for the card and the report line).""" + try: + yield + except OSError as error: + if getattr(error, 'pack_step', None) is None: + error.pack_step = name + raise + + class _GenerationPause(Exception): """Unwind the transfer so curl is stopped before waiting for generation.""" @@ -675,7 +689,8 @@ def _lease(root, engine_root=None, destructive=False): if destructive: stack.enter_context(runtime_lock(engine / 'engine.lock', inherit=False)) stack.enter_context(runtime_lock(engine / 'launcher/host-setup.lock', inherit=False)) - stack.enter_context(runtime_lock(folder / 'pack.lock', inherit=False)) + with _step('folder'): + stack.enter_context(runtime_lock(folder / 'pack.lock', inherit=False)) break except BlockingIOError as error: stack.close() @@ -749,11 +764,13 @@ def checked(current, size): ledger.pop(str(path), None) if path.exists(): # A file shared with the video install is recorded too: repair may replace it only after this record. - model_repair.record(folder, path, row, before) + with _step('record'): + model_repair.record(folder, path, row, before) todo.append(row) done += row['bytes'] if json.dumps(ledger, sort_keys=True) != snapshot or not _path(folder, LEDGER).is_file(): - save(_path(folder, LEDGER), ledger) + with _step('record'): + save(_path(folder, LEDGER), ledger) return ledger, todo @@ -838,9 +855,64 @@ def resource_check(): reason = ('integrity_failed' if failures and failures[-1][0] in ('integrity-mismatch', 'response-size-exceeded') else 'write_failed' if failures and failures[-1][0] == 'curl-23' else 'offline' if offline else 'source_failed') + if reason == 'write_failed': + raise _download_write_failure(path, row['bytes'], error) raise PackError(reason) from error +WRITE_CHECK_PREFIX = '.freevideo-write-check-' + + +def _write_answer(partial): + """(answer, left): what the system answers when FreeVideo itself opens the download's partial file for writing + (or, without one, makes a new file beside it), None when it can; and the check's own file when it could be made + but not deleted again. That is no answer about the write: the write's reason stays, and the card names the file.""" + from ..long_paths import io_path + left = None + try: + if os.path.lexists(partial): + with open(io_path(partial), 'ab'): + pass + else: + io_path(partial.parent).mkdir(parents=True, exist_ok=True) + for old in io_path(partial.parent).glob(WRITE_CHECK_PREFIX + '*'): + try: + old.unlink() # an earlier check's file that could not be deleted then + except OSError: + pass + handle, name = tempfile.mkstemp(prefix=WRITE_CHECK_PREFIX, dir=io_path(partial.parent)) + os.close(handle) + try: + os.unlink(name) + except OSError: + left = name + except OSError as answer: + return answer, None + return None, left + + +def _download_write_failure(path, size, error): + """curl stopped because it could not write the download (exit 23), which names no cause. A full disk is said as + one; otherwise FreeVideo writes the same place itself, and what the system answers is the reason on the card. The + chain keeps curl's failure under that answer for the report.""" + partial = path.with_suffix(path.suffix + '.partial') + try: + have = partial.stat().st_size if partial.is_file() else 0 + free = disk_space.free_bytes(partial.parent) + except OSError: + have, free = 0, None + if free is not None and free < size - have: + failure = PackError('disk_space', needed_bytes=size - have, free_bytes=free) + failure.__cause__ = error + return failure + answer, left = _write_answer(partial) + failure = PackError('write_failed', step='download', path=str(partial), curl=23, **(dict(check_left=left) if left else {})) + if answer is not None: + answer.__cause__ = error + failure.__cause__ = answer or error + return failure + + def _swap_record(folder, path, approved=None): """Write (or, without approved, drop) the record of a swap that has begun at path.""" values = _read(folder, SWAPS) @@ -884,7 +956,7 @@ def _swap_in(folder, path, staged, approved, prior): try: _swap_record(folder, path, approved) except PermissionError as error: - raise PackError('write_failed') from error + raise PackError('write_failed', step='record', path=error.filename or str(_path(folder, SWAPS)), kept_new=True) from error try: kept = model_repair.retain(folder, path, approved) except BaseException as error: @@ -903,16 +975,19 @@ def _swap_in(folder, path, staged, approved, prior): except OSError: pass if isinstance(error, PermissionError): - raise PackError('write_failed') from error + raise PackError('write_failed', step='replace', path=error.filename or str(path), kept_new=True) from error raise try: model_repair.rename_noreplace(staged, path) - except BaseException: + except BaseException as error: try: model_repair.restore(folder, path, kept, approved, prior) _swap_record(folder, path) except (OSError, ValueError): pass + if isinstance(error, PermissionError): + # Windows: another program or security software holds the new file. The original went back above. + raise PackError('write_failed', step='replace', path=error.filename or str(staged), kept_new=True) from error raise try: _swap_record(folder, path) @@ -920,6 +995,35 @@ def _swap_in(folder, path, staged, approved, prior): pass +def _finish_swap(staged, path): + """The rename an earlier, interrupted swap left: the verified new file takes the empty place.""" + try: + model_repair.rename_noreplace(staged, path) + except PermissionError as error: + raise PackError('write_failed', step='replace', path=error.filename or str(staged)) from error + + +def _windows_retry(call, check): + """A swap Windows refused with a code the shared table tries again (windows_blocked: security software still + examining the file, another program holding it) is tried again after each of the table's waits. _swap_in leaves + the original in place and the verified new file beside it every time, so each try starts from the same state.""" + from .. import windows_blocked + for wait in (*windows_blocked.RETRY_WAITS, None): + try: + return call() + except PackError as error: + code = getattr(error.__cause__, 'winerror', None) + if wait is None or error.reason != 'write_failed' or code not in windows_blocked.RETRYABLE: + raise + deadline = time.monotonic() + wait + while True: + check() + left = deadline - time.monotonic() + if left <= 0: + break + time.sleep(min(left, .25)) + + def install(root=None, progress=None, check=None, *, engine_root=None, repair=False, _background=None, group='image', confirm=None): """Install only missing weights. Repair also hashes and retains bad originals. @@ -946,7 +1050,8 @@ def install(root=None, progress=None, check=None, *, engine_root=None, repair=Fa # is not left without its file. Only a swap that left its record is undone, and only in a # repair (which holds the engine lease); a plain install never renames the user's files. _put_back(folder, target(row, root)) - ledger, todo = _verify(folder, root, progress, check, full=repair, group=group) + with _step('check'): + ledger, todo = _verify(folder, root, progress, check, full=repair, group=group) total = sum(r['bytes'] for r in todo) reserve = BACKGROUND_RESERVE if _background is not None else RESERVE # Each disk a file lands on must hold what lands there: the shared encoder goes to the video encoder @@ -998,7 +1103,8 @@ def install(root=None, progress=None, check=None, *, engine_root=None, repair=Fa plan = _download_plan(engine_root) plan.update(quiet=True, resource_check=check) owned = _read(folder, OWNERSHIP) - _write_notice(folder, owned, group=group) + with _step('record'): + _write_notice(folder, owned, group=group) done = 0 pending_prefixes = 0 if _background is not None: @@ -1034,9 +1140,11 @@ def install(root=None, progress=None, check=None, *, engine_root=None, repair=Fa swap = (approved, model_repair.read(folder).get(str(path))) download_to = staged else: - model_repair.retain(folder, path, approved) + with _step('replace'): + model_repair.retain(folder, path, approved) owned.pop(row['file'], None) - save(_path(folder, OWNERSHIP), owned) + with _step('record'): + save(_path(folder, OWNERSHIP), owned) partial = _side(folder, row, root, '.partial') if _background is not None and partial.is_file(): pending_prefixes -= min(row['bytes'], partial.stat().st_size) @@ -1048,38 +1156,47 @@ def moved(current, size, speed, **kwargs): transfer_check() try: try: - _transfer(plan, row, download_to, moved, transfer_check, _background, progress) + with _step('download'): + _transfer(plan, row, download_to, moved, transfer_check, _background, progress) except ValueError as error: # download() refuses to overwrite a finished file that fails its check. A leftover .replacing # that does not hold the tested bytes is our own staging file: removed, then fetched again, once. if download_to is not staged or not str(error).startswith('Existing file failed integrity check'): raise - staged.unlink() - download_to = staged - _transfer(plan, row, download_to, moved, transfer_check, _background, progress) + with _step('download'): + staged.unlink() + download_to = staged + _transfer(plan, row, download_to, moved, transfer_check, _background, progress) if swap is not None: - _swap_in(folder, path, staged, *swap) + _windows_retry(lambda: _swap_in(folder, path, staged, *swap), check) elif download_to is staged: - model_repair.rename_noreplace(staged, path) - _swap_record(folder, path) # the swap an earlier run began is finished - except BaseException: + with _step('replace'): + _windows_retry(lambda: _finish_swap(staged, path), check) + with _step('record'): + _swap_record(folder, path) # the swap an earlier run began is finished + except BaseException as error: if replacing and staged is not None and not os.path.lexists(path): _put_back(folder, path) # this run could not bring the new file: the original stays the video's + if isinstance(error, PackError) and error.details.get('kept_new') and not ( + os.path.lexists(path) and staged is not None and staged.is_file()): + error.details['kept_new'] = False # the original did not come back: the card must not say it is there raise finally: # Completed files and cancellable prefixes have separate identities. - for artifact in (partial, affinity): - if not row.get('shared') and may_own[artifact] and _path(folder, artifact.relative_to(folder).as_posix(), kind='beside').is_file(): - _own(folder, owned, artifact) + with _step('record'): + for artifact in (partial, affinity): + if not row.get('shared') and may_own[artifact] and _path(folder, artifact.relative_to(folder).as_posix(), kind='beside').is_file(): + _own(folder, owned, artifact) if staged is not None: try: _swap_record(folder, path) # a record an interrupted swap left is moot once the path has its file except OSError: pass ledger[str(path)] = provision.file_identity(path, row) - save(_path(folder, LEDGER), ledger) - if not row.get('shared'): - _own(folder, owned, path, row) # the video's text encoder is never ours to remove + with _step('record'): + save(_path(folder, LEDGER), ledger) + if not row.get('shared'): + _own(folder, owned, path, row) # the video's text encoder is never ours to remove done += row['bytes'] progress(dict(phase='download', done=done + pending_prefixes, total=total)) check() @@ -1150,13 +1267,15 @@ def remove(root=None, check=None, *, engine_root=None, group='image'): if _linked(path) or not _owned_intact(path, stamp): plan['skipped'].append(entry['file']) continue - path.unlink() + with _step('remove'): + path.unlink() removed.append(entry['file']) released += entry['bytes'] owned.pop(entry['file'], None) ledger.pop(str(path), None) - save(_path(folder, OWNERSHIP), owned) - save(_path(folder, LEDGER), ledger) + with _step('record'): + save(_path(folder, OWNERSHIP), owned) + save(_path(folder, LEDGER), ledger) return dict(released_bytes=released, removed=removed, skipped=plan['skipped']) except BlockingIOError as error: raise PackError('busy') from error @@ -1343,6 +1462,13 @@ def _failed(self, action, error): for row in entries for s in row['sources']], events=events) details = {k: v for k, v in getattr(error, 'details', {}).items() if k in ('needed_bytes', 'free_bytes') and type(v) is int} + if code == 'write_failed': + # The step, the file (from the model folder or the encoder folder) and what the system answered. + try: + folders = (base(self.root).parent, shared_root(self.root)) + except Exception: + folders = () + details['write'] = image_pack_write_details(error, folders) busy_lock = image_pack_busy_lock(error) busy_lock = dict(busy_lock=busy_lock) if busy_lock else {} redactor = Redactor() diff --git a/freevideo_engine/image_gen/service.py b/freevideo_engine/image_gen/service.py index e0b39a15..a26cfdf0 100644 --- a/freevideo_engine/image_gen/service.py +++ b/freevideo_engine/image_gen/service.py @@ -519,10 +519,12 @@ def pack_checked(call, *args, **kwargs): try: return call(*args, **kwargs), None except image_pack.PackError as error: - from ..failure_details import image_pack_error_code, image_pack_failure + from ..failure_details import image_pack_error_code, image_pack_failure, image_pack_write_details code = image_pack_error_code(error) + write = image_pack_write_details(error) return None, dict(state='failed', done=0, total=0, bytes_per_second=0, reason=code, - message_en=image_pack_failure(code)['detail'], message_zh=image_pack_failure(code, zh=True)['detail']) + message_en=image_pack_failure(code, write=write)['detail'], + message_zh=image_pack_failure(code, zh=True, write=write)['detail']) def info(self): engine_root, machine = self.installation() @@ -706,8 +708,8 @@ def pack_row(installer, ready, problem=None): # What it waits for, in the page's own words: a video, a picture, or another task on the card. row['reason'] = value.get('reason') or 'busy_engine' if value['state'] == 'failed': - row.update(reason=value.get('reason'), message_en=image_pack_failure(value.get('reason'))['detail'], - message_zh=image_pack_failure(value.get('reason'), zh=True)['detail']) + row.update(reason=value.get('reason'), message_en=image_pack_failure(value.get('reason'), write=value.get('write'))['detail'], + message_zh=image_pack_failure(value.get('reason'), zh=True, write=value.get('write'))['detail']) if value.get('report_id'): row['report_id'] = value['report_id'] return row @@ -3111,10 +3113,11 @@ async def info(request): return web.json_response(dict(error='setup_required'), status=400) except image_pack.PackError as error: # Never an empty 500: the reason and the next step, in both languages. - from ..failure_details import image_pack_error_code, image_pack_failure + from ..failure_details import image_pack_error_code, image_pack_failure, image_pack_write_details code = image_pack_error_code(error) - return web.json_response(dict(error=code, message_en=image_pack_failure(code)['detail'], - message_zh=image_pack_failure(code, zh=True)['detail']), status=409) + write = image_pack_write_details(error) + return web.json_response(dict(error=code, message_en=image_pack_failure(code, write=write)['detail'], + message_zh=image_pack_failure(code, zh=True, write=write)['detail']), status=409) except Exception: # A damaged model folder or pack record must not turn into a plain-text 500 that blocks every later action. logging.getLogger(__name__).exception('image info failed') diff --git a/freevideo_engine/launcher/Main.qml b/freevideo_engine/launcher/Main.qml index 5f20e84d..922f8678 100644 --- a/freevideo_engine/launcher/Main.qml +++ b/freevideo_engine/launcher/Main.qml @@ -66,14 +66,34 @@ ApplicationWindow { function fill(text, values) { return values ? String(text).replace(/\{(\w+)\}/g, (whole, name) => Object.prototype.hasOwnProperty.call(values, name) ? String(values[name]) : whole) : text } + // A button's name quoted in a sentence ("Connect again", “重新连接”, 「重新連線」, «Подключить снова», „Erneut verbinden“) + // is never split over two lines: on screen only, its spaces become no-break spaces, and word joiners go between + // Chinese or Japanese characters (Korean, like the languages written with spaces, needs only the no-break spaces). + // The language files and anything copied keep the plain text. Only the quotation marks are read, in any language; a + // long quotation (a sentence, a path) is left as it is, so it can still wrap inside a narrow window. + function holdNames(text) { + const ideograph = c => { const n = c.codePointAt(0); return n >= 0x2e80 && n <= 0x9fff || n >= 0xf900 && n <= 0xfaff || n >= 0x20000 } + const hold = name => { + const chars = Array.from(name.replace(/ /g, "\u00a0")) + return chars.map((c, i) => i && (ideograph(c) || ideograph(chars[i - 1])) ? "\u2060" + c : c).join("") + } + return String(text ?? "").replace(/"([^"\n]{1,32})"|“([^“”\n]{1,32})”|「([^「」\n]{1,32})」|『([^『』\n]{1,32})』|«([^«»\n]{1,32})»|„([^„“”\n]{1,32})“/g, + function (whole, a, b, c, d, e, f) { + const name = a ?? b ?? c ?? d ?? e ?? f + return whole.slice(0, whole.length - name.length - 1) + hold(name) + whole.slice(-1) + }) + } function t(en, zh, values) { - if (uiLanguage === "zh-Hans") return fill(zh, values) - if (uiLanguage === "en") return fill(en, values) + return holdNames(translated(en, zh, values)) + } + function translated(english, chinese, values) { + if (uiLanguage === "zh-Hans") return fill(chinese, values) + if (uiLanguage === "en") return fill(english, values) const own = key => catalog && typeof catalog[key] === "string" ? catalog[key] : null // A file whose fallback is zh-Hans (Traditional Chinese) shows text it does not hold as the code's Simplified // Chinese in its own characters, not as English (web/i18n.js lookup). - const missing = () => catalog && catalog._meta && catalog._meta.fallback === "zh-Hans" ? fromSimplified(zh) : en - return fill(own(en + "\u241f" + zh) ?? own(en) ?? missing(), values) + const missing = () => catalog && catalog._meta && catalog._meta.fallback === "zh-Hans" ? fromSimplified(chinese) : english + return fill(own(english + "\u241f" + chinese) ?? own(english) ?? missing(), values) } // Simplified Chinese in the characters of the language file's _meta.chars (pairs of a Simplified character and the // one it becomes). The table follows the file (computed when it changes); reading it never writes a property, so the @@ -181,7 +201,9 @@ ApplicationWindow { function diskLabel() { return disk && !disk.problem && !disk.short ? t("Disk:", "所在硬盘:") : "" } // On a Mac, a disk problem is fixed by choosing another disk, not by reporting a fault. // Not a fault: a video is still generating, and the one way on is Retry installation. - function reportOpened(error, title) { return s.report_opened === error + "\u0001" + title } + // A report carries the plain text: the marks holdNames adds on screen never reach an issue form or its link. + function plainText(text) { return String(text ?? "").replace(/\u2060/g, "").replace(/\u00a0/g, " ") } + function reportOpened(error, title) { return s.report_opened === plainText(error) + "\u0001" + plainText(title) } readonly property bool notAFault: s.failure.kind === "setup-busy" || s.failure.kind === "update-busy" || s.failure.kind === "busy" readonly property bool diskFailure: !!disk && (s.failure.kind || "").indexOf("disk") === 0 readonly property bool updateOffered: s.update.engine || (!!s.update.candidate && ["available", "downloading", "ready", "error", "cancelled"].indexOf(s.update.status) >= 0) @@ -189,39 +211,52 @@ ApplicationWindow { // A card whose way out is the user's own step (open a newer launcher, move a file) marks itself manual: // retrying first cannot help, so it is not the primary action. readonly property bool manualFailure: !!s.retry_kind && s.failure.manual === true + readonly property bool updateStartRefused: s.failure.kind === "update-start-blocked" && ["threat", "policy", "smart-app-control"].indexOf(s.failure.reason) >= 0 readonly property bool updateFirst: s.page === "launcher" && s.update.engine && !s.update.phase && !s.busy && s.status !== "open" && s.status !== "restart-required" && !s.needs_consent && !s.repair_offered function percent(row) { return row && row.total ? Math.floor(100 * row.done / row.total) + "%" : "" } readonly property var upgrade: s.model_upgrade || ({}) + // On a GPU where FP8 is the faster arithmetic the move is offered for the Fast level only, and other levels get about 5% + // slower: the card never calls that model faster, and its button switches rather than upgrades. + readonly property bool upgradeForFast: upgrade.purpose === "fast-level" readonly property bool upgradeShown: !upgrade.dismissed && ["available", "low-disk", "downloading", "downloaded", "switching", "releasing", "releasable", "complete", "failed"].indexOf(upgrade.status) >= 0 function upgradeHeadline() { var u = upgrade - if (u.status === "available") return t("A faster model is available for your GPU", "有适合这张显卡的更快模型") - if (u.status === "low-disk") return t("Not enough disk space for the faster model", "磁盘空间不够,暂时无法升级到更快的模型") - if (u.status === "downloading") return t("Downloading the faster model", "正在下载更快的模型") + if (u.status === "available") return upgradeForFast ? t("The Fast level needs a different model", "极速档需要更换模型") + : t("A faster model is available for your GPU", "有适合这张显卡的更快模型") + if (u.status === "low-disk") return upgradeForFast ? t("Not enough disk space to switch models", "磁盘空间不够,暂时无法更换模型") + : t("Not enough disk space for the faster model", "磁盘空间不够,暂时无法升级到更快的模型") + if (u.status === "downloading") return upgradeForFast ? t("Downloading the new model", "正在下载新模型") : t("Downloading the faster model", "正在下载更快的模型") if (u.status === "downloaded" && u.waiting === "comfy") return t("Switching after FreeVideo is closed", "关闭 FreeVideo 后切换") - if (u.status === "downloaded" || (u.status === "switching" && !s.busy)) return t("Switching after the current video", "当前视频完成后切换") - if (u.status === "switching") return t("Switching to the faster model", "正在切换到更快的模型") + // "After the current video" only while a video is running; otherwise the switch starts now, and the card says what + // it says while switching. + if (u.status === "downloaded" && u.video_running) return t("Switching after the current video", "当前视频完成后切换") + if (u.status === "downloaded" || u.status === "switching") return upgradeForFast ? t("Switching models", "正在切换模型") + : t("Switching to the faster model", "正在切换到更快的模型") if (u.status === "releasing") return u.waiting ? t("Removing the old model after the current video", "当前视频完成后删除旧模型") : t("Removing the old model", "正在删除旧模型") if (u.status === "releasable") return u.in_use === "int8_convrot" ? t("The old model is still on disk", "旧模型还占着磁盘空间") : t("Some model files are not in use", "有没在使用的模型文件") if (u.status === "complete" && u.in_use) return u.in_use === "int8_convrot" ? t("The old model was removed", "旧模型已删除") : t("Unused model files were removed", "没在使用的模型文件已删除") - if (u.status === "complete") return t("Upgraded to the faster model", "已升级到更快的模型") - if (u.status === "failed") return u.step === "release" ? t("The old model was not removed", "旧模型没有删除") : t("The upgrade stopped", "升级未完成") + if (u.status === "complete") return upgradeForFast ? t("Switched to the new model", "已换用新模型") : t("Upgraded to the faster model", "已升级到更快的模型") + if (u.status === "failed") return u.step === "release" ? t("The old model was not removed", "旧模型没有删除") + : upgradeForFast ? t("The model switch stopped", "更换模型未完成") : t("The upgrade stopped", "升级未完成") return "" } function upgradeBlocker(code) { if (code === "prepared-folder-redirected") return t("The model folder is linked to another location, and FreeVideo never deletes through a link.", "模型文件夹被链接到了别的位置,FreeVideo 不会通过链接删除文件。") - if (code === "unexpected-active-variant") return t("The faster model is not in use, so the old model is kept.", "没有在用更快的模型,旧模型保留。") - if (code === "active-variant-incomplete") return t("The faster model's files are incomplete, so the old model is kept.", "更快的模型文件不完整,旧模型保留。") + if (code === "unexpected-active-variant") return upgradeForFast ? t("The new model is not in use, so the old model is kept.", "没有在用新模型,旧模型保留。") + : t("The faster model is not in use, so the old model is kept.", "没有在用更快的模型,旧模型保留。") + if (code === "active-variant-incomplete") return upgradeForFast ? t("The new model's files are incomplete, so the old model is kept.", "新模型文件不完整,旧模型保留。") + : t("The faster model's files are incomplete, so the old model is kept.", "更快的模型文件不完整,旧模型保留。") return t("The model in use is not a standard FreeVideo model, so nothing was deleted.", "当前使用的模型不是标准安装的模型,为安全起见没有删除任何文件。") } function upgradeCause(code, step) { if (code === "disk") return t("There is not enough free disk space for the model files. Free some space first.", "磁盘可用空间不足,放不下模型文件。请先腾出空间。") if (code === "network") return t("The model download lost its connection. Check the network first.", "模型下载时网络连接中断。请先检查网络。") - if (step === "switch") return t("The switch to the faster model did not finish.", "切换到更快的模型没有完成。") + if (step === "switch") return upgradeForFast ? t("The switch to the new model did not finish.", "切换到新模型未完成。") + : t("The switch to the faster model did not finish.", "切换到更快的模型未完成。") if (step === "release") return t("The old model could not be removed.", "旧模型未能删除。") - return t("The model download did not finish.", "模型下载没有完成。") + return t("The model download did not finish.", "模型下载未完成。") } function upgradeReportText() { // A failed upgrade reports the whole failure, including the step log, not only the first line shown on the card. @@ -232,6 +267,13 @@ ApplicationWindow { var lora = u.lora_variants && u.lora_variants.length var speed = u.architecture === "ampere" ? t("about twice as fast on this GPU", "在这张显卡上预计快约 2 倍") : t("about 10–30% faster on this GPU", "在这张显卡上预计快约 10–30%") + if (u.status === "available" && upgradeForFast) + return (u.resized ? t("Download size updated. ", "下载量已更新。") : "") + + t("With the model that supports Fast, you can use the Fast level; on this GPU, the other levels are about 5% slower. It downloads about {size}", + "换用支持极速档的模型后,就可以使用极速档;在这张显卡上,其他档位约慢 5%。需要下载约 {size}", {size: bytes(u.download_bytes)}) + + (lora ? t("; the old model stays so your LoRAs keep working, and no space is freed.", ";为了继续使用已有的 LoRA,旧模型会保留,空间不会释放。") + : t(", then removes the old model to free about {size}.", ",完成后删除旧模型,释放约 {size}。", {size: bytes(u.release_bytes)})) + + t(" You can keep generating while it downloads.", "下载期间可以继续生成。") if (u.status === "available") return (u.resized ? t("Download size updated. ", "下载量已更新。") : "") + t("The faster model is {speed} and closer to the original quality. It downloads {size}", "更快的模型{speed},画质也更接近原版。需要下载约 {size}", @@ -241,7 +283,7 @@ ApplicationWindow { + t(" You can keep generating while it downloads.", "下载期间可以继续生成。") if (u.status === "low-disk") return t("It needs about {required} free; {free} is free. Clean the download cache in Settings → Storage or free some space, then reopen FreeVideo.", - "需要约 {required} 可用空间,目前剩 {free}。可以在 设置 → 存储 清理下载缓存,或者腾出空间后重新打开 FreeVideo。", + "需要约 {required} 可用空间,当前仅剩 {free}。可在“设置 → 存储”中清理下载缓存,或释放空间后重新打开 FreeVideo。", {required: bytes(u.required_bytes), free: bytes(u.free_bytes)}) if (u.status === "downloading") return u.progress && u.progress.unit === "bytes" && u.progress.total ? t("{done} / {total} · you can keep generating", "{done} / {total} · 可以继续生成", {done: bytes(u.progress.done), total: bytes(u.progress.total)}) @@ -252,8 +294,10 @@ ApplicationWindow { if (u.status === "downloaded" || u.status === "switching") return t("Generation pauses for about 2 minutes during the switch; settings and videos are kept.", "切换期间暂停生成约 2 分钟,设置和视频会保留。") if (u.status === "releasable" && u.in_use === "int8_convrot") - return t("FreeVideo now uses the faster model. Removing the old model frees about {size}; only its own files are removed.", - "已在用更快的模型,删除旧模型可释放约 {size},只删除旧模型自己的文件。", {size: bytes(u.release_bytes)}) + return upgradeForFast ? t("FreeVideo now uses the new model. Removing the old model frees about {size}; only its own files are removed.", + "FreeVideo 已在使用新模型。删除旧模型可释放约 {size},只删除旧模型自己的文件。", {size: bytes(u.release_bytes)}) + : t("FreeVideo now uses the faster model. Removing the old model frees about {size}; only its own files are removed.", + "FreeVideo 已在使用更快的模型。删除旧模型可释放约 {size},只删除旧模型自己的文件。", {size: bytes(u.release_bytes)}) if (u.status === "releasable") return t("Removing unused model files frees about {size}; the model in use is not touched.", "删除未使用的模型文件可释放约 {size},正在使用的模型不受影响。", {size: bytes(u.release_bytes)}) @@ -263,8 +307,9 @@ ApplicationWindow { + (lora ? t(" The old model stays for your fused LoRAs.", "旧模型为需要合并的 LoRA 保留。") : "") if (u.status === "failed") return (u.blockers && u.blockers.length ? upgradeBlocker(u.blockers[0]) + t(" ", "") : upgradeCause(u.cause, u.step) + "\n") - + (u.step === "release" ? t("The faster model is in use; the old model files are kept for now.", "已在用更快的模型,旧模型文件暂时保留。") - : u.step === "switch" && !u.kept ? t("The previous model's files are all kept. Select \"Retry\" on the setup page to restore it.", "原来的模型文件都还在,在安装页点“重试”可恢复。") + + (u.step === "release" ? (upgradeForFast ? t("The new model is in use; the old model files are kept for now.", "FreeVideo 已在使用新模型,旧模型文件暂时保留。") + : t("The faster model is in use; the old model files are kept for now.", "FreeVideo 已在使用更快的模型,旧模型文件暂时保留。")) + : u.step === "switch" && !u.kept ? t("The previous model's files are all kept. Choose \"Retry\" on the setup page to restore it.", "原来的模型文件均已保留,可在安装页点“重试”恢复。") : t("Your previous model is unchanged and still works. Select \"Try again\", or report a problem.", "原来的模型没有变化,可以继续使用。可以点“重试”,或提交问题。")) return "" } @@ -556,9 +601,9 @@ ApplicationWindow { } ColumnLayout { id: failureBody; x: 18; y: 18; width: parent.width - 36; spacing: 10 - FText { text: s.failure.title || t("Couldn’t complete this step", "暂时未能完成"); color: theme.danger; font.weight: Font.DemiBold; Layout.fillWidth: true } - FText { visible: !!(s.failure.detail || s.failure.action); text: s.failure.detail || s.failure.action; color: theme.text; Layout.fillWidth: true } - FText { visible: !!s.failure.note; text: s.failure.note || ""; color: theme.muted; Layout.fillWidth: true } + FText { text: holdNames(s.failure.title) || t("Couldn’t complete this step", "暂时未能完成"); color: theme.danger; font.weight: Font.DemiBold; Layout.fillWidth: true } + FText { visible: !!(s.failure.detail || s.failure.action); text: holdNames(s.failure.detail || s.failure.action); color: theme.text; Layout.fillWidth: true } + FText { visible: !!s.failure.note; text: holdNames(s.failure.note); color: theme.muted; Layout.fillWidth: true } // What each download source returned: one short line per source. FText { objectName: "failureSources"; visible: !!s.failure.sources; text: sourceLines(s.failure.sources); color: theme.muted; font.pixelSize: theme.micro; Layout.fillWidth: true } TextEdit { @@ -584,10 +629,19 @@ ApplicationWindow { FButton { objectName: "repairCardButton"; primary: true; visible: !!s.repair_offered; text: t("Repair", "修复"); onClicked: backend.action("repair", false) } FButton { objectName: "openInstallFolder"; visible: s.failure.kind === "missing-file"; primary: true text: t("Open install folder", "打开安装目录"); onClicked: backend.openInstallFolder() } - FButton { objectName: "latestLauncherLink"; visible: s.failure.kind === "older-launcher"; flat: true + // A threat report, a policy or Smart App Control stops the same file again from that folder; a browser + // download shows the security software's own way to allow it, so the releases page leads there. + FButton { objectName: "latestLauncherPrimary"; visible: updateStartRefused; primary: true + text: t("Download the latest ↗", "下载最新版 ↗"); onClicked: backend.link("https://github.com/FlashML-org/FreeVideo/releases/latest") } + FButton { objectName: "openUpdateFolder"; visible: s.failure.kind === "update-start-blocked" && !!s.failure.path; primary: !updateStartRefused + text: t("Open download location", "打开下载位置"); onClicked: backend.openUpdateFolder() } + FButton { objectName: "latestLauncherLink"; visible: s.failure.kind === "older-launcher" || (s.failure.kind === "update-start-blocked" && !updateStartRefused); flat: true text: t("Download the latest ↗", "下载最新版 ↗"); onClicked: backend.link("https://github.com/FlashML-org/FreeVideo/releases/latest") } + // A missing Visual C++ runtime: Microsoft's page, not the installer file itself; the person can fix it, so no report. + FButton { objectName: "vcRuntimeLink"; visible: s.failure.kind === "vc-runtime" + text: t("Download runtime ↗", "下载运行库 ↗"); onClicked: backend.link("https://learn.microsoft.com/cpp/windows/latest-supported-vc-redist") } FButton { objectName: "exportError"; visible: !diskFailure && !notAFault; text: t("Export report", "导出报告"); enabled: s.report.status !== "running"; onClicked: backend.exportReport() } - FButton { objectName: "reportProblem"; visible: !diskFailure && !notAFault && s.failure.kind !== "port-taken" && s.failure.kind !== "comfy-restart" && s.failure.kind !== "comfy-folder" && s.failure.kind !== "engine-folder-denied"; text: reportOpened(s.error, s.failure.title || "") ? t("Opened", "已打开") : t("Report a problem", "提交问题"); widthText: t("Report a problem", "提交问题"); enabled: !reportOpened(s.error, s.failure.title || ""); onClicked: backend.reportProblem(s.error, s.failure.title || "") } + FButton { objectName: "reportProblem"; visible: !diskFailure && !notAFault && s.failure.kind !== "port-taken" && s.failure.kind !== "comfy-restart" && s.failure.kind !== "comfy-folder" && s.failure.kind !== "engine-folder-denied" && s.failure.kind !== "folder-name-invalid" && s.failure.kind !== "vc-runtime" && s.failure.kind !== "python-file-blocked"; text: reportOpened(s.error, s.failure.title || "") ? t("Opened", "已打开") : t("Report a problem", "提交问题"); widthText: t("Report a problem", "提交问题"); enabled: !reportOpened(s.error, s.failure.title || ""); onClicked: backend.reportProblem(plainText(s.error), plainText(s.failure.title || "")) } } FButton { objectName: "showError"; visible: !notAFault; text: t("Technical details", "技术详情"); flat: true @@ -663,6 +717,7 @@ ApplicationWindow { FToolTip { objectName: "installationPathTooltip"; text: parent.text; delay: 500; visible: parent.hovered && parent.text.length > 0 && !win.dialogShown } } FButton { objectName: "installationBrowse"; text: t("Browse…", "浏览…"); enabled: s.can_manage; implicitHeight: theme.height + 4; onClicked: backend.browse(s.form.new_comfy ? "destination" : "comfy") } } + FText { objectName: "installationPathError"; visible: s.field_error.key === "destination"; text: visible ? s.field_error.message : ""; color: theme.danger; font.pixelSize: theme.micro; Layout.fillWidth: true; wrapMode: Text.WordWrap } FText { visible: !s.form.new_comfy; text: t("Uses your existing Python when available. A separate environment loads only FreeVideo.", "优先使用已有 Python;独立环境仅加载 FreeVideo。"); color: theme.muted; font.pixelSize: theme.micro; Layout.fillWidth: true } RowLayout { objectName: "installDisk"; visible: !!disk; Layout.fillWidth: true; spacing: 8 @@ -1011,7 +1066,7 @@ ApplicationWindow { FText { visible: !s.update.phase && !!text; text: releaseSummary(availableRelease); Layout.fillWidth: true; color: theme.muted; font.pixelSize: theme.micro } FButton { text: t("What's new", "更新内容"); flat: true; visible: !s.update.phase && !!availableRelease; implicitHeight: theme.heightSm; onClicked: releaseNotesOpen = true } FButton { objectName: "updateBannerManualDownload"; text: t("Download from the release page ↗", "去发布页手动下载 ↗"); flat: true; visible: s.update.status === "error" && !!s.update.release_page; implicitHeight: theme.heightSm; onClicked: backend.link(s.update.release_page) } - FButton { objectName: "updateBannerReport"; text: reportOpened(s.update.error, t("Update", "更新")) ? t("Opened", "已打开") : t("Report a problem", "提交问题"); widthText: t("Report a problem", "提交问题"); enabled: !reportOpened(s.update.error, t("Update", "更新")); flat: true; visible: s.update.status === "error" && !!s.update.error; implicitHeight: theme.heightSm; onClicked: backend.reportProblem(s.update.error, t("Update", "更新")) } + FButton { objectName: "updateBannerReport"; text: reportOpened(s.update.error, t("Update", "更新")) ? t("Opened", "已打开") : t("Report a problem", "提交问题"); widthText: t("Report a problem", "提交问题"); enabled: !reportOpened(s.update.error, t("Update", "更新")); flat: true; visible: s.update.status === "error" && !!s.update.error; implicitHeight: theme.heightSm; onClicked: backend.reportProblem(plainText(s.update.error), plainText(t("Update", "更新"))) } } FCard { objectName: "modelUpgradeCard" @@ -1019,26 +1074,42 @@ ApplicationWindow { reveal: true; Layout.fillWidth: true; padding: 18; spacing: 10 color: upgrade.status === "failed" || upgrade.status === "low-disk" ? theme.surface : theme.accentSubtle border.color: upgrade.status === "failed" || upgrade.status === "low-disk" ? theme.border : theme.accentDim - RowLayout { - Layout.fillWidth: true; spacing: 14 - FIcon { kind: upgrade.status === "releasable" ? "folder" : "download"; ink: upgrade.status === "failed" ? theme.muted : theme.accent; Layout.preferredWidth: 22; Layout.preferredHeight: 22 } + GridLayout { + // A narrow window puts the buttons under the words, so the words keep the card's width. + Layout.fillWidth: true; columnSpacing: 14; rowSpacing: 10; columns: win.narrow ? 2 : 3 + FIcon { Layout.row: 0; Layout.column: 0; kind: upgrade.status === "releasable" ? "folder" : "download"; ink: upgrade.status === "failed" ? theme.muted : theme.accent; Layout.preferredWidth: 22; Layout.preferredHeight: 22 } ColumnLayout { - Layout.fillWidth: true; spacing: 2 + Layout.row: 0; Layout.column: 1; Layout.fillWidth: true; spacing: 2 FText { objectName: "modelUpgradeHeadline"; text: upgradeHeadline(); font.weight: Font.DemiBold; Layout.fillWidth: true } FText { objectName: "modelUpgradeText"; visible: text !== ""; text: upgradeExplanation(); color: theme.muted; font.pixelSize: theme.micro; Layout.fillWidth: true; wrapMode: Text.WordWrap } } + Flow { + // Under the words in a narrow window, wrapping inside the card's width (three buttons in a failed + // state do not fit one line at 400 px); beside them, one line as wide as the visible buttons. + objectName: "modelUpgradeActions"; spacing: 14 + readonly property real contentWidth: { + var width = 0, shown = 0 + for (var i = 0; i < children.length; i++) + if (children[i].visible) { width += children[i].implicitWidth; shown++ } + return width + Math.max(0, shown - 1) * spacing + } + Layout.row: win.narrow ? 1 : 0; Layout.column: win.narrow ? 1 : 2 + Layout.fillWidth: win.narrow; Layout.preferredWidth: win.narrow ? 0 : contentWidth + Layout.preferredHeight: implicitHeight; Layout.alignment: win.narrow ? Qt.AlignLeft : Qt.AlignVCenter FButton { objectName: "modelUpgradeLater"; visible: ["available", "low-disk", "releasable", "complete", "failed"].indexOf(upgrade.status) >= 0; flat: true text: upgrade.status === "complete" || upgrade.status === "low-disk" ? t("Close", "关闭") : t("Later", "稍后"); onClicked: backend.dismissModelUpgrade() } FButton { objectName: "modelUpgradeStop"; visible: upgrade.status === "downloading"; flat: true; text: t("Stop download", "停止下载"); onClicked: backend.cancelModelUpgrade() } - FButton { objectName: "modelUpgradeReport"; visible: upgrade.status === "failed"; flat: true; text: reportOpened(upgradeReportText(), t("Model upgrade", "模型升级")) ? t("Opened", "已打开") : t("Report a problem", "提交问题"); widthText: t("Report a problem", "提交问题"); enabled: !reportOpened(upgradeReportText(), t("Model upgrade", "模型升级")); onClicked: backend.reportProblem(upgradeReportText(), t("Model upgrade", "模型升级")) } + FButton { objectName: "modelUpgradeReport"; visible: upgrade.status === "failed"; flat: true; text: reportOpened(upgradeReportText(), t("Model upgrade", "模型升级")) ? t("Opened", "已打开") : t("Report a problem", "提交问题"); widthText: t("Report a problem", "提交问题"); enabled: !reportOpened(upgradeReportText(), t("Model upgrade", "模型升级")); onClicked: backend.reportProblem(plainText(upgradeReportText()), plainText(t("Model upgrade", "模型升级"))) } FButton { objectName: "modelUpgradeButton"; primary: true visible: upgrade.status === "available" || upgrade.status === "releasable" || (upgrade.status === "failed" && (upgrade.step === "download" || upgrade.step === "release" || (upgrade.step === "switch" && upgrade.kept))) enabled: s.can_manage && !upgrade.busy - text: upgrade.status === "failed" ? t("Try again", "重试") : upgrade.status === "releasable" ? t("Remove…", "删除…") : t("Download & upgrade", "下载并升级") + text: upgrade.status === "failed" ? t("Try again", "重试") : upgrade.status === "releasable" ? t("Remove…", "删除…") + : upgradeForFast ? t("Switch model", "更换模型") : t("Download & upgrade", "下载并升级") onClicked: upgrade.status === "releasable" ? releaseConfirm = true : backend.upgradeModel() } + } } FMeter { // Waiting for the user to close ComfyUI is not progress. @@ -1069,7 +1140,7 @@ ApplicationWindow { Layout.fillWidth: true; spacing: 6 // A failed start stays failed while another task (an import, a cleanup) runs: the controller's own tasks clear it first. FText { objectName: "statusTitle"; text: s.status === "open" ? t("FreeVideo is ready", "FreeVideo 已就绪") : s.status === "failed" ? t("Startup interrupted", "启动未完成") : s.busy ? t("Starting FreeVideo", "正在启动 FreeVideo") : s.status === "restart-required" && s.engine_exit_text ? t("FreeVideo stopped", "FreeVideo 已停止") : s.status === "restart-required" ? t("Restart FreeVideo", "请重启 FreeVideo") : t("Ready to launch", "准备就绪"); font.pixelSize: theme.section + 2; font.weight: Font.DemiBold; Layout.fillWidth: true } - FText { objectName: "statusDetail"; text: s.status === "open" ? s.url : s.status === "restart-required" && s.engine_exit_text ? s.engine_exit_text : s.status === "restart-required" ? t("Restart FreeVideo after the update, then select \"Connect again\".", "更新后需重启 FreeVideo,再点“重新连接”。") : s.status === "failed" ? t("FreeVideo did not start. See the message above.", "FreeVideo 未能启动,原因见上方。") : t("Your models and environment are connected.", "已连接模型与运行环境。"); color: theme.muted; Layout.fillWidth: true } + FText { objectName: "statusDetail"; text: s.status === "open" ? s.url : s.status === "restart-required" && s.engine_exit_text ? holdNames(s.engine_exit_text) : s.status === "restart-required" ? t("Restart FreeVideo after the update, then choose \"Connect again\".", "更新后需重启 FreeVideo,再点“重新连接”。") : s.status === "failed" ? t("FreeVideo did not start. See the message above.", "FreeVideo 未能启动,原因见上方。") : t("Your models and environment are connected.", "已连接模型与运行环境。"); color: theme.muted; Layout.fillWidth: true } FText { objectName: "portMovedNote"; visible: s.status === "open" && s.port_from > 0; text: t("Port %1 is in use by another program, so FreeVideo now uses port %2 and will keep using this address.", "端口 %1 已被其他程序占用,FreeVideo 改用端口 %2,以后也使用这个地址。").arg(s.port_from).arg(s.port_to); font.pixelSize: 13; color: theme.muted; wrapMode: Text.WordWrap; Layout.fillWidth: true; Layout.topMargin: -2 } FText { objectName: "pluginScopedNote"; visible: s.status === "open" && s.plugin_scoped; text: t("Some installed plugins are not compatible with FreeVideo, so only FreeVideo was loaded this time.", "部分已装的插件与 FreeVideo 不兼容,这次只载入了 FreeVideo。"); font.pixelSize: 13; color: theme.muted; wrapMode: Text.WordWrap; Layout.fillWidth: true; Layout.topMargin: -2 } } @@ -1162,12 +1233,12 @@ ApplicationWindow { } FText { objectName: "imagePackEngineNote"; wrapMode: Text.WordWrap; visible: s.image_pack.engine_state === "running"; text: s.image_pack.engine_note; color: s.image_pack.engine_clicked ? theme.danger : theme.muted; Layout.fillWidth: true } FText { objectName: "imagePackFailureReason"; visible: s.image_pack.install.state === "failed"; text: s.image_pack.detail; color: theme.danger; Layout.fillWidth: true } - FButton { objectName: "imagePackReport"; visible: s.image_pack.install.state === "failed"; text: reportOpened((s.image_pack.detail || "") + (s.image_pack.report_line ? "\n" + s.image_pack.report_line : ""), t("Image pack", "图像模型包")) ? t("Opened", "已打开") : t("Report a problem", "提交问题"); widthText: t("Report a problem", "提交问题"); enabled: !reportOpened((s.image_pack.detail || "") + (s.image_pack.report_line ? "\n" + s.image_pack.report_line : ""), t("Image pack", "图像模型包")); onClicked: backend.reportProblem((s.image_pack.detail || "") + (s.image_pack.report_line ? "\n" + s.image_pack.report_line : ""), t("Image pack", "图像模型包")) } Flow { visible: s.image_pack.install.state === "failed" && !!s.image_pack.report_id Layout.fillWidth: true; spacing: 8 FButton { objectName: "imagePackExport"; text: t("Export report", "导出报告"); enabled: s.report.status !== "running"; onClicked: backend.exportReport() } } + FButton { objectName: "imagePackReport"; visible: s.image_pack.install.state === "failed" && s.image_pack.report_offered !== false; text: reportOpened((s.image_pack.detail || "") + (s.image_pack.report_line ? "\n" + s.image_pack.report_line : ""), t("Image pack", "图像模型包")) ? t("Opened", "已打开") : t("Report a problem", "提交问题"); widthText: t("Report a problem", "提交问题"); enabled: !reportOpened((s.image_pack.detail || "") + (s.image_pack.report_line ? "\n" + s.image_pack.report_line : ""), t("Image pack", "图像模型包")); onClicked: backend.reportProblem(plainText((s.image_pack.detail || "") + (s.image_pack.report_line ? "\n" + s.image_pack.report_line : "")), plainText(t("Image pack", "图像模型包"))) } FMeter { objectName: "imagePackProgress"; visible: s.image_pack.busy; Layout.fillWidth: true; active: visible fraction: s.image_pack.install.total > 0 ? s.image_pack.install.done / s.image_pack.install.total : -1 @@ -1180,7 +1251,7 @@ ApplicationWindow { Layout.fillWidth: true; padding: 22; spacing: 10 FText { objectName: "promptModelText"; Layout.fillWidth: true; wrapMode: Text.WordWrap - text: win.promptModelLine() + text: holdNames(win.promptModelLine()) } FMeter { objectName: "promptModelProgress"; visible: s.prompt_model.busy; Layout.fillWidth: true; active: visible @@ -1189,10 +1260,13 @@ ApplicationWindow { Flow { visible: !s.prompt_model.checking; Layout.fillWidth: true; spacing: 8 FButton { objectName: "promptModelDownload"; visible: !s.prompt_model.busy && !s.prompt_model.checking - text: s.prompt_model.suggest ? t("Download", "下载") : t("Resume", "继续"); enabled: !s.busy; onClicked: backend.promptModelAction("install") } + // A download that stopped or failed carries on from where it was (the image pack row says it the same way); the + // sentence above names this key, so the two always agree. + text: s.prompt_model.install.state === "failed" || s.prompt_model.downloaded_bytes > 0 ? t("Resume", "继续") : t("Download", "下载") + enabled: !s.busy; onClicked: backend.promptModelAction("install") } FButton { objectName: "promptModelPause"; visible: s.prompt_model.busy; text: t("Pause", "暂停"); onClicked: backend.promptModelAction("cancel") } FButton { objectName: "promptModelDismiss"; visible: s.prompt_model.suggest; text: t("Don't ask again", "不再提示"); flat: true; onClicked: backend.dismissPromptHint() } - FButton { objectName: "promptModelReport"; visible: s.prompt_model.install.state === "failed"; text: reportOpened(win.promptModelLine(), t("Prompt model", "提示词模型")) ? t("Opened", "已打开") : t("Report a problem", "提交问题"); widthText: t("Report a problem", "提交问题"); enabled: !reportOpened(win.promptModelLine(), t("Prompt model", "提示词模型")); flat: true; onClicked: backend.reportProblem(win.promptModelLine(), t("Prompt model", "提示词模型")) } + FButton { objectName: "promptModelReport"; visible: s.prompt_model.install.state === "failed"; text: reportOpened(win.promptModelLine(), t("Prompt model", "提示词模型")) ? t("Opened", "已打开") : t("Report a problem", "提交问题"); widthText: t("Report a problem", "提交问题"); enabled: !reportOpened(win.promptModelLine(), t("Prompt model", "提示词模型")); flat: true; onClicked: backend.reportProblem(plainText(win.promptModelLine()), plainText(t("Prompt model", "提示词模型"))) } } } } @@ -1583,7 +1657,10 @@ ApplicationWindow { FText { text: t("Video model", "视频模型"); Layout.fillWidth: true } FText { objectName: "modelStorageStatus"; Layout.fillWidth: true; font.pixelSize: theme.micro; color: theme.muted; wrapMode: Text.WordWrap - text: upgrade.status === "available" ? (upgrade.release_bytes + text: upgrade.status === "available" && upgradeForFast + ? t("A model that supports the Fast level: about {size} to download; on this GPU, the other levels are about 5% slower with it.", + "支持极速档的模型:下载约 {size};在这张显卡上,换用后其他档位约慢 5%。", {size: bytes(upgrade.download_bytes)}) + : upgrade.status === "available" ? (upgrade.release_bytes ? t("A faster model is available: about {size} to download, about {freed} freed afterwards.", "有更快的模型:下载约 {size},完成后删除旧模型,释放约 {freed}。", {size: bytes(upgrade.download_bytes), freed: bytes(upgrade.release_bytes)}) : t("A faster model is available: about {size} to download.", "有更快的模型:下载约 {size}。", {size: bytes(upgrade.download_bytes)})) @@ -1595,7 +1672,7 @@ ApplicationWindow { } FButton { objectName: "modelStorageButton"; visible: upgrade.status === "available" || upgrade.status === "releasable" - text: upgrade.status === "releasable" ? t("Remove…", "删除…") : t("Upgrade", "升级") + text: upgrade.status === "releasable" ? t("Remove…", "删除…") : upgradeForFast ? t("Switch model", "更换模型") : t("Upgrade", "升级") implicitHeight: theme.heightSm; font.pixelSize: theme.micro + 1 enabled: s.can_manage && !upgrade.busy onClicked: upgrade.status === "releasable" ? releaseConfirm = true : backend.upgradeModel() @@ -1631,6 +1708,7 @@ ApplicationWindow { Layout.fillWidth: true; title: t("Folders · optional", "目录 · 可选"); enabled: !s.portable FText { text: t("Engine folder", "引擎目录"); font.pixelSize: theme.micro; color: theme.muted } RowLayout { Layout.fillWidth: true; spacing: 8; FField { Layout.fillWidth: true; value: s.form.engine; placeholderText: t("Automatic", "自动选择"); onEditingFinished: backend.edit("engine", text) } FButton { objectName: "engineBrowse"; text: t("Browse…", "浏览…"); enabled: s.can_manage; implicitHeight: theme.height + 4; onClicked: backend.browse("engine") } } + FText { objectName: "engineError"; visible: s.field_error.key === "engine"; text: visible ? s.field_error.message : ""; color: theme.danger; font.pixelSize: theme.micro; Layout.fillWidth: true; wrapMode: Text.WordWrap } FText { text: t("Python environment", "Python 环境"); font.pixelSize: theme.micro; color: theme.muted; Layout.topMargin: 4 } FField { Layout.fillWidth: true; value: s.form.python; placeholderText: Qt.platform.os === "windows" ? t("Path to python.exe", "python.exe 的路径") : t("Path to python", "python 的路径"); onEditingFinished: backend.edit("python", text) } } @@ -1657,7 +1735,7 @@ ApplicationWindow { visible: !!s.error; Layout.fillWidth: true; implicitHeight: settingsError.implicitHeight + 28; radius: theme.radiusMd; color: theme.dangerSubtle; border.color: theme.dangerLine ColumnLayout { id: settingsError; x: 14; y: 14; width: parent.width - 28; spacing: 8 - FText { text: s.failure.title + "\n" + (s.failure.action || s.failure.detail); color: theme.danger; font.pixelSize: theme.micro + 1; Layout.fillWidth: true } + FText { text: holdNames(s.failure.title + "\n" + (s.failure.action || s.failure.detail)); color: theme.danger; font.pixelSize: theme.micro + 1; Layout.fillWidth: true } FText { objectName: "settingsFailureSources"; visible: !!s.failure.sources; text: sourceLines(s.failure.sources); color: theme.muted; font.pixelSize: theme.micro; Layout.fillWidth: true } TextEdit { objectName: "settingsFailurePath"; visible: !!s.failure.path; text: s.failure.path || ""; font.family: backend.fontFamily @@ -1669,7 +1747,7 @@ ApplicationWindow { Layout.fillWidth: true; spacing: 8 FButton { text: t("Copy details", "复制详情"); implicitHeight: theme.heightSm; font.pixelSize: theme.micro + 1; onClicked: backend.copy(s.error) } FButton { text: t("Export report", "导出报告"); implicitHeight: theme.heightSm; font.pixelSize: theme.micro + 1; enabled: s.report.status !== "running"; onClicked: backend.exportReport() } - FButton { objectName: "settingsReportProblem"; visible: s.failure.kind !== "comfy-folder" && s.failure.kind !== "engine-folder-denied"; text: reportOpened(s.error, s.failure.title || "") ? t("Opened", "已打开") : t("Report a problem", "提交问题"); widthText: t("Report a problem", "提交问题"); enabled: !reportOpened(s.error, s.failure.title || ""); implicitHeight: theme.heightSm; font.pixelSize: theme.micro + 1; onClicked: backend.reportProblem(s.error, s.failure.title || "") } + FButton { objectName: "settingsReportProblem"; visible: s.failure.kind !== "comfy-folder" && s.failure.kind !== "engine-folder-denied" && s.failure.kind !== "folder-name-invalid" && s.failure.kind !== "vc-runtime" && s.failure.kind !== "python-file-blocked"; text: reportOpened(s.error, s.failure.title || "") ? t("Opened", "已打开") : t("Report a problem", "提交问题"); widthText: t("Report a problem", "提交问题"); enabled: !reportOpened(s.error, s.failure.title || ""); implicitHeight: theme.heightSm; font.pixelSize: theme.micro + 1; onClicked: backend.reportProblem(plainText(s.error), plainText(s.failure.title || "")) } } FText { visible: s.report.status !== "idle"; Layout.fillWidth: true; font.pixelSize: theme.micro; color: theme.muted @@ -1970,7 +2048,7 @@ ApplicationWindow { objectName: "updateFailureActions"; Layout.fillWidth: true; spacing: 8 visible: s.update.status === "error" && (!!s.update.release_page || !!s.update.error) FButton { objectName: "updateManualDownloadButton"; text: t("Download from the release page ↗", "去发布页手动下载 ↗"); flat: true; visible: s.update.status === "error" && !!s.update.release_page; onClicked: backend.link(s.update.release_page) } - FButton { objectName: "updateDialogReport"; text: reportOpened(s.update.error, t("Update", "更新")) ? t("Opened", "已打开") : t("Report a problem", "提交问题"); widthText: t("Report a problem", "提交问题"); enabled: !reportOpened(s.update.error, t("Update", "更新")); flat: true; visible: s.update.status === "error" && !!s.update.error; onClicked: backend.reportProblem(s.update.error, t("Update", "更新")) } + FButton { objectName: "updateDialogReport"; text: reportOpened(s.update.error, t("Update", "更新")) ? t("Opened", "已打开") : t("Report a problem", "提交问题"); widthText: t("Report a problem", "提交问题"); enabled: !reportOpened(s.update.error, t("Update", "更新")); flat: true; visible: s.update.status === "error" && !!s.update.error; onClicked: backend.reportProblem(plainText(s.update.error), plainText(t("Update", "更新"))) } } FMeter { Layout.fillWidth: true; visible: s.update.status === "downloading"; active: true; fraction: s.update.progress && s.update.progress.total ? s.update.progress.done/s.update.progress.total : -1 } FReleaseNotes { t: win.t; objectName: "updateReleaseNotes"; visible: !!availableRelease; Layout.fillWidth: true; room: updateDialog.availableWidth; release: availableRelease; earlier: availableEarlier; zh: !!s.notes_zh; heading: releaseVersion(availableRelease) } diff --git a/freevideo_engine/launcher_copy.py b/freevideo_engine/launcher_copy.py index 700e3a63..8dc08883 100644 --- a/freevideo_engine/launcher_copy.py +++ b/freevideo_engine/launcher_copy.py @@ -73,7 +73,7 @@ # The parallel phase also downloads the models (internal names stay as they are). ('Install components in parallel', '安装组件和模型'), ('Install with space saver', '安装组件和模型(极限省空间)'), - ('Download the faster model', '下载更快的模型'), ('Model downloaded', '模型已下载'), + ('Download the new model', '下载新模型'), ('Model downloaded', '模型已下载'), ('Model download incomplete', '模型下载未完成'), ('Release installation cache', '释放安装缓存'), ('Install acceleration and download models', '安装加速组件和下载模型'), diff --git a/freevideo_engine/launcher_session.py b/freevideo_engine/launcher_session.py index 4d534c5c..06246ceb 100644 --- a/freevideo_engine/launcher_session.py +++ b/freevideo_engine/launcher_session.py @@ -14,7 +14,7 @@ from urllib.parse import parse_qsl, urlencode, urlsplit, urlunsplit from . import __version__ -from . import disk_space +from . import disk_space, windows_names from .comfy_launcher_runtime import (ENGINE_UPDATE_WAITS, SETUP_WAITS_FOR_JOB, Controller, layout, local_url, loopback_url, managed_frontend, new_layout, queue_busy, queue_state) from .desktop_runtime import launcher_root, materialize_source @@ -148,6 +148,8 @@ class Session: update_intent = None update_source = 'launcher' update_waiting = update_restarting = False + # Windows refused to start the downloaded launcher: how many times so far, when to try again, and the file. + update_start_failures, update_start_retry_at, update_blocked_path = 0, 0., '' engine_updating = engine_autoinstall = reload_expected = resume_pages = False browser_wait = queue_state = queue_thread = bridge = None # Setup that stopped for a running job and continues by itself once the queue is empty. @@ -314,6 +316,30 @@ def t(self, en, zh, values=None): from .i18n import tr return tr(en, zh, self.ui_language(), values) + def folder_name_problem(self, found): + """The line under a folder field for a name Windows refuses; the texts match windows_names.message, which + a test compares, and are written out here so the language files collect them.""" + kind, number, character = found + if kind == 'reserved': + return self.t('Folder name {number} in the path is a name Windows reserves for devices (such as CON, NUL or COM1). ' + 'Rename it or choose another folder.', + '路径中的第 {number} 个文件夹名是 Windows 为设备保留的名称(例如 CON、NUL、COM1)。请修改该名称,或另选一个文件夹。', + {'number': number}) + if kind == 'ending': + return self.t('Folder name {number} in the path ends with a space or a dot, which Windows does not allow. ' + 'Rename it or choose another folder.', + '路径中的第 {number} 个文件夹名以空格或句点结尾,Windows 不允许这样的名称。请修改该名称,或另选一个文件夹。', + {'number': number}) + if character: + return self.t('Folder name {number} in the path contains "{character}", which Windows does not allow. ' + 'Rename it or choose another folder.', + '路径中的第 {number} 个文件夹名含有 Windows 不允许出现在文件夹名中的“{character}”。请修改该名称,或另选一个文件夹。', + {'number': number, 'character': character}) + return self.t('Folder name {number} in the path contains a control character, which Windows does not allow. ' + 'Rename it or choose another folder.', + '路径中的第 {number} 个文件夹名含有 Windows 不允许出现在文件夹名中的控制字符。请修改该名称,或另选一个文件夹。', + {'number': number}) + def chinese(self): """Whether text written as an (English, Chinese) pair shows its Chinese: the interface is Simplified Chinese. Other languages read their file through t(); functions that only take zh= give them English for now.""" @@ -425,6 +451,10 @@ def edit(self, key, value): if self.controller.busy or self.importer.busy or self.cleaner.busy or self.archives_busy: self.explain_busy() return + if key in ('destination', 'engine') and isinstance(value, str) and value.strip(): + found = windows_names.refused(value) + if found: + raise ValueError(self.folder_name_problem(found)) if key in ('separate', 'repair', 'new_comfy', 'sampling_caches', 'lan_access', 'image_model', 'prompt_model', 'prompt_hint_dismissed'): value = bool(value) if key == 'url': @@ -912,6 +942,9 @@ def action(self, name, accepted=False, *, retry=None): if self.form['new_comfy'] and self.form['environment_method'] == 'manual' and not self.form['offline_runtime']: raise ValueError(self.t('Import the Environment ZIP, or choose Automatic installation.', '请导入运行环境包,或选择「自动安装」。')) + # A rejected entry never reaches the form, so the text still shown must not continue into the old location. + if self.form['new_comfy'] and self.field_error.get('key') == 'destination': + raise ValueError(self.field_error.get('message') or self.t('Choose a valid installation folder first.', '请先选择有效的安装位置。')) new_layout(self.form['destination']) if self.form['new_comfy'] else layout(self.form['comfy']) self.persist(); self.page = 'models'; return self.browser_attempted = False @@ -1100,7 +1133,7 @@ def image_disk_fits(self, total): def image_pack_view(self, model='image'): from .image_gen import image_pack - from .failure_details import image_pack_failure + from .failure_details import image_pack_failure, image_pack_write_known group = self.h3_group() if model == 'h3-image' else 'image' title = ('MiniMax H3 Image', 'MiniMax H3 Image') if model == 'h3-image' else NAMES['image'] try: @@ -1111,7 +1144,7 @@ def image_pack_view(self, model='image'): return dict(installable=False, ready=False, state='missing', visible=False, busy=False, downloaded_bytes=0, verified_bytes=0, total_bytes=total, bytes=total, title=self.t(*title), detail=self.t('Not installed', '未安装'), - install={}, can_act=False, removable_bytes=0, repairable=False, failure={}, report_id=None, report_line='', + install={}, can_act=False, removable_bytes=0, repairable=False, failure={}, report_id=None, report_line='', report_offered=True, engine_state='unknown', engine_note='', engine_clicked=False) root, engine = self._image_location() try: @@ -1160,7 +1193,7 @@ def image_pack_view(self, model='image'): elif active.get('state') == 'cancelled': detail = self.t('Paused', '已暂停') elif active.get('state') == 'failed': - failure = self.both(lambda zh: image_pack_failure(active.get('reason'), zh=zh)) + failure = self.both(lambda zh: image_pack_failure(active.get('reason'), zh=zh, write=active.get('write'))) detail = failure['detail'] repairable = repairable or active.get('reason') in ('needs_repair', 'integrity_failed') blocked = (self.controller.busy or self.importer.busy or self.cleaner.busy or self.archives_busy @@ -1174,6 +1207,8 @@ def image_pack_view(self, model='image'): detail=detail, busy=busy, install=active, can_act=not (blocked or busy or value.get('checking')), removable_bytes=removable, repairable=repairable, failure=failure, report_id=active.get('report_id'), + # A write that failed for a known reason has its own next step: the export stays, "Report a problem" goes. + report_offered=not (active.get('reason') == 'write_failed' and image_pack_write_known(active.get('write'))), report_line=self._image_pack_report_line(), engine_state=engine_state, engine_note=self.both(lambda zh: image_pack_failure('busy_engine', zh=zh))['detail'] if running else '', @@ -1186,6 +1221,11 @@ def _image_pack_report_line(self): return '' error = report.get('error') or {} parts = [str(report.get('stage_at_failure') or ''), str(error.get('code') or ''), str(error.get('class') or '')] + # A write that failed: its step and the codes the system gave (no file: the card above names it). + write = (error.get('details') or {}).get('write') or {} + parts += [str(write.get('step') or '')] + [('curl %d' % write['curl']) if type(write.get('curl')) is int else '', + str(write.get('errno') or ''), + ('WinError %d' % write['winerror']) if type(write.get('winerror')) is int else ''] return 'Image pack: ' + ', '.join(part for part in parts if part) def image_pack_report(self): @@ -1278,7 +1318,7 @@ def prompt_model_view(self): 'verify_failed': self.t('The download stopped: a downloaded file did not pass the check. Resume to download it again.', '下载中断:下载的文件没有通过校验。请点击“继续”重新下载。'), 'busy': self.t('Another download of this model is running.', '这个模型正在被另一处下载。')}.get( - active.get('reason'), self.t('The download stopped. Resume to continue; if it stops again, export the report and use "Report a problem".', + active.get('reason'), self.t('The download stopped. Choose "Resume" to continue; if it stops again, export the report and choose "Report a problem".', '下载中断。请点击“继续”;如再次中断,请导出报告,再点击“提交问题”并附上报告。')) return dict(ready=ready, checking=checking, total_bytes=total, enough_disk=enough, busy=busy, install=active, failure=failure, downloaded_bytes=active.get('done', 0), title=self.t(*NAMES['text']), @@ -1862,7 +1902,10 @@ def _restart_when_idle(self): self.update_waiting = bool(busy) if busy is not False: return - from .launcher_update import DownloadedLauncherUnavailable, handoff, launch_download + from .launcher_update import (DownloadedLauncherUnavailable, LauncherStartBlocked, START_RETRY_WAITS, handoff, + launch_download) + if time.monotonic() < self.update_start_retry_at: + return # Security software may still be examining the new file: tick tries again after the wait. self.persist() try: handoff(row['candidate'], self.updater.root, self.update_source, @@ -1872,9 +1915,20 @@ def _restart_when_idle(self): self.error = '' self.updater.run('download', row['candidate']) return + except LauncherStartBlocked as error: + if error.retryable and self.update_start_failures < len(START_RETRY_WAITS): + self.update_start_retry_at = time.monotonic() + START_RETRY_WAITS[self.update_start_failures] + self.update_start_failures += 1 + self.update_intent = 'launcher' # tick comes back here once the wait is over + return + self.update_start_failures, self.update_start_retry_at = 0, 0. + self.update_blocked_path = str(error.path) + self.update_intent = None + raise except Exception: self.update_intent = None raise + self.update_start_failures, self.update_start_retry_at, self.update_blocked_path = 0, 0., '' self.update_restarting = True self._write_bridge_status(force=True) self.closing = True @@ -2939,6 +2993,9 @@ def snapshot(self): if line.startswith(MISMATCH_PATH + ': ') and line[len(MISMATCH_PATH) + 2:]: failure['path'] = line[len(MISMATCH_PATH) + 2:] break + if failure.get('kind') == 'update-start-blocked' and self.update_blocked_path: + # The card names the folder the user can start the new launcher from; copied details stay redacted. + failure['path'] = str(Path(self.update_blocked_path).parent) if failure.get('kind') in ('permission', 'engine-folder-denied') and row.get('error') and row.get('denied'): from .denied_access import card_text # The card shows the detail instead of the action, so the action goes under the location. @@ -2969,7 +3026,8 @@ def snapshot(self): cleanup['error'] = self.both(lambda zh: display_launcher_error(cleanup['error'], zh=zh)) elif cleanup.get('status') == 'error': cleanup['message'] = self.t(*CLEANUP_FAILURES.get(cleanup.get('reason'), CLEANUP_FAILURES['failed'])) - model_upgrade = dict(self.upgrade.state, busy=self.upgrade.busy) + # A video running now (the last queue reading of our ComfyUI): the switch waits for it, and the page says so only then. + model_upgrade = dict(self.upgrade.state, busy=self.upgrade.busy, video_running=self.queue_state is True) if alias_failure(model_upgrade.get('error', '')): model_upgrade['error'] = self.both(lambda zh: display_launcher_error(model_upgrade['error'], zh=zh)) archive_offer = (self.archives_deleting_offer if self.archives_busy else diff --git a/freevideo_engine/launcher_update.py b/freevideo_engine/launcher_update.py index 40773ca4..998e1101 100644 --- a/freevideo_engine/launcher_update.py +++ b/freevideo_engine/launcher_update.py @@ -26,7 +26,7 @@ from .top_level_modules import load from .monitoring import save from .long_paths import io_path, resolved, plain, plain_errors -from . import disk_space, network +from . import disk_space, network, windows_blocked from .launcher_settings import default_language from .system import windows @@ -831,6 +831,26 @@ class DownloadedLauncherUnavailable(ValueError): """The cached executable needs downloading again before it can be started.""" +# What Windows answers when the downloaded launcher may not start (windows_blocked.json, shared with setup). 5 (access +# denied) and 32 (in use) are often security software still examining the new file, so the launcher tries again after +# these waits (seconds); the others are a decision on this computer that waiting does not change. +START_BLOCKED = windows_blocked.REASONS +START_RETRY_WAITS = windows_blocked.RETRY_WAITS +# The marker failure_details reads: the reason in brackets, then the downloaded file (local only; reports redact it). +START_BLOCKED_MARKER = 'UPDATE_START_BLOCKED' + + +class LauncherStartBlocked(RuntimeError): + """Windows did not let the downloaded launcher start; the running launcher keeps working.""" + + def __init__(self, code, path): + self.code, self.path = code, Path(path) + self.reason = START_BLOCKED[code] + self.retryable = code in windows_blocked.RETRYABLE + super().__init__('The downloaded launcher could not start [%s %s] (Windows error %d): %s' + % (START_BLOCKED_MARKER, self.reason, code, path)) + + @plain_errors def launch_download(candidate, root, *, token='', popen=None): candidate = manifest(candidate) @@ -860,7 +880,12 @@ def launch_download(candidate, root, *, token='', popen=None): kwargs['creationflags'] = subprocess.DETACHED_PROCESS | subprocess.CREATE_NEW_PROCESS_GROUP else: kwargs['start_new_session'] = True - process = (popen or execution_paths.popen)([str(path)], **kwargs) + try: + process = (popen or execution_paths.popen)([str(path)], **kwargs) + except OSError as error: + if windows() and getattr(error, 'winerror', None) in START_BLOCKED: + raise LauncherStartBlocked(error.winerror, path) from error + raise # Start first: a spawn error must not replace the approved startup receipt. save(Path(root) / 'updates' / 'active.json', dict(approved=True, candidate=candidate)) return process @@ -881,8 +906,8 @@ def forward_approved(current, root): return False # A bad release identity must never recursively launch itself. launch_download(candidate, root) return True - except (OSError, ValueError, TypeError, AttributeError): - return False # A missing/corrupt cached update leaves the original app usable. + except (OSError, ValueError, TypeError, AttributeError, LauncherStartBlocked): + return False # A missing/corrupt or blocked cached update leaves the original app usable. def handoff(candidate, root, source, *, pages=False): diff --git a/freevideo_engine/licenses/Noto-Sans-Arabic-OFL.txt b/freevideo_engine/licenses/Noto-Sans-Arabic-OFL.txt new file mode 100644 index 00000000..d4e17055 --- /dev/null +++ b/freevideo_engine/licenses/Noto-Sans-Arabic-OFL.txt @@ -0,0 +1,93 @@ +Copyright 2022 The Noto Project Authors (https://github.com/notofonts/arabic) + +This Font Software is licensed under the SIL Open Font License, Version 1.1. +This license is copied below, and is also available with a FAQ at: +https://openfontlicense.org + + +----------------------------------------------------------- +SIL OPEN FONT LICENSE Version 1.1 - 26 February 2007 +----------------------------------------------------------- + +PREAMBLE +The goals of the Open Font License (OFL) are to stimulate worldwide +development of collaborative font projects, to support the font creation +efforts of academic and linguistic communities, and to provide a free and +open framework in which fonts may be shared and improved in partnership +with others. + +The OFL allows the licensed fonts to be used, studied, modified and +redistributed freely as long as they are not sold by themselves. The +fonts, including any derivative works, can be bundled, embedded, +redistributed and/or sold with any software provided that any reserved +names are not used by derivative works. The fonts and derivatives, +however, cannot be released under any other type of license. The +requirement for fonts to remain under this license does not apply +to any document created using the fonts or their derivatives. + +DEFINITIONS +"Font Software" refers to the set of files released by the Copyright +Holder(s) under this license and clearly marked as such. This may +include source files, build scripts and documentation. + +"Reserved Font Name" refers to any names specified as such after the +copyright statement(s). + +"Original Version" refers to the collection of Font Software components as +distributed by the Copyright Holder(s). + +"Modified Version" refers to any derivative made by adding to, deleting, +or substituting -- in part or in whole -- any of the components of the +Original Version, by changing formats or by porting the Font Software to a +new environment. + +"Author" refers to any designer, engineer, programmer, technical +writer or other person who contributed to the Font Software. + +PERMISSION & CONDITIONS +Permission is hereby granted, free of charge, to any person obtaining +a copy of the Font Software, to use, study, copy, merge, embed, modify, +redistribute, and sell modified and unmodified copies of the Font +Software, subject to the following conditions: + +1) Neither the Font Software nor any of its individual components, +in Original or Modified Versions, may be sold by itself. + +2) Original or Modified Versions of the Font Software may be bundled, +redistributed and/or sold with any software, provided that each copy +contains the above copyright notice and this license. These can be +included either as stand-alone text files, human-readable headers or +in the appropriate machine-readable metadata fields within text or +binary files as long as those fields can be easily viewed by the user. + +3) No Modified Version of the Font Software may use the Reserved Font +Name(s) unless explicit written permission is granted by the corresponding +Copyright Holder. This restriction only applies to the primary font name as +presented to the users. + +4) The name(s) of the Copyright Holder(s) or the Author(s) of the Font +Software shall not be used to promote, endorse or advertise any +Modified Version, except to acknowledge the contribution(s) of the +Copyright Holder(s) and the Author(s) or with their explicit written +permission. + +5) The Font Software, modified or unmodified, in part or in whole, +must be distributed entirely under this license, and must not be +distributed under any other license. The requirement for fonts to +remain under this license does not apply to any document created +using the Font Software. + +TERMINATION +This license becomes null and void if any of the above conditions are +not met. + +DISCLAIMER +THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT +OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL THE +COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, +INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL +DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING +FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM +OTHER DEALINGS IN THE FONT SOFTWARE. diff --git a/freevideo_engine/licenses/Noto-Sans-Devanagari-OFL.txt b/freevideo_engine/licenses/Noto-Sans-Devanagari-OFL.txt new file mode 100644 index 00000000..cd2cc5c9 --- /dev/null +++ b/freevideo_engine/licenses/Noto-Sans-Devanagari-OFL.txt @@ -0,0 +1,93 @@ +Copyright 2022 The Noto Project Authors (https://github.com/notofonts/devanagari) + +This Font Software is licensed under the SIL Open Font License, Version 1.1. +This license is copied below, and is also available with a FAQ at: +https://scripts.sil.org/OFL + + +----------------------------------------------------------- +SIL OPEN FONT LICENSE Version 1.1 - 26 February 2007 +----------------------------------------------------------- + +PREAMBLE +The goals of the Open Font License (OFL) are to stimulate worldwide +development of collaborative font projects, to support the font creation +efforts of academic and linguistic communities, and to provide a free and +open framework in which fonts may be shared and improved in partnership +with others. + +The OFL allows the licensed fonts to be used, studied, modified and +redistributed freely as long as they are not sold by themselves. The +fonts, including any derivative works, can be bundled, embedded, +redistributed and/or sold with any software provided that any reserved +names are not used by derivative works. The fonts and derivatives, +however, cannot be released under any other type of license. The +requirement for fonts to remain under this license does not apply +to any document created using the fonts or their derivatives. + +DEFINITIONS +"Font Software" refers to the set of files released by the Copyright +Holder(s) under this license and clearly marked as such. This may +include source files, build scripts and documentation. + +"Reserved Font Name" refers to any names specified as such after the +copyright statement(s). + +"Original Version" refers to the collection of Font Software components as +distributed by the Copyright Holder(s). + +"Modified Version" refers to any derivative made by adding to, deleting, +or substituting -- in part or in whole -- any of the components of the +Original Version, by changing formats or by porting the Font Software to a +new environment. + +"Author" refers to any designer, engineer, programmer, technical +writer or other person who contributed to the Font Software. + +PERMISSION & CONDITIONS +Permission is hereby granted, free of charge, to any person obtaining +a copy of the Font Software, to use, study, copy, merge, embed, modify, +redistribute, and sell modified and unmodified copies of the Font +Software, subject to the following conditions: + +1) Neither the Font Software nor any of its individual components, +in Original or Modified Versions, may be sold by itself. + +2) Original or Modified Versions of the Font Software may be bundled, +redistributed and/or sold with any software, provided that each copy +contains the above copyright notice and this license. These can be +included either as stand-alone text files, human-readable headers or +in the appropriate machine-readable metadata fields within text or +binary files as long as those fields can be easily viewed by the user. + +3) No Modified Version of the Font Software may use the Reserved Font +Name(s) unless explicit written permission is granted by the corresponding +Copyright Holder. This restriction only applies to the primary font name as +presented to the users. + +4) The name(s) of the Copyright Holder(s) or the Author(s) of the Font +Software shall not be used to promote, endorse or advertise any +Modified Version, except to acknowledge the contribution(s) of the +Copyright Holder(s) and the Author(s) or with their explicit written +permission. + +5) The Font Software, modified or unmodified, in part or in whole, +must be distributed entirely under this license, and must not be +distributed under any other license. The requirement for fonts to +remain under this license does not apply to any document created +using the Font Software. + +TERMINATION +This license becomes null and void if any of the above conditions are +not met. + +DISCLAIMER +THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT +OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL THE +COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, +INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL +DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING +FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM +OTHER DEALINGS IN THE FONT SOFTWARE. diff --git a/freevideo_engine/licenses/Noto-Sans-OFL.txt b/freevideo_engine/licenses/Noto-Sans-OFL.txt new file mode 100644 index 00000000..6843f318 --- /dev/null +++ b/freevideo_engine/licenses/Noto-Sans-OFL.txt @@ -0,0 +1,93 @@ +Copyright 2022 The Noto Project Authors (https://github.com/notofonts/latin-greek-cyrillic) + +This Font Software is licensed under the SIL Open Font License, Version 1.1. +This license is copied below, and is also available with a FAQ at: +https://scripts.sil.org/OFL + + +----------------------------------------------------------- +SIL OPEN FONT LICENSE Version 1.1 - 26 February 2007 +----------------------------------------------------------- + +PREAMBLE +The goals of the Open Font License (OFL) are to stimulate worldwide +development of collaborative font projects, to support the font creation +efforts of academic and linguistic communities, and to provide a free and +open framework in which fonts may be shared and improved in partnership +with others. + +The OFL allows the licensed fonts to be used, studied, modified and +redistributed freely as long as they are not sold by themselves. The +fonts, including any derivative works, can be bundled, embedded, +redistributed and/or sold with any software provided that any reserved +names are not used by derivative works. The fonts and derivatives, +however, cannot be released under any other type of license. The +requirement for fonts to remain under this license does not apply +to any document created using the fonts or their derivatives. + +DEFINITIONS +"Font Software" refers to the set of files released by the Copyright +Holder(s) under this license and clearly marked as such. This may +include source files, build scripts and documentation. + +"Reserved Font Name" refers to any names specified as such after the +copyright statement(s). + +"Original Version" refers to the collection of Font Software components as +distributed by the Copyright Holder(s). + +"Modified Version" refers to any derivative made by adding to, deleting, +or substituting -- in part or in whole -- any of the components of the +Original Version, by changing formats or by porting the Font Software to a +new environment. + +"Author" refers to any designer, engineer, programmer, technical +writer or other person who contributed to the Font Software. + +PERMISSION & CONDITIONS +Permission is hereby granted, free of charge, to any person obtaining +a copy of the Font Software, to use, study, copy, merge, embed, modify, +redistribute, and sell modified and unmodified copies of the Font +Software, subject to the following conditions: + +1) Neither the Font Software nor any of its individual components, +in Original or Modified Versions, may be sold by itself. + +2) Original or Modified Versions of the Font Software may be bundled, +redistributed and/or sold with any software, provided that each copy +contains the above copyright notice and this license. These can be +included either as stand-alone text files, human-readable headers or +in the appropriate machine-readable metadata fields within text or +binary files as long as those fields can be easily viewed by the user. + +3) No Modified Version of the Font Software may use the Reserved Font +Name(s) unless explicit written permission is granted by the corresponding +Copyright Holder. This restriction only applies to the primary font name as +presented to the users. + +4) The name(s) of the Copyright Holder(s) or the Author(s) of the Font +Software shall not be used to promote, endorse or advertise any +Modified Version, except to acknowledge the contribution(s) of the +Copyright Holder(s) and the Author(s) or with their explicit written +permission. + +5) The Font Software, modified or unmodified, in part or in whole, +must be distributed entirely under this license, and must not be +distributed under any other license. The requirement for fonts to +remain under this license does not apply to any document created +using the Font Software. + +TERMINATION +This license becomes null and void if any of the above conditions are +not met. + +DISCLAIMER +THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT +OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL THE +COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, +INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL +DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING +FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM +OTHER DEALINGS IN THE FONT SOFTWARE. diff --git a/freevideo_engine/licenses/Noto-Sans-Thai-OFL.txt b/freevideo_engine/licenses/Noto-Sans-Thai-OFL.txt new file mode 100644 index 00000000..7fa8dcb0 --- /dev/null +++ b/freevideo_engine/licenses/Noto-Sans-Thai-OFL.txt @@ -0,0 +1,93 @@ +Copyright 2022 The Noto Project Authors (https://github.com/notofonts/thai) + +This Font Software is licensed under the SIL Open Font License, Version 1.1. +This license is copied below, and is also available with a FAQ at: +https://scripts.sil.org/OFL + + +----------------------------------------------------------- +SIL OPEN FONT LICENSE Version 1.1 - 26 February 2007 +----------------------------------------------------------- + +PREAMBLE +The goals of the Open Font License (OFL) are to stimulate worldwide +development of collaborative font projects, to support the font creation +efforts of academic and linguistic communities, and to provide a free and +open framework in which fonts may be shared and improved in partnership +with others. + +The OFL allows the licensed fonts to be used, studied, modified and +redistributed freely as long as they are not sold by themselves. The +fonts, including any derivative works, can be bundled, embedded, +redistributed and/or sold with any software provided that any reserved +names are not used by derivative works. The fonts and derivatives, +however, cannot be released under any other type of license. The +requirement for fonts to remain under this license does not apply +to any document created using the fonts or their derivatives. + +DEFINITIONS +"Font Software" refers to the set of files released by the Copyright +Holder(s) under this license and clearly marked as such. This may +include source files, build scripts and documentation. + +"Reserved Font Name" refers to any names specified as such after the +copyright statement(s). + +"Original Version" refers to the collection of Font Software components as +distributed by the Copyright Holder(s). + +"Modified Version" refers to any derivative made by adding to, deleting, +or substituting -- in part or in whole -- any of the components of the +Original Version, by changing formats or by porting the Font Software to a +new environment. + +"Author" refers to any designer, engineer, programmer, technical +writer or other person who contributed to the Font Software. + +PERMISSION & CONDITIONS +Permission is hereby granted, free of charge, to any person obtaining +a copy of the Font Software, to use, study, copy, merge, embed, modify, +redistribute, and sell modified and unmodified copies of the Font +Software, subject to the following conditions: + +1) Neither the Font Software nor any of its individual components, +in Original or Modified Versions, may be sold by itself. + +2) Original or Modified Versions of the Font Software may be bundled, +redistributed and/or sold with any software, provided that each copy +contains the above copyright notice and this license. These can be +included either as stand-alone text files, human-readable headers or +in the appropriate machine-readable metadata fields within text or +binary files as long as those fields can be easily viewed by the user. + +3) No Modified Version of the Font Software may use the Reserved Font +Name(s) unless explicit written permission is granted by the corresponding +Copyright Holder. This restriction only applies to the primary font name as +presented to the users. + +4) The name(s) of the Copyright Holder(s) or the Author(s) of the Font +Software shall not be used to promote, endorse or advertise any +Modified Version, except to acknowledge the contribution(s) of the +Copyright Holder(s) and the Author(s) or with their explicit written +permission. + +5) The Font Software, modified or unmodified, in part or in whole, +must be distributed entirely under this license, and must not be +distributed under any other license. The requirement for fonts to +remain under this license does not apply to any document created +using the Font Software. + +TERMINATION +This license becomes null and void if any of the above conditions are +not met. + +DISCLAIMER +THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT +OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL THE +COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, +INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL +DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING +FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM +OTHER DEALINGS IN THE FONT SOFTWARE. diff --git a/freevideo_engine/long_paths.py b/freevideo_engine/long_paths.py index 1d2def42..0060505c 100644 --- a/freevideo_engine/long_paths.py +++ b/freevideo_engine/long_paths.py @@ -251,18 +251,39 @@ def path_chars(path): # A file URL comes first, with its own guard (a word or a URL's slash before "file" stops it, so # "uri:file:///..." counts and "https://host/file:x" stays a URL): its slashes are a path, which the # guard below would otherwise leave as a URL's. + # An absolute path may follow a colon with no space ("Error:C:\Users\...", "error:/home/..."): a URL's + # "://" never starts one, as a slash before a slash or right after one is no path, and after a colon + # a single slash starts one only before a letter or "_" ("fe80::/10" stays). r'''(?\./setup\.sh(?![\w/\\-]|\.\w))|\.{1,2}/[^"'<>;\r\n,\)\]}]*|''' - r'''(?:(?:[A-Za-z]:[\\/])|(?:\\\\[^\\/\s"'<>]+[\\/])|/(?![/\s]))[^"'<>;\r\n,\)\]}]*)''') - -# A path that ends at a user's own folder: its last component is the user name, so none is kept. -HOME_FOLDER = re.compile(r'(?i)^(?:[A-Za-z]:)?[\\/]+(?:users|home|documents and settings)[\\/]+[^\\/]+$') + r'''(?\./setup\.sh(?![\w/\\-]|\.\w))|\.{1,2}/[^"'<>;\r\n,\)\]}]*)|''' + r'''(?]+[\\/])|(?;\r\n,\)\]}]*''') + +# Folders whose folders are users' own, at any depth (C:\Users, /home, /var/home, /mnt/c/Users, +# /System/Volumes/Data/Users, roaming profile and home shares). +USER_FOLDER_PARENTS = frozenset(('users', 'home', 'homes', 'documents and settings', 'profiles', 'profiles$', + 'users$', 'home$', 'homes$')) +# \\server\share\name: the folder right under a share is often a user's own (a roaming profile, a +# redirected or home folder), and so is a share itself (\\nas\bob, \\server\bob$). The \\?\ and +# \\?\UNC\ prefixes count as their plain spelling. +_SHARE_FOLDER = re.compile(r'^[\\/]{2}[^\\/]+[\\/]+[^\\/]+(?:[\\/]+[^\\/]+)?$') +_EXTENDED = re.compile(r'(?i)^[\\/]{2}[?.][\\/](?:unc[\\/])?') + + +def ends_at_user_folder(value): + """Whether a path's last part is (or may be) a user's own folder, whose name is the user's.""" + text = str(value).rstrip('\\/') + unc = re.match(r'(?i)^[\\/]{2}[?.][\\/]unc[\\/]', text) + # A function, not a replacement string: there "\\\\" would come out as one backslash. + text = _EXTENDED.sub(lambda found: '\\\\' if unc else '', text) + parts = re.split(r'[\\/]+', text) + return (len(parts) >= 2 and parts[-2].lower() in USER_FOLDER_PARENTS) or bool(_SHARE_FOLDER.match(text)) def path_placeholder(value): """``/`` and the last component: no usernames, drives, shares or parent directories.""" normalized = str(value).rstrip('\\/') - if HOME_FOLDER.match(normalized): + if ends_at_user_folder(normalized): return '' name = re.split(r'[\\/]', normalized)[-1] return '/' + name if name else '' diff --git a/freevideo_engine/macos_compute.py b/freevideo_engine/macos_compute.py index 1e2758a1..c9ad973e 100644 --- a/freevideo_engine/macos_compute.py +++ b/freevideo_engine/macos_compute.py @@ -107,6 +107,15 @@ def sequence_tokens(canvas, prompt_rows): return dict(rows, total=sum(rows.values())) +def fast_budget(budget_bytes, fast_mode): + """The bytes a sampling stage may plan with: in the fastest mode the adapter's whole BF16 matrices of blocks + 46-49 (policy.FAST2_PINNED_BYTES) stay in unified memory beside the stage, so they are not the plan's to use.""" + if fast_mode != 'fast2': + return budget_bytes + from .policy import FAST2_PINNED_BYTES + return max(1, int(budget_bytes) - FAST2_PINNED_BYTES) + + def plan(budget_bytes, tokens, *, frames=72, reserve_bytes=GiB, layers=50, allow_retention=True, allow_bounded=False, force_bounded=False): """Head group, row chunks and retained-layer bytes for one sampling stage.""" @@ -155,7 +164,7 @@ def generated_audio_tokens(frames): def request_admission(resource, sampling, *, preview=False, working_set_bytes=None, reference_tokens=0, - text_tokens=None, continuation=None): + text_tokens=None, continuation=None, fast_mode=None): """Before any model loads: does this request's largest sampling pass fit? Each sampling stage plans against the request's allocator capacity, live @@ -193,6 +202,19 @@ def request_admission(resource, sampling, *, preview=False, working_set_bytes=No tokens, frames = (shape['video_tokens'] + conditioning_tokens + reference_tokens + continuation_tokens, shape['latent_frames']) needed = bounded_working_bytes(tokens, frames=frames) + GiB + LAYER_BYTES + PREFETCH_BYTES + decode = None + if fast_mode == 'fast2': + # The fastest mode keeps the adapter's whole BF16 matrices of blocks 46-49 in unified memory while it samples, + # and its decode stage (a process of its own) holds the last step's features beside the pixel head, whose + # peak is the one measured on CUDA (reserved bytes, weights and margin included). + from .policy import FAST2_FEATURE_BYTES_PER_TOKEN, FAST2_PINNED_BYTES, pixel_head_bytes + needed += FAST2_PINNED_BYTES + # Unified memory also holds the head's uint8 frames as it returns them and once more joined (torch.cat), + # which a CUDA reserved peak does not count: twice frames x height x width x 3. + decode = (pixel_head_bytes(canvas) + shape['video_tokens'] * FAST2_FEATURE_BYTES_PER_TOKEN + + 2 * canvas['frames'] * canvas['width'] * canvas['height'] * 3) + if decode > needed: + phase, needed = 'decode', decode capacity, allowance = resource['allocator_capacity_bytes'], resource['allocator_bytes'] if working_set_bytes is not None: capacity, allowance = min(capacity, working_set_bytes), min(allowance, working_set_bytes) @@ -201,6 +223,7 @@ def request_admission(resource, sampling, *, preview=False, working_set_bytes=No capacity_bytes=int(capacity), tokens=tokens, width=canvas['width'], height=canvas['height'], frames=canvas['frames'], working_set_bytes=working_set_bytes, reference_tokens=reference_tokens, text_tokens=text_tokens, continuation_tokens=continuation_tokens, + **(dict(fast_mode=fast_mode, decode_bytes=int(decode)) if decode is not None else {}), scope='Smallest grouped-projection plan of the largest sampling pass, before model load.') diff --git a/freevideo_engine/macos_generate.py b/freevideo_engine/macos_generate.py index d78efc66..54a03928 100644 --- a/freevideo_engine/macos_generate.py +++ b/freevideo_engine/macos_generate.py @@ -159,6 +159,9 @@ def run(args): from .support_report import write as write_debug, code_identity from .two_pass import plan require_native() + from . import fast_tier + # The fastest mode: one pass of its two steps; refused with a preview, a continuation and the like (as on CUDA). + fast_spec = fast_tier.request(args) from .preview import validate_flags, source as preview_source preview = getattr(args, 'preview', False) is True validate_flags(preview, getattr(args, 'refine_from', None), args.two_pass, getattr(args, 'base_steps', None)) @@ -228,6 +231,12 @@ def interrupted(signum, frame): base = str(Path(args.base or base_path()).resolve()) adapters = [row for row in media.get('loras', []) if row['strength'] != 0] prepared_cache = Path(args.cache).resolve() + if fast_spec is not None: + if json.loads((prepared_cache / 'manifest.json').read_text(encoding='utf-8')).get('precision') != 'int8': + raise ValueError('The fastest mode needs the int8 model') + # First, so its branch order does not depend on which user LoRAs are on. + adapters = [fast_tier.adapter_row(fast_spec), *adapters] + report['fast_tier'] = dict(mode=fast_spec['mode'], adapter_sha256=fast_spec['adapter_sha256']) if output_size: report['output_size'] = output_size report.update(geometry=canvas, sampling_plan=sampling, profile=dict(policy=resource, @@ -243,7 +252,8 @@ def interrupted(signum, frame): + conditioning_info.get('reference_audio_tokens', 0)) admission = report['memory_admission'] = request_admission(resource, sampling, preview=preview, working_set_bytes=working_set, - reference_tokens=reference_tokens, continuation=continuation) + reference_tokens=reference_tokens, continuation=continuation, + fast_mode=fast_spec and fast_spec['mode']) _check_admission(admission, sampling) if preview: report['preview'] = dict(geometry=dict(sampling['first'], fps=canvas['fps'])) @@ -268,7 +278,8 @@ def execute(value, name, module='freevideo_engine.macos_generate'): result_path = artifacts / 'lora-result.json' print(json.dumps(dict(event='lora_prepare_start')), flush=True) report['lora_resources'] = execute(dict(cache=str(prepared_cache), adapters=adapters, - result=str(result_path), mode='online'), 'lora', module='freevideo_engine.lora_cache') + result=str(result_path), mode='online'), 'lora', + module='freevideo_engine.fast_tier' if fast_spec is not None else 'freevideo_engine.lora_cache') prepared = json.loads(result_path.read_text(encoding='utf-8')) prepared_cache = Path(prepared['cache']).resolve() report['lora'] = prepared['report'] @@ -278,7 +289,8 @@ def execute(value, name, module='freevideo_engine.macos_generate'): if 'tail' in continuation: report['continuation']['context'] = 'encoded' refreshed = request_admission(resource, sampling, working_set_bytes=working_set, - reference_tokens=reference_tokens, continuation=continuation) + reference_tokens=reference_tokens, continuation=continuation, + fast_mode=fast_spec and fast_spec['mode']) if refreshed['needed_bytes'] > admission['needed_bytes']: admission = report['memory_admission'] = refreshed _check_admission(admission, sampling) @@ -367,7 +379,7 @@ def execute(value, name, module='freevideo_engine.macos_generate'): report['memory_admission_before_encoding'] = admission admission = report['memory_admission'] = request_admission(resource, sampling, preview=preview, working_set_bytes=working_set, reference_tokens=reference_tokens, text_tokens=text_tokens, - continuation=continuation) + continuation=continuation, fast_mode=fast_spec and fast_spec['mode']) _check_admission(admission, sampling) report['phase'] = 'engine' save(output.with_suffix('.request.json'), report) @@ -381,6 +393,8 @@ def execute(value, name, module='freevideo_engine.macos_generate'): engine['continuation'] = continuation if hide_tail_frames: engine['hide_tail_frames'] = hide_tail_frames + if fast_spec is not None: + engine['fast_tier'] = fast_spec['mode'] if getattr(args, 'step_cache', None) == 'easycache-av': engine['step_cache'] = report['step_cache'] = args.step_cache if output_size: diff --git a/freevideo_engine/macos_runtime.py b/freevideo_engine/macos_runtime.py index b576a20d..c9b9c60c 100644 --- a/freevideo_engine/macos_runtime.py +++ b/freevideo_engine/macos_runtime.py @@ -141,7 +141,7 @@ def __init__(self, cache, *, base, checkpoint, steps=8, budget_bytes=4 * 2**30, weight_decoder='cpu', budget_ceiling_bytes=None, attention_chunk=None, task='t2va', canvas=None, head_chunk=4, window_batch=1, attention_impl='torch', fast_kernels=False, resident_bytes=0, attention_batch_bytes=1 << 29, plan_compute=False, memory_retry=False, - step_cache=None, adaln_task=None): + step_cache=None, adaln_task=None, fast_tier=None): if step_cache not in (None, 'easycache-av'): raise ValueError('MPS supports the easycache-av step cache only') self.step_cache = step_cache @@ -217,6 +217,18 @@ def __init__(self, cache, *, base, checkpoint, steps=8, budget_bytes=4 * 2**30, int8_compute = mps_int8.available() self.linear_compute = 'int8' if int8_compute else {'fp8': 'bf16-weight-only', 'int8': 'bf16-weight-only'}.get( precision, 'bf16') + # The fastest mode: the adapter's own modulation, output heads and last-step features, as on CUDA + # (runtime.Engine). M5 and newer run the base's int8 layers as int8, earlier Macs read them as BF16; the + # adapter's whole matrices are BF16 either way. + fast, FAST_REPLACED = None, () + self.raw_grid = None + if fast_tier is not None: + from .fast_tier import RAW_GRID, STEPS + from .fast_tier_runtime import REPLACED as FAST_REPLACED, Runtime + if precision != 'int8' or steps != STEPS or step_cache is not None: + raise ValueError('The fastest mode runs two steps on the int8 model') + fast, self.raw_grid = Runtime('mps'), RAW_GRID + self.fast = fast self.backend.prepare_linears(None, manifest, self.linear_compute, 'auto') groups = {row['group']: row for row in manifest['groups']} if len(groups) != len(manifest['groups']): @@ -259,18 +271,36 @@ def path(name): load_group(model, root, self.linears, exclude=('transformer_blocks.', 'token_refiner.refiner_blocks.', 'rope.'), decoder=self.weight_decoder) + if fast is not None: + # After the root weights, which the adapter's output heads and final norm replace. + fast.install_root(model) + fast.install_features(model, steps) model.rope.to('mps') times = schedule_timesteps(steps, device='mps', task=schedule_task) self.cursor = ScheduleCursor(times) - tables = TableCache(self.cache, manifest['source_id'], steps, manifest=manifest, - timesteps=times, channels=model.config.hidden_size, device='cpu', task=schedule_task) + tables = None if fast is not None else TableCache(self.cache, manifest['source_id'], steps, + manifest=manifest, timesteps=times, channels=model.config.hidden_size, device='cpu', task=schedule_task) embeddings = None delivery_checked = False for index, layer in enumerate(model.token_refiner.refiner_blocks): files = [root, root_lora] if root_lora is not None else root self.specs.append((layer, files, f'token_refiner.refiner_blocks.{index}.', ())) + fast_replaced = 0 for index, layer in enumerate(model.transformer_blocks): self._block_originals.append((layer, layer.forward)) + if fast is not None: + # No schedule table: the adapter's modulation, and its whole matrices in blocks 46-49. Those + # matrices stay on the GPU (unified memory) and are left out of the streamed block weights. + layer.adaln_proj = fast.modulation(index) + replaced = fast.replace_matrices(index, layer, True) + fast_replaced += replaced + factors = attach_lora(layer, index, self.cache, manifest) + files = [path(f'blocks/{index:02d}'), factors] if factors is not None else path(f'blocks/{index:02d}') + excluded = ('adaln_proj.',) + (tuple(module + '.' for _, module in FAST_REPLACED) if replaced else ()) + self.specs.append((layer, files, f'transformer_blocks.{index}.', excluded)) + self._ff_originals.append((layer.ff, layer.ff.forward)) + self.backend.install_chunked_ff(layer.ff, ff_chunk) + continue table = tables.load(index, steps) if (table is None and not delivery_checked and manifest.get('format') in SLIM_FORMATS and f'adaln/{index:02d}' not in groups): @@ -334,6 +364,8 @@ def path(name): self.kernels['int8_linears'] = int8_info['implementation'] self._bind_attention(head_chunk=head_chunk, row_chunk=attention_chunk, ff_chunk=ff_chunk) self.kernels['attention'] = attention_impl + if fast is not None: + self.kernels['fast_tier'] = dict(mode=fast_tier, replaced_matrices=fast_replaced) model.eval().requires_grad_(False) self.backend.synchronize() self.load_seconds = time.monotonic() - started @@ -449,10 +481,11 @@ def _plan_compute(self, canvas, prompt_rows): """ if not getattr(self, 'plan_compute', False): return - from .macos_compute import plan, sequence_tokens + from .macos_compute import fast_budget, plan, sequence_tokens from .backends.mps_linear import install as install_linear rows = sequence_tokens(canvas, prompt_rows) - computed = plan(self.policy['effective_allocator_limit_bytes'], rows['total'], + fast_mode = 'fast2' if vars(self).get('fast') is not None else None + computed = plan(fast_budget(self.policy['effective_allocator_limit_bytes'], fast_mode), rows['total'], frames=canvas['latent_frames'], layers=len(self.model.transformer_blocks), allow_bounded=True, force_bounded=getattr(self, 'memory_retry', False)) computed.update(tokens=rows['total'], packed_rows=rows, frames=canvas['latent_frames'], @@ -493,7 +526,13 @@ def _refine_prompt(self, prompt): def sample(self, *args, **kwargs): from .refine_schedule import modulation - with modulation(self, kwargs.get('refine_schedule')) as prepared: + from .step_grid import using + if vars(self).get('fast') is not None: + from .geometry import geometry + canvas = geometry(kwargs['width'], kwargs['height'], frames=kwargs['frames']) + # The token grid of the video rows the pixel head reads: latent frames, height and width / 32. + self.fast.features.begin((canvas['latent_frames'], canvas['height'] // 32, canvas['width'] // 32)) + with using(vars(self).get('raw_grid')), modulation(self, kwargs.get('refine_schedule')) as prepared: result = self._sample(*args, **kwargs) if prepared is not None: result[2]['refinement_schedule_preparation'] = prepared diff --git a/freevideo_engine/macos_stages.py b/freevideo_engine/macos_stages.py index 523d5dc1..fcdf2269 100644 --- a/freevideo_engine/macos_stages.py +++ b/freevideo_engine/macos_stages.py @@ -329,7 +329,7 @@ def interrupted(signum, frame): save(path, result) -def stage_compute(resource, canvas, retry=False, avoid_mlx=False): +def stage_compute(resource, canvas, retry=False, avoid_mlx=False, fast_mode=None): """Partitions for this sampling stage from its live unified-memory allowance. The supervisor's policy fixes the reserve and allocator ceiling; the stage @@ -340,10 +340,10 @@ def stage_compute(resource, canvas, retry=False, avoid_mlx=False): if resource.get('compute_plan') is False: return {} from .geometry import geometry - from .macos_compute import plan + from .macos_compute import fast_budget, plan from .system import system_memory available = system_memory()['available_bytes'] - resource['reserve_bytes'] - budget = int(max(0, min(resource['allocator_capacity_bytes'], available))) + budget = fast_budget(int(max(0, min(resource['allocator_capacity_bytes'], available))), fast_mode) shape = geometry(canvas['width'], canvas['height'], frames=canvas['frames']) tokens, frames = shape['video_tokens'] + 1024, shape['latent_frames'] result = plan(budget, tokens, frames=frames, allow_bounded=True, force_bounded=retry) @@ -430,7 +430,7 @@ def capture_first(video): print(json.dumps(dict(event='model_load_phase', phase='Loading native MPS model')), flush=True) retry = value.get('memory_retry') is True compute = stage_compute(resource, sampling['second' if refining else 'first'], retry=retry, - avoid_mlx=value.get('avoid_mlx') is True) + avoid_mlx=value.get('avoid_mlx') is True, fast_mode=value.get('fast_tier')) result['compute'] = compute if retry: result['memory_retry'] = True @@ -450,6 +450,7 @@ def capture_first(video): plan_compute=bool(compute), memory_retry=retry and bool(compute), task=value.get('task', 't2va'), canvas=value['canvas'], step_cache=None if refining else value.get('step_cache'), + **(dict(fast_tier=value['fast_tier']) if value.get('fast_tier') is not None else {}), **(dict(adaln_task=chain.ANCHOR_ADALN_TASK if continuation.get('anchor') else chain.ADALN_TASK) if continuation is not None else {})) as engine: result['load_seconds'] = engine.load_seconds @@ -511,6 +512,15 @@ def first_saved(video, audio, metrics): if measured.get('compute') is not None: result.update(initial_compute=compute, compute=measured['compute']) result.update(sampling=measured, work_seconds=time.monotonic() - tick) + if value.get('fast_tier') is not None: + # The fastest mode's last-step features, already on the CPU, for the pixel head in the decode + # stage (another process: the transformer is released before the head loads). + features, grid = engine.fast.features.take() + tick = time.monotonic() + torch.save(dict(features=features, grid=list(grid), adapter=str(engine.fast.adapter)), + artifacts / 'pixel-features.pt') + result['feature_save_seconds'] = time.monotonic() - tick + del features if refining: first_tail = initial.get('continuation_first') elif not result.get('joined_sampling'): @@ -531,6 +541,19 @@ def first_saved(video, audio, metrics): first_tail = initial.get('continuation_first') result.update(upscale=stats, work_seconds=stats['stage_seconds']) name = 'upscaled.pt' + elif phase == 'decode' and value.get('fast_tier') is not None: + # The fastest mode draws its pixels with the adapter's head; the video VAE is never read. No + # continuation, preview or hidden tail reaches this mode (fast_tier.request refuses them). + from .dwd_decode import pixels_to_file + initial = torch.load(artifacts / 'latents.pt', map_location='cpu', weights_only=True) + kept = torch.load(artifacts / 'pixel-features.pt', map_location='cpu', weights_only=True) + tick = time.monotonic() + result['decode'] = pixels_to_file(kept['features'], tuple(kept['grid']), initial['audio'], value['output'], + base=value['base'], adapter=kept['adapter'], artifacts_dir=artifacts, + output_size=value.get('output_size'), device='mps') + del kept + result.update(work_seconds=time.monotonic() - tick, success=True) + return elif phase == 'decode': from .macos_decode import decode_to_file # A preview decodes its first pass; the upscale input stays for later. diff --git a/freevideo_engine/model_transfer.py b/freevideo_engine/model_transfer.py index cc9a85ea..f0aebdda 100644 --- a/freevideo_engine/model_transfer.py +++ b/freevideo_engine/model_transfer.py @@ -142,8 +142,9 @@ def update(self, amount, *, transfer=False): def verify(path, row, progress=None): if path.stat().st_size != row['bytes']: raise ValueError('Downloaded size differs from the pinned manifest') - return network.hash_file(path, 'sha256' if row.get('sha256') else 'sha1', not row.get('sha256'), - discard_cache=True, progress=progress) == (row.get('sha256') or row['git_blob']) + verify.observed = network.hash_file(path, 'sha256' if row.get('sha256') else 'sha1', not row.get('sha256'), + discard_cache=True, progress=progress) + return verify.observed == (row.get('sha256') or row['git_blob']) def checked_range_response(response, requested, total, progress): @@ -200,8 +201,12 @@ def sdk_worker(request): emit(phase='verify', done_bytes=0, total_bytes=row['bytes']) if verify(target, row, progress=verifying): emit(phase='ready', backend='verified-stage', seconds=time.monotonic()-started, fingerprint=fingerprint(target)) + network.forget_failed(target, {}, category='models') return 0 - network.retain_partial(target, 'hash-rejected') + # Worker output: the parent passes these network events on to the run's log. + network.retain_partial(target, 'hash-rejected', observed=getattr(verify, 'observed', None), + algorithm='sha256' if row.get('sha256') else 'sha1-git-blob', + network={}, category='models', source=source) emit(phase='connect') if source == 'modelscope' or request.get('manual_ranges'): from modelscope_hub import HubApi @@ -343,11 +348,12 @@ def report(done, total, rate): download_seconds=downloaded-started, verification_seconds=time.monotonic()-downloaded, done_bytes=row['bytes'], total_bytes=row['bytes'], transfer_bytes=progress.transferred, fingerprint=fingerprint(target)) + network.forget_failed(target, {}, category='models') return 0 except Exception as error: # Signed CDN URLs and authentication details can appear in SDK errors. if target.is_file(): - network.retain_partial(target, 'rejected') + network.retain_partial(target, 'rejected', network={}, category='models', source=source) import traceback traceback.print_exc() emit(phase='failed', error_type=type(error).__name__, message=safe_log(str(error))) @@ -631,6 +637,9 @@ def read_output(): raise receipt['promoted'] = True save(report / 'result.json', receipt) + # The right file is in place: what did not pass for it, in the stage and beside it, goes. + network.forget_failed(staged, networking, category=network.model_family(row)) + network.forget_failed(stage, networking, category=network.model_family(row)) return final @@ -804,7 +813,7 @@ def _download(row, path, plan, progress_callback, headers_for, *, transfer_compl else: network.event(networking, category=family, source=name, file=path.name, action='restart-approved', retained_bytes=retained, reason=reason) - network.retain_partial(stage, 'restart-approved') + network.retain_partial(stage, 'restart-approved', network=networking, category=family, source=name) if not resource_failure: network.source_health(networking, family, name, False) network.event(networking, category=family, source=name, file=path.name, action='fallback', diff --git a/freevideo_engine/model_upgrade.py b/freevideo_engine/model_upgrade.py index e41cc7e9..14de9915 100644 --- a/freevideo_engine/model_upgrade.py +++ b/freevideo_engine/model_upgrade.py @@ -80,8 +80,10 @@ def offer(root): int8_ready = bool(readiness(rows).get('int8_ready')) except (KeyError, TypeError, AttributeError): checked = int8_ready = False - reason = ('fp8-is-faster' if preferred_format(hardware) != TARGET - else 'int8-kernels' if checked and not int8_ready else None) + # Where FP8 is the faster arithmetic (workstation and datacenter Ada and Blackwell) the move is still offered, because + # only the int8 model runs the fastest mode; the card then says what it costs on this GPU (purpose 'fast-level'). + purpose = 'faster' if preferred_format(hardware) == TARGET else 'fast-level' + reason = 'int8-kernels' if checked and not int8_ready else None if reason: # For example an int8 download this GPU then failed to run. return unused(root, catalog, current) or dict(status='unavailable', reason=reason, receipt=stamp) @@ -90,7 +92,7 @@ def offer(root): fused = variant_cleanup.fused_lora_variants(root, catalog, current) release = 0 if fused else variant_cleanup.retire(root, catalog, current)['bytes'] free = disk_space.free_bytes(root) - return dict(status='available' if free >= download + MARGIN else 'low-disk', + return dict(status='available' if free >= download + MARGIN else 'low-disk', purpose=purpose, architecture=hardware.architecture, gpu=hardware.gpu_name, current=current, download_bytes=download, release_bytes=release, free_bytes=free, required_bytes=download + MARGIN, lora_variants=fused, int8_checked=checked) diff --git a/freevideo_engine/modern_launcher.py b/freevideo_engine/modern_launcher.py index 6379b6db..ff4c9edc 100644 --- a/freevideo_engine/modern_launcher.py +++ b/freevideo_engine/modern_launcher.py @@ -295,7 +295,7 @@ def edit_field(): try: session.edit(key, value) except ValueError as exc: - if key not in ('token', 'url'): + if key not in ('token', 'url', 'destination', 'engine'): raise session.field_error = dict(key=key, message=str(exc)) self.invoke(edit_field) @@ -502,6 +502,17 @@ def openInstallFolder(self): return self.invoke(QDesktopServices.openUrl, QUrl.fromLocalFile(str(folder.resolve()))) + @Slot() + def openUpdateFolder(self): + """The folder of a downloaded launcher Windows did not let start, so the user can start it there.""" + from PySide6.QtGui import QDesktopServices + folder = Path(session.update_blocked_path).parent if session.update_blocked_path else None + if folder is None or not folder.is_dir(): + session.action_notice = 'folder_open_failed' + self.refresh() + return + self.invoke(QDesktopServices.openUrl, QUrl.fromLocalFile(str(folder.resolve()))) + @Slot() def openDownloadFolder(self): from PySide6.QtGui import QDesktopServices diff --git a/freevideo_engine/monitoring.py b/freevideo_engine/monitoring.py index e47604e9..e22eb9dd 100644 --- a/freevideo_engine/monitoring.py +++ b/freevideo_engine/monitoring.py @@ -4,6 +4,7 @@ import ctypes import json import os +import re from pathlib import Path import threading import time @@ -138,6 +139,74 @@ def thermal_slowdown(measured, *, share=.5, clock_ratio=.7, minimum_samples=200) temperature_mean_c=round(temperature, 1) if type(temperature) in (int, float) and 0 <= temperature <= 1000 else None) +# A module FreeVideo starts a helper with: processes.module_command, `-m` or the AppImage's --freevideo-module. +FREEVIDEO_MODULE = re.compile(r'freevideo_engine(\.[A-Za-z_][A-Za-z0-9_]*)+\Z') + + +def started_module(command): + """The freevideo_engine module a command line runs, or None. + + `python -m module`, the Linux AppImage's `--freevideo-module module`, or + processes.module_command's `python -c module`. + Windows' process_host wrapper is such a module too, so the helper it + holds is found as its descendant. A third-party node's script is not.""" + command = [str(part) for part in command or ()] + for index, part in enumerate(command[:-1]): + if part in ('-m', '--freevideo-module'): + module = command[index + 1] + break + if part == '-c': + module = command[index + 3] if 'runpy.run_module' in command[index + 1] and len(command) > index + 3 else None + break + else: + return None + return module if module and FREEVIDEO_MODULE.match(module) else None + + +def process_command(pid): + """A process's command line, or None when it is gone or cannot be read (read again at every refresh, so a + reused process id is judged by its new command).""" + try: + import psutil + return psutil.Process(pid).cmdline() + except Exception: + return None + + +def power_limited(measured, *, share=.25, clock_ratio=.7, minimum_samples=200): + """The worker's busy time held back by the driver's power limit, or None. + + A desktop card often sits at its power limit near its full clock; that is + normal and not reported. Counted only when the power-limit reasons cover + at least `share` of the busy samples and the mean SM clock stays below + `clock_ratio` of the highest one observed (a laptop or small system whose + power limit is lowered on battery, in a power-saving mode or to keep its + case cool). A run thermal_slowdown already names gives None: one note. + `share` in the result is the part of the busy time held at the limit; the + page's note gives the mean clock as a share of the peak instead. + """ + if thermal_slowdown(measured) is not None: + return None + busy = measured.get('busy_activity') if isinstance(measured, dict) else None + if not isinstance(busy, dict): + return None + samples = _count(busy.get('clock_reason_samples')) + counts = busy.get('clock_reason_counts') + counts = counts if isinstance(counts, dict) else {} + clock = busy.get('sm_clock_mhz') + clock = clock if isinstance(clock, dict) else {} + mean, peak = _count(clock.get('mean')), _count(clock.get('maximum')) + if samples < minimum_samples or not mean or not peak: + return None + limited = min(samples, max(_count(counts.get('sw_power_cap')), _count(counts.get('hw_power_brake')))) + if limited < share * samples or mean > clock_ratio * peak: + return None + power = busy.get('power_mw') + power = power.get('mean') if isinstance(power, dict) else None + return dict(share=round(limited / samples, 3), sm_clock_mean_mhz=round(mean), sm_clock_max_mhz=round(peak), + power_mean_w=round(power / 1000, 1) if type(power) in (int, float) and 0 <= power <= 1e7 else None) + + class OtherPrograms: """Other programs' share of the GPU's cores while a worker computes. @@ -145,8 +214,15 @@ class OtherPrograms: step, yet the device still reads fully busy at its full clock, exactly as when the worker has it alone. NVML's per-process samples tell the two apart where the driver reports them. Our processes are the one that - monitors, the worker and their descendants. Constant space: counts and - sums over the checks made while the worker was computing. + monitors, the worker and their descendants. With `host`, the FreeVideo + process that started this request, the processes under it that FreeVideo + started by a known entry (a freevideo_engine module: the prompt model, + pictures, music, an idle encoder) and their descendants are FreeVideo's + other work, counted apart from other programs. Anything else under the + host, such as a third-party node's child process, and the host itself + stay other programs. Windows gives no per-process graphics memory, so + only shares of the cores are kept. Constant space: counts and sums over + the checks made while the worker was computing. """ seconds = 1. refresh_seconds = 5. @@ -156,16 +232,20 @@ class OtherPrograms: own_percent = 15 failures_allowed = 5 - def __init__(self, lib, handle, pid=None): - self.lib, self.handle, self.pid = lib, handle, pid + def __init__(self, lib, handle, pid=None, host=None): + self.lib, self.handle, self.pid, self.host = lib, handle, pid, host self.since = int(time.time() * 1e6) - self.ours, self.seen = set(), set() + self.ours, self.seen, self.helpers = set(), set(), set() self.checked = self.refreshed = 0. self.supported = None self.own_reported = False self.failures = 0 self.checks = self.shared = 0 self.other_total = self.own_total = self.other_peak = 0. + self.helper_shared = 0 + self.helper_total = self.helper_peak = 0. + # FreeVideo's other work in the last counted check, for the sample file. + self.last_helpers = None def read(self): """{pid: mean % of cores} over the sample periods newer than the last ones read; None when unavailable. @@ -201,18 +281,39 @@ def read(self): return {pid: total / number for pid, total in totals.items()} def refresh(self): - """A worker must never turn into another program for want of a process list: the last known ones stay ours.""" - from .background_room import family + """A worker must never turn into another program for want of a process list: the last known ones stay ours. + + One listing serves every family; a process is never both ours and FreeVideo's other work.""" + from .background_room import family, parents try: - self.ours = family(os.getpid()) | (family(self.pid) if self.pid else set()) + table = parents() + self.ours = family(os.getpid(), table) | (family(self.pid, table) if self.pid else set()) except OSError: self.ours = self.ours or {pid for pid in (os.getpid(), self.pid) if pid} + self.helpers -= self.ours + return + if self.host: + try: + self.helpers = self.freevideo_work(table) - self.ours + except OSError: + self.helpers -= self.ours # The last known ones stay FreeVideo's. + + def freevideo_work(self, table): + """The processes under the host that FreeVideo started by a known entry, with their descendants.""" + from .background_room import family + work = set() + for pid in family(self.host, table) - {self.host} - self.ours: + if started_module(process_command(pid)) is not None: + work |= family(pid, table) + return work def check(self, util): """Read once a second; count the reading when the worker is computing on a busy device. - Returns the other programs' share of the cores in percent for a reading that was counted, else None. + Returns the other programs' share of the cores in percent for a reading that was counted, else None; + FreeVideo's other work in that reading is left in `last_helpers`. """ + self.last_helpers = None now = time.monotonic() if self.supported is False or now - self.checked < self.seconds: return None @@ -230,13 +331,14 @@ def check(self, util): if now - self.refreshed >= self.refresh_seconds or any(pid not in self.seen for pid in found): self.refresh() self.refreshed, self.seen = now, set(found) - other = min(100., sum(value for pid, value in found.items() if pid not in self.ours)) + other = min(100., sum(value for pid, value in found.items() if pid not in self.ours and pid not in self.helpers)) + helpers = min(100., sum(value for pid, value in found.items() if pid in self.helpers and pid not in self.ours)) own = min(100., sum(value for pid, value in found.items() if pid in self.ours)) self.own_reported = self.own_reported or own > 0 if not self.own_reported: # Some drivers report no samples for a compute process: what the # device did beyond the other programs was the worker's. - own = max(0., util - other) + own = max(0., util - other - helpers) if own < self.own_percent: return None self.checks += 1 @@ -244,6 +346,11 @@ def check(self, util): self.other_total += other self.own_total += own self.other_peak = max(self.other_peak, other) + if self.host: + self.helper_shared += helpers >= self.share_percent + self.helper_total += helpers + self.helper_peak = max(self.helper_peak, helpers) + self.last_helpers = helpers return other def result(self): @@ -252,25 +359,32 @@ def result(self): if self.checks: result.update(other_mean_percent=self.other_total / self.checks, other_peak_percent=self.other_peak, own_mean_percent=self.own_total / self.checks) + if self.host: + result.update(helpers_counted=True, helpers_shared_checks=self.helper_shared) + if self.checks: + result.update(helpers_mean_percent=self.helper_total / self.checks, helpers_peak_percent=self.helper_peak) return result -def shared_gpu(measured, *, share=.5, minimum_checks=30): +def shared_gpu(measured, *, share=.5, minimum_checks=30, who='other'): """Other programs holding a real part of the GPU for most of the time the worker computed, or None. Counted only when they took at least `share_percent` of the cores in at least `share` of the checks, so a desktop that draws now and then or a - short video is not reported. + short video is not reported. `who='helpers'` asks the same of FreeVideo's + other work (OtherPrograms with a host); the result then holds + helpers_mean_percent. """ programs = measured.get('other_programs') if isinstance(measured, dict) else None if not isinstance(programs, dict): return None - checks, shared, mean = (programs.get(key) for key in ('checks', 'shared_checks', 'other_mean_percent')) + shared_key = 'shared_checks' if who == 'other' else who + '_shared_checks' + checks, shared, mean = (programs.get(key) for key in ('checks', shared_key, who + '_mean_percent')) if (any(type(value) not in (int, float) for value in (checks, shared, mean)) or not minimum_checks <= checks <= 1e9 or not 0 <= shared <= checks or not 0 <= mean <= 100 or shared < share * checks): return None - return dict(share=round(shared / checks, 3), other_mean_percent=round(mean)) + return {'share': round(shared / checks, 3), who + '_mean_percent': round(mean)} # Other programs' mean share of the GPU, in percent, from which the result says so: @@ -279,16 +393,20 @@ def shared_gpu(measured, *, share=.5, minimum_checks=30): def shared_gpu_note(measured): - """{other_mean_percent} for the note under a result, or None. + """{other_mean_percent, helpers_mean_percent} for the note under a result, either or both, or None. - Shown when other programs averaged at least SHARED_NOTE_PERCENT of the - GPU, and shared_gpu holds: at least 30 checks, with other programs using - at least 20% in at least half of them. + Each is given when it averaged at least SHARED_NOTE_PERCENT of the GPU, + and shared_gpu holds for it: at least 30 checks, using at least 20% in at + least half of them. Other programs and FreeVideo's other work are said + apart, so the note never asks a user to close FreeVideo's own work. """ - if shared_gpu(measured) is None: - return None - mean = measured['other_programs']['other_mean_percent'] - return dict(other_mean_percent=mean) if mean >= SHARED_NOTE_PERCENT else None + note = {} + for who in ('other', 'helpers'): + if shared_gpu(measured, who=who) is not None: + mean = measured['other_programs'][who + '_mean_percent'] + if mean >= SHARED_NOTE_PERCENT: + note[who + '_mean_percent'] = mean + return note or None def _count(value): @@ -298,7 +416,7 @@ def _count(value): def combined(rows): """Several attempts' busy-time clock reasons and other programs' checks as one observation. - Only what thermal_slowdown and shared_gpu read: counts add up, means are + Only what thermal_slowdown, power_limited and shared_gpu read: counts add up, means are weighted by their samples and peaks are the highest. """ result = {} @@ -308,7 +426,7 @@ def combined(rows): clock_reason_counts={key: sum(_count(item['clock_reason_counts'].get(key)) for item in busy if isinstance(item.get('clock_reason_counts'), dict)) for key in Activity.clock_reasons}) - for field in ('sm_clock_mhz', 'temperature_c'): + for field in ('sm_clock_mhz', 'temperature_c', 'power_mw'): parts = [(item[field], _count(item[field].get('samples')) or _count(item.get('clock_reason_samples'))) for item in busy if isinstance(item.get(field), dict) and _count(item[field].get('mean'))] weight = sum(samples for _, samples in parts) @@ -327,6 +445,16 @@ def combined(rows): merged.update(other_mean_percent=sum(_count(item.get('other_mean_percent')) * number for item, number in counted) / checks, other_peak_percent=max(_count(item.get('other_peak_percent')) for item in programs), own_mean_percent=sum(_count(item.get('own_mean_percent')) * number for item, number in counted) / checks) + helped = [(item, number) for item, number in counted if item.get('helpers_counted') is True] + if helped: + # Only attempts that told FreeVideo's other work apart; their checks are the mean's weight. + weight = sum(number for _, number in helped) + merged.update(helpers_counted=True, + helpers_shared_checks=sum(_count(item.get('helpers_shared_checks')) for item, _ in helped)) + if weight: + merged.update(helpers_mean_percent=sum(_count(item.get('helpers_mean_percent')) * number + for item, number in helped) / weight, + helpers_peak_percent=max(_count(item.get('helpers_peak_percent')) for item, _ in helped)) result['other_programs'] = merged return result @@ -404,10 +532,10 @@ def close(self): class Monitor: - def __init__(self, path, interval=0.05, device=None, pid=None): + def __init__(self, path, interval=0.05, device=None, pid=None, host=None): self.lib, self.handle, device = nvml_device(device) self.device = device - self.programs = OtherPrograms(self.lib, self.handle, pid) + self.programs = OtherPrograms(self.lib, self.handle, pid, host) self.path, self.interval = Path(path), interval self.stop_event = threading.Event() self.peak = 0 @@ -466,7 +594,7 @@ def loop(self): writer = csv.writer(f) writer.writerow(['epoch_seconds', 'monotonic_seconds', 'used_bytes', 'total_bytes', 'gpu_util_percent', 'temperature_c', 'power_mw', 'sm_clock_mhz', 'memory_clock_mhz', 'clock_reason_mask', - 'other_programs_percent']) + 'other_programs_percent', 'freevideo_helpers_percent']) while not self.stop_event.is_set(): try: used, total, util = self.sample() @@ -484,10 +612,12 @@ def loop(self): self.max_power_mw = max(self.max_power_mw or 0, auxiliary[1]) try: other = self.programs.check(util) + helpers = self.programs.last_helpers except Exception: - other = None + other = helpers = None writer.writerow([time.time(), time.monotonic(), used, total, util, *auxiliary, reasons, - '' if other is None else '%.1f' % other]) + '' if other is None else '%.1f' % other, + '' if other is None or helpers is None else '%.1f' % helpers]) except Exception as e: if str(e) not in self.errors and len(self.errors) < 20: self.errors.append(str(e)) @@ -510,7 +640,9 @@ def stop(self): 'busy device: the share of its cores used by processes outside this worker and its ' 'monitor. shared_checks counts readings at or above share_percent. Without own_reported ' "the worker's share is the device's utilization beyond the other programs. A driver " - 'without per-process samples reports no checks.', + 'without per-process samples reports no checks. With helpers_counted, the rest of the ' + "FreeVideo process tree that started this request is FreeVideo's other work: its share " + 'is helpers_* and is not in other_*. Shares of the cores only; no per-process memory.', 'sampling_interval_seconds': self.interval, 'samples': self.count, 'sampling_errors': self.errors, 'sample_csv': str(self.path)} @@ -570,6 +702,13 @@ def number(sample, key): total = item['sums'].setdefault('other_programs_percent_mean', [0., 0]) total[0] += other total[1] += 1 + helpers = number(sample, 'freevideo_helpers_percent') + if helpers is not None and helpers <= 100: + item['freevideo_helpers_checks'] = item.get('freevideo_helpers_checks', 0) + 1 + item['freevideo_helpers_percent_peak'] = max(item.get('freevideo_helpers_percent_peak', 0.), helpers) + total = item['sums'].setdefault('freevideo_helpers_percent_mean', [0., 0]) + total[0] += helpers + total[1] += 1 used, size = number(sample, 'used_bytes'), number(sample, 'total_bytes') if used is not None: item['device_used_peak_bytes'] = max(item.get('device_used_peak_bytes', 0), int(used)) diff --git a/freevideo_engine/network.py b/freevideo_engine/network.py index df6cbc04..11639ccc 100644 --- a/freevideo_engine/network.py +++ b/freevideo_engine/network.py @@ -25,6 +25,7 @@ from urllib.parse import quote, unquote, urlencode, urljoin, urlsplit from . import proxy from .long_paths import io_path, is_windows, path_chars, plain, plain_errors, ABSOLUTE_PATH, AUTHORIZATION, EMAIL, path_match +from . import report_addresses from .system import curl_executable, curl_ca_arguments, missing_curl_message, windows @@ -644,6 +645,9 @@ def _redact(value): if isinstance(value, bytes): value = value.decode('utf-8', errors='replace') value = _ANSI_ESCAPE.sub('', str(value)).replace('\x00', '') + # An address keeps the path report_addresses keeps (on a repository host only FreeVideo's own + # repositories), with no query or fragment; its user and password go below. + value = report_addresses.URL.sub(report_addresses.record, value) # User information in any URL (https, socks5, a token alone before @), up to # the last @ before the host, so a password holding an @ goes as a whole. value = re.sub(r'(?i)\b([a-z][a-z0-9+.-]*://)[^\s/\x27\x22]+@', r'\1@', value) @@ -1017,12 +1021,33 @@ def hash_file(path, algorithm='sha256', git_blob=False, *, discard_cache=False, return value.hexdigest() -def retain_partial(path, reason): +def retain_partial(path, reason, *, observed=None, algorithm='sha256', network=None, category=None, source=None): + """Keep a file or prefix that failed its check, as .-