add face library: face recognition, student refs, manual assign
Сервис face-id (insightface/ArcFace) ищет лица на фото групп и записей, сравнивает их с эталонными фото учеников и предлагает привязки по процентам косинусного сходства. - face-id/: FastAPI-сервис /detect, /compare, /health, ленивая загрузка модели - таблицы photo_faces + student_face_refs, face_scanned_at в фото групп и записей - настройки: face_id_enabled, face_scan_on_upload, face_id_threshold - пересчёт привязок по всем фото rematchFaces(): считает по сохранённым эмбеддингам, сервис face-id не нужен; автозапуск после добавления эталона плюс кнопка в настройках - просмотрщик фото: рамки с процентом сходства, подсказка-кандидат, ручная привязка по всем группам - бэкап/restore, sweep сиротских файлов, удаление лиц вместе с фото
This commit is contained in:
@@ -137,6 +137,8 @@ async function openPhotos(groupId, groupName) {
|
||||
editingPhotoId = null;
|
||||
document.getElementById('photosTitle').textContent = `Фото — ${groupName}`;
|
||||
document.getElementById('photosModal').classList.add('open');
|
||||
await loadAllStudents();
|
||||
renderFaceStudentFilter();
|
||||
await loadGroupPhotos();
|
||||
}
|
||||
|
||||
@@ -149,6 +151,10 @@ 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;
|
||||
@@ -162,21 +168,239 @@ async function loadGroupPhotos() {
|
||||
|
||||
function goPhotoPage(p) { photoPage = p; loadGroupPhotos(); }
|
||||
|
||||
let allStudents = [];
|
||||
let allStudentsLoaded = false;
|
||||
let faceViewer = { photoId: null, faces: [], sourceType: 'group', layout: null };
|
||||
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 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 {
|
||||
const res = await fetch(`${API}/api/photos/group/${photoId}/faces`, { headers: hdr() });
|
||||
if (!res.ok) {
|
||||
body.innerHTML = `<div class="empty">${res.status === 404 ? 'Фото не найдено' : 'Не удалось загрузить лица'}</div>`;
|
||||
return;
|
||||
}
|
||||
const data = await res.json();
|
||||
faceViewer.faces = data.faces || [];
|
||||
renderFaceViewer(photo.photo_path);
|
||||
} catch {
|
||||
body.innerHTML = '<div class="empty">Не удалось загрузить лица</div>';
|
||||
}
|
||||
}
|
||||
|
||||
const FACE_CANDIDATE_MIN = 0.5;
|
||||
const facePct = v => Math.round((Number(v) || 0) * 100) + '%';
|
||||
|
||||
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 >= FACE_CANDIDATE_MIN) {
|
||||
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>';
|
||||
};
|
||||
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);
|
||||
document.getElementById('faceViewerModal').classList.remove('open');
|
||||
faceViewer = { photoId: null, faces: [], sourceType: 'group', layout: null };
|
||||
}
|
||||
|
||||
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 >= FACE_CANDIDATE_MIN
|
||||
? (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) {
|
||||
const photo = photos.find(x => x.id === photoId);
|
||||
const r = await fetch(`${API}/api/photos/group/${photoId}/faces`, { headers: hdr() });
|
||||
if (r.ok && photo) {
|
||||
const d = await r.json();
|
||||
faceViewer.faces = d.faces || [];
|
||||
renderFaceViewer(photo.photo_path);
|
||||
}
|
||||
}
|
||||
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}` : ''}">👤 ${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' : ''}>🖼️</button>
|
||||
<button class="p-edit" data-edit-photo="${p.id}" title="Редактировать">✎</button>
|
||||
<button class="p-faces-btn" data-faces-photo="${p.id}" title="Лица на фото">👤</button>
|
||||
<button class="p-enhance" data-enhance-photo="${p.id}" title="Улучшить фото">✨</button>
|
||||
<button class="p-del" data-del-photo="${p.id}" title="Удалить">×</button>
|
||||
</div>
|
||||
@@ -495,6 +719,11 @@ document.getElementById('photoGrid').addEventListener('dragend', e => {
|
||||
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);
|
||||
@@ -1241,6 +1470,24 @@ 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('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; }
|
||||
|
||||
@@ -69,9 +69,23 @@ async function loadGroupOptions() {
|
||||
async function loadStudentOptions() {
|
||||
if (studentsLoaded) return;
|
||||
const dl = document.getElementById('studentFilterList');
|
||||
const fs = document.getElementById('faceStudentFilter');
|
||||
const res = await fetch(`${API}/api/students/names`, { headers: hdr() });
|
||||
const names = await res.json();
|
||||
dl.innerHTML = names.map(n => `<option value="${esc(n)}">`).join('');
|
||||
if (fs) {
|
||||
try {
|
||||
const r2 = await fetch(`${API}/api/students?limit=1000`, { headers: hdr() });
|
||||
const data = r2.ok ? await r2.json() : null;
|
||||
const list = Array.isArray(data) ? data : (data && data.students) || [];
|
||||
list.filter(s => !s.deleted_at).forEach(s => {
|
||||
const o = document.createElement('option');
|
||||
o.value = String(s.id);
|
||||
o.textContent = s.name;
|
||||
fs.appendChild(o);
|
||||
});
|
||||
} catch {}
|
||||
}
|
||||
studentsLoaded = true;
|
||||
}
|
||||
|
||||
@@ -101,6 +115,9 @@ async function loadPhotos() {
|
||||
if (gid) p.set('group_id', gid);
|
||||
if (df) p.set('date_from', df);
|
||||
if (dt) p.set('date_to', dt);
|
||||
const fv = document.getElementById('faceStudentFilter') ? document.getElementById('faceStudentFilter').value : '';
|
||||
if (fv === '__unassigned__') p.set('unassigned_faces', '1');
|
||||
else if (fv) p.set('student_id', fv);
|
||||
p.set('limit', PAGE_SIZE);
|
||||
p.set('offset', (page - 1) * PAGE_SIZE);
|
||||
const res = await fetch(`${API}/api/photos?${p}`, { headers: hdr() });
|
||||
@@ -125,6 +142,7 @@ function goPage(p) {
|
||||
document.getElementById('studentFilter').addEventListener('change', () => { page = 1; loadPhotos(); });
|
||||
document.getElementById('groupFilter').addEventListener('change', () => { page = 1; loadPhotos(); });
|
||||
document.getElementById('sourceFilter').addEventListener('change', () => { page = 1; loadPhotos(); });
|
||||
document.getElementById('faceStudentFilter')?.addEventListener('change', () => { page = 1; loadPhotos(); });
|
||||
document.getElementById('dateFrom').addEventListener('change', () => { page = 1; loadPhotos(); });
|
||||
document.getElementById('dateTo').addEventListener('change', () => { page = 1; loadPhotos(); });
|
||||
document.getElementById('searchInput').addEventListener('input', () => {
|
||||
|
||||
@@ -286,6 +286,12 @@ async function loadSettings() {
|
||||
document.getElementById('lessonAiEnabled').checked = s.lesson_ai_enabled !== 'false';
|
||||
document.getElementById('lessonAiPrompt').value = s.lesson_ai_prompt || '';
|
||||
document.getElementById('notesAiEnabled').checked = s.notes_ai_enabled !== 'false';
|
||||
const fe = document.getElementById('faceIdEnabled');
|
||||
const fsu = document.getElementById('faceScanOnUpload');
|
||||
const fth = document.getElementById('faceIdThreshold');
|
||||
if (fe) fe.checked = s.face_id_enabled === 'true';
|
||||
if (fsu) fsu.checked = s.face_scan_on_upload !== 'false';
|
||||
if (fth) fth.value = s.face_id_threshold || '0.6';
|
||||
document.getElementById('shareShowMessage').checked = s.share_show_student_message === 'true';
|
||||
document.getElementById('shareShowDate').checked = s.share_show_entry_date === 'true';
|
||||
document.getElementById('shareShowNames').checked = s.share_show_student_names !== 'false';
|
||||
@@ -892,6 +898,9 @@ async function saveSettings() {
|
||||
lesson_ai_enabled: document.getElementById('lessonAiEnabled').checked ? 'true' : 'false',
|
||||
lesson_ai_prompt: document.getElementById('lessonAiPrompt').value.trim(),
|
||||
notes_ai_enabled: document.getElementById('notesAiEnabled').checked ? 'true' : 'false',
|
||||
face_id_enabled: (document.getElementById('faceIdEnabled') || {}).checked ? 'true' : 'false',
|
||||
face_scan_on_upload: (document.getElementById('faceScanOnUpload') || {}).checked ? 'true' : 'false',
|
||||
face_id_threshold: String((document.getElementById('faceIdThreshold') || {}).value || '0.6').trim(),
|
||||
share_show_student_message: document.getElementById('shareShowMessage').checked ? 'true' : 'false',
|
||||
share_show_entry_date: document.getElementById('shareShowDate').checked ? 'true' : 'false',
|
||||
share_show_student_names: document.getElementById('shareShowNames').checked ? 'true' : 'false',
|
||||
@@ -1068,6 +1077,27 @@ if (photoAiRefreshBtn) photoAiRefreshBtn.addEventListener('click', () => loadPho
|
||||
const photoAiDevicePref = document.getElementById('photoAiDevicePref');
|
||||
if (photoAiDevicePref) photoAiDevicePref.addEventListener('change', () => renderPhotoAiStatus());
|
||||
|
||||
const faceRematchBtn = document.getElementById('faceRematchBtn');
|
||||
if (faceRematchBtn) faceRematchBtn.addEventListener('click', async () => {
|
||||
const hint = document.getElementById('faceRematchHint');
|
||||
faceRematchBtn.classList.add('spinning');
|
||||
faceRematchBtn.disabled = true;
|
||||
if (hint) hint.textContent = 'Считаю сходство...';
|
||||
try {
|
||||
const res = await fetch(`${API}/api/faces/rematch`, { method: 'POST', headers: hdr() });
|
||||
const d = await res.json().catch(() => ({}));
|
||||
if (!res.ok) { showError(d.error || 'Не удалось пересчитать лица'); if (hint) hint.textContent = 'Ошибка пересчёта'; return; }
|
||||
showToast(`Пересчитано лиц: ${d.scanned}, привязано: ${d.matched}`);
|
||||
if (hint) hint.textContent = `Готово: просмотрено ${d.scanned}, привязано ${d.matched} (порог ${d.threshold})`;
|
||||
} catch {
|
||||
showError('Не удалось пересчитать лица');
|
||||
if (hint) hint.textContent = 'Ошибка пересчёта';
|
||||
} finally {
|
||||
faceRematchBtn.classList.remove('spinning');
|
||||
faceRematchBtn.disabled = false;
|
||||
}
|
||||
});
|
||||
|
||||
const notifyTestBtn = document.getElementById('notifyTestBtn');
|
||||
if (notifyTestBtn) notifyTestBtn.addEventListener('click', async () => {
|
||||
notifyTestBtn.classList.add('spinning');
|
||||
|
||||
@@ -6,6 +6,8 @@ const S_PAGE_SIZE = 25;
|
||||
let sSearchTimer = null;
|
||||
let aSearchTimer = null;
|
||||
let attachGroupLoaded = false;
|
||||
let faceRefs = [];
|
||||
let facePhotos = [];
|
||||
|
||||
async function loadGroupOptions(sel, selected) {
|
||||
if (!groupOptionsLoaded) {
|
||||
@@ -245,6 +247,8 @@ function openProfileData(id) {
|
||||
profileDataId = id;
|
||||
loadGroupOptions();
|
||||
loadStudentPhotos(id);
|
||||
loadFaceRefs(id);
|
||||
loadFacePhotos(id);
|
||||
fetch(`${API}/api/students/${id}/profile`, { headers: hdr() })
|
||||
.then(r => (r.ok ? r.json() : Promise.reject(new Error('load'))))
|
||||
.then(data => fillProfileForm(data.profile, data.name, data.photo_path))
|
||||
@@ -255,6 +259,113 @@ function openProfileData(id) {
|
||||
function closeProfileData() {
|
||||
document.getElementById('profileDataModal').classList.remove('open');
|
||||
profileDataId = null;
|
||||
faceRefs = [];
|
||||
facePhotos = [];
|
||||
}
|
||||
|
||||
async function loadFaceRefs(id) {
|
||||
try {
|
||||
const res = await fetch(`${API}/api/students/${id}/face-refs`, { headers: hdr() });
|
||||
if (!res.ok) {
|
||||
renderFaceRefs();
|
||||
return;
|
||||
}
|
||||
const data = await res.json();
|
||||
faceRefs = data.refs || [];
|
||||
renderFaceRefs();
|
||||
} catch {
|
||||
faceRefs = [];
|
||||
renderFaceRefs();
|
||||
}
|
||||
}
|
||||
|
||||
function renderFaceRefs() {
|
||||
const wrap = document.getElementById('faceRefsList');
|
||||
if (!wrap) return;
|
||||
if (!faceRefs.length) {
|
||||
wrap.innerHTML = '<span class="face-empty">Эталонов пока нет — распознавание по этому ученику работать не будет</span>';
|
||||
return;
|
||||
}
|
||||
wrap.innerHTML = faceRefs.map(r => `
|
||||
<div class="face-ref">
|
||||
<img src="${esc(thumbSrc(r.photo_path))}" alt="" loading="lazy">
|
||||
<button type="button" class="pf-del" data-face-ref-del="${r.id}" title="Удалить эталон">✕</button>
|
||||
</div>
|
||||
`).join('');
|
||||
}
|
||||
|
||||
async function addFaceRef(file) {
|
||||
if (!profileDataId || !file) return;
|
||||
if (!file.type.startsWith('image/')) {
|
||||
showToast('Можно загружать только изображения');
|
||||
return;
|
||||
}
|
||||
showToast('Ищем лицо на фото...');
|
||||
const fd = new FormData();
|
||||
fd.append('photo', file);
|
||||
try {
|
||||
const res = await fetch(`${API}/api/students/${profileDataId}/face-refs`, { method: 'POST', headers: hdr(), body: fd });
|
||||
const data = await res.json();
|
||||
if (!res.ok) {
|
||||
showToast(data.error || 'Не удалось добавить эталон');
|
||||
return;
|
||||
}
|
||||
faceRefs.push(data);
|
||||
renderFaceRefs();
|
||||
showToast('Эталон добавлен');
|
||||
} catch {
|
||||
showToast('Не удалось добавить эталон');
|
||||
}
|
||||
}
|
||||
|
||||
async function delFaceRef(refId) {
|
||||
try {
|
||||
const res = await fetch(`${API}/api/students/${profileDataId}/face-refs/${refId}`, { method: 'DELETE', headers: hdr() });
|
||||
if (!res.ok) {
|
||||
showToast('Не удалось удалить эталон');
|
||||
return;
|
||||
}
|
||||
faceRefs = faceRefs.filter(r => r.id !== refId);
|
||||
renderFaceRefs();
|
||||
} catch {
|
||||
showToast('Не удалось удалить эталон');
|
||||
}
|
||||
}
|
||||
|
||||
async function loadFacePhotos(id) {
|
||||
try {
|
||||
const res = await fetch(`${API}/api/students/${id}/face-photos`, { headers: hdr() });
|
||||
if (!res.ok) {
|
||||
renderFacePhotos();
|
||||
return;
|
||||
}
|
||||
const data = await res.json();
|
||||
facePhotos = data.photos || [];
|
||||
renderFacePhotos();
|
||||
} catch {
|
||||
facePhotos = [];
|
||||
renderFacePhotos();
|
||||
}
|
||||
}
|
||||
|
||||
function facePhotoHref(p) {
|
||||
if (p.source_type === 'entry') return `journal.html#entry-${p.source_id}`;
|
||||
return 'photos.html';
|
||||
}
|
||||
|
||||
function renderFacePhotos() {
|
||||
const wrap = document.getElementById('facePhotosList');
|
||||
if (!wrap) return;
|
||||
if (!facePhotos.length) {
|
||||
wrap.innerHTML = '<span class="face-empty">Пока нет фото, где распознан этот ученик</span>';
|
||||
return;
|
||||
}
|
||||
wrap.innerHTML = facePhotos.map((p, i) => `
|
||||
<div class="face-shot">
|
||||
<img src="${esc(thumbSrc(p.path))}" data-face-shot="${i}" alt="" loading="lazy">
|
||||
<a class="face-src" href="${facePhotoHref(p)}">${p.source_type === 'entry' ? 'Запись' : 'Группа'}</a>
|
||||
</div>
|
||||
`).join('');
|
||||
}
|
||||
|
||||
async function loadStudentPhotos(id) {
|
||||
@@ -640,6 +751,29 @@ document.addEventListener('paste', e => {
|
||||
});
|
||||
document.getElementById('profileDataModal').addEventListener('click', e => { if (e.target === e.currentTarget) closeProfileData(); });
|
||||
|
||||
document.getElementById('faceRefAddBtn').addEventListener('click', () => document.getElementById('faceRefFile').click());
|
||||
document.getElementById('faceRefFile').addEventListener('change', e => {
|
||||
const f = e.target.files[0];
|
||||
e.target.value = '';
|
||||
addFaceRef(f);
|
||||
});
|
||||
document.getElementById('faceRefsList').addEventListener('click', e => {
|
||||
const btn = e.target.closest('[data-face-ref-del]');
|
||||
if (!btn) return;
|
||||
delFaceRef(parseInt(btn.dataset.faceRefDel, 10));
|
||||
});
|
||||
document.getElementById('facePhotosList').addEventListener('click', e => {
|
||||
const img = e.target.closest('[data-face-shot]');
|
||||
if (!img) return;
|
||||
const p = facePhotos[parseInt(img.dataset.faceShot, 10)];
|
||||
if (!p) return;
|
||||
const m = document.getElementById('imgModal');
|
||||
const s = document.getElementById('imgModalSrc');
|
||||
if (!m || !s) return;
|
||||
s.src = `${API}${p.path}`;
|
||||
m.classList.add('open');
|
||||
});
|
||||
|
||||
(async () => {
|
||||
if (await checkAuth()) {
|
||||
buildSidebar(document.body.dataset.page);
|
||||
|
||||
Reference in New Issue
Block a user