groups: AI enhance for gallery photos (photo_jobs.group_photo_id, before/after compare modal)
This commit is contained in:
+703
-1
@@ -177,6 +177,7 @@ function photoHTML(p) {
|
||||
<div class="p-actions">
|
||||
<button class="p-cover${isCover ? ' active' : ''}" data-photo-id="${p.id}" data-photo-path="${esc(p.photo_path)}" title="${isCover ? 'Текущая обложка' : 'Сделать обложкой'}" ${isCover ? 'disabled' : ''}>🖼️</button>
|
||||
<button class="p-edit" data-edit-photo="${p.id}" title="Редактировать">✎</button>
|
||||
<button class="p-enhance" data-enhance-photo="${p.id}" title="Улучшить фото">✨</button>
|
||||
<button class="p-del" data-del-photo="${p.id}" title="Удалить">×</button>
|
||||
</div>
|
||||
</div>
|
||||
@@ -523,6 +524,8 @@ document.getElementById('photoGrid').addEventListener('click', async e => {
|
||||
}
|
||||
const ed = e.target.closest('[data-edit-photo]');
|
||||
if (ed) { openEditPhoto(parseInt(ed.dataset.editPhoto, 10)); return; }
|
||||
const en = e.target.closest('[data-enhance-photo]');
|
||||
if (en) { openEnhance(parseInt(en.dataset.enhancePhoto, 10)); return; }
|
||||
const dl = e.target.closest('[data-del-photo]');
|
||||
if (dl) { deletePhoto(parseInt(dl.dataset.delPhoto, 10)); }
|
||||
});
|
||||
@@ -548,4 +551,703 @@ async function populateNewGroupBranch() {
|
||||
await populateNewGroupBranch();
|
||||
loadGroups();
|
||||
}
|
||||
})();
|
||||
})();
|
||||
let enhancePhotoId = null;
|
||||
let enhanceAiJobId = null;
|
||||
let enhanceAiResultPath = null;
|
||||
let enhanceSourceImg = null;
|
||||
let photoAiEnabled = false;
|
||||
let photoAiFaceMode = 'off';
|
||||
let photoAiFaceModel = 'gfpgan';
|
||||
let photoAiDevice = '';
|
||||
let photoAiConfigLoaded = false;
|
||||
let enhanceSaving = false;
|
||||
let enhanceTimer = null;
|
||||
let enhanceClipPos = 50;
|
||||
let enhanceZoom = 1;
|
||||
let enhancePanX = 0;
|
||||
let enhancePanY = 0;
|
||||
|
||||
async function loadPhotoAiConfig() {
|
||||
if (photoAiConfigLoaded) return;
|
||||
try {
|
||||
const res = await fetch(API + '/api/public-settings', { headers: hdr() });
|
||||
if (res.ok) {
|
||||
const s = await res.json();
|
||||
photoAiEnabled = s.photo_ai_enabled === 'true';
|
||||
if (['off', 'face', 'all'].includes(s.photo_ai_face_mode)) photoAiFaceMode = s.photo_ai_face_mode;
|
||||
if (['gfpgan', 'codeformer'].includes(s.photo_ai_face_model)) photoAiFaceModel = s.photo_ai_face_model;
|
||||
}
|
||||
} catch (e) { photoAiEnabled = false; }
|
||||
photoAiConfigLoaded = true;
|
||||
const sel = document.getElementById('enhanceAiMode');
|
||||
if (sel) sel.value = defaultPhotoAiModeKey();
|
||||
loadPhotoAiDevice();
|
||||
}
|
||||
|
||||
async function loadPhotoAiDevice() {
|
||||
if (!isAdmin()) return;
|
||||
try {
|
||||
const r = await fetch(`${API}/api/photo-ai/health`, { headers: hdr() });
|
||||
if (!r.ok) return;
|
||||
const h = await r.json();
|
||||
if (h && h.device) photoAiDevice = String(h.device);
|
||||
updateAiHint();
|
||||
} catch (e) {}
|
||||
}
|
||||
|
||||
const PHOTO_AI_MODES = {
|
||||
x2: { model: 'x2plus', face: 'off', face_model: null, title: 'Универсально (x2)' },
|
||||
x4: { model: 'general-x4v3', face: 'off', face_model: null, title: 'Быстро (x4)' },
|
||||
faces: { model: 'x2plus', face: 'face', face_model: null, title: 'Лица (восстановление)' },
|
||||
facesbg: { model: 'x2plus', face: 'all', face_model: null, title: 'Лица + фон' },
|
||||
};
|
||||
|
||||
function photoAiMode() {
|
||||
const sel = document.getElementById('enhanceAiMode');
|
||||
const key = sel && PHOTO_AI_MODES[sel.value] ? sel.value : 'x2';
|
||||
const m = { ...PHOTO_AI_MODES[key] };
|
||||
m.face_model = m.face === 'off' ? null : photoAiFaceModel;
|
||||
return m;
|
||||
}
|
||||
|
||||
function defaultPhotoAiModeKey() {
|
||||
if (photoAiFaceMode === 'all') return 'facesbg';
|
||||
if (photoAiFaceMode === 'face') return 'faces';
|
||||
return 'x2';
|
||||
}
|
||||
|
||||
function updateAiHint() {
|
||||
const hint = document.getElementById('enhanceAiHint');
|
||||
if (!hint) return;
|
||||
const cpu = photoAiDevice.startsWith('cpu');
|
||||
hint.textContent = cpu ? 'Фото-ИИ считает на CPU — лицевые режимы могут занять несколько минут' : '';
|
||||
hint.style.display = photoAiEnabled && cpu ? '' : 'none';
|
||||
}
|
||||
|
||||
function showEnhanceResult(show) {
|
||||
const top = document.getElementById('enhanceTop');
|
||||
const loading = document.getElementById('enhanceLoading');
|
||||
if (top) top.style.display = show ? '' : 'none';
|
||||
if (loading) loading.style.display = show ? 'none' : '';
|
||||
}
|
||||
|
||||
function setEnhanceLoadingText(text) {
|
||||
const el = document.getElementById('enhanceLoading');
|
||||
if (!el) return;
|
||||
el.style.display = '';
|
||||
el.textContent = text;
|
||||
}
|
||||
|
||||
function medianFilterPass(ctx, w, h) {
|
||||
const data = ctx.getImageData(0, 0, w, h);
|
||||
const src = data.data;
|
||||
const out = new Uint8ClampedArray(src);
|
||||
const row = w * 4;
|
||||
const win = new Array(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++) {
|
||||
win[0] = src[i - row - 4 + ch]; win[1] = src[i - row + ch]; win[2] = src[i - row + 4 + ch];
|
||||
win[3] = src[i - 4 + ch]; win[4] = src[i + ch]; win[5] = src[i + 4 + ch];
|
||||
win[6] = src[i + row - 4 + ch]; win[7] = src[i + row + ch]; win[8] = src[i + row + 4 + ch];
|
||||
win.sort((a, b) => a - b);
|
||||
out[i + ch] = win[4];
|
||||
}
|
||||
}
|
||||
}
|
||||
data.data.set(out);
|
||||
ctx.putImageData(data, 0, 0);
|
||||
}
|
||||
|
||||
function sharpenPass(ctx, w, h, sharp) {
|
||||
const data = ctx.getImageData(0, 0, w, h);
|
||||
const src = data.data;
|
||||
const out = new Uint8ClampedArray(src);
|
||||
const row = w * 4;
|
||||
const a = (sharp / 100) * 1.5;
|
||||
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 v = (1 + 4 * a) * src[i + ch]
|
||||
- a * src[i - 4 + ch] - a * src[i + 4 + ch]
|
||||
- a * src[i - row + ch] - a * src[i + row + ch];
|
||||
out[i + ch] = v;
|
||||
}
|
||||
}
|
||||
}
|
||||
data.data.set(out);
|
||||
ctx.putImageData(data, 0, 0);
|
||||
}
|
||||
|
||||
function drawEnhanced(ctx, img, w, h) {
|
||||
const b = document.getElementById('enhanceBrightness').value;
|
||||
const c = document.getElementById('enhanceContrast').value;
|
||||
const s = document.getElementById('enhanceSaturate').value;
|
||||
const dn = parseInt(document.getElementById('enhanceDenoise').value, 10);
|
||||
const sp = parseInt(document.getElementById('enhanceSharp').value, 10);
|
||||
ctx.filter = `brightness(${b}%) contrast(${c}%) saturate(${s}%)`;
|
||||
ctx.drawImage(img, 0, 0, w, h);
|
||||
ctx.filter = 'none';
|
||||
if (dn > 0) {
|
||||
medianFilterPass(ctx, w, h);
|
||||
if (dn > 70) medianFilterPass(ctx, w, h);
|
||||
}
|
||||
if (sp > 0) sharpenPass(ctx, w, h, sp);
|
||||
}
|
||||
|
||||
function renderEnhancePreview() {
|
||||
if (!enhanceSourceImg) return;
|
||||
const img = enhanceSourceImg;
|
||||
const scale = Math.min(1, 1600 / img.naturalWidth);
|
||||
const w = Math.max(1, Math.round(img.naturalWidth * scale));
|
||||
const h = Math.max(1, Math.round(img.naturalHeight * scale));
|
||||
const canvas = document.getElementById('enhanceCanvas');
|
||||
if (!canvas) return;
|
||||
canvas.width = w;
|
||||
canvas.height = h;
|
||||
const ctx = canvas.getContext('2d');
|
||||
drawEnhanced(ctx, img, w, h);
|
||||
showEnhanceResult(true);
|
||||
}
|
||||
|
||||
function scheduleEnhancePreview() {
|
||||
document.getElementById('enhanceBrightnessVal').textContent = document.getElementById('enhanceBrightness').value + '%';
|
||||
document.getElementById('enhanceContrastVal').textContent = document.getElementById('enhanceContrast').value + '%';
|
||||
document.getElementById('enhanceSaturateVal').textContent = document.getElementById('enhanceSaturate').value + '%';
|
||||
document.getElementById('enhanceDenoiseVal').textContent = document.getElementById('enhanceDenoise').value + '%';
|
||||
document.getElementById('enhanceSharpVal').textContent = document.getElementById('enhanceSharp').value + '%';
|
||||
if (enhanceTimer) clearTimeout(enhanceTimer);
|
||||
enhanceTimer = setTimeout(renderEnhancePreview, 120);
|
||||
}
|
||||
|
||||
function enhanceParams() {
|
||||
return {
|
||||
brightness: parseInt(document.getElementById('enhanceBrightness').value, 10),
|
||||
contrast: parseInt(document.getElementById('enhanceContrast').value, 10),
|
||||
saturate: parseInt(document.getElementById('enhanceSaturate').value, 10),
|
||||
denoise: parseInt(document.getElementById('enhanceDenoise').value, 10),
|
||||
sharp: parseInt(document.getElementById('enhanceSharp').value, 10),
|
||||
};
|
||||
}
|
||||
|
||||
function isDefaultEnhanceParams() {
|
||||
const p = enhanceParams();
|
||||
return p.brightness === 100 && p.contrast === 100 && p.saturate === 100 && p.denoise === 0 && p.sharp === 0;
|
||||
}
|
||||
|
||||
function setEnhanceClip(p) {
|
||||
enhanceClipPos = Math.min(100, Math.max(0, p));
|
||||
const top = document.getElementById('enhanceTop');
|
||||
const divider = document.getElementById('enhanceDivider');
|
||||
if (top) top.style.clipPath = `inset(0 0 0 ${enhanceClipPos}%)`;
|
||||
if (divider) divider.style.left = enhanceClipPos + '%';
|
||||
}
|
||||
|
||||
function applyEnhanceTransform() {
|
||||
const t = `translate(${enhancePanX}px, ${enhancePanY}px) scale(${enhanceZoom})`;
|
||||
const stage = document.getElementById('enhanceStage');
|
||||
const inner = document.getElementById('enhanceInner');
|
||||
if (stage) stage.style.transform = t;
|
||||
if (inner) inner.style.transform = t;
|
||||
const area = document.getElementById('enhanceCompare');
|
||||
if (area) {
|
||||
area.classList.toggle('zoomed', enhanceZoom > 1);
|
||||
if (enhanceZoom <= 1) area.classList.remove('panning');
|
||||
}
|
||||
}
|
||||
|
||||
function clampEnhancePan() {
|
||||
const area = document.getElementById('enhanceCompare');
|
||||
if (!area) return;
|
||||
const rect = area.getBoundingClientRect();
|
||||
const minX = rect.width * (1 - enhanceZoom);
|
||||
const minY = rect.height * (1 - enhanceZoom);
|
||||
enhancePanX = Math.min(0, Math.max(minX, enhancePanX));
|
||||
enhancePanY = Math.min(0, Math.max(minY, enhancePanY));
|
||||
}
|
||||
|
||||
function resetEnhanceZoom() {
|
||||
enhanceZoom = 1;
|
||||
enhancePanX = 0;
|
||||
enhancePanY = 0;
|
||||
applyEnhanceTransform();
|
||||
}
|
||||
|
||||
(function initEnhanceDrag() {
|
||||
const area = document.getElementById('enhanceCompare');
|
||||
if (!area) return;
|
||||
let dragging = false;
|
||||
let dividerDrag = false;
|
||||
let lastX = 0;
|
||||
let lastY = 0;
|
||||
const move = ev => {
|
||||
const rect = area.getBoundingClientRect();
|
||||
setEnhanceClip(((ev.clientX - rect.left) / rect.width) * 100);
|
||||
};
|
||||
area.addEventListener('pointerdown', ev => {
|
||||
dividerDrag = !!ev.target.closest('#enhanceDivider');
|
||||
dragging = true;
|
||||
lastX = ev.clientX;
|
||||
lastY = ev.clientY;
|
||||
area.setPointerCapture(ev.pointerId);
|
||||
if (!dividerDrag && enhanceZoom === 1) move(ev);
|
||||
});
|
||||
area.addEventListener('pointermove', ev => {
|
||||
if (!dragging) return;
|
||||
if (dividerDrag || enhanceZoom === 1) {
|
||||
move(ev);
|
||||
} else {
|
||||
area.classList.add('panning');
|
||||
enhancePanX += ev.clientX - lastX;
|
||||
enhancePanY += ev.clientY - lastY;
|
||||
lastX = ev.clientX;
|
||||
lastY = ev.clientY;
|
||||
clampEnhancePan();
|
||||
applyEnhanceTransform();
|
||||
}
|
||||
});
|
||||
const end = () => {
|
||||
dragging = false;
|
||||
area.classList.remove('panning');
|
||||
};
|
||||
area.addEventListener('pointerup', end);
|
||||
area.addEventListener('pointercancel', end);
|
||||
area.addEventListener('wheel', ev => {
|
||||
ev.preventDefault();
|
||||
const rect = area.getBoundingClientRect();
|
||||
const cx = ev.clientX - rect.left;
|
||||
const cy = ev.clientY - rect.top;
|
||||
const prev = enhanceZoom;
|
||||
const next = Math.min(5, Math.max(1, enhanceZoom * (ev.deltaY < 0 ? 1.15 : 1 / 1.15)));
|
||||
if (next === prev) return;
|
||||
enhanceZoom = next;
|
||||
enhancePanX = cx - (cx - enhancePanX) * (next / prev);
|
||||
enhancePanY = cy - (cy - enhancePanY) * (next / prev);
|
||||
clampEnhancePan();
|
||||
applyEnhanceTransform();
|
||||
}, { passive: false });
|
||||
area.addEventListener('dblclick', resetEnhanceZoom);
|
||||
})();
|
||||
|
||||
function estimateNoise(img) {
|
||||
const aw = 160;
|
||||
const ah = Math.max(1, Math.round(img.naturalHeight * aw / img.naturalWidth));
|
||||
const ac = document.createElement('canvas');
|
||||
ac.width = aw;
|
||||
ac.height = ah;
|
||||
const actx = ac.getContext('2d');
|
||||
actx.drawImage(img, 0, 0, aw, ah);
|
||||
const d = actx.getImageData(0, 0, aw, ah).data;
|
||||
let sum = 0;
|
||||
let n = 0;
|
||||
for (let y = 0; y < ah - 1; y++) {
|
||||
for (let x = 0; x < aw - 1; x++) {
|
||||
const i = (y * aw + x) * 4;
|
||||
const l = 0.299 * d[i] + 0.587 * d[i + 1] + 0.114 * d[i + 2];
|
||||
const lr = 0.299 * d[i + 4] + 0.587 * d[i + 5] + 0.114 * d[i + 6];
|
||||
const lb = 0.299 * d[i + aw * 4] + 0.587 * d[i + aw * 4 + 1] + 0.114 * d[i + aw * 4 + 2];
|
||||
sum += Math.abs(l - lr) + Math.abs(l - lb);
|
||||
n += 2;
|
||||
}
|
||||
}
|
||||
return n ? sum / n : 0;
|
||||
}
|
||||
|
||||
function autoEnhance() {
|
||||
if (!enhanceSourceImg) return;
|
||||
const img = enhanceSourceImg;
|
||||
const aw = 160;
|
||||
const ah = Math.max(1, Math.round(img.naturalHeight * aw / img.naturalWidth));
|
||||
const ac = document.createElement('canvas');
|
||||
ac.width = aw;
|
||||
ac.height = ah;
|
||||
const actx = ac.getContext('2d');
|
||||
actx.drawImage(img, 0, 0, aw, ah);
|
||||
const d = actx.getImageData(0, 0, aw, ah).data;
|
||||
const hist = new Array(256).fill(0);
|
||||
let total = 0;
|
||||
for (let i = 0; i < d.length; i += 4) {
|
||||
if (d[i + 3] < 16) continue;
|
||||
hist[Math.round(0.299 * d[i] + 0.587 * d[i + 1] + 0.114 * d[i + 2])]++;
|
||||
total++;
|
||||
}
|
||||
const pct = p => {
|
||||
let acc = 0;
|
||||
const target = total * p;
|
||||
for (let v = 0; v < 256; v++) {
|
||||
acc += hist[v];
|
||||
if (acc >= target) return v;
|
||||
}
|
||||
return 255;
|
||||
};
|
||||
let lo = pct(0.005);
|
||||
let hi = pct(0.995);
|
||||
if (hi - lo < 30) {
|
||||
lo = Math.max(0, lo - 15);
|
||||
hi = Math.min(255, hi + 15);
|
||||
}
|
||||
const contrast = Math.round(Math.min(150, Math.max(100, 25500 / (hi - lo))));
|
||||
const brightness = Math.round(Math.min(120, Math.max(85, 12800 / Math.max(1, (lo + hi) / 2))));
|
||||
const noise = estimateNoise(img);
|
||||
let denoise = 0;
|
||||
let sharp = 30;
|
||||
if (noise > 6) {
|
||||
denoise = Math.min(50, Math.round(noise * 6));
|
||||
sharp = 15;
|
||||
}
|
||||
const saturate = 106;
|
||||
document.getElementById('enhanceBrightness').value = brightness;
|
||||
document.getElementById('enhanceContrast').value = contrast;
|
||||
document.getElementById('enhanceSaturate').value = saturate;
|
||||
document.getElementById('enhanceDenoise').value = denoise;
|
||||
document.getElementById('enhanceSharp').value = sharp;
|
||||
scheduleEnhancePreview();
|
||||
}
|
||||
|
||||
const PHOTO_JOB_ACTION_LABELS = { ai: 'ИИ-обработка', ai_face: 'ИИ-обработка (лица)', enhance: 'Улучшение', restore: 'Возврат оригинала', rollback: 'Откат' };
|
||||
const PHOTO_JOB_STATUS_LABELS = { pending: 'В очереди', processing: 'Обрабатывается', done: 'Готово', error: 'Ошибка', rejected: 'Отклонено' };
|
||||
|
||||
function photoJobThumb(p) {
|
||||
if (!p) return '';
|
||||
if (p.startsWith('/uploads/.originals/')) return `${API}${p}`;
|
||||
return `${API}/uploads/thumb/${p.split('/').pop()}`;
|
||||
}
|
||||
|
||||
async function loadPhotoHistory() {
|
||||
if (!enhancePhotoId || !currentGroupId) return;
|
||||
const list = document.getElementById('photoHistoryList');
|
||||
if (!list) return;
|
||||
list.innerHTML = '<div style="color:var(--muted);font-size:.85rem">Загрузка...</div>';
|
||||
try {
|
||||
const res = await fetch(`${API}/api/groups/${currentGroupId}/photos/${enhancePhotoId}/jobs`, { headers: hdr() });
|
||||
if (!res.ok) throw new Error('Ошибка загрузки истории');
|
||||
const rows = await res.json();
|
||||
if (!rows.length) {
|
||||
list.innerHTML = '<div style="color:var(--muted);font-size:.85rem">Изменений фотографии пока не было.</div>';
|
||||
return;
|
||||
}
|
||||
list.innerHTML = rows.map(r => {
|
||||
const before = r.before_path ? `<img class="photo-thumb" loading="lazy" src="${esc(photoJobThumb(r.before_path))}" alt="было">` : '<span style="color:var(--muted)">—</span>';
|
||||
const after = r.after_path ? `<img class="photo-thumb" loading="lazy" src="${esc(photoJobThumb(r.after_path))}" alt="стало">` : '<span style="color:var(--muted)">—</span>';
|
||||
const canApply = r.status === 'done' && r.applied === false && (r.action === 'ai' || r.action === 'ai_face') && !!r.after_path;
|
||||
const canRollback = r.status === 'done' && r.before_path && r.action !== 'rollback' && !canApply;
|
||||
const err = r.error ? `<div style="color:#ef4444;font-size:.75rem;margin-top:4px">${esc(r.error)}</div>` : '';
|
||||
const time = r.finished_at || r.created_at;
|
||||
return `<div style="display:flex;gap:10px;align-items:center;border:1px solid var(--border);border-radius:10px;padding:10px">
|
||||
<div style="display:flex;flex-direction:column;gap:4px;text-align:center">
|
||||
${before}
|
||||
<span style="font-size:.65rem;color:var(--muted)">было</span>
|
||||
</div>
|
||||
<div style="color:var(--muted)">→</div>
|
||||
<div style="display:flex;flex-direction:column;gap:4px;text-align:center">
|
||||
${after}
|
||||
<span style="font-size:.65rem;color:var(--muted)">стало</span>
|
||||
</div>
|
||||
<div style="flex:1;min-width:0">
|
||||
<div style="font-size:.85rem">${esc(PHOTO_JOB_ACTION_LABELS[r.action] || r.action)}
|
||||
<span style="color:var(--muted);font-size:.75rem;margin-left:6px">${esc(PHOTO_JOB_STATUS_LABELS[r.status] || r.status)} · ${esc(fmtFull(time))}</span>
|
||||
</div>
|
||||
${err}
|
||||
</div>
|
||||
${canRollback ? `<button type="button" class="btn-primary ghost" style="white-space:nowrap" data-job-rollback="${r.id}">↩ Откатить</button>` : ''}
|
||||
${canApply ? `<button type="button" class="btn-primary" style="white-space:nowrap" data-job-apply="${r.id}">✓ Применить</button>` : ''}
|
||||
</div>`;
|
||||
}).join('');
|
||||
} catch (e) {
|
||||
list.innerHTML = `<div style="color:#ef4444;font-size:.85rem">${esc(e.message)}</div>`;
|
||||
}
|
||||
}
|
||||
|
||||
function openPhotoHistory() {
|
||||
if (!enhancePhotoId) return;
|
||||
document.getElementById('photoHistoryTitle').textContent = `История изменений фотографии — фото #${enhancePhotoId}`;
|
||||
document.getElementById('photoHistoryModal').classList.add('open');
|
||||
loadPhotoHistory();
|
||||
}
|
||||
|
||||
async function refreshEnhanceFromPath(mp) {
|
||||
document.getElementById('enhanceOrig').src = `${API}${mp}`;
|
||||
showEnhanceResult(false);
|
||||
setEnhanceLoadingText('Загрузка...');
|
||||
await new Promise(resolve => {
|
||||
const img = new Image();
|
||||
img.onload = () => { enhanceSourceImg = img; renderEnhancePreview(); resolve(); };
|
||||
img.onerror = () => { setEnhanceLoadingText('Не удалось загрузить фото'); resolve(); };
|
||||
img.src = `${API}${mp}`;
|
||||
});
|
||||
}
|
||||
|
||||
async function rollbackPhotoJob(jobId) {
|
||||
if (!enhancePhotoId || !currentGroupId || enhanceSaving) return;
|
||||
if (!confirm('Откатить фотографию к сохранённой версии? Текущая версия сохранится в истории.')) return;
|
||||
enhanceSaving = true;
|
||||
try {
|
||||
const res = await fetch(`${API}/api/groups/${currentGroupId}/photos/${enhancePhotoId}/jobs/${jobId}/rollback`, { method: 'POST', headers: hdr() });
|
||||
const data = await res.json().catch(() => ({}));
|
||||
if (!res.ok) throw new Error(data.error || 'Ошибка отката');
|
||||
showToast('Фотография откатана');
|
||||
document.getElementById('photoHistoryModal').classList.remove('open');
|
||||
await refreshEnhanceFromPath(data.photo_path);
|
||||
await loadGroupPhotos();
|
||||
loadGroups();
|
||||
} catch (e) {
|
||||
alert(e.message);
|
||||
} finally {
|
||||
enhanceSaving = false;
|
||||
}
|
||||
}
|
||||
|
||||
async function applyPhotoJob(jobId) {
|
||||
if (!enhancePhotoId || !currentGroupId || enhanceSaving) return;
|
||||
if (!confirm('Применить обработанную фотографию? Текущая версия сохранится в истории.')) return;
|
||||
enhanceSaving = true;
|
||||
try {
|
||||
const res = await fetch(`${API}/api/groups/${currentGroupId}/photos/${enhancePhotoId}/jobs/${jobId}/apply`, { method: 'POST', headers: hdr() });
|
||||
const data = await res.json().catch(() => ({}));
|
||||
if (!res.ok) throw new Error(data.error || 'Ошибка применения');
|
||||
showToast('Фотография обновлена');
|
||||
document.getElementById('photoHistoryModal').classList.remove('open');
|
||||
await refreshEnhanceFromPath(data.photo_path);
|
||||
await loadGroupPhotos();
|
||||
loadGroups();
|
||||
} catch (e) {
|
||||
alert(e.message);
|
||||
} finally {
|
||||
enhanceSaving = false;
|
||||
}
|
||||
}
|
||||
|
||||
async function saveEnhance() {
|
||||
if (!enhancePhotoId || !currentGroupId || !enhanceSourceImg || enhanceSaving) return;
|
||||
if (enhanceAiResultPath && isDefaultEnhanceParams()) return applyAiResult();
|
||||
const btn = document.getElementById('enhanceSaveBtn');
|
||||
enhanceSaving = true;
|
||||
if (btn) { btn.disabled = true; btn.textContent = 'Сохранение...'; }
|
||||
const groupId = currentGroupId;
|
||||
const photoId = enhancePhotoId;
|
||||
try {
|
||||
const img = enhanceSourceImg;
|
||||
const canvas = document.createElement('canvas');
|
||||
canvas.width = img.naturalWidth;
|
||||
canvas.height = img.naturalHeight;
|
||||
const ctx = canvas.getContext('2d');
|
||||
drawEnhanced(ctx, img, canvas.width, canvas.height);
|
||||
const blob = await new Promise((resolve, reject) => canvas.toBlob(b => b ? resolve(b) : reject(new Error('toBlob failed')), 'image/jpeg', 0.92));
|
||||
const fd = new FormData();
|
||||
fd.append('photo', blob, 'enhanced.jpg');
|
||||
const res = await fetch(`${API}/api/groups/${groupId}/photos/${photoId}/enhance`, { method: 'PUT', headers: hdr(), body: fd });
|
||||
if (!res.ok) { const err = await res.json().catch(() => ({})); throw new Error(err.error || 'Ошибка сохранения'); }
|
||||
enhanceSaving = false;
|
||||
showToast('Фото улучшено и сохранено');
|
||||
closeEnhance();
|
||||
await loadGroupPhotos();
|
||||
loadGroups();
|
||||
} catch (e) {
|
||||
enhanceSaving = false;
|
||||
alert(e.message);
|
||||
} finally {
|
||||
if (btn) { btn.disabled = false; btn.textContent = 'Применить'; }
|
||||
}
|
||||
}
|
||||
|
||||
function openEnhance(id) {
|
||||
const p = photos.find(x => x.id === id);
|
||||
if (!p) return;
|
||||
enhancePhotoId = id;
|
||||
enhanceAiJobId = null;
|
||||
enhanceAiResultPath = null;
|
||||
enhanceSourceImg = null;
|
||||
enhanceSaving = false;
|
||||
resetEnhanceZoom();
|
||||
setEnhanceClip(50);
|
||||
const modal = document.getElementById('enhanceModal');
|
||||
if (!modal) return;
|
||||
['Brightness', 'Contrast', 'Saturate'].forEach(k => {
|
||||
document.getElementById('enhance' + k).value = 100;
|
||||
document.getElementById('enhance' + k + 'Val').textContent = '100%';
|
||||
});
|
||||
document.getElementById('enhanceDenoise').value = 0;
|
||||
document.getElementById('enhanceDenoiseVal').textContent = '0%';
|
||||
document.getElementById('enhanceSharp').value = 0;
|
||||
document.getElementById('enhanceSharpVal').textContent = '0%';
|
||||
const orig = document.getElementById('enhanceOrig');
|
||||
if (orig) orig.src = API + p.photo_path;
|
||||
const btnAi = document.getElementById('enhanceAiBtn');
|
||||
if (btnAi) { btnAi.disabled = false; btnAi.textContent = '🤖 ИИ'; }
|
||||
const saveBtn = document.getElementById('enhanceSaveBtn');
|
||||
if (saveBtn) saveBtn.disabled = true;
|
||||
loadPhotoAiConfig().then(() => {
|
||||
const show = photoAiEnabled ? '' : 'none';
|
||||
if (btnAi) btnAi.style.display = show;
|
||||
const modeSel = document.getElementById('enhanceAiMode');
|
||||
if (modeSel) modeSel.style.display = show;
|
||||
updateAiHint();
|
||||
});
|
||||
showEnhanceResult(false);
|
||||
setEnhanceLoadingText('Загрузка...');
|
||||
const img = new Image();
|
||||
img.onload = () => {
|
||||
enhanceSourceImg = img;
|
||||
renderEnhancePreview();
|
||||
if (saveBtn) saveBtn.disabled = false;
|
||||
};
|
||||
img.onerror = () => setEnhanceLoadingText('Не удалось загрузить фото');
|
||||
img.src = API + p.photo_path;
|
||||
modal.classList.add('open');
|
||||
}
|
||||
|
||||
function closeEnhance() {
|
||||
cleanupAiPreview();
|
||||
const modal = document.getElementById('enhanceModal');
|
||||
if (modal) modal.classList.remove('open');
|
||||
const history = document.getElementById('photoHistoryModal');
|
||||
if (history) history.classList.remove('open');
|
||||
enhancePhotoId = null;
|
||||
enhanceAiJobId = null;
|
||||
enhanceAiResultPath = null;
|
||||
enhanceSourceImg = null;
|
||||
enhanceSaving = false;
|
||||
resetEnhanceZoom();
|
||||
if (enhanceTimer) { clearTimeout(enhanceTimer); enhanceTimer = null; }
|
||||
}
|
||||
|
||||
async function runPhotoAi() {
|
||||
if (!enhancePhotoId || !currentGroupId || enhanceSaving) return;
|
||||
const mode = photoAiMode();
|
||||
const faceNote = mode.face === 'off'
|
||||
? 'Может занять до минуты на CPU.'
|
||||
: `Восстановление лиц (${mode.face_model}), на CPU может занять несколько минут.`;
|
||||
if (!confirm(`ИИ-обработка фото: ${mode.title}. ${faceNote} Продолжить?`)) return;
|
||||
const btnAi = document.getElementById('enhanceAiBtn');
|
||||
const saveBtn = document.getElementById('enhanceSaveBtn');
|
||||
enhanceSaving = true;
|
||||
if (btnAi) { btnAi.disabled = true; btnAi.textContent = '⏳ ИИ...'; }
|
||||
if (saveBtn) saveBtn.disabled = true;
|
||||
showEnhanceResult(false);
|
||||
setEnhanceLoadingText(mode.face === 'off'
|
||||
? 'ИИ обрабатывает фото... (может занять до минуты)'
|
||||
: 'ИИ обрабатывает фото и восстанавливает лица...');
|
||||
try {
|
||||
const res = await fetch(API + `/api/groups/${currentGroupId}/photos/${enhancePhotoId}/enhance-ai`, {
|
||||
method: 'POST', headers: hdrJson(), body: JSON.stringify({ model: mode.model, face: mode.face, face_model: mode.face_model }),
|
||||
});
|
||||
if (!res.ok) { const e = await res.json().catch(() => ({})); throw new Error(e.error || 'Ошибка постановки задания'); }
|
||||
const data = await res.json();
|
||||
enhanceAiJobId = data.jobId;
|
||||
pollAiResult();
|
||||
} catch (err) {
|
||||
enhanceSaving = false;
|
||||
if (btnAi) { btnAi.disabled = false; btnAi.textContent = '🤖 ИИ'; }
|
||||
if (saveBtn) saveBtn.disabled = (enhanceAiJobId == null);
|
||||
showEnhanceResult(true);
|
||||
alert(err.message);
|
||||
}
|
||||
}
|
||||
|
||||
async function pollAiResult() {
|
||||
if (!enhancePhotoId || !enhanceAiJobId || !currentGroupId) return;
|
||||
try {
|
||||
const res = await fetch(API + `/api/groups/${currentGroupId}/photos/${enhancePhotoId}/enhance-ai/${enhanceAiJobId}`, { headers: hdr() });
|
||||
if (!res.ok) { const e = await res.json().catch(() => ({})); throw new Error(e.error || 'Ошибка статуса'); }
|
||||
const data = await res.json();
|
||||
if (data.status === 'done' && data.photo_path) {
|
||||
enhanceSaving = false;
|
||||
enhanceAiResultPath = data.photo_path;
|
||||
const btnAi = document.getElementById('enhanceAiBtn');
|
||||
if (btnAi) { btnAi.disabled = false; btnAi.textContent = '🤖 ИИ'; }
|
||||
const saveBtn = document.getElementById('enhanceSaveBtn');
|
||||
if (saveBtn) saveBtn.disabled = false;
|
||||
const img = new Image();
|
||||
img.onload = () => {
|
||||
enhanceSourceImg = img;
|
||||
['Brightness', 'Contrast', 'Saturate'].forEach(k => {
|
||||
document.getElementById('enhance' + k).value = 100;
|
||||
document.getElementById('enhance' + k + 'Val').textContent = '100%';
|
||||
});
|
||||
document.getElementById('enhanceDenoise').value = 0;
|
||||
document.getElementById('enhanceDenoiseVal').textContent = '0%';
|
||||
document.getElementById('enhanceSharp').value = 0;
|
||||
document.getElementById('enhanceSharpVal').textContent = '0%';
|
||||
renderEnhancePreview();
|
||||
};
|
||||
img.onerror = () => setEnhanceLoadingText('Не удалось загрузить результат ИИ');
|
||||
img.src = API + data.photo_path;
|
||||
showToast('ИИ результат готов');
|
||||
return;
|
||||
}
|
||||
if (data.status === 'error') {
|
||||
enhanceSaving = false;
|
||||
alert(data.error || 'Ошибка обработки');
|
||||
const btnAi = document.getElementById('enhanceAiBtn');
|
||||
if (btnAi) { btnAi.disabled = false; btnAi.textContent = '🤖 ИИ'; }
|
||||
showEnhanceResult(true);
|
||||
return;
|
||||
}
|
||||
setTimeout(pollAiResult, 2000);
|
||||
} catch (err) {
|
||||
enhanceSaving = false;
|
||||
alert(err.message);
|
||||
const btnAi = document.getElementById('enhanceAiBtn');
|
||||
if (btnAi) { btnAi.disabled = false; btnAi.textContent = '🤖 ИИ'; }
|
||||
showEnhanceResult(true);
|
||||
}
|
||||
}
|
||||
|
||||
async function applyAiResult() {
|
||||
if (!enhancePhotoId || !enhanceAiJobId || !currentGroupId || enhanceSaving) return;
|
||||
enhanceSaving = true;
|
||||
const saveBtn = document.getElementById('enhanceSaveBtn');
|
||||
if (saveBtn) { saveBtn.disabled = true; saveBtn.textContent = 'Применение...'; }
|
||||
const jobId = enhanceAiJobId;
|
||||
try {
|
||||
const res = await fetch(API + `/api/groups/${currentGroupId}/photos/${enhancePhotoId}/jobs/${jobId}/apply`, {
|
||||
method: 'POST', headers: hdrJson(),
|
||||
});
|
||||
if (!res.ok) { const e = await res.json().catch(() => ({})); throw new Error(e.error || 'Ошибка применения'); }
|
||||
enhanceAiJobId = null;
|
||||
enhanceAiResultPath = null;
|
||||
closeEnhance();
|
||||
await loadGroupPhotos();
|
||||
loadGroups();
|
||||
} catch (err) {
|
||||
alert(err.message);
|
||||
enhanceSaving = false;
|
||||
if (saveBtn) { saveBtn.disabled = false; saveBtn.textContent = 'Применить'; }
|
||||
}
|
||||
}
|
||||
|
||||
function cleanupAiPreview() {
|
||||
if (!enhancePhotoId || !currentGroupId || !enhanceAiJobId) return;
|
||||
fetch(API + `/api/groups/${currentGroupId}/photos/${enhancePhotoId}/jobs/${enhanceAiJobId}/reject`, {
|
||||
method: 'POST', headers: hdr(),
|
||||
}).catch(() => {});
|
||||
}
|
||||
|
||||
document.getElementById('enhanceCancelBtn')?.addEventListener('click', () => { closeEnhance(); });
|
||||
document.getElementById('enhanceAiBtn')?.addEventListener('click', runPhotoAi);
|
||||
document.getElementById('enhanceSaveBtn')?.addEventListener('click', saveEnhance);
|
||||
document.getElementById('enhanceAutoBtn')?.addEventListener('click', autoEnhance);
|
||||
document.getElementById('enhanceHistoryBtn')?.addEventListener('click', openPhotoHistory);
|
||||
document.getElementById('enhanceModal')?.addEventListener('click', e => { if (e.target === e.currentTarget) closeEnhance(); });
|
||||
document.getElementById('photoHistoryCloseBtn')?.addEventListener('click', () => {
|
||||
const m = document.getElementById('photoHistoryModal');
|
||||
if (m) m.classList.remove('open');
|
||||
});
|
||||
document.getElementById('photoHistoryModal')?.addEventListener('click', e => {
|
||||
if (e.target === e.currentTarget) e.currentTarget.classList.remove('open');
|
||||
});
|
||||
document.getElementById('photoHistoryList')?.addEventListener('click', e => {
|
||||
const rollbackBtn = e.target.closest('[data-job-rollback]');
|
||||
if (rollbackBtn) { rollbackPhotoJob(parseInt(rollbackBtn.dataset.jobRollback, 10)); return; }
|
||||
const applyBtn = e.target.closest('[data-job-apply]');
|
||||
if (applyBtn) applyPhotoJob(parseInt(applyBtn.dataset.jobApply, 10));
|
||||
});
|
||||
['enhanceBrightness', 'enhanceContrast', 'enhanceSaturate', 'enhanceDenoise', 'enhanceSharp'].forEach(id => {
|
||||
document.getElementById(id)?.addEventListener('input', scheduleEnhancePreview);
|
||||
});
|
||||
|
||||
loadPhotoAiConfig();
|
||||
|
||||
|
||||
Reference in New Issue
Block a user