students: add face reference from the profile photo

POST /api/students/:id/face-refs/from-profile inserts a student_face_refs
row straight from students.photo_path, with no new upload. The file is copied
under a fresh name via storage.copyObject: deleting a ref unlinks its
photo_path, so reusing the original would destroy the profile photo. Path must
start with /uploads/, otherwise 400.

The faces modal gets a "Взять из фото профиля" button, hidden unless the
student has an /uploads/ profile photo (state from GET /api/students/:id/profile).
.face-ref-profile-btn[hidden]{display:none} is required — .btn-primary sets
inline-flex, which overrides the UA [hidden] rule.
This commit is contained in:
dev
2026-10-10 13:31:39 +03:00
parent 60e701d1d3
commit 8847028b7e
5 changed files with 93 additions and 1 deletions
+1
View File
@@ -242,6 +242,7 @@ This document defines how AI agents should work with the WhatIDo codebase. Follo
- **Три состояния рамки** в `#faceViewerModal` (классы `.face-box--matched` / `--candidate` / `--unassigned`): привязано автоматически → `Имя · NN%`; привязано вручную → `Имя · вручную`; не привязано, но `best_score` ≥ `candidate_min` → `Похож: Имя · NN%`; иначе `Не опознано`. Клик по рамке с кандидатом открывает `#faceAssignModal` и подставляет имя кандидата в `#faceAssignSearch` — привязка в один клик
- **Ручная привязка всегда доступна**: `PUT /api/photo-faces/:faceId/assign` ставит `confidence = 1`, `student_id: 0`/отсутствие снимает привязку. Автопорог — `face_id_threshold` (валидация в `PUT /api/settings`: 0.3..0.99), «неопознано» ≠ ошибка
- **Доступ**: `studentProfileAccess()` для эталонов, `groupBelongsToBranches()` для лиц фото — не-admin не видит и не привязывает лица чужих филиалов. `POST /api/faces/scan-unscanned` под `requireAdmin`
- **Эталон из фото профиля**: `POST /api/students/:id/face-refs/from-profile` (без multipart, под `requireAuth`) берёт `students.photo_path` и добавляет его в `student_face_refs` без повторной загрузки. Файл **обязательно копируется** через `storage.copyObject(keyFromPath(src), <hex>.jpg)` под новым именем: `DELETE /api/students/:id/face-refs/:refId` вызывает `safeUnlink(photo_path)` и без копии удаление эталона снесло бы фото профиля. Путь обязан начинаться с `/uploads/` (иначе 400 «У ученика нет фото профиля» — фото может быть `/api/files/...`-ссылкой). Остальное как у загрузки: `faceIdDetect(name, null)` → 503 при недоступности, 400 если лицо не найдено, лучшее лицо по `det_score`, аудит `student.face_ref.create` с `source: 'profile'`, `rematchFacesBackground()` после ответа. Копия через `storage.*` сразу попадает в S3, хук `res.on('finish')` тут не участвует. Фронт — `#faceRefProfileBtn` в `#studentFacesModal` (`public/students.html`, `addFaceRefFromProfile()` в `public/js/students.js`): кнопка `hidden`, пока нет `/uploads/`-фото профиля, состояние берётся из `GET /api/students/:id/profile` в `loadFaceProfilePhoto(id)`; после добавления и после удаления любого эталона кнопка переоценивается
- **Фильтры** — и в галерее группы, и в глобальном `/api/photos`: `student_id` и `unassigned_faces=1` через `EXISTS` по `photo_faces`. В `/api/photos` матчинг идёт **по `pf.photo_path = t.path`, а не по id**: в этом агрегаторе `source_id` для `group_photo` — это `group_id`, а для `entry` — `id` записи, так что сопоставление с `photo_faces.source_id` (там id фото) даёт ложные совпадения и молча теряет результат. Путь фото — единственный общий ключ. В галерее группы (`GET /api/groups/:id/photos`) матчинг по `pf.source_id = gp.id` корректен
- **Бэкап и sweep**: `student_face_refs` + `photo_faces` в `BACKUP_TABLES` и `BACKUP_SEQUENCE_TABLES`, в `normalizeRestoreData` и restore-INSERT (с проверкой FK: фото → `group_photos`/`entry_photos`, `student_id` → `students`). `student_face_refs.photo_path` **обязан** быть в `sweepOrphanedUploads`, иначе файлы эталонов снесутся как сироты сразу после restore
- **Фронт**: `students.html`/`students.js` — «Библиотека лиц» + «Фото с учеником» в `#profileDataModal`; `groups.html`/`groups.js` — оверлей `.face-box` (`.face-box--matched` / `.face-box--candidate` / `.face-box--unassigned`) в модалке `#faceViewerModal`, привязка в `#faceAssignModal`, селект-фильтр и кнопка «Найти лица»; `photos.html`/`photos.js` — фильтр «По лицам»; настройки — карточка `#sec-faces`. CSS в `public/admin.css`, блок `/* --- Библиотека лиц --- */`
+1
View File
@@ -289,6 +289,7 @@ body{font-family:-apple-system,BlinkMacSystemFont,'Segoe UI',Roboto,sans-serif;b
.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}
.face-ref-profile-btn[hidden]{display:none}
.btn-primary.ghost.spinning svg{animation:spin 1s linear infinite}
.p-faces{position:absolute;right: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;display:inline-flex;align-items:center;gap:4px}
.p-faces svg{width:12px;height:12px}
+48 -1
View File
@@ -9,6 +9,7 @@ let attachGroupLoaded = false;
let faceRefs = [];
let facePhotos = [];
let faceSimilar = [];
let faceProfilePhoto = '';
async function loadGroupOptions(sel, selected) {
if (!groupOptionsLoaded) {
@@ -266,12 +267,14 @@ async function openStudentFaces(id, name) {
faceRefs = [];
facePhotos = [];
faceSimilar = [];
faceProfilePhoto = '';
renderFaceProfileBtn();
document.getElementById('studentFacesName').textContent = name || '';
renderFaceRefs();
renderFacePhotos();
renderFaceSimilar();
document.getElementById('studentFacesModal').classList.add('open');
await Promise.all([loadFaceRefs(id), loadFacePhotos(id)]);
await Promise.all([loadFaceRefs(id), loadFacePhotos(id), loadFaceProfilePhoto(id)]);
}
function closeStudentFaces() {
@@ -280,6 +283,27 @@ function closeStudentFaces() {
faceRefs = [];
facePhotos = [];
faceSimilar = [];
faceProfilePhoto = '';
renderFaceProfileBtn();
}
function renderFaceProfileBtn() {
const btn = document.getElementById('faceRefProfileBtn');
if (btn) btn.hidden = !faceProfilePhoto;
}
async function loadFaceProfilePhoto(id) {
faceProfilePhoto = '';
try {
const res = await fetch(`${API}/api/students/${id}/profile`, { headers: hdr() });
if (!res.ok) return;
const data = await res.json();
if (typeof data.photo_path === 'string' && data.photo_path.startsWith('/uploads/')) faceProfilePhoto = data.photo_path;
} catch {
faceProfilePhoto = '';
} finally {
if (profileDataId === id) renderFaceProfileBtn();
}
}
async function loadFaceRefs(id) {
@@ -346,6 +370,27 @@ async function addFaceRef(file) {
}
}
async function addFaceRefFromProfile() {
if (!profileDataId) return;
showToast('Ищем лицо на фото профиля...');
try {
const res = await fetch(`${API}/api/students/${profileDataId}/face-refs/from-profile`, { method: 'POST', headers: hdr() });
const data = await res.json();
if (!res.ok) {
showToast(data.error || 'Не удалось добавить эталон');
return;
}
faceRefs.push(data);
faceProfilePhoto = '';
renderFaceProfileBtn();
renderFaceRefs();
showToast('Эталон добавлен из фото профиля, пересчитываем лица на всех фото...');
refreshFacesAfterRefChange();
} catch {
showToast('Не удалось добавить эталон');
}
}
async function delFaceRef(refId) {
try {
const res = await fetch(`${API}/api/students/${profileDataId}/face-refs/${refId}`, { method: 'DELETE', headers: hdr() });
@@ -357,6 +402,7 @@ async function delFaceRef(refId) {
renderFaceRefs();
showToast('Эталон удалён, пересчитываем лица...');
refreshFacesAfterRefChange();
if (profileDataId) loadFaceProfilePhoto(profileDataId);
} catch {
showToast('Не удалось удалить эталон');
}
@@ -819,6 +865,7 @@ document.getElementById('pfFacesBtn').addEventListener('click', () => {
document.getElementById('studentFacesCloseBtn').addEventListener('click', closeStudentFaces);
document.getElementById('studentFacesModal').addEventListener('click', e => { if (e.target === e.currentTarget) closeStudentFaces(); });
document.getElementById('faceRefAddBtn').addEventListener('click', () => document.getElementById('faceRefFile').click());
document.getElementById('faceRefProfileBtn').addEventListener('click', addFaceRefFromProfile);
document.getElementById('faceRefFile').addEventListener('change', e => {
const f = e.target.files[0];
e.target.value = '';
+1
View File
@@ -235,6 +235,7 @@
<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>
<button type="button" class="btn-primary ghost face-ref-profile-btn" id="faceRefProfileBtn" hidden>Взять из фото профиля</button>
<span class="hint">1–2 фото анфас при хорошем свете. После добавления система пересчитает лица на всех фото.</span>
</div>
</div>
+42
View File
@@ -8463,6 +8463,48 @@ app.post('/api/students/:id/face-refs', requireAuth, (req, res, next) => {
}
});
app.post('/api/students/:id/face-refs/from-profile', requireAuth, async (req, res) => {
if (!faceIdConfigured()) return res.status(503).json({ error: 'Face-ID сервис не настроен (FACE_ID_URL)' });
let id;
try {
id = reqInt(req.params.id);
} catch {
return res.status(400).json({ error: 'Неверный id ученика' });
}
const acc = await studentProfileAccess(req.user, id);
if (!acc.found) return res.status(acc.forbidden ? 403 : 404).json({ error: acc.forbidden ? 'Нет доступа к этому ученику' : 'Ученик не найден' });
const profilePath = String(acc.student.photo_path || '');
const srcKey = profilePath.startsWith('/uploads/') ? storage.keyFromPath(profilePath) : null;
if (!srcKey) return res.status(400).json({ error: 'У ученика нет фото профиля' });
const copyName = `${crypto.randomBytes(12).toString('hex')}${path.extname(srcKey) || '.jpg'}`;
if (!(await storage.copyObject(srcKey, copyName))) {
return res.status(400).json({ error: 'Файл фото профиля не найден' });
}
try {
const faces = await faceIdDetect(copyName, null);
if (!faces) {
safeUnlink(`uploads/${copyName}`);
return res.status(503).json({ error: 'Face-ID сервис недоступен' });
}
if (!faces.length) {
safeUnlink(`uploads/${copyName}`);
return res.status(400).json({ error: 'Лицо не найдено на фото профиля. Загрузите фото анфас' });
}
const best = faces.reduce((a, b) => ((b.det_score || 0) > (a.det_score || 0) ? b : a));
const { rows } = await pool.query(
`INSERT INTO student_face_refs (student_id, photo_path, embedding, det_score) VALUES ($1, $2, $3, $4) RETURNING id, student_id, photo_path, det_score, created_at`,
[id, `/uploads/${copyName}`, JSON.stringify(best.embedding), Number(best.det_score) || 0]
);
await logAudit(req, 'student.face_ref.create', { student_id: id, ref_id: rows[0].id, source: 'profile' });
res.status(201).json(rows[0]);
rematchFacesBackground();
} catch (e) {
safeUnlink(`uploads/${copyName}`);
console.error('POST /api/students/:id/face-refs/from-profile:', e);
res.status(500).json({ error: e.message });
}
});
app.get('/api/students/:id/face-refs', requireAuth, async (req, res) => {
let id;
try {