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:
+32
-6
@@ -264,7 +264,7 @@ async function rescanFaceViewerPhoto() {
|
||||
if (!photoId || faceViewer.rescanBusy) return;
|
||||
faceViewer.rescanBusy = true;
|
||||
const btn = document.getElementById('faceViewerRescanBtn');
|
||||
if (btn) { btn.disabled = true; btn.textContent = 'Сканируем...'; }
|
||||
if (btn) { btn.disabled = true; btn.textContent = 'В очередь...'; }
|
||||
try {
|
||||
const res = await fetch(`${API}/api/photos/group/${photoId}/faces/rescan`, {
|
||||
method: 'POST',
|
||||
@@ -272,9 +272,8 @@ async function rescanFaceViewerPhoto() {
|
||||
body: JSON.stringify({}),
|
||||
});
|
||||
const data = await res.json().catch(() => ({}));
|
||||
if (!res.ok) throw new Error(data.error || 'Не удалось распознать лица');
|
||||
showToast(`Распознано лиц: ${data.scanned || 0}`);
|
||||
await refreshOpenFaceViewer();
|
||||
if (!res.ok) throw new Error(data.error || 'Не удалось поставить фото в очередь');
|
||||
showToast('Фото поставлено в очередь проверки — рамки обновятся автоматически');
|
||||
loadGroupPhotos();
|
||||
} catch (e) {
|
||||
alert(e.message);
|
||||
@@ -284,6 +283,32 @@ async function rescanFaceViewerPhoto() {
|
||||
}
|
||||
}
|
||||
|
||||
let faceScanLiveSource = null;
|
||||
|
||||
function connectFaceScanLive() {
|
||||
if (faceScanLiveSource) { faceScanLiveSource.close(); faceScanLiveSource = null; }
|
||||
const connect = () => {
|
||||
const t = sessionStorage.getItem('authToken');
|
||||
if (!t) return;
|
||||
faceScanLiveSource = new EventSource(`${API}/api/events?token=${encodeURIComponent(t)}`);
|
||||
faceScanLiveSource.addEventListener('face_scan_status', ev => {
|
||||
let p = null;
|
||||
try { p = JSON.parse(ev.data); } catch { return; }
|
||||
if (!p || p.status === 'processing' || p.status === 'pending') return;
|
||||
if (Number(p.source_id) === Number(faceViewer.photoId) && faceViewer.photoId) {
|
||||
refreshOpenFaceViewer();
|
||||
loadGroupPhotos();
|
||||
}
|
||||
});
|
||||
faceScanLiveSource.onerror = () => {
|
||||
if (faceScanLiveSource) { faceScanLiveSource.close(); faceScanLiveSource = null; }
|
||||
setTimeout(connect, 5000);
|
||||
};
|
||||
};
|
||||
connect();
|
||||
window.addEventListener('beforeunload', () => { if (faceScanLiveSource) faceScanLiveSource.close(); });
|
||||
}
|
||||
|
||||
async function openFaceViewer(photoId) {
|
||||
const photo = photos.find(x => x.id === photoId);
|
||||
if (!photo) return;
|
||||
@@ -420,7 +445,7 @@ async function scanGroupFaces() {
|
||||
const btn = document.getElementById('scanFacesBtn');
|
||||
btn.disabled = true;
|
||||
const label = btn.textContent;
|
||||
btn.textContent = 'Сканируем...';
|
||||
btn.textContent = 'В очередь...';
|
||||
try {
|
||||
const res = await fetch(`${API}/api/groups/${currentGroupId}/photos/scan-faces`, {
|
||||
method: 'POST',
|
||||
@@ -432,7 +457,7 @@ async function scanGroupFaces() {
|
||||
showToast((data && data.error) || 'Не удалось запустить сканирование');
|
||||
return;
|
||||
}
|
||||
showToast(`Обработано: ${data.scanned}${data.failed ? `, ошибок: ${data.failed}` : ''}`);
|
||||
showToast(`В очередь добавлено фото: ${data.queued}${data.skipped ? `, уже в очереди: ${data.skipped}` : ''}`);
|
||||
loadGroupPhotos();
|
||||
} catch {
|
||||
showToast('Не удалось запустить сканирование');
|
||||
@@ -843,6 +868,7 @@ async function populateNewGroupBranch() {
|
||||
buildSidebar(document.body.dataset.page);
|
||||
await populateNewGroupBranch();
|
||||
loadGroups();
|
||||
connectFaceScanLive();
|
||||
}
|
||||
})();
|
||||
let enhancePhotoId = null;
|
||||
|
||||
Reference in New Issue
Block a user