students: эталоны лиц из всех фото профиля и привязка похожих лиц из карточки
- POST /api/students/:id/face-refs/from-profile берёт все фото профиля
(students.photo_path + student_photos) с дедупликацией и возвращает
{ refs, added, skipped }, фото без лица пропускаются
- «Похожие лица» в #studentFacesModal: селект ученика (по умолчанию
владелец) и кнопка «Привязать» через PUT /api/photo-faces/:id/assign
- face_id в GET /api/students/:id/face-photos для привязки
- миниатюры эталонов через faceRefThumbSrc(); PAGE_SIZE файлов/фото -> 28
- AGENTS.md: описание эталонов из всех фото профиля
This commit is contained in:
@@ -8772,37 +8772,55 @@ app.post('/api/students/:id/face-refs/from-profile', requireAuth, async (req, re
|
||||
}
|
||||
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: 'Файл фото профиля не найден' });
|
||||
}
|
||||
const srcKeys = [];
|
||||
const seenKeys = new Set();
|
||||
const addKey = (p) => {
|
||||
if (typeof p !== 'string' || !p.startsWith('/uploads/')) return;
|
||||
const key = storage.keyFromPath(p);
|
||||
if (key && !seenKeys.has(key)) {
|
||||
seenKeys.add(key);
|
||||
srcKeys.push(key);
|
||||
}
|
||||
};
|
||||
addKey(acc.student.photo_path);
|
||||
const { rows: photoRows } = await pool.query('SELECT photo_path FROM student_photos WHERE student_id = $1 ORDER BY id DESC', [id]);
|
||||
for (const r of photoRows) addKey(r.photo_path);
|
||||
if (!srcKeys.length) return res.status(400).json({ error: 'У ученика нет фото профиля' });
|
||||
const created = [];
|
||||
let skipped = 0;
|
||||
try {
|
||||
const detected = await faceIdDetect(copyName, null);
|
||||
if (!detected) {
|
||||
safeUnlink(`uploads/${copyName}`);
|
||||
return res.status(503).json({ error: 'Face-ID сервис недоступен' });
|
||||
for (const srcKey of srcKeys) {
|
||||
const copyName = `${crypto.randomBytes(12).toString('hex')}${path.extname(srcKey) || '.jpg'}`;
|
||||
if (!(await storage.copyObject(srcKey, copyName))) {
|
||||
skipped++;
|
||||
continue;
|
||||
}
|
||||
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}`);
|
||||
skipped++;
|
||||
continue;
|
||||
}
|
||||
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' });
|
||||
created.push(rows[0]);
|
||||
}
|
||||
const faces = detected.faces;
|
||||
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 });
|
||||
return res.status(500).json({ error: e.message });
|
||||
}
|
||||
if (!created.length) return res.status(400).json({ error: 'Лицо не найдено ни на одном фото профиля. Загрузите фото анфас' });
|
||||
res.status(201).json({ refs: created, added: created.length, skipped });
|
||||
rematchFacesBackground();
|
||||
});
|
||||
|
||||
app.get('/api/students/:id/face-refs', requireAuth, async (req, res) => {
|
||||
@@ -9189,7 +9207,7 @@ app.get('/api/students/:id/face-photos', requireAuth, async (req, res) => {
|
||||
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,
|
||||
`SELECT DISTINCT ON (pf.source_type, pf.source_id) pf.id AS face_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
|
||||
@@ -9213,6 +9231,7 @@ app.get('/api/students/:id/face-photos', requireAuth, async (req, res) => {
|
||||
manual: Number(r.confidence) >= 1,
|
||||
})),
|
||||
similar: srows.map(r => ({
|
||||
face_id: r.face_id,
|
||||
source_type: r.source_type,
|
||||
source_id: r.source_type === 'group' ? r.group_id : (r.entry_ref || r.source_id),
|
||||
path: r.photo_path,
|
||||
|
||||
Reference in New Issue
Block a user