feat(photo): CPU-обработка фото с пайплайном sharp

- новые эндпоинты: /api/entries/:id/photo/cpu-analyze, cpu-preview, enhance-cpu
- серверный пайплайн sharp: Lanczos ×2, median+blur, CLAHE, modulate, tint, linear, sharpen, mozjpeg
- авто-подбор параметров по статистике фото, превью ограничено 1400px
- worker: CPU-постобработка поверх результата photo-ai, no-op при нейтральных значениях
- модалка #cpuEnhanceModal: сравнение оригинал/результат, зум, 8 ползунков, режимы auto/ai/cpu, горячие клавиши
- индикатор прогресса фото-ИИ остаётся видимым до загрузки результата
This commit is contained in:
dev
2026-10-17 11:23:40 +03:00
parent 1d74813b0f
commit f5910d9524
4 changed files with 1523 additions and 9 deletions
+206 -2
View File
@@ -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 @@
</div>
</div>
<div class="modal-overlay" id="cpuEnhanceModal">
<div class="edit-modal enhance-modal cpu-enhance-modal" role="dialog" aria-modal="true" aria-labelledby="cpuEnhanceTitle">
<div class="cpu-enhance-head">
<div class="cpu-enhance-head-main">
<h3 id="cpuEnhanceTitle">Обработка фотографии</h3>
<div class="cpu-enhance-sub" id="cpuEnhanceContext"></div>
</div>
<div class="cpu-enhance-head-side">
<span class="cpu-enhance-badge is-cpu" id="cpuEnhanceEngineBadge">CPU</span>
<button type="button" class="cpu-enhance-x" id="cpuEnhanceCloseX" title="Закрыть (Esc)"><i data-lucide="x"></i></button>
</div>
</div>
<div class="cpu-enhance-bodywrap">
<div class="enhance-body">
<div class="cpu-enhance-stage">
<div class="cpu-enhance-compare" id="cpuEnhanceCompare" tabindex="-1" aria-label="Сравнение оригинала и результата">
<div class="cpu-enhance-layer" id="cpuEnhanceOrigLayer"><img id="cpuEnhanceOrig" alt="Оригинал"></div>
<div class="cpu-enhance-top" id="cpuEnhanceTop" style="clip-path:inset(0 0 0 50%)">
<div class="cpu-enhance-layer"><img id="cpuEnhanceResult" alt="Результат"></div>
</div>
<div class="cpu-enhance-empty" id="cpuEnhanceEmpty">
<div class="cpu-enhance-empty-card">
<i data-lucide="image-plus"></i>
<span>Результат появится здесь</span>
<small>Подберите параметры и нажмите «Активировать»</small>
</div>
</div>
<div class="cpu-enhance-divider" id="cpuEnhanceDivider"><div class="cpu-enhance-handle"><i data-lucide="move-horizontal" style="width:18px;height:18px"></i></div></div>
<div class="cpu-enhance-tools">
<div class="cpu-enhance-seg" id="cpuEnhanceView" role="group" aria-label="Что показывать в сравнении">
<button type="button" data-cpu-view="orig" title="Только оригинал (1)" aria-pressed="false"><i data-lucide="image"></i> Было</button>
<button type="button" data-cpu-view="split" class="active" title="Обе версии, разделитель — мышью (2)" aria-pressed="true"><i data-lucide="columns-2"></i> Обе</button>
<button type="button" data-cpu-view="result" title="Только результат (3)" aria-pressed="false"><i data-lucide="sparkles"></i> Стало</button>
</div>
<div class="cpu-enhance-seg cpu-enhance-zoom" role="group" aria-label="Масштаб">
<button type="button" id="cpuZoomOut" title="Отдалить (−)"><i data-lucide="zoom-out"></i></button>
<button type="button" id="cpuZoomReset" class="cpu-enhance-zoom-level" title="Сбросить масштаб (0)"><span id="cpuZoomLevel">100%</span></button>
<button type="button" id="cpuZoomIn" title="Приблизить (+)"><i data-lucide="zoom-in"></i></button>
</div>
</div>
<div class="cpu-enhance-badge-tag left" id="cpuEnhanceBadgeOrig">Оригинал</div>
<div class="cpu-enhance-badge-tag right" id="cpuEnhanceBadgeRes">Результат</div>
<div class="enhance-loading cpu-enhance-loading" id="cpuEnhanceLoading" style="display:none">
<div class="enhance-thinking">
<div class="enhance-thinking-text" id="cpuEnhanceLoadingText">Обработка…</div>
<div class="enhance-thinking-dots">
<div class="enhance-thinking-dot"></div>
<div class="enhance-thinking-dot"></div>
<div class="enhance-thinking-dot"></div>
</div>
<div class="enhance-progress" id="cpuEnhanceProgress" hidden><div class="enhance-progress-bar" id="cpuEnhanceProgressBar"></div></div>
</div>
</div>
</div>
<div class="cpu-enhance-meta" id="cpuEnhanceInfo"></div>
</div>
<div class="cpu-enhance-side">
<input type="hidden" id="cpuEnhanceMode" value="auto">
<div class="settings-field">
<label id="cpuEnhanceModeLabel">Режим обработки</label>
<div class="cpu-enhance-seg cpu-enhance-modes" id="cpuEnhanceModeGroup" role="group" aria-labelledby="cpuEnhanceModeLabel">
<button type="button" data-cpu-mode="auto" class="active" aria-pressed="true" title="photo-ai на GPU, а без него — CPU-пайплайн"><i data-lucide="plug-zap"></i> Авто</button>
<button type="button" data-cpu-mode="ai" aria-pressed="false" title="Только photo-ai на GPU"><i data-lucide="server"></i> GPU</button>
<button type="button" data-cpu-mode="cpu" aria-pressed="false" title="Локальный пайплайн: Lanczos + CLAHE + unsharp"><i data-lucide="cpu"></i> CPU</button>
</div>
</div>
<div class="settings-field"><label for="cpuEnhanceScale">Масштаб</label>
<select id="cpuEnhanceScale" class="settings-input"><option value="1">×1 — без увеличения</option><option value="2">×2 — Lanczos</option></select>
</div>
<div class="cpu-enhance-controls">
<div class="settings-field"><label for="cpuEnhanceQuality">Качество JPEG <span id="cpuEnhanceQualityVal">92%</span></label><input type="range" id="cpuEnhanceQuality" min="70" max="100" value="92" title="Качество итогового JPEG: ниже — меньше файл"></div>
<div class="settings-field"><label for="cpuEnhanceBrightness">Яркость <span id="cpuEnhanceBrightnessVal">100</span></label><input type="range" id="cpuEnhanceBrightness" min="40" max="200" value="100"></div>
<div class="settings-field"><label for="cpuEnhanceContrast">Контраст <span id="cpuEnhanceContrastVal">100</span></label><input type="range" id="cpuEnhanceContrast" min="40" max="200" value="100"></div>
<div class="settings-field"><label for="cpuEnhanceSaturate">Насыщенность <span id="cpuEnhanceSaturateVal">100</span></label><input type="range" id="cpuEnhanceSaturate" min="0" max="200" value="100"></div>
<div class="settings-field"><label for="cpuEnhanceWarmth">Тепло <span id="cpuEnhanceWarmthVal">0</span></label><input type="range" id="cpuEnhanceWarmth" min="-100" max="100" value="0" title="Минус — холоднее, плюс — теплее"></div>
<div class="settings-field"><label for="cpuEnhanceClarity">Детализация (CLAHE) <span id="cpuEnhanceClarityVal">40</span></label><input type="range" id="cpuEnhanceClarity" min="0" max="100" value="40"></div>
<div class="settings-field"><label for="cpuEnhanceSharp">Резкость <span id="cpuEnhanceSharpVal">30</span></label><input type="range" id="cpuEnhanceSharp" min="0" max="100" value="30"></div>
<div class="settings-field"><label for="cpuEnhanceDenoise">Шумодав <span id="cpuEnhanceDenoiseVal">0</span></label><input type="range" id="cpuEnhanceDenoise" min="0" max="100" value="0"></div>
</div>
<div class="cpu-enhance-actions">
<button type="button" class="btn-primary ghost" id="cpuEnhanceAutoBtn" title="Подобрать параметры по статистике фото. Ручные правки не перезаписываются"><i data-lucide="wand-sparkles"></i> Авто</button>
<button type="button" class="btn-primary ghost" id="cpuEnhancePreviewBtn" title="Серверный предпросмотр текущих параметров"><i data-lucide="eye"></i> Превью</button>
<button type="button" class="btn-primary ghost" id="cpuEnhanceResetBtn" title="Вернуть все ползунки к значениям по умолчанию"><i data-lucide="rotate-ccw"></i> Сброс</button>
</div>
<div class="cpu-enhance-note cpu-enhance-gpu-note" id="cpuEnhanceGpuNote" hidden>ИИ обработает фото на GPU, ползунки применятся как пост-обработка на CPU</div>
<div class="cpu-enhance-note cpu-enhance-error" id="cpuEnhanceError" hidden role="alert"><i data-lucide="triangle-alert"></i><span id="cpuEnhanceErrorText"></span></div>
</div>
</div>
</div>
<div class="cpu-enhance-footwrap">
<div class="cpu-enhance-status is-idle" id="cpuEnhanceStatus" role="status" aria-live="polite">
<span class="cpu-enhance-status-dot"></span>
<span class="cpu-enhance-status-text" id="cpuEnhanceStatusText"></span>
<span class="cpu-enhance-keys"><kbd>1</kbd><kbd>2</kbd><kbd>3</kbd><span>сравнение</span><kbd>+</kbd><kbd>−</kbd><kbd>0</kbd><span>масштаб</span></span>
</div>
<div class="card-foot cpu-enhance-foot">
<button type="button" class="btn-primary ghost" id="cpuEnhanceRestoreBtn" style="display:none" title="Вернуть исходную фотографию"><i data-lucide="undo-2"></i> Вернуть оригинал</button>
<button type="button" class="btn-primary ghost" id="cpuEnhanceCancelBtn">Закрыть</button>
<button type="button" class="btn-primary" id="cpuEnhanceActivateBtn" title="Запустить обработку и получить результат"><i data-lucide="zap"></i> Активировать</button>
<button type="button" class="btn-primary" id="cpuEnhanceApplyBtn" title="Сохранить результат к записи"><i data-lucide="check"></i> <span id="cpuEnhanceApplyLabel">Сохранить</span></button>
</div>
</div>
</div>
</div>
<div class="modal-overlay" id="photoHistoryModal">
<div class="edit-modal enhance-modal">
<h3 id="photoHistoryTitle">История изменений фотографии</h3>
+987 -6
View File
File diff suppressed because it is too large Load Diff
+259
View File
@@ -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') {
+71 -1
View File
@@ -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 };
}