students: modal for student face refs and found/similar photos

Кнопка "Лица" в строке ученика открывает #studentFacesModal: эталонные
фото, фото, где лицо ученика уже найдено, и похожие непривязанные лица.
Эталоны переехали из #profileDataModal — id элементов должны быть в
документе ровно один раз.

Поиск похожих личностей переведён с перебора эмбеддингов на хранение
кандидата в БД: photo_faces.best_student_id + best_score заполняются при
скане и при пересчёте, у привязанных лиц обнуляются. Частичный индекс
WHERE student_id IS NULL - без него запрос поднимал бы все эмбеддинги.

Также:
- пересчёт по всем фото теперь запускается и при удалении эталона,
  иначе кандидаты устаревают
- иконки в панели действий карточки фото и в бейдже лиц - lucide
- бейдж лиц прижат вправо, панель действий прижата к низу карточки
This commit is contained in:
dev
2026-10-10 12:50:29 +03:00
parent 0356fd4e02
commit 60e701d1d3
9 changed files with 238 additions and 77 deletions
+80 -35
View File
@@ -1720,12 +1720,17 @@ async function ensureFaceTables() {
det_score REAL DEFAULT 0,
student_id INT REFERENCES students(id) ON DELETE SET NULL,
confidence REAL DEFAULT 0,
best_student_id INT REFERENCES students(id) ON DELETE SET NULL,
best_score REAL NOT NULL DEFAULT 0,
created_at TIMESTAMPTZ DEFAULT now(),
updated_at TIMESTAMPTZ DEFAULT now()
)`);
await pool.query('ALTER TABLE photo_faces ADD COLUMN IF NOT EXISTS best_student_id INT REFERENCES students(id) ON DELETE SET NULL');
await pool.query('ALTER TABLE photo_faces ADD COLUMN IF NOT EXISTS best_score REAL NOT NULL DEFAULT 0');
await pool.query('CREATE INDEX IF NOT EXISTS idx_photo_faces_source ON photo_faces(source_type, source_id)');
await pool.query('CREATE INDEX IF NOT EXISTS idx_photo_faces_student ON photo_faces(student_id)');
await pool.query('CREATE INDEX IF NOT EXISTS idx_photo_faces_source_student ON photo_faces(source_type, source_id, student_id)');
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');
}
@@ -1777,6 +1782,8 @@ function faceThreshold(v) {
return Math.min(0.99, Math.max(0.3, n));
}
const FACE_CANDIDATE_MIN = 0.5;
function safeId(v) {
const n = parseInt(v, 10);
return Number.isFinite(n) && n > 0 ? n : 0;
@@ -1815,11 +1822,6 @@ function matchFaceToStudent(embedding, refs, threshold) {
return { student_id: studentId, confidence: best, best_id: bestId, best_name: bestName };
}
function bestFaceCandidate(embedding, refs) {
const m = matchFaceToStudent(embedding, refs, Infinity);
return { score: m.confidence, student_id: m.best_id, name: m.best_name };
}
async function photoFaceGroupId(sourceType, sourceId) {
if (sourceType === 'entry') {
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]);
@@ -1849,9 +1851,15 @@ async function rematchFaces(opts = {}) {
scanned += rows.length;
for (const r of rows) {
const m = matchFaceToStudent(r.embedding, refs, threshold);
if (!m.student_id) continue;
if (!m.student_id) {
await client.query(
'UPDATE photo_faces SET best_student_id = $1, best_score = $2, updated_at = now() WHERE id = $3',
[m.best_id || null, Number(m.confidence) || 0, r.id]
);
continue;
}
await client.query(
'UPDATE photo_faces SET student_id = $1, confidence = $2, updated_at = now() WHERE id = $3',
'UPDATE photo_faces SET student_id = $1, confidence = $2, best_student_id = NULL, best_score = 0, updated_at = now() WHERE id = $3',
[m.student_id, m.confidence, r.id]
);
matched++;
@@ -1892,10 +1900,11 @@ async function scanFacesForPhoto(sourceType, sourceId, photoPath, opts = {}) {
const m = matchFaceToStudent(f.embedding, refs, threshold);
const b = Array.isArray(f.bbox) ? f.bbox : [];
await client.query(
`INSERT INTO photo_faces (source_type, source_id, photo_path, bbox, embedding, det_score, student_id, confidence)
VALUES ($1, $2, $3, $4, $5, $6, $7, $8)`,
`INSERT INTO photo_faces (source_type, source_id, photo_path, bbox, embedding, det_score, student_id, confidence, best_student_id, best_score)
VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10)`,
[sourceType, sourceId, photoPath, JSON.stringify({ x: b[0] || 0, y: b[1] || 0, w: b[2] || 0, h: b[3] || 0 }),
JSON.stringify(f.embedding), Number(f.det_score) || 0, m.student_id, m.confidence]
JSON.stringify(f.embedding), Number(f.det_score) || 0, m.student_id, m.confidence,
m.student_id ? null : (m.best_id || null), m.student_id ? 0 : (Number(m.confidence) || 0)]
);
}
await client.query(
@@ -5271,11 +5280,16 @@ app.post('/api/restore', requireAdmin, uploadBackup.single('backup'), async (req
const st = await client.query('SELECT 1 FROM students WHERE id = $1', [x.student_id]);
if (!st.rowCount) continue;
}
if (x.best_student_id != null) {
const bs = await client.query('SELECT 1 FROM students WHERE id = $1', [x.best_student_id]);
if (!bs.rowCount) continue;
}
await client.query(
`INSERT INTO photo_faces (id, source_type, source_id, photo_path, bbox, embedding, det_score, student_id, confidence, created_at, updated_at)
VALUES ($1,$2,$3,$4,$5::jsonb,$6::jsonb,$7,$8,$9,$10,$11)`,
`INSERT INTO photo_faces (id, source_type, source_id, photo_path, bbox, embedding, det_score, student_id, confidence, best_student_id, best_score, created_at, updated_at)
VALUES ($1,$2,$3,$4,$5::jsonb,$6::jsonb,$7,$8,$9,$10,$11,$12,$13)`,
[x.id, x.source_type, x.source_id, x.photo_path, JSON.stringify(x.bbox || {}), JSON.stringify(x.embedding || []),
x.det_score || 0, x.student_id, x.confidence || 0, x.created_at || null, x.updated_at || null]
x.det_score || 0, x.student_id, x.confidence || 0, x.best_student_id || null, x.best_score || 0,
x.created_at || null, x.updated_at || null]
);
}
for (const x of ndata.student_photos) {
@@ -8481,6 +8495,7 @@ app.delete('/api/students/:id/face-refs/:refId', requireAuth, async (req, res) =
safeUnlink(rows[0].photo_path.replace(/^\/?uploads\//, 'uploads/'));
await logAudit(req, 'student.face_ref.delete', { student_id: id, ref_id: refId });
res.json({ ok: true });
rematchFacesBackground();
});
@@ -8506,32 +8521,29 @@ app.get('/api/photos/:sourceType/:sourceId/faces', requireAuth, async (req, res)
return res.status(403).json({ error: 'Нет доступа' });
}
const { rows } = await pool.query(
`SELECT pf.id, pf.bbox, pf.student_id, pf.confidence, pf.det_score, pf.embedding, s.name AS student_name
`SELECT pf.id, pf.bbox, pf.student_id, pf.confidence, pf.det_score,
pf.best_student_id, pf.best_score, s.name AS student_name, bs.name AS best_student_name
FROM photo_faces pf
LEFT JOIN students s ON s.id = pf.student_id
LEFT JOIN students bs ON bs.id = pf.best_student_id
WHERE pf.source_type = $1 AND pf.source_id = $2
ORDER BY (pf.bbox->>'y')::int ASC, (pf.bbox->>'x')::int ASC`,
[sourceType, sourceId]
);
const refs = await loadFaceRefs();
res.json({
faces: rows.map(r => {
const best = r.student_id
? { score: Number(r.confidence) || 0, student_id: r.student_id, name: r.student_name }
: bestFaceCandidate(r.embedding, refs);
return {
id: r.id,
x: r.bbox.x || 0, y: r.bbox.y || 0, w: r.bbox.w || 0, h: r.bbox.h || 0,
student_id: r.student_id,
student_name: r.student_name,
confidence: Number(r.confidence) || 0,
det_score: r.det_score,
manual: r.student_id ? Number(r.confidence) >= 1 : false,
best_score: best.score || 0,
best_student_id: best.student_id || null,
best_student_name: best.name || null,
};
}),
candidate_min: FACE_CANDIDATE_MIN,
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,
student_id: r.student_id,
student_name: r.student_name,
confidence: Number(r.confidence) || 0,
det_score: r.det_score,
manual: r.student_id ? Number(r.confidence) >= 1 : false,
best_score: Number(r.best_score) || 0,
best_student_id: r.best_student_id,
best_student_name: r.best_student_name,
})),
});
});
@@ -8564,7 +8576,10 @@ app.put('/api/photo-faces/:faceId/assign', requireAuth, async (req, res) => {
if (req.user.role !== 'admin' && !(await groupBelongsToBranches(req.user, faceGroupId))) {
return res.status(403).json({ error: 'Нет доступа к этому фото' });
}
await pool.query('UPDATE photo_faces SET student_id = $1, confidence = 1, updated_at = now() WHERE id = $2', [studentId || null, faceId]);
await pool.query(
'UPDATE photo_faces SET student_id = $1, confidence = 1, best_student_id = NULL, best_score = 0, updated_at = now() WHERE id = $2',
[studentId || null, faceId]
);
await logAudit(req, 'photo_face.assign', { face_id: faceId, student_id: studentId || null, was: chk[0].student_id });
res.json({ ok: true, student_id: studentId || null });
});
@@ -8578,6 +8593,9 @@ app.get('/api/students/:id/face-photos', requireAuth, async (req, res) => {
}
const acc = await studentProfileAccess(req.user, id);
if (!acc.found) return res.status(acc.forbidden ? 403 : 404).json({ error: 'Ученик не найден' });
const params = [];
const gscope = apiBranchClause(req.user, 'g.branch_id', params);
params.push(id);
const { rows } = await pool.query(
`SELECT DISTINCT ON (pf.source_type, pf.source_id) pf.source_type, pf.source_id, pf.photo_path,
gp.group_id, e.id AS entry_ref, g.name AS group_name,
@@ -8587,9 +8605,26 @@ app.get('/api/students/:id/face-photos', requireAuth, async (req, res) => {
LEFT JOIN entry_photos ep ON ep.id = pf.source_id AND pf.source_type = 'entry'
LEFT JOIN entries e ON e.id = ep.entry_id
LEFT JOIN groups g ON g.id = COALESCE(gp.group_id, e.group_id)
WHERE pf.student_id = $1
WHERE pf.student_id = $${params.length}${gscope}
ORDER BY pf.source_type, pf.source_id, COALESCE(gp.created_at, ep.created_at) DESC`,
[id]
params
);
const sparams = [];
const sscope = apiBranchClause(req.user, 'g.branch_id', sparams);
sparams.push(id);
const { rows: srows } = await pool.query(
`SELECT DISTINCT ON (pf.source_type, pf.source_id) pf.source_type, pf.source_id, pf.photo_path,
gp.group_id, e.id AS entry_ref, g.name AS group_name,
COALESCE(gp.created_at, ep.created_at) AS created_at, pf.best_score
FROM photo_faces pf
LEFT JOIN group_photos gp ON gp.id = pf.source_id AND pf.source_type = 'group'
LEFT JOIN entry_photos ep ON ep.id = pf.source_id AND pf.source_type = 'entry'
LEFT JOIN entries e ON e.id = ep.entry_id
LEFT JOIN groups g ON g.id = COALESCE(gp.group_id, e.group_id)
WHERE pf.student_id IS NULL AND pf.best_student_id = $${sparams.length}
AND pf.best_score >= $${sparams.length + 1}${sscope}
ORDER BY pf.source_type, pf.source_id, pf.best_score DESC`,
sparams.concat([FACE_CANDIDATE_MIN])
);
res.json({
photos: rows.map(r => ({
@@ -8599,8 +8634,18 @@ app.get('/api/students/:id/face-photos', requireAuth, async (req, res) => {
group_name: r.group_name,
created_at: r.created_at,
confidence: r.confidence,
manual: Number(r.confidence) >= 1,
})),
similar: srows.map(r => ({
source_type: r.source_type,
source_id: r.source_type === 'group' ? r.group_id : (r.entry_ref || r.source_id),
path: r.photo_path,
group_name: r.group_name,
created_at: r.created_at,
score: Number(r.best_score) || 0,
})),
total: rows.length,
similar_total: srows.length,
});
});