diff --git a/public/journal.html b/public/journal.html index 99eb9b1..6c47d52 100644 --- a/public/journal.html +++ b/public/journal.html @@ -23,8 +23,7 @@ .enhance-badge { position: absolute; top: 10px; padding: 3px 10px; border-radius: 999px; background: rgba(0,0,0,.55); color: #fff; font-size: .72rem; pointer-events: none; } .enhance-badge.left { left: 10px; } .enhance-badge.right { right: 10px; } -.enhance-loading { position: absolute; inset: 0; display: flex; align-items: center; justify-content: center; color: var(--muted); font-size: .85rem; background: rgba(255,255,255,.8); } -.enhance-loading::backdrop-filter { backdrop-filter: blur(2px); } +.enhance-loading { position: absolute; inset: 0; display: flex; align-items: center; justify-content: center; color: var(--muted); font-size: .85rem; background: rgba(255,255,255,.82); backdrop-filter: blur(2px); } .enhance-thinking { display: flex; flex-direction: column; align-items: center; gap: 12px; } .enhance-thinking-text { font-size: .9rem; } .enhance-thinking-dots { display: flex; gap: 6px; } @@ -35,6 +34,8 @@ @keyframes thinking-pulse { 0%, 80%, 100% { opacity: .4; transform: scale(.8); } 40% { opacity: 1; transform: scale(1); } } .enhance-progress { width: 180px; height: 4px; background: var(--border); border-radius: 2px; overflow: hidden; } .enhance-progress-bar { height: 100%; width: 0%; background: var(--accent); border-radius: 2px; transition: width .3s ease; } +.enhance-progress-bar.indeterminate { width: 38%; transition: none; animation: enhance-progress-slide 1.2s ease-in-out infinite; } +@keyframes enhance-progress-slide { 0% { transform: translateX(-105%); } 100% { transform: translateX(265%); } } .enhance-compare.enhance-flash::after { content: ''; position: absolute; inset: 0; background: #fff; opacity: 0; pointer-events: none; animation: enhance-flash 1.2s ease-out; z-index: 5; } @keyframes enhance-flash { 0% { opacity: .9; } 30% { opacity: 0; } 45% { opacity: .5; } 100% { opacity: 0; } } .enhance-sliders { flex: 0 0 240px; display: flex; flex-direction: column; gap: 14px; } @@ -42,6 +43,101 @@ .enhance-foot { justify-content: flex-end; gap: 8px; margin-top: 14px; } .enhance-ai-mode { width: auto; min-width: 200px; padding: 9px 12px; font-size: .85rem; } .enhance-ai-hint { font-size: .75rem; color: var(--muted); max-width: 340px; } +.cpu-enhance-modal { max-width: 1180px; width: 95vw; max-height: calc(100dvh - 40px); padding: 0; gap: 0; overflow-y: auto; overscroll-behavior: contain; } +.cpu-enhance-head { position: sticky; top: 0; z-index: 6; display: flex; align-items: center; gap: 14px; padding: 15px 20px; background: var(--card); border-bottom: 1px solid var(--border); } +.cpu-enhance-head-main { flex: 1 1 auto; min-width: 0; } +.cpu-enhance-head-main h3 { font-size: 1.05rem; font-weight: 600; margin: 0; } +.cpu-enhance-sub { font-size: .78rem; color: var(--muted); margin-top: 3px; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; } +.cpu-enhance-head-side { display: flex; align-items: center; gap: 8px; flex: 0 0 auto; } +.cpu-enhance-badge { font-size: .7rem; font-weight: 600; padding: 4px 10px; border-radius: 999px; white-space: nowrap; } +.cpu-enhance-badge.is-gpu { background: rgba(124,58,237,.14); color: #7c3aed; } +.cpu-enhance-badge.is-cpu { background: rgba(37,99,235,.14); color: var(--accent); } +.cpu-enhance-badge.is-warn { background: rgba(245,158,11,.16); color: #b45309; } +.cpu-enhance-x { display: inline-flex; align-items: center; justify-content: center; width: 32px; height: 32px; border-radius: 9px; border: none; background: transparent; color: var(--muted); cursor: pointer; transition: background .15s, color .15s; } +.cpu-enhance-x:hover { background: rgba(127,127,127,.16); color: var(--text); } +.cpu-enhance-x svg { width: 17px; height: 17px; } +.cpu-enhance-bodywrap { padding: 18px 20px; } +.cpu-enhance-stage { flex: 1 1 auto; min-width: 0; display: flex; flex-direction: column; gap: 10px; } +.cpu-enhance-compare { position: relative; flex: 1 1 auto; min-height: 220px; border-radius: 12px; overflow: hidden; background: var(--bg); border: 1px solid var(--border); user-select: none; touch-action: none; cursor: ew-resize; } +.cpu-enhance-compare:focus-visible { outline: 2px solid var(--accent); outline-offset: 2px; } +.cpu-enhance-layer { position: absolute; inset: 0; transform-origin: 0 0; will-change: transform; } +.cpu-enhance-layer > img { display: block; width: 100%; height: 100%; object-fit: contain; user-select: none; -webkit-user-drag: none; } +.cpu-enhance-top { position: absolute; inset: 0; overflow: hidden; z-index: 2; } +.cpu-enhance-empty { position: absolute; inset: 0; z-index: 3; display: flex; align-items: center; justify-content: center; padding: 16px; pointer-events: none; } +.cpu-enhance-empty[hidden] { display: none; } +.cpu-enhance-empty-card { display: flex; flex-direction: column; align-items: center; gap: 4px; text-align: center; max-width: 100%; padding: 14px 20px; border-radius: 12px; background: rgba(255,255,255,.93); backdrop-filter: blur(4px); border: 1px solid var(--border); box-shadow: 0 4px 16px rgba(0,0,0,.12); } +.cpu-enhance-empty-card svg { width: 24px; height: 24px; color: var(--accent); margin-bottom: 2px; } +.cpu-enhance-empty-card span { font-size: .86rem; font-weight: 600; color: var(--text); } +.cpu-enhance-empty-card small { font-size: .76rem; color: var(--muted); } +.cpu-enhance-divider { position: absolute; top: 0; bottom: 0; left: 50%; z-index: 4; width: 34px; transform: translateX(-50%); cursor: ew-resize; } +.cpu-enhance-divider::before { content: ''; position: absolute; top: 0; bottom: 0; left: 50%; width: 2px; transform: translateX(-50%); background: #fff; box-shadow: 0 0 6px rgba(0,0,0,.6); } +.cpu-enhance-handle { position: absolute; top: 50%; left: 50%; transform: translate(-50%,-50%); width: 32px; height: 32px; border-radius: 50%; background: #fff; color: #333; display: flex; align-items: center; justify-content: center; box-shadow: 0 2px 10px rgba(0,0,0,.45); pointer-events: none; } +.cpu-enhance-tools { position: absolute; top: 10px; right: 10px; z-index: 5; display: flex; flex-direction: column; align-items: flex-end; gap: 6px; } +.cpu-enhance-badge-tag { position: absolute; bottom: 10px; z-index: 5; padding: 3px 10px; border-radius: 999px; background: rgba(0,0,0,.55); color: #fff; font-size: .72rem; pointer-events: none; } +.cpu-enhance-badge-tag.left { left: 10px; } +.cpu-enhance-badge-tag.right { right: 10px; } +.cpu-enhance-compare.zoomed { cursor: grab; } +.cpu-enhance-compare.zoomed.panning { cursor: grabbing; } +.cpu-enhance-compare.view-orig .cpu-enhance-top, +.cpu-enhance-compare.view-orig .cpu-enhance-divider, +.cpu-enhance-compare.view-orig .cpu-enhance-badge-tag.right, +.cpu-enhance-compare.view-result .cpu-enhance-divider, +.cpu-enhance-compare.view-result .cpu-enhance-badge-tag.left { display: none; } +.cpu-enhance-compare.no-result .cpu-enhance-divider, +.cpu-enhance-compare.no-result .cpu-enhance-badge-tag.right { display: none; } +.cpu-enhance-meta { display: flex; flex-wrap: wrap; gap: 6px; } +.cpu-enhance-meta:empty { display: none; } +.cpu-enhance-chip { display: inline-flex; align-items: baseline; gap: 5px; padding: 4px 9px; border-radius: 8px; background: var(--bg); border: 1px solid var(--border); font-size: .74rem; color: var(--muted); } +.cpu-enhance-chip b { color: var(--text); font-weight: 600; font-variant-numeric: tabular-nums; } +.cpu-enhance-chip.is-wide { flex: 1 1 100%; } +.cpu-enhance-side { flex: 0 0 300px; min-width: 0; display: flex; flex-direction: column; gap: 12px; } +.cpu-enhance-controls { display: flex; flex-direction: column; gap: 9px; } +.cpu-enhance-controls .settings-field { gap: 3px; } +.cpu-enhance-controls label { display: flex; align-items: baseline; justify-content: space-between; gap: 8px; font-size: .82rem; font-weight: 500; margin: 0; } +.cpu-enhance-controls label span { font-variant-numeric: tabular-nums; color: var(--muted); font-weight: 600; } +.cpu-enhance-controls input[type=range] { width: 100%; height: 22px; padding: 0; border: none; background: transparent; accent-color: var(--accent); cursor: pointer; } +.cpu-enhance-controls input[type=range]:focus-visible { outline: 2px solid var(--accent); outline-offset: 4px; border-radius: 4px; } +.cpu-enhance-controls .is-changed label { color: var(--accent); } +.cpu-enhance-controls .is-changed label span { color: var(--accent); } +.cpu-enhance-actions { display: grid; grid-template-columns: repeat(3, 1fr); gap: 8px; } +.cpu-enhance-actions button { justify-content: center; padding: 9px 6px; font-size: .82rem; } +.cpu-enhance-note { font-size: .76rem; line-height: 1.35; padding: 7px 10px; border-radius: 8px; } +.cpu-enhance-note[hidden] { display: none; } +.cpu-enhance-gpu-note { color: #6d28d9; background: rgba(124,58,237,.1); border: 1px solid rgba(124,58,237,.28); } +.cpu-enhance-error { color: #b91c1c; background: rgba(239,68,68,.1); border: 1px solid rgba(239,68,68,.32); display: flex; gap: 7px; align-items: flex-start; } +.cpu-enhance-error svg { width: 15px; height: 15px; flex: 0 0 auto; margin-top: 1px; } +.cpu-enhance-footwrap { position: sticky; bottom: 0; z-index: 6; padding: 10px 20px 12px; background: var(--card); border-top: 1px solid var(--border); } +.cpu-enhance-foot { margin: 0; padding: 10px 0 0; border-top: 1px solid var(--border); } +.cpu-enhance-foot #cpuEnhanceRestoreBtn { margin-right: auto; } +.cpu-enhance-status { display: flex; align-items: center; gap: 9px; font-size: .8rem; color: var(--muted); } +.cpu-enhance-status-dot { width: 8px; height: 8px; border-radius: 50%; flex: 0 0 auto; background: #cbd5e1; transition: background .15s, box-shadow .15s; } +.cpu-enhance-status-text { flex: 1 1 auto; min-width: 0; } +.cpu-enhance-status.is-dirty .cpu-enhance-status-dot { background: #f59e0b; box-shadow: 0 0 0 3px rgba(245,158,11,.18); } +.cpu-enhance-status.is-dirty .cpu-enhance-status-text { color: #b45309; font-weight: 600; } +.cpu-enhance-status.is-ok .cpu-enhance-status-dot { background: #22c55e; box-shadow: 0 0 0 3px rgba(34,197,94,.18); } +.cpu-enhance-status.is-ok .cpu-enhance-status-text { color: var(--text); } +.cpu-enhance-keys { display: none; align-items: center; gap: 3px; flex: 0 0 auto; font-size: .72rem; white-space: nowrap; } +.cpu-enhance-keys span { margin: 0 8px 0 3px; } +.cpu-enhance-keys kbd { display: inline-block; min-width: 18px; padding: 1px 5px; border-radius: 5px; border: 1px solid var(--border); background: var(--bg); color: var(--muted); font-family: inherit; font-size: .7rem; text-align: center; } +.btn-primary.attention { box-shadow: 0 0 0 3px rgba(245,158,11,.4); } +.cpu-enhance-seg { display: inline-flex; align-items: stretch; border: 1px solid var(--border); border-radius: 8px; overflow: hidden; background: var(--card); } +.cpu-enhance-seg button { display: inline-flex; align-items: center; gap: 6px; border: none; background: transparent; color: var(--text); padding: 8px 11px; font-size: .8rem; cursor: pointer; white-space: nowrap; } +.cpu-enhance-seg button + button { border-left: 1px solid var(--border); } +.cpu-enhance-seg button:hover { background: rgba(37,99,235,.1); } +.cpu-enhance-seg button.active { background: rgba(37,99,235,.16); color: var(--accent); font-weight: 600; } +.cpu-enhance-seg button:focus-visible { outline: 2px solid var(--accent); outline-offset: -2px; } +.cpu-enhance-seg button svg, .cpu-enhance-seg button i { width: 15px; height: 15px; } +.cpu-enhance-modes { display: grid; grid-template-columns: repeat(3, 1fr); width: 100%; } +.cpu-enhance-modes button { justify-content: center; padding: 8px 4px; } +.cpu-enhance-zoom-level { min-width: 58px; justify-content: center; font-variant-numeric: tabular-nums; } +.cpu-enhance-loading { z-index: 7; border-radius: inherit; } +@media (min-width: 861px) { .cpu-enhance-keys { display: flex; } } +@media (max-width: 860px) { + .cpu-enhance-modal { width: 97vw; } + .cpu-enhance-compare { min-height: 180px; } + .cpu-enhance-side { flex: 1 1 auto; width: 100%; } + .cpu-enhance-actions { grid-template-columns: 1fr; } +} .photo-thumb { width: 56px; height: 56px; object-fit: cover; border-radius: 6px; border: 1px solid var(--border); display: block; } @media (max-width: 800px) { .enhance-body { flex-direction: column; } @@ -283,6 +379,114 @@ +
+ @@ -1344,6 +1346,744 @@ function closeEnhance() { if (loadingEl) loadingEl.style.display = 'none'; } +let cpuEnhanceEntryId = null; +let cpuEnhanceSaving = false; +let cpuEnhanceAiJobId = null; +let cpuEnhanceAiResultPath = null; +let cpuEnhancePreviewUrl = ''; +let cpuEnhanceParamsTouched = false; +let cpuEnhanceActiveKey = ''; +let cpuEnhanceDevice = { device: '', name: '', ready: false }; +let cpuEnhanceZoom = 1; +let cpuEnhancePanX = 0; +let cpuEnhancePanY = 0; +let cpuEnhanceView = 'split'; +let cpuEnhanceBusy = false; +let cpuEnhanceReturnFocus = null; + +const CPU_ENHANCE_SLIDERS = ['Quality', 'Clarity', 'Denoise', 'Sharp', 'Brightness', 'Contrast', 'Saturate', 'Warmth']; +const CPU_ENHANCE_DEFAULTS = { Quality: 92, Clarity: 40, Denoise: 0, Sharp: 30, Brightness: 100, Contrast: 100, Saturate: 100, Warmth: 0 }; +const CPU_ENHANCE_PREVIEW_MAX_PX = 1400; + +function cpuEnhanceSliderLabel(k) { + const el = document.getElementById('cpuEnhance' + k); + if (!el) return ''; + const v = parseInt(el.value, 10) || 0; + if (k === 'Warmth') return (v > 0 ? '+' : '') + v; + if (k === 'Quality') return v + '%'; + return String(v); +} + +function cpuEnhanceSyncSlider(k) { + const el = document.getElementById('cpuEnhance' + k); + if (!el) return; + const text = cpuEnhanceSliderLabel(k); + const out = document.getElementById('cpuEnhance' + k + 'Val'); + if (out) out.textContent = text; + el.setAttribute('aria-valuetext', text); + const field = el.closest('.settings-field'); + if (field) field.classList.toggle('is-changed', parseInt(el.value, 10) !== CPU_ENHANCE_DEFAULTS[k]); +} + +function cpuEnhanceHasResult() { + const el = document.getElementById('cpuEnhanceResult'); + return !!(el && el.getAttribute('src')); +} + +function cpuEnhanceSetResultSrc(src) { + const el = document.getElementById('cpuEnhanceResult'); + const empty = document.getElementById('cpuEnhanceEmpty'); + if (el) { + if (src) el.src = src; + else el.removeAttribute('src'); + } + const area = document.getElementById('cpuEnhanceCompare'); + if (area) area.classList.toggle('no-result', !src); + if (empty) empty.hidden = !!src; + if (!src && cpuEnhanceView !== 'orig') cpuEnhanceSetView('split'); +} + +function cpuEnhanceSetError(msg) { + const box = document.getElementById('cpuEnhanceError'); + const text = document.getElementById('cpuEnhanceErrorText'); + if (text) text.textContent = msg || ''; + if (box) box.hidden = !msg; +} + +function cpuEnhanceClearError() { + cpuEnhanceSetError(''); +} + +function cpuEnhanceFocusables() { + const modal = document.getElementById('cpuEnhanceModal'); + if (!modal) return []; + return [...modal.querySelectorAll('button:not([disabled]),input:not([disabled]),select:not([disabled]),textarea:not([disabled]),[tabindex]:not([tabindex="-1"])')] + .filter(el => el.offsetParent !== null || el.id === 'cpuEnhanceCompare'); +} + +function cpuEnhanceReadParams() { + const get = id => document.getElementById('cpuEnhance' + id); + const num = id => parseInt(get(id).value, 10) || 0; + const mode = get('Mode').value; + const preset = mode === 'cpu' ? 'quality' : 'auto'; + const params = { + preset, + scale: parseInt(get('Scale').value, 10) || 1, + quality: num('Quality'), + clarity: num('Clarity'), + denoise: num('Denoise'), + sharp: num('Sharp'), + brightness: num('Brightness'), + contrast: num('Contrast'), + saturate: num('Saturate'), + warmth: num('Warmth'), + }; + return params; +} + +async function cpuEnhanceProbeDevice() { + cpuEnhanceDevice = { device: '', name: '', ready: false }; + try { + const res = await fetch(`${API}/api/photo-ai/health`, { headers: hdr() }); + if (!res.ok) throw new Error('health ' + res.status); + const h = await res.json(); + const dev = String(h && h.device ? h.device : ''); + if (dev.startsWith('cuda')) cpuEnhanceDevice = { device: dev, name: String(h.device_name || 'GPU'), ready: true, gpu: true }; + else if (dev === 'mps') cpuEnhanceDevice = { device: dev, name: String(h.device_name || 'Apple GPU'), ready: true, gpu: true }; + else cpuEnhanceDevice = { device: dev || 'cpu', name: String((h && h.device_name) || 'CPU'), ready: false, gpu: false }; + } catch (e) { + cpuEnhanceDevice = { device: 'cpu', name: 'CPU (фото-ИИ недоступно)', ready: false, gpu: false }; + } + cpuEnhanceSetMode(cpuEnhanceDevice.gpu ? 'ai' : 'auto'); + return cpuEnhanceDevice; +} + +let cpuEnhanceBaseImg = null; +let cpuEnhanceBaseKind = 'orig'; + +function cpuEnhanceNum(id) { + const el = document.getElementById('cpuEnhance' + id); + return el ? parseInt(el.value, 10) || 0 : 0; +} + +function cpuEnhanceWarmthFilter(v) { + if (!v) return ''; + const t = Math.max(-100, Math.min(100, v)) / 100; + const sep = 'sepia(' + Math.round(Math.abs(t) * 0.7) + ')'; + return t > 0 ? 'sepia(' + Math.round(t * 0.5) + ') hue-rotate(' + Math.round(-8 * t) + 'deg) saturate(' + (1 + t * 0.25) + ')' : sep + ' hue-rotate(' + Math.round(8 * Math.abs(t)) + 'deg) saturate(1.1)'; +} + +function cpuEnhanceUnsharpPass(ctx, w, h, amount) { + if (amount <= 0) return; + const img = ctx.getImageData(0, 0, w, h); + const src = img.data; + const out = new Uint8ClampedArray(src); + const row = w * 4; + const a = Math.max(0, Math.min(1, (amount / 100) * 0.9)); + for (let y = 1; y < h - 1; y++) { + for (let x = 1; x < w - 1; x++) { + const i = y * row + x * 4; + for (let ch = 0; ch < 3; ch++) { + const c = src[i + ch]; + const blur = (src[i - 4 + ch] + src[i + 4 + ch] + src[i - row + ch] + src[i + row + ch] + 2 * c) / 6; + out[i + ch] = c + (c - blur) * a * 2; + } + } + } + ctx.putImageData(new ImageData(out, w, h), 0, 0); +} + +let cpuEnhanceDrawRaf = 0; + +function cpuEnhanceDrawLocal() { + if (cpuEnhanceDrawRaf) return; + cpuEnhanceDrawRaf = requestAnimationFrame(() => { + cpuEnhanceDrawRaf = 0; + cpuEnhanceDrawLocalNow(); + }); +} + +function cpuEnhanceDrawLocalNow() { + const result = document.getElementById('cpuEnhanceResult'); + if (!result || !cpuEnhanceBaseImg) return; + const img = cpuEnhanceBaseImg; + const scale = Math.min(1, CPU_ENHANCE_PREVIEW_MAX_PX / (img.naturalWidth || 1)); + const w = Math.max(1, Math.round((img.naturalWidth || 1) * scale)); + const h = Math.max(1, Math.round((img.naturalHeight || 1) * scale)); + const canvas = document.createElement('canvas'); + canvas.width = w; + canvas.height = h; + const ctx = canvas.getContext('2d'); + + const brightness = cpuEnhanceNum('Brightness'); + const contrast = cpuEnhanceNum('Contrast'); + const saturate = cpuEnhanceNum('Saturate'); + const denoise = cpuEnhanceNum('Denoise'); + const sharp = cpuEnhanceNum('Sharp'); + const clarity = cpuEnhanceNum('Clarity'); + const warmth = cpuEnhanceNum('Warmth'); + + const filters = []; + if (brightness !== 100) filters.push('brightness(' + (brightness / 100) + ')'); + if (contrast !== 100) filters.push('contrast(' + (contrast / 100) + ')'); + if (saturate !== 100) filters.push('saturate(' + (saturate / 100) + ')'); + const wf = cpuEnhanceWarmthFilter(warmth); + if (wf) filters.push(wf); + ctx.filter = filters.join(' ') || 'none'; + ctx.drawImage(img, 0, 0, w, h); + ctx.filter = 'none'; + + if (denoise > 0) { + medianFilterPass(ctx, w, h); + if (denoise > 70) medianFilterPass(ctx, w, h); + } + if (clarity > 0) cpuEnhanceUnsharpPass(ctx, w, h, clarity); + if (sharp > 0) sharpenPass(ctx, w, h, sharp); + + const url = canvas.toDataURL('image/jpeg', Math.min(1, cpuEnhanceNum('Quality') / 100)); + cpuEnhanceSetResultSrc(url); +} + +function cpuEnhanceSetBaseImg(path) { + cpuEnhanceBaseImg = null; + cpuEnhanceBaseKind = 'orig'; + const img = new Image(); + img.onload = () => { + if (String(cpuEnhanceBaseKind) !== 'orig') return; + cpuEnhanceBaseImg = img; + cpuEnhanceDrawLocal(); + }; + img.onerror = () => { cpuEnhanceBaseImg = null; }; + img.src = `${API}${path}`; +} + +function cpuEnhanceAdoptPreviewAsBase() { + if (!cpuEnhancePreviewUrl) return; + const img = new Image(); + img.onload = () => { + cpuEnhanceBaseImg = img; + cpuEnhanceBaseKind = 'preview'; + }; + img.onerror = () => {}; + img.src = cpuEnhancePreviewUrl; +} + +function cpuEnhanceLoadAiBase() { + if (!cpuEnhanceAiResultPath) return; + const img = new Image(); + img.onload = () => { + cpuEnhanceBaseImg = img; + cpuEnhanceBaseKind = 'result'; + }; + img.onerror = () => {}; + img.src = `${API}${cpuEnhanceAiResultPath}`; +} + +function cpuEnhanceSetBase(src, kind) { + if (!src) return; + cpuEnhanceBaseImg = src; + cpuEnhanceBaseKind = kind === 'result' ? 'result' : 'orig'; + cpuEnhanceDrawLocal(); +} + +function cpuEnhanceParamsKey() { + return JSON.stringify(cpuEnhanceReadParams()); +} + +function cpuEnhanceIsDirty() { + return cpuEnhanceActiveKey !== cpuEnhanceParamsKey(); +} + +function cpuEnhanceSyncPending() { + const dirty = cpuEnhanceIsDirty(); + const ready = !!cpuEnhanceActiveKey; + const mode = (document.getElementById('cpuEnhanceMode') || {}).value || 'auto'; + const status = document.getElementById('cpuEnhanceStatus'); + const text = document.getElementById('cpuEnhanceStatusText'); + if (status) { + status.classList.toggle('is-dirty', dirty && ready); + status.classList.toggle('is-ok', ready && !dirty); + status.classList.toggle('is-idle', !ready); + } + if (text) { + if (!ready) text.textContent = 'Результата пока нет — настройте параметры и нажмите «Активировать»'; + else if (dirty) text.textContent = 'Параметры изменены — результат устарел, нажмите «Активировать»'; + else text.textContent = 'Результат готов — можно сохранять'; + } + const applyBtn = document.getElementById('cpuEnhanceApplyBtn'); + if (applyBtn) { + applyBtn.disabled = cpuEnhanceBusy || !ready || dirty; + applyBtn.title = !ready + ? 'Сначала получите результат — «Активировать»' + : dirty ? 'Параметры изменены: обновите результат через «Активировать»' : 'Сохранить результат к записи'; + } + const activateBtn = document.getElementById('cpuEnhanceActivateBtn'); + if (activateBtn) { + activateBtn.disabled = cpuEnhanceBusy; + activateBtn.classList.toggle('attention', dirty && ready && !cpuEnhanceBusy); + } + const previewBtn = document.getElementById('cpuEnhancePreviewBtn'); + if (previewBtn) { + const cpuOnly = mode === 'cpu'; + previewBtn.disabled = cpuEnhanceBusy || !cpuOnly; + previewBtn.title = cpuOnly + ? 'Серверный предпросмотр текущих параметров' + : 'Превью доступно только в режиме CPU — в режиме GPU жмите «Активировать»'; + } + const autoBtn = document.getElementById('cpuEnhanceAutoBtn'); + if (autoBtn) autoBtn.disabled = cpuEnhanceBusy; + const resetBtn = document.getElementById('cpuEnhanceResetBtn'); + if (resetBtn) resetBtn.disabled = cpuEnhanceBusy; +} + +function cpuEnhanceMarkApplied() { + cpuEnhanceActiveKey = cpuEnhanceParamsKey(); + cpuEnhanceSyncPending(); +} + +function cpuEnhanceMarkCleared() { + cpuEnhanceActiveKey = ''; + cpuEnhanceSyncPending(); +} + +function cpuEnhanceApplySuggested(s) { + const set = (id, v) => { + const el = document.getElementById('cpuEnhance' + id); + if (!el) return; + el.value = Math.max(parseInt(el.min, 10), Math.min(parseInt(el.max, 10), Math.round(v))); + cpuEnhanceSyncSlider(id); + }; + if (!s) return; + if (s.clarity !== undefined) set('Clarity', s.clarity); + if (s.denoise !== undefined) set('Denoise', s.denoise); + if (s.sharp !== undefined) set('Sharp', s.sharp); + if (s.brightness !== undefined) set('Brightness', s.brightness); + if (s.contrast !== undefined) set('Contrast', s.contrast); + if (s.saturate !== undefined) set('Saturate', s.saturate); +} + +function cpuEnhanceResetSliders(resetMode) { + CPU_ENHANCE_SLIDERS.forEach(k => { + const el = document.getElementById('cpuEnhance' + k); + if (!el) return; + el.value = CPU_ENHANCE_DEFAULTS[k]; + cpuEnhanceSyncSlider(k); + }); + const scale = document.getElementById('cpuEnhanceScale'); + if (scale) scale.value = '1'; + if (resetMode) cpuEnhanceSetMode('auto'); +} + +const CPU_ENHANCE_INFO_FMT = { + 'Среднее': v => Math.round(v) + ' / 255', + 'Контраст': v => Math.round(v), + 'Резкость': v => Number(v).toFixed(1), +}; + +function cpuEnhanceInfoValue(key, value) { + const fmt = CPU_ENHANCE_INFO_FMT[key]; + const n = Number(value); + if (fmt && Number.isFinite(n)) return fmt(n); + return String(value); +} + +function cpuEnhanceSetInfo(analyze, extra) { + const box = document.getElementById('cpuEnhanceInfo'); + if (!box) return; + const items = []; + if (analyze) { + items.push(['Размер', `${analyze.width}×${analyze.height}`]); + items.push(['Среднее', analyze.mean]); + items.push(['Контраст', analyze.stdev]); + items.push(['Резкость', analyze.sharpness]); + } + if (extra) items.push(...extra); + box.innerHTML = items.map(([k, v]) => { + const wide = String(v).length > 22 ? ' is-wide' : ''; + return `${esc(k)}: ${esc(cpuEnhanceInfoValue(k, v))}`; + }).join(''); +} + +function cpuEnhanceSetLoading(on, text, progress) { + const el = document.getElementById('cpuEnhanceLoading'); + const t = document.getElementById('cpuEnhanceLoadingText'); + const track = document.getElementById('cpuEnhanceProgress'); + const bar = document.getElementById('cpuEnhanceProgressBar'); + const modal = document.getElementById('cpuEnhanceModal'); + if (!el) return; + el.style.display = on ? '' : 'none'; + if (modal) modal.setAttribute('aria-busy', on ? 'true' : 'false'); + if (t && text) t.textContent = text; + if (track) track.hidden = !on; + if (bar) { + if (!on) { + bar.classList.remove('indeterminate'); + bar.style.width = '0%'; + } else if (typeof progress === 'number') { + bar.classList.remove('indeterminate'); + bar.style.width = Math.max(2, Math.min(100, progress)) + '%'; + } else { + bar.classList.add('indeterminate'); + } + } + cpuEnhanceSetBusy(!!on); +} + +function cpuEnhanceSetBusy(on) { + cpuEnhanceBusy = !!on; + CPU_ENHANCE_SLIDERS.forEach(k => { + const el = document.getElementById('cpuEnhance' + k); + if (el) el.disabled = cpuEnhanceBusy; + }); + const mode = document.getElementById('cpuEnhanceMode'); + const scale = document.getElementById('cpuEnhanceScale'); + if (scale) scale.disabled = cpuEnhanceBusy; + if (mode) mode.disabled = cpuEnhanceBusy; + document.querySelectorAll('#cpuEnhanceModeGroup button[data-cpu-mode]').forEach(b => { b.disabled = cpuEnhanceBusy; }); + cpuEnhanceSyncPending(); +} + +function cpuEnhanceSetClip(pct) { + const top = document.getElementById('cpuEnhanceTop'); + const divider = document.getElementById('cpuEnhanceDivider'); + if (!top || !divider) return; + const v = Math.max(0, Math.min(100, pct)); + top.style.clipPath = `inset(0 0 0 ${v}%)`; + divider.style.left = `${v}%`; +} + +function cpuEnhanceSetMode(mode) { + const m = mode === 'ai' || mode === 'cpu' ? mode : 'auto'; + const sel = document.getElementById('cpuEnhanceMode'); + if (sel) sel.value = m; + const gpuMode = m === 'ai' || m === 'auto'; + const gpuActive = gpuMode && !!cpuEnhanceDevice.gpu; + document.querySelectorAll('#cpuEnhanceModeGroup button[data-cpu-mode]').forEach(b => { + const on = b.dataset.cpuMode === m; + b.classList.toggle('active', on); + b.setAttribute('aria-pressed', on ? 'true' : 'false'); + }); + const note = document.getElementById('cpuEnhanceGpuNote'); + if (note) note.hidden = !gpuActive; + const badge = document.getElementById('cpuEnhanceEngineBadge'); + if (badge) { + badge.classList.toggle('is-gpu', gpuActive); + badge.classList.toggle('is-cpu', m === 'cpu'); + badge.classList.toggle('is-warn', !gpuActive && m !== 'cpu'); + if (m === 'cpu') badge.textContent = 'CPU · ' + (cpuEnhanceDevice.name || 'пайплайн'); + else if (gpuActive) badge.textContent = 'GPU · ' + (cpuEnhanceDevice.name || 'photo-ai'); + else if (m === 'ai') badge.textContent = 'GPU недоступен'; + else badge.textContent = 'GPU недоступен → CPU'; + } + if (gpuActive && cpuEnhanceBaseKind === 'orig' && cpuEnhanceBaseImg) cpuEnhanceDrawLocal(); + cpuEnhanceSyncPending(); +} + +async function openCpuEnhance(id) { + const e = currentEntries.find(x => x.id === id); + if (!e) return; + const mp = mainPhotoPath(e); + if (!mp) { showToast('У записи нет фото'); return; } + cpuEnhanceReturnFocus = document.activeElement; + cpuEnhanceEntryId = id; + cpuEnhanceSaving = false; + cpuEnhanceAiJobId = null; + cpuEnhanceAiResultPath = null; + cpuEnhanceParamsTouched = false; + cpuEnhanceActiveKey = ''; + cpuEnhanceSetBusy(false); + cpuEnhanceResetSliders(true); + cpuEnhanceSetClip(50); + cpuEnhanceResetZoom(); + cpuEnhanceSetView('split'); + const orig = document.getElementById('cpuEnhanceOrig'); + if (orig) orig.src = `${API}${mp}`; + cpuEnhanceClearResult(); + cpuEnhanceSetBaseImg(mp); + cpuEnhanceSetInfo(null, [['Движок', 'анализ…']]); + cpuEnhanceClearError(); + const applyLabel = document.getElementById('cpuEnhanceApplyLabel'); + if (applyLabel) applyLabel.textContent = 'Сохранить'; + const restoreBtn = document.getElementById('cpuEnhanceRestoreBtn'); + if (restoreBtn) restoreBtn.style.display = e.photo_original_path ? '' : 'none'; + const context = document.getElementById('cpuEnhanceContext'); + if (context) { + const parts = [e.student_name, e.group_name].filter(Boolean); + if (e.module_name) parts.push(e.module_name); + if (e.created_at) parts.push(fmtFull(e.created_at)); + context.textContent = parts.join(' · '); + } + document.getElementById('cpuEnhanceModal').classList.add('open'); + cpuEnhanceSetMode(cpuEnhanceDevice.gpu ? 'ai' : 'auto'); + cpuEnhanceSyncPending(); + renderIcons(); + const compare = document.getElementById('cpuEnhanceCompare'); + if (compare) compare.focus({ preventScroll: true }); + cpuEnhanceProbeDevice(); +} + +function cpuEnhanceClearResult() { + if (cpuEnhancePreviewUrl) { + if (cpuEnhancePreviewUrl.startsWith('blob:')) URL.revokeObjectURL(cpuEnhancePreviewUrl); + cpuEnhancePreviewUrl = ''; + } + cpuEnhanceSetResultSrc(''); + cpuEnhanceMarkCleared(); +} + +async function cpuEnhanceAuto(showToastMsg) { + if (!cpuEnhanceEntryId || cpuEnhanceSaving) return; + cpuEnhanceClearError(); + cpuEnhanceSetLoading(true, 'Анализ фото…'); + try { + const res = await fetch(`${API}/api/entries/${cpuEnhanceEntryId}/photo/cpu-analyze`, { + method: 'POST', + headers: hdrJson(), + body: JSON.stringify({}), + }); + const data = await res.json().catch(() => ({})); + if (!res.ok) throw new Error(data.error || 'Ошибка анализа'); + const kept = cpuEnhanceParamsTouched; + if (!kept) cpuEnhanceApplySuggested(data.suggested); + cpuEnhanceSetInfo(data.analyze, [ + ['Движок', 'CPU'], + ['ИИ доступен', data.ai_available ? 'да' : 'нет'], + kept ? ['Авто', 'не применён — есть ручные правки'] : null, + ].filter(Boolean)); + if (showToastMsg) showToast(kept ? 'Авто-параметры рассчитаны, но ручные правки оставлены' : 'Параметры подобраны автоматически'); + cpuEnhanceSyncPending(); + } catch (e) { + cpuEnhanceSetError(e.message); + if (showToastMsg) showToast(e.message, true); + } finally { + cpuEnhanceSetLoading(false); + } +} + +async function cpuEnhancePreview() { + if (!cpuEnhanceEntryId || cpuEnhanceSaving) return; + const m = document.getElementById('cpuEnhanceMode').value; + if (m === 'ai' || m === 'auto') { + showToast('Превью доступно только в режиме CPU'); + return; + } + cpuEnhanceClearError(); + cpuEnhanceSetLoading(true, 'Предпросмотр…'); + try { + const res = await fetch(`${API}/api/entries/${cpuEnhanceEntryId}/photo/cpu-preview`, { + method: 'POST', + headers: hdrJson(), + body: JSON.stringify({ params: cpuEnhanceReadParams(), width: 720 }), + }); + const data = await res.json().catch(() => ({})); + if (!res.ok) throw new Error(data.error || 'Ошибка предпросмотра'); + const bytes = Uint8Array.from(atob(data.image_base64), c => c.charCodeAt(0)); + if (cpuEnhancePreviewUrl && cpuEnhancePreviewUrl.startsWith('blob:')) URL.revokeObjectURL(cpuEnhancePreviewUrl); + cpuEnhancePreviewUrl = URL.createObjectURL(new Blob([bytes], { type: 'image/jpeg' })); + cpuEnhanceSetResultSrc(cpuEnhancePreviewUrl); + cpuEnhanceAdoptPreviewAsBase(); + if (data.params) cpuEnhanceApplySuggested(data.params); + cpuEnhanceMarkApplied(); + cpuEnhanceSetInfo(data.analyze, [['Превью', `${Math.round((data.bytes || 0) / 1024)} КБ`]]); + } catch (e) { + cpuEnhanceMarkCleared(); + cpuEnhanceSetError(e.message); + showToast(e.message, true); + } finally { + cpuEnhanceSetLoading(false); + } +} + +async function cpuEnhanceRunAi(entryId, mode) { + cpuEnhanceSetLoading(true, 'Постановка ИИ-задачи…', 12); + const res = await fetch(`${API}/api/entries/${entryId}/photo/enhance-cpu`, { + method: 'POST', + headers: hdrJson(), + body: JSON.stringify({ mode: mode === 'auto' ? 'auto' : 'ai', params: cpuEnhanceReadParams(), face: 'face', face_model: 'gfpgan' }), + }); + const data = await res.json().catch(() => ({})); + if (!res.ok) throw new Error(data.error || 'Не удалось запустить ИИ'); + if (!data.jobId) throw new Error('ИИ-задача не создана'); + cpuEnhanceAiJobId = data.jobId; + cpuEnhanceSetInfo(null, [['Движок', 'ИИ / photo-ai'], ['Задача', `#${data.jobId}`]]); + const done = await cpuEnhancePollAi(entryId, data.jobId); + cpuEnhanceAiResultPath = done.photo_path || ''; + if (cpuEnhanceAiResultPath) { + cpuEnhanceSetResultSrc(`${API}${cpuEnhanceAiResultPath}`); + cpuEnhanceLoadAiBase(); + cpuEnhanceSetView('result'); + } + cpuEnhanceMarkApplied(); + cpuEnhanceSetInfo(null, [['Движок', 'ИИ / photo-ai'], ['Задача', `#${data.jobId}`]]); +} + +async function cpuEnhanceRun() { + if (!cpuEnhanceEntryId || cpuEnhanceSaving) return; + const mode = document.getElementById('cpuEnhanceMode').value; + const entryId = cpuEnhanceEntryId; + if (mode === 'ai' || mode === 'auto') { + cpuEnhanceSaving = true; + cpuEnhanceClearError(); + let fellBack = false; + try { + await cpuEnhanceRunAi(entryId, mode); + } catch (e) { + if (mode === 'auto') { + fellBack = true; + cpuEnhanceFallbackCpu(e.message); + } else { + cpuEnhanceMarkCleared(); + cpuEnhanceSetError(e.message); + showToast(e.message, true); + } + } finally { + cpuEnhanceSaving = false; + if (!fellBack) cpuEnhanceSetLoading(false); + } + return; + } + await cpuEnhancePreview(); +} + +function cpuEnhanceFallbackCpu(reason) { + cpuEnhanceDevice = { device: 'cpu', name: 'CPU (GPU недоступен)', ready: false, gpu: false }; + cpuEnhanceSetMode('cpu'); + showToast('GPU недоступен, переключаюсь на CPU'); + cpuEnhanceSetInfo(null, [['Причина', reason || 'GPU недоступен'], ['Движок', 'CPU']]); + cpuEnhanceSaving = false; + cpuEnhancePreview(); +} + +async function cpuEnhanceApply() { + if (!cpuEnhanceEntryId || cpuEnhanceSaving) return; + const mode = document.getElementById('cpuEnhanceMode').value; + if (cpuEnhanceIsDirty()) { + showToast('Параметры изменены — сначала обновите результат через «Активировать»', true); + return; + } + if (!cpuEnhanceActiveKey) { + showToast('Сначала нажмите «Активировать», чтобы получить результат', true); + return; + } + cpuEnhanceSaving = true; + cpuEnhanceClearError(); + let fellBack = false; + const applyLabel = document.getElementById('cpuEnhanceApplyLabel'); + if (applyLabel) applyLabel.textContent = 'Сохраняю…'; + cpuEnhanceSetBusy(true); + cpuEnhanceSetLoading(true, 'Сохранение результата…'); + const entryId = cpuEnhanceEntryId; + try { + if (cpuEnhanceAiJobId) { + await cpuEnhanceApplyAi(entryId, cpuEnhanceAiJobId); + showToast(cpuEnhanceDevice.gpu ? 'ИИ-результат сохранён' : 'Результат сохранён'); + closeCpuEnhance(true); + refreshEntryCard(entryId); + return; + } + const payload = { + mode, + params: cpuEnhanceReadParams(), + face: mode === 'cpu' ? 'off' : 'face', + face_model: 'gfpgan', + }; + const res = await fetch(`${API}/api/entries/${entryId}/photo/enhance-cpu`, { + method: 'POST', + headers: hdrJson(), + body: JSON.stringify(payload), + }); + const data = await res.json().catch(() => ({})); + if (!res.ok) throw new Error(data.error || 'Ошибка обработки'); + if (data.jobId) { + cpuEnhanceAiJobId = data.jobId; + await cpuEnhancePollAi(entryId, data.jobId); + await cpuEnhanceApplyAi(entryId, data.jobId); + } else { + showToast('Фото обработано'); + } + closeCpuEnhance(true); + refreshEntryCard(entryId); + } catch (e) { + if (mode === 'auto' && /ИИ-обработка фото не настроена|503/i.test(e.message)) { + cpuEnhanceFallbackCpu(e.message); + fellBack = true; + return; + } + cpuEnhanceSetError(e.message); + showToast(e.message, true); + } finally { + cpuEnhanceSaving = false; + if (applyLabel) applyLabel.textContent = 'Сохранить'; + if (!fellBack) { + cpuEnhanceSetLoading(false); + cpuEnhanceSetBusy(false); + } + } +} + +function cpuEnhancePollAi(entryId, jobId) { + return new Promise((resolve, reject) => { + let done = false; + const tick = async () => { + if (done) return; + try { + const r = await fetch(`${API}/api/entries/${entryId}/photo/enhance-ai/${jobId}`, { headers: hdr() }); + if (!r.ok) throw new Error('Ошибка опроса'); + const s = await r.json(); + if (done) return; + if (s.status === 'done') { done = true; clearInterval(t); resolve(s); return; } + if (s.status === 'error') { done = true; clearInterval(t); reject(new Error(s.error || 'Ошибка ИИ')); return; } + if (s.status === 'pending') cpuEnhanceSetLoading(true, 'В очереди — ждём свободный воркер', 18); + else cpuEnhanceSetLoading(true, 'ИИ обрабатывает фото…', 62); + } catch (e) { + done = true; + clearInterval(t); + reject(e); + } + }; + const t = setInterval(tick, 1200); + tick(); + }); +} + +async function cpuEnhanceApplyAi(entryId, jobId) { + cpuEnhanceSetLoading(true, 'Сохранение результата…', 88); + const res = await fetch(`${API}/api/entries/${entryId}/photo/jobs/${jobId}/apply`, { method: 'POST', headers: hdr() }); + const data = await res.json().catch(() => ({})); + if (!res.ok) throw new Error(data.error || 'Ошибка применения ИИ-результата'); + cpuEnhanceAiJobId = null; + cpuEnhanceAiResultPath = null; +} + +function closeCpuEnhance(force) { + if (!force && cpuEnhanceActiveKey && cpuEnhanceIsDirty()) { + if (!confirm('Параметры изменены, результат не сохранён. Закрыть без сохранения?')) return; + } + if (cpuEnhancePreviewUrl) { + if (cpuEnhancePreviewUrl.startsWith('blob:')) URL.revokeObjectURL(cpuEnhancePreviewUrl); + cpuEnhancePreviewUrl = ''; + } + if (cpuEnhanceAiJobId && cpuEnhanceEntryId) { + const entryId = cpuEnhanceEntryId; + const jobId = cpuEnhanceAiJobId; + cpuEnhanceAiJobId = null; + fetch(`${API}/api/entries/${entryId}/photo/jobs/${jobId}/reject`, { method: 'POST', headers: hdr() }).catch(() => {}); + } + cpuEnhanceAiResultPath = null; + const modal = document.getElementById('cpuEnhanceModal'); + if (modal) modal.classList.remove('open'); + cpuEnhanceEntryId = null; + cpuEnhanceSaving = false; + cpuEnhanceSetBusy(false); + cpuEnhanceClearResult(); + cpuEnhanceResetZoom(); + cpuEnhanceSetView('split'); + cpuEnhanceClearError(); + const restore = cpuEnhanceReturnFocus; + cpuEnhanceReturnFocus = null; + if (restore && typeof restore.focus === 'function' && document.contains(restore)) restore.focus({ preventScroll: true }); +} + function photoJobThumb(p) { if (!p) return ''; if (p.startsWith('/uploads/.originals/')) return `${API}${p}`; @@ -2215,6 +2955,8 @@ document.getElementById('grid').addEventListener('click', e => { if (ed) { openEdit(parseInt(ed.dataset.edit, 10)); return; } const en = e.target.closest('[data-enhance]'); if (en) { openEnhance(parseInt(en.dataset.enhance, 10)); return; } + const ce = e.target.closest('[data-cpuenhance]'); + if (ce) { openCpuEnhance(parseInt(ce.dataset.cpuenhance, 10)); return; } const dl = e.target.closest('[data-del]'); if (dl) { delEntry(parseInt(dl.dataset.del, 10)); } }); @@ -2286,11 +3028,223 @@ async function applyPhotoJob(jobId) { } } document.getElementById('enhanceModal').addEventListener('click', e => { if (e.target === e.currentTarget) closeEnhance(); }); -document.getElementById('enhanceBrightness').addEventListener('input', scheduleEnhancePreview); -document.getElementById('enhanceContrast').addEventListener('input', scheduleEnhancePreview); -document.getElementById('enhanceSaturate').addEventListener('input', scheduleEnhancePreview); -document.getElementById('enhanceDenoise').addEventListener('input', scheduleEnhancePreview); -document.getElementById('enhanceSharp').addEventListener('input', scheduleEnhancePreview); +document.getElementById('cpuEnhanceModal').addEventListener('click', e => { if (e.target === e.currentTarget) closeCpuEnhance(); }); +document.getElementById('cpuEnhanceCancelBtn').addEventListener('click', () => closeCpuEnhance()); +document.getElementById('cpuEnhanceCloseX').addEventListener('click', () => closeCpuEnhance()); +document.getElementById('cpuEnhanceApplyBtn').addEventListener('click', cpuEnhanceApply); +document.getElementById('cpuEnhancePreviewBtn').addEventListener('click', cpuEnhancePreview); +document.getElementById('cpuEnhanceActivateBtn').addEventListener('click', cpuEnhanceActivate); +document.getElementById('cpuZoomIn').addEventListener('click', () => cpuEnhanceZoomBy(1.25)); +document.getElementById('cpuZoomOut').addEventListener('click', () => cpuEnhanceZoomBy(1 / 1.25)); +document.getElementById('cpuZoomReset').addEventListener('click', cpuEnhanceResetZoom); +document.getElementById('cpuEnhanceView').addEventListener('click', e => { + const btn = e.target.closest('button[data-cpu-view]'); + if (btn) cpuEnhanceSetView(btn.dataset.cpuView); +}); +document.querySelector('.cpu-enhance-tools').addEventListener('pointerdown', e => e.stopPropagation()); +document.getElementById('cpuEnhanceAutoBtn').addEventListener('click', () => cpuEnhanceAuto(true)); +document.getElementById('cpuEnhanceResetBtn').addEventListener('click', () => { + if (cpuEnhanceBusy) return; + cpuEnhanceResetSliders(false); + cpuEnhanceClearError(); + cpuEnhanceSetInfo(null, [['Параметры', 'сброшены к значениям по умолчанию']]); + if (cpuEnhanceBaseImg) cpuEnhanceDrawLocal(); + cpuEnhanceSyncPending(); + showToast('Параметры сброшены к значениям по умолчанию'); +}); +document.getElementById('cpuEnhanceModeGroup').addEventListener('click', e => { + const btn = e.target.closest('button[data-cpu-mode]'); + if (!btn || btn.disabled) return; + cpuEnhanceClearError(); + cpuEnhanceSetMode(btn.dataset.cpuMode); +}); +document.getElementById('cpuEnhanceModeGroup').addEventListener('keydown', e => { + if (!['ArrowLeft', 'ArrowRight', 'ArrowUp', 'ArrowDown'].includes(e.key)) return; + const group = document.getElementById('cpuEnhanceModeGroup'); + const buttons = [...group.querySelectorAll('button[data-cpu-mode]')].filter(b => !b.disabled); + const at = buttons.indexOf(document.activeElement); + if (at < 0) return; + e.preventDefault(); + const step = e.key === 'ArrowLeft' || e.key === 'ArrowUp' ? -1 : 1; + const next = buttons[(at + step + buttons.length) % buttons.length]; + next.focus(); + cpuEnhanceSetMode(next.dataset.cpuMode); +}); +document.getElementById('cpuEnhanceScale').addEventListener('change', () => { + if (cpuEnhanceBaseImg) cpuEnhanceDrawLocal(); + cpuEnhanceSyncPending(); +}); +document.getElementById('cpuEnhanceRestoreBtn').addEventListener('click', async () => { + if (!cpuEnhanceEntryId) return; + if (!confirm('Вернуть исходную фотографию?')) return; + try { + const res = await fetch(`${API}/api/entries/${cpuEnhanceEntryId}/photo/restore-original`, { method: 'POST', headers: hdr() }); + if (!res.ok) throw new Error('Ошибка восстановления'); + showToast('Оригинал возвращён'); + const saved = cpuEnhanceEntryId; + closeCpuEnhance(true); + refreshEntryCard(saved); + } catch (e) { showToast(e.message, true); } +}); +CPU_ENHANCE_SLIDERS.forEach(k => { + const el = document.getElementById('cpuEnhance' + k); + if (!el) return; + el.addEventListener('input', () => { + cpuEnhanceSyncSlider(k); + cpuEnhanceClearError(); + if (k !== 'Quality') cpuEnhanceParamsTouched = true; + if (k !== 'Quality' && cpuEnhanceBaseImg) cpuEnhanceDrawLocal(); + cpuEnhanceSyncPending(); + }); + el.addEventListener('dblclick', () => { + if (cpuEnhanceBusy) return; + el.value = CPU_ENHANCE_DEFAULTS[k]; + cpuEnhanceSyncSlider(k); + cpuEnhanceParamsTouched = true; + if (k !== 'Quality' && cpuEnhanceBaseImg) cpuEnhanceDrawLocal(); + cpuEnhanceSyncPending(); + }); +}); + +function cpuEnhanceApplyTransform() { + const t = `translate(${cpuEnhancePanX}px, ${cpuEnhancePanY}px) scale(${cpuEnhanceZoom})`; + const area = document.getElementById('cpuEnhanceCompare'); + if (area) area.querySelectorAll('.cpu-enhance-layer').forEach(el => { el.style.transform = t; }); + if (area) area.classList.toggle('zoomed', cpuEnhanceZoom > 1.001); +} + +function cpuEnhanceClampPan() { + const area = document.getElementById('cpuEnhanceCompare'); + if (!area) return; + const rect = area.getBoundingClientRect(); + const minX = rect.width * (1 - cpuEnhanceZoom); + const minY = rect.height * (1 - cpuEnhanceZoom); + cpuEnhancePanX = Math.min(0, Math.max(minX, cpuEnhancePanX)); + cpuEnhancePanY = Math.min(0, Math.max(minY, cpuEnhancePanY)); +} + +function cpuEnhanceSyncZoomLabel() { + const el = document.getElementById('cpuZoomLevel'); + if (el) el.textContent = Math.round(cpuEnhanceZoom * 100) + '%'; +} + +function cpuEnhanceSetZoom(next, cx, cy) { + const area = document.getElementById('cpuEnhanceCompare'); + if (!area) return; + const prev = cpuEnhanceZoom; + const clamped = Math.min(8, Math.max(1, next)); + if (Math.abs(clamped - prev) < 0.001) { cpuEnhanceSyncZoomLabel(); return; } + const rect = area.getBoundingClientRect(); + const px = typeof cx === 'number' ? cx : rect.width / 2; + const py = typeof cy === 'number' ? cy : rect.height / 2; + cpuEnhanceZoom = clamped; + cpuEnhancePanX = px - (px - cpuEnhancePanX) * (clamped / prev); + cpuEnhancePanY = py - (py - cpuEnhancePanY) * (clamped / prev); + cpuEnhanceClampPan(); + cpuEnhanceApplyTransform(); + cpuEnhanceSyncZoomLabel(); +} + +function cpuEnhanceZoomBy(factor) { + cpuEnhanceSetZoom(cpuEnhanceZoom * factor); +} + +function cpuEnhanceResetZoom() { + cpuEnhanceZoom = 1; + cpuEnhancePanX = 0; + cpuEnhancePanY = 0; + cpuEnhanceApplyTransform(); + cpuEnhanceSyncZoomLabel(); +} + +function cpuEnhanceSetView(view) { + const area = document.getElementById('cpuEnhanceCompare'); + if (!area) return; + let next = ['orig', 'split', 'result'].includes(view) ? view : 'split'; + if (next !== 'orig' && !cpuEnhanceHasResult()) next = 'split'; + cpuEnhanceView = next; + area.classList.remove('view-orig', 'view-result'); + if (cpuEnhanceView === 'orig') area.classList.add('view-orig'); + if (cpuEnhanceView === 'result') area.classList.add('view-result'); + cpuEnhanceSetClip(50); + const top = document.getElementById('cpuEnhanceTop'); + if (top) top.style.clipPath = 'inset(0 0 0 50%)'; + const divider = document.getElementById('cpuEnhanceDivider'); + if (divider) divider.style.left = '50%'; + const seg = document.getElementById('cpuEnhanceView'); + if (seg) { + seg.querySelectorAll('button[data-cpu-view]').forEach(b => { + const on = b.dataset.cpuView === cpuEnhanceView; + b.classList.toggle('active', on); + b.setAttribute('aria-pressed', on ? 'true' : 'false'); + }); + } + if (cpuEnhanceView === 'result' && cpuEnhanceZoom > 1.001) cpuEnhanceResetZoom(); +} + +(function initCpuEnhanceView() { + const area = document.getElementById('cpuEnhanceCompare'); + if (!area) return; + let dragging = false; + let dividerDrag = false; + let lastX = 0; + let lastY = 0; + const moveClip = ev => { + const rect = area.getBoundingClientRect(); + cpuEnhanceSetClip(((ev.clientX - rect.left) / rect.width) * 100); + }; + const inTools = ev => !!(ev.target && ev.target.closest && ev.target.closest('.cpu-enhance-tools')); + area.addEventListener('pointerdown', ev => { + if (ev.button !== 0 && ev.pointerType === 'mouse') return; + if (inTools(ev)) return; + dividerDrag = !!ev.target.closest('#cpuEnhanceDivider') && cpuEnhanceView === 'split' && cpuEnhanceHasResult(); + dragging = true; + lastX = ev.clientX; + lastY = ev.clientY; + area.setPointerCapture(ev.pointerId); + if (dividerDrag || (cpuEnhanceZoom <= 1.001 && cpuEnhanceView === 'split' && cpuEnhanceHasResult())) moveClip(ev); + }); + area.addEventListener('wheel', ev => { + if (inTools(ev)) return; + if (!ev.ctrlKey && cpuEnhanceZoom <= 1.001) return; + ev.preventDefault(); + const rect = area.getBoundingClientRect(); + cpuEnhanceSetZoom(cpuEnhanceZoom * (ev.deltaY < 0 ? 1.15 : 1 / 1.15), ev.clientX - rect.left, ev.clientY - rect.top); + }, { passive: false }); + area.addEventListener('pointermove', ev => { + if (!dragging) return; + if (dividerDrag) { + moveClip(ev); + return; + } + if (cpuEnhanceZoom > 1.001) { + area.classList.add('panning'); + cpuEnhancePanX += ev.clientX - lastX; + cpuEnhancePanY += ev.clientY - lastY; + lastX = ev.clientX; + lastY = ev.clientY; + cpuEnhanceClampPan(); + cpuEnhanceApplyTransform(); + } else if (cpuEnhanceView === 'split' && cpuEnhanceHasResult()) { + moveClip(ev); + } + }); + const endDrag = () => { + dragging = false; + dividerDrag = false; + area.classList.remove('panning'); + }; + area.addEventListener('pointerup', endDrag); + area.addEventListener('pointercancel', endDrag); + area.addEventListener('dblclick', ev => { + if (inTools(ev)) return; + cpuEnhanceResetZoom(); + }); +})(); + +function cpuEnhanceActivate() { + cpuEnhanceRun(); +} document.getElementById('aiAcceptBtn').addEventListener('click', acceptAiCorrect); document.getElementById('aiRejectBtn').addEventListener('click', closeAiCorrect); document.getElementById('aiCorrectModal').addEventListener('click', e => { @@ -2330,8 +3284,35 @@ document.getElementById('videoClose').addEventListener('click', closeVideo); document.addEventListener('keydown', e => { if (e.key !== 'Escape') return; if (document.getElementById('videoModal').classList.contains('open')) closeVideo(); + if (document.getElementById('cpuEnhanceModal').classList.contains('open')) closeCpuEnhance(); +}); +document.addEventListener('keydown', e => { + if (!document.getElementById('cpuEnhanceModal').classList.contains('open')) return; + if (e.key === 'Tab') { + const items = cpuEnhanceFocusables(); + if (!items.length) return; + const first = items[0]; + const last = items[items.length - 1]; + if (e.shiftKey && (document.activeElement === first || !items.includes(document.activeElement))) { + e.preventDefault(); + last.focus(); + } else if (!e.shiftKey && (document.activeElement === last || !items.includes(document.activeElement))) { + e.preventDefault(); + first.focus(); + } + return; + } + if (e.ctrlKey || e.metaKey || e.altKey) return; + const tag = (e.target && e.target.tagName) || ''; + if (tag === 'INPUT' || tag === 'SELECT' || tag === 'TEXTAREA') return; + if (cpuEnhanceBusy) return; + if (e.key === '+' || e.key === '=') { e.preventDefault(); cpuEnhanceZoomBy(1.25); return; } + if (e.key === '-' || e.key === '_') { e.preventDefault(); cpuEnhanceZoomBy(1 / 1.25); return; } + if (e.key === '0') { e.preventDefault(); cpuEnhanceResetZoom(); return; } + if (e.key === '1') { e.preventDefault(); cpuEnhanceSetView('orig'); return; } + if (e.key === '2') { e.preventDefault(); cpuEnhanceSetView('split'); return; } + if (e.key === '3') { e.preventDefault(); cpuEnhanceSetView('result'); } }); - document.addEventListener('click', e => { const v = e.target.closest('[data-video]'); if (!v) return; diff --git a/server.js b/server.js index 27fd2d1..9e372fd 100644 --- a/server.js +++ b/server.js @@ -11232,6 +11232,265 @@ app.post('/api/entries/:id/photo/enhance-ai', requireAuth, async (req, res) => { } }); +function cpuEnhanceDefaults() { + return { + preset: 'auto', + scale: 1, + clarity: 40, + denoise: 0, + sharp: 30, + brightness: 100, + contrast: 100, + saturate: 100, + warmth: 0, + quality: 92, + }; +} + +function cpuEnhanceLockFast(p) { + if (p.preset !== 'fast') return p; + p.clarity = 0; + p.warmth = 0; + p.saturate = 100; + p.contrast = 100; + p.brightness = 100; + return p; +} + +function clampNum(v, min, max, def) { + const n = Number(v); + if (!Number.isFinite(n)) return def; + return Math.min(max, Math.max(min, n)); +} + +function cpuEnhanceParams(src) { + const d = cpuEnhanceDefaults(); + const p = src && typeof src === 'object' && !Array.isArray(src) ? src : {}; + const params = { + preset: ['auto', 'fast', 'quality'].includes(String(p.preset)) ? String(p.preset) : d.preset, + scale: clampNum(p.scale, 1, 2, d.scale), + clarity: clampNum(p.clarity, 0, 100, d.clarity), + denoise: clampNum(p.denoise, 0, 100, d.denoise), + sharp: clampNum(p.sharp, 0, 100, d.sharp), + brightness: clampNum(p.brightness, 40, 200, d.brightness), + contrast: clampNum(p.contrast, 40, 200, d.contrast), + saturate: clampNum(p.saturate, 0, 200, d.saturate), + warmth: clampNum(p.warmth, -100, 100, d.warmth), + quality: clampNum(p.quality, 70, 100, d.quality), + }; + return cpuEnhanceLockFast(params); +} + +async function cpuEnhanceAnalyze(srcPath) { + const base = sharp(srcPath).rotate(); + const meta = await base.metadata(); + const st = await base.stats(); + const first = st.channels[0] || {}; + let sharpness = 0; + try { + const w = 256; + const h = Math.max(1, Math.round((meta.height || 1) * w / (meta.width || 1))); + const { data } = await base.clone().resize(w, h, { fit: 'fill' }).greyscale().raw().toBuffer({ resolveWithObject: true }); + let sum = 0; + let sumSq = 0; + for (let i = 1; i < data.length; i++) { + const d = data[i] - data[i - 1]; + sum += d; + sumSq += d * d; + } + const n = data.length; + const mean = sum / n; + const variance = Math.max(0, sumSq / n - mean * mean); + sharpness = Math.sqrt(variance); + } catch (e) {} + return { + width: meta.width || 0, + height: meta.height || 0, + format: meta.format || 'jpeg', + mean: Math.round((first && first.mean) || 0), + stdev: Math.round((first && first.stdev) || 0), + shadow: Math.round((first && first.shadow) || 0), + highlight: Math.round((first && first.highlight) || 0), + isOpaque: st.isOpaque, + sharpness: Math.round(sharpness * 10) / 10, + }; +} + +function cpuEnhanceAutoTune(an) { + const out = { brightness: 100, contrast: 100, saturate: 100, clarity: 40, denoise: 0, sharp: 30 }; + const mean = Number(an.mean) || 0; + const stdev = Number(an.stdev) || 0; + const sharp = Number(an.sharpness) || 0; + if (mean < 96) out.brightness = Math.min(150, Math.round(100 + (110 - mean) * 0.7)); + else if (mean > 168) out.brightness = Math.max(65, Math.round(100 - (mean - 150) * 0.6)); + if (stdev < 32) out.contrast = Math.min(140, Math.round(100 + (48 - stdev) * 0.9)); + else if (stdev > 68) out.contrast = Math.max(75, Math.round(100 - (stdev - 68) * 0.9)); + out.saturate = 105; + out.clarity = stdev < 40 ? 50 : 35; + if (sharp < 12) out.sharp = 45; + else if (sharp < 25) out.sharp = 32; + else out.sharp = 20; + if (stdev < 14) out.denoise = Math.min(55, Math.round((20 - stdev) * 4)); + return out; +} + +async function runCpuEnhance(srcPath, params) { + const p = cpuEnhanceParams(params); + let img = sharp(srcPath).rotate(); + const meta = await img.metadata(); + const maxSide = Math.max(meta.width || 0, meta.height || 0); + if (p.scale > 1 && maxSide > 0) { + img = img.resize({ width: Math.round((meta.width || 1) * p.scale), height: Math.round((meta.height || 1) * p.scale), kernel: 'lanczos3', fit: 'fill' }); + } + if (p.denoise > 0) { + img = img.median(p.denoise > 70 ? 5 : 3); + img = img.blur(p.denoise > 70 ? 0.6 : 0.4); + } + if (p.clarity > 0) { + const scaleCap = Math.min(2, p.scale); + try { + img = img.clahe({ + width: Math.max(64, Math.round(((meta.width || 800) * scaleCap) / 8)), + height: Math.max(64, Math.round(((meta.height || 600) * scaleCap) / 8)), + maxSlope: Math.max(1, Math.min(100, Math.round(1 + (p.clarity / 100) * 2.2))), + }); + } catch (e) { + console.warn('clahe failed:', e.message); + } + } + img = img.modulate({ brightness: p.brightness / 100, saturation: p.saturate / 100 }); + if (Math.abs(p.warmth) > 0.5) { + const t = p.warmth / 100; + img = t > 0 + ? img.modulate({ brightness: p.brightness / 100, saturation: p.saturate / 100, tint: Math.min(1, t * 0.25) }) + : img.tint({ r: 255, g: Math.round(255 - t * 12), b: Math.round(255 + t * 22) }); + } + if (p.contrast !== 100) { + const a = p.contrast / 100; + img = img.linear(a, 128 * (1 - a)); + } + if (p.sharp > 0) { + img = img.sharpen({ sigma: 0.4 + (p.sharp / 100) * 1.4, m1: 0, m2: 1 + p.sharp / 60 }); + } + return { buffer: await img.jpeg({ quality: Math.round(p.quality), mozjpeg: true }).toBuffer(), params: p }; +} + +async function entryPhotoAccess(req, id) { + if (req.user.role === 'admin') return { ok: true }; + const acc = await entryAccessible(req.user, id); + if (!acc.found) return { ok: false, status: 404, error: 'Not found' }; + if (!acc.allowed) return { ok: false, status: 403, error: 'Нет доступа к этой записи' }; + return { ok: true }; +} + +app.post('/api/entries/:id/photo/cpu-analyze', requireAuth, async (req, res) => { + const acc = await entryPhotoAccess(req, req.params.id); + if (!acc.ok) return res.status(acc.status).json({ error: acc.error }); + try { + const { rows } = await pool.query('SELECT photo_path FROM entries WHERE id = $1', [req.params.id]); + if (!rows.length) return res.status(404).json({ error: 'Запись не найдена' }); + if (!rows[0].photo_path) return res.status(400).json({ error: 'У записи нет фото' }); + const srcKey = storage.keyFromPath(rows[0].photo_path); + const srcPath = srcKey ? await storage.localize(srcKey) : null; + if (!srcPath) return res.status(400).json({ error: 'Файл фото не найден' }); + const analyze = await cpuEnhanceAnalyze(srcPath); + res.json({ analyze, suggested: cpuEnhanceAutoTune(analyze), device: 'cpu', ai_available: !!PHOTO_AI_URL }); + } catch (e) { + console.error('POST /api/entries/:id/photo/cpu-analyze:', e); + res.status(500).json({ error: 'Ошибка анализа фото' }); + } +}); + +app.post('/api/entries/:id/photo/cpu-preview', requireAuth, async (req, res) => { + if (!sharp) return res.status(503).json({ error: 'sharp недоступен на сервере' }); + const acc = await entryPhotoAccess(req, req.params.id); + if (!acc.ok) return res.status(acc.status).json({ error: acc.error }); + try { + const { rows } = await pool.query('SELECT photo_path FROM entries WHERE id = $1', [req.params.id]); + if (!rows.length) return res.status(404).json({ error: 'Запись не найдена' }); + if (!rows[0].photo_path) return res.status(400).json({ error: 'У записи нет фото' }); + const srcKey = storage.keyFromPath(rows[0].photo_path); + const srcPath = srcKey ? await storage.localize(srcKey) : null; + if (!srcPath) return res.status(400).json({ error: 'Файл фото не найден' }); + const preview = cpuEnhanceParams(req.body && req.body.params); + const width = clampNum(req.body && req.body.width, 160, 1600, 640); + const analyze = await cpuEnhanceAnalyze(srcPath); + const full = await runCpuEnhance(srcPath, preview); + const buf = await sharp(full.buffer).resize({ width, withoutEnlargement: true }).jpeg({ quality: 78 }).toBuffer(); + res.json({ + ok: true, + image_base64: buf.toString('base64'), + params: full.params, + analyze, + bytes: full.buffer.length, + engine: 'cpu-classic', + ai_available: !!PHOTO_AI_URL, + }); + } catch (e) { + console.error('POST /api/entries/:id/photo/cpu-preview:', e); + res.status(500).json({ error: 'Ошибка предпросмотра' }); + } +}); + +app.post('/api/entries/:id/photo/enhance-cpu', requireAuth, async (req, res) => { + const acc = await entryPhotoAccess(req, req.params.id); + if (!acc.ok) return res.status(acc.status).json({ error: acc.error }); + const body = req.body && typeof req.body === 'object' && !Array.isArray(req.body) ? req.body : {}; + const mode = String(body.mode || 'auto').toLowerCase(); + const { rows: cur } = await pool.query('SELECT photo_path FROM entries WHERE id = $1', [req.params.id]); + if (!cur.length) return res.status(404).json({ error: 'Запись не найдена' }); + if (!cur[0].photo_path) return res.status(400).json({ error: 'У записи нет фото' }); + const oldPath = cur[0].photo_path; + const wantAi = mode === 'ai' || (mode === 'auto' && PHOTO_AI_URL); + if (wantAi) { + if (!PHOTO_AI_URL) return res.status(503).json({ error: 'ИИ-обработка фото не настроена' }); + const face = String(body.face || 'off').toLowerCase(); + const parsed = parsePhotoAiRequest({ model: body.model, face, face_model: body.face_model, strength: body.strength }); + if (parsed.error) return res.status(400).json({ error: parsed.error }); + const cpuParams = cpuEnhanceParams(body.params); + const jobParams = { ...parsed.params, cpu: cpuParams }; + try { + const { rows } = await pool.query( + `INSERT INTO photo_jobs (entry_id, action, status, params) VALUES ($1, $2, 'pending', $3) RETURNING id`, + [req.params.id, parsed.action, JSON.stringify(jobParams)] + ); + if (photoWorker) photoWorker.notify(); + await logAudit(req, 'entry.photo.enhance-cpu.queue', { entry_id: req.params.id, job_id: rows[0].id, mode, action: parsed.action }); + return res.json({ jobId: rows[0].id, action: parsed.action, params: jobParams, engine: 'ai' }); + } catch (e) { + console.error('POST /api/entries/:id/photo/enhance-cpu:', e); + return res.status(500).json({ error: 'Ошибка постановки задания' }); + } + } + if (!sharp) return res.status(503).json({ error: 'sharp недоступен на сервере' }); + try { + const params = cpuEnhanceParams(body.params); + if (params.preset === 'auto') { + const srcKey = storage.keyFromPath(oldPath); + const srcPath = srcKey ? await storage.localize(srcKey) : null; + if (srcPath) { + const auto = cpuEnhanceAutoTune(await cpuEnhanceAnalyze(srcPath)); + if (body.params === undefined || body.params === null) Object.assign(params, auto); + } + } + const srcKey = storage.keyFromPath(oldPath); + const srcPath = srcKey ? await storage.localize(srcKey) : null; + if (!srcPath) return res.status(400).json({ error: 'Файл фото не найден' }); + const result = await runCpuEnhance(srcPath, params); + const newName = crypto.randomBytes(12).toString('hex') + '.jpg'; + const outPath = path.join(UPLOADS_DIR, newName); + await fs.promises.writeFile(outPath, result.buffer); + await storage.persist(newName, outPath); + const newPath = `/uploads/${newName}`; + await swapEntryPhotoFiles(req, req.params.id, oldPath, newPath, { action: 'enhance' }); + await logAudit(req, 'entry.photo.enhance-cpu.apply', { entry_id: req.params.id, engine: 'cpu-classic', params }); + res.json({ ok: true, photo_path: newPath, engine: 'cpu-classic', params, bytes: result.buffer.length }); + } catch (e) { + console.error('POST /api/entries/:id/photo/enhance-cpu:', e); + res.status(500).json({ error: 'Ошибка обработки фото' }); + } +}); + app.get('/api/entries/:id/photo/enhance-ai/:jobId', requireAuth, async (req, res) => { try { if (req.user.role !== 'admin') { diff --git a/worker.js b/worker.js index a3c0ba7..bf9834a 100644 --- a/worker.js +++ b/worker.js @@ -282,10 +282,80 @@ function createPhotoEnhanceWorker({ pool, getSetting, logAudit, invalidateEntrie }; } + function cpuPostParams(job) { + const p = job && job.params && typeof job.params === 'object' ? job.params.cpu : null; + if (!p || typeof p !== 'object') return null; + const num = (v, min, max, def) => { + const n = Number(v); + return Number.isFinite(n) ? Math.min(max, Math.max(min, n)) : def; + }; + return { + clarity: num(p.clarity, 0, 100, 0), + denoise: num(p.denoise, 0, 100, 0), + sharp: num(p.sharp, 0, 100, 0), + brightness: num(p.brightness, 40, 200, 100), + contrast: num(p.contrast, 40, 200, 100), + saturate: num(p.saturate, 0, 200, 100), + warmth: num(p.warmth, -100, 100, 0), + quality: num(p.quality, 70, 100, 92), + scale: num(p.scale, 1, 2, 1), + }; + } + + function cpuPostIsNoop(c) { + if (!c) return true; + return c.clarity === 0 && c.denoise === 0 && c.sharp === 0 + && c.brightness === 100 && c.contrast === 100 && c.saturate === 100 + && c.warmth === 0 && c.quality >= 92 && c.scale === 1; + } + + async function cpuFinishBuffer(buf, c) { + if (!sharp || !c || cpuPostIsNoop(c)) return buf; + let img = sharp(buf); + const meta = await img.metadata(); + if (c.scale > 1 && (meta.width || 0) > 0) { + img = img.resize({ + width: Math.round((meta.width || 1) * c.scale), + height: Math.round((meta.height || 1) * c.scale), + kernel: 'lanczos3', + fit: 'fill', + }); + } + if (c.denoise > 0) { + img = img.median(c.denoise > 70 ? 5 : 3); + img = img.blur(c.denoise > 70 ? 0.6 : 0.4); + } + if (c.clarity > 0) { + try { + img = img.clahe({ + width: Math.max(64, Math.round((meta.width || 800) / 8)), + height: Math.max(64, Math.round((meta.height || 600) / 8)), + maxSlope: Math.max(1, Math.min(100, Math.round(1 + (c.clarity / 100) * 2.2))), + }); + } catch (e) {} + } + img = img.modulate({ brightness: c.brightness / 100, saturation: c.saturate / 100 }); + if (Math.abs(c.warmth) > 0.5) { + const t = c.warmth / 100; + img = t > 0 + ? img.modulate({ brightness: c.brightness / 100, saturation: c.saturate / 100, tint: Math.min(1, t * 0.25) }) + : img.tint({ r: 255, g: Math.round(255 - t * 12), b: Math.round(255 + t * 22) }); + } + if (c.contrast !== 100) { + const a = c.contrast / 100; + img = img.linear(a, 128 * (1 - a)); + } + if (c.sharp > 0) { + img = img.sharpen({ sigma: 0.4 + (c.sharp / 100) * 1.4, m1: 0, m2: 1 + c.sharp / 60 }); + } + return img.jpeg({ quality: Math.round(c.quality), mozjpeg: true }).toBuffer(); + } + async function enhanceWithAi(srcKey, job) { const { out, meta } = await runAiEnhance(srcKey, job); + const finalBuf = await cpuFinishBuffer(out, cpuPostParams(job)); const newName = crypto.randomBytes(12).toString('hex') + '.jpg'; - await storage.put(newName, out); + await storage.put(newName, finalBuf); return { path: `/uploads/${newName}`, meta }; }