diff --git a/.gitignore b/.gitignore index c1dc2f9..c95b3da 100644 --- a/.gitignore +++ b/.gitignore @@ -15,6 +15,11 @@ server/data/ *.log .DS_Store +# Experiments and session notes that never ship +spike/ +.pi/ +HANDOFF-*.md + # Windows native-window build output windows/launcher/webview2/bin/ windows/launcher/webview2/obj/ diff --git a/Dockerfile b/Dockerfile index d686a83..cf3e438 100644 --- a/Dockerfile +++ b/Dockerfile @@ -4,6 +4,10 @@ FROM node:24-bookworm-slim AS deps WORKDIR /app COPY package.json package-lock.json ./ +# onnxruntime-node's postinstall downloads the CUDA build (hundreds of MB) that +# a CPU-only server never loads; the package itself already carries its CPU +# binaries, so skip the download in both install stages. +ENV ONNXRUNTIME_NODE_INSTALL=skip RUN npm ci # ---------------------------------------------------------------------- build @@ -20,7 +24,8 @@ RUN npm run build # ------------------------------------------------------- production node_modules FROM node:24-bookworm-slim AS prod-deps WORKDIR /app -ENV NODE_ENV=production +ENV NODE_ENV=production \ + ONNXRUNTIME_NODE_INSTALL=skip COPY package.json package-lock.json ./ RUN npm ci --omit=dev && npm cache clean --force diff --git a/README.md b/README.md index 4ec20c3..d2b04b5 100644 --- a/README.md +++ b/README.md @@ -442,7 +442,7 @@ Node server (node:http, port 8787) raw.mjs LibRaw demosaic, embedded-preview fallback libraw-*.mjs Node <-> browser shim and decoder worker pool imaging.mjs sharp encode/resize, dependency-free PNG fallback - denoise.mjs job queue and on-disk render cache + denoise.mjs denoise queue, base selection and render cache quota.mjs usage accounting, prune plans, warnings, worker mail.mjs nodemailer transport, admin-editable settings bridge.mjs dashboard token verification and metadata import @@ -453,7 +453,7 @@ Data directory originals/ uploaded files, byte-for-byte, original extension kept previews/ editable JPEG proxies (raw) and normalised previews thumbs/ grid thumbnails (server-rendered proofs are 560 px) - denoised/ full-strength denoise renders keyed by pipeline version + denoised/ full-strength denoise renders, one per base model proofs/ rendered proofs for client galleries proofThumbs/ thumbnails of those proofs ``` @@ -534,7 +534,7 @@ that predate workspaces are assigned to the oldest account. | `originals/` | `.` | Uploaded bytes, untouched; extension preserved | | `previews/` | `.jpg` or `.png` | Editable proxies; PNG when `sharp` is unavailable | | `thumbs/` | `.jpg` | Grid thumbnails; server-rendered proof thumbnails are 560 px | -| `denoised/` | `..jpg` | Key encodes the pipeline version; old keys are pruned | +| `denoised/` | `..jpg` | Key encodes the pipeline version and the base model; one render is kept per model | | `proofs/` | `.jpg` | Rendered client-gallery proofs | | `proofThumbs/` | `.jpg` | Thumbnails of those proofs | @@ -596,8 +596,8 @@ routes are public and are gated only by the share token. | GET | `/api/photos/:id/preview` | owner | Stream the editable proxy | | GET | `/api/photos/:id/thumb` | owner | Stream the thumbnail (proof thumbnail first, if present) | | POST | `/api/photos/:id/proof` | owner | Store a rendered JPEG proof and its thumbnail from base64 | -| POST | `/api/photos/:id/denoise` | owner | Queue a full-strength denoise render; returns a job id | -| GET | `/api/denoise/jobs/:id` | session | Job state: running/done/error, timing, stats, cache hit | +| POST | `/api/photos/:id/denoise` | owner | Queue a full-strength render; body `{"base": "guided" \| "scunet" \| "nlm"}`, default `guided`; returns a job id | +| GET | `/api/denoise/jobs/:id` | session | Job state: running/done/error, `progress` (`stage`, `done`, `total` tiles), `ms`, `bytes`, `stats` and `cached` for a cache hit | | GET | `/api/photos/:id/denoised?v=` | owner | Stream the cached denoise render | | DELETE | `/api/photos/:id/denoised` | owner | Drop all denoise renders for the photo | | GET | `/api/quota` | session | The caller's quota state | @@ -922,26 +922,52 @@ busy count. ## Detail-preserving denoise -`server/denoise/` is a dependency-free pipeline (planes, noise estimation, colour, -detail, RGB reconstruction) adapted from the `raw-noise` project. It reconstructs each -pixel as a crossfade between the source and a denoised base, so the result is bounded by -the original pixels and cannot ring or overshoot: flat noise is replaced, structure is -handed back verbatim. +`server/denoise/` is Luminary's denoise pipeline: planes, noise estimation, colour, +detail and RGB reconstruction, adapted from the `raw-noise` project, driving one of three +base denoisers. The result is a per-pixel crossfade between the source and the denoised +base, so it is bounded by the original pixels and cannot ring or overshoot: flat noise is +replaced, structure is handed back verbatim. -**Provenance.** `raw-noise` is not published on npm, and no copyright or licence notice -for it is included in this repository. Before redistributing Luminary, add the origin's -notice and terms to `server/denoise/`, or replace that folder with an independently -licensed implementation. +The **AI denoise** panel offers the three bases in this order: + +| Base | Implementation | One 256 × 256 test frame | +| --- | --- | --- | +| **Guided** (default) | Guided filter in the copied pipeline; fastest, keeps the most fine texture | 0.06 s | +| **SCUNet** | Learned colour denoiser `server/denoise/scunet_color_25.onnx`, run through `onnxruntime-node` on 256 px tiles with a 32 px overlap | 12.1 s (4 tiles) | +| **NLM** | Non-local means in the copied pipeline; slower than Guided, smooths less than SCUNet | 0.43 s | + +Timings are what the three bases measured here on a 256² noisy frame; a full frame costs +more in proportion to its area (and SCUNet to its tile count). The base is stored per +photo in `aiDenoise.model` and is part of the render key, so switching models does not +invalidate another model's render. SCUNet is the only path that needs +`onnxruntime-node`; it is imported lazily, so Guided and NLM keep working when the native +binding cannot load. The package is pinned to `1.23.0`, the last release that ships both +macOS architectures, and its install step is skipped in the Dockerfile and the desktop +builds (`ONNXRUNTIME_NODE_INSTALL=skip`) because only the CPU binaries in the package are +used. + +**Provenance and licences.** `raw-noise` is not published on npm, and no copyright or +licence notice for it is included in this repository. Before redistributing Luminary, add +the origin's notice and terms to `server/denoise/`, or replace that folder with an +independently licensed implementation. The SCUNet weights are Apache-2.0 (upstream +`cszn/SCUNet`, ONNX export by `Heliosoph/scunet-onnx`) and ONNX Runtime is MIT; both are +listed in [`THIRD_PARTY_NOTICES.md`](THIRD_PARTY_NOTICES.md). - The server always renders the full-strength denoise and the GPU blends it, so the Amount slider is instant, one file serves every amount, and the amount cannot be applied twice. -- Renders are cached in `denoised/` under a key that includes `PIPELINE_VERSION`. Bump - that constant whenever the copied pipeline changes output, or stale renders will be - served as current. +- Renders are cached in `denoised/` as `..jpg`, where the key is the first + 12 hex characters of `sha1(photoId|PIPELINE_VERSION|base)`. One render is kept per + model, so switching back to a model is instant; a finished run prunes only keys from an + older pipeline version. Bump `PIPELINE_VERSION` in `server/denoise.mjs` whenever the + copied pipeline or the SCUNet tiling changes output, or stale renders will be served as + current. - Each run is seconds of CPU, so jobs go through a capped queue (`LUMINARY_DENOISE_WORKERS`, default `min(4, cores−1)`). A second request for the same - photo joins the run already in progress instead of starting an identical one. + photo and base joins the run already in progress instead of starting an identical one, + and a request whose render already exists returns at once with `cached: true`. +- While a job runs it reports `progress` (`stage` and, for SCUNet, the tile count), which + the panel turns into a real status line instead of a spinner. - The job table keeps the newest 40 entries and never drops a queued or running job. --- @@ -997,6 +1023,11 @@ positions. Camera-lens defaults require both a normalised camera and lens name t | `npm run predeploy` | Typecheck, unit suite, render check, then build — run this before pushing a deploy; the build is skipped when only test files changed since the last build | | `npm run deploy` | Predeploy gate, then rsync, remote build, restart and bundle-hash check (see [Production deployment](#production-deployment)) | +`npm install` also installs `onnxruntime-node` for the SCUNet denoise base. Its install +step downloads the CUDA build (~350 MB) unless `ONNXRUNTIME_NODE_INSTALL=skip` is set +before the install; the Dockerfile and the desktop builds set it, because only the CPU +binaries that ship inside the package are used. + ### Continuous integration `.gitea/workflows/ci.yml` runs on every push and pull request: `npm ci`, @@ -1007,8 +1038,9 @@ built and attached by hand; the workflow is what keeps `main` buildable. Conventions worth knowing before changing code: -- The server is plain ESM (`.mjs`) with no build step. Keep it framework-free and avoid - native modules; `node:sqlite` is deliberate, and `sharp` must stay optional. +- The server is plain ESM (`.mjs`) with no build step. Keep it framework-free; native + modules stay optional — `node:sqlite` is deliberate, `sharp` must stay optional, and + `onnxruntime-node` is loaded lazily and only for SCUNet. - The client is strict TypeScript with `noEmit`; Vite builds only `src/` and `public/`. - Edits are data, not pixels: adding a control means extending `src/types.ts`, the renderer uniforms/shaders, `normalizeEdits()` defaults, the export path and the panel @@ -1213,7 +1245,9 @@ full CC BY-SA 3.0 text. Before distributing Luminary or its container image: (OFL-1.1) and DejaVu Sans Mono (Bitstream Vera licence) — with any redistributed copy. 7. Record the terms of the `server/denoise/` pipeline's `raw-noise` origin; it is not - published on npm and its licence is currently undocumented here. + published on npm and its licence is currently undocumented here. The SCUNet weights + and ONNX Runtime are already catalogued in `THIRD_PARTY_NOTICES.md`; ship that file + and the model's `.onnx.data` shard with the app. ### No endorsement diff --git a/THIRD_PARTY_NOTICES.md b/THIRD_PARTY_NOTICES.md index fb9bf15..4c61f5a 100644 --- a/THIRD_PARTY_NOTICES.md +++ b/THIRD_PARTY_NOTICES.md @@ -24,8 +24,17 @@ Versions are those resolved in `package-lock.json`; the lens database pin is | libvips (bundled in `sharp` binaries) | shipped by `sharp` 0.35.5 | LGPL-2.1-or-later | © libvips contributors — https://github.com/libvips/libvips | | `exifr` | 7.1.3 | MIT | © 2020 Mike Kovařík, Mutiny.cz — https://github.com/MikeKovarik/exifr | | `nodemailer` | 7.0.13 | MIT-0 | © 2011-2023 Andris Reinman — https://github.com/nodemailer/nodemailer | +| `onnxruntime-node` (ONNX Runtime native libraries) | 1.23.0 | MIT | © Microsoft Corporation — https://github.com/microsoft/onnxruntime | +| SCUNet colour-denoise weights (`server/denoise/scunet_color_25.onnx`) | `scunet_color_25` | Apache-2.0 | © Kai Zhang and SCUNet contributors — https://github.com/cszn/SCUNet; ONNX export https://github.com/Heliosoph/scunet-onnx | | React / React DOM | 18.3.1 | MIT | © Facebook, Inc. and its affiliates — https://github.com/facebook/react | +`onnxruntime-node` is pulled in only by the optional SCUNet denoise base; the Guided and +NLM bases are plain TypeScript. Its install step is skipped in the Docker image and the +desktop bundles (`ONNXRUNTIME_NODE_INSTALL=skip`), so only the CPU runtime that ships in +the package is distributed. The SCUNet model is a converted export of the upstream +Apache-2.0 weights and keeps that licence; its `.onnx` file and the external `.onnx.data` +shard are one artefact and must travel together. + The lens database is a separate asset from Luminary's code: CC BY-SA 3.0 applies to Lensfun's calibration data, not to the correction engine that reads it. Attribution and share-alike requirements are summarised in the README under @@ -138,9 +147,9 @@ the following restrictions: ### Apache-2.0 -Applies to `sharp` and TypeScript. The full text is included verbatim in -[`licenses/Apache-2.0.txt`](licenses/Apache-2.0.txt), copied from the licence that -`sharp` ships. +Applies to `sharp`, TypeScript and the SCUNet denoise weights. The full text is included +verbatim in [`licenses/Apache-2.0.txt`](licenses/Apache-2.0.txt), copied from the licence +that `sharp` ships. ### ISC @@ -172,6 +181,6 @@ and libvips notices with it. ## Trademarks -Lensfun, LibRaw, libvips, sharp, React, Node.js, Debian, Liberation and DejaVu are the -marks of their respective owners. They are used only to identify the software +Lensfun, LibRaw, libvips, sharp, ONNX Runtime, SCUNet, Microsoft, React, Node.js, +Debian, Liberation and DejaVu are the marks of their respective owners. They are used only to identify the software involved; Luminary is not affiliated with or endorsed by any of them. diff --git a/docs/user-guide/guide.html b/docs/user-guide/guide.html index c54ac57..2f33802 100644 --- a/docs/user-guide/guide.html +++ b/docs/user-guide/guide.html @@ -722,7 +722,9 @@ Sharpen — DetailHow much fine structure is included; lower values protect smooth areas. Noise reduction — LuminanceSmooths luminance noise at the cost of fine detail. Noise reduction — DetailHow much texture survives the smoothing. - DenoiseDetail-preserving pass that runs on the server for difficult high-ISO frames; the result is cached per parameter set. + DenoiseDetail-preserving pass that runs on the server for difficult high-ISO frames; the result is cached per model, so switching back to a model you already rendered is instant. + AI denoise — ModelGuided (default, fastest, keeps the most fine texture), SCUNet (learned model, removes the most grain and smooths more) or NLM (non-local means, between the two). Pick one and press Generate; the model is saved with the photo. + AI denoise — AmountBlends the rendered result into the frame. The server always renders at full strength, so the slider is instant and never re-runs the model. @@ -1244,7 +1246,7 @@ previews/<id>.p16.png16-bit sidecar: the decoded samples before JPEG quantisation. previews/<id>.t16.pngCamera-native grid thumbnail generated from the sidecar. thumbs/<id>.jpgGrid thumbnail. - denoised/<id>.<hash>.jpgCached denoise result per parameter set. + denoised/<id>.<hash>.jpgCached denoise result, one per model (Guided, SCUNet, NLM) per photo. proofs/, proofThumbs/Published client proofs and their thumbnails. tether/<event>/The tethered capture drop folder. secret.keyGenerated key sealing SMTP and API credentials. Back it up with the database. diff --git a/linux/build.mjs b/linux/build.mjs index 7937dbe..dbb3321 100644 --- a/linux/build.mjs +++ b/linux/build.mjs @@ -237,11 +237,14 @@ function installLinuxDeps(bundle) { cpSync(path.join(ROOT, 'package-lock.json'), path.join(appDir, 'package-lock.json')); log('deps', 'npm ci --omit=dev --os=linux --cpu=x64 (sharp linux-x64 prebuild)'); // --ignore-scripts is safe: sharp 0.35 has no install step, it resolves the - // prebuilt binary through optionalDependencies. + // prebuilt binary through optionalDependencies. ONNXRUNTIME_NODE_INSTALL=skip + // also keeps onnxruntime-node's postinstall from pulling the CUDA libraries; + // the package already ships its CPU binaries. run( NPM, ['ci', '--omit=dev', '--os=linux', '--cpu=x64', '--no-audit', '--no-fund', '--ignore-scripts'], appDir, + { ONNXRUNTIME_NODE_INSTALL: 'skip' }, ); // .bin shims are for an interactive shell, not for `node server/index.mjs`. rmSync(path.join(appDir, 'node_modules', '.bin'), { recursive: true, force: true }); @@ -529,6 +532,16 @@ function debCopyright() { 'License: MIT', ' The full MIT licence text is in /opt/luminary/LICENSE.', '', + 'Files: opt/luminary/app/node_modules/onnxruntime-node/*', + 'Copyright: Microsoft Corporation', + 'License: MIT', + ' ONNX Runtime; see /opt/luminary/THIRD_PARTY_NOTICES.md.', + '', + 'Files: opt/luminary/app/server/denoise/scunet_color_25.onnx*', + 'Copyright: Kai Zhang and SCUNet contributors', + 'License: Apache-2.0', + ' See /opt/luminary/THIRD_PARTY_NOTICES.md.', + '', ].join('\n'); } diff --git a/macos/build.mjs b/macos/build.mjs index d907601..f19bc6f 100644 --- a/macos/build.mjs +++ b/macos/build.mjs @@ -333,11 +333,14 @@ function installDeps(appDir, archs, outDir) { log('deps', `npm ci --omit=dev --os=darwin --cpu=${archs[0]} (sharp darwin-${archs[0]})`); // sharp resolves its prebuilt binary through optionalDependencies, so npm can - // fetch the target architecture's package from any host. + // fetch the target architecture's package from any host. The ONNX skip keeps + // the postinstall from downloading the CUDA build; CPU binaries ship in the + // package. run( 'npm', ['ci', '--omit=dev', '--os=darwin', `--cpu=${archs[0]}`, '--ignore-scripts', '--no-audit', '--no-fund'], appDir, + { ONNXRUNTIME_NODE_INSTALL: 'skip' }, ); rmSync(path.join(appDir, 'node_modules', '.bin'), { recursive: true, force: true }); @@ -353,6 +356,7 @@ function installDeps(appDir, archs, outDir) { 'npm', ['ci', '--omit=dev', '--os=darwin', `--cpu=${arch}`, '--ignore-scripts', '--no-audit', '--no-fund'], side, + { ONNXRUNTIME_NODE_INSTALL: 'skip' }, ); for (const pkg of [`@img/sharp-darwin-${arch}`, `@img/sharp-libvips-darwin-${arch}`]) { const from = path.join(side, 'node_modules', pkg); diff --git a/package-lock.json b/package-lock.json index 4ad05e9..1a73d24 100644 --- a/package-lock.json +++ b/package-lock.json @@ -12,6 +12,7 @@ "exifr": "^7.1.3", "libraw-wasm": "^1.6.0", "nodemailer": "^10.6.1", + "onnxruntime-node": "1.23.0", "react": "^18.3.1", "react-dom": "^18.3.1", "sharp": "^0.35.5" @@ -819,9 +820,6 @@ "cpu": [ "arm" ], - "libc": [ - "glibc" - ], "license": "LGPL-3.0-or-later", "optional": true, "os": [ @@ -838,9 +836,6 @@ "cpu": [ "arm64" ], - "libc": [ - "glibc" - ], "license": "LGPL-3.0-or-later", "optional": true, "os": [ @@ -857,9 +852,6 @@ "cpu": [ "ppc64" ], - "libc": [ - "glibc" - ], "license": "LGPL-3.0-or-later", "optional": true, "os": [ @@ -876,9 +868,6 @@ "cpu": [ "riscv64" ], - "libc": [ - "glibc" - ], "license": "LGPL-3.0-or-later", "optional": true, "os": [ @@ -895,9 +884,6 @@ "cpu": [ "s390x" ], - "libc": [ - "glibc" - ], "license": "LGPL-3.0-or-later", "optional": true, "os": [ @@ -914,9 +900,6 @@ "cpu": [ "x64" ], - "libc": [ - "glibc" - ], "license": "LGPL-3.0-or-later", "optional": true, "os": [ @@ -933,9 +916,6 @@ "cpu": [ "arm64" ], - "libc": [ - "musl" - ], "license": "LGPL-3.0-or-later", "optional": true, "os": [ @@ -952,9 +932,6 @@ "cpu": [ "x64" ], - "libc": [ - "musl" - ], "license": "LGPL-3.0-or-later", "optional": true, "os": [ @@ -971,9 +948,6 @@ "cpu": [ "arm" ], - "libc": [ - "glibc" - ], "license": "Apache-2.0", "optional": true, "os": [ @@ -996,9 +970,6 @@ "cpu": [ "arm64" ], - "libc": [ - "glibc" - ], "license": "Apache-2.0", "optional": true, "os": [ @@ -1021,9 +992,6 @@ "cpu": [ "ppc64" ], - "libc": [ - "glibc" - ], "license": "Apache-2.0", "optional": true, "os": [ @@ -1046,9 +1014,6 @@ "cpu": [ "riscv64" ], - "libc": [ - "glibc" - ], "license": "Apache-2.0", "optional": true, "os": [ @@ -1071,9 +1036,6 @@ "cpu": [ "s390x" ], - "libc": [ - "glibc" - ], "license": "Apache-2.0", "optional": true, "os": [ @@ -1096,9 +1058,6 @@ "cpu": [ "x64" ], - "libc": [ - "glibc" - ], "license": "Apache-2.0", "optional": true, "os": [ @@ -1121,9 +1080,6 @@ "cpu": [ "arm64" ], - "libc": [ - "musl" - ], "license": "Apache-2.0", "optional": true, "os": [ @@ -1146,9 +1102,6 @@ "cpu": [ "x64" ], - "libc": [ - "musl" - ], "license": "Apache-2.0", "optional": true, "os": [ @@ -1419,9 +1372,6 @@ "arm" ], "dev": true, - "libc": [ - "glibc" - ], "license": "MIT", "optional": true, "os": [ @@ -1436,9 +1386,6 @@ "arm" ], "dev": true, - "libc": [ - "musl" - ], "license": "MIT", "optional": true, "os": [ @@ -1453,9 +1400,6 @@ "arm64" ], "dev": true, - "libc": [ - "glibc" - ], "license": "MIT", "optional": true, "os": [ @@ -1470,9 +1414,6 @@ "arm64" ], "dev": true, - "libc": [ - "musl" - ], "license": "MIT", "optional": true, "os": [ @@ -1487,9 +1428,6 @@ "loong64" ], "dev": true, - "libc": [ - "glibc" - ], "license": "MIT", "optional": true, "os": [ @@ -1504,9 +1442,6 @@ "loong64" ], "dev": true, - "libc": [ - "musl" - ], "license": "MIT", "optional": true, "os": [ @@ -1521,9 +1456,6 @@ "ppc64" ], "dev": true, - "libc": [ - "glibc" - ], "license": "MIT", "optional": true, "os": [ @@ -1538,9 +1470,6 @@ "ppc64" ], "dev": true, - "libc": [ - "musl" - ], "license": "MIT", "optional": true, "os": [ @@ -1555,9 +1484,6 @@ "riscv64" ], "dev": true, - "libc": [ - "glibc" - ], "license": "MIT", "optional": true, "os": [ @@ -1572,9 +1498,6 @@ "riscv64" ], "dev": true, - "libc": [ - "musl" - ], "license": "MIT", "optional": true, "os": [ @@ -1589,9 +1512,6 @@ "s390x" ], "dev": true, - "libc": [ - "glibc" - ], "license": "MIT", "optional": true, "os": [ @@ -1606,9 +1526,6 @@ "x64" ], "dev": true, - "libc": [ - "glibc" - ], "license": "MIT", "optional": true, "os": [ @@ -1623,9 +1540,6 @@ "x64" ], "dev": true, - "libc": [ - "musl" - ], "license": "MIT", "optional": true, "os": [ @@ -1930,6 +1844,15 @@ "url": "https://opencollective.com/vitest" } }, + "node_modules/adm-zip": { + "version": "0.5.18", + "resolved": "https://registry.npmjs.org/adm-zip/-/adm-zip-0.5.18.tgz", + "integrity": "sha512-ufJnssQGbxzLNS1Ho9bCtX4rQKCCvoVuDLHoJyc3F9dOGDB4BkWs2Ci0kv53lqocAEQ/Cbi+I2XCsNYGqVYqng==", + "license": "MIT", + "engines": { + "node": ">=12.0" + } + }, "node_modules/assertion-error": { "version": "2.0.1", "resolved": "https://registry.npmjs.org/assertion-error/-/assertion-error-2.0.1.tgz", @@ -1953,6 +1876,13 @@ "node": ">=6.0.0" } }, + "node_modules/boolean": { + "version": "3.2.0", + "resolved": "https://registry.npmjs.org/boolean/-/boolean-3.2.0.tgz", + "integrity": "sha512-d0II/GO9uf9lfUHH2BQsjxzRJZBdsjgsBiW4BvhWk/3qoKwQFjIDVN19PfX8F2D/r9PCMTtLWjYVCFrpeYUzsw==", + "deprecated": "Package no longer supported. Contact Support at https://www.npmjs.com/support for more info.", + "license": "MIT" + }, "node_modules/browserslist": { "version": "4.29.6", "resolved": "https://registry.npmjs.org/browserslist/-/browserslist-4.29.6.tgz", @@ -2087,6 +2017,40 @@ "node": ">=6" } }, + "node_modules/define-data-property": { + "version": "1.1.4", + "resolved": "https://registry.npmjs.org/define-data-property/-/define-data-property-1.1.4.tgz", + "integrity": "sha512-rBMvIzlpA8v6E+SJZoo++HAYqsLrkg7MSfIinMPFhmkorw7X+dOXVJQs+QT69zGkzMyfDnIMN2Wid1+NbL3T+A==", + "license": "MIT", + "dependencies": { + "es-define-property": "^1.0.0", + "es-errors": "^1.3.0", + "gopd": "^1.0.1" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/define-properties": { + "version": "1.2.1", + "resolved": "https://registry.npmjs.org/define-properties/-/define-properties-1.2.1.tgz", + "integrity": "sha512-8QmQKqEASLd5nx0U1B1okLElbUuuttJ/AnYmRXbbbGDWh6uS208EjD4Xqq/I9wK7u0v6O08XhTWnt5XtEbR6Dg==", + "license": "MIT", + "dependencies": { + "define-data-property": "^1.0.1", + "has-property-descriptors": "^1.0.0", + "object-keys": "^1.1.1" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, "node_modules/detect-libc": { "version": "2.1.2", "resolved": "https://registry.npmjs.org/detect-libc/-/detect-libc-2.1.2.tgz", @@ -2096,6 +2060,12 @@ "node": ">=8" } }, + "node_modules/detect-node": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/detect-node/-/detect-node-2.1.0.tgz", + "integrity": "sha512-T0NIuQpnTvFDATNuHN5roPwSBG83rFsuO+MXXH9/3N1eFbn4wcPjttvjMLEPWJ0RGUYgQE7cGgS3tNxbqCGM7g==", + "license": "MIT" + }, "node_modules/electron-to-chromium": { "version": "1.5.492", "resolved": "https://registry.npmjs.org/electron-to-chromium/-/electron-to-chromium-1.5.492.tgz", @@ -2103,6 +2073,24 @@ "dev": true, "license": "ISC" }, + "node_modules/es-define-property": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/es-define-property/-/es-define-property-1.0.1.tgz", + "integrity": "sha512-e3nRfgfUZ4rNGL232gUgX06QNyyez04KdjFrF+LTRoOXmrOgFKDg4BCdsjW8EnT69eqdYGmRpJwiPVYNrCaW3g==", + "license": "MIT", + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/es-errors": { + "version": "1.3.0", + "resolved": "https://registry.npmjs.org/es-errors/-/es-errors-1.3.0.tgz", + "integrity": "sha512-Zf5H2Kxt2xjTvbJvP2ZWLEICxA6j+hAmMzIlypy4xcBg1vKVnx89Wy0GbS+kf5cwCVFFzdCFh2XSCFNULS6csw==", + "license": "MIT", + "engines": { + "node": ">= 0.4" + } + }, "node_modules/es-module-lexer": { "version": "1.7.0", "resolved": "https://registry.npmjs.org/es-module-lexer/-/es-module-lexer-1.7.0.tgz", @@ -2110,6 +2098,12 @@ "dev": true, "license": "MIT" }, + "node_modules/es6-error": { + "version": "4.1.1", + "resolved": "https://registry.npmjs.org/es6-error/-/es6-error-4.1.1.tgz", + "integrity": "sha512-Um/+FxMr9CISWh0bi5Zv0iOD+4cFh5qLeks1qhAopKVAJw3drgKbKySikp7wGhDL0HPeaja0P5ULZrxLkniUVg==", + "license": "MIT" + }, "node_modules/esbuild": { "version": "0.21.5", "resolved": "https://registry.npmjs.org/esbuild/-/esbuild-0.21.5.tgz", @@ -2159,6 +2153,18 @@ "node": ">=6" } }, + "node_modules/escape-string-regexp": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/escape-string-regexp/-/escape-string-regexp-4.0.0.tgz", + "integrity": "sha512-TtpcNJ3XAzx3Gq8sWRzJaVajRs0uVxA2YAkdb1jm2YkPz4G6egUFAyA3n5vtEIZefPk5Wa4UXbKuS5fKkJWdgA==", + "license": "MIT", + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, "node_modules/estree-walker": { "version": "3.0.3", "resolved": "https://registry.npmjs.org/estree-walker/-/estree-walker-3.0.3.tgz", @@ -2210,6 +2216,75 @@ "node": ">=6.9.0" } }, + "node_modules/global-agent": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/global-agent/-/global-agent-3.0.0.tgz", + "integrity": "sha512-PT6XReJ+D07JvGoxQMkT6qji/jVNfX/h364XHZOWeRzy64sSFr+xJ5OX7LI3b4MPQzdL4H8Y8M0xzPpsVMwA8Q==", + "license": "BSD-3-Clause", + "dependencies": { + "boolean": "^3.0.1", + "es6-error": "^4.1.1", + "matcher": "^3.0.0", + "roarr": "^2.15.3", + "semver": "^7.3.2", + "serialize-error": "^7.0.1" + }, + "engines": { + "node": ">=10.0" + } + }, + "node_modules/global-agent/node_modules/semver": { + "version": "7.8.6", + "resolved": "https://registry.npmjs.org/semver/-/semver-7.8.6.tgz", + "integrity": "sha512-9lpSSU4Mly3mrtruwLs1eLK6+gzbzqeBFwRNjIjE+9LuDpWdYctrQlQ3ej1Ilgi7gknpsTRnPoLP8DpCHqHIJw==", + "license": "ISC", + "bin": { + "semver": "bin/semver.js" + }, + "engines": { + "node": ">=10" + } + }, + "node_modules/globalthis": { + "version": "1.0.4", + "resolved": "https://registry.npmjs.org/globalthis/-/globalthis-1.0.4.tgz", + "integrity": "sha512-DpLKbNU4WylpxJykQujfCcwYWiV/Jhm50Goo0wrVILAv5jOr9d+H+UR3PhSCD2rCCEIg0uc+G+muBTwD54JhDQ==", + "license": "MIT", + "dependencies": { + "define-properties": "^1.2.1", + "gopd": "^1.0.1" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/gopd": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/gopd/-/gopd-1.2.0.tgz", + "integrity": "sha512-ZUKRh6/kUFoAiTAtTYPZJ3hw9wNxx+BIBOijnlG9PnrJsCcSjs1wyyD6vJpaYtgnzDrKYRSqf3OO6Rfa93xsRg==", + "license": "MIT", + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/has-property-descriptors": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/has-property-descriptors/-/has-property-descriptors-1.0.2.tgz", + "integrity": "sha512-55JNKuIW+vq4Ke1BjOTjM2YctQIvCT7GFzHwmfZPGo5wnrgkid0YQtnAleFSqumZm4az3n2BS+erby5ipJdgrg==", + "license": "MIT", + "dependencies": { + "es-define-property": "^1.0.0" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, "node_modules/js-tokens": { "version": "4.0.0", "resolved": "https://registry.npmjs.org/js-tokens/-/js-tokens-4.0.0.tgz", @@ -2229,6 +2304,12 @@ "node": ">=6" } }, + "node_modules/json-stringify-safe": { + "version": "5.0.1", + "resolved": "https://registry.npmjs.org/json-stringify-safe/-/json-stringify-safe-5.0.1.tgz", + "integrity": "sha512-ZClg6AaYvamvYEE82d3Iyd3vSSIjQ+odgjaTzRuO3s7toCdFKczob2i0zCh7JE8kWn17yvAWhUVxvqGwUalsRA==", + "license": "ISC" + }, "node_modules/json5": { "version": "2.2.3", "resolved": "https://registry.npmjs.org/json5/-/json5-2.2.3.tgz", @@ -2287,6 +2368,18 @@ "@jridgewell/sourcemap-codec": "^1.5.5" } }, + "node_modules/matcher": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/matcher/-/matcher-3.0.0.tgz", + "integrity": "sha512-OkeDaAZ/bQCxeFAozM55PKcKU0yJMPGifLwV4Qgjitu+5MoAfSQN4lsLJeXZ1b8w0x+/Emda6MZgXS1jvsapng==", + "license": "MIT", + "dependencies": { + "escape-string-regexp": "^4.0.0" + }, + "engines": { + "node": ">=10" + } + }, "node_modules/ms": { "version": "2.1.3", "resolved": "https://registry.npmjs.org/ms/-/ms-2.1.3.tgz", @@ -2332,6 +2425,38 @@ "node": ">=20.0.0" } }, + "node_modules/object-keys": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/object-keys/-/object-keys-1.1.1.tgz", + "integrity": "sha512-NuAESUOUMrlIXOfHKzD6bpPu3tYt3xvjNdRIQ+FeT0lNb4K8WR70CaDxhuNguS2XG+GjkyMwOzsN5ZktImfhLA==", + "license": "MIT", + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/onnxruntime-common": { + "version": "1.23.0", + "resolved": "https://registry.npmjs.org/onnxruntime-common/-/onnxruntime-common-1.23.0.tgz", + "integrity": "sha512-Auz8S9D7vpF8ok7fzTobvD1XdQDftRf/S7pHmjeCr3Xdymi4z1C7zx4vnT6nnUjbpelZdGwda0BmWHCCTMKUTg==", + "license": "MIT" + }, + "node_modules/onnxruntime-node": { + "version": "1.23.0", + "resolved": "https://registry.npmjs.org/onnxruntime-node/-/onnxruntime-node-1.23.0.tgz", + "integrity": "sha512-j7QVuR4ouektZjOopKtXcIGsB3C6R9kVbgS10lc2e5SxoWMUhmCwxNl4qBslpWJaPrFxvrQrQaQLQdqku8V19w==", + "hasInstallScript": true, + "license": "MIT", + "os": [ + "win32", + "darwin", + "linux" + ], + "dependencies": { + "adm-zip": "^0.5.16", + "global-agent": "^3.0.0", + "onnxruntime-common": "1.23.0" + } + }, "node_modules/pathe": { "version": "1.1.2", "resolved": "https://registry.npmjs.org/pathe/-/pathe-1.1.2.tgz", @@ -2420,6 +2545,23 @@ "node": ">=0.10.0" } }, + "node_modules/roarr": { + "version": "2.15.4", + "resolved": "https://registry.npmjs.org/roarr/-/roarr-2.15.4.tgz", + "integrity": "sha512-CHhPh+UNHD2GTXNYhPWLnU8ONHdI+5DI+4EYIAOaiD63rHeYlZvyh8P+in5999TTSFgUYuKUAjzRI4mdh/p+2A==", + "license": "BSD-3-Clause", + "dependencies": { + "boolean": "^3.0.1", + "detect-node": "^2.0.4", + "globalthis": "^1.0.1", + "json-stringify-safe": "^5.0.1", + "semver-compare": "^1.0.0", + "sprintf-js": "^1.1.2" + }, + "engines": { + "node": ">=8.0" + } + }, "node_modules/rollup": { "version": "4.68.7", "resolved": "https://registry.npmjs.org/rollup/-/rollup-4.68.7.tgz", @@ -2485,6 +2627,27 @@ "semver": "bin/semver.js" } }, + "node_modules/semver-compare": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/semver-compare/-/semver-compare-1.0.0.tgz", + "integrity": "sha512-YM3/ITh2MJ5MtzaM429anh+x2jiLVjqILF4m4oyQB18W7Ggea7BfqdH/wGMK7dDiMghv/6WG7znWMwUDzJiXow==", + "license": "MIT" + }, + "node_modules/serialize-error": { + "version": "7.0.1", + "resolved": "https://registry.npmjs.org/serialize-error/-/serialize-error-7.0.1.tgz", + "integrity": "sha512-8I8TjW5KMOKsZQTvoxjuSIa7foAwPWGOts+6o7sgjz41/qMD9VQHEDxi6PBvK2l0MXUmqZyNpUK+T2tQaaElvw==", + "license": "MIT", + "dependencies": { + "type-fest": "^0.13.1" + }, + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, "node_modules/sharp": { "version": "0.35.5", "resolved": "https://registry.npmjs.org/sharp/-/sharp-0.35.5.tgz", @@ -2563,6 +2726,12 @@ "node": ">=6.0.0" } }, + "node_modules/sprintf-js": { + "version": "1.1.3", + "resolved": "https://registry.npmjs.org/sprintf-js/-/sprintf-js-1.1.3.tgz", + "integrity": "sha512-Oo+0REFV59/rz3gfJNKQiBlwfHaSESl1pcGyABQsnnIfWOFt6JNj5gCog2U6MLZ//IGYD+nA8nI+mTShREReaA==", + "license": "BSD-3-Clause" + }, "node_modules/stackback": { "version": "0.0.2", "resolved": "https://registry.npmjs.org/stackback/-/stackback-0.0.2.tgz", @@ -2628,6 +2797,18 @@ "license": "0BSD", "optional": true }, + "node_modules/type-fest": { + "version": "0.13.1", + "resolved": "https://registry.npmjs.org/type-fest/-/type-fest-0.13.1.tgz", + "integrity": "sha512-34R7HTnG0XIJcBSn5XhDd7nNFPRcXYRZrBB2O2jdKqYODldSzBAqzsWoZYYvduky73toYS/ESqxPvkDf/F0XMg==", + "license": "(MIT OR CC0-1.0)", + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, "node_modules/typescript": { "version": "5.9.3", "resolved": "https://registry.npmjs.org/typescript/-/typescript-5.9.3.tgz", diff --git a/package.json b/package.json index b372977..69339b7 100644 --- a/package.json +++ b/package.json @@ -24,6 +24,7 @@ "exifr": "^7.1.3", "libraw-wasm": "^1.6.0", "nodemailer": "^10.6.1", + "onnxruntime-node": "1.23.0", "react": "^18.3.1", "react-dom": "^18.3.1", "sharp": "^0.35.5" diff --git a/server/denoise-worker.mjs b/server/denoise-worker.mjs index c46bcd6..ef3c9da 100644 --- a/server/denoise-worker.mjs +++ b/server/denoise-worker.mjs @@ -10,10 +10,10 @@ import { parentPort, workerData } from 'node:worker_threads'; import fs from 'node:fs/promises'; import sharp from 'sharp'; import { denoiseRgb } from './denoise/rgbPipeline.ts'; -import { guidedDenoiser } from './denoise/standin.ts'; +import { createBaseDenoiser } from './denoise/baseDenoiser.ts'; try { - const { sourcePath, outPath } = workerData; + const { sourcePath, outPath, base = 'guided' } = workerData; const buffer = await fs.readFile(sourcePath); const { data, info } = await sharp(buffer) .rotate() @@ -37,8 +37,21 @@ try { const started = performance.now(); // Always full strength: the Amount slider blends on the client, so one render - // serves every setting and the cache key does not move with the slider. - const out = await denoiseRgb({ rgb, width, height }, { amount: 1 }, guidedDenoiser()); + // serves every setting and the cache key does not move with the slider. The + // base denoiser (guided / nlm / scunet) is chosen by the request; the cache + // key already folds it in, so a different model is a different render. + // + // Progress is the only window the panel has into a 95 s SCUNet run, so both + // the stage boundaries and the tile counter are forwarded to the job. + const report = (progress) => parentPort?.postMessage({ type: 'progress', progress }); + const out = await denoiseRgb( + { rgb, width, height }, + { amount: 1 }, + createBaseDenoiser(base, (tiles) => + report({ stage: 'base', done: tiles.done, total: tiles.total }), + ), + (stage) => report({ stage }), + ); // 4:4:4 so the chroma work is not immediately thrown away by the encoder. const jpeg = await sharp(Buffer.from(out.rgb), { raw: { width, height, channels: 3 } }) .jpeg({ quality: 95, chromaSubsampling: '4:4:4' }) diff --git a/server/denoise.mjs b/server/denoise.mjs index e3a9e1f..109c5cd 100644 --- a/server/denoise.mjs +++ b/server/denoise.mjs @@ -1,11 +1,13 @@ /** * Job runner for the detail-preserving denoise. * - * `server/denoise/` is a verbatim copy of the dependency-free pipeline from the - * raw-noise package. It reconstructs from a per-pixel crossfade between the - * source and a denoised base, so the result is bounded by the original pixels and - * cannot ring or overshoot; flat noise is replaced, structure is given back - * verbatim. The GPU's own `noise` sliders are a separate, much simpler path. + * `server/denoise/` starts from the dependency-free pipeline of the raw-noise + * package, which supplies the Guided and NLM bases; SCUNet runs the same stages + * around an ONNX model. Every base is reconstructed from a per-pixel crossfade + * between the source and the denoised base, so the result is bounded by the + * original pixels and cannot ring or overshoot; flat noise is replaced, structure + * is given back verbatim. The GPU's own `noise` sliders are a separate, much + * simpler path. * * Three things here are deliberate: * @@ -33,6 +35,9 @@ export function clearDenoised(photoId) { return removeDenoised(photoId); } +/** Every base the picker offers; the cache keeps one render for each of them. */ +export const DENOISE_BASES = ['guided', 'scunet', 'nlm']; + /** * Bump whenever the copied modules under `server/denoise/` change output. The key * is the only thing between a fixed pipeline and a stale cached file. @@ -59,23 +64,23 @@ export function getDenoiseJob(id) { return jobs.get(id) ?? null; } -/** Stable for a photo and a pipeline version -- Amount is the client's business. */ -export function denoiseKey(photoId) { +/** Stable for a photo, a pipeline version and a base denoiser -- Amount is the client's business. */ +export function denoiseKey(photoId, base = 'guided') { return crypto .createHash('sha1') - .update(`${photoId}|${PIPELINE_VERSION}`) + .update(`${photoId}|${PIPELINE_VERSION}|${base}`) .digest('hex') .slice(0, 12); } -export function startDenoise({ photoId, sourcePath }) { - const key = denoiseKey(photoId); +export function startDenoise({ photoId, sourcePath, base = 'guided' }) { + const key = denoiseKey(photoId, base); const joined = byKey.get(key); if (joined) return joined; const url = `/api/photos/${encodeURIComponent(photoId)}/denoised?v=${key}`; - const job = { id: crypto.randomUUID(), photoId, key, state: 'running', startedAt: Date.now() }; + const job = { id: crypto.randomUUID(), photoId, key, base, state: 'running', startedAt: Date.now() }; // Re-running after the edit was cleared, or a second browser, should not pay // for the CPU again. The file is the cache; the job just reports it. @@ -108,19 +113,26 @@ function run(job) { active += 1; const outPath = denoisedPath(job.photoId, job.key); const worker = new Worker(new URL('./denoise-worker.mjs', import.meta.url), { - workerData: { sourcePath: job.sourcePath, outPath }, + workerData: { sourcePath: job.sourcePath, outPath, base: job.base }, }); worker.on('message', (message) => { - if (message?.type === 'done') { + if (message?.type === 'progress') { + job.progress = message.progress; + } else if (message?.type === 'done') { job.state = 'done'; + job.progress = null; job.ms = message.ms; job.bytes = message.bytes; job.stats = message.stats; - // A version bump (or an older build) leaves its render behind; keep the - // current one and drop the rest so the folder cannot grow without bound. + // A version bump (or an older build) leaves its render behind. Keep the + // current key of every base and drop only the older ones, so switching + // models reuses its cached render instead of paying for the CPU again. try { - removeDenoised(job.photoId, job.key); + removeDenoised( + job.photoId, + DENOISE_BASES.map((base) => denoiseKey(job.photoId, base)), + ); } catch { /* cleanup is best effort -- never fail a finished job over it */ } diff --git a/server/denoise/baseDenoiser.ts b/server/denoise/baseDenoiser.ts new file mode 100644 index 0000000..a9d891d --- /dev/null +++ b/server/denoise/baseDenoiser.ts @@ -0,0 +1,38 @@ +/** + * Resolve a base denoiser by name -- the slot the pipeline calls as `runBase`. + * + * Three choices, all occupying the same interface from `standin.ts`: + * + * - `guided` (default): the classical guided filter. Fast, edge-preserving, + * the current shipping path. + * - `nlm`: non-local means. Slower, the quality reference the model must beat. + * - `scunet`: the learned SCUNet model, run tiled with overlap-add. + * + * Constructing is free: the ONNX session is created lazily on first use, so the + * model selector can show all three even before a run ever picks SCUNet. A + * missing model surfaces as a clear error at run time, not at import time. + */ + +import { fileURLToPath } from 'node:url'; +import { guidedDenoiser, nlmDenoiser, type BaseDenoiser } from './standin.ts'; +import { createOnnxBaseDenoiser, type TileProgress } from './onnx.ts'; + +export type BaseDenoiserName = 'guided' | 'nlm' | 'scunet'; + +/** The SCUNet weights shipped with the server, next to this file. */ +const SCUNET_MODEL = fileURLToPath(new URL('./scunet_color_25.onnx', import.meta.url)); + +export function createBaseDenoiser( + base: BaseDenoiserName, + onProgress?: (progress: TileProgress) => void, +): BaseDenoiser { + switch (base) { + case 'nlm': + return nlmDenoiser(); + case 'scunet': + return createOnnxBaseDenoiser({ modelPath: SCUNET_MODEL, tile: 256, overlap: 32, onProgress }); + case 'guided': + default: + return guidedDenoiser(); + } +} diff --git a/server/denoise/onnx.ts b/server/denoise/onnx.ts new file mode 100644 index 0000000..a804c00 --- /dev/null +++ b/server/denoise/onnx.ts @@ -0,0 +1,205 @@ +/** + * Tiled ONNX inference for the base plane -- the SCUNet path. + * + * This is the only file that may import `onnxruntime-node`, and it imports it + * lazily: nothing here requires a model to exist until a denoiser is actually + * asked to run. The classical stand-ins (`guided`, `nlm`) occupy the same slot + * and need no model at all, so the model selector is safe to show even before a + * run ever selects SCUNet. + * + * The model contract is fixed and small: + * + * input 1 x 3 x TILE x TILE float32, RGB in 0..1 + * output 1 x 3 x TILE x TILE float32, same + * + * `runTiled` is separated from the session so the tiling, padding, feathering + * and normalisation can be reasoned about independently of ORT. + */ + +import type { BaseDenoiser, BaseImage } from './standin.ts'; + +/** Runs one `tile x tile`, 3-channel tile. Input and output are interleaved RGB. */ +export type RgbTileRunner = (input: Float32Array, tile: number) => Promise; + +export interface TileProgress { + done: number; + total: number; +} + +export interface OnnxBaseOptions { + modelPath: string; + /** Fixed square size the graph was exported at. Must match the graph. */ + tile?: number; + /** Overlap in pixels between neighbouring tiles. */ + overlap?: number; + /** Defaults to physical cores. Keep it below the host's raw decode pool. */ + intraOpThreads?: number; + /** Called after each tile lands, so a long run can report where it is. */ + onProgress?: (progress: TileProgress) => void; +} + +/** + * Raised-cosine feather along one axis, floored so no pixel is weighted zero. + * + * The floor matters: at the image border a tile is the only contributor, and a + * zero weight there would divide 0 by 0. + */ +export function featherWeights(tile: number, overlap: number): Float32Array { + const weights = new Float32Array(tile).fill(1); + const edge = Math.min(Math.max(0, overlap), Math.floor(tile / 2)); + for (let i = 0; i < edge; i++) { + const t = (i + 0.5) / edge; + weights[i] = Math.max(0.5 - 0.5 * Math.cos(Math.PI * t), 1e-3); + weights[tile - 1 - i] = weights[i]; + } + return weights; +} + +/** Tiled inference with overlap-add and feathering. */ +export async function runTiled( + runTile: RgbTileRunner, + image: BaseImage, + tile: number, + overlap: number, + onProgress?: (progress: TileProgress) => void, +): Promise { + const { width, height } = image; + if (!Number.isInteger(tile) || tile < 8) throw new Error(`tile must be an integer >= 8, got ${tile}`); + if (overlap < 0 || overlap >= tile) throw new Error(`overlap must be in [0, tile), got ${overlap}`); + + const expected = 3 * tile * tile; + const step = tile - overlap; + const weights = featherWeights(tile, overlap); + + const acc = new Float32Array(3 * width * height); + const weight = new Float32Array(width * height); + const patch = new Float32Array(expected); + // Tiles start every `step` pixels, so the last one may hang off the edge. + const total = Math.ceil(width / step) * Math.ceil(height / step); + let done = 0; + + for (let ty = 0; ty < height; ty += step) { + for (let tx = 0; tx < width; tx += step) { + // Gather with clamp-to-edge padding; the convolution needs a full tile + // even when the tile hangs off the right or bottom edge. + for (let y = 0; y < tile; y++) { + const sy = ty + y; + const cy = sy < 0 ? 0 : sy >= height ? height - 1 : sy; + for (let x = 0; x < tile; x++) { + const sx = tx + x; + const cx = sx < 0 ? 0 : sx >= width ? width - 1 : sx; + const src = (cy * width + cx) * 3; + const dst = (y * tile + x) * 3; + patch[dst] = image.rgb[src]; + patch[dst + 1] = image.rgb[src + 1]; + patch[dst + 2] = image.rgb[src + 2]; + } + } + + const out = await runTile(patch, tile); + if (out.length !== expected) { + throw new Error(`tile runner returned ${out.length} values, expected ${expected}`); + } + + for (let y = 0; y < tile; y++) { + const sy = ty + y; + if (sy < 0 || sy >= height) continue; + for (let x = 0; x < tile; x++) { + const sx = tx + x; + if (sx < 0 || sx >= width) continue; + const w = weights[y] * weights[x]; + const dst = (sy * width + sx) * 3; + const src = (y * tile + x) * 3; + acc[dst] += out[src] * w; + acc[dst + 1] += out[src + 1] * w; + acc[dst + 2] += out[src + 2] * w; + weight[sy * width + sx] += w; + } + } + done += 1; + onProgress?.({ done, total }); + } + } + + const rgb = new Float32Array(3 * width * height); + for (let i = 0, p = 0; i < width * height; i++, p += 3) { + const w = weight[i] || 1; + for (let k = 0; k < 3; k++) { + const v = acc[p + k] / w; + rgb[p + k] = v < 0 ? 0 : v > 255 ? 255 : v; + } + } + return { rgb, width, height }; +} + +interface Session { + run(feeds: Record): Promise>; + inputNames: readonly string[]; + outputNames: readonly string[]; +} + +/** + * Build a `BaseDenoiser` backed by an ONNX model. + * + * The session is created on first use and memoised, so constructing this is + * free and a missing model surfaces as a clear error at run time rather than at + * import time. + */ +export function createOnnxBaseDenoiser(options: OnnxBaseOptions): BaseDenoiser { + const tile = options.tile ?? 256; + const overlap = options.overlap ?? 32; + let sessionPromise: Promise | null = null; + + const session = (): Promise => { + if (!sessionPromise) { + sessionPromise = (async () => { + const ort = await import('onnxruntime-node'); + const created = await ort.InferenceSession.create(options.modelPath, { + executionProviders: ['cpu'], + graphOptimizationLevel: 'all', + intraOpNumThreads: options.intraOpThreads ?? 0, + }); + return created as unknown as Session; + })(); + } + return sessionPromise; + }; + + return async (image: BaseImage): Promise => { + const active = await session(); + const ort = await import('onnxruntime-node'); + const inputName = active.inputNames[0]; + const outputName = active.outputNames[0]; + if (!inputName || !outputName) throw new Error('model has no input/output'); + + // The model expects 0..1; everything above works in 0..255. + // + // But the two sides disagree about layout: `runTiled` is interleaved (HWC), + // while every published denoiser is NCHW (`1x3xTILExTILE`). Handing HWC bytes + // to a `[1,3,T,T]` tensor does not throw -- it silently feeds a scrambled + // image, so channel 0 holds a third of every row rather than red. The output + // needs the mirror transpose for the same reason. + const plane = tile * tile; + const runTile: RgbTileRunner = async (input, size) => { + const normalised = new Float32Array(3 * plane); + for (let p = 0, i = 0; p < plane; p++, i += 3) { + normalised[p] = input[i] / 255; + normalised[plane + p] = input[i + 1] / 255; + normalised[2 * plane + p] = input[i + 2] / 255; + } + const tensor = new ort.Tensor('float32', normalised, [1, 3, size, size]); + const result = await active.run({ [inputName]: tensor }); + const output = result[outputName]?.data; + if (!output) throw new Error(`model produced no output named ${outputName}`); + const scaled = new Float32Array(output.length); + for (let p = 0, i = 0; p < plane; p++, i += 3) { + scaled[i] = output[p] * 255; + scaled[i + 1] = output[plane + p] * 255; + scaled[i + 2] = output[2 * plane + p] * 255; + } + return scaled; + }; + + return runTiled(runTile, image, tile, overlap, options.onProgress); + }; +} diff --git a/server/denoise/rgbPipeline.ts b/server/denoise/rgbPipeline.ts index e67ebe8..4f0f587 100644 --- a/server/denoise/rgbPipeline.ts +++ b/server/denoise/rgbPipeline.ts @@ -105,6 +105,13 @@ export interface DenoiseStats { timings: StageTimings; } +/** + * Where a run currently is. The base stage is the expensive one (SCUNet runs it + * tile by tile); the rest are seconds at most, but naming them beats a dead + * spinner while the base is between tiles. + */ +export type DenoiseStage = 'analyse' | 'base' | 'gate' | 'render'; + export interface DenoiseOutput { rgb: Uint8Array; /** Luma of the denoised base, before detail re-injection, for inspection. */ @@ -184,6 +191,7 @@ export async function denoiseRgb( image: RgbImage, options: Partial, runBase: BaseDenoiser, + onStage?: (stage: DenoiseStage) => void, ): Promise { const opts: DenoiseOptions = { ...DEFAULT_OPTIONS, ...options, gate: { ...DEFAULT_GATE, ...options.gate } }; const started = now(); @@ -193,6 +201,7 @@ export async function denoiseRgb( const { y, cb, cr } = toYcc(image); let mark = now(); + onStage?.('analyse'); const noise: NoiseModel = estimateNoise(y, width, height); const timings: StageTimings = { noise: now() - mark, @@ -231,6 +240,7 @@ export async function denoiseRgb( const decimatedSigma = backscale > 1.001 ? (prefilterWidth - 1 / 3) / (prefilterWidth * prefilterWidth) : 1; const baseSigma = noise.sigmaAt(110) * decimatedSigma; + onStage?.('base'); const baseOut = await runBase(baseInput, baseSigma); const baseUp = toYcc(upsampleBase(baseOut, width, height)); timings.base = now() - mark; @@ -266,6 +276,7 @@ export async function denoiseRgb( timings.structure = now() - mark; mark = now(); + onStage?.('gate'); let gate = detailGate(detail, width, height, sigmaMap, coherence, opts.gate); // Second, coarser band: `smooth2 - smooth6` is a band-pass around 3-8 px. It @@ -292,6 +303,7 @@ export async function denoiseRgb( const autoGate = opts.cleanSigma > 0 ? smoothstep(0.8, opts.cleanSigma, noise.global) : 1; const amount = clamp01(opts.amount) * autoGate; + onStage?.('render'); const outY = new Float32Array(pixels); const outCb = new Float32Array(pixels); const outCr = new Float32Array(pixels); diff --git a/server/denoise/scunet_color_25.onnx b/server/denoise/scunet_color_25.onnx new file mode 100644 index 0000000..10433b3 Binary files /dev/null and b/server/denoise/scunet_color_25.onnx differ diff --git a/server/denoise/scunet_color_25.onnx.data b/server/denoise/scunet_color_25.onnx.data new file mode 100644 index 0000000..a2a1521 Binary files /dev/null and b/server/denoise/scunet_color_25.onnx.data differ diff --git a/server/index.mjs b/server/index.mjs index 3ad2389..f960a7e 100644 --- a/server/index.mjs +++ b/server/index.mjs @@ -2475,10 +2475,14 @@ route('POST', '/api/photos/:id/denoise', async ({ req, res, params }) => { if (!ownedBy(photoOwner(params.id), user)) return error(res, 404, 'Not found'); // Denoise the proxy the editor actually shows, not the raw: the result has to // line up pixel for pixel with the canvas and with the client's export path. - // The Amount slider is the client's: the render is always full strength. + // The Amount slider is the client's: the render is always full strength. The + // base denoiser (guided / nlm / scunet) is chosen here and folded into the + // cache key, so each model renders to its own asset. const source = findPreview(params.id) ?? findOriginal(params.id); if (!source) return error(res, 404, 'Nothing to denoise'); - const job = startDenoise({ photoId: params.id, sourcePath: source }); + const body = await readJson(req).catch(() => ({})); + const base = body?.base === 'nlm' || body?.base === 'scunet' ? body.base : 'guided'; + const job = startDenoise({ photoId: params.id, sourcePath: source, base }); return json(res, 202, { jobId: job.id, state: job.state }); }); @@ -2496,6 +2500,12 @@ route('GET', '/api/denoise/jobs/:id', async ({ req, res, params }) => { error: job.error ?? null, url: job.url ?? null, stats: job.stats ?? null, + // Where a long run is, so the panel can name the stage instead of showing a + // spinner with no truth in it. + progress: job.progress ?? null, + // Without this the panel cannot tell a reused render from a fresh one and + // reports "Denoise ready" for both. + cached: Boolean(job.cached), }); }); diff --git a/server/storage.mjs b/server/storage.mjs index 6166cc6..aed7073 100644 --- a/server/storage.mjs +++ b/server/storage.mjs @@ -199,16 +199,21 @@ export function findDenoised(id, key) { return path.join(dir, names[0]); } -/** Remove every denoised render for a photo, sparing `keepKey` if given. */ -export function removeDenoised(id, keepKey) { +/** + * Remove denoised renders for a photo, sparing the keys named in `keepKeys`. + * A single key is accepted too; with none, every render for the photo goes. + */ +export function removeDenoised(id, keepKeys) { const safe = lookupId(id); if (!safe) return 0; const dir = path.join(storageRoot(), 'denoised'); - const key = keepKey ? String(keepKey).replace(/[^a-z0-9]/gi, '') : null; - const keep = key ? `${safe}.${key}.jpg` : null; + const keys = (Array.isArray(keepKeys) ? keepKeys : keepKeys ? [keepKeys] : []) + .map((key) => String(key).replace(/[^a-z0-9]/gi, '')) + .filter(Boolean); + const keep = new Set(keys.map((key) => `${safe}.${key}.jpg`)); let removed = 0; for (const name of listFiles(dir)) { - if (!name.startsWith(`${safe}.`) || name === keep) continue; + if (!name.startsWith(`${safe}.`) || keep.has(name)) continue; fs.rmSync(path.join(dir, name), { force: true }); removed += 1; } diff --git a/src/components/Panels.tsx b/src/components/Panels.tsx index 2625aca..ea1cc8b 100644 --- a/src/components/Panels.tsx +++ b/src/components/Panels.tsx @@ -3,6 +3,13 @@ import { ASPECTS, BW_FILTERS, HUE_BANDS, identityCurve, MAX_LOCAL_COMPONENTS, MA import { computeAutoEdits, computeAutoWhiteBalance } from '../lib/auto'; import { autoNoiseFor } from '../lib/noiseProfile'; import { clearDenoised, getDenoiseJob, startDenoise } from '../lib/api'; +import { + DENOISE_MODELS, + denoiseProgressLabel, + withDenoiseRender, + type DenoiseModel, +} from '../lib/denoiseModels'; +import type { DenoiseProgress } from '../lib/api'; import { clamp } from '../lib/curves'; import type { CurveChannel, @@ -610,34 +617,60 @@ export function EffectsPanel({ edits, photo, set, grainFreeze }: PanelSetProps & export function DetailPanel({ edits, photo, set }: PanelSetProps) { const [aiBusy, setAiBusy] = useState(false); const [aiNote, setAiNote] = useState(null); + const [aiStartedAt, setAiStartedAt] = useState(null); + const [aiElapsed, setAiElapsed] = useState(0); + const [aiProgress, setAiProgress] = useState(null); const aiActive = Boolean(edits.aiDenoise.key); + // A render reports no progress of its own, so the elapsed time is the one + // honest measurement the panel can show. It ticks only while one is running: + // a full-size frame is seconds of solid CPU on the server, not a spinner. + useEffect(() => { + if (aiStartedAt == null) return; + setAiElapsed(0); + const timer = window.setInterval( + () => setAiElapsed(Math.round((performance.now() - aiStartedAt) / 1000)), + 1000, + ); + return () => window.clearInterval(timer); + }, [aiStartedAt]); + // Poll rather than stream: the job is seconds long, and a failed poll just // leaves the previous note on screen instead of breaking the panel. - const generateAi = async () => { + const generateAi = async (base: DenoiseModel = edits.aiDenoise.model) => { if (aiBusy) return; setAiBusy(true); - setAiNote('Rendering the denoised version on the server…'); + setAiStartedAt(performance.now()); + setAiProgress(null); + setAiNote(null); try { - const { jobId } = await startDenoise(photo.id); + const { jobId } = await startDenoise(photo.id, base); for (let attempt = 0; attempt < 180; attempt++) { await new Promise((resolve) => setTimeout(resolve, 1000)); const job = await getDenoiseJob(jobId); + // The worker names its stage and counts SCUNet tiles; poll it rather than + // inventing a percentage on the client. + if (job.state === 'running') setAiProgress(job.progress ?? null); if (job.state === 'done') { - set({ aiDenoise: { ...edits.aiDenoise, key: job.key } }, 'AI denoise'); + // `edits` here is the render captured when the run started -- before + // the chip click that picked the model was committed. Spreading it + // writes the previous model back, so an SCUNet render would flip the + // picker to Guided on completion. The key belongs to one specific + // base, so pin the model to the base that actually rendered. + set({ aiDenoise: withDenoiseRender(edits.aiDenoise, base, job.key) }, 'AI denoise'); // The pipeline tapers itself down on frames it measures as clean. That // taper is in the rendered file now, so report it -- the Amount slider // multiplies it rather than replacing it. const applied = job.stats?.autoGate ?? 1; - const base = job.cached + const note = job.cached ? 'Using the cached version' : job.ms != null ? `Cleaned in ${(job.ms / 1000).toFixed(1)}s` : 'Denoise ready'; setAiNote( applied < 0.95 - ? `${base} · clean frame, correction reduced to ${Math.round(applied * 100)}%` - : base, + ? `${note} · clean frame, correction reduced to ${Math.round(applied * 100)}%` + : note, ); return; } @@ -650,6 +683,8 @@ export function DetailPanel({ edits, photo, set }: PanelSetProps) { } catch (err) { setAiNote(err instanceof Error ? err.message : 'Denoise failed'); } finally { + setAiStartedAt(null); + setAiProgress(null); setAiBusy(false); } }; @@ -747,12 +782,31 @@ export function DetailPanel({ edits, photo, set }: PanelSetProps) { +
+ {/* One render belongs to one model: switching mid-run would leave a chip + selected with no render behind it. */} + {DENOISE_MODELS.map((opt) => ( + + ))} +
{aiActive ? ( ) : null}

- {aiNote ?? + {aiBusy ? ( + <> + {denoiseProgressLabel(aiProgress, edits.aiDenoise.model, aiElapsed)}. A full-size frame + can take a minute or two; the picker unlocks when it lands. + + ) : ( + aiNote ?? (aiActive ? 'Detail-preserving denoise, rendered from the full proxy.' - : 'Removes noise only where there is no structure to keep.')} + : 'Removes noise only where there is no structure to keep.') + )}

{aiActive ? (