Offer SCUNet and NLM alongside the guided denoise

The AI denoise panel now picks between three bases: the existing guided
filter, non-local means and a learned SCUNet model run through
onnxruntime-node on overlapping tiles. The base is part of the render key, so
each model keeps its own cached render and switching back is instant, and jobs
report stage and tile progress instead of a bare spinner.

onnxruntime-node is pinned to 1.23.0, the last release that ships both macOS
architectures, and every Docker and desktop install skips its CUDA download
because only the CPU binaries in the package are used. The SCUNet weights and
ONNX Runtime are added to the third-party notices, the deb copyright file and
the README's denoise, API and redistribution sections.
This commit is contained in:
2026-12-01 04:03:53 +00:00
parent b34d34dacb
commit f7942d0bd0
26 changed files with 945 additions and 161 deletions
+72 -11
View File
@@ -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<string | null>(null);
const [aiStartedAt, setAiStartedAt] = useState<number | null>(null);
const [aiElapsed, setAiElapsed] = useState(0);
const [aiProgress, setAiProgress] = useState<DenoiseProgress | null>(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) {
<button
className="chip tiny"
disabled={aiBusy}
onClick={generateAi}
title="Clean up noise while keeping edges and fine texture"
onClick={() => void generateAi()}
title="Clean up noise with a detail-preserving model"
>
{aiBusy ? 'Working…' : aiActive ? 'Regenerate' : 'Generate'}
</button>
</div>
<div className="model-picker" role="radiogroup" aria-label="AI denoise model">
{/* One render belongs to one model: switching mid-run would leave a chip
selected with no render behind it. */}
{DENOISE_MODELS.map((opt) => (
<button
key={opt.value}
type="button"
disabled={aiBusy}
className={`chip small ${edits.aiDenoise.model === opt.value ? 'on' : ''}`}
onClick={() => {
set({ aiDenoise: { ...edits.aiDenoise, model: opt.value } }, 'AI denoise model');
void generateAi(opt.value);
}}
title={opt.title}
>
{opt.label}
</button>
))}
</div>
{aiActive ? (
<Slider
label="Amount"
@@ -763,10 +817,17 @@ export function DetailPanel({ edits, photo, set }: PanelSetProps) {
/>
) : null}
<p className="muted small panel-hint">
{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.')
)}
</p>
{aiActive ? (
<button
+15 -2
View File
@@ -180,6 +180,13 @@ export interface ProofUpload {
}
/** Upload a rendered (edited) proof for the client gallery and owner grid. */
export interface DenoiseProgress {
stage: 'analyse' | 'base' | 'gate' | 'render';
/** Tile counter, present while the base model is running. */
done?: number;
total?: number;
}
export interface DenoiseJob {
id: string;
key: string;
@@ -187,14 +194,20 @@ export interface DenoiseJob {
ms: number | null;
error: string | null;
url: string | null;
/** Where the worker is inside the run; null once it finishes. */
progress?: DenoiseProgress | null;
/** Reported by a job that found the render already on disk. */
cached?: boolean;
stats: { amount: number; autoGate: number; gate: number; noise: number; baseWidth: number } | null;
}
/** Starts a server-side denoise job; the work runs off the request thread. */
export function startDenoise(photoId: string): Promise<{ jobId: string }> {
return request(`/api/photos/${encodeURIComponent(photoId)}/denoise`, { method: 'POST' });
export function startDenoise(photoId: string, base: 'guided' | 'nlm' | 'scunet' = 'guided'): Promise<{ jobId: string }> {
return request(`/api/photos/${encodeURIComponent(photoId)}/denoise`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ base }),
});
}
/** Drops the rendered files for a photo; the next run renders from scratch. */
+84
View File
@@ -0,0 +1,84 @@
import { describe, expect, it } from 'vitest';
import { defaultEdits, normalizeEdits } from './edits';
import {
DENOISE_MODELS,
denoiseModelLabel,
denoiseProgressLabel,
withDenoiseRender,
} from './denoiseModels';
describe('AI denoise edit normalization', () => {
it('keeps the model the user picked', () => {
for (const model of ['guided', 'scunet', 'nlm'] as const) {
expect(normalizeEdits({ aiDenoise: { model } } as never).aiDenoise.model).toBe(model);
}
});
it('defaults an unknown or missing model to guided', () => {
expect(normalizeEdits({}).aiDenoise.model).toBe('guided');
expect(normalizeEdits({ aiDenoise: {} } as never).aiDenoise.model).toBe('guided');
expect(normalizeEdits({ aiDenoise: { model: 'swinir' } } as never).aiDenoise.model).toBe(
'guided',
);
});
it('keeps the render key and the amount, and drops an unusable key', () => {
const kept = normalizeEdits({ aiDenoise: { model: 'nlm', key: 'abc123', amount: 40 } } as never);
expect(kept.aiDenoise).toEqual({ model: 'nlm', key: 'abc123', amount: 40 });
const dropped = normalizeEdits({ aiDenoise: { key: '' } } as never);
expect(dropped.aiDenoise.key).toBeNull();
});
});
describe('AI denoise model selection', () => {
it('commits the render under the base that produced it', () => {
// The regression: the panel's completion path used to spread a copy of the
// edit captured before the chip click, which put the previous model back.
const previous = { ...defaultEdits().aiDenoise, model: 'guided' as const, amount: 70 };
const next = withDenoiseRender(previous, 'scunet', 'key-scunet');
expect(next).toEqual({ model: 'scunet', key: 'key-scunet', amount: 70 });
expect(previous).toEqual({ model: 'guided', key: null, amount: 70 });
});
it('keeps a stale picker honest for every base', () => {
const previous = { ...defaultEdits().aiDenoise, model: 'guided' as const };
for (const option of DENOISE_MODELS) {
expect(withDenoiseRender(previous, option.value, `key-${option.value}`).model).toBe(
option.value,
);
}
});
it('names the stage and tile count a running render reports', () => {
expect(denoiseProgressLabel({ stage: 'base', done: 12, total: 40 }, 'scunet', 31)).toBe(
'Rendering with SCUNet · denoising 12/40 tiles · 31s elapsed',
);
expect(denoiseProgressLabel({ stage: 'gate' }, 'guided', 7.4)).toBe(
'Rendering with Guided · mapping detail · 7s elapsed',
);
// No tile counter for the classical models, and no stage at all before the
// first poll lands.
expect(denoiseProgressLabel({ stage: 'base' }, 'nlm', 2)).toBe(
'Rendering with NLM · denoising · 2s elapsed',
);
expect(denoiseProgressLabel(null, 'scunet', 0)).toBe(
'Rendering with SCUNet · starting · 0s elapsed',
);
// A worker that over-counts cannot report past the end of the run.
expect(denoiseProgressLabel({ stage: 'base', done: 99, total: 40 }, 'scunet', 90)).toContain(
'40/40 tiles',
);
});
it('offers each selectable model exactly once, with a label', () => {
const values = DENOISE_MODELS.map((option) => option.value);
expect(new Set(values).size).toBe(values.length);
expect(values).toEqual(['guided', 'scunet', 'nlm']);
for (const option of DENOISE_MODELS) {
expect(option.label, option.value).toBeTruthy();
expect(option.title, option.value).toBeTruthy();
expect(denoiseModelLabel(option.value)).toBe(option.label);
}
});
});
+57
View File
@@ -0,0 +1,57 @@
import type { DenoiseProgress } from './api';
import type { Edits } from '../types';
/** One of the base denoisers the AI denoise panel can render with. */
export type DenoiseModel = Edits['aiDenoise']['model'];
export type AiDenoise = Edits['aiDenoise'];
/**
* The models in panel order. `guided` is the default and the fast one; the two
* learned/classical alternates are additive, so the list is also the contract
* the picker and the help text are built from.
*/
export const DENOISE_MODELS: { value: DenoiseModel; label: string; title: string }[] = [
{ value: 'guided', label: 'Guided', title: 'Guided filter — fast, keeps the most fine texture' },
{ value: 'scunet', label: 'SCUNet', title: 'SCUNet — learned model, removes the most grain, smooths more' },
{ value: 'nlm', label: 'NLM', title: 'Non-local means — slower, between Guided and SCUNet' },
];
export function denoiseModelLabel(model: DenoiseModel): string {
return DENOISE_MODELS.find((option) => option.value === model)?.label ?? 'Guided';
}
/** Human names for the pipeline stages the worker reports. */
const STAGE_LABELS: Record<DenoiseProgress['stage'], string> = {
analyse: 'reading the noise profile',
base: 'denoising',
gate: 'mapping detail',
render: 'blending the result',
};
/**
* One line describing a running render. The stage names and the tile counter
* come from the worker, so this is real progress rather than a spinner -- the
* elapsed time is only the fallback for the first second or two.
*/
export function denoiseProgressLabel(
progress: DenoiseProgress | null | undefined,
model: DenoiseModel,
elapsedSeconds: number,
): string {
const seconds = Math.max(0, Math.round(elapsedSeconds));
const stage = progress?.stage ? (STAGE_LABELS[progress.stage] ?? 'working') : 'starting';
const tiles =
progress?.stage === 'base' && progress.total
? ` ${Math.min(progress.done ?? 0, progress.total)}/${progress.total} tiles`
: '';
return `Rendering with ${denoiseModelLabel(model)} · ${stage}${tiles} · ${seconds}s elapsed`;
}
/**
* Commit a finished render to the edit. The cache key belongs to the base that
* produced it, so the picker follows that base: a caller holding an older copy
* of the edit cannot put the previous model back in front of a fresh key.
*/
export function withDenoiseRender(ai: AiDenoise, base: DenoiseModel, key: string): AiDenoise {
return { ...ai, model: base, key };
}
+4 -1
View File
@@ -500,7 +500,10 @@ export function normalizeEdits(input: Partial<Edits> | undefined | null): Edits
aiDenoise: {
amount: num(aiDenoise.amount, d.aiDenoise.amount, 0, 100),
key: typeof aiDenoise.key === 'string' && aiDenoise.key ? aiDenoise.key : null,
model: 'guided',
model:
aiDenoise.model === 'guided' || aiDenoise.model === 'nlm' || aiDenoise.model === 'scunet'
? aiDenoise.model
: 'guided',
},
temp: num(input.temp, 0, -100, 100),
tint: num(input.tint, 0, -100, 100),
+15
View File
@@ -604,6 +604,21 @@ img {
font-size: 11px;
}
.model-picker {
display: flex;
gap: 3px;
padding: 3px;
margin: 2px 0 6px;
width: fit-content;
background: var(--panel-3);
border-radius: 6px;
}
.model-picker .chip {
border-radius: 3px;
font-size: 11px;
}
.color-filter {
display: flex;
gap: 5px;
+1 -1
View File
@@ -224,7 +224,7 @@ export interface Edits {
* generated asset and is null until one exists; `amount` blends it over the
* source. Separate from `noise`, which is a small GPU-side filter.
*/
aiDenoise: { amount: number; key: string | null; model: string };
aiDenoise: { amount: number; key: string | null; model: 'guided' | 'nlm' | 'scunet' };
/** fringe removal amounts for the two casts lens CA produces */
defringe: { purple: number; green: number };
/** spot healing, applied to the source before grading */