faces: очередь проверки лиц и страница «Сканер лиц»

Вынести распознавание лиц с загрузки в фоновую очередь:
- таблица face_scan_jobs (pending/processing/done/error) + воркер
  createFaceScanWorker (FOR UPDATE SKIP LOCKED, backoff, retry, очистка хвоста)
- дедупликация активных задач частичным уникальным индексом, ON CONFLICT
  обновляет photo_path
- scanFacesForPhoto теперь бросает ошибку вместо возврата null
- ручные эндпоинты scan-unscanned/scan-faces/rescan только ставят задачи
  и отвечают { queued, skipped, total }

Уведомления и SSE:
- face.scan.done (по умолчанию выключено), face.recognized, face.scan.error
- notifyFaceScan определяет филиал по источнику, SSE face_scan_status
  обновляет открытый вьюер лиц

Новая админ-страница «Сканер лиц» (faces.html, faces.js):
- мониторинг очереди и воркера, библиотека лиц, ошибки, аудит
- действия: wake, retry, clear, rematch, scan-unscanned
- GET /api/faces/monitor, POST /api/faces/queue/{wake,clear}

Обновлены AGENTS.md, db/init.sql, db/migration.sql (сид notify_face_*),
public/js/{groups,journal,settings}.js, public/admin.js, public/settings.html
This commit is contained in:
dev
2026-10-11 00:37:50 +03:00
parent 22466629c8
commit 8137fd35d5
12 changed files with 1480 additions and 72 deletions
+469 -61
View File
@@ -6,7 +6,7 @@ const { ipKeyGenerator } = require('express-rate-limit');
const helmet = require('helmet');
const bcrypt = require('bcrypt');
const heicConvert = require('heic-convert');
const { createEntryAutoChecker, createPhotoEnhanceWorker, createLessonReportChecker, createFeedbackWriter, createNoteTitleWorker } = require('./worker');
const { createEntryAutoChecker, createPhotoEnhanceWorker, createLessonReportChecker, createFeedbackWriter, createNoteTitleWorker, createFaceScanWorker } = require('./worker');
const { createZipWriter, renderStudentReport } = require('./student-report');
const { createStorage, mimeFor } = require('./storage');
@@ -136,6 +136,7 @@ const PHOTO_WAKE_CHANNEL = 'whatido:wake:photo';
const LESSON_AI_WAKE_CHANNEL = 'whatido:wake:lesson-ai';
const FEEDBACK_WAKE_CHANNEL = 'whatido:wake:feedback';
const NOTE_AI_WAKE_CHANNEL = 'whatido:wake:note-ai';
const FACE_SCAN_WAKE_CHANNEL = 'whatido:wake:face-scan';
function createWorkerBus(channel) {
return {
@@ -174,6 +175,19 @@ function dispatchEvent(payload) {
writeFrame('feedback_status', payload);
return;
}
if (payload && payload.type === 'face_scan_status') {
writeFrame('face_scan_status', {
source_type: payload.source_type,
source_id: payload.source_id,
status: payload.status,
faces: payload.faces || 0,
matched: payload.matched || 0,
names: payload.names || '',
error: payload.error || null,
ts: Date.now(),
});
return;
}
if (payload && (payload.type === 'entries_changed' || payload.type === 'lessons_changed' || payload.type === 'shorts_changed' || payload.type === 'notes_changed')) {
writeFrame(payload.type, { ts: Date.now() });
return;
@@ -266,6 +280,9 @@ const NOTIFY_TYPES = {
'lesson.report': { label: 'Отчёт о занятии', hint: 'Тьютор сохранил отчёт о том, что прошли на занятии', icon: 'notebook-pen', level: 'info', enabled: true, admin: false },
'lesson.ai.formatted': { label: 'Отчёт оформлен по шаблону', hint: 'ИИ привёл текст отчёта о занятии к деловому виду', icon: 'file-check', level: 'info', enabled: false, admin: false },
'feedback.ai.ready': { label: 'Отзыв сгенерирован', hint: 'ИИ сформировал отзыв по результатам занятия', icon: 'message-square-heart', level: 'info', enabled: true, admin: false },
'face.scan.done': { label: 'Найдены лица на фото', hint: 'Фоновая проверка нашла лица на загруженном фото. Сколько именно — в тексте уведомления', icon: 'scan-face', level: 'info', enabled: false, admin: false },
'face.recognized': { label: 'Ученики распознаны на фото', hint: 'Фоновая проверка сопоставила лица с эталонами и назвала учеников', icon: 'user-round-check', level: 'info', enabled: true, admin: false },
'face.scan.error': { label: 'Ошибка проверки лиц', hint: 'Сервис face-id недоступен или очередь проверки исчерпала попытки', icon: 'scan-search', level: 'warning', enabled: true, admin: false },
};
function notifySettingKey(type) {
@@ -1737,6 +1754,34 @@ async function ensureFaceTables() {
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');
await pool.query(`CREATE TABLE IF NOT EXISTS face_scan_jobs (
id SERIAL PRIMARY KEY,
source_type VARCHAR(20) NOT NULL,
source_id INT NOT NULL,
photo_path VARCHAR(255) NOT NULL,
status VARCHAR(20) NOT NULL DEFAULT 'pending',
attempts INT NOT NULL DEFAULT 0,
faces_found INT NOT NULL DEFAULT 0,
faces_matched INT NOT NULL DEFAULT 0,
matched_names TEXT,
error TEXT,
user_id INT,
created_at TIMESTAMPTZ DEFAULT now(),
updated_at TIMESTAMPTZ DEFAULT now()
)`);
await pool.query('ALTER TABLE face_scan_jobs ADD COLUMN IF NOT EXISTS source_type VARCHAR(20) NOT NULL DEFAULT \'\'');
await pool.query('ALTER TABLE face_scan_jobs ADD COLUMN IF NOT EXISTS source_id INT NOT NULL DEFAULT 0');
await pool.query('ALTER TABLE face_scan_jobs ADD COLUMN IF NOT EXISTS photo_path VARCHAR(255) NOT NULL DEFAULT \'\'');
await pool.query('ALTER TABLE face_scan_jobs ADD COLUMN IF NOT EXISTS status VARCHAR(20) NOT NULL DEFAULT \'pending\'');
await pool.query('ALTER TABLE face_scan_jobs ADD COLUMN IF NOT EXISTS attempts INT NOT NULL DEFAULT 0');
await pool.query('ALTER TABLE face_scan_jobs ADD COLUMN IF NOT EXISTS faces_found INT NOT NULL DEFAULT 0');
await pool.query('ALTER TABLE face_scan_jobs ADD COLUMN IF NOT EXISTS faces_matched INT NOT NULL DEFAULT 0');
await pool.query('ALTER TABLE face_scan_jobs ADD COLUMN IF NOT EXISTS matched_names TEXT');
await pool.query('ALTER TABLE face_scan_jobs ADD COLUMN IF NOT EXISTS error TEXT');
await pool.query('ALTER TABLE face_scan_jobs ADD COLUMN IF NOT EXISTS user_id INT');
await pool.query('CREATE INDEX IF NOT EXISTS idx_face_scan_jobs_status ON face_scan_jobs(status, id)');
await pool.query('DROP INDEX IF EXISTS idx_face_scan_jobs_active');
await pool.query('CREATE UNIQUE INDEX IF NOT EXISTS idx_face_scan_jobs_active ON face_scan_jobs(source_type, source_id) WHERE status IN (\'pending\', \'processing\')');
}
function faceIdConfigured() {
@@ -1772,6 +1817,28 @@ async function faceIdDetect(key, refs) {
}
}
async function faceIdHealth(timeoutMs = 3000) {
if (!faceIdConfigured()) return { configured: false, reachable: false, latency_ms: 0, ready: false, error: 'FACE_ID_URL не настроен' };
const startedAt = Date.now();
const controller = new AbortController();
const timer = setTimeout(() => controller.abort(), timeoutMs);
try {
const r = await fetch(`${faceIdUrl()}/health`, { signal: controller.signal });
const latency_ms = Date.now() - startedAt;
if (!r.ok) return { configured: true, reachable: false, latency_ms, ready: false, error: `HTTP ${r.status}` };
let data = null;
try { data = await r.json(); } catch (e) { data = null; }
const payload = data && typeof data === 'object' && !Array.isArray(data) ? data : {};
return { ...payload, configured: true, reachable: true, latency_ms, error: null };
} catch (e) {
const latency_ms = Date.now() - startedAt;
const error = e && e.name === 'AbortError' ? 'timeout' : (e && e.message ? e.message : 'unreachable');
return { configured: true, reachable: false, latency_ms, ready: false, error };
} finally {
clearTimeout(timer);
}
}
function cosineSimilarity(a, b) {
if (!Array.isArray(a) || !Array.isArray(b) || a.length !== b.length || !a.length) return 0;
let dot = 0, na = 0, nb = 0;
@@ -1792,6 +1859,16 @@ function faceThreshold(v) {
const FACE_CANDIDATE_MIN = 0.5;
const FACE_JOB_STATUSES = new Set(['pending', 'processing', 'done', 'error']);
const FACE_ACTIONS = [
'face.scan.retry', 'face.scan.error',
'student.face_ref.create', 'student.face_ref.delete',
'photo.faces.rescan', 'faces.rematch', 'faces.queue.retry', 'faces.queue.wake', 'faces.queue.clear',
'photo_face.assign', 'faces.scan_unscanned',
'entry.photos.scan_faces', 'group.photos.scan_faces',
];
function safeId(v) {
const n = parseInt(v, 10);
return Number.isFinite(n) && n > 0 ? n : 0;
@@ -1886,23 +1963,24 @@ async function rematchFaces(opts = {}) {
}
async function scanFacesForPhoto(sourceType, sourceId, photoPath, opts = {}) {
if (!faceIdConfigured()) return null;
if (!faceIdConfigured()) throw new Error('Face-ID сервис не настроен (FACE_ID_URL)');
const key = storage.keyFromPath(photoPath);
if (!key) return null;
if (!key) throw new Error('Некорректный путь к фото');
let detected;
try {
detected = await faceIdDetect(key, null);
} catch (e) {
console.error(`Face detect failed (${sourceType} ${sourceId}):`, e.message);
return null;
throw new Error(`face-id /detect: ${e.message}`);
}
if (!detected) return null;
if (!detected) throw new Error('face-id не вернул результат');
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();
const names = new Set();
let matched = 0;
try {
await client.query('BEGIN');
await client.query('DELETE FROM photo_faces WHERE source_type = $1 AND source_id = $2', [sourceType, sourceId]);
@@ -1910,6 +1988,11 @@ async function scanFacesForPhoto(sourceType, sourceId, photoPath, opts = {}) {
if (!Array.isArray(f.embedding) || !f.embedding.length) continue;
const m = matchFaceToStudent(f.embedding, refs, threshold);
const b = Array.isArray(f.bbox) ? f.bbox : [];
if (m.student_id) {
matched++;
const ref = refs.find(r => r.student_id === m.student_id);
if (ref && ref.name) names.add(ref.name);
}
await client.query(
`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)`,
@@ -1925,33 +2008,155 @@ async function scanFacesForPhoto(sourceType, sourceId, photoPath, opts = {}) {
[sourceId, imgW || null, imgH || null]
);
await client.query('COMMIT');
return faces.length;
return { faces: faces.length, matched, names: [...names].join(', ') };
} catch (e) {
await client.query('ROLLBACK').catch(() => {});
console.error(`Face scan failed (${sourceType} ${sourceId}):`, e.message);
return null;
throw e;
} finally {
client.release();
}
}
async function scanFacesBackground(sourceType, sourceId, photoPath) {
async function runFaceScanJob(job) {
return scanFacesForPhoto(job.sourceType, job.sourceId, job.photoPath);
}
async function enqueueFaceScan(sourceType, sourceId, photoPath, userId) {
const type = sourceType === 'entry' ? 'entry' : 'group';
const id = safeId(sourceId);
const path = String(photoPath || '');
if (!id || !path) return 0;
try {
const { rows } = await pool.query(
`INSERT INTO face_scan_jobs (source_type, source_id, photo_path, user_id)
VALUES ($1, $2, $3, $4)
ON CONFLICT (source_type, source_id) WHERE status IN ('pending', 'processing')
DO UPDATE SET photo_path = EXCLUDED.photo_path, updated_at = now()
RETURNING (xmax = 0) AS inserted`,
[type, id, path, userId ? safeId(userId) : null]
);
if (!rows.length || !rows[0].inserted) return 0;
wakeFaceScanWorker();
return 1;
} catch (e) {
console.error('Face scan enqueue failed:', e.message);
return 0;
}
}
async function enqueueFaceScans(rows, sourceType, userId) {
let queued = 0;
for (const p of rows) queued += await enqueueFaceScan(sourceType, p.id, p.photo_path, userId);
return queued;
}
function enqueueFaceScanBackground(sourceType, sourceId, photoPath, userId) {
setImmediate(async () => {
try {
if (!faceIdConfigured()) return;
if ((await getSetting('face_id_enabled', 'false')) !== 'true') return;
if ((await getSetting('face_scan_on_upload', 'true')) !== 'true') return;
await scanFacesForPhoto(sourceType, sourceId, photoPath);
if ((await getSetting('face_scan_on_upload', 'true')) === 'false') return;
await enqueueFaceScan(sourceType, sourceId, photoPath, userId);
} catch (e) {
console.error('Face background scan failed:', e.message);
console.error('Face scan enqueue failed:', e.message);
}
});
}
async function notifyFaceScan(sourceType, sourceId, { type, title, body, link, target, level }) {
const kind = sourceType === 'entry' ? 'entry' : 'group';
const id = safeId(sourceId);
if (!id) return null;
const { rows } = kind === 'entry'
? await pool.query(
`SELECT e.id AS entry_id, e.student_name, e.group_id, g.name AS group_name, g.branch_id
FROM entry_photos ep JOIN entries e ON e.id = ep.entry_id
LEFT JOIN groups g ON g.id = e.group_id WHERE ep.id = $1`,
[id]
)
: await pool.query(
`SELECT gp.group_id, g.name AS group_name, g.branch_id
FROM group_photos gp LEFT JOIN groups g ON g.id = gp.group_id WHERE gp.id = $1`,
[id]
);
if (!rows.length) return null;
const ctx = rows[0];
const fill = s => String(s === null || s === undefined ? '' : s)
.replace(/\{student\}/g, ctx.student_name || '')
.replace(/\{group\}/g, ctx.group_name || '—');
return pushNotification({
type,
level,
title: fill(title),
body: fill(body),
link: link || (kind === 'entry' ? 'journal.html' : 'groups.html'),
target: Object.assign({
face_source_type: kind,
face_source_id: id,
entry_id: ctx.entry_id || null,
group_id: ctx.group_id || null,
group_name: ctx.group_name || null,
}, target || {}),
branchId: ctx.branch_id || null,
});
}
async function onFaceScanDone({ row, status, faces, matched, names, error }) {
try {
cache.publish(EVENTS_CHANNEL, {
type: 'face_scan_status',
source_type: row.source_type,
source_id: row.source_id,
status,
faces,
matched,
names,
error: error || null,
}).catch(err => console.error('Publish failed:', err.message));
if (status === 'error') {
await notifyFaceScan(row.source_type, row.source_id, {
type: 'face.scan.error',
title: 'Не удалось проверить лица: {group}',
body: `${row.source_type === 'entry' ? '{student}' : 'Фото группы'} · ${String(error || '').slice(0, 200)}`,
target: { error: String(error || '').slice(0, 300) },
});
return;
}
if (!faces) return;
const where = row.source_type === 'entry' ? '{student} · группа {group}' : 'фото группы {group}';
if (names) {
await notifyFaceScan(row.source_type, row.source_id, {
type: 'face.recognized',
title: `Распознаны: ${names}`,
body: `${where} · найдено лиц: ${faces}, привязано: ${matched}`,
});
}
await notifyFaceScan(row.source_type, row.source_id, {
type: 'face.scan.done',
title: `Найдено лиц на фото: ${faces}`,
body: `${where}${matched ? ` · распознано: ${matched}` : ''}${names ? ` (${names})` : ''}`,
});
} catch (e) {
console.error('Face scan onDone error:', e.message);
}
}
function rematchFacesBackground() {
setImmediate(async () => {
try {
if ((await getSetting('face_id_enabled', 'false')) !== 'true') return;
await rematchFaces();
const out = await rematchFaces();
if (out && !out.error && out.matched) {
await pushNotification({
type: 'face.recognized',
title: `Пересчёт лиц: привязано ${out.matched}`,
body: `Просмотрено лиц без привязки: ${out.scanned}, порог ${out.threshold}`,
link: 'settings.html',
target: { scanned: out.scanned, matched: out.matched, threshold: out.threshold },
});
}
} catch (e) {
console.error('Face background rematch failed:', e.message);
}
@@ -4765,6 +4970,11 @@ let photoWorker = null;
let lessonAiChecker = null;
let feedbackWorker = null;
let noteAiWorker = null;
let faceScanWorker = null;
function wakeFaceScanWorker() {
if (faceScanWorker) faceScanWorker.notify();
}
function wakeLessonAiWorker() {
if (lessonAiChecker) lessonAiChecker.notify();
@@ -6222,7 +6432,7 @@ app.post('/api/groups/:id/photos', requireAuth, (req, res, next) => {
invalidateGroups();
invalidateStats();
res.status(201).json(rows[0]);
scanFacesBackground('group', rows[0].id, rows[0].photo_path);
enqueueFaceScanBackground('group', rows[0].id, rows[0].photo_path, req.user.id);
} catch (e) {
safeUnlink(`uploads/${req.file.filename}`);
console.error('POST /api/groups/:id/photos:', e);
@@ -6453,6 +6663,7 @@ app.post('/api/groups/:id/photos/:photoId/jobs/:jobId/apply', requireAuth, async
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');
if (faceMode === 'rescan') enqueueFaceScanBackground('group', photoId, job.after_path, req.user.id);
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();
@@ -6628,6 +6839,7 @@ app.post('/api/groups/:id/photos/:photoId/jobs/:jobId/rollback', requireAuth, as
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);
if (faceMode === 'rescan') enqueueFaceScanBackground('group', photoId, newPath, req.user.id);
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]
@@ -8709,10 +8921,9 @@ app.post('/api/photos/:sourceType/:sourceId/faces/rescan', requireAuth, async (r
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 });
await enqueueFaceScan(sourceType, sourceId, photoPath, req.user.id);
await logAudit(req, 'photo.faces.rescan', { source_type: sourceType, source_id: sourceId });
res.json({ ok: true, queued: 1, scanned: 0 });
});
app.post('/api/faces/rematch', requireAuth, requireAdmin, async (req, res) => {
@@ -8722,6 +8933,203 @@ app.post('/api/faces/rematch', requireAuth, requireAdmin, async (req, res) => {
res.json(out);
});
app.get('/api/faces/queue', requireAuth, requireAdmin, async (req, res) => {
const { rows: counts } = await pool.query(
`SELECT status, count(*)::int AS n FROM face_scan_jobs GROUP BY status`
);
const totals = { pending: 0, processing: 0, done: 0, error: 0 };
for (const c of counts) totals[c.status] = c.n;
const { rows: recent } = await pool.query(
`SELECT id, source_type, source_id, status, attempts, faces_found, faces_matched, matched_names, error, updated_at
FROM face_scan_jobs ORDER BY id DESC LIMIT 15`
);
res.json({
totals,
busy: totals.pending > 0 || totals.processing > 0,
worker: faceScanWorker ? faceScanWorker.getInfo() : null,
recent,
});
});
app.post('/api/faces/queue/retry', requireAuth, requireAdmin, async (req, res) => {
const { rowCount } = await pool.query(
`UPDATE face_scan_jobs SET status = 'pending', attempts = 0, error = NULL, updated_at = now()
WHERE status = 'error' AND photo_path <> ''`
);
await logAudit(req, 'faces.queue.retry', { requeued: rowCount });
wakeFaceScanWorker();
res.json({ ok: true, requeued: rowCount });
});
app.post('/api/faces/queue/wake', requireAuth, requireAdmin, async (req, res) => {
wakeFaceScanWorker();
await logAudit(req, 'faces.queue.wake', {});
res.json({ ok: true });
});
app.post('/api/faces/queue/clear', requireAuth, requireAdmin, async (req, res) => {
const days = Math.min(365, Math.max(0, safeId(req.body.days) || 0));
const { rowCount } = await pool.query(
`DELETE FROM face_scan_jobs
WHERE status IN ('done', 'error')
AND ($1 = 0 OR updated_at < now() - ($1 || ' days')::interval)`,
[String(days)]
);
await logAudit(req, 'faces.queue.clear', { deleted: rowCount, days });
res.json({ ok: true, deleted: rowCount });
});
app.get('/api/faces/monitor', requireAuth, requireAdmin, async (req, res) => {
const recentLimit = Math.min(200, Math.max(1, safeId(req.query.recent_limit) || 15));
const recentOffset = Math.max(0, safeId(req.query.recent_offset) || 0);
const statusFilter = typeof req.query.status === 'string' && FACE_JOB_STATUSES.has(req.query.status.trim()) ? req.query.status.trim() : '';
const enabled = (await getSetting('face_id_enabled', 'false')) === 'true';
const scanOnUpload = (await getSetting('face_scan_on_upload', 'true')) !== 'false';
const threshold = faceThreshold(await getSetting('face_id_threshold', '0.6'));
const service = await faceIdHealth(2500);
const { rows: counts } = await pool.query(`SELECT status, count(*)::int AS n FROM face_scan_jobs GROUP BY status`);
const totals = { pending: 0, processing: 0, done: 0, error: 0 };
for (const c of counts) if (Object.prototype.hasOwnProperty.call(totals, c.status)) totals[c.status] = c.n;
const params = [];
const where = statusFilter ? `WHERE j.status = $${params.push(statusFilter)}` : '';
params.push(recentLimit, recentOffset);
const { rows: recent } = await pool.query(
`SELECT j.id, j.source_type, j.source_id, j.status, j.attempts, j.faces_found, j.faces_matched,
j.matched_names, j.error, j.photo_path, j.created_at, j.updated_at,
COALESCE(gp.group_id, e.group_id) AS group_id, g.name AS group_name, g.branch_id,
e.student_name
FROM face_scan_jobs j
LEFT JOIN group_photos gp ON gp.id = j.source_id AND j.source_type = 'group'
LEFT JOIN entry_photos ep ON ep.id = j.source_id AND j.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}
ORDER BY j.id DESC LIMIT $${params.length - 1} OFFSET $${params.length}`,
params
);
const { rows: totalRows } = await pool.query(
`SELECT count(*)::int AS n FROM face_scan_jobs j ${where}`,
statusFilter ? [statusFilter] : []
);
const { rows: pending } = await pool.query(
`SELECT j.id, j.source_type, j.source_id, j.attempts, j.created_at,
COALESCE(gp.group_id, e.group_id) AS group_id, g.name AS group_name, e.student_name
FROM face_scan_jobs j
LEFT JOIN group_photos gp ON gp.id = j.source_id AND j.source_type = 'group'
LEFT JOIN entry_photos ep ON ep.id = j.source_id AND j.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 j.status IN ('pending', 'processing')
ORDER BY j.id ASC LIMIT 25`
);
const { rows: library } = await pool.query(
`SELECT
(SELECT count(*) FROM group_photos) + (SELECT count(*) FROM entry_photos) AS photos_total,
(SELECT count(*) FROM group_photos WHERE face_scanned_at IS NOT NULL)
+ (SELECT count(*) FROM entry_photos WHERE face_scanned_at IS NOT NULL) AS photos_scanned,
(SELECT count(*) FROM group_photos WHERE photo_path <> '' AND face_scanned_at IS NULL)
+ (SELECT count(*) FROM entry_photos WHERE photo_path <> '' AND face_scanned_at IS NULL) AS photos_unscanned,
(SELECT count(*) FROM photo_faces) AS faces_total,
(SELECT count(*) FROM photo_faces WHERE student_id IS NOT NULL) AS faces_matched,
(SELECT count(*) FROM photo_faces WHERE student_id IS NOT NULL AND confidence >= 1) AS faces_manual,
(SELECT count(*) FROM photo_faces WHERE student_id IS NULL) AS faces_unassigned,
(SELECT count(*) FROM photo_faces WHERE student_id IS NULL AND best_student_id IS NOT NULL) AS faces_candidates,
(SELECT count(*) FROM student_face_refs) AS refs_total,
(SELECT count(DISTINCT student_id) FROM student_face_refs) AS ref_students`
);
const lib = library[0] || {};
const { rows: groups } = await pool.query(
`SELECT g.id, g.name,
(SELECT count(*) FROM group_photos gp WHERE gp.group_id = g.id)
+ (SELECT count(*) FROM entry_photos ep JOIN entries e2 ON e2.id = ep.entry_id WHERE e2.group_id = g.id) AS photos,
(SELECT count(*) FROM group_photos gp WHERE gp.group_id = g.id AND gp.photo_path <> '' AND gp.face_scanned_at IS NULL)
+ (SELECT count(*) FROM entry_photos ep JOIN entries e2 ON e2.id = ep.entry_id
WHERE e2.group_id = g.id AND ep.photo_path <> '' AND ep.face_scanned_at IS NULL) AS unscanned,
(SELECT count(*) FROM photo_faces pf
JOIN group_photos gp2 ON gp2.id = pf.source_id AND pf.source_type = 'group'
WHERE gp2.group_id = g.id) AS faces,
(SELECT count(*) FROM photo_faces pf
JOIN group_photos gp2 ON gp2.id = pf.source_id AND pf.source_type = 'group'
WHERE gp2.group_id = g.id AND pf.student_id IS NOT NULL) AS faces_matched
FROM groups g
WHERE g.deleted_at IS NULL
AND (
EXISTS (SELECT 1 FROM group_photos gp3 WHERE gp3.group_id = g.id)
OR EXISTS (SELECT 1 FROM entry_photos ep3 JOIN entries e3 ON e3.id = ep3.entry_id WHERE e3.group_id = g.id)
)
ORDER BY faces DESC, g.name ASC
LIMIT 50`
);
const { rows: errors } = await pool.query(
`SELECT j.id, j.source_type, j.source_id, j.attempts, j.error, j.photo_path, j.updated_at,
g.name AS group_name, e.student_name
FROM face_scan_jobs j
LEFT JOIN group_photos gp ON gp.id = j.source_id AND j.source_type = 'group'
LEFT JOIN entry_photos ep ON ep.id = j.source_id AND j.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 j.status = 'error'
ORDER BY j.id DESC LIMIT 25`
);
const { rows: refStudents } = await pool.query(
`SELECT s.id, s.name, count(r.id)::int AS refs,
(SELECT count(*) FROM photo_faces pf WHERE pf.student_id = s.id) AS found,
(SELECT count(*) FROM photo_faces pf WHERE pf.best_student_id = s.id AND pf.student_id IS NULL AND pf.best_score >= $1) AS similar
FROM student_face_refs r
JOIN students s ON s.id = r.student_id AND s.deleted_at IS NULL
GROUP BY s.id, s.name
ORDER BY refs DESC, s.name ASC
LIMIT 50`,
[String(FACE_CANDIDATE_MIN)]
);
const { rows: actions } = await pool.query(
`SELECT a.id, a.action, a.target, a.created_at, a.user_id, u.username AS user_name
FROM audit_log a LEFT JOIN users u ON u.id = a.user_id
WHERE a.action = ANY($1::text[])
ORDER BY a.id DESC LIMIT 40`,
[FACE_ACTIONS.slice()]
);
res.json({
enabled,
scan_on_upload: scanOnUpload,
threshold,
candidate_min: FACE_CANDIDATE_MIN,
service,
totals,
busy: totals.pending > 0 || totals.processing > 0,
worker: faceScanWorker ? faceScanWorker.getInfo() : null,
pending,
recent,
recent_total: totalRows.length ? totalRows[0].n : 0,
errors,
library: {
photos_total: Number(lib.photos_total) || 0,
photos_scanned: Number(lib.photos_scanned) || 0,
photos_unscanned: Number(lib.photos_unscanned) || 0,
faces_total: Number(lib.faces_total) || 0,
faces_matched: Number(lib.faces_matched) || 0,
faces_manual: Number(lib.faces_manual) || 0,
faces_unassigned: Number(lib.faces_unassigned) || 0,
faces_candidates: Number(lib.faces_candidates) || 0,
refs_total: Number(lib.refs_total) || 0,
ref_students: Number(lib.ref_students) || 0,
},
groups,
ref_students: refStudents,
actions,
});
});
app.put('/api/photo-faces/:faceId/assign', requireAuth, async (req, res) => {
let faceId;
try {
@@ -8823,20 +9231,10 @@ app.post('/api/faces/scan-unscanned', requireAuth, requireAdmin, async (req, res
const limit = Math.min(500, Math.max(1, safeId(req.body.limit) || 50));
const g = await pool.query('SELECT id, photo_path FROM group_photos WHERE face_scanned_at IS NULL ORDER BY id LIMIT $1', [limit]);
const e = await pool.query('SELECT id, photo_path FROM entry_photos WHERE face_scanned_at IS NULL ORDER BY id LIMIT $1', [limit]);
let scanned = 0;
let failed = 0;
for (const p of g.rows) {
const n = await scanFacesForPhoto('group', p.id, p.photo_path);
if (n === null) failed++;
else scanned++;
}
for (const p of e.rows) {
const n = await scanFacesForPhoto('entry', p.id, p.photo_path);
if (n === null) failed++;
else scanned++;
}
await logAudit(req, 'faces.scan_unscanned', { scanned, failed, total: g.rows.length + e.rows.length });
res.json({ scanned, failed, total: g.rows.length + e.rows.length });
const queued = (await enqueueFaceScans(g.rows, 'group', req.user.id)) + (await enqueueFaceScans(e.rows, 'entry', req.user.id));
const total = g.rows.length + e.rows.length;
await logAudit(req, 'faces.scan_unscanned', { queued, skipped: total - queued, total });
res.json({ queued, skipped: total - queued, total });
});
app.post('/api/entries/:id/photos/scan-faces', requireAuth, async (req, res) => {
@@ -8859,15 +9257,9 @@ app.post('/api/entries/:id/photos/scan-faces', requireAuth, async (req, res) =>
: 'SELECT id, photo_path FROM entry_photos WHERE entry_id = $1 AND face_scanned_at IS NULL ORDER BY id',
[eid]
);
let scanned = 0;
let failed = 0;
for (const p of rows) {
const n = await scanFacesForPhoto('entry', p.id, p.photo_path);
if (n === null) failed++;
else scanned++;
}
await logAudit(req, 'entry.photos.scan_faces', { entry_id: eid, scanned, failed, rescans });
res.json({ scanned, failed, total: rows.length });
const queued = await enqueueFaceScans(rows, 'entry', req.user.id);
await logAudit(req, 'entry.photos.scan_faces', { entry_id: eid, queued, skipped: rows.length - queued, rescans });
res.json({ queued, skipped: rows.length - queued, total: rows.length });
});
app.post('/api/groups/:id/photos/scan-faces', requireAuth, async (req, res) => {
@@ -8888,15 +9280,9 @@ app.post('/api/groups/:id/photos/scan-faces', requireAuth, async (req, res) => {
: 'SELECT id, photo_path FROM group_photos WHERE group_id = $1 AND face_scanned_at IS NULL ORDER BY id',
[gid]
);
let scanned = 0;
let failed = 0;
for (const p of rows) {
const n = await scanFacesForPhoto('group', p.id, p.photo_path);
if (n === null) failed++;
else scanned++;
}
await logAudit(req, 'group.photos.scan_faces', { group_id: gid, scanned, failed, rescans });
res.json({ scanned, failed, total: rows.length });
const queued = await enqueueFaceScans(rows, 'group', req.user.id);
await logAudit(req, 'group.photos.scan_faces', { group_id: gid, queued, skipped: rows.length - queued, rescans });
res.json({ queued, skipped: rows.length - queued, total: rows.length });
});
@@ -9315,6 +9701,7 @@ app.post('/api/entries', entryLimiter, (req, res, next) => {
await convertPhoto(p);
}
const client = await pool.connect();
let committed = false;
try {
await client.query('BEGIN');
await client.query(
@@ -9342,24 +9729,33 @@ app.post('/api/entries', entryLimiter, (req, res, next) => {
);
}
await client.query('COMMIT');
committed = true;
if (entryAutoChecker) entryAutoChecker.notify();
invalidateEntries();
invalidateStats();
broadcastEntryChanged();
res.status(201).json({ ...rows[0], files: projectFiles.length, photos: photos.length });
for (let i = 0; i < photos.length; i++) {
const { rows: ep } = await pool.query(
'SELECT id FROM entry_photos WHERE entry_id = $1 AND photo_path = $2 ORDER BY sort_order LIMIT 1',
[rows[0].id, `/uploads/${photos[i].filename}`]
);
if (ep.length) scanFacesBackground('entry', ep[0].id, `/uploads/${photos[i].filename}`);
}
setImmediate(async () => {
try {
for (let i = 0; i < photos.length; i++) {
const { rows: ep } = await pool.query(
'SELECT id FROM entry_photos WHERE entry_id = $1 AND photo_path = $2 ORDER BY sort_order LIMIT 1',
[rows[0].id, `/uploads/${photos[i].filename}`]
);
if (ep.length) enqueueFaceScanBackground('entry', ep[0].id, `/uploads/${photos[i].filename}`);
}
} catch (err) {
console.error('Entry face scan enqueue failed:', err);
}
});
} catch (e) {
await client.query('ROLLBACK').catch(() => {});
photos.forEach(removeUpload);
projectFiles.forEach(removeUpload);
if (!committed) {
await client.query('ROLLBACK').catch(() => {});
photos.forEach(removeUpload);
projectFiles.forEach(removeUpload);
if (!res.headersSent) res.status(500).json({ error: e.message });
}
console.error('POST /api/entries:', e);
res.status(500).json({ error: e.message });
} finally {
client.release();
}
@@ -9837,6 +10233,7 @@ app.post('/api/entries/:id/photo/jobs/:jobId/apply', requireAuth, async (req, re
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');
if (faceMode === 'rescan') for (const ep of epRows) enqueueFaceScanBackground('entry', ep.id, job.after_path, req.user.id);
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 });
@@ -9946,6 +10343,7 @@ app.post('/api/entries/:id/photo/jobs/:jobId/rollback', requireAuth, async (req,
let faceMode = 'skip';
for (const ep of epRows) {
faceMode = await rescalePhotoFaces(null, 'entry', ep.id, newPath, faceDims.w, faceDims.h);
if (faceMode === 'rescan') enqueueFaceScanBackground('entry', ep.id, newPath, req.user.id);
}
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())',
@@ -11392,4 +11790,14 @@ try { await ensureFeedbacksTable(); } catch (err) { console.error('Feedbacks tab
});
noteAiWorker.start();
console.log('Note title AI worker started');
faceScanWorker = createFaceScanWorker({
pool,
getSetting,
logAudit,
scan: runFaceScanJob,
bus: createWorkerBus(FACE_SCAN_WAKE_CHANNEL),
onDone: onFaceScanDone,
});
faceScanWorker.start();
console.log('Face scan worker started');
})();