fix(face-id): пересчитывать рамки лиц при подмене фото после ИИ-улучшения
Рамки в #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 в транзакции с откатом.
This commit is contained in:
@@ -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) {
|
||||
|
||||
Reference in New Issue
Block a user