let currentEntries = [];
let seenEntryIds = new Set();
let highlightNewIds = new Set();
let highlightClearTimer = null;
let editId = null;
let editGroups = [];
let editModules = [];
let moduleNames = new Map();
let moduleFilterId = '';
const MODULE_LIST_LIMIT = 1000;
let moduleSearchTimer = null;
let editModuleSearchTimer = null;
let moduleFilterSeq = 0;
let editModuleSeq = 0;
const moduleOptionsKeys = new Map();
let modulesLoaded = false;
let groupsLoaded = false;
let studentsLoaded = false;
const PAGE_SIZE = 20;
let page = 1;
let totalEntries = 0;
let searchTimer = null;
let view = localStorage.getItem('journalView') === 'cards' ? 'cards' : 'list';
let aiCorrecting = false;
let editDeletePhoto = false;
let editAiSuggestion = null;
let linkSettings = null;
async function loadLinkSettings() {
if (!linkSettings) {
const res = await fetch(`${API}/api/settings`, { headers: hdr() });
linkSettings = await res.json().catch(() => ({}));
}
return linkSettings;
}
function isImageFile(name) {
return /\.(jpe?g|jfif|png|gif|webp|bmp|avif|svg|ico)$/i.test(name || '');
}
function isPlayableVideoFile(name) {
return /\.(mp4|m4v|webm|ogv)$/i.test(name || '');
}
function isVideoFile(name) {
return /\.(mp4|m4v|webm|ogv|mov|mkv|avi|mpeg|mpg|3gp|ts)$/i.test(name || '');
}
function mainPhotoPath(e) {
if (e.photo_path) return e.photo_path;
if (e.photos && e.photos.length) return e.photos[0].photo_path;
return null;
}
function journalImgHTML(mp) {
return `
Загрузка…
`;
}
const REPORT_CARD_FIELDS = [
{ key: 'photo', label: 'Фото' },
{ key: 'lastname', label: 'Фамилия' },
{ key: 'firstname', label: 'Имя' },
{ key: 'group', label: 'Группа' },
{ key: 'module', label: 'Модуль' },
{ key: 'topic', label: 'Сообщение' },
{ key: 'date', label: 'Дата и время' },
{ key: 'files', label: 'Файлы' },
];
const REPORT_CARD_FIELDS_KEY = 'reportCardFields';
const reportCardFields = loadReportCardFields();
const REPORT_CARD_EMBED_KEY = 'reportCardEmbedImages';
let reportCardEmbed = loadReportCardEmbed();
const REPORT_CARD_STUDENT_WORKS_KEY = 'reportCardStudentWorks';
let reportCardStudentWorks = loadReportCardStudentWorks();
const REPORT_CARD_LOGO_KEY = 'reportCardLogo';
let reportCardLogoOn = loadReportCardLogo();
let reportCardLogoSrc = '';
let reportCardEntryId = null;
let galleryList = [];
let galleryIndex = -1;
const studentWorksCache = new Map();
const studentImagesCache = new Map();
let reportCardEmbedImages = [];
function loadReportCardEmbed() {
try {
return localStorage.getItem(REPORT_CARD_EMBED_KEY) === '1';
} catch (err) {
return false;
}
}
function saveReportCardEmbed() {
try {
localStorage.setItem(REPORT_CARD_EMBED_KEY, reportCardEmbed ? '1' : '0');
} catch (err) {
showToast('Не удалось сохранить настройку галереи', true);
}
}
function loadReportCardStudentWorks() {
try {
return localStorage.getItem(REPORT_CARD_STUDENT_WORKS_KEY) === '1';
} catch (err) {
return false;
}
}
function saveReportCardStudentWorks() {
try {
localStorage.setItem(REPORT_CARD_STUDENT_WORKS_KEY, reportCardStudentWorks ? '1' : '0');
} catch (err) {
showToast('Не удалось сохранить настройку «Фото на занятиях»', true);
}
}
function loadReportCardLogo() {
try {
return localStorage.getItem(REPORT_CARD_LOGO_KEY) !== '0';
} catch (err) {
return true;
}
}
function saveReportCardLogo() {
try {
localStorage.setItem(REPORT_CARD_LOGO_KEY, reportCardLogoOn ? '1' : '0');
} catch (err) {
showToast('Не удалось сохранить настройку «Логотип»', true);
}
}
function reportCardEmbedTokens() {
return new Set(reportCardEmbedImages.map(f => f.token));
}
function loadReportCardFields() {
const all = REPORT_CARD_FIELDS.map(f => f.key);
try {
const raw = JSON.parse(localStorage.getItem(REPORT_CARD_FIELDS_KEY) || 'null');
if (Array.isArray(raw)) return all.filter(k => raw.includes(k));
} catch (err) {
return all;
}
return all;
}
function saveReportCardFields() {
try {
localStorage.setItem(REPORT_CARD_FIELDS_KEY, JSON.stringify(reportCardFields));
} catch (err) {
showToast('Не удалось сохранить настройки полей', true);
}
}
function reportCardFieldOn(key) {
return reportCardFields.includes(key);
}
function splitStudentName(full) {
const s = String(full || '').trim();
const i = s.indexOf(' ');
if (i < 0) return { lastname: s, firstname: '' };
return { lastname: s.slice(0, i), firstname: s.slice(i + 1).trim() };
}
function reportCardFilesHTML(e) {
const hidden = reportCardEmbed ? reportCardEmbedTokens() : null;
const files = (e.files || []).filter(f => !(hidden && hidden.has(f.token)));
if (!files.length) return '';
return `
${files.map(f => {
const url = `${API}/api/files/${f.token}`;
if (isImageFile(f.name)) return `${esc(f.name)}`;
if (isPlayableVideoFile(f.name)) return `${esc(f.name)}`;
const note = isVideoFile(f.name) ? 'Скачать (браузер не умеет играть этот формат)' : 'Скачать';
return `${esc(f.name)}`;
}).join('')}
`;
}
function reportCardGalleryHTML() {
if (!reportCardEmbed) return '';
return '';
}
function paintReportCardEmbedGallery(box, images) {
if (!box) return;
box.classList.remove('is-loading');
if (!images.length) { box.remove(); galleryList = []; return; }
galleryList = images.map(f => `${API}/api/files/${f.token}`);
box.innerHTML = images.map((f, i) => {
const url = `${API}/api/files/${f.token}`;
return ``;
}).join('');
settleReportGallery(box);
equalizeReportGallery(box);
}
function equalizeReportGallery(root) {
if (!root) return;
const imgs = Array.from(root.querySelectorAll('.sc-gal__img'));
if (!imgs.length) return;
let pending = imgs.length;
const apply = () => {
requestAnimationFrame(() => {
let maxH = 0;
imgs.forEach(img => {
const h = img.getBoundingClientRect().height;
if (h > maxH) maxH = h;
});
if (maxH > 0) {
root.style.setProperty('--gal-h', `${Math.round(maxH)}px`);
root.classList.add('is-equal');
}
});
};
const done = () => { pending -= 1; if (pending <= 0) apply(); };
imgs.forEach(img => {
if (img.complete && img.naturalWidth > 0) { done(); return; }
img.addEventListener('load', done, { once: true });
img.addEventListener('error', done, { once: true });
});
}
function settleReportGallery(root) {
if (!root) return;
root.querySelectorAll('.sc-gal__img').forEach(img => {
const shot = img.closest('.sc-gal__shot');
const ready = () => {
img.classList.add('is-loaded');
if (img.naturalWidth > 0 && img.naturalHeight > 0 && img.naturalWidth > img.naturalHeight) img.classList.add('is-landscape');
if (shot) shot.classList.add('is-ready');
};
const failed = () => {
img.classList.add('is-error');
if (shot) shot.classList.add('is-error');
};
if (img.complete) {
if (img.naturalWidth > 0) ready(); else failed();
return;
}
img.addEventListener('load', ready, { once: true });
img.addEventListener('error', failed, { once: true });
});
}
async function hydrateReportCardEmbedGallery(e) {
const box = document.getElementById('reportCardEmbedGallery');
if (!box) { reportCardEmbedImages = []; galleryList = []; return; }
const name = String(e.student_name || '').trim();
if (!name) { reportCardEmbedImages = []; box.remove(); galleryList = []; return; }
let images = studentImagesCache.get(name);
if (!images) {
box.innerHTML = '';
try {
const res = await fetch(`${API}/api/students/image-files-by-name?name=${encodeURIComponent(name)}&limit=3`, { headers: hdr() });
const data = await res.json();
images = (data.files || []).filter(f => f && f.token);
studentImagesCache.set(name, images);
} catch (err) {
if (reportCardEntryId === e.id) {
const cur = document.getElementById('reportCardEmbedGallery');
if (cur) cur.remove();
}
return;
}
}
if (reportCardEntryId !== e.id) return;
reportCardEmbedImages = images;
paintReportCardEmbedGallery(box, images);
refreshReportCardFiles(e);
renderIcons();
}
function refreshReportCardFiles(e) {
const el = document.getElementById('reportCardFiles');
const html = reportCardFilesHTML(e);
if (!html) { if (el) el.remove(); return; }
if (el) el.outerHTML = html;
}
function paintReportCardStudentWorks(box, photos, entryId) {
if (!box || reportCardEntryId !== entryId) return;
if (!photos.length) { box.remove(); return; }
box.classList.remove('is-loading');
box.innerHTML = photos.map(p => ``).join('');
}
async function hydrateReportCardStudentWorks(e) {
const box = document.getElementById('reportCardStudentWorks');
if (!box) return;
const name = String(e.student_name || '').trim();
if (!name) { box.remove(); return; }
const key = `${name}#${e.id}`;
const cached = studentWorksCache.get(key);
if (cached) { paintReportCardStudentWorks(box, cached, e.id); return; }
box.classList.add('is-loading');
box.innerHTML = '';
try {
const res = await fetch(`${API}/api/students/works-by-name?name=${encodeURIComponent(name)}&limit=3&exclude_entry=${encodeURIComponent(e.id)}`, { headers: hdr() });
const data = await res.json();
const photos = (data.photos || []).filter(Boolean);
studentWorksCache.set(key, photos);
if (reportCardEntryId !== e.id) return;
paintReportCardStudentWorks(document.getElementById('reportCardStudentWorks'), photos, e.id);
} catch (err) {
if (reportCardEntryId === e.id) {
const cur = document.getElementById('reportCardStudentWorks');
if (cur) cur.remove();
}
}
}
function reportCardMetaHTML(e) {
let html = '';
if (reportCardFieldOn('date') && e.created_at) {
html += `
`;
}
function renderGrid() {
const grid = document.getElementById('grid');
if (!currentEntries.length) {
const fmt = d => d ? d.split('-').reverse().join('.') : '';
const from = fmt(document.getElementById('dateFrom').value);
const to = fmt(document.getElementById('dateTo').value);
let range = '';
if (from && to) range = ` за ${from} – ${to}`;
else if (from) range = ` с ${from}`;
else if (to) range = ` по ${to}`;
grid.className = 'grid';
grid.innerHTML = `
Ничего не найдено${range}
`;
return;
}
if (view === 'cards') {
grid.className = 'journal-cards';
grid.innerHTML = currentEntries.map(cardEntryHTML).join('');
} else {
grid.className = 'grid';
grid.innerHTML = currentEntries.map(gridEntryHTML).join('');
}
const items = Array.from(grid.children);
items.forEach((el, i) => {
el.style.animationDelay = `${Math.min(i * 45, 500)}ms`;
});
renderIcons();
settleJournalThumbs(grid);
}
function settleJournalThumbs(root) {
if (!root) return;
root.querySelectorAll('.img-media img.img-load, .img-media img.img-error').forEach((img) => {
if (img.complete && img.naturalWidth > 0) {
img.classList.remove('img-load', 'img-error');
img.classList.add('img-loaded');
} else if (img.complete && img.naturalWidth === 0) {
img.classList.remove('img-load');
img.classList.add('img-error');
const sk = img.parentElement && img.parentElement.querySelector('.img-skeleton');
if (sk) sk.innerHTML = 'Нет фото';
}
});
}
function bindJournalThumbLoading() {
const grid = document.getElementById('grid');
if (!grid) return;
const settle = (img) => {
if (!img || !img.classList) return;
img.classList.remove('img-load', 'img-error');
img.classList.add('img-loaded');
};
const fail = (img) => {
if (!img || !img.classList) return;
img.classList.remove('img-load');
img.classList.add('img-error');
const sk = img.parentElement && img.parentElement.querySelector('.img-skeleton');
if (sk) sk.innerHTML = 'Нет фото';
};
grid.addEventListener('load', (e) => {
if (e.target.tagName === 'IMG') settle(e.target);
}, true);
grid.addEventListener('error', (e) => {
if (e.target.tagName === 'IMG') fail(e.target);
}, true);
}
function refreshEntryCardDom(e) {
const btn = document.querySelector(`[data-edit="${e.id}"]`);
const card = btn ? btn.closest('.card, .journal-card') : null;
if (!card) return;
const tmp = document.createElement('div');
tmp.innerHTML = (view === 'cards' ? cardEntryHTML(e) : gridEntryHTML(e)).trim();
const fresh = tmp.firstElementChild;
fresh.classList.remove('entry-enter', 'entry-appear');
fresh.style.animationDelay = '';
card.replaceWith(fresh);
renderIcons();
settleJournalThumbs(fresh);
}
async function refreshEntryCard(id) {
const res = await fetch(`${API}/api/entries/${id}`, { headers: hdr() });
if (!res.ok) return false;
const e = await res.json();
const idx = currentEntries.findIndex(x => x.id === e.id);
if (idx !== -1) currentEntries[idx] = e;
refreshEntryCardDom(e);
return true;
}
function setView(v) {
view = v === 'cards' ? 'cards' : 'list';
localStorage.setItem('journalView', view);
document.querySelectorAll('#viewToggle button').forEach(b => {
b.classList.toggle('active', b.dataset.view === view);
});
renderGrid();
}
function setDefaultDates() {
const today = todayIso();
document.getElementById('dateFrom').value = today;
document.getElementById('dateTo').value = today;
}
async function loadGroupOptions() {
if (groupsLoaded) return;
const sel = document.getElementById('groupFilter');
while (sel.options.length > 1) sel.remove(1);
const res = await fetch(`${API}/api/groups`, { headers: hdr() });
const groups = await res.json();
groups.forEach(g => {
const o = document.createElement('option');
o.value = g.id; o.textContent = g.name;
sel.appendChild(o);
});
groupsLoaded = true;
}
function renderModuleOptions(datalistId, list, force) {
list.forEach(m => moduleNames.set(m.name, m.id));
const dl = document.getElementById(datalistId);
if (!dl) return;
const input = document.querySelector(`input[list="${datalistId}"]`);
const value = (input ? input.value : '').trim().toLowerCase();
if (!force && value && list.some(m => String(m.name).trim().toLowerCase() === value)) return;
const key = list.map(m => m.name).join('\n');
if (!force && key === moduleOptionsKeys.get(datalistId)) return;
moduleOptionsKeys.set(datalistId, key);
dl.innerHTML = '';
list.forEach(m => {
const opt = document.createElement('option');
opt.value = m.name;
dl.appendChild(opt);
});
}
async function fetchModules(q, limit, attempts = 2) {
const p = new URLSearchParams();
if (q) p.set('search', q);
p.set('limit', String(limit));
p.set('active', '1');
for (let i = 0; i < attempts; i++) {
try {
const res = await fetch(`${API}/api/modules?${p}`, { headers: hdr() });
if (!res.ok) return null;
const data = await res.json().catch(() => ({}));
return data.modules || [];
} catch (e) {
if (i < attempts - 1) await new Promise(r => setTimeout(r, 600));
}
}
return null;
}
async function resolveModuleId(name) {
const n = (name || '').trim();
if (!n) return '';
if (moduleNames.has(n)) return String(moduleNames.get(n));
const list = await fetchModules(n, 10);
if (!list) return null;
const lower = n.toLowerCase();
const exact = list.find(m => m.name.toLowerCase() === lower);
return exact ? String(exact.id) : null;
}
async function loadModuleOptions() {
const list = await fetchModules('', MODULE_LIST_LIMIT);
if (list) {
editModules = list;
modulesLoaded = true;
}
renderModuleOptions('moduleFilterList', editModules);
}
async function applyModuleFilter() {
const inp = document.getElementById('moduleFilter');
const resolved = await resolveModuleId(inp.value);
if (resolved === null) {
inp.value = '';
moduleFilterId = '';
showToast('Модуль не найден — фильтр сброшен');
} else {
moduleFilterId = resolved;
}
page = 1;
loadEntries();
}
function fillEditModuleInput(entry) {
const inp = document.getElementById('editModule');
if (!inp) return;
if (entry.module_name && entry.module_id) moduleNames.set(entry.module_name, entry.module_id);
inp.value = entry.module_name || '';
renderModuleOptions('editModuleList', editModules, true);
}
async function loadStudentOptions() {
if (studentsLoaded) return;
const dl = document.getElementById('studentFilterList');
const res = await fetch(`${API}/api/students/names`, { headers: hdr() });
const names = await res.json();
dl.innerHTML = names.map(n => ``).join('');
}
sel.value = e.group_id;
if (!modulesLoaded) await loadModuleOptions();
fillEditModuleInput(e);
renderEditPhotos(e.photos || [], e.photo_path);
document.getElementById('editModal').classList.add('open');
}
function renderEditPhotos(photos, mainPath) {
const preview = document.getElementById('editPhotoPreview');
preview.innerHTML = '';
if (!photos.length) return;
photos.forEach((p) => {
const isMain = p.photo_path === mainPath;
const div = document.createElement('div');
div.className = 'file-preview-item';
div.style.cssText = 'display:flex;align-items:center;gap:8px;padding:6px 8px;background:var(--bg);border:1px solid var(--border);border-radius:6px;font-size:.8rem';
div.dataset.photoId = p.id;
const applyStyle = isMain
? 'background:#16a34a;border:none;color:#fff;border-radius:6px;padding:4px 10px;font-size:.75rem;cursor:default;white-space:nowrap'
: 'background:var(--card);border:1px solid var(--border);color:var(--text);border-radius:6px;padding:4px 10px;font-size:.75rem;cursor:pointer;white-space:nowrap';
div.innerHTML = `${esc(p.photo_path.split('/').pop())} `;
preview.appendChild(div);
const thumb = div.querySelector('img');
const showMissing = () => {
const ph = document.createElement('span');
ph.textContent = 'нет файла';
ph.style.cssText = 'width:48px;height:48px;display:flex;align-items:center;justify-content:center;background:var(--bg);border:1px dashed var(--border);border-radius:4px;font-size:.6rem;color:var(--muted);text-align:center;line-height:1.1;flex:0 0 auto';
thumb.replaceWith(ph);
};
thumb.addEventListener('error', showMissing);
if (thumb.complete && thumb.naturalWidth === 0) showMissing();
div.querySelector('.delete-entry-photo').addEventListener('click', async () => {
if (!confirm('Удалить это фото?')) return;
const res = await fetch(`${API}/api/entries/${editId}/photos/${p.id}`, { method: 'DELETE', headers: hdr() });
if (res.ok) {
div.remove();
showToast('Фото удалено');
refreshEntryCard(editId);
} else {
alert('Ошибка удаления');
}
});
});
}
async function applyMainPhoto(btn) {
const div = btn.closest('.file-preview-item');
const photoId = div?.dataset.photoId;
if (!photoId) return;
btn.disabled = true;
const res = await fetch(`${API}/api/entries/${editId}/photos/${photoId}/main`, { method: 'PUT', headers: hdr() });
if (!res.ok) {
btn.disabled = false;
const err = await res.json().catch(() => ({}));
alert(err.error || 'Ошибка');
return;
}
document.querySelectorAll('#editPhotoPreview .apply-photo-btn').forEach(b => {
b.disabled = false;
b.textContent = 'Применить';
b.title = 'Сделать главным фото записи';
b.style.background = 'var(--card)';
b.style.color = 'var(--text)';
});
btn.disabled = true;
btn.textContent = 'Применено ✓';
btn.title = 'Главное фото записи';
btn.style.background = '#16a34a';
btn.style.color = '#fff';
showToast('Главное фото обновлено');
refreshEntryCard(editId);
}
function closeEdit() {
document.getElementById('editModal').classList.remove('open');
document.getElementById('editFiles').value = '';
document.getElementById('editFilesPreview').innerHTML = '';
document.getElementById('editPhoto').value = '';
document.getElementById('editPhotoPreview').innerHTML = '';
document.getElementById('editAiStatus').style.display = 'none';
editId = null;
editDeletePhoto = false;
}
let enhanceEntryId = null;
let enhanceSourceImg = null;
let enhanceTimer = null;
let enhanceSaving = false;
let enhanceEngine = 'auto';
let enhanceEngineLoaded = false;
let photoAiEnabled = false;
let photoAiFaceMode = 'off';
let photoAiFaceModel = 'gfpgan';
let photoAiDevice = '';
let photoAiPollTimer = null;
let enhanceAiResultPath = null;
let enhanceAiJobId = null;
let enhanceClipPos = 50;
function setEnhanceClip(p) {
enhanceClipPos = Math.min(100, Math.max(0, p));
document.getElementById('enhanceTop').style.clipPath = `inset(0 0 0 ${enhanceClipPos}%)`;
document.getElementById('enhanceDivider').style.left = enhanceClipPos + '%';
}
function showEnhanceResult(show) {
document.getElementById('enhanceTop').style.display = show ? '' : 'none';
document.getElementById('enhanceLoading').style.display = show ? 'none' : '';
}
function flashEnhanceResult() {
const area = document.getElementById('enhanceCompare');
if (!area) return;
area.classList.remove('enhance-flash');
void area.offsetWidth;
area.classList.add('enhance-flash');
setTimeout(() => area.classList.remove('enhance-flash'), 1200);
}
function setBtnLabel(btn, text) {
if (!btn) return;
const icon = btn.querySelector('svg, i[data-lucide]');
btn.textContent = '';
if (icon) {
btn.appendChild(icon);
btn.appendChild(document.createTextNode(' ' + text));
} else {
btn.textContent = text;
}
}
function setEnhanceLoadingText(text) {
const el = document.getElementById('enhanceLoading');
if (!el) return;
el.style.display = '';
const textEl = document.getElementById('enhanceThinkingText');
if (textEl) textEl.textContent = text;
const dots = el.querySelector('.enhance-thinking-dots');
if (dots) dots.style.display = '';
const progress = document.getElementById('enhanceProgress');
if (progress) progress.style.display = 'none';
}
function setEnhanceLoadingProgress(pct, text) {
const el = document.getElementById('enhanceLoading');
if (!el) return;
el.style.display = '';
const textEl = document.getElementById('enhanceThinkingText');
if (textEl && text) textEl.textContent = text;
const dots = el.querySelector('.enhance-thinking-dots');
if (dots) dots.style.display = pct >= 100 ? 'none' : '';
const progress = document.getElementById('enhanceProgress');
const bar = document.getElementById('enhanceProgressBar');
if (progress && bar) {
progress.style.display = '';
bar.style.width = Math.min(100, Math.max(0, pct)) + '%';
}
}
let enhanceZoom = 1;
let enhancePanX = 0;
let enhancePanY = 0;
function applyEnhanceTransform() {
const t = `translate(${enhancePanX}px, ${enhancePanY}px) scale(${enhanceZoom})`;
document.getElementById('enhanceStage').style.transform = t;
document.getElementById('enhanceInner').style.transform = t;
const area = document.getElementById('enhanceCompare');
area.classList.toggle('zoomed', enhanceZoom > 1);
if (enhanceZoom <= 1) area.classList.remove('panning');
}
function clampEnhancePan() {
const rect = document.getElementById('enhanceCompare').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');
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);
})();
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';
}
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) {}
}
async function loadEnhanceEngine() {
if (enhanceEngineLoaded) return;
enhanceEngineLoaded = true;
try {
const r = await fetch(`${API}/api/public-settings`);
const f = await r.json();
if (['auto', 'server', 'client'].includes(f.photo_enhance_engine)) enhanceEngine = f.photo_enhance_engine;
photoAiEnabled = f.photo_ai_enabled === 'true';
if (['off', 'face', 'all'].includes(f.photo_ai_face_mode)) photoAiFaceMode = f.photo_ai_face_mode;
if (['gfpgan', 'codeformer'].includes(f.photo_ai_face_model)) photoAiFaceModel = f.photo_ai_face_model;
const sel = document.getElementById('enhanceAiMode');
if (sel) sel.value = defaultPhotoAiModeKey();
loadPhotoAiDevice();
} catch (e) {}
}
async function runPhotoAi() {
if (!enhanceEntryId || enhanceSaving) return;
const entryId = enhanceEntryId;
const mode = photoAiMode();
const faceNote = mode.face === 'off'
? 'Может занять до минуты на CPU.'
: `Восстановление лиц (${mode.face_model}), на CPU может занять несколько минут.`;
if (!confirm(`ИИ-обработка фото: ${mode.title}. ${faceNote} Продолжить?`)) return;
enhanceSaving = true;
const btn = document.getElementById('enhanceAiBtn');
if (btn) btn.disabled = true;
try {
const res = await fetch(`${API}/api/entries/${entryId}/photo/enhance-ai`, {
method: 'POST',
headers: hdrJson(),
body: JSON.stringify({ model: mode.model, face: mode.face, face_model: mode.face_model }),
});
if (!res.ok) {
const err = await res.json().catch(() => ({}));
throw new Error(err.error || 'Ошибка запуска ИИ');
}
const { jobId } = await res.json();
enhanceAiJobId = jobId;
showEnhanceResult(false);
setEnhanceLoadingProgress(0, mode.face === 'off'
? 'ИИ обрабатывает фото...'
: 'ИИ обрабатывает фото и восстанавливает лица...');
setBtnLabel(btn, '⏳ ИИ...');
let doneHandled = false;
const result = await new Promise((resolve, reject) => {
photoAiPollTimer = setInterval(async () => {
if (doneHandled) 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 (doneHandled) return;
if (s.status === 'done') {
doneHandled = true;
clearInterval(photoAiPollTimer);
setEnhanceLoadingProgress(100, 'Загрузка результата...');
resolve(s);
}
else if (s.status === 'error') {
doneHandled = true;
clearInterval(photoAiPollTimer);
showEnhanceResult(true);
reject(new Error(s.error || 'Ошибка ИИ'));
}
else {
const progress = Math.min(95, Date.now() % 10000 / 100);
setEnhanceLoadingProgress(progress, mode.face === 'off'
? 'ИИ обрабатывает фото...'
: 'ИИ обрабатывает фото и восстанавливает лица...');
}
} catch (e) {
doneHandled = true;
clearInterval(photoAiPollTimer);
showEnhanceResult(true);
reject(e);
}
}, 500);
});
showToast('ИИ результат готов');
enhanceAiResultPath = result.photo_path;
const aiImg = new Image();
aiImg.onload = () => {
enhanceSourceImg = aiImg;
['Brightness', 'Contrast', 'Saturate'].forEach(k => {
document.getElementById('enhance' + k).value = 100;
document.getElementById('enhance' + k + 'Val').textContent = '100%';
});
document.getElementById('enhanceSharp').value = 0;
document.getElementById('enhanceSharpVal').textContent = '0%';
document.getElementById('enhanceDenoise').value = 0;
document.getElementById('enhanceDenoiseVal').textContent = '0%';
renderEnhancePreview();
flashEnhanceResult();
};
aiImg.onerror = () => { showEnhanceResult(true); showToast('Не удалось загрузить результат ИИ'); };
aiImg.src = `${API}${result.photo_path}`;
} catch (e) {
showEnhanceResult(true);
alert(e.message);
} finally {
enhanceSaving = false;
if (btn) btn.disabled = false;
setBtnLabel(btn, 'ИИ');
}
}
async function restoreOriginal() {
if (!enhanceEntryId || enhanceSaving) return;
if (!confirm('Вернуть исходную фотографию? Текущая улучшенная версия будет удалена.')) return;
enhanceSaving = true;
const btn = document.getElementById('enhanceRestoreBtn');
btn.disabled = true;
try {
const res = await fetch(`${API}/api/entries/${enhanceEntryId}/photo/restore-original`, { method: 'POST', headers: hdr() });
if (!res.ok) {
const err = await res.json().catch(() => ({}));
throw new Error(err.error || 'Ошибка восстановления');
}
const savedId = enhanceEntryId;
showToast('Оригинал возвращён');
closeEnhance();
refreshEntryCard(savedId);
} catch (e) {
alert(e.message);
} finally {
enhanceSaving = false;
btn.disabled = false;
}
}
function openEnhance(id) {
const e = currentEntries.find(x => x.id === id);
if (!e) return;
const mp = mainPhotoPath(e);
if (!mp) { showToast('У записи нет фото'); return; }
enhanceEntryId = id;
enhanceSourceImg = null;
enhanceAiResultPath = null;
enhanceAiJobId = null;
['Brightness', 'Contrast', 'Saturate'].forEach(k => {
const el = document.getElementById('enhance' + k);
el.value = 100;
document.getElementById('enhance' + k + 'Val').textContent = '100%';
});
const sharp = document.getElementById('enhanceSharp');
sharp.value = 0;
document.getElementById('enhanceSharpVal').textContent = '0%';
const orig = document.getElementById('enhanceOrig');
orig.src = `${API}${mp}`;
document.getElementById('enhanceRestoreBtn').style.display = e.photo_original_path ? '' : 'none';
const aiBtn = document.getElementById('enhanceAiBtn');
if (aiBtn) { aiBtn.disabled = false; setBtnLabel(aiBtn, 'ИИ'); }
loadEnhanceEngine().then(() => {
const show = photoAiEnabled ? '' : 'none';
document.getElementById('enhanceAiBtn').style.display = show;
document.getElementById('enhanceAiMode').style.display = show;
updateAiHint();
});
const canvas = document.getElementById('enhanceCanvas');
setEnhanceClip(50);
resetEnhanceZoom();
showEnhanceResult(false);
setEnhanceLoadingProgress(0, 'Загрузка...');
renderIcons();
const img = new Image();
img.onload = () => {
if (enhanceAiResultPath) return;
enhanceSourceImg = img;
renderEnhancePreview();
};
img.onerror = () => {
const loadingEl = document.getElementById('enhanceLoading');
if (loadingEl) {
const textEl = document.getElementById('enhanceThinkingText');
if (textEl) textEl.textContent = 'Не удалось загрузить фото';
const dots = loadingEl.querySelector('.enhance-thinking-dots');
if (dots) dots.style.display = 'none';
const progress = document.getElementById('enhanceProgress');
if (progress) progress.style.display = 'none';
}
};
img.src = `${API}${mp}`;
document.getElementById('enhanceModal').classList.add('open');
}
function isDefaultEnhanceParams() {
const p = enhanceParams();
return p.brightness === 100 && p.contrast === 100 && p.saturate === 100 && p.denoise === 0 && p.sharp === 0;
}
async function applyAiResult(signal) {
if (!enhanceAiJobId || !enhanceEntryId) return false;
const res = await fetch(`${API}/api/entries/${enhanceEntryId}/photo/jobs/${enhanceAiJobId}/apply`, {
method: 'POST',
headers: hdr(),
signal,
});
const data = await res.json().catch(() => ({}));
if (!res.ok) throw new Error(data.error || 'Ошибка применения ИИ-результата');
enhanceAiResultPath = null;
enhanceAiJobId = null;
return true;
}
function cleanupAiPreview() {
if (!enhanceEntryId) return;
if (enhanceAiJobId) {
fetch(`${API}/api/entries/${enhanceEntryId}/photo/jobs/${enhanceAiJobId}/reject`, {
method: 'POST',
headers: hdr(),
}).catch(() => {});
} else if (enhanceAiResultPath) {
fetch(`${API}/api/entries/${enhanceEntryId}/photo/enhance-ai/preview`, {
method: 'DELETE',
headers: hdrJson(),
body: JSON.stringify({ path: enhanceAiResultPath }),
}).catch(() => {});
}
enhanceAiResultPath = null;
enhanceAiJobId = null;
}
function closeEnhance() {
cleanupAiPreview();
document.getElementById('enhanceModal').classList.remove('open');
document.getElementById('photoHistoryModal').classList.remove('open');
enhanceEntryId = null;
enhanceSourceImg = null;
enhanceAiResultPath = null;
const loadingEl = document.getElementById('enhanceLoading');
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;
const applyCpuBtn = document.getElementById('cpuEnhanceApplyCpuBtn');
if (applyCpuBtn) applyCpuBtn.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 applyCpuLabel = document.getElementById('cpuEnhanceApplyCpuLabel');
if (applyCpuLabel) applyCpuLabel.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);
}
}
}
async function cpuEnhanceApplyCpuOnly() {
if (!cpuEnhanceEntryId || cpuEnhanceSaving) return;
const entryId = cpuEnhanceEntryId;
const label = document.getElementById('cpuEnhanceApplyCpuLabel');
cpuEnhanceSaving = true;
cpuEnhanceClearError();
if (label) label.textContent = 'Сохраняю…';
cpuEnhanceSetBusy(true);
cpuEnhanceSetLoading(true, 'Применение эффектов…');
try {
const res = await fetch(`${API}/api/entries/${entryId}/photo/enhance-cpu`, {
method: 'POST',
headers: hdrJson(),
body: JSON.stringify({
mode: 'cpu',
params: { ...cpuEnhanceReadParams(), preset: 'quality' },
face: 'off',
face_model: 'gfpgan',
}),
});
const data = await res.json().catch(() => ({}));
if (!res.ok) throw new Error(data.error || 'Ошибка обработки');
showToast('Эффекты применены, ИИ не использовался');
closeCpuEnhance(true);
refreshEntryCard(entryId);
} catch (e) {
cpuEnhanceSetError(e.message);
showToast(e.message, true);
} finally {
cpuEnhanceSaving = false;
if (label) label.textContent = 'Только эффекты';
cpuEnhanceSetLoading(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}`;
return `${API}/uploads/thumb/${p.split('/').pop()}`;
}
const PHOTO_JOB_ACTION_LABELS = { ai: 'ИИ-обработка', enhance: 'Улучшение', restore: 'Возврат оригинала', rollback: 'Откат' };
const PHOTO_JOB_STATUS_LABELS = { pending: 'В очереди', processing: 'Обрабатывается', done: 'Готово', error: 'Ошибка', rejected: 'Отклонено' };
async function loadPhotoHistory() {
if (!enhanceEntryId) return;
const list = document.getElementById('photoHistoryList');
list.innerHTML = '
Загрузка...
';
try {
const res = await fetch(`${API}/api/entries/${enhanceEntryId}/photo/jobs`, { headers: hdr() });
if (!res.ok) throw new Error('Ошибка загрузки истории');
const rows = await res.json();
if (!rows.length) {
list.innerHTML = '