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:
@@ -263,6 +263,37 @@ body{font-family:-apple-system,BlinkMacSystemFont,'Segoe UI',Roboto,sans-serif;b
|
||||
.pf-del{position:absolute;top:4px;right:4px;width:20px;height:20px;border:none;border-radius:50%;background:rgba(0,0,0,.6);color:#fff;font-size:.7rem;line-height:1;cursor:pointer;display:flex;align-items:center;justify-content:center}
|
||||
.pf-del:hover{background:#ef4444}
|
||||
|
||||
/* --- Библиотека лиц --- */
|
||||
.face-refs{display:flex;flex-wrap:wrap;gap:10px;min-height:34px;align-items:center}
|
||||
.face-ref{position:relative;width:88px;height:88px;border-radius:10px;overflow:hidden;border:2px solid var(--border);flex:0 0 auto}
|
||||
.face-ref img{width:100%;height:100%;object-fit:cover;display:block}
|
||||
.face-ref .pf-del{position:absolute;top:4px;right:4px;width:20px;height:20px;border:none;border-radius:50%;background:rgba(0,0,0,.6);color:#fff;font-size:.7rem;line-height:1;cursor:pointer;display:flex;align-items:center;justify-content:center}
|
||||
.face-ref .pf-del:hover{background:#ef4444}
|
||||
.face-shot{position:relative;width:104px;height:78px;border-radius:8px;overflow:hidden;border:1px solid var(--border);flex:0 0 auto}
|
||||
.face-shot img{width:100%;height:100%;object-fit:cover;display:block;cursor:zoom-in}
|
||||
.face-shot a.face-src{position:absolute;left:4px;bottom:4px;background:rgba(0,0,0,.6);color:#fff;font-size:.6rem;font-weight:600;padding:1px 5px;border-radius:5px;text-decoration:none}
|
||||
.face-box{position:absolute;border:2px solid rgba(148,163,184,.9);border-radius:4px;cursor:pointer;box-sizing:border-box}
|
||||
.face-box:hover{border-color:#fff}
|
||||
.face-box--unassigned{background:rgba(148,163,184,.18);border-style:dashed}
|
||||
.face-box--candidate{background:rgba(245,158,11,.14);border-color:#f59e0b;border-style:dotted}
|
||||
.face-box--matched{background:rgba(59,130,246,.16);border-color:#3b82f6}
|
||||
.face-box-label{position:absolute;left:-2px;top:-1.35em;background:#3b82f6;color:#fff;font-size:.62rem;font-weight:600;padding:1px 5px;border-radius:4px;white-space:nowrap}
|
||||
.face-box--unassigned .face-box-label{background:rgba(71,85,105,.92)}
|
||||
.face-box--candidate .face-box-label{background:rgba(180,83,9,.94)}
|
||||
.face-overlay{position:absolute;inset:0;pointer-events:none}
|
||||
.face-stage{position:relative;display:inline-block;line-height:0;max-width:100%}
|
||||
.face-stage img{max-width:100%;max-height:74vh;display:block}
|
||||
.face-stage .face-box{pointer-events:auto}
|
||||
.face-empty{color:var(--muted);font-size:.78rem}
|
||||
.btn-primary.ghost.spinning svg{animation:spin 1s linear infinite}
|
||||
.p-faces{position:absolute;left:8px;top:8px;background:rgba(15,23,42,.72);color:#e2e8f0;font-size:.68rem;font-weight:700;padding:2px 7px;border-radius:999px;pointer-events:none}
|
||||
.p-faces.unassigned{background:#b45309;color:#fff}
|
||||
.p-faces-btn{background:none;border:none;color:var(--accent);cursor:pointer;font-size:.9rem;padding:2px 4px}
|
||||
.attach-item{display:flex;align-items:center;gap:8px;width:100%;text-align:left;background:var(--bg);border:1px solid var(--border);border-radius:8px;padding:8px 10px;cursor:pointer}
|
||||
.attach-item:hover{border-color:var(--accent)}
|
||||
.attach-name{font-size:.84rem;font-weight:600;min-width:0;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}
|
||||
.attach-sub{margin-left:auto;flex:0 0 auto;max-width:45%;font-size:.72rem;color:var(--muted);overflow:hidden;text-overflow:ellipsis;white-space:nowrap}
|
||||
|
||||
/* --- Фото группы (хронология) --- */
|
||||
.group-cover{width:100%;aspect-ratio:16/9;object-fit:cover;border-radius:10px;display:block;background:var(--bg)}
|
||||
.group-cover:hover{opacity:.9}
|
||||
|
||||
+32
-1
@@ -52,7 +52,14 @@
|
||||
<div class="gallery-modal">
|
||||
<div class="gallery-head">
|
||||
<h3 id="photosTitle">Фото</h3>
|
||||
<button class="upload-btn" type="button" id="openPhotoBtn">Загрузить фото</button>
|
||||
<div style="display:flex;gap:8px;align-items:center;flex-wrap:wrap">
|
||||
<select id="faceStudentFilter" class="settings-input" style="width:auto;min-width:170px;padding:7px 10px;font-size:.82rem">
|
||||
<option value="">Все фото</option>
|
||||
<option value="__unassigned__">С неопознанными лицами</option>
|
||||
</select>
|
||||
<button class="upload-btn" type="button" id="scanFacesBtn" title="Найти лица на ещё не обработанных фото">Найти лица</button>
|
||||
<button class="upload-btn" type="button" id="openPhotoBtn">Загрузить фото</button>
|
||||
</div>
|
||||
</div>
|
||||
<div class="photo-grid" id="photoGrid"><div class="empty">Загрузка...</div></div>
|
||||
<div class="pager" id="photosPager"></div>
|
||||
@@ -206,6 +213,30 @@
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="modal-overlay" id="faceViewerModal">
|
||||
<div class="edit-modal" style="max-width:1000px;width:96%;max-height:94dvh">
|
||||
<div style="display:flex;justify-content:space-between;align-items:center;gap:12px;margin-bottom:12px">
|
||||
<h3 style="font-size:1.05rem;font-weight:600">Распознанные лица</h3>
|
||||
<button type="button" class="btn-primary ghost" id="faceViewerCloseBtn">Закрыть</button>
|
||||
</div>
|
||||
<div id="faceViewerBody" style="display:flex;justify-content:center"></div>
|
||||
<p class="hint" style="margin-top:10px">Синяя рамка — лицо привязано автоматически, в подписи процент сходства; «вручную» — привязано вами. Оранжевая пунктирная — похоже на известного ученика, но сходство ниже порога. Серая — не опознано. Клик по любой рамке — привязать или сменить ученика.</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="modal-overlay" id="faceAssignModal">
|
||||
<div class="edit-modal" style="max-width:460px">
|
||||
<h3 style="font-size:1.05rem;font-weight:600;margin-bottom:12px">Привязать лицо к ученику</h3>
|
||||
<input type="text" id="faceAssignSearch" class="settings-input" placeholder="Поиск ученика или группы..." autocomplete="off">
|
||||
<p class="hint" style="margin:6px 0 0">Поиск по всем группам — на фото может быть ученик из другой группы. Сначала идут ученики текущей группы.</p>
|
||||
<div class="attach-list" id="faceAssignList" style="margin-top:10px;max-height:44vh;overflow:auto"></div>
|
||||
<div class="card-foot" style="justify-content:flex-end;gap:8px;margin-top:12px">
|
||||
<button type="button" class="btn-primary ghost" id="faceUnassignBtn">Снять привязку</button>
|
||||
<button type="button" class="btn-primary ghost" id="faceAssignCancelBtn">Отмена</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="modal-overlay" id="photoHistoryModal">
|
||||
<div class="edit-modal enhance-modal">
|
||||
<h3 id="photoHistoryTitle">История изменений фотографии</h3>
|
||||
|
||||
@@ -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);
|
||||
|
||||
@@ -27,6 +27,7 @@
|
||||
<div class="filters">
|
||||
<div><label>Поиск</label><input type="text" id="searchInput" class="search-input" placeholder="Описание или имя"></div>
|
||||
<div><label>Ученик</label><input type="text" id="studentFilter" list="studentFilterList" placeholder="Все / введите имя..."><datalist id="studentFilterList"></datalist></div>
|
||||
<div><label>По лицам</label><select id="faceStudentFilter"><option value="">Без фильтра</option><option value="__unassigned__">Неопознанные лица</option></select></div>
|
||||
<div><label>Группа</label><select id="groupFilter"><option value="">Все группы</option></select></div>
|
||||
<div><label>Источник</label><select id="sourceFilter"><option value="">Все источники</option></select></div>
|
||||
<div><label>С</label><input type="date" id="dateFrom"></div>
|
||||
|
||||
@@ -31,6 +31,7 @@
|
||||
<a href="#sec-notify" data-nav="sec-notify"><i data-lucide="bell"></i> Уведомления</a>
|
||||
<a href="#sec-ai" data-nav="sec-ai"><i data-lucide="bot"></i> ИИ</a>
|
||||
<a href="#sec-lesson-ai" data-nav="sec-lesson-ai"><i data-lucide="notebook-pen"></i> Шаблон отчёта</a>
|
||||
<a href="#sec-faces" data-nav="sec-faces"><i data-lucide="scan-face"></i> Библиотека лиц</a>
|
||||
<a href="#sec-notes-ai" data-nav="sec-notes-ai"><i data-lucide="sticky-note"></i> Заголовки заметок</a>
|
||||
<a href="#sec-backup" data-nav="sec-backup"><i data-lucide="database"></i> Бэкапы</a>
|
||||
<a href="#sec-trash" data-nav="sec-trash"><i data-lucide="trash-2"></i> Корзина</a>
|
||||
@@ -210,6 +211,33 @@
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="settings-card" id="sec-faces">
|
||||
<div class="card-head">
|
||||
<div class="ic"><i data-lucide="scan-face"></i></div>
|
||||
<h3>Библиотека лиц</h3>
|
||||
</div>
|
||||
<p class="hint">Сервис <b>face-id</b> ищет лица на фото групп и записей журнала, сравнивает их с эталонными фото учеников и позволяет привязать лицо к ученику вручную. Если <code>FACE_ID_URL</code> не задан или контейнер не запущен, распознавание отключено — остальная функциональность приложения не меняется.</p>
|
||||
<label class="toggle">
|
||||
<input type="checkbox" id="faceIdEnabled">
|
||||
<span class="toggle-track"><span class="toggle-thumb"></span></span>
|
||||
<span class="toggle-text"><b>Распознавать лица на фото</b><small>Эталоны задаются в карточке ученика — «Библиотека лиц»</small></span>
|
||||
</label>
|
||||
<label class="toggle">
|
||||
<input type="checkbox" id="faceScanOnUpload">
|
||||
<span class="toggle-track"><span class="toggle-thumb"></span></span>
|
||||
<span class="toggle-text"><b>Сканировать сразу при загрузке фото</b><small>В фоне, не задерживая ответ. Недосканированные фото добираются кнопкой «Найти лица»</small></span>
|
||||
</label>
|
||||
<div class="settings-field">
|
||||
<label for="faceIdThreshold">Порог совпадения (косинусное сходство)</label>
|
||||
<input type="number" id="faceIdThreshold" class="settings-input" min="0.3" max="0.99" step="0.01">
|
||||
<span class="hint">0.3–0.99. Выше — строже: меньше ложных совпадений, но выше шанс не узнать ученика. Ручная привязка доступна всегда</span>
|
||||
</div>
|
||||
<div style="display:flex;gap:10px;align-items:center;flex-wrap:wrap;margin-top:4px">
|
||||
<button type="button" class="btn-primary ghost" id="faceRematchBtn"><i data-lucide="refresh-cw"></i> Пересчитать лица по всем фото</button>
|
||||
<span class="hint" id="faceRematchHint">Сопоставляет уже найденные лица с эталонами — сервис face-id не нужен, работает по сохранённым эмбеддингам. Запускается автоматически после добавления эталона. Ручные привязки не трогает.</span>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="settings-card" id="sec-notes-ai">
|
||||
<div class="card-head">
|
||||
<div class="ic"><i data-lucide="sticky-note"></i></div>
|
||||
|
||||
@@ -207,6 +207,19 @@
|
||||
<span class="hint">Клик по фото — сделать главным. Можно вставить из буфера обмена (Ctrl+V)</span>
|
||||
</div>
|
||||
</div>
|
||||
<div class="settings-field" style="grid-column:1/-1">
|
||||
<label>Библиотека лиц — эталонные фото для распознавания</label>
|
||||
<div class="face-refs" id="faceRefsList"></div>
|
||||
<div style="display:flex;gap:10px;align-items:center;flex-wrap:wrap;margin-top:6px">
|
||||
<input type="file" id="faceRefFile" accept="image/*" hidden>
|
||||
<button type="button" class="btn-primary ghost" id="faceRefAddBtn">Добавить эталон</button>
|
||||
<span class="hint">1–2 фото анфас при хорошем свете. Лицо на фото ищет сервис face-id.</span>
|
||||
</div>
|
||||
</div>
|
||||
<div class="settings-field" style="grid-column:1/-1">
|
||||
<label>Фото с учеником (по распознаванию лиц)</label>
|
||||
<div class="face-refs" id="facePhotosList"></div>
|
||||
</div>
|
||||
<div style="grid-column:1/-1;display:flex;justify-content:flex-end;gap:8px">
|
||||
<button type="button" class="btn-primary ghost" id="profileDataCancelBtn">Отмена</button>
|
||||
<button type="submit" class="btn-primary">Сохранить</button>
|
||||
|
||||
Reference in New Issue
Block a user