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; let prevErrors = 0; 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)}`; const svcState = svc.reachable ? 'check' : (svc.configured ? 'x' : 'minus'); const svcColor = svc.reachable ? '#16a34a' : (svc.configured ? '#ef4444' : 'var(--muted)'); const svcLabel = svc.reachable ? 'доступен' : (svc.configured ? 'недоступен' : 'не настроен'); document.getElementById('serviceLine').innerHTML = ` face-id: ${svcLabel}${svc.latency_ms !== undefined ? ` · ${svc.latency_ms} мс` : ''}`; const btn = document.getElementById('toggleBtn'); btn.classList.toggle('is-on', !!enabled); btn.classList.toggle('is-off', !enabled); btn.innerHTML = `${enabled ? 'Выключить' : 'Включить'} распознавание`; } function renderCards() { const w = state.worker || {}; const svc = state.service || {}; const cfg = w.config || {}; const lib = state.library || {}; const t = state.totals || {}; 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; const kpi = [ { ic: 'hourglass', label: 'В очереди', num: t.pending || 0, cls: t.pending ? 'face-kpi--warn' : '', sub: `проверяется ${t.processing || 0}`, jump: 'queue' }, { ic: 'circle-check', label: 'Проверено фото', num: lib.photos_scanned || 0, cls: 'face-kpi--ok', sub: `из ${lib.photos_total || 0} · ${scannedPct}%` }, { ic: 'scan-face', label: 'Найдено лиц', num: lib.faces_total || 0, cls: 'face-kpi--accent', sub: `не опознано ${lib.faces_unassigned || 0} · кандидат ${lib.faces_candidates || 0}` }, { ic: 'activity', label: 'Привязано', num: lib.faces_matched || 0, cls: 'face-kpi--ok', sub: `${matchedPct}% · вручную ${lib.faces_manual || 0}` }, { ic: 'contact-round', label: 'Эталоны', num: lib.refs_total || 0, cls: '', sub: `${lib.ref_students || 0} учеников` }, { ic: 'triangle-alert', label: 'Ошибки', num: t.error || 0, cls: t.error ? 'face-kpi--err' : '', sub: `повторов ${w.retries || 0}`, jump: 'errors' }, ]; document.getElementById('workerCards').innerHTML = kpi.map(c => `
${c.label}
${c.num}
${c.sub}
`).join(''); document.getElementById('techDetailsBody').innerHTML = `
Воркер
Режим${w.processing ? 'Проверка' : 'Ожидание'}
Текущее задание${w.current_id ? '#' + w.current_id : '—'}
Работает${fmtDur(w.uptime_ms)}
Запущен${fmtTime(w.started_at)}
Активность${ago(w.last_at)}
Повторов${w.retries || 0}
${w.last_error ? `
${esc(w.last_error)}
` : ''}
Сервис 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)}
` : ''}
Параметры (мин. нагрузка)
Скан при загрузке${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 jumpTo(kind) { if (kind === 'queue') { document.getElementById('queueCard').scrollIntoView({ behavior: 'smooth', block: 'start' }); return; } const card = document.getElementById('errorsCard'); const total = (state.totals && state.totals.error) || 0; if (total) { card.open = true; card.scrollIntoView({ behavior: 'smooth', block: 'start' }); return; } document.getElementById('recentFilter').value = 'error'; recentPage = 1; recentOffset = 0; load(); } function renderLibrary() { const lib = state.library || {}; document.getElementById('coverageHint').textContent = lib.photos_unscanned ? `Осталось проверить фото: ${lib.photos_unscanned}. Кнопка «Сканировать необработанные» поставит их в очередь (до 50 за раз).` : 'Все фото с изображением уже проверены.'; } 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; const card = document.getElementById('errorsCard'); card.style.display = total ? '' : 'none'; if (total > 0 && prevErrors === 0) card.open = true; prevErrors = total; 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(); 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('workerCards').addEventListener('click', e => { const el = e.target.closest('[data-jump]'); if (el) jumpTo(el.dataset.jump); }); 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(); } })();