From 8479fbb68d92ffe9745ecbd1b4cd6c568b292485 Mon Sep 17 00:00:00 2001 From: dev Date: Sat, 10 Oct 2026 14:40:06 +0300 Subject: [PATCH] =?UTF-8?q?fix(face-id):=20=D0=BF=D0=B5=D1=80=D0=B5=D1=81?= =?UTF-8?q?=D1=87=D0=B8=D1=82=D1=8B=D0=B2=D0=B0=D1=82=D1=8C=20=D1=80=D0=B0?= =?UTF-8?q?=D0=BC=D0=BA=D0=B8=20=D0=BB=D0=B8=D1=86=20=D0=BF=D1=80=D0=B8=20?= =?UTF-8?q?=D0=BF=D0=BE=D0=B4=D0=BC=D0=B5=D0=BD=D0=B5=20=D1=84=D0=BE=D1=82?= =?UTF-8?q?=D0=BE=20=D0=BF=D0=BE=D1=81=D0=BB=D0=B5=20=D0=98=D0=98-=D1=83?= =?UTF-8?q?=D0=BB=D1=83=D1=87=D1=88=D0=B5=D0=BD=D0=B8=D1=8F?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Рамки в #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 в транзакции с откатом. --- AGENTS.md | 3 + backup-restore.js | 6 ++ backup.selftest.js | 24 ++++++ db/init.sql | 4 + db/migration.sql | 4 + public/groups.html | 6 +- public/js/groups.js | 104 ++++++++++++++++++++----- server.js | 180 ++++++++++++++++++++++++++++++++++++++------ 8 files changed, 290 insertions(+), 41 deletions(-) diff --git a/AGENTS.md b/AGENTS.md index a082317..5ae0e93 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -234,6 +234,9 @@ This document defines how AI agents should work with the WhatIDo codebase. Follo - **Таблицы**: `student_face_refs` (эталоны: `photo_path`, `embedding` jsonb, `det_score`) и `photo_faces` (найденные: `source_type` = `group`|`entry`, `source_id`, `bbox` jsonb `{x,y,w,h}`, `embedding`, `student_id` nullable, `confidence`). Схема в `db/init.sql` + `db/migration.sql` + `ensureFaceTables()`. Кропы лиц **не** хранятся — только эмбеддинги, bbox и путь фото - **`bbox` хранится в пикселях исходника, не в долях**. `face-id` отдаёт абсолютные координаты, `scanFacesForPhoto` кладёт их как есть, `GET /api/photos/:sourceType/:sourceId/faces` отдаёт `x/y/w/h` без нормализации. Нормировать обязан фронт: `faceBoxesHTML(nw, nh)` в `public/js/groups.js` делит на `naturalWidth`/`naturalHeight` и рисует в `%`, а вызывается из `layout()` — то есть **после** загрузки картинки (до неё `naturalWidth === 0`). Умножать пиксели на 100 нельзя: рамки уезжают за фото, их не видно и кликнуть по ним (а значит и привязать лицо) невозможно - **`face_scanned_at`** в `group_photos` и `entry_photos` — единственный признак «несканировано». Кнопка «Найти лица» и `POST /api/faces/scan-unscanned` берут `WHERE face_scanned_at IS NULL`; `rescan: true` в теле проходит все фото заново +- **`bbox` живёт в пикселях того файла, который сканировали**: `photo_faces.bbox` — абсолютные координаты исходника, а фронт делит их на `naturalWidth/naturalHeight` **текущего** ``. Смена файла без пересчёта = рамки в чужом масштабе. Поэтому рядом с `face_scanned_at` лежат `face_img_width`/`face_img_height` в `group_photos` и `entry_photos` — размеры картинки, к которой относятся сохранённые рамки. Их пишет `scanFacesForPhoto` из ответа `/detect` (для этого `faceIdDetect` возвращает `{ faces, width, height }`, а не просто массив), а новая колонка объявляется в `db/init.sql`, `db/migration.sql`, `ensureFaceTables()`, `normalizeRestoreData` и restore-INSERT +- **Любая подмена файла обязана звать `rescalePhotoFaces(client, sourceType, sourceId, newPath, w, h)`**: размеры нового файла берёт `imagePixelSize()` (`storage.localize` + `sharp().metadata()`), старые — из `face_img_*`. Масштаб известен → рамки умножаются на `new/old` и вместе с ними обновляется `photo_faces.photo_path` (без него фильтр «по лицам» в `/api/photos` перестаёт находить фото после apply). Размеры неизвестны (строка просканирована до появления колонок) → рамки удаляются, `face_scanned_at = NULL`, фото уходит в фоновый скан. Вызывается из **всех** мест, меняющих `photo_path`: apply и rollback для группы и для записи журнала. Забытый вызов — это ровно тот баг со «съехавшими» рамками, который здесь описан +- **Ручная переиндексация одного фото** — `POST /api/photos/:sourceType/:sourceId/faces/rescan` (`source_id` = id `group_photos`/`entry_photos`, не записи), кнопка `#faceViewerRescanBtn` в `#faceViewerModal`. `GET /api/photos/:sourceType/:sourceId/faces` отдаёт `img_width`/`img_height`/`scanned`; `checkFaceViewerSync()` в `public/js/groups.js` сравнивает их с `img.naturalWidth` после загрузки картинки и показывает `#faceViewerWarn`, если фото подменили. После apply/rollback/сохранения улучшения вьюер перерисовывается через `refreshOpenFaceViewer()` — иначе рамки остались бы от старого файла до ручного переоткрытия - **Скан при загрузке** — `scanFacesBackground()` через `setImmediate` **после** `res.json(...)`: в группе после `INSERT ... RETURNING`, в записи журнала после `COMMIT` (там фото в транзакции, поэтому id `entry_photos` дотягиваются отдельным SELECT). Роут не блокируется - **Эмбеддинги не переиспользуются между фото**: при каждом скане фото refs перечитываются целиком (`loadFaceRefs`) — объём маленький (десятки строк), кэш дал бы риск устаревшей привязки - **Пересчёт привязок по всем фото** — `rematchFaces()`: идёт по `photo_faces` **с `student_id IS NULL`**, батчами по 1000 (пагинация по `id > lastId`, не по `LIMIT` — молча терять хвост нельзя), и каждому лицу пересчитывает косинус к эталонам. Детект не повторяется: эмбеддинги уже в БД, `face-id` не нужен. Автозапуск — `rematchFacesBackground()` из `POST`/`DELETE /api/students/:id/face-refs` (через `setImmediate` **после** ответа, под `face_id_enabled = 'true'`) — удаление эталона пересчёт тоже вызывает, иначе кандидаты устареют; ручной запуск — `POST /api/faces/rematch` под `requireAuth, requireAdmin`, кнопка `#faceRematchBtn` в `#sec-faces`. Смысл: фото, просканированные до появления эталона, получили `student_id = NULL` навсегда — без пересчёта они так и остались бы нераспознанными. При ошибке возвращает `error` и эндпоинт отвечает 500 — молчаливый 200 на откатившейся транзакции вводил бы в заблуждение diff --git a/backup-restore.js b/backup-restore.js index 95b1296..9395730 100644 --- a/backup-restore.js +++ b/backup-restore.js @@ -379,6 +379,9 @@ function normalizeRestoreData(data) { photo_path: reqUploadPath(x.photo_path, 255), caption: optStr(x.caption, 10000), sort_order: optInt(x.sort_order, -2147483648, 2147483647), + face_scanned_at: optTs(x.face_scanned_at), + face_img_width: optInt(x.face_img_width, 1, 100000), + face_img_height: optInt(x.face_img_height, 1, 100000), created_at: optTs(x.created_at), })); const student_photos = (data.student_photos || []).map(x => ({ @@ -395,6 +398,9 @@ function normalizeRestoreData(data) { caption: optStr(x.caption, 10000), taken_at: optDate(x.taken_at), sort_order: optInt(x.sort_order, -2147483648, 2147483647), + face_scanned_at: optTs(x.face_scanned_at), + face_img_width: optInt(x.face_img_width, 1, 100000), + face_img_height: optInt(x.face_img_height, 1, 100000), created_at: optTs(x.created_at), })); const share_links = (data.share_links || []).map(x => ({ diff --git a/backup.selftest.js b/backup.selftest.js index eacd4c9..9b390f0 100644 --- a/backup.selftest.js +++ b/backup.selftest.js @@ -151,5 +151,29 @@ try { } ok('путь картинки закладки вне uploads отклоняется', bkmBadPath); +const faceGeo = normalizeRestoreData({ + ...base, + group_photos: [{ id: 1, group_id: 1, photo_path: '/uploads/a.jpg', face_scanned_at: '2026-01-02T03:04:05.000Z', face_img_width: 4000, face_img_height: 3000 }], + entry_photos: [{ id: 1, entry_id: 1, photo_path: '/uploads/b.jpg', face_img_width: 2000, face_img_height: 1500 }], +}); +ok('размеры фото для рамок лиц сохраняются', + faceGeo.group_photos[0].face_img_width === 4000 && faceGeo.group_photos[0].face_img_height === 3000 + && faceGeo.entry_photos[0].face_img_width === 2000 && faceGeo.entry_photos[0].face_img_height === 1500, + faceGeo.group_photos[0]); +const faceGeoNone = normalizeRestoreData({ + ...base, + entry_photos: [{ id: 1, entry_id: 1, photo_path: '/uploads/b.jpg' }], +}); +ok('пустые размеры рамок лиц остаются null', + faceGeoNone.entry_photos[0].face_scanned_at === null && faceGeoNone.entry_photos[0].face_img_width === null, + faceGeoNone.entry_photos[0]); +let faceGeoBad = false; +try { + normalizeRestoreData({ ...base, entry_photos: [{ id: 1, entry_id: 1, photo_path: '/uploads/b.jpg', face_img_width: 0 }] }); +} catch (e) { + faceGeoBad = true; +} +ok('некорректный размер рамки лица отклоняется', faceGeoBad); + console.log(failed ? `\n${failed} проверок провалено` : '\nBACKUP SELFTEST OK'); process.exit(failed ? 1 : 0); \ No newline at end of file diff --git a/db/init.sql b/db/init.sql index d28f5ef..cffeee8 100644 --- a/db/init.sql +++ b/db/init.sql @@ -612,6 +612,10 @@ CREATE INDEX IF NOT EXISTS idx_photo_faces_best ON photo_faces(best_student_id) ALTER TABLE group_photos ADD COLUMN IF NOT EXISTS face_scanned_at TIMESTAMPTZ; ALTER TABLE entry_photos ADD COLUMN IF NOT EXISTS face_scanned_at TIMESTAMPTZ; +ALTER TABLE group_photos ADD COLUMN IF NOT EXISTS face_img_width INT; +ALTER TABLE group_photos ADD COLUMN IF NOT EXISTS face_img_height INT; +ALTER TABLE entry_photos ADD COLUMN IF NOT EXISTS face_img_width INT; +ALTER TABLE entry_photos ADD COLUMN IF NOT EXISTS face_img_height INT; INSERT INTO settings (key, value) VALUES ('face_id_enabled', 'false') ON CONFLICT (key) DO NOTHING; INSERT INTO settings (key, value) VALUES ('face_id_threshold', '0.6') ON CONFLICT (key) DO NOTHING; diff --git a/db/migration.sql b/db/migration.sql index b81ada6..33c0608 100644 --- a/db/migration.sql +++ b/db/migration.sql @@ -771,6 +771,10 @@ CREATE INDEX IF NOT EXISTS idx_photo_faces_best ON photo_faces(best_student_id) ALTER TABLE group_photos ADD COLUMN IF NOT EXISTS face_scanned_at TIMESTAMPTZ; ALTER TABLE entry_photos ADD COLUMN IF NOT EXISTS face_scanned_at TIMESTAMPTZ; +ALTER TABLE group_photos ADD COLUMN IF NOT EXISTS face_img_width INT; +ALTER TABLE group_photos ADD COLUMN IF NOT EXISTS face_img_height INT; +ALTER TABLE entry_photos ADD COLUMN IF NOT EXISTS face_img_width INT; +ALTER TABLE entry_photos ADD COLUMN IF NOT EXISTS face_img_height INT; INSERT INTO settings (key, value) VALUES ('face_id_enabled', 'false') ON CONFLICT (key) DO NOTHING; INSERT INTO settings (key, value) VALUES ('face_id_threshold', '0.6') ON CONFLICT (key) DO NOTHING; diff --git a/public/groups.html b/public/groups.html index 9d830e1..6567c48 100644 --- a/public/groups.html +++ b/public/groups.html @@ -217,8 +217,12 @@

Распознанные лица

- +
+ + +
+

Синяя рамка — лицо привязано автоматически, в подписи процент сходства; «вручную» — привязано вами. Оранжевая пунктирная — похоже на известного ученика, но сходство ниже порога. Серая — не опознано. Клик по любой рамке — привязать или сменить ученика.

diff --git a/public/js/groups.js b/public/js/groups.js index 9f0ad13..5fdb015 100644 --- a/public/js/groups.js +++ b/public/js/groups.js @@ -210,6 +210,80 @@ function renderFaceStudentFilter() { 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; @@ -219,17 +293,10 @@ async function openFaceViewer(photoId) { body.innerHTML = '
Загрузка...
'; document.getElementById('faceViewerModal').classList.add('open'); try { - const res = await fetch(`${API}/api/photos/group/${photoId}/faces`, { headers: hdr() }); - if (!res.ok) { - body.innerHTML = `
${res.status === 404 ? 'Фото не найдено' : 'Не удалось загрузить лица'}
`; - return; - } - const data = await res.json(); - faceViewer.faces = data.faces || []; - faceViewer.candidateMin = Number(data.candidate_min) > 0 ? Number(data.candidate_min) : FACE_CANDIDATE_MIN; + await loadFaceViewerFaces(photoId); renderFaceViewer(photo.photo_path); - } catch { - body.innerHTML = '
Не удалось загрузить лица
'; + } catch (e) { + body.innerHTML = `
${e.status === 404 ? 'Фото не найдено' : 'Не удалось загрузить лица'}
`; } } @@ -276,6 +343,7 @@ function renderFaceViewer(photoPath) { ov.style.left = img.offsetLeft + 'px'; ov.style.top = img.offsetTop + 'px'; ov.innerHTML = faceViewer.faces.length ? faceBoxesHTML(nw, nh) : '
Лиц не найдено
'; + checkFaceViewerSync(nw, nh); }; if (img.complete && img.naturalWidth) layout(); else img.addEventListener('load', layout, { once: true }); @@ -285,6 +353,7 @@ function renderFaceViewer(photoPath) { 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 }; } @@ -339,15 +408,7 @@ async function assignFace(studentId) { 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); - } - } + if (photoId) await refreshOpenFaceViewer(); loadGroupPhotos(); } catch { showToast('Не удалось сохранить привязку'); @@ -1224,6 +1285,7 @@ async function rollbackPhotoJob(jobId) { document.getElementById('photoHistoryModal').classList.remove('open'); await refreshEnhanceFromPath(data.photo_path); await loadGroupPhotos(); + await refreshOpenFaceViewer(); loadGroups(); } catch (e) { alert(e.message); @@ -1244,6 +1306,7 @@ async function applyPhotoJob(jobId) { document.getElementById('photoHistoryModal').classList.remove('open'); await refreshEnhanceFromPath(data.photo_path); await loadGroupPhotos(); + await refreshOpenFaceViewer(); loadGroups(); } catch (e) { alert(e.message); @@ -1276,6 +1339,7 @@ async function saveEnhance() { showToast('Фото улучшено и сохранено'); closeEnhance(); await loadGroupPhotos(); + await refreshOpenFaceViewer(); loadGroups(); } catch (e) { enhanceSaving = false; @@ -1443,6 +1507,7 @@ async function applyAiResult() { enhanceAiResultPath = null; closeEnhance(); await loadGroupPhotos(); + await refreshOpenFaceViewer(); loadGroups(); } catch (err) { alert(err.message); @@ -1475,6 +1540,7 @@ document.getElementById('imgModal')?.addEventListener('click', e => e.currentTar 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]'); diff --git a/server.js b/server.js index a8ffd85..f49efd1 100644 --- a/server.js +++ b/server.js @@ -1733,6 +1733,10 @@ async function ensureFaceTables() { await pool.query('CREATE INDEX IF NOT EXISTS idx_photo_faces_best ON photo_faces(best_student_id) WHERE student_id IS NULL'); await pool.query('ALTER TABLE group_photos ADD COLUMN IF NOT EXISTS face_scanned_at TIMESTAMPTZ'); await pool.query('ALTER TABLE entry_photos ADD COLUMN IF NOT EXISTS face_scanned_at TIMESTAMPTZ'); + await pool.query('ALTER TABLE group_photos ADD COLUMN IF NOT EXISTS face_img_width INT'); + await pool.query('ALTER TABLE group_photos ADD COLUMN IF NOT EXISTS face_img_height INT'); + await pool.query('ALTER TABLE entry_photos ADD COLUMN IF NOT EXISTS face_img_width INT'); + await pool.query('ALTER TABLE entry_photos ADD COLUMN IF NOT EXISTS face_img_height INT'); } function faceIdConfigured() { @@ -1758,7 +1762,11 @@ async function faceIdDetect(key, refs) { const r = await fetch(faceIdUrl() + endpoint, { method: 'POST', body: form, signal: ctrl.signal }); if (!r.ok) throw new Error(`face-id ${endpoint}: HTTP ${r.status}`); const data = await r.json(); - return Array.isArray(data.faces) ? data.faces : []; + return { + faces: Array.isArray(data.faces) ? data.faces : [], + width: Number(data.width) || 0, + height: Number(data.height) || 0, + }; } finally { clearTimeout(t); } @@ -1881,14 +1889,17 @@ async function scanFacesForPhoto(sourceType, sourceId, photoPath, opts = {}) { if (!faceIdConfigured()) return null; const key = storage.keyFromPath(photoPath); if (!key) return null; - let faces; + let detected; try { - faces = await faceIdDetect(key, null); + detected = await faceIdDetect(key, null); } catch (e) { console.error(`Face detect failed (${sourceType} ${sourceId}):`, e.message); return null; } - if (!faces) return null; + if (!detected) return null; + const faces = detected.faces; + const imgW = Number(detected.width) || 0; + const imgH = Number(detected.height) || 0; const threshold = faceThreshold(await getSetting('face_id_threshold', '0.6')); const refs = opts.noMatch ? [] : await loadFaceRefs(); const client = await pool.connect(); @@ -1909,9 +1920,9 @@ async function scanFacesForPhoto(sourceType, sourceId, photoPath, opts = {}) { } await client.query( sourceType === 'entry' - ? 'UPDATE entry_photos SET face_scanned_at = now() WHERE id = $1' - : 'UPDATE group_photos SET face_scanned_at = now() WHERE id = $1', - [sourceId] + ? 'UPDATE entry_photos SET face_scanned_at = now(), face_img_width = $2, face_img_height = $3 WHERE id = $1' + : 'UPDATE group_photos SET face_scanned_at = now(), face_img_width = $2, face_img_height = $3 WHERE id = $1', + [sourceId, imgW || null, imgH || null] ); await client.query('COMMIT'); return faces.length; @@ -1947,6 +1958,77 @@ function rematchFacesBackground() { }); } +async function imagePixelSize(photoPath) { + if (!sharp) return { w: 0, h: 0 }; + const key = photoPath ? storage.keyFromPath(photoPath) : null; + if (!key) return { w: 0, h: 0 }; + try { + const local = await storage.localize(key); + if (!local) return { w: 0, h: 0 }; + const meta = await sharp(local).metadata(); + return { w: Number(meta.width) || 0, h: Number(meta.height) || 0 }; + } catch (e) { + console.error('imagePixelSize failed:', e.message); + return { w: 0, h: 0 }; + } +} + +function facePhotoTable(sourceType) { + return sourceType === 'entry' ? 'entry_photos' : 'group_photos'; +} + +async function rescalePhotoFaces(client, sourceType, sourceId, newPath, newW, newH) { + const table = facePhotoTable(sourceType); + const q = (sql, params) => (client || pool).query(sql, params); + const { rows: cur } = await q( + `SELECT face_img_width, face_img_height FROM ${table} WHERE id = $1`, + [sourceId] + ); + const oldW = Number(cur[0] && cur[0].face_img_width) || 0; + const oldH = Number(cur[0] && cur[0].face_img_height) || 0; + if (!newW || !newH) return 'skip'; + if (!oldW || !oldH) { + await q('DELETE FROM photo_faces WHERE source_type = $1 AND source_id = $2', [sourceType, sourceId]); + await q( + `UPDATE ${table} SET face_scanned_at = NULL, face_img_width = $2, face_img_height = $3 WHERE id = $1`, + [sourceId, newW, newH] + ); + return 'rescan'; + } + if (oldW === newW && oldH === newH) { + await q( + `UPDATE ${table} SET face_img_width = $2, face_img_height = $3 WHERE id = $1`, + [sourceId, newW, newH] + ); + await q( + 'UPDATE photo_faces SET photo_path = $1, updated_at = now() WHERE source_type = $2 AND source_id = $3', + [newPath, sourceType, sourceId] + ); + return 'same'; + } + const kx = newW / oldW; + const ky = newH / oldH; + const { rows: faces } = await q( + 'SELECT id, bbox FROM photo_faces WHERE source_type = $1 AND source_id = $2', + [sourceType, sourceId] + ); + for (const f of faces) { + const b = f.bbox || {}; + const box = { + x: Math.round((Number(b.x) || 0) * kx), + y: Math.round((Number(b.y) || 0) * ky), + w: Math.max(1, Math.round((Number(b.w) || 0) * kx)), + h: Math.max(1, Math.round((Number(b.h) || 0) * ky)), + }; + await q('UPDATE photo_faces SET bbox = $1, photo_path = $2, updated_at = now() WHERE id = $3', [JSON.stringify(box), newPath, f.id]); + } + await q( + `UPDATE ${table} SET face_img_width = $2, face_img_height = $3 WHERE id = $1`, + [sourceId, newW, newH] + ); + return 'scaled'; +} + async function ensureEntryAiColumns() { await pool.query(`ALTER TABLE entries ADD COLUMN IF NOT EXISTS description_original TEXT`); @@ -5262,14 +5344,14 @@ app.post('/api/restore', requireAdmin, uploadBackup.single('backup'), async (req } for (const x of ndata.group_photos) { await client.query( - 'INSERT INTO group_photos (id, group_id, photo_path, photo_original_path, caption, taken_at, sort_order, created_at) VALUES ($1,$2,$3,$4,$5,$6,$7,$8)', - [x.id, x.group_id, x.photo_path, x.photo_original_path || null, x.caption, x.taken_at, x.sort_order, x.created_at] + 'INSERT INTO group_photos (id, group_id, photo_path, photo_original_path, caption, taken_at, sort_order, face_scanned_at, face_img_width, face_img_height, created_at) VALUES ($1,$2,$3,$4,$5,$6,$7,$8,$9,$10,$11)', + [x.id, x.group_id, x.photo_path, x.photo_original_path || null, x.caption, x.taken_at, x.sort_order, x.face_scanned_at || null, x.face_img_width || null, x.face_img_height || null, x.created_at] ); } for (const x of ndata.entry_photos) { await client.query( - 'INSERT INTO entry_photos (id, entry_id, photo_path, caption, sort_order, created_at) VALUES ($1,$2,$3,$4,$5,$6)', - [x.id, x.entry_id, x.photo_path, x.caption, x.sort_order, x.created_at] + 'INSERT INTO entry_photos (id, entry_id, photo_path, caption, sort_order, face_scanned_at, face_img_width, face_img_height, created_at) VALUES ($1,$2,$3,$4,$5,$6,$7,$8,$9)', + [x.id, x.entry_id, x.photo_path, x.caption, x.sort_order, x.face_scanned_at || null, x.face_img_width || null, x.face_img_height || null, x.created_at] ); } for (const x of (ndata.photo_faces || [])) { @@ -6366,10 +6448,12 @@ app.post('/api/groups/:id/photos/:photoId/jobs/:jobId/apply', requireAuth, async } await client.query('UPDATE group_photos SET photo_path = $1, photo_original_path = $2 WHERE id = $3 AND group_id = $4', [job.after_path, originalPath, photoId, req.params.id]); await client.query('UPDATE groups SET cover_path = $1 WHERE id = $2 AND cover_path = $3', [job.after_path, req.params.id, oldPath]); + const faceDims = await imagePixelSize(job.after_path); + const faceMode = await rescalePhotoFaces(client, 'group', photoId, job.after_path, faceDims.w, faceDims.h); thumbUnlinkFor(oldPath); await client.query(`UPDATE photo_jobs SET applied = true, before_path = COALESCE(before_path, $1) WHERE id = $2`, [beforePath, jobId]); await client.query('COMMIT'); - await logAudit(req, 'group.photo.apply', { group_id: req.params.id, photo_id: photoId, job_id: jobId, before_path: beforePath, after_path: job.after_path }); + await logAudit(req, 'group.photo.apply', { group_id: req.params.id, photo_id: photoId, job_id: jobId, before_path: beforePath, after_path: job.after_path, faces: faceMode }); invalidateShare(); invalidateGroups(); invalidateStats(); @@ -6542,11 +6626,13 @@ app.post('/api/groups/:id/photos/:photoId/jobs/:jobId/rollback', requireAuth, as thumbUnlinkFor(oldPath); await pool.query('UPDATE group_photos SET photo_path = $1 WHERE id = $2 AND group_id = $3', [newPath, photoId, req.params.id]); await pool.query('UPDATE groups SET cover_path = $1 WHERE id = $2 AND cover_path = $3', [newPath, req.params.id, oldPath]); + const faceDims = await imagePixelSize(newPath); + const faceMode = await rescalePhotoFaces(null, 'group', photoId, newPath, faceDims.w, faceDims.h); await pool.query( 'INSERT INTO photo_jobs (group_photo_id, action, status, before_path, after_path, finished_at) VALUES ($1, $2, $3, $4, $5, now())', [photoId, 'rollback', 'done', rollbackBefore, newPath] ); - await logAudit(req, 'group.photo.rollback', { group_id: req.params.id, photo_id: photoId, job_id: jobId, restored_path: newPath }); + await logAudit(req, 'group.photo.rollback', { group_id: req.params.id, photo_id: photoId, job_id: jobId, restored_path: newPath, faces: faceMode }); invalidateShare(); invalidateGroups(); invalidateStats(); @@ -8438,11 +8524,12 @@ app.post('/api/students/:id/face-refs', requireAuth, (req, res, next) => { } try { await convertPhoto(req.file); - const faces = await faceIdDetect(req.file.filename, null); - if (!faces) { + const detected = await faceIdDetect(req.file.filename, null); + if (!detected) { removeUpload(req.file); return res.status(503).json({ error: 'Face-ID сервис недоступен' }); } + const faces = detected.faces; if (!faces.length) { removeUpload(req.file); return res.status(400).json({ error: 'Лицо не найдено на фото. Загрузите фото анфас' }); @@ -8481,11 +8568,12 @@ app.post('/api/students/:id/face-refs/from-profile', requireAuth, async (req, re return res.status(400).json({ error: 'Файл фото профиля не найден' }); } try { - const faces = await faceIdDetect(copyName, null); - if (!faces) { + const detected = await faceIdDetect(copyName, null); + if (!detected) { safeUnlink(`uploads/${copyName}`); return res.status(503).json({ error: 'Face-ID сервис недоступен' }); } + const faces = detected.faces; if (!faces.length) { safeUnlink(`uploads/${copyName}`); return res.status(400).json({ error: 'Лицо не найдено на фото профиля. Загрузите фото анфас' }); @@ -8550,14 +8638,17 @@ app.get('/api/photos/:sourceType/:sourceId/faces', requireAuth, async (req, res) return res.status(400).json({ error: 'Неверный id' }); } let groupId = null; + let faceImg = null; if (sourceType === 'group') { - const { rows } = await pool.query('SELECT group_id FROM group_photos WHERE id = $1', [sourceId]); + const { rows } = await pool.query('SELECT group_id, face_scanned_at, face_img_width, face_img_height FROM group_photos WHERE id = $1', [sourceId]); if (!rows.length) return res.status(404).json({ error: 'Фото не найдено' }); groupId = rows[0].group_id; + faceImg = rows[0]; } else { - const { rows } = await pool.query('SELECT e.group_id FROM entry_photos ep JOIN entries e ON e.id = ep.entry_id WHERE ep.id = $1', [sourceId]); + const { rows } = await pool.query('SELECT e.group_id, ep.face_scanned_at, ep.face_img_width, ep.face_img_height FROM entry_photos ep JOIN entries e ON e.id = ep.entry_id WHERE ep.id = $1', [sourceId]); if (!rows.length) return res.status(404).json({ error: 'Фото не найдено' }); groupId = rows[0].group_id; + faceImg = rows[0]; } if (req.user.role !== 'admin' && groupId && !(await groupBelongsToBranches(req.user, groupId))) { return res.status(403).json({ error: 'Нет доступа' }); @@ -8574,6 +8665,9 @@ app.get('/api/photos/:sourceType/:sourceId/faces', requireAuth, async (req, res) ); res.json({ candidate_min: FACE_CANDIDATE_MIN, + scanned: Boolean(faceImg && faceImg.face_scanned_at), + img_width: Number(faceImg && faceImg.face_img_width) || 0, + img_height: Number(faceImg && faceImg.face_img_height) || 0, faces: rows.map(r => ({ id: r.id, x: r.bbox.x || 0, y: r.bbox.y || 0, w: r.bbox.w || 0, h: r.bbox.h || 0, @@ -8589,6 +8683,38 @@ app.get('/api/photos/:sourceType/:sourceId/faces', requireAuth, async (req, res) }); }); +app.post('/api/photos/:sourceType/:sourceId/faces/rescan', requireAuth, async (req, res) => { + if (!faceIdConfigured()) return res.status(503).json({ error: 'Face-ID сервис не настроен (FACE_ID_URL)' }); + const sourceType = req.params.sourceType === 'entry' ? 'entry' : 'group'; + let sourceId; + try { + sourceId = reqInt(req.params.sourceId); + } catch { + return res.status(400).json({ error: 'Неверный id' }); + } + let groupId = null; + let photoPath = ''; + if (sourceType === 'group') { + const { rows } = await pool.query('SELECT group_id, photo_path FROM group_photos WHERE id = $1', [sourceId]); + if (!rows.length) return res.status(404).json({ error: 'Фото не найдено' }); + groupId = rows[0].group_id; + photoPath = rows[0].photo_path || ''; + } else { + const { rows } = await pool.query('SELECT e.group_id, ep.photo_path FROM entry_photos ep JOIN entries e ON e.id = ep.entry_id WHERE ep.id = $1', [sourceId]); + if (!rows.length) return res.status(404).json({ error: 'Фото не найдено' }); + groupId = rows[0].group_id; + photoPath = rows[0].photo_path || ''; + } + if (req.user.role !== 'admin' && groupId && !(await groupBelongsToBranches(req.user, groupId))) { + return res.status(403).json({ error: 'Нет доступа' }); + } + if (!photoPath) return res.status(400).json({ error: 'У фото нет изображения' }); + const found = await scanFacesForPhoto(sourceType, sourceId, photoPath); + if (found === null) return res.status(503).json({ error: 'Не удалось распознать лица' }); + await logAudit(req, 'photo.faces.rescan', { source_type: sourceType, source_id: sourceId, faces: found }); + res.json({ ok: true, scanned: found }); +}); + app.post('/api/faces/rematch', requireAuth, requireAdmin, async (req, res) => { const out = await rematchFaces(); await logAudit(req, 'faces.rematch', out); @@ -9700,12 +9826,18 @@ app.post('/api/entries/:id/photo/jobs/:jobId/apply', requireAuth, async (req, re console.error('photo apply backup failed:', e); } } + const { rows: epRows } = await client.query('SELECT id FROM entry_photos WHERE entry_id = $1 AND photo_path = $2', [req.params.id, oldPath]); await client.query('UPDATE entries SET photo_path = $1, photo_original_path = $2 WHERE id = $3', [job.after_path, originalPath, req.params.id]); await client.query('UPDATE entry_photos SET photo_path = $1 WHERE entry_id = $2 AND photo_path = $3', [job.after_path, req.params.id, oldPath]); + const faceDims = await imagePixelSize(job.after_path); + let faceMode = 'skip'; + for (const ep of epRows) { + faceMode = await rescalePhotoFaces(client, 'entry', ep.id, job.after_path, faceDims.w, faceDims.h); + } thumbUnlinkFor(oldPath); await client.query(`UPDATE photo_jobs SET applied = true, before_path = COALESCE(before_path, $1) WHERE id = $2`, [beforePath, jobId]); await client.query('COMMIT'); - await logAudit(req, 'entry.photo.apply', { entry_id: req.params.id, job_id: jobId, before_path: beforePath, after_path: job.after_path }); + await logAudit(req, 'entry.photo.apply', { entry_id: req.params.id, job_id: jobId, before_path: beforePath, after_path: job.after_path, faces: faceMode }); invalidateEntries(); res.json({ ok: true, photo_path: job.after_path }); } catch (e) { @@ -9807,13 +9939,19 @@ app.post('/api/entries/:id/photo/jobs/:jobId/rollback', requireAuth, async (req, } } thumbUnlinkFor(oldPath); + const { rows: epRows } = await pool.query('SELECT id FROM entry_photos WHERE entry_id = $1 AND photo_path = $2', [req.params.id, oldPath]); await pool.query('UPDATE entries SET photo_path = $1 WHERE id = $2', [newPath, req.params.id]); await pool.query('UPDATE entry_photos SET photo_path = $1 WHERE entry_id = $2 AND photo_path = $3', [newPath, req.params.id, oldPath]); + const faceDims = await imagePixelSize(newPath); + let faceMode = 'skip'; + for (const ep of epRows) { + faceMode = await rescalePhotoFaces(null, 'entry', ep.id, newPath, faceDims.w, faceDims.h); + } await pool.query( 'INSERT INTO photo_jobs (entry_id, action, status, before_path, after_path, error, finished_at) VALUES ($1, $2, $3, $4, $5, NULL, now())', [req.params.id, 'rollback', 'done', rollbackBefore, newPath] ); - await logAudit(req, 'entry.photo.rollback', { entry_id: req.params.id, job_id: jobId, restored_path: newPath }); + await logAudit(req, 'entry.photo.rollback', { entry_id: req.params.id, job_id: jobId, restored_path: newPath, faces: faceMode }); invalidateEntries(); res.json({ ok: true, photo_path: newPath }); } catch (e) {