Рамки в #faceViewerModal уезжали после улучшения фотографии. Причина:
photo_faces.bbox хранит абсолютные пиксели того файла, который сканировали,
а фронт делит их на naturalWidth/naturalHeight текущей картинки. Апскейл ×2/×4
подменял photo_path, apply-маршруты меняли только путь — рамки оставались в
пикселях старого разрешения. При этом face_scanned_at не сбрасывался, поэтому
ни автоскан, ни «Найти лица» их не подхватывали.
- face_img_width/face_img_height в group_photos/entry_photos — размеры
картинки, к которой относятся сохранённые рамки. Пишет scanFacesForPhoto
из ответа /detect: faceIdDetect теперь возвращает { faces, width, height }
- rescalePhotoFaces() пересчитывает bbox пропорционально и обновляет
photo_faces.photo_path (без него фильтр «по лицам» в /api/photos отваливался
бы после apply). Вызывается из всех мест, меняющих photo_path: apply и
rollback для группы и для записи журнала
- Если размеры неизвестны (строка просканирована до появления колонок) —
рамки сбрасываются, face_scanned_at = NULL, фото уходит в фоновый скан
- POST /api/photos/:sourceType/:sourceId/faces/rescan + кнопка
«Переиндексировать»; эндпоинт чтения отдаёт img_width/img_height,
checkFaceViewerSync() предупреждает о подмене файла, refreshOpenFaceViewer()
перерисовывает вьюер после apply/rollback/сохранения улучшения
- Колонки добавлены в db/init.sql, db/migration.sql, ensureFaceTables(),
normalizeRestoreData и restore-INSERT
Проверено: apply фото 4032×2268 → 8064×4536 пересчитал рамки ровно вдвое,
откат вернул исходные координаты; api.smoketest 124 PASS / 0 FAIL,
backup.selftest OK, migration.sql в транзакции с откатом.
1571 lines
67 KiB
JavaScript
1571 lines
67 KiB
JavaScript
const DAYS = ['Вс', 'Пн', 'Вт', 'Ср', 'Чт', 'Пт', 'Сб'];
|
||
const FACE_CANDIDATE_MIN = 0.5;
|
||
const facePct = v => Math.round((Number(v) || 0) * 100) + '%';
|
||
const faceCandidateMin = () => (Number(faceViewer.candidateMin) > 0 ? Number(faceViewer.candidateMin) : FACE_CANDIDATE_MIN);
|
||
let branchesCache = [];
|
||
let tutorsCache = [];
|
||
let allGroups = [];
|
||
let currentCover = null;
|
||
|
||
async function loadBranchesCache() {
|
||
const res = await fetch(`${API}/api/branches`, { headers: hdr() });
|
||
if (res.ok) branchesCache = await res.json();
|
||
}
|
||
|
||
async function loadTutorsCache() {
|
||
const res = await fetch(`${API}/api/users/tutors`, { headers: hdr() });
|
||
if (res.ok) tutorsCache = await res.json();
|
||
}
|
||
|
||
function tutorSelectHTML(selectedId) {
|
||
const opts = tutorsCache.map(t => `<option value="${t.id}" ${t.id === selectedId ? 'selected' : ''}>${esc(t.name || t.username)}</option>`).join('');
|
||
return `<div><label>Тутор</label><select class="tutor-select" style="background:var(--bg);border:1px solid var(--border);color:var(--text);border-radius:6px;padding:6px 8px;font-size:.8rem"><option value="">— не назначен —</option>${opts}</select></div>`;
|
||
}
|
||
|
||
function branchSelectHTML(selectedId) {
|
||
const opts = branchesCache.map(b => `<option value="${b.id}" ${b.id === selectedId ? 'selected' : ''}>${esc(b.name)}</option>`).join('');
|
||
return `<div><label>Филиал</label><select class="branch-select" style="background:var(--bg);border:1px solid var(--border);color:var(--text);border-radius:6px;padding:6px 8px;font-size:.8rem"><option value="">— без филиала —</option>${opts}</select></div>`;
|
||
}
|
||
|
||
async function loadGroups() {
|
||
await loadBranchesCache();
|
||
await loadTutorsCache();
|
||
const res = await fetch(`${API}/api/groups`, { headers: hdr() });
|
||
const groups = await res.json();
|
||
allGroups = groups;
|
||
const list = document.getElementById('groupList');
|
||
if (!groups.length) { list.innerHTML = '<div style="color:var(--muted);text-align:center;padding:32px">Нет групп</div>'; return; }
|
||
list.innerHTML = `<div class="group-grid">` + groups.map(g => {
|
||
const schedSet = g.day_of_week != null && g.time_start && g.time_end;
|
||
return `
|
||
<div class="group-card" data-group-id="${g.id}">
|
||
${g.cover_path
|
||
? `<img class="group-cover" src="${thumbSrc(g.cover_path)}" data-img="${API}${g.cover_path}" loading="lazy" decoding="async" alt="">`
|
||
: `<div class="group-cover empty-cover">📷</div>`}
|
||
<div class="group-head">
|
||
<input class="name-input" id="name-${g.id}" value="${esc(g.name)}">
|
||
<button class="del" data-del-group="${g.id}" title="Удалить">×</button>
|
||
</div>
|
||
<div class="group-schedule">
|
||
${branchSelectHTML(g.branch_id)}
|
||
${tutorSelectHTML(g.tutor_id)}
|
||
<div><label>День</label>
|
||
<select id="dow-${g.id}">
|
||
<option value="">—</option>
|
||
${DAYS.map((d, i) => `<option value="${i}" ${g.day_of_week === i ? 'selected' : ''}>${d}</option>`).join('')}
|
||
</select>
|
||
</div>
|
||
<div><label>С</label>
|
||
<input type="time" id="ts-${g.id}" value="${g.time_start ? g.time_start.slice(0,5) : ''}">
|
||
</div>
|
||
<div><label>По</label>
|
||
<input type="time" id="te-${g.id}" value="${g.time_end ? g.time_end.slice(0,5) : ''}">
|
||
</div>
|
||
</div>
|
||
<div class="group-foot">
|
||
<div style="display:flex;gap:8px">
|
||
<button class="save-sched" data-save-group="${g.id}">Сохранить</button>
|
||
<button class="photo-btn" data-group-id="${g.id}" data-group-name="${esc(g.name)}" title="Фото группы (хронология)">Фото</button>
|
||
<button class="btn-link" data-export-group="${g.id}" data-group-name="${esc(g.name)}" title="Экспортировать записи группы">CSV</button>
|
||
<button class="btn-link" data-export-urls="${g.id}" data-group-name="${esc(g.name)}" title="Скачать .url файлы учеников группы">URL</button>
|
||
<button class="btn-link" data-export-files="${g.id}" data-group-name="${esc(g.name)}" title="Скачать ZIP-архив файлов группы за период">ZIP</button>
|
||
</div>
|
||
<div class="sched-status">${schedSet ? `${DAYS[g.day_of_week]} ${fmtHmStr(g.time_start)}–${fmtHmStr(g.time_end)}` : 'Не настроено'}</div>
|
||
</div>
|
||
</div>`;
|
||
}).join('') + `</div>`;
|
||
}
|
||
|
||
async function saveGroup(id) {
|
||
const name = document.getElementById(`name-${id}`).value.trim();
|
||
if (!name) return;
|
||
const nameInput = document.getElementById(`name-${id}`);
|
||
const groupCard = nameInput.closest('.group-card');
|
||
const branchSelect = groupCard ? groupCard.querySelector('.branch-select') : null;
|
||
const branch_id = branchSelect ? branchSelect.value : '';
|
||
const tutorSelect = groupCard ? groupCard.querySelector('.tutor-select') : null;
|
||
const tutor_id = tutorSelect ? (tutorSelect.value || null) : undefined;
|
||
const dow = document.getElementById(`dow-${id}`).value;
|
||
const ts = document.getElementById(`ts-${id}`).value;
|
||
const te = document.getElementById(`te-${id}`).value;
|
||
const res = await fetch(`${API}/api/groups/${id}`, {
|
||
method: 'PUT',
|
||
headers: hdrJson(),
|
||
body: JSON.stringify({ name, branch_id: branch_id || null, tutor_id, day_of_week: dow !== '' ? parseInt(dow) : null, time_start: ts || null, time_end: te || null })
|
||
});
|
||
if (res.ok) {
|
||
loadGroups();
|
||
const dayLabel = dow !== '' ? DAYS[dow] : 'без расписания';
|
||
const timeLabel = ts && te ? `, ${ts}–${te}` : '';
|
||
showToast(`Сохранено: «${name}» — ${dayLabel}${timeLabel}`);
|
||
} else { const e = await res.json(); alert(e.error); }
|
||
}
|
||
|
||
async function addGroup() {
|
||
const input = document.getElementById('newGroup');
|
||
const name = input.value.trim();
|
||
if (!name) return;
|
||
await loadBranchesCache();
|
||
await loadTutorsCache();
|
||
const branchSelect = document.getElementById('newGroupBranch');
|
||
const branch_id = branchSelect ? branchSelect.value : '';
|
||
const tutorSelect = document.getElementById('newGroupTutor');
|
||
const tutor_id = tutorSelect && tutorSelect.value ? tutorSelect.value : null;
|
||
const res = await fetch(`${API}/api/groups`, { method: 'POST', headers: hdrJson(), body: JSON.stringify({ name, branch_id: branch_id || null, tutor_id }) });
|
||
if (res.ok) { input.value = ''; loadGroups(); }
|
||
else { const e = await res.json(); alert(e.error); }
|
||
}
|
||
|
||
async function delGroup(id) {
|
||
if (!confirm('Удалить группу? Группа попадёт в корзину, восстановить её можно будет позже.')) return;
|
||
const res = await fetch(`${API}/api/groups/${id}`, { method: 'DELETE', headers: hdr() });
|
||
if (!res.ok) { const e = await res.json(); alert(e.error || 'Ошибка'); }
|
||
loadGroups();
|
||
}
|
||
|
||
const PHOTO_PAGE_SIZE = 24;
|
||
let currentGroupId = null;
|
||
let currentGroupName = '';
|
||
let photos = [];
|
||
let photoPage = 1;
|
||
let totalPhotos = 0;
|
||
let editingPhotoId = null;
|
||
|
||
async function openPhotos(groupId, groupName) {
|
||
currentGroupId = groupId;
|
||
currentGroupName = groupName;
|
||
const g = allGroups.find(x => String(x.id) === String(groupId));
|
||
currentCover = g ? g.cover_path : null;
|
||
photoPage = 1;
|
||
editingPhotoId = null;
|
||
document.getElementById('photosTitle').textContent = `Фото — ${groupName}`;
|
||
document.getElementById('photosModal').classList.add('open');
|
||
await loadAllStudents();
|
||
renderFaceStudentFilter();
|
||
await loadGroupPhotos();
|
||
}
|
||
|
||
function closePhotos() {
|
||
document.getElementById('photosModal').classList.remove('open');
|
||
currentGroupId = null;
|
||
}
|
||
|
||
async function loadGroupPhotos() {
|
||
const p = new URLSearchParams();
|
||
p.set('limit', PHOTO_PAGE_SIZE);
|
||
p.set('offset', (photoPage - 1) * PHOTO_PAGE_SIZE);
|
||
const sel = document.getElementById('faceStudentFilter');
|
||
const fv = sel ? sel.value : '';
|
||
if (fv === '__unassigned__') p.set('unassigned_faces', '1');
|
||
else if (fv) p.set('student_id', fv);
|
||
const res = await fetch(`${API}/api/groups/${currentGroupId}/photos?${p}`, { headers: hdr() });
|
||
const data = await res.json();
|
||
photos = data.photos;
|
||
totalPhotos = data.total;
|
||
document.getElementById('photoGrid').className = 'photo-grid';
|
||
document.getElementById('photoGrid').innerHTML = photos.length
|
||
? photos.map(photoHTML).join('')
|
||
: '<div class="empty" style="grid-column:1/-1">Фото пока нет. Загрузите первое фото.</div>';
|
||
renderIcons();
|
||
renderPager(document.getElementById('photosPager'), photoPage, Math.max(1, Math.ceil(totalPhotos / PHOTO_PAGE_SIZE)), goPhotoPage);
|
||
}
|
||
|
||
function goPhotoPage(p) { photoPage = p; loadGroupPhotos(); }
|
||
|
||
let allStudents = [];
|
||
let allStudentsLoaded = false;
|
||
let faceViewer = { photoId: null, faces: [], sourceType: 'group', layout: null, candidateMin: FACE_CANDIDATE_MIN };
|
||
let faceAssignFaceId = null;
|
||
|
||
async function loadAllStudents() {
|
||
if (allStudentsLoaded) return;
|
||
try {
|
||
const res = await fetch(`${API}/api/students`, { headers: hdr() });
|
||
const data = res.ok ? await res.json() : null;
|
||
const list = Array.isArray(data) ? data : (data && data.students) || [];
|
||
allStudents = list
|
||
.filter(s => !s.deleted_at)
|
||
.map(s => ({ id: s.id, name: s.name, group_id: s.group_id, group_name: s.group_name || '' }));
|
||
allStudentsLoaded = true;
|
||
} catch {
|
||
allStudents = [];
|
||
}
|
||
}
|
||
|
||
function groupStudents() {
|
||
return allStudents.filter(s => String(s.group_id) === String(currentGroupId));
|
||
}
|
||
|
||
function renderFaceStudentFilter() {
|
||
const sel = document.getElementById('faceStudentFilter');
|
||
if (!sel) return;
|
||
const cur = sel.value;
|
||
sel.innerHTML = '<option value="">Без фильтра</option><option value="__unassigned__">Неопознанные лица</option>';
|
||
groupStudents().forEach(s => {
|
||
const o = document.createElement('option');
|
||
o.value = String(s.id);
|
||
o.textContent = s.name;
|
||
sel.appendChild(o);
|
||
});
|
||
if (Array.from(sel.options).some(o => o.value === cur)) sel.value = cur;
|
||
}
|
||
|
||
async function loadFaceViewerFaces(photoId) {
|
||
const res = await fetch(`${API}/api/photos/group/${photoId}/faces`, { headers: hdr() });
|
||
if (!res.ok) {
|
||
const err = new Error(res.status === 404 ? 'Фото не найдено' : 'Не удалось загрузить лица');
|
||
err.status = res.status;
|
||
throw err;
|
||
}
|
||
const data = await res.json();
|
||
faceViewer.faces = data.faces || [];
|
||
faceViewer.candidateMin = Number(data.candidate_min) > 0 ? Number(data.candidate_min) : FACE_CANDIDATE_MIN;
|
||
faceViewer.imgWidth = Number(data.img_width) || 0;
|
||
faceViewer.imgHeight = Number(data.img_height) || 0;
|
||
faceViewer.scanned = Boolean(data.scanned);
|
||
return faceViewer;
|
||
}
|
||
|
||
async function refreshOpenFaceViewer() {
|
||
const photoId = faceViewer.photoId;
|
||
if (!photoId) return;
|
||
const photo = photos.find(x => x.id === photoId);
|
||
if (!photo) return;
|
||
try {
|
||
await loadFaceViewerFaces(photoId);
|
||
renderFaceViewer(photo.photo_path);
|
||
} catch {
|
||
/* фотография могла исчезнуть — закрывать просмотр не нужно */
|
||
}
|
||
}
|
||
|
||
function faceViewerWarn(msg) {
|
||
const el = document.getElementById('faceViewerWarn');
|
||
if (!el) return;
|
||
if (!msg) { el.hidden = true; el.textContent = ''; return; }
|
||
el.hidden = false;
|
||
el.textContent = msg;
|
||
}
|
||
|
||
function checkFaceViewerSync(nw, nh) {
|
||
if (!faceViewer.faces.length || !faceViewer.imgWidth || !faceViewer.imgHeight) {
|
||
faceViewerWarn('');
|
||
return;
|
||
}
|
||
if (faceViewer.imgWidth === nw && faceViewer.imgHeight === nh) {
|
||
faceViewerWarn('');
|
||
return;
|
||
}
|
||
faceViewerWarn(`Фото было заменено (было ${faceViewer.imgWidth}×${faceViewer.imgHeight}, стало ${nw}×${nh}) — рамки сохранены в старом масштабе. Нажмите «Переиндексировать», чтобы распознать лица заново.`);
|
||
}
|
||
|
||
async function rescanFaceViewerPhoto() {
|
||
const photoId = faceViewer.photoId;
|
||
if (!photoId || faceViewer.rescanBusy) return;
|
||
faceViewer.rescanBusy = true;
|
||
const btn = document.getElementById('faceViewerRescanBtn');
|
||
if (btn) { btn.disabled = true; btn.textContent = 'Сканируем...'; }
|
||
try {
|
||
const res = await fetch(`${API}/api/photos/group/${photoId}/faces/rescan`, {
|
||
method: 'POST',
|
||
headers: { ...hdr(), 'Content-Type': 'application/json' },
|
||
body: JSON.stringify({}),
|
||
});
|
||
const data = await res.json().catch(() => ({}));
|
||
if (!res.ok) throw new Error(data.error || 'Не удалось распознать лица');
|
||
showToast(`Распознано лиц: ${data.scanned || 0}`);
|
||
await refreshOpenFaceViewer();
|
||
loadGroupPhotos();
|
||
} catch (e) {
|
||
alert(e.message);
|
||
} finally {
|
||
faceViewer.rescanBusy = false;
|
||
if (btn) { btn.disabled = false; btn.textContent = 'Переиндексировать'; }
|
||
}
|
||
}
|
||
|
||
async function openFaceViewer(photoId) {
|
||
const photo = photos.find(x => x.id === photoId);
|
||
if (!photo) return;
|
||
if (faceViewer.layout) window.removeEventListener('resize', faceViewer.layout);
|
||
faceViewer = { photoId, faces: [], sourceType: 'group', layout: null };
|
||
const body = document.getElementById('faceViewerBody');
|
||
body.innerHTML = '<div class="empty">Загрузка...</div>';
|
||
document.getElementById('faceViewerModal').classList.add('open');
|
||
try {
|
||
await loadFaceViewerFaces(photoId);
|
||
renderFaceViewer(photo.photo_path);
|
||
} catch (e) {
|
||
body.innerHTML = `<div class="empty">${e.status === 404 ? 'Фото не найдено' : 'Не удалось загрузить лица'}</div>`;
|
||
}
|
||
}
|
||
|
||
function faceBoxesHTML(nw, nh) {
|
||
if (!nw || !nh) return '';
|
||
return faceViewer.faces.map(f => {
|
||
const matched = Boolean(f.student_id);
|
||
let cls = 'face-box face-box--unassigned';
|
||
let label = 'Не опознано';
|
||
if (matched) {
|
||
cls = 'face-box face-box--matched';
|
||
const name = f.student_name || 'Ученик';
|
||
label = f.manual ? name + ' · вручную' : name + ' · ' + facePct(f.confidence);
|
||
} else if (f.best_student_id && f.best_score >= faceCandidateMin()) {
|
||
cls = 'face-box face-box--candidate';
|
||
label = 'Похож: ' + (f.best_student_name || 'ученик') + ' · ' + facePct(f.best_score);
|
||
}
|
||
const px = v => (Number(v) || 0);
|
||
const left = (px(f.x) / nw) * 100, top = (px(f.y) / nh) * 100;
|
||
const width = (px(f.w) / nw) * 100, height = (px(f.h) / nh) * 100;
|
||
return `<button type="button" class="${cls}" data-face-box="${f.id}"
|
||
style="left:${left.toFixed(3)}%;top:${top.toFixed(3)}%;width:${width.toFixed(3)}%;height:${height.toFixed(3)}%"
|
||
title="${esc(label)}"><span class="face-box-label">${esc(label)}</span></button>`;
|
||
}).join('');
|
||
}
|
||
|
||
function renderFaceViewer(photoPath) {
|
||
if (faceViewer.layout) window.removeEventListener('resize', faceViewer.layout);
|
||
const body = document.getElementById('faceViewerBody');
|
||
body.innerHTML = `
|
||
<div class="face-stage" id="faceStage">
|
||
<img src="${API}${photoPath}" alt="" id="faceStageImg">
|
||
<div class="face-overlay" id="faceOverlay"></div>
|
||
</div>`;
|
||
const img = document.getElementById('faceStageImg');
|
||
const ov = document.getElementById('faceOverlay');
|
||
ov.innerHTML = '<div class="empty">Загрузка...</div>';
|
||
const layout = () => {
|
||
const nw = img.naturalWidth;
|
||
const nh = img.naturalHeight;
|
||
if (!nw || !nh) return;
|
||
ov.style.width = img.clientWidth + 'px';
|
||
ov.style.height = img.clientHeight + 'px';
|
||
ov.style.left = img.offsetLeft + 'px';
|
||
ov.style.top = img.offsetTop + 'px';
|
||
ov.innerHTML = faceViewer.faces.length ? faceBoxesHTML(nw, nh) : '<div class="empty">Лиц не найдено</div>';
|
||
checkFaceViewerSync(nw, nh);
|
||
};
|
||
if (img.complete && img.naturalWidth) layout();
|
||
else img.addEventListener('load', layout, { once: true });
|
||
window.addEventListener('resize', layout);
|
||
faceViewer.layout = layout;
|
||
}
|
||
|
||
function closeFaceViewer() {
|
||
if (faceViewer.layout) window.removeEventListener('resize', faceViewer.layout);
|
||
faceViewerWarn('');
|
||
document.getElementById('faceViewerModal').classList.remove('open');
|
||
faceViewer = { photoId: null, faces: [], sourceType: 'group', layout: null, candidateMin: FACE_CANDIDATE_MIN };
|
||
}
|
||
|
||
async function openFaceAssign(faceId) {
|
||
await loadAllStudents();
|
||
faceAssignFaceId = faceId;
|
||
const face = faceViewer.faces.find(f => String(f.id) === String(faceId));
|
||
const inp = document.getElementById('faceAssignSearch');
|
||
inp.value = face && !face.student_id && face.best_student_id && face.best_score >= faceCandidateMin()
|
||
? (face.best_student_name || '')
|
||
: '';
|
||
renderFaceAssignList(inp.value);
|
||
document.getElementById('faceAssignModal').classList.add('open');
|
||
}
|
||
|
||
function renderFaceAssignList(q) {
|
||
const wrap = document.getElementById('faceAssignList');
|
||
const needle = q.trim().toLowerCase();
|
||
const list = allStudents.filter(s =>
|
||
s.name.toLowerCase().includes(needle) || (s.group_name || '').toLowerCase().includes(needle));
|
||
list.sort((a, b) => {
|
||
const own = x => (String(x.group_id) === String(currentGroupId) ? 0 : 1);
|
||
if (own(a) !== own(b)) return own(a) - own(b);
|
||
return a.name.localeCompare(b.name, 'ru');
|
||
});
|
||
if (!list.length) {
|
||
wrap.innerHTML = '<div class="empty">Ученики не найдены</div>';
|
||
return;
|
||
}
|
||
wrap.innerHTML = list.map(s => `
|
||
<button type="button" class="attach-item" data-face-pick="${s.id}">
|
||
<span class="attach-name">${esc(s.name)}</span>
|
||
<span class="attach-sub">${esc(s.group_name || 'Без группы')}</span>
|
||
</button>
|
||
`).join('');
|
||
}
|
||
|
||
async function assignFace(studentId) {
|
||
if (!faceAssignFaceId) return;
|
||
try {
|
||
const res = await fetch(`${API}/api/photo-faces/${faceAssignFaceId}/assign`, {
|
||
method: 'PUT',
|
||
headers: { ...hdr(), 'Content-Type': 'application/json' },
|
||
body: JSON.stringify({ student_id: studentId }),
|
||
});
|
||
if (!res.ok) {
|
||
const d = await res.json().catch(() => ({}));
|
||
showToast(d.error || 'Не удалось сохранить привязку');
|
||
return;
|
||
}
|
||
showToast(studentId ? 'Лицо привязано' : 'Привязка снята');
|
||
document.getElementById('faceAssignModal').classList.remove('open');
|
||
const photoId = faceViewer.photoId;
|
||
if (photoId) await refreshOpenFaceViewer();
|
||
loadGroupPhotos();
|
||
} catch {
|
||
showToast('Не удалось сохранить привязку');
|
||
}
|
||
}
|
||
|
||
async function scanGroupFaces() {
|
||
if (!currentGroupId) return;
|
||
const btn = document.getElementById('scanFacesBtn');
|
||
btn.disabled = true;
|
||
const label = btn.textContent;
|
||
btn.textContent = 'Сканируем...';
|
||
try {
|
||
const res = await fetch(`${API}/api/groups/${currentGroupId}/photos/scan-faces`, {
|
||
method: 'POST',
|
||
headers: { ...hdr(), 'Content-Type': 'application/json' },
|
||
body: JSON.stringify({}),
|
||
});
|
||
const data = res.ok ? await res.json() : null;
|
||
if (!res.ok) {
|
||
showToast((data && data.error) || 'Не удалось запустить сканирование');
|
||
return;
|
||
}
|
||
showToast(`Обработано: ${data.scanned}${data.failed ? `, ошибок: ${data.failed}` : ''}`);
|
||
loadGroupPhotos();
|
||
} catch {
|
||
showToast('Не удалось запустить сканирование');
|
||
} finally {
|
||
btn.disabled = false;
|
||
btn.textContent = label;
|
||
}
|
||
}
|
||
|
||
function fmtPhotoDate(d) { return fmtDateOnlyIso(d); }
|
||
|
||
function photoHTML(p) {
|
||
const taken = p.taken_at ? `Дата: ${fmtPhotoDate(p.taken_at)}` : '';
|
||
const uploaded = `Загружено: ${fmtDateFull(p.created_at)}`;
|
||
const isCover = currentCover && p.photo_path === currentCover;
|
||
const faces = p.face_count || 0;
|
||
const unassigned = p.face_unassigned || 0;
|
||
const faceBadge = faces
|
||
? `<span class="p-faces${unassigned ? ' unassigned' : ''}" data-faces-photo="${p.id}" title="Распознанных лиц: ${faces}${unassigned ? `, не опознано: ${unassigned}` : ''}"><i data-lucide="scan-face"></i> ${faces}${unassigned ? ` (${unassigned})` : ''}</span>`
|
||
: '';
|
||
return `
|
||
<div class="photo-item" data-photo-id="${p.id}" data-photo-path="${esc(p.photo_path)}" draggable="true">
|
||
<div class="drag-hint" title="Перетащите, чтобы изменить порядок">⠿</div>
|
||
<img src="${thumbSrc(p.photo_path)}" data-img="${API}${p.photo_path}" loading="lazy" decoding="async" alt="">
|
||
${faceBadge}
|
||
<div class="p-cap">${esc(p.caption || '')}</div>
|
||
<div class="p-date">${taken ? taken + ' · ' : ''}${uploaded}</div>
|
||
<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' : ''}><i data-lucide="image"></i></button>
|
||
<button class="p-edit" data-edit-photo="${p.id}" title="Редактировать"><i data-lucide="pencil"></i></button>
|
||
<button class="p-faces-btn" data-faces-photo="${p.id}" title="Лица на фото"><i data-lucide="scan-face"></i></button>
|
||
<button class="p-enhance" data-enhance-photo="${p.id}" title="Улучшить фото"><i data-lucide="sparkles"></i></button>
|
||
<button class="p-del" data-del-photo="${p.id}" title="Удалить"><i data-lucide="trash-2"></i></button>
|
||
</div>
|
||
</div>
|
||
`;
|
||
}
|
||
|
||
function openAddPhoto() {
|
||
editingPhotoId = null;
|
||
document.getElementById('photoFormTitle').textContent = `Добавить фото — ${currentGroupName}`;
|
||
document.getElementById('photoFile').value = '';
|
||
document.getElementById('photoCaption').value = '';
|
||
document.getElementById('photoTakenAt').value = '';
|
||
document.getElementById('photoFormPreview').style.display = 'none';
|
||
document.getElementById('photoFormModal').classList.add('open');
|
||
}
|
||
|
||
async function openEditPhoto(id) {
|
||
const p = photos.find(x => x.id === id);
|
||
if (!p) return;
|
||
editingPhotoId = id;
|
||
document.getElementById('photoFormTitle').textContent = 'Редактировать фото';
|
||
document.getElementById('photoFile').value = '';
|
||
document.getElementById('photoCaption').value = p.caption || '';
|
||
document.getElementById('photoTakenAt').value = p.taken_at || '';
|
||
const prev = document.getElementById('photoFormPreview');
|
||
const img = document.getElementById('photoPreviewImg');
|
||
img.src = `${API}${p.photo_path}`;
|
||
prev.style.display = 'block';
|
||
document.getElementById('photoFormModal').classList.add('open');
|
||
}
|
||
|
||
function closePhotoForm() {
|
||
document.getElementById('photoFormModal').classList.remove('open');
|
||
editingPhotoId = null;
|
||
}
|
||
|
||
function previewPhotoFile() {
|
||
const file = document.getElementById('photoFile').files[0];
|
||
const prev = document.getElementById('photoFormPreview');
|
||
if (!file) { prev.style.display = 'none'; return; }
|
||
const img = document.getElementById('photoPreviewImg');
|
||
img.src = URL.createObjectURL(file);
|
||
prev.style.display = 'block';
|
||
}
|
||
|
||
async function savePhotoForm() {
|
||
const caption = document.getElementById('photoCaption').value.trim();
|
||
const taken_at = document.getElementById('photoTakenAt').value;
|
||
if (editingPhotoId) {
|
||
const res = await fetch(`${API}/api/groups/${currentGroupId}/photos/${editingPhotoId}`, {
|
||
method: 'PUT',
|
||
headers: hdrJson(),
|
||
body: JSON.stringify({ caption: caption || null, taken_at: taken_at || null })
|
||
});
|
||
if (!res.ok) { const e = await res.json(); alert(e.error || 'Ошибка'); return; }
|
||
showToast('Фото обновлено');
|
||
} else {
|
||
const file = document.getElementById('photoFile').files[0];
|
||
if (!file) { alert('Выберите файл'); return; }
|
||
const fd = new FormData();
|
||
fd.append('photo', file);
|
||
fd.append('caption', caption);
|
||
fd.append('taken_at', taken_at);
|
||
const res = await fetch(`${API}/api/groups/${currentGroupId}/photos`, {
|
||
method: 'POST',
|
||
headers: hdr(),
|
||
body: fd
|
||
});
|
||
if (!res.ok) { const e = await res.json(); alert(e.error || 'Ошибка'); return; }
|
||
showToast('Фото добавлено в хронологию');
|
||
}
|
||
closePhotoForm();
|
||
loadGroupPhotos();
|
||
loadGroups();
|
||
}
|
||
|
||
async function deletePhoto(id) {
|
||
if (!confirm('Удалить это фото безвозвратно?')) return;
|
||
const res = await fetch(`${API}/api/groups/${currentGroupId}/photos/${id}`, { method: 'DELETE', headers: hdr() });
|
||
if (!res.ok) { const e = await res.json(); alert(e.error || 'Ошибка'); return; }
|
||
const p = photos.find(x => x.id === id);
|
||
if (p && currentCover === p.photo_path) currentCover = null;
|
||
showToast('Фото удалено');
|
||
loadGroupPhotos();
|
||
loadGroups();
|
||
}
|
||
|
||
async function exportGroup(id, name) {
|
||
const res = await fetch(`${API}/api/entries?group_id=${id}`, { headers: hdr() });
|
||
const { entries } = await res.json();
|
||
if (!entries.length) { alert('Нет данных для экспорта'); return; }
|
||
const rows = [['Фамилия Имя', 'Группа', 'Описание', 'Дата', 'Ссылка на страницу']];
|
||
entries.forEach(e => {
|
||
rows.push([
|
||
e.student_name,
|
||
e.group_name,
|
||
e.description.replace(/\n/g, ' '),
|
||
fmtFull(e.created_at),
|
||
`${location.origin}/?nameInput=${encodeURIComponent(e.student_name)}`
|
||
]);
|
||
});
|
||
const csv = rows.map(r => r.map(c => `"${String(c).replace(/"/g, '""')}"`).join(';')).join('\n');
|
||
const blob = new Blob(['\uFEFF' + csv], { type: 'text/csv;charset=utf-8' });
|
||
const url = URL.createObjectURL(blob);
|
||
const a = document.createElement('a');
|
||
a.href = url;
|
||
a.download = `group_${name.replace(/[\\/:*?"<>|]/g, '_')}.csv`;
|
||
a.click();
|
||
URL.revokeObjectURL(url);
|
||
showToast(`Экспортировано записей: ${entries.length}`);
|
||
}
|
||
|
||
async function exportGroupUrls(groupId, groupName) {
|
||
const res = await fetch(`${API}/api/students`, { headers: hdr() });
|
||
const students = await res.json();
|
||
const list = students.filter(s => s.group_id === groupId);
|
||
if (!list.length) { alert('В группе нет учеников'); return; }
|
||
await exportStudentUrlZip(list, `group_${groupName.replace(/[\\/:*?"<>|]/g, '_')}.zip`);
|
||
showToast(`Экспортировано: ${list.length}`);
|
||
}
|
||
|
||
function openGroupFilesModal(groupId, groupName) {
|
||
const sel = document.getElementById('groupFilesGroup');
|
||
sel.innerHTML = allGroups.map(g => `<option value="${g.id}" ${String(g.id) === String(groupId) ? 'selected' : ''}>${esc(g.name)}</option>`).join('');
|
||
document.getElementById('groupFilesTitle').textContent = `Архив файлов — ${groupName}`;
|
||
document.getElementById('groupFilesFrom').value = '';
|
||
document.getElementById('groupFilesTo').value = todayISOLocal();
|
||
document.getElementById('groupFilesIncludeWorks').checked = true;
|
||
document.getElementById('groupFilesIncludePhotos').checked = false;
|
||
document.getElementById('groupFilesMainPhoto').checked = true;
|
||
document.getElementById('groupFilesGallery').checked = false;
|
||
document.getElementById('groupFilesOriginals').checked = false;
|
||
onGroupFilesPhotosToggle();
|
||
document.getElementById('groupFilesModal').classList.add('open');
|
||
}
|
||
|
||
function closeGroupFilesModal() {
|
||
document.getElementById('groupFilesModal').classList.remove('open');
|
||
}
|
||
|
||
function todayISOLocal() {
|
||
return todayIso();
|
||
}
|
||
|
||
const GROUP_FILES_PHOTO_BOXES = ['groupFilesMainPhoto', 'groupFilesGallery', 'groupFilesOriginals'];
|
||
|
||
function onGroupFilesPhotosToggle() {
|
||
const on = document.getElementById('groupFilesIncludePhotos').checked;
|
||
GROUP_FILES_PHOTO_BOXES.forEach(id => {
|
||
const el = document.getElementById(id);
|
||
if (el) el.disabled = !on;
|
||
});
|
||
}
|
||
|
||
function groupFilesPhotosOptions() {
|
||
const main = document.getElementById('groupFilesMainPhoto').checked;
|
||
const gallery = document.getElementById('groupFilesGallery').checked;
|
||
const originals = document.getElementById('groupFilesOriginals').checked;
|
||
return {
|
||
main,
|
||
gallery,
|
||
originals,
|
||
mode: gallery ? 'all' : 'latest',
|
||
any: main || gallery || originals,
|
||
};
|
||
}
|
||
|
||
async function downloadGroupFiles() {
|
||
const groupId = document.getElementById('groupFilesGroup').value;
|
||
const dateFrom = document.getElementById('groupFilesFrom').value;
|
||
const dateTo = document.getElementById('groupFilesTo').value;
|
||
const includeWorks = document.getElementById('groupFilesIncludeWorks').checked;
|
||
const includePhotos = document.getElementById('groupFilesIncludePhotos').checked;
|
||
const photoOpts = groupFilesPhotosOptions();
|
||
if (!groupId) { alert('Выберите группу'); return; }
|
||
if (!includeWorks && !includePhotos) { alert('Выберите хотя бы одну категорию: работы или фото записи'); return; }
|
||
if (includePhotos && !photoOpts.any) { alert('Выберите, какие фото выгружать: главное фото, галерея или оригиналы'); return; }
|
||
if (dateFrom && dateTo && dateFrom > dateTo) { alert('Дата «С» позже даты «По»'); return; }
|
||
const btn = document.getElementById('downloadGroupFilesBtn');
|
||
btn.disabled = true;
|
||
btn.textContent = 'Формируем...';
|
||
try {
|
||
const q = new URLSearchParams();
|
||
if (dateFrom) q.set('date_from', dateFrom);
|
||
if (dateTo) q.set('date_to', dateTo);
|
||
q.set('include_files', includeWorks ? '1' : '0');
|
||
q.set('include_photos', includePhotos ? '1' : '0');
|
||
q.set('include_main', photoOpts.main ? '1' : '0');
|
||
q.set('photos_mode', photoOpts.mode);
|
||
q.set('include_originals', photoOpts.originals ? '1' : '0');
|
||
const res = await fetch(`${API}/api/groups/${groupId}/export/files?${q}`, { headers: hdr() });
|
||
if (!res.ok) {
|
||
let msg = 'Не удалось сформировать архив';
|
||
try { const e = await res.json(); msg = e.error || msg; } catch {}
|
||
alert(msg);
|
||
return;
|
||
}
|
||
const blob = await res.blob();
|
||
let disp = res.headers.get('Content-Disposition') || '';
|
||
let fname = 'group_files.zip';
|
||
const star = disp.match(/filename\*=UTF-8''([^;]+)/i);
|
||
const plain = disp.match(/filename="?([^";]+)"?/i);
|
||
if (star) { try { fname = decodeURIComponent(star[1]); } catch { fname = plain ? plain[1] : fname; } }
|
||
else if (plain) fname = plain[1];
|
||
downloadBlob(blob, fname);
|
||
showToast('Архив сформирован');
|
||
closeGroupFilesModal();
|
||
} catch (err) {
|
||
alert('Ошибка при формировании архива: ' + err.message);
|
||
} finally {
|
||
btn.disabled = false;
|
||
btn.textContent = 'Скачать ZIP';
|
||
}
|
||
}
|
||
|
||
document.getElementById('newGroup').addEventListener('keydown', e => { if (e.key === 'Enter') addGroup(); });
|
||
document.getElementById('addGroupBtn').addEventListener('click', addGroup);
|
||
document.getElementById('photoFile').addEventListener('change', previewPhotoFile);
|
||
document.getElementById('photoForm').addEventListener('submit', e => {
|
||
e.preventDefault();
|
||
savePhotoForm();
|
||
});
|
||
|
||
document.getElementById('photosModal').addEventListener('click', e => { if (e.target === e.currentTarget) closePhotos(); });
|
||
document.getElementById('photoFormModal').addEventListener('click', e => { if (e.target === e.currentTarget) closePhotoForm(); });
|
||
document.getElementById('groupFilesModal').addEventListener('click', e => { if (e.target === e.currentTarget) closeGroupFilesModal(); });
|
||
document.getElementById('closeGroupFilesBtn').addEventListener('click', closeGroupFilesModal);
|
||
document.getElementById('groupFilesForm').addEventListener('submit', e => { e.preventDefault(); downloadGroupFiles(); });
|
||
document.getElementById('groupFilesIncludePhotos').addEventListener('change', onGroupFilesPhotosToggle);
|
||
document.getElementById('openPhotoBtn').addEventListener('click', openAddPhoto);
|
||
document.getElementById('closePhotosBtn').addEventListener('click', closePhotos);
|
||
document.getElementById('closePhotoFormBtn').addEventListener('click', closePhotoForm);
|
||
|
||
document.getElementById('groupList').addEventListener('click', e => {
|
||
const sg = e.target.closest('[data-save-group]');
|
||
if (sg) { saveGroup(parseInt(sg.dataset.saveGroup, 10)); return; }
|
||
const dg = e.target.closest('[data-del-group]');
|
||
if (dg) { delGroup(parseInt(dg.dataset.delGroup, 10)); return; }
|
||
const eg = e.target.closest('[data-export-group]');
|
||
if (eg) { exportGroup(parseInt(eg.dataset.exportGroup, 10), eg.dataset.groupName); return; }
|
||
const eu = e.target.closest('[data-export-urls]');
|
||
if (eu) { exportGroupUrls(parseInt(eu.dataset.exportUrls, 10), eu.dataset.groupName); return; }
|
||
const ef = e.target.closest('[data-export-files]');
|
||
if (ef) { openGroupFilesModal(parseInt(ef.dataset.exportFiles, 10), ef.dataset.groupName); return; }
|
||
const photoBtn = e.target.closest('.photo-btn');
|
||
if (photoBtn) {
|
||
const id = parseInt(photoBtn.dataset.groupId, 10);
|
||
const name = photoBtn.dataset.groupName;
|
||
if (!isNaN(id)) openPhotos(id, name);
|
||
}
|
||
});
|
||
|
||
function updateGroupCoverUI(coverPath) {
|
||
const card = document.querySelector(`.group-card[data-group-id="${currentGroupId}"]`);
|
||
if (!card) return;
|
||
const g = allGroups.find(x => String(x.id) === String(currentGroupId));
|
||
const existing = card.querySelector('.group-cover');
|
||
if (existing && existing.tagName === 'IMG') { existing.src = API + coverPath; existing.dataset.img = API + coverPath; return; }
|
||
const el = document.createElement('img');
|
||
el.className = 'group-cover';
|
||
el.src = API + coverPath;
|
||
el.dataset.img = API + coverPath;
|
||
el.alt = '';
|
||
if (existing) existing.replaceWith(el);
|
||
else card.insertBefore(el, card.firstChild);
|
||
}
|
||
|
||
let dragPhotoId = null;
|
||
|
||
async function persistPhotoOrder() {
|
||
const items = [...document.querySelectorAll('#photoGrid .photo-item')];
|
||
const order = items.map(el => parseInt(el.dataset.photoId, 10));
|
||
if (JSON.stringify(order) === JSON.stringify(photos.map(p => p.id))) return;
|
||
const res = await fetch(`${API}/api/groups/${currentGroupId}/photos/reorder`, {
|
||
method: 'PUT',
|
||
headers: hdrJson(),
|
||
body: JSON.stringify({ order })
|
||
});
|
||
if (res.ok) showToast('Порядок фото сохранён');
|
||
else {
|
||
try { const err = await res.json(); alert(err.error || 'Ошибка'); } catch { alert('Ошибка'); }
|
||
loadGroupPhotos();
|
||
}
|
||
}
|
||
|
||
document.getElementById('photoGrid').addEventListener('dragstart', e => {
|
||
const item = e.target.closest('.photo-item');
|
||
if (!item) return;
|
||
e.stopPropagation();
|
||
dragPhotoId = parseInt(item.dataset.photoId, 10);
|
||
item.classList.add('dragging');
|
||
e.dataTransfer.effectAllowed = 'move';
|
||
e.dataTransfer.setData('text/plain', String(dragPhotoId));
|
||
});
|
||
|
||
document.getElementById('photoGrid').addEventListener('dragover', e => {
|
||
e.preventDefault();
|
||
e.dataTransfer.dropEffect = 'move';
|
||
const target = e.target.closest('.photo-item');
|
||
const dragged = dragPhotoId != null ? document.querySelector(`.photo-item[data-photo-id="${dragPhotoId}"]`) : null;
|
||
if (!target || !dragged || target === dragged) return;
|
||
if (target.contains(dragged)) return;
|
||
const rect = target.getBoundingClientRect();
|
||
const grid = document.getElementById('photoGrid');
|
||
grid.insertBefore(dragged, e.clientX > rect.left + rect.width / 2 ? target.nextSibling : target);
|
||
});
|
||
|
||
document.getElementById('photoGrid').addEventListener('dragend', e => {
|
||
const item = e.target.closest('.photo-item');
|
||
if (item) item.classList.remove('dragging');
|
||
if (dragPhotoId != null) persistPhotoOrder();
|
||
dragPhotoId = null;
|
||
});
|
||
|
||
document.getElementById('photoGrid').addEventListener('drop', e => e.preventDefault());
|
||
|
||
document.getElementById('photoGrid').addEventListener('click', async e => {
|
||
const facesBtn = e.target.closest('[data-faces-photo]');
|
||
if (facesBtn) {
|
||
openFaceViewer(parseInt(facesBtn.dataset.facesPhoto, 10));
|
||
return;
|
||
}
|
||
const coverBtn = e.target.closest('.p-cover');
|
||
if (coverBtn) {
|
||
const photoId = parseInt(coverBtn.dataset.photoId, 10);
|
||
const photoPath = coverBtn.dataset.photoPath;
|
||
if (!isNaN(photoId)) {
|
||
try {
|
||
const res = await fetch(`${API}/api/groups/${currentGroupId}/photos/${photoId}/cover`, {
|
||
method: 'PUT',
|
||
headers: hdrJson(),
|
||
});
|
||
if (res.ok) {
|
||
const g = await res.json();
|
||
currentCover = g.cover_path || null;
|
||
const grp = allGroups.find(x => String(x.id) === String(currentGroupId));
|
||
if (grp) grp.cover_path = currentCover;
|
||
showToast('Обложка обновлена');
|
||
updateGroupCoverUI(currentCover);
|
||
loadGroupPhotos();
|
||
} else {
|
||
const err = await res.json();
|
||
alert(err.error || 'Ошибка');
|
||
}
|
||
} catch (err) {
|
||
alert('Ошибка сети: ' + err.message);
|
||
}
|
||
}
|
||
return;
|
||
}
|
||
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)); }
|
||
});
|
||
|
||
async function populateNewGroupBranch() {
|
||
const res = await fetch(`${API}/api/branches`, { headers: hdr() });
|
||
if (res.ok) {
|
||
const branches = await res.json();
|
||
const sel = document.getElementById('newGroupBranch');
|
||
sel.innerHTML = '<option value="">— без филиала —</option>' + branches.map(b => `<option value="${b.id}">${esc(b.name)}</option>`).join('');
|
||
}
|
||
const tRes = await fetch(`${API}/api/users/tutors`, { headers: hdr() });
|
||
if (tRes.ok) {
|
||
const tutors = await tRes.json();
|
||
const tSel = document.getElementById('newGroupTutor');
|
||
tSel.innerHTML = '<option value="">— не назначен —</option>' + tutors.map(t => `<option value="${t.id}">${esc(t.name || t.username)}</option>`).join('');
|
||
}
|
||
}
|
||
|
||
(async () => {
|
||
if (await checkAuth()) {
|
||
buildSidebar(document.body.dataset.page);
|
||
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();
|
||
await refreshOpenFaceViewer();
|
||
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();
|
||
await refreshOpenFaceViewer();
|
||
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();
|
||
await refreshOpenFaceViewer();
|
||
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();
|
||
await refreshOpenFaceViewer();
|
||
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('imgModal')?.addEventListener('click', e => e.currentTarget.classList.remove('open'));
|
||
document.getElementById('scanFacesBtn')?.addEventListener('click', scanGroupFaces);
|
||
document.getElementById('faceStudentFilter')?.addEventListener('change', () => { photoPage = 1; loadGroupPhotos(); });
|
||
document.getElementById('faceViewerCloseBtn')?.addEventListener('click', closeFaceViewer);
|
||
document.getElementById('faceViewerRescanBtn')?.addEventListener('click', rescanFaceViewerPhoto);
|
||
document.getElementById('faceViewerModal')?.addEventListener('click', e => { if (e.target === e.currentTarget) closeFaceViewer(); });
|
||
document.getElementById('faceViewerBody')?.addEventListener('click', e => {
|
||
const box = e.target.closest('[data-face-box]');
|
||
if (!box) return;
|
||
openFaceAssign(parseInt(box.dataset.faceBox, 10));
|
||
});
|
||
document.getElementById('faceAssignCancelBtn')?.addEventListener('click', () => document.getElementById('faceAssignModal').classList.remove('open'));
|
||
document.getElementById('faceAssignModal')?.addEventListener('click', e => { if (e.target === e.currentTarget) document.getElementById('faceAssignModal').classList.remove('open'); });
|
||
document.getElementById('faceAssignList')?.addEventListener('click', e => {
|
||
const pick = e.target.closest('[data-face-pick]');
|
||
if (!pick) return;
|
||
assignFace(parseInt(pick.dataset.facePick, 10));
|
||
});
|
||
document.getElementById('faceUnassignBtn')?.addEventListener('click', () => assignFace(0));
|
||
document.getElementById('faceAssignSearch')?.addEventListener('input', e => renderFaceAssignList(e.target.value));
|
||
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();
|
||
|