From 8137fd35d5904cec83cd128e83427be5b10aab69 Mon Sep 17 00:00:00 2001 From: dev Date: Sun, 11 Oct 2026 00:37:50 +0300 Subject: [PATCH] =?UTF-8?q?faces:=20=D0=BE=D1=87=D0=B5=D1=80=D0=B5=D0=B4?= =?UTF-8?q?=D1=8C=20=D0=BF=D1=80=D0=BE=D0=B2=D0=B5=D1=80=D0=BA=D0=B8=20?= =?UTF-8?q?=D0=BB=D0=B8=D1=86=20=D0=B8=20=D1=81=D1=82=D1=80=D0=B0=D0=BD?= =?UTF-8?q?=D0=B8=D1=86=D0=B0=20=C2=AB=D0=A1=D0=BA=D0=B0=D0=BD=D0=B5=D1=80?= =?UTF-8?q?=20=D0=BB=D0=B8=D1=86=C2=BB?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Вынести распознавание лиц с загрузки в фоновую очередь: - таблица 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 --- AGENTS.md | 19 +- db/init.sql | 21 ++ db/migration.sql | 33 +++ public/admin.js | 5 + public/faces.html | 190 +++++++++++++++ public/js/faces.js | 464 ++++++++++++++++++++++++++++++++++++ public/js/groups.js | 38 ++- public/js/journal.js | 6 +- public/js/settings.js | 50 ++++ public/settings.html | 9 + server.js | 530 +++++++++++++++++++++++++++++++++++++----- worker.js | 187 ++++++++++++++- 12 files changed, 1480 insertions(+), 72 deletions(-) create mode 100644 public/faces.html create mode 100644 public/js/faces.js diff --git a/AGENTS.md b/AGENTS.md index 49cfad4..b94fca9 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -237,8 +237,25 @@ This document defines how AI agents should work with the WhatIDo codebase. Follo - **`bbox` живёт в пикселях того файла, который сканировали**: `photo_faces.bbox` — абсолютные координаты исходника, а фронт делит их на `naturalWidth/naturalHeight` **текущего** ``. Смена файла без пересчёта = рамки в чужом масштабе. Поэтому рядом с `face_scanned_at` лежат `face_img_width`/`face_img_height` в `group_photos` и `entry_photos` — размеры картинки, к которой относятся сохранённые рамки. Их пишет `scanFacesForPhoto` из ответа `/detect` (для этого `faceIdDetect` возвращает `{ faces, width, height }`, а не просто массив), а новая колонка объявляется в `db/init.sql`, `db/migration.sql`, `ensureFaceTables()`, `normalizeRestoreData` и restore-INSERT - **Любая подмена файла обязана звать `rescalePhotoFaces(client, sourceType, sourceId, newPath, w, h)`**: размеры нового файла берёт `imagePixelSize()` (`storage.localize` + `sharp().metadata()`), старые — из `face_img_*`. Масштаб известен → рамки умножаются на `new/old` и вместе с ними обновляется `photo_faces.photo_path` (без него фильтр «по лицам» в `/api/photos` перестаёт находить фото после apply). Размеры неизвестны (строка просканирована до появления колонок) → рамки удаляются, `face_scanned_at = NULL`, фото уходит в фоновый скан. Вызывается из **всех** мест, меняющих `photo_path`: apply и rollback для группы и для записи журнала. Забытый вызов — это ровно тот баг со «съехавшими» рамками, который здесь описан - **Ручная переиндексация одного фото** — `POST /api/photos/:sourceType/:sourceId/faces/rescan` (`source_id` = id `group_photos`/`entry_photos`, не записи), кнопка `#faceViewerRescanBtn` в `#faceViewerModal`. `GET /api/photos/:sourceType/:sourceId/faces` отдаёт `img_width`/`img_height`/`scanned`; `checkFaceViewerSync()` в `public/js/groups.js` сравнивает их с `img.naturalWidth` после загрузки картинки и показывает `#faceViewerWarn`, если фото подменили. После apply/rollback/сохранения улучшения вьюер перерисовывается через `refreshOpenFaceViewer()` — иначе рамки остались бы от старого файла до ручного переоткрытия -- **Скан при загрузке** — `scanFacesBackground()` через `setImmediate` **после** `res.json(...)`: в группе после `INSERT ... RETURNING`, в записи журнала после `COMMIT` (там фото в транзакции, поэтому id `entry_photos` дотягиваются отдельным SELECT). Роут не блокируется +- **Скан при загрузке ставится в очередь, а не выполняется сразу**: `enqueueFaceScanBackground()` через `setImmediate` **после** `res.json(...)`: в группе после `INSERT ... RETURNING`, в записи журнала после `COMMIT` (там фото в транзакции, поэтому id `entry_photos` дотягиваются отдельным SELECT). Проверяет `face_id_enabled` + `face_scan_on_upload` и вызывает `enqueueFaceScan()`. Роут не блокируется - **Эмбеддинги не переиспользуются между фото**: при каждом скане фото refs перечитываются целиком (`loadFaceRefs`) — объём маленький (десятки строк), кэш дал бы риск устаревшей привязки + +#### Очередь проверки лиц (`face_scan_jobs` + воркер) +- **Таблица `face_scan_jobs`**: `source_type` (`group`|`entry`), `source_id` (id фото), `photo_path`, `status` (`pending`|`processing`|`done`|`error`), `attempts`, `faces_found`, `faces_matched`, `matched_names`, `error`, `user_id`. Схема — `db/init.sql`, `db/migration.sql` и `ensureFaceTables()` (`server.js`) +- **В в бэкап не входит** (как `sessions`/`api_keys`): очередь — производная от фото, результат лежит в `photo_faces`, после restore она не нужна. В `sweepOrphanedUploads` `photo_path` **не добавлять**: это ссылка на уже существующее фото, владельцем остаётся `group_photos`/`entry_photos` +- **Воркер** — `createFaceScanWorker` в `worker.js` по образцу `createLessonReportChecker`: `pending → processing → done|error`, захват `FOR UPDATE SKIP LOCKED`, backoff `idleMs`, `resetStale()` на старте. Логика распознавания **не** в воркере: она внедрена как `scan: runFaceScanJob` из `server.js` (доступ к `faceIdDetect`, `loadFaceRefs`, `matchFaceToStudent`). `runFaceScanJob` возвращает `{ faces, matched, names }` +- **Ошибки бросаются, а не возвращаются**: `scanFacesForPhoto()` больше не возвращает `null` при сбое — он `throw`ит. Иначе воркер считал бы сломанное фото успешно обработанным. `null` означал «пропустить»; теперь это исключение, и `attempts` растёт до `FACE_MAX_ATTEMPTS` (3, env `FACE_SCAN_MAX_ATTEMPTS`) +- **Дедупликация**: частичный уникальный индекс `idx_face_scan_jobs_active` на `(source_type, source_id) WHERE status IN ('pending','processing')` + `ON CONFLICT ... DO UPDATE SET photo_path`. Повторная постановка того же фото не плодит задачи, но освежает путь (фото могло подмениться). `RETURNING (xmax = 0) AS inserted` отличает вставку от обновления — вернуть `queued` можно только для первой +- **`rescalePhotoFaces` в режиме `rescan`** (размеры нового файла неизвестны → рамки удалены, `face_scanned_at = NULL`) обязан вернуть фото в очередь. Вызовы — `enqueueFaceScanBackground()` **после `COMMIT`**, иначе воркер увидит незакоммиченные данные +- **Ручные эндпоинты больше не сканируют синхронно**: `POST /api/faces/scan-unscanned`, `POST /api/{entries,groups}/:id/photos/scan-faces`, `POST /api/photos/:sourceType/:sourceId/faces/rescan` только ставят задачи и отвечают `{ queued, skipped, total }`. Фронт (`public/js/groups.js`) на это и переписан — не ждёт результата +- **Наблюдаемость**: `GET /api/faces/queue` (`requireAuth, requireAdmin`) — `totals` по статусам, `busy`, `getInfo()` воркера и последние 15 задач; `POST /api/faces/queue/retry` возвращает `error`-задачи в `pending`. UI — блок «Фоновая очередь проверки» в `#sec-faces` (`#faceQueueHint`, `#faceQueueRefreshBtn`, `#faceQueueRetryBtn`), опрос раз в 5 с +- **Хвост очереди чистится воркером**: каждые 50 задач `DELETE ... WHERE status IN ('done','error') AND updated_at < now() - FACE_KEEP_DONE_MS` (7 суток, env `FACE_SCAN_KEEP_DONE_MS`) +- **Уведомления** (`NOTIFY_TYPES` в `server.js`, сид `notify_face_*` в обоих SQL, иконки в `NOTIFY_ICONS` в `public/admin.js`), событие — в `onFaceScanDone`: + - `face.scan.done` («Найдено лиц на фото: N») — **по умолчанию выключено**: при загрузке каждого фото оно превратилось бы в поток + - `face.recognized` («Распознаны: <имена>») — по умолчанию включено, и только когда есть хотя бы одно имя; имена берутся из `matched_names`, который копит `scanFacesForPhoto` из `loadFaceRefs` + - `face.scan.error` («Не удалось проверить лица») — по умолчанию включено + - Филиал для видимости — через `notifyFaceScan()`: он сам достаёт `branch_id` по `entry_photos → entries → groups` или `group_photos → groups` (у `notifyGroupPhoto` для фото записи нет, там только `group_photos.id`) +- **SSE `face_scan_status`** — новая ветка в `dispatchEvent` (`server.js`), её обязан слушать `groups.js`: `connectFaceScanLive()` подписан на `/api/events` и при `status = done|error` для открытого фото вызывает `refreshOpenFaceViewer()`. Без этого кнопка «Переиндексировать» возвращала бы «в очередь» и оставляла рамки пустыми навсегда. Воркер в `EVENTS_CHANNEL` писать не может — публикует `onFaceScanDone` в `server.js` - **Пересчёт привязок по всем фото** — `rematchFaces()`: идёт по `photo_faces` **с `student_id IS NULL`**, батчами по 1000 (пагинация по `id > lastId`, не по `LIMIT` — молча терять хвост нельзя), и каждому лицу пересчитывает косинус к эталонам. Детект не повторяется: эмбеддинги уже в БД, `face-id` не нужен. Автозапуск — `rematchFacesBackground()` из `POST`/`DELETE /api/students/:id/face-refs` (через `setImmediate` **после** ответа, под `face_id_enabled = 'true'`) — удаление эталона пересчёт тоже вызывает, иначе кандидаты устареют; ручной запуск — `POST /api/faces/rematch` под `requireAuth, requireAdmin`, кнопка `#faceRematchBtn` в `#sec-faces`. Смысл: фото, просканированные до появления эталона, получили `student_id = NULL` навсегда — без пересчёта они так и остались бы нераспознанными. При ошибке возвращает `error` и эндпоинт отвечает 500 — молчаливый 200 на откатившейся транзакции вводил бы в заблуждение - **`confidence` — это косинусное сходство, а не вероятность**. `matchFaceToStudent` возвращает лучший score **всегда** (и для непривязанных), флаг «ручная привязка» — `confidence >= 1`, его ставит только `PUT /api/photo-faces/:faceId/assign`. Уже привязанные лица пересчёт **не трогает**: ручная привязка имеет приоритет, а ошибочный авто-матч остаётся — чинить его можно только вручную - **Кандидат хранится в БД, а не считается на лету**: `photo_faces.best_student_id` + `best_score` заполняются при скане (`scanFacesForPhoto`) и при пересчёте (`rematchFaces`), у привязанных лиц обнуляются. `GET /api/photos/:sourceType/:sourceId/faces` читает колонки и отдаёт `candidate_min` — фронт берёт порог оттуда. Колонки правятся в `db/init.sql`, `db/migration.sql` (**`ALTER ... ADD COLUMN IF NOT EXISTS` обязательно до `CREATE INDEX` по ним**), `ensureFaceTables()`, `normalizeRestoreData` и restore-INSERT (с проверкой FK). Частичный индекс `idx_photo_faces_best ... WHERE student_id IS NULL` — по нему ищутся «похожие», без него запрос поднимал бы все эмбеддинги diff --git a/db/init.sql b/db/init.sql index cffeee8..db00d4a 100644 --- a/db/init.sql +++ b/db/init.sql @@ -610,6 +610,24 @@ CREATE INDEX IF NOT EXISTS idx_photo_faces_student ON photo_faces(student_id); CREATE INDEX IF NOT EXISTS idx_photo_faces_source_student ON photo_faces(source_type, source_id, student_id); CREATE INDEX IF NOT EXISTS idx_photo_faces_best ON photo_faces(best_student_id) WHERE student_id IS NULL; +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() +); +CREATE INDEX IF NOT EXISTS idx_face_scan_jobs_status ON face_scan_jobs(status, id); +CREATE UNIQUE INDEX IF NOT EXISTS idx_face_scan_jobs_active ON face_scan_jobs(source_type, source_id) WHERE status IN ('pending', 'processing'); + ALTER TABLE group_photos ADD COLUMN IF NOT EXISTS face_scanned_at TIMESTAMPTZ; ALTER TABLE entry_photos ADD COLUMN IF NOT EXISTS face_scanned_at TIMESTAMPTZ; ALTER TABLE group_photos ADD COLUMN IF NOT EXISTS face_img_width INT; @@ -620,3 +638,6 @@ ALTER TABLE entry_photos ADD COLUMN IF NOT EXISTS face_img_height INT; INSERT INTO settings (key, value) VALUES ('face_id_enabled', 'false') ON CONFLICT (key) DO NOTHING; INSERT INTO settings (key, value) VALUES ('face_id_threshold', '0.6') ON CONFLICT (key) DO NOTHING; INSERT INTO settings (key, value) VALUES ('face_scan_on_upload', 'true') ON CONFLICT (key) DO NOTHING; +INSERT INTO settings (key, value) VALUES ('notify_face_scan_done', 'false') ON CONFLICT (key) DO NOTHING; +INSERT INTO settings (key, value) VALUES ('notify_face_recognized', 'true') ON CONFLICT (key) DO NOTHING; +INSERT INTO settings (key, value) VALUES ('notify_face_scan_error', 'true') ON CONFLICT (key) DO NOTHING; diff --git a/db/migration.sql b/db/migration.sql index 33c0608..424d859 100644 --- a/db/migration.sql +++ b/db/migration.sql @@ -769,6 +769,36 @@ CREATE INDEX IF NOT EXISTS idx_photo_faces_student ON photo_faces(student_id); CREATE INDEX IF NOT EXISTS idx_photo_faces_source_student ON photo_faces(source_type, source_id, student_id); CREATE INDEX IF NOT EXISTS idx_photo_faces_best ON photo_faces(best_student_id) WHERE student_id IS NULL; +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() +); +ALTER TABLE face_scan_jobs ADD COLUMN IF NOT EXISTS source_type VARCHAR(20) NOT NULL DEFAULT ''; +ALTER TABLE face_scan_jobs ADD COLUMN IF NOT EXISTS source_id INT NOT NULL DEFAULT 0; +ALTER TABLE face_scan_jobs ADD COLUMN IF NOT EXISTS photo_path VARCHAR(255) NOT NULL DEFAULT ''; +ALTER TABLE face_scan_jobs ADD COLUMN IF NOT EXISTS status VARCHAR(20) NOT NULL DEFAULT 'pending'; +ALTER TABLE face_scan_jobs ADD COLUMN IF NOT EXISTS attempts INT NOT NULL DEFAULT 0; +ALTER TABLE face_scan_jobs ADD COLUMN IF NOT EXISTS faces_found INT NOT NULL DEFAULT 0; +ALTER TABLE face_scan_jobs ADD COLUMN IF NOT EXISTS faces_matched INT NOT NULL DEFAULT 0; +ALTER TABLE face_scan_jobs ADD COLUMN IF NOT EXISTS matched_names TEXT; +ALTER TABLE face_scan_jobs ADD COLUMN IF NOT EXISTS error TEXT; +ALTER TABLE face_scan_jobs ADD COLUMN IF NOT EXISTS user_id INT; + +CREATE INDEX IF NOT EXISTS idx_face_scan_jobs_status ON face_scan_jobs(status, id); +DROP INDEX IF EXISTS idx_face_scan_jobs_active; +CREATE UNIQUE INDEX IF NOT EXISTS idx_face_scan_jobs_active ON face_scan_jobs(source_type, source_id) WHERE status IN ('pending', 'processing'); + ALTER TABLE group_photos ADD COLUMN IF NOT EXISTS face_scanned_at TIMESTAMPTZ; ALTER TABLE entry_photos ADD COLUMN IF NOT EXISTS face_scanned_at TIMESTAMPTZ; ALTER TABLE group_photos ADD COLUMN IF NOT EXISTS face_img_width INT; @@ -779,3 +809,6 @@ ALTER TABLE entry_photos ADD COLUMN IF NOT EXISTS face_img_height INT; INSERT INTO settings (key, value) VALUES ('face_id_enabled', 'false') ON CONFLICT (key) DO NOTHING; INSERT INTO settings (key, value) VALUES ('face_id_threshold', '0.6') ON CONFLICT (key) DO NOTHING; INSERT INTO settings (key, value) VALUES ('face_scan_on_upload', 'true') ON CONFLICT (key) DO NOTHING; +INSERT INTO settings (key, value) VALUES ('notify_face_scan_done', 'false') ON CONFLICT (key) DO NOTHING; +INSERT INTO settings (key, value) VALUES ('notify_face_recognized', 'true') ON CONFLICT (key) DO NOTHING; +INSERT INTO settings (key, value) VALUES ('notify_face_scan_error', 'true') ON CONFLICT (key) DO NOTHING; diff --git a/public/admin.js b/public/admin.js index b4efb8a..12a0dec 100644 --- a/public/admin.js +++ b/public/admin.js @@ -71,6 +71,7 @@ function buildSidebar(active) { { page: 'branches', label: 'Филиалы', icon: 'building-2' }, { page: 'audit', label: 'Аудит', icon: 'scroll-text' }, { page: 'worker', label: 'Воркер ИИ', icon: 'bot' }, + { page: 'faces', label: 'Сканер лиц', icon: 'scan-face' }, { page: 'apikeys', label: 'API-ключи', icon: 'key-round' }, { page: 'bans', label: 'Блокировки', icon: 'shield-off' }, ]; @@ -190,6 +191,10 @@ const NOTIFY_ICONS = { 'system.test': 'send', 'lesson.report': 'notebook-pen', 'lesson.ai.formatted': 'file-check', + 'feedback.ai.ready': 'message-square-heart', + 'face.scan.done': 'scan-face', + 'face.recognized': 'user-round-check', + 'face.scan.error': 'scan-search', }; const NOTIFY_LEVELS = { warning: 'Предупреждение', critical: 'Важно', info: '' }; diff --git a/public/faces.html b/public/faces.html new file mode 100644 index 0000000..67723eb --- /dev/null +++ b/public/faces.html @@ -0,0 +1,190 @@ + + + + + +Сканер лиц — Админ-панель + + + + +
+ +
+
+

Сканер лиц

+

Поиск лиц на фото, сопоставление с эталонами учеников и состояние фоновой очереди

+
+ +
+ Загрузка… + + + + + + + + +
+ +
+
Загрузка…
+
+ +
+ +
+
+
+
+

Библиотека лиц

+
+

Найденные лица хранятся в базе и не зависят от сервиса face-id: пересчёт привязок работает по сохранённым эмбеддингам.

+
+
+ + + +
+
+ + + + + +
ГруппаФотоНайдено лицПривязано
+ +
+
+ +
+
+
+

Очередь (0)

+
+

Фото, ожидающие проверки. Воркер берёт по одному и повторяет ошибки автоматически.

+
+ + + + + +
IDТипФотоУченикГруппаПопытокПоставлено
+ +
+
+ +
+
+
+

Последние проверки

+
+
+ + +
+
+ + + + + +
ОбновленоIDФотоГруппаСтатусЛицПривязаноРаспознано
+ +
+
+
+ +
+
+
+

Эталоны учеников

+
+

Эталонные фото, по которым воркер узнаёт ученика на фотографиях. «Похожие» — ненайденные лица, у которых этот ученик в кандидатах.

+
+ + + + + +
УченикЭталоновНайдено на фотоПохожие
+ +
+
+ + + +
+
+
+

Журнал действий

+
+
+ + +
+
+ + + + + +
ВремяДействиеКтоДетали
+ +
+
+
+
+
+ +
+ + + + + + \ No newline at end of file diff --git a/public/js/faces.js b/public/js/faces.js new file mode 100644 index 0000000..497d4fb --- /dev/null +++ b/public/js/faces.js @@ -0,0 +1,464 @@ +const AUTO_REFRESH_MS = 5000; +const RECENT_PAGE_SIZE = 15; +const FACE_STATUS_LABELS = { + pending: 'В очереди', + processing: 'Проверяется', + done: 'Проверено', + error: 'Ошибка', +}; +const FACE_STATUS_BADGE = { + done: 'ai-badge-done', + error: 'ai-badge-error', + processing: 'ai-badge-skipped', +}; +const ACTION_LABELS = { + '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': 'Проверка фото группы', +}; +const ACTION_GROUPS = { + scan: ['face.scan.retry', 'face.scan.error', 'photo.faces.rescan', 'faces.rematch', 'faces.scan_unscanned', 'entry.photos.scan_faces', 'group.photos.scan_faces'], + refs: ['student.face_ref.create', 'student.face_ref.delete'], + assign: ['photo_face.assign'], + queue: ['faces.queue.retry', 'faces.queue.wake', 'faces.queue.clear'], +}; + +let state = null; +let refreshTimer = null; +let busy = false; +let recentPage = 1; +let recentOffset = 0; +let faceJobRow = null; + +function fmtDur(ms) { + if (ms === null || ms === undefined || ms < 0) return '—'; + const s = Math.floor(ms / 1000); + const d = Math.floor(s / 86400); + const h = Math.floor((s % 86400) / 3600); + const m = Math.floor((s % 3600) / 60); + const sec = s % 60; + if (d) return `${d} д ${h} ч`; + if (h) return `${h} ч ${m} мин`; + if (m) return `${m} мин ${sec} с`; + return `${sec} с`; +} + +function fmtTime(t) { + if (!t) return '—'; + return fmtFull(t) || String(t); +} + +function ago(t) { + if (!t) return '—'; + const diff = Date.now() - new Date(t).getTime(); + if (Number.isNaN(diff)) return '—'; + return fmtDur(diff) + ' назад'; +} + +function statusBadge(s) { + return `${esc(FACE_STATUS_LABELS[s] || s)}`; +} + +function sourceLabel(row) { + const kind = row.source_type === 'entry' ? 'Запись' : 'Группа'; + return `${kind} #${row.source_id}`; +} + +function thumbUrl(p) { + if (!p) return ''; + if (p.startsWith('/api/files/')) return `${API}${p}`; + if (p.startsWith('/uploads/.originals/')) return `${API}${p}`; + return `${API}/uploads/thumb/${p.split('/').pop()}`; +} + +function renderState() { + const w = (state && state.worker) || {}; + const svc = (state && state.service) || {}; + const enabled = state && state.enabled; + const processing = !!w.processing; + const dotClass = !enabled ? '' : (svc.reachable ? (processing ? 'busy' : 'on') : 'err'); + const label = !enabled + ? 'Распознавание лиц выключено' + : (!svc.reachable ? 'Сервис face-id недоступен' : (processing ? `Проверяется фото #${w.current_id ?? ''}` : 'Ожидание очереди')); + document.getElementById('stateLine').innerHTML = ` ${esc(label)}`; + document.getElementById('toggleBtn').textContent = enabled ? 'Выключить распознавание' : 'Включить распознавание'; +} + +function renderCards() { + const w = state.worker || {}; + const svc = state.service || {}; + const cfg = w.config || {}; + const lib = state.library || {}; + const scannedPct = lib.photos_total ? Math.round(((lib.photos_scanned || 0) / lib.photos_total) * 100) : 0; + const matchedPct = lib.faces_total ? Math.round(((lib.faces_matched || 0) / lib.faces_total) * 100) : 0; + document.getElementById('workerCards').innerHTML = ` +
+
Состояние воркера
+
Режим${w.processing ? 'Проверка' : 'Ожидание'}
+
Текущее задание${w.current_id ? '#' + w.current_id : '—'}
+
Работает${fmtDur(w.uptime_ms)}
+
Запущен${fmtTime(w.started_at)}
+
+
+
Сервис face-id
+
Сервис${svc.reachable ? ' доступен' : (svc.configured ? ' недоступен' : ' не настроен')}
+
Модель${svc.ready ? 'загружена' : 'загружается'}
+
Отклик${svc.latency_ms !== undefined ? svc.latency_ms + ' мс' : '—'}
+
Порог${state.threshold} (кандидат от ${state.candidate_min})
+ ${svc.error ? `
${esc(svc.error)}
` : ''} +
+
+
Итоги работы
+
Фото проверено${w.scanned || 0}
+
Найдено лиц${w.faces || 0}
+
Привязано${w.matched || 0}
+
Ошибок${w.errors || 0}
+
Повторов${w.retries || 0}
+
Активность${ago(w.last_at)}
+ ${w.last_error ? `
${esc(w.last_error)}
` : ''} +
+
+
Покрытие
+
Фото с лицами${lib.photos_scanned || 0} из ${lib.photos_total || 0} (${scannedPct}%)
+
Лиц в базе${lib.faces_total || 0}
+
Привязано к ученикам${lib.faces_matched || 0} (${matchedPct}%)
+
Вручную${lib.faces_manual || 0}
+
Эталонов${lib.refs_total || 0} (${lib.ref_students || 0} уч.)
+
+
+
Параметры (мин. нагрузка)
+
Скан при загрузке${state.scan_on_upload ? 'включён' : 'выключен'}
+
Пауза простоя${fmtDur(cfg.idle_min_ms)} → ${fmtDur(cfg.idle_max_ms)}
+
Повторы при сбое${cfg.max_attempts || 0}
+
Хранение завершённых${fmtDur(cfg.keep_done_ms)}
+
Не обработано фото${lib.photos_unscanned || 0}
+
+ `; +} + +function renderCounts() { + const t = state.totals || {}; + const chips = [ + ['pending', 'В очереди', t.pending || 0], + ['processing', 'Проверяется', t.processing || 0], + ['done', 'Проверено', t.done || 0], + ['error', 'Ошибки', t.error || 0], + ]; + document.getElementById('workerCounts').innerHTML = chips + .map(([cls, label, n]) => `${label}: ${n}`) + .join(''); +} + +function renderLibrary() { + const lib = state.library || {}; + const stats = [ + ['Фото всего', lib.photos_total || 0], + ['Проверено', lib.photos_scanned || 0], + ['Не обработано', lib.photos_unscanned || 0], + ['Найдено лиц', lib.faces_total || 0], + ['Привязано', lib.faces_matched || 0], + ['Не опознано', lib.faces_unassigned || 0], + ['Есть кандидат', lib.faces_candidates || 0], + ['Эталонов', lib.refs_total || 0], + ]; + document.getElementById('libraryStats').innerHTML = stats + .map(([label, n]) => `${label}: ${n}`) + .join(''); + document.getElementById('coverageHint').textContent = lib.photos_unscanned + ? `Осталось проверить фото: ${lib.photos_unscanned}. Кнопка «Сканировать необработанные» поставит их в очередь (до 50 за раз).` + : 'Все фото с изображением уже проверены.'; + renderIcons(); +} + +function renderGroups() { + const rows = state.groups || []; + const tbody = document.querySelector('#groupsTable tbody'); + const empty = document.getElementById('groupsEmpty'); + if (!rows.length) { tbody.innerHTML = ''; empty.style.display = 'block'; return; } + empty.style.display = 'none'; + tbody.innerHTML = rows.map(g => ` + + ${esc(g.name)} + ${g.photos} + ${g.faces} + ${g.faces_matched} + ${g.unscanned || '—'} + Открыть + `).join(''); +} + +function renderPending() { + const rows = state.pending || []; + document.getElementById('pendingCount').textContent = rows.length; + const tbody = document.querySelector('#pendingTable tbody'); + const empty = document.getElementById('pendingEmpty'); + if (!rows.length) { tbody.innerHTML = ''; empty.style.display = 'block'; return; } + empty.style.display = 'none'; + tbody.innerHTML = rows.map(r => ` + + #${r.id} + ${r.source_type === 'entry' ? 'Запись' : 'Группа'} + #${r.source_id} + ${esc(r.student_name || '—')} + ${esc(r.group_name || '')} + ${r.attempts} + ${fmtTime(r.created_at)} + `).join(''); +} + +function renderRecent() { + const rows = state.recent || []; + const total = state.recent_total || 0; + document.getElementById('recentCount').textContent = rows.length ? `${recentOffset + 1}–${recentOffset + rows.length} из ${total}` : ''; + const tbody = document.querySelector('#recentTable tbody'); + const empty = document.getElementById('recentEmpty'); + if (!rows.length) { + tbody.innerHTML = ''; + empty.style.display = 'block'; + renderPager(document.getElementById('recentPager'), 1, 1, () => {}); + return; + } + empty.style.display = 'none'; + tbody.innerHTML = rows.map((r, i) => ` + + ${fmtTime(r.updated_at)} + #${r.id} + ${sourceLabel(r)} + ${esc(r.group_name || '')} + ${statusBadge(r.status)} + ${r.status === 'done' ? r.faces_found : '—'} + ${r.status === 'done' ? r.faces_matched : '—'} + ${esc(r.matched_names || '')} + + `).join(''); + const maxPage = Math.max(1, Math.ceil(total / RECENT_PAGE_SIZE)); + renderPager(document.getElementById('recentPager'), recentPage, maxPage, p => { recentPage = p; load(); }); +} + +function renderErrors() { + const rows = state.errors || []; + const total = (state.totals && state.totals.error) || 0; + document.getElementById('errorsCount').textContent = total; + document.getElementById('errorsCard').style.display = total ? 'flex' : 'none'; + const tbody = document.querySelector('#errorsTable tbody'); + if (!rows.length) { tbody.innerHTML = ''; return; } + tbody.innerHTML = rows.map(r => ` + + ${fmtTime(r.updated_at)} + #${r.id} + ${sourceLabel(r)} + ${esc(r.group_name || '')} + ${r.attempts} + ${esc(r.error || '')} + `).join(''); +} + +function renderRefs() { + const rows = state.ref_students || []; + const tbody = document.querySelector('#refsTable tbody'); + const empty = document.getElementById('refsEmpty'); + if (!rows.length) { tbody.innerHTML = ''; empty.style.display = 'block'; return; } + empty.style.display = 'none'; + tbody.innerHTML = rows.map(r => ` + + ${esc(r.name)} + ${r.refs} + ${r.found} + ${r.similar} + Открыть + `).join(''); +} + +function actionSummary(action, t) { + if (!t || typeof t !== 'object') return ''; + const parts = []; + if (t.student_id) parts.push('ученик #' + t.student_id); + if (t.ref_id) parts.push('эталон #' + t.ref_id); + if (t.face_id) parts.push('лицо #' + t.face_id); + if (t.source_type && t.source_id) parts.push(sourceLabel(t)); + if (t.group_id) parts.push('группа #' + t.group_id); + if (t.entry_id) parts.push('запись #' + t.entry_id); + if (t.requeued !== undefined) parts.push('возвращено ' + t.requeued); + if (t.deleted !== undefined) parts.push('удалено ' + t.deleted); + if (t.queued !== undefined) parts.push('в очереди ' + t.queued + (t.total ? ' из ' + t.total : '')); + if (t.matched !== undefined) parts.push(`привязано ${t.matched}${t.scanned !== undefined ? ' из ' + t.scanned : ''}`); + if (t.attempt !== undefined) parts.push('попытка ' + t.attempt); + if (t.attempts !== undefined && t.attempt === undefined) parts.push('попыток ' + t.attempts); + if (t.source) parts.push('источник: ' + t.source); + if (t.was) parts.push('был #' + t.was); + if (t.student_id !== undefined && t.student_id === null && t.face_id) parts.push('привязка снята'); + if (t.error) parts.push(String(t.error).slice(0, 120)); + return parts.join(' · '); +} + +function renderActions() { + const filter = document.getElementById('actionFilter').value; + const allowed = filter ? (ACTION_GROUPS[filter] || []) : null; + const all = state.actions || []; + const rows = allowed ? all.filter(a => allowed.includes(a.action)) : all; + document.getElementById('actionCount').textContent = rows.length ? `${rows.length} записей` : ''; + const tbody = document.querySelector('#actionsTable tbody'); + const empty = document.getElementById('actionsEmpty'); + if (!rows.length) { tbody.innerHTML = ''; empty.style.display = 'block'; return; } + empty.style.display = 'none'; + tbody.innerHTML = rows.map(a => ` + + ${fmtTime(a.created_at)} + ${esc(ACTION_LABELS[a.action] || a.action)} + ${esc(a.user_name || 'воркер')} + ${esc(actionSummary(a.action, a.target))} + `).join(''); +} + +function render() { + renderState(); + renderCards(); + renderCounts(); + renderLibrary(); + renderGroups(); + renderPending(); + renderRecent(); + renderErrors(); + renderRefs(); + renderActions(); + renderIcons(); +} + +async function load() { + if (busy) return; + busy = true; + const filter = document.getElementById('recentFilter').value; + try { + const res = await fetch(`${API}/api/faces/monitor?recent_limit=${RECENT_PAGE_SIZE}&recent_offset=${recentOffset}${filter ? `&status=${encodeURIComponent(filter)}` : ''}`, { headers: hdr() }); + if (!res.ok) return; + state = await res.json(); + render(); + } catch { + } finally { + busy = false; + } +} + +async function post(path, body) { + const opts = { method: 'POST', headers: body ? hdrJson() : hdr() }; + if (body) opts.body = JSON.stringify(body); + const res = await fetch(`${API}${path}`, opts); + const data = await res.json().catch(() => ({})); + if (!res.ok) { showToast(data.error || 'Ошибка'); return null; } + return data; +} + +function openFaceJob(row) { + if (!row) return; + faceJobRow = row; + document.getElementById('faceJobTitle').textContent = `Задание #${row.id} — ${sourceLabel(row)}`; + const img = document.getElementById('faceJobImage'); + img.src = row.photo_path ? `${API}/api/files/${encodeURIComponent(row.photo_path.split('/').pop())}` : ''; + img.style.display = row.photo_path ? 'block' : 'none'; + document.getElementById('faceJobMeta').innerHTML = [ + ['Статус', FACE_STATUS_LABELS[row.status] || row.status], + ['Группа', row.group_name || '—'], + ['Ученик', row.student_name || '—'], + ['Попыток', row.attempts], + ['Найдено лиц', row.faces_found], + ['Привязано', row.faces_matched], + ['Распознано', row.matched_names || '—'], + ['Поставлено', fmtTime(row.created_at)], + ['Обновлено', fmtTime(row.updated_at)], + ['Ошибка', row.error || '—'], + ].map(([k, v]) => `${esc(k)}: ${esc(v)}`).join(''); + renderIcons(); + document.getElementById('faceJobModal').classList.add('open'); +} + +document.getElementById('refreshBtn').addEventListener('click', load); +document.getElementById('wakeBtn').addEventListener('click', async () => { + if (await post('/api/faces/queue/wake')) { showToast('Воркер разбужен'); load(); } +}); +document.getElementById('scanBtn').addEventListener('click', async () => { + const data = await post('/api/faces/scan-unscanned', { limit: 50 }); + if (data) { + showToast(data.queued ? `В очередь добавлено фото: ${data.queued}` : 'Новых фото для проверки нет'); + load(); + } +}); +document.getElementById('requeueBtn').addEventListener('click', async () => { + if (!confirm('Вернуть все задания с ошибкой в очередь на повторную проверку?')) return; + const data = await post('/api/faces/queue/retry'); + if (data) { showToast(`В очередь возвращено: ${data.requeued}`); load(); } +}); +document.getElementById('rematchBtn').addEventListener('click', async () => { + if (!confirm('Пересчитать привязки по всем найденным лицам? Сервис face-id не нужен — считается по сохранённым эмбеддингам.')) return; + const data = await post('/api/faces/rematch'); + if (data) { showToast(`Просмотрено лиц: ${data.scanned}, привязано: ${data.matched}`); load(); } +}); +document.getElementById('toggleBtn').addEventListener('click', async () => { + const next = !(state && state.enabled); + const res = await fetch(`${API}/api/settings`, { + method: 'PUT', + headers: hdrJson(), + body: JSON.stringify({ settings: { face_id_enabled: next ? 'true' : 'false' } }), + }); + if (!res.ok) { + const d = await res.json().catch(() => ({})); + showToast(d.error || 'Ошибка'); + return; + } + showToast(next ? 'Распознавание лиц включено' : 'Распознавание лиц выключено'); + load(); +}); +document.getElementById('clearQueueBtn').addEventListener('click', async () => { + if (!confirm('Удалить завершённые и ошибочные задания из очереди? На найденные лица это не влияет.')) return; + const data = await post('/api/faces/queue/clear', {}); + if (data) { showToast(`Удалено заданий: ${data.deleted}`); load(); } +}); +document.getElementById('autoRefresh').addEventListener('change', e => { + if (refreshTimer) { clearInterval(refreshTimer); refreshTimer = null; } + if (e.target.checked) refreshTimer = setInterval(load, AUTO_REFRESH_MS); +}); +document.getElementById('recentFilter').addEventListener('change', () => { + recentPage = 1; + recentOffset = 0; + load(); +}); +document.getElementById('actionFilter').addEventListener('change', renderActions); + +document.getElementById('recentTable').addEventListener('click', e => { + const btn = e.target.closest('[data-face-job]'); + if (!btn) return; + const row = (state.recent || [])[parseInt(btn.dataset.faceJob, 10)]; + if (row) openFaceJob(row); +}); +document.getElementById('faceJobCloseBtn').addEventListener('click', () => { + document.getElementById('faceJobModal').classList.remove('open'); +}); +document.getElementById('faceJobModal').addEventListener('click', e => { + if (e.target === e.currentTarget) e.currentTarget.classList.remove('open'); +}); +document.getElementById('faceJobRetryBtn').addEventListener('click', async () => { + const r = faceJobRow; + if (!r) return; + const data = await post(`/api/photos/${r.source_type}/${r.source_id}/faces/rescan`, {}); + if (data) { + showToast('Фото поставлено в очередь заново'); + document.getElementById('faceJobModal').classList.remove('open'); + load(); + } +}); + +(async () => { + if (await requireAdminPage()) { + buildSidebar(document.body.dataset.page); + load(); + } +})(); \ No newline at end of file diff --git a/public/js/groups.js b/public/js/groups.js index 5fdb015..8c3927b 100644 --- a/public/js/groups.js +++ b/public/js/groups.js @@ -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; diff --git a/public/js/journal.js b/public/js/journal.js index 712e724..7d65b26 100644 --- a/public/js/journal.js +++ b/public/js/journal.js @@ -96,7 +96,7 @@ function reportCardFilesHTML(e) { if (!e.files || !e.files.length) return ''; return `
${e.files.map(f => { const url = `${API}/api/files/${f.token}`; - if (isImageFile(f.name)) return `${esc(f.name)}`; + if (isImageFile(f.name)) return `${esc(f.name)}`; if (isPlayableVideoFile(f.name)) return `${esc(f.name)}`; const note = isVideoFile(f.name) ? 'Скачать (браузер не умеет играть этот формат)' : 'Скачать'; return `${esc(f.name)}`; @@ -243,7 +243,7 @@ function gridEntryHTML(e) { const mp = mainPhotoPath(e); return `
- ${mp ? `` : ''} + ${mp ? `` : ''}
${esc(e.student_name)}
${esc(e.group_name)}${e.module_name ? ' · ' + esc(e.module_name) : ''}
@@ -264,7 +264,7 @@ function cardEntryHTML(e) { return `
${mp - ? `` + ? `` : `
`} ${e.group_name ? `${esc(e.group_name)}` : ''} ${e.module_name ? `${esc(e.module_name)}` : ''} diff --git a/public/js/settings.js b/public/js/settings.js index 69542c5..a5fec98 100644 --- a/public/js/settings.js +++ b/public/js/settings.js @@ -1098,6 +1098,56 @@ if (faceRematchBtn) faceRematchBtn.addEventListener('click', async () => { } }); +const faceQueueHint = document.getElementById('faceQueueHint'); +const faceQueueRetryBtn = document.getElementById('faceQueueRetryBtn'); +const faceQueueRefreshBtn = document.getElementById('faceQueueRefreshBtn'); +let faceQueueTimer = null; + +function renderFaceQueue(d) { + if (!faceQueueHint || !d) return; + const t = d.totals || {}; + const w = d.worker || {}; + const parts = [ + `в очереди ${t.pending || 0}`, + `в работе ${t.processing || 0}`, + `готово ${t.done || 0}`, + ]; + if (t.error) parts.push(`ошибок ${t.error}`); + let text = `Очередь проверки: ${parts.join(' · ')}`; + if (w.last_error) text += ` · последняя ошибка: ${w.last_error}`; + faceQueueHint.textContent = text; + if (faceQueueRetryBtn) faceQueueRetryBtn.disabled = !(t.error > 0); +} + +async function loadFaceQueue() { + try { + const res = await fetch(`${API}/api/faces/queue`, { headers: hdr() }); + if (!res.ok) return; + renderFaceQueue(await res.json()); + } catch { /* сеть недоступна — статус обновится при следующем тике */ } +} + +if (faceQueueRefreshBtn) faceQueueRefreshBtn.addEventListener('click', loadFaceQueue); +if (faceQueueRetryBtn) faceQueueRetryBtn.addEventListener('click', async () => { + faceQueueRetryBtn.disabled = true; + try { + const res = await fetch(`${API}/api/faces/queue/retry`, { method: 'POST', headers: hdr() }); + const d = await res.json().catch(() => ({})); + if (!res.ok) { showError(d.error || 'Не удалось повторить ошибки'); return; } + showToast(`В очередь возвращено: ${d.requeued}`); + loadFaceQueue(); + } catch { + showError('Не удалось повторить ошибки'); + } finally { + faceQueueRetryBtn.disabled = false; + } +}); +if (faceQueueHint) { + loadFaceQueue(); + faceQueueTimer = setInterval(loadFaceQueue, 5000); + window.addEventListener('beforeunload', () => { if (faceQueueTimer) clearInterval(faceQueueTimer); }); +} + const notifyTestBtn = document.getElementById('notifyTestBtn'); if (notifyTestBtn) notifyTestBtn.addEventListener('click', async () => { notifyTestBtn.classList.add('spinning'); diff --git a/public/settings.html b/public/settings.html index 79d1592..5f0ca3f 100644 --- a/public/settings.html +++ b/public/settings.html @@ -232,6 +232,15 @@ 0.3–0.99. Выше — строже: меньше ложных совпадений, но выше шанс не узнать ученика. Ручная привязка доступна всегда
+
+ +
+ Очередь проверки: загрузка состояния... + + +
+ Фото попадает в очередь при загрузке и при ручной переиндексации. Воркер обрабатывает её по одной штуке, повторяет ошибки до 3 раз и сообщает результат в уведомлениях +
Сопоставляет уже найденные лица с эталонами — сервис face-id не нужен, работает по сохранённым эмбеддингам. Запускается автоматически после добавления эталона. Ручные привязки не трогает. diff --git a/server.js b/server.js index f49efd1..9cc3562 100644 --- a/server.js +++ b/server.js @@ -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'); })(); diff --git a/worker.js b/worker.js index 239f7bb..f82c2b5 100644 --- a/worker.js +++ b/worker.js @@ -1726,4 +1726,189 @@ function createNoteTitleWorker({ pool, getSetting, logAudit, aiUrl, model, defau return { start, stop, notify, getInfo }; } -module.exports = { createEntryAutoChecker, createPhotoEnhanceWorker, createLessonReportChecker, createFeedbackWriter, createNoteTitleWorker, lessonTopicPosition }; +const FACE_MAX_ATTEMPTS = Math.max(1, parseInt(process.env.FACE_SCAN_MAX_ATTEMPTS || '3', 10) || 3); +const FACE_KEEP_DONE_MS = Math.max(3600000, parseInt(process.env.FACE_SCAN_KEEP_DONE_MS || '604800000', 10) || 604800000); + +function createFaceScanWorker({ pool, getSetting, logAudit, bus, scan, onDone }) { + const runScan = scan || (async () => { throw new Error('scan не передан воркеру'); }); + + let started = false; + let stopped = false; + let idleMs = IDLE_MIN_MS; + let wake = null; + let processing = false; + let currentId = null; + let startedAt = null; + let sincePrune = 0; + const stats = { scanned: 0, faces: 0, matched: 0, errors: 0, retries: 0, last_at: null, last_error: null }; + + function sleep(ms) { + return new Promise((resolve) => { + const t = setTimeout(() => { wake = null; resolve(); }, ms); + wake = () => { clearTimeout(t); wake = null; resolve(); }; + }); + } + + function notify() { + if (wake) wake(); + if (bus) bus.publish(); + } + + if (bus) bus.subscribe(() => notify()); + + async function isEnabled() { + return String(await getSetting('face_id_enabled', 'false')) === 'true'; + } + + async function claimNext() { + const client = await pool.connect(); + try { + await client.query('BEGIN'); + const { rows } = await client.query( + `SELECT id, source_type, source_id, photo_path, attempts + FROM face_scan_jobs + WHERE status = 'pending' + ORDER BY id ASC LIMIT 1 FOR UPDATE SKIP LOCKED` + ); + if (!rows.length) { + await client.query('COMMIT'); + return null; + } + await client.query( + `UPDATE face_scan_jobs SET status = 'processing', attempts = attempts + 1, updated_at = now() WHERE id = $1`, + [rows[0].id] + ); + await client.query('COMMIT'); + return rows[0]; + } catch (e) { + await client.query('ROLLBACK').catch(() => {}); + throw e; + } finally { + client.release(); + } + } + + function pruneFinished() { + return pool.query( + `DELETE FROM face_scan_jobs + WHERE status IN ('done', 'error') AND updated_at < now() - ($1 || ' milliseconds')::interval`, + [String(FACE_KEEP_DONE_MS)] + ); + } + + async function finish(row, status, result, error) { + const faces = status === 'done' ? Number(result && result.faces) || 0 : 0; + const matched = status === 'done' ? Number(result && result.matched) || 0 : 0; + const names = status === 'done' ? String((result && result.names) || '').slice(0, 500) : ''; + await pool.query( + `UPDATE face_scan_jobs + SET status = $2, faces_found = $3, faces_matched = $4, matched_names = $5, + error = $6, updated_at = now() + WHERE id = $1`, + [row.id, status, faces, matched, names || null, error ? String(error).slice(0, 1000) : null] + ); + if (status === 'done') { + stats.scanned++; + stats.faces += faces; + stats.matched += matched; + stats.last_at = new Date().toISOString(); + } else { + stats.errors++; + stats.last_error = error ? String(error).slice(0, 300) : null; + } + if (onDone) await onDone({ row, status, faces, matched, names, error: error || null }); + } + + async function processOne(row) { + let result; + try { + result = await runScan({ sourceType: row.source_type, sourceId: row.source_id, photoPath: row.photo_path }); + } catch (e) { + const message = String(e && e.message ? e.message : e).slice(0, 500); + const tries = (Number(row.attempts) || 0) + 1; + if (tries < FACE_MAX_ATTEMPTS) { + await pool.query(`UPDATE face_scan_jobs SET status = 'pending', error = $2, updated_at = now() WHERE id = $1`, [row.id, message]); + stats.retries++; + if (logAudit) await logAudit(null, 'face.scan.retry', { id: row.id, source_type: row.source_type, source_id: row.source_id, attempt: tries, error: message }); + return false; + } + await finish(row, 'error', null, message); + if (logAudit) await logAudit(null, 'face.scan.error', { id: row.id, source_type: row.source_type, source_id: row.source_id, attempts: tries, error: message }); + return true; + } + await finish(row, 'done', result, null); + return true; + } + + async function loop() { + while (!stopped) { + let row = null; + try { + if (!(await isEnabled())) { + await sleep(IDLE_MAX_MS); + continue; + } + row = await claimNext(); + } catch (e) { + console.error('Face scan claim error:', e.message); + await sleep(IDLE_MAX_MS); + continue; + } + if (!row) { + await sleep(idleMs); + idleMs = Math.min(idleMs * 2, IDLE_MAX_MS); + continue; + } + idleMs = IDLE_MIN_MS; + processing = true; + currentId = row.id; + let ok = true; + try { + ok = await processOne(row); + } catch (e) { + console.error('Face scan process error:', e.message); + } finally { + processing = false; + currentId = null; + } + if (!ok) await sleep(IDLE_MAX_MS); + if (++sincePrune >= 50) { + sincePrune = 0; + pruneFinished().catch(e => console.error('Face scan prune error:', e.message)); + } + } + } + + function resetStale() { + return pool.query(`UPDATE face_scan_jobs SET status = 'pending', updated_at = now() WHERE status = 'processing'`); + } + + function start() { + if (started) return; + started = true; + startedAt = Date.now(); + resetStale() + .catch(e => console.error('Face scan reset error:', e.message)) + .finally(() => { loop().catch(e => console.error('Face scan loop error:', e.message)); }); + } + + function stop() { + stopped = true; + notify(); + } + + function getInfo() { + return { + started_at: startedAt ? new Date(startedAt).toISOString() : null, + uptime_ms: startedAt ? Date.now() - startedAt : 0, + processing, + current_id: currentId, + config: { idle_min_ms: IDLE_MIN_MS, idle_max_ms: IDLE_MAX_MS, max_attempts: FACE_MAX_ATTEMPTS, keep_done_ms: FACE_KEEP_DONE_MS }, + ...stats, + }; + } + + return { start, stop, notify, getInfo }; +} + +module.exports = { createEntryAutoChecker, createPhotoEnhanceWorker, createLessonReportChecker, createFeedbackWriter, createNoteTitleWorker, createFaceScanWorker, lessonTopicPosition };